]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/BookmarksActivity.java
Make SSL errors tab aware.
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / activities / BookmarksActivity.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.app.Activity;
24 import android.content.Context;
25 import android.content.Intent;
26 import android.content.SharedPreferences;
27 import android.database.Cursor;
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.preference.PreferenceManager;
35 import android.util.SparseBooleanArray;
36 import android.view.ActionMode;
37 import android.view.Menu;
38 import android.view.MenuItem;
39 import android.view.View;
40 import android.view.ViewGroup;
41 import android.view.WindowManager;
42 import android.widget.AbsListView;
43 import android.widget.CursorAdapter;
44 import android.widget.EditText;
45 import android.widget.ImageView;
46 import android.widget.ListView;
47 import android.widget.RadioButton;
48 import android.widget.TextView;
49
50 import androidx.appcompat.app.ActionBar;
51 import androidx.appcompat.app.AppCompatActivity;
52 import androidx.appcompat.widget.Toolbar;  // The AndroidX toolbar must be used until the minimum API is >= 21.
53 import androidx.core.app.NavUtils;
54 import androidx.fragment.app.DialogFragment;
55
56 import com.google.android.material.floatingactionbutton.FloatingActionButton;
57 import com.google.android.material.snackbar.Snackbar;
58
59 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
60 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
61 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
62 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
63 import com.stoutner.privacybrowser.dialogs.MoveToFolderDialog;
64 import com.stoutner.privacybrowser.R;
65 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
66
67 import java.io.ByteArrayOutputStream;
68
69 public class BookmarksActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener, EditBookmarkDialog.EditBookmarkListener,
70         EditBookmarkFolderDialog.EditBookmarkFolderListener, MoveToFolderDialog.MoveToFolderListener {
71
72     // `currentFolder` is public static so it can be accessed from `MoveToFolderDialog` and `BookmarksDatabaseViewActivity`.
73     // It is used in `onCreate`, `onOptionsItemSelected()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveBookmark()`, `onSaveBookmarkFolder()`, `onMoveToFolder()`,
74     // and `loadFolder()`.
75     public static String currentFolder;
76
77     // `checkedItemIds` is public static so it can be accessed from `MoveToFolderDialog`.  It is also used in `onCreate()`, `onSaveBookmark()`, `onSaveBookmarkFolder()`, `onMoveToFolder()`,
78     // and `updateMoveIcons()`.
79     public static long[] checkedItemIds;
80
81     // `restartFromBookmarksDatabaseViewActivity` is public static so it can be accessed from `BookmarksDatabaseViewActivity`.  It is also used in `onRestart()`.
82     public static boolean restartFromBookmarksDatabaseViewActivity;
83
84
85     // `bookmarksDatabaseHelper` is used in `onCreate()`, `onOptionsItemSelected()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveBookmark()`, `onSaveBookmarkFolder()`,
86     // `onMoveToFolder()`, `deleteBookmarkFolderContents()`, `loadFolder()`, and `onDestroy()`.
87     private BookmarksDatabaseHelper bookmarksDatabaseHelper;
88
89     // `bookmarksListView` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveBookmark()`, `onSaveBookmarkFolder()`, `onMoveToFolder()`,
90     // `updateMoveIcons()`, `scrollBookmarks()`, and `loadFolder()`.
91     private ListView bookmarksListView;
92
93     // `bookmarksCursor` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveBookmark()`, `onSaveBookmarkFolder()`, `onMoveToFolder()`, `deleteBookmarkFolderContents()`,
94     // `loadFolder()`, and `onDestroy()`.
95     private Cursor bookmarksCursor;
96
97     // `bookmarksCursorAdapter` is used in `onCreate(), `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveBookmark()`, `onSaveBookmarkFolder()`, `onMoveToFolder()`, and `onLoadFolder()`.
98     private CursorAdapter bookmarksCursorAdapter;
99
100     // `contextualActionMode` is used in `onCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()` and `onMoveToFolder()`.
101     private ActionMode contextualActionMode;
102
103     // `appBar` is used in `onCreate()` and `loadFolder()`.
104     private ActionBar appBar;
105
106     // `oldFolderName` is used in `onCreate()` and `onSaveBookmarkFolder()`.
107     private String oldFolderNameString;
108
109     // `moveBookmarkUpMenuItem` is used in `onCreate()` and `updateMoveIcons()`.
110     private MenuItem moveBookmarkUpMenuItem;
111
112     // `moveBookmarkDownMenuItem` is used in `onCreate()` and `updateMoveIcons()`.
113     private MenuItem moveBookmarkDownMenuItem;
114
115     // `bookmarksDeletedSnackbar` is used in `onCreate()`, `onOptionsItemSelected()`, and `onBackPressed()`.
116     private Snackbar bookmarksDeletedSnackbar;
117
118     // `closeActivityAfterDismissingSnackbar` is used in `onCreate()`, `onOptionsItemSelected()`, and `onBackPressed()`.
119     private boolean closeActivityAfterDismissingSnackbar;
120
121     // The favorite icon byte array is populated in `onCreate()` and used in `onOptionsItemSelected()`.
122     private byte[] favoriteIconByteArray;
123
124     @Override
125     protected void onCreate(Bundle savedInstanceState) {
126         // Get a handle for the shared preferences.
127         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
128
129         // Get the theme and screenshot preferences.
130         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
131         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
132
133         // Disable screenshots if not allowed.
134         if (!allowScreenshots) {
135             getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
136         }
137
138         // Set the activity theme.
139         if (darkTheme) {
140             setTheme(R.style.PrivacyBrowserDark_SecondaryActivity);
141         } else {
142             setTheme(R.style.PrivacyBrowserLight_SecondaryActivity);
143         }
144
145         // Run the default commands.
146         super.onCreate(savedInstanceState);
147
148         // Get the intent that launched the activity.
149         Intent launchingIntent = getIntent();
150
151         // Store the current URL and title.
152         String currentUrl = launchingIntent.getStringExtra("current_url");
153         String currentTitle = launchingIntent.getStringExtra("current_title");
154
155         // Set the current folder variable.
156         if (launchingIntent.getStringExtra("current_folder") != null) {  // Set the current folder from the intent.
157             currentFolder = launchingIntent.getStringExtra("current_folder");
158         } else {  // Set the current folder to be `""`, which is the home folder.
159             currentFolder = "";
160         }
161
162         // Get the favorite icon byte array.
163         favoriteIconByteArray = launchingIntent.getByteArrayExtra("favorite_icon_byte_array");
164
165         // Convert the favorite icon byte array to a bitmap.
166         Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
167
168         // Set the content view.
169         setContentView(R.layout.bookmarks_coordinatorlayout);
170
171         // The AndroidX toolbar must be used until the minimum API is >= 21.
172         final Toolbar toolbar = findViewById(R.id.bookmarks_toolbar);
173         setSupportActionBar(toolbar);
174
175         // Get a handle for the activity, the app bar, and the ListView.
176         final Activity bookmarksActivity = this;
177         appBar = getSupportActionBar();
178         bookmarksListView = findViewById(R.id.bookmarks_listview);
179
180         // Remove the incorrect lint warning that `appBar` might be null.
181         assert appBar != null;
182
183         // Display the home arrow on the app bar.
184         appBar.setDisplayHomeAsUpEnabled(true);
185
186         // Initialize the database helper.  `this` specifies the context.  The two `nulls` do not specify the database name or a `CursorFactory`.
187         // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
188         bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
189
190         // Load the home folder.
191         loadFolder();
192
193         // Set a listener so that tapping a list item loads the URL or folder.
194         bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
195             // Convert the id from long to int to match the format of the bookmarks database.
196             int databaseID = (int) id;
197
198             // Get the bookmark cursor for this ID and move it to the first row.
199             Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseID);
200             bookmarkCursor.moveToFirst();
201
202             // Act upon the bookmark according to the type.
203             if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {  // The selected bookmark is a folder.
204                 // Update the current folder.
205                 currentFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
206
207                 // Load the new folder.
208                 loadFolder();
209             } else {  // The selected bookmark is not a folder.
210                 // Get the bookmark URL and assign it to `formattedUrlString`.
211                 MainWebViewActivity.urlToLoadOnRestart = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL));
212
213                 // Set `MainWebViewActivity` to load the new URL on restart.
214                 MainWebViewActivity.loadUrlOnRestart = true;
215
216                 // Update the bookmarks folder for the bookmarks drawer in `MainWebViewActivity`.
217                 MainWebViewActivity.currentBookmarksFolder = currentFolder;
218
219                 // Close the bookmarks drawer and reload the bookmarks `ListView` when returning to `MainWebViewActivity`.
220                 MainWebViewActivity.restartFromBookmarksActivity = true;
221
222                 // Return to `MainWebViewActivity`.
223                 NavUtils.navigateUpFromSameTask(bookmarksActivity);
224             }
225
226             // Close the `Cursor`.
227             bookmarkCursor.close();
228         });
229
230         // Handle long presses on the list view.
231         bookmarksListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
232             // Instantiate the common variables.
233             MenuItem editBookmarkMenuItem;
234             MenuItem deleteBookmarksMenuItem;
235             MenuItem selectAllBookmarksMenuItem;
236             boolean deletingBookmarks;
237
238             @Override
239             public boolean onCreateActionMode(ActionMode mode, Menu menu) {
240                 // Inflate the menu for the contextual app bar.
241                 getMenuInflater().inflate(R.menu.bookmarks_context_menu, menu);
242
243                 // Set the title.
244                 if (currentFolder.isEmpty()) {  // Use `R.string.bookmarks` if in the home folder.
245                     mode.setTitle(R.string.bookmarks);
246                 } else {  // Use the current folder name as the title.
247                     mode.setTitle(currentFolder);
248                 }
249
250                 // Get handles for menu items that need to be selectively disabled.
251                 moveBookmarkUpMenuItem = menu.findItem(R.id.move_bookmark_up);
252                 moveBookmarkDownMenuItem = menu.findItem(R.id.move_bookmark_down);
253                 editBookmarkMenuItem = menu.findItem(R.id.edit_bookmark);
254                 deleteBookmarksMenuItem = menu.findItem(R.id.delete_bookmark);
255                 selectAllBookmarksMenuItem = menu.findItem(R.id.context_menu_select_all_bookmarks);
256
257                 // Disable the delete bookmarks menu item if a delete is pending.
258                 deleteBookmarksMenuItem.setEnabled(!deletingBookmarks);
259
260                 // Store a handle for the contextual action mode so it can be closed programatically.
261                 contextualActionMode = mode;
262
263                 // Make it so.
264                 return true;
265             }
266
267             @Override
268             public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
269                 // Get a handle for the move to folder menu item.
270                 MenuItem moveToFolderMenuItem = menu.findItem(R.id.move_to_folder);
271
272                 // Get a Cursor with all of the folders.
273                 Cursor folderCursor = bookmarksDatabaseHelper.getAllFolders();
274
275                 // Enable the move to folder menu item if at least one folder exists.
276                 moveToFolderMenuItem.setVisible(folderCursor.getCount() > 0);
277
278                 // Make it so.
279                 return true;
280             }
281
282             @Override
283             public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
284                 // Get the number of selected bookmarks.
285                 int numberOfSelectedBookmarks = bookmarksListView.getCheckedItemCount();
286
287                 // Adjust the ActionMode and the menu according to the number of selected bookmarks.
288                 if (numberOfSelectedBookmarks == 1) {  // One bookmark is selected.
289                     // List the number of selected bookmarks in the subtitle.
290                     mode.setSubtitle(getString(R.string.selected) + "  1");
291
292                     // Show the `Move Up`, `Move Down`, and  `Edit` options.
293                     moveBookmarkUpMenuItem.setVisible(true);
294                     moveBookmarkDownMenuItem.setVisible(true);
295                     editBookmarkMenuItem.setVisible(true);
296
297                     // Update the enabled status of the move icons.
298                     updateMoveIcons();
299                 } else {  // More than one bookmark is selected.
300                     // List the number of selected bookmarks in the subtitle.
301                     mode.setSubtitle(getString(R.string.selected) + "  " + numberOfSelectedBookmarks);
302
303                     // Hide non-applicable `MenuItems`.
304                     moveBookmarkUpMenuItem.setVisible(false);
305                     moveBookmarkDownMenuItem.setVisible(false);
306                     editBookmarkMenuItem.setVisible(false);
307                 }
308
309                 // Do not show the select all menu item if all the bookmarks are already checked.
310                 if (bookmarksListView.getCheckedItemCount() == bookmarksListView.getCount()) {
311                     selectAllBookmarksMenuItem.setVisible(false);
312                 } else {
313                     selectAllBookmarksMenuItem.setVisible(true);
314                 }
315             }
316
317             @Override
318             public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
319                 // Instantiate the common variables.
320                 int selectedBookmarkPosition;
321                 int selectedBookmarkNewPosition;
322                 final SparseBooleanArray selectedBookmarksPositionsSparseBooleanArray;
323
324                 switch (item.getItemId()) {
325                     case R.id.move_bookmark_up:
326                         // Get the array of checked bookmark positions.
327                         selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
328
329                         // Store the position of the selected bookmark.  Only one bookmark is selected when `move_bookmark_up` is enabled.
330                         selectedBookmarkPosition = selectedBookmarksPositionsSparseBooleanArray.keyAt(0);
331
332                         // Calculate the new position of the selected bookmark.
333                         selectedBookmarkNewPosition = selectedBookmarkPosition - 1;
334
335                         // Iterate through the bookmarks.
336                         for (int i = 0; i < bookmarksListView.getCount(); i++) {
337                             // Get the database ID for the current bookmark.
338                             int currentBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i);
339
340                             // Update the display order for the current bookmark.
341                             if (i == selectedBookmarkPosition) {  // The current bookmark is the selected bookmark.
342                                 // Move the current bookmark up one.
343                                 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i - 1);
344                             } else if ((i + 1) == selectedBookmarkPosition){  // The current bookmark is immediately above the selected bookmark.
345                                 // Move the current bookmark down one.
346                                 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i + 1);
347                             } else {  // The current bookmark is not changing positions.
348                                 // Move `bookmarksCursor` to the current bookmark position.
349                                 bookmarksCursor.moveToPosition(i);
350
351                                 // Update the display order only if it is not correct in the database.
352                                 if (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER)) != i) {
353                                     bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i);
354                                 }
355                             }
356                         }
357
358                         // Update the bookmarks cursor with the current contents of the bookmarks database.
359                         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolder);
360
361                         // Update the `ListView`.
362                         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
363
364                         // Scroll with the bookmark.
365                         scrollBookmarks(selectedBookmarkNewPosition);
366
367                         // Update the enabled status of the move icons.
368                         updateMoveIcons();
369                         break;
370
371                     case R.id.move_bookmark_down:
372                         // Get the array of checked bookmark positions.
373                         selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
374
375                         // Store the position of the selected bookmark.  Only one bookmark is selected when `move_bookmark_down` is enabled.
376                         selectedBookmarkPosition = selectedBookmarksPositionsSparseBooleanArray.keyAt(0);
377
378                         // Calculate the new position of the selected bookmark.
379                         selectedBookmarkNewPosition = selectedBookmarkPosition + 1;
380
381                         // Iterate through the bookmarks.
382                         for (int i = 0; i <bookmarksListView.getCount(); i++) {
383                             // Get the database ID for the current bookmark.
384                             int currentBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i);
385
386                             // Update the display order for the current bookmark.
387                             if (i == selectedBookmarkPosition) {  // The current bookmark is the selected bookmark.
388                                 // Move the current bookmark down one.
389                                 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i + 1);
390                             } else if ((i - 1) == selectedBookmarkPosition) {  // The current bookmark is immediately below the selected bookmark.
391                                 // Move the bookmark below the selected bookmark up one.
392                                 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i - 1);
393                             } else {  // The current bookmark is not changing positions.
394                                 // Move `bookmarksCursor` to the current bookmark position.
395                                 bookmarksCursor.moveToPosition(i);
396
397                                 // Update the display order only if it is not correct in the database.
398                                 if (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER)) != i) {
399                                     bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i);
400                                 }
401                             }
402                         }
403
404                         // Update the bookmarks cursor with the current contents of the bookmarks database.
405                         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolder);
406
407                         // Update the `ListView`.
408                         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
409
410                         // Scroll with the bookmark.
411                         scrollBookmarks(selectedBookmarkNewPosition);
412
413                         // Update the enabled status of the move icons.
414                         updateMoveIcons();
415                         break;
416
417                     case R.id.move_to_folder:
418                         // Store `checkedItemIds` for use by the `AlertDialog`.
419                         checkedItemIds = bookmarksListView.getCheckedItemIds();
420
421                         // Show the `MoveToFolderDialog` `AlertDialog` and name the instance `@string/move_to_folder
422                         DialogFragment moveToFolderDialog = new MoveToFolderDialog();
423                         moveToFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.move_to_folder));
424                         break;
425
426                     case R.id.edit_bookmark:
427                         // Get the array of checked bookmark positions.
428                         selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
429
430                         // Get the position of the selected bookmark.  Only one bookmark is selected when `edit_bookmark_down` is enabled.
431                         selectedBookmarkPosition = selectedBookmarksPositionsSparseBooleanArray.keyAt(0);
432
433                         // Move the `Cursor` to the selected position and find out if it is a folder.
434                         bookmarksCursor.moveToPosition(selectedBookmarkPosition);
435                         boolean isFolder = (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1);
436
437                         // Get the selected bookmark database ID.
438                         int databaseId = bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper._ID));
439
440                         // Show the edit bookmark or edit bookmark folder dialog.
441                         if (isFolder) {
442                             // Save the current folder name, which is used in `onSaveBookmarkFolder()`.
443                             oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
444
445                             // Show the edit bookmark folder dialog.
446                             DialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, favoriteIconBitmap);
447                             editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
448                         } else {
449                             // Show the edit bookmark dialog.
450                             DialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId, favoriteIconBitmap);
451                             editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
452                         }
453                         break;
454
455                     case R.id.delete_bookmark:
456                         // Set the deleting bookmarks flag, which prevents the delete menu item from being enabled until the current process finishes.
457                         deletingBookmarks = true;
458
459                         // Get an array of the selected row IDs.
460                         final long[] selectedBookmarksIdsLongArray = bookmarksListView.getCheckedItemIds();
461
462                         // 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.
463                         selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions().clone();
464
465                         // Update the bookmarks cursor with the current contents of the bookmarks database except for the specified database IDs.
466                         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrderExcept(selectedBookmarksIdsLongArray, currentFolder);
467
468                         // Update the list view.
469                         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
470
471                         // Show a Snackbar with the number of deleted bookmarks.
472                         bookmarksDeletedSnackbar = Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), getString(R.string.bookmarks_deleted) + "  " + selectedBookmarksIdsLongArray.length,
473                                 Snackbar.LENGTH_LONG)
474                                 .setAction(R.string.undo, view -> {
475                                     // Do nothing because everything will be handled by `onDismissed()` below.
476                                 })
477                                 .addCallback(new Snackbar.Callback() {
478                                     @SuppressLint("SwitchIntDef")  // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
479                                     @Override
480                                     public void onDismissed(Snackbar snackbar, int event) {
481                                         if (event == Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The user pushed the undo button.
482                                             // Update the bookmarks cursor with the current contents of the bookmarks database, including the "deleted" bookmarks.
483                                             bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolder);
484
485                                             // Update the list view.
486                                             bookmarksCursorAdapter.changeCursor(bookmarksCursor);
487
488                                             // Re-select the previously selected bookmarks.
489                                             for (int i = 0; i < selectedBookmarksPositionsSparseBooleanArray.size(); i++) {
490                                                 bookmarksListView.setItemChecked(selectedBookmarksPositionsSparseBooleanArray.keyAt(i), true);
491                                             }
492                                         } else {  // The snackbar was dismissed without the undo button being pushed.
493                                             // Delete each selected bookmark.
494                                             for (long databaseIdLong : selectedBookmarksIdsLongArray) {
495                                                 // Convert `databaseIdLong` to an int.
496                                                 int databaseIdInt = (int) databaseIdLong;
497
498                                                 // Delete the contents of the folder if the selected bookmark is a folder.
499                                                 if (bookmarksDatabaseHelper.isFolder(databaseIdInt)) {
500                                                     deleteBookmarkFolderContents(databaseIdInt);
501                                                 }
502
503                                                 // Delete the selected bookmark.
504                                                 bookmarksDatabaseHelper.deleteBookmark(databaseIdInt);
505                                             }
506
507                                             // Update the display order.
508                                             for (int i = 0; i < bookmarksListView.getCount(); i++) {
509                                                 // Get the database ID for the current bookmark.
510                                                 int currentBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i);
511
512                                                 // Move `bookmarksCursor` to the current bookmark position.
513                                                 bookmarksCursor.moveToPosition(i);
514
515                                                 // Update the display order only if it is not correct in the database.
516                                                 if (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER)) != i) {
517                                                     bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i);
518                                                 }
519                                             }
520                                         }
521
522                                         // Reset the deleting bookmarks flag.
523                                         deletingBookmarks = false;
524
525                                         // Enable the delete bookmarks menu item.
526                                         deleteBookmarksMenuItem.setEnabled(true);
527
528                                         // Close the activity if back has been pressed.
529                                         if (closeActivityAfterDismissingSnackbar) {
530                                             onBackPressed();
531                                         }
532                                     }
533                                 });
534
535                         //Show the Snackbar.
536                         bookmarksDeletedSnackbar.show();
537                         break;
538
539                     case R.id.context_menu_select_all_bookmarks:
540                         // Get the total number of bookmarks.
541                         int numberOfBookmarks = bookmarksListView.getCount();
542
543                         // Select them all.
544                         for (int i = 0; i < numberOfBookmarks; i++) {
545                             bookmarksListView.setItemChecked(i, true);
546                         }
547                         break;
548                 }
549
550                 // Consume the click.
551                 return true;
552             }
553
554             @Override
555             public void onDestroyActionMode(ActionMode mode) {
556                 // Do nothing.
557             }
558         });
559
560         // Get handles for the `FloatingActionButtons`.
561         FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
562         FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
563
564         // Set the create new bookmark folder FAB to display the `AlertDialog`.
565         createBookmarkFolderFab.setOnClickListener(v -> {
566             // Create a create bookmark folder dialog.
567             DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(favoriteIconBitmap);
568
569             // Show the create bookmark folder dialog.
570             createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
571         });
572
573         // Set the create new bookmark FAB to display the `AlertDialog`.
574         createBookmarkFab.setOnClickListener(view -> {
575             // Instantiate the create bookmark dialog.
576             DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentUrl, currentTitle, favoriteIconBitmap);
577
578             // Display the create bookmark dialog.
579             createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
580         });
581     }
582
583     @Override
584     public void onRestart() {
585         // Run the default commands.
586         super.onRestart();
587
588         // Update the list view if returning from the bookmarks database view activity.
589         if (restartFromBookmarksDatabaseViewActivity) {
590             // Load the current folder in the list view.
591             loadFolder();
592
593             // Reset `restartFromBookmarksDatabaseViewActivity`.
594             restartFromBookmarksDatabaseViewActivity = false;
595         }
596     }
597
598     @Override
599     public boolean onCreateOptionsMenu(Menu menu) {
600         // Inflate the menu.
601         getMenuInflater().inflate(R.menu.bookmarks_options_menu, menu);
602
603         // Success.
604         return true;
605     }
606
607     @Override
608     public boolean onOptionsItemSelected(MenuItem menuItem) {
609         switch (menuItem.getItemId()) {
610             case android.R.id.home:  // The home arrow is identified as `android.R.id.home`, not just `R.id.home`.
611                 if (currentFolder.isEmpty()) {  // Currently in the home folder.
612                     // Run the back commands.
613                     onBackPressed();
614                 } else {  // Currently in a subfolder.
615                     // Place the former parent folder in `currentFolder`.
616                     currentFolder = bookmarksDatabaseHelper.getParentFolderName(currentFolder);
617
618                     // Load the new folder.
619                     loadFolder();
620                 }
621                 break;
622
623             case R.id.options_menu_select_all_bookmarks:
624                 // Get the total number of bookmarks.
625                 int numberOfBookmarks = bookmarksListView.getCount();
626
627                 // Select them all.
628                 for (int i = 0; i < numberOfBookmarks; i++) {
629                     bookmarksListView.setItemChecked(i, true);
630                 }
631                 break;
632
633             case R.id.bookmarks_database_view:
634                 // Create an intent to launch the bookmarks database view activity.
635                 Intent bookmarksDatabaseViewIntent = new Intent(this, BookmarksDatabaseViewActivity.class);
636
637                 // Include the favorite icon byte array to the intent.
638                 bookmarksDatabaseViewIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
639
640                 // Make it so.
641                 startActivity(bookmarksDatabaseViewIntent);
642                 break;
643         }
644         return true;
645     }
646
647     @Override
648     public void onBackPressed() {
649         // Check to see if a snackbar is currently displayed.  If so, it must be closed before exiting so that a pending delete is completed before reloading the list view in the bookmarks drawer.
650         if ((bookmarksDeletedSnackbar != null) && bookmarksDeletedSnackbar.isShown()) {  // Close the bookmarks deleted snackbar before going home.
651             // Set the close flag.
652             closeActivityAfterDismissingSnackbar = true;
653
654             // Dismiss the snackbar.
655             bookmarksDeletedSnackbar.dismiss();
656         } else {  // Go home immediately.
657             // Update the bookmarks folder for the bookmarks drawer in the main WebView activity.
658             MainWebViewActivity.currentBookmarksFolder = currentFolder;
659
660             // Close the bookmarks drawer and reload the bookmarks ListView when returning to the main WebView activity.
661             MainWebViewActivity.restartFromBookmarksActivity = true;
662
663             // Exit the bookmarks activity.
664             super.onBackPressed();
665         }
666     }
667
668     @Override
669     public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
670         // Get the views from the dialog fragment.
671         EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
672         EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
673
674         // Extract the strings from the edit texts.
675         String bookmarkNameString = createBookmarkNameEditText.getText().toString();
676         String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
677
678         // Create a favorite icon byte array output stream.
679         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
680
681         // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
682         favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
683
684         // Convert the favorite icon byte array stream to a byte array.
685         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
686
687         // Display the new bookmark below the current items in the (0 indexed) list.
688         int newBookmarkDisplayOrder = bookmarksListView.getCount();
689
690         // Create the bookmark.
691         bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
692
693         // Update the bookmarks cursor with the current contents of this folder.
694         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolder);
695
696         // Update the `ListView`.
697         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
698
699         // Scroll to the new bookmark.
700         bookmarksListView.setSelection(newBookmarkDisplayOrder);
701     }
702
703     @Override
704     public void onCreateBookmarkFolder(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
705         // Get handles for the views in the dialog fragment.
706         EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
707         RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
708         ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
709
710         // Get new folder name string.
711         String folderNameString = createFolderNameEditText.getText().toString();
712
713         // Create a folder icon bitmap.
714         Bitmap folderIconBitmap;
715
716         // Set the folder icon bitmap according to the dialog.
717         if (defaultFolderIconRadioButton.isChecked()) {  // Use the default folder icon.
718             // Get the default folder icon drawable.
719             Drawable folderIconDrawable = folderIconImageView.getDrawable();
720
721             // Convert the folder icon drawable to a bitmap drawable.
722             BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
723
724             // Convert the folder icon bitmap drawable to a bitmap.
725             folderIconBitmap = folderIconBitmapDrawable.getBitmap();
726         } else {  // Use the WebView favorite icon.
727             // Copy the favorite icon bitmap to the folder icon bitmap.
728             folderIconBitmap = favoriteIconBitmap;
729         }
730
731         // Create a folder icon byte array output stream.
732         ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
733
734         // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
735         folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
736
737         // Convert the folder icon byte array stream to a byte array.
738         byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
739
740         // Move all the bookmarks down one in the display order.
741         for (int i = 0; i < bookmarksListView.getCount(); i++) {
742             int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
743             bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
744         }
745
746         // Create the folder, which will be placed at the top of the `ListView`.
747         bookmarksDatabaseHelper.createFolder(folderNameString, currentFolder, folderIconByteArray);
748
749         // Update the bookmarks cursor with the current contents of this folder.
750         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolder);
751
752         // Update the `ListView`.
753         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
754
755         // Scroll to the new folder.
756         bookmarksListView.setSelection(0);
757     }
758
759     @Override
760     public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) {
761         // Get handles for the views from `dialogFragment`.
762         EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
763         EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
764         RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
765
766         // Store the bookmark strings.
767         String bookmarkNameString = editBookmarkNameEditText.getText().toString();
768         String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
769
770         // Update the bookmark.
771         if (currentBookmarkIconRadioButton.isChecked()) {  // Update the bookmark without changing the favorite icon.
772             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
773         } else {  // Update the bookmark using the WebView favorite icon.
774             // Create a favorite icon byte array output stream.
775             ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
776
777             // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
778             favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
779
780             // Convert the favorite icon byte array stream to a byte array.
781             byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
782
783             //  Update the bookmark and the favorite icon.
784             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
785         }
786
787         // Close the contextual action mode.
788         contextualActionMode.finish();
789
790         // Update the bookmarks cursor with the contents of the current folder.
791         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolder);
792
793         // Update the `ListView`.
794         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
795     }
796
797     @Override
798     public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap) {
799         // Get handles for the views from `dialogFragment`.
800         RadioButton currentFolderIconRadioButton = 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 editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
804
805         // Get the new folder name.
806         String newFolderNameString = editFolderNameEditText.getText().toString();
807
808         // Check if the favorite icon has changed.
809         if (currentFolderIconRadioButton.isChecked()) {  // Only the name has changed.
810             // Update the name in the database.
811             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
812         } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) {  // Only the icon has changed.
813             // Create the new folder icon Bitmap.
814             Bitmap folderIconBitmap;
815
816             // Populate the new folder icon bitmap.
817             if (defaultFolderIconRadioButton.isChecked()) {
818                 // Get the default folder icon drawable.
819                 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
820
821                 // Convert the folder icon drawable to a bitmap drawable.
822                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
823
824                 // Convert the folder icon bitmap drawable to a bitmap.
825                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
826             } else {  // Use the WebView favorite icon.
827                 // Copy the favorite icon bitmap to the folder icon bitmap.
828                 folderIconBitmap = favoriteIconBitmap;
829             }
830
831             // Create a folder icon byte array output stream.
832             ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
833
834             // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
835             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
836
837             // Convert the folder icon byte array stream to a byte array.
838             byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
839
840             // Update the folder icon in the database.
841             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
842         } else {  // The folder icon and the name have changed.
843             // Instantiate 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                 // Copy the favorite icon bitmap to the folder 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 name and icon in the database.
871             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
872         }
873
874         // Update the bookmarks cursor with the current contents of this folder.
875         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolder);
876
877         // Update the `ListView`.
878         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
879
880         // Close the contextual action mode.
881         contextualActionMode.finish();
882     }
883
884     @Override
885     public void onMoveToFolder(DialogFragment dialogFragment) {
886         // Get a handle for the `ListView` from `dialogFragment`.
887         ListView folderListView = dialogFragment.getDialog().findViewById(R.id.move_to_folder_listview);
888
889         // Store a long array of the selected folders.
890         long[] newFolderLongArray = folderListView.getCheckedItemIds();
891
892         // Get the new folder database ID.  Only one folder will be selected.
893         int newFolderDatabaseId = (int) newFolderLongArray[0];
894
895         // Instantiate `newFolderName`.
896         String newFolderName;
897
898         // Set the new folder name.
899         if (newFolderDatabaseId == 0) {
900             // The new folder is the home folder, represented as `""` in the database.
901             newFolderName = "";
902         } else {
903             // Get the new folder name from the database.
904             newFolderName = bookmarksDatabaseHelper.getFolderName(newFolderDatabaseId);
905         }
906
907         // Get a long array with the the database ID of the selected bookmarks.
908         long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
909
910         // Move each of the selected bookmarks to the new folder.
911         for (long databaseIdLong : selectedBookmarksLongArray) {
912             // Get `databaseIdInt` for each selected bookmark.
913             int databaseIdInt = (int) databaseIdLong;
914
915             // Move the selected bookmark to the new folder.
916             bookmarksDatabaseHelper.moveToFolder(databaseIdInt, newFolderName);
917         }
918
919         // Update the bookmarks cursor with the current contents of this folder.
920         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolder);
921
922         // Update the `ListView`.
923         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
924
925         // Close the contextual app bar.
926         contextualActionMode.finish();
927     }
928
929     private void deleteBookmarkFolderContents(int databaseId) {
930         // Get the name of the folder.
931         String folderName = bookmarksDatabaseHelper.getFolderName(databaseId);
932
933         // Get the contents of the folder.
934         Cursor folderCursor = bookmarksDatabaseHelper.getBookmarkIDs(folderName);
935
936         // Delete each of the bookmarks in the folder.
937         for (int i = 0; i < folderCursor.getCount(); i++) {
938             // Move `folderCursor` to the current row.
939             folderCursor.moveToPosition(i);
940
941             // Get the database ID of the item.
942             int itemDatabaseId = folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID));
943
944             // If this is a folder, recursively delete the contents first.
945             if (bookmarksDatabaseHelper.isFolder(itemDatabaseId)) {
946                 deleteBookmarkFolderContents(itemDatabaseId);
947             }
948
949             // Delete the bookmark.
950             bookmarksDatabaseHelper.deleteBookmark(itemDatabaseId);
951         }
952     }
953
954     private void updateMoveIcons() {
955         // Get a handle for the shared preferences.
956         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
957
958         // Get the theme and screenshot preferences.
959         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
960
961         // Get a long array of the selected bookmarks.
962         long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
963
964         // Get the database IDs for the first, last, and selected bookmarks.
965         int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
966         int firstBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(0);
967         // bookmarksListView is 0 indexed.
968         int lastBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(bookmarksListView.getCount() - 1);
969
970         // Update the move bookmark up `MenuItem`.
971         if (selectedBookmarkDatabaseId == firstBookmarkDatabaseId) {  // The selected bookmark is in the first position.
972             // Disable the move bookmark up `MenuItem`.
973             moveBookmarkUpMenuItem.setEnabled(false);
974
975             //  Set the move bookmark up icon to be ghosted.
976             moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_disabled);
977         } else {  // The selected bookmark is not in the first position.
978             // Enable the move bookmark up `MenuItem`.
979             moveBookmarkUpMenuItem.setEnabled(true);
980
981             // Set the icon according to the theme.
982             if (darkTheme) {
983                 moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_enabled_dark);
984             } else {
985                 moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_enabled_light);
986             }
987         }
988
989         // Update the move bookmark down `MenuItem`.
990         if (selectedBookmarkDatabaseId == lastBookmarkDatabaseId) {  // The selected bookmark is in the last position.
991             // Disable the move bookmark down `MenuItem`.
992             moveBookmarkDownMenuItem.setEnabled(false);
993
994             // Set the move bookmark down icon to be ghosted.
995             moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_disabled);
996         } else {  // The selected bookmark is not in the last position.
997             // Enable the move bookmark down `MenuItem`.
998             moveBookmarkDownMenuItem.setEnabled(true);
999
1000             // Set the icon according to the theme.
1001             if (darkTheme) {
1002                 moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_enabled_dark);
1003             } else {
1004                 moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_enabled_light);
1005             }
1006         }
1007     }
1008
1009     private void scrollBookmarks(int selectedBookmarkPosition) {
1010         // Get the first and last visible bookmark positions.
1011         int firstVisibleBookmarkPosition = bookmarksListView.getFirstVisiblePosition();
1012         int lastVisibleBookmarkPosition = bookmarksListView.getLastVisiblePosition();
1013
1014         // Calculate the number of bookmarks per screen.
1015         int numberOfBookmarksPerScreen = lastVisibleBookmarkPosition - firstVisibleBookmarkPosition;
1016
1017         // Scroll with the moved bookmark if necessary.
1018         if (selectedBookmarkPosition <= firstVisibleBookmarkPosition) {  // The selected bookmark position is at or above the top of the screen.
1019             // Scroll to the selected bookmark position.
1020             bookmarksListView.setSelection(selectedBookmarkPosition);
1021         } else if (selectedBookmarkPosition >= (lastVisibleBookmarkPosition - 1)) {  // The selected bookmark is at or below the bottom of the screen.
1022             // The `-1` handles partial bookmarks displayed at the bottom of the list view.  This command scrolls to display the selected bookmark at the bottom of the screen.
1023             // `+1` assures that the entire bookmark will be displayed in situations where only a partial bookmark fits at the bottom of the list view.
1024             bookmarksListView.setSelection(selectedBookmarkPosition - numberOfBookmarksPerScreen + 1);
1025         }
1026     }
1027
1028     private void loadFolder() {
1029         // Update bookmarks cursor with the contents of the bookmarks database for the current folder.
1030         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolder);
1031
1032         // Setup a `CursorAdapter`.  `this` specifies the `Context`.  `false` disables `autoRequery`.
1033         bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
1034             @Override
1035             public View newView(Context context, Cursor cursor, ViewGroup parent) {
1036                 // Inflate the individual item layout.  `false` does not attach it to the root.
1037                 return getLayoutInflater().inflate(R.layout.bookmarks_activity_item_linearlayout, parent, false);
1038             }
1039
1040             @Override
1041             public void bindView(View view, Context context, Cursor cursor) {
1042                 // Get handles for the views.
1043                 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
1044                 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
1045
1046                 // Get the favorite icon byte array from the `Cursor`.
1047                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
1048
1049                 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
1050                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
1051
1052                 // Display the bitmap in `bookmarkFavoriteIcon`.
1053                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
1054
1055                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
1056                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
1057                 bookmarkNameTextView.setText(bookmarkNameString);
1058
1059                 // Make the font bold for folders.
1060                 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
1061                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
1062                 } else {  // Reset the font to default for normal bookmarks.
1063                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
1064                 }
1065             }
1066         };
1067
1068         // Populate the list view with the adapter.
1069         bookmarksListView.setAdapter(bookmarksCursorAdapter);
1070
1071         // Set the `AppBar` title.
1072         if (currentFolder.isEmpty()) {
1073             appBar.setTitle(R.string.bookmarks);
1074         } else {
1075             appBar.setTitle(currentFolder);
1076         }
1077     }
1078
1079     @Override
1080     public void onDestroy() {
1081         // Close the bookmarks cursor and database.
1082         bookmarksCursor.close();
1083         bookmarksDatabaseHelper.close();
1084
1085         // Run the default commands.
1086         super.onDestroy();
1087     }
1088 }