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