]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/BookmarksDatabaseViewActivity.java
Update the URL in the copyright header. https://redmine.stoutner.com/issues/796
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / activities / BookmarksDatabaseViewActivity.java
1 /*
2  * Copyright © 2016-2022 Soren Stoutner <soren@stoutner.com>.
3  *
4  * This file is part of Privacy Browser Android <https://www.stoutner.com/privacy-browser-android>.
5  *
6  * Privacy Browser Android 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 Android 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 Android.  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.Dialog;
24 import android.content.Context;
25 import android.content.Intent;
26 import android.content.SharedPreferences;
27 import android.content.res.Configuration;
28 import android.database.Cursor;
29 import android.database.MatrixCursor;
30 import android.database.MergeCursor;
31 import android.graphics.Bitmap;
32 import android.graphics.BitmapFactory;
33 import android.graphics.Typeface;
34 import android.graphics.drawable.BitmapDrawable;
35 import android.graphics.drawable.Drawable;
36 import android.os.Bundle;
37 import android.preference.PreferenceManager;
38 import android.util.SparseBooleanArray;
39 import android.view.ActionMode;
40 import android.view.Menu;
41 import android.view.MenuItem;
42 import android.view.View;
43 import android.view.ViewGroup;
44 import android.view.Window;
45 import android.view.WindowManager;
46 import android.widget.AbsListView;
47 import android.widget.AdapterView;
48 import android.widget.EditText;
49 import android.widget.ImageView;
50 import android.widget.ListView;
51 import android.widget.RadioButton;
52 import android.widget.ResourceCursorAdapter;
53 import android.widget.Spinner;
54 import android.widget.TextView;
55
56 import androidx.annotation.NonNull;
57 import androidx.appcompat.app.ActionBar;
58 import androidx.appcompat.app.AppCompatActivity;
59 import androidx.appcompat.widget.Toolbar;  // The AndroidX toolbar must be used until the minimum API is >= 21.
60 import androidx.core.content.ContextCompat;
61 import androidx.cursoradapter.widget.CursorAdapter;
62 import androidx.fragment.app.DialogFragment;  // The AndroidX dialog fragment must be used or an error is produced on API <=22.
63
64 import com.google.android.material.snackbar.Snackbar;
65
66 import com.stoutner.privacybrowser.R;
67 import com.stoutner.privacybrowser.dialogs.EditBookmarkDatabaseViewDialog;
68 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDatabaseViewDialog;
69 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
70
71 import java.io.ByteArrayOutputStream;
72 import java.util.Arrays;
73
74 public class BookmarksDatabaseViewActivity extends AppCompatActivity implements EditBookmarkDatabaseViewDialog.EditBookmarkDatabaseViewListener,
75         EditBookmarkFolderDatabaseViewDialog.EditBookmarkFolderDatabaseViewListener {
76     // Define the class constants.
77     private static final int ALL_FOLDERS_DATABASE_ID = -2;
78     public static final int HOME_FOLDER_DATABASE_ID = -1;
79
80     // Define the saved instance state constants.
81     private final String CURRENT_FOLDER_DATABASE_ID = "current_folder_database_id";
82     private final String CURRENT_FOLDER_NAME = "current_folder_name";
83     private final String SORT_BY_DISPLAY_ORDER = "sort_by_display_order";
84
85     // Define the class variables.
86     private int currentFolderDatabaseId;
87     private String currentFolderName;
88     private boolean sortByDisplayOrder;
89     private BookmarksDatabaseHelper bookmarksDatabaseHelper;
90     private Cursor bookmarksCursor;
91     private CursorAdapter bookmarksCursorAdapter;
92     private String oldFolderNameString;
93     private Snackbar bookmarksDeletedSnackbar;
94     private boolean closeActivityAfterDismissingSnackbar;
95
96     @Override
97     public void onCreate(Bundle savedInstanceState) {
98         // Get a handle for the shared preferences.
99         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
100
101         // Get the preferences.
102         boolean allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false);
103         boolean bottomAppBar = sharedPreferences.getBoolean(getString(R.string.bottom_app_bar_key), false);
104
105         // Disable screenshots if not allowed.
106         if (!allowScreenshots) {
107             getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
108         }
109
110         // Set the activity theme.
111         setTheme(R.style.PrivacyBrowser);
112
113         // Run the default commands.
114         super.onCreate(savedInstanceState);
115
116         // Get the intent that launched the activity.
117         Intent launchingIntent = getIntent();
118
119         // Get the favorite icon byte array.
120         byte[] favoriteIconByteArray = launchingIntent.getByteArrayExtra("favorite_icon_byte_array");
121
122         // Remove the incorrect lint warning below that the favorite icon byte array might be null.
123         assert favoriteIconByteArray != null;
124
125         // Convert the favorite icon byte array to a bitmap and store it in a class variable.
126         Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
127
128         // Set the view according to the theme.
129         if (bottomAppBar) {
130             // Set the content view.
131             setContentView(R.layout.bookmarks_databaseview_bottom_appbar);
132         } else {
133             // `Window.FEATURE_ACTION_MODE_OVERLAY` makes the contextual action mode cover the support action bar.  It must be requested before the content is set.
134             supportRequestWindowFeature(Window.FEATURE_ACTION_MODE_OVERLAY);
135
136             // Set the content view.
137             setContentView(R.layout.bookmarks_databaseview_top_appbar);
138         }
139
140         // Get a handle for the toolbar.
141         Toolbar toolbar = findViewById(R.id.bookmarks_databaseview_toolbar);
142
143         // Set the support action bar.
144         setSupportActionBar(toolbar);
145
146         // Get a handle for the action bar.
147         ActionBar actionBar = getSupportActionBar();
148
149         // Remove the incorrect lint warning that the action bar might be null.
150         assert actionBar != null;
151
152         // Display the spinner and the back arrow in the action bar.
153         actionBar.setCustomView(R.layout.spinner);
154         actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_HOME_AS_UP);
155
156         // Initialize the database handler.  The `0` is to specify a database version, but that is set instead using a constant in `BookmarksDatabaseHelper`.
157         bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
158
159         // Setup a matrix cursor for "All Folders" and "Home Folder".
160         String[] matrixCursorColumnNames = {BookmarksDatabaseHelper._ID, BookmarksDatabaseHelper.BOOKMARK_NAME};
161         MatrixCursor matrixCursor = new MatrixCursor(matrixCursorColumnNames);
162         matrixCursor.addRow(new Object[]{ALL_FOLDERS_DATABASE_ID, getString(R.string.all_folders)});
163         matrixCursor.addRow(new Object[]{HOME_FOLDER_DATABASE_ID, getString(R.string.home_folder)});
164
165         // Get a cursor with the list of all the folders.
166         Cursor foldersCursor = bookmarksDatabaseHelper.getAllFolders();
167
168         // Combine the matrix cursor and the folders cursor.
169         MergeCursor foldersMergeCursor = new MergeCursor(new Cursor[]{matrixCursor, foldersCursor});
170
171
172         // Get the default folder bitmap.  `ContextCompat` must be used until the minimum API >= 21.
173         Drawable defaultFolderDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.folder_blue_bitmap);
174
175         // Cast the default folder drawable to a bitmap drawable.
176         BitmapDrawable defaultFolderBitmapDrawable = (BitmapDrawable) defaultFolderDrawable;
177
178         // Remove the incorrect lint warning that `.getBitmap()` might be null.
179         assert defaultFolderBitmapDrawable != null;
180
181         // Convert the default folder bitmap drawable to a bitmap.
182         Bitmap defaultFolderBitmap = defaultFolderBitmapDrawable.getBitmap();
183
184
185         // Create a resource cursor adapter for the spinner.
186         ResourceCursorAdapter foldersCursorAdapter = new ResourceCursorAdapter(this, R.layout.appbar_spinner_item, foldersMergeCursor, 0) {
187             @Override
188             public void bindView(View view, Context context, Cursor cursor) {
189                 // Get handles for the spinner views.
190                 ImageView spinnerItemImageView = view.findViewById(R.id.spinner_item_imageview);
191                 TextView spinnerItemTextView = view.findViewById(R.id.spinner_item_textview);
192
193                 // Set the folder icon according to the type.
194                 if (foldersMergeCursor.getPosition() > 1) {  // Set a user folder icon.
195                     // Initialize a default folder icon byte array output stream.
196                     ByteArrayOutputStream defaultFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
197
198                     // Covert the default folder bitmap to a PNG and store it in the output stream.  `0` is for lossless compression (the only option for a PNG).
199                     defaultFolderBitmap.compress(Bitmap.CompressFormat.PNG, 0, defaultFolderIconByteArrayOutputStream);
200
201                     // Convert the default folder icon output stream to a byte array.
202                     byte[] defaultFolderIconByteArray = defaultFolderIconByteArrayOutputStream.toByteArray();
203
204
205                     // Get the folder icon byte array from the cursor.
206                     byte[] folderIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.FAVORITE_ICON));
207
208                     // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
209                     Bitmap folderIconBitmap = BitmapFactory.decodeByteArray(folderIconByteArray, 0, folderIconByteArray.length);
210
211
212                     // Set the icon according to the type.
213                     if (Arrays.equals(folderIconByteArray, defaultFolderIconByteArray)) {  // The default folder icon is used.
214                         // Set a smaller and darker folder icon, which works well with the spinner.
215                         spinnerItemImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.folder_dark_blue));
216                     } else {  // A custom folder icon is uses.
217                         // Set the folder image stored in the cursor.
218                         spinnerItemImageView.setImageBitmap(folderIconBitmap);
219                     }
220                 } else {  // Set the `All Folders` or `Home Folder` icon.
221                     // Set the gray folder image.  `ContextCompat` must be used until the minimum API >= 21.
222                     spinnerItemImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.folder_gray));
223                 }
224
225                 // Set the text view to display the folder name.
226                 spinnerItemTextView.setText(cursor.getString(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME)));
227             }
228         };
229
230         // Set the resource cursor adapter drop drown view resource.
231         foldersCursorAdapter.setDropDownViewResource(R.layout.appbar_spinner_dropdown_item);
232
233         // Get a handle for the folder spinner and set the adapter.
234         Spinner folderSpinner = findViewById(R.id.spinner);
235         folderSpinner.setAdapter(foldersCursorAdapter);
236
237         // Wait to set the on item selected listener until the spinner has been inflated.  Otherwise the activity will crash on restart.
238         folderSpinner.post(() -> {
239             // Handle taps on the spinner dropdown.
240             folderSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
241                 @Override
242                 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
243                     // Store the current folder database ID.
244                     currentFolderDatabaseId = (int) id;
245
246                     // Get a handle for the selected view.
247                     TextView selectedFolderTextView = findViewById(R.id.spinner_item_textview);
248
249                     // Store the current folder name.
250                     currentFolderName = selectedFolderTextView.getText().toString();
251
252                     // Update the list view.
253                     updateBookmarksListView();
254                 }
255
256                 @Override
257                 public void onNothingSelected(AdapterView<?> parent) {
258                     // Do nothing.
259                 }
260             });
261         });
262
263
264         // Get a handle for the bookmarks listview.
265         ListView bookmarksListView = findViewById(R.id.bookmarks_databaseview_listview);
266
267         // Check to see if the activity was restarted.
268         if (savedInstanceState == null) {  // The activity was not restarted.
269             // Set the default current folder database ID.
270             currentFolderDatabaseId = ALL_FOLDERS_DATABASE_ID;
271         } else {  // The activity was restarted.
272             // Restore the class variables from the saved instance state.
273             currentFolderDatabaseId = savedInstanceState.getInt(CURRENT_FOLDER_DATABASE_ID);
274             currentFolderName = savedInstanceState.getString(CURRENT_FOLDER_NAME);
275             sortByDisplayOrder = savedInstanceState.getBoolean(SORT_BY_DISPLAY_ORDER);
276
277             // Update the spinner if the home folder is selected.  Android handles this by default for the main cursor but not the matrix cursor.
278             if (currentFolderDatabaseId == HOME_FOLDER_DATABASE_ID) {
279                 folderSpinner.setSelection(1);
280             }
281         }
282
283         // Update the bookmarks listview.
284         updateBookmarksListView();
285
286         // Setup a `CursorAdapter` with `this` context.  `false` disables autoRequery.
287         bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
288             @Override
289             public View newView(Context context, Cursor cursor, ViewGroup parent) {
290                 // Inflate the individual item layout.  `false` does not attach it to the root.
291                 return getLayoutInflater().inflate(R.layout.bookmarks_databaseview_item_linearlayout, parent, false);
292             }
293
294             @Override
295             public void bindView(View view, Context context, Cursor cursor) {
296                 boolean isFolder = (cursor.getInt(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.IS_FOLDER)) == 1);
297
298                 // Get the database ID from the `Cursor` and display it in `bookmarkDatabaseIdTextView`.
299                 int bookmarkDatabaseId = cursor.getInt(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper._ID));
300                 TextView bookmarkDatabaseIdTextView = view.findViewById(R.id.bookmarks_databaseview_database_id);
301                 bookmarkDatabaseIdTextView.setText(String.valueOf(bookmarkDatabaseId));
302
303                 // Get the favorite icon byte array from the `Cursor`.
304                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.FAVORITE_ICON));
305                 // Convert the byte array to a `Bitmap` beginning at the beginning at the first byte and ending at the last.
306                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
307                 // Display the bitmap in `bookmarkFavoriteIcon`.
308                 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmarks_databaseview_favorite_icon);
309                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
310
311                 // Get the bookmark name from the `Cursor` and display it in `bookmarkNameTextView`.
312                 String bookmarkNameString = cursor.getString(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
313                 TextView bookmarkNameTextView = view.findViewById(R.id.bookmarks_databaseview_bookmark_name);
314                 bookmarkNameTextView.setText(bookmarkNameString);
315
316                 // Make the font bold for folders.
317                 if (isFolder) {
318                     // The first argument is `null` prevent changing of the font.
319                     bookmarkNameTextView.setTypeface(null, Typeface.BOLD);
320                 } else {  // Reset the font to default.
321                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
322                 }
323
324                 // Get the bookmark URL form the `Cursor` and display it in `bookmarkUrlTextView`.
325                 String bookmarkUrlString = cursor.getString(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL));
326                 TextView bookmarkUrlTextView = view.findViewById(R.id.bookmarks_databaseview_bookmark_url);
327                 bookmarkUrlTextView.setText(bookmarkUrlString);
328
329                 // Hide the URL if the bookmark is a folder.
330                 if (isFolder) {
331                     bookmarkUrlTextView.setVisibility(View.GONE);
332                 } else {
333                     bookmarkUrlTextView.setVisibility(View.VISIBLE);
334                 }
335
336                 // Get the display order from the `Cursor` and display it in `bookmarkDisplayOrderTextView`.
337                 int bookmarkDisplayOrder = cursor.getInt(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.DISPLAY_ORDER));
338                 TextView bookmarkDisplayOrderTextView = view.findViewById(R.id.bookmarks_databaseview_display_order);
339                 bookmarkDisplayOrderTextView.setText(String.valueOf(bookmarkDisplayOrder));
340
341                 // Get the parent folder from the `Cursor` and display it in `bookmarkParentFolder`.
342                 String bookmarkParentFolder = cursor.getString(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.PARENT_FOLDER));
343                 ImageView parentFolderImageView = view.findViewById(R.id.bookmarks_databaseview_parent_folder_icon);
344                 TextView bookmarkParentFolderTextView = view.findViewById(R.id.bookmarks_databaseview_parent_folder);
345
346                 // Make the folder name gray if it is the home folder.
347                 if (bookmarkParentFolder.isEmpty()) {
348                     parentFolderImageView.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.folder_gray));
349                     bookmarkParentFolderTextView.setText(R.string.home_folder);
350                     bookmarkParentFolderTextView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.gray_500));
351                 } else {
352                     parentFolderImageView.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.folder_dark_blue));
353                     bookmarkParentFolderTextView.setText(bookmarkParentFolder);
354
355                     // Get the current theme status.
356                     int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
357
358                     // Set the text color according to the theme.
359                     if (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES) {
360                         // This color is a little darker than the default night mode text.  But the effect is rather nice.
361                         bookmarkParentFolderTextView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.gray_300));
362                     } else {
363                         bookmarkParentFolderTextView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.black));
364                     }
365                 }
366             }
367         };
368
369         // Update the ListView.
370         bookmarksListView.setAdapter(bookmarksCursorAdapter);
371
372         // Set a listener to edit a bookmark when it is tapped.
373         bookmarksListView.setOnItemClickListener((AdapterView<?> parent, View view, int position, long id) -> {
374             // Convert the database ID to an int.
375             int databaseId = (int) id;
376
377             // Show the edit bookmark or edit bookmark folder dialog.
378             if (bookmarksDatabaseHelper.isFolder(databaseId)) {
379                 // Save the current folder name, which is used in `onSaveBookmarkFolder()`.
380                 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
381
382                 // Show the edit bookmark folder dialog.
383                 DialogFragment editBookmarkFolderDatabaseViewDialog = EditBookmarkFolderDatabaseViewDialog.folderDatabaseId(databaseId, favoriteIconBitmap);
384                 editBookmarkFolderDatabaseViewDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
385             } else {
386                 // Show the edit bookmark dialog.
387                 DialogFragment editBookmarkDatabaseViewDialog = EditBookmarkDatabaseViewDialog.bookmarkDatabaseId(databaseId, favoriteIconBitmap);
388                 editBookmarkDatabaseViewDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
389             }
390         });
391
392         // Handle long presses on the list view.
393         bookmarksListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
394             // Instantiate the common variables.
395             MenuItem selectAllMenuItem;
396             MenuItem deleteMenuItem;
397             boolean deletingBookmarks;
398
399             @Override
400             public boolean onCreateActionMode(ActionMode mode, Menu menu) {
401                 // Inflate the menu for the contextual app bar.
402                 getMenuInflater().inflate(R.menu.bookmarks_databaseview_context_menu, menu);
403
404                 // Set the title.
405                 mode.setTitle(R.string.bookmarks);
406
407                 // Get handles for the menu items.
408                 selectAllMenuItem = menu.findItem(R.id.select_all);
409                 deleteMenuItem = menu.findItem(R.id.delete);
410
411                 // Disable the delete menu item if a delete is pending.
412                 deleteMenuItem.setEnabled(!deletingBookmarks);
413
414                 // Get the number of currently selected bookmarks.
415                 int numberOfSelectedBookmarks = bookmarksListView.getCheckedItemCount();
416
417                 // Set the action mode subtitle according to the number of selected bookmarks.  This must be set here or it will be missing if the activity is restarted.
418                 mode.setSubtitle(getString(R.string.selected) + "  " + numberOfSelectedBookmarks);
419
420                 // Do not show the select all menu item if all the bookmarks are already checked.
421                 if (bookmarksListView.getCheckedItemCount() == bookmarksListView.getCount()) {
422                     selectAllMenuItem.setVisible(false);
423                 }
424
425                 // Make it so.
426                 return true;
427             }
428
429             @Override
430             public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
431                 // Do nothing.
432                 return false;
433             }
434
435             @Override
436             public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
437                 // Calculate the number of selected bookmarks.
438                 int numberOfSelectedBookmarks = bookmarksListView.getCheckedItemCount();
439
440                 // Only run the commands if at least one bookmark is selected.  Otherwise, a context menu with 0 selected bookmarks is briefly displayed.
441                 if (numberOfSelectedBookmarks > 0) {
442                     // Update the action mode subtitle according to the number of selected bookmarks.
443                     mode.setSubtitle(getString(R.string.selected) + "  " + numberOfSelectedBookmarks);
444
445                     // Only show the select all menu item if all of the bookmarks are not already selected.
446                     selectAllMenuItem.setVisible(bookmarksListView.getCheckedItemCount() != bookmarksListView.getCount());
447
448                     // Convert the database ID to an int.
449                     int databaseId = (int) id;
450
451                     // If a folder was selected, also select all the contents.
452                     if (checked && bookmarksDatabaseHelper.isFolder(databaseId)) {
453                         selectAllBookmarksInFolder(databaseId);
454                     }
455
456                     // Do not allow a bookmark to be deselected if the folder is selected.
457                     if (!checked) {
458                         // Get the folder name.
459                         String folderName = bookmarksDatabaseHelper.getParentFolderName((int) id);
460
461                         // If the bookmark is not in the root folder, check to see if the folder is selected.
462                         if (!folderName.isEmpty()) {
463                             // Get the database ID of the folder.
464                             int folderDatabaseId = bookmarksDatabaseHelper.getFolderDatabaseId(folderName);
465
466                             // Move the bookmarks cursor to the first position.
467                             bookmarksCursor.moveToFirst();
468
469                             // Initialize the folder position variable.
470                             int folderPosition = -1;
471
472                             // Get the position of the folder in the bookmarks cursor.
473                             while ((folderPosition < 0) && (bookmarksCursor.getPosition() < bookmarksCursor.getCount())) {
474                                 // Check if the folder database ID matches the bookmark database ID.
475                                 if (folderDatabaseId == bookmarksCursor.getInt(bookmarksCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper._ID))) {
476                                     // Get the folder position.
477                                     folderPosition = bookmarksCursor.getPosition();
478
479                                     // Check if the folder is selected.
480                                     if (bookmarksListView.isItemChecked(folderPosition)) {
481                                         // Reselect the bookmark.
482                                         bookmarksListView.setItemChecked(position, true);
483
484                                         // Display a snackbar explaining why the bookmark cannot be deselected.
485                                         Snackbar.make(bookmarksListView, R.string.cannot_deselect_bookmark, Snackbar.LENGTH_LONG).show();
486                                     }
487                                 }
488
489                                 // Increment the bookmarks cursor.
490                                 bookmarksCursor.moveToNext();
491                             }
492                         }
493                     }
494                 }
495             }
496
497             @Override
498             public boolean onActionItemClicked(ActionMode mode, MenuItem menuItem) {
499                 // Get a the menu item ID.
500                 int menuItemId = menuItem.getItemId();
501
502                 // Run the command that corresponds to the selected menu item.
503                 if (menuItemId == R.id.select_all) {  // Select all the bookmarks.
504                     // Get the total number of bookmarks.
505                     int numberOfBookmarks = bookmarksListView.getCount();
506
507                     // Select them all.
508                     for (int i = 0; i < numberOfBookmarks; i++) {
509                         bookmarksListView.setItemChecked(i, true);
510                     }
511                 } else if (menuItemId == R.id.delete) {  // Delete the selected bookmarks.
512                     // Set the deleting bookmarks flag, which prevents the delete menu item from being enabled until the current process finishes.
513                     deletingBookmarks = true;
514
515                     // Get an array of the selected row IDs.
516                     long[] selectedBookmarksIdsLongArray = bookmarksListView.getCheckedItemIds();
517
518                     // 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.
519                     SparseBooleanArray selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions().clone();
520
521                     // Update the bookmarks cursor with the current contents of the bookmarks database except for the specified database IDs.
522                     switch (currentFolderDatabaseId) {
523                         // Get a cursor with all the folders.
524                         case ALL_FOLDERS_DATABASE_ID:
525                             if (sortByDisplayOrder) {
526                                 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksByDisplayOrderExcept(selectedBookmarksIdsLongArray);
527                             } else {
528                                 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksExcept(selectedBookmarksIdsLongArray);
529                             }
530                             break;
531
532                         // Get a cursor for the home folder.
533                         case HOME_FOLDER_DATABASE_ID:
534                             if (sortByDisplayOrder) {
535                                 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrderExcept(selectedBookmarksIdsLongArray, "");
536                             } else {
537                                 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksExcept(selectedBookmarksIdsLongArray, "");
538                             }
539                             break;
540
541                         // Display the selected folder.
542                         default:
543                             // Get a cursor for the selected folder.
544                             if (sortByDisplayOrder) {
545                                 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrderExcept(selectedBookmarksIdsLongArray, currentFolderName);
546                             } else {
547                                 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksExcept(selectedBookmarksIdsLongArray, currentFolderName);
548                             }
549                     }
550
551                     // Update the list view.
552                     bookmarksCursorAdapter.changeCursor(bookmarksCursor);
553
554                     // Create a Snackbar with the number of deleted bookmarks.
555                     bookmarksDeletedSnackbar = Snackbar.make(findViewById(R.id.bookmarks_databaseview_coordinatorlayout),
556                             getString(R.string.bookmarks_deleted) + "  " + selectedBookmarksIdsLongArray.length, Snackbar.LENGTH_LONG)
557                             .setAction(R.string.undo, view -> {
558                                 // Do nothing because everything will be handled by `onDismissed()` below.
559                             })
560                             .addCallback(new Snackbar.Callback() {
561                                 @SuppressLint("SwitchIntDef")  // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
562                                 @Override
563                                 public void onDismissed(Snackbar snackbar, int event) {
564                                     if (event == Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The user pushed the undo button.
565                                         // Update the bookmarks list view with the current contents of the bookmarks database, including the "deleted bookmarks.
566                                         updateBookmarksListView();
567
568                                         // Re-select the previously selected bookmarks.
569                                         for (int i = 0; i < selectedBookmarksPositionsSparseBooleanArray.size(); i++) {
570                                             bookmarksListView.setItemChecked(selectedBookmarksPositionsSparseBooleanArray.keyAt(i), true);
571                                         }
572                                     } else {  // The Snackbar was dismissed without the undo button being pushed.
573                                         // Delete each selected bookmark.
574                                         for (long databaseIdLong : selectedBookmarksIdsLongArray) {
575                                             // Convert `databaseIdLong` to an int.
576                                             int databaseIdInt = (int) databaseIdLong;
577
578                                             // Delete the selected bookmark.
579                                             bookmarksDatabaseHelper.deleteBookmark(databaseIdInt);
580                                         }
581                                     }
582
583                                     // Reset the deleting bookmarks flag.
584                                     deletingBookmarks = false;
585
586                                     // Enable the delete menu item.
587                                     deleteMenuItem.setEnabled(true);
588
589                                     // Close the activity if back has been pressed.
590                                     if (closeActivityAfterDismissingSnackbar) {
591                                         onBackPressed();
592                                     }
593                                 }
594                             });
595
596                     // Show the Snackbar.
597                     bookmarksDeletedSnackbar.show();
598                 }
599
600                 // Consume the click.
601                 return false;
602             }
603
604             @Override
605             public void onDestroyActionMode(ActionMode mode) {
606                 // Do nothing.
607             }
608         });
609     }
610
611     @Override
612     public boolean onCreateOptionsMenu(Menu menu) {
613         // Inflate the menu.
614         getMenuInflater().inflate(R.menu.bookmarks_databaseview_options_menu, menu);
615
616         // Get the current theme status.
617         int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
618
619         // Get a handle for the sort menu item.
620         MenuItem sortMenuItem = menu.findItem(R.id.sort);
621
622         // Change the sort menu item icon if the listview is sorted by display order, which restores the state after a restart.
623         if (sortByDisplayOrder) {
624             if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
625                 sortMenuItem.setIcon(R.drawable.sort_selected_day);
626             } else {
627                 sortMenuItem.setIcon(R.drawable.sort_selected_night);
628             }
629         }
630
631         // Success.
632         return true;
633     }
634
635     @Override
636     public boolean onOptionsItemSelected(MenuItem menuItem) {
637         // Get the menu item ID.
638         int menuItemId = menuItem.getItemId();
639
640         // Run the command that corresponds to the selected menu item.
641         if (menuItemId == android.R.id.home) {  // Go Home.  The home arrow is identified as `android.R.id.home`, not just `R.id.home`.
642             // Exit the activity.
643             onBackPressed();
644         } else if (menuItemId == R.id.sort) {  // Toggle the sort mode.
645             // Update the sort by display order tracker.
646             sortByDisplayOrder = !sortByDisplayOrder;
647
648             // Get a handle for the bookmarks list view.
649             ListView bookmarksListView = findViewById(R.id.bookmarks_databaseview_listview);
650
651             // Get the current theme status.
652             int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
653
654             // Update the icon and display a snackbar.
655             if (sortByDisplayOrder) {  // Sort by display order.
656                 // Update the icon according to the theme.
657                 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
658                     menuItem.setIcon(R.drawable.sort_selected_day);
659                 } else {
660                     menuItem.setIcon(R.drawable.sort_selected_night);
661                 }
662
663                 // Display a Snackbar indicating the current sort type.
664                 Snackbar.make(bookmarksListView, R.string.sorted_by_display_order, Snackbar.LENGTH_SHORT).show();
665             } else {  // Sort by database id.
666                 // Update the icon according to the theme.
667                 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
668                     menuItem.setIcon(R.drawable.sort_day);
669                 } else {
670                     menuItem.setIcon(R.drawable.sort_night);
671                 }
672
673                 // Display a Snackbar indicating the current sort type.
674                 Snackbar.make(bookmarksListView, R.string.sorted_by_database_id, Snackbar.LENGTH_SHORT).show();
675             }
676
677             // Update the list view.
678             updateBookmarksListView();
679         }
680
681         // Consume the event.
682         return true;
683     }
684
685     @Override
686     public void onSaveInstanceState (@NonNull Bundle savedInstanceState) {
687         // Run the default commands.
688         super.onSaveInstanceState(savedInstanceState);
689
690         // Store the class variables in the bundle.
691         savedInstanceState.putInt(CURRENT_FOLDER_DATABASE_ID, currentFolderDatabaseId);
692         savedInstanceState.putString(CURRENT_FOLDER_NAME, currentFolderName);
693         savedInstanceState.putBoolean(SORT_BY_DISPLAY_ORDER, sortByDisplayOrder);
694     }
695
696     @Override
697     public void onBackPressed() {
698         // Check to see if a snackbar is currently displayed.  If so, it must be closed before existing so that a pending delete is completed before reloading the list view in the bookmarks activity.
699         if ((bookmarksDeletedSnackbar != null) && bookmarksDeletedSnackbar.isShown()) { // Close the bookmarks deleted snackbar before going home.
700             // Set the close flag.
701             closeActivityAfterDismissingSnackbar = true;
702
703             // Dismiss the snackbar.
704             bookmarksDeletedSnackbar.dismiss();
705         } else {  // Go home immediately.
706             // Update the current folder in the bookmarks activity.
707             if ((currentFolderDatabaseId == ALL_FOLDERS_DATABASE_ID) || (currentFolderDatabaseId == HOME_FOLDER_DATABASE_ID)) {  // All folders or the the home folder are currently displayed.
708                 // Load the home folder.
709                 BookmarksActivity.currentFolder = "";
710             } else {  // A subfolder is currently displayed.
711                 // Load the current folder.
712                 BookmarksActivity.currentFolder = currentFolderName;
713             }
714
715             // Reload the bookmarks list view when returning to the bookmarks activity.
716             BookmarksActivity.restartFromBookmarksDatabaseViewActivity = true;
717
718             // Exit the bookmarks database view activity.
719             super.onBackPressed();
720         }
721     }
722
723     private void updateBookmarksListView() {
724         // Populate the bookmarks list view based on the spinner selection.
725         switch (currentFolderDatabaseId) {
726             // Get a cursor with all the folders.
727             case ALL_FOLDERS_DATABASE_ID:
728                 if (sortByDisplayOrder) {
729                     bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksByDisplayOrder();
730                 } else {
731                     bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarks();
732                 }
733                 break;
734
735             // Get a cursor for the home folder.
736             case HOME_FOLDER_DATABASE_ID:
737                 if (sortByDisplayOrder) {
738                     bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder("");
739                 } else {
740                     bookmarksCursor = bookmarksDatabaseHelper.getBookmarks("");
741                 }
742                 break;
743
744             // Display the selected folder.
745             default:
746                 // Get a cursor for the selected folder.
747                 if (sortByDisplayOrder) {
748                     bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolderName);
749                 } else {
750                     bookmarksCursor = bookmarksDatabaseHelper.getBookmarks(currentFolderName);
751                 }
752         }
753
754         // Update the cursor adapter if it isn't null, which happens when the activity is restarted.
755         if (bookmarksCursorAdapter != null) {
756             bookmarksCursorAdapter.changeCursor(bookmarksCursor);
757         }
758     }
759
760     private void selectAllBookmarksInFolder(int folderId) {
761         // Get a handle for the bookmarks list view.
762         ListView bookmarksListView = findViewById(R.id.bookmarks_databaseview_listview);
763
764         // Get the folder name.
765         String folderName = bookmarksDatabaseHelper.getFolderName(folderId);
766
767         // Get a cursor with the contents of the folder.
768         Cursor folderCursor = bookmarksDatabaseHelper.getBookmarks(folderName);
769
770         // Move to the beginning of the cursor.
771         folderCursor.moveToFirst();
772
773         while (folderCursor.getPosition() < folderCursor.getCount()) {
774             // Get the bookmark database ID.
775             int bookmarkId = folderCursor.getInt(folderCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper._ID));
776
777             // Move the bookmarks cursor to the first position.
778             bookmarksCursor.moveToFirst();
779
780             // Initialize the bookmark position variable.
781             int bookmarkPosition = -1;
782
783             // Get the position of this bookmark in the bookmarks cursor.
784             while ((bookmarkPosition < 0) && (bookmarksCursor.getPosition() < bookmarksCursor.getCount())) {
785                 // Check if the bookmark IDs match.
786                 if (bookmarkId == bookmarksCursor.getInt(bookmarksCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper._ID))) {
787                     // Get the bookmark position.
788                     bookmarkPosition = bookmarksCursor.getPosition();
789
790                     // If this bookmark is a folder, select all the bookmarks inside it.
791                     if (bookmarksDatabaseHelper.isFolder(bookmarkId)) {
792                         selectAllBookmarksInFolder(bookmarkId);
793                     }
794
795                     // Select the bookmark.
796                     bookmarksListView.setItemChecked(bookmarkPosition, true);
797                 }
798
799                 // Increment the bookmarks cursor position.
800                 bookmarksCursor.moveToNext();
801             }
802
803             // Move to the next position.
804             folderCursor.moveToNext();
805         }
806     }
807
808     @Override
809     public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, @NonNull Bitmap favoriteIconBitmap) {
810         // Get the dialog from the dialog fragment.
811         Dialog dialog = dialogFragment.getDialog();
812
813         // Remove the incorrect lint warning below that the dialog might be null.
814         assert dialog != null;
815
816         // Get handles for the views from dialog fragment.
817         RadioButton currentIconRadioButton = dialog.findViewById(R.id.current_icon_radiobutton);
818         EditText bookmarkNameEditText = dialog.findViewById(R.id.bookmark_name_edittext);
819         EditText bookmarkUrlEditText = dialog.findViewById(R.id.bookmark_url_edittext);
820         Spinner folderSpinner = dialog.findViewById(R.id.bookmark_folder_spinner);
821         EditText displayOrderEditText = dialog.findViewById(R.id.bookmark_display_order_edittext);
822
823         // Extract the bookmark information.
824         String bookmarkNameString = bookmarkNameEditText.getText().toString();
825         String bookmarkUrlString = bookmarkUrlEditText.getText().toString();
826         int folderDatabaseId = (int) folderSpinner.getSelectedItemId();
827         int displayOrderInt = Integer.parseInt(displayOrderEditText.getText().toString());
828
829         // Instantiate the parent folder name `String`.
830         String parentFolderNameString;
831
832         // Set the parent folder name.
833         if (folderDatabaseId == HOME_FOLDER_DATABASE_ID) {  // The home folder is selected.  Use `""`.
834             parentFolderNameString = "";
835         } else {  // Get the parent folder name from the database.
836             parentFolderNameString = bookmarksDatabaseHelper.getFolderName(folderDatabaseId);
837         }
838
839         // Update the bookmark.
840         if (currentIconRadioButton.isChecked()) {  // Update the bookmark without changing the favorite icon.
841             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, parentFolderNameString, displayOrderInt);
842         } else {  // Update the bookmark using the `WebView` favorite icon.
843             // Create a favorite icon byte array output stream.
844             ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
845
846             // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
847             favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
848
849             // Convert the favorite icon byte array stream to a byte array.
850             byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
851
852             //  Update the bookmark and the favorite icon.
853             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, parentFolderNameString, displayOrderInt, newFavoriteIconByteArray);
854         }
855
856         // Update the list view.
857         updateBookmarksListView();
858     }
859
860     @Override
861     public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, @NonNull Bitmap favoriteIconBitmap) {
862         // Get the dialog from the dialog fragment.
863         Dialog dialog = dialogFragment.getDialog();
864
865         // Remove the incorrect lint warning below that the dialog might be null.
866         assert dialog != null;
867
868         // Get handles for the views from dialog fragment.
869         RadioButton currentIconRadioButton = dialog.findViewById(R.id.current_icon_radiobutton);
870         RadioButton defaultIconRadioButton = dialog.findViewById(R.id.default_icon_radiobutton);
871         ImageView defaultIconImageView = dialog.findViewById(R.id.default_icon_imageview);
872         EditText folderNameEditText = dialog.findViewById(R.id.folder_name_edittext);
873         Spinner parentFolderSpinner = dialog.findViewById(R.id.parent_folder_spinner);
874         EditText displayOrderEditText = dialog.findViewById(R.id.display_order_edittext);
875
876         // Extract the folder information.
877         String newFolderNameString = folderNameEditText.getText().toString();
878         int parentFolderDatabaseId = (int) parentFolderSpinner.getSelectedItemId();
879         int displayOrderInt = Integer.parseInt(displayOrderEditText.getText().toString());
880
881         // Instantiate the parent folder name `String`.
882         String parentFolderNameString;
883
884         // Set the parent folder name.
885         if (parentFolderDatabaseId == HOME_FOLDER_DATABASE_ID) {  // The home folder is selected.  Use `""`.
886             parentFolderNameString = "";
887         } else {  // Get the parent folder name from the database.
888             parentFolderNameString = bookmarksDatabaseHelper.getFolderName(parentFolderDatabaseId);
889         }
890
891         // Update the folder.
892         if (currentIconRadioButton.isChecked()) {  // Update the folder without changing the favorite icon.
893             bookmarksDatabaseHelper.updateFolder(selectedBookmarkDatabaseId, oldFolderNameString, newFolderNameString, parentFolderNameString, displayOrderInt);
894         } else {  // Update the folder and the icon.
895             // Create the new folder icon Bitmap.
896             Bitmap folderIconBitmap;
897
898             // Populate the new folder icon bitmap.
899             if (defaultIconRadioButton.isChecked()) {
900                 // Get the default folder icon drawable.
901                 Drawable folderIconDrawable = defaultIconImageView.getDrawable();
902
903                 // Convert the folder icon drawable to a bitmap drawable.
904                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
905
906                 // Convert the folder icon bitmap drawable to a bitmap.
907                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
908             } else {  // Use the `WebView` favorite icon.
909                 // Get a copy of the favorite icon bitmap.
910                 folderIconBitmap = favoriteIconBitmap;
911             }
912
913             // Create a folder icon byte array output stream.
914             ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
915
916             // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
917             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
918
919             // Convert the folder icon byte array stream to a byte array.
920             byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
921
922             //  Update the folder and the icon.
923             bookmarksDatabaseHelper.updateFolder(selectedBookmarkDatabaseId, oldFolderNameString, newFolderNameString, parentFolderNameString, displayOrderInt, newFolderIconByteArray);
924         }
925
926         // Update the list view.
927         updateBookmarksListView();
928     }
929
930     @Override
931     public void onDestroy() {
932         // Close the bookmarks cursor and database.
933         bookmarksCursor.close();
934         bookmarksDatabaseHelper.close();
935
936         // Run the default commands.
937         super.onDestroy();
938     }
939 }