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.database.Cursor;
36 import android.graphics.Bitmap;
37 import android.graphics.drawable.BitmapDrawable;
38 import android.graphics.drawable.Drawable;
39 import android.net.Uri;
40 import android.net.http.SslCertificate;
41 import android.net.http.SslError;
42 import android.os.Build;
43 import android.os.Bundle;
44 import android.preference.PreferenceManager;
45 import android.print.PrintDocumentAdapter;
46 import android.print.PrintManager;
47 import android.support.annotation.NonNull;
48 import android.support.design.widget.CoordinatorLayout;
49 import android.support.design.widget.NavigationView;
50 import android.support.design.widget.Snackbar;
51 import android.support.v4.app.ActivityCompat;
52 import android.support.v4.content.ContextCompat;
53 import android.support.v4.view.GravityCompat;
54 import android.support.v4.widget.DrawerLayout;
55 import android.support.v4.widget.SwipeRefreshLayout;
56 import android.support.v7.app.ActionBar;
57 import android.support.v7.app.ActionBarDrawerToggle;
58 import android.support.v7.app.AppCompatActivity;
59 import android.support.v7.app.AppCompatDialogFragment;
60 import android.support.v7.widget.Toolbar;
61 import android.text.Editable;
62 import android.text.TextWatcher;
63 import android.util.Patterns;
64 import android.view.ContextMenu;
65 import android.view.GestureDetector;
66 import android.view.KeyEvent;
67 import android.view.Menu;
68 import android.view.MenuItem;
69 import android.view.MotionEvent;
70 import android.view.View;
71 import android.view.WindowManager;
72 import android.view.inputmethod.InputMethodManager;
73 import android.webkit.CookieManager;
74 import android.webkit.DownloadListener;
75 import android.webkit.SslErrorHandler;
76 import android.webkit.WebBackForwardList;
77 import android.webkit.WebChromeClient;
78 import android.webkit.WebResourceResponse;
79 import android.webkit.WebStorage;
80 import android.webkit.WebView;
81 import android.webkit.WebViewClient;
82 import android.webkit.WebViewDatabase;
83 import android.widget.EditText;
84 import android.widget.FrameLayout;
85 import android.widget.ImageView;
86 import android.widget.LinearLayout;
87 import android.widget.ProgressBar;
88 import android.widget.RelativeLayout;
89 import android.widget.TextView;
91 import com.stoutner.privacybrowser.BannerAd;
92 import com.stoutner.privacybrowser.BuildConfig;
93 import com.stoutner.privacybrowser.R;
94 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
95 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
96 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
97 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
98 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
99 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
100 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
101 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
103 import java.io.BufferedReader;
104 import java.io.ByteArrayInputStream;
105 import java.io.IOException;
106 import java.io.InputStreamReader;
107 import java.io.UnsupportedEncodingException;
108 import java.net.MalformedURLException;
110 import java.net.URLDecoder;
111 import java.net.URLEncoder;
112 import java.util.HashMap;
113 import java.util.HashSet;
114 import java.util.Map;
115 import java.util.Set;
117 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
118 public class MainWebViewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcutDialog.CreateHomeScreenSchortcutListener,
119 SslCertificateErrorDialog.SslCertificateErrorListener, DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, UrlHistoryDialog.UrlHistoryListener {
121 // `appBar` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
122 public static ActionBar appBar;
124 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `ViewSslCertificateDialog`.
125 // It is also used in `onCreate()`, `onCreateHomeScreenShortcutCreate()`, and `applyDomainSettings`.
126 public static Bitmap favoriteIconBitmap;
128 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
129 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
130 public static String formattedUrlString;
132 // `sslCertificate` is public static so it can be accessed from `ViewSslCertificateDialog`. It is also used in `onCreate()`.
133 public static SslCertificate sslCertificate;
135 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`.
136 public static String orbotStatus;
138 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
139 public static String webViewTitle;
141 // `displayWebpageImagesBoolean` is public static so it can be accessed from `DomainSettingsFragment`. It is also used in `applyAppSettings()` and `applyDomainSettings()`.
142 public static boolean displayWebpageImagesBoolean;
144 // `reloadOnRestartBoolean` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`
145 public static boolean reloadOnRestartBoolean;
148 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, and `applyDomainSettings()`.
149 private boolean navigatingHistory;
151 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
152 private Bitmap favoriteIconDefaultBitmap;
154 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
155 private DrawerLayout drawerLayout;
157 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
158 private CoordinatorLayout rootCoordinatorLayout;
160 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`
161 // and `setDisplayWebpageImages()`.
162 private WebView mainWebView;
164 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
165 private FrameLayout fullScreenVideoFrameLayout;
167 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
168 private SwipeRefreshLayout swipeRefreshLayout;
170 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
171 private RelativeLayout urlAppBarRelativeLayout;
173 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
174 private ImageView favoriteIconImageView;
176 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
177 private CookieManager cookieManager;
179 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
180 private final Map<String, String> customHeaders = new HashMap<>();
182 // `javaScriptEnabled` is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `applyAppSettings()`.
183 // It is `Boolean` instead of `boolean` because `applyAppSettings()` needs to know if it is `null`.
184 private Boolean javaScriptEnabled;
186 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyAppSettings()`.
187 private boolean firstPartyCookiesEnabled;
189 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
190 private boolean thirdPartyCookiesEnabled;
192 // `domStorageEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
193 private boolean domStorageEnabled;
195 // `saveFormDataEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
196 private boolean saveFormDataEnabled;
198 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applyAppSettings()`.
199 private boolean swipeToRefreshEnabled;
201 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
202 private String homepage;
204 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
205 private String searchURL;
207 // `adBlockerEnabled` is used in `onCreate()` and `applyAppSettings()`.
208 private boolean adBlockerEnabled;
210 // `privacyBrowserRuntime` is used in `onCreate()` and `applyAppSettings()`.
211 private Runtime privacyBrowserRuntime;
213 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
214 private boolean incognitoModeEnabled;
216 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
217 private boolean fullScreenBrowsingModeEnabled;
219 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
220 private boolean inFullScreenBrowsingMode;
222 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
223 private boolean hideSystemBarsOnFullscreen;
225 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
226 private boolean translucentNavigationBarOnFullscreen;
228 // `currentDomainName` is used in `onCreate()`, `onNavigationItemSelected()`, and `applyDomainSettings()`.
229 private String currentDomainName;
231 // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
232 private boolean waitingForOrbot;
234 // `domainSettingsApplied` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
235 private boolean domainSettingsApplied;
237 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
238 private int displayWebpageImagesInt;
240 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
241 private boolean onTheFlyDisplayImagesSet;
243 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
244 private String waitingForOrbotHTMLString;
246 // `privateDataDirectoryString` is used in `onCreate()` and `onNavigationItemSelected()`.
247 private String privateDataDirectoryString;
249 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
250 private LinearLayout findOnPageLinearLayout;
252 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
253 private EditText findOnPageEditText;
255 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
256 private Menu mainMenu;
258 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
259 private ActionBarDrawerToggle drawerToggle;
261 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
262 private Toolbar supportAppBar;
264 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `loadUrl()`.
265 private EditText urlTextBox;
267 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
270 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
271 private SslErrorHandler sslErrorHandler;
273 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
274 private InputMethodManager inputMethodManager;
276 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
277 private RelativeLayout mainWebViewRelativeLayout;
280 // 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.
281 @SuppressLint("SetJavaScriptEnabled")
282 protected void onCreate(Bundle savedInstanceState) {
283 super.onCreate(savedInstanceState);
284 setContentView(R.layout.main_drawerlayout);
286 // Get a handle for `inputMethodManager`.
287 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
289 // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
290 supportAppBar = (Toolbar) findViewById(R.id.app_bar);
291 setSupportActionBar(supportAppBar);
292 appBar = getSupportActionBar();
294 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
295 assert appBar != null;
297 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
298 appBar.setCustomView(R.layout.url_app_bar);
299 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
301 // Set the "go" button on the keyboard to load the URL in urlTextBox.
302 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.url_edittext);
303 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
305 public boolean onKey(View v, int keyCode, KeyEvent event) {
306 // If the event is a key-down event on the `enter` button, load the URL.
307 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
308 // Load the URL into the mainWebView and consume the event.
310 loadUrlFromTextBox();
311 } catch (UnsupportedEncodingException e) {
314 // If the enter key was pressed, consume the event.
317 // If any other key was pressed, do not consume the event.
323 // Set `waitingForOrbotHTMLString`.
324 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
326 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
327 currentDomainName = "";
328 orbotStatus = "unknown";
329 waitingForOrbot = false;
331 // Create an Orbot status `BroadcastReceiver`.
332 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
334 public void onReceive(Context context, Intent intent) {
335 // Store the content of the status message in `orbotStatus`.
336 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
338 // If we are waiting on Orbot, load the website now that Orbot is connected.
339 if (orbotStatus.equals("ON") && waitingForOrbot) {
340 // Reset `waitingForOrbot`.
341 waitingForOrbot = false;
343 // Load `formattedUrlString
344 loadUrl(formattedUrlString);
349 // Register `orbotStatusBroadcastReceiver` on `this` context.
350 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
352 // Get handles for views that need to be accessed.
353 drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
354 rootCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.root_coordinatorlayout);
355 mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.main_webview_relativelayout);
356 mainWebView = (WebView) findViewById(R.id.main_webview);
357 findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
358 findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
359 fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.full_screen_video_framelayout);
360 urlAppBarRelativeLayout = (RelativeLayout) findViewById(R.id.url_app_bar_relativelayout);
361 favoriteIconImageView = (ImageView) findViewById(R.id.favorite_icon);
363 // Create a double-tap listener to toggle full-screen mode.
364 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
365 // Override `onDoubleTap()`. All other events are handled using the default settings.
367 public boolean onDoubleTap(MotionEvent event) {
368 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
369 // Toggle `inFullScreenBrowsingMode`.
370 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
372 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
373 // Hide the `appBar`.
376 // Hide the `BannerAd` in the free flavor.
377 if (BuildConfig.FLAVOR.contentEquals("free")) {
378 BannerAd.hideAd(adView);
381 // Modify the system bars.
382 if (hideSystemBarsOnFullscreen) { // Hide everything.
383 // Remove the translucent overlays.
384 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
386 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
387 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
389 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
390 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
391 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
393 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
395 // Set `rootCoordinatorLayout` to fill the whole screen.
396 rootCoordinatorLayout.setFitsSystemWindows(false);
397 } else { // Hide everything except the status and navigation bars.
398 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
399 rootCoordinatorLayout.setFitsSystemWindows(false);
401 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.
402 // Set the navigation bar to be translucent.
403 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
406 } else { // Switch to normal viewing mode.
407 // Show the `appBar`.
410 // Show the `BannerAd` in the free flavor.
411 if (BuildConfig.FLAVOR.contentEquals("free")) {
412 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
413 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
415 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
416 adView = findViewById(R.id.adview);
419 // Remove the translucent navigation bar flag if it is set.
420 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
422 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
423 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
425 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
426 rootCoordinatorLayout.setSystemUiVisibility(0);
428 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
429 rootCoordinatorLayout.setFitsSystemWindows(true);
432 // Consume the double-tap.
434 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
440 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
441 mainWebView.setOnTouchListener(new View.OnTouchListener() {
443 public boolean onTouch(View v, MotionEvent event) {
444 // Send the `event` to `gestureDetector`.
445 return gestureDetector.onTouchEvent(event);
449 // Update `findOnPageCountTextView`.
450 mainWebView.setFindListener(new WebView.FindListener() {
451 // Get a handle for `findOnPageCountTextView`.
452 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
455 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
456 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
457 // Set `findOnPageCountTextView` to `0/0`.
458 findOnPageCountTextView.setText(R.string.zero_of_zero);
459 } else if (isDoneCounting) { // There are matches.
460 // `activeMatchOrdinal` is zero-based.
461 int activeMatch = activeMatchOrdinal + 1;
463 // Set `findOnPageCountTextView`.
464 findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
469 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
470 findOnPageEditText.addTextChangedListener(new TextWatcher() {
472 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
477 public void onTextChanged(CharSequence s, int start, int before, int count) {
482 public void afterTextChanged(Editable s) {
483 // Search for the text in `mainWebView`.
484 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
488 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
489 findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
491 public boolean onKey(View v, int keyCode, KeyEvent event) {
492 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
493 // Hide the soft keyboard. `0` indicates no additional flags.
494 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
496 // Consume the event.
498 } else { // A different key was pressed.
499 // Do not consume the event.
505 // Implement swipe to refresh
506 swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refreshlayout);
507 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
508 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
510 public void onRefresh() {
511 mainWebView.reload();
515 // `DrawerTitle` identifies the `DrawerLayout` in accessibility mode.
516 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
518 // Listen for touches on the navigation menu.
519 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationview);
520 navigationView.setNavigationItemSelectedListener(this);
522 // 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.
523 final Menu navigationMenu = navigationView.getMenu();
524 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
525 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
526 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
528 // The `DrawerListener` allows us to update the Navigation Menu.
529 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
531 public void onDrawerSlide(View drawerView, float slideOffset) {
535 public void onDrawerOpened(View drawerView) {
539 public void onDrawerClosed(View drawerView) {
543 public void onDrawerStateChanged(int newState) {
544 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
545 // Update the `Back`, `Forward`, and `History` menu items.
546 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
547 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
548 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
550 // Hide the keyboard so we can see the navigation menu. `0` indicates no additional flags.
551 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
556 // drawerToggle creates the hamburger icon at the start of the AppBar.
557 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
559 // Initialize `adServerSet`.
560 final Set<String> adServersSet = new HashSet<>();
562 // Load the list of ad servers into memory.
564 // Load `pgl.yoyo.org_adservers.txt` into a `BufferedReader`.
565 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("pgl.yoyo.org_adservers.txt")));
567 // Create a string for storing each ad server.
570 // Populate `adServersSet`.
571 while ((adServer = bufferedReader.readLine()) != null) {
572 adServersSet.add(adServer);
575 // Close `bufferedReader`.
576 bufferedReader.close();
577 } catch (IOException ioException) {
578 // We're pretty sure the asset exists, so we don't need to worry about the `IOException` ever being thrown.
581 mainWebView.setWebViewClient(new WebViewClient() {
582 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
583 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
584 @SuppressWarnings("deprecation")
586 public boolean shouldOverrideUrlLoading(WebView view, String url) {
587 if (url.startsWith("mailto:")) { // Load the URL in an external email program because it begins with `mailto:`.
588 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
589 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
591 // Parse the url and set it as the data for the `Intent`.
592 emailIntent.setData(Uri.parse(url));
594 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
595 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
598 startActivity(emailIntent);
600 // Returning `true` indicates the application is handling the URL.
602 } else { // Load the URL in Privacy Browser.
603 // Apply the domain settings for the new URL.
604 applyDomainSettings(url);
606 // Returning `false` causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
611 // Block ads. We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
612 @SuppressWarnings("deprecation")
614 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
615 if (adBlockerEnabled) { // Block ads.
616 // Extract the host from `url`.
617 Uri requestUri = Uri.parse(url);
618 String requestHost = requestUri.getHost();
620 // Initialize a variable to track if this is an ad server.
621 boolean requestHostIsAdServer = false;
623 // Check all the subdomains of `requestHost` if it is not `null` against the ad server database.
624 if (requestHost != null) {
625 while (requestHost.contains(".") && !requestHostIsAdServer) { // Stop checking if we run out of `.` or if we already know that `requestHostIsAdServer` is `true`.
626 if (adServersSet.contains(requestHost)) {
627 requestHostIsAdServer = true;
630 // Strip out the lowest subdomain of `requestHost`.
631 requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
635 if (requestHostIsAdServer) { // It is an ad server.
636 // Return an empty `WebResourceResponse`.
637 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
638 } else { // It is not an ad server.
639 // `return null` loads the requested resource.
642 } else { // Ad blocking is disabled.
643 // `return null` loads the requested resource.
648 // Update the URL in urlTextBox when the page starts to load.
650 public void onPageStarted(WebView view, String url, Bitmap favicon) {
651 // Reset `webViewTitle`
652 webViewTitle = getString(R.string.no_title);
654 // Check to see if we are waiting on Orbot.
655 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
656 // 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.
657 formattedUrlString = url;
659 // Display the loading URL is the URL text box.
660 urlTextBox.setText(url);
662 // Apply any custom domain settings if the URL was loaded by navigating history.
663 if (navigatingHistory) {
664 applyDomainSettings(url);
669 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
671 public void onPageFinished(WebView view, String url) {
672 // Clear the cache and history if Incognito Mode is enabled.
673 if (incognitoModeEnabled) {
674 // Clear the cache. `true` includes disk files.
675 mainWebView.clearCache(true);
677 // Clear the back/forward history.
678 mainWebView.clearHistory();
680 // Manually delete cache folders.
682 // Delete the main `cache` folder.
683 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
685 // 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`.
686 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
687 } catch (IOException e) {
688 // Do nothing if an error is thrown.
692 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
693 if (!waitingForOrbot) {
694 // Check to see if `WebView` has set `url` to be `about:blank`.
695 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
696 // Set `formattedUrlString` to `""`.
697 formattedUrlString = "";
699 // Update `urlTextBox`.
700 urlTextBox.setText(formattedUrlString);
702 // Request focus for `urlTextBox`.
703 urlTextBox.requestFocus();
705 // Display the keyboard.
706 inputMethodManager.showSoftInput(urlTextBox, 0);
708 // Apply the domain settings.
709 applyDomainSettings(formattedUrlString);
710 } else { // `WebView` has loaded a webpage.
711 // Set `formattedUrlString`.
712 formattedUrlString = url;
714 // Only update `urlTextBox` if the user is not typing in it.
715 if (!urlTextBox.hasFocus()) {
716 urlTextBox.setText(formattedUrlString);
720 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog`.
721 sslCertificate = mainWebView.getCertificate();
725 // Handle SSL Certificate errors.
727 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
728 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
729 sslErrorHandler = handler;
731 // Display the SSL error `AlertDialog`.
732 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
733 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
737 // Get a handle for the progress bar.
738 final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
740 mainWebView.setWebChromeClient(new WebChromeClient() {
741 // Update the progress bar when a page is loading.
743 public void onProgressChanged(WebView view, int progress) {
744 progressBar.setProgress(progress);
745 if (progress < 100) {
746 progressBar.setVisibility(View.VISIBLE);
748 progressBar.setVisibility(View.GONE);
750 //Stop the `SwipeToRefresh` indicator if it is running
751 swipeRefreshLayout.setRefreshing(false);
755 // Set the favorite icon when it changes.
757 public void onReceivedIcon(WebView view, Bitmap icon) {
758 // Only update the favorite icon if the website has finished loading.
759 if (progressBar.getVisibility() == View.GONE) {
760 // Save a copy of the favorite icon.
761 favoriteIconBitmap = icon;
763 // Place the favorite icon in the appBar.
764 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
768 // Save a copy of the title when it changes.
770 public void onReceivedTitle(WebView view, String title) {
771 // Save a copy of the title.
772 webViewTitle = title;
775 // Enter full screen video
777 public void onShowCustomView(View view, CustomViewCallback callback) {
778 // Pause the ad if this is the free flavor.
779 if (BuildConfig.FLAVOR.contentEquals("free")) {
780 BannerAd.pauseAd(adView);
783 // Remove the translucent overlays.
784 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
786 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
787 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
789 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
790 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
791 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
793 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
795 // Set `rootCoordinatorLayout` to fill the entire screen.
796 rootCoordinatorLayout.setFitsSystemWindows(false);
798 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
799 fullScreenVideoFrameLayout.addView(view);
800 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
803 // Exit full screen video
804 public void onHideCustomView() {
805 // Hide `fullScreenVideoFrameLayout`.
806 fullScreenVideoFrameLayout.removeAllViews();
807 fullScreenVideoFrameLayout.setVisibility(View.GONE);
809 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
810 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
812 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
813 rootCoordinatorLayout.setFitsSystemWindows(true);
815 // Show the ad if this is the free flavor.
816 if (BuildConfig.FLAVOR.contentEquals("free")) {
817 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
818 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
820 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
821 adView = findViewById(R.id.adview);
826 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
827 registerForContextMenu(mainWebView);
829 // Allow the downloading of files.
830 mainWebView.setDownloadListener(new DownloadListener() {
832 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
833 // Show the `DownloadFileDialog` `AlertDialog` and name this instance `@string/download`.
834 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
835 downloadFileDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
839 // Allow pinch to zoom.
840 mainWebView.getSettings().setBuiltInZoomControls(true);
842 // Hide zoom controls.
843 mainWebView.getSettings().setDisplayZoomControls(false);
845 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
846 mainWebView.getSettings().setUseWideViewPort(true);
848 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
849 mainWebView.getSettings().setLoadWithOverviewMode(true);
851 // Initialize cookieManager.
852 cookieManager = CookieManager.getInstance();
854 // 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).
855 customHeaders.put("X-Requested-With", "");
857 // 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.
858 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
860 // Get the intent that started the app.
861 final Intent launchingIntent = getIntent();
863 // Extract the launching intent data as `launchingIntentUriData`.
864 final Uri launchingIntentUriData = launchingIntent.getData();
866 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
867 if (launchingIntentUriData != null) {
868 formattedUrlString = launchingIntentUriData.toString();
871 // Get a handle for the `Runtime`.
872 privacyBrowserRuntime = Runtime.getRuntime();
874 // Store the application's private data directory.
875 privateDataDirectoryString = 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`.
877 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
878 inFullScreenBrowsingMode = false;
880 // Initialize AdView for the free flavor.
881 adView = findViewById(R.id.adview);
883 // Initialize the privacy settings variables.
884 javaScriptEnabled = false;
885 firstPartyCookiesEnabled = false;
886 thirdPartyCookiesEnabled = false;
887 domStorageEnabled = false;
888 saveFormDataEnabled = false;
890 // Initialize `webViewTitle`.
891 webViewTitle = getString(R.string.no_title);
893 // Initialize `favoriteIconBitmap`. We have to use `ContextCompat` until API >= 21.
894 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
895 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
896 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
898 // If the favorite icon is null, load the default.
899 if (favoriteIconBitmap == null) {
900 favoriteIconBitmap = favoriteIconDefaultBitmap;
903 // Apply the app settings from the shared preferences.
906 // Load `formattedUrlString` if we are not waiting for Orbot to connect.
907 if (!waitingForOrbot) {
908 loadUrl(formattedUrlString);
913 protected void onNewIntent(Intent intent) {
914 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
917 if (intent.getData() != null) {
918 // Get the intent data and convert it to a string.
919 final Uri intentUriData = intent.getData();
920 formattedUrlString = intentUriData.toString();
923 // Close the navigation drawer if it is open.
924 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
925 drawerLayout.closeDrawer(GravityCompat.START);
929 loadUrl(formattedUrlString);
931 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
932 mainWebView.requestFocus();
936 public void onRestart() {
939 // Apply the app settings, which may have been changed in `SettingsActivity`.
942 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
943 updatePrivacyIcons(true);
945 // Set the display webpage images mode.
946 setDisplayWebpageImages();
948 // Reload the webpage if displaying of images has been disabled in `SettingsFragment`.
949 if (reloadOnRestartBoolean) {
950 // Reload `mainWebView`.
951 mainWebView.reload();
953 // Reset `reloadOnRestartBoolean`.
954 reloadOnRestartBoolean = false;
958 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
960 public void onResume() {
963 // Resume JavaScript (if enabled).
964 mainWebView.resumeTimers();
966 // Resume `mainWebView`.
967 mainWebView.onResume();
969 // Resume the adView for the free flavor.
970 if (BuildConfig.FLAVOR.contentEquals("free")) {
971 BannerAd.resumeAd(adView);
976 public void onPause() {
977 // Pause `mainWebView`.
978 mainWebView.onPause();
980 // Stop all JavaScript.
981 mainWebView.pauseTimers();
983 // Pause the adView or it will continue to consume resources in the background on the free flavor.
984 if (BuildConfig.FLAVOR.contentEquals("free")) {
985 BannerAd.pauseAd(adView);
992 public boolean onCreateOptionsMenu(Menu menu) {
993 // Inflate the menu; this adds items to the action bar if it is present.
994 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
996 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
999 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1000 updatePrivacyIcons(false);
1002 // Get handles for the menu items.
1003 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1004 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1005 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1006 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1008 // Only display third-party cookies if SDK >= 21
1009 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1011 // Get the shared preference values. `this` references the current context.
1012 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1014 // Set the status of the additional app bar icons. The default is `false`.
1015 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1016 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1017 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1018 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1019 } else { //Do not display the additional icons.
1020 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1021 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1022 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1029 public boolean onPrepareOptionsMenu(Menu menu) {
1030 // Get handles for the menu items.
1031 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1032 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1033 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1034 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1035 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1036 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1037 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1038 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1039 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1041 // Set the status of the menu item checkboxes.
1042 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1043 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1044 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1045 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1046 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1048 // Enable third-party cookies if first-party cookies are enabled.
1049 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1051 // Enable DOM Storage if JavaScript is enabled.
1052 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1054 // Enable Clear Cookies if there are any.
1055 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1057 // Enable Clear Form Data is there is any.
1058 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1059 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1061 // Initialize font size variables.
1062 int fontSize = mainWebView.getSettings().getTextZoom();
1063 String fontSizeTitle;
1064 MenuItem selectedFontSizeMenuItem;
1066 // Prepare the font size title and current size menu item.
1069 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.twenty_five_percent);
1070 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1074 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
1075 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1079 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
1080 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1084 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1085 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1089 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
1090 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1094 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
1095 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1099 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
1100 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1104 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
1105 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1109 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1110 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1114 // Set the font size title and select the current size menu item.
1115 fontSizeMenuItem.setTitle(fontSizeTitle);
1116 selectedFontSizeMenuItem.setChecked(true);
1118 // Only show `Refresh` if `swipeToRefresh` is disabled.
1119 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1121 // Run all the other default commands.
1122 super.onPrepareOptionsMenu(menu);
1124 // `return true` displays the menu.
1129 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1130 @SuppressLint("SetJavaScriptEnabled")
1131 // removeAllCookies is deprecated, but it is required for API < 21.
1132 @SuppressWarnings("deprecation")
1133 public boolean onOptionsItemSelected(MenuItem menuItem) {
1134 int menuItemId = menuItem.getItemId();
1136 // Set the commands that relate to the menu entries.
1137 switch (menuItemId) {
1138 case R.id.toggle_javascript:
1139 // Switch the status of javaScriptEnabled.
1140 javaScriptEnabled = !javaScriptEnabled;
1142 // Apply the new JavaScript status.
1143 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1145 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1146 updatePrivacyIcons(true);
1148 // Display a `Snackbar`.
1149 if (javaScriptEnabled) { // JavaScrip is enabled.
1150 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1151 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1152 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1153 } else { // Privacy mode.
1154 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1157 // Reload the WebView.
1158 mainWebView.reload();
1161 case R.id.toggle_first_party_cookies:
1162 // Switch the status of firstPartyCookiesEnabled.
1163 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1165 // Update the menu checkbox.
1166 menuItem.setChecked(firstPartyCookiesEnabled);
1168 // Apply the new cookie status.
1169 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1171 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1172 updatePrivacyIcons(true);
1174 // Display a `Snackbar`.
1175 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1176 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1177 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1178 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1179 } else { // Privacy mode.
1180 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1183 // Reload the WebView.
1184 mainWebView.reload();
1187 case R.id.toggle_third_party_cookies:
1188 if (Build.VERSION.SDK_INT >= 21) {
1189 // Switch the status of thirdPartyCookiesEnabled.
1190 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1192 // Update the menu checkbox.
1193 menuItem.setChecked(thirdPartyCookiesEnabled);
1195 // Apply the new cookie status.
1196 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1198 // Display a `Snackbar`.
1199 if (thirdPartyCookiesEnabled) {
1200 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1202 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1205 // Reload the WebView.
1206 mainWebView.reload();
1207 } // Else do nothing because SDK < 21.
1210 case R.id.toggle_dom_storage:
1211 // Switch the status of domStorageEnabled.
1212 domStorageEnabled = !domStorageEnabled;
1214 // Update the menu checkbox.
1215 menuItem.setChecked(domStorageEnabled);
1217 // Apply the new DOM Storage status.
1218 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1220 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1221 updatePrivacyIcons(true);
1223 // Display a `Snackbar`.
1224 if (domStorageEnabled) {
1225 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1227 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1230 // Reload the WebView.
1231 mainWebView.reload();
1234 case R.id.toggle_save_form_data:
1235 // Switch the status of saveFormDataEnabled.
1236 saveFormDataEnabled = !saveFormDataEnabled;
1238 // Update the menu checkbox.
1239 menuItem.setChecked(saveFormDataEnabled);
1241 // Apply the new form data status.
1242 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1244 // Display a `Snackbar`.
1245 if (saveFormDataEnabled) {
1246 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1248 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1251 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1252 updatePrivacyIcons(true);
1254 // Reload the WebView.
1255 mainWebView.reload();
1258 case R.id.clear_cookies:
1259 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1260 .setAction(R.string.undo, new View.OnClickListener() {
1262 public void onClick(View v) {
1263 // Do nothing because everything will be handled by `onDismissed()` below.
1266 .addCallback(new Snackbar.Callback() {
1268 public void onDismissed(Snackbar snackbar, int event) {
1270 // The user pushed the `Undo` button.
1271 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1275 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1277 // `cookieManager.removeAllCookie()` varies by SDK.
1278 if (Build.VERSION.SDK_INT < 21) {
1279 cookieManager.removeAllCookie();
1281 // `null` indicates no callback.
1282 cookieManager.removeAllCookies(null);
1290 case R.id.clear_dom_storage:
1291 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1292 .setAction(R.string.undo, new View.OnClickListener() {
1294 public void onClick(View v) {
1295 // Do nothing because everything will be handled by `onDismissed()` below.
1298 .addCallback(new Snackbar.Callback() {
1300 public void onDismissed(Snackbar snackbar, int event) {
1302 // The user pushed the `Undo` button.
1303 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1307 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1309 // Delete the DOM Storage.
1310 WebStorage webStorage = WebStorage.getInstance();
1311 webStorage.deleteAllData();
1318 case R.id.clear_form_data:
1319 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1320 .setAction(R.string.undo, new View.OnClickListener() {
1322 public void onClick(View v) {
1323 // Do nothing because everything will be handled by `onDismissed()` below.
1326 .addCallback(new Snackbar.Callback() {
1328 public void onDismissed(Snackbar snackbar, int event) {
1330 // The user pushed the `Undo` button.
1331 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1335 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1337 // Delete the form data.
1338 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1339 mainWebViewDatabase.clearFormData();
1346 case R.id.font_size_twenty_five_percent:
1347 mainWebView.getSettings().setTextZoom(25);
1350 case R.id.font_size_fifty_percent:
1351 mainWebView.getSettings().setTextZoom(50);
1354 case R.id.font_size_seventy_five_percent:
1355 mainWebView.getSettings().setTextZoom(75);
1358 case R.id.font_size_one_hundred_percent:
1359 mainWebView.getSettings().setTextZoom(100);
1362 case R.id.font_size_one_hundred_twenty_five_percent:
1363 mainWebView.getSettings().setTextZoom(125);
1366 case R.id.font_size_one_hundred_fifty_percent:
1367 mainWebView.getSettings().setTextZoom(150);
1370 case R.id.font_size_one_hundred_seventy_five_percent:
1371 mainWebView.getSettings().setTextZoom(175);
1374 case R.id.font_size_two_hundred_percent:
1375 mainWebView.getSettings().setTextZoom(200);
1378 case R.id.display_images:
1379 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1380 mainWebView.getSettings().setLoadsImagesAutomatically(false);
1381 mainWebView.reload();
1382 } else { // Images are not currently loaded automatically.
1383 mainWebView.getSettings().setLoadsImagesAutomatically(true);
1386 // Set `onTheFlyDisplayImagesSet`.
1387 onTheFlyDisplayImagesSet = true;
1391 // Setup the share string.
1393 if (webViewTitle != null) {
1394 shareString = webViewTitle + " – " + urlTextBox.getText().toString();
1396 shareString = urlTextBox.getText().toString();
1399 // Create the share intent.
1400 Intent shareIntent = new Intent();
1401 shareIntent.setAction(Intent.ACTION_SEND);
1402 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1403 shareIntent.setType("text/plain");
1406 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1409 case R.id.find_on_page:
1410 // Hide the URL app bar.
1411 supportAppBar.setVisibility(View.GONE);
1413 // Show the Find on Page `RelativeLayout`.
1414 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1416 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
1417 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1418 findOnPageEditText.postDelayed(new Runnable()
1423 // Set the focus on `findOnPageEditText`.
1424 findOnPageEditText.requestFocus();
1426 // Display the keyboard.
1427 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1433 // Get a `PrintManager` instance.
1434 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1436 // Convert `mainWebView` to `printDocumentAdapter`.
1437 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1439 // Print the document. The print attributes are `null`.
1440 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1443 case R.id.add_to_homescreen:
1444 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1445 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1446 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
1448 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1452 mainWebView.reload();
1456 // Don't consume the event.
1457 return super.onOptionsItemSelected(menuItem);
1461 // removeAllCookies is deprecated, but it is required for API < 21.
1462 @SuppressWarnings("deprecation")
1464 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1465 int menuItemId = menuItem.getItemId();
1467 switch (menuItemId) {
1473 if (mainWebView.canGoBack()) {
1474 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1475 navigatingHistory = true;
1477 // Load the previous website in the history.
1478 mainWebView.goBack();
1483 if (mainWebView.canGoForward()) {
1484 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1485 navigatingHistory = true;
1487 // Load the next website in the history.
1488 mainWebView.goForward();
1493 // Get the `WebBackForwardList`.
1494 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1496 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1497 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
1498 urlHistoryDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.history));
1501 case R.id.bookmarks:
1502 // Launch BookmarksActivity.
1503 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
1504 startActivity(bookmarksIntent);
1507 case R.id.downloads:
1508 // Launch the system Download Manager.
1509 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1511 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1512 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1514 startActivity(downloadManagerIntent);
1518 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1519 currentDomainName = "";
1521 // Launch `SettingsActivity`.
1522 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1523 startActivity(settingsIntent);
1527 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1528 currentDomainName = "";
1530 // Launch `DomainsActivity`.
1531 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1532 startActivity(domainsIntent);
1536 // Launch `GuideActivity`.
1537 Intent guideIntent = new Intent(this, GuideActivity.class);
1538 startActivity(guideIntent);
1542 // Launch `AboutActivity`.
1543 Intent aboutIntent = new Intent(this, AboutActivity.class);
1544 startActivity(aboutIntent);
1547 case R.id.clearAndExit:
1548 // Get a handle for `sharedPreferences`. `this` references the current context.
1549 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1551 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
1554 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
1555 // The command to remove cookies changed slightly in API 21.
1556 if (Build.VERSION.SDK_INT >= 21) {
1557 cookieManager.removeAllCookies(null);
1559 cookieManager.removeAllCookie();
1562 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1564 // We have to use two commands because `Runtime.exec()` does not like `*`.
1565 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
1566 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
1567 } catch (IOException e) {
1568 // Do nothing if an error is thrown.
1572 // Clear DOM storage.
1573 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
1574 // Ask `WebStorage` to clear the DOM storage.
1575 WebStorage webStorage = WebStorage.getInstance();
1576 webStorage.deleteAllData();
1578 // Manually delete the DOM storage directory, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1580 // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1581 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1582 } catch (IOException e) {
1583 // Do nothing if an error is thrown.
1588 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
1589 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1590 webViewDatabase.clearFormData();
1592 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1594 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1595 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
1596 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
1597 } catch (IOException e) {
1598 // Do nothing if an error is thrown.
1603 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
1604 // `true` includes disk files.
1605 mainWebView.clearCache(true);
1607 // Manually delete the cache directories.
1609 // Delete the main cache directory.
1610 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1612 // Delete the secondary `Service Worker` cache directory. We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1613 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1614 } catch (IOException e) {
1615 // Do nothing if an error is thrown.
1619 // Clear SSL certificate preferences.
1620 mainWebView.clearSslPreferences();
1622 // Clear the back/forward history.
1623 mainWebView.clearHistory();
1625 // Clear `formattedUrlString`.
1626 formattedUrlString = null;
1628 // Clear `customHeaders`.
1629 customHeaders.clear();
1631 // Detach all views from `mainWebViewRelativeLayout`.
1632 mainWebViewRelativeLayout.removeAllViews();
1634 // Destroy the internal state of `mainWebView`.
1635 mainWebView.destroy();
1637 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
1638 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
1639 if (clearEverything) {
1641 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
1642 } catch (IOException e) {
1643 // Do nothing if an error is thrown.
1647 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1648 if (Build.VERSION.SDK_INT >= 21) {
1649 finishAndRemoveTask();
1654 // Remove the terminated program from RAM. The status code is `0`.
1659 // Close the navigation drawer.
1660 drawerLayout.closeDrawer(GravityCompat.START);
1665 public void onPostCreate(Bundle savedInstanceState) {
1666 super.onPostCreate(savedInstanceState);
1668 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1669 drawerToggle.syncState();
1673 public void onConfigurationChanged(Configuration newConfig) {
1674 super.onConfigurationChanged(newConfig);
1676 // Reload the ad for the free flavor if we are not in full screen mode.
1677 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
1679 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1681 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1682 adView = findViewById(R.id.adview);
1685 // `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
1686 // ActivityCompat.invalidateOptionsMenu(this);
1690 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1691 // Store the `HitTestResult`.
1692 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1695 final String imageUrl;
1696 final String linkUrl;
1698 // Get a handle for the `ClipboardManager`.
1699 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1701 switch (hitTestResult.getType()) {
1702 // `SRC_ANCHOR_TYPE` is a link.
1703 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1704 // Get the target URL.
1705 linkUrl = hitTestResult.getExtra();
1707 // Set the target URL as the title of the `ContextMenu`.
1708 menu.setHeaderTitle(linkUrl);
1710 // Add a `Load URL` entry.
1711 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1713 public boolean onMenuItemClick(MenuItem item) {
1719 // Add a `Copy URL` entry.
1720 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1722 public boolean onMenuItemClick(MenuItem item) {
1723 // Save the link URL in a `ClipData`.
1724 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), linkUrl);
1726 // Set the `ClipData` as the clipboard's primary clip.
1727 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
1732 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1733 menu.add(R.string.cancel);
1736 case WebView.HitTestResult.EMAIL_TYPE:
1737 // Get the target URL.
1738 linkUrl = hitTestResult.getExtra();
1740 // Set the target URL as the title of the `ContextMenu`.
1741 menu.setHeaderTitle(linkUrl);
1743 // Add a `Write Email` entry.
1744 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1746 public boolean onMenuItemClick(MenuItem item) {
1747 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1748 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1750 // Parse the url and set it as the data for the `Intent`.
1751 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1753 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1754 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1757 startActivity(emailIntent);
1762 // Add a `Copy Email Address` entry.
1763 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1765 public boolean onMenuItemClick(MenuItem item) {
1766 // Save the email address in a `ClipData`.
1767 ClipData srcEmailTypeClipData = ClipData.newPlainText(getResources().getString(R.string.email_address), linkUrl);
1769 // Set the `ClipData` as the clipboard's primary clip.
1770 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
1775 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1776 menu.add(R.string.cancel);
1779 // `IMAGE_TYPE` is an image.
1780 case WebView.HitTestResult.IMAGE_TYPE:
1781 // Get the image URL.
1782 imageUrl = hitTestResult.getExtra();
1784 // Set the image URL as the title of the `ContextMenu`.
1785 menu.setHeaderTitle(imageUrl);
1787 // Add a `View Image` entry.
1788 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1790 public boolean onMenuItemClick(MenuItem item) {
1796 // Add a `Download Image` entry.
1797 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1799 public boolean onMenuItemClick(MenuItem item) {
1800 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1801 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1802 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1807 // Add a `Copy URL` entry.
1808 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1810 public boolean onMenuItemClick(MenuItem item) {
1811 // Save the image URL in a `ClipData`.
1812 ClipData srcImageTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1814 // Set the `ClipData` as the clipboard's primary clip.
1815 clipboardManager.setPrimaryClip(srcImageTypeClipData);
1820 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1821 menu.add(R.string.cancel);
1825 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
1826 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1827 // Get the image URL.
1828 imageUrl = hitTestResult.getExtra();
1830 // Set the image URL as the title of the `ContextMenu`.
1831 menu.setHeaderTitle(imageUrl);
1833 // Add a `View Image` entry.
1834 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1836 public boolean onMenuItemClick(MenuItem item) {
1842 // Add a `Download Image` entry.
1843 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1845 public boolean onMenuItemClick(MenuItem item) {
1846 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1847 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1848 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1853 // Add a `Copy URL` entry.
1854 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1856 public boolean onMenuItemClick(MenuItem item) {
1857 // Save the image URL in a `ClipData`.
1858 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1860 // Set the `ClipData` as the clipboard's primary clip.
1861 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
1866 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1867 menu.add(R.string.cancel);
1873 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
1874 // Get shortcutNameEditText from the alert dialog.
1875 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
1877 // Create the bookmark shortcut based on formattedUrlString.
1878 Intent bookmarkShortcut = new Intent();
1879 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
1880 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
1882 // Place the bookmark shortcut on the home screen.
1883 Intent placeBookmarkShortcut = new Intent();
1884 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
1885 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
1886 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIconBitmap);
1887 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
1888 sendBroadcast(placeBookmarkShortcut);
1892 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
1893 // Download the image if it has an HTTP or HTTPS URI.
1894 if (imageUrl.startsWith("http")) {
1895 // Get a handle for the system `DOWNLOAD_SERVICE`.
1896 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1898 // Parse `imageUrl`.
1899 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
1901 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
1902 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
1903 if (firstPartyCookiesEnabled) {
1904 // Get the cookies for `imageUrl`.
1905 String cookies = cookieManager.getCookie(imageUrl);
1907 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
1908 downloadRequest.addRequestHeader("Cookie", cookies);
1911 // Get the file name from `dialogFragment`.
1912 EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
1913 String imageName = downloadImageNameEditText.getText().toString();
1915 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1916 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
1917 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
1918 } else { // Only set the title using `imageName`.
1919 downloadRequest.setTitle(imageName);
1922 // Allow `MediaScanner` to index the download if it is a media file.
1923 downloadRequest.allowScanningByMediaScanner();
1925 // Add the URL as the description for the download.
1926 downloadRequest.setDescription(imageUrl);
1928 // Show the download notification after the download is completed.
1929 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1931 // Initiate the download.
1932 downloadManager.enqueue(downloadRequest);
1933 } else { // The image is not an HTTP or HTTPS URI.
1934 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
1939 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
1940 // Download the file if it has an HTTP or HTTPS URI.
1941 if (downloadUrl.startsWith("http")) {
1943 // Get a handle for the system `DOWNLOAD_SERVICE`.
1944 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1946 // Parse `downloadUrl`.
1947 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
1949 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
1950 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
1951 if (firstPartyCookiesEnabled) {
1952 // Get the cookies for `downloadUrl`.
1953 String cookies = cookieManager.getCookie(downloadUrl);
1955 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
1956 downloadRequest.addRequestHeader("Cookie", cookies);
1959 // Get the file name from `dialogFragment`.
1960 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
1961 String fileName = downloadFileNameEditText.getText().toString();
1963 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1964 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
1965 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
1966 } else { // Only set the title using `fileName`.
1967 downloadRequest.setTitle(fileName);
1970 // Allow `MediaScanner` to index the download if it is a media file.
1971 downloadRequest.allowScanningByMediaScanner();
1973 // Add the URL as the description for the download.
1974 downloadRequest.setDescription(downloadUrl);
1976 // Show the download notification after the download is completed.
1977 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1979 // Initiate the download.
1980 downloadManager.enqueue(downloadRequest);
1981 } else { // The download is not an HTTP or HTTPS URI.
1982 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
1986 public void viewSslCertificate(View view) {
1987 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
1988 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
1989 viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
1993 public void onSslErrorCancel() {
1994 sslErrorHandler.cancel();
1998 public void onSslErrorProceed() {
1999 sslErrorHandler.proceed();
2003 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2004 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2005 navigatingHistory = true;
2007 // Load the history entry.
2008 mainWebView.goBackOrForward(moveBackOrForwardSteps);
2012 public void onClearHistory() {
2013 // Clear the history.
2014 mainWebView.clearHistory();
2017 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2019 public void onBackPressed() {
2020 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
2021 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
2022 drawerLayout.closeDrawer(GravityCompat.START);
2024 // Load the previous URL if available.
2025 if (mainWebView.canGoBack()) {
2026 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2027 navigatingHistory = true;
2030 mainWebView.goBack();
2032 // Pass `onBackPressed()` to the system.
2033 super.onBackPressed();
2038 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2039 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2040 String unformattedUrlString = urlTextBox.getText().toString().trim();
2042 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2043 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2044 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
2045 if (!unformattedUrlString.startsWith("http")) {
2046 unformattedUrlString = "http://" + unformattedUrlString;
2049 // Initialize `unformattedUrl`.
2050 URL unformattedUrl = null;
2052 // 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.
2054 unformattedUrl = new URL(unformattedUrlString);
2055 } catch (MalformedURLException e) {
2056 e.printStackTrace();
2059 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2060 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2061 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2062 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2063 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2064 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2067 Uri.Builder formattedUri = new Uri.Builder();
2068 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2070 // Decode `formattedUri` as a `String` in `UTF-8`.
2071 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
2073 // Sanitize the search input and convert it to a search.
2074 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2076 // Add the base search URL.
2077 formattedUrlString = searchURL + encodedUrlString;
2080 loadUrl(formattedUrlString);
2082 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2083 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2087 private void loadUrl(String url) {
2088 // Apply any custom domain settings.
2089 applyDomainSettings(url);
2092 mainWebView.loadUrl(url, customHeaders);
2095 public void findPreviousOnPage(View view) {
2096 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2097 mainWebView.findNext(false);
2100 public void findNextOnPage(View view) {
2101 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2102 mainWebView.findNext(true);
2105 public void closeFindOnPage(View view) {
2106 // Delete the contents of `find_on_page_edittext`.
2107 findOnPageEditText.setText(null);
2109 // Clear the highlighted phrases.
2110 mainWebView.clearMatches();
2112 // Hide the Find on Page `RelativeLayout`.
2113 findOnPageLinearLayout.setVisibility(View.GONE);
2115 // Show the URL app bar.
2116 supportAppBar.setVisibility(View.VISIBLE);
2118 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2119 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2122 private void applyAppSettings() {
2123 // Get a handle for `sharedPreferences`. `this` references the current context.
2124 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2126 // Store the values from `sharedPreferences` in variables.
2127 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
2128 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2129 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2130 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
2131 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
2132 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
2133 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
2134 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2135 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2136 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2137 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
2138 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2139 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2140 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
2141 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
2143 // Set the homepage, search, and proxy options.
2144 if (proxyThroughOrbot) { // Set the Tor options.
2145 // Set `torHomepageString` as `homepage`.
2146 homepage = torHomepageString;
2148 // If formattedUrlString is null assign the homepage to it.
2149 if (formattedUrlString == null) {
2150 formattedUrlString = homepage;
2153 // Set the search URL.
2154 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
2155 searchURL = torSearchCustomURLString;
2156 } else { // Use the string from the pre-built list.
2157 searchURL = torSearchString;
2160 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
2161 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2163 // Display a message to the user if we are waiting on Orbot.
2164 if (!orbotStatus.equals("ON")) {
2165 // Set `waitingForOrbot`.
2166 waitingForOrbot = true;
2168 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
2169 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2171 } else { // Set the non-Tor options.
2172 // Set `homepageString` as `homepage`.
2173 homepage = homepageString;
2175 // If formattedUrlString is null assign the homepage to it.
2176 if (formattedUrlString == null) {
2177 formattedUrlString = homepage;
2180 // Set the search URL.
2181 if (searchString.equals("Custom URL")) { // Get the custom URL string.
2182 searchURL = searchCustomURLString;
2183 } else { // Use the string from the pre-built list.
2184 searchURL = searchString;
2187 // Reset the proxy to default. The host is `""` and the port is `"0"`.
2188 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2190 // Reset `waitingForOrbot.
2191 waitingForOrbot = false;
2194 // Set swipe to refresh.
2195 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2197 // Set Do Not Track status.
2198 if (doNotTrackEnabled) {
2199 customHeaders.put("DNT", "1");
2201 customHeaders.remove("DNT");
2204 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2205 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2206 if (hideSystemBarsOnFullscreen) { // Hide everything.
2207 // Remove the translucent navigation setting if it is currently flagged.
2208 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2210 // Remove the translucent status bar overlay.
2211 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2213 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2214 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2216 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2217 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2218 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2220 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2221 } else { // Hide everything except the status and navigation bars.
2222 // Add the translucent status flag if it is unset.
2223 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2225 if (translucentNavigationBarOnFullscreen) {
2226 // Set the navigation bar to be translucent.
2227 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2229 // Set the navigation bar to be black.
2230 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2233 } else { // Switch to normal viewing mode.
2234 // Reset `inFullScreenBrowsingMode` to `false`.
2235 inFullScreenBrowsingMode = false;
2237 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
2238 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
2242 // Show the `BannerAd` in the free flavor.
2243 if (BuildConfig.FLAVOR.contentEquals("free")) {
2244 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
2245 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2247 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2248 adView = findViewById(R.id.adview);
2251 // Remove the translucent navigation bar flag if it is set.
2252 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2254 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2255 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2257 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
2258 rootCoordinatorLayout.setSystemUiVisibility(0);
2260 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
2261 rootCoordinatorLayout.setFitsSystemWindows(true);
2265 // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2266 @SuppressWarnings("deprecation")
2267 private void applyDomainSettings(String url) {
2268 // Reset `navigatingHistory`.
2269 navigatingHistory = false;
2271 // Parse the URL into a URI.
2272 Uri uri = Uri.parse(url);
2274 // Extract the domain from `uri`.
2275 String hostName = uri.getHost();
2277 // Initialize `loadingNewDomainName`.
2278 boolean loadingNewDomainName;
2280 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
2281 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
2282 //noinspection SimplifiableIfStatement
2283 if ((hostName == null) || (currentDomainName == null)) {
2284 loadingNewDomainName = true;
2285 } else { // Determine if `hostName` equals `currentDomainName`.
2286 loadingNewDomainName = !hostName.equals(currentDomainName);
2289 // Only apply the domain settings if we are loading a new domain. This allows the user to set temporary settings for JavaScript, cookies, DOM storage, etc.
2290 if (loadingNewDomainName) {
2291 // Set the new `hostname` as the `currentDomainName`.
2292 currentDomainName = hostName;
2294 // Reset `favoriteIconBitmap` and display it in the `appbar`.
2295 favoriteIconBitmap = favoriteIconDefaultBitmap;
2296 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
2298 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
2299 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2300 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2302 // Get a full cursor from `domainsDatabaseHelper`.
2303 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
2305 // Initialize `domainSettingsSet`.
2306 Set<String> domainSettingsSet = new HashSet<>();
2308 // Get the domain name column index.
2309 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
2311 // Populate `domainSettingsSet`.
2312 for (int i = 0; i < domainNameCursor.getCount(); i++) {
2313 // Move `domainsCursor` to the current row.
2314 domainNameCursor.moveToPosition(i);
2316 // Store the domain name in `domainSettingsSet`.
2317 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
2320 // Close `domainNameCursor.
2321 domainNameCursor.close();
2323 // Initialize variables to track if domain settings will be applied and, if so, under which name.
2324 domainSettingsApplied = false;
2325 String domainNameInDatabase = null;
2327 // Check the hostname.
2328 if (domainSettingsSet.contains(hostName)) {
2329 domainSettingsApplied = true;
2330 domainNameInDatabase = hostName;
2333 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
2334 if (hostName != null) {
2335 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
2336 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
2337 domainSettingsApplied = true;
2338 domainNameInDatabase = "*." + hostName;
2341 // Strip out the lowest subdomain of `host`.
2342 hostName = hostName.substring(hostName.indexOf(".") + 1);
2346 // Get a handle for the shared preference. `this` references the current context.
2347 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2349 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
2350 // Get a cursor for the current host and move it to the first position.
2351 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
2352 currentHostDomainSettingsCursor.moveToFirst();
2354 // Get the settings from the cursor.
2355 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
2356 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
2357 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
2358 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
2359 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
2360 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
2361 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
2362 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
2364 // Close `currentHostDomainSettingsCursor`.
2365 currentHostDomainSettingsCursor.close();
2367 // Apply the domain settings.
2368 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2369 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2370 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2371 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2372 mainWebView.getSettings().setTextZoom(fontSize);
2374 // Set third-party cookies status if API >= 21.
2375 if (Build.VERSION.SDK_INT >= 21) {
2376 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2379 // Set the user agent.
2380 if (userAgentString.equals("WebView default user agent")) {
2381 // Set the user agent to `""`, which uses the default value.
2382 mainWebView.getSettings().setUserAgentString("");
2384 // Use the selected user agent.
2385 mainWebView.getSettings().setUserAgentString(userAgentString);
2388 // Set a green background on `urlTextBox` to indicate that custom domain settings are being used. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2389 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_green));
2390 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
2391 // Store the values from `sharedPreferences` in variables.
2392 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
2393 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
2394 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
2395 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
2396 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
2397 String userAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
2398 String customUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
2399 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
2401 // Apply the default settings.
2402 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2403 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2404 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2405 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2406 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2408 // Set third-party cookies status if API >= 21.
2409 if (Build.VERSION.SDK_INT >= 21) {
2410 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2413 // Set the default user agent.
2414 switch (userAgentString) {
2415 case "WebView default user agent":
2416 // Set the user agent to `""`, which uses the default value.
2417 mainWebView.getSettings().setUserAgentString("");
2420 case "Custom user agent":
2421 // Set the custom user agent.
2422 mainWebView.getSettings().setUserAgentString(customUserAgentString);
2426 // Use the selected user agent.
2427 mainWebView.getSettings().setUserAgentString(userAgentString);
2431 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2432 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.url_bar_background_transparent));
2435 // Close `domainsDatabaseHelper`.
2436 domainsDatabaseHelper.close();
2438 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
2439 onTheFlyDisplayImagesSet = false;
2440 setDisplayWebpageImages();
2442 // Update the privacy icons, but only if `mainMenu` has already been populated.
2443 if (mainMenu != null) {
2444 updatePrivacyIcons(true);
2449 private void setDisplayWebpageImages() {
2450 if (!onTheFlyDisplayImagesSet) {
2451 if (domainSettingsApplied) { // Custom domain settings are applied.
2452 switch (displayWebpageImagesInt) {
2453 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
2454 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2457 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
2458 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2461 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
2462 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2465 } else { // Default settings are applied.
2466 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2471 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
2472 // Get handles for the icons.
2473 MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
2474 MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
2475 MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
2476 MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
2478 // Update `privacyIcon`.
2479 if (javaScriptEnabled) { // JavaScript is enabled.
2480 privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
2481 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
2482 privacyIconMenuItem.setIcon(R.drawable.warning);
2483 } else { // All the dangerous features are disabled.
2484 privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
2487 // Update `firstPartyCookiesIcon`.
2488 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2489 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
2490 } else { // First-party cookies are disabled.
2491 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled);
2494 // Update `domStorageIcon`.
2495 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
2496 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
2497 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
2498 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled);
2499 } else { // JavaScript is disabled, so DOM storage is ghosted.
2500 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted);
2503 // Update `formDataIcon`.
2504 if (saveFormDataEnabled) { // Form data is enabled.
2505 formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
2506 } else { // Form data is disabled.
2507 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled);
2510 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
2511 if (runInvalidateOptionsMenu) {
2512 ActivityCompat.invalidateOptionsMenu(this);