2 * Copyright © 2016-2020 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
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.
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.
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/>.
20 package com.stoutner.privacybrowser.activities;
22 import android.annotation.SuppressLint;
23 import android.app.Dialog;
24 import android.content.Context;
25 import android.content.Intent;
26 import android.content.SharedPreferences;
27 import android.database.Cursor;
28 import android.database.MatrixCursor;
29 import android.database.MergeCursor;
30 import android.graphics.Bitmap;
31 import android.graphics.BitmapFactory;
32 import android.graphics.Typeface;
33 import android.graphics.drawable.BitmapDrawable;
34 import android.graphics.drawable.Drawable;
35 import android.os.Bundle;
36 import android.preference.PreferenceManager;
37 import android.util.SparseBooleanArray;
38 import android.view.ActionMode;
39 import android.view.Menu;
40 import android.view.MenuItem;
41 import android.view.View;
42 import android.view.ViewGroup;
43 import android.view.WindowManager;
44 import android.widget.AbsListView;
45 import android.widget.AdapterView;
46 import android.widget.EditText;
47 import android.widget.ImageView;
48 import android.widget.ListView;
49 import android.widget.RadioButton;
50 import android.widget.ResourceCursorAdapter;
51 import android.widget.Spinner;
52 import android.widget.TextView;
54 import androidx.appcompat.app.ActionBar;
55 import androidx.appcompat.app.AppCompatActivity;
56 import androidx.appcompat.widget.Toolbar; // The AndroidX toolbar must be used until the minimum API is >= 21.
57 import androidx.core.content.ContextCompat;
58 import androidx.cursoradapter.widget.CursorAdapter;
59 import androidx.fragment.app.DialogFragment; // The AndroidX dialog fragment must be used or an error is produced on API <=22.
61 import com.google.android.material.snackbar.Snackbar;
63 import com.stoutner.privacybrowser.R;
64 import com.stoutner.privacybrowser.dialogs.EditBookmarkDatabaseViewDialog;
65 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDatabaseViewDialog;
66 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
68 import java.io.ByteArrayOutputStream;
69 import java.util.Arrays;
71 public class BookmarksDatabaseViewActivity extends AppCompatActivity implements EditBookmarkDatabaseViewDialog.EditBookmarkDatabaseViewListener,
72 EditBookmarkFolderDatabaseViewDialog.EditBookmarkFolderDatabaseViewListener {
73 // Instantiate the constants.
74 private static final int ALL_FOLDERS_DATABASE_ID = -2;
75 private static final int HOME_FOLDER_DATABASE_ID = -1;
77 // `bookmarksDatabaseHelper` is used in `onCreate()`, `updateBookmarksListView()`, `selectAllBookmarksInFolder()`, and `onDestroy()`.
78 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
80 // `bookmarksCursor` is used in `onCreate()`, `updateBookmarksListView()`, `onSaveBookmark()`, `onSaveBookmarkFolder()`, and `onDestroy()`.
81 private Cursor bookmarksCursor;
83 // `bookmarksCursorAdapter` is used in `onCreate()`, `selectAllBookmarksInFolder()`, and `updateBookmarksListView()`.
84 private CursorAdapter bookmarksCursorAdapter;
86 // `oldFolderNameString` is used in `onCreate()` and `onSaveBookmarkFolder()`.
87 private String oldFolderNameString;
89 // `currentFolderDatabaseId` is used in `onCreate()`, `updateBookmarksListView()`, `onSaveBookmark()`, and `onSaveBookmarkFolder()`.
90 private int currentFolderDatabaseId;
92 // `currentFolder` is used in `onCreate()`, `onSaveBookmark()`, and `onSaveBookmarkFolder()`.
93 private String currentFolderName;
95 // `sortByDisplayOrder` is used in `onCreate()`, `onOptionsItemSelected()`, and `updateBookmarksListView()`.
96 private boolean sortByDisplayOrder;
98 // `bookmarksDeletedSnackbar` is used in `onCreate()`, `onOptionsItemSelected()`, and `onBackPressed()`.
99 private Snackbar bookmarksDeletedSnackbar;
101 // `closeActivityAfterDismissingSnackbar` is used in `onCreate()`, `onOptionsItemSelected()`, and `onBackPressed()`.
102 private boolean closeActivityAfterDismissingSnackbar;
105 public void onCreate(Bundle savedInstanceState) {
106 // Get a handle for the shared preferences.
107 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
109 // Get the theme and screenshot preferences.
110 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
111 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
113 // Disable screenshots if not allowed.
114 if (!allowScreenshots) {
115 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
118 // Set the activity theme.
120 setTheme(R.style.PrivacyBrowserDark_SecondaryActivity);
122 setTheme(R.style.PrivacyBrowserLight_SecondaryActivity);
125 // Run the default commands.
126 super.onCreate(savedInstanceState);
128 // Get the intent that launched the activity.
129 Intent launchingIntent = getIntent();
131 // Get the favorite icon byte array.
132 byte[] favoriteIconByteArray = launchingIntent.getByteArrayExtra("favorite_icon_byte_array");
134 // Remove the incorrect lint warning below that the favorite icon byte array might be null.
135 assert favoriteIconByteArray != null;
137 // Convert the favorite icon byte array to a bitmap and store it in a class variable.
138 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
140 // Set the content view.
141 setContentView(R.layout.bookmarks_databaseview_coordinatorlayout);
143 // The AndroidX toolbar must be used until the minimum API is >= 21.
144 Toolbar toolbar = findViewById(R.id.bookmarks_databaseview_toolbar);
145 setSupportActionBar(toolbar);
147 // Get a handle for the action bar.
148 ActionBar actionBar = getSupportActionBar();
150 // Remove the incorrect lint warning that the action bar might be null.
151 assert actionBar != null;
153 // Display the spinner and the back arrow in the action bar.
154 actionBar.setCustomView(R.layout.spinner);
155 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_HOME_AS_UP);
157 // Initialize the database handler. The `0` is to specify a database version, but that is set instead using a constant in `BookmarksDatabaseHelper`.
158 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
160 // Setup a matrix cursor for "All Folders" and "Home Folder".
161 String[] matrixCursorColumnNames = {BookmarksDatabaseHelper._ID, BookmarksDatabaseHelper.BOOKMARK_NAME};
162 MatrixCursor matrixCursor = new MatrixCursor(matrixCursorColumnNames);
163 matrixCursor.addRow(new Object[]{ALL_FOLDERS_DATABASE_ID, getString(R.string.all_folders)});
164 matrixCursor.addRow(new Object[]{HOME_FOLDER_DATABASE_ID, getString(R.string.home_folder)});
166 // Get a cursor with the list of all the folders.
167 Cursor foldersCursor = bookmarksDatabaseHelper.getAllFolders();
169 // Combine `matrixCursor` and `foldersCursor`.
170 MergeCursor foldersMergeCursor = new MergeCursor(new Cursor[]{matrixCursor, foldersCursor});
173 // Get the default folder bitmap. `ContextCompat` must be used until the minimum API >= 21.
174 Drawable defaultFolderDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.folder_blue_bitmap);
176 // Cast the default folder drawable to a `BitmapDrawable`.
177 BitmapDrawable defaultFolderBitmapDrawable = (BitmapDrawable) defaultFolderDrawable;
179 // Remove the incorrect lint warning that `.getBitmap()` might be null.
180 assert defaultFolderBitmapDrawable != null;
182 // Convert the default folder `BitmapDrawable` to a bitmap.
183 Bitmap defaultFolderBitmap = defaultFolderBitmapDrawable.getBitmap();
186 // Create a resource cursor adapter for the spinner.
187 ResourceCursorAdapter foldersCursorAdapter = new ResourceCursorAdapter(this, R.layout.appbar_spinner_item, foldersMergeCursor, 0) {
189 public void bindView(View view, Context context, Cursor cursor) {
190 // Get handles for the spinner views.
191 ImageView spinnerItemImageView = view.findViewById(R.id.spinner_item_imageview);
192 TextView spinnerItemTextView = view.findViewById(R.id.spinner_item_textview);
194 // Set the folder icon according to the type.
195 if (foldersMergeCursor.getPosition() > 1) { // Set a user folder icon.
196 // Initialize a default folder icon byte array output stream.
197 ByteArrayOutputStream defaultFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
199 // Covert the default folder bitmap to a PNG and store it in the output stream. `0` is for lossless compression (the only option for a PNG).
200 defaultFolderBitmap.compress(Bitmap.CompressFormat.PNG, 0, defaultFolderIconByteArrayOutputStream);
202 // Convert the default folder icon output stream to a byte array.
203 byte[] defaultFolderIconByteArray = defaultFolderIconByteArrayOutputStream.toByteArray();
206 // Get the folder icon byte array from the cursor.
207 byte[] folderIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
209 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
210 Bitmap folderIconBitmap = BitmapFactory.decodeByteArray(folderIconByteArray, 0, folderIconByteArray.length);
213 // Set the icon according to the type.
214 if (Arrays.equals(folderIconByteArray, defaultFolderIconByteArray)) { // The default folder icon is used.
215 // Set a smaller and darker folder icon, which works well with the spinner.
216 spinnerItemImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.folder_dark_blue));
217 } else { // A custom folder icon is uses.
218 // Set the folder image stored in the cursor.
219 spinnerItemImageView.setImageBitmap(folderIconBitmap);
221 } else { // Set the `All Folders` or `Home Folder` icon.
222 // Set the gray folder image. `ContextCompat` must be used until the minimum API >= 21.
223 spinnerItemImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.folder_gray));
226 // Set the text view to display the folder name.
227 spinnerItemTextView.setText(cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME)));
231 // Set the resource cursor adapter drop drown view resource.
232 foldersCursorAdapter.setDropDownViewResource(R.layout.appbar_spinner_dropdown_item);
234 // Get a handle for the folder spinner and set the adapter.
235 Spinner folderSpinner = findViewById(R.id.spinner);
236 folderSpinner.setAdapter(foldersCursorAdapter);
238 // Handle taps on the spinner dropdown.
239 folderSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
241 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
242 // Store the current folder database ID.
243 currentFolderDatabaseId = (int) id;
245 // Get a handle for the selected view.
246 TextView selectedFolderTextView = findViewById(R.id.spinner_item_textview);
248 // Store the current folder name.
249 currentFolderName = selectedFolderTextView.getText().toString();
251 // Update the list view.
252 updateBookmarksListView();
256 public void onNothingSelected(AdapterView<?> parent) {
261 // Get a handle for the bookmarks `ListView`.
262 ListView bookmarksListView = findViewById(R.id.bookmarks_databaseview_listview);
264 // Get a `Cursor` with the current contents of the bookmarks database.
265 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarks();
267 // Setup a `CursorAdapter` with `this` context. `false` disables autoRequery.
268 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
270 public View newView(Context context, Cursor cursor, ViewGroup parent) {
271 // Inflate the individual item layout. `false` does not attach it to the root.
272 return getLayoutInflater().inflate(R.layout.bookmarks_databaseview_item_linearlayout, parent, false);
276 public void bindView(View view, Context context, Cursor cursor) {
277 boolean isFolder = (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1);
279 // Get the database ID from the `Cursor` and display it in `bookmarkDatabaseIdTextView`.
280 int bookmarkDatabaseId = cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper._ID));
281 TextView bookmarkDatabaseIdTextView = view.findViewById(R.id.bookmarks_databaseview_database_id);
282 bookmarkDatabaseIdTextView.setText(String.valueOf(bookmarkDatabaseId));
284 // Get the favorite icon byte array from the `Cursor`.
285 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
286 // Convert the byte array to a `Bitmap` beginning at the beginning at the first byte and ending at the last.
287 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
288 // Display the bitmap in `bookmarkFavoriteIcon`.
289 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmarks_databaseview_favorite_icon);
290 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
292 // Get the bookmark name from the `Cursor` and display it in `bookmarkNameTextView`.
293 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
294 TextView bookmarkNameTextView = view.findViewById(R.id.bookmarks_databaseview_bookmark_name);
295 bookmarkNameTextView.setText(bookmarkNameString);
297 // Make the font bold for folders.
299 // The first argument is `null` prevent changing of the font.
300 bookmarkNameTextView.setTypeface(null, Typeface.BOLD);
301 } else { // Reset the font to default.
302 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
305 // Get the bookmark URL form the `Cursor` and display it in `bookmarkUrlTextView`.
306 String bookmarkUrlString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL));
307 TextView bookmarkUrlTextView = view.findViewById(R.id.bookmarks_databaseview_bookmark_url);
308 bookmarkUrlTextView.setText(bookmarkUrlString);
310 // Hide the URL if the bookmark is a folder.
312 bookmarkUrlTextView.setVisibility(View.GONE);
314 bookmarkUrlTextView.setVisibility(View.VISIBLE);
317 // Get the display order from the `Cursor` and display it in `bookmarkDisplayOrderTextView`.
318 int bookmarkDisplayOrder = cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER));
319 TextView bookmarkDisplayOrderTextView = view.findViewById(R.id.bookmarks_databaseview_display_order);
320 bookmarkDisplayOrderTextView.setText(String.valueOf(bookmarkDisplayOrder));
322 // Get the parent folder from the `Cursor` and display it in `bookmarkParentFolder`.
323 String bookmarkParentFolder = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.PARENT_FOLDER));
324 ImageView parentFolderImageView = view.findViewById(R.id.bookmarks_databaseview_parent_folder_icon);
325 TextView bookmarkParentFolderTextView = view.findViewById(R.id.bookmarks_databaseview_parent_folder);
327 // Make the folder name gray if it is the home folder.
328 if (bookmarkParentFolder.isEmpty()) {
329 parentFolderImageView.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.folder_gray));
330 bookmarkParentFolderTextView.setText(R.string.home_folder);
331 bookmarkParentFolderTextView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.gray_500));
333 parentFolderImageView.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.folder_dark_blue));
334 bookmarkParentFolderTextView.setText(bookmarkParentFolder);
336 // Set the text color according to the theme.
338 bookmarkParentFolderTextView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.gray_300));
340 bookmarkParentFolderTextView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.black));
346 // Update the ListView.
347 bookmarksListView.setAdapter(bookmarksCursorAdapter);
349 // Set the current folder database ID.
350 currentFolderDatabaseId = ALL_FOLDERS_DATABASE_ID;
352 // Set a listener to edit a bookmark when it is tapped.
353 bookmarksListView.setOnItemClickListener((AdapterView<?> parent, View view, int position, long id) -> {
354 // Convert the database ID to an int.
355 int databaseId = (int) id;
357 // Show the edit bookmark or edit bookmark folder dialog.
358 if (bookmarksDatabaseHelper.isFolder(databaseId)) {
359 // Save the current folder name, which is used in `onSaveBookmarkFolder()`.
360 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
362 // Show the edit bookmark folder dialog.
363 DialogFragment editBookmarkFolderDatabaseViewDialog = EditBookmarkFolderDatabaseViewDialog.folderDatabaseId(databaseId, favoriteIconBitmap);
364 editBookmarkFolderDatabaseViewDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
366 // Show the edit bookmark dialog.
367 DialogFragment editBookmarkDatabaseViewDialog = EditBookmarkDatabaseViewDialog.bookmarkDatabaseId(databaseId, favoriteIconBitmap);
368 editBookmarkDatabaseViewDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
372 // Handle long presses on the list view.
373 bookmarksListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
374 // Instantiate the common variables.
375 MenuItem selectAllMenuItem;
376 MenuItem deleteMenuItem;
377 boolean deletingBookmarks;
380 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
381 // Inflate the menu for the contextual app bar.
382 getMenuInflater().inflate(R.menu.bookmarks_databaseview_context_menu, menu);
385 mode.setTitle(R.string.bookmarks);
387 // Get handles for the menu items.
388 selectAllMenuItem = menu.findItem(R.id.select_all);
389 deleteMenuItem = menu.findItem(R.id.delete);
391 // Disable the delete menu item if a delete is pending.
392 deleteMenuItem.setEnabled(!deletingBookmarks);
399 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
405 public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
406 // Calculate the number of selected bookmarks.
407 int numberOfSelectedBookmarks = bookmarksListView.getCheckedItemCount();
409 // Adjust the ActionMode according to the number of selected bookmarks.
410 mode.setSubtitle(getString(R.string.selected) + " " + numberOfSelectedBookmarks);
412 // Do not show the select all menu item if all the bookmarks are already checked.
413 if (bookmarksListView.getCheckedItemCount() == bookmarksListView.getCount()) {
414 selectAllMenuItem.setVisible(false);
416 selectAllMenuItem.setVisible(true);
419 // Convert the database ID to an int.
420 int databaseId = (int) id;
422 // If a folder was selected, also select all the contents.
423 if (checked && bookmarksDatabaseHelper.isFolder(databaseId)) {
424 selectAllBookmarksInFolder(databaseId);
427 // Do not allow a bookmark to be deselected if the folder is selected.
429 // Get the folder name.
430 String folderName = bookmarksDatabaseHelper.getParentFolderName((int) id);
432 // If the bookmark is not in the root folder, check to see if the folder is selected.
433 if (!folderName.isEmpty()) {
434 // Get the database ID of the folder.
435 int folderDatabaseId = bookmarksDatabaseHelper.getFolderDatabaseId(folderName);
437 // Move the bookmarks cursor to the first position.
438 bookmarksCursor.moveToFirst();
440 // Initialize the folder position variable.
441 int folderPosition = -1;
443 // Get the position of the folder in the bookmarks cursor.
444 while ((folderPosition < 0) && (bookmarksCursor.getPosition() < bookmarksCursor.getCount())) {
445 // Check if the folder database ID matches the bookmark database ID.
446 if (folderDatabaseId == bookmarksCursor.getInt((bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper._ID)))) {
447 // Get the folder position.
448 folderPosition = bookmarksCursor.getPosition();
450 // Check if the folder is selected.
451 if (bookmarksListView.isItemChecked(folderPosition)) {
452 // Reselect the bookmark.
453 bookmarksListView.setItemChecked(position, true);
455 // Display a snackbar explaining why the bookmark cannot be deselected.
456 Snackbar.make(bookmarksListView, R.string.cannot_deselect_bookmark, Snackbar.LENGTH_LONG).show();
460 // Increment the bookmarks cursor.
461 bookmarksCursor.moveToNext();
468 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
469 switch (item.getItemId()) {
470 case R.id.select_all:
471 // Get the total number of bookmarks.
472 int numberOfBookmarks = bookmarksListView.getCount();
475 for (int i = 0; i < numberOfBookmarks; i++) {
476 bookmarksListView.setItemChecked(i, true);
481 // Set the deleting bookmarks flag, which prevents the delete menu item from being enabled until the current process finishes.
482 deletingBookmarks = true;
484 // Get an array of the selected row IDs.
485 long[] selectedBookmarksIdsLongArray = bookmarksListView.getCheckedItemIds();
487 // Get an array of checked bookmarks. `.clone()` makes a copy that won't change if the list view is reloaded, which is needed for re-selecting the bookmarks on undelete.
488 SparseBooleanArray selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions().clone();
490 // Update the bookmarks cursor with the current contents of the bookmarks database except for the specified database IDs.
491 switch (currentFolderDatabaseId) {
492 // Get a cursor with all the folders.
493 case ALL_FOLDERS_DATABASE_ID:
494 if (sortByDisplayOrder) {
495 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksByDisplayOrderExcept(selectedBookmarksIdsLongArray);
497 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksExcept(selectedBookmarksIdsLongArray);
501 // Get a cursor for the home folder.
502 case HOME_FOLDER_DATABASE_ID:
503 if (sortByDisplayOrder) {
504 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrderExcept(selectedBookmarksIdsLongArray, "");
506 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksExcept(selectedBookmarksIdsLongArray, "");
510 // Display the selected folder.
512 // Get a cursor for the selected folder.
513 if (sortByDisplayOrder) {
514 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrderExcept(selectedBookmarksIdsLongArray, currentFolderName);
516 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksExcept(selectedBookmarksIdsLongArray, currentFolderName);
520 // Update the list view.
521 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
523 // Create a Snackbar with the number of deleted bookmarks.
524 bookmarksDeletedSnackbar = Snackbar.make(findViewById(R.id.bookmarks_databaseview_coordinatorlayout),
525 getString(R.string.bookmarks_deleted) + " " + selectedBookmarksIdsLongArray.length, Snackbar.LENGTH_LONG)
526 .setAction(R.string.undo, view -> {
527 // Do nothing because everything will be handled by `onDismissed()` below.
529 .addCallback(new Snackbar.Callback() {
530 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
532 public void onDismissed(Snackbar snackbar, int event) {
533 if (event == Snackbar.Callback.DISMISS_EVENT_ACTION) { // The user pushed the undo button.
534 // Update the bookmarks list view with the current contents of the bookmarks database, including the "deleted bookmarks.
535 updateBookmarksListView();
537 // Re-select the previously selected bookmarks.
538 for (int i = 0; i < selectedBookmarksPositionsSparseBooleanArray.size(); i++) {
539 bookmarksListView.setItemChecked(selectedBookmarksPositionsSparseBooleanArray.keyAt(i), true);
541 } else { // The Snackbar was dismissed without the undo button being pushed.
542 // Delete each selected bookmark.
543 for (long databaseIdLong : selectedBookmarksIdsLongArray) {
544 // Convert `databaseIdLong` to an int.
545 int databaseIdInt = (int) databaseIdLong;
547 // Delete the selected bookmark.
548 bookmarksDatabaseHelper.deleteBookmark(databaseIdInt);
552 // Reset the deleting bookmarks flag.
553 deletingBookmarks = false;
555 // Enable the delete menu item.
556 deleteMenuItem.setEnabled(true);
558 // Close the activity if back has been pressed.
559 if (closeActivityAfterDismissingSnackbar) {
565 // Show the Snackbar.
566 bookmarksDeletedSnackbar.show();
570 // Consume the click.
575 public void onDestroyActionMode(ActionMode mode) {
582 public boolean onCreateOptionsMenu(Menu menu) {
584 getMenuInflater().inflate(R.menu.bookmarks_databaseview_options_menu, menu);
591 public boolean onOptionsItemSelected(MenuItem menuItem) {
592 // Get a handle for the shared preferences.
593 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
595 // Get the theme preferences.
596 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
598 // Get the ID of the menu item that was selected.
599 int menuItemId = menuItem.getItemId();
601 // Run the command that corresponds to the selected menu item.
602 switch (menuItemId) {
603 case android.R.id.home: // The home arrow is identified as `android.R.id.home`, not just `R.id.home`.
604 // Exit the activity.
608 case R.id.options_menu_sort:
609 // Update the sort by display order tracker.
610 sortByDisplayOrder = !sortByDisplayOrder;
612 // Get a handle for the bookmarks `ListView`.
613 ListView bookmarksListView = findViewById(R.id.bookmarks_databaseview_listview);
615 // Update the icon and display a snackbar.
616 if (sortByDisplayOrder) { // Sort by display order.
617 // Update the icon according to the theme.
619 menuItem.setIcon(R.drawable.sort_selected_dark);
621 menuItem.setIcon(R.drawable.sort_selected_light);
624 // Display a Snackbar indicating the current sort type.
625 Snackbar.make(bookmarksListView, R.string.sorted_by_display_order, Snackbar.LENGTH_SHORT).show();
626 } else { // Sort by database id.
627 // Update the icon according to the theme.
629 menuItem.setIcon(R.drawable.sort_dark);
631 menuItem.setIcon(R.drawable.sort_light);
634 // Display a Snackbar indicating the current sort type.
635 Snackbar.make(bookmarksListView, R.string.sorted_by_database_id, Snackbar.LENGTH_SHORT).show();
638 // Update the list view.
639 updateBookmarksListView();
646 public void onBackPressed() {
647 // Check to see if a snackbar is currently displayed. If so, it must be closed before existing so that a pending delete is completed before reloading the list view in the bookmarks activity.
648 if ((bookmarksDeletedSnackbar != null) && bookmarksDeletedSnackbar.isShown()) { // Close the bookmarks deleted snackbar before going home.
649 // Set the close flag.
650 closeActivityAfterDismissingSnackbar = true;
652 // Dismiss the snackbar.
653 bookmarksDeletedSnackbar.dismiss();
654 } else { // Go home immediately.
655 // Update the current folder in the bookmarks activity.
656 if ((currentFolderDatabaseId == ALL_FOLDERS_DATABASE_ID) || (currentFolderDatabaseId == HOME_FOLDER_DATABASE_ID)) { // All folders or the the home folder are currently displayed.
657 // Load the home folder.
658 BookmarksActivity.currentFolder = "";
659 } else { // A subfolder is currently displayed.
660 // Load the current folder.
661 BookmarksActivity.currentFolder = currentFolderName;
664 // Reload the bookmarks list view when returning to the bookmarks activity.
665 BookmarksActivity.restartFromBookmarksDatabaseViewActivity = true;
667 // Exit the bookmarks database view activity.
668 super.onBackPressed();
672 private void updateBookmarksListView() {
673 // Populate the bookmarks list view based on the spinner selection.
674 switch (currentFolderDatabaseId) {
675 // Get a cursor with all the folders.
676 case ALL_FOLDERS_DATABASE_ID:
677 if (sortByDisplayOrder) {
678 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksByDisplayOrder();
680 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarks();
684 // Get a cursor for the home folder.
685 case HOME_FOLDER_DATABASE_ID:
686 if (sortByDisplayOrder) {
687 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder("");
689 bookmarksCursor = bookmarksDatabaseHelper.getBookmarks("");
693 // Display the selected folder.
695 // Get a cursor for the selected folder.
696 if (sortByDisplayOrder) {
697 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolderName);
699 bookmarksCursor = bookmarksDatabaseHelper.getBookmarks(currentFolderName);
703 // Update the list view.
704 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
707 private void selectAllBookmarksInFolder(int folderId) {
708 // Get a handle for the bookmarks list view.
709 ListView bookmarksListView = findViewById(R.id.bookmarks_databaseview_listview);
711 // Get the folder name.
712 String folderName = bookmarksDatabaseHelper.getFolderName(folderId);
714 // Get a cursor with the contents of the folder.
715 Cursor folderCursor = bookmarksDatabaseHelper.getBookmarks(folderName);
717 // Move to the beginning of the cursor.
718 folderCursor.moveToFirst();
720 while (folderCursor.getPosition() < folderCursor.getCount()) {
721 // Get the bookmark database ID.
722 int bookmarkId = folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID));
724 // Move the bookmarks cursor to the first position.
725 bookmarksCursor.moveToFirst();
727 // Initialize the bookmark position variable.
728 int bookmarkPosition = -1;
730 // Get the position of this bookmark in the bookmarks cursor.
731 while ((bookmarkPosition < 0) && (bookmarksCursor.getPosition() < bookmarksCursor.getCount())) {
732 // Check if the bookmark IDs match.
733 if (bookmarkId == bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper._ID))) {
734 // Get the bookmark position.
735 bookmarkPosition = bookmarksCursor.getPosition();
737 // If this bookmark is a folder, select all the bookmarks inside it.
738 if (bookmarksDatabaseHelper.isFolder(bookmarkId)) {
739 selectAllBookmarksInFolder(bookmarkId);
742 // Select the bookmark.
743 bookmarksListView.setItemChecked(bookmarkPosition, true);
746 // Increment the bookmarks cursor position.
747 bookmarksCursor.moveToNext();
750 // Move to the next position.
751 folderCursor.moveToNext();
756 public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) {
757 // Get the dialog from the dialog fragment.
758 Dialog dialog = dialogFragment.getDialog();
760 // Remove the incorrect lint warning below that the dialog might be null.
761 assert dialog != null;
763 // Get handles for the views from dialog fragment.
764 RadioButton currentBookmarkIconRadioButton = dialog.findViewById(R.id.edit_bookmark_current_icon_radiobutton);
765 EditText editBookmarkNameEditText = dialog.findViewById(R.id.edit_bookmark_name_edittext);
766 EditText editBookmarkUrlEditText = dialog.findViewById(R.id.edit_bookmark_url_edittext);
767 Spinner folderSpinner = dialog.findViewById(R.id.edit_bookmark_folder_spinner);
768 EditText displayOrderEditText = dialog.findViewById(R.id.edit_bookmark_display_order_edittext);
770 // Extract the bookmark information.
771 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
772 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
773 int folderDatabaseId = (int) folderSpinner.getSelectedItemId();
774 int displayOrderInt = Integer.parseInt(displayOrderEditText.getText().toString());
776 // Instantiate the parent folder name `String`.
777 String parentFolderNameString;
779 // Set the parent folder name.
780 if (folderDatabaseId == EditBookmarkDatabaseViewDialog.HOME_FOLDER_DATABASE_ID) { // The home folder is selected. Use `""`.
781 parentFolderNameString = "";
782 } else { // Get the parent folder name from the database.
783 parentFolderNameString = bookmarksDatabaseHelper.getFolderName(folderDatabaseId);
786 // Update the bookmark.
787 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
788 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, parentFolderNameString, displayOrderInt);
789 } else { // Update the bookmark using the `WebView` favorite icon.
790 // Create a favorite icon byte array output stream.
791 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
793 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
794 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
796 // Convert the favorite icon byte array stream to a byte array.
797 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
799 // Update the bookmark and the favorite icon.
800 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, parentFolderNameString, displayOrderInt, newFavoriteIconByteArray);
803 // Update the list view.
804 updateBookmarksListView();
808 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) {
809 // Get the dialog from the dialog fragment.
810 Dialog dialog = dialogFragment.getDialog();
812 // Remove the incorrect lint warning below that the dialog might be null.
813 assert dialog != null;
815 // Get handles for the views from dialog fragment.
816 RadioButton currentBookmarkIconRadioButton = dialog.findViewById(R.id.edit_folder_current_icon_radiobutton);
817 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_default_icon_radiobutton);
818 ImageView defaultFolderIconImageView = dialog.findViewById(R.id.edit_folder_default_icon_imageview);
819 EditText editBookmarkNameEditText = dialog.findViewById(R.id.edit_folder_name_edittext);
820 Spinner parentFolderSpinner = dialog.findViewById(R.id.edit_folder_parent_folder_spinner);
821 EditText displayOrderEditText = dialog.findViewById(R.id.edit_folder_display_order_edittext);
823 // Extract the folder information.
824 String newFolderNameString = editBookmarkNameEditText.getText().toString();
825 int parentFolderDatabaseId = (int) parentFolderSpinner.getSelectedItemId();
826 int displayOrderInt = Integer.parseInt(displayOrderEditText.getText().toString());
828 // Instantiate the parent folder name `String`.
829 String parentFolderNameString;
831 // Set the parent folder name.
832 if (parentFolderDatabaseId == EditBookmarkFolderDatabaseViewDialog.HOME_FOLDER_DATABASE_ID) { // The home folder is selected. Use `""`.
833 parentFolderNameString = "";
834 } else { // Get the parent folder name from the database.
835 parentFolderNameString = bookmarksDatabaseHelper.getFolderName(parentFolderDatabaseId);
838 // Update the folder.
839 if (currentBookmarkIconRadioButton.isChecked()) { // Update the folder without changing the favorite icon.
840 bookmarksDatabaseHelper.updateFolder(selectedBookmarkDatabaseId, oldFolderNameString, newFolderNameString, parentFolderNameString, displayOrderInt);
841 } else { // Update the folder and the icon.
842 // Create the new folder icon Bitmap.
843 Bitmap folderIconBitmap;
845 // Populate the new folder icon bitmap.
846 if (defaultFolderIconRadioButton.isChecked()) {
847 // Get the default folder icon drawable.
848 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
850 // Convert the folder icon drawable to a bitmap drawable.
851 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
853 // Convert the folder icon bitmap drawable to a bitmap.
854 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
855 } else { // Use the `WebView` favorite icon.
856 // Get a copy of the favorite icon bitmap.
857 folderIconBitmap = favoriteIconBitmap;
860 // Create a folder icon byte array output stream.
861 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
863 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
864 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
866 // Convert the folder icon byte array stream to a byte array.
867 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
869 // Update the folder and the icon.
870 bookmarksDatabaseHelper.updateFolder(selectedBookmarkDatabaseId, oldFolderNameString, newFolderNameString, parentFolderNameString, displayOrderInt, newFolderIconByteArray);
873 // Update the list view.
874 updateBookmarksListView();
878 public void onDestroy() {
879 // Close the bookmarks cursor and database.
880 bookmarksCursor.close();
881 bookmarksDatabaseHelper.close();
883 // Run the default commands.