d29e54c4cc6e8b9ddcdfeebabf9ef96d6098a8e8
[PrivacyBrowser.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                                         switch (event) {
482                                             // The user pushed the `Undo` button.
483                                             case Snackbar.Callback.DISMISS_EVENT_ACTION:
484                                                 // Update the bookmarks cursor with the current contents of the bookmarks database, including the "deleted" bookmarks.
485                                                 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolder);
486
487                                                 // Update the list view.
488                                                 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
489
490                                                 // Re-select the previously selected bookmarks.
491                                                 for (int i = 0; i < selectedBookmarksPositionsSparseBooleanArray.size(); i++) {
492                                                     bookmarksListView.setItemChecked(selectedBookmarksPositionsSparseBooleanArray.keyAt(i), true);
493                                                 }
494                                                 break;
495
496                                             // The Snackbar was dismissed without the `Undo` button being pushed.
497                                             default:
498                                                 // Delete each selected bookmark.
499                                                 for (long databaseIdLong : selectedBookmarksIdsLongArray) {
500                                                     // Convert `databaseIdLong` to an int.
501                                                     int databaseIdInt = (int) databaseIdLong;
502
503                                                     // Delete the contents of the folder if the selected bookmark is a folder.
504                                                     if (bookmarksDatabaseHelper.isFolder(databaseIdInt)) {
505                                                         deleteBookmarkFolderContents(databaseIdInt);
506                                                     }
507
508                                                     // Delete the selected bookmark.
509                                                     bookmarksDatabaseHelper.deleteBookmark(databaseIdInt);
510                                                 }
511
512                                                 // Update the display order.
513                                                 for (int i = 0; i < bookmarksListView.getCount(); i++) {
514                                                     // Get the database ID for the current bookmark.
515                                                     int currentBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i);
516
517                                                     // Move `bookmarksCursor` to the current bookmark position.
518                                                     bookmarksCursor.moveToPosition(i);
519
520                                                     // Update the display order only if it is not correct in the database.
521                                                     if (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER)) != i) {
522                                                         bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i);
523                                                     }
524                                                 }
525                                         }
526
527                                         // Reset the deleting bookmarks flag.
528                                         deletingBookmarks = false;
529
530                                         // Enable the delete bookmarks menu item.
531                                         deleteBookmarksMenuItem.setEnabled(true);
532
533                                         // Close the activity if back has been pressed.
534                                         if (closeActivityAfterDismissingSnackbar) {
535                                             onBackPressed();
536                                         }
537                                     }
538                                 });
539
540                         //Show the Snackbar.
541                         bookmarksDeletedSnackbar.show();
542                         break;
543
544                     case R.id.context_menu_select_all_bookmarks:
545                         // Get the total number of bookmarks.
546                         int numberOfBookmarks = bookmarksListView.getCount();
547
548                         // Select them all.
549                         for (int i = 0; i < numberOfBookmarks; i++) {
550                             bookmarksListView.setItemChecked(i, true);
551                         }
552                         break;
553                 }
554
555                 // Consume the click.
556                 return true;
557             }
558
559             @Override
560             public void onDestroyActionMode(ActionMode mode) {
561                 // Do nothing.
562             }
563         });
564
565         // Get handles for the `FloatingActionButtons`.
566         FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
567         FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
568
569         // Set the create new bookmark folder FAB to display the `AlertDialog`.
570         createBookmarkFolderFab.setOnClickListener(v -> {
571             // Create a create bookmark folder dialog.
572             DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(favoriteIconBitmap);
573
574             // Show the create bookmark folder dialog.
575             createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
576         });
577
578         // Set the create new bookmark FAB to display the `AlertDialog`.
579         createBookmarkFab.setOnClickListener(view -> {
580             // Instantiate the create bookmark dialog.
581             DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentUrl, currentTitle, favoriteIconBitmap);
582
583             // Display the create bookmark dialog.
584             createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
585         });
586     }
587
588     @Override
589     public void onRestart() {
590         // Run the default commands.
591         super.onRestart();
592
593         // Update the list view if returning from the bookmarks database view activity.
594         if (restartFromBookmarksDatabaseViewActivity) {
595             // Load the current folder in the list view.
596             loadFolder();
597
598             // Reset `restartFromBookmarksDatabaseViewActivity`.
599             restartFromBookmarksDatabaseViewActivity = false;
600         }
601     }
602
603     @Override
604     public boolean onCreateOptionsMenu(Menu menu) {
605         // Inflate the menu.
606         getMenuInflater().inflate(R.menu.bookmarks_options_menu, menu);
607
608         // Success.
609         return true;
610     }
611
612     @Override
613     public boolean onOptionsItemSelected(MenuItem menuItem) {
614         switch (menuItem.getItemId()) {
615             case android.R.id.home:  // The home arrow is identified as `android.R.id.home`, not just `R.id.home`.
616                 if (currentFolder.isEmpty()) {  // Currently in the home folder.
617                     // Run the back commands.
618                     onBackPressed();
619                 } else {  // Currently in a subfolder.
620                     // Place the former parent folder in `currentFolder`.
621                     currentFolder = bookmarksDatabaseHelper.getParentFolderName(currentFolder);
622
623                     // Load the new folder.
624                     loadFolder();
625                 }
626                 break;
627
628             case R.id.options_menu_select_all_bookmarks:
629                 // Get the total number of bookmarks.
630                 int numberOfBookmarks = bookmarksListView.getCount();
631
632                 // Select them all.
633                 for (int i = 0; i < numberOfBookmarks; i++) {
634                     bookmarksListView.setItemChecked(i, true);
635                 }
636                 break;
637
638             case R.id.bookmarks_database_view:
639                 // Create an intent to launch the bookmarks database view activity.
640                 Intent bookmarksDatabaseViewIntent = new Intent(this, BookmarksDatabaseViewActivity.class);
641
642                 // Include the favorite icon byte array to the intent.
643                 bookmarksDatabaseViewIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
644
645                 // Make it so.
646                 startActivity(bookmarksDatabaseViewIntent);
647                 break;
648         }
649         return true;
650     }
651
652     @Override
653     public void onBackPressed() {
654         // 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.
655         if ((bookmarksDeletedSnackbar != null) && bookmarksDeletedSnackbar.isShown()) {  // Close the bookmarks deleted snackbar before going home.
656             // Set the close flag.
657             closeActivityAfterDismissingSnackbar = true;
658
659             // Dismiss the snackbar.
660             bookmarksDeletedSnackbar.dismiss();
661         } else {  // Go home immediately.
662             // Update the bookmarks folder for the bookmarks drawer in the main WebView activity.
663             MainWebViewActivity.currentBookmarksFolder = currentFolder;
664
665             // Close the bookmarks drawer and reload the bookmarks ListView when returning to the main WebView activity.
666             MainWebViewActivity.restartFromBookmarksActivity = true;
667
668             // Exit the bookmarks activity.
669             super.onBackPressed();
670         }
671     }
672
673     @Override
674     public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
675         // Get the views from the dialog fragment.
676         EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
677         EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
678
679         // Extract the strings from the edit texts.
680         String bookmarkNameString = createBookmarkNameEditText.getText().toString();
681         String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
682
683         // Create a favorite icon byte array output stream.
684         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
685
686         // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
687         favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
688
689         // Convert the favorite icon byte array stream to a byte array.
690         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
691
692         // Display the new bookmark below the current items in the (0 indexed) list.
693         int newBookmarkDisplayOrder = bookmarksListView.getCount();
694
695         // Create the bookmark.
696         bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
697
698         // Update the bookmarks cursor with the current contents of this folder.
699         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolder);
700
701         // Update the `ListView`.
702         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
703
704         // Scroll to the new bookmark.
705         bookmarksListView.setSelection(newBookmarkDisplayOrder);
706     }
707
708     @Override
709     public void onCreateBookmarkFolder(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
710         // Get handles for the views in the dialog fragment.
711         EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
712         RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
713         ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
714
715         // Get new folder name string.
716         String folderNameString = createFolderNameEditText.getText().toString();
717
718         // Create a folder icon bitmap.
719         Bitmap folderIconBitmap;
720
721         // Set the folder icon bitmap according to the dialog.
722         if (defaultFolderIconRadioButton.isChecked()) {  // Use the default folder icon.
723             // Get the default folder icon drawable.
724             Drawable folderIconDrawable = folderIconImageView.getDrawable();
725
726             // Convert the folder icon drawable to a bitmap drawable.
727             BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
728
729             // Convert the folder icon bitmap drawable to a bitmap.
730             folderIconBitmap = folderIconBitmapDrawable.getBitmap();
731         } else {  // Use the WebView favorite icon.
732             // Copy the favorite icon bitmap to the folder icon bitmap.
733             folderIconBitmap = favoriteIconBitmap;
734         }
735
736         // Create a folder icon byte array output stream.
737         ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
738
739         // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
740         folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
741
742         // Convert the folder icon byte array stream to a byte array.
743         byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
744
745         // Move all the bookmarks down one in the display order.
746         for (int i = 0; i < bookmarksListView.getCount(); i++) {
747             int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
748             bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
749         }
750
751         // Create the folder, which will be placed at the top of the `ListView`.
752         bookmarksDatabaseHelper.createFolder(folderNameString, currentFolder, folderIconByteArray);
753
754         // Update the bookmarks cursor with the current contents of this folder.
755         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolder);
756
757         // Update the `ListView`.
758         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
759
760         // Scroll to the new folder.
761         bookmarksListView.setSelection(0);
762     }
763
764     @Override
765     public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) {
766         // Get handles for the views from `dialogFragment`.
767         EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
768         EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
769         RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
770
771         // Store the bookmark strings.
772         String bookmarkNameString = editBookmarkNameEditText.getText().toString();
773         String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
774
775         // Update the bookmark.
776         if (currentBookmarkIconRadioButton.isChecked()) {  // Update the bookmark without changing the favorite icon.
777             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
778         } else {  // Update the bookmark using the WebView favorite icon.
779             // Create a favorite icon byte array output stream.
780             ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
781
782             // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
783             favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
784
785             // Convert the favorite icon byte array stream to a byte array.
786             byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
787
788             //  Update the bookmark and the favorite icon.
789             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
790         }
791
792         // Close the contextual action mode.
793         contextualActionMode.finish();
794
795         // Update the bookmarks cursor with the contents of the current folder.
796         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolder);
797
798         // Update the `ListView`.
799         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
800     }
801
802     @Override
803     public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap) {
804         // Get handles for the views from `dialogFragment`.
805         RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
806         RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
807         ImageView defaultFolderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
808         EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
809
810         // Get the new folder name.
811         String newFolderNameString = editFolderNameEditText.getText().toString();
812
813         // Check if the favorite icon has changed.
814         if (currentFolderIconRadioButton.isChecked()) {  // Only the name has changed.
815             // Update the name in the database.
816             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
817         } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) {  // Only the icon has changed.
818             // Create the new folder icon Bitmap.
819             Bitmap folderIconBitmap;
820
821             // Populate the new folder icon bitmap.
822             if (defaultFolderIconRadioButton.isChecked()) {
823                 // Get the default folder icon drawable.
824                 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
825
826                 // Convert the folder icon drawable to a bitmap drawable.
827                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
828
829                 // Convert the folder icon bitmap drawable to a bitmap.
830                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
831             } else {  // Use the WebView favorite icon.
832                 // Copy the favorite icon bitmap to the folder icon bitmap.
833                 folderIconBitmap = favoriteIconBitmap;
834             }
835
836             // Create a folder icon byte array output stream.
837             ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
838
839             // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
840             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
841
842             // Convert the folder icon byte array stream to a byte array.
843             byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
844
845             // Update the folder icon in the database.
846             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
847         } else {  // The folder icon and the name have changed.
848             // Instantiate the new folder icon `Bitmap`.
849             Bitmap folderIconBitmap;
850
851             // Populate the new folder icon bitmap.
852             if (defaultFolderIconRadioButton.isChecked()) {
853                 // Get the default folder icon drawable.
854                 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
855
856                 // Convert the folder icon drawable to a bitmap drawable.
857                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
858
859                 // Convert the folder icon bitmap drawable to a bitmap.
860                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
861             } else {  // Use the WebView favorite icon.
862                 // Copy the favorite icon bitmap to the folder icon bitmap.
863                 folderIconBitmap = favoriteIconBitmap;
864             }
865
866             // Create a folder icon byte array output stream.
867             ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
868
869             // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
870             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
871
872             // Convert the folder icon byte array stream to a byte array.
873             byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
874
875             // Update the folder name and icon in the database.
876             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
877         }
878
879         // Update the bookmarks cursor with the current contents of this folder.
880         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolder);
881
882         // Update the `ListView`.
883         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
884
885         // Close the contextual action mode.
886         contextualActionMode.finish();
887     }
888
889     @Override
890     public void onMoveToFolder(DialogFragment dialogFragment) {
891         // Get a handle for the `ListView` from `dialogFragment`.
892         ListView folderListView = dialogFragment.getDialog().findViewById(R.id.move_to_folder_listview);
893
894         // Store a long array of the selected folders.
895         long[] newFolderLongArray = folderListView.getCheckedItemIds();
896
897         // Get the new folder database ID.  Only one folder will be selected.
898         int newFolderDatabaseId = (int) newFolderLongArray[0];
899
900         // Instantiate `newFolderName`.
901         String newFolderName;
902
903         // Set the new folder name.
904         if (newFolderDatabaseId == 0) {
905             // The new folder is the home folder, represented as `""` in the database.
906             newFolderName = "";
907         } else {
908             // Get the new folder name from the database.
909             newFolderName = bookmarksDatabaseHelper.getFolderName(newFolderDatabaseId);
910         }
911
912         // Get a long array with the the database ID of the selected bookmarks.
913         long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
914
915         // Move each of the selected bookmarks to the new folder.
916         for (long databaseIdLong : selectedBookmarksLongArray) {
917             // Get `databaseIdInt` for each selected bookmark.
918             int databaseIdInt = (int) databaseIdLong;
919
920             // Move the selected bookmark to the new folder.
921             bookmarksDatabaseHelper.moveToFolder(databaseIdInt, newFolderName);
922         }
923
924         // Update the bookmarks cursor with the current contents of this folder.
925         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolder);
926
927         // Update the `ListView`.
928         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
929
930         // Close the contextual app bar.
931         contextualActionMode.finish();
932     }
933
934     private void deleteBookmarkFolderContents(int databaseId) {
935         // Get the name of the folder.
936         String folderName = bookmarksDatabaseHelper.getFolderName(databaseId);
937
938         // Get the contents of the folder.
939         Cursor folderCursor = bookmarksDatabaseHelper.getBookmarkIDs(folderName);
940
941         // Delete each of the bookmarks in the folder.
942         for (int i = 0; i < folderCursor.getCount(); i++) {
943             // Move `folderCursor` to the current row.
944             folderCursor.moveToPosition(i);
945
946             // Get the database ID of the item.
947             int itemDatabaseId = folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID));
948
949             // If this is a folder, recursively delete the contents first.
950             if (bookmarksDatabaseHelper.isFolder(itemDatabaseId)) {
951                 deleteBookmarkFolderContents(itemDatabaseId);
952             }
953
954             // Delete the bookmark.
955             bookmarksDatabaseHelper.deleteBookmark(itemDatabaseId);
956         }
957     }
958
959     private void updateMoveIcons() {
960         // Get a handle for the shared preferences.
961         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
962
963         // Get the theme and screenshot preferences.
964         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
965
966         // Get a long array of the selected bookmarks.
967         long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
968
969         // Get the database IDs for the first, last, and selected bookmarks.
970         int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
971         int firstBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(0);
972         // bookmarksListView is 0 indexed.
973         int lastBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(bookmarksListView.getCount() - 1);
974
975         // Update the move bookmark up `MenuItem`.
976         if (selectedBookmarkDatabaseId == firstBookmarkDatabaseId) {  // The selected bookmark is in the first position.
977             // Disable the move bookmark up `MenuItem`.
978             moveBookmarkUpMenuItem.setEnabled(false);
979
980             //  Set the move bookmark up icon to be ghosted.
981             moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_disabled);
982         } else {  // The selected bookmark is not in the first position.
983             // Enable the move bookmark up `MenuItem`.
984             moveBookmarkUpMenuItem.setEnabled(true);
985
986             // Set the icon according to the theme.
987             if (darkTheme) {
988                 moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_enabled_dark);
989             } else {
990                 moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_enabled_light);
991             }
992         }
993
994         // Update the move bookmark down `MenuItem`.
995         if (selectedBookmarkDatabaseId == lastBookmarkDatabaseId) {  // The selected bookmark is in the last position.
996             // Disable the move bookmark down `MenuItem`.
997             moveBookmarkDownMenuItem.setEnabled(false);
998
999             // Set the move bookmark down icon to be ghosted.
1000             moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_disabled);
1001         } else {  // The selected bookmark is not in the last position.
1002             // Enable the move bookmark down `MenuItem`.
1003             moveBookmarkDownMenuItem.setEnabled(true);
1004
1005             // Set the icon according to the theme.
1006             if (darkTheme) {
1007                 moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_enabled_dark);
1008             } else {
1009                 moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_enabled_light);
1010             }
1011         }
1012     }
1013
1014     private void scrollBookmarks(int selectedBookmarkPosition) {
1015         // Get the first and last visible bookmark positions.
1016         int firstVisibleBookmarkPosition = bookmarksListView.getFirstVisiblePosition();
1017         int lastVisibleBookmarkPosition = bookmarksListView.getLastVisiblePosition();
1018
1019         // Calculate the number of bookmarks per screen.
1020         int numberOfBookmarksPerScreen = lastVisibleBookmarkPosition - firstVisibleBookmarkPosition;
1021
1022         // Scroll with the moved bookmark if necessary.
1023         if (selectedBookmarkPosition <= firstVisibleBookmarkPosition) {  // The selected bookmark position is at or above the top of the screen.
1024             // Scroll to the selected bookmark position.
1025             bookmarksListView.setSelection(selectedBookmarkPosition);
1026         } else if (selectedBookmarkPosition >= (lastVisibleBookmarkPosition - 1)) {  // The selected bookmark is at or below the bottom of the screen.
1027             // 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.
1028             // `+1` assures that the entire bookmark will be displayed in situations where only a partial bookmark fits at the bottom of the list view.
1029             bookmarksListView.setSelection(selectedBookmarkPosition - numberOfBookmarksPerScreen + 1);
1030         }
1031     }
1032
1033     private void loadFolder() {
1034         // Update bookmarks cursor with the contents of the bookmarks database for the current folder.
1035         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolder);
1036
1037         // Setup a `CursorAdapter`.  `this` specifies the `Context`.  `false` disables `autoRequery`.
1038         bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
1039             @Override
1040             public View newView(Context context, Cursor cursor, ViewGroup parent) {
1041                 // Inflate the individual item layout.  `false` does not attach it to the root.
1042                 return getLayoutInflater().inflate(R.layout.bookmarks_activity_item_linearlayout, parent, false);
1043             }
1044
1045             @Override
1046             public void bindView(View view, Context context, Cursor cursor) {
1047                 // Get handles for the views.
1048                 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
1049                 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
1050
1051                 // Get the favorite icon byte array from the `Cursor`.
1052                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
1053
1054                 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
1055                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
1056
1057                 // Display the bitmap in `bookmarkFavoriteIcon`.
1058                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
1059
1060                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
1061                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
1062                 bookmarkNameTextView.setText(bookmarkNameString);
1063
1064                 // Make the font bold for folders.
1065                 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
1066                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
1067                 } else {  // Reset the font to default for normal bookmarks.
1068                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
1069                 }
1070             }
1071         };
1072
1073         // Populate the list view with the adapter.
1074         bookmarksListView.setAdapter(bookmarksCursorAdapter);
1075
1076         // Set the `AppBar` title.
1077         if (currentFolder.isEmpty()) {
1078             appBar.setTitle(R.string.bookmarks);
1079         } else {
1080             appBar.setTitle(currentFolder);
1081         }
1082     }
1083
1084     @Override
1085     public void onDestroy() {
1086         // Close the bookmarks cursor and database.
1087         bookmarksCursor.close();
1088         bookmarksDatabaseHelper.close();
1089
1090         // Run the default commands.
1091         super.onDestroy();
1092     }
1093 }