]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/Bookmarks.java
Create Java subpackage folders.
[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.
115         // `this` specifies the context.  The two `null`s do not specify the database name or a `CursorFactory`.
116         // The `0` is to specify a database version, but that is set instead using a constant in `BookmarksDatabaseHelper`.
117         bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
118         bookmarksListView = (ListView) findViewById(R.id.bookmarks_listview);
119
120         // Set currentFolder to the home folder, which is null in the database.
121         currentFolder = "";
122
123         // Display the bookmarks in the ListView.
124         updateBookmarksListView(currentFolder);
125
126         // Set a listener so that tapping a list item loads the URL.  We need to store the activity
127         // in a variable so that we can return to the parent activity after loading the URL.
128         final Activity bookmarksActivity = this;
129         bookmarksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
130             @Override
131             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
132                 // Convert the id from long to int to match the format of the bookmarks database.
133                 int databaseID = (int) id;
134
135                 // Get the bookmark `Cursor` and move it to the first row.
136                 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
137                 bookmarkCursor.moveToFirst();
138
139                 // If the bookmark is a folder load its contents into the ListView.
140                 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
141                     // Update `currentFolder`.
142                     currentFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
143
144                     // Reload the ListView with `currentFolder`.
145                     updateBookmarksListView(currentFolder);
146                 } else {  // Load the URL into `mainWebView`.
147                     // Get the bookmark URL and assign it to formattedUrlString.  `mainWebView` will automatically reload when `Bookmarks` closes.
148                     MainWebView.formattedUrlString = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL));
149
150                     NavUtils.navigateUpFromSameTask(bookmarksActivity);
151                 }
152
153                 // Close the `Cursor`.
154                 bookmarkCursor.close();
155             }
156         });
157
158         // `MultiChoiceModeListener` handles long clicks.
159         bookmarksListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
160             // `moveBookmarkUpMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
161             MenuItem moveBookmarkUpMenuItem;
162
163             // `moveBookmarkDownMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
164             MenuItem moveBookmarkDownMenuItem;
165
166             // `editBookmarkMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
167             MenuItem editBookmarkMenuItem;
168
169             // `selectAllBookmarks` is used in `onCreateActionMode()` and `onItemCheckedStateChanges`.
170             MenuItem selectAllBookmarksMenuItem;
171
172             @Override
173             public boolean onCreateActionMode(ActionMode mode, Menu menu) {
174                 // Inflate the menu for the contextual app bar and set the title.
175                 getMenuInflater().inflate(R.menu.bookmarks_context_menu, menu);
176
177                 // Set the title.
178                 if (currentFolder.isEmpty()) {
179                     // Use `R.string.bookmarks` if we are in the home folder.
180                     mode.setTitle(R.string.bookmarks);
181                 } else {  // Use the current folder name as the title.
182                     mode.setTitle(currentFolder);
183                 }
184
185                 // Get a handle for MenuItems we need to selectively disable.
186                 moveBookmarkUpMenuItem = menu.findItem(R.id.move_bookmark_up);
187                 moveBookmarkDownMenuItem = menu.findItem(R.id.move_bookmark_down);
188                 editBookmarkMenuItem = menu.findItem(R.id.edit_bookmark);
189                 selectAllBookmarksMenuItem = menu.findItem(R.id.context_menu_select_all_bookmarks);
190
191                 // Get a handle for `contextualActionMode` so we can close it programatically.
192                 contextualActionMode = mode;
193
194                 return true;
195             }
196
197             @Override
198             public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
199                 return false;
200             }
201
202             @Override
203             public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
204                 // Get an array of the selected bookmarks.
205                 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
206
207                 // Calculate the number of selected bookmarks.
208                 int numberOfSelectedBookmarks = selectedBookmarksLongArray.length;
209
210                 // Sometimes Android forgets to close the contextual app bar when all the items are deselected.
211                 if (numberOfSelectedBookmarks == 0) {
212                     mode.finish();
213                 }
214
215                 // List the number of selected bookmarks in the subtitle.
216                 mode.setSubtitle(numberOfSelectedBookmarks + " " + getString(R.string.selected));
217
218                 if (numberOfSelectedBookmarks == 1) {
219                     // Show the `Move Up`, `Move Down`, and  `Edit` option only if 1 bookmark is selected.
220                     moveBookmarkUpMenuItem.setVisible(true);
221                     moveBookmarkDownMenuItem.setVisible(true);
222                     editBookmarkMenuItem.setVisible(true);
223
224                     // Get the database IDs for the bookmarks.
225                     int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
226                     int firstBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(0);
227                     // bookmarksListView is 0 indexed.
228                     int lastBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(bookmarksListView.getCount() - 1);
229
230                     // Disable `moveBookmarkUpMenuItem` if the selected bookmark is at the top of the ListView.
231                     if (selectedBookmarkDatabaseId == firstBookmarkDatabaseId) {
232                         moveBookmarkUpMenuItem.setEnabled(false);
233                         moveBookmarkUpMenuItem.setIcon(R.drawable.move_bookmark_up_disabled);
234                     } else {  // Otherwise enable `moveBookmarkUpMenuItem`.
235                         moveBookmarkUpMenuItem.setEnabled(true);
236                         moveBookmarkUpMenuItem.setIcon(R.drawable.move_bookmark_up_enabled);
237                     }
238
239                     // Disable `moveBookmarkDownMenuItem` if the selected bookmark is at the bottom of the ListView.
240                     if (selectedBookmarkDatabaseId == lastBookmarkDatabaseId) {
241                         moveBookmarkDownMenuItem.setEnabled(false);
242                         moveBookmarkDownMenuItem.setIcon(R.drawable.move_bookmark_down_disabled);
243                     } else {  // Otherwise enable `moveBookmarkDownMenuItem`.
244                         moveBookmarkDownMenuItem.setEnabled(true);
245                         moveBookmarkDownMenuItem.setIcon(R.drawable.move_bookmark_down_enabled);
246                     }
247                 } else {  // Hide the MenuItems because more than one bookmark is selected.
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                 // Exit Bookmarks if currently at the home folder.
527                 if (currentFolder.isEmpty()) {
528                     NavUtils.navigateUpFromSameTask(this);
529                 } else {  // Navigate up one folder.
530                     // Place the former parent folder in `currentFolder`.
531                     currentFolder = bookmarksDatabaseHelper.getParentFolder(currentFolder);
532
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 onCreateBookmark(AppCompatDialogFragment dialogFragment) {
562         // Get the `EditText`s from the `createBookmarkDialogFragment` and extract the strings.
563         EditText createBookmarkNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
564         String bookmarkNameString = createBookmarkNameEditText.getText().toString();
565         EditText createBookmarkUrlEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
566         String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
567
568         // Convert the favoriteIcon Bitmap to a byte array.
569         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
570         // `0` is for lossless compression (the only option for a PNG).
571         MainWebView.favoriteIcon.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
572         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
573
574         // Display the new bookmark below the current items in the (0 indexed) list.
575         int newBookmarkDisplayOrder = bookmarksListView.getCount();
576
577         // Create the bookmark.
578         bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, newBookmarkDisplayOrder, currentFolder, favoriteIconByteArray);
579
580         // Refresh the ListView.  `setSelection` scrolls to the bottom of the list.
581         updateBookmarksListView(currentFolder);
582         bookmarksListView.setSelection(newBookmarkDisplayOrder);
583     }
584
585     @Override
586     public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
587         // Get `create_folder_name_edit_text` and extract the string.
588         EditText createFolderNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
589         String folderNameString = createFolderNameEditText.getText().toString();
590
591         // Check to see if the folder already exists.
592         Cursor bookmarkFolderCursor = bookmarksDatabaseHelper.getFolderCursor(folderNameString);
593         int existingFoldersWithNewName = bookmarkFolderCursor.getCount();
594         bookmarkFolderCursor.close();
595         if (folderNameString.isEmpty() || (existingFoldersWithNewName > 0)) {
596             String cannotCreateFolder = getResources().getString(R.string.cannot_create_folder) + " \"" + folderNameString + "\"";
597             Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), cannotCreateFolder, Snackbar.LENGTH_INDEFINITE).show();
598         } else {  // Create the folder.
599             // Get the new folder icon `Bitmap`.
600             RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
601             Bitmap folderIconBitmap;
602             if (defaultFolderIconRadioButton.isChecked()) {
603                 // Get the default folder icon `ImageView` from the `Dialog` and convert it to a `Bitmap`.
604                 ImageView folderIconImageView = (ImageView) dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
605                 Drawable folderIconDrawable = folderIconImageView.getDrawable();
606                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
607                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
608             } else {  // Assign `favoriteIcon` from the `WebView`.
609                 folderIconBitmap = MainWebView.favoriteIcon;
610             }
611
612             // Convert `folderIconBitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
613             ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
614             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
615             byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
616
617             // Move all the bookmarks down one in the display order.
618             for (int i = 0; i < bookmarksListView.getCount(); i++) {
619                 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
620                 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i + 1);
621             }
622
623             // Create the folder, placing it at the top of the ListView
624             bookmarksDatabaseHelper.createFolder(folderNameString, 0, currentFolder, folderIconByteArray);
625
626             // Refresh the ListView.
627             updateBookmarksListView(currentFolder);
628         }
629     }
630
631     @Override
632     public void onSaveEditBookmark(AppCompatDialogFragment dialogFragment) {
633         // Get a long array with the the databaseId of the selected bookmark and convert it to an `int`.
634         long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
635         int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
636
637         // Get the `EditText`s from the `editBookmarkDialogFragment` and extract the strings.
638         EditText editBookmarkNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
639         String bookmarkNameString = editBookmarkNameEditText.getText().toString();
640         EditText editBookmarkUrlEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
641         String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
642
643         // Get `edit_bookmark_current_icon_radiobutton`.
644         RadioButton currentBookmarkIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
645
646         if (currentBookmarkIconRadioButton.isChecked()) {  // Update the bookmark without changing the favorite icon.
647             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
648         } else {  // Update the bookmark using the `WebView` favorite icon.
649             ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
650             MainWebView.favoriteIcon.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
651             byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
652
653             //  Update the bookmark and the favorite icon.
654             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
655         }
656
657         // Close the contextual action mode.
658         contextualActionMode.finish();
659
660         // Refresh the `ListView`.  `setSelection` scrolls to the position of the bookmark that was edited.
661         updateBookmarksListView(currentFolder);
662         bookmarksListView.setSelection(selectedBookmarkPosition);
663     }
664
665     @Override
666     public void onSaveEditBookmarkFolder(AppCompatDialogFragment dialogFragment) {
667         // Get the new folder name.
668         EditText editFolderNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
669         String newFolderNameString = editFolderNameEditText.getText().toString();
670
671         // Check to see if the new folder name is unique.
672         Cursor bookmarkFolderCursor = bookmarksDatabaseHelper.getFolderCursor(newFolderNameString);
673         int existingFoldersWithNewName = bookmarkFolderCursor.getCount();
674         bookmarkFolderCursor.close();
675         if ( ((existingFoldersWithNewName == 0) || newFolderNameString.equals(oldFolderNameString)) && !newFolderNameString.isEmpty()) {
676             // Get a long array with the the database ID of the selected folder and convert it to an `int`.
677             long[] selectedFolderLongArray = bookmarksListView.getCheckedItemIds();
678             int selectedFolderDatabaseId = (int) selectedFolderLongArray[0];
679
680             // Get the `RadioButtons` from the `Dialog`.
681             RadioButton currentFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
682             RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
683
684             // Check if the favorite icon has changed.
685             if (currentFolderIconRadioButton.isChecked()) {
686                 // Update the folder name if it has changed without modifying the favorite icon.
687                 if (!newFolderNameString.equals(oldFolderNameString)) {
688                     bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
689
690                     // Refresh the `ListView`.  `setSelection` scrolls to the position of the folder that was edited.
691                     updateBookmarksListView(currentFolder);
692                     bookmarksListView.setSelection(selectedBookmarkPosition);
693                 }
694             } else {  // Update the folder icon.
695                 // Get the new folder icon `Bitmap`.
696                 Bitmap folderIconBitmap;
697                 if (defaultFolderIconRadioButton.isChecked()) {
698                     // Get the default folder icon `ImageView` from the `Drawable` and convert it to a `Bitmap`.
699                     ImageView folderIconImageView = (ImageView) dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon);
700                     Drawable folderIconDrawable = folderIconImageView.getDrawable();
701                     BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
702                     folderIconBitmap = folderIconBitmapDrawable.getBitmap();
703                 } else {  // Get the web page icon `ImageView` from the `Dialog`.
704                     folderIconBitmap = MainWebView.favoriteIcon;
705                 }
706
707                 // Convert the folder `Bitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
708                 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
709                 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
710                 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
711
712                 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
713
714                 // Refresh the `ListView`.  `setSelection` scrolls to the position of the folder that was edited.
715                 updateBookmarksListView(currentFolder);
716                 bookmarksListView.setSelection(selectedBookmarkPosition);
717             }
718         } else {  // Don't edit the folder because the new name is not unique.
719             String cannot_rename_folder = getResources().getString(R.string.cannot_rename_folder) + " \"" + newFolderNameString + "\"";
720             Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), cannot_rename_folder, Snackbar.LENGTH_INDEFINITE).show();
721         }
722
723         // Close the contextual action mode.
724         contextualActionMode.finish();
725     }
726
727     @Override
728     public void onMoveToFolder(AppCompatDialogFragment dialogFragment) {
729         // Get the new folder database id.
730         ListView folderListView = (ListView) dialogFragment.getDialog().findViewById(R.id.move_to_folder_listview);
731         long[] newFolderLongArray = folderListView.getCheckedItemIds();
732
733         if (newFolderLongArray.length == 0) {  // No new folder was selected.
734             Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), getString(R.string.cannot_move_bookmarks), Snackbar.LENGTH_LONG).show();
735         } else {  // Move the selected bookmarks.
736             // Get the new folder database ID.
737             int newFolderDatabaseId = (int) newFolderLongArray[0];
738
739             // Instantiate `newFolderName`.
740             String newFolderName;
741
742             if (newFolderDatabaseId == 0) {
743                 // The new folder is the home folder, represented as `""` in the database.
744                 newFolderName = "";
745             } else {
746                 // Get the new folder name from the database.
747                 newFolderName = bookmarksDatabaseHelper.getFolderName(newFolderDatabaseId);
748             }
749
750             // Get a long array with the the database ID of the selected bookmarks.
751             long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
752             for (long databaseIdLong : selectedBookmarksLongArray) {
753                 // Get `databaseIdInt` for each selected bookmark.
754                 int databaseIdInt = (int) databaseIdLong;
755
756                 // Move the selected bookmark to the new folder.
757                 bookmarksDatabaseHelper.moveToFolder(databaseIdInt, newFolderName);
758             }
759
760             // Refresh the `ListView`.
761             updateBookmarksListView(currentFolder);
762
763             // Close the contextual app bar.
764             contextualActionMode.finish();
765         }
766     }
767
768     private void updateBookmarksListView(String folderName) {
769         // Get a `Cursor` with the current contents of the bookmarks database.
770         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(folderName);
771
772         // Setup `bookmarksCursorAdapter` with `this` context.  `false` disables autoRequery.
773         CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
774             @Override
775             public View newView(Context context, Cursor cursor, ViewGroup parent) {
776                 // Inflate the individual item layout.  `false` does not attach it to the root.
777                 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
778             }
779
780             @Override
781             public void bindView(View view, Context context, Cursor cursor) {
782                 // Get the favorite icon byte array from the `Cursor`.
783                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
784
785                 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
786                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
787
788                 // Display the bitmap in `bookmarkFavoriteIcon`.
789                 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
790                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
791
792
793                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
794                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
795                 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
796                 bookmarkNameTextView.setText(bookmarkNameString);
797
798                 // Make the font bold for folders.
799                 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
800                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
801                 } else {  // Reset the font to default for normal bookmarks.
802                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
803                 }
804             }
805         };
806
807         // Update the ListView.
808         bookmarksListView.setAdapter(bookmarksCursorAdapter);
809
810         // Set the AppBar title.
811         if (currentFolder.isEmpty()) {
812             appBar.setTitle(R.string.bookmarks);
813         } else {
814             appBar.setTitle(currentFolder);
815         }
816     }
817
818     private void updateBookmarksListViewExcept(long[] exceptIdLongArray, String folderName) {
819         // Get a `Cursor` with the current contents of the bookmarks database except for the specified database IDs.
820         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksCursorExcept(exceptIdLongArray, folderName);
821
822         // Setup `bookmarksCursorAdapter` with `this` context.  `false` disables autoRequery.
823         CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
824             @Override
825             public View newView(Context context, Cursor cursor, ViewGroup parent) {
826                 // Inflate the individual item layout.  `false` does not attach it to the root.
827                 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
828             }
829
830             @Override
831             public void bindView(View view, Context context, Cursor cursor) {
832                 // Get the favorite icon byte array from the cursor.
833                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
834
835                 // Convert the byte array to a Bitmap beginning at the first byte and ending at the last.
836                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
837
838                 // Display the bitmap in `bookmarkFavoriteIcon`.
839                 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
840                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
841
842
843                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
844                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
845                 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
846                 bookmarkNameTextView.setText(bookmarkNameString);
847
848                 // Make the font bold for folders.
849                 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
850                     // The first argument is `null` because we don't want to change the font.
851                     bookmarkNameTextView.setTypeface(null, Typeface.BOLD);
852                 } else {  // Reset the font to default.
853                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
854                 }
855             }
856         };
857
858         // Update the ListView.
859         bookmarksListView.setAdapter(bookmarksCursorAdapter);
860     }
861
862     private void deleteBookmarkFolderContents(int databaseId) {
863         // Get the name of the folder.
864         String folderName = bookmarksDatabaseHelper.getFolderName(databaseId);
865
866         // Get the contents of the folder.
867         Cursor folderCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(folderName);
868
869         for (int i = 0; i < folderCursor.getCount(); i++) {
870             // Move `folderCursor` to the current row.
871             folderCursor.moveToPosition(i);
872
873             // Get the database ID of the item.
874             int itemDatabaseId = folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID));
875
876             // If this is a folder, delete the contents first.
877             if (bookmarksDatabaseHelper.isFolder(itemDatabaseId)) {
878                 deleteBookmarkFolderContents(itemDatabaseId);
879             }
880
881             bookmarksDatabaseHelper.deleteBookmark(itemDatabaseId);
882         }
883     }
884 }