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.database.MatrixCursor;
29 import android.database.MergeCursor;
30 import android.graphics.Bitmap;
31 import android.graphics.BitmapFactory;
32 import android.os.Bundle;
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.AdapterView;
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 import android.widget.ResourceCursorAdapter;
45 import android.widget.Spinner;
46 import android.widget.TextView;
48 import com.stoutner.privacybrowser.R;
49 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
50 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
52 import java.io.ByteArrayOutputStream;
54 import androidx.annotation.NonNull;
55 import androidx.core.content.ContextCompat;
56 import androidx.fragment.app.DialogFragment; // The AndroidX dialog fragment must be used or an error is produced on API <=22.
58 public class EditBookmarkDatabaseViewDialog extends DialogFragment {
59 // Define the home folder database ID constant.
60 public static final int HOME_FOLDER_DATABASE_ID = -1;
62 // Define the edit bookmark database view listener.
63 private EditBookmarkDatabaseViewListener editBookmarkDatabaseViewListener;
66 // The public interface is used to send information back to the parent activity.
67 public interface EditBookmarkDatabaseViewListener {
68 void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap);
72 public void onAttach(Context context) {
73 // Run the default commands.
74 super.onAttach(context);
76 // Get a handle for edit bookmark database view listener from the launching context.
77 editBookmarkDatabaseViewListener = (EditBookmarkDatabaseViewListener) context;
81 public static EditBookmarkDatabaseViewDialog bookmarkDatabaseId(int databaseId, Bitmap favoriteIconBitmap) {
82 // Create a favorite icon byte array output stream.
83 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
85 // 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).
86 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
88 // Convert the byte array output stream to a byte array.
89 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
91 // Create an arguments bundle.
92 Bundle argumentsBundle = new Bundle();
94 // Store the variables in the bundle.
95 argumentsBundle.putInt("database_id", databaseId);
96 argumentsBundle.putByteArray("favorite_icon_byte_array", favoriteIconByteArray);
98 // Create a new instance of the dialog.
99 EditBookmarkDatabaseViewDialog editBookmarkDatabaseViewDialog = new EditBookmarkDatabaseViewDialog();
101 // Add the arguments bundle to the dialog.
102 editBookmarkDatabaseViewDialog.setArguments(argumentsBundle);
104 // Return the new dialog.
105 return editBookmarkDatabaseViewDialog;
108 // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
109 @SuppressLint("InflateParams")
112 public Dialog onCreateDialog(Bundle savedInstanceState) {
113 // Get the arguments.
114 Bundle arguments = getArguments();
116 // Remove the incorrect lint warning below that the arguments might be null.
117 assert arguments != null;
119 // Get the bookmark database ID from the bundle.
120 int bookmarkDatabaseId = getArguments().getInt("database_id");
122 // Get the favorite icon byte array.
123 byte[] favoriteIconByteArray = arguments.getByteArray("favorite_icon_byte_array");
125 // Remove the incorrect lint warning below that the favorite icon byte array might be null.
126 assert favoriteIconByteArray != null;
128 // Convert the favorite icon byte array to a bitmap.
129 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
131 // Initialize the database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
132 BookmarksDatabaseHelper bookmarksDatabaseHelper = new BookmarksDatabaseHelper(getContext(), null, null, 0);
134 // Get a cursor with the selected bookmark and move it to the first position.
135 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(bookmarkDatabaseId);
136 bookmarkCursor.moveToFirst();
138 // Use an alert dialog builder to create the alert dialog.
139 AlertDialog.Builder dialogBuilder;
141 // Set the style according to the theme.
142 if (MainWebViewActivity.darkTheme) {
143 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
145 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
149 dialogBuilder.setTitle(R.string.edit_bookmark);
151 // Remove the incorrect lint warning below that `getLayoutInflater()` might be null.
152 assert getActivity() != null;
154 // Set the view. The parent view is `null` because it will be assigned by `AlertDialog`.
155 dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.edit_bookmark_databaseview_dialog, null));
157 // Set the listener for the negative button.
158 dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
159 // Do nothing. The `AlertDialog` will close automatically.
162 // Set the listener for the positive button.
163 dialogBuilder.setPositiveButton(R.string.save, (DialogInterface dialog, int which) -> {
164 // Return the `DialogFragment` to the parent activity on save.
165 editBookmarkDatabaseViewListener.onSaveBookmark(this, bookmarkDatabaseId, favoriteIconBitmap);
168 // Create an alert dialog from the alert dialog builder`.
169 final AlertDialog alertDialog = dialogBuilder.create();
171 // Remove the warning below that `getWindow()` might be null.
172 assert alertDialog.getWindow() != null;
174 // Disable screenshots if not allowed.
175 if (!MainWebViewActivity.allowScreenshots) {
176 alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
179 // The alert dialog must be shown before items in the layout can be modified.
182 // Get handles for the layout items.
183 TextView databaseIdTextView = alertDialog.findViewById(R.id.edit_bookmark_database_id_textview);
184 RadioGroup iconRadioGroup = alertDialog.findViewById(R.id.edit_bookmark_icon_radiogroup);
185 ImageView currentIconImageView = alertDialog.findViewById(R.id.edit_bookmark_current_icon);
186 ImageView newFavoriteIconImageView = alertDialog.findViewById(R.id.edit_bookmark_webpage_favorite_icon);
187 RadioButton newIconRadioButton = alertDialog.findViewById(R.id.edit_bookmark_webpage_favorite_icon_radiobutton);
188 EditText nameEditText = alertDialog.findViewById(R.id.edit_bookmark_name_edittext);
189 EditText urlEditText = alertDialog.findViewById(R.id.edit_bookmark_url_edittext);
190 Spinner folderSpinner = alertDialog.findViewById(R.id.edit_bookmark_folder_spinner);
191 EditText displayOrderEditText = alertDialog.findViewById(R.id.edit_bookmark_display_order_edittext);
192 Button editButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
194 // Store the current bookmark values.
195 String currentBookmarkName = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
196 String currentUrl = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL));
197 int currentDisplayOrder = bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER));
199 // Set the database ID.
200 databaseIdTextView.setText(String.valueOf(bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper._ID))));
202 // Get the current favorite icon byte array from the `Cursor`.
203 byte[] currentIconByteArray = bookmarkCursor.getBlob(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
205 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
206 Bitmap currentIconBitmap = BitmapFactory.decodeByteArray(currentIconByteArray, 0, currentIconByteArray.length);
208 // Display `currentIconBitmap` in `edit_bookmark_current_icon`.
209 currentIconImageView.setImageBitmap(currentIconBitmap);
211 // Set the new favorite icon bitmap.
212 newFavoriteIconImageView.setImageBitmap(favoriteIconBitmap);
214 // Populate the bookmark name and URL `EditTexts`.
215 nameEditText.setText(currentBookmarkName);
216 urlEditText.setText(currentUrl);
218 // Setup a matrix cursor for "Home Folder".
219 String[] matrixCursorColumnNames = {BookmarksDatabaseHelper._ID, BookmarksDatabaseHelper.BOOKMARK_NAME};
220 MatrixCursor matrixCursor = new MatrixCursor(matrixCursorColumnNames);
221 matrixCursor.addRow(new Object[]{HOME_FOLDER_DATABASE_ID, getString(R.string.home_folder)});
223 // Get a cursor with the list of all the folders.
224 Cursor foldersCursor = bookmarksDatabaseHelper.getAllFolders();
226 // Combine `matrixCursor` and `foldersCursor`.
227 MergeCursor foldersMergeCursor = new MergeCursor(new Cursor[]{matrixCursor, foldersCursor});
229 // Remove the incorrect lint warning below that `getContext()` might be null.
230 assert getContext() != null;
232 // Create a resource cursor adapter for the spinner.
233 ResourceCursorAdapter foldersCursorAdapter = new ResourceCursorAdapter(getContext(), R.layout.databaseview_spinner_item, foldersMergeCursor, 0) {
235 public void bindView(View view, Context context, Cursor cursor) {
236 // Get handles for the spinner views.
237 ImageView spinnerItemImageView = view.findViewById(R.id.spinner_item_imageview);
238 TextView spinnerItemTextView = view.findViewById(R.id.spinner_item_textview);
240 // Set the folder icon according to the type.
241 if (foldersMergeCursor.getPosition() == 0) { // Set the `Home Folder` icon.
242 // Set the gray folder image. `ContextCompat` must be used until the minimum API >= 21.
243 spinnerItemImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.folder_gray));
244 } else { // Set a user folder icon.
245 // Get the folder icon byte array.
246 byte[] folderIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
248 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
249 Bitmap folderIconBitmap = BitmapFactory.decodeByteArray(folderIconByteArray, 0, folderIconByteArray.length);
251 // Set the folder icon.
252 spinnerItemImageView.setImageBitmap(folderIconBitmap);
255 // Set the text view to display the folder name.
256 spinnerItemTextView.setText(cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME)));
260 // Set the `ResourceCursorAdapter` drop drown view resource.
261 foldersCursorAdapter.setDropDownViewResource(R.layout.databaseview_spinner_dropdown_items);
263 // Set the adapter for the folder `Spinner`.
264 folderSpinner.setAdapter(foldersCursorAdapter);
266 // Get the parent folder name.
267 String parentFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.PARENT_FOLDER));
269 // Select the current folder in the `Spinner` if the bookmark isn't in the "Home Folder".
270 if (!parentFolder.equals("")) {
271 // Get the database ID of the parent folder.
272 int folderDatabaseId = bookmarksDatabaseHelper.getFolderDatabaseId(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.PARENT_FOLDER)));
274 // Initialize `parentFolderPosition` and the iteration variable.
275 int parentFolderPosition = 0;
278 // Find the parent folder position in folders `ResourceCursorAdapter`.
280 if (foldersCursorAdapter.getItemId(i) == folderDatabaseId) {
281 // Store the current position for the parent folder.
282 parentFolderPosition = i;
284 // Try the next entry.
287 // Stop when the parent folder position is found or all the items in the `ResourceCursorAdapter` have been checked.
288 } while ((parentFolderPosition == 0) && (i < foldersCursorAdapter.getCount()));
290 // Select the parent folder in the `Spinner`.
291 folderSpinner.setSelection(parentFolderPosition);
294 // Store the current folder database ID.
295 int currentFolderDatabaseId = (int) folderSpinner.getSelectedItemId();
297 // Populate the display order `EditText`.
298 displayOrderEditText.setText(String.valueOf(bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER))));
300 // Initially disable the edit button.
301 editButton.setEnabled(false);
303 // Update the edit button if the icon selection changes.
304 iconRadioGroup.setOnCheckedChangeListener((group, checkedId) -> {
305 // Update the edit button.
306 updateEditButton(nameEditText, urlEditText, displayOrderEditText, folderSpinner, newIconRadioButton, editButton, currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder);
309 // Update the edit button if the bookmark name changes.
310 nameEditText.addTextChangedListener(new TextWatcher() {
312 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
317 public void onTextChanged(CharSequence s, int start, int before, int count) {
322 public void afterTextChanged(Editable s) {
323 // Update the edit button.
324 updateEditButton(nameEditText, urlEditText, displayOrderEditText, folderSpinner, newIconRadioButton, editButton, currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder);
328 // Update the edit button if the URL changes.
329 urlEditText.addTextChangedListener(new TextWatcher() {
331 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
336 public void onTextChanged(CharSequence s, int start, int before, int count) {
341 public void afterTextChanged(Editable s) {
342 // Update the edit button.
343 updateEditButton(nameEditText, urlEditText, displayOrderEditText, folderSpinner, newIconRadioButton, editButton, currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder);
347 // Update the edit button if the folder changes.
348 folderSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
350 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
351 // Update the edit button.
352 updateEditButton(nameEditText, urlEditText, displayOrderEditText, folderSpinner, newIconRadioButton, editButton, currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder);
356 public void onNothingSelected(AdapterView<?> parent) {
361 // Update the edit button if the display order changes.
362 displayOrderEditText.addTextChangedListener(new TextWatcher() {
364 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
369 public void onTextChanged(CharSequence s, int start, int before, int count) {
374 public void afterTextChanged(Editable s) {
375 // Update the edit button.
376 updateEditButton(nameEditText, urlEditText, displayOrderEditText, folderSpinner, newIconRadioButton, editButton, currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder);
380 // Allow the `enter` key on the keyboard to save the bookmark from the bookmark name `EditText`.
381 nameEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
382 // Save the bookmark if the event is a key-down on the "enter" button.
383 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) { // The enter key was pressed and the edit button is enabled.
384 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
385 editBookmarkDatabaseViewListener.onSaveBookmark(EditBookmarkDatabaseViewDialog.this, bookmarkDatabaseId, favoriteIconBitmap);
387 // Manually dismiss `alertDialog`.
388 alertDialog.dismiss();
390 // Consume the event.
392 } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
397 // Allow the "enter" key on the keyboard to save the bookmark from the URL `EditText`.
398 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
399 // Save the bookmark if the event is a key-down on the "enter" button.
400 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) { // The enter key was pressed and the edit button is enabled.
401 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
402 editBookmarkDatabaseViewListener.onSaveBookmark(EditBookmarkDatabaseViewDialog.this, bookmarkDatabaseId, favoriteIconBitmap);
404 // Manually dismiss the `AlertDialog`.
405 alertDialog.dismiss();
407 // Consume the event.
409 } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
414 // Allow the "enter" key on the keyboard to save the bookmark from the display order `EditText`.
415 displayOrderEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
416 // Save the bookmark if the event is a key-down on the "enter" button.
417 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) { // The enter key was pressed and the edit button is enabled.
418 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
419 editBookmarkDatabaseViewListener.onSaveBookmark(EditBookmarkDatabaseViewDialog.this, bookmarkDatabaseId, favoriteIconBitmap);
421 // Manually dismiss the `AlertDialog`.
422 alertDialog.dismiss();
424 // Consume the event.
426 } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
431 // `onCreateDialog` requires the return of an `AlertDialog`.
435 private void updateEditButton(EditText nameEditText, EditText urlEditText, EditText displayOrderEditText, Spinner folderSpinner, RadioButton newIconRadioButton, Button editButton,
436 String currentBookmarkName, String currentUrl, int currentFolderDatabaseId, int currentDisplayOrder) {
437 // Get the values from the dialog.
438 String newName = nameEditText.getText().toString();
439 String newUrl = urlEditText.getText().toString();
440 int newFolderDatabaseId = (int) folderSpinner.getSelectedItemId();
441 String newDisplayOrder = displayOrderEditText.getText().toString();
443 // Has the favorite icon changed?
444 boolean iconChanged = newIconRadioButton.isChecked();
446 // Has the name changed?
447 boolean nameChanged = !newName.equals(currentBookmarkName);
449 // Has the URL changed?
450 boolean urlChanged = !newUrl.equals(currentUrl);
452 // Has the folder changed?
453 boolean folderChanged = newFolderDatabaseId != currentFolderDatabaseId;
455 // Has the display order changed?
456 boolean displayOrderChanged = !newDisplayOrder.equals(String.valueOf(currentDisplayOrder));
458 // Is the display order empty?
459 boolean displayOrderNotEmpty = !newDisplayOrder.isEmpty();
461 // Update the enabled status of the edit button.
462 editButton.setEnabled((iconChanged || nameChanged || urlChanged || folderChanged || displayOrderChanged) && displayOrderNotEmpty);