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