]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/MoveToFolderDialog.java
2bbd4e6674cbe2f9397aa8e70fe0c2b5d9a8d52f
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / MoveToFolderDialog.java
1 /*
2  * Copyright © 2016-2018 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.AlertDialog;
24 import android.app.Dialog;
25 import android.content.Context;
26 import android.content.DialogInterface;
27 import android.database.Cursor;
28 import android.database.DatabaseUtils;
29 import android.database.MatrixCursor;
30 import android.database.MergeCursor;
31 import android.graphics.Bitmap;
32 import android.graphics.BitmapFactory;
33 import android.graphics.drawable.BitmapDrawable;
34 import android.graphics.drawable.Drawable;
35 import android.os.Bundle;
36 import android.support.annotation.NonNull;
37 import android.support.v4.content.ContextCompat;
38 // `AppCompatDialogFragment` must be used instead of `DialogFragment` or an error is produced on API <=22.
39 import android.support.v7.app.AppCompatDialogFragment;
40 import android.view.View;
41 import android.view.ViewGroup;
42 import android.view.WindowManager;
43 import android.widget.AdapterView;
44 import android.widget.Button;
45 import android.widget.CursorAdapter;
46 import android.widget.ImageView;
47 import android.widget.ListView;
48 import android.widget.TextView;
49
50 import com.stoutner.privacybrowser.R;
51 import com.stoutner.privacybrowser.activities.BookmarksActivity;
52 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
53 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
54
55 import java.io.ByteArrayOutputStream;
56
57 public class MoveToFolderDialog extends AppCompatDialogFragment {
58     // Instantiate the class variables.
59     private MoveToFolderListener moveToFolderListener;
60     private BookmarksDatabaseHelper bookmarksDatabaseHelper;
61     private StringBuilder exceptFolders;
62
63     // The public interface is used to send information back to the parent activity.
64     public interface MoveToFolderListener {
65         void onMoveToFolder(AppCompatDialogFragment dialogFragment);
66     }
67
68     public void onAttach(Context context) {
69         // Run the default commands.
70         super.onAttach(context);
71
72         // Get a handle for `MoveToFolderListener` from the launching context.
73         moveToFolderListener = (MoveToFolderListener) context;
74     }
75
76     // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
77     @SuppressLint("InflateParams")
78     @Override
79     @NonNull
80     public Dialog onCreateDialog(Bundle savedInstanceState) {
81         // Initialize the database helper.  The two `nulls` do not specify the database name or a `CursorFactory`.  The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
82         bookmarksDatabaseHelper = new BookmarksDatabaseHelper(getContext(), null, null, 0);
83
84         // Use an alert dialog builder to create the alert dialog.
85         AlertDialog.Builder dialogBuilder;
86
87         // Set the style according to the theme.
88         if (MainWebViewActivity.darkTheme) {
89             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
90         } else {
91             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
92         }
93
94         // Set the title.
95         dialogBuilder.setTitle(R.string.move_to_folder);
96
97         // Remove the incorrect lint warning that `getActivity()` might be null.
98         assert getActivity() != null;
99
100         // Set the view.  The parent view is `null` because it will be assigned by `AlertDialog`.
101         dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.move_to_folder_dialog, null));
102
103         // Set the listener for the negative button.
104         dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
105             // Do nothing.  The `AlertDialog` will close automatically.
106         });
107
108         // Set the listener fo the positive button.
109         dialogBuilder.setPositiveButton(R.string.move, (DialogInterface dialog, int which) -> {
110             // Return the `DialogFragment` to the parent activity on save.
111             moveToFolderListener.onMoveToFolder(MoveToFolderDialog.this);
112         });
113
114         // Create an alert dialog from the alert dialog builder.
115         final AlertDialog alertDialog = dialogBuilder.create();
116
117         // Disable screenshots if not allowed.
118         if (!MainWebViewActivity.allowScreenshots) {
119             // Remove the warning below that `getWindow()` might be null.
120             assert alertDialog.getWindow() != null;
121
122             // Disable screenshots.
123             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
124         }
125
126         // Show the alert dialog so the items in the layout can be modified.
127         alertDialog.show();
128
129         // Get a handle for the positive button.
130         final Button moveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
131
132         // Initially disable the positive button.
133         moveButton.setEnabled(false);
134
135         // Initialize the variables.
136         Cursor foldersCursor;
137         CursorAdapter foldersCursorAdapter;
138         exceptFolders = new StringBuilder();
139
140         // Check to see if we are in the `Home Folder`.
141         if (BookmarksActivity.currentFolder.isEmpty()) {  // Don't display `Home Folder` at the top of the `ListView`.
142             // If a folder is selected, add it and all children to the list of folders not to display.
143             long[] selectedBookmarksLongArray = BookmarksActivity.checkedItemIds;
144             for (long databaseIdLong : selectedBookmarksLongArray) {
145                 // Get `databaseIdInt` for each selected bookmark.
146                 int databaseIdInt = (int) databaseIdLong;
147
148                 // If `databaseIdInt` is a folder.
149                 if (bookmarksDatabaseHelper.isFolder(databaseIdInt)) {
150                     // Get the name of the selected folder.
151                     String folderName = bookmarksDatabaseHelper.getFolderName(databaseIdInt);
152
153                     // Populate the list of folders not to get.
154                     if (exceptFolders.toString().isEmpty()){
155                         // Add the selected folder to the list of folders not to display.
156                         exceptFolders.append(DatabaseUtils.sqlEscapeString(folderName));
157                     } else {
158                         // Add the selected folder to the end of the list of folders not to display.
159                         exceptFolders.append(",");
160                         exceptFolders.append(DatabaseUtils.sqlEscapeString(folderName));
161                     }
162
163                     // Add the selected folder's subfolders to the list of folders not to display.
164                     addSubfoldersToExceptFolders(folderName);
165                 }
166             }
167
168             // Get a `Cursor` containing the folders to display.
169             foldersCursor = bookmarksDatabaseHelper.getFoldersCursorExcept(exceptFolders.toString());
170
171             // Setup `foldersCursorAdaptor` with `this` context.  `false` disables autoRequery.
172             foldersCursorAdapter = new CursorAdapter(alertDialog.getContext(), foldersCursor, false) {
173                 @Override
174                 public View newView(Context context, Cursor cursor, ViewGroup parent) {
175                     // Inflate the individual item layout.  `false` does not attach it to the root.
176                     return getActivity().getLayoutInflater().inflate(R.layout.move_to_folder_item_linearlayout, parent, false);
177                 }
178
179                 @Override
180                 public void bindView(View view, Context context, Cursor cursor) {
181                     // Get the folder icon from `cursor`.
182                     byte[] folderIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
183                     // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
184                     Bitmap folderIconBitmap = BitmapFactory.decodeByteArray(folderIconByteArray, 0, folderIconByteArray.length);
185                     // Display `folderIconBitmap` in `move_to_folder_icon`.
186                     ImageView folderIconImageView = view.findViewById(R.id.move_to_folder_icon);
187                     folderIconImageView.setImageBitmap(folderIconBitmap);
188
189                     // Get the folder name from `cursor` and display it in `move_to_folder_name_textview`.
190                     String folderName = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
191                     TextView folderNameTextView = view.findViewById(R.id.move_to_folder_name_textview);
192                     folderNameTextView.setText(folderName);
193                 }
194             };
195         } else {  // Display `Home Folder` at the top of the `ListView`.
196             // Get the home folder icon drawable and convert it to a `Bitmap`.
197             Drawable homeFolderIconDrawable = ContextCompat.getDrawable(getActivity().getApplicationContext(), R.drawable.folder_gray_bitmap);
198             BitmapDrawable homeFolderIconBitmapDrawable = (BitmapDrawable) homeFolderIconDrawable;
199             assert homeFolderIconDrawable != null;
200             Bitmap homeFolderIconBitmap = homeFolderIconBitmapDrawable.getBitmap();
201
202             // Convert the folder `Bitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
203             ByteArrayOutputStream homeFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
204             homeFolderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, homeFolderIconByteArrayOutputStream);
205             byte[] homeFolderIconByteArray = homeFolderIconByteArrayOutputStream.toByteArray();
206
207             // Setup a `MatrixCursor` for the `Home Folder`.
208             String[] homeFolderMatrixCursorColumnNames = {BookmarksDatabaseHelper._ID, BookmarksDatabaseHelper.BOOKMARK_NAME, BookmarksDatabaseHelper.FAVORITE_ICON};
209             MatrixCursor homeFolderMatrixCursor = new MatrixCursor(homeFolderMatrixCursorColumnNames);
210             homeFolderMatrixCursor.addRow(new Object[]{0, getString(R.string.home_folder), homeFolderIconByteArray});
211
212             // Add the parent folder to the list of folders not to display.
213             exceptFolders.append(DatabaseUtils.sqlEscapeString(BookmarksActivity.currentFolder));
214
215             // If a folder is selected, add it and all children to the list of folders not to display.
216             long[] selectedBookmarksLongArray = BookmarksActivity.checkedItemIds;
217             for (long databaseIdLong : selectedBookmarksLongArray) {
218                 // Get `databaseIdInt` for each selected bookmark.
219                 int databaseIdInt = (int) databaseIdLong;
220
221                 // If `databaseIdInt` is a folder.
222                 if (bookmarksDatabaseHelper.isFolder(databaseIdInt)) {
223                     // Get the name of the selected folder.
224                     String folderName = bookmarksDatabaseHelper.getFolderName(databaseIdInt);
225
226                     // Add the selected folder to the end of the list of folders not to display.
227                     exceptFolders.append(",");
228                     exceptFolders.append(DatabaseUtils.sqlEscapeString(folderName));
229
230                     // Add the selected folder's subfolders to the list of folders not to display.
231                     addSubfoldersToExceptFolders(folderName);
232                 }
233             }
234
235             // Get a `Cursor` containing the folders to display.
236             foldersCursor = bookmarksDatabaseHelper.getFoldersCursorExcept(exceptFolders.toString());
237
238             // Combine `homeFolderMatrixCursor` and `foldersCursor`.
239             MergeCursor foldersMergeCursor = new MergeCursor(new Cursor[]{homeFolderMatrixCursor, foldersCursor});
240
241             // Setup `foldersCursorAdaptor`.  `false` disables autoRequery.
242             foldersCursorAdapter = new CursorAdapter(alertDialog.getContext(), foldersMergeCursor, false) {
243                 @Override
244                 public View newView(Context context, Cursor cursor, ViewGroup parent) {
245                     // Inflate the individual item layout.  `false` does not attach it to the root.
246                     return getActivity().getLayoutInflater().inflate(R.layout.move_to_folder_item_linearlayout, parent, false);
247                 }
248
249                 @Override
250                 public void bindView(View view, Context context, Cursor cursor) {
251                     // Get the folder icon from `cursor`.
252                     byte[] folderIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
253                     // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
254                     Bitmap folderIconBitmap = BitmapFactory.decodeByteArray(folderIconByteArray, 0, folderIconByteArray.length);
255                     // Display `folderIconBitmap` in `move_to_folder_icon`.
256                     ImageView folderIconImageView = view.findViewById(R.id.move_to_folder_icon);
257                     folderIconImageView.setImageBitmap(folderIconBitmap);
258
259                     // Get the folder name from `cursor` and display it in `move_to_folder_name_textview`.
260                     String folderName = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
261                     TextView folderNameTextView = view.findViewById(R.id.move_to_folder_name_textview);
262                     folderNameTextView.setText(folderName);
263                 }
264             };
265         }
266
267         // Display the ListView
268         ListView foldersListView = alertDialog.findViewById(R.id.move_to_folder_listview);
269         foldersListView.setAdapter(foldersCursorAdapter);
270
271         // Enable the move button when a folder is selected.
272         foldersListView.setOnItemClickListener((AdapterView<?> parent, View view, int position, long id) -> {
273             // Enable the move button.
274             moveButton.setEnabled(true);
275         });
276
277         // `onCreateDialog` requires the return of an `AlertDialog`.
278         return alertDialog;
279     }
280
281     private void addSubfoldersToExceptFolders(String folderName) {
282         // Get a `Cursor` will all the immediate subfolders.
283         Cursor subfoldersCursor = bookmarksDatabaseHelper.getSubfoldersCursor(folderName);
284
285         for (int i = 0; i < subfoldersCursor.getCount(); i++) {
286             // Move `subfolderCursor` to the current item.
287             subfoldersCursor.moveToPosition(i);
288
289             // Get the name of the subfolder.
290             String subfolderName = subfoldersCursor.getString(subfoldersCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
291
292             // Add the subfolder to `exceptFolders`.
293             exceptFolders.append(",");
294             exceptFolders.append(DatabaseUtils.sqlEscapeString(subfolderName));
295
296             // Run the same tasks for any subfolders of the subfolder.
297             addSubfoldersToExceptFolders(subfolderName);
298         }
299     }
300 }