]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/EditBookmarkFolderDialog.kt
Combine the light and dark Guide and About pages. https://redmine.stoutner.com/issue...
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / EditBookmarkFolderDialog.kt
1 /*
2  * Copyright © 2016-2020 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.RadioButton
38 import android.widget.RadioGroup
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 // Declare 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     // The public interface is used to send information back to the parent activity.
55     interface EditBookmarkFolderListener {
56         fun onSaveBookmarkFolder(dialogFragment: DialogFragment?, selectedFolderDatabaseId: Int, favoriteIconBitmap: Bitmap?)
57     }
58
59     // Declare the class variables.
60     private lateinit var editBookmarkFolderListener: EditBookmarkFolderListener
61     private lateinit var bookmarksDatabaseHelper: BookmarksDatabaseHelper
62     private lateinit var currentFolderName: String
63
64     // Declare the class views.
65     private lateinit var currentIconRadioButton: RadioButton
66     private lateinit var folderNameEditText: EditText
67     private lateinit var saveButton: Button
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.  Also, the function can then be moved out of a companion object and just become a package-level function.
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 `AlertDialog`.
137         dialogBuilder.setView(requireActivity().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 iconRadioGroup = alertDialog.findViewById<RadioGroup>(R.id.edit_folder_icon_radio_group)!!
167         currentIconRadioButton = alertDialog.findViewById(R.id.edit_folder_current_icon_radiobutton)!!
168         val currentIconImageView = alertDialog.findViewById<ImageView>(R.id.edit_folder_current_icon_imageview)!!
169         val webPageFavoriteIconImageView = alertDialog.findViewById<ImageView>(R.id.edit_folder_web_page_favorite_icon_imageview)!!
170         folderNameEditText = alertDialog.findViewById(R.id.edit_folder_name_edittext)!!
171         saveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
172
173         // Get the current favorite icon byte array from the cursor.
174         val currentIconByteArray = folderCursor.getBlob(folderCursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON))
175
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)
178
179         // Display the current icon bitmap.
180         currentIconImageView.setImageBitmap(currentIconBitmap)
181
182         // Set the new favorite icon bitmap.
183         webPageFavoriteIconImageView.setImageBitmap(favoriteIconBitmap)
184
185         // Get the current folder name.
186         currentFolderName = folderCursor.getString(folderCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME))
187
188         // Display the current folder name.
189         folderNameEditText.setText(currentFolderName)
190
191         // Initially disable the save button.
192         saveButton.isEnabled = false
193
194         // Update the status of the save button when the folder name is changed.
195         folderNameEditText.addTextChangedListener(object: TextWatcher {
196             override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
197                 // Do nothing.
198             }
199
200             override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
201                 // Do nothing.
202             }
203
204             override fun afterTextChanged(s: Editable) {
205                 // Update the save button.
206                 updateSaveButton()
207             }
208         })
209
210         // Update the status of the save button when the icon is changed.
211         iconRadioGroup.setOnCheckedChangeListener { _: RadioGroup?, _: Int ->
212             // Update the save button.
213             updateSaveButton()
214         }
215
216         // Allow the enter key on the keyboard to save the bookmark from the edit bookmark name edit text.
217         folderNameEditText.setOnKeyListener { _: View?, keyCode: Int, event: KeyEvent ->
218             // Check the key code, event, and button status.
219             if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && saveButton.isEnabled) {  // The enter key was pressed and the save button is enabled.
220                 // Trigger the listener and return the dialog fragment to the parent activity.
221                 editBookmarkFolderListener.onSaveBookmarkFolder(this, selectedFolderDatabaseId, favoriteIconBitmap)
222
223                 // Manually dismiss the the alert dialog.
224                 alertDialog.dismiss()
225
226                 // Consume the event.
227                 return@setOnKeyListener true
228             } else {  // If any other key was pressed, or if the save button is currently disabled, do not consume the event.
229                 return@setOnKeyListener false
230             }
231         }
232
233         // Return the alert dialog.
234         return alertDialog
235     }
236
237     private fun updateSaveButton() {
238         // Get the new folder name.
239         val newFolderName = folderNameEditText.text.toString()
240
241         // Get a cursor for the new folder name if it exists.
242         val folderExistsCursor = bookmarksDatabaseHelper.getFolder(newFolderName)
243
244         // Is the new folder name empty?
245         val folderNameEmpty = newFolderName.isEmpty()
246
247         // Does the folder name already exist?
248         val folderNameAlreadyExists = (newFolderName != currentFolderName) && folderExistsCursor.count > 0
249
250         // Has the folder been renamed?
251         val folderRenamed = (newFolderName != currentFolderName) && !folderNameAlreadyExists
252
253         // Has the favorite icon changed?
254         val iconChanged = !currentIconRadioButton.isChecked && !folderNameAlreadyExists
255
256         // Enable the save button if something has been edited and the new folder name is valid.
257         saveButton.isEnabled = !folderNameEmpty && (folderRenamed || iconChanged)
258     }
259 }