2 * Copyright © 2016-2023 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser Android <https://www.stoutner.com/privacy-browser-android>.
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.
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.
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/>.
20 package com.stoutner.privacybrowser.dialogs
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
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
52 import com.stoutner.privacybrowser.R
53 import com.stoutner.privacybrowser.activities.BookmarksDatabaseViewActivity
54 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper
56 import java.io.ByteArrayOutputStream
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"
62 class EditBookmarkDatabaseViewDialog : DialogFragment() {
64 fun bookmarkDatabaseId(databaseId: Int, favoriteIconBitmap: Bitmap): EditBookmarkDatabaseViewDialog {
65 // Create a favorite icon byte array output stream.
66 val favoriteIconByteArrayOutputStream = ByteArrayOutputStream()
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)
71 // Convert the byte array output stream to a byte array.
72 val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray()
74 // Create an arguments bundle.
75 val argumentsBundle = Bundle()
77 // Store the variables in the bundle.
78 argumentsBundle.putInt(DATABASE_ID, databaseId)
79 argumentsBundle.putByteArray(FAVORITE_ICON_BYTE_ARRAY, favoriteIconByteArray)
81 // Create a new instance of the dialog.
82 val editBookmarkDatabaseViewDialog = EditBookmarkDatabaseViewDialog()
84 // Add the arguments bundle to the dialog.
85 editBookmarkDatabaseViewDialog.arguments = argumentsBundle
87 // Return the new dialog.
88 return editBookmarkDatabaseViewDialog
92 // Declare the class variables.
93 private lateinit var editBookmarkDatabaseViewListener: EditBookmarkDatabaseViewListener
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
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)
108 override fun onAttach(context: Context) {
109 // Run the default commands.
110 super.onAttach(context)
112 // Get a handle for edit bookmark database view listener from the launching context.
113 editBookmarkDatabaseViewListener = context as EditBookmarkDatabaseViewListener
116 override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
117 // Get the arguments.
118 val arguments = requireArguments()
120 // Get the variables from the arguments.
121 val bookmarkDatabaseId = arguments.getInt(DATABASE_ID)
122 val favoriteIconByteArray = arguments.getByteArray(FAVORITE_ICON_BYTE_ARRAY)!!
124 // Convert the favorite icon byte array to a bitmap.
125 val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size)
127 // Initialize the database helper.
128 val bookmarksDatabaseHelper = BookmarksDatabaseHelper(requireContext())
130 // Get a cursor with the selected bookmark.
131 val bookmarkCursor = bookmarksDatabaseHelper.getBookmark(bookmarkDatabaseId)
133 // Move the cursor to the first position.
134 bookmarkCursor.moveToFirst()
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)
140 dialogBuilder.setTitle(R.string.edit_bookmark)
143 dialogBuilder.setView(R.layout.edit_bookmark_databaseview_dialog)
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)
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)
154 // Create an alert dialog from the alert dialog builder.
155 val alertDialog = dialogBuilder.create()
157 // Get a handle for the shared preferences.
158 val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(requireContext())
160 // Get the screenshot preference.
161 val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false)
163 // Disable screenshots if not allowed.
164 if (!allowScreenshots) {
165 alertDialog.window!!.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
168 // The alert dialog must be shown before items in the layout can be modified.
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)
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))
190 // Set the database ID.
191 databaseIdTextView.text = bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.ID)).toString()
193 // Get the current favorite icon byte array from the cursor.
194 val currentIconByteArray = bookmarkCursor.getBlob(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.FAVORITE_ICON))
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)
199 // Display the current icon bitmap.
200 currentIconImageView.setImageBitmap(currentIconBitmap)
202 // Set the webpage favorite icon bitmap.
203 webpageFavoriteIconImageView.setImageBitmap(favoriteIconBitmap)
205 // Populate the bookmark name and URL edit texts.
206 nameEditText.setText(currentBookmarkName)
207 urlEditText.setText(currentUrl)
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)
212 // Create a matrix cursor based on the column names array.
213 val matrixCursor = MatrixCursor(matrixCursorColumnNamesArray)
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)))
218 // Get a cursor with the list of all the folders.
219 val foldersCursor = bookmarksDatabaseHelper.allFolders
221 // Combine the matrix cursor and the folders cursor.
222 val foldersMergeCursor = MergeCursor(arrayOf(matrixCursor, foldersCursor))
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)
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))
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)
242 // Set the folder icon.
243 spinnerItemImageView.setImageBitmap(folderIconBitmap)
246 // Set the text view to display the folder name.
247 spinnerItemTextView.text = cursor.getString(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME))
251 // Set the folder cursor adapter drop drown view resource.
252 foldersCursorAdapter.setDropDownViewResource(R.layout.databaseview_spinner_dropdown_items)
254 // Set the adapter for the folder spinner.
255 folderSpinner.adapter = foldersCursorAdapter
257 // Get the parent folder name.
258 val parentFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.PARENT_FOLDER))
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)))
265 // Initialize the parent folder position and the iteration variable.
266 var parentFolderPosition = 0
269 // Find the parent folder position in folders cursor adapter.
271 if (foldersCursorAdapter.getItemId(i) == folderDatabaseId.toLong()) {
272 // Store the current position for the parent folder.
273 parentFolderPosition = i
275 // Try the next entry.
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)
281 // Select the parent folder in the spinner.
282 folderSpinner.setSelection(parentFolderPosition)
285 // Store the current folder database ID.
286 val currentFolderDatabaseId = folderSpinner.selectedItemId.toInt()
288 // Populate the display order edit text.
289 displayOrderEditText.setText(bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.DISPLAY_ORDER)).toString())
291 // Initially disable the save button.
292 saveButton.isEnabled = false
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() }
298 // Set the current icon linear layout click listener.
299 currentIconLinearLayout.setOnClickListener {
300 // Check the current icon radio button.
301 currentIconRadioButton.isChecked = true
303 // Uncheck the webpage favorite icon radio button.
304 webpageFavoriteIconRadioButton.isChecked = false
306 // Update the save button.
307 updateSaveButton(currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder)
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
315 // Uncheck the current icon radio button.
316 currentIconRadioButton.isChecked = false
318 // Update the save button.
319 updateSaveButton(currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder)
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) {
328 override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
332 override fun afterTextChanged(s: Editable) {
333 // Update the Save button.
334 updateSaveButton(currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder)
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) {
344 override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
348 override fun afterTextChanged(s: Editable) {
349 // Update the save button.
350 updateSaveButton(currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder)
354 // Wait to set the on item selected listener until the spinner has been inflated. Otherwise the dialog will crash on restart.
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)
363 override fun onNothingSelected(parent: AdapterView<*>) {
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) {
375 override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
379 override fun afterTextChanged(s: Editable) {
380 // Update the save button.
381 updateSaveButton(currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder)
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)
392 // Manually dismiss the alert dialog.
393 alertDialog.dismiss()
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
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)
409 // Manually dismiss the alert dialog.
410 alertDialog.dismiss()
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
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)
426 // Manually dismiss the alert dialog.
427 alertDialog.dismiss()
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
436 // Return the alert dialog.
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()
447 // Has the favorite icon changed?
448 val iconChanged = webpageFavoriteIconRadioButton.isChecked
450 // Has the name changed?
451 val nameChanged = (newName != currentBookmarkName)
453 // Has the URL changed?
454 val urlChanged = (newUrl != currentUrl)
456 // Has the folder changed?
457 val folderChanged = (newFolderDatabaseId != currentFolderDatabaseId)
459 // Has the display order changed?
460 val displayOrderChanged = (newDisplayOrder != currentDisplayOrder.toString())
462 // Is the display order empty?
463 val displayOrderNotEmpty = newDisplayOrder.isNotEmpty()
465 // Update the enabled status of the save button.
466 saveButton.isEnabled = (iconChanged || nameChanged || urlChanged || folderChanged || displayOrderChanged) && displayOrderNotEmpty