2 * Copyright © 2016-2020 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.RadioButton
38 import android.widget.RadioGroup
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 // Declare 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 // The public interface is used to send information back to the parent activity.
55 interface EditBookmarkListener {
56 fun onSaveBookmark(dialogFragment: DialogFragment, selectedBookmarkDatabaseId: Int, favoriteIconBitmap: Bitmap)
59 // Declare the class variables.
60 private lateinit var editBookmarkListener: EditBookmarkListener
62 // Declare the class views.
63 private lateinit var nameEditText: EditText
64 private lateinit var urlEditText: EditText
65 private lateinit var newIconRadioButton: RadioButton
66 private lateinit var saveButton: Button
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. Also, the function can then be moved out of a companion object and just become a package-level function.
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(requireActivity().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 iconRadioGroup = alertDialog.findViewById<RadioGroup>(R.id.edit_bookmark_icon_radiogroup)!!
166 val currentIconImageView = alertDialog.findViewById<ImageView>(R.id.edit_bookmark_current_icon)!!
167 val newFavoriteIconImageView = alertDialog.findViewById<ImageView>(R.id.edit_bookmark_webpage_favorite_icon)!!
168 newIconRadioButton = alertDialog.findViewById(R.id.edit_bookmark_webpage_favorite_icon_radiobutton)!!
169 nameEditText = alertDialog.findViewById(R.id.edit_bookmark_name_edittext)!!
170 urlEditText = alertDialog.findViewById(R.id.edit_bookmark_url_edittext)!!
171 saveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
173 // Get the current favorite icon byte array from the cursor.
174 val currentIconByteArray = bookmarkCursor.getBlob(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON))
176 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
177 val currentIconBitmap = BitmapFactory.decodeByteArray(currentIconByteArray, 0, currentIconByteArray.size)
179 // Display the current icon bitmap.
180 currentIconImageView.setImageBitmap(currentIconBitmap)
182 // Set the new favorite icon bitmap.
183 newFavoriteIconImageView.setImageBitmap(favoriteIconBitmap)
185 // Store the current bookmark name and URL.
186 val currentName = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME))
187 val currentUrl = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL))
189 // Populate the edit texts.
190 nameEditText.setText(currentName)
191 urlEditText.setText(currentUrl)
193 // Initially disable the save button.
194 saveButton.isEnabled = false
196 // Update the save button if the icon selection changes.
197 iconRadioGroup.setOnCheckedChangeListener { _: RadioGroup?, _: Int ->
198 // Update the save button.
199 updateSaveButton(currentName, currentUrl)
202 // Update the save button if the bookmark name changes.
203 nameEditText.addTextChangedListener(object: TextWatcher {
204 override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
208 override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
212 override fun afterTextChanged(s: Editable) {
213 // Update the save button.
214 updateSaveButton(currentName, currentUrl)
218 // Update the save button if the URL changes.
219 urlEditText.addTextChangedListener(object: TextWatcher {
220 override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
224 override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
228 override fun afterTextChanged(s: Editable) {
229 // Update the edit button.
230 updateSaveButton(currentName, currentUrl)
234 // Allow the enter key on the keyboard to save the bookmark from the bookmark name edit text.
235 nameEditText.setOnKeyListener { _: View?, keyCode: Int, event: KeyEvent ->
236 // Check the key code, event, and button status.
237 if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && saveButton.isEnabled) { // The enter key was pressed and the save button is enabled.
238 // Trigger the listener and return the dialog fragment to the parent activity.
239 editBookmarkListener.onSaveBookmark(this, selectedBookmarkDatabaseId, favoriteIconBitmap)
241 // Manually dismiss the alert dialog.
242 alertDialog.dismiss()
244 // Consume the event.
245 return@setOnKeyListener true
246 } else { // If any other key was pressed, or if the save button is currently disabled, do not consume the event.
247 return@setOnKeyListener false
251 // Allow the enter key on the keyboard to save the bookmark from the URL edit text.
252 urlEditText.setOnKeyListener { _: View?, keyCode: Int, event: KeyEvent ->
253 // Check the key code, event, and button status.
254 if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && saveButton.isEnabled) { // The enter key was pressed and the save button is enabled.
255 // Trigger the listener and return the dialog fragment to the parent activity.
256 editBookmarkListener.onSaveBookmark(this, selectedBookmarkDatabaseId, favoriteIconBitmap)
258 // Manually dismiss the alert dialog.
259 alertDialog.dismiss()
261 // Consume the event.
262 return@setOnKeyListener true
263 } else { // If any other key was pressed, or if the save button is currently disabled, do not consume the event.
264 return@setOnKeyListener false
268 // Return the alert dialog.
272 private fun updateSaveButton(currentName: String, currentUrl: String) {
273 // Get the text from the edit texts.
274 val newName = nameEditText.text.toString()
275 val newUrl = urlEditText.text.toString()
277 // Has the favorite icon changed?
278 val iconChanged = newIconRadioButton.isChecked
280 // Has the name changed?
281 val nameChanged = newName != currentName
283 // Has the URL changed?
284 val urlChanged = newUrl != currentUrl
286 // Update the enabled status of the save button.
287 saveButton.isEnabled = iconChanged || nameChanged || urlChanged