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