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.DatabaseUtils;
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.text.Editable;
35 import android.text.TextWatcher;
36 import android.util.Log;
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 androidx.annotation.NonNull;
51 import androidx.core.content.ContextCompat;
52 import androidx.fragment.app.DialogFragment; // The AndroidX dialog fragment must be used or an error is produced on API <=22.
54 import com.stoutner.privacybrowser.R;
55 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
56 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
58 import java.io.ByteArrayOutputStream;
60 public class EditBookmarkFolderDatabaseViewDialog extends DialogFragment {
61 // Define the home folder database ID constant.
62 public static final int HOME_FOLDER_DATABASE_ID = -1;
64 // Define the edit bookmark folder database view listener.
65 private EditBookmarkFolderDatabaseViewListener editBookmarkFolderDatabaseViewListener;
68 // The public interface is used to send information back to the parent activity.
69 public interface EditBookmarkFolderDatabaseViewListener {
70 void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap);
73 public void onAttach(Context context) {
74 // Run the default commands.
75 super.onAttach(context);
77 // Get a handle for `EditBookmarkDatabaseViewListener` from the launching context.
78 editBookmarkFolderDatabaseViewListener = (EditBookmarkFolderDatabaseViewListener) context;
82 public static EditBookmarkFolderDatabaseViewDialog folderDatabaseId(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 EditBookmarkFolderDatabaseViewDialog editBookmarkFolderDatabaseViewDialog = new EditBookmarkFolderDatabaseViewDialog();
102 // Add the arguments bundle to the dialog.
103 editBookmarkFolderDatabaseViewDialog.setArguments(argumentsBundle);
105 // Return the new dialog.
106 return editBookmarkFolderDatabaseViewDialog;
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 folderDatabaseId = 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 folderCursor = bookmarksDatabaseHelper.getBookmark(folderDatabaseId);
137 folderCursor.moveToFirst();
139 // Use an alert dialog builder to create the alert dialog.
140 AlertDialog.Builder dialogBuilder;
142 // Set the style according to the theme.
143 if (MainWebViewActivity.darkTheme) {
144 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
146 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
150 dialogBuilder.setTitle(R.string.edit_folder);
152 // Remove the incorrect lint warning that `getActivity()` might be null.
153 assert getActivity() != null;
155 // Set the view. The parent view is `null` because it will be assigned by `AlertDialog`.
156 dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.edit_bookmark_folder_databaseview_dialog, null));
158 // Set the listener for the negative button.
159 dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
160 // Do nothing. The `AlertDialog` will close automatically.
163 // Set the listener fo the positive button.
164 dialogBuilder.setPositiveButton(R.string.save, (DialogInterface dialog, int which) -> {
165 // Return the `DialogFragment` to the parent activity on save.
166 editBookmarkFolderDatabaseViewListener.onSaveBookmarkFolder(this, folderDatabaseId, favoriteIconBitmap);
169 // Create an alert dialog from the alert dialog builder.
170 final AlertDialog alertDialog = dialogBuilder.create();
172 // Remove the warning below that `getWindow()` might be null.
173 assert alertDialog.getWindow() != null;
175 // Disable screenshots if not allowed.
176 if (!MainWebViewActivity.allowScreenshots) {
177 alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
180 // The alert dialog must be shown before items in the layout can be modified.
183 // Get handles for the layout items.
184 TextView databaseIdTextView = alertDialog.findViewById(R.id.edit_folder_database_id_textview);
185 RadioGroup iconRadioGroup = alertDialog.findViewById(R.id.edit_folder_icon_radiogroup);
186 ImageView currentIconImageView = alertDialog.findViewById(R.id.edit_folder_current_icon_imageview);
187 ImageView newFavoriteIconImageView = alertDialog.findViewById(R.id.edit_folder_webpage_favorite_icon_imageview);
188 EditText nameEditText = alertDialog.findViewById(R.id.edit_folder_name_edittext);
189 Spinner folderSpinner = alertDialog.findViewById(R.id.edit_folder_parent_folder_spinner);
190 EditText displayOrderEditText = alertDialog.findViewById(R.id.edit_folder_display_order_edittext);
191 Button editButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
193 // Store the current folder values.
194 String currentFolderName = folderCursor.getString(folderCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
195 int currentDisplayOrder = folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER));
196 String parentFolder = folderCursor.getString(folderCursor.getColumnIndex(BookmarksDatabaseHelper.PARENT_FOLDER));
198 // Set the database ID.
199 databaseIdTextView.setText(String.valueOf(folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID))));
201 // Get the current favorite icon byte array from the `Cursor`.
202 byte[] currentIconByteArray = folderCursor.getBlob(folderCursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
204 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
205 Bitmap currentIconBitmap = BitmapFactory.decodeByteArray(currentIconByteArray, 0, currentIconByteArray.length);
207 // Display the current icon bitmap in `edit_bookmark_current_icon`.
208 currentIconImageView.setImageBitmap(currentIconBitmap);
210 // Set the new favorite icon bitmap.
211 newFavoriteIconImageView.setImageBitmap(favoriteIconBitmap);
213 // Populate the folder name edit text.
214 nameEditText.setText(currentFolderName);
216 // Setup a matrix cursor for "Home Folder".
217 String[] matrixCursorColumnNames = {BookmarksDatabaseHelper._ID, BookmarksDatabaseHelper.BOOKMARK_NAME};
218 MatrixCursor matrixCursor = new MatrixCursor(matrixCursorColumnNames);
219 matrixCursor.addRow(new Object[]{HOME_FOLDER_DATABASE_ID, getString(R.string.home_folder)});
221 // Add all subfolders of the current folder to the list of folders not to display.
222 String exceptFolders = getStringOfSubfolders(currentFolderName, bookmarksDatabaseHelper);
224 Log.i("Folders", "String of Folders Not To Display: " + exceptFolders);
226 // Get a cursor with the list of all the folders.
227 Cursor foldersCursor = bookmarksDatabaseHelper.getFoldersExcept(exceptFolders);
229 // Combine the matrix cursor and the folders cursor.
230 MergeCursor foldersMergeCursor = new MergeCursor(new Cursor[]{matrixCursor, foldersCursor});
232 // Remove the incorrect lint warning that `getContext()` might be null.
233 assert getContext() != null;
235 // Create a resource cursor adapter for the spinner.
236 ResourceCursorAdapter foldersCursorAdapter = new ResourceCursorAdapter(getContext(), R.layout.databaseview_spinner_item, foldersMergeCursor, 0) {
238 public void bindView(View view, Context context, Cursor cursor) {
239 // Get handles for the spinner views.
240 ImageView spinnerItemImageView = view.findViewById(R.id.spinner_item_imageview);
241 TextView spinnerItemTextView = view.findViewById(R.id.spinner_item_textview);
243 // Set the folder icon according to the type.
244 if (foldersMergeCursor.getPosition() == 0) { // Set the `Home Folder` icon.
245 // Set the gray folder image. `ContextCompat` must be used until the minimum API >= 21.
246 spinnerItemImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.folder_gray));
247 } else { // Set a user folder icon.
248 // Get the folder icon byte array.
249 byte[] folderIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
251 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
252 Bitmap folderIconBitmap = BitmapFactory.decodeByteArray(folderIconByteArray, 0, folderIconByteArray.length);
254 // Set the folder icon.
255 spinnerItemImageView.setImageBitmap(folderIconBitmap);
258 // Set the text view to display the folder name.
259 spinnerItemTextView.setText(cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME)));
263 // Set the `ResourceCursorAdapter` drop drown view resource.
264 foldersCursorAdapter.setDropDownViewResource(R.layout.databaseview_spinner_dropdown_items);
266 // Set the adapter for the folder `Spinner`.
267 folderSpinner.setAdapter(foldersCursorAdapter);
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 parentFolderDatabaseId = bookmarksDatabaseHelper.getFolderDatabaseId(folderCursor.getString(folderCursor.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) == parentFolderDatabaseId) {
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 currentParentFolderDatabaseId = (int) folderSpinner.getSelectedItemId();
297 // Populate the display order `EditText`.
298 displayOrderEditText.setText(String.valueOf(folderCursor.getInt(folderCursor.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(alertDialog, bookmarksDatabaseHelper, currentFolderName, currentParentFolderDatabaseId, 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(alertDialog, bookmarksDatabaseHelper, currentFolderName, currentParentFolderDatabaseId, currentDisplayOrder);
328 // Update the edit button if the folder changes.
329 folderSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
331 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
332 // Update the edit button.
333 updateEditButton(alertDialog, bookmarksDatabaseHelper, currentFolderName, currentParentFolderDatabaseId, currentDisplayOrder);
337 public void onNothingSelected(AdapterView<?> parent) {
342 // Update the edit button if the display order changes.
343 displayOrderEditText.addTextChangedListener(new TextWatcher() {
345 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
350 public void onTextChanged(CharSequence s, int start, int before, int count) {
355 public void afterTextChanged(Editable s) {
356 // Update the edit button.
357 updateEditButton(alertDialog, bookmarksDatabaseHelper, currentFolderName, currentParentFolderDatabaseId, currentDisplayOrder);
361 // Allow the `enter` key on the keyboard to save the bookmark from the bookmark name `EditText`.
362 nameEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
363 // Save the bookmark if the event is a key-down on the "enter" button.
364 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) { // The enter key was pressed and the edit button is enabled.
365 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
366 editBookmarkFolderDatabaseViewListener.onSaveBookmarkFolder(this, folderDatabaseId, favoriteIconBitmap);
368 // Manually dismiss `alertDialog`.
369 alertDialog.dismiss();
371 // Consume the event.
373 } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
378 // Allow the "enter" key on the keyboard to save the bookmark from the display order `EditText`.
379 displayOrderEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
380 // Save the bookmark if the event is a key-down on the "enter" button.
381 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) { // The enter key was pressed and the edit button is enabled.
382 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
383 editBookmarkFolderDatabaseViewListener.onSaveBookmarkFolder(this, folderDatabaseId, favoriteIconBitmap);
385 // Manually dismiss the `AlertDialog`.
386 alertDialog.dismiss();
388 // Consume the event.
390 } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
395 // `onCreateDialog` requires the return of an `AlertDialog`.
399 private void updateEditButton(AlertDialog alertDialog, BookmarksDatabaseHelper bookmarksDatabaseHelper, String currentFolderName, int currentParentFolderDatabaseId, int currentDisplayOrder) {
400 // Get handles for the views.
401 EditText nameEditText = alertDialog.findViewById(R.id.edit_folder_name_edittext);
402 Spinner folderSpinner = alertDialog.findViewById(R.id.edit_folder_parent_folder_spinner);
403 EditText displayOrderEditText = alertDialog.findViewById(R.id.edit_folder_display_order_edittext);
404 RadioButton currentIconRadioButton = alertDialog.findViewById(R.id.edit_folder_current_icon_radiobutton);
405 Button editButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
407 // Get the values from the dialog.
408 String newFolderName = nameEditText.getText().toString();
409 int newParentFolderDatabaseId = (int) folderSpinner.getSelectedItemId();
410 String newDisplayOrder = displayOrderEditText.getText().toString();
412 // Get a cursor for the new folder name if it exists.
413 Cursor folderExistsCursor = bookmarksDatabaseHelper.getFolder(newFolderName);
415 // Is the new folder name empty?
416 boolean folderNameNotEmpty = !newFolderName.isEmpty();
418 // Does the folder name already exist?
419 boolean folderNameAlreadyExists = (!newFolderName.equals(currentFolderName) && (folderExistsCursor.getCount() > 0));
421 // Has the favorite icon changed?
422 boolean iconChanged = !currentIconRadioButton.isChecked();
424 // Has the name been renamed?
425 boolean folderRenamed = (!newFolderName.equals(currentFolderName) && !folderNameAlreadyExists);
427 // Has the folder changed?
428 boolean parentFolderChanged = newParentFolderDatabaseId != currentParentFolderDatabaseId;
430 // Has the display order changed?
431 boolean displayOrderChanged = !newDisplayOrder.equals(String.valueOf(currentDisplayOrder));
433 // Is the display order empty?
434 boolean displayOrderNotEmpty = !newDisplayOrder.isEmpty();
436 // Update the enabled status of the edit button.
437 editButton.setEnabled((iconChanged || folderRenamed || parentFolderChanged || displayOrderChanged) && folderNameNotEmpty && displayOrderNotEmpty);
440 private String getStringOfSubfolders(String folderName, BookmarksDatabaseHelper bookmarksDatabaseHelper) {
441 // Get a cursor will all the immediate subfolders.
442 Cursor subfoldersCursor = bookmarksDatabaseHelper.getSubfolders(folderName);
444 // Initialize a string builder to track the folders not to display in the spinner and populate it with the current folder.
445 StringBuilder exceptFoldersStringBuilder = new StringBuilder(DatabaseUtils.sqlEscapeString(folderName));
447 for (int i = 0; i < subfoldersCursor.getCount(); i++) {
448 // Move the subfolder cursor to the current item.
449 subfoldersCursor.moveToPosition(i);
451 // Get the name of the subfolder.
452 String subfolderName = subfoldersCursor.getString(subfoldersCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
454 // Add a comma to the end of the existing string.
455 exceptFoldersStringBuilder.append(",");
457 // Get the folder name and run the task for any subfolders.
458 String subfolderString = getStringOfSubfolders(subfolderName, bookmarksDatabaseHelper);
460 // Add the folder name to the string builder.
461 exceptFoldersStringBuilder.append(subfolderString);
464 // Return the string of folders.
465 return exceptFoldersStringBuilder.toString();