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;
142 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, and `applyDomainSettings()`.
143 private boolean navigatingHistory;
145 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
146 private Bitmap favoriteIconDefaultBitmap;
148 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
149 private DrawerLayout drawerLayout;
151 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
152 private CoordinatorLayout rootCoordinatorLayout;
154 // 'mainWebView' is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, and `loadUrlFromTextBox()`.
155 private WebView mainWebView;
157 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
158 private FrameLayout fullScreenVideoFrameLayout;
160 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
161 private SwipeRefreshLayout swipeRefreshLayout;
163 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
164 private RelativeLayout urlAppBarRelativeLayout;
166 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
167 private ImageView favoriteIconImageView;
169 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
170 private CookieManager cookieManager;
172 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
173 private final Map<String, String> customHeaders = new HashMap<>();
175 // `javaScriptEnabled` is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `applyAppSettings()`.
176 // It is `Boolean` instead of `boolean` because `applyAppSettings()` needs to know if it is `null`.
177 private Boolean javaScriptEnabled;
179 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyAppSettings()`.
180 private boolean firstPartyCookiesEnabled;
182 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
183 private boolean thirdPartyCookiesEnabled;
185 // `domStorageEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
186 private boolean domStorageEnabled;
188 // `saveFormDataEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
189 private boolean saveFormDataEnabled;
191 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applyAppSettings()`.
192 private boolean swipeToRefreshEnabled;
194 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
195 private String homepage;
197 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
198 private String searchURL;
200 // `adBlockerEnabled` is used in `onCreate()` and `applyAppSettings()`.
201 private boolean adBlockerEnabled;
203 // `privacyBrowserRuntime` is used in `onCreate()` and `applyAppSettings()`.
204 Runtime privacyBrowserRuntime;
206 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
207 private boolean incognitoModeEnabled;
209 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
210 private boolean fullScreenBrowsingModeEnabled;
212 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
213 private boolean inFullScreenBrowsingMode;
215 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
216 private boolean hideSystemBarsOnFullscreen;
218 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
219 private boolean translucentNavigationBarOnFullscreen;
221 // `currentDomainName` is used in `onCreate(), `onNavigationItemSelected()`, and `applyDomainSettings()`.
222 private String currentDomainName;
224 // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
225 private boolean waitingForOrbot;
227 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
228 private String waitingForOrbotHTMLString;
230 // `privateDataDirectoryString` is used in `onCreate()` and `onNavigationItemSelected()`.
231 private String privateDataDirectoryString;
233 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
234 private LinearLayout findOnPageLinearLayout;
236 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
237 private EditText findOnPageEditText;
239 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
240 private Menu mainMenu;
242 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
243 private ActionBarDrawerToggle drawerToggle;
245 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
246 private Toolbar supportAppBar;
248 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `loadUrl()`.
249 private EditText urlTextBox;
251 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
254 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
255 private SslErrorHandler sslErrorHandler;
257 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
258 private InputMethodManager inputMethodManager;
260 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
261 private RelativeLayout mainWebViewRelativeLayout;
264 // 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.
265 @SuppressLint("SetJavaScriptEnabled")
266 protected void onCreate(Bundle savedInstanceState) {
267 super.onCreate(savedInstanceState);
268 setContentView(R.layout.main_drawerlayout);
270 // Get a handle for `inputMethodManager`.
271 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
273 // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
274 supportAppBar = (Toolbar) findViewById(R.id.app_bar);
275 setSupportActionBar(supportAppBar);
276 appBar = getSupportActionBar();
278 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
279 assert appBar != null;
281 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
282 appBar.setCustomView(R.layout.url_app_bar);
283 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
285 // Set the "go" button on the keyboard to load the URL in urlTextBox.
286 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.url_edittext);
287 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
289 public boolean onKey(View v, int keyCode, KeyEvent event) {
290 // If the event is a key-down event on the `enter` button, load the URL.
291 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
292 // Load the URL into the mainWebView and consume the event.
294 loadUrlFromTextBox();
295 } catch (UnsupportedEncodingException e) {
298 // If the enter key was pressed, consume the event.
301 // If any other key was pressed, do not consume the event.
307 // Set `waitingForOrbotHTMLString`.
308 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
310 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
311 currentDomainName = "";
312 orbotStatus = "unknown";
313 waitingForOrbot = false;
315 // Create an Orbot status `BroadcastReceiver`.
316 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
318 public void onReceive(Context context, Intent intent) {
319 // Store the content of the status message in `orbotStatus`.
320 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
322 // If we are waiting on Orbot, load the website now that Orbot is connected.
323 if (orbotStatus.equals("ON") && waitingForOrbot) {
324 // Reset `waitingForOrbot`.
325 waitingForOrbot = false;
327 // Load `formattedUrlString
328 loadUrl(formattedUrlString);
333 // Register `orbotStatusBroadcastReceiver` on `this` context.
334 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
336 // Get handles for views that need to be accessed.
337 drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
338 rootCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.root_coordinatorlayout);
339 mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.main_webview_relativelayout);
340 mainWebView = (WebView) findViewById(R.id.main_webview);
341 findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
342 findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
343 fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.full_screen_video_framelayout);
344 urlAppBarRelativeLayout = (RelativeLayout) findViewById(R.id.url_app_bar_relativelayout);
345 favoriteIconImageView = (ImageView) findViewById(R.id.favorite_icon);
347 // Create a double-tap listener to toggle full-screen mode.
348 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
349 // Override `onDoubleTap()`. All other events are handled using the default settings.
351 public boolean onDoubleTap(MotionEvent event) {
352 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
353 // Toggle `inFullScreenBrowsingMode`.
354 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
356 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
357 // Hide the `appBar`.
360 // Hide the `BannerAd` in the free flavor.
361 if (BuildConfig.FLAVOR.contentEquals("free")) {
362 BannerAd.hideAd(adView);
365 // Modify the system bars.
366 if (hideSystemBarsOnFullscreen) { // Hide everything.
367 // Remove the translucent overlays.
368 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
370 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
371 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
373 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
374 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
375 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
377 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
379 // Set `rootCoordinatorLayout` to fill the whole screen.
380 rootCoordinatorLayout.setFitsSystemWindows(false);
381 } else { // Hide everything except the status and navigation bars.
382 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
383 rootCoordinatorLayout.setFitsSystemWindows(false);
385 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.
386 // Set the navigation bar to be translucent.
387 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
390 } else { // Switch to normal viewing mode.
391 // Show the `appBar`.
394 // Show the `BannerAd` in the free flavor.
395 if (BuildConfig.FLAVOR.contentEquals("free")) {
396 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
397 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
399 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
400 adView = findViewById(R.id.adview);
403 // Remove the translucent navigation bar flag if it is set.
404 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
406 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
407 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
409 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
410 rootCoordinatorLayout.setSystemUiVisibility(0);
412 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
413 rootCoordinatorLayout.setFitsSystemWindows(true);
416 // Consume the double-tap.
418 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
424 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
425 mainWebView.setOnTouchListener(new View.OnTouchListener() {
427 public boolean onTouch(View v, MotionEvent event) {
428 // Send the `event` to `gestureDetector`.
429 return gestureDetector.onTouchEvent(event);
433 // Update `findOnPageCountTextView`.
434 mainWebView.setFindListener(new WebView.FindListener() {
435 // Get a handle for `findOnPageCountTextView`.
436 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
439 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
440 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
441 // Set `findOnPageCountTextView` to `0/0`.
442 findOnPageCountTextView.setText(R.string.zero_of_zero);
443 } else if (isDoneCounting) { // There are matches.
444 // `activeMatchOrdinal` is zero-based.
445 int activeMatch = activeMatchOrdinal + 1;
447 // Set `findOnPageCountTextView`.
448 findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
453 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
454 findOnPageEditText.addTextChangedListener(new TextWatcher() {
456 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
461 public void onTextChanged(CharSequence s, int start, int before, int count) {
466 public void afterTextChanged(Editable s) {
467 // Search for the text in `mainWebView`.
468 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
472 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
473 findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
475 public boolean onKey(View v, int keyCode, KeyEvent event) {
476 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
477 // Hide the soft keyboard. `0` indicates no additional flags.
478 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
480 // Consume the event.
482 } else { // A different key was pressed.
483 // Do not consume the event.
489 // Implement swipe to refresh
490 swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refreshlayout);
491 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
492 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
494 public void onRefresh() {
495 mainWebView.reload();
499 // `DrawerTitle` identifies the `DrawerLayout` in accessibility mode.
500 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
502 // Listen for touches on the navigation menu.
503 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationview);
504 navigationView.setNavigationItemSelectedListener(this);
506 // 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.
507 final Menu navigationMenu = navigationView.getMenu();
508 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
509 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
510 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
512 // The `DrawerListener` allows us to update the Navigation Menu.
513 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
515 public void onDrawerSlide(View drawerView, float slideOffset) {
519 public void onDrawerOpened(View drawerView) {
523 public void onDrawerClosed(View drawerView) {
527 public void onDrawerStateChanged(int newState) {
528 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
529 // Update the `Back`, `Forward`, and `History` menu items.
530 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
531 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
532 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
534 // Hide the keyboard so we can see the navigation menu. `0` indicates no additional flags.
535 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
540 // drawerToggle creates the hamburger icon at the start of the AppBar.
541 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
543 // Initialize `adServerSet`.
544 final Set<String> adServersSet = new HashSet<>();
546 // Load the list of ad servers into memory.
548 // Load `pgl.yoyo.org_adservers.txt` into a `BufferedReader`.
549 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("pgl.yoyo.org_adservers.txt")));
551 // Create a string for storing each ad server.
554 // Populate `adServersSet`.
555 while ((adServer = bufferedReader.readLine()) != null) {
556 adServersSet.add(adServer);
559 // Close `bufferedReader`.
560 bufferedReader.close();
561 } catch (IOException ioException) {
562 // We're pretty sure the asset exists, so we don't need to worry about the `IOException` ever being thrown.
565 mainWebView.setWebViewClient(new WebViewClient() {
566 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
567 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
568 @SuppressWarnings("deprecation")
570 public boolean shouldOverrideUrlLoading(WebView view, String url) {
571 // Use an external email program if the link begins with `mailto:`.
572 if (url.startsWith("mailto:")) {
573 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
574 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
576 // Parse the url and set it as the data for the `Intent`.
577 emailIntent.setData(Uri.parse(url));
579 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
580 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
583 startActivity(emailIntent);
585 } else { // Load the URL in Privacy Browser.
591 // Block ads. We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
592 @SuppressWarnings("deprecation")
594 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
595 if (adBlockerEnabled) { // Block ads.
596 // Extract the host from `url`.
597 Uri requestUri = Uri.parse(url);
598 String requestHost = requestUri.getHost();
600 // Initialize a variable to track if this is an ad server.
601 boolean requestHostIsAdServer = false;
603 // Check all the subdomains of `requestHost` if it is not `null` against the ad server database.
604 if (requestHost != null) {
605 while (requestHost.contains(".") && !requestHostIsAdServer) { // Stop checking if we run out of `.` or if we already know that `requestHostIsAdServer` is `true`.
606 if (adServersSet.contains(requestHost)) {
607 requestHostIsAdServer = true;
610 // Strip out the lowest subdomain of `requestHost`.
611 requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
615 if (requestHostIsAdServer) { // It is an ad server.
616 // Return an empty `WebResourceResponse`.
617 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
618 } else { // It is not an ad server.
619 // `return null` loads the requested resource.
622 } else { // Ad blocking is disabled.
623 // `return null` loads the requested resource.
628 // Update the URL in urlTextBox when the page starts to load.
630 public void onPageStarted(WebView view, String url, Bitmap favicon) {
631 // Reset `webViewTitle`
632 webViewTitle = getString(R.string.no_title);
634 // Check to see if we are waiting on Orbot.
635 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
636 // 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.
637 formattedUrlString = url;
639 // Display the loading URL is the URL text box.
640 urlTextBox.setText(url);
642 // Apply any custom domain settings if the URL was loaded by navigating history.
643 if (navigatingHistory) {
644 applyDomainSettings(url);
649 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
651 public void onPageFinished(WebView view, String url) {
652 // Clear the cache and history if Incognito Mode is enabled.
653 if (incognitoModeEnabled) {
654 // Clear the cache. `true` includes disk files.
655 mainWebView.clearCache(true);
657 // Clear the back/forward history.
658 mainWebView.clearHistory();
660 // Manually delete cache folders.
662 // Delete the main `cache` folder.
663 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
665 // 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`.
666 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
667 } catch (IOException e) {
668 // Do nothing if an error is thrown.
672 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
673 if (!waitingForOrbot) {
674 // Check to see if `WebView` has set `url` to be `about:blank`.
675 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
676 // Set `formattedUrlString` to `""`.
677 formattedUrlString = "";
679 // Update `urlTextBox`.
680 urlTextBox.setText(formattedUrlString);
682 // Request focus for `urlTextBox`.
683 urlTextBox.requestFocus();
685 // Display the keyboard.
686 inputMethodManager.showSoftInput(urlTextBox, 0);
688 // Apply the domain settings.
689 applyDomainSettings(formattedUrlString);
690 } else { // `WebView` has loaded a webpage.
691 // Set `formattedUrlString`.
692 formattedUrlString = url;
694 // Only update `urlTextBox` if the user is not typing in it.
695 if (!urlTextBox.hasFocus()) {
696 urlTextBox.setText(formattedUrlString);
700 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog`.
701 sslCertificate = mainWebView.getCertificate();
705 // Handle SSL Certificate errors.
707 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
708 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
709 sslErrorHandler = handler;
711 // Display the SSL error `AlertDialog`.
712 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
713 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
717 // Get a handle for the progress bar.
718 final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
720 mainWebView.setWebChromeClient(new WebChromeClient() {
721 // Update the progress bar when a page is loading.
723 public void onProgressChanged(WebView view, int progress) {
724 progressBar.setProgress(progress);
725 if (progress < 100) {
726 progressBar.setVisibility(View.VISIBLE);
728 progressBar.setVisibility(View.GONE);
730 //Stop the `SwipeToRefresh` indicator if it is running
731 swipeRefreshLayout.setRefreshing(false);
735 // Set the favorite icon when it changes.
737 public void onReceivedIcon(WebView view, Bitmap icon) {
738 // Only update the favorite icon if the website has finished loading.
739 if (progressBar.getVisibility() == View.GONE) {
740 // Save a copy of the favorite icon.
741 favoriteIconBitmap = icon;
743 // Place the favorite icon in the appBar.
744 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
748 // Save a copy of the title when it changes.
750 public void onReceivedTitle(WebView view, String title) {
751 // Save a copy of the title.
752 webViewTitle = title;
755 // Enter full screen video
757 public void onShowCustomView(View view, CustomViewCallback callback) {
758 // Pause the ad if this is the free flavor.
759 if (BuildConfig.FLAVOR.contentEquals("free")) {
760 BannerAd.pauseAd(adView);
763 // Remove the translucent overlays.
764 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
766 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
767 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
769 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
770 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
771 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
773 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
775 // Set `rootCoordinatorLayout` to fill the entire screen.
776 rootCoordinatorLayout.setFitsSystemWindows(false);
778 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
779 fullScreenVideoFrameLayout.addView(view);
780 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
783 // Exit full screen video
784 public void onHideCustomView() {
785 // Hide `fullScreenVideoFrameLayout`.
786 fullScreenVideoFrameLayout.removeAllViews();
787 fullScreenVideoFrameLayout.setVisibility(View.GONE);
789 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
790 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
792 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
793 rootCoordinatorLayout.setFitsSystemWindows(true);
795 // Show the ad if this is the free flavor.
796 if (BuildConfig.FLAVOR.contentEquals("free")) {
797 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
798 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
800 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
801 adView = findViewById(R.id.adview);
806 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
807 registerForContextMenu(mainWebView);
809 // Allow the downloading of files.
810 mainWebView.setDownloadListener(new DownloadListener() {
812 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
813 // Show the `DownloadFileDialog` `AlertDialog` and name this instance `@string/download`.
814 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
815 downloadFileDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
819 // Allow pinch to zoom.
820 mainWebView.getSettings().setBuiltInZoomControls(true);
822 // Hide zoom controls.
823 mainWebView.getSettings().setDisplayZoomControls(false);
825 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
826 mainWebView.getSettings().setUseWideViewPort(true);
828 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
829 mainWebView.getSettings().setLoadWithOverviewMode(true);
831 // Initialize cookieManager.
832 cookieManager = CookieManager.getInstance();
834 // 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).
835 customHeaders.put("X-Requested-With", "");
837 // 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.
838 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
840 // Get the intent that started the app.
841 final Intent launchingIntent = getIntent();
843 // Extract the launching intent data as `launchingIntentUriData`.
844 final Uri launchingIntentUriData = launchingIntent.getData();
846 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
847 if (launchingIntentUriData != null) {
848 formattedUrlString = launchingIntentUriData.toString();
851 // Get a handle for the `Runtime`.
852 privacyBrowserRuntime = Runtime.getRuntime();
854 // Store the application's private data directory.
855 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`.
857 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
858 inFullScreenBrowsingMode = false;
860 // Initialize AdView for the free flavor.
861 adView = findViewById(R.id.adview);
863 // Initialize the privacy settings variables.
864 javaScriptEnabled = false;
865 firstPartyCookiesEnabled = false;
866 thirdPartyCookiesEnabled = false;
867 domStorageEnabled = false;
868 saveFormDataEnabled = false;
870 // Initialize `webViewTitle`.
871 webViewTitle = getString(R.string.no_title);
873 // Initialize `favoriteIconBitmap`. We have to use `ContextCompat` until API >= 21.
874 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
875 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
876 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
878 // If the favorite icon is null, load the default.
879 if (favoriteIconBitmap == null) {
880 favoriteIconBitmap = favoriteIconDefaultBitmap;
883 // Apply the app settings from the shared preferences.
886 // Load `formattedUrlString` if we are not waiting for Orbot to connect.
887 if (!waitingForOrbot) {
888 loadUrl(formattedUrlString);
894 protected void onNewIntent(Intent intent) {
895 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
898 if (intent.getData() != null) {
899 // Get the intent data and convert it to a string.
900 final Uri intentUriData = intent.getData();
901 formattedUrlString = intentUriData.toString();
904 // Close the navigation drawer if it is open.
905 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
906 drawerLayout.closeDrawer(GravityCompat.START);
910 loadUrl(formattedUrlString);
912 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
913 mainWebView.requestFocus();
917 public boolean onCreateOptionsMenu(Menu menu) {
918 // Inflate the menu; this adds items to the action bar if it is present.
919 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
921 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
924 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
925 updatePrivacyIcons(false);
927 // Get handles for the menu items.
928 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
929 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
930 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
931 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
933 // Only display third-party cookies if SDK >= 21
934 toggleThirdPartyCookies.setVisible(Build.VERSION.SDK_INT >= 21);
936 // Get the shared preference values. `this` references the current context.
937 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
939 // Set the status of the additional app bar icons. The default is `false`.
940 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
941 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
942 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
943 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
944 } else { //Do not display the additional icons.
945 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
946 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
947 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
954 public boolean onPrepareOptionsMenu(Menu menu) {
955 // Get handles for the menu items.
956 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
957 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
958 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
959 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
960 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
961 MenuItem clearFormData = menu.findItem(R.id.clearFormData);
962 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
964 // Set the status of the menu item checkboxes.
965 toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
966 toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
967 toggleDomStorage.setChecked(domStorageEnabled);
968 toggleSaveFormData.setChecked(saveFormDataEnabled);
970 // Enable third-party cookies if first-party cookies are enabled.
971 toggleThirdPartyCookies.setEnabled(firstPartyCookiesEnabled);
973 // Enable DOM Storage if JavaScript is enabled.
974 toggleDomStorage.setEnabled(javaScriptEnabled);
976 // Enable Clear Cookies if there are any.
977 clearCookies.setEnabled(cookieManager.hasCookies());
979 // Enable Clear Form Data is there is any.
980 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
981 clearFormData.setEnabled(mainWebViewDatabase.hasFormData());
983 // Only show `Refresh` if `swipeToRefresh` is disabled.
984 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
986 // Initialize font size variables.
987 int fontSize = mainWebView.getSettings().getTextZoom();
988 String fontSizeTitle;
989 MenuItem selectedFontSizeMenuItem;
991 // Prepare the font size title and current size menu item.
994 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.twenty_five_percent);
995 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeTwentyFivePercent);
999 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
1000 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeFiftyPercent);
1004 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
1005 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeSeventyFivePercent);
1009 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1010 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
1014 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
1015 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredTwentyFivePercent);
1019 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
1020 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredFiftyPercent);
1024 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
1025 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredSeventyFivePercent);
1029 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
1030 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeTwoHundredPercent);
1034 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1035 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
1039 // Set the font size title and select the current size menu item.
1040 MenuItem fontSizeMenuItem = menu.findItem(R.id.fontSize);
1041 fontSizeMenuItem.setTitle(fontSizeTitle);
1042 selectedFontSizeMenuItem.setChecked(true);
1044 // Run all the other default commands.
1045 super.onPrepareOptionsMenu(menu);
1047 // `return true` displays the menu.
1052 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1053 @SuppressLint("SetJavaScriptEnabled")
1054 // removeAllCookies is deprecated, but it is required for API < 21.
1055 @SuppressWarnings("deprecation")
1056 public boolean onOptionsItemSelected(MenuItem menuItem) {
1057 int menuItemId = menuItem.getItemId();
1059 // Set the commands that relate to the menu entries.
1060 switch (menuItemId) {
1061 case R.id.toggleJavaScript:
1062 // Switch the status of javaScriptEnabled.
1063 javaScriptEnabled = !javaScriptEnabled;
1065 // Apply the new JavaScript status.
1066 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1068 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1069 updatePrivacyIcons(true);
1071 // Display a `Snackbar`.
1072 if (javaScriptEnabled) { // JavaScrip is enabled.
1073 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1074 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1075 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1076 } else { // Privacy mode.
1077 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1080 // Reload the WebView.
1081 mainWebView.reload();
1084 case R.id.toggleFirstPartyCookies:
1085 // Switch the status of firstPartyCookiesEnabled.
1086 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1088 // Update the menu checkbox.
1089 menuItem.setChecked(firstPartyCookiesEnabled);
1091 // Apply the new cookie status.
1092 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1094 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1095 updatePrivacyIcons(true);
1097 // Display a `Snackbar`.
1098 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1099 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1100 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1101 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1102 } else { // Privacy mode.
1103 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1106 // Reload the WebView.
1107 mainWebView.reload();
1110 case R.id.toggleThirdPartyCookies:
1111 if (Build.VERSION.SDK_INT >= 21) {
1112 // Switch the status of thirdPartyCookiesEnabled.
1113 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1115 // Update the menu checkbox.
1116 menuItem.setChecked(thirdPartyCookiesEnabled);
1118 // Apply the new cookie status.
1119 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1121 // Display a `Snackbar`.
1122 if (thirdPartyCookiesEnabled) {
1123 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1125 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1128 // Reload the WebView.
1129 mainWebView.reload();
1130 } // Else do nothing because SDK < 21.
1133 case R.id.toggleDomStorage:
1134 // Switch the status of domStorageEnabled.
1135 domStorageEnabled = !domStorageEnabled;
1137 // Update the menu checkbox.
1138 menuItem.setChecked(domStorageEnabled);
1140 // Apply the new DOM Storage status.
1141 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1143 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1144 updatePrivacyIcons(true);
1146 // Display a `Snackbar`.
1147 if (domStorageEnabled) {
1148 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1150 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1153 // Reload the WebView.
1154 mainWebView.reload();
1157 case R.id.toggleSaveFormData:
1158 // Switch the status of saveFormDataEnabled.
1159 saveFormDataEnabled = !saveFormDataEnabled;
1161 // Update the menu checkbox.
1162 menuItem.setChecked(saveFormDataEnabled);
1164 // Apply the new form data status.
1165 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1167 // Display a `Snackbar`.
1168 if (saveFormDataEnabled) {
1169 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1171 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1174 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1175 updatePrivacyIcons(true);
1177 // Reload the WebView.
1178 mainWebView.reload();
1181 case R.id.clearCookies:
1182 if (Build.VERSION.SDK_INT < 21) {
1183 cookieManager.removeAllCookie();
1185 cookieManager.removeAllCookies(null);
1187 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
1190 case R.id.clearDomStorage:
1191 WebStorage webStorage = WebStorage.getInstance();
1192 webStorage.deleteAllData();
1193 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
1196 case R.id.clearFormData:
1197 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1198 mainWebViewDatabase.clearFormData();
1199 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_SHORT).show();
1202 case R.id.fontSizeTwentyFivePercent:
1203 mainWebView.getSettings().setTextZoom(25);
1206 case R.id.fontSizeFiftyPercent:
1207 mainWebView.getSettings().setTextZoom(50);
1210 case R.id.fontSizeSeventyFivePercent:
1211 mainWebView.getSettings().setTextZoom(75);
1214 case R.id.fontSizeOneHundredPercent:
1215 mainWebView.getSettings().setTextZoom(100);
1218 case R.id.fontSizeOneHundredTwentyFivePercent:
1219 mainWebView.getSettings().setTextZoom(125);
1222 case R.id.fontSizeOneHundredFiftyPercent:
1223 mainWebView.getSettings().setTextZoom(150);
1226 case R.id.fontSizeOneHundredSeventyFivePercent:
1227 mainWebView.getSettings().setTextZoom(175);
1230 case R.id.fontSizeTwoHundredPercent:
1231 mainWebView.getSettings().setTextZoom(200);
1235 Intent shareIntent = new Intent();
1236 shareIntent.setAction(Intent.ACTION_SEND);
1237 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
1238 shareIntent.setType("text/plain");
1239 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1242 case R.id.find_on_page:
1243 // Hide the URL app bar.
1244 supportAppBar.setVisibility(View.GONE);
1246 // Show the Find on Page `RelativeLayout`.
1247 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1249 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
1250 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1251 findOnPageEditText.postDelayed(new Runnable()
1256 // Set the focus on `findOnPageEditText`.
1257 findOnPageEditText.requestFocus();
1259 // Display the keyboard.
1260 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1266 mainWebView.reload();
1270 // Get a `PrintManager` instance.
1271 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1273 // Convert `mainWebView` to `printDocumentAdapter`.
1274 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1276 // Print the document. The print attributes are `null`.
1277 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1280 case R.id.addToHomescreen:
1281 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1282 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1283 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
1285 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1289 // Don't consume the event.
1290 return super.onOptionsItemSelected(menuItem);
1294 // removeAllCookies is deprecated, but it is required for API < 21.
1295 @SuppressWarnings("deprecation")
1297 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1298 int menuItemId = menuItem.getItemId();
1300 switch (menuItemId) {
1306 if (mainWebView.canGoBack()) {
1307 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1308 navigatingHistory = true;
1310 // Load the previous website in the history.
1311 mainWebView.goBack();
1316 if (mainWebView.canGoForward()) {
1317 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1318 navigatingHistory = true;
1320 // Load the next website in the history.
1321 mainWebView.goForward();
1326 // Get the `WebBackForwardList`.
1327 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1329 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1330 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
1331 urlHistoryDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.history));
1334 case R.id.bookmarks:
1335 // Launch BookmarksActivity.
1336 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
1337 startActivity(bookmarksIntent);
1340 case R.id.downloads:
1341 // Launch the system Download Manager.
1342 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1344 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1345 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1347 startActivity(downloadManagerIntent);
1351 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1352 currentDomainName = "";
1354 // Launch `SettingsActivity`.
1355 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1356 startActivity(settingsIntent);
1360 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1361 currentDomainName = "";
1363 // Launch `DomainsActivity`.
1364 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1365 startActivity(domainsIntent);
1369 // Launch `GuideActivity`.
1370 Intent guideIntent = new Intent(this, GuideActivity.class);
1371 startActivity(guideIntent);
1375 // Launch `AboutActivity`.
1376 Intent aboutIntent = new Intent(this, AboutActivity.class);
1377 startActivity(aboutIntent);
1380 case R.id.clearAndExit:
1381 // Clear cookies. The commands changed slightly in API 21.
1382 if (Build.VERSION.SDK_INT >= 21) {
1383 cookieManager.removeAllCookies(null);
1385 cookieManager.removeAllCookie();
1388 // Clear DOM storage.
1389 WebStorage domStorage = WebStorage.getInstance();
1390 domStorage.deleteAllData();
1393 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1394 webViewDatabase.clearFormData();
1396 // Clear the cache. `true` includes disk files.
1397 mainWebView.clearCache(true);
1399 // Clear the back/forward history.
1400 mainWebView.clearHistory();
1402 // Clear any SSL certificate preferences.
1403 mainWebView.clearSslPreferences();
1405 // Clear `formattedUrlString`.
1406 formattedUrlString = null;
1408 // Clear `customHeaders`.
1409 customHeaders.clear();
1411 // Detach all views from `mainWebViewRelativeLayout`.
1412 mainWebViewRelativeLayout.removeAllViews();
1414 // Destroy the internal state of `mainWebView`.
1415 mainWebView.destroy();
1417 // Manually delete cache folders.
1419 // Delete the main `cache` folder.
1420 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1422 // 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`.
1423 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
1424 } catch (IOException e) {
1425 // Do nothing if an error is thrown.
1428 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1429 if (Build.VERSION.SDK_INT >= 21) {
1430 finishAndRemoveTask();
1435 // Remove the terminated program from RAM. The status code is `0`.
1443 // Close the navigation drawer.
1444 drawerLayout.closeDrawer(GravityCompat.START);
1449 public void onPostCreate(Bundle savedInstanceState) {
1450 super.onPostCreate(savedInstanceState);
1452 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1453 drawerToggle.syncState();
1457 public void onConfigurationChanged(Configuration newConfig) {
1458 super.onConfigurationChanged(newConfig);
1460 // Reload the ad for the free flavor if we are not in full screen mode.
1461 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
1463 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1465 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1466 adView = findViewById(R.id.adview);
1469 // `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
1470 // ActivityCompat.invalidateOptionsMenu(this);
1474 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1475 // Store the `HitTestResult`.
1476 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1479 final String imageUrl;
1480 final String linkUrl;
1482 // Get a handle for the `ClipboardManager`.
1483 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1485 switch (hitTestResult.getType()) {
1486 // `SRC_ANCHOR_TYPE` is a link.
1487 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1488 // Get the target URL.
1489 linkUrl = hitTestResult.getExtra();
1491 // Set the target URL as the title of the `ContextMenu`.
1492 menu.setHeaderTitle(linkUrl);
1494 // Add a `Load URL` entry.
1495 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1497 public boolean onMenuItemClick(MenuItem item) {
1503 // Add a `Copy URL` entry.
1504 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1506 public boolean onMenuItemClick(MenuItem item) {
1507 // Save the link URL in a `ClipData`.
1508 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), linkUrl);
1510 // Set the `ClipData` as the clipboard's primary clip.
1511 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
1516 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1517 menu.add(R.string.cancel);
1520 case WebView.HitTestResult.EMAIL_TYPE:
1521 // Get the target URL.
1522 linkUrl = hitTestResult.getExtra();
1524 // Set the target URL as the title of the `ContextMenu`.
1525 menu.setHeaderTitle(linkUrl);
1527 // Add a `Write Email` entry.
1528 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1530 public boolean onMenuItemClick(MenuItem item) {
1531 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1532 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1534 // Parse the url and set it as the data for the `Intent`.
1535 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1537 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1538 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1541 startActivity(emailIntent);
1546 // Add a `Copy Email Address` entry.
1547 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1549 public boolean onMenuItemClick(MenuItem item) {
1550 // Save the email address in a `ClipData`.
1551 ClipData srcEmailTypeClipData = ClipData.newPlainText(getResources().getString(R.string.email_address), linkUrl);
1553 // Set the `ClipData` as the clipboard's primary clip.
1554 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
1559 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1560 menu.add(R.string.cancel);
1563 // `IMAGE_TYPE` is an image.
1564 case WebView.HitTestResult.IMAGE_TYPE:
1565 // Get the image URL.
1566 imageUrl = hitTestResult.getExtra();
1568 // Set the image URL as the title of the `ContextMenu`.
1569 menu.setHeaderTitle(imageUrl);
1571 // Add a `View Image` entry.
1572 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1574 public boolean onMenuItemClick(MenuItem item) {
1580 // Add a `Download Image` entry.
1581 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1583 public boolean onMenuItemClick(MenuItem item) {
1584 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1585 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1586 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1591 // Add a `Copy URL` entry.
1592 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1594 public boolean onMenuItemClick(MenuItem item) {
1595 // Save the image URL in a `ClipData`.
1596 ClipData srcImageTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1598 // Set the `ClipData` as the clipboard's primary clip.
1599 clipboardManager.setPrimaryClip(srcImageTypeClipData);
1604 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1605 menu.add(R.string.cancel);
1609 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
1610 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1611 // Get the image URL.
1612 imageUrl = hitTestResult.getExtra();
1614 // Set the image URL as the title of the `ContextMenu`.
1615 menu.setHeaderTitle(imageUrl);
1617 // Add a `View Image` entry.
1618 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1620 public boolean onMenuItemClick(MenuItem item) {
1626 // Add a `Download Image` entry.
1627 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1629 public boolean onMenuItemClick(MenuItem item) {
1630 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1631 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1632 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1637 // Add a `Copy URL` entry.
1638 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1640 public boolean onMenuItemClick(MenuItem item) {
1641 // Save the image URL in a `ClipData`.
1642 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1644 // Set the `ClipData` as the clipboard's primary clip.
1645 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
1650 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1651 menu.add(R.string.cancel);
1657 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
1658 // Get shortcutNameEditText from the alert dialog.
1659 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
1661 // Create the bookmark shortcut based on formattedUrlString.
1662 Intent bookmarkShortcut = new Intent();
1663 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
1664 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
1666 // Place the bookmark shortcut on the home screen.
1667 Intent placeBookmarkShortcut = new Intent();
1668 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
1669 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
1670 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIconBitmap);
1671 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
1672 sendBroadcast(placeBookmarkShortcut);
1676 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
1677 // Download the image if it has an HTTP or HTTPS URI.
1678 if (imageUrl.startsWith("http")) {
1679 // Get a handle for the system `DOWNLOAD_SERVICE`.
1680 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1682 // Parse `imageUrl`.
1683 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
1685 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
1686 if (firstPartyCookiesEnabled) {
1687 // Get the cookies for `imageUrl`.
1688 String cookies = cookieManager.getCookie(imageUrl);
1690 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
1691 downloadRequest.addRequestHeader("Cookie", cookies);
1694 // Get the file name from `dialogFragment`.
1695 EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
1696 String imageName = downloadImageNameEditText.getText().toString();
1698 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1699 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
1700 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
1701 } else { // Only set the title using `imageName`.
1702 downloadRequest.setTitle(imageName);
1705 // Allow `MediaScanner` to index the download if it is a media file.
1706 downloadRequest.allowScanningByMediaScanner();
1708 // Add the URL as the description for the download.
1709 downloadRequest.setDescription(imageUrl);
1711 // Show the download notification after the download is completed.
1712 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1714 // Initiate the download.
1715 downloadManager.enqueue(downloadRequest);
1716 } else { // The image is not an HTTP or HTTPS URI.
1717 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
1722 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
1723 // Download the file if it has an HTTP or HTTPS URI.
1724 if (downloadUrl.startsWith("http")) {
1726 // Get a handle for the system `DOWNLOAD_SERVICE`.
1727 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1729 // Parse `downloadUrl`.
1730 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
1732 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
1733 if (firstPartyCookiesEnabled) {
1734 // Get the cookies for `downloadUrl`.
1735 String cookies = cookieManager.getCookie(downloadUrl);
1737 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
1738 downloadRequest.addRequestHeader("Cookie", cookies);
1741 // Get the file name from `dialogFragment`.
1742 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
1743 String fileName = downloadFileNameEditText.getText().toString();
1745 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1746 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
1747 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
1748 } else { // Only set the title using `fileName`.
1749 downloadRequest.setTitle(fileName);
1752 // Allow `MediaScanner` to index the download if it is a media file.
1753 downloadRequest.allowScanningByMediaScanner();
1755 // Add the URL as the description for the download.
1756 downloadRequest.setDescription(downloadUrl);
1758 // Show the download notification after the download is completed.
1759 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1761 // Initiate the download.
1762 downloadManager.enqueue(downloadRequest);
1763 } else { // The download is not an HTTP or HTTPS URI.
1764 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
1768 public void viewSslCertificate(View view) {
1769 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
1770 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
1771 viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
1775 public void onSslErrorCancel() {
1776 sslErrorHandler.cancel();
1780 public void onSslErrorProceed() {
1781 sslErrorHandler.proceed();
1785 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
1786 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1787 navigatingHistory = true;
1789 // Load the history entry.
1790 mainWebView.goBackOrForward(moveBackOrForwardSteps);
1794 public void onClearHistory() {
1795 // Clear the history.
1796 mainWebView.clearHistory();
1799 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
1801 public void onBackPressed() {
1802 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
1803 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1804 drawerLayout.closeDrawer(GravityCompat.START);
1806 // Load the previous URL if available.
1807 if (mainWebView.canGoBack()) {
1808 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1809 navigatingHistory = true;
1812 mainWebView.goBack();
1814 // Pass `onBackPressed()` to the system.
1815 super.onBackPressed();
1821 public void onPause() {
1822 // Pause `mainWebView`.
1823 mainWebView.onPause();
1825 // Stop all JavaScript.
1826 mainWebView.pauseTimers();
1828 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1829 if (BuildConfig.FLAVOR.contentEquals("free")) {
1830 BannerAd.pauseAd(adView);
1837 public void onResume() { // `onResume()` also runs every time the app starts after `onCreate()` and `onStart()`.
1840 // Resume JavaScript (if enabled).
1841 mainWebView.resumeTimers();
1843 // Resume `mainWebView`.
1844 mainWebView.onResume();
1846 // Resume the adView for the free flavor.
1847 if (BuildConfig.FLAVOR.contentEquals("free")) {
1848 BannerAd.resumeAd(adView);
1853 public void onRestart() {
1856 // Apply the settings from shared preferences, which might have been changed in `SettingsActivity`.
1859 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1860 updatePrivacyIcons(true);
1864 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
1865 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
1866 String unformattedUrlString = urlTextBox.getText().toString().trim();
1868 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
1869 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
1870 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
1871 if (!unformattedUrlString.startsWith("http")) {
1872 unformattedUrlString = "http://" + unformattedUrlString;
1875 // Initialize `unformattedUrl`.
1876 URL unformattedUrl = null;
1878 // 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.
1880 unformattedUrl = new URL(unformattedUrlString);
1881 } catch (MalformedURLException e) {
1882 e.printStackTrace();
1885 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
1886 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
1887 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
1888 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
1889 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
1890 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
1893 Uri.Builder formattedUri = new Uri.Builder();
1894 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
1896 // Decode `formattedUri` as a `String` in `UTF-8`.
1897 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
1899 // Sanitize the search input and convert it to a search.
1900 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
1902 // Add the base search URL.
1903 formattedUrlString = searchURL + encodedUrlString;
1906 loadUrl(formattedUrlString);
1908 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
1909 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1913 private void loadUrl(String url) {
1914 // Apply any custom domain settings.
1915 applyDomainSettings(url);
1918 mainWebView.loadUrl(url, customHeaders);
1921 // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
1922 @SuppressWarnings("deprecation")
1923 private void applyDomainSettings(String url) {
1924 // Reset `navigatingHistory`.
1925 navigatingHistory = false;
1927 // Parse the URL into a URI.
1928 Uri uri = Uri.parse(url);
1930 // Extract the domain from `uri`.
1931 String hostName = uri.getHost();
1933 // Initialize `loadingNewDomainName`.
1934 boolean loadingNewDomainName;
1936 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
1937 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
1938 //noinspection SimplifiableIfStatement
1939 if ((hostName == null) || (currentDomainName == null)) {
1940 loadingNewDomainName = true;
1941 } else { // Determine if `hostName` equals `currentDomainName`.
1942 loadingNewDomainName = !hostName.equals(currentDomainName);
1945 // 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.
1946 if (loadingNewDomainName) {
1947 // Set the new `hostname` as the `currentDomainName`.
1948 currentDomainName = hostName;
1950 // Reset `favoriteIconBitmap` and display it in the `appbar`.
1951 favoriteIconBitmap = favoriteIconDefaultBitmap;
1952 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
1954 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
1955 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1956 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1958 // Get a full cursor from `domainsDatabaseHelper`.
1959 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
1961 // Initialize `domainSettingsSet`.
1962 Set<String> domainSettingsSet = new HashSet<>();
1964 // Get the domain name column index.
1965 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
1967 // Populate `domainSettingsSet`.
1968 for (int i = 0; i < domainNameCursor.getCount(); i++) {
1969 // Move `domainsCursor` to the current row.
1970 domainNameCursor.moveToPosition(i);
1972 // Store the domain name in `domainSettingsSet`.
1973 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
1976 // Close `domainNameCursor.
1977 domainNameCursor.close();
1979 // Initialize variables to track if this domain has stored domain settings, and if so, under which name.
1980 boolean hostHasDomainSettings = false;
1981 String domainNameInDatabase = null;
1983 // Check the hostname.
1984 if (domainSettingsSet.contains(hostName)) {
1985 hostHasDomainSettings = true;
1986 domainNameInDatabase = hostName;
1989 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
1990 if (hostName != null) {
1991 while (hostName.contains(".") && !hostHasDomainSettings) { // Stop checking if we run out of `.` or if we already know that `hostHasDomainSettings` is `true`.
1992 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
1993 hostHasDomainSettings = true;
1994 domainNameInDatabase = "*." + hostName;
1997 // Strip out the lowest subdomain of `host`.
1998 hostName = hostName.substring(hostName.indexOf(".") + 1);
2002 if (hostHasDomainSettings) { // The url we are loading has custom domain settings.
2003 // Get a cursor for the current host and move it to the first position.
2004 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
2005 currentHostDomainSettingsCursor.moveToFirst();
2007 // Get the settings from the cursor.
2008 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
2009 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
2010 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
2011 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
2012 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
2013 String userAgentString = (currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT)));
2014 int fontSize = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE)));
2016 // Close `currentHostDomainSettingsCursor`.
2017 currentHostDomainSettingsCursor.close();
2019 // Apply the domain settings.
2020 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2021 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2022 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2023 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2024 mainWebView.getSettings().setTextZoom(fontSize);
2026 // Set third-party cookies status if API >= 21.
2027 if (Build.VERSION.SDK_INT >= 21) {
2028 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2031 // Set the user agent.
2032 if (userAgentString.equals("WebView default user agent")) {
2033 // Set the user agent to `""`, which uses the default value.
2034 mainWebView.getSettings().setUserAgentString("");
2036 // Use the selected user agent.
2037 mainWebView.getSettings().setUserAgentString(userAgentString);
2040 // 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.
2041 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_green));
2042 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
2043 // Get the shared preference values. `this` references the current context.
2044 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2046 // Store the values from `sharedPreferences` in variables.
2047 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
2048 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
2049 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
2050 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
2051 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
2052 String userAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
2053 String customUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
2054 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
2056 // Apply the default settings.
2057 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2058 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2059 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2060 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2061 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2063 // Set third-party cookies status if API >= 21.
2064 if (Build.VERSION.SDK_INT >= 21) {
2065 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2068 // Set the default user agent.
2069 switch (userAgentString) {
2070 case "WebView default user agent":
2071 // Set the user agent to `""`, which uses the default value.
2072 mainWebView.getSettings().setUserAgentString("");
2075 case "Custom user agent":
2076 // Set the custom user agent.
2077 mainWebView.getSettings().setUserAgentString(customUserAgentString);
2081 // Use the selected user agent.
2082 mainWebView.getSettings().setUserAgentString(userAgentString);
2086 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2087 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.url_bar_background_transparent));
2090 // Close `domainsDatabaseHelper`.
2091 domainsDatabaseHelper.close();
2093 // Update the privacy icons, but only if `mainMenu` has already been populated.
2094 if (mainMenu != null) {
2095 updatePrivacyIcons(true);
2100 public void findPreviousOnPage(View view) {
2101 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2102 mainWebView.findNext(false);
2105 public void findNextOnPage(View view) {
2106 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2107 mainWebView.findNext(true);
2110 public void closeFindOnPage(View view) {
2111 // Delete the contents of `find_on_page_edittext`.
2112 findOnPageEditText.setText(null);
2114 // Clear the highlighted phrases.
2115 mainWebView.clearMatches();
2117 // Hide the Find on Page `RelativeLayout`.
2118 findOnPageLinearLayout.setVisibility(View.GONE);
2120 // Show the URL app bar.
2121 supportAppBar.setVisibility(View.VISIBLE);
2123 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2124 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2127 private void applyAppSettings() {
2128 // Get the shared preference values. `this` references the current context.
2129 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2131 // Store the values from `sharedPreferences` in variables.
2132 String homepageString = sharedPreferences.getString("homepage", "https://duckduckgo.com");
2133 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2134 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2135 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
2136 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
2137 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
2138 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
2139 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2140 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2141 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2142 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("enable_full_screen_browsing_mode", false);
2143 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2144 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2145 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
2147 // Set the homepage, search, and proxy options.
2148 if (proxyThroughOrbot) { // Set the Tor options.
2149 // Set `torHomepageString` as `homepage`.
2150 homepage = torHomepageString;
2152 // If formattedUrlString is null assign the homepage to it.
2153 if (formattedUrlString == null) {
2154 formattedUrlString = homepage;
2157 // Set the search URL.
2158 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
2159 searchURL = torSearchCustomURLString;
2160 } else { // Use the string from the pre-built list.
2161 searchURL = torSearchString;
2164 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
2165 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2167 // Display a message to the user if we are waiting on Orbot.
2168 if (!orbotStatus.equals("ON")) {
2169 // Set `waitingForOrbot`.
2170 waitingForOrbot = true;
2172 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
2173 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2175 } else { // Set the non-Tor options.
2176 // Set `homepageString` as `homepage`.
2177 homepage = homepageString;
2179 // If formattedUrlString is null assign the homepage to it.
2180 if (formattedUrlString == null) {
2181 formattedUrlString = homepage;
2184 // Set the search URL.
2185 if (searchString.equals("Custom URL")) { // Get the custom URL string.
2186 searchURL = searchCustomURLString;
2187 } else { // Use the string from the pre-built list.
2188 searchURL = searchString;
2191 // Reset the proxy to default. The host is `""` and the port is `"0"`.
2192 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2194 // Reset `waitingForOrbot.
2195 waitingForOrbot = false;
2198 // Set swipe to refresh.
2199 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2201 // Set Do Not Track status.
2202 if (doNotTrackEnabled) {
2203 customHeaders.put("DNT", "1");
2205 customHeaders.remove("DNT");
2208 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2209 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2210 if (hideSystemBarsOnFullscreen) { // Hide everything.
2211 // Remove the translucent navigation setting if it is currently flagged.
2212 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2214 // Remove the translucent status bar overlay.
2215 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2217 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2218 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2220 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2221 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2222 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2224 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2225 } else { // Hide everything except the status and navigation bars.
2226 // Add the translucent status flag if it is unset.
2227 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2229 if (translucentNavigationBarOnFullscreen) {
2230 // Set the navigation bar to be translucent.
2231 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2233 // Set the navigation bar to be black.
2234 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2237 } else { // Switch to normal viewing mode.
2238 // Reset `inFullScreenBrowsingMode` to `false`.
2239 inFullScreenBrowsingMode = false;
2241 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
2242 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
2246 // Show the `BannerAd` in the free flavor.
2247 if (BuildConfig.FLAVOR.contentEquals("free")) {
2248 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
2249 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2251 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2252 adView = findViewById(R.id.adview);
2255 // Remove the translucent navigation bar flag if it is set.
2256 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2258 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2259 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2261 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
2262 rootCoordinatorLayout.setSystemUiVisibility(0);
2264 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
2265 rootCoordinatorLayout.setFitsSystemWindows(true);
2269 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
2270 // Get handles for the icons.
2271 MenuItem privacyIcon = mainMenu.findItem(R.id.toggleJavaScript);
2272 MenuItem firstPartyCookiesIcon = mainMenu.findItem(R.id.toggleFirstPartyCookies);
2273 MenuItem domStorageIcon = mainMenu.findItem(R.id.toggleDomStorage);
2274 MenuItem formDataIcon = mainMenu.findItem(R.id.toggleSaveFormData);
2276 // Update `privacyIcon`.
2277 if (javaScriptEnabled) { // JavaScript is enabled.
2278 privacyIcon.setIcon(R.drawable.javascript_enabled);
2279 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
2280 privacyIcon.setIcon(R.drawable.warning);
2281 } else { // All the dangerous features are disabled.
2282 privacyIcon.setIcon(R.drawable.privacy_mode);
2285 // Update `firstPartyCookiesIcon`.
2286 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2287 firstPartyCookiesIcon.setIcon(R.drawable.cookies_enabled);
2288 } else { // First-party cookies are disabled.
2289 firstPartyCookiesIcon.setIcon(R.drawable.cookies_disabled);
2292 // Update `domStorageIcon`.
2293 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
2294 domStorageIcon.setIcon(R.drawable.dom_storage_enabled);
2295 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
2296 domStorageIcon.setIcon(R.drawable.dom_storage_disabled);
2297 } else { // JavaScript is disabled, so DOM storage is ghosted.
2298 domStorageIcon.setIcon(R.drawable.dom_storage_ghosted);
2301 // Update `formDataIcon`.
2302 if (saveFormDataEnabled) { // Form data is enabled.
2303 formDataIcon.setIcon(R.drawable.form_data_enabled);
2304 } else { // Form data is disabled.
2305 formDataIcon.setIcon(R.drawable.form_data_disabled);
2308 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
2309 if (runInvalidateOptionsMenu) {
2310 ActivityCompat.invalidateOptionsMenu(this);