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