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