2 * Copyright © 2016-2020 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.content.SharedPreferences;
27 import android.content.res.Configuration;
28 import android.database.Cursor;
29 import android.database.DatabaseUtils;
30 import android.database.MatrixCursor;
31 import android.database.MergeCursor;
32 import android.graphics.Bitmap;
33 import android.graphics.BitmapFactory;
34 import android.graphics.drawable.BitmapDrawable;
35 import android.graphics.drawable.Drawable;
36 import android.os.Bundle;
37 import android.preference.PreferenceManager;
38 import android.view.View;
39 import android.view.ViewGroup;
40 import android.view.WindowManager;
41 import android.widget.AdapterView;
42 import android.widget.Button;
43 import android.widget.CursorAdapter;
44 import android.widget.ImageView;
45 import android.widget.ListView;
46 import android.widget.TextView;
48 import androidx.annotation.NonNull;
49 import androidx.appcompat.app.AlertDialog;
50 import androidx.core.content.ContextCompat;
51 import androidx.fragment.app.DialogFragment;
53 import com.stoutner.privacybrowser.R;
54 import com.stoutner.privacybrowser.activities.BookmarksActivity;
55 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
57 import java.io.ByteArrayOutputStream;
59 public class MoveToFolderDialog extends DialogFragment {
60 // Instantiate the class variables.
61 private MoveToFolderListener moveToFolderListener;
62 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
63 private StringBuilder exceptFolders;
65 // The public interface is used to send information back to the parent activity.
66 public interface MoveToFolderListener {
67 void onMoveToFolder(DialogFragment dialogFragment);
70 public void onAttach(@NonNull Context context) {
71 // Run the default commands.
72 super.onAttach(context);
74 // Get a handle for `MoveToFolderListener` from the launching context.
75 moveToFolderListener = (MoveToFolderListener) context;
78 // `@SuppressLint("InflateParams")` removes the warning about using `null` as the parent view group when inflating the alert dialog.
79 @SuppressLint("InflateParams")
82 public Dialog onCreateDialog(Bundle savedInstanceState) {
83 // Initialize the database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
84 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(getContext(), null, null, 0);
86 // Use an alert dialog builder to create the alert dialog.
87 AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(requireContext(), R.style.PrivacyBrowserAlertDialog);
89 // Get the current theme status.
90 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
92 // Set the icon according to the theme.
93 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
94 dialogBuilder.setIcon(R.drawable.move_to_folder_blue_day);
96 dialogBuilder.setIcon(R.drawable.move_to_folder_blue_night);
100 dialogBuilder.setTitle(R.string.move_to_folder);
102 // Remove the incorrect lint warning that `getActivity()` might be null.
103 assert getActivity() != null;
105 // Set the view. The parent view is `null` because it will be assigned by `AlertDialog`.
106 dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.move_to_folder_dialog, null));
108 // Set the listener for the negative button.
109 dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
110 // Do nothing. The `AlertDialog` will close automatically.
113 // Set the listener fo the positive button.
114 dialogBuilder.setPositiveButton(R.string.move, (DialogInterface dialog, int which) -> {
115 // Return the `DialogFragment` to the parent activity on save.
116 moveToFolderListener.onMoveToFolder(MoveToFolderDialog.this);
119 // Create an alert dialog from the alert dialog builder.
120 final AlertDialog alertDialog = dialogBuilder.create();
122 // Get a handle for the shared preferences.
123 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
125 // Get the screenshot preference.
126 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
128 // Disable screenshots if not allowed.
129 if (!allowScreenshots) {
130 // Remove the warning below that `getWindow()` might be null.
131 assert alertDialog.getWindow() != null;
133 // Disable screenshots.
134 alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
137 // Show the alert dialog so the items in the layout can be modified.
140 // Get a handle for the positive button.
141 final Button moveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
143 // Initially disable the positive button.
144 moveButton.setEnabled(false);
146 // Initialize the variables.
147 Cursor foldersCursor;
148 CursorAdapter foldersCursorAdapter;
149 exceptFolders = new StringBuilder();
151 // Check to see if we are in the `Home Folder`.
152 if (BookmarksActivity.currentFolder.isEmpty()) { // Don't display `Home Folder` at the top of the `ListView`.
153 // If a folder is selected, add it and all children to the list of folders not to display.
154 long[] selectedBookmarksLongArray = BookmarksActivity.checkedItemIds;
155 for (long databaseIdLong : selectedBookmarksLongArray) {
156 // Get `databaseIdInt` for each selected bookmark.
157 int databaseIdInt = (int) databaseIdLong;
159 // If `databaseIdInt` is a folder.
160 if (bookmarksDatabaseHelper.isFolder(databaseIdInt)) {
161 // Get the name of the selected folder.
162 String folderName = bookmarksDatabaseHelper.getFolderName(databaseIdInt);
164 // Populate the list of folders not to get.
165 if (exceptFolders.toString().isEmpty()){
166 // Add the selected folder to the list of folders not to display.
167 exceptFolders.append(DatabaseUtils.sqlEscapeString(folderName));
169 // Add the selected folder to the end of the list of folders not to display.
170 exceptFolders.append(",");
171 exceptFolders.append(DatabaseUtils.sqlEscapeString(folderName));
174 // Add the selected folder's subfolders to the list of folders not to display.
175 addSubfoldersToExceptFolders(folderName);
179 // Get a cursor containing the folders to display.
180 foldersCursor = bookmarksDatabaseHelper.getFoldersExcept(exceptFolders.toString());
182 // Setup `foldersCursorAdaptor` with `this` context. `false` disables autoRequery.
183 foldersCursorAdapter = new CursorAdapter(alertDialog.getContext(), foldersCursor, false) {
185 public View newView(Context context, Cursor cursor, ViewGroup parent) {
186 // Remove the incorrect lint warning that `.getLayoutInflater()` might be false.
187 assert getActivity() != null;
189 // Inflate the individual item layout. `false` does not attach it to the root.
190 return getActivity().getLayoutInflater().inflate(R.layout.move_to_folder_item_linearlayout, parent, false);
194 public void bindView(View view, Context context, Cursor cursor) {
195 // Get the folder icon from `cursor`.
196 byte[] folderIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
197 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
198 Bitmap folderIconBitmap = BitmapFactory.decodeByteArray(folderIconByteArray, 0, folderIconByteArray.length);
199 // Display `folderIconBitmap` in `move_to_folder_icon`.
200 ImageView folderIconImageView = view.findViewById(R.id.move_to_folder_icon);
201 folderIconImageView.setImageBitmap(folderIconBitmap);
203 // Get the folder name from `cursor` and display it in `move_to_folder_name_textview`.
204 String folderName = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
205 TextView folderNameTextView = view.findViewById(R.id.move_to_folder_name_textview);
206 folderNameTextView.setText(folderName);
209 } else { // Display `Home Folder` at the top of the `ListView`.
210 // Get the home folder icon drawable and convert it to a `Bitmap`.
211 Drawable homeFolderIconDrawable = ContextCompat.getDrawable(getActivity().getApplicationContext(), R.drawable.folder_gray_bitmap);
212 BitmapDrawable homeFolderIconBitmapDrawable = (BitmapDrawable) homeFolderIconDrawable;
213 assert homeFolderIconDrawable != null;
214 Bitmap homeFolderIconBitmap = homeFolderIconBitmapDrawable.getBitmap();
216 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
217 ByteArrayOutputStream homeFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
218 homeFolderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, homeFolderIconByteArrayOutputStream);
219 byte[] homeFolderIconByteArray = homeFolderIconByteArrayOutputStream.toByteArray();
221 // Setup a `MatrixCursor` for the `Home Folder`.
222 String[] homeFolderMatrixCursorColumnNames = {BookmarksDatabaseHelper._ID, BookmarksDatabaseHelper.BOOKMARK_NAME, BookmarksDatabaseHelper.FAVORITE_ICON};
223 MatrixCursor homeFolderMatrixCursor = new MatrixCursor(homeFolderMatrixCursorColumnNames);
224 homeFolderMatrixCursor.addRow(new Object[]{0, getString(R.string.home_folder), homeFolderIconByteArray});
226 // Add the parent folder to the list of folders not to display.
227 exceptFolders.append(DatabaseUtils.sqlEscapeString(BookmarksActivity.currentFolder));
229 // If a folder is selected, add it and all children to the list of folders not to display.
230 long[] selectedBookmarksLongArray = BookmarksActivity.checkedItemIds;
231 for (long databaseIdLong : selectedBookmarksLongArray) {
232 // Get `databaseIdInt` for each selected bookmark.
233 int databaseIdInt = (int) databaseIdLong;
235 // If `databaseIdInt` is a folder.
236 if (bookmarksDatabaseHelper.isFolder(databaseIdInt)) {
237 // Get the name of the selected folder.
238 String folderName = bookmarksDatabaseHelper.getFolderName(databaseIdInt);
240 // Add the selected folder to the end of the list of folders not to display.
241 exceptFolders.append(",");
242 exceptFolders.append(DatabaseUtils.sqlEscapeString(folderName));
244 // Add the selected folder's subfolders to the list of folders not to display.
245 addSubfoldersToExceptFolders(folderName);
249 // Get a `Cursor` containing the folders to display.
250 foldersCursor = bookmarksDatabaseHelper.getFoldersExcept(exceptFolders.toString());
252 // Combine `homeFolderMatrixCursor` and `foldersCursor`.
253 MergeCursor foldersMergeCursor = new MergeCursor(new Cursor[]{homeFolderMatrixCursor, foldersCursor});
255 // Setup `foldersCursorAdaptor`. `false` disables autoRequery.
256 foldersCursorAdapter = new CursorAdapter(alertDialog.getContext(), foldersMergeCursor, false) {
258 public View newView(Context context, Cursor cursor, ViewGroup parent) {
259 // Remove the incorrect lint warning that `.getLayoutInflater()` might be false.
260 assert getActivity() != null;
262 // Inflate the individual item layout. `false` does not attach it to the root.
263 return getActivity().getLayoutInflater().inflate(R.layout.move_to_folder_item_linearlayout, parent, false);
267 public void bindView(View view, Context context, Cursor cursor) {
268 // Get the folder icon from `cursor`.
269 byte[] folderIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
270 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
271 Bitmap folderIconBitmap = BitmapFactory.decodeByteArray(folderIconByteArray, 0, folderIconByteArray.length);
272 // Display `folderIconBitmap` in `move_to_folder_icon`.
273 ImageView folderIconImageView = view.findViewById(R.id.move_to_folder_icon);
274 folderIconImageView.setImageBitmap(folderIconBitmap);
276 // Get the folder name from `cursor` and display it in `move_to_folder_name_textview`.
277 String folderName = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
278 TextView folderNameTextView = view.findViewById(R.id.move_to_folder_name_textview);
279 folderNameTextView.setText(folderName);
284 // Get a handle for the folders list view.
285 ListView foldersListView = alertDialog.findViewById(R.id.move_to_folder_listview);
287 // Remove the incorrect lint warning below that the view might be null.
288 assert foldersListView != null;
290 // Set the folder list view adapter.
291 foldersListView.setAdapter(foldersCursorAdapter);
293 // Enable the move button when a folder is selected.
294 foldersListView.setOnItemClickListener((AdapterView<?> parent, View view, int position, long id) -> {
295 // Enable the move button.
296 moveButton.setEnabled(true);
299 // `onCreateDialog` requires the return of an `AlertDialog`.
303 private void addSubfoldersToExceptFolders(String folderName) {
304 // Get a `Cursor` will all the immediate subfolders.
305 Cursor subfoldersCursor = bookmarksDatabaseHelper.getSubfolders(folderName);
307 for (int i = 0; i < subfoldersCursor.getCount(); i++) {
308 // Move `subfolderCursor` to the current item.
309 subfoldersCursor.moveToPosition(i);
311 // Get the name of the subfolder.
312 String subfolderName = subfoldersCursor.getString(subfoldersCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
314 // Add the subfolder to `exceptFolders`.
315 exceptFolders.append(",");
316 exceptFolders.append(DatabaseUtils.sqlEscapeString(subfolderName));
318 // Run the same tasks for any subfolders of the subfolder.
319 addSubfoldersToExceptFolders(subfolderName);