Migrate five dialogs to Kotlin. https://redmine.stoutner.com/issues/543
[PrivacyBrowser.git] / app / src / main / java / com / stoutner / privacybrowser / activities / BookmarksDatabaseViewActivity.java
1 /*
2  * Copyright © 2016-2020 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.activities;
21
22 import android.annotation.SuppressLint;
23 import android.app.Dialog;
24 import android.content.Context;
25 import android.content.Intent;
26 import android.content.SharedPreferences;
27 import android.database.Cursor;
28 import android.database.MatrixCursor;
29 import android.database.MergeCursor;
30 import android.graphics.Bitmap;
31 import android.graphics.BitmapFactory;
32 import android.graphics.Typeface;
33 import android.graphics.drawable.BitmapDrawable;
34 import android.graphics.drawable.Drawable;
35 import android.os.Bundle;
36 import android.preference.PreferenceManager;
37 import android.util.SparseBooleanArray;
38 import android.view.ActionMode;
39 import android.view.Menu;
40 import android.view.MenuItem;
41 import android.view.View;
42 import android.view.ViewGroup;
43 import android.view.WindowManager;
44 import android.widget.AbsListView;
45 import android.widget.AdapterView;
46 import android.widget.EditText;
47 import android.widget.ImageView;
48 import android.widget.ListView;
49 import android.widget.RadioButton;
50 import android.widget.ResourceCursorAdapter;
51 import android.widget.Spinner;
52 import android.widget.TextView;
53
54 import androidx.annotation.NonNull;
55 import androidx.appcompat.app.ActionBar;
56 import androidx.appcompat.app.AppCompatActivity;
57 import androidx.appcompat.widget.Toolbar;  // The AndroidX toolbar must be used until the minimum API is >= 21.
58 import androidx.core.content.ContextCompat;
59 import androidx.cursoradapter.widget.CursorAdapter;
60 import androidx.fragment.app.DialogFragment;  // The AndroidX dialog fragment must be used or an error is produced on API <=22.
61
62 import com.google.android.material.snackbar.Snackbar;
63
64 import com.stoutner.privacybrowser.R;
65 import com.stoutner.privacybrowser.dialogs.EditBookmarkDatabaseViewDialog;
66 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDatabaseViewDialog;
67 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
68
69 import java.io.ByteArrayOutputStream;
70 import java.util.Arrays;
71
72 public class BookmarksDatabaseViewActivity extends AppCompatActivity implements EditBookmarkDatabaseViewDialog.EditBookmarkDatabaseViewListener,
73         EditBookmarkFolderDatabaseViewDialog.EditBookmarkFolderDatabaseViewListener {
74     // Instantiate the constants.
75     private static final int ALL_FOLDERS_DATABASE_ID = -2;
76     public static final int HOME_FOLDER_DATABASE_ID = -1;
77
78     // `bookmarksDatabaseHelper` is used in `onCreate()`, `updateBookmarksListView()`, `selectAllBookmarksInFolder()`, and `onDestroy()`.
79     private BookmarksDatabaseHelper bookmarksDatabaseHelper;
80
81     // `bookmarksCursor` is used in `onCreate()`, `updateBookmarksListView()`, `onSaveBookmark()`, `onSaveBookmarkFolder()`, and `onDestroy()`.
82     private Cursor bookmarksCursor;
83
84     // `bookmarksCursorAdapter` is used in `onCreate()`, `selectAllBookmarksInFolder()`, and `updateBookmarksListView()`.
85     private CursorAdapter bookmarksCursorAdapter;
86
87     // `oldFolderNameString` is used in `onCreate()` and `onSaveBookmarkFolder()`.
88     private String oldFolderNameString;
89
90     // `currentFolderDatabaseId` is used in `onCreate()`, `updateBookmarksListView()`, `onSaveBookmark()`, and `onSaveBookmarkFolder()`.
91     private int currentFolderDatabaseId;
92
93     // `currentFolder` is used in `onCreate()`, `onSaveBookmark()`, and `onSaveBookmarkFolder()`.
94     private String currentFolderName;
95
96     // `sortByDisplayOrder` is used in `onCreate()`, `onOptionsItemSelected()`, and `updateBookmarksListView()`.
97     private boolean sortByDisplayOrder;
98
99     // `bookmarksDeletedSnackbar` is used in `onCreate()`, `onOptionsItemSelected()`, and `onBackPressed()`.
100     private Snackbar bookmarksDeletedSnackbar;
101
102     // `closeActivityAfterDismissingSnackbar` is used in `onCreate()`, `onOptionsItemSelected()`, and `onBackPressed()`.
103     private boolean closeActivityAfterDismissingSnackbar;
104
105     @Override
106     public void onCreate(Bundle savedInstanceState) {
107         // Get a handle for the shared preferences.
108         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
109
110         // Get the theme and screenshot preferences.
111         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
112         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
113
114         // Disable screenshots if not allowed.
115         if (!allowScreenshots) {
116             getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
117         }
118
119         // Set the activity theme.
120         if (darkTheme) {
121             setTheme(R.style.PrivacyBrowserDark_SecondaryActivity);
122         } else {
123             setTheme(R.style.PrivacyBrowserLight_SecondaryActivity);
124         }
125
126         // Run the default commands.
127         super.onCreate(savedInstanceState);
128
129         // Get the intent that launched the activity.
130         Intent launchingIntent = getIntent();
131
132         // Get the favorite icon byte array.
133         byte[] favoriteIconByteArray = launchingIntent.getByteArrayExtra("favorite_icon_byte_array");
134
135         // Remove the incorrect lint warning below that the favorite icon byte array might be null.
136         assert favoriteIconByteArray != null;
137
138         // Convert the favorite icon byte array to a bitmap and store it in a class variable.
139         Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
140
141         // Set the content view.
142         setContentView(R.layout.bookmarks_databaseview_coordinatorlayout);
143
144         // The AndroidX toolbar must be used until the minimum API is >= 21.
145         Toolbar toolbar = findViewById(R.id.bookmarks_databaseview_toolbar);
146         setSupportActionBar(toolbar);
147
148         // Get a handle for the action bar.
149         ActionBar actionBar = getSupportActionBar();
150
151         // Remove the incorrect lint warning that the action bar might be null.
152         assert actionBar != null;
153
154         // Display the spinner and the back arrow in the action bar.
155         actionBar.setCustomView(R.layout.spinner);
156         actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_HOME_AS_UP);
157
158         // Initialize the database handler.  The `0` is to specify a database version, but that is set instead using a constant in `BookmarksDatabaseHelper`.
159         bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
160
161         // Setup a matrix cursor for "All Folders" and "Home Folder".
162         String[] matrixCursorColumnNames = {BookmarksDatabaseHelper._ID, BookmarksDatabaseHelper.BOOKMARK_NAME};
163         MatrixCursor matrixCursor = new MatrixCursor(matrixCursorColumnNames);
164         matrixCursor.addRow(new Object[]{ALL_FOLDERS_DATABASE_ID, getString(R.string.all_folders)});
165         matrixCursor.addRow(new Object[]{HOME_FOLDER_DATABASE_ID, getString(R.string.home_folder)});
166
167         // Get a cursor with the list of all the folders.
168         Cursor foldersCursor = bookmarksDatabaseHelper.getAllFolders();
169
170         // Combine `matrixCursor` and `foldersCursor`.
171         MergeCursor foldersMergeCursor = new MergeCursor(new Cursor[]{matrixCursor, foldersCursor});
172
173
174         // Get the default folder bitmap.  `ContextCompat` must be used until the minimum API >= 21.
175         Drawable defaultFolderDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.folder_blue_bitmap);
176
177         // Cast the default folder drawable to a `BitmapDrawable`.
178         BitmapDrawable defaultFolderBitmapDrawable = (BitmapDrawable) defaultFolderDrawable;
179
180         // Remove the incorrect lint warning that `.getBitmap()` might be null.
181         assert defaultFolderBitmapDrawable != null;
182
183         // Convert the default folder `BitmapDrawable` to a bitmap.
184         Bitmap defaultFolderBitmap = defaultFolderBitmapDrawable.getBitmap();
185
186
187         // Create a resource cursor adapter for the spinner.
188         ResourceCursorAdapter foldersCursorAdapter = new ResourceCursorAdapter(this, R.layout.appbar_spinner_item, foldersMergeCursor, 0) {
189             @Override
190             public void bindView(View view, Context context, Cursor cursor) {
191                 // Get handles for the spinner views.
192                 ImageView spinnerItemImageView = view.findViewById(R.id.spinner_item_imageview);
193                 TextView spinnerItemTextView = view.findViewById(R.id.spinner_item_textview);
194
195                 // Set the folder icon according to the type.
196                 if (foldersMergeCursor.getPosition() > 1) {  // Set a user folder icon.
197                     // Initialize a default folder icon byte array output stream.
198                     ByteArrayOutputStream defaultFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
199
200                     // Covert the default folder bitmap to a PNG and store it in the output stream.  `0` is for lossless compression (the only option for a PNG).
201                     defaultFolderBitmap.compress(Bitmap.CompressFormat.PNG, 0, defaultFolderIconByteArrayOutputStream);
202
203                     // Convert the default folder icon output stream to a byte array.
204                     byte[] defaultFolderIconByteArray = defaultFolderIconByteArrayOutputStream.toByteArray();
205
206
207                     // Get the folder icon byte array from the cursor.
208                     byte[] folderIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
209
210                     // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
211                     Bitmap folderIconBitmap = BitmapFactory.decodeByteArray(folderIconByteArray, 0, folderIconByteArray.length);
212
213
214                     // Set the icon according to the type.
215                     if (Arrays.equals(folderIconByteArray, defaultFolderIconByteArray)) {  // The default folder icon is used.
216                         // Set a smaller and darker folder icon, which works well with the spinner.
217                         spinnerItemImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.folder_dark_blue));
218                     } else {  // A custom folder icon is uses.
219                         // Set the folder image stored in the cursor.
220                         spinnerItemImageView.setImageBitmap(folderIconBitmap);
221                     }
222                 } else {  // Set the `All Folders` or `Home Folder` icon.
223                     // Set the gray folder image.  `ContextCompat` must be used until the minimum API >= 21.
224                     spinnerItemImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.folder_gray));
225                 }
226
227                 // Set the text view to display the folder name.
228                 spinnerItemTextView.setText(cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME)));
229             }
230         };
231
232         // Set the resource cursor adapter drop drown view resource.
233         foldersCursorAdapter.setDropDownViewResource(R.layout.appbar_spinner_dropdown_item);
234
235         // Get a handle for the folder spinner and set the adapter.
236         Spinner folderSpinner = findViewById(R.id.spinner);
237         folderSpinner.setAdapter(foldersCursorAdapter);
238
239         // Handle taps on the spinner dropdown.
240         folderSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
241             @Override
242             public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
243                 // Store the current folder database ID.
244                 currentFolderDatabaseId = (int) id;
245
246                 // Get a handle for the selected view.
247                 TextView selectedFolderTextView = findViewById(R.id.spinner_item_textview);
248
249                 // Store the current folder name.
250                 currentFolderName = selectedFolderTextView.getText().toString();
251
252                 // Update the list view.
253                 updateBookmarksListView();
254             }
255
256             @Override
257             public void onNothingSelected(AdapterView<?> parent) {
258                 // Do nothing.
259             }
260         });
261
262         // Get a handle for the bookmarks `ListView`.
263         ListView bookmarksListView = findViewById(R.id.bookmarks_databaseview_listview);
264
265         // Get a `Cursor` with the current contents of the bookmarks database.
266         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarks();
267
268         // Setup a `CursorAdapter` with `this` context.  `false` disables autoRequery.
269         bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
270             @Override
271             public View newView(Context context, Cursor cursor, ViewGroup parent) {
272                 // Inflate the individual item layout.  `false` does not attach it to the root.
273                 return getLayoutInflater().inflate(R.layout.bookmarks_databaseview_item_linearlayout, parent, false);
274             }
275
276             @Override
277             public void bindView(View view, Context context, Cursor cursor) {
278                 boolean isFolder = (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1);
279
280                 // Get the database ID from the `Cursor` and display it in `bookmarkDatabaseIdTextView`.
281                 int bookmarkDatabaseId = cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper._ID));
282                 TextView bookmarkDatabaseIdTextView = view.findViewById(R.id.bookmarks_databaseview_database_id);
283                 bookmarkDatabaseIdTextView.setText(String.valueOf(bookmarkDatabaseId));
284
285                 // Get the favorite icon byte array from the `Cursor`.
286                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
287                 // Convert the byte array to a `Bitmap` beginning at the beginning at the first byte and ending at the last.
288                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
289                 // Display the bitmap in `bookmarkFavoriteIcon`.
290                 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmarks_databaseview_favorite_icon);
291                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
292
293                 // Get the bookmark name from the `Cursor` and display it in `bookmarkNameTextView`.
294                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
295                 TextView bookmarkNameTextView = view.findViewById(R.id.bookmarks_databaseview_bookmark_name);
296                 bookmarkNameTextView.setText(bookmarkNameString);
297
298                 // Make the font bold for folders.
299                 if (isFolder) {
300                     // The first argument is `null` prevent changing of the font.
301                     bookmarkNameTextView.setTypeface(null, Typeface.BOLD);
302                 } else {  // Reset the font to default.
303                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
304                 }
305
306                 // Get the bookmark URL form the `Cursor` and display it in `bookmarkUrlTextView`.
307                 String bookmarkUrlString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL));
308                 TextView bookmarkUrlTextView = view.findViewById(R.id.bookmarks_databaseview_bookmark_url);
309                 bookmarkUrlTextView.setText(bookmarkUrlString);
310
311                 // Hide the URL if the bookmark is a folder.
312                 if (isFolder) {
313                     bookmarkUrlTextView.setVisibility(View.GONE);
314                 } else {
315                     bookmarkUrlTextView.setVisibility(View.VISIBLE);
316                 }
317
318                 // Get the display order from the `Cursor` and display it in `bookmarkDisplayOrderTextView`.
319                 int bookmarkDisplayOrder = cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER));
320                 TextView bookmarkDisplayOrderTextView = view.findViewById(R.id.bookmarks_databaseview_display_order);
321                 bookmarkDisplayOrderTextView.setText(String.valueOf(bookmarkDisplayOrder));
322
323                 // Get the parent folder from the `Cursor` and display it in `bookmarkParentFolder`.
324                 String bookmarkParentFolder = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.PARENT_FOLDER));
325                 ImageView parentFolderImageView = view.findViewById(R.id.bookmarks_databaseview_parent_folder_icon);
326                 TextView bookmarkParentFolderTextView = view.findViewById(R.id.bookmarks_databaseview_parent_folder);
327
328                 // Make the folder name gray if it is the home folder.
329                 if (bookmarkParentFolder.isEmpty()) {
330                     parentFolderImageView.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.folder_gray));
331                     bookmarkParentFolderTextView.setText(R.string.home_folder);
332                     bookmarkParentFolderTextView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.gray_500));
333                 } else {
334                     parentFolderImageView.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.folder_dark_blue));
335                     bookmarkParentFolderTextView.setText(bookmarkParentFolder);
336
337                     // Set the text color according to the theme.
338                     if (darkTheme) {
339                         bookmarkParentFolderTextView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.gray_300));
340                     } else {
341                         bookmarkParentFolderTextView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.black));
342                     }
343                 }
344             }
345         };
346
347         // Update the ListView.
348         bookmarksListView.setAdapter(bookmarksCursorAdapter);
349
350         // Set the current folder database ID.
351         currentFolderDatabaseId = ALL_FOLDERS_DATABASE_ID;
352
353         // Set a listener to edit a bookmark when it is tapped.
354         bookmarksListView.setOnItemClickListener((AdapterView<?> parent, View view, int position, long id) -> {
355             // Convert the database ID to an int.
356             int databaseId = (int) id;
357
358             // Show the edit bookmark or edit bookmark folder dialog.
359             if (bookmarksDatabaseHelper.isFolder(databaseId)) {
360                 // Save the current folder name, which is used in `onSaveBookmarkFolder()`.
361                 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
362
363                 // Show the edit bookmark folder dialog.
364                 DialogFragment editBookmarkFolderDatabaseViewDialog = EditBookmarkFolderDatabaseViewDialog.folderDatabaseId(databaseId, favoriteIconBitmap);
365                 editBookmarkFolderDatabaseViewDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
366             } else {
367                 // Show the edit bookmark dialog.
368                 DialogFragment editBookmarkDatabaseViewDialog = EditBookmarkDatabaseViewDialog.bookmarkDatabaseId(databaseId, favoriteIconBitmap);
369                 editBookmarkDatabaseViewDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
370             }
371         });
372
373         // Handle long presses on the list view.
374         bookmarksListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
375             // Instantiate the common variables.
376             MenuItem selectAllMenuItem;
377             MenuItem deleteMenuItem;
378             boolean deletingBookmarks;
379
380             @Override
381             public boolean onCreateActionMode(ActionMode mode, Menu menu) {
382                 // Inflate the menu for the contextual app bar.
383                 getMenuInflater().inflate(R.menu.bookmarks_databaseview_context_menu, menu);
384
385                 // Set the title.
386                 mode.setTitle(R.string.bookmarks);
387
388                 // Get handles for the menu items.
389                 selectAllMenuItem = menu.findItem(R.id.select_all);
390                 deleteMenuItem = menu.findItem(R.id.delete);
391
392                 // Disable the delete menu item if a delete is pending.
393                 deleteMenuItem.setEnabled(!deletingBookmarks);
394
395                 // Make it so.
396                 return true;
397             }
398
399             @Override
400             public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
401                 // Do nothing.
402                 return false;
403             }
404
405             @Override
406             public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
407                 // Calculate the number of selected bookmarks.
408                 int numberOfSelectedBookmarks = bookmarksListView.getCheckedItemCount();
409
410                 // Adjust the ActionMode according to the number of selected bookmarks.
411                 mode.setSubtitle(getString(R.string.selected) + "  " + numberOfSelectedBookmarks);
412
413                 // Do not show the select all menu item if all the bookmarks are already checked.
414                 if (bookmarksListView.getCheckedItemCount() == bookmarksListView.getCount()) {
415                     selectAllMenuItem.setVisible(false);
416                 } else {
417                     selectAllMenuItem.setVisible(true);
418                 }
419
420                 // Convert the database ID to an int.
421                 int databaseId = (int) id;
422
423                 // If a folder was selected, also select all the contents.
424                 if (checked && bookmarksDatabaseHelper.isFolder(databaseId)) {
425                     selectAllBookmarksInFolder(databaseId);
426                 }
427
428                 // Do not allow a bookmark to be deselected if the folder is selected.
429                 if (!checked) {
430                     // Get the folder name.
431                     String folderName = bookmarksDatabaseHelper.getParentFolderName((int) id);
432
433                     // If the bookmark is not in the root folder, check to see if the folder is selected.
434                     if (!folderName.isEmpty()) {
435                         // Get the database ID of the folder.
436                         int folderDatabaseId = bookmarksDatabaseHelper.getFolderDatabaseId(folderName);
437
438                         // Move the bookmarks cursor to the first position.
439                         bookmarksCursor.moveToFirst();
440
441                         // Initialize the folder position variable.
442                         int folderPosition = -1;
443
444                         // Get the position of the folder in the bookmarks cursor.
445                         while ((folderPosition < 0) && (bookmarksCursor.getPosition() < bookmarksCursor.getCount())) {
446                             // Check if the folder database ID matches the bookmark database ID.
447                             if (folderDatabaseId == bookmarksCursor.getInt((bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper._ID)))) {
448                                 // Get the folder position.
449                                 folderPosition = bookmarksCursor.getPosition();
450
451                                 // Check if the folder is selected.
452                                 if (bookmarksListView.isItemChecked(folderPosition)) {
453                                     // Reselect the bookmark.
454                                     bookmarksListView.setItemChecked(position, true);
455
456                                     // Display a snackbar explaining why the bookmark cannot be deselected.
457                                     Snackbar.make(bookmarksListView, R.string.cannot_deselect_bookmark, Snackbar.LENGTH_LONG).show();
458                                 }
459                             }
460
461                             // Increment the bookmarks cursor.
462                             bookmarksCursor.moveToNext();
463                         }
464                     }
465                 }
466             }
467
468             @Override
469             public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
470                 switch (item.getItemId()) {
471                     case R.id.select_all:
472                         // Get the total number of bookmarks.
473                         int numberOfBookmarks = bookmarksListView.getCount();
474
475                         // Select them all.
476                         for (int i = 0; i < numberOfBookmarks; i++) {
477                             bookmarksListView.setItemChecked(i, true);
478                         }
479                         break;
480
481                     case R.id.delete:
482                         // Set the deleting bookmarks flag, which prevents the delete menu item from being enabled until the current process finishes.
483                         deletingBookmarks = true;
484
485                         // Get an array of the selected row IDs.
486                         long[] selectedBookmarksIdsLongArray = bookmarksListView.getCheckedItemIds();
487
488                         // Get an array of checked bookmarks.  `.clone()` makes a copy that won't change if the list view is reloaded, which is needed for re-selecting the bookmarks on undelete.
489                         SparseBooleanArray selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions().clone();
490
491                         // Update the bookmarks cursor with the current contents of the bookmarks database except for the specified database IDs.
492                         switch (currentFolderDatabaseId) {
493                             // Get a cursor with all the folders.
494                             case ALL_FOLDERS_DATABASE_ID:
495                                 if (sortByDisplayOrder) {
496                                     bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksByDisplayOrderExcept(selectedBookmarksIdsLongArray);
497                                 } else {
498                                     bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksExcept(selectedBookmarksIdsLongArray);
499                                 }
500                                 break;
501
502                             // Get a cursor for the home folder.
503                             case HOME_FOLDER_DATABASE_ID:
504                                 if (sortByDisplayOrder) {
505                                     bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrderExcept(selectedBookmarksIdsLongArray, "");
506                                 } else {
507                                     bookmarksCursor = bookmarksDatabaseHelper.getBookmarksExcept(selectedBookmarksIdsLongArray, "");
508                                 }
509                                 break;
510
511                             // Display the selected folder.
512                             default:
513                                 // Get a cursor for the selected folder.
514                                 if (sortByDisplayOrder) {
515                                     bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrderExcept(selectedBookmarksIdsLongArray, currentFolderName);
516                                 } else {
517                                     bookmarksCursor = bookmarksDatabaseHelper.getBookmarksExcept(selectedBookmarksIdsLongArray, currentFolderName);
518                                 }
519                         }
520
521                         // Update the list view.
522                         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
523
524                         // Create a Snackbar with the number of deleted bookmarks.
525                         bookmarksDeletedSnackbar = Snackbar.make(findViewById(R.id.bookmarks_databaseview_coordinatorlayout),
526                                 getString(R.string.bookmarks_deleted) + "  " + selectedBookmarksIdsLongArray.length, Snackbar.LENGTH_LONG)
527                                 .setAction(R.string.undo, view -> {
528                                     // Do nothing because everything will be handled by `onDismissed()` below.
529                                 })
530                                 .addCallback(new Snackbar.Callback() {
531                                     @SuppressLint("SwitchIntDef")  // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
532                                     @Override
533                                     public void onDismissed(Snackbar snackbar, int event) {
534                                         if (event == Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The user pushed the undo button.
535                                             // Update the bookmarks list view with the current contents of the bookmarks database, including the "deleted bookmarks.
536                                             updateBookmarksListView();
537
538                                             // Re-select the previously selected bookmarks.
539                                             for (int i = 0; i < selectedBookmarksPositionsSparseBooleanArray.size(); i++) {
540                                                 bookmarksListView.setItemChecked(selectedBookmarksPositionsSparseBooleanArray.keyAt(i), true);
541                                             }
542                                         } else {  // The Snackbar was dismissed without the undo button being pushed.
543                                             // Delete each selected bookmark.
544                                             for (long databaseIdLong : selectedBookmarksIdsLongArray) {
545                                                 // Convert `databaseIdLong` to an int.
546                                                 int databaseIdInt = (int) databaseIdLong;
547
548                                                 // Delete the selected bookmark.
549                                                 bookmarksDatabaseHelper.deleteBookmark(databaseIdInt);
550                                             }
551                                         }
552
553                                         // Reset the deleting bookmarks flag.
554                                         deletingBookmarks = false;
555
556                                         // Enable the delete menu item.
557                                         deleteMenuItem.setEnabled(true);
558
559                                         // Close the activity if back has been pressed.
560                                         if (closeActivityAfterDismissingSnackbar) {
561                                             onBackPressed();
562                                         }
563                                     }
564                                 });
565
566                         // Show the Snackbar.
567                         bookmarksDeletedSnackbar.show();
568                         break;
569                 }
570
571                 // Consume the click.
572                 return false;
573             }
574
575             @Override
576             public void onDestroyActionMode(ActionMode mode) {
577                 // Do nothing.
578             }
579         });
580     }
581
582     @Override
583     public boolean onCreateOptionsMenu(Menu menu) {
584         // Inflate the menu.
585         getMenuInflater().inflate(R.menu.bookmarks_databaseview_options_menu, menu);
586
587         // Success.
588         return true;
589     }
590
591     @Override
592     public boolean onOptionsItemSelected(MenuItem menuItem) {
593         // Get a handle for the shared preferences.
594         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
595
596         // Get the theme preferences.
597         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
598
599         // Get the ID of the menu item that was selected.
600         int menuItemId = menuItem.getItemId();
601
602         // Run the command that corresponds to the selected menu item.
603         switch (menuItemId) {
604             case android.R.id.home:  // The home arrow is identified as `android.R.id.home`, not just `R.id.home`.
605                 // Exit the activity.
606                 onBackPressed();
607                 break;
608
609             case R.id.options_menu_sort:
610                 // Update the sort by display order tracker.
611                 sortByDisplayOrder = !sortByDisplayOrder;
612
613                 // Get a handle for the bookmarks `ListView`.
614                 ListView bookmarksListView = findViewById(R.id.bookmarks_databaseview_listview);
615
616                 // Update the icon and display a snackbar.
617                 if (sortByDisplayOrder) {  // Sort by display order.
618                     // Update the icon according to the theme.
619                     if (darkTheme) {
620                         menuItem.setIcon(R.drawable.sort_selected_dark);
621                     } else {
622                         menuItem.setIcon(R.drawable.sort_selected_light);
623                     }
624
625                     // Display a Snackbar indicating the current sort type.
626                     Snackbar.make(bookmarksListView, R.string.sorted_by_display_order, Snackbar.LENGTH_SHORT).show();
627                 } else {  // Sort by database id.
628                     // Update the icon according to the theme.
629                     if (darkTheme) {
630                         menuItem.setIcon(R.drawable.sort_dark);
631                     } else {
632                         menuItem.setIcon(R.drawable.sort_light);
633                     }
634
635                     // Display a Snackbar indicating the current sort type.
636                     Snackbar.make(bookmarksListView, R.string.sorted_by_database_id, Snackbar.LENGTH_SHORT).show();
637                 }
638
639                 // Update the list view.
640                 updateBookmarksListView();
641                 break;
642         }
643         return true;
644     }
645
646     @Override
647     public void onBackPressed() {
648         // Check to see if a snackbar is currently displayed.  If so, it must be closed before existing so that a pending delete is completed before reloading the list view in the bookmarks activity.
649         if ((bookmarksDeletedSnackbar != null) && bookmarksDeletedSnackbar.isShown()) { // Close the bookmarks deleted snackbar before going home.
650             // Set the close flag.
651             closeActivityAfterDismissingSnackbar = true;
652
653             // Dismiss the snackbar.
654             bookmarksDeletedSnackbar.dismiss();
655         } else {  // Go home immediately.
656             // Update the current folder in the bookmarks activity.
657             if ((currentFolderDatabaseId == ALL_FOLDERS_DATABASE_ID) || (currentFolderDatabaseId == HOME_FOLDER_DATABASE_ID)) {  // All folders or the the home folder are currently displayed.
658                 // Load the home folder.
659                 BookmarksActivity.currentFolder = "";
660             } else {  // A subfolder is currently displayed.
661                 // Load the current folder.
662                 BookmarksActivity.currentFolder = currentFolderName;
663             }
664
665             // Reload the bookmarks list view when returning to the bookmarks activity.
666             BookmarksActivity.restartFromBookmarksDatabaseViewActivity = true;
667
668             // Exit the bookmarks database view activity.
669             super.onBackPressed();
670         }
671     }
672
673     private void updateBookmarksListView() {
674         // Populate the bookmarks list view based on the spinner selection.
675         switch (currentFolderDatabaseId) {
676             // Get a cursor with all the folders.
677             case ALL_FOLDERS_DATABASE_ID:
678                 if (sortByDisplayOrder) {
679                     bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksByDisplayOrder();
680                 } else {
681                     bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarks();
682                 }
683                 break;
684
685             // Get a cursor for the home folder.
686             case HOME_FOLDER_DATABASE_ID:
687                 if (sortByDisplayOrder) {
688                     bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder("");
689                 } else {
690                     bookmarksCursor = bookmarksDatabaseHelper.getBookmarks("");
691                 }
692                 break;
693
694             // Display the selected folder.
695             default:
696                 // Get a cursor for the selected folder.
697                 if (sortByDisplayOrder) {
698                     bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolderName);
699                 } else {
700                     bookmarksCursor = bookmarksDatabaseHelper.getBookmarks(currentFolderName);
701                 }
702         }
703
704         // Update the list view.
705         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
706     }
707
708     private void selectAllBookmarksInFolder(int folderId) {
709         // Get a handle for the bookmarks list view.
710         ListView bookmarksListView = findViewById(R.id.bookmarks_databaseview_listview);
711
712         // Get the folder name.
713         String folderName = bookmarksDatabaseHelper.getFolderName(folderId);
714
715         // Get a cursor with the contents of the folder.
716         Cursor folderCursor = bookmarksDatabaseHelper.getBookmarks(folderName);
717
718         // Move to the beginning of the cursor.
719         folderCursor.moveToFirst();
720
721         while (folderCursor.getPosition() < folderCursor.getCount()) {
722             // Get the bookmark database ID.
723             int bookmarkId = folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID));
724
725             // Move the bookmarks cursor to the first position.
726             bookmarksCursor.moveToFirst();
727
728             // Initialize the bookmark position variable.
729             int bookmarkPosition = -1;
730
731             // Get the position of this bookmark in the bookmarks cursor.
732             while ((bookmarkPosition < 0) && (bookmarksCursor.getPosition() < bookmarksCursor.getCount())) {
733                 // Check if the bookmark IDs match.
734                 if (bookmarkId == bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper._ID))) {
735                     // Get the bookmark position.
736                     bookmarkPosition = bookmarksCursor.getPosition();
737
738                     // If this bookmark is a folder, select all the bookmarks inside it.
739                     if (bookmarksDatabaseHelper.isFolder(bookmarkId)) {
740                         selectAllBookmarksInFolder(bookmarkId);
741                     }
742
743                     // Select the bookmark.
744                     bookmarksListView.setItemChecked(bookmarkPosition, true);
745                 }
746
747                 // Increment the bookmarks cursor position.
748                 bookmarksCursor.moveToNext();
749             }
750
751             // Move to the next position.
752             folderCursor.moveToNext();
753         }
754     }
755
756     @Override
757     public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, @NonNull Bitmap favoriteIconBitmap) {
758         // Get the dialog from the dialog fragment.
759         Dialog dialog = dialogFragment.getDialog();
760
761         // Remove the incorrect lint warning below that the dialog might be null.
762         assert dialog != null;
763
764         // Get handles for the views from dialog fragment.
765         RadioButton currentBookmarkIconRadioButton = dialog.findViewById(R.id.edit_bookmark_current_icon_radiobutton);
766         EditText editBookmarkNameEditText = dialog.findViewById(R.id.edit_bookmark_name_edittext);
767         EditText editBookmarkUrlEditText = dialog.findViewById(R.id.edit_bookmark_url_edittext);
768         Spinner folderSpinner = dialog.findViewById(R.id.edit_bookmark_folder_spinner);
769         EditText displayOrderEditText = dialog.findViewById(R.id.edit_bookmark_display_order_edittext);
770
771         // Extract the bookmark information.
772         String bookmarkNameString = editBookmarkNameEditText.getText().toString();
773         String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
774         int folderDatabaseId = (int) folderSpinner.getSelectedItemId();
775         int displayOrderInt = Integer.parseInt(displayOrderEditText.getText().toString());
776
777         // Instantiate the parent folder name `String`.
778         String parentFolderNameString;
779
780         // Set the parent folder name.
781         if (folderDatabaseId == HOME_FOLDER_DATABASE_ID) {  // The home folder is selected.  Use `""`.
782             parentFolderNameString = "";
783         } else {  // Get the parent folder name from the database.
784             parentFolderNameString = bookmarksDatabaseHelper.getFolderName(folderDatabaseId);
785         }
786
787         // Update the bookmark.
788         if (currentBookmarkIconRadioButton.isChecked()) {  // Update the bookmark without changing the favorite icon.
789             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, parentFolderNameString, displayOrderInt);
790         } else {  // Update the bookmark using the `WebView` favorite icon.
791             // Create a favorite icon byte array output stream.
792             ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
793
794             // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
795             favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
796
797             // Convert the favorite icon byte array stream to a byte array.
798             byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
799
800             //  Update the bookmark and the favorite icon.
801             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, parentFolderNameString, displayOrderInt, newFavoriteIconByteArray);
802         }
803
804         // Update the list view.
805         updateBookmarksListView();
806     }
807
808     @Override
809     public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) {
810         // Get the dialog from the dialog fragment.
811         Dialog dialog = dialogFragment.getDialog();
812
813         // Remove the incorrect lint warning below that the dialog might be null.
814         assert dialog != null;
815
816         // Get handles for the views from dialog fragment.
817         RadioButton currentBookmarkIconRadioButton = dialog.findViewById(R.id.edit_folder_current_icon_radiobutton);
818         RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_default_icon_radiobutton);
819         ImageView defaultFolderIconImageView = dialog.findViewById(R.id.edit_folder_default_icon_imageview);
820         EditText editBookmarkNameEditText = dialog.findViewById(R.id.edit_folder_name_edittext);
821         Spinner parentFolderSpinner = dialog.findViewById(R.id.edit_folder_parent_folder_spinner);
822         EditText displayOrderEditText = dialog.findViewById(R.id.edit_folder_display_order_edittext);
823
824         // Extract the folder information.
825         String newFolderNameString = editBookmarkNameEditText.getText().toString();
826         int parentFolderDatabaseId = (int) parentFolderSpinner.getSelectedItemId();
827         int displayOrderInt = Integer.parseInt(displayOrderEditText.getText().toString());
828
829         // Instantiate the parent folder name `String`.
830         String parentFolderNameString;
831
832         // Set the parent folder name.
833         if (parentFolderDatabaseId == HOME_FOLDER_DATABASE_ID) {  // The home folder is selected.  Use `""`.
834             parentFolderNameString = "";
835         } else {  // Get the parent folder name from the database.
836             parentFolderNameString = bookmarksDatabaseHelper.getFolderName(parentFolderDatabaseId);
837         }
838
839         // Update the folder.
840         if (currentBookmarkIconRadioButton.isChecked()) {  // Update the folder without changing the favorite icon.
841             bookmarksDatabaseHelper.updateFolder(selectedBookmarkDatabaseId, oldFolderNameString, newFolderNameString, parentFolderNameString, displayOrderInt);
842         } else {  // Update the folder and the icon.
843             // Create the new folder icon Bitmap.
844             Bitmap folderIconBitmap;
845
846             // Populate the new folder icon bitmap.
847             if (defaultFolderIconRadioButton.isChecked()) {
848                 // Get the default folder icon drawable.
849                 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
850
851                 // Convert the folder icon drawable to a bitmap drawable.
852                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
853
854                 // Convert the folder icon bitmap drawable to a bitmap.
855                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
856             } else {  // Use the `WebView` favorite icon.
857                 // Get a copy of the favorite icon bitmap.
858                 folderIconBitmap = favoriteIconBitmap;
859             }
860
861             // Create a folder icon byte array output stream.
862             ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
863
864             // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
865             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
866
867             // Convert the folder icon byte array stream to a byte array.
868             byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
869
870             //  Update the folder and the icon.
871             bookmarksDatabaseHelper.updateFolder(selectedBookmarkDatabaseId, oldFolderNameString, newFolderNameString, parentFolderNameString, displayOrderInt, newFolderIconByteArray);
872         }
873
874         // Update the list view.
875         updateBookmarksListView();
876     }
877
878     @Override
879     public void onDestroy() {
880         // Close the bookmarks cursor and database.
881         bookmarksCursor.close();
882         bookmarksDatabaseHelper.close();
883
884         // Run the default commands.
885         super.onDestroy();
886     }
887 }