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