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.content.SharedPreferences;
28 import android.database.Cursor;
29 import android.graphics.Bitmap;
30 import android.graphics.BitmapFactory;
31 import android.os.Bundle;
32 import android.preference.PreferenceManager;
33 import android.text.Editable;
34 import android.text.TextWatcher;
35 import android.view.KeyEvent;
36 import android.view.View;
37 import android.view.WindowManager;
38 import android.widget.Button;
39 import android.widget.EditText;
40 import android.widget.ImageView;
41 import android.widget.RadioButton;
42 import android.widget.RadioGroup;
44 import androidx.annotation.NonNull;
45 import androidx.fragment.app.DialogFragment; // The AndroidX dialog fragment must be used or an error is produced on API <=22.
47 import com.stoutner.privacybrowser.R;
48 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
50 import java.io.ByteArrayOutputStream;
52 public class EditBookmarkDialog extends DialogFragment {
53 // Define the edit bookmark listener.
54 private EditBookmarkListener editBookmarkListener;
56 // The public interface is used to send information back to the parent activity.
57 public interface EditBookmarkListener {
58 void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap);
61 public void onAttach(@NonNull Context context) {
62 // Run the default commands.
63 super.onAttach(context);
65 // Get a handle for `EditBookmarkListener` from the launching context.
66 editBookmarkListener = (EditBookmarkListener) context;
69 // Store the database ID in the arguments bundle.
70 public static EditBookmarkDialog bookmarkDatabaseId(int databaseId, Bitmap favoriteIconBitmap) {
71 // Create a favorite icon byte array output stream.
72 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
74 // 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).
75 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
77 // Convert the byte array output stream to a byte array.
78 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
80 // Create an arguments bundle.
81 Bundle argumentsBundle = new Bundle();
83 // Store the variables in the bundle.
84 argumentsBundle.putInt("database_id", databaseId);
85 argumentsBundle.putByteArray("favorite_icon_byte_array", favoriteIconByteArray);
87 // Create a new instance of the dialog.
88 EditBookmarkDialog editBookmarkDialog = new EditBookmarkDialog();
90 // Add the arguments bundle to the dialog.
91 editBookmarkDialog.setArguments(argumentsBundle);
93 // Return the new dialog.
94 return editBookmarkDialog;
97 // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
98 @SuppressLint("InflateParams")
101 public Dialog onCreateDialog(Bundle savedInstanceState) {
102 // Get the arguments.
103 Bundle arguments = getArguments();
105 // Remove the incorrect lint warning below that the arguments might be null.
106 assert arguments != null;
108 // Store the bookmark database ID in the class variable.
109 int selectedBookmarkDatabaseId = arguments.getInt("database_id");
111 // Get the favorite icon byte array.
112 byte[] favoriteIconByteArray = arguments.getByteArray("favorite_icon_byte_array");
114 // Remove the incorrect lint warning below that the favorite icon byte array might be null.
115 assert favoriteIconByteArray != null;
117 // Convert the favorite icon byte array to a bitmap.
118 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
120 // Initialize the database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
121 BookmarksDatabaseHelper bookmarksDatabaseHelper = new BookmarksDatabaseHelper(getContext(), null, null, 0);
123 // Get a `Cursor` with the selected bookmark and move it to the first position.
124 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(selectedBookmarkDatabaseId);
125 bookmarkCursor.moveToFirst();
127 // Use an alert dialog builder to create the alert dialog.
128 AlertDialog.Builder dialogBuilder;
130 // Get a handle for the shared preferences.
131 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
133 // Get the screenshot and theme preferences.
134 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
135 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
137 // Set the style according to the theme.
139 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
141 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
145 dialogBuilder.setTitle(R.string.edit_bookmark);
147 // Remove the incorrect lint warning that `getActivity().getLayoutInflater()` might be null.
148 assert getActivity() != null;
150 // Set the view. The parent view is null because it will be assigned by the alert dialog.
151 dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.edit_bookmark_dialog, null));
153 // Set the cancel button listener.
154 dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
155 // Do nothing. The alert dialog will close automatically.
158 // Set the save button listener.
159 dialogBuilder.setPositiveButton(R.string.save, (DialogInterface dialog, int which) -> {
160 // Return the dialog fragment to the parent activity.
161 editBookmarkListener.onSaveBookmark(this, selectedBookmarkDatabaseId, favoriteIconBitmap);
164 // Create an alert dialog from the builder.
165 final AlertDialog alertDialog = dialogBuilder.create();
167 // remove the incorrect lint warning below that `getWindow().addFlags()` might be null.
168 assert alertDialog.getWindow() != null;
170 // Disable screenshots if not allowed.
171 if (!allowScreenshots) {
172 alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
175 // The alert dialog must be shown before items in the layout can be modified.
178 // Get handles for the layout items.
179 RadioGroup iconRadioGroup = alertDialog.findViewById(R.id.edit_bookmark_icon_radiogroup);
180 ImageView currentIconImageView = alertDialog.findViewById(R.id.edit_bookmark_current_icon);
181 ImageView newFavoriteIconImageView = alertDialog.findViewById(R.id.edit_bookmark_webpage_favorite_icon);
182 EditText nameEditText = alertDialog.findViewById(R.id.edit_bookmark_name_edittext);
183 EditText urlEditText = alertDialog.findViewById(R.id.edit_bookmark_url_edittext);
184 Button editButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
186 // Get the current favorite icon byte array from the cursor.
187 byte[] currentIconByteArray = bookmarkCursor.getBlob(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
189 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
190 Bitmap currentIconBitmap = BitmapFactory.decodeByteArray(currentIconByteArray, 0, currentIconByteArray.length);
192 // Display the current icon bitmap.
193 currentIconImageView.setImageBitmap(currentIconBitmap);
195 // Set the new favorite icon bitmap.
196 newFavoriteIconImageView.setImageBitmap(favoriteIconBitmap);
198 // Store the current bookmark name and URL.
199 String currentName = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
200 String currentUrl = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL));
202 // Populate the edit texts.
203 nameEditText.setText(currentName);
204 urlEditText.setText(currentUrl);
206 // Initially disable the edit button.
207 editButton.setEnabled(false);
209 // Update the edit button if the icon selection changes.
210 iconRadioGroup.setOnCheckedChangeListener((RadioGroup group, int checkedId) -> {
211 // Update the edit button.
212 updateEditButton(alertDialog, currentName, currentUrl);
215 // Update the edit button if the bookmark name changes.
216 nameEditText.addTextChangedListener(new TextWatcher() {
218 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
223 public void onTextChanged(CharSequence s, int start, int before, int count) {
228 public void afterTextChanged(Editable s) {
229 // Update the edit button.
230 updateEditButton(alertDialog, currentName, currentUrl);
234 // Update the edit button if the URL changes.
235 urlEditText.addTextChangedListener(new TextWatcher() {
237 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
242 public void onTextChanged(CharSequence s, int start, int before, int count) {
247 public void afterTextChanged(Editable s) {
248 // Update the edit button.
249 updateEditButton(alertDialog, currentName, currentUrl);
253 // Allow the enter key on the keyboard to save the bookmark from the bookmark name edit text.
254 nameEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
255 // Save the bookmark if the event is a key-down on the "enter" button.
256 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) { // The enter key was pressed and the edit button is enabled.
257 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
258 editBookmarkListener.onSaveBookmark(this, selectedBookmarkDatabaseId, favoriteIconBitmap);
260 // Manually dismiss `alertDialog`.
261 alertDialog.dismiss();
263 // Consume the event.
265 } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
270 // Allow the enter key on the keyboard to save the bookmark from the URL edit text.
271 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
272 // Save the bookmark if the event is a key-down on the "enter" button.
273 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) { // The enter key was pressed and the edit button is enabled.
274 // Trigger the `Listener` and return the DialogFragment to the parent activity.
275 editBookmarkListener.onSaveBookmark(this, selectedBookmarkDatabaseId, favoriteIconBitmap);
277 // Manually dismiss the alert dialog.
278 alertDialog.dismiss();
280 // Consume the event.
282 } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
287 // Return the alert dialog.
291 private void updateEditButton(AlertDialog alertdialog, String currentName, String currentUrl) {
292 // Get handles for the views.
293 EditText nameEditText = alertdialog.findViewById(R.id.edit_bookmark_name_edittext);
294 EditText urlEditText = alertdialog.findViewById(R.id.edit_bookmark_url_edittext);
295 RadioButton newIconRadioButton = alertdialog.findViewById(R.id.edit_bookmark_webpage_favorite_icon_radiobutton);
296 Button editButton = alertdialog.getButton(AlertDialog.BUTTON_POSITIVE);
298 // Get the text from the edit texts.
299 String newName = nameEditText.getText().toString();
300 String newUrl = urlEditText.getText().toString();
302 // Has the favorite icon changed?
303 boolean iconChanged = newIconRadioButton.isChecked();
305 // Has the name changed?
306 boolean nameChanged = !newName.equals(currentName);
308 // Has the URL changed?
309 boolean urlChanged = !newUrl.equals(currentUrl);
311 // Update the enabled status of the edit button.
312 editButton.setEnabled(iconChanged || nameChanged || urlChanged);