2 * Copyright © 2016-2021 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
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.
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.
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/>.
20 package com.stoutner.privacybrowser.dialogs
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.EditText
35 import android.widget.ImageView
36 import android.widget.LinearLayout
37 import android.widget.RadioButton
39 import androidx.appcompat.app.AlertDialog
40 import androidx.fragment.app.DialogFragment
41 import androidx.preference.PreferenceManager
43 import com.stoutner.privacybrowser.R
44 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper
46 import java.io.ByteArrayOutputStream
48 // Define the class constants.
49 private const val FAVORITE_ICON_BYTE_ARRAY = "favorite_icon_byte_array"
51 class CreateBookmarkFolderDialog : DialogFragment() {
52 // Declare the class variables.
53 private lateinit var createBookmarkFolderListener: CreateBookmarkFolderListener
55 // The public interface is used to send information back to the parent activity.
56 interface CreateBookmarkFolderListener {
57 fun onCreateBookmarkFolder(dialogFragment: DialogFragment, favoriteIconBitmap: Bitmap)
60 override fun onAttach(context: Context) {
61 // Run the default commands.
62 super.onAttach(context)
64 // Get a handle for the create bookmark folder listener from the launching context.
65 createBookmarkFolderListener = context as CreateBookmarkFolderListener
69 // `@JvmStatic` will no longer be required once all the code has transitioned to Kotlin.
71 fun createBookmarkFolder(favoriteIconBitmap: Bitmap): CreateBookmarkFolderDialog {
72 // Create a favorite icon byte array output stream.
73 val favoriteIconByteArrayOutputStream = ByteArrayOutputStream()
75 // 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).
76 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream)
78 // Convert the byte array output stream to a byte array.
79 val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray()
81 // Create an arguments bundle.
82 val argumentsBundle = Bundle()
84 // Store the favorite icon in the bundle.
85 argumentsBundle.putByteArray(FAVORITE_ICON_BYTE_ARRAY, favoriteIconByteArray)
87 // Create a new instance of the dialog.
88 val createBookmarkFolderDialog = CreateBookmarkFolderDialog()
90 // Add the bundle to the dialog.
91 createBookmarkFolderDialog.arguments = argumentsBundle
93 // Return the new dialog.
94 return createBookmarkFolderDialog
98 // `@SuppressLint("InflateParams")` removes the warning about using `null` as the parent view group when inflating the alert dialog.
99 @SuppressLint("InflateParams")
100 override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
101 // Get the arguments.
102 val arguments = requireArguments()
104 // Get the favorite icon byte array.
105 val favoriteIconByteArray = arguments.getByteArray(FAVORITE_ICON_BYTE_ARRAY)!!
107 // Convert the favorite icon byte array to a bitmap.
108 val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size)
110 // Use an alert dialog builder to create the dialog.
111 val dialogBuilder = AlertDialog.Builder(requireContext(), R.style.PrivacyBrowserAlertDialog)
114 dialogBuilder.setTitle(R.string.create_folder)
116 // Set the view. The parent view is null because it will be assigned by the alert dialog.
117 dialogBuilder.setView(layoutInflater.inflate(R.layout.create_bookmark_folder_dialog, null))
119 // Set a listener on the cancel button. Using `null` as the listener closes the dialog without doing anything else.
120 dialogBuilder.setNegativeButton(R.string.cancel, null)
122 // Set the create button listener.
123 dialogBuilder.setPositiveButton(R.string.create) { _: DialogInterface, _: Int ->
124 // Return the dialog fragment to the parent activity on create.
125 createBookmarkFolderListener.onCreateBookmarkFolder(this, favoriteIconBitmap)
128 // Create an alert dialog from the builder.
129 val alertDialog = dialogBuilder.create()
131 // Get a handle for the shared preferences.
132 val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
134 // Get the screenshot preference.
135 val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false)
137 // Disable screenshots if not allowed.
138 if (!allowScreenshots) {
139 alertDialog.window!!.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
142 // Display the keyboard.
143 alertDialog.window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
145 // The alert dialog must be shown before the content can be modified.
148 // Get handles for the views in the dialog.
149 val defaultIconLinearLayout = alertDialog.findViewById<LinearLayout>(R.id.default_icon_linearlayout)!!
150 val defaultIconRadioButton = alertDialog.findViewById<RadioButton>(R.id.default_icon_radiobutton)!!
151 val webpageFavoriteIconLinearLayout = alertDialog.findViewById<LinearLayout>(R.id.webpage_favorite_icon_linearlayout)!!
152 val webpageFavoriteIconRadioButton = alertDialog.findViewById<RadioButton>(R.id.webpage_favorite_icon_radiobutton)!!
153 val webpageFavoriteIconImageView = alertDialog.findViewById<ImageView>(R.id.webpage_favorite_icon_imageview)!!
154 val folderNameEditText = alertDialog.findViewById<EditText>(R.id.folder_name_edittext)!!
155 val createButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
157 // Display the current favorite icon.
158 webpageFavoriteIconImageView.setImageBitmap(favoriteIconBitmap)
160 // Initially disable the create button.
161 createButton.isEnabled = false
163 // Set the radio button listeners. These perform a click on the linear layout, which contains the necessary logic.
164 defaultIconRadioButton.setOnClickListener { defaultIconLinearLayout.performClick() }
165 webpageFavoriteIconRadioButton.setOnClickListener { webpageFavoriteIconLinearLayout.performClick() }
167 // Set the default icon linear layout click listener.
168 defaultIconLinearLayout.setOnClickListener {
169 // Check the default icon radio button.
170 defaultIconRadioButton.isChecked = true
172 // Uncheck the webpage favorite icon radio button.
173 webpageFavoriteIconRadioButton.isChecked = false
176 // Set the webpage favorite icon linear layout click listener.
177 webpageFavoriteIconLinearLayout.setOnClickListener {
178 // Check the webpage favorite icon radio button.
179 webpageFavoriteIconRadioButton.isChecked = true
181 // Uncheck the default icon radio button.
182 defaultIconRadioButton.isChecked = false
185 // Initialize the database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
186 val bookmarksDatabaseHelper = BookmarksDatabaseHelper(context, null, null, 0)
188 // Enable the create button if the new folder name is unique.
189 folderNameEditText.addTextChangedListener(object: TextWatcher {
190 override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
194 override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
198 override fun afterTextChanged(editable: Editable) {
199 // Convert the current text to a string.
200 val folderName = editable.toString()
202 // Check if a folder with the name already exists.
203 val folderExistsCursor = bookmarksDatabaseHelper.getFolder(folderName)
205 // Enable the create button if the new folder name is not empty and doesn't already exist.
206 createButton.isEnabled = folderName.isNotEmpty() && (folderExistsCursor.count == 0)
210 // Set the enter key on the keyboard to create the folder from the edit text.
211 folderNameEditText.setOnKeyListener { _: View?, keyCode: Int, keyEvent: KeyEvent ->
212 // Check the key code, event, and button status.
213 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.
214 // Trigger the create bookmark folder listener and return the dialog fragment to the parent activity.
215 createBookmarkFolderListener.onCreateBookmarkFolder(this, favoriteIconBitmap)
217 // Manually dismiss the alert dialog.
218 alertDialog.dismiss()
220 // Consume the event.
221 return@setOnKeyListener true
222 } else { // Some other key was pressed or the create button is disabled.
223 return@setOnKeyListener false
227 // Return the alert dialog.