Create a dark theme for `BookMarksActivity` and `BookmarksDatabaseViewActivity`.
[PrivacyBrowser.git] / app / src / main / java / com / stoutner / privacybrowser / activities / BookmarksActivity.java
1 /*
2  * Copyright © 2016-2017 Soren Stoutner <soren@stoutner.com>.
3  *
4  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 package com.stoutner.privacybrowser.activities;
21
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;
53
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;
61
62 import java.io.ByteArrayOutputStream;
63
64 public class BookmarksActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener, EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener,
65         MoveToFolderDialog.MoveToFolderListener {
66
67     // `bookmarksDatabaseHelper` is public static so it can be accessed from `EditBookmarkDialog` and `MoveToFolderDialog`.  It is also used in `onCreate()`,
68     // `onCreateBookmarkCreate()`, `updateBookmarksListView()`, and `updateBookmarksListViewExcept()`.
69     public static BookmarksDatabaseHelper bookmarksDatabaseHelper;
70
71     // `currentFolder` is public static so it can be accessed from `MoveToFolderDialog`.
72     // It is used in `onCreate`, `onOptionsItemSelected()`, `onCreateBookmarkCreate`, `onCreateBookmarkFolderCreate`, and `onEditBookmarkSave`.
73     public static String currentFolder;
74
75     // `checkedItemIds` is public static so it can be accessed from `EditBookmarkDialog`, `EditBookmarkFolderDialog`, and `MoveToFolderDialog`.
76     // It is also used in `onActionItemClicked`.
77     public static long[] checkedItemIds;
78
79
80     // `bookmarksListView` is used in `onCreate()`, `updateBookmarksListView()`, and `updateBookmarksListViewExcept()`.
81     private ListView bookmarksListView;
82
83     // `contextualActionMode` is used in `onCreate()` and `onEditBookmarkSave()`.
84     private ActionMode contextualActionMode;
85
86     // `selectedBookmarkPosition` is used in `onCreate()` and `onEditBookmarkSave()`.
87     private int selectedBookmarkPosition;
88
89     // `appBar` is used in `onCreate()` and `updateBookmarksListView()`.
90     private ActionBar appBar;
91
92     // `bookmarksCursor` is used in `onCreate()`, `updateBookmarksListView()`, and `updateBookmarksListViewExcept()`.
93     private Cursor bookmarksCursor;
94
95     // `oldFolderName` is used in `onCreate()` and `onEditBookmarkFolderSave()`.
96     private String oldFolderNameString;
97
98     @Override
99     protected void onCreate(Bundle savedInstanceState) {
100         // Set the activity theme.
101         if (MainWebViewActivity.darkTheme) {
102             setTheme(R.style.PrivacyBrowserDark_SecondaryActivity);
103         } else {
104             setTheme(R.style.PrivacyBrowserLight_SecondaryActivity);
105         }
106
107         // Run the default commands.
108         super.onCreate(savedInstanceState);
109
110         // Set the content view.
111         setContentView(R.layout.bookmarks_coordinatorlayout);
112
113         // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
114         final Toolbar bookmarksAppBar = (Toolbar) findViewById(R.id.bookmarks_toolbar);
115         setSupportActionBar(bookmarksAppBar);
116
117         // Display the home arrow on `SupportActionBar`.
118         appBar = getSupportActionBar();
119         assert appBar != null;// This assert removes the incorrect warning in Android Studio on the following line that `appBar` might be null.
120         appBar.setDisplayHomeAsUpEnabled(true);
121
122
123         // Initialize the database handler and the `ListView`.  `this` specifies the context.  The two `nulls` do not specify the database name or a `CursorFactory`.
124         // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
125         bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
126         bookmarksListView = (ListView) findViewById(R.id.bookmarks_listview);
127
128         // Set currentFolder to the home folder, which is `""` in the database.
129         currentFolder = "";
130
131         // Display the bookmarks in the ListView.
132         updateBookmarksListView(currentFolder);
133
134         // Set a listener so that tapping a list item loads the URL.  We need to store the activity in a variable so that we can return to the parent activity after loading the URL.
135         final Activity bookmarksActivity = this;
136         bookmarksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
137             @Override
138             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
139                 // Convert the id from long to int to match the format of the bookmarks database.
140                 int databaseID = (int) id;
141
142                 // Get the bookmark `Cursor` for this ID and move it to the first row.
143                 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
144                 bookmarkCursor.moveToFirst();
145
146                 // If the bookmark is a folder load its contents into the ListView.
147                 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
148                     // Update `currentFolder`.
149                     currentFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
150
151                     // Reload the ListView with `currentFolder`.
152                     updateBookmarksListView(currentFolder);
153                 } else {  // Load the URL into `mainWebView`.
154                     // Get the bookmark URL and assign it to formattedUrlString.  `mainWebView` will automatically reload when `BookmarksActivity` closes.
155                     MainWebViewActivity.formattedUrlString = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL));
156
157                     NavUtils.navigateUpFromSameTask(bookmarksActivity);
158                 }
159
160                 // Close the `Cursor`.
161                 bookmarkCursor.close();
162             }
163         });
164
165         // `MultiChoiceModeListener` handles long clicks.
166         bookmarksListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
167             // `moveBookmarkUpMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
168             MenuItem moveBookmarkUpMenuItem;
169
170             // `moveBookmarkDownMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
171             MenuItem moveBookmarkDownMenuItem;
172
173             // `editBookmarkMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
174             MenuItem editBookmarkMenuItem;
175
176             // `selectAllBookmarks` is used in `onCreateActionMode()` and `onItemCheckedStateChanges`.
177             MenuItem selectAllBookmarksMenuItem;
178
179             @Override
180             public boolean onCreateActionMode(ActionMode mode, Menu menu) {
181                 // Inflate the menu for the contextual app bar and set the title.
182                 getMenuInflater().inflate(R.menu.bookmarks_context_menu, menu);
183
184                 // Set the title.
185                 if (currentFolder.isEmpty()) {
186                     // Use `R.string.bookmarks` if we are in the home folder.
187                     mode.setTitle(R.string.bookmarks);
188                 } else {  // Use the current folder name as the title.
189                     mode.setTitle(currentFolder);
190                 }
191
192                 // Get a handle for MenuItems we need to selectively disable.
193                 moveBookmarkUpMenuItem = menu.findItem(R.id.move_bookmark_up);
194                 moveBookmarkDownMenuItem = menu.findItem(R.id.move_bookmark_down);
195                 editBookmarkMenuItem = menu.findItem(R.id.edit_bookmark);
196                 selectAllBookmarksMenuItem = menu.findItem(R.id.context_menu_select_all_bookmarks);
197
198                 // Store `contextualActionMode` so we can close it programatically.
199                 contextualActionMode = mode;
200
201                 return true;
202             }
203
204             @Override
205             public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
206                 return false;
207             }
208
209             @Override
210             public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
211                 // Get an array of the selected bookmarks.
212                 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
213
214                 // Calculate the number of selected bookmarks.
215                 int numberOfSelectedBookmarks = selectedBookmarksLongArray.length;
216
217                 // Adjust the `mode` and the menu for the number of selected bookmarks.
218                 if (numberOfSelectedBookmarks == 0) {
219                     mode.finish();
220                 } else if (numberOfSelectedBookmarks == 1) {
221                     // List the number of selected bookmarks in the subtitle.
222                     mode.setSubtitle(getString(R.string.one_selected));
223
224                     // Show the `Move Up`, `Move Down`, and  `Edit` options.
225                     moveBookmarkUpMenuItem.setVisible(true);
226                     moveBookmarkDownMenuItem.setVisible(true);
227                     editBookmarkMenuItem.setVisible(true);
228
229                     // Get the database IDs for the bookmarks.
230                     int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
231                     int firstBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(0);
232                     // bookmarksListView is 0 indexed.
233                     int lastBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(bookmarksListView.getCount() - 1);
234
235                     // Disable `moveBookmarkUpMenuItem` if the selected bookmark is at the top of the ListView.
236                     if (selectedBookmarkDatabaseId == firstBookmarkDatabaseId) {
237                         moveBookmarkUpMenuItem.setEnabled(false);
238                         moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_disabled);
239                     } else {  // Otherwise enable `moveBookmarkUpMenuItem`.
240                         moveBookmarkUpMenuItem.setEnabled(true);
241
242                         // Set the icon according to the theme.
243                         if (MainWebViewActivity.darkTheme) {
244                             moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_enabled_dark);
245                         } else {
246                             moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_enabled_light);
247                         }
248                     }
249
250                     // Disable `moveBookmarkDownMenuItem` if the selected bookmark is at the bottom of the ListView.
251                     if (selectedBookmarkDatabaseId == lastBookmarkDatabaseId) {
252                         moveBookmarkDownMenuItem.setEnabled(false);
253                         moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_disabled);
254                     } else {  // Otherwise enable `moveBookmarkDownMenuItem`.
255                         moveBookmarkDownMenuItem.setEnabled(true);
256
257                         // Set the icon according to the theme.
258                         if (MainWebViewActivity.darkTheme) {
259                             moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_enabled_dark);
260                         } else {
261                             moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_enabled_light);
262                         }
263                     }
264                 } else {  // More than one bookmark is selected.
265                     // List the number of selected bookmarks in the subtitle.
266                     mode.setSubtitle(numberOfSelectedBookmarks + " " + getString(R.string.selected));
267
268                     // Hide non-applicable `MenuItems`.
269                     moveBookmarkUpMenuItem.setVisible(false);
270                     moveBookmarkDownMenuItem.setVisible(false);
271                     editBookmarkMenuItem.setVisible(false);
272                 }
273
274                 // Do not show `Select All` if all the bookmarks are already checked.
275                 if (bookmarksListView.getCheckedItemIds().length == bookmarksListView.getCount()) {
276                     selectAllBookmarksMenuItem.setVisible(false);
277                 } else {
278                     selectAllBookmarksMenuItem.setVisible(true);
279                 }
280             }
281
282             @Override
283             public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
284                 int menuItemId = item.getItemId();
285
286                 // `numberOfBookmarks` is used in `R.id.move_bookmark_up_enabled`, `R.id.move_bookmark_down_enabled`, and `R.id.context_menu_select_all_bookmarks`.
287                 int numberOfBookmarks;
288
289                 // `selectedBookmarkLongArray` is used in `R.id.move_bookmark_up`, `R.id.move_bookmark_down`, and `R.id.edit_bookmark`.
290                 long[]selectedBookmarkLongArray;
291                 // `selectedBookmarkDatabaseId` is used in `R.id.move_bookmark_up`, `R.id.move_bookmark_down`, and `R.id.edit_bookmark`.
292                 int selectedBookmarkDatabaseId;
293                 // `selectedBookmarkNewPosition` is used in `R.id.move_bookmark_up` and `R.id.move_bookmark_down`.
294                 int selectedBookmarkNewPosition;
295                 // `bookmarkPositionSparseBooleanArray` is used in `R.id.edit_bookmark` and `R.id.delete_bookmark`.
296                 SparseBooleanArray bookmarkPositionSparseBooleanArray;
297
298                 switch (menuItemId) {
299                     case R.id.move_bookmark_up:
300                         // Get the selected bookmark database ID.
301                         selectedBookmarkLongArray = bookmarksListView.getCheckedItemIds();
302                         selectedBookmarkDatabaseId = (int) selectedBookmarkLongArray[0];
303
304                         // Initialize `selectedBookmarkNewPosition`.
305                         selectedBookmarkNewPosition = 0;
306
307                         for (int i = 0; i < bookmarksListView.getCount(); i++) {
308                             int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
309                             int nextBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i + 1);
310
311                             if (databaseId == selectedBookmarkDatabaseId || nextBookmarkDatabaseId == selectedBookmarkDatabaseId) {
312                                 if (databaseId == selectedBookmarkDatabaseId) {
313                                     // Move the selected bookmark up one and store the new bookmark position.
314                                     bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i - 1);
315                                     selectedBookmarkNewPosition = i - 1;
316                                 } else {  // Move the bookmark above the selected bookmark down one.
317                                     bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i + 1);
318                                 }
319                             } else {
320                                 // Reset the rest of the bookmarks' DISPLAY_ORDER to match the position in the ListView.
321                                 // This isn't necessary, but it clears out any stray values that might have crept into the database.
322                                 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i);
323                             }
324                         }
325
326                         // Refresh the ListView.
327                         updateBookmarksListView(currentFolder);
328
329                         // Select the previously selected bookmark in the new location.
330                         bookmarksListView.setItemChecked(selectedBookmarkNewPosition, true);
331
332                         // Scroll `bookmarksListView` to five items above `selectedBookmarkNewPosition`.
333                         bookmarksListView.setSelection(selectedBookmarkNewPosition - 5);
334
335                         break;
336
337                     case R.id.move_bookmark_down:
338                         // Get the selected bookmark database ID.
339                         selectedBookmarkLongArray = bookmarksListView.getCheckedItemIds();
340                         selectedBookmarkDatabaseId = (int) selectedBookmarkLongArray[0];
341
342                         // Initialize `selectedBookmarkNewPosition`.
343                         selectedBookmarkNewPosition = 0;
344
345                         for (int i = 0; i <bookmarksListView.getCount(); i++) {
346                             int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
347                             int previousBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i - 1);
348
349                             if (databaseId == selectedBookmarkDatabaseId || previousBookmarkDatabaseId == selectedBookmarkDatabaseId) {
350                                 if (databaseId == selectedBookmarkDatabaseId) {
351                                     // Move the selected bookmark down one and store the new bookmark position.
352                                     bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i + 1);
353                                     selectedBookmarkNewPosition = i + 1;
354                                 } else {  // Move the bookmark below the selected bookmark up one.
355                                     bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i - 1);
356                                 }
357                             } else {
358                                 // Reset the rest of the bookmark' DISPLAY_ORDER to match the position in the ListView.
359                                 // This isn't necessary, but it clears out any stray values that might have crept into the database.
360                                 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i);
361                             }
362                         }
363
364                         // Refresh the ListView.
365                         updateBookmarksListView(currentFolder);
366
367                         // Select the previously selected bookmark in the new location.
368                         bookmarksListView.setItemChecked(selectedBookmarkNewPosition, true);
369
370                         // Scroll `bookmarksListView` to five items above `selectedBookmarkNewPosition`.
371                         bookmarksListView.setSelection(selectedBookmarkNewPosition - 5);
372                         break;
373
374                     case R.id.move_to_folder:
375                         // Store `checkedItemIds` for use by the `AlertDialog`.
376                         checkedItemIds = bookmarksListView.getCheckedItemIds();
377
378                         // Show the `MoveToFolderDialog` `AlertDialog` and name the instance `@string/move_to_folder
379                         AppCompatDialogFragment moveToFolderDialog = new MoveToFolderDialog();
380                         moveToFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.move_to_folder));
381                         break;
382
383                     case R.id.edit_bookmark:
384                         // Get a handle for `selectedBookmarkPosition` so we can scroll to it after refreshing the ListView.
385                         bookmarkPositionSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
386                         for (int i = 0; i < bookmarkPositionSparseBooleanArray.size(); i++) {
387                             // Find the bookmark that is selected and save the position to `selectedBookmarkPosition`.
388                             if (bookmarkPositionSparseBooleanArray.valueAt(i))
389                                 selectedBookmarkPosition = bookmarkPositionSparseBooleanArray.keyAt(i);
390                         }
391
392                         // Move to the selected database ID and find out if it is a folder.
393                         bookmarksCursor.moveToPosition(selectedBookmarkPosition);
394                         boolean isFolder = (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1);
395
396                         // Store `checkedItemIds` for use by the `AlertDialog`.
397                         checkedItemIds = bookmarksListView.getCheckedItemIds();
398
399                         if (isFolder) {
400                             // Save the current folder name.
401                             oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
402
403                             // Show the `EditBookmarkFolderDialog` `AlertDialog` and name the instance `@string/edit_folder`.
404                             AppCompatDialogFragment editFolderDialog = new EditBookmarkFolderDialog();
405                             editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
406                         } else {
407                             // Show the `EditBookmarkDialog` `AlertDialog` and name the instance `@string/edit_bookmark`.
408                             AppCompatDialogFragment editBookmarkDialog = new EditBookmarkDialog();
409                             editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
410                         }
411                         break;
412
413                     case R.id.delete_bookmark:
414                         // Get an array of the selected rows.
415                         final long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
416
417                         // Get a handle for `selectedBookmarkPosition` so we can scroll to it after refreshing the ListView.
418                         bookmarkPositionSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
419                         for (int i = 0; i < bookmarkPositionSparseBooleanArray.size(); i++) {
420                             // Find the bookmark that is selected and save the position to `selectedBookmarkPosition`.
421                             if (bookmarkPositionSparseBooleanArray.valueAt(i))
422                                 selectedBookmarkPosition = bookmarkPositionSparseBooleanArray.keyAt(i);
423                         }
424
425                         updateBookmarksListViewExcept(selectedBookmarksLongArray, currentFolder);
426
427                         // Scroll to where the deleted bookmark was located.
428                         bookmarksListView.setSelection(selectedBookmarkPosition - 5);
429
430                         // Initialize `snackbarMessage`.
431                         String snackbarMessage;
432
433                         // Determine how many items are in the array and prepare an appropriate Snackbar message.
434                         if (selectedBookmarksLongArray.length == 1) {
435                             snackbarMessage = getString(R.string.one_bookmark_deleted);
436                         } else {
437                             snackbarMessage = selectedBookmarksLongArray.length + " " + getString(R.string.bookmarks_deleted);
438                         }
439
440                         // Show a SnackBar.
441                         Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), snackbarMessage, Snackbar.LENGTH_LONG)
442                                 .setAction(R.string.undo, new View.OnClickListener() {
443                                     @Override
444                                     public void onClick(View view) {
445                                         // Do nothing because everything will be handled by `onDismissed()` below.
446                                     }
447                                 })
448                                 .addCallback(new Snackbar.Callback() {
449                                     @Override
450                                     public void onDismissed(Snackbar snackbar, int event) {
451                                         switch (event) {
452                                             // The user pushed the `Undo` button.
453                                             case Snackbar.Callback.DISMISS_EVENT_ACTION:
454                                                 // Refresh the ListView to show the rows again.
455                                                 updateBookmarksListView(currentFolder);
456
457                                                 // Scroll to where the deleted bookmark was located.
458                                                 bookmarksListView.setSelection(selectedBookmarkPosition - 5);
459                                                 break;
460
461                                             // The `Snackbar` was dismissed without the `Undo` button being pushed.
462                                             default:
463                                                 // Delete each selected row.
464                                                 for (long databaseIdLong : selectedBookmarksLongArray) {
465                                                     // Convert `databaseIdLong` to an int.
466                                                     int databaseIdInt = (int) databaseIdLong;
467
468                                                     if (bookmarksDatabaseHelper.isFolder(databaseIdInt)) {
469                                                         deleteBookmarkFolderContents(databaseIdInt);
470                                                     }
471
472                                                     // Delete `databaseIdInt`.
473                                                     bookmarksDatabaseHelper.deleteBookmark(databaseIdInt);
474                                                 }
475                                                 break;
476                                         }
477                                     }
478                                 })
479                                 .show();
480
481                         // Close the contextual app bar.
482                         mode.finish();
483                         break;
484
485                     case R.id.context_menu_select_all_bookmarks:
486                         numberOfBookmarks = bookmarksListView.getCount();
487
488                         for (int i = 0; i < numberOfBookmarks; i++) {
489                             bookmarksListView.setItemChecked(i, true);
490                         }
491                         break;
492                 }
493                 // Consume the click.
494                 return true;
495             }
496
497             @Override
498             public void onDestroyActionMode(ActionMode mode) {
499
500             }
501         });
502
503         // Set a FloatingActionButton for creating new bookmarks.
504         FloatingActionButton createBookmarkFAB = (FloatingActionButton) findViewById(R.id.create_bookmark_fab);
505         createBookmarkFAB.setOnClickListener(new View.OnClickListener() {
506             @Override
507             public void onClick(View view) {
508                 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
509                 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
510                 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
511             }
512         });
513     }
514
515     @Override
516     public boolean onCreateOptionsMenu(Menu menu) {
517         // Inflate the menu.
518         getMenuInflater().inflate(R.menu.bookmarks_options_menu, menu);
519
520         // Success.
521         return true;
522     }
523
524     @Override
525     public boolean onOptionsItemSelected(MenuItem menuItem) {
526         // Get the ID of the `MenuItem` that was selected.
527         int menuItemId = menuItem.getItemId();
528
529         switch (menuItemId) {
530             case android.R.id.home:  // The home arrow is identified as `android.R.id.home`, not just `R.id.home`.
531                 if (currentFolder.isEmpty()) {  // Exit BookmarksActivity if currently in the home folder.
532                     NavUtils.navigateUpFromSameTask(this);
533                 } else {  // Navigate up one folder.
534                     // Place the former parent folder in `currentFolder`.
535                     currentFolder = bookmarksDatabaseHelper.getParentFolder(currentFolder);
536
537                     // Update `bookmarksListView`.
538                     updateBookmarksListView(currentFolder);
539                 }
540                 break;
541
542             case R.id.create_folder:
543                 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
544                 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
545                 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
546                 break;
547
548             case R.id.options_menu_select_all_bookmarks:
549                 int numberOfBookmarks = bookmarksListView.getCount();
550
551                 for (int i = 0; i < numberOfBookmarks; i++) {
552                     bookmarksListView.setItemChecked(i, true);
553                 }
554                 break;
555
556             case R.id.bookmarks_database_view:
557                 // Launch `BookmarksDatabaseViewActivity`.
558                 Intent bookmarksDatabaseViewIntent = new Intent(this, BookmarksDatabaseViewActivity.class);
559                 startActivity(bookmarksDatabaseViewIntent);
560                 break;
561         }
562         return true;
563     }
564
565     @Override
566     public void onBackPressed() {
567         if (currentFolder.isEmpty()) {  // Exit BookmarksActivity if currently in the home folder.
568             super.onBackPressed();
569         } else {  // Navigate up one folder.
570             // Place the former parent folder in `currentFolder`.
571             currentFolder = bookmarksDatabaseHelper.getParentFolder(currentFolder);
572
573             // Reload the `ListView`.
574             updateBookmarksListView(currentFolder);
575         }
576     }
577
578     @Override
579     public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
580         // Get the `EditTexts` from the `dialogFragment`.
581         EditText createBookmarkNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
582         EditText createBookmarkUrlEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
583
584         // Extract the strings from the `EditTexts`.
585         String bookmarkNameString = createBookmarkNameEditText.getText().toString();
586         String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
587
588         // Convert the favoriteIcon Bitmap to a byte array.
589         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
590         // `0` is for lossless compression (the only option for a PNG).
591         MainWebViewActivity.favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
592         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
593
594         // Display the new bookmark below the current items in the (0 indexed) list.
595         int newBookmarkDisplayOrder = bookmarksListView.getCount();
596
597         // Create the bookmark.
598         bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, newBookmarkDisplayOrder, currentFolder, favoriteIconByteArray);
599
600         // Refresh the `ListView`.  `setSelection` scrolls to the bottom of the list.
601         updateBookmarksListView(currentFolder);
602         bookmarksListView.setSelection(newBookmarkDisplayOrder);
603     }
604
605     @Override
606     public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
607         // Get `create_folder_name_edit_text` and extract the string.
608         EditText createFolderNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
609         String folderNameString = createFolderNameEditText.getText().toString();
610
611         // Check to see if the folder already exists.
612         Cursor bookmarkFolderCursor = bookmarksDatabaseHelper.getFolderCursor(folderNameString);
613         int existingFoldersWithNewName = bookmarkFolderCursor.getCount();
614         bookmarkFolderCursor.close();
615         if (folderNameString.isEmpty() || (existingFoldersWithNewName > 0)) {
616             String cannotCreateFolder = getResources().getString(R.string.cannot_create_folder) + " \"" + folderNameString + "\"";
617             Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), cannotCreateFolder, Snackbar.LENGTH_INDEFINITE).show();
618         } else {  // Create the folder.
619             // Get the new folder icon `Bitmap`.
620             RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
621             Bitmap folderIconBitmap;
622             if (defaultFolderIconRadioButton.isChecked()) {
623                 // Get the default folder icon `ImageView` from the `Dialog` and convert it to a `Bitmap`.
624                 ImageView folderIconImageView = (ImageView) dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
625                 Drawable folderIconDrawable = folderIconImageView.getDrawable();
626                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
627                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
628             } else {  // Assign `favoriteIcon` from the `WebView`.
629                 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
630             }
631
632             // Convert `folderIconBitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
633             ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
634             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
635             byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
636
637             // Move all the bookmarks down one in the display order.
638             for (int i = 0; i < bookmarksListView.getCount(); i++) {
639                 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
640                 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i + 1);
641             }
642
643             // Create the folder, placing it at the top of the ListView
644             bookmarksDatabaseHelper.createFolder(folderNameString, 0, currentFolder, folderIconByteArray);
645
646             // Refresh the ListView.
647             updateBookmarksListView(currentFolder);
648         }
649     }
650
651     @Override
652     public void onSaveEditBookmark(AppCompatDialogFragment dialogFragment) {
653         // Get a long array with the the databaseId of the selected bookmark and convert it to an `int`.
654         long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
655         int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
656
657         // Get the `EditText`s from the `editBookmarkDialogFragment` and extract the strings.
658         EditText editBookmarkNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
659         String bookmarkNameString = editBookmarkNameEditText.getText().toString();
660         EditText editBookmarkUrlEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
661         String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
662
663         // Get `edit_bookmark_current_icon_radiobutton`.
664         RadioButton currentBookmarkIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
665
666         if (currentBookmarkIconRadioButton.isChecked()) {  // Update the bookmark without changing the favorite icon.
667             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
668         } else {  // Update the bookmark using the `WebView` favorite icon.
669             ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
670             MainWebViewActivity.favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
671             byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
672
673             //  Update the bookmark and the favorite icon.
674             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
675         }
676
677         // Close the contextual action mode.
678         contextualActionMode.finish();
679
680         // Refresh the `ListView`.  `setSelection` scrolls to the position of the bookmark that was edited.
681         updateBookmarksListView(currentFolder);
682         bookmarksListView.setSelection(selectedBookmarkPosition);
683     }
684
685     @Override
686     public void onSaveEditBookmarkFolder(AppCompatDialogFragment dialogFragment) {
687         // Get the new folder name.
688         EditText editFolderNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
689         String newFolderNameString = editFolderNameEditText.getText().toString();
690
691         // Check to see if the new folder name is unique.
692         Cursor bookmarkFolderCursor = bookmarksDatabaseHelper.getFolderCursor(newFolderNameString);
693         int existingFoldersWithNewName = bookmarkFolderCursor.getCount();
694         bookmarkFolderCursor.close();
695         if ( ((existingFoldersWithNewName == 0) || newFolderNameString.equals(oldFolderNameString)) && !newFolderNameString.isEmpty()) {
696             // Get a long array with the the database ID of the selected folder and convert it to an `int`.
697             long[] selectedFolderLongArray = bookmarksListView.getCheckedItemIds();
698             int selectedFolderDatabaseId = (int) selectedFolderLongArray[0];
699
700             // Get the `RadioButtons` from the `Dialog`.
701             RadioButton currentFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
702             RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
703
704             // Check if the favorite icon has changed.
705             if (currentFolderIconRadioButton.isChecked()) {
706                 // Update the folder name if it has changed without modifying the favorite icon.
707                 if (!newFolderNameString.equals(oldFolderNameString)) {
708                     bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
709
710                     // Refresh the `ListView`.  `setSelection` scrolls to the position of the folder that was edited.
711                     updateBookmarksListView(currentFolder);
712                     bookmarksListView.setSelection(selectedBookmarkPosition);
713                 }
714             } else {  // Update the folder icon.
715                 // Get the new folder icon `Bitmap`.
716                 Bitmap folderIconBitmap;
717                 if (defaultFolderIconRadioButton.isChecked()) {
718                     // Get the default folder icon `ImageView` from the `Drawable` and convert it to a `Bitmap`.
719                     ImageView folderIconImageView = (ImageView) dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon);
720                     Drawable folderIconDrawable = folderIconImageView.getDrawable();
721                     BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
722                     folderIconBitmap = folderIconBitmapDrawable.getBitmap();
723                 } else {  // Get the web page icon `ImageView` from the `Dialog`.
724                     folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
725                 }
726
727                 // Convert the folder `Bitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
728                 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
729                 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
730                 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
731
732                 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
733
734                 // Refresh the `ListView`.  `setSelection` scrolls to the position of the folder that was edited.
735                 updateBookmarksListView(currentFolder);
736                 bookmarksListView.setSelection(selectedBookmarkPosition);
737             }
738         } else {  // Don't edit the folder because the new name is not unique.
739             String cannot_rename_folder = getResources().getString(R.string.cannot_save_folder) + " \"" + newFolderNameString + "\"";
740             Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), cannot_rename_folder, Snackbar.LENGTH_INDEFINITE).show();
741         }
742
743         // Close the contextual action mode.
744         contextualActionMode.finish();
745     }
746
747     @Override
748     public void onMoveToFolder(AppCompatDialogFragment dialogFragment) {
749         // Get the new folder database id.
750         ListView folderListView = (ListView) dialogFragment.getDialog().findViewById(R.id.move_to_folder_listview);
751         long[] newFolderLongArray = folderListView.getCheckedItemIds();
752
753         if (newFolderLongArray.length == 0) {  // No new folder was selected.
754             Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), getString(R.string.cannot_move_bookmarks), Snackbar.LENGTH_INDEFINITE).show();
755         } else {  // Move the selected bookmarks.
756             // Get the new folder database ID.
757             int newFolderDatabaseId = (int) newFolderLongArray[0];
758
759             // Instantiate `newFolderName`.
760             String newFolderName;
761
762             if (newFolderDatabaseId == 0) {
763                 // The new folder is the home folder, represented as `""` in the database.
764                 newFolderName = "";
765             } else {
766                 // Get the new folder name from the database.
767                 newFolderName = bookmarksDatabaseHelper.getFolderName(newFolderDatabaseId);
768             }
769
770             // Get a long array with the the database ID of the selected bookmarks.
771             long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
772             for (long databaseIdLong : selectedBookmarksLongArray) {
773                 // Get `databaseIdInt` for each selected bookmark.
774                 int databaseIdInt = (int) databaseIdLong;
775
776                 // Move the selected bookmark to the new folder.
777                 bookmarksDatabaseHelper.moveToFolder(databaseIdInt, newFolderName);
778             }
779
780             // Refresh the `ListView`.
781             updateBookmarksListView(currentFolder);
782
783             // Close the contextual app bar.
784             contextualActionMode.finish();
785         }
786     }
787
788     private void updateBookmarksListView(String folderName) {
789         // Get a `Cursor` with the current contents of the bookmarks database.
790         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(folderName);
791
792         // Setup `bookmarksCursorAdapter` with `this` context.  `false` disables `autoRequery`.
793         CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
794             @Override
795             public View newView(Context context, Cursor cursor, ViewGroup parent) {
796                 // Inflate the individual item layout.  `false` does not attach it to the root.
797                 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
798             }
799
800             @Override
801             public void bindView(View view, Context context, Cursor cursor) {
802                 // Get the favorite icon byte array from the `Cursor`.
803                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
804
805                 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
806                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
807
808                 // Display the bitmap in `bookmarkFavoriteIcon`.
809                 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
810                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
811
812
813                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
814                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
815                 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
816                 bookmarkNameTextView.setText(bookmarkNameString);
817
818                 // Make the font bold for folders.
819                 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
820                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
821                 } else {  // Reset the font to default for normal bookmarks.
822                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
823                 }
824             }
825         };
826
827         // Update the ListView.
828         bookmarksListView.setAdapter(bookmarksCursorAdapter);
829
830         // Set the AppBar title.
831         if (currentFolder.isEmpty()) {
832             appBar.setTitle(R.string.bookmarks);
833         } else {
834             appBar.setTitle(currentFolder);
835         }
836     }
837
838     private void updateBookmarksListViewExcept(long[] exceptIdLongArray, String folderName) {
839         // Get a `Cursor` with the current contents of the bookmarks database except for the specified database IDs.
840         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksCursorExcept(exceptIdLongArray, folderName);
841
842         // Setup `bookmarksCursorAdapter` with `this` context.  `false` disables autoRequery.
843         CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
844             @Override
845             public View newView(Context context, Cursor cursor, ViewGroup parent) {
846                 // Inflate the individual item layout.  `false` does not attach it to the root.
847                 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
848             }
849
850             @Override
851             public void bindView(View view, Context context, Cursor cursor) {
852                 // Get the favorite icon byte array from the cursor.
853                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
854
855                 // Convert the byte array to a Bitmap beginning at the first byte and ending at the last.
856                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
857
858                 // Display the bitmap in `bookmarkFavoriteIcon`.
859                 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
860                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
861
862
863                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
864                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
865                 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
866                 bookmarkNameTextView.setText(bookmarkNameString);
867
868                 // Make the font bold for folders.
869                 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
870                     // The first argument is `null` because we don't want to change the font.
871                     bookmarkNameTextView.setTypeface(null, Typeface.BOLD);
872                 } else {  // Reset the font to default.
873                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
874                 }
875             }
876         };
877
878         // Update the `ListView`.
879         bookmarksListView.setAdapter(bookmarksCursorAdapter);
880     }
881
882     private void deleteBookmarkFolderContents(int databaseId) {
883         // Get the name of the folder.
884         String folderName = bookmarksDatabaseHelper.getFolderName(databaseId);
885
886         // Get the contents of the folder.
887         Cursor folderCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(folderName);
888
889         for (int i = 0; i < folderCursor.getCount(); i++) {
890             // Move `folderCursor` to the current row.
891             folderCursor.moveToPosition(i);
892
893             // Get the database ID of the item.
894             int itemDatabaseId = folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID));
895
896             // If this is a folder, delete the contents first.
897             if (bookmarksDatabaseHelper.isFolder(itemDatabaseId)) {
898                 deleteBookmarkFolderContents(itemDatabaseId);
899             }
900
901             bookmarksDatabaseHelper.deleteBookmark(itemDatabaseId);
902         }
903     }
904 }