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.database.MatrixCursor;
30 import android.database.MergeCursor;
31 import android.graphics.Bitmap;
32 import android.graphics.BitmapFactory;
33 import android.os.Bundle;
34 import android.preference.PreferenceManager;
35 import android.text.Editable;
36 import android.text.TextWatcher;
37 import android.view.KeyEvent;
38 import android.view.View;
39 import android.view.WindowManager;
40 import android.widget.AdapterView;
41 import android.widget.Button;
42 import android.widget.EditText;
43 import android.widget.ImageView;
44 import android.widget.RadioButton;
45 import android.widget.RadioGroup;
46 import android.widget.ResourceCursorAdapter;
47 import android.widget.Spinner;
48 import android.widget.TextView;
50 import com.stoutner.privacybrowser.R;
51 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
53 import java.io.ByteArrayOutputStream;
55 import androidx.annotation.NonNull;
56 import androidx.core.content.ContextCompat;
57 import androidx.fragment.app.DialogFragment; // The AndroidX dialog fragment must be used or an error is produced on API <=22.
59 public class EditBookmarkDatabaseViewDialog extends DialogFragment {
60 // Define the home folder database ID constant.
61 public static final int HOME_FOLDER_DATABASE_ID = -1;
63 // Define the edit bookmark database view listener.
64 private EditBookmarkDatabaseViewListener editBookmarkDatabaseViewListener;
67 // The public interface is used to send information back to the parent activity.
68 public interface EditBookmarkDatabaseViewListener {
69 void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap);
73 public void onAttach(@NonNull Context context) {
74 // Run the default commands.
75 super.onAttach(context);
77 // Get a handle for edit bookmark database view listener from the launching context.
78 editBookmarkDatabaseViewListener = (EditBookmarkDatabaseViewListener) context;
82 public static EditBookmarkDatabaseViewDialog bookmarkDatabaseId(int databaseId, Bitmap favoriteIconBitmap) {
83 // Create a favorite icon byte array output stream.
84 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
86 // 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).
87 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
89 // Convert the byte array output stream to a byte array.
90 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
92 // Create an arguments bundle.
93 Bundle argumentsBundle = new Bundle();
95 // Store the variables in the bundle.
96 argumentsBundle.putInt("database_id", databaseId);
97 argumentsBundle.putByteArray("favorite_icon_byte_array", favoriteIconByteArray);
99 // Create a new instance of the dialog.
100 EditBookmarkDatabaseViewDialog editBookmarkDatabaseViewDialog = new EditBookmarkDatabaseViewDialog();
102 // Add the arguments bundle to the dialog.
103 editBookmarkDatabaseViewDialog.setArguments(argumentsBundle);
105 // Return the new dialog.
106 return editBookmarkDatabaseViewDialog;
109 // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
110 @SuppressLint("InflateParams")
113 public Dialog onCreateDialog(Bundle savedInstanceState) {
114 // Get the arguments.
115 Bundle arguments = getArguments();
117 // Remove the incorrect lint warning below that the arguments might be null.
118 assert arguments != null;
120 // Get the bookmark database ID from the bundle.
121 int bookmarkDatabaseId = getArguments().getInt("database_id");
123 // Get the favorite icon byte array.
124 byte[] favoriteIconByteArray = arguments.getByteArray("favorite_icon_byte_array");
126 // Remove the incorrect lint warning below that the favorite icon byte array might be null.
127 assert favoriteIconByteArray != null;
129 // Convert the favorite icon byte array to a bitmap.
130 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
132 // Initialize the database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
133 BookmarksDatabaseHelper bookmarksDatabaseHelper = new BookmarksDatabaseHelper(getContext(), null, null, 0);
135 // Get a cursor with the selected bookmark and move it to the first position.
136 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(bookmarkDatabaseId);
137 bookmarkCursor.moveToFirst();
139 // Use an alert dialog builder to create the alert dialog.
140 AlertDialog.Builder dialogBuilder;
142 // Get a handle for the shared preferences.
143 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
145 // Get the screenshot and theme preferences.
146 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
147 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
149 // Set the style according to the theme.
151 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
153 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
157 dialogBuilder.setTitle(R.string.edit_bookmark);
159 // Remove the incorrect lint warning below that `getLayoutInflater()` might be null.
160 assert getActivity() != null;
162 // Set the view. The parent view is `null` because it will be assigned by `AlertDialog`.
163 dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.edit_bookmark_databaseview_dialog, null));
165 // Set the listener for the negative button.
166 dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
167 // Do nothing. The `AlertDialog` will close automatically.
170 // Set the listener for the positive button.
171 dialogBuilder.setPositiveButton(R.string.save, (DialogInterface dialog, int which) -> {
172 // Return the `DialogFragment` to the parent activity on save.
173 editBookmarkDatabaseViewListener.onSaveBookmark(this, bookmarkDatabaseId, favoriteIconBitmap);
176 // Create an alert dialog from the alert dialog builder`.
177 final AlertDialog alertDialog = dialogBuilder.create();
179 // Remove the warning below that `getWindow()` might be null.
180 assert alertDialog.getWindow() != null;
182 // Disable screenshots if not allowed.
183 if (!allowScreenshots) {
184 alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
187 // The alert dialog must be shown before items in the layout can be modified.
190 // Get handles for the layout items.
191 TextView databaseIdTextView = alertDialog.findViewById(R.id.edit_bookmark_database_id_textview);
192 RadioGroup iconRadioGroup = alertDialog.findViewById(R.id.edit_bookmark_icon_radiogroup);
193 ImageView currentIconImageView = alertDialog.findViewById(R.id.edit_bookmark_current_icon);
194 ImageView newFavoriteIconImageView = alertDialog.findViewById(R.id.edit_bookmark_webpage_favorite_icon);
195 RadioButton newIconRadioButton = alertDialog.findViewById(R.id.edit_bookmark_webpage_favorite_icon_radiobutton);
196 EditText nameEditText = alertDialog.findViewById(R.id.edit_bookmark_name_edittext);
197 EditText urlEditText = alertDialog.findViewById(R.id.edit_bookmark_url_edittext);
198 Spinner folderSpinner = alertDialog.findViewById(R.id.edit_bookmark_folder_spinner);
199 EditText displayOrderEditText = alertDialog.findViewById(R.id.edit_bookmark_display_order_edittext);
200 Button editButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
202 // Store the current bookmark values.
203 String currentBookmarkName = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
204 String currentUrl = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL));
205 int currentDisplayOrder = bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER));
207 // Set the database ID.
208 databaseIdTextView.setText(String.valueOf(bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper._ID))));
210 // Get the current favorite icon byte array from the `Cursor`.
211 byte[] currentIconByteArray = bookmarkCursor.getBlob(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
213 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
214 Bitmap currentIconBitmap = BitmapFactory.decodeByteArray(currentIconByteArray, 0, currentIconByteArray.length);
216 // Display `currentIconBitmap` in `edit_bookmark_current_icon`.
217 currentIconImageView.setImageBitmap(currentIconBitmap);
219 // Set the new favorite icon bitmap.
220 newFavoriteIconImageView.setImageBitmap(favoriteIconBitmap);
222 // Populate the bookmark name and URL `EditTexts`.
223 nameEditText.setText(currentBookmarkName);
224 urlEditText.setText(currentUrl);
226 // Setup a matrix cursor for "Home Folder".
227 String[] matrixCursorColumnNames = {BookmarksDatabaseHelper._ID, BookmarksDatabaseHelper.BOOKMARK_NAME};
228 MatrixCursor matrixCursor = new MatrixCursor(matrixCursorColumnNames);
229 matrixCursor.addRow(new Object[]{HOME_FOLDER_DATABASE_ID, getString(R.string.home_folder)});
231 // Get a cursor with the list of all the folders.
232 Cursor foldersCursor = bookmarksDatabaseHelper.getAllFolders();
234 // Combine `matrixCursor` and `foldersCursor`.
235 MergeCursor foldersMergeCursor = new MergeCursor(new Cursor[]{matrixCursor, foldersCursor});
237 // Remove the incorrect lint warning below that `getContext()` might be null.
238 assert getContext() != null;
240 // Create a resource cursor adapter for the spinner.
241 ResourceCursorAdapter foldersCursorAdapter = new ResourceCursorAdapter(getContext(), R.layout.databaseview_spinner_item, foldersMergeCursor, 0) {
243 public void bindView(View view, Context context, Cursor cursor) {
244 // Get handles for the spinner views.
245 ImageView spinnerItemImageView = view.findViewById(R.id.spinner_item_imageview);
246 TextView spinnerItemTextView = view.findViewById(R.id.spinner_item_textview);
248 // Set the folder icon according to the type.
249 if (foldersMergeCursor.getPosition() == 0) { // Set the `Home Folder` icon.
250 // Set the gray folder image. `ContextCompat` must be used until the minimum API >= 21.
251 spinnerItemImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.folder_gray));
252 } else { // Set a user folder icon.
253 // Get the folder icon byte array.
254 byte[] folderIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
256 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
257 Bitmap folderIconBitmap = BitmapFactory.decodeByteArray(folderIconByteArray, 0, folderIconByteArray.length);
259 // Set the folder icon.
260 spinnerItemImageView.setImageBitmap(folderIconBitmap);
263 // Set the text view to display the folder name.
264 spinnerItemTextView.setText(cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME)));
268 // Set the `ResourceCursorAdapter` drop drown view resource.
269 foldersCursorAdapter.setDropDownViewResource(R.layout.databaseview_spinner_dropdown_items);
271 // Set the adapter for the folder `Spinner`.
272 folderSpinner.setAdapter(foldersCursorAdapter);
274 // Get the parent folder name.
275 String parentFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.PARENT_FOLDER));
277 // Select the current folder in the `Spinner` if the bookmark isn't in the "Home Folder".
278 if (!parentFolder.equals("")) {
279 // Get the database ID of the parent folder.
280 int folderDatabaseId = bookmarksDatabaseHelper.getFolderDatabaseId(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.PARENT_FOLDER)));
282 // Initialize `parentFolderPosition` and the iteration variable.
283 int parentFolderPosition = 0;
286 // Find the parent folder position in folders `ResourceCursorAdapter`.
288 if (foldersCursorAdapter.getItemId(i) == folderDatabaseId) {
289 // Store the current position for the parent folder.
290 parentFolderPosition = i;
292 // Try the next entry.
295 // Stop when the parent folder position is found or all the items in the `ResourceCursorAdapter` have been checked.
296 } while ((parentFolderPosition == 0) && (i < foldersCursorAdapter.getCount()));
298 // Select the parent folder in the `Spinner`.
299 folderSpinner.setSelection(parentFolderPosition);
302 // Store the current folder database ID.
303 int currentFolderDatabaseId = (int) folderSpinner.getSelectedItemId();
305 // Populate the display order `EditText`.
306 displayOrderEditText.setText(String.valueOf(bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER))));
308 // Initially disable the edit button.
309 editButton.setEnabled(false);
311 // Update the edit button if the icon selection changes.
312 iconRadioGroup.setOnCheckedChangeListener((group, checkedId) -> {
313 // Update the edit button.
314 updateEditButton(nameEditText, urlEditText, displayOrderEditText, folderSpinner, newIconRadioButton, editButton, currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder);
317 // Update the edit button if the bookmark name changes.
318 nameEditText.addTextChangedListener(new TextWatcher() {
320 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
325 public void onTextChanged(CharSequence s, int start, int before, int count) {
330 public void afterTextChanged(Editable s) {
331 // Update the edit button.
332 updateEditButton(nameEditText, urlEditText, displayOrderEditText, folderSpinner, newIconRadioButton, editButton, currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder);
336 // Update the edit button if the URL changes.
337 urlEditText.addTextChangedListener(new TextWatcher() {
339 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
344 public void onTextChanged(CharSequence s, int start, int before, int count) {
349 public void afterTextChanged(Editable s) {
350 // Update the edit button.
351 updateEditButton(nameEditText, urlEditText, displayOrderEditText, folderSpinner, newIconRadioButton, editButton, currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder);
355 // Update the edit button if the folder changes.
356 folderSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
358 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
359 // Update the edit button.
360 updateEditButton(nameEditText, urlEditText, displayOrderEditText, folderSpinner, newIconRadioButton, editButton, currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder);
364 public void onNothingSelected(AdapterView<?> parent) {
369 // Update the edit button if the display order changes.
370 displayOrderEditText.addTextChangedListener(new TextWatcher() {
372 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
377 public void onTextChanged(CharSequence s, int start, int before, int count) {
382 public void afterTextChanged(Editable s) {
383 // Update the edit button.
384 updateEditButton(nameEditText, urlEditText, displayOrderEditText, folderSpinner, newIconRadioButton, editButton, currentBookmarkName, currentUrl, currentFolderDatabaseId, currentDisplayOrder);
388 // Allow the `enter` key on the keyboard to save the bookmark from the bookmark name `EditText`.
389 nameEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
390 // Save the bookmark if the event is a key-down on the "enter" button.
391 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) { // The enter key was pressed and the edit button is enabled.
392 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
393 editBookmarkDatabaseViewListener.onSaveBookmark(EditBookmarkDatabaseViewDialog.this, bookmarkDatabaseId, favoriteIconBitmap);
395 // Manually dismiss `alertDialog`.
396 alertDialog.dismiss();
398 // Consume the event.
400 } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
405 // Allow the "enter" key on the keyboard to save the bookmark from the URL `EditText`.
406 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
407 // Save the bookmark if the event is a key-down on the "enter" button.
408 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) { // The enter key was pressed and the edit button is enabled.
409 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
410 editBookmarkDatabaseViewListener.onSaveBookmark(EditBookmarkDatabaseViewDialog.this, bookmarkDatabaseId, favoriteIconBitmap);
412 // Manually dismiss the `AlertDialog`.
413 alertDialog.dismiss();
415 // Consume the event.
417 } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
422 // Allow the "enter" key on the keyboard to save the bookmark from the display order `EditText`.
423 displayOrderEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
424 // Save the bookmark if the event is a key-down on the "enter" button.
425 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) { // The enter key was pressed and the edit button is enabled.
426 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
427 editBookmarkDatabaseViewListener.onSaveBookmark(EditBookmarkDatabaseViewDialog.this, bookmarkDatabaseId, favoriteIconBitmap);
429 // Manually dismiss the `AlertDialog`.
430 alertDialog.dismiss();
432 // Consume the event.
434 } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
439 // `onCreateDialog` requires the return of an `AlertDialog`.
443 private void updateEditButton(EditText nameEditText, EditText urlEditText, EditText displayOrderEditText, Spinner folderSpinner, RadioButton newIconRadioButton, Button editButton,
444 String currentBookmarkName, String currentUrl, int currentFolderDatabaseId, int currentDisplayOrder) {
445 // Get the values from the dialog.
446 String newName = nameEditText.getText().toString();
447 String newUrl = urlEditText.getText().toString();
448 int newFolderDatabaseId = (int) folderSpinner.getSelectedItemId();
449 String newDisplayOrder = displayOrderEditText.getText().toString();
451 // Has the favorite icon changed?
452 boolean iconChanged = newIconRadioButton.isChecked();
454 // Has the name changed?
455 boolean nameChanged = !newName.equals(currentBookmarkName);
457 // Has the URL changed?
458 boolean urlChanged = !newUrl.equals(currentUrl);
460 // Has the folder changed?
461 boolean folderChanged = newFolderDatabaseId != currentFolderDatabaseId;
463 // Has the display order changed?
464 boolean displayOrderChanged = !newDisplayOrder.equals(String.valueOf(currentDisplayOrder));
466 // Is the display order empty?
467 boolean displayOrderNotEmpty = !newDisplayOrder.isEmpty();
469 // Update the enabled status of the edit button.
470 editButton.setEnabled((iconChanged || nameChanged || urlChanged || folderChanged || displayOrderChanged) && displayOrderNotEmpty);