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