]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/EditBookmarkDatabaseViewDialog.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 / EditBookmarkDatabaseViewDialog.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.MatrixCursor;
29 import android.database.MergeCursor;
30 import android.graphics.Bitmap;
31 import android.graphics.BitmapFactory;
32 import android.os.Bundle;
33 import android.text.Editable;
34 import android.text.TextWatcher;
35 import android.view.KeyEvent;
36 import android.view.View;
37 import android.view.WindowManager;
38 import android.widget.AdapterView;
39 import android.widget.Button;
40 import android.widget.EditText;
41 import android.widget.ImageView;
42 import android.widget.RadioButton;
43 import android.widget.RadioGroup;
44 import android.widget.ResourceCursorAdapter;
45 import android.widget.Spinner;
46 import android.widget.TextView;
47
48 import com.stoutner.privacybrowser.R;
49 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
50 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
51
52 import androidx.annotation.NonNull;
53 import androidx.core.content.ContextCompat;
54 import androidx.fragment.app.DialogFragment;  // The AndroidX dialog fragment must be used or an error is produced on API <=22.
55
56 public class EditBookmarkDatabaseViewDialog extends DialogFragment {
57     // Instantiate the constants.
58     public static final int HOME_FOLDER_DATABASE_ID = -1;
59
60     // Instantiate the class variables.
61     private EditBookmarkDatabaseViewListener editBookmarkDatabaseViewListener;
62     private String currentBookmarkName;
63     private String currentUrl;
64     private int currentFolderDatabaseId;
65     private String currentDisplayOrder;
66     private RadioButton newIconRadioButton;
67     private EditText nameEditText;
68     private EditText urlEditText;
69     private Spinner folderSpinner;
70     private EditText displayOrderEditText;
71     private Button editButton;
72
73     // The public interface is used to send information back to the parent activity.
74     public interface EditBookmarkDatabaseViewListener {
75         void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId);
76     }
77
78     @Override
79     public void onAttach(Context context) {
80         // Run the default commands.
81         super.onAttach(context);
82
83         // Get a handle for edit bookmark database view listener from the launching context.
84         editBookmarkDatabaseViewListener = (EditBookmarkDatabaseViewListener) context;
85     }
86
87     // Store the database ID in the arguments bundle.
88     public static EditBookmarkDatabaseViewDialog bookmarkDatabaseId(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         EditBookmarkDatabaseViewDialog editBookmarkDatabaseViewDialog = new EditBookmarkDatabaseViewDialog();
97         editBookmarkDatabaseViewDialog.setArguments(bundle);
98
99         // Return the new dialog.
100         return editBookmarkDatabaseViewDialog;
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 below that `getInt()` might be null.
109         assert getArguments() != null;
110
111         // Get the bookmark database ID from the bundle.
112         int bookmarkDatabaseId = getArguments().getInt("Database ID");
113
114         // Initialize the database helper.  The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
115         BookmarksDatabaseHelper 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 bookmarkCursor = bookmarksDatabaseHelper.getBookmark(bookmarkDatabaseId);
119         bookmarkCursor.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_bookmark);
133
134         // Remove the incorrect lint warning below that `getLayoutInflater()` 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_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             editBookmarkDatabaseViewListener.onSaveBookmark(EditBookmarkDatabaseViewDialog.this, bookmarkDatabaseId);
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_bookmark_database_id_textview);
167         RadioGroup iconRadioGroup = alertDialog.findViewById(R.id.edit_bookmark_icon_radiogroup);
168         ImageView currentIconImageView = alertDialog.findViewById(R.id.edit_bookmark_current_icon);
169         ImageView newFavoriteIconImageView = alertDialog.findViewById(R.id.edit_bookmark_webpage_favorite_icon);
170         newIconRadioButton = alertDialog.findViewById(R.id.edit_bookmark_webpage_favorite_icon_radiobutton);
171         nameEditText = alertDialog.findViewById(R.id.edit_bookmark_name_edittext);
172         urlEditText = alertDialog.findViewById(R.id.edit_bookmark_url_edittext);
173         folderSpinner = alertDialog.findViewById(R.id.edit_bookmark_folder_spinner);
174         displayOrderEditText = alertDialog.findViewById(R.id.edit_bookmark_display_order_edittext);
175         editButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
176
177         // Store the current bookmark values.
178         currentBookmarkName = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
179         currentUrl = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL));
180         currentDisplayOrder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER));
181
182         // Set the database ID.
183         databaseIdTextView.setText(String.valueOf(bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper._ID))));
184
185         // Get the current favorite icon byte array from the `Cursor`.
186         byte[] currentIconByteArray = bookmarkCursor.getBlob(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
187
188         // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
189         Bitmap currentIconBitmap = BitmapFactory.decodeByteArray(currentIconByteArray, 0, currentIconByteArray.length);
190
191         // Display `currentIconBitmap` in `edit_bookmark_current_icon`.
192         currentIconImageView.setImageBitmap(currentIconBitmap);
193
194         // Get a copy of the favorite icon bitmap.
195         Bitmap favoriteIconBitmap = MainWebViewActivity.favoriteIconBitmap;
196
197         // Scale the favorite icon bitmap down if it is larger than 256 x 256.  Filtering uses bilinear interpolation.
198         if ((favoriteIconBitmap.getHeight() > 256) || (favoriteIconBitmap.getWidth() > 256)) {
199             favoriteIconBitmap = Bitmap.createScaledBitmap(favoriteIconBitmap, 256, 256, true);
200         }
201
202         // Set the new favorite icon bitmap.
203         newFavoriteIconImageView.setImageBitmap(favoriteIconBitmap);
204
205         // Populate the bookmark name and URL `EditTexts`.
206         nameEditText.setText(currentBookmarkName);
207         urlEditText.setText(currentUrl);
208
209         // Setup a matrix cursor for "Home Folder".
210         String[] matrixCursorColumnNames = {BookmarksDatabaseHelper._ID, BookmarksDatabaseHelper.BOOKMARK_NAME};
211         MatrixCursor matrixCursor = new MatrixCursor(matrixCursorColumnNames);
212         matrixCursor.addRow(new Object[]{HOME_FOLDER_DATABASE_ID, getString(R.string.home_folder)});
213
214         // Get a cursor with the list of all the folders.
215         Cursor foldersCursor = bookmarksDatabaseHelper.getAllFolders();
216
217         // Combine `matrixCursor` and `foldersCursor`.
218         MergeCursor foldersMergeCursor = new MergeCursor(new Cursor[]{matrixCursor, foldersCursor});
219
220         // Remove the incorrect lint warning below that `getContext()` might be null.
221         assert getContext() != null;
222
223         // Create a resource cursor adapter for the spinner.
224         ResourceCursorAdapter foldersCursorAdapter = new ResourceCursorAdapter(getContext(), R.layout.databaseview_spinner_item, foldersMergeCursor, 0) {
225             @Override
226             public void bindView(View view, Context context, Cursor cursor) {
227                 // Get handles for the spinner views.
228                 ImageView spinnerItemImageView = view.findViewById(R.id.spinner_item_imageview);
229                 TextView spinnerItemTextView = view.findViewById(R.id.spinner_item_textview);
230
231                 // Set the folder icon according to the type.
232                 if (foldersMergeCursor.getPosition() == 0) {  // Set the `Home Folder` icon.
233                     // Set the gray folder image.  `ContextCompat` must be used until the minimum API >= 21.
234                     spinnerItemImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.folder_gray));
235                 } else {  // Set a user folder icon.
236                     // Get the folder icon byte array.
237                     byte[] folderIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
238
239                     // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
240                     Bitmap folderIconBitmap = BitmapFactory.decodeByteArray(folderIconByteArray, 0, folderIconByteArray.length);
241
242                     // Set the folder icon.
243                     spinnerItemImageView.setImageBitmap(folderIconBitmap);
244                 }
245
246                 // Set the text view to display the folder name.
247                 spinnerItemTextView.setText(cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME)));
248             }
249         };
250
251         // Set the `ResourceCursorAdapter` drop drown view resource.
252         foldersCursorAdapter.setDropDownViewResource(R.layout.databaseview_spinner_dropdown_items);
253
254         // Set the adapter for the folder `Spinner`.
255         folderSpinner.setAdapter(foldersCursorAdapter);
256
257         // Get the parent folder name.
258         String parentFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.PARENT_FOLDER));
259
260         // Select the current folder in the `Spinner` if the bookmark isn't in the "Home Folder".
261         if (!parentFolder.equals("")) {
262             // Get the database ID of the parent folder.
263             int folderDatabaseId = bookmarksDatabaseHelper.getFolderDatabaseId(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.PARENT_FOLDER)));
264
265             // Initialize `parentFolderPosition` and the iteration variable.
266             int parentFolderPosition = 0;
267             int i = 0;
268
269             // Find the parent folder position in folders `ResourceCursorAdapter`.
270             do {
271                 if (foldersCursorAdapter.getItemId(i) == folderDatabaseId) {
272                     // Store the current position for the parent folder.
273                     parentFolderPosition = i;
274                 } else {
275                     // Try the next entry.
276                     i++;
277                 }
278                 // Stop when the parent folder position is found or all the items in the `ResourceCursorAdapter` have been checked.
279             } while ((parentFolderPosition == 0) && (i < foldersCursorAdapter.getCount()));
280
281             // Select the parent folder in the `Spinner`.
282             folderSpinner.setSelection(parentFolderPosition);
283         }
284
285         // Store the current folder database ID.
286         currentFolderDatabaseId = (int) folderSpinner.getSelectedItemId();
287
288         // Populate the display order `EditText`.
289         displayOrderEditText.setText(String.valueOf(bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER))));
290
291         // Initially disable the edit button.
292         editButton.setEnabled(false);
293
294         // Update the edit button if the icon selection changes.
295         iconRadioGroup.setOnCheckedChangeListener((group, checkedId) -> {
296             // Update the edit button.
297             updateEditButton();
298         });
299
300         // Update the edit button if the bookmark name changes.
301         nameEditText.addTextChangedListener(new TextWatcher() {
302             @Override
303             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
304                 // Do nothing.
305             }
306
307             @Override
308             public void onTextChanged(CharSequence s, int start, int before, int count) {
309                 // Do nothing.
310             }
311
312             @Override
313             public void afterTextChanged(Editable s) {
314                 // Update the edit button.
315                 updateEditButton();
316             }
317         });
318
319         // Update the edit button if the URL changes.
320         urlEditText.addTextChangedListener(new TextWatcher() {
321             @Override
322             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
323                 // Do nothing.
324             }
325
326             @Override
327             public void onTextChanged(CharSequence s, int start, int before, int count) {
328                 // Do nothing.
329             }
330
331             @Override
332             public void afterTextChanged(Editable s) {
333                 // Update the edit button.
334                 updateEditButton();
335             }
336         });
337
338         // Update the edit button if the folder changes.
339         folderSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
340             @Override
341             public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
342                 // Update the edit button.
343                 updateEditButton();
344             }
345
346             @Override
347             public void onNothingSelected(AdapterView<?> parent) {
348
349             }
350         });
351
352         // Update the edit button if the display order changes.
353         displayOrderEditText.addTextChangedListener(new TextWatcher() {
354             @Override
355             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
356                 // Do nothing.
357             }
358
359             @Override
360             public void onTextChanged(CharSequence s, int start, int before, int count) {
361                 // Do nothing.
362             }
363
364             @Override
365             public void afterTextChanged(Editable s) {
366                 // Update the edit button.
367                 updateEditButton();
368             }
369         });
370
371         // Allow the `enter` key on the keyboard to save the bookmark from the bookmark name `EditText`.
372         nameEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
373             // Save the bookmark if the event is a key-down on the "enter" button.
374             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) {  // The enter key was pressed and the edit button is enabled.
375                 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
376                 editBookmarkDatabaseViewListener.onSaveBookmark(EditBookmarkDatabaseViewDialog.this, bookmarkDatabaseId);
377
378                 // Manually dismiss `alertDialog`.
379                 alertDialog.dismiss();
380
381                 // Consume the event.
382                 return true;
383             } else {  // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
384                 return false;
385             }
386         });
387
388         // Allow the "enter" key on the keyboard to save the bookmark from the URL `EditText`.
389         urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
390             // Save the bookmark if the event is a key-down on the "enter" button.
391             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) {  // The enter key was pressed and the edit button is enabled.
392                 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
393                 editBookmarkDatabaseViewListener.onSaveBookmark(EditBookmarkDatabaseViewDialog.this, bookmarkDatabaseId);
394
395                 // Manually dismiss the `AlertDialog`.
396                 alertDialog.dismiss();
397
398                 // Consume the event.
399                 return true;
400             } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
401                 return false;
402             }
403         });
404
405         // Allow the "enter" key on the keyboard to save the bookmark from the display order `EditText`.
406         displayOrderEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
407             // Save the bookmark if the event is a key-down on the "enter" button.
408             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) {  // The enter key was pressed and the edit button is enabled.
409                 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
410                 editBookmarkDatabaseViewListener.onSaveBookmark(EditBookmarkDatabaseViewDialog.this, bookmarkDatabaseId);
411
412                 // Manually dismiss the `AlertDialog`.
413                 alertDialog.dismiss();
414
415                 // Consume the event.
416                 return true;
417             } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
418                 return false;
419             }
420         });
421
422         // `onCreateDialog` requires the return of an `AlertDialog`.
423         return alertDialog;
424     }
425
426     private void updateEditButton() {
427         // Get the values from the dialog.
428         String newName = nameEditText.getText().toString();
429         String newUrl = urlEditText.getText().toString();
430         int newFolderDatabaseId = (int) folderSpinner.getSelectedItemId();
431         String newDisplayOrder = displayOrderEditText.getText().toString();
432
433         // Has the favorite icon changed?
434         boolean iconChanged = newIconRadioButton.isChecked();
435
436         // Has the name changed?
437         boolean nameChanged = !newName.equals(currentBookmarkName);
438
439         // Has the URL changed?
440         boolean urlChanged = !newUrl.equals(currentUrl);
441
442         // Has the folder changed?
443         boolean folderChanged = newFolderDatabaseId != currentFolderDatabaseId;
444
445         // Has the display order changed?
446         boolean displayOrderChanged = !newDisplayOrder.equals(currentDisplayOrder);
447
448         // Is the display order empty?
449         boolean displayOrderNotEmpty = !newDisplayOrder.isEmpty();
450
451         // Update the enabled status of the edit button.
452         editButton.setEnabled((iconChanged || nameChanged || urlChanged || folderChanged || displayOrderChanged) && displayOrderNotEmpty);
453     }
454 }