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