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