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.app.Dialog
23 import android.content.Context
24 import android.content.DialogInterface
25 import android.graphics.Bitmap
26 import android.graphics.BitmapFactory
27 import android.os.Bundle
28 import android.text.Editable
29 import android.text.TextWatcher
30 import android.view.KeyEvent
31 import android.view.View
32 import android.view.WindowManager
33 import android.widget.Button
34 import android.widget.EditText
35 import android.widget.ImageView
36 import android.widget.LinearLayout
37 import android.widget.RadioButton
39 import androidx.appcompat.app.AlertDialog
40 import androidx.fragment.app.DialogFragment
41 import androidx.preference.PreferenceManager
43 import com.stoutner.privacybrowser.R
44 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper
46 import java.io.ByteArrayOutputStream
48 // Define the class constants.
49 private const val DATABASE_ID = "database_id"
50 private const val FAVORITE_ICON_BYTE_ARRAY = "favorite_icon_byte_array"
52 class EditBookmarkDialog : DialogFragment() {
53 // Declare the class variables.
54 private lateinit var editBookmarkListener: EditBookmarkListener
56 // Declare the class views.
57 private lateinit var webpageFavoriteIconRadioButton: RadioButton
58 private lateinit var nameEditText: EditText
59 private lateinit var urlEditText: EditText
60 private lateinit var saveButton: Button
62 // The public interface is used to send information back to the parent activity.
63 interface EditBookmarkListener {
64 fun onSaveBookmark(dialogFragment: DialogFragment, selectedBookmarkDatabaseId: Int, favoriteIconBitmap: Bitmap)
67 override fun onAttach(context: Context) {
68 // Run the default commands.
69 super.onAttach(context)
71 // Get a handle for the edit bookmark listener from the launching context.
72 editBookmarkListener = context as EditBookmarkListener
76 // `@JvmStatic` will no longer be required once all the code has transitioned to Kotlin.
78 fun bookmarkDatabaseId(databaseId: Int, favoriteIconBitmap: Bitmap): EditBookmarkDialog {
79 // Create a favorite icon byte array output stream.
80 val favoriteIconByteArrayOutputStream = ByteArrayOutputStream()
82 // 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).
83 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream)
85 // Convert the byte array output stream to a byte array.
86 val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray()
88 // Create an arguments bundle.
89 val argumentsBundle = Bundle()
91 // Store the variables in the bundle.
92 argumentsBundle.putInt(DATABASE_ID, databaseId)
93 argumentsBundle.putByteArray(FAVORITE_ICON_BYTE_ARRAY, favoriteIconByteArray)
95 // Create a new instance of the dialog.
96 val editBookmarkDialog = EditBookmarkDialog()
98 // Add the arguments bundle to the dialog.
99 editBookmarkDialog.arguments = argumentsBundle
101 // Return the new dialog.
102 return editBookmarkDialog
106 override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
107 // Get the arguments.
108 val arguments = requireArguments()
110 // Get the variables from the arguments.
111 val selectedBookmarkDatabaseId = arguments.getInt(DATABASE_ID)
112 val favoriteIconByteArray = arguments.getByteArray(FAVORITE_ICON_BYTE_ARRAY)!!
114 // Convert the favorite icon byte array to a bitmap.
115 val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size)
117 // Initialize the bookmarks database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
118 val bookmarksDatabaseHelper = BookmarksDatabaseHelper(context, null, null, 0)
120 // Get a cursor with the selected bookmark.
121 val bookmarkCursor = bookmarksDatabaseHelper.getBookmark(selectedBookmarkDatabaseId)
123 // Move the cursor to the first position.
124 bookmarkCursor.moveToFirst()
126 // Use an alert dialog builder to create the alert dialog.
127 val dialogBuilder = AlertDialog.Builder(requireContext(), R.style.PrivacyBrowserAlertDialog)
130 dialogBuilder.setTitle(R.string.edit_bookmark)
133 dialogBuilder.setView(R.layout.edit_bookmark_dialog)
135 // Set the cancel button listener. Using `null` as the listener closes the dialog without doing anything else.
136 dialogBuilder.setNegativeButton(R.string.cancel, null)
138 // Set the save button listener.
139 dialogBuilder.setPositiveButton(R.string.save) { _: DialogInterface?, _: Int ->
140 // Return the dialog fragment to the parent activity.
141 editBookmarkListener.onSaveBookmark(this, selectedBookmarkDatabaseId, favoriteIconBitmap)
144 // Create an alert dialog from the builder.
145 val alertDialog = dialogBuilder.create()
147 // Get a handle for the shared preferences.
148 val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
150 // Get the screenshot preference.
151 val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false)
153 // Disable screenshots if not allowed.
154 if (!allowScreenshots) {
155 alertDialog.window!!.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
158 // The alert dialog must be shown before items in the layout can be modified.
161 // Get handles for the layout items.
162 val currentIconLinearLayout = alertDialog.findViewById<LinearLayout>(R.id.current_icon_linearlayout)!!
163 val currentIconRadioButton = alertDialog.findViewById<RadioButton>(R.id.current_icon_radiobutton)!!
164 val currentIconImageView = alertDialog.findViewById<ImageView>(R.id.current_icon_imageview)!!
165 val webpageFavoriteIconLinearLayout = alertDialog.findViewById<LinearLayout>(R.id.webpage_favorite_icon_linearlayout)!!
166 webpageFavoriteIconRadioButton = alertDialog.findViewById(R.id.webpage_favorite_icon_radiobutton)!!
167 val webpageFavoriteIconImageView = alertDialog.findViewById<ImageView>(R.id.webpage_favorite_icon_imageview)!!
168 nameEditText = alertDialog.findViewById(R.id.bookmark_name_edittext)!!
169 urlEditText = alertDialog.findViewById(R.id.bookmark_url_edittext)!!
170 saveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
172 // Get the current favorite icon byte array from the cursor.
173 val currentIconByteArray = bookmarkCursor.getBlob(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON))
175 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
176 val currentIconBitmap = BitmapFactory.decodeByteArray(currentIconByteArray, 0, currentIconByteArray.size)
178 // Display the current icon bitmap.
179 currentIconImageView.setImageBitmap(currentIconBitmap)
181 // Set the webpage favorite icon bitmap.
182 webpageFavoriteIconImageView.setImageBitmap(favoriteIconBitmap)
184 // Store the current bookmark name and URL.
185 val currentName = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME))
186 val currentUrl = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL))
188 // Populate the edit texts.
189 nameEditText.setText(currentName)
190 urlEditText.setText(currentUrl)
192 // Initially disable the save button.
193 saveButton.isEnabled = false
195 // Set the radio button listeners. These perform a click on the linear layout, which contains the necessary logic.
196 currentIconRadioButton.setOnClickListener { currentIconLinearLayout.performClick() }
197 webpageFavoriteIconRadioButton.setOnClickListener { webpageFavoriteIconLinearLayout.performClick() }
199 // Set the current icon linear layout click listener.
200 currentIconLinearLayout.setOnClickListener {
201 // Check the current icon radio button.
202 currentIconRadioButton.isChecked = true
204 // Uncheck the webpage favorite icon radio button.
205 webpageFavoriteIconRadioButton.isChecked = false
207 // Update the save button.
208 updateSaveButton(currentName, currentUrl)
211 // Set the webpage favorite icon linear layout click listener.
212 webpageFavoriteIconLinearLayout.setOnClickListener {
213 // Check the webpage favorite icon radio button.
214 webpageFavoriteIconRadioButton.isChecked = true
216 // Uncheck the current icon radio button.
217 currentIconRadioButton.isChecked = false
219 // Update the save button.
220 updateSaveButton(currentName, currentUrl)
223 // Update the save button if the bookmark name changes.
224 nameEditText.addTextChangedListener(object: TextWatcher {
225 override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
229 override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
233 override fun afterTextChanged(s: Editable) {
234 // Update the save button.
235 updateSaveButton(currentName, currentUrl)
239 // Update the save button if the URL changes.
240 urlEditText.addTextChangedListener(object: TextWatcher {
241 override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
245 override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
249 override fun afterTextChanged(s: Editable) {
250 // Update the edit button.
251 updateSaveButton(currentName, currentUrl)
255 // Allow the enter key on the keyboard to save the bookmark from the bookmark name edit text.
256 nameEditText.setOnKeyListener { _: View?, keyCode: Int, event: KeyEvent ->
257 // Check the key code, event, and button status.
258 if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && saveButton.isEnabled) { // The enter key was pressed and the save button is enabled.
259 // Trigger the listener and return the dialog fragment to the parent activity.
260 editBookmarkListener.onSaveBookmark(this, selectedBookmarkDatabaseId, favoriteIconBitmap)
262 // Manually dismiss the alert dialog.
263 alertDialog.dismiss()
265 // Consume the event.
266 return@setOnKeyListener true
267 } else { // If any other key was pressed, or if the save button is currently disabled, do not consume the event.
268 return@setOnKeyListener false
272 // Allow the enter key on the keyboard to save the bookmark from the URL edit text.
273 urlEditText.setOnKeyListener { _: View?, keyCode: Int, event: KeyEvent ->
274 // Check the key code, event, and button status.
275 if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && saveButton.isEnabled) { // The enter key was pressed and the save button is enabled.
276 // Trigger the listener and return the dialog fragment to the parent activity.
277 editBookmarkListener.onSaveBookmark(this, selectedBookmarkDatabaseId, favoriteIconBitmap)
279 // Manually dismiss the alert dialog.
280 alertDialog.dismiss()
282 // Consume the event.
283 return@setOnKeyListener true
284 } else { // If any other key was pressed, or if the save button is currently disabled, do not consume the event.
285 return@setOnKeyListener false
289 // Return the alert dialog.
293 private fun updateSaveButton(currentName: String, currentUrl: String) {
294 // Get the text from the edit texts.
295 val newName = nameEditText.text.toString()
296 val newUrl = urlEditText.text.toString()
298 // Has the favorite icon changed?
299 val iconChanged = webpageFavoriteIconRadioButton.isChecked
301 // Has the name changed?
302 val nameChanged = newName != currentName
304 // Has the URL changed?
305 val urlChanged = newUrl != currentUrl
307 // Update the enabled status of the save button.
308 saveButton.isEnabled = iconChanged || nameChanged || urlChanged