2 * Copyright © 2016-2021 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.LinearLayout
38 import android.widget.RadioButton
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 // Define 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 // Declare the class variables.
55 private lateinit var editBookmarkFolderListener: EditBookmarkFolderListener
56 private lateinit var bookmarksDatabaseHelper: BookmarksDatabaseHelper
57 private lateinit var currentFolderName: String
59 // Declare the class views.
60 private lateinit var currentIconRadioButton: RadioButton
61 private lateinit var folderNameEditText: EditText
62 private lateinit var saveButton: Button
64 // The public interface is used to send information back to the parent activity.
65 interface EditBookmarkFolderListener {
66 fun onSaveBookmarkFolder(dialogFragment: DialogFragment, selectedFolderDatabaseId: Int, favoriteIconBitmap: Bitmap)
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.
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 the alert dialog.
137 dialogBuilder.setView(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 currentIconLinearLayout = alertDialog.findViewById<LinearLayout>(R.id.current_icon_linearlayout)!!
167 currentIconRadioButton = alertDialog.findViewById(R.id.current_icon_radiobutton)!!
168 val currentIconImageView = alertDialog.findViewById<ImageView>(R.id.current_icon_imageview)!!
169 val defaultIconLinearLayout = alertDialog.findViewById<LinearLayout>(R.id.default_icon_linearlayout)!!
170 val defaultIconRadioButton = alertDialog.findViewById<RadioButton>(R.id.default_icon_radiobutton)!!
171 val webpageFavoriteIconLinearLayout = alertDialog.findViewById<LinearLayout>(R.id.webpage_favorite_icon_linearlayout)!!
172 val webpageFavoriteIconRadioButton = alertDialog.findViewById<RadioButton>(R.id.webpage_favorite_icon_radiobutton)!!
173 val webpageFavoriteIconImageView = alertDialog.findViewById<ImageView>(R.id.webpage_favorite_icon_imageview)!!
174 folderNameEditText = alertDialog.findViewById(R.id.folder_name_edittext)!!
175 saveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
177 // Get the current favorite icon byte array from the cursor.
178 val currentIconByteArray = folderCursor.getBlob(folderCursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON))
180 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
181 val currentIconBitmap = BitmapFactory.decodeByteArray(currentIconByteArray, 0, currentIconByteArray.size)
183 // Display the current icon bitmap.
184 currentIconImageView.setImageBitmap(currentIconBitmap)
186 // Set the webpage favorite icon bitmap.
187 webpageFavoriteIconImageView.setImageBitmap(favoriteIconBitmap)
189 // Get the current folder name.
190 currentFolderName = folderCursor.getString(folderCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME))
192 // Display the current folder name.
193 folderNameEditText.setText(currentFolderName)
195 // Initially disable the save button.
196 saveButton.isEnabled = false
198 // Set the radio button listeners. These perform a click on the linear layout, which contains the necessary logic.
199 currentIconRadioButton.setOnClickListener { currentIconLinearLayout.performClick() }
200 defaultIconRadioButton.setOnClickListener { defaultIconLinearLayout.performClick() }
201 webpageFavoriteIconRadioButton.setOnClickListener { webpageFavoriteIconLinearLayout.performClick() }
203 // Set the current icon linear layout click listener.
204 currentIconLinearLayout.setOnClickListener {
205 // Check the current icon radio button.
206 currentIconRadioButton.isChecked = true
208 // Uncheck the other radio buttons.
209 defaultIconRadioButton.isChecked = false
210 webpageFavoriteIconRadioButton.isChecked = false
212 // Update the save button.
216 // Set the default icon linear layout click listener.
217 defaultIconLinearLayout.setOnClickListener {
218 // Check the default icon radio button.
219 defaultIconRadioButton.isChecked = true
221 // Uncheck the other radio buttons.
222 currentIconRadioButton.isChecked = false
223 webpageFavoriteIconRadioButton.isChecked = false
225 // Update the save button.
229 // Set the webpage favorite icon linear layout click listener.
230 webpageFavoriteIconLinearLayout.setOnClickListener {
231 // Check the webpage favorite icon radio button.
232 webpageFavoriteIconRadioButton.isChecked = true
234 // Uncheck the other radio buttons.
235 currentIconRadioButton.isChecked = false
236 defaultIconRadioButton.isChecked = false
238 // Update the save button.
242 // Update the status of the save button when the folder name is changed.
243 folderNameEditText.addTextChangedListener(object: TextWatcher {
244 override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
248 override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
252 override fun afterTextChanged(s: Editable) {
253 // Update the save button.
258 // Allow the enter key on the keyboard to save the bookmark from the edit bookmark name edit text.
259 folderNameEditText.setOnKeyListener { _: View?, keyCode: Int, event: KeyEvent ->
260 // Check the key code, event, and button status.
261 if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && saveButton.isEnabled) { // The enter key was pressed and the save button is enabled.
262 // Trigger the listener and return the dialog fragment to the parent activity.
263 editBookmarkFolderListener.onSaveBookmarkFolder(this, selectedFolderDatabaseId, favoriteIconBitmap)
265 // Manually dismiss the the alert dialog.
266 alertDialog.dismiss()
268 // Consume the event.
269 return@setOnKeyListener true
270 } else { // If any other key was pressed, or if the save button is currently disabled, do not consume the event.
271 return@setOnKeyListener false
275 // Return the alert dialog.
279 private fun updateSaveButton() {
280 // Get the new folder name.
281 val newFolderName = folderNameEditText.text.toString()
283 // Get a cursor for the new folder name if it exists.
284 val folderExistsCursor = bookmarksDatabaseHelper.getFolder(newFolderName)
286 // Is the new folder name empty?
287 val folderNameEmpty = newFolderName.isEmpty()
289 // Does the folder name already exist?
290 val folderNameAlreadyExists = (newFolderName != currentFolderName) && folderExistsCursor.count > 0
292 // Has the folder been renamed?
293 val folderRenamed = (newFolderName != currentFolderName) && !folderNameAlreadyExists
295 // Has the favorite icon changed?
296 val iconChanged = !currentIconRadioButton.isChecked && !folderNameAlreadyExists
298 // Enable the save button if something has been edited and the new folder name is valid.
299 saveButton.isEnabled = !folderNameEmpty && (folderRenamed || iconChanged)