2 * Copyright © 2016-2021 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
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.
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.
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/>.
20 package com.stoutner.privacybrowser.dialogs
22 import android.annotation.SuppressLint
23 import android.app.Dialog
24 import android.content.Context
25 import android.content.DialogInterface
26 import android.graphics.Bitmap
27 import android.graphics.BitmapFactory
28 import android.os.Bundle
29 import android.text.Editable
30 import android.text.TextWatcher
31 import android.view.KeyEvent
32 import android.view.View
33 import android.view.WindowManager
34 import android.widget.Button
35 import android.widget.EditText
36 import android.widget.ImageView
37 import android.widget.LinearLayout
38 import android.widget.RadioButton
40 import androidx.appcompat.app.AlertDialog
41 import androidx.fragment.app.DialogFragment
42 import androidx.preference.PreferenceManager
44 import com.stoutner.privacybrowser.R
45 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper
47 import java.io.ByteArrayOutputStream
49 // Define the class constants.
50 private const val DATABASE_ID = "database_id"
51 private const val FAVORITE_ICON_BYTE_ARRAY = "favorite_icon_byte_array"
53 class EditBookmarkDialog : DialogFragment() {
54 // Declare the class variables.
55 private lateinit var editBookmarkListener: EditBookmarkListener
57 // Declare the class views.
58 private lateinit var webpageFavoriteIconRadioButton: RadioButton
59 private lateinit var nameEditText: EditText
60 private lateinit var urlEditText: EditText
61 private lateinit var saveButton: Button
63 // The public interface is used to send information back to the parent activity.
64 interface EditBookmarkListener {
65 fun onSaveBookmark(dialogFragment: DialogFragment, selectedBookmarkDatabaseId: Int, favoriteIconBitmap: Bitmap)
68 override fun onAttach(context: Context) {
69 // Run the default commands.
70 super.onAttach(context)
72 // Get a handle for the edit bookmark listener from the launching context.
73 editBookmarkListener = context as EditBookmarkListener
77 // `@JvmStatic` will no longer be required once all the code has transitioned to Kotlin.
79 fun bookmarkDatabaseId(databaseId: Int, favoriteIconBitmap: Bitmap): EditBookmarkDialog {
80 // Create a favorite icon byte array output stream.
81 val favoriteIconByteArrayOutputStream = ByteArrayOutputStream()
83 // 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).
84 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream)
86 // Convert the byte array output stream to a byte array.
87 val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray()
89 // Create an arguments bundle.
90 val argumentsBundle = Bundle()
92 // Store the variables in the bundle.
93 argumentsBundle.putInt(DATABASE_ID, databaseId)
94 argumentsBundle.putByteArray(FAVORITE_ICON_BYTE_ARRAY, favoriteIconByteArray)
96 // Create a new instance of the dialog.
97 val editBookmarkDialog = EditBookmarkDialog()
99 // Add the arguments bundle to the dialog.
100 editBookmarkDialog.arguments = argumentsBundle
102 // Return the new dialog.
103 return editBookmarkDialog
107 // `@SuppressLint("InflateParams")` removes the warning about using `null` as the parent view group when inflating the alert dialog.
108 @SuppressLint("InflateParams")
109 override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
110 // Get the arguments.
111 val arguments = requireArguments()
113 // Get the variables from the arguments.
114 val selectedBookmarkDatabaseId = arguments.getInt(DATABASE_ID)
115 val favoriteIconByteArray = arguments.getByteArray(FAVORITE_ICON_BYTE_ARRAY)!!
117 // Convert the favorite icon byte array to a bitmap.
118 val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size)
120 // Initialize the bookmarks database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
121 val bookmarksDatabaseHelper = BookmarksDatabaseHelper(context, null, null, 0)
123 // Get a cursor with the selected bookmark.
124 val bookmarkCursor = bookmarksDatabaseHelper.getBookmark(selectedBookmarkDatabaseId)
126 // Move the cursor to the first position.
127 bookmarkCursor.moveToFirst()
129 // Use an alert dialog builder to create the alert dialog.
130 val dialogBuilder = AlertDialog.Builder(requireContext(), R.style.PrivacyBrowserAlertDialog)
133 dialogBuilder.setTitle(R.string.edit_bookmark)
135 // Set the view. The parent view is null because it will be assigned by the alert dialog.
136 dialogBuilder.setView(layoutInflater.inflate(R.layout.edit_bookmark_dialog, null))
138 // Set the cancel button listener. Using `null` as the listener closes the dialog without doing anything else.
139 dialogBuilder.setNegativeButton(R.string.cancel, null)
141 // Set the save button listener.
142 dialogBuilder.setPositiveButton(R.string.save) { _: DialogInterface?, _: Int ->
143 // Return the dialog fragment to the parent activity.
144 editBookmarkListener.onSaveBookmark(this, selectedBookmarkDatabaseId, favoriteIconBitmap)
147 // Create an alert dialog from the builder.
148 val alertDialog = dialogBuilder.create()
150 // Get a handle for the shared preferences.
151 val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
153 // Get the screenshot preference.
154 val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false)
156 // Disable screenshots if not allowed.
157 if (!allowScreenshots) {
158 alertDialog.window!!.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
161 // The alert dialog must be shown before items in the layout can be modified.
164 // Get handles for the layout items.
165 val currentIconLinearLayout = alertDialog.findViewById<LinearLayout>(R.id.current_icon_linearlayout)!!
166 val currentIconRadioButton = alertDialog.findViewById<RadioButton>(R.id.current_icon_radiobutton)!!
167 val currentIconImageView = alertDialog.findViewById<ImageView>(R.id.current_icon_imageview)!!
168 val webpageFavoriteIconLinearLayout = alertDialog.findViewById<LinearLayout>(R.id.webpage_favorite_icon_linearlayout)!!
169 webpageFavoriteIconRadioButton = alertDialog.findViewById(R.id.webpage_favorite_icon_radiobutton)!!
170 val webpageFavoriteIconImageView = alertDialog.findViewById<ImageView>(R.id.webpage_favorite_icon_imageview)!!
171 nameEditText = alertDialog.findViewById(R.id.bookmark_name_edittext)!!
172 urlEditText = alertDialog.findViewById(R.id.bookmark_url_edittext)!!
173 saveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
175 // Get the current favorite icon byte array from the cursor.
176 val currentIconByteArray = bookmarkCursor.getBlob(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON))
178 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
179 val currentIconBitmap = BitmapFactory.decodeByteArray(currentIconByteArray, 0, currentIconByteArray.size)
181 // Display the current icon bitmap.
182 currentIconImageView.setImageBitmap(currentIconBitmap)
184 // Set the webpage favorite icon bitmap.
185 webpageFavoriteIconImageView.setImageBitmap(favoriteIconBitmap)
187 // Store the current bookmark name and URL.
188 val currentName = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME))
189 val currentUrl = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL))
191 // Populate the edit texts.
192 nameEditText.setText(currentName)
193 urlEditText.setText(currentUrl)
195 // Initially disable the save button.
196 saveButton.isEnabled = false
198 // Set the radio button listeners. These perform a click on the linear layout, which contains the necessary logic.
199 currentIconRadioButton.setOnClickListener { currentIconLinearLayout.performClick() }
200 webpageFavoriteIconRadioButton.setOnClickListener { webpageFavoriteIconLinearLayout.performClick() }
202 // Set the current icon linear layout click listener.
203 currentIconLinearLayout.setOnClickListener {
204 // Check the current icon radio button.
205 currentIconRadioButton.isChecked = true
207 // Uncheck the webpage favorite icon radio button.
208 webpageFavoriteIconRadioButton.isChecked = false
210 // Update the save button.
211 updateSaveButton(currentName, currentUrl)
214 // Set the webpage favorite icon linear layout click listener.
215 webpageFavoriteIconLinearLayout.setOnClickListener {
216 // Check the webpage favorite icon radio button.
217 webpageFavoriteIconRadioButton.isChecked = true
219 // Uncheck the current icon radio button.
220 currentIconRadioButton.isChecked = false
222 // Update the save button.
223 updateSaveButton(currentName, currentUrl)
226 // Update the save button if the bookmark name changes.
227 nameEditText.addTextChangedListener(object: TextWatcher {
228 override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
232 override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
236 override fun afterTextChanged(s: Editable) {
237 // Update the save button.
238 updateSaveButton(currentName, currentUrl)
242 // Update the save button if the URL changes.
243 urlEditText.addTextChangedListener(object: TextWatcher {
244 override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
248 override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
252 override fun afterTextChanged(s: Editable) {
253 // Update the edit button.
254 updateSaveButton(currentName, currentUrl)
258 // Allow the enter key on the keyboard to save the bookmark from the bookmark name edit text.
259 nameEditText.setOnKeyListener { _: View?, keyCode: Int, event: KeyEvent ->
260 // Check the key code, event, and button status.
261 if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && saveButton.isEnabled) { // The enter key was pressed and the save button is enabled.
262 // Trigger the listener and return the dialog fragment to the parent activity.
263 editBookmarkListener.onSaveBookmark(this, selectedBookmarkDatabaseId, favoriteIconBitmap)
265 // Manually dismiss the alert dialog.
266 alertDialog.dismiss()
268 // Consume the event.
269 return@setOnKeyListener true
270 } else { // If any other key was pressed, or if the save button is currently disabled, do not consume the event.
271 return@setOnKeyListener false
275 // Allow the enter key on the keyboard to save the bookmark from the URL edit text.
276 urlEditText.setOnKeyListener { _: View?, keyCode: Int, event: KeyEvent ->
277 // Check the key code, event, and button status.
278 if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && saveButton.isEnabled) { // The enter key was pressed and the save button is enabled.
279 // Trigger the listener and return the dialog fragment to the parent activity.
280 editBookmarkListener.onSaveBookmark(this, selectedBookmarkDatabaseId, favoriteIconBitmap)
282 // Manually dismiss the alert dialog.
283 alertDialog.dismiss()
285 // Consume the event.
286 return@setOnKeyListener true
287 } else { // If any other key was pressed, or if the save button is currently disabled, do not consume the event.
288 return@setOnKeyListener false
292 // Return the alert dialog.
296 private fun updateSaveButton(currentName: String, currentUrl: String) {
297 // Get the text from the edit texts.
298 val newName = nameEditText.text.toString()
299 val newUrl = urlEditText.text.toString()
301 // Has the favorite icon changed?
302 val iconChanged = webpageFavoriteIconRadioButton.isChecked
304 // Has the name changed?
305 val nameChanged = newName != currentName
307 // Has the URL changed?
308 val urlChanged = newUrl != currentUrl
310 // Update the enabled status of the save button.
311 saveButton.isEnabled = iconChanged || nameChanged || urlChanged