]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/EditBookmarkDialog.java
Add swipe to refresh to domain and on-the-fly settings. https://redmine.stoutner...
[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.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         // Store the bookmark database ID in the class variable.
99         selectedBookmarkDatabaseId = getArguments().getInt("Database ID");
100     }
101
102     // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
103     @SuppressLint("InflateParams")
104     @Override
105     @NonNull
106     public Dialog onCreateDialog(Bundle savedInstanceState) {
107         // 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`.
108         BookmarksDatabaseHelper bookmarksDatabaseHelper = new BookmarksDatabaseHelper(getContext(), null, null, 0);
109
110         // Get a `Cursor` with the selected bookmark and move it to the first position.
111         Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(selectedBookmarkDatabaseId);
112         bookmarkCursor.moveToFirst();
113
114         // Use `AlertDialog.Builder` to create the `AlertDialog`.
115         AlertDialog.Builder dialogBuilder;
116
117         // Set the style according to the theme.
118         if (MainWebViewActivity.darkTheme) {
119             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
120         } else {
121             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
122         }
123
124         // Set the title.
125         dialogBuilder.setTitle(R.string.edit_bookmark);
126
127         // Set the view.  The parent view is `null` because it will be assigned by `AlertDialog`.
128         dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.edit_bookmark_dialog, null));
129
130         // Set an `onClick()` listener for the negative button.
131         dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
132             // Do nothing.  The `AlertDialog` will close automatically.
133         });
134
135         // Set the `onClick()` listener fo the positive button.
136         dialogBuilder.setPositiveButton(R.string.save, (DialogInterface dialog, int which) -> {
137             // Return the `DialogFragment` to the parent activity on save.
138             editBookmarkListener.onSaveBookmark(EditBookmarkDialog.this, selectedBookmarkDatabaseId);
139         });
140
141         // Create an `AlertDialog` from the `AlertDialog.Builder`.
142         final AlertDialog alertDialog = dialogBuilder.create();
143
144         // Remove the warning below that `setSoftInputMode` might produce `java.lang.NullPointerException`.
145         assert alertDialog.getWindow() != null;
146
147         // Show the keyboard when `alertDialog` is displayed on the screen.
148         alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
149
150         // The `AlertDialog` must be shown before items in the layout can be modified.
151         alertDialog.show();
152
153         // Get handles for the layout items.
154         RadioGroup iconRadioGroup = alertDialog.findViewById(R.id.edit_bookmark_icon_radiogroup);
155         ImageView currentIconImageView = alertDialog.findViewById(R.id.edit_bookmark_current_icon);
156         ImageView newFavoriteIconImageView = alertDialog.findViewById(R.id.edit_bookmark_webpage_favorite_icon);
157         newIconRadioButton = alertDialog.findViewById(R.id.edit_bookmark_webpage_favorite_icon_radiobutton);
158         nameEditText = alertDialog.findViewById(R.id.edit_bookmark_name_edittext);
159         urlEditText = alertDialog.findViewById(R.id.edit_bookmark_url_edittext);
160         editButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
161
162         // Get the current favorite icon byte array from the `Cursor`.
163         byte[] currentIconByteArray = bookmarkCursor.getBlob(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
164
165         // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
166         Bitmap currentIconBitmap = BitmapFactory.decodeByteArray(currentIconByteArray, 0, currentIconByteArray.length);
167
168         // Display `currentIconBitmap` in `edit_bookmark_current_icon`.
169         currentIconImageView.setImageBitmap(currentIconBitmap);
170
171         // Get a `Bitmap` of the favorite icon from `MainWebViewActivity` and display it in `edit_bookmark_web_page_favorite_icon`.
172         newFavoriteIconImageView.setImageBitmap(MainWebViewActivity.favoriteIconBitmap);
173
174         // Store the current bookmark name and URL.
175         currentName = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
176         currentUrl = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL));
177
178         // Populate the `EditTexts`.
179         nameEditText.setText(currentName);
180         urlEditText.setText(currentUrl);
181
182         // Initially disable the edit button.
183         editButton.setEnabled(false);
184
185         // Update the edit button if the icon selection changes.
186         iconRadioGroup.setOnCheckedChangeListener((RadioGroup group, int checkedId) -> {
187             // Update the edit button.
188             updateEditButton();
189         });
190
191         // Update the edit button if the bookmark name changes.
192         nameEditText.addTextChangedListener(new TextWatcher() {
193             @Override
194             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
195                 // Do nothing.
196             }
197
198             @Override
199             public void onTextChanged(CharSequence s, int start, int before, int count) {
200                 // Do nothing.
201             }
202
203             @Override
204             public void afterTextChanged(Editable s) {
205                 // Update the edit button.
206                 updateEditButton();
207             }
208         });
209
210         // Update the edit button if the URL changes.
211         urlEditText.addTextChangedListener(new TextWatcher() {
212             @Override
213             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
214                 // Do nothing.
215             }
216
217             @Override
218             public void onTextChanged(CharSequence s, int start, int before, int count) {
219                 // Do nothing.
220             }
221
222             @Override
223             public void afterTextChanged(Editable s) {
224                 // Update the edit button.
225                 updateEditButton();
226             }
227         });
228
229         // Allow the `enter` key on the keyboard to save the bookmark from the bookmark name `EditText`.
230         nameEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
231             // Save the bookmark if the event is a key-down on the "enter" button.
232             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) {  // The enter key was pressed and the edit button is enabled.
233                 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
234                 editBookmarkListener.onSaveBookmark(EditBookmarkDialog.this, selectedBookmarkDatabaseId);
235
236                 // Manually dismiss `alertDialog`.
237                 alertDialog.dismiss();
238
239                 // Consume the event.
240                 return true;
241             } else {  // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
242                 return false;
243             }
244         });
245
246         // Allow the "enter" key on the keyboard to save the bookmark from the URL `EditText`.
247         urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
248             // Save the bookmark if the event is a key-down on the "enter" button.
249             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) {  // The enter key was pressed and the edit button is enabled.
250                 // Trigger the `Listener` and return the DialogFragment to the parent activity.
251                 editBookmarkListener.onSaveBookmark(EditBookmarkDialog.this, selectedBookmarkDatabaseId);
252
253                 // Manually dismiss the `AlertDialog`.
254                 alertDialog.dismiss();
255
256                 // Consume the event.
257                 return true;
258             } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
259                 return false;
260             }
261         });
262
263         // `onCreateDialog` requires the return of an `AlertDialog`.
264         return alertDialog;
265     }
266
267     private void updateEditButton() {
268         // Get the text from the `EditTexts`.
269         String newName = nameEditText.getText().toString();
270         String newUrl = urlEditText.getText().toString();
271
272         // Has the favorite icon changed?
273         boolean iconChanged = newIconRadioButton.isChecked();
274
275         // Has the name changed?
276         boolean nameChanged = !newName.equals(currentName);
277
278         // Has the URL changed?
279         boolean urlChanged = !newUrl.equals(currentUrl);
280
281         // Update the enabled status of the edit button.
282         editButton.setEnabled(iconChanged || nameChanged || urlChanged);
283     }
284 }