2 * Copyright © 2016-2023 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.BOOKMARK_NAME
45 import com.stoutner.privacybrowser.helpers.BOOKMARK_URL
46 import com.stoutner.privacybrowser.helpers.FAVORITE_ICON
47 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper
49 import java.io.ByteArrayOutputStream
51 // Define the class constants.
52 private const val DATABASE_ID = "database_id"
53 private const val FAVORITE_ICON_BYTE_ARRAY = "favorite_icon_byte_array"
55 class EditBookmarkDialog : DialogFragment() {
57 fun editBookmark(databaseId: Int, favoriteIconBitmap: Bitmap): EditBookmarkDialog {
58 // Create a favorite icon byte array output stream.
59 val favoriteIconByteArrayOutputStream = ByteArrayOutputStream()
61 // 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).
62 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream)
64 // Convert the byte array output stream to a byte array.
65 val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray()
67 // Create an arguments bundle.
68 val argumentsBundle = Bundle()
70 // Store the variables in the bundle.
71 argumentsBundle.putInt(DATABASE_ID, databaseId)
72 argumentsBundle.putByteArray(FAVORITE_ICON_BYTE_ARRAY, favoriteIconByteArray)
74 // Create a new instance of the dialog.
75 val editBookmarkDialog = EditBookmarkDialog()
77 // Add the arguments bundle to the dialog.
78 editBookmarkDialog.arguments = argumentsBundle
80 // Return the new dialog.
81 return editBookmarkDialog
85 // Declare the class variables.
86 private lateinit var editBookmarkListener: EditBookmarkListener
88 // Declare the class views.
89 private lateinit var webpageFavoriteIconRadioButton: RadioButton
90 private lateinit var nameEditText: EditText
91 private lateinit var urlEditText: EditText
92 private lateinit var saveButton: Button
94 // The public interface is used to send information back to the parent activity.
95 interface EditBookmarkListener {
96 fun onSaveBookmark(dialogFragment: DialogFragment, selectedBookmarkDatabaseId: Int, favoriteIconBitmap: Bitmap)
99 override fun onAttach(context: Context) {
100 // Run the default commands.
101 super.onAttach(context)
103 // Get a handle for the edit bookmark listener from the launching context.
104 editBookmarkListener = context as EditBookmarkListener
107 override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
108 // Get the arguments.
109 val arguments = requireArguments()
111 // Get the variables from the arguments.
112 val selectedBookmarkDatabaseId = 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 bookmarks database helper.
119 val bookmarksDatabaseHelper = BookmarksDatabaseHelper(requireContext())
121 // Get a cursor with the selected bookmark.
122 val bookmarkCursor = bookmarksDatabaseHelper.getBookmark(selectedBookmarkDatabaseId)
124 // Move the cursor to the first position.
125 bookmarkCursor.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_bookmark)
134 dialogBuilder.setView(R.layout.edit_bookmark_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.
142 editBookmarkListener.onSaveBookmark(this, selectedBookmarkDatabaseId, favoriteIconBitmap)
145 // Create an alert dialog from the builder.
146 val alertDialog = dialogBuilder.create()
148 // Get a handle for the shared preferences.
149 val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(requireContext())
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 layout items.
163 val currentIconLinearLayout = alertDialog.findViewById<LinearLayout>(R.id.current_icon_linearlayout)!!
164 val currentIconRadioButton = alertDialog.findViewById<RadioButton>(R.id.current_icon_radiobutton)!!
165 val currentIconImageView = alertDialog.findViewById<ImageView>(R.id.current_icon_imageview)!!
166 val webpageFavoriteIconLinearLayout = alertDialog.findViewById<LinearLayout>(R.id.webpage_favorite_icon_linearlayout)!!
167 webpageFavoriteIconRadioButton = alertDialog.findViewById(R.id.webpage_favorite_icon_radiobutton)!!
168 val webpageFavoriteIconImageView = alertDialog.findViewById<ImageView>(R.id.webpage_favorite_icon_imageview)!!
169 nameEditText = alertDialog.findViewById(R.id.bookmark_name_edittext)!!
170 urlEditText = alertDialog.findViewById(R.id.bookmark_url_edittext)!!
171 saveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
173 // Get the current favorite icon byte array from the cursor.
174 val currentIconByteArray = bookmarkCursor.getBlob(bookmarkCursor.getColumnIndexOrThrow(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 webpage favorite icon bitmap.
183 webpageFavoriteIconImageView.setImageBitmap(favoriteIconBitmap)
185 // Store the current bookmark name and URL.
186 val currentName = bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BOOKMARK_NAME))
187 val currentUrl = bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BOOKMARK_URL))
189 // Populate the edit texts.
190 nameEditText.setText(currentName)
191 urlEditText.setText(currentUrl)
193 // Initially disable the save button.
194 saveButton.isEnabled = false
196 // Set the radio button listeners. These perform a click on the linear layout, which contains the necessary logic.
197 currentIconRadioButton.setOnClickListener { currentIconLinearLayout.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 webpage favorite icon radio button.
206 webpageFavoriteIconRadioButton.isChecked = false
208 // Update the save button.
209 updateSaveButton(currentName, currentUrl)
212 // Set the webpage favorite icon linear layout click listener.
213 webpageFavoriteIconLinearLayout.setOnClickListener {
214 // Check the webpage favorite icon radio button.
215 webpageFavoriteIconRadioButton.isChecked = true
217 // Uncheck the current icon radio button.
218 currentIconRadioButton.isChecked = false
220 // Update the save button.
221 updateSaveButton(currentName, currentUrl)
224 // Update the save button if the bookmark name changes.
225 nameEditText.addTextChangedListener(object: TextWatcher {
226 override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
230 override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
234 override fun afterTextChanged(s: Editable) {
235 // Update the save button.
236 updateSaveButton(currentName, currentUrl)
240 // Update the save button if the URL changes.
241 urlEditText.addTextChangedListener(object: TextWatcher {
242 override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
246 override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
250 override fun afterTextChanged(s: Editable) {
251 // Update the edit button.
252 updateSaveButton(currentName, currentUrl)
256 // Allow the enter key on the keyboard to save the bookmark from the bookmark name edit text.
257 nameEditText.setOnKeyListener { _: View?, keyCode: Int, event: KeyEvent ->
258 // Check the key code, event, and button status.
259 if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && saveButton.isEnabled) { // The enter key was pressed and the save button is enabled.
260 // Trigger the listener and return the dialog fragment to the parent activity.
261 editBookmarkListener.onSaveBookmark(this, selectedBookmarkDatabaseId, favoriteIconBitmap)
263 // Manually dismiss the alert dialog.
264 alertDialog.dismiss()
266 // Consume the event.
267 return@setOnKeyListener true
268 } else { // If any other key was pressed, or if the save button is currently disabled, do not consume the event.
269 return@setOnKeyListener false
273 // Allow the enter key on the keyboard to save the bookmark from the URL edit text.
274 urlEditText.setOnKeyListener { _: View?, keyCode: Int, event: KeyEvent ->
275 // Check the key code, event, and button status.
276 if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && saveButton.isEnabled) { // The enter key was pressed and the save button is enabled.
277 // Trigger the listener and return the dialog fragment to the parent activity.
278 editBookmarkListener.onSaveBookmark(this, selectedBookmarkDatabaseId, favoriteIconBitmap)
280 // Manually dismiss the alert dialog.
281 alertDialog.dismiss()
283 // Consume the event.
284 return@setOnKeyListener true
285 } else { // If any other key was pressed, or if the save button is currently disabled, do not consume the event.
286 return@setOnKeyListener false
290 // Return the alert dialog.
294 private fun updateSaveButton(currentName: String, currentUrl: String) {
295 // Get the text from the edit texts.
296 val newName = nameEditText.text.toString()
297 val newUrl = urlEditText.text.toString()
299 // Has the favorite icon changed?
300 val iconChanged = webpageFavoriteIconRadioButton.isChecked
302 // Has the name changed?
303 val nameChanged = newName != currentName
305 // Has the URL changed?
306 val urlChanged = newUrl != currentUrl
308 // Update the enabled status of the save button.
309 saveButton.isEnabled = iconChanged || nameChanged || urlChanged