]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/EditBookmarkFolderDialog.java
Finish creating the bookmark drawer. https://redmine.stoutner.com/issues/132
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / EditBookmarkFolderDialog.java
1 /*
2  * Copyright © 2016-2017 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.support.annotation.IdRes;
32 import android.support.annotation.NonNull;
33 // `AppCompatDialogFragment` is required instead of `DialogFragment` or an error is produced on API <=22.
34 import android.support.v7.app.AppCompatDialogFragment;
35 import android.text.Editable;
36 import android.text.TextWatcher;
37 import android.view.KeyEvent;
38 import android.view.View;
39 import android.view.WindowManager;
40 import android.widget.Button;
41 import android.widget.EditText;
42 import android.widget.ImageView;
43 import android.widget.RadioButton;
44 import android.widget.RadioGroup;
45
46 import com.stoutner.privacybrowser.R;
47 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
48 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
49
50 public class EditBookmarkFolderDialog extends AppCompatDialogFragment {
51     // The public interface is used to send information back to the parent activity.
52     public interface EditBookmarkFolderListener {
53         void onSaveEditBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId);
54     }
55
56     // Instantiate the class variables.
57     private EditBookmarkFolderListener editBookmarkFolderListener;
58     private int selectedFolderDatabaseId;
59
60     public void onAttach(Context context) {
61         // Run the default commands.
62         super.onAttach(context);
63
64         // Get a handle for `EditFolderListener` from `parentActivity`.
65         try {
66             editBookmarkFolderListener = (EditBookmarkFolderListener) context;
67         } catch(ClassCastException exception) {
68             throw new ClassCastException(context.toString() + " must implement EditBookmarkFolderListener.");
69         }
70     }
71
72     // Store the database ID in the arguments bundle.
73     public static EditBookmarkFolderDialog folderDatabaseId(int databaseId) {
74         // Create a bundle
75         Bundle bundle = new Bundle();
76
77         // Store the folder database ID in the bundle.
78         bundle.putInt("Database ID", databaseId);
79
80         // Add the bundle to the dialog.
81         EditBookmarkFolderDialog editBookmarkFolderDialog = new EditBookmarkFolderDialog();
82         editBookmarkFolderDialog.setArguments(bundle);
83
84         // Return the new dialog.
85         return editBookmarkFolderDialog;
86     }
87
88     @Override
89     public void onCreate(Bundle savedInstanceState) {
90         // Run the default commands.
91         super.onCreate(savedInstanceState);
92
93         // Store the folder database ID in the class variable.
94         selectedFolderDatabaseId = getArguments().getInt("Database ID");
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         // 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`.
103         final BookmarksDatabaseHelper bookmarksDatabaseHelper = new BookmarksDatabaseHelper(getContext(), null, null, 0);
104
105         // Get a `Cursor` with the selected folder and move it to the first position.
106         Cursor folderCursor = bookmarksDatabaseHelper.getBookmarkCursor(selectedFolderDatabaseId);
107         folderCursor.moveToFirst();
108
109         // Use `AlertDialog.Builder` to create the `AlertDialog`.
110         AlertDialog.Builder dialogBuilder;
111
112         // Set the style according to the theme.
113         if (MainWebViewActivity.darkTheme) {
114             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
115         } else {
116             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
117         }
118
119         // Set the title.
120         dialogBuilder.setTitle(R.string.edit_folder);
121
122         // Set the view.  The parent view is `null` because it will be assigned by `AlertDialog`.
123         dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.edit_bookmark_folder_dialog, null));
124
125         // Set an `onClick()` listener for the negative button.
126         dialogBuilder.setNegativeButton(R.string.cancel, new Dialog.OnClickListener() {
127             @Override
128             public void onClick(DialogInterface dialog, int which) {
129                 // Do nothing.  The `AlertDialog` will close automatically.
130             }
131         });
132
133         // Set the `onClick()` listener fo the positive button.
134         dialogBuilder.setPositiveButton(R.string.save, new Dialog.OnClickListener() {
135             @Override
136             public void onClick(DialogInterface dialog, int which) {
137                 // Return the `DialogFragment` to the parent activity on save.
138                 editBookmarkFolderListener.onSaveEditBookmarkFolder(EditBookmarkFolderDialog.this, selectedFolderDatabaseId);
139             }
140         });
141
142         // Create an `AlertDialog` from the `AlertDialog.Builder`.
143         final AlertDialog alertDialog = dialogBuilder.create();
144
145         // Remove the warning below that `setSoftInputMode` might produce `java.lang.NullPointerException`.
146         assert alertDialog.getWindow() != null;
147
148         // Show the keyboard when the `Dialog` is displayed on the screen.
149         alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
150
151         // The `AlertDialog` must be shown before items in the layout can be modified.
152         alertDialog.show();
153
154         // Get handles for layout items in the `AlertDialog`.
155         final Button editButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
156         final RadioButton currentIconRadioButton = (RadioButton) alertDialog.findViewById(R.id.edit_folder_current_icon_radiobutton);
157         RadioGroup iconRadioGroup = (RadioGroup) alertDialog.findViewById(R.id.edit_folder_icon_radio_group);
158
159         // Initially disable the edit button.
160         editButton.setEnabled(false);
161
162         // Get the current favorite icon byte array from the `Cursor`.
163         byte[] currentIconByteArray = folderCursor.getBlob(folderCursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
164         // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
165         Bitmap currentIconBitmap = BitmapFactory.decodeByteArray(currentIconByteArray, 0, currentIconByteArray.length);
166         // Display `currentIconBitmap` in `edit_folder_current_icon`.
167         ImageView currentIconImageView = (ImageView) alertDialog.findViewById(R.id.edit_folder_current_icon);
168         currentIconImageView.setImageBitmap(currentIconBitmap);
169
170         // Get a `Bitmap` of the favorite icon from `MainWebViewActivity` and display it in `edit_folder_web_page_favorite_icon`.
171         ImageView webPageFavoriteIconImageView = (ImageView) alertDialog.findViewById(R.id.edit_folder_web_page_favorite_icon);
172         webPageFavoriteIconImageView.setImageBitmap(MainWebViewActivity.favoriteIconBitmap);
173
174         // Get the current folder name.
175         final String currentFolderName = folderCursor.getString(folderCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
176
177         // Display the current folder name in `edit_folder_name_edittext`.
178         final EditText folderNameEditText = (EditText) alertDialog.findViewById(R.id.edit_folder_name_edittext);
179         folderNameEditText.setText(currentFolderName);
180
181         // Update the status of the edit button when the folder name is changed.
182         folderNameEditText.addTextChangedListener(new TextWatcher() {
183             @Override
184             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
185                 // Do nothing.
186             }
187
188             @Override
189             public void onTextChanged(CharSequence s, int start, int before, int count) {
190                 // Do nothing.
191             }
192
193             @Override
194             public void afterTextChanged(Editable s) {
195                 // Convert the current text to a string.
196                 String newFolderName = s.toString();
197
198                 // Get a cursor for the new folder name if it exists.
199                 Cursor folderExistsCursor = bookmarksDatabaseHelper.getFolderCursor(newFolderName);
200
201                 // Is the new folder name empty?
202                 boolean folderNameEmpty = newFolderName.isEmpty();
203
204                 // Does the folder name already exist?
205                 boolean folderNameAlreadyExists = (!newFolderName.equals(currentFolderName) && (folderExistsCursor.getCount() > 0));
206
207                 // Has the folder been renamed?
208                 boolean folderRenamed = (!newFolderName.equals(currentFolderName) && !folderNameAlreadyExists);
209
210                 // Has the favorite icon changed?
211                 boolean iconChanged = (!currentIconRadioButton.isChecked() && !folderNameAlreadyExists);
212
213                 // Enable the create button if something has been edited and the new folder name is valid.
214                 editButton.setEnabled(!folderNameEmpty && (folderRenamed || iconChanged));
215             }
216         });
217
218         // Update the status of the edit button when the icon is changed.
219         iconRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
220             @Override
221             public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
222                 // Get the new folder name.
223                 String newFolderName = folderNameEditText.getText().toString();
224
225                 // Get a cursor for the new folder name if it exists.
226                 Cursor folderExistsCursor = bookmarksDatabaseHelper.getFolderCursor(newFolderName);
227
228                 // Is the new folder name empty?
229                 boolean folderNameEmpty = newFolderName.isEmpty();
230
231                 // Does the folder name already exist?
232                 boolean folderNameAlreadyExists = (!newFolderName.equals(currentFolderName) && (folderExistsCursor.getCount() > 0));
233
234                 // Has the folder been renamed?
235                 boolean folderRenamed = (!newFolderName.equals(currentFolderName) && !folderNameAlreadyExists);
236
237                 // Has the favorite icon changed?
238                 boolean iconChanged = (!currentIconRadioButton.isChecked() && !folderNameAlreadyExists);
239
240                 // Enable the create button if something has been edited and the new folder name is valid.
241                 editButton.setEnabled(!folderNameEmpty && (folderRenamed || iconChanged));
242             }
243         });
244
245         // Allow the `enter` key on the keyboard to save the bookmark from `edit_bookmark_name_edittext`.
246         folderNameEditText.setOnKeyListener(new View.OnKeyListener() {
247             public boolean onKey(View v, int keyCode, KeyEvent event) {
248                 // If the event is a key-down on the "enter" button, select the PositiveButton `Save`.
249                 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) {  // The enter key was pressed and the edit button is enabled.
250                     // Trigger `editBookmarkListener` and return the DialogFragment to the parent activity.
251                     editBookmarkFolderListener.onSaveEditBookmarkFolder(EditBookmarkFolderDialog.this, selectedFolderDatabaseId);
252
253                     // Manually dismiss the `AlertDialog`.
254                     alertDialog.dismiss();
255
256                     // Consume the event.
257                     return true;
258                 } else {  // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
259                     return false;
260                 }
261             }
262         });
263
264         // `onCreateDialog` requires the return of an `AlertDialog`.
265         return alertDialog;
266     }
267 }