]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/EditBookmarkDatabaseViewDialog.kt
Fix scrolling of the bottom app bar. https://redmine.stoutner.com/issues/791
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / EditBookmarkDatabaseViewDialog.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.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     // Declare the class variables.
64     private lateinit var editBookmarkDatabaseViewListener: EditBookmarkDatabaseViewListener
65
66     // Declare the class views.
67     private lateinit var webpageFavoriteIconRadioButton: RadioButton
68     private lateinit var nameEditText: EditText
69     private lateinit var urlEditText: EditText
70     private lateinit var folderSpinner: Spinner
71     private lateinit var displayOrderEditText: EditText
72     private lateinit var saveButton: Button
73
74     // The public interface is used to send information back to the parent activity.
75     interface EditBookmarkDatabaseViewListener {
76         fun onSaveBookmark(dialogFragment: DialogFragment, selectedBookmarkDatabaseId: Int, favoriteIconBitmap: Bitmap)
77     }
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.
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     override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
119         // Get the arguments.
120         val arguments = requireArguments()
121
122         // Get the variables from the arguments.
123         val bookmarkDatabaseId = arguments.getInt(DATABASE_ID)
124         val favoriteIconByteArray = arguments.getByteArray(FAVORITE_ICON_BYTE_ARRAY)!!
125
126         // Convert the favorite icon byte array to a bitmap.
127         val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size)
128
129         // Initialize the database helper.  The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
130         val bookmarksDatabaseHelper = BookmarksDatabaseHelper(context, null, null, 0)
131
132         // Get a cursor with the selected bookmark.
133         val bookmarkCursor = bookmarksDatabaseHelper.getBookmark(bookmarkDatabaseId)
134
135         // Move the cursor to the first position.
136         bookmarkCursor.moveToFirst()
137
138         // Use an alert dialog builder to create the dialog and set the style according to the theme.
139         val dialogBuilder = AlertDialog.Builder(requireContext(), R.style.PrivacyBrowserAlertDialog)
140
141         // Set the title.
142         dialogBuilder.setTitle(R.string.edit_bookmark)
143
144         // Set the view.
145         dialogBuilder.setView(R.layout.edit_bookmark_databaseview_dialog)
146
147         // Set the cancel button listener.  Using `null` as the listener closes the dialog without doing anything else.
148         dialogBuilder.setNegativeButton(R.string.cancel, null)
149
150         // Set the save button listener.
151         dialogBuilder.setPositiveButton(R.string.save) { _: DialogInterface, _: Int ->
152             // Return the dialog fragment to the parent activity on save.
153             editBookmarkDatabaseViewListener.onSaveBookmark(this, bookmarkDatabaseId, favoriteIconBitmap)
154         }
155
156         // Create an alert dialog from the alert dialog builder.
157         val alertDialog = dialogBuilder.create()
158
159         // Get a handle for the shared preferences.
160         val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
161
162         // Get the screenshot preference.
163         val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false)
164
165         // Disable screenshots if not allowed.
166         if (!allowScreenshots) {
167             alertDialog.window!!.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
168         }
169
170         // The alert dialog must be shown before items in the layout can be modified.
171         alertDialog.show()
172
173         // Get handles for the layout items.
174         val databaseIdTextView = alertDialog.findViewById<TextView>(R.id.bookmark_database_id_textview)!!
175         val currentIconLinearLayout = alertDialog.findViewById<LinearLayout>(R.id.current_icon_linearlayout)!!
176         val currentIconRadioButton = alertDialog.findViewById<RadioButton>(R.id.current_icon_radiobutton)!!
177         val currentIconImageView = alertDialog.findViewById<ImageView>(R.id.current_icon_imageview)!!
178         val webpageFavoriteIconLinearLayout = alertDialog.findViewById<LinearLayout>(R.id.webpage_favorite_icon_linearlayout)!!
179         webpageFavoriteIconRadioButton = alertDialog.findViewById(R.id.webpage_favorite_icon_radiobutton)!!
180         val webpageFavoriteIconImageView = alertDialog.findViewById<ImageView>(R.id.webpage_favorite_icon_imageview)!!
181         nameEditText = alertDialog.findViewById(R.id.bookmark_name_edittext)!!
182         urlEditText = alertDialog.findViewById(R.id.bookmark_url_edittext)!!
183         folderSpinner = alertDialog.findViewById(R.id.bookmark_folder_spinner)!!
184         displayOrderEditText = alertDialog.findViewById(R.id.bookmark_display_order_edittext)!!
185         saveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
186
187         // Store the current bookmark values.
188         val currentBookmarkName = bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME))
189         val currentUrl = bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL))
190         val currentDisplayOrder = bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.DISPLAY_ORDER))
191
192         // Set the database ID.
193         databaseIdTextView.text = bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper._ID)).toString()
194
195         // Get the current favorite icon byte array from the cursor.
196         val currentIconByteArray = bookmarkCursor.getBlob(bookmarkCursor.getColumnIndexOrThrow(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 webpage favorite icon bitmap.
205         webpageFavoriteIconImageView.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.getColumnIndexOrThrow(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.getColumnIndexOrThrow(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.getColumnIndexOrThrow(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.getColumnIndexOrThrow(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.getColumnIndexOrThrow(BookmarksDatabaseHelper.DISPLAY_ORDER)).toString())
292
293         // Initially disable the save button.
294         saveButton.isEnabled = false
295
296         // Set the radio button listeners.  These perform a click on the linear layout, which contains the necessary logic.
297         currentIconRadioButton.setOnClickListener { currentIconLinearLayout.performClick() }
298         webpageFavoriteIconRadioButton.setOnClickListener { webpageFavoriteIconLinearLayout.performClick() }
299
300         // Set the current icon linear layout click listener.
301         currentIconLinearLayout.setOnClickListener {
302             // Check the current icon radio button.
303             currentIconRadioButton.isChecked = true
304
305             // Uncheck the webpage favorite icon radio button.
306             webpageFavoriteIconRadioButton.isChecked = false
307
308             // Update the save button.
309             updateSaveButton(currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder)
310         }
311
312         // Set the webpage favorite icon linear layout click listener.
313         webpageFavoriteIconLinearLayout.setOnClickListener {
314             // Check the webpage favorite icon radio button.
315             webpageFavoriteIconRadioButton.isChecked = true
316
317             // Uncheck the current icon radio button.
318             currentIconRadioButton.isChecked = false
319
320             // Update the save button.
321             updateSaveButton(currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder)
322         }
323
324         // Update the save button if the bookmark name changes.
325         nameEditText.addTextChangedListener(object: TextWatcher {
326             override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
327                 // Do nothing.
328             }
329
330             override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
331                 // Do nothing.
332             }
333
334             override fun afterTextChanged(s: Editable) {
335                 // Update the Save button.
336                 updateSaveButton(currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder)
337             }
338         })
339
340         // Update the save button if the URL changes.
341         urlEditText.addTextChangedListener(object: TextWatcher {
342             override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
343                 // Do nothing.
344             }
345
346             override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
347                 // Do nothing.
348             }
349
350             override fun afterTextChanged(s: Editable) {
351                 // Update the save button.
352                 updateSaveButton(currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder)
353             }
354         })
355
356         // Wait to set the on item selected listener until the spinner has been inflated.  Otherwise the dialog will crash on restart.
357         folderSpinner.post {
358             // Update the save button if the folder changes.
359             folderSpinner.onItemSelectedListener = object: OnItemSelectedListener {
360                 override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
361                     // Update the save button.
362                     updateSaveButton(currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder)
363                 }
364
365                 override fun onNothingSelected(parent: AdapterView<*>) {
366                     // Do nothing.
367                 }
368             }
369         }
370
371         // Update the save button if the display order changes.
372         displayOrderEditText.addTextChangedListener(object: TextWatcher {
373             override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
374                 // Do nothing.
375             }
376
377             override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
378                 // Do nothing.
379             }
380
381             override fun afterTextChanged(s: Editable) {
382                 // Update the save button.
383                 updateSaveButton(currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder)
384             }
385         })
386
387         // Allow the enter key on the keyboard to save the bookmark from the bookmark name edit text.
388         nameEditText.setOnKeyListener { _: View, keyCode: Int, keyEvent: KeyEvent ->
389             // Check the key code, event, and button status.
390             if (keyEvent.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && saveButton.isEnabled) {  // The enter key was pressed and the save button is enabled.
391                 // Trigger the listener and return the dialog fragment to the parent activity.
392                 editBookmarkDatabaseViewListener.onSaveBookmark(this, bookmarkDatabaseId, favoriteIconBitmap)
393
394                 // Manually dismiss the alert dialog.
395                 alertDialog.dismiss()
396
397                 // Consume the event.
398                 return@setOnKeyListener true
399             } else {  // If any other key was pressed, or if the save button is currently disabled, do not consume the event.
400                 return@setOnKeyListener false
401             }
402         }
403
404         // Allow the enter key on the keyboard to save the bookmark from the URL edit text.
405         urlEditText.setOnKeyListener { _: View, keyCode: Int, keyEvent: KeyEvent ->
406             // Check the key code, event, and button status.
407             if (keyEvent.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && saveButton.isEnabled) {  // The enter key was pressed and the save button is enabled.
408                 // Trigger the listener and return the dialog fragment to the parent activity.
409                 editBookmarkDatabaseViewListener.onSaveBookmark(this, bookmarkDatabaseId, favoriteIconBitmap)
410
411                 // Manually dismiss the alert dialog.
412                 alertDialog.dismiss()
413
414                 // Consume the event.
415                 return@setOnKeyListener true
416             } else { // If any other key was pressed, or if the save button is currently disabled, do not consume the event.
417                 return@setOnKeyListener false
418             }
419         }
420
421         // Allow the enter key on the keyboard to save the bookmark from the display order edit text.
422         displayOrderEditText.setOnKeyListener { _: View, keyCode: Int, keyEvent: KeyEvent ->
423             // Check the key code, event, and button status.
424             if (keyEvent.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && saveButton.isEnabled) {  // The enter key was pressed and the save button is enabled.
425                 // Trigger the listener and return the dialog fragment to the parent activity.
426                 editBookmarkDatabaseViewListener.onSaveBookmark(this, bookmarkDatabaseId, favoriteIconBitmap)
427
428                 // Manually dismiss the alert dialog.
429                 alertDialog.dismiss()
430
431                 // Consume the event.
432                 return@setOnKeyListener true
433             } else { // If any other key was pressed, or if the save button is currently disabled, do not consume the event.
434                 return@setOnKeyListener false
435             }
436         }
437
438         // Return the alert dialog.
439         return alertDialog
440     }
441
442     private fun updateSaveButton(currentBookmarkName: String, currentUrl: String, currentFolderDatabaseId: Int, currentDisplayOrder: Int) {
443         // Get the values from the dialog.
444         val newName = nameEditText.text.toString()
445         val newUrl = urlEditText.text.toString()
446         val newFolderDatabaseId = folderSpinner.selectedItemId.toInt()
447         val newDisplayOrder = displayOrderEditText.text.toString()
448
449         // Has the favorite icon changed?
450         val iconChanged = webpageFavoriteIconRadioButton.isChecked
451
452         // Has the name changed?
453         val nameChanged = (newName != currentBookmarkName)
454
455         // Has the URL changed?
456         val urlChanged = (newUrl != currentUrl)
457
458         // Has the folder changed?
459         val folderChanged = (newFolderDatabaseId != currentFolderDatabaseId)
460
461         // Has the display order changed?
462         val displayOrderChanged = (newDisplayOrder != currentDisplayOrder.toString())
463
464         // Is the display order empty?
465         val displayOrderNotEmpty = newDisplayOrder.isNotEmpty()
466
467         // Update the enabled status of the save button.
468         saveButton.isEnabled = (iconChanged || nameChanged || urlChanged || folderChanged || displayOrderChanged) && displayOrderNotEmpty
469     }
470 }