]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/BookmarksActivity.java
108dcc043625b0595a39b4e3f1b6235299087fdc
[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.database.Cursor;
26 import android.graphics.Bitmap;
27 import android.graphics.BitmapFactory;
28 import android.graphics.drawable.BitmapDrawable;
29 import android.graphics.drawable.Drawable;
30 import android.os.Bundle;
31 import android.support.design.widget.FloatingActionButton;
32 import android.support.design.widget.Snackbar;
33 import android.support.v4.app.NavUtils;
34 import android.support.v4.widget.CursorAdapter;
35 import android.support.v7.app.ActionBar;
36 import android.support.v7.app.AppCompatActivity;
37 import android.support.v7.widget.Toolbar;
38 import android.view.ActionMode;
39 import android.view.Menu;
40 import android.view.MenuItem;
41 import android.view.View;
42 import android.view.ViewGroup;
43 import android.widget.AbsListView;
44 import android.widget.AdapterView;
45 import android.widget.CheckBox;
46 import android.widget.EditText;
47 import android.widget.ImageView;
48 import android.widget.ListView;
49 import android.widget.TextView;
50
51 import java.io.ByteArrayOutputStream;
52
53 public class BookmarksActivity extends AppCompatActivity implements CreateBookmark.CreateBookmarkListener, EditBookmark.EditBookmarkListener {
54     // `bookmarksDatabaseHandler` is public static so it can be accessed from EditBookmark.  It is also used in `onCreate()`,
55     // `onCreateBookmarkCreate()`, `updateBookmarksListView()`, and `updateBookmarksListViewExcept()`.
56     public static BookmarksDatabaseHandler bookmarksDatabaseHandler;
57
58     // `bookmarksListView` is public static so it can be accessed from EditBookmark.
59     // It is also used in `onCreate()`, `updateBookmarksListView()`, and `updateBookmarksListViewExcept()`.
60     public static ListView bookmarksListView;
61
62     // `contextualActionMode` is used in `onCreate()` and `onEditBookmarkSave()`.
63     private ActionMode contextualActionMode;
64
65     @Override
66     protected void onCreate(Bundle savedInstanceState) {
67         super.onCreate(savedInstanceState);
68         setContentView(R.layout.bookmarks_coordinatorlayout);
69
70         // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
71         final Toolbar bookmarksAppBar = (Toolbar) findViewById(R.id.bookmarks_toolbar);
72         setSupportActionBar(bookmarksAppBar);
73
74         // Display the home arrow on supportAppBar.
75         final ActionBar appBar = getSupportActionBar();
76         assert appBar != null;// This assert removes the incorrect warning in Android Studio on the following line that appBar might be null.
77         appBar.setDisplayHomeAsUpEnabled(true);
78
79         // Initialize the database handler and the ListView.
80         // `this` specifies the context.  The two `null`s do not specify the database name or a `CursorFactory`.
81         // The `0` is to specify a database version, but that is set instead using a constant in BookmarksDatabaseHandler.
82         bookmarksDatabaseHandler = new BookmarksDatabaseHandler(this, null, null, 0);
83         bookmarksListView = (ListView) findViewById(R.id.bookmarks_listview);
84
85         // Display the bookmarks in the ListView.
86         updateBookmarksListView();
87
88         // Set a listener so that tapping a list item loads the URL.  We need to store the activity
89         // in a variable so that we can return to the parent activity after loading the URL.
90         final Activity bookmarksActivity = this;
91         bookmarksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
92             @Override
93             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
94                 // Convert the id from long to int to match the format of the bookmarks database.
95                 int databaseID = (int) id;
96
97                 // Get the bookmark URL and assign it to formattedUrlString.
98                 MainWebViewActivity.formattedUrlString = bookmarksDatabaseHandler.getBookmarkURL(databaseID);
99
100                 //  Load formattedUrlString and return to the main activity.
101                 MainWebViewActivity.mainWebView.loadUrl(MainWebViewActivity.formattedUrlString);
102                 NavUtils.navigateUpFromSameTask(bookmarksActivity);
103             }
104         });
105
106         // `MultiChoiceModeListener` handles long clicks.
107         bookmarksListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
108             // `editBookmarkMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
109             MenuItem editBookmarkMenuItem;
110
111             @Override
112             public boolean onCreateActionMode(ActionMode mode, Menu menu) {
113                 // Inflate the menu for the contextual app bar and set the title.
114                 getMenuInflater().inflate(R.menu.bookmarks_context_menu, menu);
115                 mode.setTitle(R.string.bookmarks);
116
117                 // Get a handle for `R.id.edit_bookmark`.
118                 editBookmarkMenuItem = menu.findItem(R.id.edit_bookmark);
119
120                 return true;
121             }
122
123             @Override
124             public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
125                 return false;
126             }
127
128             @Override
129             public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
130                 // Get an array of the selected bookmarks.
131                 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
132
133                 // Calculate the number of selected bookmarks.
134                 int numberOfSelectedBookmarks = selectedBookmarksLongArray.length;
135
136                 // List the number of selected bookmarks in the subtitle.
137                 mode.setSubtitle(numberOfSelectedBookmarks + " " + getString(R.string.selected));
138
139                 // Show the `Edit` option only if 1 bookmark is selected.
140                 if (numberOfSelectedBookmarks == 1) {
141                     editBookmarkMenuItem.setVisible(true);
142                 } else {
143                     editBookmarkMenuItem.setVisible(false);
144                 }
145             }
146
147             @Override
148             public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
149                 int menuItemId = item.getItemId();
150
151                 switch (menuItemId) {
152                     case R.id.edit_bookmark:
153                         // Show the `EditBookmark` `AlertDialog` and name the instance `@string/edit_bookmark`.
154                         DialogFragment editBookmarkDialog = new EditBookmark();
155                         editBookmarkDialog.show(getFragmentManager(), "@string/edit_bookmark");
156
157                         contextualActionMode = mode;
158                         break;
159
160                     case R.id.delete_bookmark:
161                         // Get an array of the selected rows.
162                         final long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
163
164                         String snackbarMessage;
165
166                         // Determine how many items are in the array and prepare an appropriate Snackbar message.
167                         if (selectedBookmarksLongArray.length == 1) {
168                             snackbarMessage = getString(R.string.one_bookmark_deleted);
169                         } else {
170                             snackbarMessage = selectedBookmarksLongArray.length + " " + getString(R.string.bookmarks_deleted);
171                         }
172
173                         updateBookmarksListViewExcept(selectedBookmarksLongArray);
174
175                         // Show a SnackBar.
176                         Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), snackbarMessage, Snackbar.LENGTH_LONG)
177                                 .setAction(R.string.undo, new View.OnClickListener() {
178                                     @Override
179                                     public void onClick(View view) {
180                                         // Do nothing because everything will be handled by `onDismissed()` below.
181                                     }
182                                 })
183                                 .setCallback(new Snackbar.Callback() {
184                                     @Override
185                                     public void onDismissed(Snackbar snackbar, int event) {
186                                         switch (event) {
187                                             // The user pushed the "Undo" button.
188                                             case Snackbar.Callback.DISMISS_EVENT_ACTION:
189                                                 // Refresh the ListView to show the rows again.
190                                                 updateBookmarksListView();
191
192                                                 break;
193
194                                             // The Snackbar was dismissed without the "Undo" button being pushed.
195                                             default:
196                                                 // Delete each selected row.
197                                                 for (long databaseIdLong : selectedBookmarksLongArray) {
198                                                     // Convert `databaseIdLong` to an int.
199                                                     int databaseIdInt = (int) databaseIdLong;
200
201                                                     // Delete the database row.
202                                                     bookmarksDatabaseHandler.deleteBookmark(databaseIdInt);
203                                                 }
204                                                 break;
205                                         }
206                                     }
207                                 })
208                                 .show();
209
210                         // Close the contextual app bar.
211                         mode.finish();
212                         break;
213                 }
214                 // Consume the click.
215                 return true;
216             }
217
218             @Override
219             public void onDestroyActionMode(ActionMode mode) {
220
221             }
222         });
223
224         // Set a FloatingActionButton for creating new bookmarks.
225         FloatingActionButton createBookmarkFAB = (FloatingActionButton) findViewById(R.id.create_bookmark_fab);
226         assert createBookmarkFAB != null;
227         createBookmarkFAB.setOnClickListener(new View.OnClickListener() {
228             @Override
229             public void onClick(View view) {
230                 // Show the `CreateBookmark` `AlertDialog` and name the instance `@string/create_bookmark`.
231                 DialogFragment createBookmarkDialog = new CreateBookmark();
232                 createBookmarkDialog.show(getFragmentManager(), "@string/create_bookmark");
233             }
234         });
235     }
236
237     @Override
238     public void onCreateBookmarkCancel(DialogFragment createBookmarkDialogFragment) {
239         // Do nothing because the user selected `Cancel`.
240     }
241
242     @Override
243     public void onCreateBookmarkCreate(DialogFragment createBookmarkDialogFragment) {
244         // Get the `EditText`s from the `createBookmarkDialogFragment` and extract the strings.
245         EditText createBookmarkNameEditText = (EditText) createBookmarkDialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
246         String bookmarkNameString = createBookmarkNameEditText.getText().toString();
247         EditText createBookmarkUrlEditText = (EditText) createBookmarkDialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
248         String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
249
250         // Convert the favoriteIcon Bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
251         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
252         MainWebViewActivity.favoriteIcon.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
253         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
254
255         // Create the bookmark.
256         bookmarksDatabaseHandler.createBookmark(bookmarkNameString, bookmarkUrlString, favoriteIconByteArray);
257
258         // Refresh the ListView.
259         updateBookmarksListView();
260     }
261
262     @Override
263     public void onEditBookmarkCancel(DialogFragment editBookmarkDialogFragment) {
264         // Do nothing because the user selected `Cancel`.
265     }
266
267     @Override
268     public void onEditBookmarkSave(DialogFragment editBookmarkDialogFragment) {
269         // Get the `EditText`s from the `editBookmarkDialogFragment` and extract the strings.
270         EditText editBookmarkNameEditText = (EditText) editBookmarkDialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
271         String bookmarkNameString = editBookmarkNameEditText.getText().toString();
272         EditText editBookmarkUrlEditText = (EditText) editBookmarkDialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
273         String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
274
275         CheckBox useNewFavoriteIconBitmap = (CheckBox) editBookmarkDialogFragment.getDialog().findViewById(R.id.edit_bookmark_use_new_favorite_icon_checkbox);
276         byte[] favoriteIconByteArray;
277
278         // Get a long array with the the databaseId of the selected bookmark and convert it to an `int`.
279         long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
280         int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
281
282         if (useNewFavoriteIconBitmap.isChecked()) {
283             ImageView newFavoriteIconImageView = (ImageView) editBookmarkDialogFragment.getDialog().findViewById(R.id.edit_bookmark_new_favorite_icon);
284             Drawable favoriteIconDrawable = newFavoriteIconImageView.getDrawable();
285             Bitmap favoriteIconBitmap = ((BitmapDrawable) favoriteIconDrawable).getBitmap();
286             ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
287             favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
288             favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
289             bookmarksDatabaseHandler.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, favoriteIconByteArray);
290
291         } else {
292             // Update the bookmark.
293             bookmarksDatabaseHandler.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
294         }
295
296         contextualActionMode.finish();
297
298         // Refresh the `ListView`.
299         updateBookmarksListView();
300     }
301
302     private void updateBookmarksListView() {
303         // Get a Cursor with the current contents of the bookmarks database.
304         final Cursor bookmarksCursor = bookmarksDatabaseHandler.getAllBookmarksCursor();
305
306         // Setup bookmarksCursorAdapter with `this` context.  The `false` disables autoRequery.
307         CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
308             @Override
309             public View newView(Context context, Cursor cursor, ViewGroup parent) {
310                 // Inflate the individual item layout.  `false` does not attach it to the root.
311                 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
312             }
313
314             @Override
315             public void bindView(View view, Context context, Cursor cursor) {
316                 // Get the favorite icon byte array from the `Cursor`.
317                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHandler.FAVORITE_ICON));
318
319                 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
320                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
321
322                 // Display the bitmap in `bookmarkFavoriteIcon`.
323                 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
324                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
325
326
327                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
328                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHandler.BOOKMARK_NAME));
329                 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
330                 assert bookmarkNameTextView != null;  // This assert removes the warning that bookmarkNameTextView might be null.
331                 bookmarkNameTextView.setText(bookmarkNameString);
332             }
333         };
334
335         // Update the ListView.
336         bookmarksListView.setAdapter(bookmarksCursorAdapter);
337     }
338
339     private void updateBookmarksListViewExcept(long[] exceptIdLongArray) {
340         // Get a Cursor with the current contents of the bookmarks database except for the specified database IDs.
341         final Cursor bookmarksCursor = bookmarksDatabaseHandler.getBookmarksCursorExcept(exceptIdLongArray);
342
343         // Setup bookmarksCursorAdapter with `this` context.  The `false` disables autoRequery.
344         CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
345             @Override
346             public View newView(Context context, Cursor cursor, ViewGroup parent) {
347                 // Inflate the individual item layout.  `false` does not attach it to the root.
348                 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
349             }
350
351             @Override
352             public void bindView(View view, Context context, Cursor cursor) {
353                 // Get the favorite icon byte array from the cursor.
354                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHandler.FAVORITE_ICON));
355
356                 // Convert the byte array to a Bitmap beginning at the first byte and ending at the last.
357                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
358
359                 // Display the bitmap in `bookmarkFavoriteIcon`.
360                 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
361                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
362
363
364                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
365                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHandler.BOOKMARK_NAME));
366                 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
367                 assert bookmarkNameTextView != null;  // This assert removes the warning that bookmarkNameTextView might be null.
368                 bookmarkNameTextView.setText(bookmarkNameString);
369             }
370         };
371
372         // Update the ListView.
373         bookmarksListView.setAdapter(bookmarksCursorAdapter);
374     }
375 }