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.appcompat.content.res.AppCompatResources
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.HOME_FOLDER_DATABASE_ID
54 import com.stoutner.privacybrowser.activities.HOME_FOLDER_ID
55 import com.stoutner.privacybrowser.helpers.BOOKMARK_NAME
56 import com.stoutner.privacybrowser.helpers.BOOKMARK_URL
57 import com.stoutner.privacybrowser.helpers.DISPLAY_ORDER
58 import com.stoutner.privacybrowser.helpers.FAVORITE_ICON
59 import com.stoutner.privacybrowser.helpers.FOLDER_ID
60 import com.stoutner.privacybrowser.helpers.ID
61 import com.stoutner.privacybrowser.helpers.PARENT_FOLDER_ID
62 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper
64 import java.io.ByteArrayOutputStream
66 // Define the class constants.
67 private const val DATABASE_ID = "database_id"
68 private const val FAVORITE_ICON_BYTE_ARRAY = "favorite_icon_byte_array"
70 class EditBookmarkDatabaseViewDialog : DialogFragment() {
72 fun bookmarkDatabaseId(databaseId: Int, favoriteIconBitmap: Bitmap): EditBookmarkDatabaseViewDialog {
73 // Create a favorite icon byte array output stream.
74 val favoriteIconByteArrayOutputStream = ByteArrayOutputStream()
76 // 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).
77 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream)
79 // Convert the byte array output stream to a byte array.
80 val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray()
82 // Create an arguments bundle.
83 val argumentsBundle = Bundle()
85 // Store the variables in the bundle.
86 argumentsBundle.putInt(DATABASE_ID, databaseId)
87 argumentsBundle.putByteArray(FAVORITE_ICON_BYTE_ARRAY, favoriteIconByteArray)
89 // Create a new instance of the dialog.
90 val editBookmarkDatabaseViewDialog = EditBookmarkDatabaseViewDialog()
92 // Add the arguments bundle to the dialog.
93 editBookmarkDatabaseViewDialog.arguments = argumentsBundle
95 // Return the new dialog.
96 return editBookmarkDatabaseViewDialog
100 // Declare the class variables.
101 private lateinit var editBookmarkDatabaseViewListener: EditBookmarkDatabaseViewListener
103 // Declare the class views.
104 private lateinit var webpageFavoriteIconRadioButton: RadioButton
105 private lateinit var nameEditText: EditText
106 private lateinit var urlEditText: EditText
107 private lateinit var folderSpinner: Spinner
108 private lateinit var displayOrderEditText: EditText
109 private lateinit var saveButton: Button
111 // The public interface is used to send information back to the parent activity.
112 interface EditBookmarkDatabaseViewListener {
113 fun saveBookmark(dialogFragment: DialogFragment, selectedBookmarkDatabaseId: Int, favoriteIconBitmap: Bitmap)
116 override fun onAttach(context: Context) {
117 // Run the default commands.
118 super.onAttach(context)
120 // Get a handle for edit bookmark database view listener from the launching context.
121 editBookmarkDatabaseViewListener = context as EditBookmarkDatabaseViewListener
124 override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
125 // Get the arguments.
126 val arguments = requireArguments()
128 // Get the variables from the arguments.
129 val bookmarkDatabaseId = arguments.getInt(DATABASE_ID)
130 val favoriteIconByteArray = arguments.getByteArray(FAVORITE_ICON_BYTE_ARRAY)!!
132 // Convert the favorite icon byte array to a bitmap.
133 val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size)
135 // Initialize the database helper.
136 val bookmarksDatabaseHelper = BookmarksDatabaseHelper(requireContext())
138 // Get a cursor with the selected bookmark.
139 val bookmarkCursor = bookmarksDatabaseHelper.getBookmark(bookmarkDatabaseId)
141 // Move the cursor to the first position.
142 bookmarkCursor.moveToFirst()
144 // Use an alert dialog builder to create the dialog and set the style according to the theme.
145 val dialogBuilder = AlertDialog.Builder(requireContext(), R.style.PrivacyBrowserAlertDialog)
148 dialogBuilder.setTitle(R.string.edit_bookmark)
151 dialogBuilder.setView(R.layout.edit_bookmark_databaseview_dialog)
153 // Set the cancel button listener. Using `null` as the listener closes the dialog without doing anything else.
154 dialogBuilder.setNegativeButton(R.string.cancel, null)
156 // Set the save button listener.
157 dialogBuilder.setPositiveButton(R.string.save) { _: DialogInterface, _: Int ->
158 // Return the dialog fragment to the parent activity on save.
159 editBookmarkDatabaseViewListener.saveBookmark(this, bookmarkDatabaseId, favoriteIconBitmap)
162 // Create an alert dialog from the alert dialog builder.
163 val alertDialog = dialogBuilder.create()
165 // Get a handle for the shared preferences.
166 val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(requireContext())
168 // Get the screenshot preference.
169 val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false)
171 // Disable screenshots if not allowed.
172 if (!allowScreenshots) {
173 alertDialog.window!!.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
176 // The alert dialog must be shown before items in the layout can be modified.
179 // Get handles for the layout items.
180 val databaseIdTextView = alertDialog.findViewById<TextView>(R.id.bookmark_database_id_textview)!!
181 val currentIconLinearLayout = alertDialog.findViewById<LinearLayout>(R.id.current_icon_linearlayout)!!
182 val currentIconRadioButton = alertDialog.findViewById<RadioButton>(R.id.current_icon_radiobutton)!!
183 val currentIconImageView = alertDialog.findViewById<ImageView>(R.id.current_icon_imageview)!!
184 val webpageFavoriteIconLinearLayout = alertDialog.findViewById<LinearLayout>(R.id.webpage_favorite_icon_linearlayout)!!
185 webpageFavoriteIconRadioButton = alertDialog.findViewById(R.id.webpage_favorite_icon_radiobutton)!!
186 val webpageFavoriteIconImageView = alertDialog.findViewById<ImageView>(R.id.webpage_favorite_icon_imageview)!!
187 nameEditText = alertDialog.findViewById(R.id.bookmark_name_edittext)!!
188 urlEditText = alertDialog.findViewById(R.id.bookmark_url_edittext)!!
189 folderSpinner = alertDialog.findViewById(R.id.bookmark_folder_spinner)!!
190 displayOrderEditText = alertDialog.findViewById(R.id.bookmark_display_order_edittext)!!
191 saveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
193 // Store the current bookmark values.
194 val currentBookmarkName = bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BOOKMARK_NAME))
195 val currentUrl = bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BOOKMARK_URL))
196 val currentDisplayOrder = bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(DISPLAY_ORDER))
198 // Set the database ID.
199 databaseIdTextView.text = bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(ID)).toString()
201 // Get the current favorite icon byte array from the cursor.
202 val currentIconByteArray = bookmarkCursor.getBlob(bookmarkCursor.getColumnIndexOrThrow(FAVORITE_ICON))
204 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
205 val currentIconBitmap = BitmapFactory.decodeByteArray(currentIconByteArray, 0, currentIconByteArray.size)
207 // Display the current icon bitmap.
208 currentIconImageView.setImageBitmap(currentIconBitmap)
210 // Set the webpage favorite icon bitmap.
211 webpageFavoriteIconImageView.setImageBitmap(favoriteIconBitmap)
213 // Populate the bookmark name and URL edit texts.
214 nameEditText.setText(currentBookmarkName)
215 urlEditText.setText(currentUrl)
217 // Create an an array of column names for the matrix cursor comprised of the ID and the name.
218 val matrixCursorColumnNamesArray = arrayOf(ID, BOOKMARK_NAME, PARENT_FOLDER_ID)
220 // Create a matrix cursor based on the column names array.
221 val matrixCursor = MatrixCursor(matrixCursorColumnNamesArray)
223 // Add `Home Folder` as the first entry in the matrix folder.
224 matrixCursor.addRow(arrayOf(HOME_FOLDER_DATABASE_ID, getString(R.string.home_folder), HOME_FOLDER_ID))
226 // Get a cursor with the list of all the folders.
227 val foldersCursor = bookmarksDatabaseHelper.getFoldersExcept(listOf())
229 // Combine the matrix cursor and the folders cursor.
230 val foldersMergeCursor = MergeCursor(arrayOf(matrixCursor, foldersCursor))
232 // Create a resource cursor adapter for the spinner.
233 val foldersCursorAdapter: ResourceCursorAdapter = object: ResourceCursorAdapter(context, R.layout.databaseview_spinner_item, foldersMergeCursor, 0) {
234 override fun bindView(view: View, context: Context, cursor: Cursor) {
235 // Get handles for the spinner views.
236 val subfolderSpacerTextView = view.findViewById<TextView>(R.id.subfolder_spacer_textview)
237 val folderIconImageView = view.findViewById<ImageView>(R.id.folder_icon_imageview)
238 val folderNameTextView = view.findViewById<TextView>(R.id.folder_name_textview)
240 // Populate the subfolder spacer if it is not null (the spinner is open).
241 if (subfolderSpacerTextView != null) {
242 // Indent subfolders.
243 if (cursor.getLong(cursor.getColumnIndexOrThrow(PARENT_FOLDER_ID)) != HOME_FOLDER_ID) { // The folder is not in the home folder.
244 // Get the subfolder spacer.
245 subfolderSpacerTextView.text = bookmarksDatabaseHelper.getSubfolderSpacer(cursor.getLong(cursor.getColumnIndexOrThrow(FOLDER_ID)))
246 } else { // The folder is in the home folder.
247 // Reset the subfolder spacer.
248 subfolderSpacerTextView.text = ""
252 // Set the folder icon according to the type.
253 if (foldersMergeCursor.position == 0) { // The home folder.
254 // Set the gray folder image.
255 folderIconImageView.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.folder_gray))
256 } else { // A user folder
257 // Get the folder icon byte array.
258 val folderIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(FAVORITE_ICON))
260 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
261 val folderIconBitmap = BitmapFactory.decodeByteArray(folderIconByteArray, 0, folderIconByteArray.size)
263 // Set the folder icon.
264 folderIconImageView.setImageBitmap(folderIconBitmap)
267 // Set the folder name.
268 folderNameTextView.text = cursor.getString(cursor.getColumnIndexOrThrow(BOOKMARK_NAME))
272 // Set the folder cursor adapter drop drown view resource.
273 foldersCursorAdapter.setDropDownViewResource(R.layout.databaseview_spinner_dropdown_items)
275 // Set the adapter for the folder spinner.
276 folderSpinner.adapter = foldersCursorAdapter
278 // Get the parent folder name.
279 val parentFolderId = bookmarkCursor.getLong(bookmarkCursor.getColumnIndexOrThrow(PARENT_FOLDER_ID))
281 // Select the parent folder in the spinner if the bookmark isn't in the home folder.
282 if (parentFolderId != HOME_FOLDER_ID) {
283 // Get the database ID of the parent folder.
284 val parentFolderDatabaseId = bookmarksDatabaseHelper.getFolderDatabaseId(parentFolderId)
286 // Initialize the parent folder position and the iteration variable.
287 var parentFolderPosition = 0
290 // Find the parent folder position in the folders cursor adapter.
292 if (foldersCursorAdapter.getItemId(i) == parentFolderDatabaseId.toLong()) {
293 // Store the current position for the parent folder.
294 parentFolderPosition = i
296 // Try the next entry.
299 // Stop when the parent folder position is found or all the items in the folders cursor adapter have been checked.
300 } while (parentFolderPosition == 0 && i < foldersCursorAdapter.count)
302 // Select the parent folder in the spinner.
303 folderSpinner.setSelection(parentFolderPosition)
306 // Store the current folder database ID.
307 val currentFolderDatabaseId = folderSpinner.selectedItemId.toInt()
309 // Populate the display order edit text.
310 displayOrderEditText.setText(bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(DISPLAY_ORDER)).toString())
312 // Initially disable the save button.
313 saveButton.isEnabled = false
315 // Set the radio button listeners. These perform a click on the linear layout, which contains the necessary logic.
316 currentIconRadioButton.setOnClickListener { currentIconLinearLayout.performClick() }
317 webpageFavoriteIconRadioButton.setOnClickListener { webpageFavoriteIconLinearLayout.performClick() }
319 // Set the current icon linear layout click listener.
320 currentIconLinearLayout.setOnClickListener {
321 // Check the current icon radio button.
322 currentIconRadioButton.isChecked = true
324 // Uncheck the webpage favorite icon radio button.
325 webpageFavoriteIconRadioButton.isChecked = false
327 // Update the save button.
328 updateSaveButton(currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder)
331 // Set the webpage favorite icon linear layout click listener.
332 webpageFavoriteIconLinearLayout.setOnClickListener {
333 // Check the webpage favorite icon radio button.
334 webpageFavoriteIconRadioButton.isChecked = true
336 // Uncheck the current icon radio button.
337 currentIconRadioButton.isChecked = false
339 // Update the save button.
340 updateSaveButton(currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder)
343 // Update the save button if the bookmark name changes.
344 nameEditText.addTextChangedListener(object: TextWatcher {
345 override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
349 override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
353 override fun afterTextChanged(s: Editable) {
354 // Update the Save button.
355 updateSaveButton(currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder)
359 // Update the save button if the URL changes.
360 urlEditText.addTextChangedListener(object: TextWatcher {
361 override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
365 override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
369 override fun afterTextChanged(s: Editable) {
370 // Update the save button.
371 updateSaveButton(currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder)
375 // Wait to set the on item selected listener until the spinner has been inflated. Otherwise the dialog will crash on restart.
377 // Update the save button if the folder changes.
378 folderSpinner.onItemSelectedListener = object: OnItemSelectedListener {
379 override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
380 // Update the save button.
381 updateSaveButton(currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder)
384 override fun onNothingSelected(parent: AdapterView<*>) {
390 // Update the save button if the display order changes.
391 displayOrderEditText.addTextChangedListener(object: TextWatcher {
392 override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
396 override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
400 override fun afterTextChanged(s: Editable) {
401 // Update the save button.
402 updateSaveButton(currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder)
406 // Allow the enter key on the keyboard to save the bookmark from the bookmark name edit text.
407 nameEditText.setOnKeyListener { _: View, keyCode: Int, keyEvent: KeyEvent ->
408 // Check the key code, event, and button status.
409 if (keyEvent.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && saveButton.isEnabled) { // The enter key was pressed and the save button is enabled.
410 // Trigger the listener and return the dialog fragment to the parent activity.
411 editBookmarkDatabaseViewListener.saveBookmark(this, bookmarkDatabaseId, favoriteIconBitmap)
413 // Manually dismiss the alert dialog.
414 alertDialog.dismiss()
416 // Consume the event.
417 return@setOnKeyListener true
418 } else { // If any other key was pressed, or if the save button is currently disabled, do not consume the event.
419 return@setOnKeyListener false
423 // Allow the enter key on the keyboard to save the bookmark from the URL edit text.
424 urlEditText.setOnKeyListener { _: View, keyCode: Int, keyEvent: KeyEvent ->
425 // Check the key code, event, and button status.
426 if (keyEvent.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && saveButton.isEnabled) { // The enter key was pressed and the save button is enabled.
427 // Trigger the listener and return the dialog fragment to the parent activity.
428 editBookmarkDatabaseViewListener.saveBookmark(this, bookmarkDatabaseId, favoriteIconBitmap)
430 // Manually dismiss the alert dialog.
431 alertDialog.dismiss()
433 // Consume the event.
434 return@setOnKeyListener true
435 } else { // If any other key was pressed, or if the save button is currently disabled, do not consume the event.
436 return@setOnKeyListener false
440 // Allow the enter key on the keyboard to save the bookmark from the display order edit text.
441 displayOrderEditText.setOnKeyListener { _: View, keyCode: Int, keyEvent: KeyEvent ->
442 // Check the key code, event, and button status.
443 if (keyEvent.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && saveButton.isEnabled) { // The enter key was pressed and the save button is enabled.
444 // Trigger the listener and return the dialog fragment to the parent activity.
445 editBookmarkDatabaseViewListener.saveBookmark(this, bookmarkDatabaseId, favoriteIconBitmap)
447 // Manually dismiss the alert dialog.
448 alertDialog.dismiss()
450 // Consume the event.
451 return@setOnKeyListener true
452 } else { // If any other key was pressed, or if the save button is currently disabled, do not consume the event.
453 return@setOnKeyListener false
457 // Return the alert dialog.
461 private fun updateSaveButton(currentBookmarkName: String, currentUrl: String, currentFolderDatabaseId: Int, currentDisplayOrder: Int) {
462 // Get the values from the dialog.
463 val newName = nameEditText.text.toString()
464 val newUrl = urlEditText.text.toString()
465 val newFolderDatabaseId = folderSpinner.selectedItemId.toInt()
466 val newDisplayOrder = displayOrderEditText.text.toString()
468 // Has the favorite icon changed?
469 val iconChanged = webpageFavoriteIconRadioButton.isChecked
471 // Has the name changed?
472 val nameChanged = (newName != currentBookmarkName)
474 // Has the URL changed?
475 val urlChanged = (newUrl != currentUrl)
477 // Has the folder changed?
478 val folderChanged = (newFolderDatabaseId != currentFolderDatabaseId)
480 // Has the display order changed?
481 val displayOrderChanged = (newDisplayOrder != currentDisplayOrder.toString())
483 // Is the display order empty?
484 val displayOrderNotEmpty = newDisplayOrder.isNotEmpty()
486 // Update the enabled status of the save button.
487 saveButton.isEnabled = (iconChanged || nameChanged || urlChanged || folderChanged || displayOrderChanged) && displayOrderNotEmpty