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