]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/EditBookmarkFolderDialog.kt
Migrate five dialogs to Kotlin. https://redmine.stoutner.com/issues/604
[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 package com.stoutner.privacybrowser.dialogs
20
21 import android.annotation.SuppressLint
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.RadioButton
37 import android.widget.RadioGroup
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 // Declare 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     // The public interface is used to send information back to the parent activity.
54     interface EditBookmarkFolderListener {
55         fun onSaveBookmarkFolder(dialogFragment: DialogFragment?, selectedFolderDatabaseId: Int, favoriteIconBitmap: Bitmap?)
56     }
57
58     // Declare the class variables.
59     private lateinit var editBookmarkFolderListener: EditBookmarkFolderListener
60     private lateinit var bookmarksDatabaseHelper: BookmarksDatabaseHelper
61     private lateinit var currentFolderName: String
62
63     // Declare the class views.
64     private lateinit var currentIconRadioButton: RadioButton
65     private lateinit var folderNameEditText: EditText
66     private lateinit var saveButton: Button
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.  Also, the function can then be moved out of a companion object and just become a package-level function.
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     // `@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 a handle for the arguments.
111         val arguments = requireArguments()
112
113         // Get the variables from the arguments.
114         val selectedFolderDatabaseId = arguments.getInt(DATABASE_ID)
115         val favoriteIconByteArray = arguments.getByteArray(FAVORITE_ICON_BYTE_ARRAY)!!
116
117         // Convert the favorite icon byte array to a bitmap.
118         val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size)
119
120         // Initialize the database helper.  The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
121         bookmarksDatabaseHelper = BookmarksDatabaseHelper(context, null, null, 0)
122
123         // Get a cursor with the selected folder.
124         val folderCursor = bookmarksDatabaseHelper.getBookmark(selectedFolderDatabaseId)
125
126         // Move the cursor to the first position.
127         folderCursor.moveToFirst()
128
129         // Use an alert dialog builder to create the alert dialog.
130         val dialogBuilder = AlertDialog.Builder(requireContext(), R.style.PrivacyBrowserAlertDialog)
131
132         // Set the title.
133         dialogBuilder.setTitle(R.string.edit_folder)
134
135         // Set the view.  The parent view is `null` because it will be assigned by `AlertDialog`.
136         dialogBuilder.setView(requireActivity().layoutInflater.inflate(R.layout.edit_bookmark_folder_dialog, null))
137
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)
140
141         // Set the save button listener.
142         dialogBuilder.setPositiveButton(R.string.save) { _: DialogInterface?, _: Int ->
143             // Return the dialog fragment to the parent activity on save.
144             editBookmarkFolderListener.onSaveBookmarkFolder(this, selectedFolderDatabaseId, favoriteIconBitmap)
145         }
146
147         // Create an alert dialog from the alert dialog builder.
148         val alertDialog = dialogBuilder.create()
149
150         // Get a handle for the shared preferences.
151         val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
152
153         // Get the screenshot preference.
154         val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false)
155
156         // Disable screenshots if not allowed.
157         if (!allowScreenshots) {
158             alertDialog.window!!.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
159         }
160
161         // The alert dialog must be shown before items in the layout can be modified.
162         alertDialog.show()
163
164         // Get handles for the views in the alert dialog.
165         val iconRadioGroup = alertDialog.findViewById<RadioGroup>(R.id.edit_folder_icon_radio_group)!!
166         currentIconRadioButton = alertDialog.findViewById(R.id.edit_folder_current_icon_radiobutton)!!
167         val currentIconImageView = alertDialog.findViewById<ImageView>(R.id.edit_folder_current_icon_imageview)!!
168         val webPageFavoriteIconImageView = alertDialog.findViewById<ImageView>(R.id.edit_folder_web_page_favorite_icon_imageview)!!
169         folderNameEditText = alertDialog.findViewById(R.id.edit_folder_name_edittext)!!
170         saveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
171
172         // Get the current favorite icon byte array from the cursor.
173         val currentIconByteArray = folderCursor.getBlob(folderCursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON))
174
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)
177
178         // Display the current icon bitmap.
179         currentIconImageView.setImageBitmap(currentIconBitmap)
180
181         // Set the new favorite icon bitmap.
182         webPageFavoriteIconImageView.setImageBitmap(favoriteIconBitmap)
183
184         // Get the current folder name.
185         currentFolderName = folderCursor.getString(folderCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME))
186
187         // Display the current folder name.
188         folderNameEditText.setText(currentFolderName)
189
190         // Initially disable the save button.
191         saveButton.isEnabled = false
192
193         // Update the status of the save button when the folder name is changed.
194         folderNameEditText.addTextChangedListener(object: TextWatcher {
195             override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
196                 // Do nothing.
197             }
198
199             override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
200                 // Do nothing.
201             }
202
203             override fun afterTextChanged(s: Editable) {
204                 // Update the save button.
205                 updateSaveButton()
206             }
207         })
208
209         // Update the status of the save button when the icon is changed.
210         iconRadioGroup.setOnCheckedChangeListener { _: RadioGroup?, _: Int ->
211             // Update the save button.
212             updateSaveButton()
213         }
214
215         // Allow the enter key on the keyboard to save the bookmark from the edit bookmark name edit text.
216         folderNameEditText.setOnKeyListener { _: View?, keyCode: Int, event: KeyEvent ->
217             // Check the key code, event, and button status.
218             if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && saveButton.isEnabled) {  // The enter key was pressed and the save button is enabled.
219                 // Trigger the listener and return the dialog fragment to the parent activity.
220                 editBookmarkFolderListener.onSaveBookmarkFolder(this, selectedFolderDatabaseId, favoriteIconBitmap)
221
222                 // Manually dismiss the the alert dialog.
223                 alertDialog.dismiss()
224
225                 // Consume the event.
226                 return@setOnKeyListener true
227             } else {  // If any other key was pressed, or if the save button is currently disabled, do not consume the event.
228                 return@setOnKeyListener false
229             }
230         }
231
232         // Return the alert dialog.
233         return alertDialog
234     }
235
236     private fun updateSaveButton() {
237         // Get the new folder name.
238         val newFolderName = folderNameEditText.text.toString()
239
240         // Get a cursor for the new folder name if it exists.
241         val folderExistsCursor = bookmarksDatabaseHelper.getFolder(newFolderName)
242
243         // Is the new folder name empty?
244         val folderNameEmpty = newFolderName.isEmpty()
245
246         // Does the folder name already exist?
247         val folderNameAlreadyExists = (newFolderName != currentFolderName) && folderExistsCursor.count > 0
248
249         // Has the folder been renamed?
250         val folderRenamed = (newFolderName != currentFolderName) && !folderNameAlreadyExists
251
252         // Has the favorite icon changed?
253         val iconChanged = !currentIconRadioButton.isChecked && !folderNameAlreadyExists
254
255         // Enable the save button if something has been edited and the new folder name is valid.
256         saveButton.isEnabled = !folderNameEmpty && (folderRenamed || iconChanged)
257     }
258 }