]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/EditBookmarkDialog.java
Switch to the new Day/Night theme. https://redmine.stoutner.com/issues/522
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / EditBookmarkDialog.java
1 /*
2  * Copyright © 2016-2020 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.Dialog;
24 import android.content.Context;
25 import android.content.DialogInterface;
26 import android.content.SharedPreferences;
27 import android.database.Cursor;
28 import android.graphics.Bitmap;
29 import android.graphics.BitmapFactory;
30 import android.os.Bundle;
31 import android.preference.PreferenceManager;
32 import android.text.Editable;
33 import android.text.TextWatcher;
34 import android.view.KeyEvent;
35 import android.view.View;
36 import android.view.WindowManager;
37 import android.widget.Button;
38 import android.widget.EditText;
39 import android.widget.ImageView;
40 import android.widget.RadioButton;
41 import android.widget.RadioGroup;
42
43 import androidx.annotation.NonNull;
44 import androidx.appcompat.app.AlertDialog;
45 import androidx.fragment.app.DialogFragment;
46
47 import com.stoutner.privacybrowser.R;
48 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
49
50 import java.io.ByteArrayOutputStream;
51
52 public class EditBookmarkDialog extends DialogFragment {
53     // Define the edit bookmark listener.
54     private EditBookmarkListener editBookmarkListener;
55
56     // The public interface is used to send information back to the parent activity.
57     public interface EditBookmarkListener {
58         void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap);
59     }
60
61     public void onAttach(@NonNull Context context) {
62         // Run the default commands.
63         super.onAttach(context);
64
65         // Get a handle for `EditBookmarkListener` from the launching context.
66         editBookmarkListener = (EditBookmarkListener) context;
67     }
68
69     // Store the database ID in the arguments bundle.
70     public static EditBookmarkDialog bookmarkDatabaseId(int databaseId, Bitmap favoriteIconBitmap) {
71         // Create a favorite icon byte array output stream.
72         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
73
74         // Convert the favorite icon to a PNG and place it in the byte array output stream.  `0` is for lossless compression (the only option for a PNG).
75         favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
76
77         // Convert the byte array output stream to a byte array.
78         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
79
80         // Create an arguments bundle.
81         Bundle argumentsBundle = new Bundle();
82
83         // Store the variables in the bundle.
84         argumentsBundle.putInt("database_id", databaseId);
85         argumentsBundle.putByteArray("favorite_icon_byte_array", favoriteIconByteArray);
86
87         // Create a new instance of the dialog.
88         EditBookmarkDialog editBookmarkDialog = new EditBookmarkDialog();
89
90         // Add the arguments bundle to the dialog.
91         editBookmarkDialog.setArguments(argumentsBundle);
92
93         // Return the new dialog.
94         return editBookmarkDialog;
95     }
96
97     // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
98     @SuppressLint("InflateParams")
99     @Override
100     @NonNull
101     public Dialog onCreateDialog(Bundle savedInstanceState) {
102         // Get the arguments.
103         Bundle arguments = getArguments();
104
105         // Remove the incorrect lint warning below that the arguments might be null.
106         assert arguments != null;
107
108         // Store the bookmark database ID in the class variable.
109         int selectedBookmarkDatabaseId = arguments.getInt("database_id");
110
111         // Get the favorite icon byte array.
112         byte[] favoriteIconByteArray = arguments.getByteArray("favorite_icon_byte_array");
113
114         // Remove the incorrect lint warning below that the favorite icon byte array might be null.
115         assert favoriteIconByteArray != null;
116
117         // Convert the favorite icon byte array to a bitmap.
118         Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
119
120         // Initialize the database helper.  The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
121         BookmarksDatabaseHelper bookmarksDatabaseHelper = new BookmarksDatabaseHelper(getContext(), null, null, 0);
122
123         // Get a `Cursor` with the selected bookmark and move it to the first position.
124         Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(selectedBookmarkDatabaseId);
125         bookmarkCursor.moveToFirst();
126
127         // Use an alert dialog builder to create the alert dialog.
128         AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(requireContext(), R.style.PrivacyBrowserAlertDialog);
129
130         // Set the title.
131         dialogBuilder.setTitle(R.string.edit_bookmark);
132
133         // Remove the incorrect lint warning that `getActivity().getLayoutInflater()` might be null.
134         assert getActivity() != null;
135
136         // Set the view.  The parent view is null because it will be assigned by the alert dialog.
137         dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.edit_bookmark_dialog, null));
138
139         // Set the cancel button listener.
140         dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
141             // Do nothing.  The alert dialog will close automatically.
142         });
143
144         // Set the save button listener.
145         dialogBuilder.setPositiveButton(R.string.save, (DialogInterface dialog, int which) -> {
146             // Return the dialog fragment to the parent activity.
147             editBookmarkListener.onSaveBookmark(this, selectedBookmarkDatabaseId, favoriteIconBitmap);
148         });
149
150         // Create an alert dialog from the builder.
151         final AlertDialog alertDialog = dialogBuilder.create();
152
153         // remove the incorrect lint warning below that `getWindow().addFlags()` might be null.
154         assert alertDialog.getWindow() != null;
155
156         // Get a handle for the shared preferences.
157         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
158
159         // Get the screenshot preference.
160         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
161
162         // Disable screenshots if not allowed.
163         if (!allowScreenshots) {
164             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
165         }
166
167         // The alert dialog must be shown before items in the layout can be modified.
168         alertDialog.show();
169
170         // Get handles for the layout items.
171         RadioGroup iconRadioGroup = alertDialog.findViewById(R.id.edit_bookmark_icon_radiogroup);
172         ImageView currentIconImageView = alertDialog.findViewById(R.id.edit_bookmark_current_icon);
173         ImageView newFavoriteIconImageView = alertDialog.findViewById(R.id.edit_bookmark_webpage_favorite_icon);
174         EditText nameEditText = alertDialog.findViewById(R.id.edit_bookmark_name_edittext);
175         EditText urlEditText = alertDialog.findViewById(R.id.edit_bookmark_url_edittext);
176         Button editButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
177
178         // Remove the incorrect lint warnings below that the views might be null.
179         assert iconRadioGroup != null;
180         assert currentIconImageView != null;
181         assert newFavoriteIconImageView != null;
182         assert nameEditText != null;
183         assert urlEditText != null;
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 the current icon bitmap.
192         currentIconImageView.setImageBitmap(currentIconBitmap);
193
194         // Set the new favorite icon bitmap.
195         newFavoriteIconImageView.setImageBitmap(favoriteIconBitmap);
196
197         // Store the current bookmark name and URL.
198         String currentName = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
199         String currentUrl = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL));
200
201         // Populate the edit texts.
202         nameEditText.setText(currentName);
203         urlEditText.setText(currentUrl);
204
205         // Initially disable the edit button.
206         editButton.setEnabled(false);
207
208         // Update the edit button if the icon selection changes.
209         iconRadioGroup.setOnCheckedChangeListener((RadioGroup group, int checkedId) -> {
210             // Update the edit button.
211             updateEditButton(alertDialog, currentName, currentUrl);
212         });
213
214         // Update the edit button if the bookmark name changes.
215         nameEditText.addTextChangedListener(new TextWatcher() {
216             @Override
217             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
218                 // Do nothing.
219             }
220
221             @Override
222             public void onTextChanged(CharSequence s, int start, int before, int count) {
223                 // Do nothing.
224             }
225
226             @Override
227             public void afterTextChanged(Editable s) {
228                 // Update the edit button.
229                 updateEditButton(alertDialog, currentName, currentUrl);
230             }
231         });
232
233         // Update the edit button if the URL changes.
234         urlEditText.addTextChangedListener(new TextWatcher() {
235             @Override
236             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
237                 // Do nothing.
238             }
239
240             @Override
241             public void onTextChanged(CharSequence s, int start, int before, int count) {
242                 // Do nothing.
243             }
244
245             @Override
246             public void afterTextChanged(Editable s) {
247                 // Update the edit button.
248                 updateEditButton(alertDialog, currentName, currentUrl);
249             }
250         });
251
252         // Allow the enter key on the keyboard to save the bookmark from the bookmark name edit text.
253         nameEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
254             // Save the bookmark if the event is a key-down on the "enter" button.
255             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) {  // The enter key was pressed and the edit button is enabled.
256                 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
257                 editBookmarkListener.onSaveBookmark(this, selectedBookmarkDatabaseId, favoriteIconBitmap);
258
259                 // Manually dismiss `alertDialog`.
260                 alertDialog.dismiss();
261
262                 // Consume the event.
263                 return true;
264             } else {  // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
265                 return false;
266             }
267         });
268
269         // Allow the enter key on the keyboard to save the bookmark from the URL edit text.
270         urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
271             // Save the bookmark if the event is a key-down on the "enter" button.
272             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) {  // The enter key was pressed and the edit button is enabled.
273                 // Trigger the `Listener` and return the DialogFragment to the parent activity.
274                 editBookmarkListener.onSaveBookmark(this, selectedBookmarkDatabaseId, favoriteIconBitmap);
275
276                 // Manually dismiss the alert dialog.
277                 alertDialog.dismiss();
278
279                 // Consume the event.
280                 return true;
281             } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
282                 return false;
283             }
284         });
285
286         // Return the alert dialog.
287         return alertDialog;
288     }
289
290     private void updateEditButton(AlertDialog alertdialog, String currentName, String currentUrl) {
291         // Get handles for the views.
292         EditText nameEditText = alertdialog.findViewById(R.id.edit_bookmark_name_edittext);
293         EditText urlEditText = alertdialog.findViewById(R.id.edit_bookmark_url_edittext);
294         RadioButton newIconRadioButton = alertdialog.findViewById(R.id.edit_bookmark_webpage_favorite_icon_radiobutton);
295         Button editButton = alertdialog.getButton(AlertDialog.BUTTON_POSITIVE);
296
297         // Remove the incorrect lint warnings below that the views might be null.
298         assert nameEditText != null;
299         assert urlEditText != null;
300         assert newIconRadioButton != null;
301
302         // Get the text from the edit texts.
303         String newName = nameEditText.getText().toString();
304         String newUrl = urlEditText.getText().toString();
305
306         // Has the favorite icon changed?
307         boolean iconChanged = newIconRadioButton.isChecked();
308
309         // Has the name changed?
310         boolean nameChanged = !newName.equals(currentName);
311
312         // Has the URL changed?
313         boolean urlChanged = !newUrl.equals(currentUrl);
314
315         // Update the enabled status of the edit button.
316         editButton.setEnabled(iconChanged || nameChanged || urlChanged);
317     }
318 }