2 * Copyright © 2016-2017 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
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.
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.
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/>.
20 package com.stoutner.privacybrowser.dialogs;
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;
45 import com.stoutner.privacybrowser.R;
46 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
47 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
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;
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);
65 public void onAttach(Context context) {
66 // Run the default commands.
67 super.onAttach(context);
69 // Get a handle for `EditBookmarkListener` from `context`.
71 editBookmarkListener = (EditBookmarkListener) context;
72 } catch(ClassCastException exception) {
73 throw new ClassCastException(context.toString() + " must implement EditBookmarkListener.");
77 // Store the database ID in the arguments bundle.
78 public static EditBookmarkDialog bookmarkDatabaseId(int databaseId) {
80 Bundle bundle = new Bundle();
82 // Store the bookmark database ID in the bundle.
83 bundle.putInt("Database ID", databaseId);
85 // Add the bundle to the dialog.
86 EditBookmarkDialog editBookmarkDialog = new EditBookmarkDialog();
87 editBookmarkDialog.setArguments(bundle);
89 // Return the new dialog.
90 return editBookmarkDialog;
94 public void onCreate(Bundle savedInstanceState) {
95 // Run the default commands.
96 super.onCreate(savedInstanceState);
98 // Store the bookmark database ID in the class variable.
99 selectedBookmarkDatabaseId = getArguments().getInt("Database ID");
102 // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
103 @SuppressLint("InflateParams")
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);
110 // Get a `Cursor` with the selected bookmark and move it to the first position.
111 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(selectedBookmarkDatabaseId);
112 bookmarkCursor.moveToFirst();
114 // Use `AlertDialog.Builder` to create the `AlertDialog`.
115 AlertDialog.Builder dialogBuilder;
117 // Set the style according to the theme.
118 if (MainWebViewActivity.darkTheme) {
119 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
121 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
125 dialogBuilder.setTitle(R.string.edit_bookmark);
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));
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.
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);
141 // Create an `AlertDialog` from the `AlertDialog.Builder`.
142 final AlertDialog alertDialog = dialogBuilder.create();
144 // Remove the warning below that `setSoftInputMode` might produce `java.lang.NullPointerException`.
145 assert alertDialog.getWindow() != null;
147 // Show the keyboard when `alertDialog` is displayed on the screen.
148 alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
150 // The `AlertDialog` must be shown before items in the layout can be modified.
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);
162 // Get the current favorite icon byte array from the `Cursor`.
163 byte[] currentIconByteArray = bookmarkCursor.getBlob(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
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);
168 // Display `currentIconBitmap` in `edit_bookmark_current_icon`.
169 currentIconImageView.setImageBitmap(currentIconBitmap);
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);
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));
178 // Populate the `EditTexts`.
179 nameEditText.setText(currentName);
180 urlEditText.setText(currentUrl);
182 // Initially disable the edit button.
183 editButton.setEnabled(false);
185 // Update the edit button if the icon selection changes.
186 iconRadioGroup.setOnCheckedChangeListener((RadioGroup group, int checkedId) -> {
187 // Update the edit button.
191 // Update the edit button if the bookmark name changes.
192 nameEditText.addTextChangedListener(new TextWatcher() {
194 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
199 public void onTextChanged(CharSequence s, int start, int before, int count) {
204 public void afterTextChanged(Editable s) {
205 // Update the edit button.
210 // Update the edit button if the URL changes.
211 urlEditText.addTextChangedListener(new TextWatcher() {
213 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
218 public void onTextChanged(CharSequence s, int start, int before, int count) {
223 public void afterTextChanged(Editable s) {
224 // Update the edit button.
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);
236 // Manually dismiss `alertDialog`.
237 alertDialog.dismiss();
239 // Consume the event.
241 } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
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);
253 // Manually dismiss the `AlertDialog`.
254 alertDialog.dismiss();
256 // Consume the event.
258 } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
263 // `onCreateDialog` requires the return of an `AlertDialog`.
267 private void updateEditButton() {
268 // Get the text from the `EditTexts`.
269 String newName = nameEditText.getText().toString();
270 String newUrl = urlEditText.getText().toString();
272 // Has the favorite icon changed?
273 boolean iconChanged = newIconRadioButton.isChecked();
275 // Has the name changed?
276 boolean nameChanged = !newName.equals(currentName);
278 // Has the URL changed?
279 boolean urlChanged = !newUrl.equals(currentUrl);
281 // Update the enabled status of the edit button.
282 editButton.setEnabled(iconChanged || nameChanged || urlChanged);