]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/EditBookmarkDatabaseViewDialog.kt
Migrate the remaining classes to Kotlin. https://redmine.stoutner.com/issues/989
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / EditBookmarkDatabaseViewDialog.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.database.Cursor
26 import android.database.MatrixCursor
27 import android.database.MergeCursor
28 import android.graphics.Bitmap
29 import android.graphics.BitmapFactory
30 import android.os.Bundle
31 import android.text.Editable
32 import android.text.TextWatcher
33 import android.view.KeyEvent
34 import android.view.View
35 import android.view.WindowManager
36 import android.widget.AdapterView
37 import android.widget.AdapterView.OnItemSelectedListener
38 import android.widget.Button
39 import android.widget.EditText
40 import android.widget.ImageView
41 import android.widget.LinearLayout
42 import android.widget.RadioButton
43 import android.widget.Spinner
44 import android.widget.TextView
45
46 import androidx.appcompat.app.AlertDialog
47 import androidx.core.content.ContextCompat
48 import androidx.cursoradapter.widget.ResourceCursorAdapter
49 import androidx.fragment.app.DialogFragment
50 import androidx.preference.PreferenceManager
51
52 import com.stoutner.privacybrowser.R
53 import com.stoutner.privacybrowser.activities.BookmarksDatabaseViewActivity
54 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper
55
56 import java.io.ByteArrayOutputStream
57
58 // Define the class constants.
59 private const val DATABASE_ID = "database_id"
60 private const val FAVORITE_ICON_BYTE_ARRAY = "favorite_icon_byte_array"
61
62 class EditBookmarkDatabaseViewDialog : DialogFragment() {
63     companion object {
64         fun bookmarkDatabaseId(databaseId: Int, favoriteIconBitmap: Bitmap): EditBookmarkDatabaseViewDialog {
65             // Create a favorite icon byte array output stream.
66             val favoriteIconByteArrayOutputStream = ByteArrayOutputStream()
67
68             // 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).
69             favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream)
70
71             // Convert the byte array output stream to a byte array.
72             val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray()
73
74             // Create an arguments bundle.
75             val argumentsBundle = Bundle()
76
77             // Store the variables in the bundle.
78             argumentsBundle.putInt(DATABASE_ID, databaseId)
79             argumentsBundle.putByteArray(FAVORITE_ICON_BYTE_ARRAY, favoriteIconByteArray)
80
81             // Create a new instance of the dialog.
82             val editBookmarkDatabaseViewDialog = EditBookmarkDatabaseViewDialog()
83
84             // Add the arguments bundle to the dialog.
85             editBookmarkDatabaseViewDialog.arguments = argumentsBundle
86
87             // Return the new dialog.
88             return editBookmarkDatabaseViewDialog
89         }
90     }
91
92     // Declare the class variables.
93     private lateinit var editBookmarkDatabaseViewListener: EditBookmarkDatabaseViewListener
94
95     // Declare the class views.
96     private lateinit var webpageFavoriteIconRadioButton: RadioButton
97     private lateinit var nameEditText: EditText
98     private lateinit var urlEditText: EditText
99     private lateinit var folderSpinner: Spinner
100     private lateinit var displayOrderEditText: EditText
101     private lateinit var saveButton: Button
102
103     // The public interface is used to send information back to the parent activity.
104     interface EditBookmarkDatabaseViewListener {
105         fun onSaveBookmark(dialogFragment: DialogFragment, selectedBookmarkDatabaseId: Int, favoriteIconBitmap: Bitmap)
106     }
107
108     override fun onAttach(context: Context) {
109         // Run the default commands.
110         super.onAttach(context)
111
112         // Get a handle for edit bookmark database view listener from the launching context.
113         editBookmarkDatabaseViewListener = context as EditBookmarkDatabaseViewListener
114     }
115
116     override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
117         // Get the arguments.
118         val arguments = requireArguments()
119
120         // Get the variables from the arguments.
121         val bookmarkDatabaseId = arguments.getInt(DATABASE_ID)
122         val favoriteIconByteArray = arguments.getByteArray(FAVORITE_ICON_BYTE_ARRAY)!!
123
124         // Convert the favorite icon byte array to a bitmap.
125         val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size)
126
127         // Initialize the database helper.
128         val bookmarksDatabaseHelper = BookmarksDatabaseHelper(requireContext())
129
130         // Get a cursor with the selected bookmark.
131         val bookmarkCursor = bookmarksDatabaseHelper.getBookmark(bookmarkDatabaseId)
132
133         // Move the cursor to the first position.
134         bookmarkCursor.moveToFirst()
135
136         // Use an alert dialog builder to create the dialog and set the style according to the theme.
137         val dialogBuilder = AlertDialog.Builder(requireContext(), R.style.PrivacyBrowserAlertDialog)
138
139         // Set the title.
140         dialogBuilder.setTitle(R.string.edit_bookmark)
141
142         // Set the view.
143         dialogBuilder.setView(R.layout.edit_bookmark_databaseview_dialog)
144
145         // Set the cancel button listener.  Using `null` as the listener closes the dialog without doing anything else.
146         dialogBuilder.setNegativeButton(R.string.cancel, null)
147
148         // Set the save button listener.
149         dialogBuilder.setPositiveButton(R.string.save) { _: DialogInterface, _: Int ->
150             // Return the dialog fragment to the parent activity on save.
151             editBookmarkDatabaseViewListener.onSaveBookmark(this, bookmarkDatabaseId, favoriteIconBitmap)
152         }
153
154         // Create an alert dialog from the alert dialog builder.
155         val alertDialog = dialogBuilder.create()
156
157         // Get a handle for the shared preferences.
158         val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(requireContext())
159
160         // Get the screenshot preference.
161         val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false)
162
163         // Disable screenshots if not allowed.
164         if (!allowScreenshots) {
165             alertDialog.window!!.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
166         }
167
168         // The alert dialog must be shown before items in the layout can be modified.
169         alertDialog.show()
170
171         // Get handles for the layout items.
172         val databaseIdTextView = alertDialog.findViewById<TextView>(R.id.bookmark_database_id_textview)!!
173         val currentIconLinearLayout = alertDialog.findViewById<LinearLayout>(R.id.current_icon_linearlayout)!!
174         val currentIconRadioButton = alertDialog.findViewById<RadioButton>(R.id.current_icon_radiobutton)!!
175         val currentIconImageView = alertDialog.findViewById<ImageView>(R.id.current_icon_imageview)!!
176         val webpageFavoriteIconLinearLayout = alertDialog.findViewById<LinearLayout>(R.id.webpage_favorite_icon_linearlayout)!!
177         webpageFavoriteIconRadioButton = alertDialog.findViewById(R.id.webpage_favorite_icon_radiobutton)!!
178         val webpageFavoriteIconImageView = alertDialog.findViewById<ImageView>(R.id.webpage_favorite_icon_imageview)!!
179         nameEditText = alertDialog.findViewById(R.id.bookmark_name_edittext)!!
180         urlEditText = alertDialog.findViewById(R.id.bookmark_url_edittext)!!
181         folderSpinner = alertDialog.findViewById(R.id.bookmark_folder_spinner)!!
182         displayOrderEditText = alertDialog.findViewById(R.id.bookmark_display_order_edittext)!!
183         saveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
184
185         // Store the current bookmark values.
186         val currentBookmarkName = bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME))
187         val currentUrl = bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL))
188         val currentDisplayOrder = bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.DISPLAY_ORDER))
189
190         // Set the database ID.
191         databaseIdTextView.text = bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.ID)).toString()
192
193         // Get the current favorite icon byte array from the cursor.
194         val currentIconByteArray = bookmarkCursor.getBlob(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.FAVORITE_ICON))
195
196         // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
197         val currentIconBitmap = BitmapFactory.decodeByteArray(currentIconByteArray, 0, currentIconByteArray.size)
198
199         // Display the current icon bitmap.
200         currentIconImageView.setImageBitmap(currentIconBitmap)
201
202         // Set the webpage favorite icon bitmap.
203         webpageFavoriteIconImageView.setImageBitmap(favoriteIconBitmap)
204
205         // Populate the bookmark name and URL edit texts.
206         nameEditText.setText(currentBookmarkName)
207         urlEditText.setText(currentUrl)
208
209         // Create an an array of column names for the matrix cursor comprised of the ID and the name.
210         val matrixCursorColumnNamesArray = arrayOf(BookmarksDatabaseHelper.ID, BookmarksDatabaseHelper.BOOKMARK_NAME)
211
212         // Create a matrix cursor based on the column names array.
213         val matrixCursor = MatrixCursor(matrixCursorColumnNamesArray)
214
215         // Add `Home Folder` as the first entry in the matrix folder.
216         matrixCursor.addRow(arrayOf(BookmarksDatabaseViewActivity.HOME_FOLDER_DATABASE_ID, getString(R.string.home_folder)))
217
218         // Get a cursor with the list of all the folders.
219         val foldersCursor = bookmarksDatabaseHelper.allFolders
220
221         // Combine the matrix cursor and the folders cursor.
222         val foldersMergeCursor = MergeCursor(arrayOf(matrixCursor, foldersCursor))
223
224         // Create a resource cursor adapter for the spinner.
225         val foldersCursorAdapter: ResourceCursorAdapter = object: ResourceCursorAdapter(context, R.layout.databaseview_spinner_item, foldersMergeCursor, 0) {
226             override fun bindView(view: View, context: Context, cursor: Cursor) {
227                 // Get handles for the spinner views.
228                 val spinnerItemImageView = view.findViewById<ImageView>(R.id.spinner_item_imageview)
229                 val spinnerItemTextView = view.findViewById<TextView>(R.id.spinner_item_textview)
230
231                 // Set the folder icon according to the type.
232                 if (foldersMergeCursor.position == 0) {  // The home folder.
233                     // Set the gray folder image.  `ContextCompat` must be used until the minimum API >= 21.
234                     spinnerItemImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.folder_gray))
235                 } else {  // A user folder
236                     // Get the folder icon byte array.
237                     val folderIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.FAVORITE_ICON))
238
239                     // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
240                     val folderIconBitmap = BitmapFactory.decodeByteArray(folderIconByteArray, 0, folderIconByteArray.size)
241
242                     // Set the folder icon.
243                     spinnerItemImageView.setImageBitmap(folderIconBitmap)
244                 }
245
246                 // Set the text view to display the folder name.
247                 spinnerItemTextView.text = cursor.getString(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME))
248             }
249         }
250
251         // Set the folder cursor adapter drop drown view resource.
252         foldersCursorAdapter.setDropDownViewResource(R.layout.databaseview_spinner_dropdown_items)
253
254         // Set the adapter for the folder spinner.
255         folderSpinner.adapter = foldersCursorAdapter
256
257         // Get the parent folder name.
258         val parentFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.PARENT_FOLDER))
259
260         // Select the current folder in the spinner if the bookmark isn't in the home folder.
261         if (parentFolder != "") {
262             // Get the database ID of the parent folder.
263             val folderDatabaseId = bookmarksDatabaseHelper.getFolderDatabaseId(bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.PARENT_FOLDER)))
264
265             // Initialize the parent folder position and the iteration variable.
266             var parentFolderPosition = 0
267             var i = 0
268
269             // Find the parent folder position in folders cursor adapter.
270             do {
271                 if (foldersCursorAdapter.getItemId(i) == folderDatabaseId.toLong()) {
272                     // Store the current position for the parent folder.
273                     parentFolderPosition = i
274                 } else {
275                     // Try the next entry.
276                     i++
277                 }
278                 // Stop when the parent folder position is found or all the items in the folders cursor adapter have been checked.
279             } while (parentFolderPosition == 0 && i < foldersCursorAdapter.count)
280
281             // Select the parent folder in the spinner.
282             folderSpinner.setSelection(parentFolderPosition)
283         }
284
285         // Store the current folder database ID.
286         val currentFolderDatabaseId = folderSpinner.selectedItemId.toInt()
287
288         // Populate the display order edit text.
289         displayOrderEditText.setText(bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.DISPLAY_ORDER)).toString())
290
291         // Initially disable the save button.
292         saveButton.isEnabled = false
293
294         // Set the radio button listeners.  These perform a click on the linear layout, which contains the necessary logic.
295         currentIconRadioButton.setOnClickListener { currentIconLinearLayout.performClick() }
296         webpageFavoriteIconRadioButton.setOnClickListener { webpageFavoriteIconLinearLayout.performClick() }
297
298         // Set the current icon linear layout click listener.
299         currentIconLinearLayout.setOnClickListener {
300             // Check the current icon radio button.
301             currentIconRadioButton.isChecked = true
302
303             // Uncheck the webpage favorite icon radio button.
304             webpageFavoriteIconRadioButton.isChecked = false
305
306             // Update the save button.
307             updateSaveButton(currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder)
308         }
309
310         // Set the webpage favorite icon linear layout click listener.
311         webpageFavoriteIconLinearLayout.setOnClickListener {
312             // Check the webpage favorite icon radio button.
313             webpageFavoriteIconRadioButton.isChecked = true
314
315             // Uncheck the current icon radio button.
316             currentIconRadioButton.isChecked = false
317
318             // Update the save button.
319             updateSaveButton(currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder)
320         }
321
322         // Update the save button if the bookmark name changes.
323         nameEditText.addTextChangedListener(object: TextWatcher {
324             override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
325                 // Do nothing.
326             }
327
328             override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
329                 // Do nothing.
330             }
331
332             override fun afterTextChanged(s: Editable) {
333                 // Update the Save button.
334                 updateSaveButton(currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder)
335             }
336         })
337
338         // Update the save button if the URL changes.
339         urlEditText.addTextChangedListener(object: TextWatcher {
340             override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
341                 // Do nothing.
342             }
343
344             override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
345                 // Do nothing.
346             }
347
348             override fun afterTextChanged(s: Editable) {
349                 // Update the save button.
350                 updateSaveButton(currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder)
351             }
352         })
353
354         // Wait to set the on item selected listener until the spinner has been inflated.  Otherwise the dialog will crash on restart.
355         folderSpinner.post {
356             // Update the save button if the folder changes.
357             folderSpinner.onItemSelectedListener = object: OnItemSelectedListener {
358                 override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
359                     // Update the save button.
360                     updateSaveButton(currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder)
361                 }
362
363                 override fun onNothingSelected(parent: AdapterView<*>) {
364                     // Do nothing.
365                 }
366             }
367         }
368
369         // Update the save button if the display order changes.
370         displayOrderEditText.addTextChangedListener(object: TextWatcher {
371             override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
372                 // Do nothing.
373             }
374
375             override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
376                 // Do nothing.
377             }
378
379             override fun afterTextChanged(s: Editable) {
380                 // Update the save button.
381                 updateSaveButton(currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder)
382             }
383         })
384
385         // Allow the enter key on the keyboard to save the bookmark from the bookmark name edit text.
386         nameEditText.setOnKeyListener { _: View, keyCode: Int, keyEvent: KeyEvent ->
387             // Check the key code, event, and button status.
388             if (keyEvent.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && saveButton.isEnabled) {  // The enter key was pressed and the save button is enabled.
389                 // Trigger the listener and return the dialog fragment to the parent activity.
390                 editBookmarkDatabaseViewListener.onSaveBookmark(this, bookmarkDatabaseId, favoriteIconBitmap)
391
392                 // Manually dismiss the alert dialog.
393                 alertDialog.dismiss()
394
395                 // Consume the event.
396                 return@setOnKeyListener true
397             } else {  // If any other key was pressed, or if the save button is currently disabled, do not consume the event.
398                 return@setOnKeyListener false
399             }
400         }
401
402         // Allow the enter key on the keyboard to save the bookmark from the URL edit text.
403         urlEditText.setOnKeyListener { _: View, keyCode: Int, keyEvent: KeyEvent ->
404             // Check the key code, event, and button status.
405             if (keyEvent.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && saveButton.isEnabled) {  // The enter key was pressed and the save button is enabled.
406                 // Trigger the listener and return the dialog fragment to the parent activity.
407                 editBookmarkDatabaseViewListener.onSaveBookmark(this, bookmarkDatabaseId, favoriteIconBitmap)
408
409                 // Manually dismiss the alert dialog.
410                 alertDialog.dismiss()
411
412                 // Consume the event.
413                 return@setOnKeyListener true
414             } else { // If any other key was pressed, or if the save button is currently disabled, do not consume the event.
415                 return@setOnKeyListener false
416             }
417         }
418
419         // Allow the enter key on the keyboard to save the bookmark from the display order edit text.
420         displayOrderEditText.setOnKeyListener { _: View, keyCode: Int, keyEvent: KeyEvent ->
421             // Check the key code, event, and button status.
422             if (keyEvent.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && saveButton.isEnabled) {  // The enter key was pressed and the save button is enabled.
423                 // Trigger the listener and return the dialog fragment to the parent activity.
424                 editBookmarkDatabaseViewListener.onSaveBookmark(this, bookmarkDatabaseId, favoriteIconBitmap)
425
426                 // Manually dismiss the alert dialog.
427                 alertDialog.dismiss()
428
429                 // Consume the event.
430                 return@setOnKeyListener true
431             } else { // If any other key was pressed, or if the save button is currently disabled, do not consume the event.
432                 return@setOnKeyListener false
433             }
434         }
435
436         // Return the alert dialog.
437         return alertDialog
438     }
439
440     private fun updateSaveButton(currentBookmarkName: String, currentUrl: String, currentFolderDatabaseId: Int, currentDisplayOrder: Int) {
441         // Get the values from the dialog.
442         val newName = nameEditText.text.toString()
443         val newUrl = urlEditText.text.toString()
444         val newFolderDatabaseId = folderSpinner.selectedItemId.toInt()
445         val newDisplayOrder = displayOrderEditText.text.toString()
446
447         // Has the favorite icon changed?
448         val iconChanged = webpageFavoriteIconRadioButton.isChecked
449
450         // Has the name changed?
451         val nameChanged = (newName != currentBookmarkName)
452
453         // Has the URL changed?
454         val urlChanged = (newUrl != currentUrl)
455
456         // Has the folder changed?
457         val folderChanged = (newFolderDatabaseId != currentFolderDatabaseId)
458
459         // Has the display order changed?
460         val displayOrderChanged = (newDisplayOrder != currentDisplayOrder.toString())
461
462         // Is the display order empty?
463         val displayOrderNotEmpty = newDisplayOrder.isNotEmpty()
464
465         // Update the enabled status of the save button.
466         saveButton.isEnabled = (iconChanged || nameChanged || urlChanged || folderChanged || displayOrderChanged) && displayOrderNotEmpty
467     }
468 }