]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/EditBookmarkDialog.kt
e30cf5db3163432a74dd8f1651524b1c1c2219a0
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / EditBookmarkDialog.kt
1 /*
2  * Copyright © 2016-2022 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.BookmarksDatabaseHelper
45
46 import java.io.ByteArrayOutputStream
47
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"
51
52 class EditBookmarkDialog : DialogFragment() {
53     // Declare the class variables.
54     private lateinit var editBookmarkListener: EditBookmarkListener
55
56     // Declare the class views.
57     private lateinit var webpageFavoriteIconRadioButton: RadioButton
58     private lateinit var nameEditText: EditText
59     private lateinit var urlEditText: EditText
60     private lateinit var saveButton: Button
61
62     // The public interface is used to send information back to the parent activity.
63     interface EditBookmarkListener {
64         fun onSaveBookmark(dialogFragment: DialogFragment, selectedBookmarkDatabaseId: Int, favoriteIconBitmap: Bitmap)
65     }
66
67     override fun onAttach(context: Context) {
68         // Run the default commands.
69         super.onAttach(context)
70
71         // Get a handle for the edit bookmark listener from the launching context.
72         editBookmarkListener = context as EditBookmarkListener
73     }
74
75     companion object {
76         // `@JvmStatic` will no longer be required once all the code has transitioned to Kotlin.
77         @JvmStatic
78         fun bookmarkDatabaseId(databaseId: Int, favoriteIconBitmap: Bitmap): EditBookmarkDialog {
79             // Create a favorite icon byte array output stream.
80             val favoriteIconByteArrayOutputStream = ByteArrayOutputStream()
81
82             // 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).
83             favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream)
84
85             // Convert the byte array output stream to a byte array.
86             val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray()
87
88             // Create an arguments bundle.
89             val argumentsBundle = Bundle()
90
91             // Store the variables in the bundle.
92             argumentsBundle.putInt(DATABASE_ID, databaseId)
93             argumentsBundle.putByteArray(FAVORITE_ICON_BYTE_ARRAY, favoriteIconByteArray)
94
95             // Create a new instance of the dialog.
96             val editBookmarkDialog = EditBookmarkDialog()
97
98             // Add the arguments bundle to the dialog.
99             editBookmarkDialog.arguments = argumentsBundle
100
101             // Return the new dialog.
102             return editBookmarkDialog
103         }
104     }
105
106     override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
107         // Get the arguments.
108         val arguments = requireArguments()
109
110         // Get the variables from the arguments.
111         val selectedBookmarkDatabaseId = arguments.getInt(DATABASE_ID)
112         val favoriteIconByteArray = arguments.getByteArray(FAVORITE_ICON_BYTE_ARRAY)!!
113
114         // Convert the favorite icon byte array to a bitmap.
115         val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size)
116
117         // Initialize the bookmarks database helper.  The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
118         val bookmarksDatabaseHelper = BookmarksDatabaseHelper(context, null, null, 0)
119
120         // Get a cursor with the selected bookmark.
121         val bookmarkCursor = bookmarksDatabaseHelper.getBookmark(selectedBookmarkDatabaseId)
122
123         // Move the cursor to the first position.
124         bookmarkCursor.moveToFirst()
125
126         // Use an alert dialog builder to create the alert dialog.
127         val dialogBuilder = AlertDialog.Builder(requireContext(), R.style.PrivacyBrowserAlertDialog)
128
129         // Set the title.
130         dialogBuilder.setTitle(R.string.edit_bookmark)
131
132         // Set the view.
133         dialogBuilder.setView(R.layout.edit_bookmark_dialog)
134
135         // Set the cancel button listener.  Using `null` as the listener closes the dialog without doing anything else.
136         dialogBuilder.setNegativeButton(R.string.cancel, null)
137
138         // Set the save button listener.
139         dialogBuilder.setPositiveButton(R.string.save) { _: DialogInterface?, _: Int ->
140             // Return the dialog fragment to the parent activity.
141             editBookmarkListener.onSaveBookmark(this, selectedBookmarkDatabaseId, favoriteIconBitmap)
142         }
143
144         // Create an alert dialog from the builder.
145         val alertDialog = dialogBuilder.create()
146
147         // Get a handle for the shared preferences.
148         val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(requireContext())
149
150         // Get the screenshot preference.
151         val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false)
152
153         // Disable screenshots if not allowed.
154         if (!allowScreenshots) {
155             alertDialog.window!!.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
156         }
157
158         // The alert dialog must be shown before items in the layout can be modified.
159         alertDialog.show()
160
161         // Get handles for the layout items.
162         val currentIconLinearLayout = alertDialog.findViewById<LinearLayout>(R.id.current_icon_linearlayout)!!
163         val currentIconRadioButton = alertDialog.findViewById<RadioButton>(R.id.current_icon_radiobutton)!!
164         val currentIconImageView = alertDialog.findViewById<ImageView>(R.id.current_icon_imageview)!!
165         val webpageFavoriteIconLinearLayout = alertDialog.findViewById<LinearLayout>(R.id.webpage_favorite_icon_linearlayout)!!
166         webpageFavoriteIconRadioButton = alertDialog.findViewById(R.id.webpage_favorite_icon_radiobutton)!!
167         val webpageFavoriteIconImageView = alertDialog.findViewById<ImageView>(R.id.webpage_favorite_icon_imageview)!!
168         nameEditText = alertDialog.findViewById(R.id.bookmark_name_edittext)!!
169         urlEditText = alertDialog.findViewById(R.id.bookmark_url_edittext)!!
170         saveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
171
172         // Get the current favorite icon byte array from the cursor.
173         val currentIconByteArray = bookmarkCursor.getBlob(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.FAVORITE_ICON))
174
175         // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
176         val currentIconBitmap = BitmapFactory.decodeByteArray(currentIconByteArray, 0, currentIconByteArray.size)
177
178         // Display the current icon bitmap.
179         currentIconImageView.setImageBitmap(currentIconBitmap)
180
181         // Set the webpage favorite icon bitmap.
182         webpageFavoriteIconImageView.setImageBitmap(favoriteIconBitmap)
183
184         // Store the current bookmark name and URL.
185         val currentName = bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME))
186         val currentUrl = bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL))
187
188         // Populate the edit texts.
189         nameEditText.setText(currentName)
190         urlEditText.setText(currentUrl)
191
192         // Initially disable the save button.
193         saveButton.isEnabled = false
194
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         webpageFavoriteIconRadioButton.setOnClickListener { webpageFavoriteIconLinearLayout.performClick() }
198
199         // Set the current icon linear layout click listener.
200         currentIconLinearLayout.setOnClickListener {
201             // Check the current icon radio button.
202             currentIconRadioButton.isChecked = true
203
204             // Uncheck the webpage favorite icon radio button.
205             webpageFavoriteIconRadioButton.isChecked = false
206
207             // Update the save button.
208             updateSaveButton(currentName, currentUrl)
209         }
210
211         // Set the webpage favorite icon linear layout click listener.
212         webpageFavoriteIconLinearLayout.setOnClickListener {
213             // Check the webpage favorite icon radio button.
214             webpageFavoriteIconRadioButton.isChecked = true
215
216             // Uncheck the current icon radio button.
217             currentIconRadioButton.isChecked = false
218
219             // Update the save button.
220             updateSaveButton(currentName, currentUrl)
221         }
222
223         // Update the save button if the bookmark name changes.
224         nameEditText.addTextChangedListener(object: TextWatcher {
225             override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
226                 // Do nothing.
227             }
228
229             override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
230                 // Do nothing.
231             }
232
233             override fun afterTextChanged(s: Editable) {
234                 // Update the save button.
235                 updateSaveButton(currentName, currentUrl)
236             }
237         })
238
239         // Update the save button if the URL changes.
240         urlEditText.addTextChangedListener(object: TextWatcher {
241             override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
242                 // Do nothing.
243             }
244
245             override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
246                 // Do nothing.
247             }
248
249             override fun afterTextChanged(s: Editable) {
250                 // Update the edit button.
251                 updateSaveButton(currentName, currentUrl)
252             }
253         })
254
255         // Allow the enter key on the keyboard to save the bookmark from the bookmark name edit text.
256         nameEditText.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                 editBookmarkListener.onSaveBookmark(this, selectedBookmarkDatabaseId, favoriteIconBitmap)
261
262                 // Manually dismiss the alert dialog.
263                 alertDialog.dismiss()
264
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
269             }
270         }
271
272         // Allow the enter key on the keyboard to save the bookmark from the URL edit text.
273         urlEditText.setOnKeyListener { _: View?, keyCode: Int, event: KeyEvent ->
274             // Check the key code, event, and button status.
275             if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && saveButton.isEnabled) {  // The enter key was pressed and the save button is enabled.
276                 // Trigger the listener and return the dialog fragment to the parent activity.
277                 editBookmarkListener.onSaveBookmark(this, selectedBookmarkDatabaseId, favoriteIconBitmap)
278
279                 // Manually dismiss the alert dialog.
280                 alertDialog.dismiss()
281
282                 // Consume the event.
283                 return@setOnKeyListener true
284             } else { // If any other key was pressed, or if the save button is currently disabled, do not consume the event.
285                 return@setOnKeyListener false
286             }
287         }
288
289         // Return the alert dialog.
290         return alertDialog
291     }
292
293     private fun updateSaveButton(currentName: String, currentUrl: String) {
294         // Get the text from the edit texts.
295         val newName = nameEditText.text.toString()
296         val newUrl = urlEditText.text.toString()
297
298         // Has the favorite icon changed?
299         val iconChanged = webpageFavoriteIconRadioButton.isChecked
300
301         // Has the name changed?
302         val nameChanged = newName != currentName
303
304         // Has the URL changed?
305         val urlChanged = newUrl != currentUrl
306
307         // Update the enabled status of the save button.
308         saveButton.isEnabled = iconChanged || nameChanged || urlChanged
309     }
310 }