]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/EditBookmarkFolderDatabaseViewDialog.java
Allow specifying any font size. https://redmine.stoutner.com/issues/504
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / EditBookmarkFolderDatabaseViewDialog.java
1 /*
2  * Copyright © 2016-2019 Soren Stoutner <soren@stoutner.com>.
3  *
4  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 package com.stoutner.privacybrowser.dialogs;
21
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;
51
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.
55
56 import com.stoutner.privacybrowser.R;
57 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
58
59 import java.io.ByteArrayOutputStream;
60
61 public class EditBookmarkFolderDatabaseViewDialog extends DialogFragment {
62     // Define the home folder database ID constant.
63     public static final int HOME_FOLDER_DATABASE_ID = -1;
64
65     // Define the edit bookmark folder database view listener.
66     private EditBookmarkFolderDatabaseViewListener editBookmarkFolderDatabaseViewListener;
67
68
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);
72     }
73
74     public void onAttach(@NonNull Context context) {
75         // Run the default commands.
76         super.onAttach(context);
77
78         // Get a handle for `EditBookmarkDatabaseViewListener` from the launching context.
79         editBookmarkFolderDatabaseViewListener = (EditBookmarkFolderDatabaseViewListener) context;
80     }
81
82
83     public static EditBookmarkFolderDatabaseViewDialog folderDatabaseId(int databaseId, Bitmap favoriteIconBitmap) {
84         // Create a favorite icon byte array output stream.
85         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
86
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);
89
90         // Convert the byte array output stream to a byte array.
91         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
92
93         // Create an arguments bundle.
94         Bundle argumentsBundle = new Bundle();
95
96         // Store the variables in the bundle.
97         argumentsBundle.putInt("database_id", databaseId);
98         argumentsBundle.putByteArray("favorite_icon_byte_array", favoriteIconByteArray);
99
100         // Create a new instance of the dialog.
101         EditBookmarkFolderDatabaseViewDialog editBookmarkFolderDatabaseViewDialog = new EditBookmarkFolderDatabaseViewDialog();
102
103         // Add the arguments bundle to the dialog.
104         editBookmarkFolderDatabaseViewDialog.setArguments(argumentsBundle);
105
106         // Return the new dialog.
107         return editBookmarkFolderDatabaseViewDialog;
108     }
109
110     // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
111     @SuppressLint("InflateParams")
112     @Override
113     @NonNull
114     public Dialog onCreateDialog(Bundle savedInstanceState) {
115         // Get the arguments.
116         Bundle arguments = getArguments();
117
118         // Remove the incorrect lint warning below that the arguments might be null.
119         assert arguments != null;
120
121         // Get the bookmark database ID from the bundle.
122         int folderDatabaseId = getArguments().getInt("database_id");
123
124         // Get the favorite icon byte array.
125         byte[] favoriteIconByteArray = arguments.getByteArray("favorite_icon_byte_array");
126
127         // Remove the incorrect lint warning below that the favorite icon byte array might be null.
128         assert favoriteIconByteArray != null;
129
130         // Convert the favorite icon byte array to a bitmap.
131         Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
132
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);
135
136         // Get a `Cursor` with the selected bookmark and move it to the first position.
137         Cursor folderCursor = bookmarksDatabaseHelper.getBookmark(folderDatabaseId);
138         folderCursor.moveToFirst();
139
140         // Use an alert dialog builder to create the alert dialog.
141         AlertDialog.Builder dialogBuilder;
142
143         // Get a handle for the shared preferences.
144         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
145
146         // Get the screenshot and theme preferences.
147         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
148         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
149
150         // Set the style according to the theme.
151         if (darkTheme) {
152             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
153         } else {
154             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
155         }
156
157         // Set the title.
158         dialogBuilder.setTitle(R.string.edit_folder);
159
160         // Remove the incorrect lint warning that `getActivity()` might be null.
161         assert getActivity() != null;
162
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));
165
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.
169         });
170
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);
175         });
176
177         // Create an alert dialog from the alert dialog builder.
178         final AlertDialog alertDialog = dialogBuilder.create();
179
180         // Remove the warning below that `getWindow()` might be null.
181         assert alertDialog.getWindow() != null;
182
183         // Disable screenshots if not allowed.
184         if (!allowScreenshots) {
185             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
186         }
187
188         // The alert dialog must be shown before items in the layout can be modified.
189         alertDialog.show();
190
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);
200
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));
205
206         // Set the database ID.
207         databaseIdTextView.setText(String.valueOf(folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID))));
208
209         // Get the current favorite icon byte array from the `Cursor`.
210         byte[] currentIconByteArray = folderCursor.getBlob(folderCursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
211
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);
214
215         // Display the current icon bitmap in `edit_bookmark_current_icon`.
216         currentIconImageView.setImageBitmap(currentIconBitmap);
217
218         // Set the new favorite icon bitmap.
219         newFavoriteIconImageView.setImageBitmap(favoriteIconBitmap);
220
221         // Populate the folder name edit text.
222         nameEditText.setText(currentFolderName);
223
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)});
228
229         // Add all subfolders of the current folder to the list of folders not to display.
230         String exceptFolders = getStringOfSubfolders(currentFolderName, bookmarksDatabaseHelper);
231
232         Log.i("Folders", "String of Folders Not To Display:  " + exceptFolders);
233
234         // Get a cursor with the list of all the folders.
235         Cursor foldersCursor = bookmarksDatabaseHelper.getFoldersExcept(exceptFolders);
236
237         // Combine the matrix cursor and the folders cursor.
238         MergeCursor foldersMergeCursor = new MergeCursor(new Cursor[]{matrixCursor, foldersCursor});
239
240         // Remove the incorrect lint warning that `getContext()` might be null.
241         assert getContext() != null;
242
243         // Create a resource cursor adapter for the spinner.
244         ResourceCursorAdapter foldersCursorAdapter = new ResourceCursorAdapter(getContext(), R.layout.databaseview_spinner_item, foldersMergeCursor, 0) {
245             @Override
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);
250
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));
258
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);
261
262                     // Set the folder icon.
263                     spinnerItemImageView.setImageBitmap(folderIconBitmap);
264                 }
265
266                 // Set the text view to display the folder name.
267                 spinnerItemTextView.setText(cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME)));
268             }
269         };
270
271         // Set the `ResourceCursorAdapter` drop drown view resource.
272         foldersCursorAdapter.setDropDownViewResource(R.layout.databaseview_spinner_dropdown_items);
273
274         // Set the adapter for the folder `Spinner`.
275         folderSpinner.setAdapter(foldersCursorAdapter);
276
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)));
281
282             // Initialize `parentFolderPosition` and the iteration variable.
283             int parentFolderPosition = 0;
284             int i = 0;
285
286             // Find the parent folder position in folders `ResourceCursorAdapter`.
287             do {
288                 if (foldersCursorAdapter.getItemId(i) == parentFolderDatabaseId) {
289                     // Store the current position for the parent folder.
290                     parentFolderPosition = i;
291                 } else {
292                     // Try the next entry.
293                     i++;
294                 }
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()));
297
298             // Select the parent folder in the `Spinner`.
299             folderSpinner.setSelection(parentFolderPosition);
300         }
301
302         // Store the current folder database ID.
303         int currentParentFolderDatabaseId = (int) folderSpinner.getSelectedItemId();
304
305         // Populate the display order `EditText`.
306         displayOrderEditText.setText(String.valueOf(folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER))));
307
308         // Initially disable the edit button.
309         editButton.setEnabled(false);
310
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);
315         });
316
317         // Update the edit button if the bookmark name changes.
318         nameEditText.addTextChangedListener(new TextWatcher() {
319             @Override
320             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
321                 // Do nothing.
322             }
323
324             @Override
325             public void onTextChanged(CharSequence s, int start, int before, int count) {
326                 // Do nothing.
327             }
328
329             @Override
330             public void afterTextChanged(Editable s) {
331                 // Update the edit button.
332                 updateEditButton(alertDialog, bookmarksDatabaseHelper, currentFolderName, currentParentFolderDatabaseId, currentDisplayOrder);
333             }
334         });
335
336         // Update the edit button if the folder changes.
337         folderSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
338             @Override
339             public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
340                 // Update the edit button.
341                 updateEditButton(alertDialog, bookmarksDatabaseHelper, currentFolderName, currentParentFolderDatabaseId, currentDisplayOrder);
342             }
343
344             @Override
345             public void onNothingSelected(AdapterView<?> parent) {
346
347             }
348         });
349
350         // Update the edit button if the display order changes.
351         displayOrderEditText.addTextChangedListener(new TextWatcher() {
352             @Override
353             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
354                 // Do nothing.
355             }
356
357             @Override
358             public void onTextChanged(CharSequence s, int start, int before, int count) {
359                 // Do nothing.
360             }
361
362             @Override
363             public void afterTextChanged(Editable s) {
364                 // Update the edit button.
365                 updateEditButton(alertDialog, bookmarksDatabaseHelper, currentFolderName, currentParentFolderDatabaseId, currentDisplayOrder);
366             }
367         });
368
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);
375
376                 // Manually dismiss `alertDialog`.
377                 alertDialog.dismiss();
378
379                 // Consume the event.
380                 return true;
381             } else {  // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
382                 return false;
383             }
384         });
385
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);
392
393                 // Manually dismiss the `AlertDialog`.
394                 alertDialog.dismiss();
395
396                 // Consume the event.
397                 return true;
398             } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
399                 return false;
400             }
401         });
402
403         // `onCreateDialog` requires the return of an `AlertDialog`.
404         return alertDialog;
405     }
406
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);
414
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();
419
420         // Get a cursor for the new folder name if it exists.
421         Cursor folderExistsCursor = bookmarksDatabaseHelper.getFolder(newFolderName);
422
423         // Is the new folder name empty?
424         boolean folderNameNotEmpty = !newFolderName.isEmpty();
425
426         // Does the folder name already exist?
427         boolean folderNameAlreadyExists = (!newFolderName.equals(currentFolderName) && (folderExistsCursor.getCount() > 0));
428
429         // Has the favorite icon changed?
430         boolean iconChanged = !currentIconRadioButton.isChecked();
431
432         // Has the name been renamed?
433         boolean folderRenamed = (!newFolderName.equals(currentFolderName) && !folderNameAlreadyExists);
434
435         // Has the folder changed?
436         boolean parentFolderChanged = newParentFolderDatabaseId != currentParentFolderDatabaseId;
437
438         // Has the display order changed?
439         boolean displayOrderChanged = !newDisplayOrder.equals(String.valueOf(currentDisplayOrder));
440
441         // Is the display order empty?
442         boolean displayOrderNotEmpty = !newDisplayOrder.isEmpty();
443
444         // Update the enabled status of the edit button.
445         editButton.setEnabled((iconChanged || folderRenamed || parentFolderChanged || displayOrderChanged) && folderNameNotEmpty && displayOrderNotEmpty);
446     }
447
448     private String getStringOfSubfolders(String folderName, BookmarksDatabaseHelper bookmarksDatabaseHelper) {
449         // Get a cursor will all the immediate subfolders.
450         Cursor subfoldersCursor = bookmarksDatabaseHelper.getSubfolders(folderName);
451
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));
454
455         for (int i = 0; i < subfoldersCursor.getCount(); i++) {
456             // Move the subfolder cursor to the current item.
457             subfoldersCursor.moveToPosition(i);
458
459             // Get the name of the subfolder.
460             String subfolderName = subfoldersCursor.getString(subfoldersCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
461
462             // Add a comma to the end of the existing string.
463             exceptFoldersStringBuilder.append(",");
464
465             // Get the folder name and run the task for any subfolders.
466             String subfolderString = getStringOfSubfolders(subfolderName, bookmarksDatabaseHelper);
467
468             // Add the folder name to the string builder.
469             exceptFoldersStringBuilder.append(subfolderString);
470         }
471
472         // Return the string of folders.
473         return exceptFoldersStringBuilder.toString();
474     }
475 }