]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/EditBookmarkFolderDialog.kt
First wrong button text in View Headers in night theme. https://redmine.stoutner...
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / EditBookmarkFolderDialog.kt
1 /*
2  * Copyright © 2016-2022 Soren Stoutner <soren@stoutner.com>.
3  *
4  * This file is part of Privacy Browser Android <https://www.stoutner.com/privacy-browser-android>.
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 package com.stoutner.privacybrowser.dialogs
21
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
38
39 import androidx.appcompat.app.AlertDialog
40 import androidx.fragment.app.DialogFragment
41 import androidx.preference.PreferenceManager
42
43 import com.stoutner.privacybrowser.R
44 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper
45
46 import java.io.ByteArrayOutputStream
47
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"
51
52 class EditBookmarkFolderDialog : DialogFragment() {
53     // Declare the class variables.
54     private lateinit var editBookmarkFolderListener: EditBookmarkFolderListener
55     private lateinit var bookmarksDatabaseHelper: BookmarksDatabaseHelper
56     private lateinit var currentFolderName: String
57
58     // Declare the class views.
59     private lateinit var currentIconRadioButton: RadioButton
60     private lateinit var folderNameEditText: EditText
61     private lateinit var saveButton: Button
62
63     // The public interface is used to send information back to the parent activity.
64     interface EditBookmarkFolderListener {
65         fun onSaveBookmarkFolder(dialogFragment: DialogFragment, selectedFolderDatabaseId: Int, favoriteIconBitmap: Bitmap)
66     }
67
68     override fun onAttach(context: Context) {
69         // Run the default commands.
70         super.onAttach(context)
71
72         // Get a handle for the edit bookmark folder listener from the launching context.
73         editBookmarkFolderListener = context as EditBookmarkFolderListener
74     }
75
76     companion object {
77         // `@JvmStatic` will no longer be required once all the code has transitioned to Kotlin.
78         @JvmStatic
79         fun folderDatabaseId(databaseId: Int, favoriteIconBitmap: Bitmap): EditBookmarkFolderDialog {
80             // Create a favorite icon byte array output stream.
81             val favoriteIconByteArrayOutputStream = ByteArrayOutputStream()
82
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)
85
86             // Convert the byte array output stream to a byte array.
87             val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray()
88
89             // Create an arguments bundle
90             val argumentsBundle = Bundle()
91
92             // Store the variables in the bundle.
93             argumentsBundle.putInt(DATABASE_ID, databaseId)
94             argumentsBundle.putByteArray(FAVORITE_ICON_BYTE_ARRAY, favoriteIconByteArray)
95
96             // Create a new instance of the dialog.
97             val editBookmarkFolderDialog = EditBookmarkFolderDialog()
98
99             // Add the arguments bundle to the dialog.
100             editBookmarkFolderDialog.arguments = argumentsBundle
101
102             // Return the new dialog.
103             return editBookmarkFolderDialog
104         }
105     }
106
107     override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
108         // Get a handle for the arguments.
109         val arguments = requireArguments()
110
111         // Get the variables from the arguments.
112         val selectedFolderDatabaseId = arguments.getInt(DATABASE_ID)
113         val favoriteIconByteArray = arguments.getByteArray(FAVORITE_ICON_BYTE_ARRAY)!!
114
115         // Convert the favorite icon byte array to a bitmap.
116         val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size)
117
118         // Initialize the database helper.
119         bookmarksDatabaseHelper = BookmarksDatabaseHelper(requireContext())
120
121         // Get a cursor with the selected folder.
122         val folderCursor = bookmarksDatabaseHelper.getBookmark(selectedFolderDatabaseId)
123
124         // Move the cursor to the first position.
125         folderCursor.moveToFirst()
126
127         // Use an alert dialog builder to create the alert dialog.
128         val dialogBuilder = AlertDialog.Builder(requireContext(), R.style.PrivacyBrowserAlertDialog)
129
130         // Set the title.
131         dialogBuilder.setTitle(R.string.edit_folder)
132
133         // Set the view.
134         dialogBuilder.setView(R.layout.edit_bookmark_folder_dialog)
135
136         // Set the cancel button listener.  Using `null` as the listener closes the dialog without doing anything else.
137         dialogBuilder.setNegativeButton(R.string.cancel, null)
138
139         // Set the save button listener.
140         dialogBuilder.setPositiveButton(R.string.save) { _: DialogInterface?, _: Int ->
141             // Return the dialog fragment to the parent activity on save.
142             editBookmarkFolderListener.onSaveBookmarkFolder(this, selectedFolderDatabaseId, favoriteIconBitmap)
143         }
144
145         // Create an alert dialog from the alert dialog builder.
146         val alertDialog = dialogBuilder.create()
147
148         // Get a handle for the shared preferences.
149         val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(requireContext())
150
151         // Get the screenshot preference.
152         val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false)
153
154         // Disable screenshots if not allowed.
155         if (!allowScreenshots) {
156             alertDialog.window!!.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
157         }
158
159         // The alert dialog must be shown before items in the layout can be modified.
160         alertDialog.show()
161
162         // Get handles for the views in the alert dialog.
163         val currentIconLinearLayout = alertDialog.findViewById<LinearLayout>(R.id.current_icon_linearlayout)!!
164         currentIconRadioButton = alertDialog.findViewById(R.id.current_icon_radiobutton)!!
165         val currentIconImageView = alertDialog.findViewById<ImageView>(R.id.current_icon_imageview)!!
166         val defaultIconLinearLayout = alertDialog.findViewById<LinearLayout>(R.id.default_icon_linearlayout)!!
167         val defaultIconRadioButton = alertDialog.findViewById<RadioButton>(R.id.default_icon_radiobutton)!!
168         val webpageFavoriteIconLinearLayout = alertDialog.findViewById<LinearLayout>(R.id.webpage_favorite_icon_linearlayout)!!
169         val webpageFavoriteIconRadioButton = alertDialog.findViewById<RadioButton>(R.id.webpage_favorite_icon_radiobutton)!!
170         val webpageFavoriteIconImageView = alertDialog.findViewById<ImageView>(R.id.webpage_favorite_icon_imageview)!!
171         folderNameEditText = alertDialog.findViewById(R.id.folder_name_edittext)!!
172         saveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
173
174         // Get the current favorite icon byte array from the cursor.
175         val currentIconByteArray = folderCursor.getBlob(folderCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.FAVORITE_ICON))
176
177         // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
178         val currentIconBitmap = BitmapFactory.decodeByteArray(currentIconByteArray, 0, currentIconByteArray.size)
179
180         // Display the current icon bitmap.
181         currentIconImageView.setImageBitmap(currentIconBitmap)
182
183         // Set the webpage favorite icon bitmap.
184         webpageFavoriteIconImageView.setImageBitmap(favoriteIconBitmap)
185
186         // Get the current folder name.
187         currentFolderName = folderCursor.getString(folderCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME))
188
189         // Display the current folder name.
190         folderNameEditText.setText(currentFolderName)
191
192         // Initially disable the save button.
193         saveButton.isEnabled = false
194
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         defaultIconRadioButton.setOnClickListener { defaultIconLinearLayout.performClick() }
198         webpageFavoriteIconRadioButton.setOnClickListener { webpageFavoriteIconLinearLayout.performClick() }
199
200         // Set the current icon linear layout click listener.
201         currentIconLinearLayout.setOnClickListener {
202             // Check the current icon radio button.
203             currentIconRadioButton.isChecked = true
204
205             // Uncheck the other radio buttons.
206             defaultIconRadioButton.isChecked = false
207             webpageFavoriteIconRadioButton.isChecked = false
208
209             // Update the save button.
210             updateSaveButton()
211         }
212
213         // Set the default icon linear layout click listener.
214         defaultIconLinearLayout.setOnClickListener {
215             // Check the default icon radio button.
216             defaultIconRadioButton.isChecked = true
217
218             // Uncheck the other radio buttons.
219             currentIconRadioButton.isChecked = false
220             webpageFavoriteIconRadioButton.isChecked = false
221
222             // Update the save button.
223             updateSaveButton()
224         }
225
226         // Set the webpage favorite icon linear layout click listener.
227         webpageFavoriteIconLinearLayout.setOnClickListener {
228             // Check the webpage favorite icon radio button.
229             webpageFavoriteIconRadioButton.isChecked = true
230
231             // Uncheck the other radio buttons.
232             currentIconRadioButton.isChecked = false
233             defaultIconRadioButton.isChecked = false
234
235             // Update the save button.
236             updateSaveButton()
237         }
238
239         // Update the status of the save button when the folder name is changed.
240         folderNameEditText.addTextChangedListener(object: TextWatcher {
241             override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
242                 // Do nothing.
243             }
244
245             override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
246                 // Do nothing.
247             }
248
249             override fun afterTextChanged(s: Editable) {
250                 // Update the save button.
251                 updateSaveButton()
252             }
253         })
254
255         // Allow the enter key on the keyboard to save the bookmark from the edit bookmark name edit text.
256         folderNameEditText.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                 editBookmarkFolderListener.onSaveBookmarkFolder(this, selectedFolderDatabaseId, favoriteIconBitmap)
261
262                 // Manually dismiss the the alert dialog.
263                 alertDialog.dismiss()
264
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
269             }
270         }
271
272         // Return the alert dialog.
273         return alertDialog
274     }
275
276     private fun updateSaveButton() {
277         // Get the new folder name.
278         val newFolderName = folderNameEditText.text.toString()
279
280         // Get a cursor for the new folder name if it exists.
281         val folderExistsCursor = bookmarksDatabaseHelper.getFolder(newFolderName)
282
283         // Is the new folder name empty?
284         val folderNameEmpty = newFolderName.isEmpty()
285
286         // Does the folder name already exist?
287         val folderNameAlreadyExists = (newFolderName != currentFolderName) && folderExistsCursor.count > 0
288
289         // Has the folder been renamed?
290         val folderRenamed = (newFolderName != currentFolderName) && !folderNameAlreadyExists
291
292         // Has the favorite icon changed?
293         val iconChanged = !currentIconRadioButton.isChecked && !folderNameAlreadyExists
294
295         // Enable the save button if something has been edited and the new folder name is valid.
296         saveButton.isEnabled = !folderNameEmpty && (folderRenamed || iconChanged)
297     }
298 }