2 * Copyright © 2016-2019 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.text.Editable;
32 import android.text.TextWatcher;
33 import android.view.KeyEvent;
34 import android.view.View;
35 import android.view.WindowManager;
36 import android.widget.Button;
37 import android.widget.EditText;
38 import android.widget.ImageView;
39 import android.widget.RadioButton;
40 import android.widget.RadioGroup;
42 import androidx.annotation.NonNull;
43 import androidx.fragment.app.DialogFragment; // The AndroidX dialog fragment must be used or an error is produced on API <=22.
45 import com.stoutner.privacybrowser.R;
46 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
47 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
49 import java.io.ByteArrayOutputStream;
51 public class EditBookmarkDialog extends DialogFragment {
52 // Define the edit bookmark listener.
53 private EditBookmarkListener editBookmarkListener;
55 // The public interface is used to send information back to the parent activity.
56 public interface EditBookmarkListener {
57 void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap);
60 public void onAttach(Context context) {
61 // Run the default commands.
62 super.onAttach(context);
64 // Get a handle for `EditBookmarkListener` from the launching context.
65 editBookmarkListener = (EditBookmarkListener) context;
68 // Store the database ID in the arguments bundle.
69 public static EditBookmarkDialog bookmarkDatabaseId(int databaseId, Bitmap favoriteIconBitmap) {
70 // Create a favorite icon byte array output stream.
71 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
73 // Convert the favorite icon to a PNG and place it in the byte array output stream. `0` is for lossless compression (the only option for a PNG).
74 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
76 // Convert the byte array output stream to a byte array.
77 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
79 // Create an arguments bundle.
80 Bundle argumentsBundle = new Bundle();
82 // Store the variables in the bundle.
83 argumentsBundle.putInt("database_id", databaseId);
84 argumentsBundle.putByteArray("favorite_icon_byte_array", favoriteIconByteArray);
86 // Create a new instance of the dialog.
87 EditBookmarkDialog editBookmarkDialog = new EditBookmarkDialog();
89 // Add the arguments bundle to the dialog.
90 editBookmarkDialog.setArguments(argumentsBundle);
92 // Return the new dialog.
93 return editBookmarkDialog;
96 // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
97 @SuppressLint("InflateParams")
100 public Dialog onCreateDialog(Bundle savedInstanceState) {
101 // Get the arguments.
102 Bundle arguments = getArguments();
104 // Remove the incorrect lint warning below that the arguments might be null.
105 assert arguments != null;
107 // Store the bookmark database ID in the class variable.
108 int selectedBookmarkDatabaseId = arguments.getInt("database_id");
110 // Get the favorite icon byte array.
111 byte[] favoriteIconByteArray = arguments.getByteArray("favorite_icon_byte_array");
113 // Remove the incorrect lint warning below that the favorite icon byte array might be null.
114 assert favoriteIconByteArray != null;
116 // Convert the favorite icon byte array to a bitmap.
117 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
119 // Initialize the database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
120 BookmarksDatabaseHelper bookmarksDatabaseHelper = new BookmarksDatabaseHelper(getContext(), null, null, 0);
122 // Get a `Cursor` with the selected bookmark and move it to the first position.
123 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(selectedBookmarkDatabaseId);
124 bookmarkCursor.moveToFirst();
126 // Use an alert dialog builder to create the alert dialog.
127 AlertDialog.Builder dialogBuilder;
129 // Set the style according to the theme.
130 if (MainWebViewActivity.darkTheme) {
131 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
133 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
137 dialogBuilder.setTitle(R.string.edit_bookmark);
139 // Remove the incorrect lint warning that `getActivity().getLayoutInflater()` might be null.
140 assert getActivity() != null;
142 // Set the view. The parent view is null because it will be assigned by the alert dialog.
143 dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.edit_bookmark_dialog, null));
145 // Set the cancel button listener.
146 dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
147 // Do nothing. The alert dialog will close automatically.
150 // Set the save button listener.
151 dialogBuilder.setPositiveButton(R.string.save, (DialogInterface dialog, int which) -> {
152 // Return the dialog fragment to the parent activity.
153 editBookmarkListener.onSaveBookmark(this, selectedBookmarkDatabaseId, favoriteIconBitmap);
156 // Create an alert dialog from the builder.
157 final AlertDialog alertDialog = dialogBuilder.create();
159 // remove the incorrect lint warning below that `getWindow().addFlags()` might be null.
160 assert alertDialog.getWindow() != null;
162 // Disable screenshots if not allowed.
163 if (!MainWebViewActivity.allowScreenshots) {
164 alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
167 // The alert dialog must be shown before items in the layout can be modified.
170 // Get handles for the layout items.
171 RadioGroup iconRadioGroup = alertDialog.findViewById(R.id.edit_bookmark_icon_radiogroup);
172 ImageView currentIconImageView = alertDialog.findViewById(R.id.edit_bookmark_current_icon);
173 ImageView newFavoriteIconImageView = alertDialog.findViewById(R.id.edit_bookmark_webpage_favorite_icon);
174 EditText nameEditText = alertDialog.findViewById(R.id.edit_bookmark_name_edittext);
175 EditText urlEditText = alertDialog.findViewById(R.id.edit_bookmark_url_edittext);
176 Button editButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
178 // Get the current favorite icon byte array from the cursor.
179 byte[] currentIconByteArray = bookmarkCursor.getBlob(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
181 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
182 Bitmap currentIconBitmap = BitmapFactory.decodeByteArray(currentIconByteArray, 0, currentIconByteArray.length);
184 // Display the current icon bitmap.
185 currentIconImageView.setImageBitmap(currentIconBitmap);
187 // Set the new favorite icon bitmap.
188 newFavoriteIconImageView.setImageBitmap(favoriteIconBitmap);
190 // Store the current bookmark name and URL.
191 String currentName = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
192 String currentUrl = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL));
194 // Populate the edit texts.
195 nameEditText.setText(currentName);
196 urlEditText.setText(currentUrl);
198 // Initially disable the edit button.
199 editButton.setEnabled(false);
201 // Update the edit button if the icon selection changes.
202 iconRadioGroup.setOnCheckedChangeListener((RadioGroup group, int checkedId) -> {
203 // Update the edit button.
204 updateEditButton(alertDialog, currentName, currentUrl);
207 // Update the edit button if the bookmark name changes.
208 nameEditText.addTextChangedListener(new TextWatcher() {
210 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
215 public void onTextChanged(CharSequence s, int start, int before, int count) {
220 public void afterTextChanged(Editable s) {
221 // Update the edit button.
222 updateEditButton(alertDialog, currentName, currentUrl);
226 // Update the edit button if the URL changes.
227 urlEditText.addTextChangedListener(new TextWatcher() {
229 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
234 public void onTextChanged(CharSequence s, int start, int before, int count) {
239 public void afterTextChanged(Editable s) {
240 // Update the edit button.
241 updateEditButton(alertDialog, currentName, currentUrl);
245 // Allow the enter key on the keyboard to save the bookmark from the bookmark name edit text.
246 nameEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
247 // Save the bookmark if the event is a key-down on the "enter" button.
248 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) { // The enter key was pressed and the edit button is enabled.
249 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
250 editBookmarkListener.onSaveBookmark(this, selectedBookmarkDatabaseId, favoriteIconBitmap);
252 // Manually dismiss `alertDialog`.
253 alertDialog.dismiss();
255 // Consume the event.
257 } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
262 // Allow the enter key on the keyboard to save the bookmark from the URL edit text.
263 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
264 // Save the bookmark if the event is a key-down on the "enter" button.
265 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) { // The enter key was pressed and the edit button is enabled.
266 // Trigger the `Listener` and return the DialogFragment to the parent activity.
267 editBookmarkListener.onSaveBookmark(this, selectedBookmarkDatabaseId, favoriteIconBitmap);
269 // Manually dismiss the alert dialog.
270 alertDialog.dismiss();
272 // Consume the event.
274 } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
279 // Return the alert dialog.
283 private void updateEditButton(AlertDialog alertdialog, String currentName, String currentUrl) {
284 // Get handles for the views.
285 EditText nameEditText = alertdialog.findViewById(R.id.edit_bookmark_name_edittext);
286 EditText urlEditText = alertdialog.findViewById(R.id.edit_bookmark_url_edittext);
287 RadioButton newIconRadioButton = alertdialog.findViewById(R.id.edit_bookmark_webpage_favorite_icon_radiobutton);
288 Button editButton = alertdialog.getButton(AlertDialog.BUTTON_POSITIVE);
290 // Get the text from the edit texts.
291 String newName = nameEditText.getText().toString();
292 String newUrl = urlEditText.getText().toString();
294 // Has the favorite icon changed?
295 boolean iconChanged = newIconRadioButton.isChecked();
297 // Has the name changed?
298 boolean nameChanged = !newName.equals(currentName);
300 // Has the URL changed?
301 boolean urlChanged = !newUrl.equals(currentUrl);
303 // Update the enabled status of the edit button.
304 editButton.setEnabled(iconChanged || nameChanged || urlChanged);