]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/EditBookmarkFolderDatabaseViewDialog.java
0f7eff1a7ee12ba00e092b6a525f1c5123cb7e74
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / EditBookmarkFolderDatabaseViewDialog.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.DatabaseUtils;
30 import android.database.MatrixCursor;
31 import android.database.MergeCursor;
32 import android.graphics.Bitmap;
33 import android.graphics.BitmapFactory;
34 import android.os.Bundle;
35 import android.preference.PreferenceManager;
36 import android.text.Editable;
37 import android.text.TextWatcher;
38 import android.util.Log;
39 import android.view.KeyEvent;
40 import android.view.View;
41 import android.view.WindowManager;
42 import android.widget.AdapterView;
43 import android.widget.Button;
44 import android.widget.EditText;
45 import android.widget.ImageView;
46 import android.widget.RadioButton;
47 import android.widget.RadioGroup;
48 import android.widget.ResourceCursorAdapter;
49 import android.widget.Spinner;
50 import android.widget.TextView;
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 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;
140
141         // Get a handle for the shared preferences.
142         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
143
144         // Get the screenshot and theme preferences.
145         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
146         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
147
148         // Set the style according to the theme.
149         if (darkTheme) {
150             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
151         } else {
152             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
153         }
154
155         // Set the title.
156         dialogBuilder.setTitle(R.string.edit_folder);
157
158         // Remove the incorrect lint warning that `getActivity()` might be null.
159         assert getActivity() != null;
160
161         // Set the view.  The parent view is `null` because it will be assigned by `AlertDialog`.
162         dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.edit_bookmark_folder_databaseview_dialog, null));
163
164         // Set the listener for the negative button.
165         dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
166             // Do nothing.  The `AlertDialog` will close automatically.
167         });
168
169         // Set the listener fo the positive button.
170         dialogBuilder.setPositiveButton(R.string.save, (DialogInterface dialog, int which) -> {
171             // Return the `DialogFragment` to the parent activity on save.
172             editBookmarkFolderDatabaseViewListener.onSaveBookmarkFolder(this, folderDatabaseId, favoriteIconBitmap);
173         });
174
175         // Create an alert dialog from the alert dialog builder.
176         final AlertDialog alertDialog = dialogBuilder.create();
177
178         // Remove the warning below that `getWindow()` might be null.
179         assert alertDialog.getWindow() != null;
180
181         // Disable screenshots if not allowed.
182         if (!allowScreenshots) {
183             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
184         }
185
186         // The alert dialog must be shown before items in the layout can be modified.
187         alertDialog.show();
188
189         // Get handles for the layout items.
190         TextView databaseIdTextView = alertDialog.findViewById(R.id.edit_folder_database_id_textview);
191         RadioGroup iconRadioGroup = alertDialog.findViewById(R.id.edit_folder_icon_radiogroup);
192         ImageView currentIconImageView = alertDialog.findViewById(R.id.edit_folder_current_icon_imageview);
193         ImageView newFavoriteIconImageView = alertDialog.findViewById(R.id.edit_folder_webpage_favorite_icon_imageview);
194         EditText nameEditText = alertDialog.findViewById(R.id.edit_folder_name_edittext);
195         Spinner folderSpinner = alertDialog.findViewById(R.id.edit_folder_parent_folder_spinner);
196         EditText displayOrderEditText = alertDialog.findViewById(R.id.edit_folder_display_order_edittext);
197         Button editButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
198
199         // Store the current folder values.
200         String currentFolderName = folderCursor.getString(folderCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
201         int currentDisplayOrder = folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER));
202         String parentFolder = folderCursor.getString(folderCursor.getColumnIndex(BookmarksDatabaseHelper.PARENT_FOLDER));
203
204         // Set the database ID.
205         databaseIdTextView.setText(String.valueOf(folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID))));
206
207         // Get the current favorite icon byte array from the `Cursor`.
208         byte[] currentIconByteArray = folderCursor.getBlob(folderCursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
209
210         // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
211         Bitmap currentIconBitmap = BitmapFactory.decodeByteArray(currentIconByteArray, 0, currentIconByteArray.length);
212
213         // Display the current icon bitmap in `edit_bookmark_current_icon`.
214         currentIconImageView.setImageBitmap(currentIconBitmap);
215
216         // Set the new favorite icon bitmap.
217         newFavoriteIconImageView.setImageBitmap(favoriteIconBitmap);
218
219         // Populate the folder name edit text.
220         nameEditText.setText(currentFolderName);
221
222         // Setup a matrix cursor for "Home Folder".
223         String[] matrixCursorColumnNames = {BookmarksDatabaseHelper._ID, BookmarksDatabaseHelper.BOOKMARK_NAME};
224         MatrixCursor matrixCursor = new MatrixCursor(matrixCursorColumnNames);
225         matrixCursor.addRow(new Object[]{BookmarksDatabaseViewActivity.HOME_FOLDER_DATABASE_ID, getString(R.string.home_folder)});
226
227         // Add all subfolders of the current folder to the list of folders not to display.
228         String exceptFolders = getStringOfSubfolders(currentFolderName, bookmarksDatabaseHelper);
229
230         Log.i("Folders", "String of Folders Not To Display:  " + exceptFolders);
231
232         // Get a cursor with the list of all the folders.
233         Cursor foldersCursor = bookmarksDatabaseHelper.getFoldersExcept(exceptFolders);
234
235         // Combine the matrix cursor and the folders cursor.
236         MergeCursor foldersMergeCursor = new MergeCursor(new Cursor[]{matrixCursor, foldersCursor});
237
238         // Remove the incorrect lint warning that `getContext()` might be null.
239         assert getContext() != null;
240
241         // Create a resource cursor adapter for the spinner.
242         ResourceCursorAdapter foldersCursorAdapter = new ResourceCursorAdapter(getContext(), R.layout.databaseview_spinner_item, foldersMergeCursor, 0) {
243             @Override
244             public void bindView(View view, Context context, Cursor cursor) {
245                 // Get handles for the spinner views.
246                 ImageView spinnerItemImageView = view.findViewById(R.id.spinner_item_imageview);
247                 TextView spinnerItemTextView = view.findViewById(R.id.spinner_item_textview);
248
249                 // Set the folder icon according to the type.
250                 if (foldersMergeCursor.getPosition() == 0) {  // Set the `Home Folder` icon.
251                     // Set the gray folder image.  `ContextCompat` must be used until the minimum API >= 21.
252                     spinnerItemImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.folder_gray));
253                 } else {  // Set a user folder icon.
254                     // Get the folder icon byte array.
255                     byte[] folderIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
256
257                     // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
258                     Bitmap folderIconBitmap = BitmapFactory.decodeByteArray(folderIconByteArray, 0, folderIconByteArray.length);
259
260                     // Set the folder icon.
261                     spinnerItemImageView.setImageBitmap(folderIconBitmap);
262                 }
263
264                 // Set the text view to display the folder name.
265                 spinnerItemTextView.setText(cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME)));
266             }
267         };
268
269         // Set the `ResourceCursorAdapter` drop drown view resource.
270         foldersCursorAdapter.setDropDownViewResource(R.layout.databaseview_spinner_dropdown_items);
271
272         // Set the adapter for the folder `Spinner`.
273         folderSpinner.setAdapter(foldersCursorAdapter);
274
275         // Select the current folder in the `Spinner` if the bookmark isn't in the "Home Folder".
276         if (!parentFolder.equals("")) {
277             // Get the database ID of the parent folder.
278             int parentFolderDatabaseId = bookmarksDatabaseHelper.getFolderDatabaseId(folderCursor.getString(folderCursor.getColumnIndex(BookmarksDatabaseHelper.PARENT_FOLDER)));
279
280             // Initialize `parentFolderPosition` and the iteration variable.
281             int parentFolderPosition = 0;
282             int i = 0;
283
284             // Find the parent folder position in folders `ResourceCursorAdapter`.
285             do {
286                 if (foldersCursorAdapter.getItemId(i) == parentFolderDatabaseId) {
287                     // Store the current position for the parent folder.
288                     parentFolderPosition = i;
289                 } else {
290                     // Try the next entry.
291                     i++;
292                 }
293                 // Stop when the parent folder position is found or all the items in the `ResourceCursorAdapter` have been checked.
294             } while ((parentFolderPosition == 0) && (i < foldersCursorAdapter.getCount()));
295
296             // Select the parent folder in the `Spinner`.
297             folderSpinner.setSelection(parentFolderPosition);
298         }
299
300         // Store the current folder database ID.
301         int currentParentFolderDatabaseId = (int) folderSpinner.getSelectedItemId();
302
303         // Populate the display order `EditText`.
304         displayOrderEditText.setText(String.valueOf(folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER))));
305
306         // Initially disable the edit button.
307         editButton.setEnabled(false);
308
309         // Update the edit button if the icon selection changes.
310         iconRadioGroup.setOnCheckedChangeListener((group, checkedId) -> {
311             // Update the edit button.
312             updateEditButton(alertDialog, bookmarksDatabaseHelper, currentFolderName, currentParentFolderDatabaseId, currentDisplayOrder);
313         });
314
315         // Update the edit button if the bookmark name changes.
316         nameEditText.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(alertDialog, bookmarksDatabaseHelper, currentFolderName, currentParentFolderDatabaseId, currentDisplayOrder);
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(alertDialog, bookmarksDatabaseHelper, currentFolderName, currentParentFolderDatabaseId, currentDisplayOrder);
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(alertDialog, bookmarksDatabaseHelper, currentFolderName, currentParentFolderDatabaseId, currentDisplayOrder);
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                 editBookmarkFolderDatabaseViewListener.onSaveBookmarkFolder(this, folderDatabaseId, favoriteIconBitmap);
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 display order `EditText`.
385         displayOrderEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
386             // Save the bookmark if the event is a key-down on the "enter" button.
387             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) {  // The enter key was pressed and the edit button is enabled.
388                 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
389                 editBookmarkFolderDatabaseViewListener.onSaveBookmarkFolder(this, folderDatabaseId, favoriteIconBitmap);
390
391                 // Manually dismiss the `AlertDialog`.
392                 alertDialog.dismiss();
393
394                 // Consume the event.
395                 return true;
396             } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
397                 return false;
398             }
399         });
400
401         // `onCreateDialog` requires the return of an `AlertDialog`.
402         return alertDialog;
403     }
404
405     private void updateEditButton(AlertDialog alertDialog, BookmarksDatabaseHelper bookmarksDatabaseHelper, String currentFolderName, int currentParentFolderDatabaseId, int currentDisplayOrder) {
406         // Get handles for the views.
407         EditText nameEditText = alertDialog.findViewById(R.id.edit_folder_name_edittext);
408         Spinner folderSpinner = alertDialog.findViewById(R.id.edit_folder_parent_folder_spinner);
409         EditText displayOrderEditText = alertDialog.findViewById(R.id.edit_folder_display_order_edittext);
410         RadioButton currentIconRadioButton = alertDialog.findViewById(R.id.edit_folder_current_icon_radiobutton);
411         Button editButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
412
413         // Get the values from the dialog.
414         String newFolderName = nameEditText.getText().toString();
415         int newParentFolderDatabaseId = (int) folderSpinner.getSelectedItemId();
416         String newDisplayOrder = displayOrderEditText.getText().toString();
417
418         // Get a cursor for the new folder name if it exists.
419         Cursor folderExistsCursor = bookmarksDatabaseHelper.getFolder(newFolderName);
420
421         // Is the new folder name empty?
422         boolean folderNameNotEmpty = !newFolderName.isEmpty();
423
424         // Does the folder name already exist?
425         boolean folderNameAlreadyExists = (!newFolderName.equals(currentFolderName) && (folderExistsCursor.getCount() > 0));
426
427         // Has the favorite icon changed?
428         boolean iconChanged = !currentIconRadioButton.isChecked();
429
430         // Has the name been renamed?
431         boolean folderRenamed = (!newFolderName.equals(currentFolderName) && !folderNameAlreadyExists);
432
433         // Has the folder changed?
434         boolean parentFolderChanged = newParentFolderDatabaseId != currentParentFolderDatabaseId;
435
436         // Has the display order changed?
437         boolean displayOrderChanged = !newDisplayOrder.equals(String.valueOf(currentDisplayOrder));
438
439         // Is the display order empty?
440         boolean displayOrderNotEmpty = !newDisplayOrder.isEmpty();
441
442         // Update the enabled status of the edit button.
443         editButton.setEnabled((iconChanged || folderRenamed || parentFolderChanged || displayOrderChanged) && folderNameNotEmpty && displayOrderNotEmpty);
444     }
445
446     private String getStringOfSubfolders(String folderName, BookmarksDatabaseHelper bookmarksDatabaseHelper) {
447         // Get a cursor will all the immediate subfolders.
448         Cursor subfoldersCursor = bookmarksDatabaseHelper.getSubfolders(folderName);
449
450         // Initialize a string builder to track the folders not to display in the spinner and populate it with the current folder.
451         StringBuilder exceptFoldersStringBuilder = new StringBuilder(DatabaseUtils.sqlEscapeString(folderName));
452
453         for (int i = 0; i < subfoldersCursor.getCount(); i++) {
454             // Move the subfolder cursor to the current item.
455             subfoldersCursor.moveToPosition(i);
456
457             // Get the name of the subfolder.
458             String subfolderName = subfoldersCursor.getString(subfoldersCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
459
460             // Add a comma to the end of the existing string.
461             exceptFoldersStringBuilder.append(",");
462
463             // Get the folder name and run the task for any subfolders.
464             String subfolderString = getStringOfSubfolders(subfolderName, bookmarksDatabaseHelper);
465
466             // Add the folder name to the string builder.
467             exceptFoldersStringBuilder.append(subfolderString);
468         }
469
470         // Return the string of folders.
471         return exceptFoldersStringBuilder.toString();
472     }
473 }