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