2 * Copyright © 2016-2017 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.app.Activity;
23 import android.content.Context;
24 import android.content.Intent;
25 import android.database.Cursor;
26 import android.graphics.Bitmap;
27 import android.graphics.BitmapFactory;
28 import android.graphics.Typeface;
29 import android.graphics.drawable.BitmapDrawable;
30 import android.graphics.drawable.Drawable;
31 import android.os.Bundle;
32 import android.support.design.widget.FloatingActionButton;
33 import android.support.design.widget.Snackbar;
34 import android.support.v4.app.NavUtils;
35 import android.support.v7.app.ActionBar;
36 import android.support.v7.app.AppCompatActivity;
37 // `AppCompatDialogFragment` is required instead of `DialogFragment` or an error is produced on API <=22.
38 import android.support.v7.app.AppCompatDialogFragment;
39 import android.support.v7.widget.Toolbar;
40 import android.util.SparseBooleanArray;
41 import android.view.ActionMode;
42 import android.view.Menu;
43 import android.view.MenuItem;
44 import android.view.View;
45 import android.view.ViewGroup;
46 import android.widget.AbsListView;
47 import android.widget.CursorAdapter;
48 import android.widget.EditText;
49 import android.widget.ImageView;
50 import android.widget.ListView;
51 import android.widget.RadioButton;
52 import android.widget.TextView;
54 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
55 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
56 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
57 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
58 import com.stoutner.privacybrowser.dialogs.MoveToFolderDialog;
59 import com.stoutner.privacybrowser.R;
60 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
62 import java.io.ByteArrayOutputStream;
64 public class BookmarksActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener, EditBookmarkDialog.EditBookmarkListener,
65 EditBookmarkFolderDialog.EditBookmarkFolderListener, MoveToFolderDialog.MoveToFolderListener {
67 // `currentFolder` is public static so it can be accessed from `MoveToFolderDialog`.
68 // It is used in `onCreate`, `onOptionsItemSelected()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveBookmark()`, `onSaveBookmarkFolder()`, `onMoveToFolder()`, and `loadFolder()`.
69 public static String currentFolder;
71 // `checkedItemIds` is public static so it can be accessed from `MoveToFolderDialog`. It is also used in `onCreate()`, `onSaveBookmark()`, `onSaveBookmarkFolder()`, `onMoveToFolder()`, and `updateMoveIcons()`.
72 public static long[] checkedItemIds;
75 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onOptionsItemSelected()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveBookmark()`, `onSaveBookmarkFolder()`, `onMoveToFolder()`, `deleteBookmarkFolderContents()`,
77 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
79 // `bookmarksListView` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveBookmark()`, `onSaveBookmarkFolder()`, `onMoveToFolder()`, `updateMoveIcons()`, `scrollBookmarks()`,
80 // and `loadFolder()`.
81 private ListView bookmarksListView;
83 // `bookmarksCursor` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveBookmark()`, `onSaveBookmarkFolder()`, `onMoveToFolder()`, `deleteBookmarkFolderContents()`, and `loadFolder()`.
84 private Cursor bookmarksCursor;
86 // `bookmarksCursorAdapter` is used in `onCreate(), `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveBookmark()`, `onSaveBookmarkFolder()`, `onMoveToFolder()`, and `onLoadFolder()`.
87 private CursorAdapter bookmarksCursorAdapter;
89 // `contextualActionMode` is used in `onCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()` and `onMoveToFolder()`.
90 private ActionMode contextualActionMode;
92 // `appBar` is used in `onCreate()` and `loadFolder()`.
93 private ActionBar appBar;
95 // `oldFolderName` is used in `onCreate()` and `onSaveBookmarkFolder()`.
96 private String oldFolderNameString;
98 // `moveBookmarkUpMenuItem` is used in `onCreate()` and `updateMoveIcons`.
99 private MenuItem moveBookmarkUpMenuItem;
101 // `moveBookmarkDownMenuItem` is used in `onCreate()` and `updateMoveIcons`.
102 private MenuItem moveBookmarkDownMenuItem;
105 protected void onCreate(Bundle savedInstanceState) {
106 // Set the activity theme.
107 if (MainWebViewActivity.darkTheme) {
108 setTheme(R.style.PrivacyBrowserDark_SecondaryActivity);
110 setTheme(R.style.PrivacyBrowserLight_SecondaryActivity);
113 // Run the default commands.
114 super.onCreate(savedInstanceState);
116 // Get the intent that launched the activity.
117 Intent launchingIntent = getIntent();
119 // Set the current folder variable.
120 if (launchingIntent.getStringExtra("Current Folder") != null) { // Set the current folder from the intent.
121 currentFolder = launchingIntent.getStringExtra("Current Folder");
122 } else { // Set the current folder to be `""`, which is the home folder.
126 // Set the content view.
127 setContentView(R.layout.bookmarks_coordinatorlayout);
129 // Use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
130 final Toolbar bookmarksAppBar = findViewById(R.id.bookmarks_toolbar);
131 setSupportActionBar(bookmarksAppBar);
133 // Get a handle for the activity, the app bar, and the `ListView`.
134 final Activity bookmarksActivity = this;
135 appBar = getSupportActionBar();
136 bookmarksListView = findViewById(R.id.bookmarks_listview);
138 // This assert removes the incorrect warning in Android Studio on the following line that `appBar` might be null.
139 assert appBar != null;
141 // Display the home arrow on `SupportActionBar`.
142 appBar.setDisplayHomeAsUpEnabled(true);
144 // Initialize the database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
145 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
146 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
148 // Load the home folder.
151 // Set a listener so that tapping a list item loads the URL or folder.
152 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
153 // Convert the id from long to int to match the format of the bookmarks database.
154 int databaseID = (int) id;
156 // Get the bookmark `Cursor` for this ID and move it to the first row.
157 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
158 bookmarkCursor.moveToFirst();
160 // Act upon the bookmark according to the type.
161 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
162 // Update `currentFolder`.
163 currentFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
165 // Load the new folder.
167 } else { // The selected bookmark is not a folder.
168 // Get the bookmark URL and assign it to `formattedUrlString`. `mainWebView` will automatically reload when `BookmarksActivity` closes.
169 MainWebViewActivity.formattedUrlString = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL));
171 // Update the bookmarks folder for the bookmarks drawer in `MainWebViewActivity`.
172 MainWebViewActivity.currentBookmarksFolder = currentFolder;
174 // Close the bookmarks drawer and reload the bookmarks `ListView` when returning to `MainWebViewActivity`.
175 MainWebViewActivity.restartFromBookmarksActivity = true;
177 // Return to `MainWebViewActivity`.
178 NavUtils.navigateUpFromSameTask(bookmarksActivity);
181 // Close the `Cursor`.
182 bookmarkCursor.close();
185 // `MultiChoiceModeListener` handles long clicks.
186 bookmarksListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
187 // Instantiate the common variables.
188 MenuItem editBookmarkMenuItem;
189 MenuItem deleteBookmarksMenuItem;
190 MenuItem selectAllBookmarksMenuItem;
191 boolean deletingBookmarks;
194 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
195 // Inflate the menu for the contextual app bar and set the title.
196 getMenuInflater().inflate(R.menu.bookmarks_context_menu, menu);
199 if (currentFolder.isEmpty()) {
200 // Use `R.string.bookmarks` if we are in the home folder.
201 mode.setTitle(R.string.bookmarks);
202 } else { // Use the current folder name as the title.
203 mode.setTitle(currentFolder);
206 // Get a handle for `MenuItems` that need to be selectively disabled.
207 moveBookmarkUpMenuItem = menu.findItem(R.id.move_bookmark_up);
208 moveBookmarkDownMenuItem = menu.findItem(R.id.move_bookmark_down);
209 editBookmarkMenuItem = menu.findItem(R.id.edit_bookmark);
210 deleteBookmarksMenuItem = menu.findItem(R.id.delete_bookmark);
211 selectAllBookmarksMenuItem = menu.findItem(R.id.context_menu_select_all_bookmarks);
213 // Disable the delete bookmarks menu item if a delete is pending.
214 if (deletingBookmarks) {
215 deleteBookmarksMenuItem.setEnabled(false);
218 // Store `contextualActionMode` so it can be closed programatically.
219 contextualActionMode = mode;
226 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
227 // Get a handle for the move to folder menu item.
228 MenuItem moveToFolderMenuItem = menu.findItem(R.id.move_to_folder);
230 // Get a `Cursor` with all of the folders.
231 Cursor folderCursor = bookmarksDatabaseHelper.getAllFoldersCursor();
233 // Enable the move to folder menu item if at least one folder exists.
234 moveToFolderMenuItem.setVisible(folderCursor.getCount() > 0);
241 public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
242 // Get a long array of the selected bookmarks.
243 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
245 // Calculate the number of selected bookmarks.
246 int numberOfSelectedBookmarks = selectedBookmarksLongArray.length;
248 // Adjust the `ActionMode` and the `Menu` according to the number of selected bookmarks.
249 if (numberOfSelectedBookmarks == 0) { // No bookmarks are selected.
250 // Close the `ActionMode`.
252 } else if (numberOfSelectedBookmarks == 1) { // One bookmark is selected.
253 // List the number of selected bookmarks in the subtitle.
254 mode.setSubtitle(getString(R.string.one_selected));
256 // Show the `Move Up`, `Move Down`, and `Edit` options.
257 moveBookmarkUpMenuItem.setVisible(true);
258 moveBookmarkDownMenuItem.setVisible(true);
259 editBookmarkMenuItem.setVisible(true);
261 // Update the enabled status of the move icons.
263 } else { // More than one bookmark is selected.
264 // List the number of selected bookmarks in the subtitle.
265 mode.setSubtitle(numberOfSelectedBookmarks + " " + getString(R.string.selected));
267 // Hide non-applicable `MenuItems`.
268 moveBookmarkUpMenuItem.setVisible(false);
269 moveBookmarkDownMenuItem.setVisible(false);
270 editBookmarkMenuItem.setVisible(false);
273 // Do not show `Select All` if all the bookmarks are already checked.
274 if (bookmarksListView.getCheckedItemIds().length == bookmarksListView.getCount()) {
275 selectAllBookmarksMenuItem.setVisible(false);
277 selectAllBookmarksMenuItem.setVisible(true);
282 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
283 // Get the menu item ID.
284 int menuItemId = item.getItemId();
286 // Instantiate the common variables.
287 int selectedBookmarkPosition;
288 int selectedBookmarkNewPosition;
289 final SparseBooleanArray selectedBookmarksPositionsSparseBooleanArray;
291 switch (menuItemId) {
292 case R.id.move_bookmark_up:
293 // Get the array of checked bookmark positions.
294 selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
296 // Store the position of the selected bookmark. Only one bookmark is selected when `move_bookmark_up` is enabled.
297 selectedBookmarkPosition = selectedBookmarksPositionsSparseBooleanArray.keyAt(0);
299 // Calculate the new position of the selected bookmark.
300 selectedBookmarkNewPosition = selectedBookmarkPosition - 1;
302 // Iterate through the bookmarks.
303 for (int i = 0; i < bookmarksListView.getCount(); i++) {
304 // Get the database ID for the current bookmark.
305 int currentBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i);
307 // Update the display order for the current bookmark.
308 if (i == selectedBookmarkPosition) { // The current bookmark is the selected bookmark.
309 // Move the current bookmark up one.
310 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i - 1);
311 } else if ((i + 1) == selectedBookmarkPosition){ // The current bookmark is immediately above the selected bookmark.
312 // Move the current bookmark down one.
313 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i + 1);
314 } else { // The current bookmark is not changing positions.
315 // Move `bookmarksCursor` to the current bookmark position.
316 bookmarksCursor.moveToPosition(i);
318 // Update the display order only if it is not correct in the database.
319 if (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER)) != i) {
320 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i);
325 // Update `bookmarksCursor` with the current contents of the bookmarks database.
326 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
328 // Update the `ListView`.
329 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
331 // Scroll with the bookmark.
332 scrollBookmarks(selectedBookmarkNewPosition);
334 // Update the enabled status of the move icons.
338 case R.id.move_bookmark_down:
339 // Get the array of checked bookmark positions.
340 selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
342 // Store the position of the selected bookmark. Only one bookmark is selected when `move_bookmark_down` is enabled.
343 selectedBookmarkPosition = selectedBookmarksPositionsSparseBooleanArray.keyAt(0);
345 // Calculate the new position of the selected bookmark.
346 selectedBookmarkNewPosition = selectedBookmarkPosition + 1;
348 // Iterate through the bookmarks.
349 for (int i = 0; i <bookmarksListView.getCount(); i++) {
350 // Get the database ID for the current bookmark.
351 int currentBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i);
353 // Update the display order for the current bookmark.
354 if (i == selectedBookmarkPosition) { // The current bookmark is the selected bookmark.
355 // Move the current bookmark down one.
356 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i + 1);
357 } else if ((i - 1) == selectedBookmarkPosition) { // The current bookmark is immediately below the selected bookmark.
358 // Move the bookmark below the selected bookmark up one.
359 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i - 1);
360 } else { // The current bookmark is not changing positions.
361 // Move `bookmarksCursor` to the current bookmark position.
362 bookmarksCursor.moveToPosition(i);
364 // Update the display order only if it is not correct in the database.
365 if (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER)) != i) {
366 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i);
371 // Update `bookmarksCursor` with the current contents of the bookmarks database.
372 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
374 // Update the `ListView`.
375 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
377 // Scroll with the bookmark.
378 scrollBookmarks(selectedBookmarkNewPosition);
380 // Update the enabled status of the move icons.
384 case R.id.move_to_folder:
385 // Store `checkedItemIds` for use by the `AlertDialog`.
386 checkedItemIds = bookmarksListView.getCheckedItemIds();
388 // Show the `MoveToFolderDialog` `AlertDialog` and name the instance `@string/move_to_folder
389 AppCompatDialogFragment moveToFolderDialog = new MoveToFolderDialog();
390 moveToFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.move_to_folder));
393 case R.id.edit_bookmark:
394 // Get the array of checked bookmark positions.
395 selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
397 // Get the position of the selected bookmark. Only one bookmark is selected when `edit_bookmark_down` is enabled.
398 selectedBookmarkPosition = selectedBookmarksPositionsSparseBooleanArray.keyAt(0);
400 // Move the `Cursor` to the selected position and find out if it is a folder.
401 bookmarksCursor.moveToPosition(selectedBookmarkPosition);
402 boolean isFolder = (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1);
404 // Get the selected bookmark database ID.
405 int databaseId = bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper._ID));
407 // Show the edit bookmark or edit bookmark folder dialog.
409 // Save the current folder name, which is used in `onSaveBookmarkFolder()`.
410 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
412 // Show the edit bookmark folder dialog.
413 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
414 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
416 // Show the edit bookmark dialog.
417 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
418 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
422 case R.id.delete_bookmark:
423 // Set the deleting bookmarks flag, which prevents the delete menu item from being enabled until the current process finishes.
424 deletingBookmarks = true;
426 // Get an array of the selected row IDs.
427 final long[] selectedBookmarksIdsLongArray = bookmarksListView.getCheckedItemIds();
429 // Get the array of checked bookmarks. `.clone()` makes a copy that won't change if `bookmarksListView` is reloaded, which is needed for re-selecting the bookmarks on undelete.
430 selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions().clone();
432 // Update `bookmarksCursor` with the current contents of the bookmarks database except for the specified database IDs.
433 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksCursorExcept(selectedBookmarksIdsLongArray, currentFolder);
435 // Update the `ListView`.
436 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
438 // Instantiate `snackbarMessage`.
439 String snackbarMessage;
441 // Determine how many items are in the array and prepare an appropriate `Snackbar` message.
442 if (selectedBookmarksIdsLongArray.length == 1) {
443 snackbarMessage = getString(R.string.one_bookmark_deleted);
445 snackbarMessage = selectedBookmarksIdsLongArray.length + " " + getString(R.string.bookmarks_deleted);
449 Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), snackbarMessage, Snackbar.LENGTH_LONG)
450 .setAction(R.string.undo, view -> {
451 // Do nothing because everything will be handled by `onDismissed()` below.
453 .addCallback(new Snackbar.Callback() {
455 public void onDismissed(Snackbar snackbar, int event) {
457 // The user pushed the `Undo` button.
458 case Snackbar.Callback.DISMISS_EVENT_ACTION:
459 // Update `bookmarksCursor` with the current contents of the bookmarks database, including the "deleted" bookmarks.
460 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
462 // Update the `ListView`.
463 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
465 // Re-select the previously selected bookmarks.
466 for (int i = 0; i < selectedBookmarksPositionsSparseBooleanArray.size(); i++) {
467 bookmarksListView.setItemChecked(selectedBookmarksPositionsSparseBooleanArray.keyAt(i), true);
472 // The `Snackbar` was dismissed without the `Undo` button being pushed.
474 // Delete each selected bookmark.
475 for (long databaseIdLong : selectedBookmarksIdsLongArray) {
476 // Convert `databaseIdLong` to an int.
477 int databaseIdInt = (int) databaseIdLong;
479 // Delete the contents of the folder if the selected bookmark is a folder.
480 if (bookmarksDatabaseHelper.isFolder(databaseIdInt)) {
481 deleteBookmarkFolderContents(databaseIdInt);
484 // Delete the selected bookmark.
485 bookmarksDatabaseHelper.deleteBookmark(databaseIdInt);
488 // Update the display order.
489 for (int i = 0; i < bookmarksListView.getCount(); i++) {
490 // Get the database ID for the current bookmark.
491 int currentBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i);
493 // Move `bookmarksCursor` to the current bookmark position.
494 bookmarksCursor.moveToPosition(i);
496 // Update the display order only if it is not correct in the database.
497 if (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER)) != i) {
498 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i);
503 // Enable the delete bookmarks menu item.
504 deleteBookmarksMenuItem.setEnabled(true);
506 // Reset the deleting bookmarks flag.
507 deletingBookmarks = false;
510 //Show the `SnackBar`.
513 // Close the `ActionBar`.
517 case R.id.context_menu_select_all_bookmarks:
518 // Get the total number of bookmarks.
519 int numberOfBookmarks = bookmarksListView.getCount();
522 for (int i = 0; i < numberOfBookmarks; i++) {
523 bookmarksListView.setItemChecked(i, true);
528 // Consume the click.
533 public void onDestroyActionMode(ActionMode mode) {
538 // Get handles for the `FloatingActionButtons`.
539 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
540 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
542 // Set the create new bookmark folder FAB to display the `AlertDialog`.
543 createBookmarkFolderFab.setOnClickListener(v -> {
544 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
545 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
546 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
549 // Set the create new bookmark FAB to display the `AlertDialog`.
550 createBookmarkFab.setOnClickListener(view -> {
551 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
552 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
553 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
558 public boolean onCreateOptionsMenu(Menu menu) {
560 getMenuInflater().inflate(R.menu.bookmarks_options_menu, menu);
567 public boolean onOptionsItemSelected(MenuItem menuItem) {
568 // Get the ID of the `MenuItem` that was selected.
569 int menuItemId = menuItem.getItemId();
571 switch (menuItemId) {
572 case android.R.id.home: // The home arrow is identified as `android.R.id.home`, not just `R.id.home`.
573 if (currentFolder.isEmpty()) { // Currently in the home folder.
574 // Update the bookmarks folder for the bookmarks drawer in `MainWebViewActivity`.
575 MainWebViewActivity.currentBookmarksFolder = "";
577 // Close the bookmarks drawer and reload the bookmarks `ListView` when returning to `MainWebViewActivity`.
578 MainWebViewActivity.restartFromBookmarksActivity = true;
580 // Return to `MainWebViewActivity`.
581 NavUtils.navigateUpFromSameTask(this);
582 } else { // Currently in a subfolder.
583 // Place the former parent folder in `currentFolder`.
584 currentFolder = bookmarksDatabaseHelper.getParentFolder(currentFolder);
586 // Load the new folder.
591 case R.id.options_menu_select_all_bookmarks:
592 // Get the total number of bookmarks.
593 int numberOfBookmarks = bookmarksListView.getCount();
596 for (int i = 0; i < numberOfBookmarks; i++) {
597 bookmarksListView.setItemChecked(i, true);
601 case R.id.bookmarks_database_view:
602 // Launch `BookmarksDatabaseViewActivity`.
603 Intent bookmarksDatabaseViewIntent = new Intent(this, BookmarksDatabaseViewActivity.class);
604 startActivity(bookmarksDatabaseViewIntent);
611 public void onBackPressed() {
612 if (currentFolder.isEmpty()) { // Currently in the home folder.
613 // Update the bookmarks folder for the bookmarks drawer in `MainWebViewActivity`.
614 MainWebViewActivity.currentBookmarksFolder = "";
616 // Close the bookmarks drawer and reload the bookmarks `ListView` when returning to `MainWebViewActivity`.
617 MainWebViewActivity.restartFromBookmarksActivity = true;
619 // Exit `BookmarksActivity`.
620 super.onBackPressed();
621 } else { // Currently in a subfolder.
622 // Place the former parent folder in `currentFolder`.
623 currentFolder = bookmarksDatabaseHelper.getParentFolder(currentFolder);
625 // Load the new folder.
631 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
632 // Get the `EditTexts` from the `dialogFragment`.
633 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
634 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
636 // Extract the strings from the `EditTexts`.
637 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
638 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
640 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
641 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
642 MainWebViewActivity.favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
643 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
645 // Display the new bookmark below the current items in the (0 indexed) list.
646 int newBookmarkDisplayOrder = bookmarksListView.getCount();
648 // Create the bookmark.
649 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
651 // Update `bookmarksCursor` with the current contents of this folder.
652 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
654 // Update the `ListView`.
655 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
657 // Scroll to the new bookmark.
658 bookmarksListView.setSelection(newBookmarkDisplayOrder);
662 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
663 // Get handles for the views in `dialogFragment`.
664 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
665 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
666 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
668 // Get new folder name string.
669 String folderNameString = createFolderNameEditText.getText().toString();
671 // Get the new folder icon `Bitmap`.
672 Bitmap folderIconBitmap;
673 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
674 // Get the default folder icon and convert it to a `Bitmap`.
675 Drawable folderIconDrawable = folderIconImageView.getDrawable();
676 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
677 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
678 } else { // Use the `WebView` favorite icon.
679 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
682 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
683 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
684 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
685 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
687 // Move all the bookmarks down one in the display order.
688 for (int i = 0; i < bookmarksListView.getCount(); i++) {
689 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
690 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
693 // Create the folder, which will be placed at the top of the `ListView`.
694 bookmarksDatabaseHelper.createFolder(folderNameString, currentFolder, folderIconByteArray);
696 // Update `bookmarksCursor` with the current contents of this folder.
697 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
699 // Update the `ListView`.
700 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
702 // Scroll to the new folder.
703 bookmarksListView.setSelection(0);
707 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
708 // Get handles for the views from `dialogFragment`.
709 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
710 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
711 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
713 // Store the bookmark strings.
714 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
715 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
717 // Update the bookmark.
718 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
719 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
720 } else { // Update the bookmark using the `WebView` favorite icon.
721 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
722 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
723 MainWebViewActivity.favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
724 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
726 // Update the bookmark and the favorite icon.
727 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
730 // Close the contextual action mode.
731 contextualActionMode.finish();
733 // Update `bookmarksCursor` with the contents of the current folder.
734 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
736 // Update the `ListView`.
737 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
741 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
742 // Get handles for the views from `dialogFragment`.
743 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
744 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
745 ImageView defaultFolderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
746 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
748 // Get the new folder name.
749 String newFolderNameString = editFolderNameEditText.getText().toString();
751 // Check if the favorite icon has changed.
752 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
753 // Update the name in the database.
754 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
755 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
756 // Get the new folder icon `Bitmap`.
757 Bitmap folderIconBitmap;
758 if (defaultFolderIconRadioButton.isChecked()) {
759 // Get the default folder icon and convert it to a `Bitmap`.
760 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
761 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
762 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
763 } else { // Use the `WebView` favorite icon.
764 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
767 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
768 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
769 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
770 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
772 // Update the folder icon in the database.
773 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
774 } else { // The folder icon and the name have changed.
775 // Instantiate the new folder icon `Bitmap`.
776 Bitmap folderIconBitmap;
778 // Populate the new folder icon bitmap.
779 if (defaultFolderIconRadioButton.isChecked()) {
780 // Get the default folder icon and convert it to a `Bitmap`.
781 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
782 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
783 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
784 } else { // Use the `WebView` favorite icon.
785 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
788 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
789 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
790 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
791 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
793 // Update the folder name and icon in the database.
794 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
797 // Update `bookmarksCursor` with the current contents of this folder.
798 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
800 // Update the `ListView`.
801 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
803 // Close the contextual action mode.
804 contextualActionMode.finish();
808 public void onMoveToFolder(AppCompatDialogFragment dialogFragment) {
809 // Get a handle for the `ListView` from `dialogFragment`.
810 ListView folderListView = dialogFragment.getDialog().findViewById(R.id.move_to_folder_listview);
812 // Store a long array of the selected folders.
813 long[] newFolderLongArray = folderListView.getCheckedItemIds();
815 // Get the new folder database ID. Only one folder will be selected.
816 int newFolderDatabaseId = (int) newFolderLongArray[0];
818 // Instantiate `newFolderName`.
819 String newFolderName;
821 // Set the new folder name.
822 if (newFolderDatabaseId == 0) {
823 // The new folder is the home folder, represented as `""` in the database.
826 // Get the new folder name from the database.
827 newFolderName = bookmarksDatabaseHelper.getFolderName(newFolderDatabaseId);
830 // Get a long array with the the database ID of the selected bookmarks.
831 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
833 // Move each of the selected bookmarks to the new folder.
834 for (long databaseIdLong : selectedBookmarksLongArray) {
835 // Get `databaseIdInt` for each selected bookmark.
836 int databaseIdInt = (int) databaseIdLong;
838 // Move the selected bookmark to the new folder.
839 bookmarksDatabaseHelper.moveToFolder(databaseIdInt, newFolderName);
842 // Update `bookmarksCursor` with the current contents of this folder.
843 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
845 // Update the `ListView`.
846 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
848 // Close the contextual app bar.
849 contextualActionMode.finish();
852 private void deleteBookmarkFolderContents(int databaseId) {
853 // Get the name of the folder.
854 String folderName = bookmarksDatabaseHelper.getFolderName(databaseId);
856 // Get the contents of the folder.
857 Cursor folderCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(folderName);
859 // Delete each of the bookmarks in the folder.
860 for (int i = 0; i < folderCursor.getCount(); i++) {
861 // Move `folderCursor` to the current row.
862 folderCursor.moveToPosition(i);
864 // Get the database ID of the item.
865 int itemDatabaseId = folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID));
867 // If this is a folder, recursively delete the contents first.
868 if (bookmarksDatabaseHelper.isFolder(itemDatabaseId)) {
869 deleteBookmarkFolderContents(itemDatabaseId);
872 // Delete the bookmark.
873 bookmarksDatabaseHelper.deleteBookmark(itemDatabaseId);
877 private void updateMoveIcons() {
878 // Get a long array of the selected bookmarks.
879 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
881 // Get the database IDs for the first, last, and selected bookmarks.
882 int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
883 int firstBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(0);
884 // bookmarksListView is 0 indexed.
885 int lastBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(bookmarksListView.getCount() - 1);
887 // Update the move bookmark up `MenuItem`.
888 if (selectedBookmarkDatabaseId == firstBookmarkDatabaseId) { // The selected bookmark is in the first position.
889 // Disable the move bookmark up `MenuItem`.
890 moveBookmarkUpMenuItem.setEnabled(false);
892 // Set the move bookmark up icon to be ghosted.
893 moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_disabled);
894 } else { // The selected bookmark is not in the first position.
895 // Enable the move bookmark up `MenuItem`.
896 moveBookmarkUpMenuItem.setEnabled(true);
898 // Set the icon according to the theme.
899 if (MainWebViewActivity.darkTheme) {
900 moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_enabled_dark);
902 moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_enabled_light);
906 // Update the move bookmark down `MenuItem`.
907 if (selectedBookmarkDatabaseId == lastBookmarkDatabaseId) { // The selected bookmark is in the last position.
908 // Disable the move bookmark down `MenuItem`.
909 moveBookmarkDownMenuItem.setEnabled(false);
911 // Set the move bookmark down icon to be ghosted.
912 moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_disabled);
913 } else { // The selected bookmark is not in the last position.
914 // Enable the move bookmark down `MenuItem`.
915 moveBookmarkDownMenuItem.setEnabled(true);
917 // Set the icon according to the theme.
918 if (MainWebViewActivity.darkTheme) {
919 moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_enabled_dark);
921 moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_enabled_light);
926 private void scrollBookmarks(int selectedBookmarkPosition) {
927 // Get the first and last visible bookmark positions.
928 int firstVisibleBookmarkPosition = bookmarksListView.getFirstVisiblePosition();
929 int lastVisibleBookmarkPosition = bookmarksListView.getLastVisiblePosition();
931 // Calculate the number of bookmarks per screen.
932 int numberOfBookmarksPerScreen = lastVisibleBookmarkPosition - firstVisibleBookmarkPosition;
934 // Scroll with the moved bookmark if necessary.
935 if (selectedBookmarkPosition <= firstVisibleBookmarkPosition) { // The selected bookmark position is at or above the top of the screen.
936 // Scroll to the selected bookmark position.
937 bookmarksListView.setSelection(selectedBookmarkPosition);
938 } else if (selectedBookmarkPosition >= (lastVisibleBookmarkPosition - 1)) { // The selected bookmark is at or below the bottom of the screen. The `-1` handles partial bookmarks displayed at the bottom of the `ListView`.
939 // Scroll to display the selected bookmark at the bottom of the screen. `+1` assured that the entire bookmark will be displayed in situations where only a partial bookmark fits at the bottom of the `ListView`.
940 bookmarksListView.setSelection(selectedBookmarkPosition - numberOfBookmarksPerScreen + 1);
944 private void loadFolder() {
945 // Update `bookmarksCursor` with the contents of the bookmarks database for the current folder.
946 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
948 // Setup a `CursorAdapter`. `this` specifies the `Context`. `false` disables `autoRequery`.
949 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
951 public View newView(Context context, Cursor cursor, ViewGroup parent) {
952 // Inflate the individual item layout. `false` does not attach it to the root.
953 return getLayoutInflater().inflate(R.layout.bookmarks_activity_item_linearlayout, parent, false);
957 public void bindView(View view, Context context, Cursor cursor) {
958 // Get handles for the views.
959 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
960 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
962 // Get the favorite icon byte array from the `Cursor`.
963 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
965 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
966 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
968 // Display the bitmap in `bookmarkFavoriteIcon`.
969 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
971 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
972 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
973 bookmarkNameTextView.setText(bookmarkNameString);
975 // Make the font bold for folders.
976 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
977 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
978 } else { // Reset the font to default for normal bookmarks.
979 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
984 // Populate the `ListView` with the adapter.
985 bookmarksListView.setAdapter(bookmarksCursorAdapter);
987 // Set the `AppBar` title.
988 if (currentFolder.isEmpty()) {
989 appBar.setTitle(R.string.bookmarks);
991 appBar.setTitle(currentFolder);