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