]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/EditBookmarkFolderDialog.java
216f0d3833d256a00442086e09e10aab2c1224a2
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / EditBookmarkFolderDialog.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.graphics.Bitmap;
29 import android.graphics.BitmapFactory;
30 import android.os.Bundle;
31 import android.preference.PreferenceManager;
32 import android.text.Editable;
33 import android.text.TextWatcher;
34 import android.view.KeyEvent;
35 import android.view.View;
36 import android.view.WindowManager;
37 import android.widget.Button;
38 import android.widget.EditText;
39 import android.widget.ImageView;
40 import android.widget.RadioButton;
41 import android.widget.RadioGroup;
42
43 import androidx.annotation.NonNull;
44 import androidx.appcompat.app.AlertDialog;
45 import androidx.fragment.app.DialogFragment;  // The AndroidX dialog fragment must be used or an error is produced on API <=22.
46
47 import com.stoutner.privacybrowser.R;
48 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
49
50 import java.io.ByteArrayOutputStream;
51
52 public class EditBookmarkFolderDialog extends DialogFragment {
53     // Instantiate the class variable.
54     private EditBookmarkFolderListener editBookmarkFolderListener;
55
56     // The public interface is used to send information back to the parent activity.
57     public interface EditBookmarkFolderListener {
58         void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap);
59     }
60
61     public void onAttach(@NonNull Context context) {
62         // Run the default commands.
63         super.onAttach(context);
64
65         // Get a handle for `EditFolderListener` from the launching context.
66         editBookmarkFolderListener = (EditBookmarkFolderListener) context;
67     }
68
69     // Store the database ID in the arguments bundle.
70     public static EditBookmarkFolderDialog folderDatabaseId(int databaseId, Bitmap favoriteIconBitmap) {
71         // Create a favorite icon byte array output stream.
72         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
73
74         // 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).
75         favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
76
77         // Convert the byte array output stream to a byte array.
78         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
79
80         // Create an arguments bundle
81         Bundle argumentsBundle = new Bundle();
82
83         // Store the variables in the bundle.
84         argumentsBundle.putInt("database_id", databaseId);
85         argumentsBundle.putByteArray("favorite_icon_byte_array", favoriteIconByteArray);
86
87         // Create a new instance of the dialog.
88         EditBookmarkFolderDialog editBookmarkFolderDialog = new EditBookmarkFolderDialog();
89
90         // Add the arguments bundle to the dialog.
91         editBookmarkFolderDialog.setArguments(argumentsBundle);
92
93         // Return the new dialog.
94         return editBookmarkFolderDialog;
95     }
96
97     // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
98     @SuppressLint("InflateParams")
99     @Override
100     @NonNull
101     public Dialog onCreateDialog(Bundle savedInstanceState) {
102         // Get the arguments.
103         Bundle arguments = getArguments();
104
105         // Remove the incorrect lint warning below that the arguments might be null.
106         assert arguments != null;
107
108         // Store the folder database ID in the class variable.
109         int selectedFolderDatabaseId = arguments.getInt("database_id");
110
111         // Get the favorite icon byte array.
112         byte[] favoriteIconByteArray = arguments.getByteArray("favorite_icon_byte_array");
113
114         // Remove the incorrect lint warning below that the favorite icon byte array might be null.
115         assert favoriteIconByteArray != null;
116
117         // Convert the favorite icon byte array to a bitmap.
118         Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
119
120         // Initialize the database helper.  The two `nulls` do not specify the database name or a `CursorFactory`.  The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
121         BookmarksDatabaseHelper bookmarksDatabaseHelper = new BookmarksDatabaseHelper(getContext(), null, null, 0);
122
123         // Get a cursor with the selected folder and move it to the first position.
124         Cursor folderCursor = bookmarksDatabaseHelper.getBookmark(selectedFolderDatabaseId);
125         folderCursor.moveToFirst();
126
127         // Use an alert dialog builder to create the alert dialog.
128         AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(requireContext(), R.style.PrivacyBrowserAlertDialog);
129
130         // Set the title.
131         dialogBuilder.setTitle(R.string.edit_folder);
132
133         // Remove the incorrect lint warning that `getActivity()` might be null.
134         assert getActivity() != null;
135
136         // Set the view.  The parent view is `null` because it will be assigned by `AlertDialog`.
137         dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.edit_bookmark_folder_dialog, null));
138
139         // Set the listener for the negative button.
140         dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
141             // Do nothing.  The `AlertDialog` will close automatically.
142         });
143
144         // Set the listener fo the positive button.
145         dialogBuilder.setPositiveButton(R.string.save, (DialogInterface dialog, int which) -> {
146             // Return the `DialogFragment` to the parent activity on save.
147             editBookmarkFolderListener.onSaveBookmarkFolder(this, selectedFolderDatabaseId, favoriteIconBitmap);
148         });
149
150         // Create an alert dialog from the alert dialog builder.
151         AlertDialog alertDialog = dialogBuilder.create();
152
153         // Remove the warning below that `getWindow()` might be null.
154         assert alertDialog.getWindow() != null;
155
156         // Get a handle for the shared preferences.
157         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
158
159         // Get the screenshot preference.
160         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
161
162         // Disable screenshots if not allowed.
163         if (!allowScreenshots) {
164             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
165         }
166
167         // The alert dialog must be shown before items in the layout can be modified.
168         alertDialog.show();
169
170         // Get handles for the views in the alert dialog.
171         RadioGroup iconRadioGroup = alertDialog.findViewById(R.id.edit_folder_icon_radio_group);
172         RadioButton currentIconRadioButton = alertDialog.findViewById(R.id.edit_folder_current_icon_radiobutton);
173         ImageView currentIconImageView = alertDialog.findViewById(R.id.edit_folder_current_icon_imageview);
174         ImageView webPageFavoriteIconImageView = alertDialog.findViewById(R.id.edit_folder_web_page_favorite_icon_imageview);
175         EditText folderNameEditText = alertDialog.findViewById(R.id.edit_folder_name_edittext);
176         Button editButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
177
178         // Remove the incorrect lint warnings below that the views might be null.
179         assert iconRadioGroup != null;
180         assert currentIconRadioButton != null;
181         assert currentIconImageView != null;
182         assert webPageFavoriteIconImageView != null;
183         assert folderNameEditText != null;
184
185         // Initially disable the edit button.
186         editButton.setEnabled(false);
187
188         // Get the current favorite icon byte array from the Cursor.
189         byte[] currentIconByteArray = folderCursor.getBlob(folderCursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
190
191         // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
192         Bitmap currentIconBitmap = BitmapFactory.decodeByteArray(currentIconByteArray, 0, currentIconByteArray.length);
193
194         // Display the current icon bitmap.
195         currentIconImageView.setImageBitmap(currentIconBitmap);
196
197         // Set the new favorite icon bitmap.
198         webPageFavoriteIconImageView.setImageBitmap(favoriteIconBitmap);
199
200         // Get the current folder name.
201         String currentFolderName = folderCursor.getString(folderCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
202
203         // Display the current folder name in `edit_folder_name_edittext`.
204         folderNameEditText.setText(currentFolderName);
205
206         // Update the status of the edit button when the folder name is changed.
207         folderNameEditText.addTextChangedListener(new TextWatcher() {
208             @Override
209             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
210                 // Do nothing.
211             }
212
213             @Override
214             public void onTextChanged(CharSequence s, int start, int before, int count) {
215                 // Do nothing.
216             }
217
218             @Override
219             public void afterTextChanged(Editable s) {
220                 // Convert the current text to a string.
221                 String newFolderName = s.toString();
222
223                 // Get a cursor for the new folder name if it exists.
224                 Cursor folderExistsCursor = bookmarksDatabaseHelper.getFolder(newFolderName);
225
226                 // Is the new folder name empty?
227                 boolean folderNameNotEmpty = !newFolderName.isEmpty();
228
229                 // Does the folder name already exist?
230                 boolean folderNameAlreadyExists = (!newFolderName.equals(currentFolderName) && (folderExistsCursor.getCount() > 0));
231
232                 // Has the folder been renamed?
233                 boolean folderRenamed = (!newFolderName.equals(currentFolderName) && !folderNameAlreadyExists);
234
235                 // Has the favorite icon changed?
236                 boolean iconChanged = (!currentIconRadioButton.isChecked() && !folderNameAlreadyExists);
237
238                 // Enable the create button if something has been edited and the new folder name is valid.
239                 editButton.setEnabled(folderNameNotEmpty && (folderRenamed || iconChanged));
240             }
241         });
242
243         // Update the status of the edit button when the icon is changed.
244         iconRadioGroup.setOnCheckedChangeListener((RadioGroup group, int checkedId) -> {
245             // Get the new folder name.
246             String newFolderName = folderNameEditText.getText().toString();
247
248             // Get a cursor for the new folder name if it exists.
249             Cursor folderExistsCursor = bookmarksDatabaseHelper.getFolder(newFolderName);
250
251             // Is the new folder name empty?
252             boolean folderNameEmpty = newFolderName.isEmpty();
253
254             // Does the folder name already exist?
255             boolean folderNameAlreadyExists = (!newFolderName.equals(currentFolderName) && (folderExistsCursor.getCount() > 0));
256
257             // Has the folder been renamed?
258             boolean folderRenamed = (!newFolderName.equals(currentFolderName) && !folderNameAlreadyExists);
259
260             // Has the favorite icon changed?
261             boolean iconChanged = (!currentIconRadioButton.isChecked() && !folderNameAlreadyExists);
262
263             // Enable the create button if something has been edited and the new folder name is valid.
264             editButton.setEnabled(!folderNameEmpty && (folderRenamed || iconChanged));
265         });
266
267         // Allow the `enter` key on the keyboard to save the bookmark from `edit_bookmark_name_edittext`.
268         folderNameEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
269             // If the event is a key-down on the "enter" button, select the PositiveButton `Save`.
270             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) {  // The enter key was pressed and the edit button is enabled.
271                 // Trigger `editBookmarkListener` and return the DialogFragment to the parent activity.
272                 editBookmarkFolderListener.onSaveBookmarkFolder(this, selectedFolderDatabaseId, favoriteIconBitmap);
273
274                 // Manually dismiss the `AlertDialog`.
275                 alertDialog.dismiss();
276
277                 // Consume the event.
278                 return true;
279             } else {  // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
280                 return false;
281             }
282         });
283
284         // `onCreateDialog` requires the return of an `AlertDialog`.
285         return alertDialog;
286     }
287 }