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.activities.BookmarksDatabaseViewActivity;
58 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
60 import java.io.ByteArrayOutputStream;
62 public class EditBookmarkFolderDatabaseViewDialog extends DialogFragment {
63 // Define the edit bookmark folder database view listener.
64 private EditBookmarkFolderDatabaseViewListener editBookmarkFolderDatabaseViewListener;
67 // The public interface is used to send information back to the parent activity.
68 public interface EditBookmarkFolderDatabaseViewListener {
69 void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap);
72 public void onAttach(@NonNull Context context) {
73 // Run the default commands.
74 super.onAttach(context);
76 // Get a handle for `EditBookmarkDatabaseViewListener` from the launching context.
77 editBookmarkFolderDatabaseViewListener = (EditBookmarkFolderDatabaseViewListener) context;
81 public static EditBookmarkFolderDatabaseViewDialog folderDatabaseId(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 EditBookmarkFolderDatabaseViewDialog editBookmarkFolderDatabaseViewDialog = new EditBookmarkFolderDatabaseViewDialog();
101 // Add the arguments bundle to the dialog.
102 editBookmarkFolderDatabaseViewDialog.setArguments(argumentsBundle);
104 // Return the new dialog.
105 return editBookmarkFolderDatabaseViewDialog;
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 folderDatabaseId = 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 folderCursor = bookmarksDatabaseHelper.getBookmark(folderDatabaseId);
136 folderCursor.moveToFirst();
138 // Use an alert dialog builder to create the alert dialog.
139 AlertDialog.Builder dialogBuilder;
141 // Get a handle for the shared preferences.
142 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
144 // Get the screenshot and theme preferences.
145 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
146 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
148 // Set the style according to the theme.
150 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
152 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
156 dialogBuilder.setTitle(R.string.edit_folder);
158 // Remove the incorrect lint warning that `getActivity()` might be null.
159 assert getActivity() != null;
161 // Set the view. The parent view is `null` because it will be assigned by `AlertDialog`.
162 dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.edit_bookmark_folder_databaseview_dialog, null));
164 // Set the listener for the negative button.
165 dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
166 // Do nothing. The `AlertDialog` will close automatically.
169 // Set the listener fo the positive button.
170 dialogBuilder.setPositiveButton(R.string.save, (DialogInterface dialog, int which) -> {
171 // Return the `DialogFragment` to the parent activity on save.
172 editBookmarkFolderDatabaseViewListener.onSaveBookmarkFolder(this, folderDatabaseId, favoriteIconBitmap);
175 // Create an alert dialog from the alert dialog builder.
176 final AlertDialog alertDialog = dialogBuilder.create();
178 // Remove the warning below that `getWindow()` might be null.
179 assert alertDialog.getWindow() != null;
181 // Disable screenshots if not allowed.
182 if (!allowScreenshots) {
183 alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
186 // The alert dialog must be shown before items in the layout can be modified.
189 // Get handles for the layout items.
190 TextView databaseIdTextView = alertDialog.findViewById(R.id.edit_folder_database_id_textview);
191 RadioGroup iconRadioGroup = alertDialog.findViewById(R.id.edit_folder_icon_radiogroup);
192 ImageView currentIconImageView = alertDialog.findViewById(R.id.edit_folder_current_icon_imageview);
193 ImageView newFavoriteIconImageView = alertDialog.findViewById(R.id.edit_folder_webpage_favorite_icon_imageview);
194 EditText nameEditText = alertDialog.findViewById(R.id.edit_folder_name_edittext);
195 Spinner folderSpinner = alertDialog.findViewById(R.id.edit_folder_parent_folder_spinner);
196 EditText displayOrderEditText = alertDialog.findViewById(R.id.edit_folder_display_order_edittext);
197 Button editButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
199 // Store the current folder values.
200 String currentFolderName = folderCursor.getString(folderCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
201 int currentDisplayOrder = folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER));
202 String parentFolder = folderCursor.getString(folderCursor.getColumnIndex(BookmarksDatabaseHelper.PARENT_FOLDER));
204 // Set the database ID.
205 databaseIdTextView.setText(String.valueOf(folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID))));
207 // Get the current favorite icon byte array from the `Cursor`.
208 byte[] currentIconByteArray = folderCursor.getBlob(folderCursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
210 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
211 Bitmap currentIconBitmap = BitmapFactory.decodeByteArray(currentIconByteArray, 0, currentIconByteArray.length);
213 // Display the current icon bitmap in `edit_bookmark_current_icon`.
214 currentIconImageView.setImageBitmap(currentIconBitmap);
216 // Set the new favorite icon bitmap.
217 newFavoriteIconImageView.setImageBitmap(favoriteIconBitmap);
219 // Populate the folder name edit text.
220 nameEditText.setText(currentFolderName);
222 // Setup a matrix cursor for "Home Folder".
223 String[] matrixCursorColumnNames = {BookmarksDatabaseHelper._ID, BookmarksDatabaseHelper.BOOKMARK_NAME};
224 MatrixCursor matrixCursor = new MatrixCursor(matrixCursorColumnNames);
225 matrixCursor.addRow(new Object[]{BookmarksDatabaseViewActivity.HOME_FOLDER_DATABASE_ID, getString(R.string.home_folder)});
227 // Add all subfolders of the current folder to the list of folders not to display.
228 String exceptFolders = getStringOfSubfolders(currentFolderName, bookmarksDatabaseHelper);
230 Log.i("Folders", "String of Folders Not To Display: " + exceptFolders);
232 // Get a cursor with the list of all the folders.
233 Cursor foldersCursor = bookmarksDatabaseHelper.getFoldersExcept(exceptFolders);
235 // Combine the matrix cursor and the folders cursor.
236 MergeCursor foldersMergeCursor = new MergeCursor(new Cursor[]{matrixCursor, foldersCursor});
238 // Remove the incorrect lint warning that `getContext()` might be null.
239 assert getContext() != null;
241 // Create a resource cursor adapter for the spinner.
242 ResourceCursorAdapter foldersCursorAdapter = new ResourceCursorAdapter(getContext(), R.layout.databaseview_spinner_item, foldersMergeCursor, 0) {
244 public void bindView(View view, Context context, Cursor cursor) {
245 // Get handles for the spinner views.
246 ImageView spinnerItemImageView = view.findViewById(R.id.spinner_item_imageview);
247 TextView spinnerItemTextView = view.findViewById(R.id.spinner_item_textview);
249 // Set the folder icon according to the type.
250 if (foldersMergeCursor.getPosition() == 0) { // Set the `Home Folder` icon.
251 // Set the gray folder image. `ContextCompat` must be used until the minimum API >= 21.
252 spinnerItemImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.folder_gray));
253 } else { // Set a user folder icon.
254 // Get the folder icon byte array.
255 byte[] folderIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
257 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
258 Bitmap folderIconBitmap = BitmapFactory.decodeByteArray(folderIconByteArray, 0, folderIconByteArray.length);
260 // Set the folder icon.
261 spinnerItemImageView.setImageBitmap(folderIconBitmap);
264 // Set the text view to display the folder name.
265 spinnerItemTextView.setText(cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME)));
269 // Set the `ResourceCursorAdapter` drop drown view resource.
270 foldersCursorAdapter.setDropDownViewResource(R.layout.databaseview_spinner_dropdown_items);
272 // Set the adapter for the folder `Spinner`.
273 folderSpinner.setAdapter(foldersCursorAdapter);
275 // Select the current folder in the `Spinner` if the bookmark isn't in the "Home Folder".
276 if (!parentFolder.equals("")) {
277 // Get the database ID of the parent folder.
278 int parentFolderDatabaseId = bookmarksDatabaseHelper.getFolderDatabaseId(folderCursor.getString(folderCursor.getColumnIndex(BookmarksDatabaseHelper.PARENT_FOLDER)));
280 // Initialize `parentFolderPosition` and the iteration variable.
281 int parentFolderPosition = 0;
284 // Find the parent folder position in folders `ResourceCursorAdapter`.
286 if (foldersCursorAdapter.getItemId(i) == parentFolderDatabaseId) {
287 // Store the current position for the parent folder.
288 parentFolderPosition = i;
290 // Try the next entry.
293 // Stop when the parent folder position is found or all the items in the `ResourceCursorAdapter` have been checked.
294 } while ((parentFolderPosition == 0) && (i < foldersCursorAdapter.getCount()));
296 // Select the parent folder in the `Spinner`.
297 folderSpinner.setSelection(parentFolderPosition);
300 // Store the current folder database ID.
301 int currentParentFolderDatabaseId = (int) folderSpinner.getSelectedItemId();
303 // Populate the display order `EditText`.
304 displayOrderEditText.setText(String.valueOf(folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER))));
306 // Initially disable the edit button.
307 editButton.setEnabled(false);
309 // Update the edit button if the icon selection changes.
310 iconRadioGroup.setOnCheckedChangeListener((group, checkedId) -> {
311 // Update the edit button.
312 updateEditButton(alertDialog, bookmarksDatabaseHelper, currentFolderName, currentParentFolderDatabaseId, currentDisplayOrder);
315 // Update the edit button if the bookmark name changes.
316 nameEditText.addTextChangedListener(new TextWatcher() {
318 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
323 public void onTextChanged(CharSequence s, int start, int before, int count) {
328 public void afterTextChanged(Editable s) {
329 // Update the edit button.
330 updateEditButton(alertDialog, bookmarksDatabaseHelper, currentFolderName, currentParentFolderDatabaseId, currentDisplayOrder);
334 // Update the edit button if the folder changes.
335 folderSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
337 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
338 // Update the edit button.
339 updateEditButton(alertDialog, bookmarksDatabaseHelper, currentFolderName, currentParentFolderDatabaseId, currentDisplayOrder);
343 public void onNothingSelected(AdapterView<?> parent) {
348 // Update the edit button if the display order changes.
349 displayOrderEditText.addTextChangedListener(new TextWatcher() {
351 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
356 public void onTextChanged(CharSequence s, int start, int before, int count) {
361 public void afterTextChanged(Editable s) {
362 // Update the edit button.
363 updateEditButton(alertDialog, bookmarksDatabaseHelper, currentFolderName, currentParentFolderDatabaseId, currentDisplayOrder);
367 // Allow the `enter` key on the keyboard to save the bookmark from the bookmark name `EditText`.
368 nameEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
369 // Save the bookmark if the event is a key-down on the "enter" button.
370 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) { // The enter key was pressed and the edit button is enabled.
371 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
372 editBookmarkFolderDatabaseViewListener.onSaveBookmarkFolder(this, folderDatabaseId, favoriteIconBitmap);
374 // Manually dismiss `alertDialog`.
375 alertDialog.dismiss();
377 // Consume the event.
379 } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
384 // Allow the "enter" key on the keyboard to save the bookmark from the display order `EditText`.
385 displayOrderEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
386 // Save the bookmark if the event is a key-down on the "enter" button.
387 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) { // The enter key was pressed and the edit button is enabled.
388 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
389 editBookmarkFolderDatabaseViewListener.onSaveBookmarkFolder(this, folderDatabaseId, favoriteIconBitmap);
391 // Manually dismiss the `AlertDialog`.
392 alertDialog.dismiss();
394 // Consume the event.
396 } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
401 // `onCreateDialog` requires the return of an `AlertDialog`.
405 private void updateEditButton(AlertDialog alertDialog, BookmarksDatabaseHelper bookmarksDatabaseHelper, String currentFolderName, int currentParentFolderDatabaseId, int currentDisplayOrder) {
406 // Get handles for the views.
407 EditText nameEditText = alertDialog.findViewById(R.id.edit_folder_name_edittext);
408 Spinner folderSpinner = alertDialog.findViewById(R.id.edit_folder_parent_folder_spinner);
409 EditText displayOrderEditText = alertDialog.findViewById(R.id.edit_folder_display_order_edittext);
410 RadioButton currentIconRadioButton = alertDialog.findViewById(R.id.edit_folder_current_icon_radiobutton);
411 Button editButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
413 // Get the values from the dialog.
414 String newFolderName = nameEditText.getText().toString();
415 int newParentFolderDatabaseId = (int) folderSpinner.getSelectedItemId();
416 String newDisplayOrder = displayOrderEditText.getText().toString();
418 // Get a cursor for the new folder name if it exists.
419 Cursor folderExistsCursor = bookmarksDatabaseHelper.getFolder(newFolderName);
421 // Is the new folder name empty?
422 boolean folderNameNotEmpty = !newFolderName.isEmpty();
424 // Does the folder name already exist?
425 boolean folderNameAlreadyExists = (!newFolderName.equals(currentFolderName) && (folderExistsCursor.getCount() > 0));
427 // Has the favorite icon changed?
428 boolean iconChanged = !currentIconRadioButton.isChecked();
430 // Has the name been renamed?
431 boolean folderRenamed = (!newFolderName.equals(currentFolderName) && !folderNameAlreadyExists);
433 // Has the folder changed?
434 boolean parentFolderChanged = newParentFolderDatabaseId != currentParentFolderDatabaseId;
436 // Has the display order changed?
437 boolean displayOrderChanged = !newDisplayOrder.equals(String.valueOf(currentDisplayOrder));
439 // Is the display order empty?
440 boolean displayOrderNotEmpty = !newDisplayOrder.isEmpty();
442 // Update the enabled status of the edit button.
443 editButton.setEnabled((iconChanged || folderRenamed || parentFolderChanged || displayOrderChanged) && folderNameNotEmpty && displayOrderNotEmpty);
446 private String getStringOfSubfolders(String folderName, BookmarksDatabaseHelper bookmarksDatabaseHelper) {
447 // Get a cursor will all the immediate subfolders.
448 Cursor subfoldersCursor = bookmarksDatabaseHelper.getSubfolders(folderName);
450 // Initialize a string builder to track the folders not to display in the spinner and populate it with the current folder.
451 StringBuilder exceptFoldersStringBuilder = new StringBuilder(DatabaseUtils.sqlEscapeString(folderName));
453 for (int i = 0; i < subfoldersCursor.getCount(); i++) {
454 // Move the subfolder cursor to the current item.
455 subfoldersCursor.moveToPosition(i);
457 // Get the name of the subfolder.
458 String subfolderName = subfoldersCursor.getString(subfoldersCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
460 // Add a comma to the end of the existing string.
461 exceptFoldersStringBuilder.append(",");
463 // Get the folder name and run the task for any subfolders.
464 String subfolderString = getStringOfSubfolders(subfolderName, bookmarksDatabaseHelper);
466 // Add the folder name to the string builder.
467 exceptFoldersStringBuilder.append(subfolderString);
470 // Return the string of folders.
471 return exceptFoldersStringBuilder.toString();