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