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