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