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