]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/EditBookmarkFolderDatabaseViewDialog.java
Scale bookmark favorite icons larger than 256 x 256 to fix a crash. https://redmine...
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / EditBookmarkFolderDatabaseViewDialog.java
1 /*
2  * Copyright © 2016-2019 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.os.Bundle;
34 import android.text.Editable;
35 import android.text.TextWatcher;
36 import android.view.KeyEvent;
37 import android.view.View;
38 import android.view.WindowManager;
39 import android.widget.AdapterView;
40 import android.widget.Button;
41 import android.widget.EditText;
42 import android.widget.ImageView;
43 import android.widget.RadioButton;
44 import android.widget.RadioGroup;
45 import android.widget.ResourceCursorAdapter;
46 import android.widget.Spinner;
47 import android.widget.TextView;
48
49 import androidx.annotation.NonNull;
50 import androidx.core.content.ContextCompat;
51 import androidx.fragment.app.DialogFragment;  // The AndroidX dialog fragment must be used or an error is produced on API <=22.
52
53 import com.stoutner.privacybrowser.R;
54 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
55 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
56
57 public class EditBookmarkFolderDatabaseViewDialog extends DialogFragment {
58     // Instantiate the constants.
59     public static final int HOME_FOLDER_DATABASE_ID = -1;
60
61     // Instantiate the class variables.
62     private EditBookmarkFolderDatabaseViewListener editBookmarkFolderDatabaseViewListener;
63     private BookmarksDatabaseHelper bookmarksDatabaseHelper;
64     private StringBuilder exceptFolders;
65     private String currentFolderName;
66     private int currentParentFolderDatabaseId;
67     private String currentDisplayOrder;
68     private RadioButton currentIconRadioButton;
69     private EditText nameEditText;
70     private Spinner folderSpinner;
71     private EditText displayOrderEditText;
72     private Button editButton;
73
74     // The public interface is used to send information back to the parent activity.
75     public interface EditBookmarkFolderDatabaseViewListener {
76         void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId);
77     }
78
79     public void onAttach(Context context) {
80         // Run the default commands.
81         super.onAttach(context);
82
83         // Get a handle for `EditBookmarkDatabaseViewListener` from the launching context.
84         editBookmarkFolderDatabaseViewListener = (EditBookmarkFolderDatabaseViewListener) context;
85     }
86
87     // Store the database ID in the arguments bundle.
88     public static EditBookmarkFolderDatabaseViewDialog folderDatabaseId(int databaseId) {
89         // Create a bundle.
90         Bundle bundle = new Bundle();
91
92         // Store the bookmark database ID in the bundle.
93         bundle.putInt("Database ID", databaseId);
94
95         // Add the bundle to the dialog.
96         EditBookmarkFolderDatabaseViewDialog editBookmarkFolderDatabaseViewDialog = new EditBookmarkFolderDatabaseViewDialog();
97         editBookmarkFolderDatabaseViewDialog.setArguments(bundle);
98
99         // Return the new dialog.
100         return editBookmarkFolderDatabaseViewDialog;
101     }
102
103     // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
104     @SuppressLint("InflateParams")
105     @Override
106     @NonNull
107     public Dialog onCreateDialog(Bundle savedInstanceState) {
108         // Remove the incorrect lint warning that `getInt()` might be null.
109         assert getArguments() != null;
110
111         // Get the bookmark database ID from the bundle.
112         int folderDatabaseId = getArguments().getInt("Database ID");
113
114         // 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`.
115         bookmarksDatabaseHelper = new BookmarksDatabaseHelper(getContext(), null, null, 0);
116
117         // Get a `Cursor` with the selected bookmark and move it to the first position.
118         Cursor folderCursor = bookmarksDatabaseHelper.getBookmark(folderDatabaseId);
119         folderCursor.moveToFirst();
120
121         // Use an alert dialog builder to create the alert dialog.
122         AlertDialog.Builder dialogBuilder;
123
124         // Set the style according to the theme.
125         if (MainWebViewActivity.darkTheme) {
126             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
127         } else {
128             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
129         }
130
131         // Set the title.
132         dialogBuilder.setTitle(R.string.edit_folder);
133
134         // Remove the incorrect lint warning that `getActivity()` might be null.
135         assert getActivity() != null;
136
137         // Set the view.  The parent view is `null` because it will be assigned by `AlertDialog`.
138         dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.edit_bookmark_folder_databaseview_dialog, null));
139
140         // Set the listener for the negative button.
141         dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
142             // Do nothing.  The `AlertDialog` will close automatically.
143         });
144
145         // Set the listener fo the positive button.
146         dialogBuilder.setPositiveButton(R.string.save, (DialogInterface dialog, int which) -> {
147             // Return the `DialogFragment` to the parent activity on save.
148             editBookmarkFolderDatabaseViewListener.onSaveBookmarkFolder(EditBookmarkFolderDatabaseViewDialog.this, folderDatabaseId);
149         });
150
151         // Create an alert dialog from the alert dialog builder.
152         final AlertDialog alertDialog = dialogBuilder.create();
153
154         // Remove the warning below that `getWindow()` might be null.
155         assert alertDialog.getWindow() != null;
156
157         // Disable screenshots if not allowed.
158         if (!MainWebViewActivity.allowScreenshots) {
159             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
160         }
161
162         // The alert dialog must be shown before items in the layout can be modified.
163         alertDialog.show();
164
165         // Get handles for the layout items.
166         TextView databaseIdTextView = alertDialog.findViewById(R.id.edit_folder_database_id_textview);
167         RadioGroup iconRadioGroup = alertDialog.findViewById(R.id.edit_folder_icon_radiogroup);
168         ImageView currentIconImageView = alertDialog.findViewById(R.id.edit_folder_current_icon_imageview);
169         ImageView newFavoriteIconImageView = alertDialog.findViewById(R.id.edit_folder_webpage_favorite_icon_imageview);
170         currentIconRadioButton = alertDialog.findViewById(R.id.edit_folder_current_icon_radiobutton);
171         nameEditText = alertDialog.findViewById(R.id.edit_folder_name_edittext);
172         folderSpinner = alertDialog.findViewById(R.id.edit_folder_parent_folder_spinner);
173         displayOrderEditText = alertDialog.findViewById(R.id.edit_folder_display_order_edittext);
174         editButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
175
176         // Store the current folder values.
177         currentFolderName = folderCursor.getString(folderCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
178         currentDisplayOrder = folderCursor.getString(folderCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER));
179         String parentFolder = folderCursor.getString(folderCursor.getColumnIndex(BookmarksDatabaseHelper.PARENT_FOLDER));
180
181         // Set the database ID.
182         databaseIdTextView.setText(String.valueOf(folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID))));
183
184         // Get the current favorite icon byte array from the `Cursor`.
185         byte[] currentIconByteArray = folderCursor.getBlob(folderCursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
186
187         // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
188         Bitmap currentIconBitmap = BitmapFactory.decodeByteArray(currentIconByteArray, 0, currentIconByteArray.length);
189
190         // Display the current icon bitmap in `edit_bookmark_current_icon`.
191         currentIconImageView.setImageBitmap(currentIconBitmap);
192
193         // Get a copy of the favorite icon bitmap.
194         Bitmap favoriteIconBitmap = MainWebViewActivity.favoriteIconBitmap;
195
196         // Scale the favorite icon bitmap down if it is larger than 256 x 256.  Filtering uses bilinear interpolation.
197         if ((favoriteIconBitmap.getHeight() > 256) || (favoriteIconBitmap.getWidth() > 256)) {
198             favoriteIconBitmap = Bitmap.createScaledBitmap(favoriteIconBitmap, 256, 256, true);
199         }
200
201         // Set the new favorite icon bitmap.
202         newFavoriteIconImageView.setImageBitmap(favoriteIconBitmap);
203
204         // Populate the folder name edit text.
205         nameEditText.setText(currentFolderName);
206
207         // Setup a matrix cursor for "Home Folder".
208         String[] matrixCursorColumnNames = {BookmarksDatabaseHelper._ID, BookmarksDatabaseHelper.BOOKMARK_NAME};
209         MatrixCursor matrixCursor = new MatrixCursor(matrixCursorColumnNames);
210         matrixCursor.addRow(new Object[]{HOME_FOLDER_DATABASE_ID, getString(R.string.home_folder)});
211
212         // Initialize a string builder to track the folders not to display in the spinner and populate it with the current folder.
213         exceptFolders = new StringBuilder(DatabaseUtils.sqlEscapeString(currentFolderName));
214
215         // Add all subfolders of the current folder to the list of folders not to display.
216         addSubfoldersToExceptFolders(currentFolderName);
217
218         // Get a cursor with the list of all the folders.
219         Cursor foldersCursor = bookmarksDatabaseHelper.getFoldersExcept(exceptFolders.toString());
220
221         // Combine the matrix cursor and the folders cursor.
222         MergeCursor foldersMergeCursor = new MergeCursor(new Cursor[]{matrixCursor, foldersCursor});
223
224         // Remove the incorrect lint warning that `getContext()` might be null.
225         assert getContext() != null;
226
227         // Create a resource cursor adapter for the spinner.
228         ResourceCursorAdapter foldersCursorAdapter = new ResourceCursorAdapter(getContext(), R.layout.databaseview_spinner_item, foldersMergeCursor, 0) {
229             @Override
230             public void bindView(View view, Context context, Cursor cursor) {
231                 // Get handles for the spinner views.
232                 ImageView spinnerItemImageView = view.findViewById(R.id.spinner_item_imageview);
233                 TextView spinnerItemTextView = view.findViewById(R.id.spinner_item_textview);
234
235                 // Set the folder icon according to the type.
236                 if (foldersMergeCursor.getPosition() == 0) {  // Set the `Home Folder` icon.
237                     // Set the gray folder image.  `ContextCompat` must be used until the minimum API >= 21.
238                     spinnerItemImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.folder_gray));
239                 } else {  // Set a user folder icon.
240                     // Get the folder icon byte array.
241                     byte[] folderIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
242
243                     // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
244                     Bitmap folderIconBitmap = BitmapFactory.decodeByteArray(folderIconByteArray, 0, folderIconByteArray.length);
245
246                     // Set the folder icon.
247                     spinnerItemImageView.setImageBitmap(folderIconBitmap);
248                 }
249
250                 // Set the text view to display the folder name.
251                 spinnerItemTextView.setText(cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME)));
252             }
253         };
254
255         // Set the `ResourceCursorAdapter` drop drown view resource.
256         foldersCursorAdapter.setDropDownViewResource(R.layout.databaseview_spinner_dropdown_items);
257
258         // Set the adapter for the folder `Spinner`.
259         folderSpinner.setAdapter(foldersCursorAdapter);
260
261         // Select the current folder in the `Spinner` if the bookmark isn't in the "Home Folder".
262         if (!parentFolder.equals("")) {
263             // Get the database ID of the parent folder.
264             int parentFolderDatabaseId = bookmarksDatabaseHelper.getFolderDatabaseId(folderCursor.getString(folderCursor.getColumnIndex(BookmarksDatabaseHelper.PARENT_FOLDER)));
265
266             // Initialize `parentFolderPosition` and the iteration variable.
267             int parentFolderPosition = 0;
268             int i = 0;
269
270             // Find the parent folder position in folders `ResourceCursorAdapter`.
271             do {
272                 if (foldersCursorAdapter.getItemId(i) == parentFolderDatabaseId) {
273                     // Store the current position for the parent folder.
274                     parentFolderPosition = i;
275                 } else {
276                     // Try the next entry.
277                     i++;
278                 }
279                 // Stop when the parent folder position is found or all the items in the `ResourceCursorAdapter` have been checked.
280             } while ((parentFolderPosition == 0) && (i < foldersCursorAdapter.getCount()));
281
282             // Select the parent folder in the `Spinner`.
283             folderSpinner.setSelection(parentFolderPosition);
284         }
285
286         // Store the current folder database ID.
287         currentParentFolderDatabaseId = (int) folderSpinner.getSelectedItemId();
288
289         // Populate the display order `EditText`.
290         displayOrderEditText.setText(String.valueOf(folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER))));
291
292         // Initially disable the edit button.
293         editButton.setEnabled(false);
294
295         // Update the edit button if the icon selection changes.
296         iconRadioGroup.setOnCheckedChangeListener((group, checkedId) -> {
297             // Update the edit button.
298             updateEditButton();
299         });
300
301         // Update the edit button if the bookmark name changes.
302         nameEditText.addTextChangedListener(new TextWatcher() {
303             @Override
304             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
305                 // Do nothing.
306             }
307
308             @Override
309             public void onTextChanged(CharSequence s, int start, int before, int count) {
310                 // Do nothing.
311             }
312
313             @Override
314             public void afterTextChanged(Editable s) {
315                 // Update the edit button.
316                 updateEditButton();
317             }
318         });
319
320         // Update the edit button if the folder changes.
321         folderSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
322             @Override
323             public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
324                 // Update the edit button.
325                 updateEditButton();
326             }
327
328             @Override
329             public void onNothingSelected(AdapterView<?> parent) {
330
331             }
332         });
333
334         // Update the edit button if the display order changes.
335         displayOrderEditText.addTextChangedListener(new TextWatcher() {
336             @Override
337             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
338                 // Do nothing.
339             }
340
341             @Override
342             public void onTextChanged(CharSequence s, int start, int before, int count) {
343                 // Do nothing.
344             }
345
346             @Override
347             public void afterTextChanged(Editable s) {
348                 // Update the edit button.
349                 updateEditButton();
350             }
351         });
352
353         // Allow the `enter` key on the keyboard to save the bookmark from the bookmark name `EditText`.
354         nameEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
355             // Save the bookmark if the event is a key-down on the "enter" button.
356             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) {  // The enter key was pressed and the edit button is enabled.
357                 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
358                 editBookmarkFolderDatabaseViewListener.onSaveBookmarkFolder(EditBookmarkFolderDatabaseViewDialog.this, folderDatabaseId);
359
360                 // Manually dismiss `alertDialog`.
361                 alertDialog.dismiss();
362
363                 // Consume the event.
364                 return true;
365             } else {  // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
366                 return false;
367             }
368         });
369
370         // Allow the "enter" key on the keyboard to save the bookmark from the display order `EditText`.
371         displayOrderEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
372             // Save the bookmark if the event is a key-down on the "enter" button.
373             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) {  // The enter key was pressed and the edit button is enabled.
374                 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
375                 editBookmarkFolderDatabaseViewListener.onSaveBookmarkFolder(EditBookmarkFolderDatabaseViewDialog.this, folderDatabaseId);
376
377                 // Manually dismiss the `AlertDialog`.
378                 alertDialog.dismiss();
379
380                 // Consume the event.
381                 return true;
382             } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
383                 return false;
384             }
385         });
386
387         // `onCreateDialog` requires the return of an `AlertDialog`.
388         return alertDialog;
389     }
390
391     private void updateEditButton() {
392         // Get the values from the dialog.
393         String newFolderName = nameEditText.getText().toString();
394         int newParentFolderDatabaseId = (int) folderSpinner.getSelectedItemId();
395         String newDisplayOrder = displayOrderEditText.getText().toString();
396
397         // Get a cursor for the new folder name if it exists.
398         Cursor folderExistsCursor = bookmarksDatabaseHelper.getFolder(newFolderName);
399
400         // Is the new folder name empty?
401         boolean folderNameNotEmpty = !newFolderName.isEmpty();
402
403         // Does the folder name already exist?
404         boolean folderNameAlreadyExists = (!newFolderName.equals(currentFolderName) && (folderExistsCursor.getCount() > 0));
405
406         // Has the favorite icon changed?
407         boolean iconChanged = !currentIconRadioButton.isChecked();
408
409         // Has the name been renamed?
410         boolean folderRenamed = (!newFolderName.equals(currentFolderName) && !folderNameAlreadyExists);
411
412         // Has the folder changed?
413         boolean parentFolderChanged = newParentFolderDatabaseId != currentParentFolderDatabaseId;
414
415         // Has the display order changed?
416         boolean displayOrderChanged = !newDisplayOrder.equals(currentDisplayOrder);
417
418         // Is the display order empty?
419         boolean displayOrderNotEmpty = !newDisplayOrder.isEmpty();
420
421         // Update the enabled status of the edit button.
422         editButton.setEnabled((iconChanged || folderRenamed || parentFolderChanged || displayOrderChanged) && folderNameNotEmpty && displayOrderNotEmpty);
423     }
424
425     private void addSubfoldersToExceptFolders(String folderName) {
426         // Get a `Cursor` will all the immediate subfolders.
427         Cursor subfoldersCursor = bookmarksDatabaseHelper.getSubfolders(folderName);
428
429         for (int i = 0; i < subfoldersCursor.getCount(); i++) {
430             // Move `subfolderCursor` to the current item.
431             subfoldersCursor.moveToPosition(i);
432
433             // Get the name of the subfolder.
434             String subfolderName = subfoldersCursor.getString(subfoldersCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
435
436             // Add the subfolder to `exceptFolders`.
437             exceptFolders.append(",");
438             exceptFolders.append(DatabaseUtils.sqlEscapeString(subfolderName));
439
440             // Run the same tasks for any subfolders of the subfolder.
441             addSubfoldersToExceptFolders(subfolderName);
442         }
443     }
444 }