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