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