From 9df712df3780161d77d10c6f3a2444bf8f218c99 Mon Sep 17 00:00:00 2001 From: Soren Stoutner Date: Fri, 17 Apr 2020 13:41:57 -0700 Subject: [PATCH] Fix a crash when uploading files to some sites. https://redmine.stoutner.com/issues/556 --- app/build.gradle | 4 +- .../activities/BookmarksActivity.java | 73 +++- .../BookmarksDatabaseViewActivity.java | 102 +++--- .../activities/DomainsActivity.java | 7 +- .../activities/MainWebViewActivity.java | 26 +- .../dialogs/AboutViewSourceDialog.kt | 3 +- .../dialogs/AddDomainDialog.java | 213 ------------ .../privacybrowser/dialogs/AddDomainDialog.kt | 203 +++++++++++ .../dialogs/CreateBookmarkDialog.java | 222 ------------ .../dialogs/CreateBookmarkDialog.kt | 200 +++++++++++ .../dialogs/CreateBookmarkFolderDialog.java | 230 ------------- .../dialogs/CreateBookmarkFolderDialog.kt | 203 +++++++++++ .../CreateHomeScreenShortcutDialog.java | 318 ------------------ .../dialogs/CreateHomeScreenShortcutDialog.kt | 276 +++++++++++++++ .../privacybrowser/dialogs/SaveDialog.java | 74 ++-- .../res/drawable/dom_storage_cleared_dark.xml | 4 +- .../drawable/dom_storage_cleared_light.xml | 4 +- .../drawable/dom_storage_disabled_dark.xml | 4 +- .../drawable/dom_storage_disabled_light.xml | 4 +- .../main/res/drawable/dom_storage_enabled.xml | 4 +- .../res/drawable/dom_storage_ghosted_dark.xml | 4 +- .../drawable/dom_storage_ghosted_light.xml | 4 +- .../main/res/drawable/dom_storage_warning.xml | 4 +- .../{domains.xml => domains_dark.xml} | 6 +- app/src/main/res/drawable/domains_light.xml | 18 + .../res/layout/domain_settings_fragment.xml | 2 +- .../main/res/menu/webview_navigation_menu.xml | 2 +- build.gradle | 3 +- 28 files changed, 1097 insertions(+), 1120 deletions(-) delete mode 100644 app/src/main/java/com/stoutner/privacybrowser/dialogs/AddDomainDialog.java create mode 100644 app/src/main/java/com/stoutner/privacybrowser/dialogs/AddDomainDialog.kt delete mode 100644 app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateBookmarkDialog.java create mode 100644 app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateBookmarkDialog.kt delete mode 100644 app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateBookmarkFolderDialog.java create mode 100644 app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateBookmarkFolderDialog.kt delete mode 100644 app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateHomeScreenShortcutDialog.java create mode 100644 app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateHomeScreenShortcutDialog.kt rename app/src/main/res/drawable/{domains.xml => domains_dark.xml} (74%) create mode 100644 app/src/main/res/drawable/domains_light.xml diff --git a/app/build.gradle b/app/build.gradle index 785bb416..85f5cacf 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -31,7 +31,7 @@ android { versionCode 49 versionName "3.4.1" - // The `multiDexEnabled` entry could possibly be removed once the `minSdkVersion` is >= 21. + // `multiDexEnabled` can possibly be removed once the `minSdkVersion` is >= 21. multiDexEnabled true } @@ -90,7 +90,7 @@ dependencies { implementation 'androidx.webkit:webkit:1.2.0' // Include the Kotlin standard libraries - implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.3.61" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.3.72" // Include the Google material library. implementation 'com.google.android.material:material:1.1.0' diff --git a/app/src/main/java/com/stoutner/privacybrowser/activities/BookmarksActivity.java b/app/src/main/java/com/stoutner/privacybrowser/activities/BookmarksActivity.java index 12a96aee..67cff69d 100644 --- a/app/src/main/java/com/stoutner/privacybrowser/activities/BookmarksActivity.java +++ b/app/src/main/java/com/stoutner/privacybrowser/activities/BookmarksActivity.java @@ -1,5 +1,5 @@ /* - * Copyright © 2016-2019 Soren Stoutner . + * Copyright © 2016-2020 Soren Stoutner . * * This file is part of Privacy Browser . * @@ -21,6 +21,7 @@ package com.stoutner.privacybrowser.activities; import android.annotation.SuppressLint; import android.app.Activity; +import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; @@ -47,6 +48,7 @@ import android.widget.ListView; import android.widget.RadioButton; import android.widget.TextView; +import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; // The AndroidX toolbar must be used until the minimum API is >= 21. @@ -162,6 +164,9 @@ public class BookmarksActivity extends AppCompatActivity implements CreateBookma // Get the favorite icon byte array. favoriteIconByteArray = launchingIntent.getByteArrayExtra("favorite_icon_byte_array"); + // Remove the incorrect lint warning that the favorite icon byte array might be null. + assert favoriteIconByteArray != null; + // Convert the favorite icon byte array to a bitmap. Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length); @@ -468,7 +473,7 @@ public class BookmarksActivity extends AppCompatActivity implements CreateBookma // Update the list view. bookmarksCursorAdapter.changeCursor(bookmarksCursor); - // Show a Snackbar with the number of deleted bookmarks. + // Create a Snackbar with the number of deleted bookmarks. bookmarksDeletedSnackbar = Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), getString(R.string.bookmarks_deleted) + " " + selectedBookmarksIdsLongArray.length, Snackbar.LENGTH_LONG) .setAction(R.string.undo, view -> { @@ -572,6 +577,10 @@ public class BookmarksActivity extends AppCompatActivity implements CreateBookma // Set the create new bookmark FAB to display the `AlertDialog`. createBookmarkFab.setOnClickListener(view -> { + // Remove the incorrect lint warning below. + assert currentUrl != null; + assert currentTitle != null; + // Instantiate the create bookmark dialog. DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentUrl, currentTitle, favoriteIconBitmap); @@ -667,9 +676,15 @@ public class BookmarksActivity extends AppCompatActivity implements CreateBookma @Override public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) { + // Get the alert dialog from the fragment. + Dialog dialog = dialogFragment.getDialog(); + + // Remove the incorrect lint warning below that the dialog might be null. + assert dialog != null; + // Get the views from the dialog fragment. - EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext); - EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext); + EditText createBookmarkNameEditText = dialog.findViewById(R.id.create_bookmark_name_edittext); + EditText createBookmarkUrlEditText = dialog.findViewById(R.id.create_bookmark_url_edittext); // Extract the strings from the edit texts. String bookmarkNameString = createBookmarkNameEditText.getText().toString(); @@ -701,11 +716,17 @@ public class BookmarksActivity extends AppCompatActivity implements CreateBookma } @Override - public void onCreateBookmarkFolder(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) { + public void onCreateBookmarkFolder(DialogFragment dialogFragment, @NonNull Bitmap favoriteIconBitmap) { + // Get the dialog from the dialog fragment. + Dialog dialog = dialogFragment.getDialog(); + + // Remove the incorrect lint warning below that the dialog might be null. + assert dialog != null; + // Get handles for the views in the dialog fragment. - EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext); - RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton); - ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon); + EditText createFolderNameEditText = dialog.findViewById(R.id.create_folder_name_edittext); + RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.create_folder_default_icon_radiobutton); + ImageView folderIconImageView = dialog.findViewById(R.id.create_folder_default_icon); // Get new folder name string. String folderNameString = createFolderNameEditText.getText().toString(); @@ -758,10 +779,16 @@ public class BookmarksActivity extends AppCompatActivity implements CreateBookma @Override public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) { + // Get the dialog from the dialog fragment. + Dialog dialog = dialogFragment.getDialog(); + + // Remove the incorrect lint warning below that the dialog might be null. + assert dialog != null; + // Get handles for the views from `dialogFragment`. - EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext); - EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext); - RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton); + EditText editBookmarkNameEditText = dialog.findViewById(R.id.edit_bookmark_name_edittext); + EditText editBookmarkUrlEditText = dialog.findViewById(R.id.edit_bookmark_url_edittext); + RadioButton currentBookmarkIconRadioButton = dialog.findViewById(R.id.edit_bookmark_current_icon_radiobutton); // Store the bookmark strings. String bookmarkNameString = editBookmarkNameEditText.getText().toString(); @@ -796,11 +823,17 @@ public class BookmarksActivity extends AppCompatActivity implements CreateBookma @Override public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap) { + // Get the dialog from the dialog fragment. + Dialog dialog = dialogFragment.getDialog(); + + // Remove the incorrect lint warning below that the dialog might be null. + assert dialog != null; + // Get handles for the views from `dialogFragment`. - RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton); - RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton); - ImageView defaultFolderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview); - EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext); + RadioButton currentFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_current_icon_radiobutton); + RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_default_icon_radiobutton); + ImageView defaultFolderIconImageView = dialog.findViewById(R.id.edit_folder_default_icon_imageview); + EditText editFolderNameEditText = dialog.findViewById(R.id.edit_folder_name_edittext); // Get the new folder name. String newFolderNameString = editFolderNameEditText.getText().toString(); @@ -883,8 +916,14 @@ public class BookmarksActivity extends AppCompatActivity implements CreateBookma @Override public void onMoveToFolder(DialogFragment dialogFragment) { - // Get a handle for the `ListView` from `dialogFragment`. - ListView folderListView = dialogFragment.getDialog().findViewById(R.id.move_to_folder_listview); + // Get the dialog from the dialog fragment. + Dialog dialog = dialogFragment.getDialog(); + + // Remove the incorrect lint warning below that the dialog might be null. + assert dialog != null; + + // Get a handle for the list view from the dialog. + ListView folderListView = dialog.findViewById(R.id.move_to_folder_listview); // Store a long array of the selected folders. long[] newFolderLongArray = folderListView.getCheckedItemIds(); diff --git a/app/src/main/java/com/stoutner/privacybrowser/activities/BookmarksDatabaseViewActivity.java b/app/src/main/java/com/stoutner/privacybrowser/activities/BookmarksDatabaseViewActivity.java index 3cdc6792..61b5e845 100644 --- a/app/src/main/java/com/stoutner/privacybrowser/activities/BookmarksDatabaseViewActivity.java +++ b/app/src/main/java/com/stoutner/privacybrowser/activities/BookmarksDatabaseViewActivity.java @@ -1,5 +1,5 @@ /* - * Copyright © 2016-2019 Soren Stoutner . + * Copyright © 2016-2020 Soren Stoutner . * * This file is part of Privacy Browser . * @@ -20,6 +20,7 @@ package com.stoutner.privacybrowser.activities; import android.annotation.SuppressLint; +import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; @@ -519,7 +520,7 @@ public class BookmarksDatabaseViewActivity extends AppCompatActivity implements // Update the list view. bookmarksCursorAdapter.changeCursor(bookmarksCursor); - // Show a Snackbar with the number of deleted bookmarks. + // Create a Snackbar with the number of deleted bookmarks. bookmarksDeletedSnackbar = Snackbar.make(findViewById(R.id.bookmarks_databaseview_coordinatorlayout), getString(R.string.bookmarks_deleted) + " " + selectedBookmarksIdsLongArray.length, Snackbar.LENGTH_LONG) .setAction(R.string.undo, view -> { @@ -529,28 +530,23 @@ public class BookmarksDatabaseViewActivity extends AppCompatActivity implements @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`. @Override public void onDismissed(Snackbar snackbar, int event) { - switch (event) { - // The user pushed the `Undo` button. - case Snackbar.Callback.DISMISS_EVENT_ACTION: - // Update the bookmarks list view with the current contents of the bookmarks database, including the "deleted bookmarks. - updateBookmarksListView(); - - // Re-select the previously selected bookmarks. - for (int i = 0; i < selectedBookmarksPositionsSparseBooleanArray.size(); i++) { - bookmarksListView.setItemChecked(selectedBookmarksPositionsSparseBooleanArray.keyAt(i), true); - } - break; - - // The Snackbar was dismissed without the `Undo` button being pushed. - default: - // Delete each selected bookmark. - for (long databaseIdLong : selectedBookmarksIdsLongArray) { - // Convert `databaseIdLong` to an int. - int databaseIdInt = (int) databaseIdLong; - - // Delete the selected bookmark. - bookmarksDatabaseHelper.deleteBookmark(databaseIdInt); - } + if (event == Snackbar.Callback.DISMISS_EVENT_ACTION) { // The user pushed the undo button. + // Update the bookmarks list view with the current contents of the bookmarks database, including the "deleted bookmarks. + updateBookmarksListView(); + + // Re-select the previously selected bookmarks. + for (int i = 0; i < selectedBookmarksPositionsSparseBooleanArray.size(); i++) { + bookmarksListView.setItemChecked(selectedBookmarksPositionsSparseBooleanArray.keyAt(i), true); + } + } else { // The Snackbar was dismissed without the undo button being pushed. + // Delete each selected bookmark. + for (long databaseIdLong : selectedBookmarksIdsLongArray) { + // Convert `databaseIdLong` to an int. + int databaseIdInt = (int) databaseIdLong; + + // Delete the selected bookmark. + bookmarksDatabaseHelper.deleteBookmark(databaseIdInt); + } } // Reset the deleting bookmarks flag. @@ -657,20 +653,12 @@ public class BookmarksDatabaseViewActivity extends AppCompatActivity implements bookmarksDeletedSnackbar.dismiss(); } else { // Go home immediately. // Update the current folder in the bookmarks activity. - switch (currentFolderDatabaseId) { - case ALL_FOLDERS_DATABASE_ID: - // Load the home folder. - BookmarksActivity.currentFolder = ""; - break; - - case HOME_FOLDER_DATABASE_ID: - // Load the home folder. - BookmarksActivity.currentFolder = ""; - break; - - default: - // Load the current folder. - BookmarksActivity.currentFolder = currentFolderName; + if ((currentFolderDatabaseId == ALL_FOLDERS_DATABASE_ID) || (currentFolderDatabaseId == HOME_FOLDER_DATABASE_ID)) { // All folders or the the home folder are currently displayed. + // Load the home folder. + BookmarksActivity.currentFolder = ""; + } else { // A subfolder is currently displayed. + // Load the current folder. + BookmarksActivity.currentFolder = currentFolderName; } // Reload the bookmarks list view when returning to the bookmarks activity. @@ -766,18 +754,24 @@ public class BookmarksDatabaseViewActivity extends AppCompatActivity implements @Override public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) { + // Get the dialog from the dialog fragment. + Dialog dialog = dialogFragment.getDialog(); + + // Remove the incorrect lint warning below that the dialog might be null. + assert dialog != null; + // Get handles for the views from dialog fragment. - RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton); - EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext); - EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext); - Spinner folderSpinner = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_folder_spinner); - EditText displayOrderEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_display_order_edittext); + RadioButton currentBookmarkIconRadioButton = dialog.findViewById(R.id.edit_bookmark_current_icon_radiobutton); + EditText editBookmarkNameEditText = dialog.findViewById(R.id.edit_bookmark_name_edittext); + EditText editBookmarkUrlEditText = dialog.findViewById(R.id.edit_bookmark_url_edittext); + Spinner folderSpinner = dialog.findViewById(R.id.edit_bookmark_folder_spinner); + EditText displayOrderEditText = dialog.findViewById(R.id.edit_bookmark_display_order_edittext); // Extract the bookmark information. String bookmarkNameString = editBookmarkNameEditText.getText().toString(); String bookmarkUrlString = editBookmarkUrlEditText.getText().toString(); int folderDatabaseId = (int) folderSpinner.getSelectedItemId(); - int displayOrderInt = Integer.valueOf(displayOrderEditText.getText().toString()); + int displayOrderInt = Integer.parseInt(displayOrderEditText.getText().toString()); // Instantiate the parent folder name `String`. String parentFolderNameString; @@ -812,18 +806,24 @@ public class BookmarksDatabaseViewActivity extends AppCompatActivity implements @Override public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) { + // Get the dialog from the dialog fragment. + Dialog dialog = dialogFragment.getDialog(); + + // Remove the incorrect lint warning below that the dialog might be null. + assert dialog != null; + // Get handles for the views from dialog fragment. - RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton); - RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton); - ImageView defaultFolderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview); - EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext); - Spinner parentFolderSpinner = dialogFragment.getDialog().findViewById(R.id.edit_folder_parent_folder_spinner); - EditText displayOrderEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_display_order_edittext); + RadioButton currentBookmarkIconRadioButton = dialog.findViewById(R.id.edit_folder_current_icon_radiobutton); + RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_default_icon_radiobutton); + ImageView defaultFolderIconImageView = dialog.findViewById(R.id.edit_folder_default_icon_imageview); + EditText editBookmarkNameEditText = dialog.findViewById(R.id.edit_folder_name_edittext); + Spinner parentFolderSpinner = dialog.findViewById(R.id.edit_folder_parent_folder_spinner); + EditText displayOrderEditText = dialog.findViewById(R.id.edit_folder_display_order_edittext); // Extract the folder information. String newFolderNameString = editBookmarkNameEditText.getText().toString(); int parentFolderDatabaseId = (int) parentFolderSpinner.getSelectedItemId(); - int displayOrderInt = Integer.valueOf(displayOrderEditText.getText().toString()); + int displayOrderInt = Integer.parseInt(displayOrderEditText.getText().toString()); // Instantiate the parent folder name `String`. String parentFolderNameString; diff --git a/app/src/main/java/com/stoutner/privacybrowser/activities/DomainsActivity.java b/app/src/main/java/com/stoutner/privacybrowser/activities/DomainsActivity.java index 81727aac..708e622b 100644 --- a/app/src/main/java/com/stoutner/privacybrowser/activities/DomainsActivity.java +++ b/app/src/main/java/com/stoutner/privacybrowser/activities/DomainsActivity.java @@ -1,5 +1,5 @@ /* - * Copyright © 2017-2019 Soren Stoutner . + * Copyright © 2017-2020 Soren Stoutner . * * This file is part of Privacy Browser . * @@ -209,6 +209,9 @@ public class DomainsActivity extends AppCompatActivity implements AddDomainDialo // Configure the add domain floating action button. addDomainFAB.setOnClickListener((View view) -> { + // Remove the incorrect warning below that the current URL might be null. + assert currentUrl != null; + // Create an add domain dialog. DialogFragment addDomainDialog = AddDomainDialog.addDomain(currentUrl); @@ -640,7 +643,7 @@ public class DomainsActivity extends AppCompatActivity implements AddDomainDialo } @Override - public void onAddDomain(DialogFragment dialogFragment) { + public void onAddDomain(@NonNull DialogFragment dialogFragment) { // Dismiss the undo delete snackbar if it is currently displayed. if ((undoDeleteSnackbar != null) && undoDeleteSnackbar.isShown()) { undoDeleteSnackbar.dismiss(); diff --git a/app/src/main/java/com/stoutner/privacybrowser/activities/MainWebViewActivity.java b/app/src/main/java/com/stoutner/privacybrowser/activities/MainWebViewActivity.java index 42b20656..267e59bf 100644 --- a/app/src/main/java/com/stoutner/privacybrowser/activities/MainWebViewActivity.java +++ b/app/src/main/java/com/stoutner/privacybrowser/activities/MainWebViewActivity.java @@ -2393,7 +2393,7 @@ public class MainWebViewActivity extends AppCompatActivity implements CreateBook } @Override - public void onCreateBookmarkFolder(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) { + public void onCreateBookmarkFolder(DialogFragment dialogFragment, @NonNull Bitmap favoriteIconBitmap) { // Get a handle for the bookmarks list view. ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview); @@ -5513,11 +5513,29 @@ public class MainWebViewActivity extends AppCompatActivity implements CreateBook // Store the file path callback. fileChooserCallback = filePathCallback; - // Create an intent to open a chooser based ont the file chooser parameters. + // Create an intent to open a chooser based on the file chooser parameters. Intent fileChooserIntent = fileChooserParams.createIntent(); - // Open the file chooser. - startActivityForResult(fileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE); + // Get a handle for the package manager. + PackageManager packageManager = getPackageManager(); + + // Check to see if the file chooser intent resolves to an installed package. + if (fileChooserIntent.resolveActivity(packageManager) != null) { // The file chooser intent is fine. + // Start the file chooser intent. + startActivityForResult(fileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE); + } else { // The file chooser intent will cause a crash. + // Create a generic intent to open a chooser. + Intent genericFileChooserIntent = new Intent(Intent.ACTION_GET_CONTENT); + + // Request an openable file. + genericFileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE); + + // Set the file type to everything. + genericFileChooserIntent.setType("*/*"); + + // Start the generic file chooser intent. + startActivityForResult(genericFileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE); + } } return true; } diff --git a/app/src/main/java/com/stoutner/privacybrowser/dialogs/AboutViewSourceDialog.kt b/app/src/main/java/com/stoutner/privacybrowser/dialogs/AboutViewSourceDialog.kt index 21b8c4a2..30bcf8d0 100644 --- a/app/src/main/java/com/stoutner/privacybrowser/dialogs/AboutViewSourceDialog.kt +++ b/app/src/main/java/com/stoutner/privacybrowser/dialogs/AboutViewSourceDialog.kt @@ -23,12 +23,13 @@ import android.app.AlertDialog import android.app.Dialog import android.os.Bundle import android.view.WindowManager + import androidx.fragment.app.DialogFragment import androidx.preference.PreferenceManager import com.stoutner.privacybrowser.R -class AboutViewSourceDialog : DialogFragment() { +class AboutViewSourceDialog: DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { // Get a handle for the shared preferences. val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) diff --git a/app/src/main/java/com/stoutner/privacybrowser/dialogs/AddDomainDialog.java b/app/src/main/java/com/stoutner/privacybrowser/dialogs/AddDomainDialog.java deleted file mode 100644 index 87c336df..00000000 --- a/app/src/main/java/com/stoutner/privacybrowser/dialogs/AddDomainDialog.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Copyright © 2017-2019 Soren Stoutner . - * - * This file is part of Privacy Browser . - * - * Privacy Browser is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Privacy Browser is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Privacy Browser. If not, see . - */ - -package com.stoutner.privacybrowser.dialogs; - -import android.annotation.SuppressLint; -import android.app.AlertDialog; -import android.app.Dialog; -import android.content.Context; -import android.content.DialogInterface; -import android.content.SharedPreferences; -import android.net.Uri; -import android.os.Bundle; -import android.preference.PreferenceManager; -import android.text.Editable; -import android.text.TextWatcher; -import android.view.KeyEvent; -import android.view.View; -import android.view.WindowManager; -import android.widget.Button; -import android.widget.EditText; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.fragment.app.DialogFragment; // The AndroidX dialog fragment must be used or an error is produced on API <=22. - -import com.stoutner.privacybrowser.R; -import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper; - -public class AddDomainDialog extends DialogFragment { - // The public interface is used to send information back to the parent activity. - public interface AddDomainListener { - void onAddDomain(DialogFragment dialogFragment); - } - - // The add domain listener is used in `onAttach()` and `onCreateDialog()`. - private AddDomainListener addDomainListener; - - @Override - public void onAttach(@NonNull Context context) { - // Run the default commands. - super.onAttach(context); - - // Get a handle for the listener from the launching context. - addDomainListener = (AddDomainListener) context; - } - - public static AddDomainDialog addDomain(String url) { - // Create an arguments bundle. - Bundle argumentsBundle = new Bundle(); - - // Store the URL in the bundle. - argumentsBundle.putString("url", url); - - // Create a new instance of the dialog. - AddDomainDialog addDomainDialog = new AddDomainDialog(); - - // Add the bundle to the dialog. - addDomainDialog.setArguments(argumentsBundle); - - // Return the new dialog. - return addDomainDialog; - } - - // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`. - @SuppressLint("InflateParams") - @Override - @NonNull - public Dialog onCreateDialog(Bundle savedInstanceState) { - // Get the arguments. - Bundle arguments = getArguments(); - - // Remove the incorrect lint warning below that the arguments might be null. - assert arguments != null; - - // Get the URL from the bundle. - String url = arguments.getString("url"); - - // Use an alert dialog builder to create the alert dialog. - AlertDialog.Builder dialogBuilder; - - // Get a handle for the shared preferences. - SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext()); - - // Get the screenshot and theme preferences. - boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false); - boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false); - - // Set the style according to the theme. - if (darkTheme) { - dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark); - } else { - dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight); - } - - // Set the title. - dialogBuilder.setTitle(R.string.add_domain); - - // Remove the incorrect lint warning below that `getActivity()` might be null. - assert getActivity() != null; - - // Set the view. The parent view is `null` because it will be assigned by the alert dialog. - dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.add_domain_dialog, null)); - - // Set a listener for the negative button. - dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> { - // Do nothing. The alert dialog will close automatically. - }); - - // Set a listener for the positive button. - dialogBuilder.setPositiveButton(R.string.add, (DialogInterface dialog, int which) -> { - // Return the dialog fragment to the parent activity on add. - addDomainListener.onAddDomain(this); - }); - - // Create an alert dialog from the builder. - final AlertDialog alertDialog = dialogBuilder.create(); - - // Remove the warning below that `getWindow()` might be null. - assert alertDialog.getWindow() != null; - - // Disable screenshots if not allowed. - if (!allowScreenshots) { - alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE); - } - - // Show the keyboard when the alert dialog is displayed on the screen. - alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); - - // The alert dialog must be shown before the contents can be edited. - alertDialog.show(); - - // Initialize `domainsDatabaseHelper`. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`. - final DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(getContext(), null, null, 0); - - // Get handles for the views in the alert dialog. - final EditText addDomainEditText = alertDialog.findViewById(R.id.domain_name_edittext); - final TextView domainNameAlreadyExistsTextView = alertDialog.findViewById(R.id.domain_name_already_exists_textview); - final Button addButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE); - - // Update the status of the warning text and the add button. - addDomainEditText.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - // Do nothing. - } - - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - // Do nothing. - } - - @Override - public void afterTextChanged(Editable s) { - if (domainsDatabaseHelper.getCursorForDomainName(addDomainEditText.getText().toString()).getCount() >0) { // The domain already exists. - // Show the warning text. - domainNameAlreadyExistsTextView.setVisibility(View.VISIBLE); - - // Disable the add button. - addButton.setEnabled(false); - } else { // The domain do not yet exist. - // Hide the warning text. - domainNameAlreadyExistsTextView.setVisibility(View.GONE); - - // Enable the add button. - addButton.setEnabled(true); - } - } - }); - - // Convert the URL to a URI. - Uri currentUri = Uri.parse(url); - - // Display the host in the add domain edit text. - addDomainEditText.setText(currentUri.getHost()); - - // Allow the enter key on the keyboard to create the domain from the add domain edit text. - addDomainEditText.setOnKeyListener((View view, int keyCode, KeyEvent event) -> { - // If the event is a key-down on the enter key, select the `PositiveButton` `Add`. - if ((keyCode == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN)) { - // Trigger `addDomainListener` and return the dialog fragment to the parent activity. - addDomainListener.onAddDomain(this); - - // Manually dismiss the alert dialog. - alertDialog.dismiss(); - - // Consume the event. - return true; - } else { // If any other key was pressed, do not consume the event. - return false; - } - }); - - // Return the alert dialog. - return alertDialog; - } -} \ No newline at end of file diff --git a/app/src/main/java/com/stoutner/privacybrowser/dialogs/AddDomainDialog.kt b/app/src/main/java/com/stoutner/privacybrowser/dialogs/AddDomainDialog.kt new file mode 100644 index 00000000..57068354 --- /dev/null +++ b/app/src/main/java/com/stoutner/privacybrowser/dialogs/AddDomainDialog.kt @@ -0,0 +1,203 @@ +/* + * Copyright © 2017-2020 Soren Stoutner . + * + * This file is part of Privacy Browser . + * + * Privacy Browser is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Privacy Browser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Privacy Browser. If not, see . + */ + +package com.stoutner.privacybrowser.dialogs + +import android.annotation.SuppressLint +import android.app.AlertDialog +import android.app.Dialog +import android.content.Context +import android.content.DialogInterface +import android.net.Uri +import android.os.Bundle +import android.text.Editable +import android.text.TextWatcher +import android.view.KeyEvent +import android.view.View +import android.view.WindowManager +import android.widget.EditText +import android.widget.TextView + +import androidx.fragment.app.DialogFragment +import androidx.preference.PreferenceManager + +import com.stoutner.privacybrowser.R +import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper + +class AddDomainDialog: DialogFragment() { + // The public interface is used to send information back to the parent activity. + interface AddDomainListener { + fun onAddDomain(dialogFragment: DialogFragment) + } + + // The add domain listener is initialized in `onAttach()` and used in `onCreateDialog()`. + private lateinit var addDomainListener: AddDomainListener + + override fun onAttach(context: Context) { + // Run the default commands. + super.onAttach(context) + + // Get a handle for the listener from the launching context. + addDomainListener = context as AddDomainListener + } + + companion object { + // `@JvmStatic` will no longer be required once all the code has transitioned to Kotlin. Also, the function can then be moved out of a companion object and just become a package-level function. + @JvmStatic + fun addDomain(urlString: String): AddDomainDialog { + // Create an arguments bundle. + val argumentsBundle = Bundle() + + // Store the URL in the bundle. + argumentsBundle.putString("url_string", urlString) + + // Create a new instance of the dialog. + val addDomainDialog = AddDomainDialog() + + // Add the arguments bundle to the dialog. + addDomainDialog.arguments = argumentsBundle + + // Return the new dialog. + return addDomainDialog + } + } + + // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the alert dialog. + @SuppressLint("InflateParams") + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + // Get the arguments. + val arguments = arguments!! + + // Get the URL from the bundle. + val urlString = arguments.getString("url_string") + + // Get a handle for the shared preferences. + val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) + + // Get the screenshot and theme preferences. + val allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false) + val darkTheme = sharedPreferences.getBoolean("dark_theme", false) + + // Use an alert dialog builder to create the alert dialog. + val dialogBuilder: AlertDialog.Builder + + // USet the style and the icon according to the theme. + if (darkTheme) { + // Set the dark style. + dialogBuilder = AlertDialog.Builder(context, R.style.PrivacyBrowserAlertDialogDark) + + // Set the dark icon. + dialogBuilder.setIcon(R.drawable.domains_dark) + } else { + // Set the light style. + dialogBuilder = AlertDialog.Builder(context, R.style.PrivacyBrowserAlertDialogLight) + + // Set the light icon. + dialogBuilder.setIcon(R.drawable.domains_light) + } + + // Set the title. + dialogBuilder.setTitle(R.string.add_domain) + + // Set the view. The parent view is `null` because it will be assigned by the alert dialog. + dialogBuilder.setView(activity!!.layoutInflater.inflate(R.layout.add_domain_dialog, null)) + + // Set a listener on the cancel button. Using `null` as the listener closes the dialog without doing anything else. + dialogBuilder.setNegativeButton(R.string.cancel, null) + + // Set a listener on the add button. + dialogBuilder.setPositiveButton(R.string.add) { _: DialogInterface, _: Int -> + // Return the dialog fragment to the parent activity on add. + addDomainListener.onAddDomain(this) + } + + // Create an alert dialog from the builder. + val alertDialog = dialogBuilder.create() + + // Disable screenshots if not allowed. + if (!allowScreenshots) { + alertDialog.window!!.addFlags(WindowManager.LayoutParams.FLAG_SECURE) + } + + // The alert dialog must be shown before the contents can be modified. + alertDialog.show() + + // Initialize the domains database helper. The `0` specifies the database version, but that is ignored and set instead using a constant in domains database helper. + val domainsDatabaseHelper = DomainsDatabaseHelper(context, null, null, 0) + + // Get handles for the views in the alert dialog. + val addDomainEditText: EditText = alertDialog.findViewById(R.id.domain_name_edittext) + val domainNameAlreadyExistsTextView: TextView = alertDialog.findViewById(R.id.domain_name_already_exists_textview) + val addButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE) + + // Update the status of the warning text and the add button when the domain name changes. + addDomainEditText.addTextChangedListener(object: TextWatcher { + override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { + // Do nothing. + } + + override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { + // Do nothing. + } + + override fun afterTextChanged(s: Editable) { + if (domainsDatabaseHelper.getCursorForDomainName(addDomainEditText.text.toString()).count > 0) { // The domain already exists. + // Show the warning text. + domainNameAlreadyExistsTextView.visibility = View.VISIBLE + + // Disable the add button. + addButton.isEnabled = false + } else { // The domain do not yet exist. + // Hide the warning text. + domainNameAlreadyExistsTextView.visibility = View.GONE + + // Enable the add button. + addButton.isEnabled = true + } + } + }) + + // Convert the URL string to a URI. + val currentUri = Uri.parse(urlString) + + // Display the host in the add domain edit text. + addDomainEditText.setText(currentUri.host) + + // Allow the enter key on the keyboard to create the domain from the add domain edit text. + addDomainEditText.setOnKeyListener { _: View, keyCode: Int, keyEvent: KeyEvent -> + // Check the key code and event. + if (keyCode == KeyEvent.KEYCODE_ENTER && keyEvent.action == KeyEvent.ACTION_DOWN) { // The event is a key-down on the enter key. + // Trigger the add domain listener and return the dialog fragment to the parent activity. + addDomainListener.onAddDomain(this) + + // Manually dismiss the alert dialog. + alertDialog.dismiss() + + // Consume the event. + return@setOnKeyListener true + } else { // Some other key was pressed. + // Do not consume the event. + return@setOnKeyListener false + } + } + + // Return the alert dialog. + return alertDialog + } +} \ No newline at end of file diff --git a/app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateBookmarkDialog.java b/app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateBookmarkDialog.java deleted file mode 100644 index f89649bc..00000000 --- a/app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateBookmarkDialog.java +++ /dev/null @@ -1,222 +0,0 @@ -/* - * Copyright © 2016-2019 Soren Stoutner . - * - * This file is part of Privacy Browser . - * - * Privacy Browser is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Privacy Browser is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Privacy Browser. If not, see . - */ - -package com.stoutner.privacybrowser.dialogs; - -import android.annotation.SuppressLint; -import android.app.AlertDialog; -import android.app.Dialog; -import android.content.Context; -import android.content.DialogInterface; -import android.content.SharedPreferences; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.drawable.BitmapDrawable; -import android.graphics.drawable.Drawable; -import android.os.Bundle; -import android.preference.PreferenceManager; -import android.view.KeyEvent; -import android.view.View; -import android.view.WindowManager; -import android.widget.EditText; - -import androidx.annotation.NonNull; -import androidx.fragment.app.DialogFragment; // The AndroidX dialog fragment must be used or an error is produced on API <=22. - -import com.stoutner.privacybrowser.R; - -import java.io.ByteArrayOutputStream; - -public class CreateBookmarkDialog extends DialogFragment { - // The public interface is used to send information back to the parent activity. - public interface CreateBookmarkListener { - void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap); - } - - // The create bookmark listener is initialized in `onAttach()` and used in `onCreateDialog()`. - private CreateBookmarkListener createBookmarkListener; - - public void onAttach(@NonNull Context context) { - // Run the default commands. - super.onAttach(context); - - // Get a handle for the create bookmark listener from the launching context. - createBookmarkListener = (CreateBookmarkListener) context; - } - - public static CreateBookmarkDialog createBookmark(String url, String title, Bitmap favoriteIconBitmap) { - // Create a favorite icon byte array output stream. - ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream(); - - // Convert the favorite icon to a PNG and place it in the byte array output stream. `0` is for lossless compression (the only option for a PNG). - favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream); - - // Convert the byte array output stream to a byte array. - byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray(); - - // Create an arguments bundle. - Bundle argumentsBundle = new Bundle(); - - // Store the variables in the bundle. - argumentsBundle.putString("url", url); - argumentsBundle.putString("title", title); - argumentsBundle.putByteArray("favorite_icon_byte_array", favoriteIconByteArray); - - // Create a new instance of the dialog. - CreateBookmarkDialog createBookmarkDialog = new CreateBookmarkDialog(); - - // Add the bundle to the dialog. - createBookmarkDialog.setArguments(argumentsBundle); - - // Return the new dialog. - return createBookmarkDialog; - } - - // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`. - @SuppressLint("InflateParams") - @Override - @NonNull - public Dialog onCreateDialog(Bundle savedInstanceState) { - // Get the arguments. - Bundle arguments = getArguments(); - - // Remove the incorrect lint warning below that the arguments might be null. - assert arguments != null; - - // Get the strings from the arguments. - String url = arguments.getString("url"); - String title = arguments.getString("title"); - - // Get the favorite icon byte array. - byte[] favoriteIconByteArray = arguments.getByteArray("favorite_icon_byte_array"); - - // Remove the incorrect lint warning below that the favorite icon byte array might be null. - assert favoriteIconByteArray != null; - - // Convert the favorite icon byte array to a bitmap. - Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length); - - // Get a handle for the shared preferences. - SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext()); - - // Get the theme and screenshot preferences. - boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false); - boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false); - - // Create a drawable version of the favorite icon. - Drawable favoriteIconDrawable = new BitmapDrawable(getResources(), favoriteIconBitmap); - - // Use an alert dialog builder to create the alert dialog. - AlertDialog.Builder dialogBuilder; - - // Set the style according to the theme. - if (darkTheme) { - dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark); - } else { - dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight); - } - - // Set the title and icon. - dialogBuilder.setTitle(R.string.create_bookmark); - dialogBuilder.setIcon(favoriteIconDrawable); - - // Remove the warning below that `getLayoutInflater()` might be null. - assert getActivity() != null; - - // Set the view. The parent view is `null` because it will be assigned by the `AlertDialog`. - dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.create_bookmark_dialog, null)); - - // Set an `onClick()` listener for the negative button. - dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> { - // Do nothing. The `AlertDialog` will close automatically. - }); - - // Set an `onClick()` listener for the positive button. - dialogBuilder.setPositiveButton(R.string.create, (DialogInterface dialog, int which) -> { - // Return the `DialogFragment` to the parent activity. - createBookmarkListener.onCreateBookmark(this, favoriteIconBitmap); - }); - - // Create an `AlertDialog` from the `AlertDialog.Builder`. - AlertDialog alertDialog = dialogBuilder.create(); - - // Remove the warning below that `getWindow()` might be null. - assert alertDialog.getWindow() != null; - - // Disable screenshots if not allowed. - if (!allowScreenshots) { - alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE); - } - - // Show the keyboard when the `AlertDialog` is displayed on the screen. - alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); - - // The alert dialog needs to be shown before `setOnKeyListener()` can be called. - alertDialog.show(); - - // Get a handle for `create_bookmark_name_edittext`. - EditText createBookmarkNameEditText = alertDialog.findViewById(R.id.create_bookmark_name_edittext); - - // Set the current `WebView` title as the text for `create_bookmark_name_edittext`. - createBookmarkNameEditText.setText(title); - - // Allow the `enter` key on the keyboard to create the bookmark from the create bookmark name edittext`. - createBookmarkNameEditText.setOnKeyListener((View view, int keyCode, KeyEvent keyEvent) -> { - // If the event is a key-down on the `enter` key, select the create button. - if ((keyCode == KeyEvent.KEYCODE_ENTER) && (keyEvent.getAction() == KeyEvent.ACTION_DOWN)) { - // Trigger the create bookmark listener and return the dialog fragment and the favorite icon bitmap to the parent activity. - createBookmarkListener.onCreateBookmark(this, favoriteIconBitmap); - - // Manually dismiss the alert dialog. - alertDialog.dismiss(); - - // Consume the event. - return true; - } else { // Some other key was pressed. - // Do not consume the event. - return false; - } - }); - - // Set the formatted URL string as the initial text of the create bookmark URL edit text. - EditText createBookmarkUrlEditText = alertDialog.findViewById(R.id.create_bookmark_url_edittext); - createBookmarkUrlEditText.setText(url); - - // Allow the enter key on the keyboard to create the bookmark from create bookmark URL edit text. - createBookmarkUrlEditText.setOnKeyListener((View v, int keyCode, KeyEvent keyEvent) -> { - // If the event is a key-down on the `enter` key, select the create button. - if ((keyCode == KeyEvent.KEYCODE_ENTER) && (keyEvent.getAction() == KeyEvent.ACTION_DOWN)) { - // Trigger the create bookmark listener and return the dialog fragment and the favorite icon bitmap to the parent activity. - createBookmarkListener.onCreateBookmark(this, favoriteIconBitmap); - - // Manually dismiss the alert dialog. - alertDialog.dismiss(); - - // Consume the event. - return true; - } else { // Some other key was pressed. - // Do not consume the event. - return false; - } - }); - - // Return the alert dialog. - return alertDialog; - } -} \ No newline at end of file diff --git a/app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateBookmarkDialog.kt b/app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateBookmarkDialog.kt new file mode 100644 index 00000000..5bc2da25 --- /dev/null +++ b/app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateBookmarkDialog.kt @@ -0,0 +1,200 @@ +/* + * Copyright © 2016-2020 Soren Stoutner . + * + * This file is part of Privacy Browser . + * + * Privacy Browser is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Privacy Browser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Privacy Browser. If not, see . + */ + +package com.stoutner.privacybrowser.dialogs + +import android.annotation.SuppressLint +import android.app.AlertDialog +import android.app.Dialog +import android.content.Context +import android.content.DialogInterface +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.graphics.drawable.BitmapDrawable +import android.graphics.drawable.Drawable +import android.os.Bundle +import android.view.KeyEvent +import android.view.View +import android.view.WindowManager +import android.widget.EditText + +import androidx.fragment.app.DialogFragment +import androidx.preference.PreferenceManager + +import com.stoutner.privacybrowser.R + +import java.io.ByteArrayOutputStream + +class CreateBookmarkDialog: DialogFragment() { + // The public interface is used to send information back to the parent activity. + interface CreateBookmarkListener { + fun onCreateBookmark(dialogFragment: DialogFragment, favoriteIconBitmap: Bitmap) + } + + // The create bookmark listener is initialized in `onAttach()` and used in `onCreateDialog()`. + private lateinit var createBookmarkListener: CreateBookmarkListener + + override fun onAttach(context: Context) { + // Run the default commands. + super.onAttach(context) + + // Get a handle for the create bookmark listener from the launching context. + createBookmarkListener = context as CreateBookmarkListener + } + + companion object { + // `@JvmStatic` will no longer be required once all the code has transitioned to Kotlin. Also, the function can then be moved out of a companion object and just become a package-level function. + @JvmStatic + fun createBookmark(urlString: String, titleString: String, favoriteIconBitmap: Bitmap): CreateBookmarkDialog { + // Create a favorite icon byte array output stream. + val favoriteIconByteArrayOutputStream = ByteArrayOutputStream() + + // Convert the favorite icon to a PNG and place it in the byte array output stream. `0` is for lossless compression (the only option for a PNG). + favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream) + + // Convert the byte array output stream to a byte array. + val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray() + + // Create an arguments bundle. + val argumentsBundle = Bundle() + + // Store the variables in the bundle. + argumentsBundle.putString("url_string", urlString) + argumentsBundle.putString("title_string", titleString) + argumentsBundle.putByteArray("favorite_icon_byte_array", favoriteIconByteArray) + + // Create a new instance of the dialog. + val createBookmarkDialog = CreateBookmarkDialog() + + // Add the bundle to the dialog. + createBookmarkDialog.arguments = argumentsBundle + + // Return the new dialog. + return createBookmarkDialog + } + } + + // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the alert dialog. + @SuppressLint("InflateParams") + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + // Get the arguments. + val arguments = arguments!! + + // Get the contents of the arguments. + val urlString = arguments.getString("url_string") + val titleString = arguments.getString("title_string") + val favoriteIconByteArray = arguments.getByteArray("favorite_icon_byte_array")!! + + // Convert the favorite icon byte array to a bitmap. + val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size) + + // Get a handle for the shared preferences. + val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) + + // Get the screenshot and theme preferences. + val allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false) + val darkTheme = sharedPreferences.getBoolean("dark_theme", false) + + // Use an alert dialog builder to create the dialog and set the style according to the theme. + val dialogBuilder = if (darkTheme) { + AlertDialog.Builder(context, R.style.PrivacyBrowserAlertDialogDark) + } else { + AlertDialog.Builder(context, R.style.PrivacyBrowserAlertDialogLight) + } + + // Set the title. + dialogBuilder.setTitle(R.string.create_bookmark) + + // Create a drawable version of the favorite icon. + val favoriteIconDrawable: Drawable = BitmapDrawable(resources, favoriteIconBitmap) + + // Set the icon. + dialogBuilder.setIcon(favoriteIconDrawable) + + // Set the view. The parent view is `null` because it will be assigned by the alert dialog. + dialogBuilder.setView(activity!!.layoutInflater.inflate(R.layout.create_bookmark_dialog, null)) + + // Set a listener on the cancel button. Using `null` as the listener closes the dialog without doing anything else. + dialogBuilder.setNegativeButton(R.string.cancel, null) + + // Set a listener on the create button. + dialogBuilder.setPositiveButton(R.string.create) { _: DialogInterface, _: Int -> + // Return the dialog fragment and the favorite icon bitmap to the parent activity. + createBookmarkListener.onCreateBookmark(this, favoriteIconBitmap) + } + + // Create an alert dialog from the builder. + val alertDialog = dialogBuilder.create() + + // Disable screenshots if not allowed. + if (!allowScreenshots) { + alertDialog.window!!.addFlags(WindowManager.LayoutParams.FLAG_SECURE) + } + + // The alert dialog needs to be shown before the contents can be modified. + alertDialog.show() + + // Get a handle for the edit texts. + val createBookmarkNameEditText: EditText = alertDialog.findViewById(R.id.create_bookmark_name_edittext) + val createBookmarkUrlEditText: EditText = alertDialog.findViewById(R.id.create_bookmark_url_edittext) + + // Set the initial texts for the edit texts. + createBookmarkNameEditText.setText(titleString) + createBookmarkUrlEditText.setText(urlString) + + // Allow the enter key on the keyboard to create the bookmark from the create bookmark name edit text. + createBookmarkNameEditText.setOnKeyListener { _: View, keyCode: Int, keyEvent: KeyEvent -> + // Check the key code and event. + if (keyCode == KeyEvent.KEYCODE_ENTER && keyEvent.action == KeyEvent.ACTION_DOWN) { // The event is a key-down on the enter key. + // Trigger the create bookmark listener and return the dialog fragment and the favorite icon bitmap to the parent activity. + createBookmarkListener.onCreateBookmark(this, favoriteIconBitmap) + + // Manually dismiss the alert dialog. + alertDialog.dismiss() + + // Consume the event. + return@setOnKeyListener true + } else { // Some other key was pressed. + // Do not consume the event. + return@setOnKeyListener false + } + } + + // Allow the enter key on the keyboard to create the bookmark from create bookmark URL edit text. + createBookmarkUrlEditText.setOnKeyListener { _: View, keyCode: Int, keyEvent: KeyEvent -> + // Check the key code and event. + if (keyCode == KeyEvent.KEYCODE_ENTER && keyEvent.action == KeyEvent.ACTION_DOWN) { // The event is a key-down on the enter key. + // Trigger the create bookmark listener and return the dialog fragment and the favorite icon bitmap to the parent activity. + createBookmarkListener.onCreateBookmark(this, favoriteIconBitmap) + + // Manually dismiss the alert dialog. + alertDialog.dismiss() + + // Consume the event. + return@setOnKeyListener true + } else { // Some other key was pressed. + // Do not consume the event. + return@setOnKeyListener false + } + } + + // Return the alert dialog. + return alertDialog + } +} \ No newline at end of file diff --git a/app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateBookmarkFolderDialog.java b/app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateBookmarkFolderDialog.java deleted file mode 100644 index 2b012683..00000000 --- a/app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateBookmarkFolderDialog.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright © 2016-2019 Soren Stoutner . - * - * This file is part of Privacy Browser . - * - * Privacy Browser is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Privacy Browser is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Privacy Browser. If not, see . - */ - -package com.stoutner.privacybrowser.dialogs; - -import android.annotation.SuppressLint; -import android.app.AlertDialog; -import android.app.Dialog; -import android.content.Context; -import android.content.DialogInterface; -import android.content.SharedPreferences; -import android.database.Cursor; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.os.Bundle; -import android.preference.PreferenceManager; -import android.text.Editable; -import android.text.TextWatcher; -import android.view.KeyEvent; -import android.view.View; -import android.view.Window; -import android.view.WindowManager; -import android.widget.Button; -import android.widget.EditText; -import android.widget.ImageView; - -import androidx.annotation.NonNull; -import androidx.fragment.app.DialogFragment; // The AndroidX dialog fragment must be used or an error is produced on API <=22. - -import com.stoutner.privacybrowser.R; -import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper; - -import java.io.ByteArrayOutputStream; - -public class CreateBookmarkFolderDialog extends DialogFragment { - // The public interface is used to send information back to the parent activity. - public interface CreateBookmarkFolderListener { - void onCreateBookmarkFolder(DialogFragment dialogFragment, Bitmap favoriteIconBitmap); - } - - // `createBookmarkFolderListener` is used in `onAttach()` and `onCreateDialog`. - private CreateBookmarkFolderListener createBookmarkFolderListener; - - public void onAttach(@NonNull Context context) { - super.onAttach(context); - - // Get a handle for `createBookmarkFolderListener` from the launching context. - createBookmarkFolderListener = (CreateBookmarkFolderListener) context; - } - - public static CreateBookmarkFolderDialog createBookmarkFolder(Bitmap favoriteIconBitmap) { - // Create a favorite icon byte array output stream. - ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream(); - - // Convert the favorite icon to a PNG and place it in the byte array output stream. `0` is for lossless compression (the only option for a PNG). - favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream); - - // Convert the byte array output stream to a byte array. - byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray(); - - // Create an arguments bundle. - Bundle argumentsBundle = new Bundle(); - - // Store the favorite icon in the bundle. - argumentsBundle.putByteArray("favorite_icon_byte_array", favoriteIconByteArray); - - // Create a new instance of the dialog. - CreateBookmarkFolderDialog createBookmarkFolderDialog = new CreateBookmarkFolderDialog(); - - // Add the bundle to the dialog. - createBookmarkFolderDialog.setArguments(argumentsBundle); - - // Return the new dialog. - return createBookmarkFolderDialog; - } - - // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`. - @SuppressLint("InflateParams") - @Override - @NonNull - public Dialog onCreateDialog(Bundle savedInstanceState) { - // Get the arguments. - Bundle arguments = getArguments(); - - // Remove the incorrect lint warning below that the arguments might be null. - assert arguments != null; - - // Get the favorite icon byte array. - byte[] favoriteIconByteArray = arguments.getByteArray("favorite_icon_byte_array"); - - // Remove the incorrect lint warning below that the favorite icon byte array might be null. - assert favoriteIconByteArray != null; - - // Convert the favorite icon byte array to a bitmap. - Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length); - - // Use an alert dialog builder to create the alert dialog. - AlertDialog.Builder dialogBuilder; - - // Get a handle for the shared preferences. - SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext()); - - // Get the screenshot and theme preferences. - boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false); - boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false); - - // Set the style according to the theme. - if (darkTheme) { - dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark); - } else { - dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight); - } - - // Set the title. - dialogBuilder.setTitle(R.string.create_folder); - - // Remove the warning below that `getLayoutInflater()` might be null. - assert getActivity() != null; - - // Set the view. The parent view is null because it will be assigned by the alert dialog. - dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.create_bookmark_folder_dialog, null)); - - // Set an `onClick()` listener for the negative button. - dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> { - // Do nothing. The `AlertDialog` will close automatically. - }); - - // Set an `onClick()` listener fo the positive button. - dialogBuilder.setPositiveButton(R.string.create, (DialogInterface dialog, int which) -> { - // Return the `DialogFragment` to the parent activity on create. - createBookmarkFolderListener.onCreateBookmarkFolder(this, favoriteIconBitmap); - }); - - - // Create an alert dialog from the `AlertDialog.Builder`. - final AlertDialog alertDialog = dialogBuilder.create(); - - // Get the alert dialog window. - Window dialogWindow = alertDialog.getWindow(); - - // Remove the incorrect lint warning below that the dialog window might be null. - assert dialogWindow != null; - - // Disable screenshots if not allowed. - if (!allowScreenshots) { - alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE); - } - - // Display the keyboard. - dialogWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); - - // The alert dialog must be shown before items in the alert dialog can be modified. - alertDialog.show(); - - // Get handles for the views in the dialog. - final Button createButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE); - EditText folderNameEditText = alertDialog.findViewById(R.id.create_folder_name_edittext); - ImageView webPageIconImageView = alertDialog.findViewById(R.id.create_folder_web_page_icon); - - // Initially disable the create button. - createButton.setEnabled(false); - - // Initialize the database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`. - final BookmarksDatabaseHelper bookmarksDatabaseHelper = new BookmarksDatabaseHelper(getContext(), null, null, 0); - - // Enable the create button if the new folder name is unique. - folderNameEditText.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - // Do nothing. - } - - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - // Do nothing. - } - - @Override - public void afterTextChanged(Editable s) { - // Convert the current text to a string. - String folderName = s.toString(); - - // Check if a folder with the name already exists. - Cursor folderExistsCursor = bookmarksDatabaseHelper.getFolder(folderName); - - // Enable the create button if the new folder name is not empty and doesn't already exist. - createButton.setEnabled(!folderName.isEmpty() && (folderExistsCursor.getCount() == 0)); - } - }); - - // Set the enter key on the keyboard to create the folder from the edit text. - folderNameEditText.setOnKeyListener((View view, int keyCode, KeyEvent keyEvent) -> { - // If the key event is a key-down on the `enter` key create the bookmark folder. - if ((keyEvent.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && createButton.isEnabled()) { // The enter key was pressed and the create button is enabled. - // Trigger the create bookmark folder listener and return the dialog fragment to the parent activity. - createBookmarkFolderListener.onCreateBookmarkFolder(this, favoriteIconBitmap); - - // Manually dismiss the alert dialog. - alertDialog.dismiss(); - - // Consume the event. - return true; - } else { // If any other key was pressed, or if the create button is currently disabled, do not consume the event. - return false; - } - }); - - // Display the current favorite icon. - webPageIconImageView.setImageBitmap(favoriteIconBitmap); - - // Return the alert dialog. - return alertDialog; - } -} \ No newline at end of file diff --git a/app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateBookmarkFolderDialog.kt b/app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateBookmarkFolderDialog.kt new file mode 100644 index 00000000..0cca2881 --- /dev/null +++ b/app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateBookmarkFolderDialog.kt @@ -0,0 +1,203 @@ +/* + * Copyright © 2016-2020 Soren Stoutner . + * + * This file is part of Privacy Browser . + * + * Privacy Browser is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Privacy Browser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Privacy Browser. If not, see . + */ +package com.stoutner.privacybrowser.dialogs + +import android.annotation.SuppressLint +import android.app.AlertDialog +import android.app.Dialog +import android.content.Context +import android.content.DialogInterface +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.os.Bundle +import android.text.Editable +import android.text.TextWatcher +import android.view.KeyEvent +import android.view.View +import android.view.WindowManager +import android.widget.EditText +import android.widget.ImageView + +import androidx.fragment.app.DialogFragment +import androidx.preference.PreferenceManager + +import com.stoutner.privacybrowser.R +import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper + +import java.io.ByteArrayOutputStream + +class CreateBookmarkFolderDialog: DialogFragment() { + // The public interface is used to send information back to the parent activity. + interface CreateBookmarkFolderListener { + fun onCreateBookmarkFolder(dialogFragment: DialogFragment, favoriteIconBitmap: Bitmap) + } + + // The create bookmark folder listener is initialized in `onAttach()` and used in `onCreateDialog()`. + private lateinit var createBookmarkFolderListener: CreateBookmarkFolderListener + + override fun onAttach(context: Context) { + // Run the default commands. + super.onAttach(context) + + // Get a handle for the create bookmark folder listener from the launching context. + createBookmarkFolderListener = context as CreateBookmarkFolderListener + } + + companion object { + // `@JvmStatic` will no longer be required once all the code has transitioned to Kotlin. Also, the function can then be moved out of a companion object and just become a package-level function. + @JvmStatic + fun createBookmarkFolder(favoriteIconBitmap: Bitmap): CreateBookmarkFolderDialog { + // Create a favorite icon byte array output stream. + val favoriteIconByteArrayOutputStream = ByteArrayOutputStream() + + // Convert the favorite icon to a PNG and place it in the byte array output stream. `0` is for lossless compression (the only option for a PNG). + favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream) + + // Convert the byte array output stream to a byte array. + val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray() + + // Create an arguments bundle. + val argumentsBundle = Bundle() + + // Store the favorite icon in the bundle. + argumentsBundle.putByteArray("favorite_icon_byte_array", favoriteIconByteArray) + + // Create a new instance of the dialog. + val createBookmarkFolderDialog = CreateBookmarkFolderDialog() + + // Add the bundle to the dialog. + createBookmarkFolderDialog.arguments = argumentsBundle + + // Return the new dialog. + return createBookmarkFolderDialog + } + } + + // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the alert dialog. + @SuppressLint("InflateParams") + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + // Get the arguments. + val arguments = arguments!! + + // Get the favorite icon byte array. + val favoriteIconByteArray = arguments.getByteArray("favorite_icon_byte_array")!! + + // Convert the favorite icon byte array to a bitmap. + val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size) + + // Get a handle for the shared preferences. + val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) + + // Get the screenshot and theme preferences. + val allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false) + val darkTheme = sharedPreferences.getBoolean("dark_theme", false) + + // Use an alert dialog builder to create the dialog and set the style according to the theme. + val dialogBuilder = if (darkTheme) { + AlertDialog.Builder(context, R.style.PrivacyBrowserAlertDialogDark) + } else { + AlertDialog.Builder(context, R.style.PrivacyBrowserAlertDialogLight) + } + + // Set the title. + dialogBuilder.setTitle(R.string.create_folder) + + // Set the view. The parent view is null because it will be assigned by the alert dialog. + dialogBuilder.setView(activity!!.layoutInflater.inflate(R.layout.create_bookmark_folder_dialog, null)) + + // Set a listener on the cancel button. Using `null` as the listener closes the dialog without doing anything else. + dialogBuilder.setNegativeButton(R.string.cancel, null) + + // Set a listener on the create button. + dialogBuilder.setPositiveButton(R.string.create) { _: DialogInterface, _: Int -> + // Return the dialog fragment to the parent activity on create. + createBookmarkFolderListener.onCreateBookmarkFolder(this, favoriteIconBitmap) + } + + // Create an alert dialog from the builder. + val alertDialog = dialogBuilder.create() + + // Disable screenshots if not allowed. + if (!allowScreenshots) { + alertDialog.window!!.addFlags(WindowManager.LayoutParams.FLAG_SECURE) + } + + // Display the keyboard. + alertDialog.window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE) + + // The alert dialog must be shown before the content can be modified. + alertDialog.show() + + // Get handles for the views in the dialog. + val webPageIconImageView: ImageView = alertDialog.findViewById(R.id.create_folder_web_page_icon) + val folderNameEditText: EditText = alertDialog.findViewById(R.id.create_folder_name_edittext) + val createButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE) + + // Display the current favorite icon. + webPageIconImageView.setImageBitmap(favoriteIconBitmap) + + // Initially disable the create button. + createButton.isEnabled = false + + // Initialize the database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`. + val bookmarksDatabaseHelper = BookmarksDatabaseHelper(context, null, null, 0) + + // Enable the create button if the new folder name is unique. + folderNameEditText.addTextChangedListener(object: TextWatcher { + override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { + // Do nothing. + } + + override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { + // Do nothing. + } + + override fun afterTextChanged(editable: Editable) { + // Convert the current text to a string. + val folderName = editable.toString() + + // Check if a folder with the name already exists. + val folderExistsCursor = bookmarksDatabaseHelper.getFolder(folderName) + + // Enable the create button if the new folder name is not empty and doesn't already exist. + createButton.isEnabled = folderName.isNotEmpty() && (folderExistsCursor.count == 0) + } + }) + + // Set the enter key on the keyboard to create the folder from the edit text. + folderNameEditText.setOnKeyListener { _: View?, keyCode: Int, keyEvent: KeyEvent -> + // Check the key code, event, and button status. + if (keyEvent.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && createButton.isEnabled) { // The event is a key-down on the enter key and the create button is enabled. + // Trigger the create bookmark folder listener and return the dialog fragment to the parent activity. + createBookmarkFolderListener.onCreateBookmarkFolder(this, favoriteIconBitmap) + + // Manually dismiss the alert dialog. + alertDialog.dismiss() + + // Consume the event. + return@setOnKeyListener true + } else { // Some other key was pressed or the create button is disabled. + return@setOnKeyListener false + } + } + + // Return the alert dialog. + return alertDialog + } +} \ No newline at end of file diff --git a/app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateHomeScreenShortcutDialog.java b/app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateHomeScreenShortcutDialog.java deleted file mode 100644 index 8bb889ed..00000000 --- a/app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateHomeScreenShortcutDialog.java +++ /dev/null @@ -1,318 +0,0 @@ -/* - * Copyright © 2015-2019 Soren Stoutner . - * - * This file is part of Privacy Browser . - * - * Privacy Browser is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Privacy Browser is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Privacy Browser. If not, see . - */ - -package com.stoutner.privacybrowser.dialogs; - -import android.annotation.SuppressLint; -import android.app.Dialog; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.SharedPreferences; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.drawable.BitmapDrawable; -import android.graphics.drawable.Drawable; -import android.net.Uri; -import android.os.Bundle; -import android.preference.PreferenceManager; -import android.text.Editable; -import android.text.TextWatcher; -import android.view.KeyEvent; -import android.view.LayoutInflater; -import android.view.View; -import android.view.WindowManager; -import android.widget.Button; -import android.widget.EditText; -import android.widget.RadioButton; - -import androidx.annotation.NonNull; -import androidx.appcompat.app.AlertDialog; -import androidx.core.content.pm.ShortcutInfoCompat; -import androidx.core.content.pm.ShortcutManagerCompat; -import androidx.core.graphics.drawable.IconCompat; -import androidx.fragment.app.DialogFragment; - -import com.stoutner.privacybrowser.BuildConfig; -import com.stoutner.privacybrowser.R; - -import java.io.ByteArrayOutputStream; - -public class CreateHomeScreenShortcutDialog extends DialogFragment { - // Define the class variables. - private EditText shortcutNameEditText; - private EditText urlEditText; - private RadioButton openWithPrivacyBrowserRadioButton; - - // The public constructor. - public static CreateHomeScreenShortcutDialog createDialog(String shortcutName, String urlString, Bitmap favoriteIconBitmap) { - // Create a favorite icon byte array output stream. - ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream(); - - // Convert the favorite icon to a PNG and place it in the byte array output stream. `0` is for lossless compression (the only option for a PNG). - favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream); - - // Convert the byte array output stream to a byte array. - byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray(); - - // Create an arguments bundle. - Bundle argumentsBundle = new Bundle(); - - // Store the variables in the bundle. - argumentsBundle.putString("shortcut_name", shortcutName); - argumentsBundle.putString("url_string", urlString); - argumentsBundle.putByteArray("favorite_icon_byte_array", favoriteIconByteArray); - - // Create a new instance of the dialog. - CreateHomeScreenShortcutDialog createHomeScreenShortcutDialog = new CreateHomeScreenShortcutDialog(); - - // Add the bundle to the dialog. - createHomeScreenShortcutDialog.setArguments(argumentsBundle); - - // Return the new dialog. - return createHomeScreenShortcutDialog; - } - - // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`. - @SuppressLint("InflateParams") - @Override - @NonNull - public Dialog onCreateDialog(Bundle savedInstanceState) { - // Get the arguments. - Bundle arguments = getArguments(); - - // Remove the incorrect lint warning below that the arguments might be null. - assert arguments != null; - - // Get the strings from the arguments. - String initialShortcutName = arguments.getString("shortcut_name"); - String initialUrlString = arguments.getString("url_string"); - - // Get the favorite icon byte array. - byte[] favoriteIconByteArray = arguments.getByteArray("favorite_icon_byte_array"); - - // Remove the incorrect lint warning below that the favorite icon byte array might be null. - assert favoriteIconByteArray != null; - - // Convert the favorite icon byte array to a bitmap and store it in a class variable. - Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length); - - // Get a handle for the shared preferences. - SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext()); - - // Get the theme and screenshot preferences. - boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false); - boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false); - - // Remove the incorrect lint warning below that the layout inflater might be null. - assert getActivity() != null; - - // Get the activity's layout inflater. - LayoutInflater layoutInflater = getActivity().getLayoutInflater(); - - // Create a drawable version of the favorite icon. - Drawable favoriteIconDrawable = new BitmapDrawable(getResources(), favoriteIconBitmap); - - // Use a builder to create the alert dialog. - AlertDialog.Builder dialogBuilder; - - // Set the style according to the theme. - if (darkTheme) { - dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark); - } else { - dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight); - } - - // Set the title and icon. - dialogBuilder.setTitle(R.string.create_shortcut); - dialogBuilder.setIcon(favoriteIconDrawable); - - // Set the view. The parent view is null because it will be assigned by the alert dialog. - dialogBuilder.setView(layoutInflater.inflate(R.layout.create_home_screen_shortcut_dialog, null)); - - // Setup the close button. Using null closes the dialog without doing anything else. - dialogBuilder.setNegativeButton(R.string.cancel, null); - - // Set an `onClick` listener on the create button. - dialogBuilder.setPositiveButton(R.string.create, (DialogInterface dialog, int which) -> { - // Create the home screen shortcut. - createHomeScreenShortcut(favoriteIconBitmap); - }); - - // Create an alert dialog from the alert dialog builder. - final AlertDialog alertDialog = dialogBuilder.create(); - - // Remove the warning below that `getWindow()` might be null. - assert alertDialog.getWindow() != null; - - // Disable screenshots if not allowed. - if (allowScreenshots) { - alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE); - } - - // The alert dialog must be shown before the contents may be edited. - alertDialog.show(); - - // Get handles for the views. - shortcutNameEditText = alertDialog.findViewById(R.id.shortcut_name_edittext); - urlEditText = alertDialog.findViewById(R.id.url_edittext); - openWithPrivacyBrowserRadioButton = alertDialog.findViewById(R.id.open_with_privacy_browser_radiobutton); - Button createButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE); - - // Populate the edit texts. - shortcutNameEditText.setText(initialShortcutName); - urlEditText.setText(initialUrlString); - - // Add a text change listener to the shortcut name edit text. - shortcutNameEditText.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - // Do nothing. - } - - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - // Do nothing. - } - - @Override - public void afterTextChanged(Editable s) { - // Update the create button. - updateCreateButton(createButton); - } - }); - - // Add a text change listener to the URL edit text. - urlEditText.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - // Do nothing. - } - - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - // Do nothing. - } - - @Override - public void afterTextChanged(Editable s) { - // Update the create button. - updateCreateButton(createButton); - } - }); - - // Allow the enter key on the keyboard to create the shortcut when editing the name. - shortcutNameEditText.setOnKeyListener((View view, int keyCode, KeyEvent keyEvent) -> { - // Check to see if the enter key was pressed. - if ((keyEvent.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { - // Check the status of the create button. - if (createButton.isEnabled()) { // The create button is enabled. - // Create the home screen shortcut. - createHomeScreenShortcut(favoriteIconBitmap); - - // Manually dismiss the alert dialog. - alertDialog.dismiss(); - - // Consume the event. - return true; - } else { // The create button is disabled. - // Do not consume the event. - return false; - } - } else { // Some other key was pressed. - // Do not consume the event. - return false; - } - }); - - // Set the enter key on the keyboard to create the shortcut when editing the URL. - urlEditText.setOnKeyListener((View view, int keyCode, KeyEvent keyEvent) -> { - // Check to see if the enter key was pressed. - if ((keyEvent.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { - // Check the status of the create button. - if (createButton.isEnabled()) { // The create button is enabled. - // Create the home screen shortcut. - createHomeScreenShortcut(favoriteIconBitmap); - - // Manually dismiss the alert dialog. - alertDialog.dismiss(); - - // Consume the event. - return true; - } else { // The create button is disabled. - // Do not consume the event. - return false; - } - } else { // Some other key was pressed. - // Do not consume the event. - return false; - } - }); - - // Return the alert dialog. - return alertDialog; - } - - private void updateCreateButton(Button createButton) { - // Get the contents of the edit texts. - String shortcutName = shortcutNameEditText.getText().toString(); - String urlString = urlEditText.getText().toString(); - - // Enable the create button if both the shortcut name and the URL are not empty. - createButton.setEnabled(!shortcutName.isEmpty() && !urlString.isEmpty()); - } - - private void createHomeScreenShortcut(Bitmap favoriteIconBitmap) { - // Get a handle for the context. - Context context = getContext(); - - // Remove the incorrect lint warning below that the context might be null. - assert context != null; - - // Get the strings from the edit texts. - String shortcutName = shortcutNameEditText.getText().toString(); - String urlString = urlEditText.getText().toString(); - - // Convert the favorite icon bitmap to an icon. `IconCompat` must be used until the minimum API >= 26. - IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap); - - // Create a shortcut intent. - Intent shortcutIntent = new Intent(Intent.ACTION_VIEW); - - // Check to see if the shortcut should open up Privacy Browser explicitly. - if (openWithPrivacyBrowserRadioButton.isChecked()) { - // Set the current application ID as the target package. - shortcutIntent.setPackage(BuildConfig.APPLICATION_ID); - } - - // Add the URL to the intent. - shortcutIntent.setData(Uri.parse(urlString)); - - // Create a shortcut info builder. The shortcut name becomes the shortcut ID. - ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(context, shortcutName); - - // Add the required fields to the shortcut info builder. - shortcutInfoBuilder.setIcon(favoriteIcon); - shortcutInfoBuilder.setIntent(shortcutIntent); - shortcutInfoBuilder.setShortLabel(shortcutName); - - // Add the shortcut to the home screen. `ShortcutManagerCompat` can be switched to `ShortcutManager` once the minimum API >= 26. - ShortcutManagerCompat.requestPinShortcut(context, shortcutInfoBuilder.build(), null); - } -} \ No newline at end of file diff --git a/app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateHomeScreenShortcutDialog.kt b/app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateHomeScreenShortcutDialog.kt new file mode 100644 index 00000000..092d28c5 --- /dev/null +++ b/app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateHomeScreenShortcutDialog.kt @@ -0,0 +1,276 @@ +/* + * Copyright © 2015-2020 Soren Stoutner . + * + * This file is part of Privacy Browser . + * + * Privacy Browser is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Privacy Browser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Privacy Browser. If not, see . + */ + +package com.stoutner.privacybrowser.dialogs + +import android.annotation.SuppressLint +import android.app.Dialog +import android.content.DialogInterface +import android.content.Intent +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.graphics.drawable.BitmapDrawable +import android.graphics.drawable.Drawable +import android.net.Uri +import android.os.Bundle +import android.text.Editable +import android.text.TextWatcher +import android.view.KeyEvent +import android.view.View +import android.view.WindowManager +import android.widget.Button +import android.widget.EditText +import android.widget.RadioButton + +import androidx.appcompat.app.AlertDialog +import androidx.core.content.pm.ShortcutInfoCompat +import androidx.core.content.pm.ShortcutManagerCompat +import androidx.core.graphics.drawable.IconCompat +import androidx.fragment.app.DialogFragment +import androidx.preference.PreferenceManager + +import com.stoutner.privacybrowser.BuildConfig +import com.stoutner.privacybrowser.R + +import java.io.ByteArrayOutputStream + +class CreateHomeScreenShortcutDialog: DialogFragment() { + // Define the class variables. + private lateinit var shortcutNameEditText: EditText + private lateinit var urlEditText: EditText + private lateinit var openWithPrivacyBrowserRadioButton: RadioButton + + companion object { + // `@JvmStatic` will no longer be required once all the code has transitioned to Kotlin. Also, the function can then be moved out of a companion object and just become a package-level function. + @JvmStatic + fun createDialog(shortcutName: String, urlString: String, favoriteIconBitmap: Bitmap): CreateHomeScreenShortcutDialog { + // Create a favorite icon byte array output stream. + val favoriteIconByteArrayOutputStream = ByteArrayOutputStream() + + // Convert the favorite icon to a PNG and place it in the byte array output stream. `0` is for lossless compression (the only option for a PNG). + favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream) + + // Convert the byte array output stream to a byte array. + val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray() + + // Create an arguments bundle. + val argumentsBundle = Bundle() + + // Store the variables in the bundle. + argumentsBundle.putString("shortcut_name", shortcutName) + argumentsBundle.putString("url_string", urlString) + argumentsBundle.putByteArray("favorite_icon_byte_array", favoriteIconByteArray) + + // Create a new instance of the dialog. + val createHomeScreenShortcutDialog = CreateHomeScreenShortcutDialog() + + // Add the bundle to the dialog. + createHomeScreenShortcutDialog.arguments = argumentsBundle + + // Return the new dialog. + return createHomeScreenShortcutDialog + } + } + + // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`. + @SuppressLint("InflateParams") + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + // Get the arguments. + val arguments = arguments!! + + // Get the strings from the arguments. + val initialShortcutName = arguments.getString("shortcut_name") + val initialUrlString = arguments.getString("url_string") + + // Get the favorite icon byte array. + val favoriteIconByteArray = arguments.getByteArray("favorite_icon_byte_array")!! + + // Convert the favorite icon byte array to a bitmap. + val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size) + + // Get a handle for the shared preferences. + val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) + + // Get the theme and screenshot preferences. + val allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false) + val darkTheme = sharedPreferences.getBoolean("dark_theme", false) + + // Use an alert dialog builder to create the dialog and set the style according to the theme. + val dialogBuilder = if (darkTheme) { + AlertDialog.Builder(activity!!, R.style.PrivacyBrowserAlertDialogDark) + } else { + AlertDialog.Builder(activity!!, R.style.PrivacyBrowserAlertDialogLight) + } + + // Create a drawable version of the favorite icon. + val favoriteIconDrawable: Drawable = BitmapDrawable(resources, favoriteIconBitmap) + + // Set the title and icon. + dialogBuilder.setTitle(R.string.create_shortcut) + dialogBuilder.setIcon(favoriteIconDrawable) + + // Set the view. The parent view is null because it will be assigned by the alert dialog. + dialogBuilder.setView(activity!!.layoutInflater.inflate(R.layout.create_home_screen_shortcut_dialog, null)) + + // Set a listener on the close button. Using null closes the dialog without doing anything else. + dialogBuilder.setNegativeButton(R.string.cancel, null) + + // Set a listener on the create button. + dialogBuilder.setPositiveButton(R.string.create) { _: DialogInterface, _: Int -> + // Create the home screen shortcut. + createHomeScreenShortcut(favoriteIconBitmap) + } + + // Create an alert dialog from the alert dialog builder. + val alertDialog = dialogBuilder.create() + + // Disable screenshots if not allowed. + if (!allowScreenshots) { + alertDialog.window!!.addFlags(WindowManager.LayoutParams.FLAG_SECURE) + } + + // The alert dialog must be shown before the contents can be modified. + alertDialog.show() + + // Get handles for the views. + shortcutNameEditText = alertDialog.findViewById(R.id.shortcut_name_edittext)!! + urlEditText = alertDialog.findViewById(R.id.url_edittext)!! + openWithPrivacyBrowserRadioButton = alertDialog.findViewById(R.id.open_with_privacy_browser_radiobutton)!! + val createButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE) + + // Populate the edit texts. + shortcutNameEditText.setText(initialShortcutName) + urlEditText.setText(initialUrlString) + + // Add a text change listener to the shortcut name edit text. + shortcutNameEditText.addTextChangedListener(object: TextWatcher { + override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { + // Do nothing. + } + + override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { + // Do nothing. + } + + override fun afterTextChanged(s: Editable) { + // Update the create button. + updateCreateButton(createButton) + } + }) + + // Add a text change listener to the URL edit text. + urlEditText.addTextChangedListener(object : TextWatcher { + override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { + // Do nothing. + } + + override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { + // Do nothing. + } + + override fun afterTextChanged(s: Editable) { + // Update the create button. + updateCreateButton(createButton) + } + }) + + // Allow the enter key on the keyboard to create the shortcut when editing the name. + shortcutNameEditText.setOnKeyListener { _: View?, keyCode: Int, keyEvent: KeyEvent -> + // Check the key code, event, and button status. + if (keyEvent.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && createButton.isEnabled) { // The event is a key-down on the enter key and the create button is enabled. + // Create the home screen shortcut. + createHomeScreenShortcut(favoriteIconBitmap) + + // Manually dismiss the alert dialog. + alertDialog.dismiss() + + // Consume the event. + return@setOnKeyListener true + } else { // Some other key was pressed or the create button is disabled. + // Do not consume the event. + return@setOnKeyListener false + } + } + + // Set the enter key on the keyboard to create the shortcut when editing the URL. + urlEditText.setOnKeyListener { _: View?, keyCode: Int, keyEvent: KeyEvent -> + // Check the key code, event, and button status. + if (keyEvent.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && createButton.isEnabled) { // The event is a key-down on the enter key and the create button is enabled. + // Create the home screen shortcut. + createHomeScreenShortcut(favoriteIconBitmap) + + // Manually dismiss the alert dialog. + alertDialog.dismiss() + + // Consume the event. + return@setOnKeyListener true + } else { // Some other key was pressed or the create button is disabled. + // Do not consume the event. + return@setOnKeyListener false + } + } + + // Return the alert dialog. + return alertDialog + } + + private fun updateCreateButton(createButton: Button) { + // Get the contents of the edit texts. + val shortcutName = shortcutNameEditText.text.toString() + val urlString = urlEditText.text.toString() + + // Enable the create button if both the shortcut name and the URL are not empty. + createButton.isEnabled = shortcutName.isNotEmpty() && urlString.isNotEmpty() + } + + private fun createHomeScreenShortcut(favoriteIconBitmap: Bitmap) { + // Get a handle for the context. + val context = context!! + + // Get the strings from the edit texts. + val shortcutName = shortcutNameEditText.text.toString() + val urlString = urlEditText.text.toString() + + // Convert the favorite icon bitmap to an icon. `IconCompat` must be used until the minimum API >= 26. + val favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap) + + // Create a shortcut intent. + val shortcutIntent = Intent(Intent.ACTION_VIEW) + + // Check to see if the shortcut should open up Privacy Browser explicitly. + if (openWithPrivacyBrowserRadioButton.isChecked) { + // Set the current application ID as the target package. + shortcutIntent.setPackage(BuildConfig.APPLICATION_ID) + } + + // Add the URL to the intent. + shortcutIntent.data = Uri.parse(urlString) + + // Create a shortcut info builder. The shortcut name becomes the shortcut ID. + val shortcutInfoBuilder = ShortcutInfoCompat.Builder(context, shortcutName) + + // Add the required fields to the shortcut info builder. + shortcutInfoBuilder.setIcon(favoriteIcon) + shortcutInfoBuilder.setIntent(shortcutIntent) + shortcutInfoBuilder.setShortLabel(shortcutName) + + // Add the shortcut to the home screen. `ShortcutManagerCompat` can be switched to `ShortcutManager` once the minimum API >= 26. + ShortcutManagerCompat.requestPinShortcut(context, shortcutInfoBuilder.build(), null) + } +} \ No newline at end of file diff --git a/app/src/main/java/com/stoutner/privacybrowser/dialogs/SaveDialog.java b/app/src/main/java/com/stoutner/privacybrowser/dialogs/SaveDialog.java index 19ff43ce..71eecb15 100644 --- a/app/src/main/java/com/stoutner/privacybrowser/dialogs/SaveDialog.java +++ b/app/src/main/java/com/stoutner/privacybrowser/dialogs/SaveDialog.java @@ -226,45 +226,9 @@ public class SaveDialog extends DialogFragment { // Set the file size text view. fileSizeTextView.setText(fileSizeString); - // Create a file name string. - String fileName = ""; - - // Set the file name according to the type. - switch (saveType) { - case StoragePermissionDialog.SAVE_URL: - // Use the file name from the content disposition. - fileName = contentDispositionFileNameString; - break; - - case StoragePermissionDialog.SAVE_AS_ARCHIVE: - // Use an archive name ending in `.mht`. - fileName = getString(R.string.webpage_mht); - break; - - case StoragePermissionDialog.SAVE_AS_IMAGE: - // Use a file name ending in `.png`. - fileName = getString(R.string.webpage_png); - break; - } - - // Save the file name as the default file name. This must be final to be used in the lambda below. - final String defaultFileName = fileName; - - // Instantiate the download location helper. - DownloadLocationHelper downloadLocationHelper = new DownloadLocationHelper(); - - // Get the default file path. - String defaultFilePath = downloadLocationHelper.getDownloadLocation(context) + "/" + defaultFileName; - - // Populate the file name edit text. This must be done before the text change listener is created below so that the file size isn't requested again. - fileNameEditText.setText(defaultFilePath); - - // Move the cursor to the end of the default file path. - fileNameEditText.setSelection(defaultFilePath.length()); - // Modify the layout based on the save type. if (saveType == StoragePermissionDialog.SAVE_URL) { // A URL is being saved. - // Populate the URL edit text. + // Populate the URL edit text. This must be done before the text change listener is created below so that the file size isn't requested again. urlEditText.setText(urlString); // Update the file size and the status of the save button when the URL changes. @@ -345,6 +309,42 @@ public class SaveDialog extends DialogFragment { } }); + // Create a file name string. + String fileName = ""; + + // Set the file name according to the type. + switch (saveType) { + case StoragePermissionDialog.SAVE_URL: + // Use the file name from the content disposition. + fileName = contentDispositionFileNameString; + break; + + case StoragePermissionDialog.SAVE_AS_ARCHIVE: + // Use an archive name ending in `.mht`. + fileName = getString(R.string.webpage_mht); + break; + + case StoragePermissionDialog.SAVE_AS_IMAGE: + // Use a file name ending in `.png`. + fileName = getString(R.string.webpage_png); + break; + } + + // Save the file name as the default file name. This must be final to be used in the lambda below. + final String defaultFileName = fileName; + + // Instantiate the download location helper. + DownloadLocationHelper downloadLocationHelper = new DownloadLocationHelper(); + + // Get the default file path. + String defaultFilePath = downloadLocationHelper.getDownloadLocation(context) + "/" + defaultFileName; + + // Populate the file name edit text. + fileNameEditText.setText(defaultFilePath); + + // Move the cursor to the end of the default file path. + fileNameEditText.setSelection(defaultFilePath.length()); + // Handle clicks on the browse button. browseButton.setOnClickListener((View view) -> { // Create the file picker intent. diff --git a/app/src/main/res/drawable/dom_storage_cleared_dark.xml b/app/src/main/res/drawable/dom_storage_cleared_dark.xml index 6c806ee1..1fb6e498 100644 --- a/app/src/main/res/drawable/dom_storage_cleared_dark.xml +++ b/app/src/main/res/drawable/dom_storage_cleared_dark.xml @@ -1,4 +1,4 @@ - + - + diff --git a/app/src/main/res/drawable/dom_storage_cleared_light.xml b/app/src/main/res/drawable/dom_storage_cleared_light.xml index 066d5d80..117304b9 100644 --- a/app/src/main/res/drawable/dom_storage_cleared_light.xml +++ b/app/src/main/res/drawable/dom_storage_cleared_light.xml @@ -1,4 +1,4 @@ - + - + diff --git a/app/src/main/res/drawable/dom_storage_disabled_dark.xml b/app/src/main/res/drawable/dom_storage_disabled_dark.xml index 23113b42..0e2b0034 100644 --- a/app/src/main/res/drawable/dom_storage_disabled_dark.xml +++ b/app/src/main/res/drawable/dom_storage_disabled_dark.xml @@ -1,4 +1,4 @@ - + - + diff --git a/app/src/main/res/drawable/dom_storage_disabled_light.xml b/app/src/main/res/drawable/dom_storage_disabled_light.xml index 76340fc7..e49b639c 100644 --- a/app/src/main/res/drawable/dom_storage_disabled_light.xml +++ b/app/src/main/res/drawable/dom_storage_disabled_light.xml @@ -1,4 +1,4 @@ - + - + diff --git a/app/src/main/res/drawable/dom_storage_enabled.xml b/app/src/main/res/drawable/dom_storage_enabled.xml index 3156ec18..bc59cd95 100644 --- a/app/src/main/res/drawable/dom_storage_enabled.xml +++ b/app/src/main/res/drawable/dom_storage_enabled.xml @@ -1,4 +1,4 @@ - + - + diff --git a/app/src/main/res/drawable/dom_storage_ghosted_dark.xml b/app/src/main/res/drawable/dom_storage_ghosted_dark.xml index 25eb6409..9f2419f9 100644 --- a/app/src/main/res/drawable/dom_storage_ghosted_dark.xml +++ b/app/src/main/res/drawable/dom_storage_ghosted_dark.xml @@ -1,4 +1,4 @@ - + - + diff --git a/app/src/main/res/drawable/dom_storage_ghosted_light.xml b/app/src/main/res/drawable/dom_storage_ghosted_light.xml index 2bc15534..c680a7f1 100644 --- a/app/src/main/res/drawable/dom_storage_ghosted_light.xml +++ b/app/src/main/res/drawable/dom_storage_ghosted_light.xml @@ -1,4 +1,4 @@ - + - + diff --git a/app/src/main/res/drawable/dom_storage_warning.xml b/app/src/main/res/drawable/dom_storage_warning.xml index 79638016..eb42e0fa 100644 --- a/app/src/main/res/drawable/dom_storage_warning.xml +++ b/app/src/main/res/drawable/dom_storage_warning.xml @@ -1,4 +1,4 @@ - + - + diff --git a/app/src/main/res/drawable/domains.xml b/app/src/main/res/drawable/domains_dark.xml similarity index 74% rename from app/src/main/res/drawable/domains.xml rename to app/src/main/res/drawable/domains_dark.xml index fc599462..4f9557e5 100644 --- a/app/src/main/res/drawable/domains.xml +++ b/app/src/main/res/drawable/domains_dark.xml @@ -1,4 +1,4 @@ - + - + diff --git a/app/src/main/res/drawable/domains_light.xml b/app/src/main/res/drawable/domains_light.xml new file mode 100644 index 00000000..4e41917d --- /dev/null +++ b/app/src/main/res/drawable/domains_light.xml @@ -0,0 +1,18 @@ + + + + + + + + diff --git a/app/src/main/res/layout/domain_settings_fragment.xml b/app/src/main/res/layout/domain_settings_fragment.xml index 30cbf066..fbb502a7 100644 --- a/app/src/main/res/layout/domain_settings_fragment.xml +++ b/app/src/main/res/layout/domain_settings_fragment.xml @@ -52,7 +52,7 @@ android:layout_marginEnd="10dp" android:layout_marginBottom="12dp" android:layout_gravity="bottom" - android:src="@drawable/domains" + android:src="@drawable/domains_light" android:tint="?attr/domainSettingsIconTintColor" tools:ignore="contentDescription" /> diff --git a/app/src/main/res/menu/webview_navigation_menu.xml b/app/src/main/res/menu/webview_navigation_menu.xml index 04cae079..9b8726b5 100644 --- a/app/src/main/res/menu/webview_navigation_menu.xml +++ b/app/src/main/res/menu/webview_navigation_menu.xml @@ -86,7 +86,7 @@