]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/EditBookmarkDialog.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 / EditBookmarkDialog.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 EditBookmarkDialog extends DialogFragment {
50     // Instantiate the class variables.
51     private EditBookmarkListener editBookmarkListener;
52     private EditText nameEditText;
53     private EditText urlEditText;
54     private RadioButton newIconRadioButton;
55     private Button editButton;
56     private String currentName;
57     private String currentUrl;
58
59     // The public interface is used to send information back to the parent activity.
60     public interface EditBookmarkListener {
61         void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId);
62     }
63
64     public void onAttach(Context context) {
65         // Run the default commands.
66         super.onAttach(context);
67
68         // Get a handle for `EditBookmarkListener` from the launching context.
69         editBookmarkListener = (EditBookmarkListener) context;
70     }
71
72     // Store the database ID in the arguments bundle.
73     public static EditBookmarkDialog bookmarkDatabaseId(int databaseId) {
74         // Create a bundle.
75         Bundle bundle = new Bundle();
76
77         // Store the bookmark database ID in the bundle.
78         bundle.putInt("Database ID", databaseId);
79
80         // Add the bundle to the dialog.
81         EditBookmarkDialog editBookmarkDialog = new EditBookmarkDialog();
82         editBookmarkDialog.setArguments(bundle);
83
84         // Return the new dialog.
85         return editBookmarkDialog;
86     }
87
88     // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
89     @SuppressLint("InflateParams")
90     @Override
91     @NonNull
92     public Dialog onCreateDialog(Bundle savedInstanceState) {
93         // Remove the incorrect lint warning that `getInt()` might be null.
94         assert getArguments() != null;
95
96         // Store the bookmark database ID in the class variable.
97         int selectedBookmarkDatabaseId = getArguments().getInt("Database ID");
98
99         // Initialize the database helper.  The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
100         BookmarksDatabaseHelper bookmarksDatabaseHelper = new BookmarksDatabaseHelper(getContext(), null, null, 0);
101
102         // Get a `Cursor` with the selected bookmark and move it to the first position.
103         Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(selectedBookmarkDatabaseId);
104         bookmarkCursor.moveToFirst();
105
106         // Use an alert dialog builder to create the alert dialog.
107         AlertDialog.Builder dialogBuilder;
108
109         // Set the style according to the theme.
110         if (MainWebViewActivity.darkTheme) {
111             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
112         } else {
113             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
114         }
115
116         // Set the title.
117         dialogBuilder.setTitle(R.string.edit_bookmark);
118
119         // Remove the incorrect lint warning that `getActivity().getLayoutInflater()` might be null.
120         assert getActivity() != null;
121
122         // Set the view.  The parent view is null because it will be assigned by the alert dialog.
123         dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.edit_bookmark_dialog, null));
124
125         // Set the cancel button listener.
126         dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
127             // Do nothing.  The alert dialog will close automatically.
128         });
129
130         // Set the save button listener.
131         dialogBuilder.setPositiveButton(R.string.save, (DialogInterface dialog, int which) -> {
132             // Return the dialog fragment to the parent activity.
133             editBookmarkListener.onSaveBookmark(EditBookmarkDialog.this, selectedBookmarkDatabaseId);
134         });
135
136         // Create an alert dialog from the builder.
137         final AlertDialog alertDialog = dialogBuilder.create();
138
139         // remove the incorrect lint warning below that `getWindow().addFlags()` might be null.
140         assert alertDialog.getWindow() != null;
141
142         // Disable screenshots if not allowed.
143         if (!MainWebViewActivity.allowScreenshots) {
144             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
145         }
146
147         // The alert dialog must be shown before items in the layout can be modified.
148         alertDialog.show();
149
150         // Get handles for the layout items.
151         RadioGroup iconRadioGroup = alertDialog.findViewById(R.id.edit_bookmark_icon_radiogroup);
152         ImageView currentIconImageView = alertDialog.findViewById(R.id.edit_bookmark_current_icon);
153         ImageView newFavoriteIconImageView = alertDialog.findViewById(R.id.edit_bookmark_webpage_favorite_icon);
154         newIconRadioButton = alertDialog.findViewById(R.id.edit_bookmark_webpage_favorite_icon_radiobutton);
155         nameEditText = alertDialog.findViewById(R.id.edit_bookmark_name_edittext);
156         urlEditText = alertDialog.findViewById(R.id.edit_bookmark_url_edittext);
157         editButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
158
159         // Get the current favorite icon byte array from the cursor.
160         byte[] currentIconByteArray = bookmarkCursor.getBlob(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
161
162         // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
163         Bitmap currentIconBitmap = BitmapFactory.decodeByteArray(currentIconByteArray, 0, currentIconByteArray.length);
164
165         // Display the current icon bitmap.
166         currentIconImageView.setImageBitmap(currentIconBitmap);
167
168         // Get a copy of the favorite icon bitmap.
169         Bitmap favoriteIconBitmap = MainWebViewActivity.favoriteIconBitmap;
170
171         // Scale the favorite icon bitmap down if it is larger than 256 x 256.  Filtering uses bilinear interpolation.
172         if ((favoriteIconBitmap.getHeight() > 256) || (favoriteIconBitmap.getWidth() > 256)) {
173             favoriteIconBitmap = Bitmap.createScaledBitmap(favoriteIconBitmap, 256, 256, true);
174         }
175
176         // Set the new favorite icon bitmap.
177         newFavoriteIconImageView.setImageBitmap(favoriteIconBitmap);
178
179         // Store the current bookmark name and URL.
180         currentName = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
181         currentUrl = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL));
182
183         // Populate the edit texts.
184         nameEditText.setText(currentName);
185         urlEditText.setText(currentUrl);
186
187         // Initially disable the edit button.
188         editButton.setEnabled(false);
189
190         // Update the edit button if the icon selection changes.
191         iconRadioGroup.setOnCheckedChangeListener((RadioGroup group, int checkedId) -> {
192             // Update the edit button.
193             updateEditButton();
194         });
195
196         // Update the edit button if the bookmark name changes.
197         nameEditText.addTextChangedListener(new TextWatcher() {
198             @Override
199             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
200                 // Do nothing.
201             }
202
203             @Override
204             public void onTextChanged(CharSequence s, int start, int before, int count) {
205                 // Do nothing.
206             }
207
208             @Override
209             public void afterTextChanged(Editable s) {
210                 // Update the edit button.
211                 updateEditButton();
212             }
213         });
214
215         // Update the edit button if the URL changes.
216         urlEditText.addTextChangedListener(new TextWatcher() {
217             @Override
218             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
219                 // Do nothing.
220             }
221
222             @Override
223             public void onTextChanged(CharSequence s, int start, int before, int count) {
224                 // Do nothing.
225             }
226
227             @Override
228             public void afterTextChanged(Editable s) {
229                 // Update the edit button.
230                 updateEditButton();
231             }
232         });
233
234         // Allow the enter key on the keyboard to save the bookmark from the bookmark name edit text.
235         nameEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
236             // Save the bookmark if the event is a key-down on the "enter" button.
237             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) {  // The enter key was pressed and the edit button is enabled.
238                 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
239                 editBookmarkListener.onSaveBookmark(EditBookmarkDialog.this, selectedBookmarkDatabaseId);
240
241                 // Manually dismiss `alertDialog`.
242                 alertDialog.dismiss();
243
244                 // Consume the event.
245                 return true;
246             } else {  // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
247                 return false;
248             }
249         });
250
251         // Allow the enter key on the keyboard to save the bookmark from the URL edit text.
252         urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
253             // Save the bookmark if the event is a key-down on the "enter" button.
254             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) {  // The enter key was pressed and the edit button is enabled.
255                 // Trigger the `Listener` and return the DialogFragment to the parent activity.
256                 editBookmarkListener.onSaveBookmark(EditBookmarkDialog.this, selectedBookmarkDatabaseId);
257
258                 // Manually dismiss the alert dialog.
259                 alertDialog.dismiss();
260
261                 // Consume the event.
262                 return true;
263             } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
264                 return false;
265             }
266         });
267
268         // Return the alert dialog.
269         return alertDialog;
270     }
271
272     private void updateEditButton() {
273         // Get the text from the `EditTexts`.
274         String newName = nameEditText.getText().toString();
275         String newUrl = urlEditText.getText().toString();
276
277         // Has the favorite icon changed?
278         boolean iconChanged = newIconRadioButton.isChecked();
279
280         // Has the name changed?
281         boolean nameChanged = !newName.equals(currentName);
282
283         // Has the URL changed?
284         boolean urlChanged = !newUrl.equals(currentUrl);
285
286         // Update the enabled status of the edit button.
287         editButton.setEnabled(iconChanged || nameChanged || urlChanged);
288     }
289 }