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.BitmapFactory;
38 import android.graphics.Typeface;
39 import android.graphics.drawable.BitmapDrawable;
40 import android.graphics.drawable.Drawable;
41 import android.net.Uri;
42 import android.net.http.SslCertificate;
43 import android.net.http.SslError;
44 import android.os.Build;
45 import android.os.Bundle;
46 import android.os.Handler;
47 import android.preference.PreferenceManager;
48 import android.print.PrintDocumentAdapter;
49 import android.print.PrintManager;
50 import android.support.annotation.NonNull;
51 import android.support.design.widget.CoordinatorLayout;
52 import android.support.design.widget.FloatingActionButton;
53 import android.support.design.widget.NavigationView;
54 import android.support.design.widget.Snackbar;
55 import android.support.v4.app.ActivityCompat;
56 import android.support.v4.content.ContextCompat;
57 // `ShortcutInfoCompat`, `ShortcutManagerCompat`, and `IconCompat` can be switched to the non-compat version once API >= 26.
58 import android.support.v4.content.pm.ShortcutInfoCompat;
59 import android.support.v4.content.pm.ShortcutManagerCompat;
60 import android.support.v4.graphics.drawable.IconCompat;
61 import android.support.v4.view.GravityCompat;
62 import android.support.v4.widget.DrawerLayout;
63 import android.support.v4.widget.SwipeRefreshLayout;
64 import android.support.v7.app.ActionBar;
65 import android.support.v7.app.ActionBarDrawerToggle;
66 import android.support.v7.app.AppCompatActivity;
67 import android.support.v7.app.AppCompatDialogFragment;
68 import android.support.v7.widget.Toolbar;
69 import android.text.Editable;
70 import android.text.Spanned;
71 import android.text.TextWatcher;
72 import android.text.style.ForegroundColorSpan;
73 import android.util.Patterns;
74 import android.view.ContextMenu;
75 import android.view.GestureDetector;
76 import android.view.KeyEvent;
77 import android.view.Menu;
78 import android.view.MenuItem;
79 import android.view.MotionEvent;
80 import android.view.View;
81 import android.view.ViewGroup;
82 import android.view.WindowManager;
83 import android.view.inputmethod.InputMethodManager;
84 import android.webkit.CookieManager;
85 import android.webkit.HttpAuthHandler;
86 import android.webkit.SslErrorHandler;
87 import android.webkit.WebBackForwardList;
88 import android.webkit.WebChromeClient;
89 import android.webkit.WebResourceResponse;
90 import android.webkit.WebStorage;
91 import android.webkit.WebView;
92 import android.webkit.WebViewClient;
93 import android.webkit.WebViewDatabase;
94 import android.widget.CursorAdapter;
95 import android.widget.EditText;
96 import android.widget.FrameLayout;
97 import android.widget.ImageView;
98 import android.widget.LinearLayout;
99 import android.widget.ListView;
100 import android.widget.ProgressBar;
101 import android.widget.RadioButton;
102 import android.widget.RelativeLayout;
103 import android.widget.TextView;
105 import com.stoutner.privacybrowser.BannerAd;
106 import com.stoutner.privacybrowser.BuildConfig;
107 import com.stoutner.privacybrowser.R;
108 import com.stoutner.privacybrowser.dialogs.AddDomainDialog;
109 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
110 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
111 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
112 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
113 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
114 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
115 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
116 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
117 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
118 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
119 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
120 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
121 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
122 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
123 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
125 import java.io.BufferedReader;
126 import java.io.ByteArrayInputStream;
127 import java.io.ByteArrayOutputStream;
129 import java.io.IOException;
130 import java.io.InputStreamReader;
131 import java.io.UnsupportedEncodingException;
132 import java.net.MalformedURLException;
134 import java.net.URLDecoder;
135 import java.net.URLEncoder;
136 import java.util.Date;
137 import java.util.HashMap;
138 import java.util.HashSet;
139 import java.util.Map;
140 import java.util.Set;
142 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
143 public class MainWebViewActivity extends AppCompatActivity implements AddDomainDialog.AddDomainListener, CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener, CreateHomeScreenShortcutDialog.CreateHomeScreenSchortcutListener,
144 DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener, HttpAuthenticationDialog.HttpAuthenticationListener,
145 NavigationView.OnNavigationItemSelectedListener, PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener, SslCertificateErrorDialog.SslCertificateErrorListener, UrlHistoryDialog.UrlHistoryListener {
147 // `darkTheme` is public static so it can be accessed from `AboutActivity`, `GuideActivity`, `AddDomainDialog`, `SettingsActivity`, `DomainsActivity`, `DomainsListFragment`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`,
148 // `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `DownloadFileDialog`, `DownloadImageDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `EditBookmarkDatabaseViewDialog`, `HttpAuthenticationDialog`, `MoveToFolderDialog`,
149 // `SslCertificateErrorDialog`, `UrlHistoryDialog`, `ViewSslCertificateDialog`, `CreateHomeScreenShortcutDialog`, and `OrbotProxyHelper`. It is also used in `onCreate()`, `applyAppSettings()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
150 public static boolean darkTheme;
152 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `EditBookmarkDialog`,
153 // `EditBookmarkFolderDialog`, `EditBookmarkDatabaseViewDialog`, and `ViewSslCertificateDialog`. It is also used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onCreateHomeScreenShortcutCreate()`, `onSaveEditBookmark()`,
154 // `onSaveEditBookmarkFolder()`, and `applyDomainSettings()`.
155 public static Bitmap favoriteIconBitmap;
157 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
158 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
159 public static String formattedUrlString;
161 // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`, and `ViewSslCertificateDialog`. It is also used in `onCreate()`.
162 public static SslCertificate sslCertificate;
164 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`.
165 public static String orbotStatus;
167 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
168 public static String webViewTitle;
170 // `displayWebpageImagesBoolean` is public static so it can be accessed from `DomainSettingsFragment`. It is also used in `applyAppSettings()` and `applyDomainSettings()`.
171 public static boolean displayWebpageImagesBoolean;
173 // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`
174 public static boolean reloadOnRestart;
176 // `reloadUrlOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`.
177 public static boolean loadUrlOnRestart;
179 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
180 public static boolean restartFromBookmarksActivity;
182 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and
183 // `loadBookmarksFolder()`.
184 public static String currentBookmarksFolder;
186 // `domainSettingsDatabaseId` is public static so it can be accessed from `PinnedSslCertificateMismatchDialog`. It is also used in `onCreate()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
187 public static int domainSettingsDatabaseId;
189 // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`. They are also used in `onCreate()` and `applyDomainSettings()`.
190 public static String pinnedDomainSslIssuedToCNameString;
191 public static String pinnedDomainSslIssuedToONameString;
192 public static String pinnedDomainSslIssuedToUNameString;
193 public static String pinnedDomainSslIssuedByCNameString;
194 public static String pinnedDomainSslIssuedByONameString;
195 public static String pinnedDomainSslIssuedByUNameString;
196 public static Date pinnedDomainSslStartDate;
197 public static Date pinnedDomainSslEndDate;
200 // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
201 private ActionBar appBar;
203 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
204 private boolean navigatingHistory;
206 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
207 private Bitmap favoriteIconDefaultBitmap;
209 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, `onBackPressed()`, and `onRestart()`.
210 private DrawerLayout drawerLayout;
212 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
213 private CoordinatorLayout rootCoordinatorLayout;
215 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`
216 // `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
217 private WebView mainWebView;
219 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
220 private FrameLayout fullScreenVideoFrameLayout;
222 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
223 private SwipeRefreshLayout swipeRefreshLayout;
225 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
226 private RelativeLayout urlAppBarRelativeLayout;
228 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
229 private ImageView favoriteIconImageView;
231 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
232 private CookieManager cookieManager;
234 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
235 private final Map<String, String> customHeaders = new HashMap<>();
237 // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
238 private boolean javaScriptEnabled;
240 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
241 private boolean firstPartyCookiesEnabled;
243 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
244 private boolean thirdPartyCookiesEnabled;
246 // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
247 private boolean domStorageEnabled;
249 // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
250 private boolean saveFormDataEnabled;
252 // `nightMode` is used in `onCreate()` and `applyDomainSettings()`.
253 private boolean nightMode;
255 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applyAppSettings()`.
256 private boolean swipeToRefreshEnabled;
258 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
259 private String homepage;
261 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
262 private String searchURL;
264 // `adBlockerEnabled` is used in `onCreate()` and `applyAppSettings()`.
265 private boolean adBlockerEnabled;
267 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
268 private Runtime privacyBrowserRuntime;
270 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
271 private boolean incognitoModeEnabled;
273 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
274 private boolean fullScreenBrowsingModeEnabled;
276 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
277 private boolean inFullScreenBrowsingMode;
279 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
280 private boolean hideSystemBarsOnFullscreen;
282 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
283 private boolean translucentNavigationBarOnFullscreen;
285 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
286 private boolean reapplyDomainSettingsOnRestart;
288 // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
289 private String currentDomainName;
291 // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
292 private boolean ignorePinnedSslCertificate;
294 // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
295 private boolean waitingForOrbot;
297 // `domainSettingsApplied` is used in `prepareOptionsMenu()`, `applyDomainSettings()`, and `setDisplayWebpageImages()`.
298 private boolean domainSettingsApplied;
300 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
301 private int displayWebpageImagesInt;
303 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
304 private boolean onTheFlyDisplayImagesSet;
306 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
307 private String waitingForOrbotHTMLString;
309 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
310 private String privateDataDirectoryString;
312 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
313 private LinearLayout findOnPageLinearLayout;
315 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
316 private EditText findOnPageEditText;
318 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
319 private Menu mainMenu;
321 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
322 private ActionBarDrawerToggle drawerToggle;
324 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
325 private Toolbar supportAppBar;
327 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
328 private EditText urlTextBox;
330 // `redColorSpan` is used in `onCreate()` and `highlightUrlText()`.
331 private ForegroundColorSpan redColorSpan;
333 // `initialGrayColorSpan` is sued in `onCreate()` and `highlightUrlText()`.
334 private ForegroundColorSpan initialGrayColorSpan;
336 // `finalGrayColorSpam` is used in `onCreate()` and `highlightUrlText()`.
337 private ForegroundColorSpan finalGrayColorSpan;
339 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
342 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
343 private SslErrorHandler sslErrorHandler;
345 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
346 private static HttpAuthHandler httpAuthHandler;
348 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
349 private InputMethodManager inputMethodManager;
351 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
352 private RelativeLayout mainWebViewRelativeLayout;
354 // `urlIsLoading` is used in `onCreate()`, `loadUrl()`, and `applyDomainSettings()`.
355 private boolean urlIsLoading;
357 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
358 private boolean pinnedDomainSslCertificate;
360 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
361 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
363 // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
364 private ListView bookmarksListView;
366 // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
367 private TextView bookmarksTitleTextView;
369 // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
370 private Cursor bookmarksCursor;
372 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
373 private CursorAdapter bookmarksCursorAdapter;
375 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
376 private String oldFolderNameString;
379 // 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.
380 @SuppressLint({"SetJavaScriptEnabled"})
381 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
382 @SuppressWarnings("deprecation")
383 protected void onCreate(Bundle savedInstanceState) {
384 // Get a handle for `sharedPreferences`. `this` references the current context.
385 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
387 // Get the theme preference.
388 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
390 // Set the activity theme.
392 setTheme(R.style.PrivacyBrowserDark);
394 setTheme(R.style.PrivacyBrowserLight);
397 // Run the default commands.
398 super.onCreate(savedInstanceState);
400 // Set the content view.
401 setContentView(R.layout.main_drawerlayout);
403 // Get a handle for `inputMethodManager`.
404 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
406 // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
407 supportAppBar = findViewById(R.id.app_bar);
408 setSupportActionBar(supportAppBar);
409 appBar = getSupportActionBar();
411 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
412 assert appBar != null;
414 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
415 appBar.setCustomView(R.layout.url_app_bar);
416 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
418 // Initialize the `ForegroundColorSpans` and `StyleSpan` for highlighting `urlTextBox`. We have to use the deprecated `getColor()` until API >= 23.
419 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
420 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
421 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
423 // Get a handle for `urlTextBox`.
424 urlTextBox = appBar.getCustomView().findViewById(R.id.url_edittext);
426 // Remove the formatting from `urlTextBar` when the user is editing the text.
427 urlTextBox.setOnFocusChangeListener((v, hasFocus) -> {
428 if (hasFocus) { // The user is editing `urlTextBox`.
429 // Remove the highlighting.
430 urlTextBox.getText().removeSpan(redColorSpan);
431 urlTextBox.getText().removeSpan(initialGrayColorSpan);
432 urlTextBox.getText().removeSpan(finalGrayColorSpan);
433 } else { // The user has stopped editing `urlTextBox`.
434 // Reapply the highlighting.
439 // Set the `Go` button on the keyboard to load the URL in `urlTextBox`.
440 urlTextBox.setOnKeyListener((v, keyCode, event) -> {
441 // If the event is a key-down event on the `enter` button, load the URL.
442 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
443 // Load the URL into the mainWebView and consume the event.
445 loadUrlFromTextBox();
446 } catch (UnsupportedEncodingException e) {
449 // If the enter key was pressed, consume the event.
452 // If any other key was pressed, do not consume the event.
457 // Set `waitingForOrbotHTMLString`.
458 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
460 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
461 currentDomainName = "";
462 orbotStatus = "unknown";
463 waitingForOrbot = false;
465 // Create an Orbot status `BroadcastReceiver`.
466 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
468 public void onReceive(Context context, Intent intent) {
469 // Store the content of the status message in `orbotStatus`.
470 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
472 // If we are waiting on Orbot, load the website now that Orbot is connected.
473 if (orbotStatus.equals("ON") && waitingForOrbot) {
474 // Reset `waitingForOrbot`.
475 waitingForOrbot = false;
477 // Load `formattedUrlString
478 loadUrl(formattedUrlString);
483 // Register `orbotStatusBroadcastReceiver` on `this` context.
484 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
486 // Get handles for views that need to be accessed.
487 drawerLayout = findViewById(R.id.drawerlayout);
488 rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
489 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
490 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
491 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
492 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
493 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
494 mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
495 mainWebView = findViewById(R.id.main_webview);
496 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
497 findOnPageEditText = findViewById(R.id.find_on_page_edittext);
498 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
499 urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
500 favoriteIconImageView = findViewById(R.id.favorite_icon);
502 // Set the bookmarks drawer resources according to the theme. This can't be done in the layout due to compatibility issues with the `DrawerLayout` support widget.
504 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
505 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
506 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
507 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
509 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
510 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
511 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
512 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
515 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
516 launchBookmarksActivityFab.setOnClickListener(v -> {
517 // Create an intent to launch the bookmarks activity.
518 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
520 // Include the current folder with the `Intent`.
521 bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
524 startActivity(bookmarksIntent);
527 // Set the create new bookmark folder FAB to display the `AlertDialog`.
528 createBookmarkFolderFab.setOnClickListener(v -> {
529 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
530 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
531 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
534 // Set the create new bookmark FAB to display the `AlertDialog`.
535 createBookmarkFab.setOnClickListener(view -> {
536 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
537 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
538 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
541 // Create a double-tap listener to toggle full-screen mode.
542 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
543 // Override `onDoubleTap()`. All other events are handled using the default settings.
545 public boolean onDoubleTap(MotionEvent event) {
546 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
547 // Toggle `inFullScreenBrowsingMode`.
548 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
550 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
551 // Hide the `appBar`.
554 // Hide the `BannerAd` in the free flavor.
555 if (BuildConfig.FLAVOR.contentEquals("free")) {
556 BannerAd.hideAd(adView);
559 // Modify the system bars.
560 if (hideSystemBarsOnFullscreen) { // Hide everything.
561 // Remove the translucent overlays.
562 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
564 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
565 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
567 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
568 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
569 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
571 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
573 // Set `rootCoordinatorLayout` to fill the whole screen.
574 rootCoordinatorLayout.setFitsSystemWindows(false);
575 } else { // Hide everything except the status and navigation bars.
576 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
577 rootCoordinatorLayout.setFitsSystemWindows(false);
579 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.
580 // Set the navigation bar to be translucent.
581 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
584 } else { // Switch to normal viewing mode.
585 // Show the `appBar`.
588 // Show the `BannerAd` in the free flavor.
589 if (BuildConfig.FLAVOR.contentEquals("free")) {
590 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
591 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
593 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
594 adView = findViewById(R.id.adview);
597 // Remove the translucent navigation bar flag if it is set.
598 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
600 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
601 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
603 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
604 rootCoordinatorLayout.setSystemUiVisibility(0);
606 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
607 rootCoordinatorLayout.setFitsSystemWindows(true);
610 // Consume the double-tap.
612 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
618 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
619 mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
620 // Call `performClick()` on the view, which is required for accessibility.
623 // Send the `event` to `gestureDetector`.
624 return gestureDetector.onTouchEvent(event);
627 // Update `findOnPageCountTextView`.
628 mainWebView.setFindListener(new WebView.FindListener() {
629 // Get a handle for `findOnPageCountTextView`.
630 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
633 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
634 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
635 // Set `findOnPageCountTextView` to `0/0`.
636 findOnPageCountTextView.setText(R.string.zero_of_zero);
637 } else if (isDoneCounting) { // There are matches.
638 // `activeMatchOrdinal` is zero-based.
639 int activeMatch = activeMatchOrdinal + 1;
641 // Build the match string.
642 String matchString = activeMatch + "/" + numberOfMatches;
644 // Set `findOnPageCountTextView`.
645 findOnPageCountTextView.setText(matchString);
650 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
651 findOnPageEditText.addTextChangedListener(new TextWatcher() {
653 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
658 public void onTextChanged(CharSequence s, int start, int before, int count) {
663 public void afterTextChanged(Editable s) {
664 // Search for the text in `mainWebView`.
665 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
669 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
670 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
671 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
672 // Hide the soft keyboard. `0` indicates no additional flags.
673 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
675 // Consume the event.
677 } else { // A different key was pressed.
678 // Do not consume the event.
683 // Implement swipe to refresh
684 swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
685 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
686 swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
688 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
689 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
690 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
692 // Listen for touches on the navigation menu.
693 final NavigationView navigationView = findViewById(R.id.navigationview);
694 navigationView.setNavigationItemSelectedListener(this);
696 // 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.
697 final Menu navigationMenu = navigationView.getMenu();
698 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
699 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
700 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
702 // Initialize the bookmarks database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
703 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
704 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
706 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
707 currentBookmarksFolder = "";
709 // Load the home folder, which is `""` in the database.
710 loadBookmarksFolder();
712 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
713 // Convert the id from long to int to match the format of the bookmarks database.
714 int databaseID = (int) id;
716 // Get the bookmark `Cursor` for this ID and move it to the first row.
717 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
718 bookmarkCursor.moveToFirst();
720 // Act upon the bookmark according to the type.
721 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
722 // Store the new folder name in `currentBookmarksFolder`.
723 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
725 // Load the new folder.
726 loadBookmarksFolder();
727 } else { // The selected bookmark is not a folder.
728 // Load the bookmark URL.
729 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
731 // Close the bookmarks drawer.
732 drawerLayout.closeDrawer(GravityCompat.END);
735 // Close the `Cursor`.
736 bookmarkCursor.close();
739 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
740 // Convert the database ID from `long` to `int`.
741 int databaseId = (int) id;
743 // Find out if the selected bookmark is a folder.
744 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
747 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
748 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
750 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
751 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
752 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
754 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
755 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
756 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
759 // Consume the event.
763 // The `DrawerListener` allows us to update the Navigation Menu.
764 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
766 public void onDrawerSlide(View drawerView, float slideOffset) {
770 public void onDrawerOpened(View drawerView) {
774 public void onDrawerClosed(View drawerView) {
778 public void onDrawerStateChanged(int newState) {
779 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
780 // Update the `Back`, `Forward`, and `History` menu items.
781 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
782 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
783 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
785 // Hide the keyboard (if displayed) so we can see the navigation menu. `0` indicates no additional flags.
786 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
788 // Clear the focus from `urlTextBox` if it has it.
789 urlTextBox.clearFocus();
794 // drawerToggle creates the hamburger icon at the start of the AppBar.
795 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
797 // Initialize `adServerSet`.
798 final Set<String> adServersSet = new HashSet<>();
800 // Load the list of ad servers into memory.
802 // Load `pgl.yoyo.org_adservers.txt` into a `BufferedReader`.
803 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("pgl.yoyo.org_adservers.txt")));
805 // Create a string for storing each ad server.
808 // Populate `adServersSet`.
809 while ((adServer = bufferedReader.readLine()) != null) {
810 adServersSet.add(adServer);
813 // Close `bufferedReader`.
814 bufferedReader.close();
815 } catch (IOException ioException) {
816 // We're pretty sure the asset exists, so we don't need to worry about the `IOException` ever being thrown.
819 mainWebView.setWebViewClient(new WebViewClient() {
820 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
821 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
822 @SuppressWarnings("deprecation")
824 public boolean shouldOverrideUrlLoading(WebView view, String url) {
825 if (url.startsWith("mailto:")) { // Load the email address in an external email program.
826 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
827 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
829 // Parse the url and set it as the data for the `Intent`.
830 emailIntent.setData(Uri.parse(url));
832 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
833 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
836 startActivity(emailIntent);
838 // Returning `true` indicates the application is handling the URL.
840 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
841 // `ACTION_DIAL` open the dialer and loads the phone number, but waits for the user to place the call.
842 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
844 // Add the phone number to the intent.
845 dialIntent.setData(Uri.parse(url));
847 // `FLAG_ACTIVITY_NEW_TASK` opens the dialer in a new task instead as part of Privacy Browser.
848 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
851 startActivity(dialIntent);
853 // Returning `true` indicates the application is handling the URL.
855 } else { // Load the URL in Privacy Browser.
856 // Apply the domain settings for the new URL.
857 applyDomainSettings(url);
859 // Returning `false` causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
864 // Block ads. We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
865 @SuppressWarnings("deprecation")
867 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
868 if (adBlockerEnabled) { // Block ads.
869 // Extract the host from `url`.
870 Uri requestUri = Uri.parse(url);
871 String requestHost = requestUri.getHost();
873 // Initialize a variable to track if this is an ad server.
874 boolean requestHostIsAdServer = false;
876 // Check all the subdomains of `requestHost` if it is not `null` against the ad server database.
877 if (requestHost != null) {
878 while (requestHost.contains(".") && !requestHostIsAdServer) { // Stop checking if we run out of `.` or if we already know that `requestHostIsAdServer` is `true`.
879 if (adServersSet.contains(requestHost)) {
880 requestHostIsAdServer = true;
883 // Strip out the lowest subdomain of `requestHost`.
884 requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
888 if (requestHostIsAdServer) { // It is an ad server.
889 // Return an empty `WebResourceResponse`.
890 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
891 } else { // It is not an ad server.
892 // `return null` loads the requested resource.
895 } else { // Ad blocking is disabled.
896 // `return null` loads the requested resource.
901 // Handle HTTP authentication requests.
903 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
904 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
905 httpAuthHandler = handler;
907 // Display the HTTP authentication dialog.
908 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
909 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
912 // Update the URL in urlTextBox when the page starts to load.
914 public void onPageStarted(WebView view, String url, Bitmap favicon) {
915 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
917 mainWebView.setVisibility(View.INVISIBLE);
920 // Hide the keyboard. `0` indicates no additional flags.
921 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
923 // Check to see if we are waiting on Orbot.
924 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
925 // 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.
926 formattedUrlString = url;
928 // Display the formatted URL text.
929 urlTextBox.setText(formattedUrlString);
931 // Apply text highlighting to `urlTextBox`.
934 // Apply any custom domain settings if the URL was loaded by navigating history.
935 if (navigatingHistory) {
936 applyDomainSettings(url);
939 // Set `urlIsLoading` to `true`, so that redirects while loading do not trigger changes in the user agent, which forces another reload of the existing page.
944 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
946 public void onPageFinished(WebView view, String url) {
947 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
948 urlIsLoading = false;
950 // Clear the cache and history if Incognito Mode is enabled.
951 if (incognitoModeEnabled) {
952 // Clear the cache. `true` includes disk files.
953 mainWebView.clearCache(true);
955 // Clear the back/forward history.
956 mainWebView.clearHistory();
958 // Manually delete cache folders.
960 // Delete the main `cache` folder.
961 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
963 // 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`.
964 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
965 } catch (IOException e) {
966 // Do nothing if an error is thrown.
970 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
971 if (!waitingForOrbot) {
972 // Check to see if `WebView` has set `url` to be `about:blank`.
973 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
974 // Set `formattedUrlString` to `""`.
975 formattedUrlString = "";
977 urlTextBox.setText(formattedUrlString);
979 // Request focus for `urlTextBox`.
980 urlTextBox.requestFocus();
982 // Display the keyboard.
983 inputMethodManager.showSoftInput(urlTextBox, 0);
985 // Apply the domain settings. This clears any settings from the previous domain.
986 applyDomainSettings(formattedUrlString);
987 } else { // `WebView` has loaded a webpage.
988 // Set `formattedUrlString`.
989 formattedUrlString = url;
991 // Only update `urlTextBox` if the user is not typing in it.
992 if (!urlTextBox.hasFocus()) {
993 // Display the formatted URL text.
994 urlTextBox.setText(formattedUrlString);
996 // Apply text highlighting to `urlTextBox`.
1001 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1002 sslCertificate = mainWebView.getCertificate();
1004 // Check the current website SSL certificate against the pinned SSL certificate if there is a pinned SSL certificate the user has not chosen to ignore it for this session.
1005 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1006 // Initialize the current SSL certificate variables.
1007 String currentWebsiteIssuedToCName = "";
1008 String currentWebsiteIssuedToOName = "";
1009 String currentWebsiteIssuedToUName = "";
1010 String currentWebsiteIssuedByCName = "";
1011 String currentWebsiteIssuedByOName = "";
1012 String currentWebsiteIssuedByUName = "";
1013 Date currentWebsiteSslStartDate = null;
1014 Date currentWebsiteSslEndDate = null;
1017 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1018 if (sslCertificate != null) {
1019 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1020 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1021 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1022 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1023 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1024 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1025 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1026 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1029 // Initialize `String` variables to store the SSL certificate dates. `Strings` are needed to compare the values below, which doesn't work with `Dates` if they are `null`.
1030 String currentWebsiteSslStartDateString = "";
1031 String currentWebsiteSslEndDateString = "";
1032 String pinnedDomainSslStartDateString = "";
1033 String pinnedDomainSslEndDateString = "";
1035 // Convert the `Dates` to `Strings` if they are not `null`.
1036 if (currentWebsiteSslStartDate != null) {
1037 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1040 if (currentWebsiteSslEndDate != null) {
1041 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1044 if (pinnedDomainSslStartDate != null) {
1045 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1048 if (pinnedDomainSslEndDate != null) {
1049 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1052 // Check to see if the pinned SSL certificate matches the current website certificate.
1053 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) || !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) ||
1054 !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) || !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1055 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) { // The pinned SSL certificate doesn't match the current domain certificate.
1056 //Display the pinned SSL certificate mismatch `AlertDialog`.
1057 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1058 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1064 // Handle SSL Certificate errors.
1066 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1067 // Get the current website SSL certificate.
1068 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1070 // Extract the individual pieces of information from the current website SSL certificate.
1071 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1072 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1073 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1074 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1075 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1076 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1077 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1078 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1080 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1081 if (pinnedDomainSslCertificate &&
1082 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) && currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) &&
1083 currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) && currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1084 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) { // An SSL certificate is pinned and matches the current domain certificate.
1085 // Proceed to the website without displaying an error.
1087 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1088 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1089 sslErrorHandler = handler;
1091 // Display the SSL error `AlertDialog`.
1092 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1093 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1098 // Get a handle for the progress bar.
1099 final ProgressBar progressBar = findViewById(R.id.progress_bar);
1101 mainWebView.setWebChromeClient(new WebChromeClient() {
1102 // Update the progress bar when a page is loading.
1104 public void onProgressChanged(WebView view, int progress) {
1105 // Inject the night mode CSS if night mode is enabled.
1107 // `background-color: #212121` sets the background to be dark gray. `color: #BDBDBD` sets the text color to be light gray. `box-shadow: none` removes a lower underline on links used by WordPress.
1108 // `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color. `border: none` removes all borders, which can also be used to underline text.
1109 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
1110 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; style.innerHTML = '" +
1111 "* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important; text-shadow: none !important; border: none !important;}" +
1112 "a {color: #1565C0 !important;}" +
1113 "'; parent.appendChild(style)})()", value -> {
1114 // Initialize a `Handler` to display `mainWebView`.
1115 Handler displayWebViewHandler = new Handler();
1117 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
1118 Runnable displayWebViewRunnable = () -> {
1119 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
1120 if (progressBar.getVisibility() == View.GONE) {
1121 mainWebView.setVisibility(View.VISIBLE);
1125 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
1126 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
1130 progressBar.setProgress(progress);
1131 if (progress < 100) {
1132 // Show the progress bar.
1133 progressBar.setVisibility(View.VISIBLE);
1135 // Hide the progress bar.
1136 progressBar.setVisibility(View.GONE);
1138 // Display `mainWebView` if night mode is disabled.
1139 // Because of a race condition between `applyDomainSettings` and `onPageStarted`, when night mode is set by domain settings the `WebView` may be hidden even if night mode is not currently enabled.
1141 mainWebView.setVisibility(View.VISIBLE);
1144 //Stop the `SwipeToRefresh` indicator if it is running
1145 swipeRefreshLayout.setRefreshing(false);
1149 // Set the favorite icon when it changes.
1151 public void onReceivedIcon(WebView view, Bitmap icon) {
1152 // Only update the favorite icon if the website has finished loading.
1153 if (progressBar.getVisibility() == View.GONE) {
1154 // Save a copy of the favorite icon.
1155 favoriteIconBitmap = icon;
1157 // Place the favorite icon in the appBar.
1158 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
1162 // Save a copy of the title when it changes.
1164 public void onReceivedTitle(WebView view, String title) {
1165 // Save a copy of the title.
1166 webViewTitle = title;
1169 // Enter full screen video
1171 public void onShowCustomView(View view, CustomViewCallback callback) {
1172 // Pause the ad if this is the free flavor.
1173 if (BuildConfig.FLAVOR.contentEquals("free")) {
1174 BannerAd.pauseAd(adView);
1177 // Remove the translucent overlays.
1178 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1180 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1181 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1183 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1184 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1185 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
1187 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1189 // Set `rootCoordinatorLayout` to fill the entire screen.
1190 rootCoordinatorLayout.setFitsSystemWindows(false);
1192 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1193 fullScreenVideoFrameLayout.addView(view);
1194 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1197 // Exit full screen video
1198 public void onHideCustomView() {
1199 // Hide `fullScreenVideoFrameLayout`.
1200 fullScreenVideoFrameLayout.removeAllViews();
1201 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1203 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1204 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1206 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
1207 rootCoordinatorLayout.setFitsSystemWindows(true);
1209 // Show the ad if this is the free flavor.
1210 if (BuildConfig.FLAVOR.contentEquals("free")) {
1211 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
1212 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1214 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1215 adView = findViewById(R.id.adview);
1220 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
1221 registerForContextMenu(mainWebView);
1223 // Allow the downloading of files.
1224 mainWebView.setDownloadListener((url, userAgent, contentDisposition, mimetype, contentLength) -> {
1225 // Show the `DownloadFileDialog` `AlertDialog` and name this instance `@string/download`.
1226 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1227 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1230 // Allow pinch to zoom.
1231 mainWebView.getSettings().setBuiltInZoomControls(true);
1233 // Hide zoom controls.
1234 mainWebView.getSettings().setDisplayZoomControls(false);
1236 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1237 mainWebView.getSettings().setUseWideViewPort(true);
1239 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1240 mainWebView.getSettings().setLoadWithOverviewMode(true);
1242 // Explicitly disable geolocation.
1243 mainWebView.getSettings().setGeolocationEnabled(false);
1245 // Initialize cookieManager.
1246 cookieManager = CookieManager.getInstance();
1248 // 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).
1249 customHeaders.put("X-Requested-With", "");
1251 // 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.
1252 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1254 // Get the intent that started the app.
1255 final Intent launchingIntent = getIntent();
1257 // Extract the launching intent data as `launchingIntentUriData`.
1258 final Uri launchingIntentUriData = launchingIntent.getData();
1260 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1261 if (launchingIntentUriData != null) {
1262 formattedUrlString = launchingIntentUriData.toString();
1265 // Get a handle for the `Runtime`.
1266 privacyBrowserRuntime = Runtime.getRuntime();
1268 // Store the application's private data directory.
1269 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`.
1271 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1272 inFullScreenBrowsingMode = false;
1274 // Initialize AdView for the free flavor.
1275 adView = findViewById(R.id.adview);
1277 // Initialize the privacy settings variables.
1278 javaScriptEnabled = false;
1279 firstPartyCookiesEnabled = false;
1280 thirdPartyCookiesEnabled = false;
1281 domStorageEnabled = false;
1282 saveFormDataEnabled = false;
1285 // Initialize `webViewTitle`.
1286 webViewTitle = getString(R.string.no_title);
1288 // Initialize `favoriteIconBitmap`. We have to use `ContextCompat` until API >= 21.
1289 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1290 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1291 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1293 // If the favorite icon is null, load the default.
1294 if (favoriteIconBitmap == null) {
1295 favoriteIconBitmap = favoriteIconDefaultBitmap;
1298 // Apply the app settings from the shared preferences.
1301 // Load `formattedUrlString` if we are not waiting for Orbot to connect.
1302 if (!waitingForOrbot) {
1303 loadUrl(formattedUrlString);
1308 protected void onNewIntent(Intent intent) {
1309 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1312 if (intent.getData() != null) {
1313 // Get the intent data and convert it to a string.
1314 final Uri intentUriData = intent.getData();
1315 formattedUrlString = intentUriData.toString();
1318 // Close the navigation drawer if it is open.
1319 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1320 drawerLayout.closeDrawer(GravityCompat.START);
1323 // Load the website.
1324 loadUrl(formattedUrlString);
1326 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1327 mainWebView.requestFocus();
1331 public void onRestart() {
1332 // Run the default commands.
1335 // Apply the app settings, which may have been changed in `SettingsActivity`.
1338 // Apply the domain settings if returning from the Domains Activity.
1339 if (reapplyDomainSettingsOnRestart) {
1340 // Reset `reapplyDomainSettingsOnRestart`.
1341 reapplyDomainSettingsOnRestart = false;
1343 // Reapply the domain settings.
1344 applyDomainSettings(formattedUrlString);
1347 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1348 updatePrivacyIcons(true);
1350 // Set the display webpage images mode.
1351 setDisplayWebpageImages();
1353 // Reload the webpage if displaying of images has been disabled in `SettingsFragment`.
1354 if (reloadOnRestart) {
1355 // Reload `mainWebView`.
1356 mainWebView.reload();
1358 // Reset `reloadOnRestartBoolean`.
1359 reloadOnRestart = false;
1362 // Load the URL on restart to apply changes to night mode.
1363 if (loadUrlOnRestart) {
1364 // Load the current `formattedUrlString`.
1365 loadUrl(formattedUrlString);
1367 // Reset `loadUrlOnRestart.
1368 loadUrlOnRestart = false;
1372 if (restartFromBookmarksActivity) {
1373 // Close the bookmarks drawer.
1374 drawerLayout.closeDrawer(GravityCompat.END);
1376 // Reload the bookmarks drawer.
1377 loadBookmarksFolder();
1379 // Reset `restartFromBookmarksActivity`.
1380 restartFromBookmarksActivity = false;
1384 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1386 public void onResume() {
1387 // Run the default commands.
1390 // Resume JavaScript (if enabled).
1391 mainWebView.resumeTimers();
1393 // Resume `mainWebView`.
1394 mainWebView.onResume();
1396 // Resume the adView for the free flavor.
1397 if (BuildConfig.FLAVOR.contentEquals("free")) {
1398 BannerAd.resumeAd(adView);
1403 public void onPause() {
1404 // Pause `mainWebView`.
1405 mainWebView.onPause();
1407 // Stop all JavaScript.
1408 mainWebView.pauseTimers();
1410 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1411 if (BuildConfig.FLAVOR.contentEquals("free")) {
1412 BannerAd.pauseAd(adView);
1419 public boolean onCreateOptionsMenu(Menu menu) {
1420 // Inflate the menu; this adds items to the action bar if it is present.
1421 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1423 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1426 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1427 updatePrivacyIcons(false);
1429 // Get handles for the menu items.
1430 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1431 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1432 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1433 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1435 // Only display third-party cookies if SDK >= 21
1436 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1438 // Get the shared preference values. `this` references the current context.
1439 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1441 // Set the status of the additional app bar icons. The default is `false`.
1442 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1443 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1444 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1445 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1446 } else { //Do not display the additional icons.
1447 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1448 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1449 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1456 public boolean onPrepareOptionsMenu(Menu menu) {
1457 // Get handles for the menu items.
1458 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1459 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1460 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1461 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1462 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1463 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1464 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1465 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1466 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1467 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1468 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1469 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1471 // Set the text for the domain menu item.
1472 if (domainSettingsApplied) {
1473 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1475 addOrEditDomain.setTitle(R.string.add_domain_settings);
1478 // Set the status of the menu item checkboxes.
1479 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1480 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1481 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1482 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1483 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1485 // Enable third-party cookies if first-party cookies are enabled.
1486 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1488 // Enable `DOM Storage` if JavaScript is enabled.
1489 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1491 // Enable `Clear Cookies` if there are any.
1492 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1494 // Get a count of the number of files in the `Local Storage` directory.
1495 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1496 int localStorageDirectoryNumberOfFiles = 0;
1497 if (localStorageDirectory.exists()) {
1498 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1501 // Get a count of the number of files in the `IndexedDB` directory.
1502 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1503 int indexedDBDirectoryNumberOfFiles = 0;
1504 if (indexedDBDirectory.exists()) {
1505 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1508 // Enable `Clear DOM Storage` if there is any.
1509 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1511 // Enable `Clear Form Data` is there is any.
1512 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1513 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1515 // Enable `Clear Data` if any of the submenu items are enabled.
1516 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1518 // Initialize font size variables.
1519 int fontSize = mainWebView.getSettings().getTextZoom();
1520 String fontSizeTitle;
1521 MenuItem selectedFontSizeMenuItem;
1523 // Prepare the font size title and current size menu item.
1526 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1527 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1531 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1532 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1536 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1537 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1541 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1542 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1546 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1547 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1551 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1552 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1556 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1557 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1561 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1562 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1566 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1567 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1571 // Set the font size title and select the current size menu item.
1572 fontSizeMenuItem.setTitle(fontSizeTitle);
1573 selectedFontSizeMenuItem.setChecked(true);
1575 // Only show `Refresh` if `swipeToRefresh` is disabled.
1576 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1578 // Run all the other default commands.
1579 super.onPrepareOptionsMenu(menu);
1581 // `return true` displays the menu.
1586 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1587 @SuppressLint("SetJavaScriptEnabled")
1588 // removeAllCookies is deprecated, but it is required for API < 21.
1589 @SuppressWarnings("deprecation")
1590 public boolean onOptionsItemSelected(MenuItem menuItem) {
1591 int menuItemId = menuItem.getItemId();
1593 // Set the commands that relate to the menu entries.
1594 switch (menuItemId) {
1595 case R.id.add_or_edit_domain:
1596 if (domainSettingsApplied) { // Edit the current domain settings.
1597 // Reapply the domain settings on returning to `MainWebViewActivity`.
1598 reapplyDomainSettingsOnRestart = true;
1599 currentDomainName = "";
1601 // Create an intent to launch the domains activity.
1602 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1604 // Put extra information instructing the domains activity to directly load the current domain.
1605 domainsIntent.putExtra("LoadDomain", domainSettingsDatabaseId);
1608 startActivity(domainsIntent);
1609 } else { // Add a new domain.
1610 // Show the add domain `AlertDialog`.
1611 AppCompatDialogFragment addDomainDialog = new AddDomainDialog();
1612 addDomainDialog.show(getSupportFragmentManager(), getResources().getString(R.string.add_domain));
1616 case R.id.toggle_javascript:
1617 // Switch the status of javaScriptEnabled.
1618 javaScriptEnabled = !javaScriptEnabled;
1620 // Apply the new JavaScript status.
1621 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1623 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1624 updatePrivacyIcons(true);
1626 // Display a `Snackbar`.
1627 if (javaScriptEnabled) { // JavaScrip is enabled.
1628 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1629 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1630 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1631 } else { // Privacy mode.
1632 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1635 // Reload the WebView.
1636 mainWebView.reload();
1639 case R.id.toggle_first_party_cookies:
1640 // Switch the status of firstPartyCookiesEnabled.
1641 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1643 // Update the menu checkbox.
1644 menuItem.setChecked(firstPartyCookiesEnabled);
1646 // Apply the new cookie status.
1647 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1649 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1650 updatePrivacyIcons(true);
1652 // Display a `Snackbar`.
1653 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1654 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1655 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1656 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1657 } else { // Privacy mode.
1658 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1661 // Reload the WebView.
1662 mainWebView.reload();
1665 case R.id.toggle_third_party_cookies:
1666 if (Build.VERSION.SDK_INT >= 21) {
1667 // Switch the status of thirdPartyCookiesEnabled.
1668 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1670 // Update the menu checkbox.
1671 menuItem.setChecked(thirdPartyCookiesEnabled);
1673 // Apply the new cookie status.
1674 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1676 // Display a `Snackbar`.
1677 if (thirdPartyCookiesEnabled) {
1678 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1680 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1683 // Reload the WebView.
1684 mainWebView.reload();
1685 } // Else do nothing because SDK < 21.
1688 case R.id.toggle_dom_storage:
1689 // Switch the status of domStorageEnabled.
1690 domStorageEnabled = !domStorageEnabled;
1692 // Update the menu checkbox.
1693 menuItem.setChecked(domStorageEnabled);
1695 // Apply the new DOM Storage status.
1696 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1698 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1699 updatePrivacyIcons(true);
1701 // Display a `Snackbar`.
1702 if (domStorageEnabled) {
1703 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1705 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1708 // Reload the WebView.
1709 mainWebView.reload();
1712 case R.id.toggle_save_form_data:
1713 // Switch the status of saveFormDataEnabled.
1714 saveFormDataEnabled = !saveFormDataEnabled;
1716 // Update the menu checkbox.
1717 menuItem.setChecked(saveFormDataEnabled);
1719 // Apply the new form data status.
1720 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1722 // Display a `Snackbar`.
1723 if (saveFormDataEnabled) {
1724 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1726 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1729 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1730 updatePrivacyIcons(true);
1732 // Reload the WebView.
1733 mainWebView.reload();
1736 case R.id.clear_cookies:
1737 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1738 .setAction(R.string.undo, v -> {
1739 // Do nothing because everything will be handled by `onDismissed()` below.
1741 .addCallback(new Snackbar.Callback() {
1743 public void onDismissed(Snackbar snackbar, int event) {
1745 // The user pushed the `Undo` button.
1746 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1750 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1752 // `cookieManager.removeAllCookie()` varies by SDK.
1753 if (Build.VERSION.SDK_INT < 21) {
1754 cookieManager.removeAllCookie();
1756 // `null` indicates no callback.
1757 cookieManager.removeAllCookies(null);
1765 case R.id.clear_dom_storage:
1766 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1767 .setAction(R.string.undo, v -> {
1768 // Do nothing because everything will be handled by `onDismissed()` below.
1770 .addCallback(new Snackbar.Callback() {
1772 public void onDismissed(Snackbar snackbar, int event) {
1774 // The user pushed the `Undo` button.
1775 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1779 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1781 // Delete the DOM Storage.
1782 WebStorage webStorage = WebStorage.getInstance();
1783 webStorage.deleteAllData();
1785 // Manually delete the DOM storage files and directories.
1787 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1788 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1790 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1791 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1792 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1793 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1794 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1795 } catch (IOException e) {
1796 // Do nothing if an error is thrown.
1804 case R.id.clear_form_data:
1805 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1806 .setAction(R.string.undo, v -> {
1807 // Do nothing because everything will be handled by `onDismissed()` below.
1809 .addCallback(new Snackbar.Callback() {
1811 public void onDismissed(Snackbar snackbar, int event) {
1813 // The user pushed the `Undo` button.
1814 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1818 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1820 // Delete the form data.
1821 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1822 mainWebViewDatabase.clearFormData();
1829 case R.id.font_size_twenty_five_percent:
1830 mainWebView.getSettings().setTextZoom(25);
1833 case R.id.font_size_fifty_percent:
1834 mainWebView.getSettings().setTextZoom(50);
1837 case R.id.font_size_seventy_five_percent:
1838 mainWebView.getSettings().setTextZoom(75);
1841 case R.id.font_size_one_hundred_percent:
1842 mainWebView.getSettings().setTextZoom(100);
1845 case R.id.font_size_one_hundred_twenty_five_percent:
1846 mainWebView.getSettings().setTextZoom(125);
1849 case R.id.font_size_one_hundred_fifty_percent:
1850 mainWebView.getSettings().setTextZoom(150);
1853 case R.id.font_size_one_hundred_seventy_five_percent:
1854 mainWebView.getSettings().setTextZoom(175);
1857 case R.id.font_size_two_hundred_percent:
1858 mainWebView.getSettings().setTextZoom(200);
1861 case R.id.display_images:
1862 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1863 mainWebView.getSettings().setLoadsImagesAutomatically(false);
1864 mainWebView.reload();
1865 } else { // Images are not currently loaded automatically.
1866 mainWebView.getSettings().setLoadsImagesAutomatically(true);
1869 // Set `onTheFlyDisplayImagesSet`.
1870 onTheFlyDisplayImagesSet = true;
1874 // Setup the share string.
1875 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
1877 // Create the share intent.
1878 Intent shareIntent = new Intent();
1879 shareIntent.setAction(Intent.ACTION_SEND);
1880 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1881 shareIntent.setType("text/plain");
1884 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1887 case R.id.find_on_page:
1888 // Hide the URL app bar.
1889 supportAppBar.setVisibility(View.GONE);
1891 // Show the Find on Page `RelativeLayout`.
1892 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1894 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android. http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1895 findOnPageEditText.postDelayed(() -> {
1896 // Set the focus on `findOnPageEditText`.
1897 findOnPageEditText.requestFocus();
1899 // Display the keyboard. `0` sets no input flags.
1900 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1905 // Get a `PrintManager` instance.
1906 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1908 // Convert `mainWebView` to `printDocumentAdapter`.
1909 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1911 // Remove the lint error below that `printManager` might be `null`.
1912 assert printManager != null;
1914 // Print the document. The print attributes are `null`.
1915 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1918 case R.id.add_to_homescreen:
1919 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1920 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1921 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1923 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1927 mainWebView.reload();
1931 // Don't consume the event.
1932 return super.onOptionsItemSelected(menuItem);
1936 // removeAllCookies is deprecated, but it is required for API < 21.
1937 @SuppressWarnings("deprecation")
1939 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1940 int menuItemId = menuItem.getItemId();
1942 switch (menuItemId) {
1948 if (mainWebView.canGoBack()) {
1949 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1950 navigatingHistory = true;
1952 // Load the previous website in the history.
1953 mainWebView.goBack();
1958 if (mainWebView.canGoForward()) {
1959 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1960 navigatingHistory = true;
1962 // Load the next website in the history.
1963 mainWebView.goForward();
1968 // Get the `WebBackForwardList`.
1969 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1971 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1972 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
1973 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
1976 case R.id.downloads:
1977 // Launch the system Download Manager.
1978 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1980 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1981 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1983 startActivity(downloadManagerIntent);
1987 // Reapply the domain settings on returning to `MainWebViewActivity`.
1988 reapplyDomainSettingsOnRestart = true;
1989 currentDomainName = "";
1991 // Launch `DomainsActivity`.
1992 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1993 startActivity(domainsIntent);
1997 // Reapply the domain settings on returning to `MainWebViewActivity`.
1998 reapplyDomainSettingsOnRestart = true;
1999 currentDomainName = "";
2001 // Launch `SettingsActivity`.
2002 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2003 startActivity(settingsIntent);
2007 // Launch `GuideActivity`.
2008 Intent guideIntent = new Intent(this, GuideActivity.class);
2009 startActivity(guideIntent);
2013 // Launch `AboutActivity`.
2014 Intent aboutIntent = new Intent(this, AboutActivity.class);
2015 startActivity(aboutIntent);
2018 case R.id.clearAndExit:
2019 // Get a handle for `sharedPreferences`. `this` references the current context.
2020 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2022 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2025 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2026 // The command to remove cookies changed slightly in API 21.
2027 if (Build.VERSION.SDK_INT >= 21) {
2028 cookieManager.removeAllCookies(null);
2030 cookieManager.removeAllCookie();
2033 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2035 // We have to use two commands because `Runtime.exec()` does not like `*`.
2036 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2037 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2038 } catch (IOException e) {
2039 // Do nothing if an error is thrown.
2043 // Clear DOM storage.
2044 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2045 // Ask `WebStorage` to clear the DOM storage.
2046 WebStorage webStorage = WebStorage.getInstance();
2047 webStorage.deleteAllData();
2049 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2051 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2052 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2054 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2055 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2056 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2057 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2058 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2059 } catch (IOException e) {
2060 // Do nothing if an error is thrown.
2065 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
2066 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2067 webViewDatabase.clearFormData();
2069 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2071 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2072 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2073 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2074 } catch (IOException e) {
2075 // Do nothing if an error is thrown.
2080 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2081 // `true` includes disk files.
2082 mainWebView.clearCache(true);
2084 // Manually delete the cache directories.
2086 // Delete the main cache directory.
2087 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2089 // Delete the secondary `Service Worker` cache directory. We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2090 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2091 } catch (IOException e) {
2092 // Do nothing if an error is thrown.
2096 // Clear SSL certificate preferences.
2097 mainWebView.clearSslPreferences();
2099 // Clear the back/forward history.
2100 mainWebView.clearHistory();
2102 // Clear `formattedUrlString`.
2103 formattedUrlString = null;
2105 // Clear `customHeaders`.
2106 customHeaders.clear();
2108 // Detach all views from `mainWebViewRelativeLayout`.
2109 mainWebViewRelativeLayout.removeAllViews();
2111 // Destroy the internal state of `mainWebView`.
2112 mainWebView.destroy();
2114 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2115 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2116 if (clearEverything) {
2118 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2119 } catch (IOException e) {
2120 // Do nothing if an error is thrown.
2124 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2125 if (Build.VERSION.SDK_INT >= 21) {
2126 finishAndRemoveTask();
2131 // Remove the terminated program from RAM. The status code is `0`.
2136 // Close the navigation drawer.
2137 drawerLayout.closeDrawer(GravityCompat.START);
2142 public void onPostCreate(Bundle savedInstanceState) {
2143 super.onPostCreate(savedInstanceState);
2145 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2146 drawerToggle.syncState();
2150 public void onConfigurationChanged(Configuration newConfig) {
2151 super.onConfigurationChanged(newConfig);
2153 // Reload the ad for the free flavor if we are not in full screen mode.
2154 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2156 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2158 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2159 adView = findViewById(R.id.adview);
2162 // `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
2163 // ActivityCompat.invalidateOptionsMenu(this);
2167 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2168 // Store the `HitTestResult`.
2169 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2172 final String imageUrl;
2173 final String linkUrl;
2175 // Get a handle for the `ClipboardManager`.
2176 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2178 // Remove the lint errors below that `clipboardManager` might be `null`.
2179 assert clipboardManager != null;
2181 switch (hitTestResult.getType()) {
2182 // `SRC_ANCHOR_TYPE` is a link.
2183 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2184 // Get the target URL.
2185 linkUrl = hitTestResult.getExtra();
2187 // Set the target URL as the title of the `ContextMenu`.
2188 menu.setHeaderTitle(linkUrl);
2190 // Add a `Load URL` entry.
2191 menu.add(R.string.load_url).setOnMenuItemClickListener(item -> {
2196 // Add a `Copy URL` entry.
2197 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2198 // Save the link URL in a `ClipData`.
2199 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2201 // Set the `ClipData` as the clipboard's primary clip.
2202 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2206 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2207 menu.add(R.string.cancel);
2210 case WebView.HitTestResult.EMAIL_TYPE:
2211 // Get the target URL.
2212 linkUrl = hitTestResult.getExtra();
2214 // Set the target URL as the title of the `ContextMenu`.
2215 menu.setHeaderTitle(linkUrl);
2217 // Add a `Write Email` entry.
2218 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2219 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2220 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2222 // Parse the url and set it as the data for the `Intent`.
2223 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2225 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2226 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2229 startActivity(emailIntent);
2233 // Add a `Copy Email Address` entry.
2234 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2235 // Save the email address in a `ClipData`.
2236 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2238 // Set the `ClipData` as the clipboard's primary clip.
2239 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2243 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2244 menu.add(R.string.cancel);
2247 // `IMAGE_TYPE` is an image.
2248 case WebView.HitTestResult.IMAGE_TYPE:
2249 // Get the image URL.
2250 imageUrl = hitTestResult.getExtra();
2252 // Set the image URL as the title of the `ContextMenu`.
2253 menu.setHeaderTitle(imageUrl);
2255 // Add a `View Image` entry.
2256 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2261 // Add a `Download Image` entry.
2262 menu.add(R.string.download_image).setOnMenuItemClickListener(item -> {
2263 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2264 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2265 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2269 // Add a `Copy URL` entry.
2270 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2271 // Save the image URL in a `ClipData`.
2272 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2274 // Set the `ClipData` as the clipboard's primary clip.
2275 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2279 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2280 menu.add(R.string.cancel);
2284 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2285 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2286 // Get the image URL.
2287 imageUrl = hitTestResult.getExtra();
2289 // Set the image URL as the title of the `ContextMenu`.
2290 menu.setHeaderTitle(imageUrl);
2292 // Add a `View Image` entry.
2293 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2298 // Add a `Download Image` entry.
2299 menu.add(R.string.download_image).setOnMenuItemClickListener(item -> {
2300 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2301 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2302 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2306 // Add a `Copy URL` entry.
2307 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2308 // Save the image URL in a `ClipData`.
2309 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2311 // Set the `ClipData` as the clipboard's primary clip.
2312 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2316 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2317 menu.add(R.string.cancel);
2323 public void onAddDomain(AppCompatDialogFragment dialogFragment) {
2324 // Reapply the domain settings on returning to `MainWebViewActivity`.
2325 reapplyDomainSettingsOnRestart = true;
2326 currentDomainName = "";
2328 // Get the new domain name `String` from `dialogFragment`.
2329 EditText domainNameEditText = dialogFragment.getDialog().findViewById(R.id.domain_name_edittext);
2330 String domainNameString = domainNameEditText.getText().toString();
2332 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
2333 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2334 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2336 // Create the domain and store the database ID in `currentDomainDatabaseId`.
2337 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(domainNameString);
2339 // Create an intent to launch the domains activity.
2340 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2342 // Put extra information instructing the domains activity to directly load the current domain.
2343 domainsIntent.putExtra("LoadDomain", newDomainDatabaseId);
2346 startActivity(domainsIntent);
2350 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
2351 // Get the `EditTexts` from the `dialogFragment`.
2352 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2353 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2355 // Extract the strings from the `EditTexts`.
2356 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2357 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2359 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2360 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2361 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2362 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2364 // Display the new bookmark below the current items in the (0 indexed) list.
2365 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2367 // Create the bookmark.
2368 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2370 // Update `bookmarksCursor` with the current contents of this folder.
2371 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2373 // Update the `ListView`.
2374 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2376 // Scroll to the new bookmark.
2377 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2381 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
2382 // Get handles for the views in `dialogFragment`.
2383 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2384 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2385 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2387 // Get new folder name string.
2388 String folderNameString = createFolderNameEditText.getText().toString();
2390 // Get the new folder icon `Bitmap`.
2391 Bitmap folderIconBitmap;
2392 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2393 // Get the default folder icon and convert it to a `Bitmap`.
2394 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2395 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2396 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2397 } else { // Use the `WebView` favorite icon.
2398 folderIconBitmap = favoriteIconBitmap;
2401 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2402 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2403 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2404 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2406 // Move all the bookmarks down one in the display order.
2407 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2408 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2409 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2412 // Create the folder, which will be placed at the top of the `ListView`.
2413 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2415 // Update `bookmarksCursor` with the current contents of this folder.
2416 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2418 // Update the `ListView`.
2419 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2421 // Scroll to the new folder.
2422 bookmarksListView.setSelection(0);
2426 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2427 // Get the shortcut name.
2428 EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2429 String shortcutNameString = shortcutNameEditText.getText().toString();
2431 // Convert the favorite icon bitmap to an `Icon`. `IconCompat` is required until API >= 26.
2432 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
2434 // Setup the shortcut intent.
2435 Intent shortcutIntent = new Intent();
2436 shortcutIntent.setAction(Intent.ACTION_VIEW);
2437 shortcutIntent.setData(Uri.parse(formattedUrlString));
2439 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
2440 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
2442 // Add the required fields to the shortcut info builder.
2443 shortcutInfoBuilder.setIcon(favoriteIcon);
2444 shortcutInfoBuilder.setIntent(shortcutIntent);
2445 shortcutInfoBuilder.setShortLabel(shortcutNameString);
2447 // Request the pin. `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
2448 ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
2452 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
2453 // Download the image if it has an HTTP or HTTPS URI.
2454 if (imageUrl.startsWith("http")) {
2455 // Get a handle for the system `DOWNLOAD_SERVICE`.
2456 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2458 // Parse `imageUrl`.
2459 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2461 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2462 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2463 if (firstPartyCookiesEnabled) {
2464 // Get the cookies for `imageUrl`.
2465 String cookies = cookieManager.getCookie(imageUrl);
2467 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2468 downloadRequest.addRequestHeader("Cookie", cookies);
2471 // Get the file name from `dialogFragment`.
2472 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
2473 String imageName = downloadImageNameEditText.getText().toString();
2475 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2476 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
2477 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
2478 } else { // Only set the title using `imageName`.
2479 downloadRequest.setTitle(imageName);
2482 // Allow `MediaScanner` to index the download if it is a media file.
2483 downloadRequest.allowScanningByMediaScanner();
2485 // Add the URL as the description for the download.
2486 downloadRequest.setDescription(imageUrl);
2488 // Show the download notification after the download is completed.
2489 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2491 // Remove the lint warning below that `downloadManager` might be `null`.
2492 assert downloadManager != null;
2494 // Initiate the download.
2495 downloadManager.enqueue(downloadRequest);
2496 } else { // The image is not an HTTP or HTTPS URI.
2497 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2502 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
2503 // Download the file if it has an HTTP or HTTPS URI.
2504 if (downloadUrl.startsWith("http")) {
2506 // Get a handle for the system `DOWNLOAD_SERVICE`.
2507 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2509 // Parse `downloadUrl`.
2510 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2512 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2513 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2514 if (firstPartyCookiesEnabled) {
2515 // Get the cookies for `downloadUrl`.
2516 String cookies = cookieManager.getCookie(downloadUrl);
2518 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2519 downloadRequest.addRequestHeader("Cookie", cookies);
2522 // Get the file name from `dialogFragment`.
2523 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
2524 String fileName = downloadFileNameEditText.getText().toString();
2526 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2527 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
2528 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
2529 } else { // Only set the title using `fileName`.
2530 downloadRequest.setTitle(fileName);
2533 // Allow `MediaScanner` to index the download if it is a media file.
2534 downloadRequest.allowScanningByMediaScanner();
2536 // Add the URL as the description for the download.
2537 downloadRequest.setDescription(downloadUrl);
2539 // Show the download notification after the download is completed.
2540 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2542 // Remove the lint warning below that `downloadManager` might be `null`.
2543 assert downloadManager != null;
2545 // Initiate the download.
2546 downloadManager.enqueue(downloadRequest);
2547 } else { // The download is not an HTTP or HTTPS URI.
2548 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2553 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
2554 // Get handles for the views from `dialogFragment`.
2555 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
2556 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
2557 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2559 // Store the bookmark strings.
2560 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2561 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2563 // Update the bookmark.
2564 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2565 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2566 } else { // Update the bookmark using the `WebView` favorite icon.
2567 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
2568 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2569 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2570 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2572 // Update the bookmark and the favorite icon.
2573 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2576 // Update `bookmarksCursor` with the current contents of this folder.
2577 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2579 // Update the `ListView`.
2580 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2584 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
2585 // Get handles for the views from `dialogFragment`.
2586 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
2587 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
2588 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
2589 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
2591 // Get the new folder name.
2592 String newFolderNameString = editFolderNameEditText.getText().toString();
2594 // Check if the favorite icon has changed.
2595 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2596 // Update the name in the database.
2597 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2598 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2599 // Get the new folder icon `Bitmap`.
2600 Bitmap folderIconBitmap;
2601 if (defaultFolderIconRadioButton.isChecked()) {
2602 // Get the default folder icon and convert it to a `Bitmap`.
2603 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2604 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2605 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2606 } else { // Use the `WebView` favorite icon.
2607 folderIconBitmap = favoriteIconBitmap;
2610 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2611 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2612 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2613 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2615 // Update the folder icon in the database.
2616 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
2617 } else { // The folder icon and the name have changed.
2618 // Get the new folder icon `Bitmap`.
2619 Bitmap folderIconBitmap;
2620 if (defaultFolderIconRadioButton.isChecked()) {
2621 // Get the default folder icon and convert it to a `Bitmap`.
2622 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2623 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2624 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2625 } else { // Use the `WebView` favorite icon.
2626 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
2629 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2630 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2631 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2632 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2634 // Update the folder name and icon in the database.
2635 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
2638 // Update `bookmarksCursor` with the current contents of this folder.
2639 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2641 // Update the `ListView`.
2642 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2646 public void onHttpAuthenticationCancel() {
2647 // Cancel the `HttpAuthHandler`.
2648 httpAuthHandler.cancel();
2652 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
2653 // Get handles for the `EditTexts`.
2654 EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
2655 EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
2657 // Proceed with the HTTP authentication.
2658 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
2661 public void viewSslCertificate(View view) {
2662 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2663 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2664 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
2668 public void onSslErrorCancel() {
2669 sslErrorHandler.cancel();
2673 public void onSslErrorProceed() {
2674 sslErrorHandler.proceed();
2678 public void onSslMismatchBack() {
2679 if (mainWebView.canGoBack()) { // There is a back page in the history.
2680 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2681 navigatingHistory = true;
2684 mainWebView.goBack();
2685 } else { // There are no pages to go back to.
2686 // Load a blank page
2692 public void onSslMismatchProceed() {
2693 // Do not check the pinned SSL certificate for this domain again until the domain changes.
2694 ignorePinnedSslCertificate = true;
2698 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2699 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2700 navigatingHistory = true;
2702 // Load the history entry.
2703 mainWebView.goBackOrForward(moveBackOrForwardSteps);
2707 public void onClearHistory() {
2708 // Clear the history.
2709 mainWebView.clearHistory();
2712 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2714 public void onBackPressed() {
2715 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2716 // Close the navigation drawer.
2717 drawerLayout.closeDrawer(GravityCompat.START);
2718 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2719 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
2720 // close the bookmarks drawer.
2721 drawerLayout.closeDrawer(GravityCompat.END);
2722 } else { // A subfolder is displayed.
2723 // Place the former parent folder in `currentFolder`.
2724 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
2726 // Load the new folder.
2727 loadBookmarksFolder();
2730 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
2731 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2732 navigatingHistory = true;
2735 mainWebView.goBack();
2736 } else { // There isn't anything to do in Privacy Browser.
2737 // Pass `onBackPressed()` to the system.
2738 super.onBackPressed();
2742 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2743 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2744 String unformattedUrlString = urlTextBox.getText().toString().trim();
2746 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2747 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2748 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
2749 if (!unformattedUrlString.startsWith("http")) {
2750 unformattedUrlString = "http://" + unformattedUrlString;
2753 // Initialize `unformattedUrl`.
2754 URL unformattedUrl = null;
2756 // 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.
2758 unformattedUrl = new URL(unformattedUrlString);
2759 } catch (MalformedURLException e) {
2760 e.printStackTrace();
2763 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2764 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2765 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2766 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2767 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2768 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2771 Uri.Builder formattedUri = new Uri.Builder();
2772 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2774 // Decode `formattedUri` as a `String` in `UTF-8`.
2775 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
2777 // Sanitize the search input and convert it to a search.
2778 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2780 // Add the base search URL.
2781 formattedUrlString = searchURL + encodedUrlString;
2784 loadUrl(formattedUrlString);
2788 private void loadUrl(String url) {
2789 // Apply any custom domain settings.
2790 applyDomainSettings(url);
2793 mainWebView.loadUrl(url, customHeaders);
2795 // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
2796 urlIsLoading = true;
2799 public void findPreviousOnPage(View view) {
2800 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2801 mainWebView.findNext(false);
2804 public void findNextOnPage(View view) {
2805 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2806 mainWebView.findNext(true);
2809 public void closeFindOnPage(View view) {
2810 // Delete the contents of `find_on_page_edittext`.
2811 findOnPageEditText.setText(null);
2813 // Clear the highlighted phrases.
2814 mainWebView.clearMatches();
2816 // Hide the Find on Page `RelativeLayout`.
2817 findOnPageLinearLayout.setVisibility(View.GONE);
2819 // Show the URL app bar.
2820 supportAppBar.setVisibility(View.VISIBLE);
2822 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2823 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2826 private void applyAppSettings() {
2827 // Get a handle for `sharedPreferences`. `this` references the current context.
2828 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2830 // Store the values from `sharedPreferences` in variables.
2831 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
2832 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2833 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2834 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
2835 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
2836 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
2837 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
2838 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2839 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2840 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2841 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
2842 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2843 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2844 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
2845 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
2847 // Set the homepage, search, and proxy options.
2848 if (proxyThroughOrbot) { // Set the Tor options.
2849 // Set `torHomepageString` as `homepage`.
2850 homepage = torHomepageString;
2852 // If formattedUrlString is null assign the homepage to it.
2853 if (formattedUrlString == null) {
2854 formattedUrlString = homepage;
2857 // Set the search URL.
2858 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
2859 searchURL = torSearchCustomURLString;
2860 } else { // Use the string from the pre-built list.
2861 searchURL = torSearchString;
2864 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
2865 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2867 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
2869 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
2871 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
2874 // Display a message to the user if we are waiting on Orbot.
2875 if (!orbotStatus.equals("ON")) {
2876 // Set `waitingForOrbot`.
2877 waitingForOrbot = true;
2879 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
2880 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2882 } else { // Set the non-Tor options.
2883 // Set `homepageString` as `homepage`.
2884 homepage = homepageString;
2886 // If formattedUrlString is null assign the homepage to it.
2887 if (formattedUrlString == null) {
2888 formattedUrlString = homepage;
2891 // Set the search URL.
2892 if (searchString.equals("Custom URL")) { // Get the custom URL string.
2893 searchURL = searchCustomURLString;
2894 } else { // Use the string from the pre-built list.
2895 searchURL = searchString;
2898 // Reset the proxy to default. The host is `""` and the port is `"0"`.
2899 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2901 // Set the default `appBar` background. `this` refers to the context.
2903 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
2905 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
2908 // Reset `waitingForOrbot.
2909 waitingForOrbot = false;
2912 // Set swipe to refresh.
2913 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2915 // Set Do Not Track status.
2916 if (doNotTrackEnabled) {
2917 customHeaders.put("DNT", "1");
2919 customHeaders.remove("DNT");
2922 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2923 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2924 if (hideSystemBarsOnFullscreen) { // Hide everything.
2925 // Remove the translucent navigation setting if it is currently flagged.
2926 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2928 // Remove the translucent status bar overlay.
2929 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2931 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2932 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2934 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2935 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2936 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2938 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2939 } else { // Hide everything except the status and navigation bars.
2940 // Add the translucent status flag if it is unset.
2941 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2943 if (translucentNavigationBarOnFullscreen) {
2944 // Set the navigation bar to be translucent.
2945 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2947 // Set the navigation bar to be black.
2948 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2951 } else { // Switch to normal viewing mode.
2952 // Reset `inFullScreenBrowsingMode` to `false`.
2953 inFullScreenBrowsingMode = false;
2955 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
2956 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
2960 // Show the `BannerAd` in the free flavor.
2961 if (BuildConfig.FLAVOR.contentEquals("free")) {
2962 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
2963 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2965 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2966 adView = findViewById(R.id.adview);
2969 // Remove the translucent navigation bar flag if it is set.
2970 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2972 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2973 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2975 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
2976 rootCoordinatorLayout.setSystemUiVisibility(0);
2978 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
2979 rootCoordinatorLayout.setFitsSystemWindows(true);
2983 // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2984 @SuppressWarnings("deprecation")
2985 private void applyDomainSettings(String url) {
2986 // Reset `navigatingHistory`.
2987 navigatingHistory = false;
2989 // Parse the URL into a URI.
2990 Uri uri = Uri.parse(url);
2992 // Extract the domain from `uri`.
2993 String hostName = uri.getHost();
2995 // Initialize `loadingNewDomainName`.
2996 boolean loadingNewDomainName;
2998 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
2999 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
3000 //noinspection SimplifiableIfStatement
3001 if ((hostName == null) || (currentDomainName == null)) {
3002 loadingNewDomainName = true;
3003 } else { // Determine if `hostName` equals `currentDomainName`.
3004 loadingNewDomainName = !hostName.equals(currentDomainName);
3007 // 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.
3008 if (loadingNewDomainName) {
3009 // Set the new `hostname` as the `currentDomainName`.
3010 currentDomainName = hostName;
3012 // Reset `ignorePinnedSslCertificate`.
3013 ignorePinnedSslCertificate = false;
3015 // Reset `favoriteIconBitmap` and display it in the `appbar`.
3016 favoriteIconBitmap = favoriteIconDefaultBitmap;
3017 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
3019 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
3020 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3021 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3023 // Get a full cursor from `domainsDatabaseHelper`.
3024 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3026 // Initialize `domainSettingsSet`.
3027 Set<String> domainSettingsSet = new HashSet<>();
3029 // Get the domain name column index.
3030 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3032 // Populate `domainSettingsSet`.
3033 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3034 // Move `domainsCursor` to the current row.
3035 domainNameCursor.moveToPosition(i);
3037 // Store the domain name in `domainSettingsSet`.
3038 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3041 // Close `domainNameCursor.
3042 domainNameCursor.close();
3044 // Initialize variables to track if domain settings will be applied and, if so, under which name.
3045 domainSettingsApplied = false;
3046 String domainNameInDatabase = null;
3048 // Check the hostname.
3049 if (domainSettingsSet.contains(hostName)) {
3050 domainSettingsApplied = true;
3051 domainNameInDatabase = hostName;
3054 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
3055 if (hostName != null) {
3056 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
3057 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
3058 domainSettingsApplied = true;
3059 domainNameInDatabase = "*." + hostName;
3062 // Strip out the lowest subdomain of `host`.
3063 hostName = hostName.substring(hostName.indexOf(".") + 1);
3067 // Get a handle for the shared preference. `this` references the current context.
3068 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3070 // Store the general preference information.
3071 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
3072 String defaultUserAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
3073 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
3074 nightMode = sharedPreferences.getBoolean("night_mode", false);
3076 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
3077 // Get a cursor for the current host and move it to the first position.
3078 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3079 currentHostDomainSettingsCursor.moveToFirst();
3081 // Get the settings from the cursor.
3082 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3083 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3084 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3085 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3086 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3087 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3088 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3089 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3090 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3091 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3092 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3093 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3094 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3095 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3096 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3097 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3098 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3100 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3101 switch (nightModeInt) {
3102 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3106 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3111 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3113 javaScriptEnabled = true;
3116 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3117 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3118 pinnedDomainSslStartDate = null;
3120 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3123 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3124 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3125 pinnedDomainSslEndDate = null;
3127 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3130 // Close `currentHostDomainSettingsCursor`.
3131 currentHostDomainSettingsCursor.close();
3133 // Apply the domain settings.
3134 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3135 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3136 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3137 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3139 // Apply the font size.
3140 if (fontSize == 0) { // Apply the default font size.
3141 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3142 } else { // Apply the specified font size.
3143 mainWebView.getSettings().setTextZoom(fontSize);
3146 // Set third-party cookies status if API >= 21.
3147 if (Build.VERSION.SDK_INT >= 21) {
3148 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3151 // Only set the user agent if the webpage is not currently loading. Otherwise, changing the user agent on redirects can cause the original website to reload. <https://redmine.stoutner.com/issues/160>
3152 if (!urlIsLoading) {
3153 switch (userAgentString) {
3154 case "System default user agent":
3155 // Set the user agent according to the system default.
3156 switch (defaultUserAgentString) {
3157 case "WebView default user agent":
3158 // Set the user agent to `""`, which uses the default value.
3159 mainWebView.getSettings().setUserAgentString("");
3162 case "Custom user agent":
3163 // Set the custom user agent.
3164 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3168 // Use the selected user agent.
3169 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
3173 case "WebView default user agent":
3174 // Set the user agent to `""`, which uses the default value.
3175 mainWebView.getSettings().setUserAgentString("");
3179 // Use the selected user agent.
3180 mainWebView.getSettings().setUserAgentString(userAgentString);
3184 // 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.
3186 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3188 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3190 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
3191 // Store the values from `sharedPreferences` in variables.
3192 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
3193 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
3194 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
3195 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
3196 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
3198 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3200 javaScriptEnabled = true;
3203 // Apply the default settings.
3204 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3205 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3206 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3207 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3208 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3210 // Reset the pinned SSL certificate information.
3211 domainSettingsDatabaseId = -1;
3212 pinnedDomainSslCertificate = false;
3213 pinnedDomainSslIssuedToCNameString = "";
3214 pinnedDomainSslIssuedToONameString = "";
3215 pinnedDomainSslIssuedToUNameString = "";
3216 pinnedDomainSslIssuedByCNameString = "";
3217 pinnedDomainSslIssuedByONameString = "";
3218 pinnedDomainSslIssuedByUNameString = "";
3219 pinnedDomainSslStartDate = null;
3220 pinnedDomainSslEndDate = null;
3222 // Set third-party cookies status if API >= 21.
3223 if (Build.VERSION.SDK_INT >= 21) {
3224 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3227 // Only set the user agent if the webpage is not currently loading. Otherwise, changing the user agent on redirects can cause the original website to reload. <https://redmine.stoutner.com/issues/160>
3228 if (!urlIsLoading) {
3229 switch (defaultUserAgentString) {
3230 case "WebView default user agent":
3231 // Set the user agent to `""`, which uses the default value.
3232 mainWebView.getSettings().setUserAgentString("");
3235 case "Custom user agent":
3236 // Set the custom user agent.
3237 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3241 // Use the selected user agent.
3242 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
3246 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3247 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
3250 // Close `domainsDatabaseHelper`.
3251 domainsDatabaseHelper.close();
3253 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
3254 onTheFlyDisplayImagesSet = false;
3255 setDisplayWebpageImages();
3257 // Update the privacy icons, but only if `mainMenu` has already been populated.
3258 if (mainMenu != null) {
3259 updatePrivacyIcons(true);
3264 private void setDisplayWebpageImages() {
3265 if (!onTheFlyDisplayImagesSet) {
3266 if (domainSettingsApplied) { // Custom domain settings are applied.
3267 switch (displayWebpageImagesInt) {
3268 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
3269 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3272 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
3273 mainWebView.getSettings().setLoadsImagesAutomatically(true);
3276 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
3277 mainWebView.getSettings().setLoadsImagesAutomatically(false);
3280 } else { // Default settings are applied.
3281 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3286 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
3287 // Get handles for the icons.
3288 MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
3289 MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
3290 MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
3291 MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
3293 // Update `privacyIcon`.
3294 if (javaScriptEnabled) { // JavaScript is enabled.
3295 privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
3296 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
3297 privacyIconMenuItem.setIcon(R.drawable.warning);
3298 } else { // All the dangerous features are disabled.
3299 privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
3302 // Update `firstPartyCookiesIcon`.
3303 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
3304 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
3305 } else { // First-party cookies are disabled.
3307 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3309 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_light);
3313 // Update `domStorageIcon`.
3314 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
3315 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
3316 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
3318 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3320 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3322 } else { // JavaScript is disabled, so DOM storage is ghosted.
3324 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3326 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3330 // Update `formDataIcon`.
3331 if (saveFormDataEnabled) { // Form data is enabled.
3332 formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
3333 } else { // Form data is disabled.
3335 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_dark);
3337 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_light);
3341 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
3342 if (runInvalidateOptionsMenu) {
3343 ActivityCompat.invalidateOptionsMenu(this);
3347 private void highlightUrlText() {
3348 String urlString = urlTextBox.getText().toString();
3350 if (urlString.startsWith("http://")) { // Highlight connections that are not encrypted.
3351 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3352 } else if (urlString.startsWith("https://")) { // Highlight connections that are encrypted.
3353 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3356 // Get the index of the `/` immediately after the domain name.
3357 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
3359 // De-emphasize the text after the domain name.
3360 if (endOfDomainName > 0) {
3361 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3365 private void loadBookmarksFolder() {
3366 // Update `bookmarksCursor` with the contents of the bookmarks database for the current folder.
3367 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3369 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
3370 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
3372 public View newView(Context context, Cursor cursor, ViewGroup parent) {
3373 // Inflate the individual item layout. `false` does not attach it to the root.
3374 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
3378 public void bindView(View view, Context context, Cursor cursor) {
3379 // Get handles for the views.
3380 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
3381 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
3383 // Get the favorite icon byte array from the `Cursor`.
3384 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
3386 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
3387 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
3389 // Display the bitmap in `bookmarkFavoriteIcon`.
3390 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
3392 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
3393 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3394 bookmarkNameTextView.setText(bookmarkNameString);
3396 // Make the font bold for folders.
3397 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
3398 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
3399 } else { // Reset the font to default for normal bookmarks.
3400 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
3405 // Populate the `ListView` with the adapter.
3406 bookmarksListView.setAdapter(bookmarksCursorAdapter);
3408 // Set the bookmarks drawer title.
3409 if (currentBookmarksFolder.isEmpty()) {
3410 bookmarksTitleTextView.setText(R.string.bookmarks);
3412 bookmarksTitleTextView.setText(currentBookmarksFolder);