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