]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/MoveToFolderDialog.java
a421177cabcf509250f6a3e4e440447a38654eb2
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / MoveToFolderDialog.java
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
20 package com.stoutner.privacybrowser.dialogs;
21
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;
47
48 import androidx.annotation.NonNull;
49 import androidx.appcompat.app.AlertDialog;
50 import androidx.core.content.ContextCompat;
51 import androidx.fragment.app.DialogFragment;
52
53 import com.stoutner.privacybrowser.R;
54 import com.stoutner.privacybrowser.activities.BookmarksActivity;
55 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
56
57 import java.io.ByteArrayOutputStream;
58
59 public class MoveToFolderDialog extends DialogFragment {
60     // Instantiate the class variables.
61     private MoveToFolderListener moveToFolderListener;
62     private BookmarksDatabaseHelper bookmarksDatabaseHelper;
63     private StringBuilder exceptFolders;
64
65     // The public interface is used to send information back to the parent activity.
66     public interface MoveToFolderListener {
67         void onMoveToFolder(DialogFragment dialogFragment);
68     }
69
70     public void onAttach(@NonNull Context context) {
71         // Run the default commands.
72         super.onAttach(context);
73
74         // Get a handle for `MoveToFolderListener` from the launching context.
75         moveToFolderListener = (MoveToFolderListener) context;
76     }
77
78     // `@SuppressLint("InflateParams")` removes the warning about using `null` as the parent view group when inflating the alert dialog.
79     @SuppressLint("InflateParams")
80     @Override
81     @NonNull
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);
85
86         // Use an alert dialog builder to create the alert dialog.
87         AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(requireContext(), R.style.PrivacyBrowserAlertDialog);
88
89         // Get the current theme status.
90         int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
91
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);
95         } else {
96             dialogBuilder.setIcon(R.drawable.move_to_folder_blue_night);
97         }
98
99         // Set the title.
100         dialogBuilder.setTitle(R.string.move_to_folder);
101
102         // Remove the incorrect lint warning that `getActivity()` might be null.
103         assert getActivity() != null;
104
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));
107
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.
111         });
112
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);
117         });
118
119         // Create an alert dialog from the alert dialog builder.
120         final AlertDialog alertDialog = dialogBuilder.create();
121
122         // Get a handle for the shared preferences.
123         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
124
125         // Get the screenshot preference.
126         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
127
128         // Disable screenshots if not allowed.
129         if (!allowScreenshots) {
130             // Remove the warning below that `getWindow()` might be null.
131             assert alertDialog.getWindow() != null;
132
133             // Disable screenshots.
134             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
135         }
136
137         // Show the alert dialog so the items in the layout can be modified.
138         alertDialog.show();
139
140         // Get a handle for the positive button.
141         final Button moveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
142
143         // Initially disable the positive button.
144         moveButton.setEnabled(false);
145
146         // Initialize the variables.
147         Cursor foldersCursor;
148         CursorAdapter foldersCursorAdapter;
149         exceptFolders = new StringBuilder();
150
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;
158
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);
163
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));
168                     } else {
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));
172                     }
173
174                     // Add the selected folder's subfolders to the list of folders not to display.
175                     addSubfoldersToExceptFolders(folderName);
176                 }
177             }
178
179             // Get a cursor containing the folders to display.
180             foldersCursor = bookmarksDatabaseHelper.getFoldersExcept(exceptFolders.toString());
181
182             // Setup `foldersCursorAdaptor` with `this` context.  `false` disables autoRequery.
183             foldersCursorAdapter = new CursorAdapter(alertDialog.getContext(), foldersCursor, false) {
184                 @Override
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;
188
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);
191                 }
192
193                 @Override
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);
202
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);
207                 }
208             };
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();
215
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();
220
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});
225
226             // Add the parent folder to the list of folders not to display.
227             exceptFolders.append(DatabaseUtils.sqlEscapeString(BookmarksActivity.currentFolder));
228
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;
234
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);
239
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));
243
244                     // Add the selected folder's subfolders to the list of folders not to display.
245                     addSubfoldersToExceptFolders(folderName);
246                 }
247             }
248
249             // Get a `Cursor` containing the folders to display.
250             foldersCursor = bookmarksDatabaseHelper.getFoldersExcept(exceptFolders.toString());
251
252             // Combine `homeFolderMatrixCursor` and `foldersCursor`.
253             MergeCursor foldersMergeCursor = new MergeCursor(new Cursor[]{homeFolderMatrixCursor, foldersCursor});
254
255             // Setup `foldersCursorAdaptor`.  `false` disables autoRequery.
256             foldersCursorAdapter = new CursorAdapter(alertDialog.getContext(), foldersMergeCursor, false) {
257                 @Override
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;
261
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);
264                 }
265
266                 @Override
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);
275
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);
280                 }
281             };
282         }
283
284         // Get a handle for the folders list view.
285         ListView foldersListView = alertDialog.findViewById(R.id.move_to_folder_listview);
286
287         // Remove the incorrect lint warning below that the view might be null.
288         assert foldersListView != null;
289
290         // Set the folder list view adapter.
291         foldersListView.setAdapter(foldersCursorAdapter);
292
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);
297         });
298
299         // `onCreateDialog` requires the return of an `AlertDialog`.
300         return alertDialog;
301     }
302
303     private void addSubfoldersToExceptFolders(String folderName) {
304         // Get a `Cursor` will all the immediate subfolders.
305         Cursor subfoldersCursor = bookmarksDatabaseHelper.getSubfolders(folderName);
306
307         for (int i = 0; i < subfoldersCursor.getCount(); i++) {
308             // Move `subfolderCursor` to the current item.
309             subfoldersCursor.moveToPosition(i);
310
311             // Get the name of the subfolder.
312             String subfolderName = subfoldersCursor.getString(subfoldersCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
313
314             // Add the subfolder to `exceptFolders`.
315             exceptFolders.append(",");
316             exceptFolders.append(DatabaseUtils.sqlEscapeString(subfolderName));
317
318             // Run the same tasks for any subfolders of the subfolder.
319             addSubfoldersToExceptFolders(subfolderName);
320         }
321     }
322 }