]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/MoveToFolder.java
Partial Domain implementation.
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / MoveToFolder.java
1 /*
2  * Copyright 2016-2017 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 // We have to use `AppCompatDialogFragment` 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.widget.CursorAdapter;
43 import android.widget.ImageView;
44 import android.widget.ListView;
45 import android.widget.TextView;
46
47 import com.stoutner.privacybrowser.R;
48 import com.stoutner.privacybrowser.activities.Bookmarks;
49 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
50
51 import java.io.ByteArrayOutputStream;
52
53 public class MoveToFolder extends AppCompatDialogFragment {
54     // The public interface is used to send information back to the parent activity.
55     public interface MoveToFolderListener {
56         void onMoveToFolder(AppCompatDialogFragment dialogFragment);
57     }
58
59     // `moveToFolderListener` is used in `onAttach()` and `onCreateDialog`.
60     private MoveToFolderListener moveToFolderListener;
61
62     public void onAttach(Context context) {
63         super.onAttach(context);
64
65         // Get a handle for `MoveToFolderListener` from `parentActivity`.
66         try {
67             moveToFolderListener = (MoveToFolderListener) context;
68         } catch(ClassCastException exception) {
69             throw new ClassCastException(context.toString() + " must implement EditBookmarkFolderListener.");
70         }
71     }
72
73     // `exceptFolders` is used in `onCreateDialog()` and `addSubfoldersToExceptFolders()`.
74     private String exceptFolders;
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         // Use `AlertDialog.Builder` to create the `AlertDialog`.  The style formats the color of the button text.
82         AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.LightAlertDialog);
83         dialogBuilder.setTitle(R.string.move_to_folder);
84         // The parent view is `null` because it will be assigned by `AlertDialog`.
85         dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.move_to_folder_dialog, null));
86
87         // Set an `onClick()` listener for the negative button.
88         dialogBuilder.setNegativeButton(R.string.cancel, new Dialog.OnClickListener() {
89             @Override
90             public void onClick(DialogInterface dialog, int which) {
91                 // Do nothing.  The `AlertDialog` will close automatically.
92             }
93         });
94
95         // Set the `onClick()` listener fo the positive button.
96         dialogBuilder.setPositiveButton(R.string.move, new Dialog.OnClickListener() {
97             @Override
98             public void onClick(DialogInterface dialog, int which) {
99                 // Return the `DialogFragment` to the parent activity on save.
100                 moveToFolderListener.onMoveToFolder(MoveToFolder.this);
101             }
102         });
103
104         // Create an `AlertDialog` from the `AlertDialog.Builder`.
105         final AlertDialog alertDialog = dialogBuilder.create();
106
107         // We need to show the `AlertDialog` before we can modify items in the layout.
108         alertDialog.show();
109
110         // Initialize the `Cursor` and `CursorAdapter` variables.
111         Cursor foldersCursor;
112         CursorAdapter foldersCursorAdapter;
113
114         // Check to see if we are in the `Home Folder`.
115         if (Bookmarks.currentFolder.isEmpty()) {  // Don't display `Home Folder` at the top of the `ListView`.
116             // Initialize `exceptFolders`.
117             exceptFolders = "";
118
119             // If a folder is selected, add it and all children to the list of folders not to display.
120             long[] selectedBookmarksLongArray = Bookmarks.checkedItemIds;
121             for (long databaseIdLong : selectedBookmarksLongArray) {
122                 // Get `databaseIdInt` for each selected bookmark.
123                 int databaseIdInt = (int) databaseIdLong;
124
125                 // If `databaseIdInt` is a folder.
126                 if (Bookmarks.bookmarksDatabaseHelper.isFolder(databaseIdInt)) {
127                     // Get the name of the selected folder.
128                     String folderName = Bookmarks.bookmarksDatabaseHelper.getFolderName(databaseIdInt);
129
130                     if (exceptFolders.isEmpty()){
131                         // Add the selected folder to the list of folders not to display.
132                         exceptFolders = DatabaseUtils.sqlEscapeString(folderName);
133                     } else {
134                         // Add the selected folder to the end of the list of folders not to display.
135                         exceptFolders = exceptFolders + "," + DatabaseUtils.sqlEscapeString(folderName);
136                     }
137
138                     // Add the selected folder's subfolders to the list of folders not to display.
139                     addSubfoldersToExceptFolders(folderName);
140                 }
141             }
142
143             // Get a `Cursor` containing the folders to display.
144             foldersCursor = Bookmarks.bookmarksDatabaseHelper.getFoldersCursorExcept(exceptFolders);
145
146             // Setup `foldersCursorAdaptor` with `this` context.  `false` disables autoRequery.
147             foldersCursorAdapter = new CursorAdapter(alertDialog.getContext(), foldersCursor, false) {
148                 @Override
149                 public View newView(Context context, Cursor cursor, ViewGroup parent) {
150                     // Inflate the individual item layout.  `false` does not attach it to the root.
151                     return getActivity().getLayoutInflater().inflate(R.layout.move_to_folder_item_linearlayout, parent, false);
152                 }
153
154                 @Override
155                 public void bindView(View view, Context context, Cursor cursor) {
156                     // Get the folder icon from `cursor`.
157                     byte[] folderIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
158                     // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
159                     Bitmap folderIconBitmap = BitmapFactory.decodeByteArray(folderIconByteArray, 0, folderIconByteArray.length);
160                     // Display `folderIconBitmap` in `move_to_folder_icon`.
161                     ImageView folderIconImageView = (ImageView) view.findViewById(R.id.move_to_folder_icon);
162                     assert folderIconImageView != null;  // Remove the warning below that `currentIconImageView` might be null;
163                     folderIconImageView.setImageBitmap(folderIconBitmap);
164
165                     // Get the folder name from `cursor` and display it in `move_to_folder_name_textview`.
166                     String folderName = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
167                     TextView folderNameTextView = (TextView) view.findViewById(R.id.move_to_folder_name_textview);
168                     folderNameTextView.setText(folderName);
169                 }
170             };
171         } else {  // Display `Home Folder` at the top of the `ListView`.
172             // Get the home folder icon drawable and convert it to a `Bitmap`.  `this` specifies the current context.
173             Drawable homeFolderIconDrawable = ContextCompat.getDrawable(getActivity().getApplicationContext(), R.drawable.folder_gray_bitmap);
174             BitmapDrawable homeFolderIconBitmapDrawable = (BitmapDrawable) homeFolderIconDrawable;
175             Bitmap homeFolderIconBitmap = homeFolderIconBitmapDrawable.getBitmap();
176             // Convert the folder `Bitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
177             ByteArrayOutputStream homeFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
178             homeFolderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, homeFolderIconByteArrayOutputStream);
179             byte[] homeFolderIconByteArray = homeFolderIconByteArrayOutputStream.toByteArray();
180
181             // Setup a `MatrixCursor` for the `Home Folder`.
182             String[] homeFolderMatrixCursorColumnNames = {BookmarksDatabaseHelper._ID, BookmarksDatabaseHelper.BOOKMARK_NAME, BookmarksDatabaseHelper.FAVORITE_ICON};
183             MatrixCursor homeFolderMatrixCursor = new MatrixCursor(homeFolderMatrixCursorColumnNames);
184             homeFolderMatrixCursor.addRow(new Object[]{0, getString(R.string.home_folder), homeFolderIconByteArray});
185
186             // Add the parent folder to the list of folders not to display.
187             exceptFolders = DatabaseUtils.sqlEscapeString(Bookmarks.currentFolder);
188
189             // If a folder is selected, add it and all children to the list of folders not to display.
190             long[] selectedBookmarksLongArray = Bookmarks.checkedItemIds;
191             for (long databaseIdLong : selectedBookmarksLongArray) {
192                 // Get `databaseIdInt` for each selected bookmark.
193                 int databaseIdInt = (int) databaseIdLong;
194
195                 // If `databaseIdInt` is a folder.
196                 if (Bookmarks.bookmarksDatabaseHelper.isFolder(databaseIdInt)) {
197                     // Get the name of the selected folder.
198                     String folderName = Bookmarks.bookmarksDatabaseHelper.getFolderName(databaseIdInt);
199
200                     // Add the selected folder to the end of the list of folders not to display.
201                     exceptFolders = exceptFolders + "," + DatabaseUtils.sqlEscapeString(folderName);
202
203                     // Add the selected folder's subfolders to the list of folders not to display.
204                     addSubfoldersToExceptFolders(folderName);
205                 }
206             }
207
208             // Get a `foldersCursor`.
209             foldersCursor = Bookmarks.bookmarksDatabaseHelper.getFoldersCursorExcept(exceptFolders);
210
211             // Combine `homeFolderMatrixCursor` and `foldersCursor`.
212             MergeCursor foldersMergeCursor = new MergeCursor(new Cursor[]{homeFolderMatrixCursor, foldersCursor});
213
214             // Setup `foldersCursorAdaptor` with `this` context.  `false` disables autoRequery.
215             foldersCursorAdapter = new CursorAdapter(alertDialog.getContext(), foldersMergeCursor, false) {
216                 @Override
217                 public View newView(Context context, Cursor cursor, ViewGroup parent) {
218                     // Inflate the individual item layout.  `false` does not attach it to the root.
219                     return getActivity().getLayoutInflater().inflate(R.layout.move_to_folder_item_linearlayout, parent, false);
220                 }
221
222                 @Override
223                 public void bindView(View view, Context context, Cursor cursor) {
224                     // Get the folder icon from `cursor`.
225                     byte[] folderIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
226                     // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
227                     Bitmap folderIconBitmap = BitmapFactory.decodeByteArray(folderIconByteArray, 0, folderIconByteArray.length);
228                     // Display `folderIconBitmap` in `move_to_folder_icon`.
229                     ImageView folderIconImageView = (ImageView) view.findViewById(R.id.move_to_folder_icon);
230                     assert folderIconImageView != null;  // Remove the warning below that `currentIconImageView` might be null;
231                     folderIconImageView.setImageBitmap(folderIconBitmap);
232
233                     // Get the folder name from `cursor` and display it in `move_to_folder_name_textview`.
234                     String folderName = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
235                     TextView folderNameTextView = (TextView) view.findViewById(R.id.move_to_folder_name_textview);
236                     folderNameTextView.setText(folderName);
237                 }
238             };
239         }
240
241         // Display the ListView
242         ListView foldersListView = (ListView) alertDialog.findViewById(R.id.move_to_folder_listview);
243         assert foldersListView != null;  // Remove the warning below that `foldersListView` might be null.
244         foldersListView.setAdapter(foldersCursorAdapter);
245
246         // `onCreateDialog` requires the return of an `AlertDialog`.
247         return alertDialog;
248     }
249
250     private void addSubfoldersToExceptFolders(String folderName) {
251         // Get a `Cursor` will all the immediate subfolders.
252         Cursor subfoldersCursor = Bookmarks.bookmarksDatabaseHelper.getSubfoldersCursor(folderName);
253
254         for (int i = 0; i < subfoldersCursor.getCount(); i++) {
255             // Move `subfolderCursor` to the current item.
256             subfoldersCursor.moveToPosition(i);
257
258             // Get the name of the subfolder.
259             String subfolderName = subfoldersCursor.getString(subfoldersCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
260
261             // Run the same tasks for any subfolders of the subfolder.
262             addSubfoldersToExceptFolders(subfolderName);
263
264             // Add the subfolder to `exceptFolders`.
265             subfolderName = DatabaseUtils.sqlEscapeString(subfolderName);
266             exceptFolders = exceptFolders + "," + subfolderName;
267         }
268
269     }
270 }