2 * Copyright 2016-2023 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser Android <https://www.stoutner.com/privacy-browser-android>.
6 * Privacy Browser Android 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 Android 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 Android. If not, see <http://www.gnu.org/licenses/>.
20 package com.stoutner.privacybrowser.dialogs
22 import android.app.Dialog
23 import android.content.Context
24 import android.content.DialogInterface
25 import android.database.Cursor
26 import android.database.MatrixCursor
27 import android.database.MergeCursor
28 import android.graphics.Bitmap
29 import android.graphics.BitmapFactory
30 import android.graphics.drawable.BitmapDrawable
31 import android.os.Bundle
32 import android.view.View
33 import android.view.ViewGroup
34 import android.view.WindowManager
35 import android.widget.AdapterView
36 import android.widget.AdapterView.OnItemClickListener
37 import android.widget.ImageView
38 import android.widget.ListView
39 import android.widget.TextView
41 import androidx.appcompat.app.AlertDialog
42 import androidx.core.content.ContextCompat
43 import androidx.cursoradapter.widget.CursorAdapter
44 import androidx.fragment.app.DialogFragment
45 import androidx.preference.PreferenceManager
47 import com.stoutner.privacybrowser.R
48 import com.stoutner.privacybrowser.activities.HOME_FOLDER_ID
49 import com.stoutner.privacybrowser.helpers.BOOKMARK_NAME
50 import com.stoutner.privacybrowser.helpers.FAVORITE_ICON
51 import com.stoutner.privacybrowser.helpers.FOLDER_ID
52 import com.stoutner.privacybrowser.helpers.ID
53 import com.stoutner.privacybrowser.helpers.PARENT_FOLDER_ID
54 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper
56 import kotlinx.coroutines.CoroutineScope
57 import kotlinx.coroutines.Dispatchers
58 import kotlinx.coroutines.launch
59 import kotlinx.coroutines.withContext
61 import java.io.ByteArrayOutputStream
63 // Define the class constants.
64 private const val CURRENT_FOLDER_ID = "A"
65 private const val SELECTED_BOOKMARKS_LONG_ARRAY = "B"
67 class MoveToFolderDialog : DialogFragment() {
69 fun moveBookmarks(currentFolderId: Long, selectedBookmarksLongArray: LongArray): MoveToFolderDialog {
70 // Create an arguments bundle.
71 val argumentsBundle = Bundle()
73 // Store the arguments in the bundle.
74 argumentsBundle.putLong(CURRENT_FOLDER_ID, currentFolderId)
75 argumentsBundle.putLongArray(SELECTED_BOOKMARKS_LONG_ARRAY, selectedBookmarksLongArray)
77 // Create a new instance of the dialog.
78 val moveToFolderDialog = MoveToFolderDialog()
80 // And the bundle to the dialog.
81 moveToFolderDialog.arguments = argumentsBundle
83 // Return the new dialog.
84 return moveToFolderDialog
88 // Declare the class variables.
89 private lateinit var moveToFolderListener: MoveToFolderListener
90 private lateinit var bookmarksDatabaseHelper: BookmarksDatabaseHelper
92 // The public interface is used to send information back to the parent activity.
93 interface MoveToFolderListener {
94 fun onMoveToFolder(dialogFragment: DialogFragment)
97 override fun onAttach(context: Context) {
98 // Run the default commands.
99 super.onAttach(context)
101 // Get a handle for the move to folder listener from the launching context.
102 moveToFolderListener = context as MoveToFolderListener
105 override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
106 // Get the data from the arguments.
107 val currentFolderId = requireArguments().getLong(CURRENT_FOLDER_ID, HOME_FOLDER_ID)
108 val selectedBookmarksLongArray = requireArguments().getLongArray(SELECTED_BOOKMARKS_LONG_ARRAY)!!
110 // Initialize the database helper.
111 bookmarksDatabaseHelper = BookmarksDatabaseHelper(requireContext())
113 // Use an alert dialog builder to create the alert dialog.
114 val dialogBuilder = AlertDialog.Builder(requireContext(), R.style.PrivacyBrowserAlertDialog)
117 dialogBuilder.setIcon(R.drawable.move_to_folder_blue)
120 dialogBuilder.setTitle(R.string.move_to_folder)
123 dialogBuilder.setView(R.layout.move_to_folder_dialog)
125 // Set the listener for the cancel button. Using `null` as the listener closes the dialog without doing anything else.
126 dialogBuilder.setNegativeButton(R.string.cancel, null)
128 // Set the listener fo the move button.
129 dialogBuilder.setPositiveButton(R.string.move) { _: DialogInterface?, _: Int ->
130 // Return the dialog fragment to the parent activity on move.
131 moveToFolderListener.onMoveToFolder(this)
134 // Create an alert dialog from the alert dialog builder.
135 val alertDialog = dialogBuilder.create()
137 // Get a handle for the shared preferences.
138 val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(requireContext())
140 // Get the screenshot preference.
141 val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false)
143 // Disable screenshots if not allowed.
144 if (!allowScreenshots) {
145 // Disable screenshots.
146 alertDialog.window!!.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
149 // The alert dialog must be shown before items in the layout can be modified.
152 // Get a handle for the positive button.
153 val moveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
155 // Initially disable the positive button.
156 moveButton.isEnabled = false
158 // Create a list of folders not to display.
159 val folderIdsNotToDisplay = mutableListOf<Long>()
161 // Add any selected folders and their subfolders to the list of folders not to display.
162 for (databaseIdLong in selectedBookmarksLongArray) {
163 // Get the database ID int for each selected bookmark.
164 val databaseIdInt = databaseIdLong.toInt()
166 // Check to see if the bookmark is a folder.
167 if (bookmarksDatabaseHelper.isFolder(databaseIdInt)) {
168 // Add the folder to the list of folders not to display.
169 folderIdsNotToDisplay.add(bookmarksDatabaseHelper.getFolderId(databaseIdInt))
173 // Check to see if the bookmark is currently in the home folder.
174 if (currentFolderId == HOME_FOLDER_ID) { // The bookmark is currently in the home folder. Don't display `Home Folder` at the top of the list view.
175 // Get a cursor containing the folders to display.
176 val foldersCursor = bookmarksDatabaseHelper.getFoldersExcept(folderIdsNotToDisplay)
178 // Populate the folders cursor adapter.
179 val foldersCursorAdapter = populateFoldersCursorAdapter(requireContext(), foldersCursor)
181 // Get a handle for the folders list view.
182 val foldersListView = alertDialog.findViewById<ListView>(R.id.move_to_folder_listview)!!
184 // Set the folder list view adapter.
185 foldersListView.adapter = foldersCursorAdapter
187 // Enable the move button when a folder is selected.
188 foldersListView.onItemClickListener = OnItemClickListener { _: AdapterView<*>?, _: View?, _: Int, _: Long ->
189 // Enable the move button.
190 moveButton.isEnabled = true
192 } else { // The current folder is not directly in the home folder. Display `Home Folder` at the top of the list view.
193 // Get the home folder icon drawable.
194 val homeFolderIconDrawable = ContextCompat.getDrawable(requireActivity().applicationContext, R.drawable.folder_gray_bitmap)
196 // Convert the home folder icon drawable to a bitmap drawable.
197 val homeFolderIconBitmapDrawable = homeFolderIconDrawable as BitmapDrawable
199 // Convert the home folder bitmap drawable to a bitmap.
200 val homeFolderIconBitmap = homeFolderIconBitmapDrawable.bitmap
202 // Create a home folder icon byte array output stream.
203 val homeFolderIconByteArrayOutputStream = ByteArrayOutputStream()
205 // Compress the bitmap using a coroutine with Dispatchers.Default.
206 CoroutineScope(Dispatchers.Main).launch {
207 withContext(Dispatchers.Default) {
208 // Convert the home folder bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
209 homeFolderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, homeFolderIconByteArrayOutputStream)
211 // Convert the home folder icon byte array output stream to a byte array.
212 val homeFolderIconByteArray = homeFolderIconByteArrayOutputStream.toByteArray()
214 // Setup the home folder matrix cursor column names.
215 val homeFolderMatrixCursorColumnNames = arrayOf(ID, BOOKMARK_NAME, FAVORITE_ICON, PARENT_FOLDER_ID)
217 // Setup a matrix cursor for the `Home Folder`.
218 val homeFolderMatrixCursor = MatrixCursor(homeFolderMatrixCursorColumnNames)
220 // Add the home folder to the home folder matrix cursor.
221 homeFolderMatrixCursor.addRow(arrayOf<Any>(0, getString(R.string.home_folder), homeFolderIconByteArray, HOME_FOLDER_ID))
223 // Add the current folder to the list of folders not to display.
224 folderIdsNotToDisplay.add(currentFolderId)
226 // Get a cursor containing the folders to display.
227 val foldersCursor = bookmarksDatabaseHelper.getFoldersExcept(folderIdsNotToDisplay)
229 // Combine the home folder matrix cursor and the folders cursor.
230 val foldersMergeCursor = MergeCursor(arrayOf(homeFolderMatrixCursor, foldersCursor))
232 // Populate the folders cursor on the main thread.
233 withContext(Dispatchers.Main) {
234 // Populate the folders cursor adapter.
235 val foldersCursorAdapter = populateFoldersCursorAdapter(requireContext(), foldersMergeCursor)
237 // Get a handle for the folders list view.
238 val foldersListView = alertDialog.findViewById<ListView>(R.id.move_to_folder_listview)!!
240 // Set the folder list view adapter.
241 foldersListView.adapter = foldersCursorAdapter
243 // Enable the move button when a folder is selected.
244 foldersListView.onItemClickListener = OnItemClickListener { _: AdapterView<*>?, _: View?, _: Int, _: Long ->
245 // Enable the move button.
246 moveButton.isEnabled = true
253 // Return the alert dialog.
257 private fun populateFoldersCursorAdapter(context: Context, cursor: Cursor): CursorAdapter {
258 // Return the folders cursor adapter.
259 return object : CursorAdapter(context, cursor, false) {
260 override fun newView(context: Context, cursor: Cursor, parent: ViewGroup): View {
261 // Inflate the individual item layout.
262 return requireActivity().layoutInflater.inflate(R.layout.move_to_folder_item_linearlayout, parent, false)
265 override fun bindView(view: View, context: Context, cursor: Cursor) {
266 // Get the data from the cursor.
267 val folderIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(FAVORITE_ICON))
268 val folderName = cursor.getString(cursor.getColumnIndexOrThrow(BOOKMARK_NAME))
270 // Get handles for the views.
271 val subfolderSpacerTextView = view.findViewById<TextView>(R.id.subfolder_spacer_textview)
272 val folderIconImageView = view.findViewById<ImageView>(R.id.folder_icon_imageview)
273 val folderNameTextView = view.findViewById<TextView>(R.id.folder_name_textview)
275 // Populate the subfolder spacer.
276 if (cursor.getLong(cursor.getColumnIndexOrThrow(PARENT_FOLDER_ID)) != HOME_FOLDER_ID) { // The folder is not in the home folder.
277 // Get the subfolder spacer.
278 subfolderSpacerTextView.text = bookmarksDatabaseHelper.getSubfolderSpacer(cursor.getLong(cursor.getColumnIndexOrThrow(FOLDER_ID)))
279 } else { // The folder is in the home folder.
280 // Reset the subfolder spacer.
281 subfolderSpacerTextView.text = ""
284 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
285 val folderIconBitmap = BitmapFactory.decodeByteArray(folderIconByteArray, 0, folderIconByteArray.size)
287 // Display the folder icon bitmap.
288 folderIconImageView.setImageBitmap(folderIconBitmap)
290 // Display the folder name.
291 folderNameTextView.text = folderName