]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/EditBookmarkFolderDatabaseViewDialog.java
Switch to the new Day/Night theme. https://redmine.stoutner.com/issues/522
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / EditBookmarkFolderDatabaseViewDialog.java
1 /*
2  * Copyright © 2016-2020 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.Dialog;
24 import android.content.Context;
25 import android.content.DialogInterface;
26 import android.content.SharedPreferences;
27 import android.database.Cursor;
28 import android.database.DatabaseUtils;
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.util.Log;
38 import android.view.KeyEvent;
39 import android.view.View;
40 import android.view.WindowManager;
41 import android.widget.AdapterView;
42 import android.widget.Button;
43 import android.widget.EditText;
44 import android.widget.ImageView;
45 import android.widget.RadioButton;
46 import android.widget.RadioGroup;
47 import android.widget.ResourceCursorAdapter;
48 import android.widget.Spinner;
49 import android.widget.TextView;
50
51 import androidx.annotation.NonNull;
52 import androidx.appcompat.app.AlertDialog;
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 import com.stoutner.privacybrowser.R;
57 import com.stoutner.privacybrowser.activities.BookmarksDatabaseViewActivity;
58 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
59
60 import java.io.ByteArrayOutputStream;
61
62 public class EditBookmarkFolderDatabaseViewDialog extends DialogFragment {
63     // Define the edit bookmark folder database view listener.
64     private EditBookmarkFolderDatabaseViewListener editBookmarkFolderDatabaseViewListener;
65
66
67     // The public interface is used to send information back to the parent activity.
68     public interface EditBookmarkFolderDatabaseViewListener {
69         void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap);
70     }
71
72     public void onAttach(@NonNull Context context) {
73         // Run the default commands.
74         super.onAttach(context);
75
76         // Get a handle for `EditBookmarkDatabaseViewListener` from the launching context.
77         editBookmarkFolderDatabaseViewListener = (EditBookmarkFolderDatabaseViewListener) context;
78     }
79
80
81     public static EditBookmarkFolderDatabaseViewDialog folderDatabaseId(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         EditBookmarkFolderDatabaseViewDialog editBookmarkFolderDatabaseViewDialog = new EditBookmarkFolderDatabaseViewDialog();
100
101         // Add the arguments bundle to the dialog.
102         editBookmarkFolderDatabaseViewDialog.setArguments(argumentsBundle);
103
104         // Return the new dialog.
105         return editBookmarkFolderDatabaseViewDialog;
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 folderDatabaseId = 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 folderCursor = bookmarksDatabaseHelper.getBookmark(folderDatabaseId);
136         folderCursor.moveToFirst();
137
138         // Use an alert dialog builder to create the alert dialog.
139         AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(requireContext(), R.style.PrivacyBrowserAlertDialog);
140
141         // Set the title.
142         dialogBuilder.setTitle(R.string.edit_folder);
143
144         // Remove the incorrect lint warning that `getActivity()` might be null.
145         assert getActivity() != null;
146
147         // Set the view.  The parent view is `null` because it will be assigned by `AlertDialog`.
148         dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.edit_bookmark_folder_databaseview_dialog, null));
149
150         // Set the listener for the negative button.
151         dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
152             // Do nothing.  The `AlertDialog` will close automatically.
153         });
154
155         // Set the listener fo the positive button.
156         dialogBuilder.setPositiveButton(R.string.save, (DialogInterface dialog, int which) -> {
157             // Return the `DialogFragment` to the parent activity on save.
158             editBookmarkFolderDatabaseViewListener.onSaveBookmarkFolder(this, folderDatabaseId, favoriteIconBitmap);
159         });
160
161         // Create an alert dialog from the alert dialog builder.
162         final AlertDialog alertDialog = dialogBuilder.create();
163
164         // Remove the warning below that `getWindow()` might be null.
165         assert alertDialog.getWindow() != null;
166
167         // Get a handle for the shared preferences.
168         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
169
170         // Get the screenshot preference.
171         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
172
173         // Disable screenshots if not allowed.
174         if (!allowScreenshots) {
175             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
176         }
177
178         // The alert dialog must be shown before items in the layout can be modified.
179         alertDialog.show();
180
181         // Get handles for the layout items.
182         TextView databaseIdTextView = alertDialog.findViewById(R.id.edit_folder_database_id_textview);
183         RadioGroup iconRadioGroup = alertDialog.findViewById(R.id.edit_folder_icon_radiogroup);
184         ImageView currentIconImageView = alertDialog.findViewById(R.id.edit_folder_current_icon_imageview);
185         ImageView newFavoriteIconImageView = alertDialog.findViewById(R.id.edit_folder_webpage_favorite_icon_imageview);
186         EditText nameEditText = alertDialog.findViewById(R.id.edit_folder_name_edittext);
187         Spinner folderSpinner = alertDialog.findViewById(R.id.edit_folder_parent_folder_spinner);
188         EditText displayOrderEditText = alertDialog.findViewById(R.id.edit_folder_display_order_edittext);
189         Button editButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
190
191         // Remove the incorrect lint warnings below that the views might be null.
192         assert databaseIdTextView != null;
193         assert iconRadioGroup != null;
194         assert currentIconImageView != null;
195         assert newFavoriteIconImageView != null;
196         assert nameEditText != null;
197         assert folderSpinner != null;
198         assert displayOrderEditText != null;
199
200         // Store the current folder values.
201         String currentFolderName = folderCursor.getString(folderCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
202         int currentDisplayOrder = folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER));
203         String parentFolder = folderCursor.getString(folderCursor.getColumnIndex(BookmarksDatabaseHelper.PARENT_FOLDER));
204
205         // Set the database ID.
206         databaseIdTextView.setText(String.valueOf(folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID))));
207
208         // Get the current favorite icon byte array from the `Cursor`.
209         byte[] currentIconByteArray = folderCursor.getBlob(folderCursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
210
211         // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
212         Bitmap currentIconBitmap = BitmapFactory.decodeByteArray(currentIconByteArray, 0, currentIconByteArray.length);
213
214         // Display the current icon bitmap in `edit_bookmark_current_icon`.
215         currentIconImageView.setImageBitmap(currentIconBitmap);
216
217         // Set the new favorite icon bitmap.
218         newFavoriteIconImageView.setImageBitmap(favoriteIconBitmap);
219
220         // Populate the folder name edit text.
221         nameEditText.setText(currentFolderName);
222
223         // Setup a matrix cursor for "Home Folder".
224         String[] matrixCursorColumnNames = {BookmarksDatabaseHelper._ID, BookmarksDatabaseHelper.BOOKMARK_NAME};
225         MatrixCursor matrixCursor = new MatrixCursor(matrixCursorColumnNames);
226         matrixCursor.addRow(new Object[]{BookmarksDatabaseViewActivity.HOME_FOLDER_DATABASE_ID, getString(R.string.home_folder)});
227
228         // Add all subfolders of the current folder to the list of folders not to display.
229         String exceptFolders = getStringOfSubfolders(currentFolderName, bookmarksDatabaseHelper);
230
231         Log.i("Folders", "String of Folders Not To Display:  " + exceptFolders);
232
233         // Get a cursor with the list of all the folders.
234         Cursor foldersCursor = bookmarksDatabaseHelper.getFoldersExcept(exceptFolders);
235
236         // Combine the matrix cursor and the folders cursor.
237         MergeCursor foldersMergeCursor = new MergeCursor(new Cursor[]{matrixCursor, foldersCursor});
238
239         // Remove the incorrect lint warning that `getContext()` might be null.
240         assert getContext() != null;
241
242         // Create a resource cursor adapter for the spinner.
243         ResourceCursorAdapter foldersCursorAdapter = new ResourceCursorAdapter(getContext(), R.layout.databaseview_spinner_item, foldersMergeCursor, 0) {
244             @Override
245             public void bindView(View view, Context context, Cursor cursor) {
246                 // Get handles for the spinner views.
247                 ImageView spinnerItemImageView = view.findViewById(R.id.spinner_item_imageview);
248                 TextView spinnerItemTextView = view.findViewById(R.id.spinner_item_textview);
249
250                 // Set the folder icon according to the type.
251                 if (foldersMergeCursor.getPosition() == 0) {  // Set the `Home Folder` icon.
252                     // Set the gray folder image.  `ContextCompat` must be used until the minimum API >= 21.
253                     spinnerItemImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.folder_gray));
254                 } else {  // Set a user folder icon.
255                     // Get the folder icon byte array.
256                     byte[] folderIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
257
258                     // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
259                     Bitmap folderIconBitmap = BitmapFactory.decodeByteArray(folderIconByteArray, 0, folderIconByteArray.length);
260
261                     // Set the folder icon.
262                     spinnerItemImageView.setImageBitmap(folderIconBitmap);
263                 }
264
265                 // Set the text view to display the folder name.
266                 spinnerItemTextView.setText(cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME)));
267             }
268         };
269
270         // Set the `ResourceCursorAdapter` drop drown view resource.
271         foldersCursorAdapter.setDropDownViewResource(R.layout.databaseview_spinner_dropdown_items);
272
273         // Set the adapter for the folder `Spinner`.
274         folderSpinner.setAdapter(foldersCursorAdapter);
275
276         // Select the current folder in the `Spinner` if the bookmark isn't in the "Home Folder".
277         if (!parentFolder.equals("")) {
278             // Get the database ID of the parent folder.
279             int parentFolderDatabaseId = bookmarksDatabaseHelper.getFolderDatabaseId(folderCursor.getString(folderCursor.getColumnIndex(BookmarksDatabaseHelper.PARENT_FOLDER)));
280
281             // Initialize `parentFolderPosition` and the iteration variable.
282             int parentFolderPosition = 0;
283             int i = 0;
284
285             // Find the parent folder position in folders `ResourceCursorAdapter`.
286             do {
287                 if (foldersCursorAdapter.getItemId(i) == parentFolderDatabaseId) {
288                     // Store the current position for the parent folder.
289                     parentFolderPosition = i;
290                 } else {
291                     // Try the next entry.
292                     i++;
293                 }
294                 // Stop when the parent folder position is found or all the items in the `ResourceCursorAdapter` have been checked.
295             } while ((parentFolderPosition == 0) && (i < foldersCursorAdapter.getCount()));
296
297             // Select the parent folder in the `Spinner`.
298             folderSpinner.setSelection(parentFolderPosition);
299         }
300
301         // Store the current folder database ID.
302         int currentParentFolderDatabaseId = (int) folderSpinner.getSelectedItemId();
303
304         // Populate the display order `EditText`.
305         displayOrderEditText.setText(String.valueOf(folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER))));
306
307         // Initially disable the edit button.
308         editButton.setEnabled(false);
309
310         // Update the edit button if the icon selection changes.
311         iconRadioGroup.setOnCheckedChangeListener((group, checkedId) -> {
312             // Update the edit button.
313             updateEditButton(alertDialog, bookmarksDatabaseHelper, currentFolderName, currentParentFolderDatabaseId, currentDisplayOrder);
314         });
315
316         // Update the edit button if the bookmark name changes.
317         nameEditText.addTextChangedListener(new TextWatcher() {
318             @Override
319             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
320                 // Do nothing.
321             }
322
323             @Override
324             public void onTextChanged(CharSequence s, int start, int before, int count) {
325                 // Do nothing.
326             }
327
328             @Override
329             public void afterTextChanged(Editable s) {
330                 // Update the edit button.
331                 updateEditButton(alertDialog, bookmarksDatabaseHelper, currentFolderName, currentParentFolderDatabaseId, currentDisplayOrder);
332             }
333         });
334
335         // Update the edit button if the folder changes.
336         folderSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
337             @Override
338             public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
339                 // Update the edit button.
340                 updateEditButton(alertDialog, bookmarksDatabaseHelper, currentFolderName, currentParentFolderDatabaseId, currentDisplayOrder);
341             }
342
343             @Override
344             public void onNothingSelected(AdapterView<?> parent) {
345
346             }
347         });
348
349         // Update the edit button if the display order changes.
350         displayOrderEditText.addTextChangedListener(new TextWatcher() {
351             @Override
352             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
353                 // Do nothing.
354             }
355
356             @Override
357             public void onTextChanged(CharSequence s, int start, int before, int count) {
358                 // Do nothing.
359             }
360
361             @Override
362             public void afterTextChanged(Editable s) {
363                 // Update the edit button.
364                 updateEditButton(alertDialog, bookmarksDatabaseHelper, currentFolderName, currentParentFolderDatabaseId, currentDisplayOrder);
365             }
366         });
367
368         // Allow the `enter` key on the keyboard to save the bookmark from the bookmark name `EditText`.
369         nameEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
370             // Save the bookmark if the event is a key-down on the "enter" button.
371             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) {  // The enter key was pressed and the edit button is enabled.
372                 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
373                 editBookmarkFolderDatabaseViewListener.onSaveBookmarkFolder(this, folderDatabaseId, favoriteIconBitmap);
374
375                 // Manually dismiss `alertDialog`.
376                 alertDialog.dismiss();
377
378                 // Consume the event.
379                 return true;
380             } else {  // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
381                 return false;
382             }
383         });
384
385         // Allow the "enter" key on the keyboard to save the bookmark from the display order `EditText`.
386         displayOrderEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
387             // Save the bookmark if the event is a key-down on the "enter" button.
388             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) {  // The enter key was pressed and the edit button is enabled.
389                 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
390                 editBookmarkFolderDatabaseViewListener.onSaveBookmarkFolder(this, folderDatabaseId, favoriteIconBitmap);
391
392                 // Manually dismiss the `AlertDialog`.
393                 alertDialog.dismiss();
394
395                 // Consume the event.
396                 return true;
397             } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
398                 return false;
399             }
400         });
401
402         // `onCreateDialog` requires the return of an `AlertDialog`.
403         return alertDialog;
404     }
405
406     private void updateEditButton(AlertDialog alertDialog, BookmarksDatabaseHelper bookmarksDatabaseHelper, String currentFolderName, int currentParentFolderDatabaseId, int currentDisplayOrder) {
407         // Get handles for the views.
408         EditText nameEditText = alertDialog.findViewById(R.id.edit_folder_name_edittext);
409         Spinner folderSpinner = alertDialog.findViewById(R.id.edit_folder_parent_folder_spinner);
410         EditText displayOrderEditText = alertDialog.findViewById(R.id.edit_folder_display_order_edittext);
411         RadioButton currentIconRadioButton = alertDialog.findViewById(R.id.edit_folder_current_icon_radiobutton);
412         Button editButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
413
414         // Remove the incorrect lint warning below that the views might be null.
415         assert nameEditText != null;
416         assert folderSpinner != null;
417         assert displayOrderEditText != null;
418         assert currentIconRadioButton != null;
419
420         // Get the values from the dialog.
421         String newFolderName = nameEditText.getText().toString();
422         int newParentFolderDatabaseId = (int) folderSpinner.getSelectedItemId();
423         String newDisplayOrder = displayOrderEditText.getText().toString();
424
425         // Get a cursor for the new folder name if it exists.
426         Cursor folderExistsCursor = bookmarksDatabaseHelper.getFolder(newFolderName);
427
428         // Is the new folder name empty?
429         boolean folderNameNotEmpty = !newFolderName.isEmpty();
430
431         // Does the folder name already exist?
432         boolean folderNameAlreadyExists = (!newFolderName.equals(currentFolderName) && (folderExistsCursor.getCount() > 0));
433
434         // Has the favorite icon changed?
435         boolean iconChanged = !currentIconRadioButton.isChecked();
436
437         // Has the name been renamed?
438         boolean folderRenamed = (!newFolderName.equals(currentFolderName) && !folderNameAlreadyExists);
439
440         // Has the folder changed?
441         boolean parentFolderChanged = newParentFolderDatabaseId != currentParentFolderDatabaseId;
442
443         // Has the display order changed?
444         boolean displayOrderChanged = !newDisplayOrder.equals(String.valueOf(currentDisplayOrder));
445
446         // Is the display order empty?
447         boolean displayOrderNotEmpty = !newDisplayOrder.isEmpty();
448
449         // Update the enabled status of the edit button.
450         editButton.setEnabled((iconChanged || folderRenamed || parentFolderChanged || displayOrderChanged) && folderNameNotEmpty && displayOrderNotEmpty);
451     }
452
453     private String getStringOfSubfolders(String folderName, BookmarksDatabaseHelper bookmarksDatabaseHelper) {
454         // Get a cursor will all the immediate subfolders.
455         Cursor subfoldersCursor = bookmarksDatabaseHelper.getSubfolders(folderName);
456
457         // Initialize a string builder to track the folders not to display in the spinner and populate it with the current folder.
458         StringBuilder exceptFoldersStringBuilder = new StringBuilder(DatabaseUtils.sqlEscapeString(folderName));
459
460         for (int i = 0; i < subfoldersCursor.getCount(); i++) {
461             // Move the subfolder cursor to the current item.
462             subfoldersCursor.moveToPosition(i);
463
464             // Get the name of the subfolder.
465             String subfolderName = subfoldersCursor.getString(subfoldersCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
466
467             // Add a comma to the end of the existing string.
468             exceptFoldersStringBuilder.append(",");
469
470             // Get the folder name and run the task for any subfolders.
471             String subfolderString = getStringOfSubfolders(subfolderName, bookmarksDatabaseHelper);
472
473             // Add the folder name to the string builder.
474             exceptFoldersStringBuilder.append(subfolderString);
475         }
476
477         // Return the string of folders.
478         return exceptFoldersStringBuilder.toString();
479     }
480 }