]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/EditBookmarkDatabaseViewDialog.java
Add a context menu to delete bookmarks from the database view activity. https:/...
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / EditBookmarkDatabaseViewDialog.java
1 /*
2  * Copyright © 2016-2019 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.dialogs;
21
22 import android.annotation.SuppressLint;
23 import android.app.AlertDialog;
24 import android.app.Dialog;
25 import android.content.Context;
26 import android.content.DialogInterface;
27 import android.database.Cursor;
28 import android.database.MatrixCursor;
29 import android.database.MergeCursor;
30 import android.graphics.Bitmap;
31 import android.graphics.BitmapFactory;
32 import android.os.Bundle;
33 import android.support.annotation.NonNull;
34 // `AppCompatDialogFragment` is required instead of `DialogFragment` or an error is produced on API <=22.
35 import android.support.v4.widget.ResourceCursorAdapter;
36 import android.support.v7.app.AppCompatDialogFragment;
37 import android.text.Editable;
38 import android.text.TextWatcher;
39 import android.view.KeyEvent;
40 import android.view.View;
41 import android.view.WindowManager;
42 import android.widget.AdapterView;
43 import android.widget.Button;
44 import android.widget.EditText;
45 import android.widget.ImageView;
46 import android.widget.RadioButton;
47 import android.widget.RadioGroup;
48 import android.widget.Spinner;
49 import android.widget.TextView;
50
51 import com.stoutner.privacybrowser.R;
52 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
53 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
54
55 public class EditBookmarkDatabaseViewDialog extends AppCompatDialogFragment {
56     // Instantiate the constants.
57     public static final int HOME_FOLDER_DATABASE_ID = -1;
58
59     // Instantiate the class variables.
60     private EditBookmarkDatabaseViewListener editBookmarkDatabaseViewListener;
61     private String currentBookmarkName;
62     private String currentUrl;
63     private int currentFolderDatabaseId;
64     private String currentDisplayOrder;
65     private RadioButton newIconRadioButton;
66     private EditText nameEditText;
67     private EditText urlEditText;
68     private Spinner folderSpinner;
69     private EditText displayOrderEditText;
70     private Button editButton;
71
72     // The public interface is used to send information back to the parent activity.
73     public interface EditBookmarkDatabaseViewListener {
74         void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId);
75     }
76
77     @Override
78     public void onAttach(Context context) {
79         // Run the default commands.
80         super.onAttach(context);
81
82         // Get a handle for `EditBookmarkDatabaseViewListener` from the launching context.
83
84         editBookmarkDatabaseViewListener = (EditBookmarkDatabaseViewListener) context;
85     }
86
87     // Store the database ID in the arguments bundle.
88     public static EditBookmarkDatabaseViewDialog bookmarkDatabaseId(int databaseId) {
89         // Create a bundle.
90         Bundle bundle = new Bundle();
91
92         // Store the bookmark database ID in the bundle.
93         bundle.putInt("Database ID", databaseId);
94
95         // Add the bundle to the dialog.
96         EditBookmarkDatabaseViewDialog editBookmarkDatabaseViewDialog = new EditBookmarkDatabaseViewDialog();
97         editBookmarkDatabaseViewDialog.setArguments(bundle);
98
99         // Return the new dialog.
100         return editBookmarkDatabaseViewDialog;
101     }
102
103         // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
104     @SuppressLint("InflateParams")
105     @Override
106     @NonNull
107     public Dialog onCreateDialog(Bundle savedInstanceState) {
108         // Remove the incorrect lint warning below that `getInt()` might be null.
109         assert getArguments() != null;
110
111         // Get the bookmark database ID from the bundle.
112         int bookmarkDatabaseId = getArguments().getInt("Database ID");
113
114         // Initialize the database helper.  The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
115         BookmarksDatabaseHelper bookmarksDatabaseHelper = new BookmarksDatabaseHelper(getContext(), null, null, 0);
116
117         // Get a cursor with the selected bookmark and move it to the first position.
118         Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(bookmarkDatabaseId);
119         bookmarkCursor.moveToFirst();
120
121         // Use an alert dialog builder to create the alert dialog.
122         AlertDialog.Builder dialogBuilder;
123
124         // Set the style according to the theme.
125         if (MainWebViewActivity.darkTheme) {
126             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
127         } else {
128             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
129         }
130
131         // Set the title.
132         dialogBuilder.setTitle(R.string.edit_bookmark);
133
134         // Remove the incorrect lint warning below that `getLayoutInflater()` might be null.
135         assert getActivity() != null;
136
137         // Set the view.  The parent view is `null` because it will be assigned by `AlertDialog`.
138         dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.edit_bookmark_databaseview_dialog, null));
139
140         // Set the listener for the negative button.
141         dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
142             // Do nothing.  The `AlertDialog` will close automatically.
143         });
144
145         // Set the listener fo the positive button.
146         dialogBuilder.setPositiveButton(R.string.save, (DialogInterface dialog, int which) -> {
147             // Return the `DialogFragment` to the parent activity on save.
148             editBookmarkDatabaseViewListener.onSaveBookmark(EditBookmarkDatabaseViewDialog.this, bookmarkDatabaseId);
149         });
150
151         // Create an alert dialog from the alert dialog builder`.
152         final AlertDialog alertDialog = dialogBuilder.create();
153
154         // Remove the warning below that `getWindow()` might be null.
155         assert alertDialog.getWindow() != null;
156
157         // Disable screenshots if not allowed.
158         if (!MainWebViewActivity.allowScreenshots) {
159             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
160         }
161
162         // Set the keyboard to be hidden when the `AlertDialog` is first shown.  If this is not set, the `AlertDialog` will not shrink when the keyboard is displayed.
163         alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
164
165         // The alert dialog must be shown before items in the layout can be modified.
166         alertDialog.show();
167
168         // Get handles for the layout items.
169         TextView databaseIdTextView = alertDialog.findViewById(R.id.edit_bookmark_database_id_textview);
170         RadioGroup iconRadioGroup = alertDialog.findViewById(R.id.edit_bookmark_icon_radiogroup);
171         ImageView currentIconImageView = alertDialog.findViewById(R.id.edit_bookmark_current_icon);
172         ImageView newFavoriteIconImageView = alertDialog.findViewById(R.id.edit_bookmark_webpage_favorite_icon);
173         newIconRadioButton = alertDialog.findViewById(R.id.edit_bookmark_webpage_favorite_icon_radiobutton);
174         nameEditText = alertDialog.findViewById(R.id.edit_bookmark_name_edittext);
175         urlEditText = alertDialog.findViewById(R.id.edit_bookmark_url_edittext);
176         folderSpinner = alertDialog.findViewById(R.id.edit_bookmark_folder_spinner);
177         displayOrderEditText = alertDialog.findViewById(R.id.edit_bookmark_display_order_edittext);
178         editButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
179
180         // Store the current bookmark values.
181         currentBookmarkName = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
182         currentUrl = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL));
183         currentDisplayOrder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER));
184
185         // Set the database ID.
186         databaseIdTextView.setText(String.valueOf(bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper._ID))));
187
188         // Get the current favorite icon byte array from the `Cursor`.
189         byte[] currentIconByteArray = bookmarkCursor.getBlob(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
190
191         // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
192         Bitmap currentIconBitmap = BitmapFactory.decodeByteArray(currentIconByteArray, 0, currentIconByteArray.length);
193
194         // Display `currentIconBitmap` in `edit_bookmark_current_icon`.
195         currentIconImageView.setImageBitmap(currentIconBitmap);
196
197         // Get a `Bitmap` of the favorite icon from `MainWebViewActivity` and display it in `edit_bookmark_web_page_favorite_icon`.
198         newFavoriteIconImageView.setImageBitmap(MainWebViewActivity.favoriteIconBitmap);
199
200         // Populate the bookmark name and URL `EditTexts`.
201         nameEditText.setText(currentBookmarkName);
202         urlEditText.setText(currentUrl);
203
204         // Setup a `MatrixCursor` "Home Folder".
205         String[] matrixCursorColumnNames = {BookmarksDatabaseHelper._ID, BookmarksDatabaseHelper.BOOKMARK_NAME};
206         MatrixCursor matrixCursor = new MatrixCursor(matrixCursorColumnNames);
207         matrixCursor.addRow(new Object[]{HOME_FOLDER_DATABASE_ID, getString(R.string.home_folder)});
208
209         // Get a `Cursor` with the list of all the folders.
210         Cursor foldersCursor = bookmarksDatabaseHelper.getAllFolders();
211
212         // Combine `matrixCursor` and `foldersCursor`.
213         MergeCursor foldersMergeCursor = new MergeCursor(new Cursor[]{matrixCursor, foldersCursor});
214
215         // Remove the incorrect lint warning below that `getContext()` might be null.
216         assert getContext() != null;
217
218         // Create a `ResourceCursorAdapter` for the `Spinner`.  `0` specifies no flags.;
219         ResourceCursorAdapter foldersCursorAdapter = new ResourceCursorAdapter(getContext(), R.layout.spinner_item, foldersMergeCursor, 0) {
220             @Override
221             public void bindView(View view, Context context, Cursor cursor) {
222                 // Get a handle for the `Spinner` item `TextView`.
223                 TextView spinnerItemTextView = view.findViewById(R.id.spinner_item_textview);
224
225                 // Set the `TextView` to display the folder name.
226                 spinnerItemTextView.setText(cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME)));
227             }
228         };
229
230         // Set the `ResourceCursorAdapter` drop drown view resource.
231         foldersCursorAdapter.setDropDownViewResource(R.layout.spinner_dropdown_items);
232
233         // Set the adapter for the folder `Spinner`.
234         folderSpinner.setAdapter(foldersCursorAdapter);
235
236         // Get the parent folder name.
237         String parentFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.PARENT_FOLDER));
238
239         // Select the current folder in the `Spinner` if the bookmark isn't in the "Home Folder".
240         if (!parentFolder.equals("")) {
241             // Get the database ID of the parent folder.
242             int folderDatabaseId = bookmarksDatabaseHelper.getFolderDatabaseId(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.PARENT_FOLDER)));
243
244             // Initialize `parentFolderPosition` and the iteration variable.
245             int parentFolderPosition = 0;
246             int i = 0;
247
248             // Find the parent folder position in folders `ResourceCursorAdapter`.
249             do {
250                 if (foldersCursorAdapter.getItemId(i) == folderDatabaseId) {
251                     // Store the current position for the parent folder.
252                     parentFolderPosition = i;
253                 } else {
254                     // Try the next entry.
255                     i++;
256                 }
257                 // Stop when the parent folder position is found or all the items in the `ResourceCursorAdapter` have been checked.
258             } while ((parentFolderPosition == 0) && (i < foldersCursorAdapter.getCount()));
259
260             // Select the parent folder in the `Spinner`.
261             folderSpinner.setSelection(parentFolderPosition);
262         }
263
264         // Store the current folder database ID.
265         currentFolderDatabaseId = (int) folderSpinner.getSelectedItemId();
266
267         // Populate the display order `EditText`.
268         displayOrderEditText.setText(String.valueOf(bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER))));
269
270         // Initially disable the edit button.
271         editButton.setEnabled(false);
272
273         // Update the edit button if the icon selection changes.
274         iconRadioGroup.setOnCheckedChangeListener((group, checkedId) -> {
275             // Update the edit button.
276             updateEditButton();
277         });
278
279         // Update the edit button if the bookmark name changes.
280         nameEditText.addTextChangedListener(new TextWatcher() {
281             @Override
282             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
283                 // Do nothing.
284             }
285
286             @Override
287             public void onTextChanged(CharSequence s, int start, int before, int count) {
288                 // Do nothing.
289             }
290
291             @Override
292             public void afterTextChanged(Editable s) {
293                 // Update the edit button.
294                 updateEditButton();
295             }
296         });
297
298         // Update the edit button if the URL changes.
299         urlEditText.addTextChangedListener(new TextWatcher() {
300             @Override
301             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
302                 // Do nothing.
303             }
304
305             @Override
306             public void onTextChanged(CharSequence s, int start, int before, int count) {
307                 // Do nothing.
308             }
309
310             @Override
311             public void afterTextChanged(Editable s) {
312                 // Update the edit button.
313                 updateEditButton();
314             }
315         });
316
317         // Update the edit button if the folder changes.
318         folderSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
319             @Override
320             public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
321                 // Update the edit button.
322                 updateEditButton();
323             }
324
325             @Override
326             public void onNothingSelected(AdapterView<?> parent) {
327
328             }
329         });
330
331         // Update the edit button if the display order changes.
332         displayOrderEditText.addTextChangedListener(new TextWatcher() {
333             @Override
334             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
335                 // Do nothing.
336             }
337
338             @Override
339             public void onTextChanged(CharSequence s, int start, int before, int count) {
340                 // Do nothing.
341             }
342
343             @Override
344             public void afterTextChanged(Editable s) {
345                 // Update the edit button.
346                 updateEditButton();
347             }
348         });
349
350         // Allow the `enter` key on the keyboard to save the bookmark from the bookmark name `EditText`.
351         nameEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
352             // Save the bookmark if the event is a key-down on the "enter" button.
353             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) {  // The enter key was pressed and the edit button is enabled.
354                 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
355                 editBookmarkDatabaseViewListener.onSaveBookmark(EditBookmarkDatabaseViewDialog.this, bookmarkDatabaseId);
356
357                 // Manually dismiss `alertDialog`.
358                 alertDialog.dismiss();
359
360                 // Consume the event.
361                 return true;
362             } else {  // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
363                 return false;
364             }
365         });
366
367         // Allow the "enter" key on the keyboard to save the bookmark from the URL `EditText`.
368         urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
369             // Save the bookmark if the event is a key-down on the "enter" button.
370             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) {  // The enter key was pressed and the edit button is enabled.
371                 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
372                 editBookmarkDatabaseViewListener.onSaveBookmark(EditBookmarkDatabaseViewDialog.this, bookmarkDatabaseId);
373
374                 // Manually dismiss the `AlertDialog`.
375                 alertDialog.dismiss();
376
377                 // Consume the event.
378                 return true;
379             } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
380                 return false;
381             }
382         });
383
384         // Allow the "enter" key on the keyboard to save the bookmark from the display order `EditText`.
385         displayOrderEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
386             // Save the bookmark if the event is a key-down on the "enter" button.
387             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) {  // The enter key was pressed and the edit button is enabled.
388                 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
389                 editBookmarkDatabaseViewListener.onSaveBookmark(EditBookmarkDatabaseViewDialog.this, bookmarkDatabaseId);
390
391                 // Manually dismiss the `AlertDialog`.
392                 alertDialog.dismiss();
393
394                 // Consume the event.
395                 return true;
396             } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
397                 return false;
398             }
399         });
400
401         // `onCreateDialog` requires the return of an `AlertDialog`.
402         return alertDialog;
403     }
404
405     private void updateEditButton() {
406         // Get the values from the dialog.
407         String newName = nameEditText.getText().toString();
408         String newUrl = urlEditText.getText().toString();
409         int newFolderDatabaseId = (int) folderSpinner.getSelectedItemId();
410         String newDisplayOrder = displayOrderEditText.getText().toString();
411
412         // Has the favorite icon changed?
413         boolean iconChanged = newIconRadioButton.isChecked();
414
415         // Has the name changed?
416         boolean nameChanged = !newName.equals(currentBookmarkName);
417
418         // Has the URL changed?
419         boolean urlChanged = !newUrl.equals(currentUrl);
420
421         // Has the folder changed?
422         boolean folderChanged = newFolderDatabaseId != currentFolderDatabaseId;
423
424         // Has the display order changed?
425         boolean displayOrderChanged = !newDisplayOrder.equals(currentDisplayOrder);
426
427         // Is the display order empty?
428         boolean displayOrderNotEmpty = !newDisplayOrder.isEmpty();
429
430         // Update the enabled status of the edit button.
431         editButton.setEnabled((iconChanged || nameChanged || urlChanged || folderChanged || displayOrderChanged) && displayOrderNotEmpty);
432     }
433 }