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 the current folder.
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`.
169 MainWebViewActivity.formattedUrlString = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL));
171 // Set `MainWebViewActivity` to load the new URL on restart.
172 MainWebViewActivity.loadUrlOnRestart = true;
174 // Update the bookmarks folder for the bookmarks drawer in `MainWebViewActivity`.
175 MainWebViewActivity.currentBookmarksFolder = currentFolder;
177 // Close the bookmarks drawer and reload the bookmarks `ListView` when returning to `MainWebViewActivity`.
178 MainWebViewActivity.restartFromBookmarksActivity = true;
180 // Return to `MainWebViewActivity`.
181 NavUtils.navigateUpFromSameTask(bookmarksActivity);
184 // Close the `Cursor`.
185 bookmarkCursor.close();
188 // `MultiChoiceModeListener` handles long clicks.
189 bookmarksListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
190 // Instantiate the common variables.
191 MenuItem editBookmarkMenuItem;
192 MenuItem deleteBookmarksMenuItem;
193 MenuItem selectAllBookmarksMenuItem;
194 boolean deletingBookmarks;
197 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
198 // Inflate the menu for the contextual app bar and set the title.
199 getMenuInflater().inflate(R.menu.bookmarks_context_menu, menu);
202 if (currentFolder.isEmpty()) {
203 // Use `R.string.bookmarks` if we are in the home folder.
204 mode.setTitle(R.string.bookmarks);
205 } else { // Use the current folder name as the title.
206 mode.setTitle(currentFolder);
209 // Get a handle for `MenuItems` that need to be selectively disabled.
210 moveBookmarkUpMenuItem = menu.findItem(R.id.move_bookmark_up);
211 moveBookmarkDownMenuItem = menu.findItem(R.id.move_bookmark_down);
212 editBookmarkMenuItem = menu.findItem(R.id.edit_bookmark);
213 deleteBookmarksMenuItem = menu.findItem(R.id.delete_bookmark);
214 selectAllBookmarksMenuItem = menu.findItem(R.id.context_menu_select_all_bookmarks);
216 // Disable the delete bookmarks menu item if a delete is pending.
217 if (deletingBookmarks) {
218 deleteBookmarksMenuItem.setEnabled(false);
221 // Store `contextualActionMode` so it can be closed programatically.
222 contextualActionMode = mode;
229 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
230 // Get a handle for the move to folder menu item.
231 MenuItem moveToFolderMenuItem = menu.findItem(R.id.move_to_folder);
233 // Get a `Cursor` with all of the folders.
234 Cursor folderCursor = bookmarksDatabaseHelper.getAllFoldersCursor();
236 // Enable the move to folder menu item if at least one folder exists.
237 moveToFolderMenuItem.setVisible(folderCursor.getCount() > 0);
244 public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
245 // Get a long array of the selected bookmarks.
246 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
248 // Calculate the number of selected bookmarks.
249 int numberOfSelectedBookmarks = selectedBookmarksLongArray.length;
251 // Adjust the `ActionMode` and the `Menu` according to the number of selected bookmarks.
252 if (numberOfSelectedBookmarks == 0) { // No bookmarks are selected.
253 // Close the `ActionMode`.
255 } else if (numberOfSelectedBookmarks == 1) { // One bookmark is selected.
256 // List the number of selected bookmarks in the subtitle.
257 mode.setSubtitle(getString(R.string.one_selected));
259 // Show the `Move Up`, `Move Down`, and `Edit` options.
260 moveBookmarkUpMenuItem.setVisible(true);
261 moveBookmarkDownMenuItem.setVisible(true);
262 editBookmarkMenuItem.setVisible(true);
264 // Update the enabled status of the move icons.
266 } else { // More than one bookmark is selected.
267 // List the number of selected bookmarks in the subtitle.
268 mode.setSubtitle(numberOfSelectedBookmarks + " " + getString(R.string.selected));
270 // Hide non-applicable `MenuItems`.
271 moveBookmarkUpMenuItem.setVisible(false);
272 moveBookmarkDownMenuItem.setVisible(false);
273 editBookmarkMenuItem.setVisible(false);
276 // Do not show `Select All` if all the bookmarks are already checked.
277 if (bookmarksListView.getCheckedItemIds().length == bookmarksListView.getCount()) {
278 selectAllBookmarksMenuItem.setVisible(false);
280 selectAllBookmarksMenuItem.setVisible(true);
285 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
286 // Get the menu item ID.
287 int menuItemId = item.getItemId();
289 // Instantiate the common variables.
290 int selectedBookmarkPosition;
291 int selectedBookmarkNewPosition;
292 final SparseBooleanArray selectedBookmarksPositionsSparseBooleanArray;
294 switch (menuItemId) {
295 case R.id.move_bookmark_up:
296 // Get the array of checked bookmark positions.
297 selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
299 // Store the position of the selected bookmark. Only one bookmark is selected when `move_bookmark_up` is enabled.
300 selectedBookmarkPosition = selectedBookmarksPositionsSparseBooleanArray.keyAt(0);
302 // Calculate the new position of the selected bookmark.
303 selectedBookmarkNewPosition = selectedBookmarkPosition - 1;
305 // Iterate through the bookmarks.
306 for (int i = 0; i < bookmarksListView.getCount(); i++) {
307 // Get the database ID for the current bookmark.
308 int currentBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i);
310 // Update the display order for the current bookmark.
311 if (i == selectedBookmarkPosition) { // The current bookmark is the selected bookmark.
312 // Move the current bookmark up one.
313 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i - 1);
314 } else if ((i + 1) == selectedBookmarkPosition){ // The current bookmark is immediately above the selected bookmark.
315 // Move the current bookmark down one.
316 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i + 1);
317 } else { // The current bookmark is not changing positions.
318 // Move `bookmarksCursor` to the current bookmark position.
319 bookmarksCursor.moveToPosition(i);
321 // Update the display order only if it is not correct in the database.
322 if (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER)) != i) {
323 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i);
328 // Update `bookmarksCursor` with the current contents of the bookmarks database.
329 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
331 // Update the `ListView`.
332 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
334 // Scroll with the bookmark.
335 scrollBookmarks(selectedBookmarkNewPosition);
337 // Update the enabled status of the move icons.
341 case R.id.move_bookmark_down:
342 // Get the array of checked bookmark positions.
343 selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
345 // Store the position of the selected bookmark. Only one bookmark is selected when `move_bookmark_down` is enabled.
346 selectedBookmarkPosition = selectedBookmarksPositionsSparseBooleanArray.keyAt(0);
348 // Calculate the new position of the selected bookmark.
349 selectedBookmarkNewPosition = selectedBookmarkPosition + 1;
351 // Iterate through the bookmarks.
352 for (int i = 0; i <bookmarksListView.getCount(); i++) {
353 // Get the database ID for the current bookmark.
354 int currentBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i);
356 // Update the display order for the current bookmark.
357 if (i == selectedBookmarkPosition) { // The current bookmark is the selected bookmark.
358 // Move the current bookmark down one.
359 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i + 1);
360 } else if ((i - 1) == selectedBookmarkPosition) { // The current bookmark is immediately below the selected bookmark.
361 // Move the bookmark below the selected bookmark up one.
362 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i - 1);
363 } else { // The current bookmark is not changing positions.
364 // Move `bookmarksCursor` to the current bookmark position.
365 bookmarksCursor.moveToPosition(i);
367 // Update the display order only if it is not correct in the database.
368 if (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER)) != i) {
369 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i);
374 // Update `bookmarksCursor` with the current contents of the bookmarks database.
375 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
377 // Update the `ListView`.
378 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
380 // Scroll with the bookmark.
381 scrollBookmarks(selectedBookmarkNewPosition);
383 // Update the enabled status of the move icons.
387 case R.id.move_to_folder:
388 // Store `checkedItemIds` for use by the `AlertDialog`.
389 checkedItemIds = bookmarksListView.getCheckedItemIds();
391 // Show the `MoveToFolderDialog` `AlertDialog` and name the instance `@string/move_to_folder
392 AppCompatDialogFragment moveToFolderDialog = new MoveToFolderDialog();
393 moveToFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.move_to_folder));
396 case R.id.edit_bookmark:
397 // Get the array of checked bookmark positions.
398 selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
400 // Get the position of the selected bookmark. Only one bookmark is selected when `edit_bookmark_down` is enabled.
401 selectedBookmarkPosition = selectedBookmarksPositionsSparseBooleanArray.keyAt(0);
403 // Move the `Cursor` to the selected position and find out if it is a folder.
404 bookmarksCursor.moveToPosition(selectedBookmarkPosition);
405 boolean isFolder = (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1);
407 // Get the selected bookmark database ID.
408 int databaseId = bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper._ID));
410 // Show the edit bookmark or edit bookmark folder dialog.
412 // Save the current folder name, which is used in `onSaveBookmarkFolder()`.
413 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
415 // Show the edit bookmark folder dialog.
416 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
417 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
419 // Show the edit bookmark dialog.
420 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
421 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
425 case R.id.delete_bookmark:
426 // Set the deleting bookmarks flag, which prevents the delete menu item from being enabled until the current process finishes.
427 deletingBookmarks = true;
429 // Get an array of the selected row IDs.
430 final long[] selectedBookmarksIdsLongArray = bookmarksListView.getCheckedItemIds();
432 // 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.
433 selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions().clone();
435 // Update `bookmarksCursor` with the current contents of the bookmarks database except for the specified database IDs.
436 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksCursorExcept(selectedBookmarksIdsLongArray, currentFolder);
438 // Update the `ListView`.
439 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
441 // Instantiate `snackbarMessage`.
442 String snackbarMessage;
444 // Determine how many items are in the array and prepare an appropriate `Snackbar` message.
445 if (selectedBookmarksIdsLongArray.length == 1) {
446 snackbarMessage = getString(R.string.one_bookmark_deleted);
448 snackbarMessage = selectedBookmarksIdsLongArray.length + " " + getString(R.string.bookmarks_deleted);
452 Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), snackbarMessage, Snackbar.LENGTH_LONG)
453 .setAction(R.string.undo, view -> {
454 // Do nothing because everything will be handled by `onDismissed()` below.
456 .addCallback(new Snackbar.Callback() {
458 public void onDismissed(Snackbar snackbar, int event) {
460 // The user pushed the `Undo` button.
461 case Snackbar.Callback.DISMISS_EVENT_ACTION:
462 // Update `bookmarksCursor` with the current contents of the bookmarks database, including the "deleted" bookmarks.
463 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
465 // Update the `ListView`.
466 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
468 // Re-select the previously selected bookmarks.
469 for (int i = 0; i < selectedBookmarksPositionsSparseBooleanArray.size(); i++) {
470 bookmarksListView.setItemChecked(selectedBookmarksPositionsSparseBooleanArray.keyAt(i), true);
475 // The `Snackbar` was dismissed without the `Undo` button being pushed.
477 // Delete each selected bookmark.
478 for (long databaseIdLong : selectedBookmarksIdsLongArray) {
479 // Convert `databaseIdLong` to an int.
480 int databaseIdInt = (int) databaseIdLong;
482 // Delete the contents of the folder if the selected bookmark is a folder.
483 if (bookmarksDatabaseHelper.isFolder(databaseIdInt)) {
484 deleteBookmarkFolderContents(databaseIdInt);
487 // Delete the selected bookmark.
488 bookmarksDatabaseHelper.deleteBookmark(databaseIdInt);
491 // Update the display order.
492 for (int i = 0; i < bookmarksListView.getCount(); i++) {
493 // Get the database ID for the current bookmark.
494 int currentBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i);
496 // Move `bookmarksCursor` to the current bookmark position.
497 bookmarksCursor.moveToPosition(i);
499 // Update the display order only if it is not correct in the database.
500 if (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER)) != i) {
501 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i);
506 // Enable the delete bookmarks menu item.
507 deleteBookmarksMenuItem.setEnabled(true);
509 // Reset the deleting bookmarks flag.
510 deletingBookmarks = false;
513 //Show the `SnackBar`.
516 // Close the `ActionBar`.
520 case R.id.context_menu_select_all_bookmarks:
521 // Get the total number of bookmarks.
522 int numberOfBookmarks = bookmarksListView.getCount();
525 for (int i = 0; i < numberOfBookmarks; i++) {
526 bookmarksListView.setItemChecked(i, true);
531 // Consume the click.
536 public void onDestroyActionMode(ActionMode mode) {
541 // Get handles for the `FloatingActionButtons`.
542 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
543 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
545 // Set the create new bookmark folder FAB to display the `AlertDialog`.
546 createBookmarkFolderFab.setOnClickListener(v -> {
547 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
548 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
549 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
552 // Set the create new bookmark FAB to display the `AlertDialog`.
553 createBookmarkFab.setOnClickListener(view -> {
554 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
555 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
556 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
561 public boolean onCreateOptionsMenu(Menu menu) {
563 getMenuInflater().inflate(R.menu.bookmarks_options_menu, menu);
570 public boolean onOptionsItemSelected(MenuItem menuItem) {
571 // Get the ID of the `MenuItem` that was selected.
572 int menuItemId = menuItem.getItemId();
574 switch (menuItemId) {
575 case android.R.id.home: // The home arrow is identified as `android.R.id.home`, not just `R.id.home`.
576 if (currentFolder.isEmpty()) { // Currently in the home folder.
577 // Update the bookmarks folder for the bookmarks drawer in `MainWebViewActivity`.
578 MainWebViewActivity.currentBookmarksFolder = "";
580 // Close the bookmarks drawer and reload the bookmarks `ListView` when returning to `MainWebViewActivity`.
581 MainWebViewActivity.restartFromBookmarksActivity = true;
583 // Return to `MainWebViewActivity`.
584 NavUtils.navigateUpFromSameTask(this);
585 } else { // Currently in a subfolder.
586 // Place the former parent folder in `currentFolder`.
587 currentFolder = bookmarksDatabaseHelper.getParentFolder(currentFolder);
589 // Load the new folder.
594 case R.id.options_menu_select_all_bookmarks:
595 // Get the total number of bookmarks.
596 int numberOfBookmarks = bookmarksListView.getCount();
599 for (int i = 0; i < numberOfBookmarks; i++) {
600 bookmarksListView.setItemChecked(i, true);
604 case R.id.bookmarks_database_view:
605 // Launch `BookmarksDatabaseViewActivity`.
606 Intent bookmarksDatabaseViewIntent = new Intent(this, BookmarksDatabaseViewActivity.class);
607 startActivity(bookmarksDatabaseViewIntent);
614 public void onBackPressed() {
615 if (currentFolder.isEmpty()) { // Currently in the home folder.
616 // Update the bookmarks folder for the bookmarks drawer in `MainWebViewActivity`.
617 MainWebViewActivity.currentBookmarksFolder = "";
619 // Close the bookmarks drawer and reload the bookmarks `ListView` when returning to `MainWebViewActivity`.
620 MainWebViewActivity.restartFromBookmarksActivity = true;
622 // Exit `BookmarksActivity`.
623 super.onBackPressed();
624 } else { // Currently in a subfolder.
625 // Place the former parent folder in `currentFolder`.
626 currentFolder = bookmarksDatabaseHelper.getParentFolder(currentFolder);
628 // Load the new folder.
634 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
635 // Get the `EditTexts` from the `dialogFragment`.
636 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
637 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
639 // Extract the strings from the `EditTexts`.
640 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
641 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
643 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
644 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
645 MainWebViewActivity.favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
646 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
648 // Display the new bookmark below the current items in the (0 indexed) list.
649 int newBookmarkDisplayOrder = bookmarksListView.getCount();
651 // Create the bookmark.
652 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
654 // Update `bookmarksCursor` with the current contents of this folder.
655 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
657 // Update the `ListView`.
658 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
660 // Scroll to the new bookmark.
661 bookmarksListView.setSelection(newBookmarkDisplayOrder);
665 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
666 // Get handles for the views in `dialogFragment`.
667 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
668 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
669 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
671 // Get new folder name string.
672 String folderNameString = createFolderNameEditText.getText().toString();
674 // Get the new folder icon `Bitmap`.
675 Bitmap folderIconBitmap;
676 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
677 // Get the default folder icon and convert it to a `Bitmap`.
678 Drawable folderIconDrawable = folderIconImageView.getDrawable();
679 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
680 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
681 } else { // Use the `WebView` favorite icon.
682 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
685 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
686 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
687 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
688 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
690 // Move all the bookmarks down one in the display order.
691 for (int i = 0; i < bookmarksListView.getCount(); i++) {
692 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
693 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
696 // Create the folder, which will be placed at the top of the `ListView`.
697 bookmarksDatabaseHelper.createFolder(folderNameString, currentFolder, folderIconByteArray);
699 // Update `bookmarksCursor` with the current contents of this folder.
700 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
702 // Update the `ListView`.
703 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
705 // Scroll to the new folder.
706 bookmarksListView.setSelection(0);
710 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
711 // Get handles for the views from `dialogFragment`.
712 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
713 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
714 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
716 // Store the bookmark strings.
717 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
718 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
720 // Update the bookmark.
721 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
722 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
723 } else { // Update the bookmark using the `WebView` favorite icon.
724 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
725 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
726 MainWebViewActivity.favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
727 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
729 // Update the bookmark and the favorite icon.
730 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
733 // Close the contextual action mode.
734 contextualActionMode.finish();
736 // Update `bookmarksCursor` with the contents of the current folder.
737 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
739 // Update the `ListView`.
740 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
744 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
745 // Get handles for the views from `dialogFragment`.
746 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
747 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
748 ImageView defaultFolderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
749 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
751 // Get the new folder name.
752 String newFolderNameString = editFolderNameEditText.getText().toString();
754 // Check if the favorite icon has changed.
755 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
756 // Update the name in the database.
757 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
758 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
759 // Get the new folder icon `Bitmap`.
760 Bitmap folderIconBitmap;
761 if (defaultFolderIconRadioButton.isChecked()) {
762 // Get the default folder icon and convert it to a `Bitmap`.
763 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
764 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
765 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
766 } else { // Use the `WebView` favorite icon.
767 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
770 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
771 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
772 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
773 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
775 // Update the folder icon in the database.
776 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
777 } else { // The folder icon and the name have changed.
778 // Instantiate the new folder icon `Bitmap`.
779 Bitmap folderIconBitmap;
781 // Populate the new folder icon bitmap.
782 if (defaultFolderIconRadioButton.isChecked()) {
783 // Get the default folder icon and convert it to a `Bitmap`.
784 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
785 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
786 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
787 } else { // Use the `WebView` favorite icon.
788 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
791 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
792 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
793 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
794 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
796 // Update the folder name and icon in the database.
797 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
800 // Update `bookmarksCursor` with the current contents of this folder.
801 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
803 // Update the `ListView`.
804 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
806 // Close the contextual action mode.
807 contextualActionMode.finish();
811 public void onMoveToFolder(AppCompatDialogFragment dialogFragment) {
812 // Get a handle for the `ListView` from `dialogFragment`.
813 ListView folderListView = dialogFragment.getDialog().findViewById(R.id.move_to_folder_listview);
815 // Store a long array of the selected folders.
816 long[] newFolderLongArray = folderListView.getCheckedItemIds();
818 // Get the new folder database ID. Only one folder will be selected.
819 int newFolderDatabaseId = (int) newFolderLongArray[0];
821 // Instantiate `newFolderName`.
822 String newFolderName;
824 // Set the new folder name.
825 if (newFolderDatabaseId == 0) {
826 // The new folder is the home folder, represented as `""` in the database.
829 // Get the new folder name from the database.
830 newFolderName = bookmarksDatabaseHelper.getFolderName(newFolderDatabaseId);
833 // Get a long array with the the database ID of the selected bookmarks.
834 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
836 // Move each of the selected bookmarks to the new folder.
837 for (long databaseIdLong : selectedBookmarksLongArray) {
838 // Get `databaseIdInt` for each selected bookmark.
839 int databaseIdInt = (int) databaseIdLong;
841 // Move the selected bookmark to the new folder.
842 bookmarksDatabaseHelper.moveToFolder(databaseIdInt, newFolderName);
845 // Update `bookmarksCursor` with the current contents of this folder.
846 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
848 // Update the `ListView`.
849 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
851 // Close the contextual app bar.
852 contextualActionMode.finish();
855 private void deleteBookmarkFolderContents(int databaseId) {
856 // Get the name of the folder.
857 String folderName = bookmarksDatabaseHelper.getFolderName(databaseId);
859 // Get the contents of the folder.
860 Cursor folderCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(folderName);
862 // Delete each of the bookmarks in the folder.
863 for (int i = 0; i < folderCursor.getCount(); i++) {
864 // Move `folderCursor` to the current row.
865 folderCursor.moveToPosition(i);
867 // Get the database ID of the item.
868 int itemDatabaseId = folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID));
870 // If this is a folder, recursively delete the contents first.
871 if (bookmarksDatabaseHelper.isFolder(itemDatabaseId)) {
872 deleteBookmarkFolderContents(itemDatabaseId);
875 // Delete the bookmark.
876 bookmarksDatabaseHelper.deleteBookmark(itemDatabaseId);
880 private void updateMoveIcons() {
881 // Get a long array of the selected bookmarks.
882 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
884 // Get the database IDs for the first, last, and selected bookmarks.
885 int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
886 int firstBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(0);
887 // bookmarksListView is 0 indexed.
888 int lastBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(bookmarksListView.getCount() - 1);
890 // Update the move bookmark up `MenuItem`.
891 if (selectedBookmarkDatabaseId == firstBookmarkDatabaseId) { // The selected bookmark is in the first position.
892 // Disable the move bookmark up `MenuItem`.
893 moveBookmarkUpMenuItem.setEnabled(false);
895 // Set the move bookmark up icon to be ghosted.
896 moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_disabled);
897 } else { // The selected bookmark is not in the first position.
898 // Enable the move bookmark up `MenuItem`.
899 moveBookmarkUpMenuItem.setEnabled(true);
901 // Set the icon according to the theme.
902 if (MainWebViewActivity.darkTheme) {
903 moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_enabled_dark);
905 moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_enabled_light);
909 // Update the move bookmark down `MenuItem`.
910 if (selectedBookmarkDatabaseId == lastBookmarkDatabaseId) { // The selected bookmark is in the last position.
911 // Disable the move bookmark down `MenuItem`.
912 moveBookmarkDownMenuItem.setEnabled(false);
914 // Set the move bookmark down icon to be ghosted.
915 moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_disabled);
916 } else { // The selected bookmark is not in the last position.
917 // Enable the move bookmark down `MenuItem`.
918 moveBookmarkDownMenuItem.setEnabled(true);
920 // Set the icon according to the theme.
921 if (MainWebViewActivity.darkTheme) {
922 moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_enabled_dark);
924 moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_enabled_light);
929 private void scrollBookmarks(int selectedBookmarkPosition) {
930 // Get the first and last visible bookmark positions.
931 int firstVisibleBookmarkPosition = bookmarksListView.getFirstVisiblePosition();
932 int lastVisibleBookmarkPosition = bookmarksListView.getLastVisiblePosition();
934 // Calculate the number of bookmarks per screen.
935 int numberOfBookmarksPerScreen = lastVisibleBookmarkPosition - firstVisibleBookmarkPosition;
937 // Scroll with the moved bookmark if necessary.
938 if (selectedBookmarkPosition <= firstVisibleBookmarkPosition) { // The selected bookmark position is at or above the top of the screen.
939 // Scroll to the selected bookmark position.
940 bookmarksListView.setSelection(selectedBookmarkPosition);
941 } 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`.
942 // 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`.
943 bookmarksListView.setSelection(selectedBookmarkPosition - numberOfBookmarksPerScreen + 1);
947 private void loadFolder() {
948 // Update `bookmarksCursor` with the contents of the bookmarks database for the current folder.
949 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
951 // Setup a `CursorAdapter`. `this` specifies the `Context`. `false` disables `autoRequery`.
952 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
954 public View newView(Context context, Cursor cursor, ViewGroup parent) {
955 // Inflate the individual item layout. `false` does not attach it to the root.
956 return getLayoutInflater().inflate(R.layout.bookmarks_activity_item_linearlayout, parent, false);
960 public void bindView(View view, Context context, Cursor cursor) {
961 // Get handles for the views.
962 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
963 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
965 // Get the favorite icon byte array from the `Cursor`.
966 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
968 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
969 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
971 // Display the bitmap in `bookmarkFavoriteIcon`.
972 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
974 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
975 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
976 bookmarkNameTextView.setText(bookmarkNameString);
978 // Make the font bold for folders.
979 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
980 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
981 } else { // Reset the font to default for normal bookmarks.
982 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
987 // Populate the `ListView` with the adapter.
988 bookmarksListView.setAdapter(bookmarksCursorAdapter);
990 // Set the `AppBar` title.
991 if (currentFolder.isEmpty()) {
992 appBar.setTitle(R.string.bookmarks);
994 appBar.setTitle(currentFolder);