]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateBookmarkFolderDialog.kt
Fix a crash when opening a drawer while restarting. https://redmine.stoutner.com...
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / CreateBookmarkFolderDialog.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.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.EditText
34 import android.widget.ImageView
35 import android.widget.LinearLayout
36 import android.widget.RadioButton
37
38 import androidx.appcompat.app.AlertDialog
39 import androidx.fragment.app.DialogFragment
40 import androidx.preference.PreferenceManager
41
42 import com.stoutner.privacybrowser.R
43 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper
44
45 import java.io.ByteArrayOutputStream
46
47 // Define the class constants.
48 private const val FAVORITE_ICON_BYTE_ARRAY = "favorite_icon_byte_array"
49
50 class CreateBookmarkFolderDialog : DialogFragment() {
51     // Declare the class variables.
52     private lateinit var createBookmarkFolderListener: CreateBookmarkFolderListener
53
54     // The public interface is used to send information back to the parent activity.
55     interface CreateBookmarkFolderListener {
56         fun onCreateBookmarkFolder(dialogFragment: DialogFragment, favoriteIconBitmap: Bitmap)
57     }
58
59     override fun onAttach(context: Context) {
60         // Run the default commands.
61         super.onAttach(context)
62
63         // Get a handle for the create bookmark folder listener from the launching context.
64         createBookmarkFolderListener = context as CreateBookmarkFolderListener
65     }
66
67     companion object {
68         // `@JvmStatic` will no longer be required once all the code has transitioned to Kotlin.
69         @JvmStatic
70         fun createBookmarkFolder(favoriteIconBitmap: Bitmap): CreateBookmarkFolderDialog {
71             // Create a favorite icon byte array output stream.
72             val favoriteIconByteArrayOutputStream = ByteArrayOutputStream()
73
74             // 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).
75             favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream)
76
77             // Convert the byte array output stream to a byte array.
78             val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray()
79
80             // Create an arguments bundle.
81             val argumentsBundle = Bundle()
82
83             // Store the favorite icon in the bundle.
84             argumentsBundle.putByteArray(FAVORITE_ICON_BYTE_ARRAY, favoriteIconByteArray)
85
86             // Create a new instance of the dialog.
87             val createBookmarkFolderDialog = CreateBookmarkFolderDialog()
88
89             // Add the bundle to the dialog.
90             createBookmarkFolderDialog.arguments = argumentsBundle
91
92             // Return the new dialog.
93             return createBookmarkFolderDialog
94         }
95     }
96
97     override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
98         // Get the arguments.
99         val arguments = requireArguments()
100
101         // Get the favorite icon byte array.
102         val favoriteIconByteArray = arguments.getByteArray(FAVORITE_ICON_BYTE_ARRAY)!!
103
104         // Convert the favorite icon byte array to a bitmap.
105         val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size)
106
107         // Use an alert dialog builder to create the dialog.
108         val dialogBuilder = AlertDialog.Builder(requireContext(), R.style.PrivacyBrowserAlertDialog)
109
110         // Set the title.
111         dialogBuilder.setTitle(R.string.create_folder)
112
113         // Set the view.
114         dialogBuilder.setView(R.layout.create_bookmark_folder_dialog)
115
116         // Set a listener on the cancel button.  Using `null` as the listener closes the dialog without doing anything else.
117         dialogBuilder.setNegativeButton(R.string.cancel, null)
118
119         // Set the create button listener.
120         dialogBuilder.setPositiveButton(R.string.create) { _: DialogInterface, _: Int ->
121             // Return the dialog fragment to the parent activity on create.
122             createBookmarkFolderListener.onCreateBookmarkFolder(this, favoriteIconBitmap)
123         }
124
125         // Create an alert dialog from the builder.
126         val alertDialog = dialogBuilder.create()
127
128         // Get a handle for the shared preferences.
129         val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
130
131         // Get the screenshot preference.
132         val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false)
133
134         // Disable screenshots if not allowed.
135         if (!allowScreenshots) {
136             alertDialog.window!!.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
137         }
138
139         // Display the keyboard.
140         alertDialog.window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
141
142         // The alert dialog must be shown before the content can be modified.
143         alertDialog.show()
144
145         // Get handles for the views in the dialog.
146         val defaultIconLinearLayout = alertDialog.findViewById<LinearLayout>(R.id.default_icon_linearlayout)!!
147         val defaultIconRadioButton = alertDialog.findViewById<RadioButton>(R.id.default_icon_radiobutton)!!
148         val webpageFavoriteIconLinearLayout = alertDialog.findViewById<LinearLayout>(R.id.webpage_favorite_icon_linearlayout)!!
149         val webpageFavoriteIconRadioButton = alertDialog.findViewById<RadioButton>(R.id.webpage_favorite_icon_radiobutton)!!
150         val webpageFavoriteIconImageView = alertDialog.findViewById<ImageView>(R.id.webpage_favorite_icon_imageview)!!
151         val folderNameEditText = alertDialog.findViewById<EditText>(R.id.folder_name_edittext)!!
152         val createButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
153
154         // Display the current favorite icon.
155         webpageFavoriteIconImageView.setImageBitmap(favoriteIconBitmap)
156
157         // Initially disable the create button.
158         createButton.isEnabled = false
159
160         // Set the radio button listeners.  These perform a click on the linear layout, which contains the necessary logic.
161         defaultIconRadioButton.setOnClickListener { defaultIconLinearLayout.performClick() }
162         webpageFavoriteIconRadioButton.setOnClickListener { webpageFavoriteIconLinearLayout.performClick() }
163
164         // Set the default icon linear layout click listener.
165         defaultIconLinearLayout.setOnClickListener {
166             // Check the default icon radio button.
167             defaultIconRadioButton.isChecked = true
168
169             // Uncheck the webpage favorite icon radio button.
170             webpageFavoriteIconRadioButton.isChecked = false
171         }
172
173         // Set the webpage favorite icon linear layout click listener.
174         webpageFavoriteIconLinearLayout.setOnClickListener {
175             // Check the webpage favorite icon radio button.
176             webpageFavoriteIconRadioButton.isChecked = true
177
178             // Uncheck the default icon radio button.
179             defaultIconRadioButton.isChecked = false
180         }
181
182         // Initialize the database helper.  The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
183         val bookmarksDatabaseHelper = BookmarksDatabaseHelper(context, null, null, 0)
184
185         // Enable the create button if the new folder name is unique.
186         folderNameEditText.addTextChangedListener(object: TextWatcher {
187             override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
188                 // Do nothing.
189             }
190
191             override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
192                 // Do nothing.
193             }
194
195             override fun afterTextChanged(editable: Editable) {
196                 // Convert the current text to a string.
197                 val folderName = editable.toString()
198
199                 // Check if a folder with the name already exists.
200                 val folderExistsCursor = bookmarksDatabaseHelper.getFolder(folderName)
201
202                 // Enable the create button if the new folder name is not empty and doesn't already exist.
203                 createButton.isEnabled = folderName.isNotEmpty() && (folderExistsCursor.count == 0)
204             }
205         })
206
207         // Set the enter key on the keyboard to create the folder from the edit text.
208         folderNameEditText.setOnKeyListener { _: View?, keyCode: Int, keyEvent: KeyEvent ->
209             // Check the key code, event, and button status.
210             if (keyEvent.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && createButton.isEnabled) {  // The event is a key-down on the enter key and the create button is enabled.
211                 // Trigger the create bookmark folder listener and return the dialog fragment to the parent activity.
212                 createBookmarkFolderListener.onCreateBookmarkFolder(this, favoriteIconBitmap)
213
214                 // Manually dismiss the alert dialog.
215                 alertDialog.dismiss()
216
217                 // Consume the event.
218                 return@setOnKeyListener true
219             } else {  // Some other key was pressed or the create button is disabled.
220                 return@setOnKeyListener false
221             }
222         }
223
224         // Return the alert dialog.
225         return alertDialog
226     }
227 }