]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/EditBookmarkFolderDialog.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 / EditBookmarkFolderDialog.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.graphics.Bitmap;
29 import android.graphics.BitmapFactory;
30 import android.os.Bundle;
31 import android.text.Editable;
32 import android.text.TextWatcher;
33 import android.view.KeyEvent;
34 import android.view.View;
35 import android.view.WindowManager;
36 import android.widget.Button;
37 import android.widget.EditText;
38 import android.widget.ImageView;
39 import android.widget.RadioButton;
40 import android.widget.RadioGroup;
41
42 import androidx.annotation.NonNull;
43 import androidx.fragment.app.DialogFragment;  // The AndroidX dialog fragment must be used or an error is produced on API <=22.
44
45 import com.stoutner.privacybrowser.R;
46 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
47 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
48
49 public class EditBookmarkFolderDialog extends DialogFragment {
50     // Instantiate the class variable.
51     private EditBookmarkFolderListener editBookmarkFolderListener;
52
53     // The public interface is used to send information back to the parent activity.
54     public interface EditBookmarkFolderListener {
55         void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId);
56     }
57
58     public void onAttach(Context context) {
59         // Run the default commands.
60         super.onAttach(context);
61
62         // Get a handle for `EditFolderListener` from the launching context.
63         editBookmarkFolderListener = (EditBookmarkFolderListener) context;
64     }
65
66     // Store the database ID in the arguments bundle.
67     public static EditBookmarkFolderDialog folderDatabaseId(int databaseId) {
68         // Create a bundle
69         Bundle bundle = new Bundle();
70
71         // Store the folder database ID in the bundle.
72         bundle.putInt("Database ID", databaseId);
73
74         // Add the bundle to the dialog.
75         EditBookmarkFolderDialog editBookmarkFolderDialog = new EditBookmarkFolderDialog();
76         editBookmarkFolderDialog.setArguments(bundle);
77
78         // Return the new dialog.
79         return editBookmarkFolderDialog;
80     }
81
82     // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
83     @SuppressLint("InflateParams")
84     @Override
85     @NonNull
86     public Dialog onCreateDialog(Bundle savedInstanceState) {
87         // Remove the incorrect lint warning that `getInt()` might be null.
88         assert getArguments() != null;
89
90         // Store the folder database ID in the class variable.
91         int selectedFolderDatabaseId = getArguments().getInt("Database ID");
92
93         // 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`.
94         final BookmarksDatabaseHelper bookmarksDatabaseHelper = new BookmarksDatabaseHelper(getContext(), null, null, 0);
95
96         // Get a cursor with the selected folder and move it to the first position.
97         Cursor folderCursor = bookmarksDatabaseHelper.getBookmark(selectedFolderDatabaseId);
98         folderCursor.moveToFirst();
99
100         // Use an alert dialog builder to create the alert dialog.
101         AlertDialog.Builder dialogBuilder;
102
103         // Set the style according to the theme.
104         if (MainWebViewActivity.darkTheme) {
105             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
106         } else {
107             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
108         }
109
110         // Set the title.
111         dialogBuilder.setTitle(R.string.edit_folder);
112
113         // Remove the incorrect lint warning that `getActivity()` might be null.
114         assert getActivity() != null;
115
116         // Set the view.  The parent view is `null` because it will be assigned by `AlertDialog`.
117         dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.edit_bookmark_folder_dialog, null));
118
119         // Set the listener for the negative button.
120         dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
121             // Do nothing.  The `AlertDialog` will close automatically.
122         });
123
124         // Set the listener fo the positive button.
125         dialogBuilder.setPositiveButton(R.string.save, (DialogInterface dialog, int which) -> {
126             // Return the `DialogFragment` to the parent activity on save.
127             editBookmarkFolderListener.onSaveBookmarkFolder(EditBookmarkFolderDialog.this, selectedFolderDatabaseId);
128         });
129
130         // Create an alert dialog from the alert dialog builder.
131         final AlertDialog alertDialog = dialogBuilder.create();
132
133         // Remove the warning below that `getWindow()` might be null.
134         assert alertDialog.getWindow() != null;
135
136         // Disable screenshots if not allowed.
137         if (!MainWebViewActivity.allowScreenshots) {
138             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
139         }
140
141         // The alert dialog must be shown before items in the layout can be modified.
142         alertDialog.show();
143
144         // Get handles for the views in the alert dialog.
145         RadioGroup iconRadioGroup = alertDialog.findViewById(R.id.edit_folder_icon_radio_group);
146         final RadioButton currentIconRadioButton = alertDialog.findViewById(R.id.edit_folder_current_icon_radiobutton);
147         ImageView currentIconImageView = alertDialog.findViewById(R.id.edit_folder_current_icon_imageview);
148         ImageView webPageFavoriteIconImageView = alertDialog.findViewById(R.id.edit_folder_web_page_favorite_icon_imageview);
149         final EditText folderNameEditText = alertDialog.findViewById(R.id.edit_folder_name_edittext);
150         final Button editButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
151
152         // Initially disable the edit button.
153         editButton.setEnabled(false);
154
155         // Get the current favorite icon byte array from the Cursor.
156         byte[] currentIconByteArray = folderCursor.getBlob(folderCursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
157
158         // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
159         Bitmap currentIconBitmap = BitmapFactory.decodeByteArray(currentIconByteArray, 0, currentIconByteArray.length);
160
161         // Display the current icon bitmap.
162         currentIconImageView.setImageBitmap(currentIconBitmap);
163
164         // Get a copy of the favorite icon bitmap.
165         Bitmap favoriteIconBitmap = MainWebViewActivity.favoriteIconBitmap;
166
167         // Scale the favorite icon bitmap down if it is larger than 256 x 256.  Filtering uses bilinear interpolation.
168         if ((favoriteIconBitmap.getHeight() > 256) || (favoriteIconBitmap.getWidth() > 256)) {
169             favoriteIconBitmap = Bitmap.createScaledBitmap(favoriteIconBitmap, 256, 256, true);
170         }
171
172         // Set the new favorite icon bitmap.
173         webPageFavoriteIconImageView.setImageBitmap(favoriteIconBitmap);
174
175         // Get the current folder name.
176         final String currentFolderName = folderCursor.getString(folderCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
177
178         // Display the current folder name in `edit_folder_name_edittext`.
179         folderNameEditText.setText(currentFolderName);
180
181         // Update the status of the edit button when the folder name is changed.
182         folderNameEditText.addTextChangedListener(new TextWatcher() {
183             @Override
184             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
185                 // Do nothing.
186             }
187
188             @Override
189             public void onTextChanged(CharSequence s, int start, int before, int count) {
190                 // Do nothing.
191             }
192
193             @Override
194             public void afterTextChanged(Editable s) {
195                 // Convert the current text to a string.
196                 String newFolderName = s.toString();
197
198                 // Get a cursor for the new folder name if it exists.
199                 Cursor folderExistsCursor = bookmarksDatabaseHelper.getFolder(newFolderName);
200
201                 // Is the new folder name empty?
202                 boolean folderNameNotEmpty = !newFolderName.isEmpty();
203
204                 // Does the folder name already exist?
205                 boolean folderNameAlreadyExists = (!newFolderName.equals(currentFolderName) && (folderExistsCursor.getCount() > 0));
206
207                 // Has the folder been renamed?
208                 boolean folderRenamed = (!newFolderName.equals(currentFolderName) && !folderNameAlreadyExists);
209
210                 // Has the favorite icon changed?
211                 boolean iconChanged = (!currentIconRadioButton.isChecked() && !folderNameAlreadyExists);
212
213                 // Enable the create button if something has been edited and the new folder name is valid.
214                 editButton.setEnabled(folderNameNotEmpty && (folderRenamed || iconChanged));
215             }
216         });
217
218         // Update the status of the edit button when the icon is changed.
219         iconRadioGroup.setOnCheckedChangeListener((RadioGroup group, int checkedId) -> {
220             // Get the new folder name.
221             String newFolderName = folderNameEditText.getText().toString();
222
223             // Get a cursor for the new folder name if it exists.
224             Cursor folderExistsCursor = bookmarksDatabaseHelper.getFolder(newFolderName);
225
226             // Is the new folder name empty?
227             boolean folderNameEmpty = newFolderName.isEmpty();
228
229             // Does the folder name already exist?
230             boolean folderNameAlreadyExists = (!newFolderName.equals(currentFolderName) && (folderExistsCursor.getCount() > 0));
231
232             // Has the folder been renamed?
233             boolean folderRenamed = (!newFolderName.equals(currentFolderName) && !folderNameAlreadyExists);
234
235             // Has the favorite icon changed?
236             boolean iconChanged = (!currentIconRadioButton.isChecked() && !folderNameAlreadyExists);
237
238             // Enable the create button if something has been edited and the new folder name is valid.
239             editButton.setEnabled(!folderNameEmpty && (folderRenamed || iconChanged));
240         });
241
242         // Allow the `enter` key on the keyboard to save the bookmark from `edit_bookmark_name_edittext`.
243         folderNameEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
244             // If the event is a key-down on the "enter" button, select the PositiveButton `Save`.
245             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) {  // The enter key was pressed and the edit button is enabled.
246                 // Trigger `editBookmarkListener` and return the DialogFragment to the parent activity.
247                 editBookmarkFolderListener.onSaveBookmarkFolder(EditBookmarkFolderDialog.this, selectedFolderDatabaseId);
248
249                 // Manually dismiss the `AlertDialog`.
250                 alertDialog.dismiss();
251
252                 // Consume the event.
253                 return true;
254             } else {  // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
255                 return false;
256             }
257         });
258
259         // `onCreateDialog` requires the return of an `AlertDialog`.
260         return alertDialog;
261     }
262 }