- @Override
- public void afterTextChanged(Editable s) {
- // Search for the text in `mainWebView`.
- currentWebView.findAllAsync(findOnPageEditText.getText().toString());
- }
- });
-
- // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
- findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
- if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
- // Hide the soft keyboard.
- inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
-
- // Consume the event.
- return true;
- } else { // A different key was pressed.
- // Do not consume the event.
- return false;
- }
- });
-
- // Implement swipe to refresh.
- swipeRefreshLayout.setOnRefreshListener(() -> currentWebView.reload());
-
- // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
- swipeRefreshLayout.setProgressViewOffset(false, swipeRefreshLayout.getProgressViewStartOffset() - 10, swipeRefreshLayout.getProgressViewEndOffset());
-
- // Set the swipe to refresh color according to the theme.
- if (darkTheme) {
- swipeRefreshLayout.setColorSchemeResources(R.color.blue_800);
- swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_850);
- } else {
- swipeRefreshLayout.setColorSchemeResources(R.color.blue_500);
- }
-
- // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
- drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
- drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
-
- // Initialize the bookmarks database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
- bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
-
- // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
- currentBookmarksFolder = "";
-
- // Load the home folder, which is `""` in the database.
- loadBookmarksFolder();
-
- bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
- // Convert the id from long to int to match the format of the bookmarks database.
- int databaseID = (int) id;
-
- // Get the bookmark cursor for this ID and move it to the first row.
- Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseID);
- bookmarkCursor.moveToFirst();
-
- // Act upon the bookmark according to the type.
- if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
- // Store the new folder name in `currentBookmarksFolder`.
- currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
-
- // Load the new folder.
- loadBookmarksFolder();
- } else { // The selected bookmark is not a folder.
- // Load the bookmark URL.
- loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
-
- // Close the bookmarks drawer.
- drawerLayout.closeDrawer(GravityCompat.END);
- }
-
- // Close the `Cursor`.
- bookmarkCursor.close();
- });
-
- bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
- // Convert the database ID from `long` to `int`.
- int databaseId = (int) id;
-
- // Find out if the selected bookmark is a folder.
- boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
-
- if (isFolder) {
- // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
- oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
-
- // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
- DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
- editBookmarkFolderDialog.show(fragmentManager, resources.getString(R.string.edit_folder));
- } else {
- // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
- DialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
- editBookmarkDialog.show(fragmentManager, resources.getString(R.string.edit_bookmark));
- }
-
- // Consume the event.
- return true;
- });
-
- // Get the status bar pixel size.
- int statusBarResourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
- int statusBarPixelSize = resources.getDimensionPixelSize(statusBarResourceId);
-
- // Get the resource density.
- float screenDensity = resources.getDisplayMetrics().density;
-
- // Calculate the drawer header padding. This is used to move the text in the drawer headers below any cutouts.
- drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
- drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
- drawerHeaderPaddingBottom = (int) (8 * screenDensity);
-
- // The drawer listener is used to update the navigation menu.`
- drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
- @Override
- public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
- }
-
- @Override
- public void onDrawerOpened(@NonNull View drawerView) {
- }
-
- @Override
- public void onDrawerClosed(@NonNull View drawerView) {
- }
-
- @Override
- public void onDrawerStateChanged(int newState) {
- if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
- // Get handles for the drawer headers.
- TextView navigationHeaderTextView = findViewById(R.id.navigationText);
- TextView bookmarksHeaderTextView = findViewById(R.id.bookmarks_title_textview);
-
- // Apply the navigation header paddings if the view is not null (sometimes it is null if another activity has already started). This moves the text in the header below any cutouts.
- if (navigationHeaderTextView != null) {
- navigationHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
- }
-
- // Apply the bookmarks header paddings if the view is not null (sometimes it is null if another activity has already started). This moves the text in the header below any cutouts.
- if (bookmarksHeaderTextView != null) {
- bookmarksHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
- }
-
- // Update the navigation menu items.
- navigationCloseTabMenuItem.setEnabled(tabLayout.getTabCount() > 1);
- navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
- navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
- navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
- navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
-
- // Hide the keyboard (if displayed).
- inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
-
- // Clear the focus from from the URL text box and the WebView. This removes any text selection markers and context menus, which otherwise draw above the open drawers.
- urlEditText.clearFocus();
- currentWebView.clearFocus();
- }
- }
- });
-
- // Create the hamburger icon at the start of the AppBar.
- actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
-
- // Initialize cookieManager.
- cookieManager = CookieManager.getInstance();
-
- // 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).
- customHeaders.put("X-Requested-With", "");
-
- // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
- PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
-
- // Get a handle for the `Runtime`.
- privacyBrowserRuntime = Runtime.getRuntime();
-
- // Store the application's private data directory.
- 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`.
-
- // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
- inFullScreenBrowsingMode = false;
-
- // Initialize the privacy settings variables.
- javaScriptEnabled = false;
- firstPartyCookiesEnabled = false;
- thirdPartyCookiesEnabled = false;
- domStorageEnabled = false;
- saveFormDataEnabled = false; // Form data can be removed once the minimum API >= 26.
- nightMode = false;
-
- // Store the default user agent.
- // TODO webViewDefaultUserAgent = mainWebView.getSettings().getUserAgentString();
-
- // Initialize the WebView title.
- webViewTitle = getString(R.string.no_title);
-
- // Initialize the favorite icon bitmap. `ContextCompat` must be used until API >= 21.
- Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
- BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
- assert favoriteIconBitmapDrawable != null;
- favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
-
- // If the favorite icon is null, load the default.
- if (favoriteIconBitmap == null) {
- favoriteIconBitmap = favoriteIconDefaultBitmap;
- }
-
- // Initialize the user agent array adapter and string array.
- userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
- userAgentDataArray = resources.getStringArray(R.array.user_agent_data);
-
- // Get the intent that started the app.
- Intent launchingIntent = getIntent();
-
- // Get the information from the intent.
- String launchingIntentAction = launchingIntent.getAction();
- Uri launchingIntentUriData = launchingIntent.getData();
-
- // If the intent action is a web search, perform the search.
- if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {
- // Create an encoded URL string.
- String encodedUrlString;
-
- // Sanitize the search input and convert it to a search.
- try {
- encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
- } catch (UnsupportedEncodingException exception) {
- encodedUrlString = "";
- }
-
- // Add the base search URL.
- formattedUrlString = searchURL + encodedUrlString;
- } else if (launchingIntentUriData != null){ // Check to see if the intent contains a new URL.
- // Set the formatted URL string.
- formattedUrlString = launchingIntentUriData.toString();
- }
- }
-
- @Override
- protected void onNewIntent(Intent intent) {
- // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
- setIntent(intent);
-
- // Get the information from the intent.
- String intentAction = intent.getAction();
- Uri intentUriData = intent.getData();
-
- // If the intent action is a web search, perform the search.
- if ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH)) {
- // Create an encoded URL string.
- String encodedUrlString;
-
- // Sanitize the search input and convert it to a search.
- try {
- encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
- } catch (UnsupportedEncodingException exception) {
- encodedUrlString = "";
- }
-
- // Add the base search URL.
- formattedUrlString = searchURL + encodedUrlString;
- } else if (intentUriData != null){ // Check to see if the intent contains a new URL.
- // Set the formatted URL string.
- formattedUrlString = intentUriData.toString();
- }
-
- // Load the URL.
- loadUrl(formattedUrlString);
-
- // Get a handle for the drawer layout.
- DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
-
- // Close the navigation drawer if it is open.
- if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
- drawerLayout.closeDrawer(GravityCompat.START);
- }
-
- // Close the bookmarks drawer if it is open.
- if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
- drawerLayout.closeDrawer(GravityCompat.END);