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