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 import android.support.v7.app.AppCompatDialogFragment;
38 import android.support.v7.widget.Toolbar;
39 import android.util.SparseBooleanArray;
40 import android.view.ActionMode;
41 import android.view.Menu;
42 import android.view.MenuItem;
43 import android.view.View;
44 import android.view.ViewGroup;
45 import android.widget.AbsListView;
46 import android.widget.AdapterView;
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 // `bookmarksDatabaseHelper` is public static so it can be accessed from `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog` and `MoveToFolderDialog`. It is also used in `onCreate()`, `onOptionsItemSelected()`,
68 // `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, `onMoveToFolder()`, `deleteBookmarkFolderContents()`, and `loadFolder().
69 public static BookmarksDatabaseHelper bookmarksDatabaseHelper;
71 // `currentFolder` is public static so it can be accessed from `MoveToFolderDialog`.
72 // It is used in `onCreate`, `onOptionsItemSelected()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, `onMoveToFolder()`, and `loadFolder()`.
73 public static String currentFolder;
75 // `checkedItemIds` is public static so it can be accessed from `EditBookmarkDialog`, `EditBookmarkFolderDialog`, and `MoveToFolderDialog`.
76 // It is also used in `onCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, `onMoveToFolder()`, and `updateMoveIcons()`.
77 public static long[] checkedItemIds;
80 // `bookmarksListView` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, `onMoveToFolder()`, `updateMoveIcons()`, `scrollBookmarks()`,
81 // and `loadFolder()`.
82 private ListView bookmarksListView;
84 // `bookmarksCursor` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, `onMoveToFolder()`, `deleteBookmarkFolderContents()`, and `loadFolder()`.
85 private Cursor bookmarksCursor;
87 // `bookmarksCursorAdapter` is used in `onCreate(), `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, `onMoveToFolder()`, and `onLoadFolder()`.
88 private CursorAdapter bookmarksCursorAdapter;
90 // `contextualActionMode` is used in `onCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()` and `onMoveToFolder()`.
91 private ActionMode contextualActionMode;
93 // `appBar` is used in `onCreate()` and `loadFolder()`.
94 private ActionBar appBar;
96 // `oldFolderName` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
97 private String oldFolderNameString;
99 // `moveBookmarkUpMenuItem` is used in `onCreate()` and `updateMoveIcons`.
100 private MenuItem moveBookmarkUpMenuItem;
102 // `moveBookmarkDownMenuItem` is used in `onCreate()` and `updateMoveIcons`.
103 private MenuItem moveBookmarkDownMenuItem;
106 protected void onCreate(Bundle savedInstanceState) {
107 // Set the activity theme.
108 if (MainWebViewActivity.darkTheme) {
109 setTheme(R.style.PrivacyBrowserDark_SecondaryActivity);
111 setTheme(R.style.PrivacyBrowserLight_SecondaryActivity);
114 // Run the default commands.
115 super.onCreate(savedInstanceState);
117 // Set the content view.
118 setContentView(R.layout.bookmarks_coordinatorlayout);
120 // Use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
121 final Toolbar bookmarksAppBar = (Toolbar) findViewById(R.id.bookmarks_toolbar);
122 setSupportActionBar(bookmarksAppBar);
124 // Get a handle for the activity, the app bar, and the `ListView`.
125 final Activity bookmarksActivity = this;
126 appBar = getSupportActionBar();
127 bookmarksListView = (ListView) findViewById(R.id.bookmarks_listview);
129 // This assert removes the incorrect warning in Android Studio on the following line that `appBar` might be null.
130 assert appBar != null;
132 // Display the home arrow on `SupportActionBar`.
133 appBar.setDisplayHomeAsUpEnabled(true);
135 // Initialize the database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
136 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
137 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
139 // Set currentFolder to the home folder, which is `""` in the database.
142 // Load the home folder.
145 // Set a listener so that tapping a list item loads the URL or folder.
146 bookmarksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
148 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
149 // Convert the id from long to int to match the format of the bookmarks database.
150 int databaseID = (int) id;
152 // Get the bookmark `Cursor` for this ID and move it to the first row.
153 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
154 bookmarkCursor.moveToFirst();
156 // Act upon the bookmark according to the type.
157 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
158 // Update `currentFolder`.
159 currentFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
161 // Load the new folder.
163 } else { // The selected bookmark is not a folder.
164 // Get the bookmark URL and assign it to `formattedUrlString`. `mainWebView` will automatically reload when `BookmarksActivity` closes.
165 MainWebViewActivity.formattedUrlString = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL));
167 // Return to `MainWebViewActivity`.
168 NavUtils.navigateUpFromSameTask(bookmarksActivity);
171 // Close the `Cursor`.
172 bookmarkCursor.close();
176 // `MultiChoiceModeListener` handles long clicks.
177 bookmarksListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
178 // Instantiate the common variables.
179 MenuItem editBookmarkMenuItem;
180 MenuItem selectAllBookmarksMenuItem;
183 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
184 // Inflate the menu for the contextual app bar and set the title.
185 getMenuInflater().inflate(R.menu.bookmarks_context_menu, menu);
188 if (currentFolder.isEmpty()) {
189 // Use `R.string.bookmarks` if we are in the home folder.
190 mode.setTitle(R.string.bookmarks);
191 } else { // Use the current folder name as the title.
192 mode.setTitle(currentFolder);
195 // Get a handle for `MenuItems` that need to be selectively disabled.
196 moveBookmarkUpMenuItem = menu.findItem(R.id.move_bookmark_up);
197 moveBookmarkDownMenuItem = menu.findItem(R.id.move_bookmark_down);
198 editBookmarkMenuItem = menu.findItem(R.id.edit_bookmark);
199 selectAllBookmarksMenuItem = menu.findItem(R.id.context_menu_select_all_bookmarks);
201 // Store `contextualActionMode` so it can be closed programatically.
202 contextualActionMode = mode;
209 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
210 // Get a handle for the move to folder menu item.
211 MenuItem moveToFolderMenuItem = menu.findItem(R.id.move_to_folder);
213 // Get a `Cursor` with all of the folders.
214 Cursor folderCursor = bookmarksDatabaseHelper.getAllFoldersCursor();
216 // Enable the move to folder menu item if at least one folder exists.
217 moveToFolderMenuItem.setVisible(folderCursor.getCount() > 0);
224 public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
225 // Get a long array of the selected bookmarks.
226 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
228 // Calculate the number of selected bookmarks.
229 int numberOfSelectedBookmarks = selectedBookmarksLongArray.length;
231 // Adjust the `ActionMode` and the `Menu` according to the number of selected bookmarks.
232 if (numberOfSelectedBookmarks == 0) { // No bookmarks are selected.
233 // Close the `ActionMode`.
235 } else if (numberOfSelectedBookmarks == 1) { // One bookmark is selected.
236 // List the number of selected bookmarks in the subtitle.
237 mode.setSubtitle(getString(R.string.one_selected));
239 // Show the `Move Up`, `Move Down`, and `Edit` options.
240 moveBookmarkUpMenuItem.setVisible(true);
241 moveBookmarkDownMenuItem.setVisible(true);
242 editBookmarkMenuItem.setVisible(true);
244 // Update the enabled status of the move icons.
246 } else { // More than one bookmark is selected.
247 // List the number of selected bookmarks in the subtitle.
248 mode.setSubtitle(numberOfSelectedBookmarks + " " + getString(R.string.selected));
250 // Hide non-applicable `MenuItems`.
251 moveBookmarkUpMenuItem.setVisible(false);
252 moveBookmarkDownMenuItem.setVisible(false);
253 editBookmarkMenuItem.setVisible(false);
256 // Do not show `Select All` if all the bookmarks are already checked.
257 if (bookmarksListView.getCheckedItemIds().length == bookmarksListView.getCount()) {
258 selectAllBookmarksMenuItem.setVisible(false);
260 selectAllBookmarksMenuItem.setVisible(true);
265 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
266 // Get the menu item ID.
267 int menuItemId = item.getItemId();
269 // Instantiate the common variables.
270 int selectedBookmarkPosition;
271 int selectedBookmarkNewPosition;
272 final SparseBooleanArray selectedBookmarksPositionsSparseBooleanArray;
274 switch (menuItemId) {
275 case R.id.move_bookmark_up:
276 // Get the array of checked bookmark positions.
277 selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
279 // Store the position of the selected bookmark. Only one bookmark is selected when `move_bookmark_up` is enabled.
280 selectedBookmarkPosition = selectedBookmarksPositionsSparseBooleanArray.keyAt(0);
282 // Calculate the new position of the selected bookmark.
283 selectedBookmarkNewPosition = selectedBookmarkPosition - 1;
285 // Iterate through the bookmarks.
286 for (int i = 0; i < bookmarksListView.getCount(); i++) {
287 // Get the database ID for the current bookmark.
288 int currentBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i);
290 // Update the display order for the current bookmark.
291 if (i == selectedBookmarkPosition) { // The current bookmark is the selected bookmark.
292 // Move the current bookmark up one.
293 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i - 1);
294 } else if ((i + 1) == selectedBookmarkPosition){ // The current bookmark is immediately above the selected bookmark.
295 // Move the current bookmark down one.
296 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i + 1);
297 } else { // The current bookmark is not changing positions.
298 // Move `bookmarksCursor` to the current bookmark position.
299 bookmarksCursor.moveToPosition(i);
301 // Update the display order only if it is not correct in the database.
302 if (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER)) != i) {
303 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i);
308 // Update `bookmarksCursor` with the current contents of the bookmarks database.
309 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
311 // Update the `ListView`.
312 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
314 // Scroll with the bookmark.
315 scrollBookmarks(selectedBookmarkNewPosition);
317 // Update the enabled status of the move icons.
321 case R.id.move_bookmark_down:
322 // Get the array of checked bookmark positions.
323 selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
325 // Store the position of the selected bookmark. Only one bookmark is selected when `move_bookmark_down` is enabled.
326 selectedBookmarkPosition = selectedBookmarksPositionsSparseBooleanArray.keyAt(0);
328 // Calculate the new position of the selected bookmark.
329 selectedBookmarkNewPosition = selectedBookmarkPosition + 1;
331 // Iterate through the bookmarks.
332 for (int i = 0; i <bookmarksListView.getCount(); i++) {
333 // Get the database ID for the current bookmark.
334 int currentBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i);
336 // Update the display order for the current bookmark.
337 if (i == selectedBookmarkPosition) { // The current bookmark is the selected bookmark.
338 // Move the current bookmark down one.
339 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i + 1);
340 } else if ((i - 1) == selectedBookmarkPosition) { // The current bookmark is immediately below the selected bookmark.
341 // Move the bookmark below the selected bookmark up one.
342 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i - 1);
343 } else { // The current bookmark is not changing positions.
344 // Move `bookmarksCursor` to the current bookmark position.
345 bookmarksCursor.moveToPosition(i);
347 // Update the display order only if it is not correct in the database.
348 if (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER)) != i) {
349 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i);
354 // Update `bookmarksCursor` with the current contents of the bookmarks database.
355 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
357 // Update the `ListView`.
358 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
360 // Scroll with the bookmark.
361 scrollBookmarks(selectedBookmarkNewPosition);
363 // Update the enabled status of the move icons.
367 case R.id.move_to_folder:
368 // Store `checkedItemIds` for use by the `AlertDialog`.
369 checkedItemIds = bookmarksListView.getCheckedItemIds();
371 // Show the `MoveToFolderDialog` `AlertDialog` and name the instance `@string/move_to_folder
372 AppCompatDialogFragment moveToFolderDialog = new MoveToFolderDialog();
373 moveToFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.move_to_folder));
376 case R.id.edit_bookmark:
377 // Get the array of checked bookmark positions.
378 selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
380 // Get the position of the selected bookmark. Only one bookmark is selected when `edit_bookmark_down` is enabled.
381 selectedBookmarkPosition = selectedBookmarksPositionsSparseBooleanArray.keyAt(0);
383 // Move to the selected database ID and find out if it is a folder.
384 bookmarksCursor.moveToPosition(selectedBookmarkPosition);
385 boolean isFolder = (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1);
387 // Store `checkedItemIds` for use by the `AlertDialog`.
388 checkedItemIds = bookmarksListView.getCheckedItemIds();
391 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
392 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
394 // Show the `EditBookmarkFolderDialog` `AlertDialog` and name the instance `@string/edit_folder`.
395 AppCompatDialogFragment editFolderDialog = new EditBookmarkFolderDialog();
396 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
398 // Show the `EditBookmarkDialog` `AlertDialog` and name the instance `@string/edit_bookmark`.
399 AppCompatDialogFragment editBookmarkDialog = new EditBookmarkDialog();
400 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
404 case R.id.delete_bookmark:
405 // Get an array of the selected row IDs.
406 final long[] selectedBookmarksIdsLongArray = bookmarksListView.getCheckedItemIds();
408 // 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.
409 selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions().clone();
411 // Update `bookmarksCursor` with the current contents of the bookmarks database except for the specified database IDs.
412 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksCursorExcept(selectedBookmarksIdsLongArray, currentFolder);
414 // Update the `ListView`.
415 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
417 // Instantiate `snackbarMessage`.
418 String snackbarMessage;
420 // Determine how many items are in the array and prepare an appropriate `Snackbar` message.
421 if (selectedBookmarksIdsLongArray.length == 1) {
422 snackbarMessage = getString(R.string.one_bookmark_deleted);
424 snackbarMessage = selectedBookmarksIdsLongArray.length + " " + getString(R.string.bookmarks_deleted);
428 Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), snackbarMessage, Snackbar.LENGTH_LONG)
429 .setAction(R.string.undo, new View.OnClickListener() {
431 public void onClick(View view) {
432 // Do nothing because everything will be handled by `onDismissed()` below.
435 .addCallback(new Snackbar.Callback() {
437 public void onDismissed(Snackbar snackbar, int event) {
439 // The user pushed the `Undo` button.
440 case Snackbar.Callback.DISMISS_EVENT_ACTION:
441 // Update `bookmarksCursor` with the current contents of the bookmarks database, including the "deleted" bookmarks.
442 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
444 // Update the `ListView`.
445 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
447 // Re-select the previously selected bookmarks.
448 for (int i = 0; i < selectedBookmarksPositionsSparseBooleanArray.size(); i++) {
449 bookmarksListView.setItemChecked(selectedBookmarksPositionsSparseBooleanArray.keyAt(i), true);
453 // The `Snackbar` was dismissed without the `Undo` button being pushed.
455 // Delete each selected bookmark.
456 for (long databaseIdLong : selectedBookmarksIdsLongArray) {
457 // Convert `databaseIdLong` to an int.
458 int databaseIdInt = (int) databaseIdLong;
460 // Delete the contents of the folder if the selected bookmark is a folder.
461 if (bookmarksDatabaseHelper.isFolder(databaseIdInt)) {
462 deleteBookmarkFolderContents(databaseIdInt);
465 // Delete the selected bookmark.
466 bookmarksDatabaseHelper.deleteBookmark(databaseIdInt);
469 // Update the display order.
470 for (int i = 0; i < bookmarksListView.getCount(); i++) {
471 // Get the database ID for the current bookmark.
472 int currentBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i);
474 // Move `bookmarksCursor` to the current bookmark position.
475 bookmarksCursor.moveToPosition(i);
477 // Update the display order only if it is not correct in the database.
478 if (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER)) != i) {
479 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i);
486 //Show the `SnackBar`.
489 // Close the `ActionBar`.
493 case R.id.context_menu_select_all_bookmarks:
494 // Get the total number of bookmarks.
495 int numberOfBookmarks = bookmarksListView.getCount();
498 for (int i = 0; i < numberOfBookmarks; i++) {
499 bookmarksListView.setItemChecked(i, true);
504 // Consume the click.
509 public void onDestroyActionMode(ActionMode mode) {
514 // Get handles for the `FloatingActionButtons`.
515 FloatingActionButton createBookmarkFolderFab = (FloatingActionButton) findViewById(R.id.create_bookmark_folder_fab);
516 FloatingActionButton createBookmarkFab = (FloatingActionButton) findViewById(R.id.create_bookmark_fab);
518 // Set the create new bookmark folder FAB to display the `AlertDialog`.
519 createBookmarkFolderFab.setOnClickListener(new View.OnClickListener() {
521 public void onClick(View v) {
522 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
523 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
524 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
528 // Set the create new bookmark FAB to display the `AlertDialog`.
529 createBookmarkFab.setOnClickListener(new View.OnClickListener() {
531 public void onClick(View view) {
532 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
533 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
534 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
540 public boolean onCreateOptionsMenu(Menu menu) {
542 getMenuInflater().inflate(R.menu.bookmarks_options_menu, menu);
549 public boolean onOptionsItemSelected(MenuItem menuItem) {
550 // Get the ID of the `MenuItem` that was selected.
551 int menuItemId = menuItem.getItemId();
553 switch (menuItemId) {
554 case android.R.id.home: // The home arrow is identified as `android.R.id.home`, not just `R.id.home`.
555 if (currentFolder.isEmpty()) { // Currently in the home folder.
556 // Return to `MainWebViewActivity`.
557 NavUtils.navigateUpFromSameTask(this);
558 } else { // Currently in a subfolder.
559 // Place the former parent folder in `currentFolder`.
560 currentFolder = bookmarksDatabaseHelper.getParentFolder(currentFolder);
562 // Load the new folder.
567 case R.id.options_menu_select_all_bookmarks:
568 // Get the total number of bookmarks.
569 int numberOfBookmarks = bookmarksListView.getCount();
572 for (int i = 0; i < numberOfBookmarks; i++) {
573 bookmarksListView.setItemChecked(i, true);
577 case R.id.bookmarks_database_view:
578 // Launch `BookmarksDatabaseViewActivity`.
579 Intent bookmarksDatabaseViewIntent = new Intent(this, BookmarksDatabaseViewActivity.class);
580 startActivity(bookmarksDatabaseViewIntent);
587 public void onBackPressed() {
588 if (currentFolder.isEmpty()) { // Currently in the home folder.
589 // Exit `BookmarksActivity`.
590 super.onBackPressed();
591 } else { // Currently in a subfolder.
592 // Place the former parent folder in `currentFolder`.
593 currentFolder = bookmarksDatabaseHelper.getParentFolder(currentFolder);
595 // Load the new folder.
601 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
602 // Get the `EditTexts` from the `dialogFragment`.
603 EditText createBookmarkNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
604 EditText createBookmarkUrlEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
606 // Extract the strings from the `EditTexts`.
607 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
608 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
610 // Convert the favoriteIcon Bitmap to a byte array.
611 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
612 // `0` is for lossless compression (the only option for a PNG).
613 MainWebViewActivity.favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
614 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
616 // Display the new bookmark below the current items in the (0 indexed) list.
617 int newBookmarkDisplayOrder = bookmarksListView.getCount();
619 // Create the bookmark.
620 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, newBookmarkDisplayOrder, currentFolder, favoriteIconByteArray);
622 // Update `bookmarksCursor` with the current contents of this folder.
623 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
625 // Update the `ListView`.
626 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
628 // Scroll to the new bookmark.
629 bookmarksListView.setSelection(newBookmarkDisplayOrder);
633 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
634 // Get handles for the views in `dialogFragment`.
635 EditText createFolderNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
636 RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
637 ImageView folderIconImageView = (ImageView) dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
639 // Get new folder name string.
640 String folderNameString = createFolderNameEditText.getText().toString();
642 // Get the new folder icon `Bitmap`.
643 Bitmap folderIconBitmap;
644 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
645 // Get the default folder icon and convert it to a `Bitmap`.
646 Drawable folderIconDrawable = folderIconImageView.getDrawable();
647 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
648 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
649 } else { // Use the `WebView` favorite icon.
650 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
653 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
654 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
655 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
656 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
658 // Move all the bookmarks down one in the display order.
659 for (int i = 0; i < bookmarksListView.getCount(); i++) {
660 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
661 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
664 // Create the folder, placing it at the top of the ListView
665 bookmarksDatabaseHelper.createFolder(folderNameString, 0, currentFolder, folderIconByteArray);
667 // Update `bookmarksCursor` with the current contents of this folder.
668 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
670 // Update the `ListView`.
671 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
673 // Scroll to the new folder.
674 bookmarksListView.setSelection(0);
678 public void onSaveEditBookmark(AppCompatDialogFragment dialogFragment) {
679 // Get handles for the views from `dialogFragment`.
680 EditText editBookmarkNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
681 EditText editBookmarkUrlEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
682 RadioButton currentBookmarkIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
684 // Store the bookmark strings.
685 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
686 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
688 // Get an array of the selected row IDs.
689 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
691 // Get the database ID of the selected bookmark. Editing a bookmark is only possible where only one item is selected.
692 int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
694 // Update the bookmark.
695 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
696 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
697 } else { // Update the bookmark using the `WebView` favorite icon.
698 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
699 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
700 MainWebViewActivity.favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
701 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
703 // Update the bookmark and the favorite icon.
704 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
707 // Close the contextual action mode.
708 contextualActionMode.finish();
710 // Update `bookmarksCursor` with the current contents of this folder.
711 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
713 // Update the `ListView`.
714 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
718 public void onSaveEditBookmarkFolder(AppCompatDialogFragment dialogFragment) {
719 // Get handles for the views from `dialogFragment`.
720 EditText editFolderNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
721 RadioButton currentFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
722 RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
723 ImageView folderIconImageView = (ImageView) dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon);
725 // Get the new folder name.
726 String newFolderNameString = editFolderNameEditText.getText().toString();
728 // Get an array of the selected row IDs.
729 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
731 // Get the database ID of the selected bookmark. Editing a folder is only possible where only one item is selected.
732 int selectedFolderDatabaseId = (int) selectedBookmarksLongArray[0];
734 // Check if the favorite icon has changed.
735 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
736 // Update the name in the database.
737 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
738 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
739 // Get the new folder icon `Bitmap`.
740 Bitmap folderIconBitmap;
741 if (defaultFolderIconRadioButton.isChecked()) {
742 // Get the default folder icon and convert it to a `Bitmap`.
743 Drawable folderIconDrawable = folderIconImageView.getDrawable();
744 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
745 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
746 } else { // Use the `WebView` favorite icon.
747 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
750 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
751 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
752 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
753 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
755 // Update the folder icon in the database.
756 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
757 } else { // The folder icon and the name have changed.
758 // Get the new folder icon `Bitmap`.
759 Bitmap folderIconBitmap;
760 if (defaultFolderIconRadioButton.isChecked()) {
761 // Get the default folder icon and convert it to a `Bitmap`.
762 Drawable folderIconDrawable = folderIconImageView.getDrawable();
763 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
764 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
765 } else { // Use the `WebView` favorite icon.
766 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
769 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
770 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
771 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
772 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
774 // Update the folder name and icon in the database.
775 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
778 // Update `bookmarksCursor` with the current contents of this folder.
779 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
781 // Update the `ListView`.
782 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
784 // Close the contextual action mode.
785 contextualActionMode.finish();
789 public void onMoveToFolder(AppCompatDialogFragment dialogFragment) {
790 // Get a handle for the `ListView` from `dialogFragment`.
791 ListView folderListView = (ListView) dialogFragment.getDialog().findViewById(R.id.move_to_folder_listview);
793 // Store a long array of the selected folders.
794 long[] newFolderLongArray = folderListView.getCheckedItemIds();
796 // Get the new folder database ID. Only one folder will be selected.
797 int newFolderDatabaseId = (int) newFolderLongArray[0];
799 // Instantiate `newFolderName`.
800 String newFolderName;
802 // Set the new folder name.
803 if (newFolderDatabaseId == 0) {
804 // The new folder is the home folder, represented as `""` in the database.
807 // Get the new folder name from the database.
808 newFolderName = bookmarksDatabaseHelper.getFolderName(newFolderDatabaseId);
811 // Get a long array with the the database ID of the selected bookmarks.
812 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
814 // Move each of the selected bookmarks to the new folder.
815 for (long databaseIdLong : selectedBookmarksLongArray) {
816 // Get `databaseIdInt` for each selected bookmark.
817 int databaseIdInt = (int) databaseIdLong;
819 // Move the selected bookmark to the new folder.
820 bookmarksDatabaseHelper.moveToFolder(databaseIdInt, newFolderName);
823 // Update `bookmarksCursor` with the current contents of this folder.
824 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
826 // Update the `ListView`.
827 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
829 // Close the contextual app bar.
830 contextualActionMode.finish();
833 private void deleteBookmarkFolderContents(int databaseId) {
834 // Get the name of the folder.
835 String folderName = bookmarksDatabaseHelper.getFolderName(databaseId);
837 // Get the contents of the folder.
838 Cursor folderCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(folderName);
840 // Delete each of the bookmarks in the folder.
841 for (int i = 0; i < folderCursor.getCount(); i++) {
842 // Move `folderCursor` to the current row.
843 folderCursor.moveToPosition(i);
845 // Get the database ID of the item.
846 int itemDatabaseId = folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID));
848 // If this is a folder, recursively delete the contents first.
849 if (bookmarksDatabaseHelper.isFolder(itemDatabaseId)) {
850 deleteBookmarkFolderContents(itemDatabaseId);
853 // Delete the bookmark.
854 bookmarksDatabaseHelper.deleteBookmark(itemDatabaseId);
858 private void updateMoveIcons() {
859 // Get a long array of the selected bookmarks.
860 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
862 // Get the database IDs for the first, last, and selected bookmarks.
863 int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
864 int firstBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(0);
865 // bookmarksListView is 0 indexed.
866 int lastBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(bookmarksListView.getCount() - 1);
868 // Update the move bookmark up `MenuItem`.
869 if (selectedBookmarkDatabaseId == firstBookmarkDatabaseId) { // The selected bookmark is in the first position.
870 // Disable the move bookmark up `MenuItem`.
871 moveBookmarkUpMenuItem.setEnabled(false);
873 // Set the move bookmark up icon to be ghosted.
874 moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_disabled);
875 } else { // The selected bookmark is not in the first position.
876 // Enable the move bookmark up `MenuItem`.
877 moveBookmarkUpMenuItem.setEnabled(true);
879 // Set the icon according to the theme.
880 if (MainWebViewActivity.darkTheme) {
881 moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_enabled_dark);
883 moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_enabled_light);
887 // Update the move bookmark down `MenuItem`.
888 if (selectedBookmarkDatabaseId == lastBookmarkDatabaseId) { // The selected bookmark is in the last position.
889 // Disable the move bookmark down `MenuItem`.
890 moveBookmarkDownMenuItem.setEnabled(false);
892 // Set the move bookmark down icon to be ghosted.
893 moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_disabled);
894 } else { // The selected bookmark is not in the last position.
895 // Enable the move bookmark down `MenuItem`.
896 moveBookmarkDownMenuItem.setEnabled(true);
898 // Set the icon according to the theme.
899 if (MainWebViewActivity.darkTheme) {
900 moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_enabled_dark);
902 moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_enabled_light);
907 private void scrollBookmarks(int selectedBookmarkPosition) {
908 // Get the first and last visible bookmark positions.
909 int firstVisibleBookmarkPosition = bookmarksListView.getFirstVisiblePosition();
910 int lastVisibleBookmarkPosition = bookmarksListView.getLastVisiblePosition();
912 // Calculate the number of bookmarks per screen.
913 int numberOfBookmarksPerScreen = lastVisibleBookmarkPosition - firstVisibleBookmarkPosition;
915 // Scroll with the moved bookmark if necessary.
916 if (selectedBookmarkPosition <= firstVisibleBookmarkPosition) { // The selected bookmark position is at or above the top of the screen.
917 // Scroll to the selected bookmark position.
918 bookmarksListView.setSelection(selectedBookmarkPosition);
919 } 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`.
920 // 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`.
921 bookmarksListView.setSelection(selectedBookmarkPosition - numberOfBookmarksPerScreen + 1);
925 private void loadFolder() {
926 // Update `bookmarksCursor` with the contents of the bookmarks database for the current folder.
927 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
929 // Setup a `CursorAdapter`. `this` specifies the `Context`. `false` disables `autoRequery`.
930 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
932 public View newView(Context context, Cursor cursor, ViewGroup parent) {
933 // Inflate the individual item layout. `false` does not attach it to the root.
934 return getLayoutInflater().inflate(R.layout.bookmarks_activity_item_linearlayout, parent, false);
938 public void bindView(View view, Context context, Cursor cursor) {
939 // Get handles for the views.
940 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
941 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
943 // Get the favorite icon byte array from the `Cursor`.
944 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
946 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
947 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
949 // Display the bitmap in `bookmarkFavoriteIcon`.
950 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
952 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
953 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
954 bookmarkNameTextView.setText(bookmarkNameString);
956 // Make the font bold for folders.
957 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
958 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
959 } else { // Reset the font to default for normal bookmarks.
960 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
965 // Populate the `ListView` with the adapter.
966 bookmarksListView.setAdapter(bookmarksCursorAdapter);
968 // Set the `AppBar` title.
969 if (currentFolder.isEmpty()) {
970 appBar.setTitle(R.string.bookmarks);
972 appBar.setTitle(currentFolder);