2 * Copyright © 2016-2022 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser Android <https://www.stoutner.com/privacy-browser-android>.
6 * Privacy Browser Android 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 Android 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 Android. If not, see <http://www.gnu.org/licenses/>.
20 package com.stoutner.privacybrowser.dialogs
22 import android.app.Dialog
23 import android.content.Context
24 import android.content.DialogInterface
25 import android.graphics.Bitmap
26 import android.graphics.BitmapFactory
27 import android.os.Bundle
28 import android.text.Editable
29 import android.text.TextWatcher
30 import android.view.KeyEvent
31 import android.view.View
32 import android.view.WindowManager
33 import android.widget.Button
34 import android.widget.EditText
35 import android.widget.ImageView
36 import android.widget.LinearLayout
37 import android.widget.RadioButton
39 import androidx.appcompat.app.AlertDialog
40 import androidx.fragment.app.DialogFragment
41 import androidx.preference.PreferenceManager
43 import com.stoutner.privacybrowser.R
44 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper
46 import java.io.ByteArrayOutputStream
48 // Define the class constants.
49 private const val DATABASE_ID = "database_id"
50 private const val FAVORITE_ICON_BYTE_ARRAY = "favorite_icon_byte_array"
52 class EditBookmarkFolderDialog : DialogFragment() {
53 // Declare the class variables.
54 private lateinit var editBookmarkFolderListener: EditBookmarkFolderListener
55 private lateinit var bookmarksDatabaseHelper: BookmarksDatabaseHelper
56 private lateinit var currentFolderName: String
58 // Declare the class views.
59 private lateinit var currentIconRadioButton: RadioButton
60 private lateinit var folderNameEditText: EditText
61 private lateinit var saveButton: Button
63 // The public interface is used to send information back to the parent activity.
64 interface EditBookmarkFolderListener {
65 fun onSaveBookmarkFolder(dialogFragment: DialogFragment, selectedFolderDatabaseId: Int, favoriteIconBitmap: Bitmap)
68 override fun onAttach(context: Context) {
69 // Run the default commands.
70 super.onAttach(context)
72 // Get a handle for the edit bookmark folder listener from the launching context.
73 editBookmarkFolderListener = context as EditBookmarkFolderListener
77 // `@JvmStatic` will no longer be required once all the code has transitioned to Kotlin.
79 fun folderDatabaseId(databaseId: Int, favoriteIconBitmap: Bitmap): EditBookmarkFolderDialog {
80 // Create a favorite icon byte array output stream.
81 val favoriteIconByteArrayOutputStream = ByteArrayOutputStream()
83 // 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).
84 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream)
86 // Convert the byte array output stream to a byte array.
87 val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray()
89 // Create an arguments bundle
90 val argumentsBundle = Bundle()
92 // Store the variables in the bundle.
93 argumentsBundle.putInt(DATABASE_ID, databaseId)
94 argumentsBundle.putByteArray(FAVORITE_ICON_BYTE_ARRAY, favoriteIconByteArray)
96 // Create a new instance of the dialog.
97 val editBookmarkFolderDialog = EditBookmarkFolderDialog()
99 // Add the arguments bundle to the dialog.
100 editBookmarkFolderDialog.arguments = argumentsBundle
102 // Return the new dialog.
103 return editBookmarkFolderDialog
107 override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
108 // Get a handle for the arguments.
109 val arguments = requireArguments()
111 // Get the variables from the arguments.
112 val selectedFolderDatabaseId = arguments.getInt(DATABASE_ID)
113 val favoriteIconByteArray = arguments.getByteArray(FAVORITE_ICON_BYTE_ARRAY)!!
115 // Convert the favorite icon byte array to a bitmap.
116 val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size)
118 // Initialize the database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
119 bookmarksDatabaseHelper = BookmarksDatabaseHelper(context, null, null, 0)
121 // Get a cursor with the selected folder.
122 val folderCursor = bookmarksDatabaseHelper.getBookmark(selectedFolderDatabaseId)
124 // Move the cursor to the first position.
125 folderCursor.moveToFirst()
127 // Use an alert dialog builder to create the alert dialog.
128 val dialogBuilder = AlertDialog.Builder(requireContext(), R.style.PrivacyBrowserAlertDialog)
131 dialogBuilder.setTitle(R.string.edit_folder)
134 dialogBuilder.setView(R.layout.edit_bookmark_folder_dialog)
136 // Set the cancel button listener. Using `null` as the listener closes the dialog without doing anything else.
137 dialogBuilder.setNegativeButton(R.string.cancel, null)
139 // Set the save button listener.
140 dialogBuilder.setPositiveButton(R.string.save) { _: DialogInterface?, _: Int ->
141 // Return the dialog fragment to the parent activity on save.
142 editBookmarkFolderListener.onSaveBookmarkFolder(this, selectedFolderDatabaseId, favoriteIconBitmap)
145 // Create an alert dialog from the alert dialog builder.
146 val alertDialog = dialogBuilder.create()
148 // Get a handle for the shared preferences.
149 val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
151 // Get the screenshot preference.
152 val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false)
154 // Disable screenshots if not allowed.
155 if (!allowScreenshots) {
156 alertDialog.window!!.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
159 // The alert dialog must be shown before items in the layout can be modified.
162 // Get handles for the views in the alert dialog.
163 val currentIconLinearLayout = alertDialog.findViewById<LinearLayout>(R.id.current_icon_linearlayout)!!
164 currentIconRadioButton = alertDialog.findViewById(R.id.current_icon_radiobutton)!!
165 val currentIconImageView = alertDialog.findViewById<ImageView>(R.id.current_icon_imageview)!!
166 val defaultIconLinearLayout = alertDialog.findViewById<LinearLayout>(R.id.default_icon_linearlayout)!!
167 val defaultIconRadioButton = alertDialog.findViewById<RadioButton>(R.id.default_icon_radiobutton)!!
168 val webpageFavoriteIconLinearLayout = alertDialog.findViewById<LinearLayout>(R.id.webpage_favorite_icon_linearlayout)!!
169 val webpageFavoriteIconRadioButton = alertDialog.findViewById<RadioButton>(R.id.webpage_favorite_icon_radiobutton)!!
170 val webpageFavoriteIconImageView = alertDialog.findViewById<ImageView>(R.id.webpage_favorite_icon_imageview)!!
171 folderNameEditText = alertDialog.findViewById(R.id.folder_name_edittext)!!
172 saveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
174 // Get the current favorite icon byte array from the cursor.
175 val currentIconByteArray = folderCursor.getBlob(folderCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.FAVORITE_ICON))
177 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
178 val currentIconBitmap = BitmapFactory.decodeByteArray(currentIconByteArray, 0, currentIconByteArray.size)
180 // Display the current icon bitmap.
181 currentIconImageView.setImageBitmap(currentIconBitmap)
183 // Set the webpage favorite icon bitmap.
184 webpageFavoriteIconImageView.setImageBitmap(favoriteIconBitmap)
186 // Get the current folder name.
187 currentFolderName = folderCursor.getString(folderCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME))
189 // Display the current folder name.
190 folderNameEditText.setText(currentFolderName)
192 // Initially disable the save button.
193 saveButton.isEnabled = false
195 // Set the radio button listeners. These perform a click on the linear layout, which contains the necessary logic.
196 currentIconRadioButton.setOnClickListener { currentIconLinearLayout.performClick() }
197 defaultIconRadioButton.setOnClickListener { defaultIconLinearLayout.performClick() }
198 webpageFavoriteIconRadioButton.setOnClickListener { webpageFavoriteIconLinearLayout.performClick() }
200 // Set the current icon linear layout click listener.
201 currentIconLinearLayout.setOnClickListener {
202 // Check the current icon radio button.
203 currentIconRadioButton.isChecked = true
205 // Uncheck the other radio buttons.
206 defaultIconRadioButton.isChecked = false
207 webpageFavoriteIconRadioButton.isChecked = false
209 // Update the save button.
213 // Set the default icon linear layout click listener.
214 defaultIconLinearLayout.setOnClickListener {
215 // Check the default icon radio button.
216 defaultIconRadioButton.isChecked = true
218 // Uncheck the other radio buttons.
219 currentIconRadioButton.isChecked = false
220 webpageFavoriteIconRadioButton.isChecked = false
222 // Update the save button.
226 // Set the webpage favorite icon linear layout click listener.
227 webpageFavoriteIconLinearLayout.setOnClickListener {
228 // Check the webpage favorite icon radio button.
229 webpageFavoriteIconRadioButton.isChecked = true
231 // Uncheck the other radio buttons.
232 currentIconRadioButton.isChecked = false
233 defaultIconRadioButton.isChecked = false
235 // Update the save button.
239 // Update the status of the save button when the folder name is changed.
240 folderNameEditText.addTextChangedListener(object: TextWatcher {
241 override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
245 override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
249 override fun afterTextChanged(s: Editable) {
250 // Update the save button.
255 // Allow the enter key on the keyboard to save the bookmark from the edit bookmark name edit text.
256 folderNameEditText.setOnKeyListener { _: View?, keyCode: Int, event: KeyEvent ->
257 // Check the key code, event, and button status.
258 if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && saveButton.isEnabled) { // The enter key was pressed and the save button is enabled.
259 // Trigger the listener and return the dialog fragment to the parent activity.
260 editBookmarkFolderListener.onSaveBookmarkFolder(this, selectedFolderDatabaseId, favoriteIconBitmap)
262 // Manually dismiss the the alert dialog.
263 alertDialog.dismiss()
265 // Consume the event.
266 return@setOnKeyListener true
267 } else { // If any other key was pressed, or if the save button is currently disabled, do not consume the event.
268 return@setOnKeyListener false
272 // Return the alert dialog.
276 private fun updateSaveButton() {
277 // Get the new folder name.
278 val newFolderName = folderNameEditText.text.toString()
280 // Get a cursor for the new folder name if it exists.
281 val folderExistsCursor = bookmarksDatabaseHelper.getFolder(newFolderName)
283 // Is the new folder name empty?
284 val folderNameEmpty = newFolderName.isEmpty()
286 // Does the folder name already exist?
287 val folderNameAlreadyExists = (newFolderName != currentFolderName) && folderExistsCursor.count > 0
289 // Has the folder been renamed?
290 val folderRenamed = (newFolderName != currentFolderName) && !folderNameAlreadyExists
292 // Has the favorite icon changed?
293 val iconChanged = !currentIconRadioButton.isChecked && !folderNameAlreadyExists
295 // Enable the save button if something has been edited and the new folder name is valid.
296 saveButton.isEnabled = !folderNameEmpty && (folderRenamed || iconChanged)