2 * Copyright © 2016-2020 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
6 * Privacy Browser is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * Privacy Browser is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with Privacy Browser. If not, see <http://www.gnu.org/licenses/>.
20 package com.stoutner.privacybrowser.dialogs
22 import android.annotation.SuppressLint
23 import android.app.Dialog
24 import android.content.Context
25 import android.content.DialogInterface
26 import android.graphics.Bitmap
27 import android.graphics.BitmapFactory
28 import android.os.Bundle
29 import android.text.Editable
30 import android.text.TextWatcher
31 import android.view.KeyEvent
32 import android.view.View
33 import android.view.WindowManager
34 import android.widget.Button
35 import android.widget.EditText
36 import android.widget.ImageView
37 import android.widget.RadioButton
38 import android.widget.RadioGroup
40 import androidx.appcompat.app.AlertDialog
41 import androidx.fragment.app.DialogFragment
42 import androidx.preference.PreferenceManager
44 import com.stoutner.privacybrowser.R
45 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper
47 import java.io.ByteArrayOutputStream
49 // Declare the class constants.
50 private const val DATABASE_ID = "database_id"
51 private const val FAVORITE_ICON_BYTE_ARRAY = "favorite_icon_byte_array"
53 class EditBookmarkFolderDialog: DialogFragment() {
54 // The public interface is used to send information back to the parent activity.
55 interface EditBookmarkFolderListener {
56 fun onSaveBookmarkFolder(dialogFragment: DialogFragment?, selectedFolderDatabaseId: Int, favoriteIconBitmap: Bitmap?)
59 // Declare the class variables.
60 private lateinit var editBookmarkFolderListener: EditBookmarkFolderListener
61 private lateinit var bookmarksDatabaseHelper: BookmarksDatabaseHelper
62 private lateinit var currentFolderName: String
64 // Declare the class views.
65 private lateinit var currentIconRadioButton: RadioButton
66 private lateinit var folderNameEditText: EditText
67 private lateinit var saveButton: Button
69 override fun onAttach(context: Context) {
70 // Run the default commands.
71 super.onAttach(context)
73 // Get a handle for the edit bookmark folder listener from the launching context.
74 editBookmarkFolderListener = context as EditBookmarkFolderListener
78 // `@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.
80 fun folderDatabaseId(databaseId: Int, favoriteIconBitmap: Bitmap): EditBookmarkFolderDialog {
81 // Create a favorite icon byte array output stream.
82 val favoriteIconByteArrayOutputStream = ByteArrayOutputStream()
84 // 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).
85 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream)
87 // Convert the byte array output stream to a byte array.
88 val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray()
90 // Create an arguments bundle
91 val argumentsBundle = Bundle()
93 // Store the variables in the bundle.
94 argumentsBundle.putInt(DATABASE_ID, databaseId)
95 argumentsBundle.putByteArray(FAVORITE_ICON_BYTE_ARRAY, favoriteIconByteArray)
97 // Create a new instance of the dialog.
98 val editBookmarkFolderDialog = EditBookmarkFolderDialog()
100 // Add the arguments bundle to the dialog.
101 editBookmarkFolderDialog.arguments = argumentsBundle
103 // Return the new dialog.
104 return editBookmarkFolderDialog
108 // `@SuppressLint("InflateParams")` removes the warning about using `null` as the parent view group when inflating the alert dialog.
109 @SuppressLint("InflateParams")
110 override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
111 // Get a handle for the arguments.
112 val arguments = requireArguments()
114 // Get the variables from the arguments.
115 val selectedFolderDatabaseId = arguments.getInt(DATABASE_ID)
116 val favoriteIconByteArray = arguments.getByteArray(FAVORITE_ICON_BYTE_ARRAY)!!
118 // Convert the favorite icon byte array to a bitmap.
119 val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size)
121 // Initialize the database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
122 bookmarksDatabaseHelper = BookmarksDatabaseHelper(context, null, null, 0)
124 // Get a cursor with the selected folder.
125 val folderCursor = bookmarksDatabaseHelper.getBookmark(selectedFolderDatabaseId)
127 // Move the cursor to the first position.
128 folderCursor.moveToFirst()
130 // Use an alert dialog builder to create the alert dialog.
131 val dialogBuilder = AlertDialog.Builder(requireContext(), R.style.PrivacyBrowserAlertDialog)
134 dialogBuilder.setTitle(R.string.edit_folder)
136 // Set the view. The parent view is `null` because it will be assigned by `AlertDialog`.
137 dialogBuilder.setView(requireActivity().layoutInflater.inflate(R.layout.edit_bookmark_folder_dialog, null))
139 // Set the cancel button listener. Using `null` as the listener closes the dialog without doing anything else.
140 dialogBuilder.setNegativeButton(R.string.cancel, null)
142 // Set the save button listener.
143 dialogBuilder.setPositiveButton(R.string.save) { _: DialogInterface?, _: Int ->
144 // Return the dialog fragment to the parent activity on save.
145 editBookmarkFolderListener.onSaveBookmarkFolder(this, selectedFolderDatabaseId, favoriteIconBitmap)
148 // Create an alert dialog from the alert dialog builder.
149 val alertDialog = dialogBuilder.create()
151 // Get a handle for the shared preferences.
152 val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
154 // Get the screenshot preference.
155 val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false)
157 // Disable screenshots if not allowed.
158 if (!allowScreenshots) {
159 alertDialog.window!!.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
162 // The alert dialog must be shown before items in the layout can be modified.
165 // Get handles for the views in the alert dialog.
166 val iconRadioGroup = alertDialog.findViewById<RadioGroup>(R.id.edit_folder_icon_radio_group)!!
167 currentIconRadioButton = alertDialog.findViewById(R.id.edit_folder_current_icon_radiobutton)!!
168 val currentIconImageView = alertDialog.findViewById<ImageView>(R.id.edit_folder_current_icon_imageview)!!
169 val webPageFavoriteIconImageView = alertDialog.findViewById<ImageView>(R.id.edit_folder_web_page_favorite_icon_imageview)!!
170 folderNameEditText = alertDialog.findViewById(R.id.edit_folder_name_edittext)!!
171 saveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
173 // Get the current favorite icon byte array from the cursor.
174 val currentIconByteArray = folderCursor.getBlob(folderCursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON))
176 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
177 val currentIconBitmap = BitmapFactory.decodeByteArray(currentIconByteArray, 0, currentIconByteArray.size)
179 // Display the current icon bitmap.
180 currentIconImageView.setImageBitmap(currentIconBitmap)
182 // Set the new favorite icon bitmap.
183 webPageFavoriteIconImageView.setImageBitmap(favoriteIconBitmap)
185 // Get the current folder name.
186 currentFolderName = folderCursor.getString(folderCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME))
188 // Display the current folder name.
189 folderNameEditText.setText(currentFolderName)
191 // Initially disable the save button.
192 saveButton.isEnabled = false
194 // Update the status of the save button when the folder name is changed.
195 folderNameEditText.addTextChangedListener(object: TextWatcher {
196 override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
200 override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
204 override fun afterTextChanged(s: Editable) {
205 // Update the save button.
210 // Update the status of the save button when the icon is changed.
211 iconRadioGroup.setOnCheckedChangeListener { _: RadioGroup?, _: Int ->
212 // Update the save button.
216 // Allow the enter key on the keyboard to save the bookmark from the edit bookmark name edit text.
217 folderNameEditText.setOnKeyListener { _: View?, keyCode: Int, event: KeyEvent ->
218 // Check the key code, event, and button status.
219 if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && saveButton.isEnabled) { // The enter key was pressed and the save button is enabled.
220 // Trigger the listener and return the dialog fragment to the parent activity.
221 editBookmarkFolderListener.onSaveBookmarkFolder(this, selectedFolderDatabaseId, favoriteIconBitmap)
223 // Manually dismiss the the alert dialog.
224 alertDialog.dismiss()
226 // Consume the event.
227 return@setOnKeyListener true
228 } else { // If any other key was pressed, or if the save button is currently disabled, do not consume the event.
229 return@setOnKeyListener false
233 // Return the alert dialog.
237 private fun updateSaveButton() {
238 // Get the new folder name.
239 val newFolderName = folderNameEditText.text.toString()
241 // Get a cursor for the new folder name if it exists.
242 val folderExistsCursor = bookmarksDatabaseHelper.getFolder(newFolderName)
244 // Is the new folder name empty?
245 val folderNameEmpty = newFolderName.isEmpty()
247 // Does the folder name already exist?
248 val folderNameAlreadyExists = (newFolderName != currentFolderName) && folderExistsCursor.count > 0
250 // Has the folder been renamed?
251 val folderRenamed = (newFolderName != currentFolderName) && !folderNameAlreadyExists
253 // Has the favorite icon changed?
254 val iconChanged = !currentIconRadioButton.isChecked && !folderNameAlreadyExists
256 // Enable the save button if something has been edited and the new folder name is valid.
257 saveButton.isEnabled = !folderNameEmpty && (folderRenamed || iconChanged)