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