2 * Copyright © 2016-2022 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() {
63 // Declare the class variables.
64 private lateinit var editBookmarkDatabaseViewListener: EditBookmarkDatabaseViewListener
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
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)
79 override fun onAttach(context: Context) {
80 // Run the default commands.
81 super.onAttach(context)
83 // Get a handle for edit bookmark database view listener from the launching context.
84 editBookmarkDatabaseViewListener = context as EditBookmarkDatabaseViewListener
88 // `@JvmStatic` will no longer be required once all the code has transitioned to Kotlin.
90 fun bookmarkDatabaseId(databaseId: Int, favoriteIconBitmap: Bitmap): EditBookmarkDatabaseViewDialog {
91 // Create a favorite icon byte array output stream.
92 val favoriteIconByteArrayOutputStream = ByteArrayOutputStream()
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)
97 // Convert the byte array output stream to a byte array.
98 val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray()
100 // Create an arguments bundle.
101 val argumentsBundle = Bundle()
103 // Store the variables in the bundle.
104 argumentsBundle.putInt(DATABASE_ID, databaseId)
105 argumentsBundle.putByteArray(FAVORITE_ICON_BYTE_ARRAY, favoriteIconByteArray)
107 // Create a new instance of the dialog.
108 val editBookmarkDatabaseViewDialog = EditBookmarkDatabaseViewDialog()
110 // Add the arguments bundle to the dialog.
111 editBookmarkDatabaseViewDialog.arguments = argumentsBundle
113 // Return the new dialog.
114 return editBookmarkDatabaseViewDialog
118 override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
119 // Get the arguments.
120 val arguments = requireArguments()
122 // Get the variables from the arguments.
123 val bookmarkDatabaseId = arguments.getInt(DATABASE_ID)
124 val favoriteIconByteArray = arguments.getByteArray(FAVORITE_ICON_BYTE_ARRAY)!!
126 // Convert the favorite icon byte array to a bitmap.
127 val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size)
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)
132 // Get a cursor with the selected bookmark.
133 val bookmarkCursor = bookmarksDatabaseHelper.getBookmark(bookmarkDatabaseId)
135 // Move the cursor to the first position.
136 bookmarkCursor.moveToFirst()
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)
142 dialogBuilder.setTitle(R.string.edit_bookmark)
145 dialogBuilder.setView(R.layout.edit_bookmark_databaseview_dialog)
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)
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)
156 // Create an alert dialog from the alert dialog builder.
157 val alertDialog = dialogBuilder.create()
159 // Get a handle for the shared preferences.
160 val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
162 // Get the screenshot preference.
163 val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false)
165 // Disable screenshots if not allowed.
166 if (!allowScreenshots) {
167 alertDialog.window!!.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
170 // The alert dialog must be shown before items in the layout can be modified.
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)
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))
192 // Set the database ID.
193 databaseIdTextView.text = bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper._ID)).toString()
195 // Get the current favorite icon byte array from the cursor.
196 val currentIconByteArray = bookmarkCursor.getBlob(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.FAVORITE_ICON))
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)
201 // Display the current icon bitmap.
202 currentIconImageView.setImageBitmap(currentIconBitmap)
204 // Set the webpage favorite icon bitmap.
205 webpageFavoriteIconImageView.setImageBitmap(favoriteIconBitmap)
207 // Populate the bookmark name and URL edit texts.
208 nameEditText.setText(currentBookmarkName)
209 urlEditText.setText(currentUrl)
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)
214 // Create a matrix cursor based on the column names array.
215 val matrixCursor = MatrixCursor(matrixCursorColumnNamesArray)
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)))
220 // Get a cursor with the list of all the folders.
221 val foldersCursor = bookmarksDatabaseHelper.allFolders
223 // Combine the matrix cursor and the folders cursor.
224 val foldersMergeCursor = MergeCursor(arrayOf(matrixCursor, foldersCursor))
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)
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))
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)
244 // Set the folder icon.
245 spinnerItemImageView.setImageBitmap(folderIconBitmap)
248 // Set the text view to display the folder name.
249 spinnerItemTextView.text = cursor.getString(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME))
253 // Set the folder cursor adapter drop drown view resource.
254 foldersCursorAdapter.setDropDownViewResource(R.layout.databaseview_spinner_dropdown_items)
256 // Set the adapter for the folder spinner.
257 folderSpinner.adapter = foldersCursorAdapter
259 // Get the parent folder name.
260 val parentFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.PARENT_FOLDER))
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)))
267 // Initialize the parent folder position and the iteration variable.
268 var parentFolderPosition = 0
271 // Find the parent folder position in folders cursor adapter.
273 if (foldersCursorAdapter.getItemId(i) == folderDatabaseId.toLong()) {
274 // Store the current position for the parent folder.
275 parentFolderPosition = i
277 // Try the next entry.
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)
283 // Select the parent folder in the spinner.
284 folderSpinner.setSelection(parentFolderPosition)
287 // Store the current folder database ID.
288 val currentFolderDatabaseId = folderSpinner.selectedItemId.toInt()
290 // Populate the display order edit text.
291 displayOrderEditText.setText(bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.DISPLAY_ORDER)).toString())
293 // Initially disable the save button.
294 saveButton.isEnabled = false
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() }
300 // Set the current icon linear layout click listener.
301 currentIconLinearLayout.setOnClickListener {
302 // Check the current icon radio button.
303 currentIconRadioButton.isChecked = true
305 // Uncheck the webpage favorite icon radio button.
306 webpageFavoriteIconRadioButton.isChecked = false
308 // Update the save button.
309 updateSaveButton(currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder)
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
317 // Uncheck the current icon radio button.
318 currentIconRadioButton.isChecked = false
320 // Update the save button.
321 updateSaveButton(currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder)
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) {
330 override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
334 override fun afterTextChanged(s: Editable) {
335 // Update the Save button.
336 updateSaveButton(currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder)
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) {
346 override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
350 override fun afterTextChanged(s: Editable) {
351 // Update the save button.
352 updateSaveButton(currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder)
356 // Wait to set the on item selected listener until the spinner has been inflated. Otherwise the dialog will crash on restart.
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)
365 override fun onNothingSelected(parent: AdapterView<*>) {
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) {
377 override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
381 override fun afterTextChanged(s: Editable) {
382 // Update the save button.
383 updateSaveButton(currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder)
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)
394 // Manually dismiss the alert dialog.
395 alertDialog.dismiss()
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
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)
411 // Manually dismiss the alert dialog.
412 alertDialog.dismiss()
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
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)
428 // Manually dismiss the alert dialog.
429 alertDialog.dismiss()
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
438 // Return the alert dialog.
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()
449 // Has the favorite icon changed?
450 val iconChanged = webpageFavoriteIconRadioButton.isChecked
452 // Has the name changed?
453 val nameChanged = (newName != currentBookmarkName)
455 // Has the URL changed?
456 val urlChanged = (newUrl != currentUrl)
458 // Has the folder changed?
459 val folderChanged = (newFolderDatabaseId != currentFolderDatabaseId)
461 // Has the display order changed?
462 val displayOrderChanged = (newDisplayOrder != currentDisplayOrder.toString())
464 // Is the display order empty?
465 val displayOrderNotEmpty = newDisplayOrder.isNotEmpty()
467 // Update the enabled status of the save button.
468 saveButton.isEnabled = (iconChanged || nameChanged || urlChanged || folderChanged || displayOrderChanged) && displayOrderNotEmpty