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 `MoveToFolderDialog`. It is also used in `onCreate()`, `onOptionsItemSelected()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`,
68 // `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 `MoveToFolderDialog`. It is also used in `onCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, `onMoveToFolder()`, and `updateMoveIcons()`.
76 public static long[] checkedItemIds;
79 // `bookmarksListView` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, `onMoveToFolder()`, `updateMoveIcons()`, `scrollBookmarks()`,
80 // and `loadFolder()`.
81 private ListView bookmarksListView;
83 // `bookmarksCursor` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, `onMoveToFolder()`, `deleteBookmarkFolderContents()`, and `loadFolder()`.
84 private Cursor bookmarksCursor;
86 // `bookmarksCursorAdapter` is used in `onCreate(), `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, `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 `onSaveEditBookmarkFolder()`.
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 // Get the current folder from the `Intent`.
120 currentFolder = launchingIntent.getStringExtra("Current Folder");
122 // Set the content view.
123 setContentView(R.layout.bookmarks_coordinatorlayout);
125 // Use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
126 final Toolbar bookmarksAppBar = (Toolbar) findViewById(R.id.bookmarks_toolbar);
127 setSupportActionBar(bookmarksAppBar);
129 // Get a handle for the activity, the app bar, and the `ListView`.
130 final Activity bookmarksActivity = this;
131 appBar = getSupportActionBar();
132 bookmarksListView = (ListView) findViewById(R.id.bookmarks_listview);
134 // This assert removes the incorrect warning in Android Studio on the following line that `appBar` might be null.
135 assert appBar != null;
137 // Display the home arrow on `SupportActionBar`.
138 appBar.setDisplayHomeAsUpEnabled(true);
140 // Initialize the database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
141 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
142 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
144 // Load the home folder.
147 // Set a listener so that tapping a list item loads the URL or folder.
148 bookmarksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
150 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
151 // Convert the id from long to int to match the format of the bookmarks database.
152 int databaseID = (int) id;
154 // Get the bookmark `Cursor` for this ID and move it to the first row.
155 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
156 bookmarkCursor.moveToFirst();
158 // Act upon the bookmark according to the type.
159 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
160 // Update `currentFolder`.
161 currentFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
163 // Load the new folder.
165 } else { // The selected bookmark is not a folder.
166 // Get the bookmark URL and assign it to `formattedUrlString`. `mainWebView` will automatically reload when `BookmarksActivity` closes.
167 MainWebViewActivity.formattedUrlString = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL));
169 // Update the bookmarks folder for the bookmarks drawer in `MainWebViewActivity`.
170 MainWebViewActivity.currentBookmarksFolder = currentFolder;
172 // Close the bookmarks drawer and reload the bookmarks `ListView` when returning to `MainWebViewActivity`.
173 MainWebViewActivity.restartFromBookmarksActivity = true;
175 // Return to `MainWebViewActivity`.
176 NavUtils.navigateUpFromSameTask(bookmarksActivity);
179 // Close the `Cursor`.
180 bookmarkCursor.close();
184 // `MultiChoiceModeListener` handles long clicks.
185 bookmarksListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
186 // Instantiate the common variables.
187 MenuItem editBookmarkMenuItem;
188 MenuItem selectAllBookmarksMenuItem;
191 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
192 // Inflate the menu for the contextual app bar and set the title.
193 getMenuInflater().inflate(R.menu.bookmarks_context_menu, menu);
196 if (currentFolder.isEmpty()) {
197 // Use `R.string.bookmarks` if we are in the home folder.
198 mode.setTitle(R.string.bookmarks);
199 } else { // Use the current folder name as the title.
200 mode.setTitle(currentFolder);
203 // Get a handle for `MenuItems` that need to be selectively disabled.
204 moveBookmarkUpMenuItem = menu.findItem(R.id.move_bookmark_up);
205 moveBookmarkDownMenuItem = menu.findItem(R.id.move_bookmark_down);
206 editBookmarkMenuItem = menu.findItem(R.id.edit_bookmark);
207 selectAllBookmarksMenuItem = menu.findItem(R.id.context_menu_select_all_bookmarks);
209 // Store `contextualActionMode` so it can be closed programatically.
210 contextualActionMode = mode;
217 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
218 // Get a handle for the move to folder menu item.
219 MenuItem moveToFolderMenuItem = menu.findItem(R.id.move_to_folder);
221 // Get a `Cursor` with all of the folders.
222 Cursor folderCursor = bookmarksDatabaseHelper.getAllFoldersCursor();
224 // Enable the move to folder menu item if at least one folder exists.
225 moveToFolderMenuItem.setVisible(folderCursor.getCount() > 0);
232 public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
233 // Get a long array of the selected bookmarks.
234 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
236 // Calculate the number of selected bookmarks.
237 int numberOfSelectedBookmarks = selectedBookmarksLongArray.length;
239 // Adjust the `ActionMode` and the `Menu` according to the number of selected bookmarks.
240 if (numberOfSelectedBookmarks == 0) { // No bookmarks are selected.
241 // Close the `ActionMode`.
243 } else if (numberOfSelectedBookmarks == 1) { // One bookmark is selected.
244 // List the number of selected bookmarks in the subtitle.
245 mode.setSubtitle(getString(R.string.one_selected));
247 // Show the `Move Up`, `Move Down`, and `Edit` options.
248 moveBookmarkUpMenuItem.setVisible(true);
249 moveBookmarkDownMenuItem.setVisible(true);
250 editBookmarkMenuItem.setVisible(true);
252 // Update the enabled status of the move icons.
254 } else { // More than one bookmark is selected.
255 // List the number of selected bookmarks in the subtitle.
256 mode.setSubtitle(numberOfSelectedBookmarks + " " + getString(R.string.selected));
258 // Hide non-applicable `MenuItems`.
259 moveBookmarkUpMenuItem.setVisible(false);
260 moveBookmarkDownMenuItem.setVisible(false);
261 editBookmarkMenuItem.setVisible(false);
264 // Do not show `Select All` if all the bookmarks are already checked.
265 if (bookmarksListView.getCheckedItemIds().length == bookmarksListView.getCount()) {
266 selectAllBookmarksMenuItem.setVisible(false);
268 selectAllBookmarksMenuItem.setVisible(true);
273 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
274 // Get the menu item ID.
275 int menuItemId = item.getItemId();
277 // Instantiate the common variables.
278 int selectedBookmarkPosition;
279 int selectedBookmarkNewPosition;
280 final SparseBooleanArray selectedBookmarksPositionsSparseBooleanArray;
282 switch (menuItemId) {
283 case R.id.move_bookmark_up:
284 // Get the array of checked bookmark positions.
285 selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
287 // Store the position of the selected bookmark. Only one bookmark is selected when `move_bookmark_up` is enabled.
288 selectedBookmarkPosition = selectedBookmarksPositionsSparseBooleanArray.keyAt(0);
290 // Calculate the new position of the selected bookmark.
291 selectedBookmarkNewPosition = selectedBookmarkPosition - 1;
293 // Iterate through the bookmarks.
294 for (int i = 0; i < bookmarksListView.getCount(); i++) {
295 // Get the database ID for the current bookmark.
296 int currentBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i);
298 // Update the display order for the current bookmark.
299 if (i == selectedBookmarkPosition) { // The current bookmark is the selected bookmark.
300 // Move the current bookmark up one.
301 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i - 1);
302 } else if ((i + 1) == selectedBookmarkPosition){ // The current bookmark is immediately above the selected bookmark.
303 // Move the current bookmark down one.
304 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i + 1);
305 } else { // The current bookmark is not changing positions.
306 // Move `bookmarksCursor` to the current bookmark position.
307 bookmarksCursor.moveToPosition(i);
309 // Update the display order only if it is not correct in the database.
310 if (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER)) != i) {
311 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i);
316 // Update `bookmarksCursor` with the current contents of the bookmarks database.
317 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
319 // Update the `ListView`.
320 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
322 // Scroll with the bookmark.
323 scrollBookmarks(selectedBookmarkNewPosition);
325 // Update the enabled status of the move icons.
329 case R.id.move_bookmark_down:
330 // Get the array of checked bookmark positions.
331 selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
333 // Store the position of the selected bookmark. Only one bookmark is selected when `move_bookmark_down` is enabled.
334 selectedBookmarkPosition = selectedBookmarksPositionsSparseBooleanArray.keyAt(0);
336 // Calculate the new position of the selected bookmark.
337 selectedBookmarkNewPosition = selectedBookmarkPosition + 1;
339 // Iterate through the bookmarks.
340 for (int i = 0; i <bookmarksListView.getCount(); i++) {
341 // Get the database ID for the current bookmark.
342 int currentBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i);
344 // Update the display order for the current bookmark.
345 if (i == selectedBookmarkPosition) { // The current bookmark is the selected bookmark.
346 // Move the current bookmark down one.
347 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i + 1);
348 } else if ((i - 1) == selectedBookmarkPosition) { // The current bookmark is immediately below the selected bookmark.
349 // Move the bookmark below the selected bookmark up one.
350 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i - 1);
351 } else { // The current bookmark is not changing positions.
352 // Move `bookmarksCursor` to the current bookmark position.
353 bookmarksCursor.moveToPosition(i);
355 // Update the display order only if it is not correct in the database.
356 if (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER)) != i) {
357 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i);
362 // Update `bookmarksCursor` with the current contents of the bookmarks database.
363 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
365 // Update the `ListView`.
366 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
368 // Scroll with the bookmark.
369 scrollBookmarks(selectedBookmarkNewPosition);
371 // Update the enabled status of the move icons.
375 case R.id.move_to_folder:
376 // Store `checkedItemIds` for use by the `AlertDialog`.
377 checkedItemIds = bookmarksListView.getCheckedItemIds();
379 // Show the `MoveToFolderDialog` `AlertDialog` and name the instance `@string/move_to_folder
380 AppCompatDialogFragment moveToFolderDialog = new MoveToFolderDialog();
381 moveToFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.move_to_folder));
384 case R.id.edit_bookmark:
385 // Get the array of checked bookmark positions.
386 selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
388 // Get the position of the selected bookmark. Only one bookmark is selected when `edit_bookmark_down` is enabled.
389 selectedBookmarkPosition = selectedBookmarksPositionsSparseBooleanArray.keyAt(0);
391 // Move to the selected position and find out if it is a folder.
392 bookmarksCursor.moveToPosition(selectedBookmarkPosition);
393 boolean isFolder = (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1);
395 // Get the selected bookmark database ID.
396 int databaseId = bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper._ID));
399 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
400 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
402 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
403 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
404 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
406 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
407 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
408 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
412 case R.id.delete_bookmark:
413 // Get an array of the selected row IDs.
414 final long[] selectedBookmarksIdsLongArray = bookmarksListView.getCheckedItemIds();
416 // 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.
417 selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions().clone();
419 // Update `bookmarksCursor` with the current contents of the bookmarks database except for the specified database IDs.
420 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksCursorExcept(selectedBookmarksIdsLongArray, currentFolder);
422 // Update the `ListView`.
423 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
425 // Instantiate `snackbarMessage`.
426 String snackbarMessage;
428 // Determine how many items are in the array and prepare an appropriate `Snackbar` message.
429 if (selectedBookmarksIdsLongArray.length == 1) {
430 snackbarMessage = getString(R.string.one_bookmark_deleted);
432 snackbarMessage = selectedBookmarksIdsLongArray.length + " " + getString(R.string.bookmarks_deleted);
436 Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), snackbarMessage, Snackbar.LENGTH_LONG)
437 .setAction(R.string.undo, new View.OnClickListener() {
439 public void onClick(View view) {
440 // Do nothing because everything will be handled by `onDismissed()` below.
443 .addCallback(new Snackbar.Callback() {
445 public void onDismissed(Snackbar snackbar, int event) {
447 // The user pushed the `Undo` button.
448 case Snackbar.Callback.DISMISS_EVENT_ACTION:
449 // Update `bookmarksCursor` with the current contents of the bookmarks database, including the "deleted" bookmarks.
450 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
452 // Update the `ListView`.
453 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
455 // Re-select the previously selected bookmarks.
456 for (int i = 0; i < selectedBookmarksPositionsSparseBooleanArray.size(); i++) {
457 bookmarksListView.setItemChecked(selectedBookmarksPositionsSparseBooleanArray.keyAt(i), true);
461 // The `Snackbar` was dismissed without the `Undo` button being pushed.
463 // Delete each selected bookmark.
464 for (long databaseIdLong : selectedBookmarksIdsLongArray) {
465 // Convert `databaseIdLong` to an int.
466 int databaseIdInt = (int) databaseIdLong;
468 // Delete the contents of the folder if the selected bookmark is a folder.
469 if (bookmarksDatabaseHelper.isFolder(databaseIdInt)) {
470 deleteBookmarkFolderContents(databaseIdInt);
473 // Delete the selected bookmark.
474 bookmarksDatabaseHelper.deleteBookmark(databaseIdInt);
477 // Update the display order.
478 for (int i = 0; i < bookmarksListView.getCount(); i++) {
479 // Get the database ID for the current bookmark.
480 int currentBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i);
482 // Move `bookmarksCursor` to the current bookmark position.
483 bookmarksCursor.moveToPosition(i);
485 // Update the display order only if it is not correct in the database.
486 if (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER)) != i) {
487 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i);
494 //Show the `SnackBar`.
497 // Close the `ActionBar`.
501 case R.id.context_menu_select_all_bookmarks:
502 // Get the total number of bookmarks.
503 int numberOfBookmarks = bookmarksListView.getCount();
506 for (int i = 0; i < numberOfBookmarks; i++) {
507 bookmarksListView.setItemChecked(i, true);
512 // Consume the click.
517 public void onDestroyActionMode(ActionMode mode) {
522 // Get handles for the `FloatingActionButtons`.
523 FloatingActionButton createBookmarkFolderFab = (FloatingActionButton) findViewById(R.id.create_bookmark_folder_fab);
524 FloatingActionButton createBookmarkFab = (FloatingActionButton) findViewById(R.id.create_bookmark_fab);
526 // Set the create new bookmark folder FAB to display the `AlertDialog`.
527 createBookmarkFolderFab.setOnClickListener(new View.OnClickListener() {
529 public void onClick(View v) {
530 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
531 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
532 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
536 // Set the create new bookmark FAB to display the `AlertDialog`.
537 createBookmarkFab.setOnClickListener(new View.OnClickListener() {
539 public void onClick(View view) {
540 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
541 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
542 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
548 public boolean onCreateOptionsMenu(Menu menu) {
550 getMenuInflater().inflate(R.menu.bookmarks_options_menu, menu);
557 public boolean onOptionsItemSelected(MenuItem menuItem) {
558 // Get the ID of the `MenuItem` that was selected.
559 int menuItemId = menuItem.getItemId();
561 switch (menuItemId) {
562 case android.R.id.home: // The home arrow is identified as `android.R.id.home`, not just `R.id.home`.
563 if (currentFolder.isEmpty()) { // Currently in the home folder.
564 // Update the bookmarks folder for the bookmarks drawer in `MainWebViewActivity`.
565 MainWebViewActivity.currentBookmarksFolder = "";
567 // Close the bookmarks drawer and reload the bookmarks `ListView` when returning to `MainWebViewActivity`.
568 MainWebViewActivity.restartFromBookmarksActivity = true;
570 // Return to `MainWebViewActivity`.
571 NavUtils.navigateUpFromSameTask(this);
572 } else { // Currently in a subfolder.
573 // Place the former parent folder in `currentFolder`.
574 currentFolder = bookmarksDatabaseHelper.getParentFolder(currentFolder);
576 // Load the new folder.
581 case R.id.options_menu_select_all_bookmarks:
582 // Get the total number of bookmarks.
583 int numberOfBookmarks = bookmarksListView.getCount();
586 for (int i = 0; i < numberOfBookmarks; i++) {
587 bookmarksListView.setItemChecked(i, true);
591 case R.id.bookmarks_database_view:
592 // Launch `BookmarksDatabaseViewActivity`.
593 Intent bookmarksDatabaseViewIntent = new Intent(this, BookmarksDatabaseViewActivity.class);
594 startActivity(bookmarksDatabaseViewIntent);
601 public void onBackPressed() {
602 if (currentFolder.isEmpty()) { // Currently in the home folder.
603 // Update the bookmarks folder for the bookmarks drawer in `MainWebViewActivity`.
604 MainWebViewActivity.currentBookmarksFolder = "";
606 // Close the bookmarks drawer and reload the bookmarks `ListView` when returning to `MainWebViewActivity`.
607 MainWebViewActivity.restartFromBookmarksActivity = true;
609 // Exit `BookmarksActivity`.
610 super.onBackPressed();
611 } else { // Currently in a subfolder.
612 // Place the former parent folder in `currentFolder`.
613 currentFolder = bookmarksDatabaseHelper.getParentFolder(currentFolder);
615 // Load the new folder.
621 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
622 // Get the `EditTexts` from the `dialogFragment`.
623 EditText createBookmarkNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
624 EditText createBookmarkUrlEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
626 // Extract the strings from the `EditTexts`.
627 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
628 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
630 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
631 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
632 MainWebViewActivity.favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
633 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
635 // Display the new bookmark below the current items in the (0 indexed) list.
636 int newBookmarkDisplayOrder = bookmarksListView.getCount();
638 // Create the bookmark.
639 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, newBookmarkDisplayOrder, currentFolder, favoriteIconByteArray);
641 // Update `bookmarksCursor` with the current contents of this folder.
642 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
644 // Update the `ListView`.
645 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
647 // Scroll to the new bookmark.
648 bookmarksListView.setSelection(newBookmarkDisplayOrder);
652 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
653 // Get handles for the views in `dialogFragment`.
654 EditText createFolderNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
655 RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
656 ImageView folderIconImageView = (ImageView) dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
658 // Get new folder name string.
659 String folderNameString = createFolderNameEditText.getText().toString();
661 // Get the new folder icon `Bitmap`.
662 Bitmap folderIconBitmap;
663 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
664 // Get the default folder icon and convert it to a `Bitmap`.
665 Drawable folderIconDrawable = folderIconImageView.getDrawable();
666 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
667 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
668 } else { // Use the `WebView` favorite icon.
669 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
672 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
673 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
674 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
675 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
677 // Move all the bookmarks down one in the display order.
678 for (int i = 0; i < bookmarksListView.getCount(); i++) {
679 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
680 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
683 // Create the folder, placing it at the top of the ListView
684 bookmarksDatabaseHelper.createFolder(folderNameString, 0, currentFolder, folderIconByteArray);
686 // Update `bookmarksCursor` with the current contents of this folder.
687 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
689 // Update the `ListView`.
690 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
692 // Scroll to the new folder.
693 bookmarksListView.setSelection(0);
697 public void onSaveEditBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
698 // Get handles for the views from `dialogFragment`.
699 EditText editBookmarkNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
700 EditText editBookmarkUrlEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
701 RadioButton currentBookmarkIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
703 // Store the bookmark strings.
704 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
705 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
707 // Update the bookmark.
708 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
709 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
710 } else { // Update the bookmark using the `WebView` favorite icon.
711 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
712 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
713 MainWebViewActivity.favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
714 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
716 // Update the bookmark and the favorite icon.
717 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
720 // Close the contextual action mode.
721 contextualActionMode.finish();
723 // Update `bookmarksCursor` with the current contents of this folder.
724 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
726 // Update the `ListView`.
727 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
731 public void onSaveEditBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
732 // Get handles for the views from `dialogFragment`.
733 EditText editFolderNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
734 RadioButton currentFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
735 RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
736 ImageView folderIconImageView = (ImageView) dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon);
738 // Get the new folder name.
739 String newFolderNameString = editFolderNameEditText.getText().toString();
741 // Check if the favorite icon has changed.
742 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
743 // Update the name in the database.
744 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
745 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
746 // Get the new folder icon `Bitmap`.
747 Bitmap folderIconBitmap;
748 if (defaultFolderIconRadioButton.isChecked()) {
749 // Get the default folder icon and convert it to a `Bitmap`.
750 Drawable folderIconDrawable = folderIconImageView.getDrawable();
751 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
752 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
753 } else { // Use the `WebView` favorite icon.
754 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
757 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
758 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
759 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
760 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
762 // Update the folder icon in the database.
763 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
764 } else { // The folder icon and the name have changed.
765 // Get the new folder icon `Bitmap`.
766 Bitmap folderIconBitmap;
767 if (defaultFolderIconRadioButton.isChecked()) {
768 // Get the default folder icon and convert it to a `Bitmap`.
769 Drawable folderIconDrawable = folderIconImageView.getDrawable();
770 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
771 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
772 } else { // Use the `WebView` favorite icon.
773 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
776 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
777 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
778 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
779 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
781 // Update the folder name and icon in the database.
782 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
785 // Update `bookmarksCursor` with the current contents of this folder.
786 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
788 // Update the `ListView`.
789 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
791 // Close the contextual action mode.
792 contextualActionMode.finish();
796 public void onMoveToFolder(AppCompatDialogFragment dialogFragment) {
797 // Get a handle for the `ListView` from `dialogFragment`.
798 ListView folderListView = (ListView) dialogFragment.getDialog().findViewById(R.id.move_to_folder_listview);
800 // Store a long array of the selected folders.
801 long[] newFolderLongArray = folderListView.getCheckedItemIds();
803 // Get the new folder database ID. Only one folder will be selected.
804 int newFolderDatabaseId = (int) newFolderLongArray[0];
806 // Instantiate `newFolderName`.
807 String newFolderName;
809 // Set the new folder name.
810 if (newFolderDatabaseId == 0) {
811 // The new folder is the home folder, represented as `""` in the database.
814 // Get the new folder name from the database.
815 newFolderName = bookmarksDatabaseHelper.getFolderName(newFolderDatabaseId);
818 // Get a long array with the the database ID of the selected bookmarks.
819 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
821 // Move each of the selected bookmarks to the new folder.
822 for (long databaseIdLong : selectedBookmarksLongArray) {
823 // Get `databaseIdInt` for each selected bookmark.
824 int databaseIdInt = (int) databaseIdLong;
826 // Move the selected bookmark to the new folder.
827 bookmarksDatabaseHelper.moveToFolder(databaseIdInt, newFolderName);
830 // Update `bookmarksCursor` with the current contents of this folder.
831 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
833 // Update the `ListView`.
834 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
836 // Close the contextual app bar.
837 contextualActionMode.finish();
840 private void deleteBookmarkFolderContents(int databaseId) {
841 // Get the name of the folder.
842 String folderName = bookmarksDatabaseHelper.getFolderName(databaseId);
844 // Get the contents of the folder.
845 Cursor folderCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(folderName);
847 // Delete each of the bookmarks in the folder.
848 for (int i = 0; i < folderCursor.getCount(); i++) {
849 // Move `folderCursor` to the current row.
850 folderCursor.moveToPosition(i);
852 // Get the database ID of the item.
853 int itemDatabaseId = folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID));
855 // If this is a folder, recursively delete the contents first.
856 if (bookmarksDatabaseHelper.isFolder(itemDatabaseId)) {
857 deleteBookmarkFolderContents(itemDatabaseId);
860 // Delete the bookmark.
861 bookmarksDatabaseHelper.deleteBookmark(itemDatabaseId);
865 private void updateMoveIcons() {
866 // Get a long array of the selected bookmarks.
867 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
869 // Get the database IDs for the first, last, and selected bookmarks.
870 int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
871 int firstBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(0);
872 // bookmarksListView is 0 indexed.
873 int lastBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(bookmarksListView.getCount() - 1);
875 // Update the move bookmark up `MenuItem`.
876 if (selectedBookmarkDatabaseId == firstBookmarkDatabaseId) { // The selected bookmark is in the first position.
877 // Disable the move bookmark up `MenuItem`.
878 moveBookmarkUpMenuItem.setEnabled(false);
880 // Set the move bookmark up icon to be ghosted.
881 moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_disabled);
882 } else { // The selected bookmark is not in the first position.
883 // Enable the move bookmark up `MenuItem`.
884 moveBookmarkUpMenuItem.setEnabled(true);
886 // Set the icon according to the theme.
887 if (MainWebViewActivity.darkTheme) {
888 moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_enabled_dark);
890 moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_enabled_light);
894 // Update the move bookmark down `MenuItem`.
895 if (selectedBookmarkDatabaseId == lastBookmarkDatabaseId) { // The selected bookmark is in the last position.
896 // Disable the move bookmark down `MenuItem`.
897 moveBookmarkDownMenuItem.setEnabled(false);
899 // Set the move bookmark down icon to be ghosted.
900 moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_disabled);
901 } else { // The selected bookmark is not in the last position.
902 // Enable the move bookmark down `MenuItem`.
903 moveBookmarkDownMenuItem.setEnabled(true);
905 // Set the icon according to the theme.
906 if (MainWebViewActivity.darkTheme) {
907 moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_enabled_dark);
909 moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_enabled_light);
914 private void scrollBookmarks(int selectedBookmarkPosition) {
915 // Get the first and last visible bookmark positions.
916 int firstVisibleBookmarkPosition = bookmarksListView.getFirstVisiblePosition();
917 int lastVisibleBookmarkPosition = bookmarksListView.getLastVisiblePosition();
919 // Calculate the number of bookmarks per screen.
920 int numberOfBookmarksPerScreen = lastVisibleBookmarkPosition - firstVisibleBookmarkPosition;
922 // Scroll with the moved bookmark if necessary.
923 if (selectedBookmarkPosition <= firstVisibleBookmarkPosition) { // The selected bookmark position is at or above the top of the screen.
924 // Scroll to the selected bookmark position.
925 bookmarksListView.setSelection(selectedBookmarkPosition);
926 } 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`.
927 // 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`.
928 bookmarksListView.setSelection(selectedBookmarkPosition - numberOfBookmarksPerScreen + 1);
932 private void loadFolder() {
933 // Update `bookmarksCursor` with the contents of the bookmarks database for the current folder.
934 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
936 // Setup a `CursorAdapter`. `this` specifies the `Context`. `false` disables `autoRequery`.
937 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
939 public View newView(Context context, Cursor cursor, ViewGroup parent) {
940 // Inflate the individual item layout. `false` does not attach it to the root.
941 return getLayoutInflater().inflate(R.layout.bookmarks_activity_item_linearlayout, parent, false);
945 public void bindView(View view, Context context, Cursor cursor) {
946 // Get handles for the views.
947 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
948 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
950 // Get the favorite icon byte array from the `Cursor`.
951 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
953 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
954 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
956 // Display the bitmap in `bookmarkFavoriteIcon`.
957 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
959 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
960 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
961 bookmarkNameTextView.setText(bookmarkNameString);
963 // Make the font bold for folders.
964 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
965 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
966 } else { // Reset the font to default for normal bookmarks.
967 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
972 // Populate the `ListView` with the adapter.
973 bookmarksListView.setAdapter(bookmarksCursorAdapter);
975 // Set the `AppBar` title.
976 if (currentFolder.isEmpty()) {
977 appBar.setTitle(R.string.bookmarks);
979 appBar.setTitle(currentFolder);