]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/EditBookmarkDialog.kt
Expand the options for selecting a download provider. https://redmine.stoutner.com...
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / EditBookmarkDialog.kt
1 /*
2  * Copyright 2016-2023 Soren Stoutner <soren@stoutner.com>.
3  *
4  * This file is part of Privacy Browser Android <https://www.stoutner.com/privacy-browser-android>.
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 package com.stoutner.privacybrowser.dialogs
21
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
38
39 import androidx.appcompat.app.AlertDialog
40 import androidx.fragment.app.DialogFragment
41 import androidx.preference.PreferenceManager
42
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
48
49 import java.io.ByteArrayOutputStream
50
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"
54
55 class EditBookmarkDialog : DialogFragment() {
56     companion object {
57         fun editBookmark(databaseId: Int, favoriteIconBitmap: Bitmap): EditBookmarkDialog {
58             // Create a favorite icon byte array output stream.
59             val favoriteIconByteArrayOutputStream = ByteArrayOutputStream()
60
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)
63
64             // Convert the byte array output stream to a byte array.
65             val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray()
66
67             // Create an arguments bundle.
68             val argumentsBundle = Bundle()
69
70             // Store the variables in the bundle.
71             argumentsBundle.putInt(DATABASE_ID, databaseId)
72             argumentsBundle.putByteArray(FAVORITE_ICON_BYTE_ARRAY, favoriteIconByteArray)
73
74             // Create a new instance of the dialog.
75             val editBookmarkDialog = EditBookmarkDialog()
76
77             // Add the arguments bundle to the dialog.
78             editBookmarkDialog.arguments = argumentsBundle
79
80             // Return the new dialog.
81             return editBookmarkDialog
82         }
83     }
84
85     // Declare the class variables.
86     private lateinit var editBookmarkListener: EditBookmarkListener
87
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
93
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)
97     }
98
99     override fun onAttach(context: Context) {
100         // Run the default commands.
101         super.onAttach(context)
102
103         // Get a handle for the edit bookmark listener from the launching context.
104         editBookmarkListener = context as EditBookmarkListener
105     }
106
107     override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
108         // Get the arguments.
109         val arguments = requireArguments()
110
111         // Get the variables from the arguments.
112         val selectedBookmarkDatabaseId = arguments.getInt(DATABASE_ID)
113         val favoriteIconByteArray = arguments.getByteArray(FAVORITE_ICON_BYTE_ARRAY)!!
114
115         // Convert the favorite icon byte array to a bitmap.
116         val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size)
117
118         // Initialize the bookmarks database helper.
119         val bookmarksDatabaseHelper = BookmarksDatabaseHelper(requireContext())
120
121         // Get a cursor with the selected bookmark.
122         val bookmarkCursor = bookmarksDatabaseHelper.getBookmark(selectedBookmarkDatabaseId)
123
124         // Move the cursor to the first position.
125         bookmarkCursor.moveToFirst()
126
127         // Use an alert dialog builder to create the alert dialog.
128         val dialogBuilder = AlertDialog.Builder(requireContext(), R.style.PrivacyBrowserAlertDialog)
129
130         // Set the title.
131         dialogBuilder.setTitle(R.string.edit_bookmark)
132
133         // Set the view.
134         dialogBuilder.setView(R.layout.edit_bookmark_dialog)
135
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)
138
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)
143         }
144
145         // Create an alert dialog from the builder.
146         val alertDialog = dialogBuilder.create()
147
148         // Get a handle for the shared preferences.
149         val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(requireContext())
150
151         // Get the screenshot preference.
152         val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false)
153
154         // Disable screenshots if not allowed.
155         if (!allowScreenshots) {
156             alertDialog.window!!.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
157         }
158
159         // The alert dialog must be shown before items in the layout can be modified.
160         alertDialog.show()
161
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)
172
173         // Get the current favorite icon byte array from the cursor.
174         val currentIconByteArray = bookmarkCursor.getBlob(bookmarkCursor.getColumnIndexOrThrow(FAVORITE_ICON))
175
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)
178
179         // Display the current icon bitmap.
180         currentIconImageView.setImageBitmap(currentIconBitmap)
181
182         // Set the webpage favorite icon bitmap.
183         webpageFavoriteIconImageView.setImageBitmap(favoriteIconBitmap)
184
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))
188
189         // Populate the edit texts.
190         nameEditText.setText(currentName)
191         urlEditText.setText(currentUrl)
192
193         // Initially disable the save button.
194         saveButton.isEnabled = false
195
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() }
199
200         // Set the current icon linear layout click listener.
201         currentIconLinearLayout.setOnClickListener {
202             // Check the current icon radio button.
203             currentIconRadioButton.isChecked = true
204
205             // Uncheck the webpage favorite icon radio button.
206             webpageFavoriteIconRadioButton.isChecked = false
207
208             // Update the save button.
209             updateSaveButton(currentName, currentUrl)
210         }
211
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
216
217             // Uncheck the current icon radio button.
218             currentIconRadioButton.isChecked = false
219
220             // Update the save button.
221             updateSaveButton(currentName, currentUrl)
222         }
223
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) {
227                 // Do nothing.
228             }
229
230             override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
231                 // Do nothing.
232             }
233
234             override fun afterTextChanged(s: Editable) {
235                 // Update the save button.
236                 updateSaveButton(currentName, currentUrl)
237             }
238         })
239
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) {
243                 // Do nothing.
244             }
245
246             override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
247                 // Do nothing.
248             }
249
250             override fun afterTextChanged(s: Editable) {
251                 // Update the edit button.
252                 updateSaveButton(currentName, currentUrl)
253             }
254         })
255
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)
262
263                 // Manually dismiss the alert dialog.
264                 alertDialog.dismiss()
265
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
270             }
271         }
272
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)
279
280                 // Manually dismiss the alert dialog.
281                 alertDialog.dismiss()
282
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
287             }
288         }
289
290         // Return the alert dialog.
291         return alertDialog
292     }
293
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()
298
299         // Has the favorite icon changed?
300         val iconChanged = webpageFavoriteIconRadioButton.isChecked
301
302         // Has the name changed?
303         val nameChanged = newName != currentName
304
305         // Has the URL changed?
306         val urlChanged = newUrl != currentUrl
307
308         // Update the enabled status of the save button.
309         saveButton.isEnabled = iconChanged || nameChanged || urlChanged
310     }
311 }