]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/EditBookmarkDialog.java
Add a requests activity. https://redmine.stoutner.com/issues/170
[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 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(AppCompatDialogFragment 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.getBookmarkCursor(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()` 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 listener for the negative button.
126         dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
127             // Do nothing.  The `AlertDialog` will close automatically.
128         });
129
130         // Set the listener fo the positive button.
131         dialogBuilder.setPositiveButton(R.string.save, (DialogInterface dialog, int which) -> {
132             // Return the `DialogFragment` to the parent activity on save.
133             editBookmarkListener.onSaveBookmark(EditBookmarkDialog.this, selectedBookmarkDatabaseId);
134         });
135
136         // Create an alert dialog from the alert dialog builder.
137         final AlertDialog alertDialog = dialogBuilder.create();
138
139         // Remove the warning below that `getWindow()` 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         // Show the keyboard when the alert dialog is displayed on the screen.
148         alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
149
150         // The alert dialog 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 }