2 * Copyright 2015-2017 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.activities;
22 import android.annotation.SuppressLint;
23 import android.app.DialogFragment;
24 import android.app.DownloadManager;
25 import android.content.ClipData;
26 import android.content.ClipboardManager;
27 import android.content.Context;
28 import android.content.Intent;
29 import android.content.SharedPreferences;
30 import android.content.res.Configuration;
31 import android.graphics.Bitmap;
32 import android.graphics.drawable.BitmapDrawable;
33 import android.graphics.drawable.Drawable;
34 import android.net.Uri;
35 import android.net.http.SslCertificate;
36 import android.net.http.SslError;
37 import android.os.Build;
38 import android.os.Bundle;
39 import android.preference.PreferenceManager;
40 import android.print.PrintDocumentAdapter;
41 import android.print.PrintManager;
42 import android.support.annotation.NonNull;
43 import android.support.design.widget.CoordinatorLayout;
44 import android.support.design.widget.NavigationView;
45 import android.support.design.widget.Snackbar;
46 import android.support.v4.app.ActivityCompat;
47 import android.support.v4.content.ContextCompat;
48 import android.support.v4.view.GravityCompat;
49 import android.support.v4.widget.DrawerLayout;
50 import android.support.v4.widget.SwipeRefreshLayout;
51 import android.support.v7.app.ActionBar;
52 import android.support.v7.app.ActionBarDrawerToggle;
53 import android.support.v7.app.AppCompatActivity;
54 import android.support.v7.app.AppCompatDialogFragment;
55 import android.support.v7.widget.Toolbar;
56 import android.text.Editable;
57 import android.text.TextWatcher;
58 import android.util.Patterns;
59 import android.view.ContextMenu;
60 import android.view.GestureDetector;
61 import android.view.KeyEvent;
62 import android.view.Menu;
63 import android.view.MenuItem;
64 import android.view.MotionEvent;
65 import android.view.View;
66 import android.view.WindowManager;
67 import android.view.inputmethod.InputMethodManager;
68 import android.webkit.CookieManager;
69 import android.webkit.DownloadListener;
70 import android.webkit.SslErrorHandler;
71 import android.webkit.WebBackForwardList;
72 import android.webkit.WebChromeClient;
73 import android.webkit.WebResourceResponse;
74 import android.webkit.WebStorage;
75 import android.webkit.WebView;
76 import android.webkit.WebViewClient;
77 import android.webkit.WebViewDatabase;
78 import android.widget.EditText;
79 import android.widget.FrameLayout;
80 import android.widget.ImageView;
81 import android.widget.LinearLayout;
82 import android.widget.ProgressBar;
83 import android.widget.RelativeLayout;
84 import android.widget.TextView;
86 import com.stoutner.privacybrowser.BannerAd;
87 import com.stoutner.privacybrowser.BuildConfig;
88 import com.stoutner.privacybrowser.R;
89 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
90 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcut;
91 import com.stoutner.privacybrowser.dialogs.DownloadFile;
92 import com.stoutner.privacybrowser.dialogs.DownloadImage;
93 import com.stoutner.privacybrowser.dialogs.SslCertificateError;
94 import com.stoutner.privacybrowser.dialogs.UrlHistory;
95 import com.stoutner.privacybrowser.dialogs.ViewSslCertificate;
97 import java.io.BufferedReader;
98 import java.io.ByteArrayInputStream;
99 import java.io.IOException;
100 import java.io.InputStreamReader;
101 import java.io.UnsupportedEncodingException;
102 import java.net.MalformedURLException;
104 import java.net.URLEncoder;
105 import java.util.HashMap;
106 import java.util.HashSet;
107 import java.util.Map;
108 import java.util.Set;
110 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
111 public class MainWebView extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener,
112 SslCertificateError.SslCertificateErrorListener, DownloadFile.DownloadFileListener, DownloadImage.DownloadImageListener, UrlHistory.UrlHistoryListener {
114 // `appBar` is public static so it can be accessed from `OrbotProxyHelper`.
115 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applySettings()`.
116 public static ActionBar appBar;
118 // `favoriteIcon` is public static so it can be accessed from `CreateHomeScreenShortcut`, `Bookmarks`, `CreateBookmark`, `CreateBookmarkFolder`, and `EditBookmark`.
119 // It is also used in `onCreate()` and `onCreateHomeScreenShortcutCreate()`.
120 public static Bitmap favoriteIcon;
122 // `formattedUrlString` is public static so it can be accessed from `Bookmarks`.
123 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
124 public static String formattedUrlString;
126 // `sslCertificate` is public static so it can be accessed from `ViewSslCertificate`. It is also used in `onCreate()`.
127 public static SslCertificate sslCertificate;
130 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
131 private DrawerLayout drawerLayout;
133 // `rootCoordinatorLayout` is used in `onCreate()` and `applySettings()`.
134 private CoordinatorLayout rootCoordinatorLayout;
136 // 'mainWebView' is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, and `loadUrlFromTextBox()`.
137 private WebView mainWebView;
139 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
140 private FrameLayout fullScreenVideoFrameLayout;
142 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
143 private SwipeRefreshLayout swipeRefreshLayout;
145 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, and `onRestart()`.
146 private CookieManager cookieManager;
148 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrlFromTextBox()`.
149 private final Map<String, String> customHeaders = new HashMap<>();
151 // `javaScriptEnabled` is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `applySettings()`.
152 // It is `Boolean` instead of `boolean` because `applySettings()` needs to know if it is `null`.
153 private Boolean javaScriptEnabled;
155 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
156 private boolean firstPartyCookiesEnabled;
158 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
159 private boolean thirdPartyCookiesEnabled;
161 // `domStorageEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
162 private boolean domStorageEnabled;
164 // `saveFormDataEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
165 private boolean saveFormDataEnabled;
167 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applySettings()`.
168 private boolean swipeToRefreshEnabled;
170 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applySettings()`.
171 private String homepage;
173 // `javaScriptDisabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
174 private String javaScriptDisabledSearchURL;
176 // `javaScriptEnabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
177 private String javaScriptEnabledSearchURL;
179 // `adBlockerEnabled` is used in `onCreate()` and `applySettings()`.
180 private boolean adBlockerEnabled;
182 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applySettings()`.
183 private boolean fullScreenBrowsingModeEnabled;
185 // `inFullScreenBrowsingMode` is used in `onCreate()` and `applySettings()`.
186 private boolean inFullScreenBrowsingMode;
188 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applySettings()`.
189 private boolean hideSystemBarsOnFullscreen;
191 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applySettings()`.
192 private boolean translucentNavigationBarOnFullscreen;
194 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
195 private LinearLayout findOnPageLinearLayout;
197 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
198 private EditText findOnPageEditText;
200 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
201 private Menu mainMenu;
203 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
204 private ActionBarDrawerToggle drawerToggle;
206 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
207 private Toolbar supportAppBar;
209 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
210 private EditText urlTextBox;
212 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
215 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
216 private SslErrorHandler sslErrorHandler;
218 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
219 private InputMethodManager inputMethodManager;
221 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
222 private RelativeLayout mainWebViewRelativeLayout;
225 // 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.
226 @SuppressLint("SetJavaScriptEnabled")
227 protected void onCreate(Bundle savedInstanceState) {
228 super.onCreate(savedInstanceState);
229 setContentView(R.layout.drawerlayout);
231 // Get a handle for `inputMethodManager`.
232 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
234 // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
235 supportAppBar = (Toolbar) findViewById(R.id.app_bar);
236 setSupportActionBar(supportAppBar);
237 appBar = getSupportActionBar();
239 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
240 assert appBar != null;
242 // Add the custom url_app_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
243 appBar.setCustomView(R.layout.url_app_bar);
244 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
246 // Set the "go" button on the keyboard to load the URL in urlTextBox.
247 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
248 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
250 public boolean onKey(View v, int keyCode, KeyEvent event) {
251 // If the event is a key-down event on the `enter` button, load the URL.
252 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
253 // Load the URL into the mainWebView and consume the event.
255 loadUrlFromTextBox();
256 } catch (UnsupportedEncodingException e) {
259 // If the enter key was pressed, consume the event.
262 // If any other key was pressed, do not consume the event.
268 // Get handles for views that need to be accessed.
269 drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
270 rootCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.root_coordinatorlayout);
271 mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.main_webview_relativelayout);
272 mainWebView = (WebView) findViewById(R.id.mainWebView);
273 findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
274 findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
275 fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.full_screen_video_framelayout);
277 // Create a double-tap listener to toggle full-screen mode.
278 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
279 // Override `onDoubleTap()`. All other events are handled using the default settings.
281 public boolean onDoubleTap(MotionEvent event) {
282 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
283 // Toggle `inFullScreenBrowsingMode`.
284 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
286 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
287 // Hide the `appBar`.
290 // Hide the `BannerAd` in the free flavor.
291 if (BuildConfig.FLAVOR.contentEquals("free")) {
292 BannerAd.hideAd(adView);
295 // Modify the system bars.
296 if (hideSystemBarsOnFullscreen) { // Hide everything.
297 // Remove the translucent overlays.
298 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
300 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
301 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
303 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
304 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
305 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
307 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
309 // Set `rootCoordinatorLayout` to fill the whole screen.
310 rootCoordinatorLayout.setFitsSystemWindows(false);
311 } else { // Hide everything except the status and navigation bars.
312 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
313 rootCoordinatorLayout.setFitsSystemWindows(false);
315 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.
316 // Set the navigation bar to be translucent.
317 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
320 } else { // Switch to normal viewing mode.
321 // Show the `appBar`.
324 // Show the `BannerAd` in the free flavor.
325 if (BuildConfig.FLAVOR.contentEquals("free")) {
326 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
327 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
329 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
330 adView = findViewById(R.id.adView);
333 // Remove the translucent navigation bar flag if it is set.
334 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
336 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
337 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
339 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
340 rootCoordinatorLayout.setSystemUiVisibility(0);
342 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
343 rootCoordinatorLayout.setFitsSystemWindows(true);
346 // Consume the double-tap.
348 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
354 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
355 mainWebView.setOnTouchListener(new View.OnTouchListener() {
357 public boolean onTouch(View v, MotionEvent event) {
358 // Send the `event` to `gestureDetector`.
359 return gestureDetector.onTouchEvent(event);
363 // Update `findOnPageCountTextView`.
364 mainWebView.setFindListener(new WebView.FindListener() {
365 // Get a handle for `findOnPageCountTextView`.
366 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
369 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
370 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
371 // Set `findOnPageCountTextView` to `0/0`.
372 findOnPageCountTextView.setText(R.string.zero_of_zero);
373 } else if (isDoneCounting) { // There are matches.
374 // `activeMatchOrdinal` is zero-based.
375 int activeMatch = activeMatchOrdinal + 1;
377 // Set `findOnPageCountTextView`.
378 findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
383 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
384 findOnPageEditText.addTextChangedListener(new TextWatcher() {
386 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
391 public void onTextChanged(CharSequence s, int start, int before, int count) {
396 public void afterTextChanged(Editable s) {
397 // Search for the text in `mainWebView`.
398 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
402 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
403 findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
405 public boolean onKey(View v, int keyCode, KeyEvent event) {
406 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
407 // Hide the soft keyboard. `0` indicates no additional flags.
408 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
410 // Consume the event.
412 } else { // A different key was pressed.
413 // Do not consume the event.
419 // Implement swipe to refresh
420 swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
421 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
422 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
424 public void onRefresh() {
425 mainWebView.reload();
429 // `DrawerTitle` identifies the `DrawerLayout` in accessibility mode.
430 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
432 // Listen for touches on the navigation menu.
433 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationview);
434 navigationView.setNavigationItemSelectedListener(this);
436 // 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.
437 final Menu navigationMenu = navigationView.getMenu();
438 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
439 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
440 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
442 // The `DrawerListener` allows us to update the Navigation Menu.
443 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
445 public void onDrawerSlide(View drawerView, float slideOffset) {
449 public void onDrawerOpened(View drawerView) {
453 public void onDrawerClosed(View drawerView) {
457 public void onDrawerStateChanged(int newState) {
458 // Update the `Back`, `Forward`, and `History` menu items every time the drawer opens.
459 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
460 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
461 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
463 // Hide the keyboard so we can see the navigation menu. `0` indicates no additional flags.
464 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
468 // drawerToggle creates the hamburger icon at the start of the AppBar.
469 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
471 // Initialize `adServerSet`.
472 final Set<String> adServersSet = new HashSet<>();
474 // Load the list of ad servers into memory.
476 // Load `pgl.yoyo.org_adservers.txt` into a `BufferedReader`.
477 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("pgl.yoyo.org_adservers.txt")));
479 // Create a string for storing each ad server.
482 // Populate `adServersSet`.
483 while ((adServer = bufferedReader.readLine()) != null) {
484 adServersSet.add(adServer);
487 // Close `bufferedReader`.
488 bufferedReader.close();
489 } catch (IOException ioException) {
490 // We're pretty sure the asset exists, so we don't need to worry about the `IOException` ever being thrown.
493 mainWebView.setWebViewClient(new WebViewClient() {
494 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
495 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
496 @SuppressWarnings("deprecation")
498 public boolean shouldOverrideUrlLoading(WebView view, String url) {
499 // Use an external email program if the link begins with `mailto:`.
500 if (url.startsWith("mailto:")) {
501 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
502 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
504 // Parse the url and set it as the data for the `Intent`.
505 emailIntent.setData(Uri.parse(url));
507 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
508 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
511 startActivity(emailIntent);
513 } else { // Load the URL in Privacy Browser.
514 mainWebView.loadUrl(url, customHeaders);
519 // Block ads. We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
520 @SuppressWarnings("deprecation")
522 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
523 if (adBlockerEnabled) { // Block ads.
524 // Extract the host from `url`.
525 Uri requestUri = Uri.parse(url);
526 String requestHost = requestUri.getHost();
528 // Create a variable to track if this is an ad server.
529 boolean requestHostIsAdServer = false;
531 // Check all the subdomains of `requestHost` if it is not `null`.
532 if (requestHost != null) {
533 while (requestHost.contains(".")) {
534 if (adServersSet.contains(requestHost)) {
535 requestHostIsAdServer = true;
538 // Strip out the lowest subdomain of `requestHost`.
539 requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
543 if (requestHostIsAdServer) { // It is an ad server.
544 // Return an empty `WebResourceResponse`.
545 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
546 } else { // It is not an ad server.
547 // `return null` loads the requested resource.
550 } else { // Ad blocking is disabled.
551 // `return null` loads the requested resource.
556 // Update the URL in urlTextBox when the page starts to load.
558 public void onPageStarted(WebView view, String url, Bitmap favicon) {
559 // 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.
560 formattedUrlString = url;
562 // Display the loading URL is the URL text box.
563 urlTextBox.setText(url);
566 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
568 public void onPageFinished(WebView view, String url) {
569 formattedUrlString = url;
571 // Only update urlTextBox if the user is not typing in it.
572 if (!urlTextBox.hasFocus()) {
573 urlTextBox.setText(formattedUrlString);
576 // Store the SSL certificate so it can be accessed from `ViewSslCertificate`.
577 sslCertificate = mainWebView.getCertificate();
580 // Handle SSL Certificate errors.
582 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
583 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
584 sslErrorHandler = handler;
586 // Display the SSL error `AlertDialog`.
587 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateError.displayDialog(error);
588 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
592 mainWebView.setWebChromeClient(new WebChromeClient() {
593 // Update the progress bar when a page is loading.
595 public void onProgressChanged(WebView view, int progress) {
596 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
597 progressBar.setProgress(progress);
598 if (progress < 100) {
599 progressBar.setVisibility(View.VISIBLE);
601 progressBar.setVisibility(View.GONE);
603 //Stop the `SwipeToRefresh` indicator if it is running
604 swipeRefreshLayout.setRefreshing(false);
608 // Set the favorite icon when it changes.
610 public void onReceivedIcon(WebView view, Bitmap icon) {
611 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
614 // Place the favorite icon in the appBar.
615 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
616 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
619 // Enter full screen video
621 public void onShowCustomView(View view, CustomViewCallback callback) {
622 // Pause the ad if this is the free flavor.
623 if (BuildConfig.FLAVOR.contentEquals("free")) {
624 BannerAd.pauseAd(adView);
627 // Remove the translucent overlays.
628 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
630 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
631 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
633 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
634 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
635 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
637 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
639 // Set `rootCoordinatorLayout` to fill the entire screen.
640 rootCoordinatorLayout.setFitsSystemWindows(false);
642 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
643 fullScreenVideoFrameLayout.addView(view);
644 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
647 // Exit full screen video
648 public void onHideCustomView() {
649 // Hide `fullScreenVideoFrameLayout`.
650 fullScreenVideoFrameLayout.removeAllViews();
651 fullScreenVideoFrameLayout.setVisibility(View.GONE);
653 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
654 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
656 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
657 rootCoordinatorLayout.setFitsSystemWindows(true);
659 // Show the ad if this is the free flavor.
660 if (BuildConfig.FLAVOR.contentEquals("free")) {
661 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
662 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
664 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
665 adView = findViewById(R.id.adView);
670 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
671 registerForContextMenu(mainWebView);
673 // Allow the downloading of files.
674 mainWebView.setDownloadListener(new DownloadListener() {
676 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
677 // Show the `DownloadFile` `AlertDialog` and name this instance `@string/download`.
678 AppCompatDialogFragment downloadFileDialogFragment = DownloadFile.fromUrl(url, contentDisposition, contentLength);
679 downloadFileDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
683 // Allow pinch to zoom.
684 mainWebView.getSettings().setBuiltInZoomControls(true);
686 // Hide zoom controls.
687 mainWebView.getSettings().setDisplayZoomControls(false);
689 // Initialize cookieManager.
690 cookieManager = CookieManager.getInstance();
692 // 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).
693 customHeaders.put("X-Requested-With", "");
695 // 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.
696 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
698 // Apply the settings from the shared preferences.
701 // Get the intent information that started the app.
702 final Intent intent = getIntent();
704 if (intent.getData() != null) {
705 // Get the intent data and convert it to a string.
706 final Uri intentUriData = intent.getData();
707 formattedUrlString = intentUriData.toString();
710 // If formattedUrlString is null assign the homepage to it.
711 if (formattedUrlString == null) {
712 formattedUrlString = homepage;
715 // Load the initial website.
716 mainWebView.loadUrl(formattedUrlString, customHeaders);
718 // If the favorite icon is null, load the default.
719 if (favoriteIcon == null) {
720 // We have to use `ContextCompat` until API >= 21.
721 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
722 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
723 favoriteIcon = favoriteIconBitmapDrawable.getBitmap();
726 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
727 inFullScreenBrowsingMode = false;
729 // Initialize AdView for the free flavor and request an ad. If this is not the free flavor BannerAd.requestAd() does nothing.
730 adView = findViewById(R.id.adView);
731 BannerAd.requestAd(adView);
736 protected void onNewIntent(Intent intent) {
737 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
740 if (intent.getData() != null) {
741 // Get the intent data and convert it to a string.
742 final Uri intentUriData = intent.getData();
743 formattedUrlString = intentUriData.toString();
746 // Close the navigation drawer if it is open.
747 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
748 drawerLayout.closeDrawer(GravityCompat.START);
752 mainWebView.loadUrl(formattedUrlString, customHeaders);
754 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
755 mainWebView.requestFocus();
759 public boolean onCreateOptionsMenu(Menu menu) {
760 // Inflate the menu; this adds items to the action bar if it is present.
761 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
763 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
766 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
767 updatePrivacyIcons(false);
769 // Get handles for the menu items.
770 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
771 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
772 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
773 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
775 // Only display third-Party Cookies if SDK >= 21
776 toggleThirdPartyCookies.setVisible(Build.VERSION.SDK_INT >= 21);
778 // Get the shared preference values. `this` references the current context.
779 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
781 // Set the status of the additional app bar icons. The default is `false`.
782 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
783 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
784 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
785 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
786 } else { //Do not display the additional icons.
787 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
788 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
789 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
796 public boolean onPrepareOptionsMenu(Menu menu) {
797 // Get handles for the menu items.
798 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
799 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
800 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
801 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
802 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
803 MenuItem clearFormData = menu.findItem(R.id.clearFormData);
804 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
806 // Set the status of the menu item checkboxes.
807 toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
808 toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
809 toggleDomStorage.setChecked(domStorageEnabled);
810 toggleSaveFormData.setChecked(saveFormDataEnabled);
812 // Enable third-party cookies if first-party cookies are enabled.
813 toggleThirdPartyCookies.setEnabled(firstPartyCookiesEnabled);
815 // Enable DOM Storage if JavaScript is enabled.
816 toggleDomStorage.setEnabled(javaScriptEnabled);
818 // Enable Clear Cookies if there are any.
819 clearCookies.setEnabled(cookieManager.hasCookies());
821 // Enable Clear Form Data is there is any.
822 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
823 clearFormData.setEnabled(mainWebViewDatabase.hasFormData());
825 // Only show `Refresh` if `swipeToRefresh` is disabled.
826 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
828 // Initialize font size variables.
829 int fontSize = mainWebView.getSettings().getTextZoom();
830 String fontSizeTitle;
831 MenuItem selectedFontSizeMenuItem;
833 // Prepare the font size title and current size menu item.
836 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
837 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeFiftyPercent);
841 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
842 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeSeventyFivePercent);
846 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
847 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
851 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
852 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredTwentyFivePercent);
856 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
857 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredFiftyPercent);
861 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
862 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredSeventyFivePercent);
866 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
867 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeTwoHundredPercent);
871 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
872 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
876 // Set the font size title and select the current size menu item.
877 MenuItem fontSizeMenuItem = menu.findItem(R.id.fontSize);
878 fontSizeMenuItem.setTitle(fontSizeTitle);
879 selectedFontSizeMenuItem.setChecked(true);
881 // Run all the other default commands.
882 super.onPrepareOptionsMenu(menu);
884 // `return true` displays the menu.
889 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
890 @SuppressLint("SetJavaScriptEnabled")
891 // removeAllCookies is deprecated, but it is required for API < 21.
892 @SuppressWarnings("deprecation")
893 public boolean onOptionsItemSelected(MenuItem menuItem) {
894 int menuItemId = menuItem.getItemId();
896 // Set the commands that relate to the menu entries.
897 switch (menuItemId) {
898 case R.id.toggleJavaScript:
899 // Switch the status of javaScriptEnabled.
900 javaScriptEnabled = !javaScriptEnabled;
902 // Apply the new JavaScript status.
903 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
905 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
906 updatePrivacyIcons(true);
908 // Display a `Snackbar`.
909 if (javaScriptEnabled) { // JavaScrip is enabled.
910 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
911 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
912 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
913 } else { // Privacy mode.
914 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
917 // Reload the WebView.
918 mainWebView.reload();
921 case R.id.toggleFirstPartyCookies:
922 // Switch the status of firstPartyCookiesEnabled.
923 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
925 // Update the menu checkbox.
926 menuItem.setChecked(firstPartyCookiesEnabled);
928 // Apply the new cookie status.
929 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
931 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
932 updatePrivacyIcons(true);
934 // Display a `Snackbar`.
935 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
936 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
937 } else if (javaScriptEnabled){ // JavaScript is still enabled.
938 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
939 } else { // Privacy mode.
940 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
943 // Reload the WebView.
944 mainWebView.reload();
947 case R.id.toggleThirdPartyCookies:
948 if (Build.VERSION.SDK_INT >= 21) {
949 // Switch the status of thirdPartyCookiesEnabled.
950 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
952 // Update the menu checkbox.
953 menuItem.setChecked(thirdPartyCookiesEnabled);
955 // Apply the new cookie status.
956 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
958 // Display a `Snackbar`.
959 if (thirdPartyCookiesEnabled) {
960 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
962 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
965 // Reload the WebView.
966 mainWebView.reload();
967 } // Else do nothing because SDK < 21.
970 case R.id.toggleDomStorage:
971 // Switch the status of domStorageEnabled.
972 domStorageEnabled = !domStorageEnabled;
974 // Update the menu checkbox.
975 menuItem.setChecked(domStorageEnabled);
977 // Apply the new DOM Storage status.
978 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
980 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
981 updatePrivacyIcons(true);
983 // Display a `Snackbar`.
984 if (domStorageEnabled) {
985 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
987 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
990 // Reload the WebView.
991 mainWebView.reload();
994 case R.id.toggleSaveFormData:
995 // Switch the status of saveFormDataEnabled.
996 saveFormDataEnabled = !saveFormDataEnabled;
998 // Update the menu checkbox.
999 menuItem.setChecked(saveFormDataEnabled);
1001 // Apply the new form data status.
1002 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1004 // Display a `Snackbar`.
1005 if (saveFormDataEnabled) {
1006 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1008 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1011 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1012 updatePrivacyIcons(true);
1014 // Reload the WebView.
1015 mainWebView.reload();
1018 case R.id.clearCookies:
1019 if (Build.VERSION.SDK_INT < 21) {
1020 cookieManager.removeAllCookie();
1022 cookieManager.removeAllCookies(null);
1024 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
1027 case R.id.clearDomStorage:
1028 WebStorage webStorage = WebStorage.getInstance();
1029 webStorage.deleteAllData();
1030 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
1033 case R.id.clearFormData:
1034 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1035 mainWebViewDatabase.clearFormData();
1036 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_deleted, Snackbar.LENGTH_SHORT).show();
1039 case R.id.fontSizeFiftyPercent:
1040 mainWebView.getSettings().setTextZoom(50);
1043 case R.id.fontSizeSeventyFivePercent:
1044 mainWebView.getSettings().setTextZoom(75);
1047 case R.id.fontSizeOneHundredPercent:
1048 mainWebView.getSettings().setTextZoom(100);
1051 case R.id.fontSizeOneHundredTwentyFivePercent:
1052 mainWebView.getSettings().setTextZoom(125);
1055 case R.id.fontSizeOneHundredFiftyPercent:
1056 mainWebView.getSettings().setTextZoom(150);
1059 case R.id.fontSizeOneHundredSeventyFivePercent:
1060 mainWebView.getSettings().setTextZoom(175);
1063 case R.id.fontSizeTwoHundredPercent:
1064 mainWebView.getSettings().setTextZoom(200);
1067 case R.id.find_on_page:
1068 // Hide the URL app bar.
1069 supportAppBar.setVisibility(View.GONE);
1071 // Show the Find on Page `RelativeLayout`.
1072 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1074 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
1075 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1076 findOnPageEditText.postDelayed(new Runnable()
1081 // Set the focus on `findOnPageEditText`.
1082 findOnPageEditText.requestFocus();
1084 // Display the keyboard.
1085 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1091 Intent shareIntent = new Intent();
1092 shareIntent.setAction(Intent.ACTION_SEND);
1093 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
1094 shareIntent.setType("text/plain");
1095 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1098 case R.id.addToHomescreen:
1099 // Show the `CreateHomeScreenShortcut` `AlertDialog` and name this instance `R.string.create_shortcut`.
1100 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcut();
1101 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
1103 //Everything else will be handled by `CreateHomeScreenShortcut` and the associated listener below.
1107 // Get a `PrintManager` instance.
1108 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1110 // Convert `mainWebView` to `printDocumentAdapter`.
1111 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1113 // Print the document. The print attributes are `null`.
1114 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1118 mainWebView.reload();
1122 // Don't consume the event.
1123 return super.onOptionsItemSelected(menuItem);
1127 // removeAllCookies is deprecated, but it is required for API < 21.
1128 @SuppressWarnings("deprecation")
1130 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1131 int menuItemId = menuItem.getItemId();
1133 switch (menuItemId) {
1135 mainWebView.loadUrl(homepage, customHeaders);
1139 if (mainWebView.canGoBack()) {
1140 mainWebView.goBack();
1145 if (mainWebView.canGoForward()) {
1146 mainWebView.goForward();
1151 // Gte the `WebBackForwardList`.
1152 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1154 // Show the `UrlHistory` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1155 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistory.loadBackForwardList(this, webBackForwardList);
1156 urlHistoryDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.history));
1159 case R.id.bookmarks:
1160 // Launch Bookmarks.
1161 Intent bookmarksIntent = new Intent(this, Bookmarks.class);
1162 startActivity(bookmarksIntent);
1165 case R.id.downloads:
1166 // Launch the system Download Manager.
1167 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1169 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1170 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1172 startActivity(downloadManagerIntent);
1176 // Launch `Settings`.
1177 Intent settingsIntent = new Intent(this, Settings.class);
1178 startActivity(settingsIntent);
1183 Intent guideIntent = new Intent(this, Guide.class);
1184 startActivity(guideIntent);
1189 Intent aboutIntent = new Intent(this, About.class);
1190 startActivity(aboutIntent);
1193 case R.id.clearAndExit:
1194 // Clear cookies. The commands changed slightly in API 21.
1195 if (Build.VERSION.SDK_INT >= 21) {
1196 cookieManager.removeAllCookies(null);
1198 cookieManager.removeAllCookie();
1201 // Clear DOM storage.
1202 WebStorage domStorage = WebStorage.getInstance();
1203 domStorage.deleteAllData();
1206 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1207 webViewDatabase.clearFormData();
1209 // Clear cache. The argument of "true" includes disk files.
1210 mainWebView.clearCache(true);
1212 // Clear the back/forward history.
1213 mainWebView.clearHistory();
1215 // Clear any SSL certificate preferences.
1216 mainWebView.clearSslPreferences();
1218 // Clear `formattedUrlString`.
1219 formattedUrlString = null;
1221 // Clear `customHeaders`.
1222 customHeaders.clear();
1224 // Detach all views from `mainWebViewRelativeLayout`.
1225 mainWebViewRelativeLayout.removeAllViews();
1227 // Destroy the internal state of `mainWebView`.
1228 mainWebView.destroy();
1230 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1231 if (Build.VERSION.SDK_INT >= 21) {
1232 finishAndRemoveTask();
1237 // Remove the terminated program from RAM. The status code is `0`.
1245 // Close the navigation drawer.
1246 drawerLayout.closeDrawer(GravityCompat.START);
1251 public void onPostCreate(Bundle savedInstanceState) {
1252 super.onPostCreate(savedInstanceState);
1254 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1255 drawerToggle.syncState();
1259 public void onConfigurationChanged(Configuration newConfig) {
1260 super.onConfigurationChanged(newConfig);
1262 // Reload the ad for the free flavor if we are not in full screen mode.
1263 if (BuildConfig.FLAVOR.contentEquals("free") && adView.isShown() && !fullScreenVideoFrameLayout.isShown()) {
1265 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1267 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1268 adView = findViewById(R.id.adView);
1271 // `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
1272 // ActivityCompat.invalidateOptionsMenu(this);
1276 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1277 // Store the `HitTestResult`.
1278 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1281 final String imageUrl;
1282 final String linkUrl;
1284 // Get a handle for the `ClipboardManager`.
1285 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1287 switch (hitTestResult.getType()) {
1288 // `SRC_ANCHOR_TYPE` is a link.
1289 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1290 // Get the target URL.
1291 linkUrl = hitTestResult.getExtra();
1293 // Set the target URL as the title of the `ContextMenu`.
1294 menu.setHeaderTitle(linkUrl);
1296 // Add a `Load URL` entry.
1297 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1299 public boolean onMenuItemClick(MenuItem item) {
1300 mainWebView.loadUrl(linkUrl, customHeaders);
1305 // Add a `Copy URL` entry.
1306 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1308 public boolean onMenuItemClick(MenuItem item) {
1309 // Save the link URL in a `ClipData`.
1310 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), linkUrl);
1312 // Set the `ClipData` as the clipboard's primary clip.
1313 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
1318 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1319 menu.add(R.string.cancel);
1322 case WebView.HitTestResult.EMAIL_TYPE:
1323 // Get the target URL.
1324 linkUrl = hitTestResult.getExtra();
1326 // Set the target URL as the title of the `ContextMenu`.
1327 menu.setHeaderTitle(linkUrl);
1329 // Add a `Write Email` entry.
1330 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1332 public boolean onMenuItemClick(MenuItem item) {
1333 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1334 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1336 // Parse the url and set it as the data for the `Intent`.
1337 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1339 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1340 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1343 startActivity(emailIntent);
1348 // Add a `Copy Email Address` entry.
1349 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1351 public boolean onMenuItemClick(MenuItem item) {
1352 // Save the email address in a `ClipData`.
1353 ClipData srcEmailTypeClipData = ClipData.newPlainText(getResources().getString(R.string.email_address), linkUrl);
1355 // Set the `ClipData` as the clipboard's primary clip.
1356 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
1361 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1362 menu.add(R.string.cancel);
1365 // `IMAGE_TYPE` is an image.
1366 case WebView.HitTestResult.IMAGE_TYPE:
1367 // Get the image URL.
1368 imageUrl = hitTestResult.getExtra();
1370 // Set the image URL as the title of the `ContextMenu`.
1371 menu.setHeaderTitle(imageUrl);
1373 // Add a `View Image` entry.
1374 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1376 public boolean onMenuItemClick(MenuItem item) {
1377 mainWebView.loadUrl(imageUrl, customHeaders);
1382 // Add a `Download Image` entry.
1383 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1385 public boolean onMenuItemClick(MenuItem item) {
1386 // Show the `DownloadImage` `AlertDialog` and name this instance `@string/download`.
1387 AppCompatDialogFragment downloadImageDialogFragment = DownloadImage.imageUrl(imageUrl);
1388 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1393 // Add a `Copy URL` entry.
1394 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1396 public boolean onMenuItemClick(MenuItem item) {
1397 // Save the image URL in a `ClipData`.
1398 ClipData srcImageTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1400 // Set the `ClipData` as the clipboard's primary clip.
1401 clipboardManager.setPrimaryClip(srcImageTypeClipData);
1406 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1407 menu.add(R.string.cancel);
1411 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
1412 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1413 // Get the image URL.
1414 imageUrl = hitTestResult.getExtra();
1416 // Set the image URL as the title of the `ContextMenu`.
1417 menu.setHeaderTitle(imageUrl);
1419 // Add a `View Image` entry.
1420 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1422 public boolean onMenuItemClick(MenuItem item) {
1423 mainWebView.loadUrl(imageUrl, customHeaders);
1428 // Add a `Download Image` entry.
1429 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1431 public boolean onMenuItemClick(MenuItem item) {
1432 // Show the `DownloadImage` `AlertDialog` and name this instance `@string/download`.
1433 AppCompatDialogFragment downloadImageDialogFragment = DownloadImage.imageUrl(imageUrl);
1434 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1439 // Add a `Copy URL` entry.
1440 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1442 public boolean onMenuItemClick(MenuItem item) {
1443 // Save the image URL in a `ClipData`.
1444 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1446 // Set the `ClipData` as the clipboard's primary clip.
1447 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
1452 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1453 menu.add(R.string.cancel);
1459 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
1460 // Get shortcutNameEditText from the alert dialog.
1461 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
1463 // Create the bookmark shortcut based on formattedUrlString.
1464 Intent bookmarkShortcut = new Intent();
1465 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
1466 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
1468 // Place the bookmark shortcut on the home screen.
1469 Intent placeBookmarkShortcut = new Intent();
1470 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
1471 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
1472 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
1473 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
1474 sendBroadcast(placeBookmarkShortcut);
1478 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
1479 // Get a handle for the system `DOWNLOAD_SERVICE`.
1480 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1482 // Parse `imageUrl`.
1483 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
1485 // Get the file name from `dialogFragment`.
1486 EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
1487 String imageName = downloadImageNameEditText.getText().toString();
1489 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1490 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
1491 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
1492 } else { // Only set the title using `imageName`.
1493 downloadRequest.setTitle(imageName);
1496 // Allow `MediaScanner` to index the download if it is a media file.
1497 downloadRequest.allowScanningByMediaScanner();
1499 // Add the URL as the description for the download.
1500 downloadRequest.setDescription(imageUrl);
1502 // Show the download notification after the download is completed.
1503 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1505 // Initiate the download.
1506 downloadManager.enqueue(downloadRequest);
1510 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
1511 // Get a handle for the system `DOWNLOAD_SERVICE`.
1512 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1514 // Parse `downloadUrl`.
1515 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
1517 // Get the file name from `dialogFragment`.
1518 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
1519 String fileName = downloadFileNameEditText.getText().toString();
1521 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1522 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
1523 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
1524 } else { // Only set the title using `fileName`.
1525 downloadRequest.setTitle(fileName);
1528 // Allow `MediaScanner` to index the download if it is a media file.
1529 downloadRequest.allowScanningByMediaScanner();
1531 // Add the URL as the description for the download.
1532 downloadRequest.setDescription(downloadUrl);
1534 // Show the download notification after the download is completed.
1535 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1537 // Initiate the download.
1538 downloadManager.enqueue(downloadRequest);
1541 public void viewSslCertificate(View view) {
1542 // Show the `ViewSslCertificate` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
1543 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificate();
1544 viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
1548 public void onSslErrorCancel() {
1549 sslErrorHandler.cancel();
1553 public void onSslErrorProceed() {
1554 sslErrorHandler.proceed();
1558 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
1559 // Load the history entry.
1560 mainWebView.goBackOrForward(moveBackOrForwardSteps);
1564 public void onClearHistory() {
1565 // Clear the history.
1566 mainWebView.clearHistory();
1569 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
1571 public void onBackPressed() {
1572 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
1573 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1574 drawerLayout.closeDrawer(GravityCompat.START);
1576 // Load the previous URL if available.
1577 if (mainWebView.canGoBack()) {
1578 mainWebView.goBack();
1580 // Pass `onBackPressed()` to the system.
1581 super.onBackPressed();
1587 public void onPause() {
1588 // Pause `mainWebView`.
1589 mainWebView.onPause();
1591 // Stop all JavaScript.
1592 mainWebView.pauseTimers();
1594 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1595 if (BuildConfig.FLAVOR.contentEquals("free")) {
1596 BannerAd.pauseAd(adView);
1603 public void onResume() {
1606 // Resume JavaScript (if enabled).
1607 mainWebView.resumeTimers();
1609 // Resume `mainWebView`.
1610 mainWebView.onResume();
1612 // Resume the adView for the free flavor.
1613 if (BuildConfig.FLAVOR.contentEquals("free")) {
1614 BannerAd.resumeAd(adView);
1619 public void onRestart() {
1622 // Apply the settings from shared preferences, which might have been changed in `Settings`.
1625 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1626 updatePrivacyIcons(true);
1630 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
1631 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
1632 String unformattedUrlString = urlTextBox.getText().toString().trim();
1634 URL unformattedUrl = null;
1635 Uri.Builder formattedUri = new Uri.Builder();
1637 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
1638 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
1639 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
1640 if (!unformattedUrlString.startsWith("http")) {
1641 unformattedUrlString = "http://" + unformattedUrlString;
1644 // 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.
1646 unformattedUrl = new URL(unformattedUrlString);
1647 } catch (MalformedURLException e) {
1648 e.printStackTrace();
1651 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
1652 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
1653 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
1654 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
1655 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
1656 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
1658 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
1659 formattedUrlString = formattedUri.build().toString();
1661 // Sanitize the search input and convert it to a DuckDuckGo search.
1662 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
1664 // Use the correct search URL.
1665 if (javaScriptEnabled) { // JavaScript is enabled.
1666 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
1667 } else { // JavaScript is disabled.
1668 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
1672 mainWebView.loadUrl(formattedUrlString, customHeaders);
1674 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
1675 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1678 public void findPreviousOnPage(View view) {
1679 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
1680 mainWebView.findNext(false);
1683 public void findNextOnPage(View view) {
1684 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
1685 mainWebView.findNext(true);
1688 public void closeFindOnPage(View view) {
1689 // Delete the contents of `find_on_page_edittext`.
1690 findOnPageEditText.setText(null);
1692 // Clear the highlighted phrases.
1693 mainWebView.clearMatches();
1695 // Hide the Find on Page `RelativeLayout`.
1696 findOnPageLinearLayout.setVisibility(View.GONE);
1698 // Show the URL app bar.
1699 supportAppBar.setVisibility(View.VISIBLE);
1701 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
1702 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1705 private void applySettings() {
1706 // Get the shared preference values. `this` references the current context.
1707 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1709 // Store the values from `sharedPreferences` in variables.
1710 String userAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
1711 String customUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
1712 String javaScriptDisabledSearchString = sharedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
1713 String javaScriptDisabledCustomSearchString = sharedPreferences.getString("javascript_disabled_search_custom_url", "");
1714 String javaScriptEnabledSearchString = sharedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
1715 String javaScriptEnabledCustomSearchString = sharedPreferences.getString("javascript_enabled_search_custom_url", "");
1716 String homepageString = sharedPreferences.getString("homepage", "https://www.duckduckgo.com");
1717 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
1718 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh_enabled", false);
1719 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
1720 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
1721 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
1722 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("enable_full_screen_browsing_mode", false);
1723 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
1724 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
1726 // Because they can be modified on-the-fly by the user, these default settings are only applied when the program first runs.
1727 if (javaScriptEnabled == null) { // If `javaScriptEnabled` is null the program is just starting.
1728 // Get the values from `sharedPreferences`.
1729 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
1730 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
1731 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
1732 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
1733 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
1735 // Apply the default settings.
1736 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1737 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1738 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1739 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1740 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
1742 // Set third-party cookies status if API >= 21.
1743 if (Build.VERSION.SDK_INT >= 21) {
1744 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1748 // Apply the other settings from `sharedPreferences`.
1749 homepage = homepageString;
1750 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
1752 // Set the user agent initial status.
1753 switch (userAgentString) {
1754 case "Default user agent":
1755 // Set the user agent to `""`, which uses the default value.
1756 mainWebView.getSettings().setUserAgentString("");
1759 case "Custom user agent":
1760 // Set the custom user agent.
1761 mainWebView.getSettings().setUserAgentString(customUserAgentString);
1765 // Use the selected user agent.
1766 mainWebView.getSettings().setUserAgentString(userAgentString);
1770 // Set JavaScript disabled search.
1771 if (javaScriptDisabledSearchString.equals("Custom URL")) { // Get the custom URL string.
1772 javaScriptDisabledSearchURL = javaScriptDisabledCustomSearchString;
1773 } else { // Use the string from the pre-built list.
1774 javaScriptDisabledSearchURL = javaScriptDisabledSearchString;
1777 // Set JavaScript enabled search.
1778 if (javaScriptEnabledSearchString.equals("Custom URL")) { // Get the custom URL string.
1779 javaScriptEnabledSearchURL = javaScriptEnabledCustomSearchString;
1780 } else { // Use the string from the pre-built list.
1781 javaScriptEnabledSearchURL = javaScriptEnabledSearchString;
1784 // Set Do Not Track status.
1785 if (doNotTrackEnabled) {
1786 customHeaders.put("DNT", "1");
1788 customHeaders.remove("DNT");
1791 // Set Orbot proxy status.
1792 if (proxyThroughOrbot) {
1793 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
1794 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
1795 } else { // Reset the proxy to default. The host is `""` and the port is `"0"`.
1796 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
1799 // If we are in full screen mode update the `SYSTEM_UI` flags.
1800 if (inFullScreenBrowsingMode) {
1801 if (hideSystemBarsOnFullscreen) { // Hide everything.
1802 // Remove the translucent navigation setting if it is currently flagged.
1803 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1805 // Remove the translucent status bar overlay.
1806 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1808 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1809 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1811 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1812 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1813 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
1815 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1816 } else { // Hide everything except the status and navigation bars.
1817 // Add the translucent status flag if it is unset.
1818 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1820 if (translucentNavigationBarOnFullscreen) {
1821 // Set the navigation bar to be translucent.
1822 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1824 // Set the navigation bar to be black.
1825 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1831 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
1832 // Get handles for the icons.
1833 MenuItem privacyIcon = mainMenu.findItem(R.id.toggleJavaScript);
1834 MenuItem firstPartyCookiesIcon = mainMenu.findItem(R.id.toggleFirstPartyCookies);
1835 MenuItem domStorageIcon = mainMenu.findItem(R.id.toggleDomStorage);
1836 MenuItem formDataIcon = mainMenu.findItem(R.id.toggleSaveFormData);
1838 // Update `privacyIcon`.
1839 if (javaScriptEnabled) { // JavaScript is enabled.
1840 privacyIcon.setIcon(R.drawable.javascript_enabled);
1841 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
1842 privacyIcon.setIcon(R.drawable.warning);
1843 } else { // All the dangerous features are disabled.
1844 privacyIcon.setIcon(R.drawable.privacy_mode);
1847 // Update `firstPartyCookiesIcon`.
1848 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1849 firstPartyCookiesIcon.setIcon(R.drawable.cookies_enabled);
1850 } else { // First-party cookies are disabled.
1851 firstPartyCookiesIcon.setIcon(R.drawable.cookies_disabled);
1854 // Update `domStorageIcon`.
1855 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
1856 domStorageIcon.setIcon(R.drawable.dom_storage_enabled);
1857 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
1858 domStorageIcon.setIcon(R.drawable.dom_storage_disabled);
1859 } else { // JavaScript is disabled, so DOM storage is ghosted.
1860 domStorageIcon.setIcon(R.drawable.dom_storage_ghosted);
1863 // Update `formDataIcon`.
1864 if (saveFormDataEnabled) { // Form data is enabled.
1865 formDataIcon.setIcon(R.drawable.form_data_enabled);
1866 } else { // Form data is disabled.
1867 formDataIcon.setIcon(R.drawable.form_data_disabled);
1870 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
1871 if (runInvalidateOptionsMenu) {
1872 ActivityCompat.invalidateOptionsMenu(this);