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.DatabaseUtils;
30 import android.database.MatrixCursor;
31 import android.database.MergeCursor;
32 import android.graphics.Bitmap;
33 import android.graphics.BitmapFactory;
34 import android.os.Bundle;
35 import android.preference.PreferenceManager;
36 import android.text.Editable;
37 import android.text.TextWatcher;
38 import android.util.Log;
39 import android.view.KeyEvent;
40 import android.view.View;
41 import android.view.WindowManager;
42 import android.widget.AdapterView;
43 import android.widget.Button;
44 import android.widget.EditText;
45 import android.widget.ImageView;
46 import android.widget.RadioButton;
47 import android.widget.RadioGroup;
48 import android.widget.ResourceCursorAdapter;
49 import android.widget.Spinner;
50 import android.widget.TextView;
52 import androidx.annotation.NonNull;
53 import androidx.core.content.ContextCompat;
54 import androidx.fragment.app.DialogFragment; // The AndroidX dialog fragment must be used or an error is produced on API <=22.
56 import com.stoutner.privacybrowser.R;
57 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
59 import java.io.ByteArrayOutputStream;
61 public class EditBookmarkFolderDatabaseViewDialog extends DialogFragment {
62 // Define the home folder database ID constant.
63 public static final int HOME_FOLDER_DATABASE_ID = -1;
65 // Define the edit bookmark folder database view listener.
66 private EditBookmarkFolderDatabaseViewListener editBookmarkFolderDatabaseViewListener;
69 // The public interface is used to send information back to the parent activity.
70 public interface EditBookmarkFolderDatabaseViewListener {
71 void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap);
74 public void onAttach(@NonNull Context context) {
75 // Run the default commands.
76 super.onAttach(context);
78 // Get a handle for `EditBookmarkDatabaseViewListener` from the launching context.
79 editBookmarkFolderDatabaseViewListener = (EditBookmarkFolderDatabaseViewListener) context;
83 public static EditBookmarkFolderDatabaseViewDialog folderDatabaseId(int databaseId, Bitmap favoriteIconBitmap) {
84 // Create a favorite icon byte array output stream.
85 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
87 // 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).
88 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
90 // Convert the byte array output stream to a byte array.
91 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
93 // Create an arguments bundle.
94 Bundle argumentsBundle = new Bundle();
96 // Store the variables in the bundle.
97 argumentsBundle.putInt("database_id", databaseId);
98 argumentsBundle.putByteArray("favorite_icon_byte_array", favoriteIconByteArray);
100 // Create a new instance of the dialog.
101 EditBookmarkFolderDatabaseViewDialog editBookmarkFolderDatabaseViewDialog = new EditBookmarkFolderDatabaseViewDialog();
103 // Add the arguments bundle to the dialog.
104 editBookmarkFolderDatabaseViewDialog.setArguments(argumentsBundle);
106 // Return the new dialog.
107 return editBookmarkFolderDatabaseViewDialog;
110 // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
111 @SuppressLint("InflateParams")
114 public Dialog onCreateDialog(Bundle savedInstanceState) {
115 // Get the arguments.
116 Bundle arguments = getArguments();
118 // Remove the incorrect lint warning below that the arguments might be null.
119 assert arguments != null;
121 // Get the bookmark database ID from the bundle.
122 int folderDatabaseId = getArguments().getInt("database_id");
124 // Get the favorite icon byte array.
125 byte[] favoriteIconByteArray = arguments.getByteArray("favorite_icon_byte_array");
127 // Remove the incorrect lint warning below that the favorite icon byte array might be null.
128 assert favoriteIconByteArray != null;
130 // Convert the favorite icon byte array to a bitmap.
131 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
133 // Initialize the database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
134 BookmarksDatabaseHelper bookmarksDatabaseHelper = new BookmarksDatabaseHelper(getContext(), null, null, 0);
136 // Get a `Cursor` with the selected bookmark and move it to the first position.
137 Cursor folderCursor = bookmarksDatabaseHelper.getBookmark(folderDatabaseId);
138 folderCursor.moveToFirst();
140 // Use an alert dialog builder to create the alert dialog.
141 AlertDialog.Builder dialogBuilder;
143 // Get a handle for the shared preferences.
144 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
146 // Get the screenshot and theme preferences.
147 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
148 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
150 // Set the style according to the theme.
152 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
154 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
158 dialogBuilder.setTitle(R.string.edit_folder);
160 // Remove the incorrect lint warning that `getActivity()` might be null.
161 assert getActivity() != null;
163 // Set the view. The parent view is `null` because it will be assigned by `AlertDialog`.
164 dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.edit_bookmark_folder_databaseview_dialog, null));
166 // Set the listener for the negative button.
167 dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
168 // Do nothing. The `AlertDialog` will close automatically.
171 // Set the listener fo the positive button.
172 dialogBuilder.setPositiveButton(R.string.save, (DialogInterface dialog, int which) -> {
173 // Return the `DialogFragment` to the parent activity on save.
174 editBookmarkFolderDatabaseViewListener.onSaveBookmarkFolder(this, folderDatabaseId, favoriteIconBitmap);
177 // Create an alert dialog from the alert dialog builder.
178 final AlertDialog alertDialog = dialogBuilder.create();
180 // Remove the warning below that `getWindow()` might be null.
181 assert alertDialog.getWindow() != null;
183 // Disable screenshots if not allowed.
184 if (!allowScreenshots) {
185 alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
188 // The alert dialog must be shown before items in the layout can be modified.
191 // Get handles for the layout items.
192 TextView databaseIdTextView = alertDialog.findViewById(R.id.edit_folder_database_id_textview);
193 RadioGroup iconRadioGroup = alertDialog.findViewById(R.id.edit_folder_icon_radiogroup);
194 ImageView currentIconImageView = alertDialog.findViewById(R.id.edit_folder_current_icon_imageview);
195 ImageView newFavoriteIconImageView = alertDialog.findViewById(R.id.edit_folder_webpage_favorite_icon_imageview);
196 EditText nameEditText = alertDialog.findViewById(R.id.edit_folder_name_edittext);
197 Spinner folderSpinner = alertDialog.findViewById(R.id.edit_folder_parent_folder_spinner);
198 EditText displayOrderEditText = alertDialog.findViewById(R.id.edit_folder_display_order_edittext);
199 Button editButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
201 // Store the current folder values.
202 String currentFolderName = folderCursor.getString(folderCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
203 int currentDisplayOrder = folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER));
204 String parentFolder = folderCursor.getString(folderCursor.getColumnIndex(BookmarksDatabaseHelper.PARENT_FOLDER));
206 // Set the database ID.
207 databaseIdTextView.setText(String.valueOf(folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID))));
209 // Get the current favorite icon byte array from the `Cursor`.
210 byte[] currentIconByteArray = folderCursor.getBlob(folderCursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
212 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
213 Bitmap currentIconBitmap = BitmapFactory.decodeByteArray(currentIconByteArray, 0, currentIconByteArray.length);
215 // Display the current icon bitmap in `edit_bookmark_current_icon`.
216 currentIconImageView.setImageBitmap(currentIconBitmap);
218 // Set the new favorite icon bitmap.
219 newFavoriteIconImageView.setImageBitmap(favoriteIconBitmap);
221 // Populate the folder name edit text.
222 nameEditText.setText(currentFolderName);
224 // Setup a matrix cursor for "Home Folder".
225 String[] matrixCursorColumnNames = {BookmarksDatabaseHelper._ID, BookmarksDatabaseHelper.BOOKMARK_NAME};
226 MatrixCursor matrixCursor = new MatrixCursor(matrixCursorColumnNames);
227 matrixCursor.addRow(new Object[]{HOME_FOLDER_DATABASE_ID, getString(R.string.home_folder)});
229 // Add all subfolders of the current folder to the list of folders not to display.
230 String exceptFolders = getStringOfSubfolders(currentFolderName, bookmarksDatabaseHelper);
232 Log.i("Folders", "String of Folders Not To Display: " + exceptFolders);
234 // Get a cursor with the list of all the folders.
235 Cursor foldersCursor = bookmarksDatabaseHelper.getFoldersExcept(exceptFolders);
237 // Combine the matrix cursor and the folders cursor.
238 MergeCursor foldersMergeCursor = new MergeCursor(new Cursor[]{matrixCursor, foldersCursor});
240 // Remove the incorrect lint warning that `getContext()` might be null.
241 assert getContext() != null;
243 // Create a resource cursor adapter for the spinner.
244 ResourceCursorAdapter foldersCursorAdapter = new ResourceCursorAdapter(getContext(), R.layout.databaseview_spinner_item, foldersMergeCursor, 0) {
246 public void bindView(View view, Context context, Cursor cursor) {
247 // Get handles for the spinner views.
248 ImageView spinnerItemImageView = view.findViewById(R.id.spinner_item_imageview);
249 TextView spinnerItemTextView = view.findViewById(R.id.spinner_item_textview);
251 // Set the folder icon according to the type.
252 if (foldersMergeCursor.getPosition() == 0) { // Set the `Home Folder` icon.
253 // Set the gray folder image. `ContextCompat` must be used until the minimum API >= 21.
254 spinnerItemImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.folder_gray));
255 } else { // Set a user folder icon.
256 // Get the folder icon byte array.
257 byte[] folderIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
259 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
260 Bitmap folderIconBitmap = BitmapFactory.decodeByteArray(folderIconByteArray, 0, folderIconByteArray.length);
262 // Set the folder icon.
263 spinnerItemImageView.setImageBitmap(folderIconBitmap);
266 // Set the text view to display the folder name.
267 spinnerItemTextView.setText(cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME)));
271 // Set the `ResourceCursorAdapter` drop drown view resource.
272 foldersCursorAdapter.setDropDownViewResource(R.layout.databaseview_spinner_dropdown_items);
274 // Set the adapter for the folder `Spinner`.
275 folderSpinner.setAdapter(foldersCursorAdapter);
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 parentFolderDatabaseId = bookmarksDatabaseHelper.getFolderDatabaseId(folderCursor.getString(folderCursor.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) == parentFolderDatabaseId) {
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 currentParentFolderDatabaseId = (int) folderSpinner.getSelectedItemId();
305 // Populate the display order `EditText`.
306 displayOrderEditText.setText(String.valueOf(folderCursor.getInt(folderCursor.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(alertDialog, bookmarksDatabaseHelper, currentFolderName, currentParentFolderDatabaseId, 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(alertDialog, bookmarksDatabaseHelper, currentFolderName, currentParentFolderDatabaseId, currentDisplayOrder);
336 // Update the edit button if the folder changes.
337 folderSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
339 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
340 // Update the edit button.
341 updateEditButton(alertDialog, bookmarksDatabaseHelper, currentFolderName, currentParentFolderDatabaseId, currentDisplayOrder);
345 public void onNothingSelected(AdapterView<?> parent) {
350 // Update the edit button if the display order changes.
351 displayOrderEditText.addTextChangedListener(new TextWatcher() {
353 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
358 public void onTextChanged(CharSequence s, int start, int before, int count) {
363 public void afterTextChanged(Editable s) {
364 // Update the edit button.
365 updateEditButton(alertDialog, bookmarksDatabaseHelper, currentFolderName, currentParentFolderDatabaseId, currentDisplayOrder);
369 // Allow the `enter` key on the keyboard to save the bookmark from the bookmark name `EditText`.
370 nameEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
371 // Save the bookmark if the event is a key-down on the "enter" button.
372 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) { // The enter key was pressed and the edit button is enabled.
373 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
374 editBookmarkFolderDatabaseViewListener.onSaveBookmarkFolder(this, folderDatabaseId, favoriteIconBitmap);
376 // Manually dismiss `alertDialog`.
377 alertDialog.dismiss();
379 // Consume the event.
381 } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
386 // Allow the "enter" key on the keyboard to save the bookmark from the display order `EditText`.
387 displayOrderEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
388 // Save the bookmark if the event is a key-down on the "enter" button.
389 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) { // The enter key was pressed and the edit button is enabled.
390 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
391 editBookmarkFolderDatabaseViewListener.onSaveBookmarkFolder(this, folderDatabaseId, favoriteIconBitmap);
393 // Manually dismiss the `AlertDialog`.
394 alertDialog.dismiss();
396 // Consume the event.
398 } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
403 // `onCreateDialog` requires the return of an `AlertDialog`.
407 private void updateEditButton(AlertDialog alertDialog, BookmarksDatabaseHelper bookmarksDatabaseHelper, String currentFolderName, int currentParentFolderDatabaseId, int currentDisplayOrder) {
408 // Get handles for the views.
409 EditText nameEditText = alertDialog.findViewById(R.id.edit_folder_name_edittext);
410 Spinner folderSpinner = alertDialog.findViewById(R.id.edit_folder_parent_folder_spinner);
411 EditText displayOrderEditText = alertDialog.findViewById(R.id.edit_folder_display_order_edittext);
412 RadioButton currentIconRadioButton = alertDialog.findViewById(R.id.edit_folder_current_icon_radiobutton);
413 Button editButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
415 // Get the values from the dialog.
416 String newFolderName = nameEditText.getText().toString();
417 int newParentFolderDatabaseId = (int) folderSpinner.getSelectedItemId();
418 String newDisplayOrder = displayOrderEditText.getText().toString();
420 // Get a cursor for the new folder name if it exists.
421 Cursor folderExistsCursor = bookmarksDatabaseHelper.getFolder(newFolderName);
423 // Is the new folder name empty?
424 boolean folderNameNotEmpty = !newFolderName.isEmpty();
426 // Does the folder name already exist?
427 boolean folderNameAlreadyExists = (!newFolderName.equals(currentFolderName) && (folderExistsCursor.getCount() > 0));
429 // Has the favorite icon changed?
430 boolean iconChanged = !currentIconRadioButton.isChecked();
432 // Has the name been renamed?
433 boolean folderRenamed = (!newFolderName.equals(currentFolderName) && !folderNameAlreadyExists);
435 // Has the folder changed?
436 boolean parentFolderChanged = newParentFolderDatabaseId != currentParentFolderDatabaseId;
438 // Has the display order changed?
439 boolean displayOrderChanged = !newDisplayOrder.equals(String.valueOf(currentDisplayOrder));
441 // Is the display order empty?
442 boolean displayOrderNotEmpty = !newDisplayOrder.isEmpty();
444 // Update the enabled status of the edit button.
445 editButton.setEnabled((iconChanged || folderRenamed || parentFolderChanged || displayOrderChanged) && folderNameNotEmpty && displayOrderNotEmpty);
448 private String getStringOfSubfolders(String folderName, BookmarksDatabaseHelper bookmarksDatabaseHelper) {
449 // Get a cursor will all the immediate subfolders.
450 Cursor subfoldersCursor = bookmarksDatabaseHelper.getSubfolders(folderName);
452 // Initialize a string builder to track the folders not to display in the spinner and populate it with the current folder.
453 StringBuilder exceptFoldersStringBuilder = new StringBuilder(DatabaseUtils.sqlEscapeString(folderName));
455 for (int i = 0; i < subfoldersCursor.getCount(); i++) {
456 // Move the subfolder cursor to the current item.
457 subfoldersCursor.moveToPosition(i);
459 // Get the name of the subfolder.
460 String subfolderName = subfoldersCursor.getString(subfoldersCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
462 // Add a comma to the end of the existing string.
463 exceptFoldersStringBuilder.append(",");
465 // Get the folder name and run the task for any subfolders.
466 String subfolderString = getStringOfSubfolders(subfolderName, bookmarksDatabaseHelper);
468 // Add the folder name to the string builder.
469 exceptFoldersStringBuilder.append(subfolderString);
472 // Return the string of folders.
473 return exceptFoldersStringBuilder.toString();