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