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