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