]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/EditBookmarkFolderDatabaseViewDialog.java
af26e0b9170dcb162d79d73c9f34171b5a9242c5
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / EditBookmarkFolderDatabaseViewDialog.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.database.DatabaseUtils;
29 import android.database.MatrixCursor;
30 import android.database.MergeCursor;
31 import android.graphics.Bitmap;
32 import android.graphics.BitmapFactory;
33 import android.os.Bundle;
34 import android.support.annotation.NonNull;
35 import android.support.v4.widget.ResourceCursorAdapter;
36 // `AppCompatDialogFragment` is required instead of `DialogFragment` or an error is produced on API <=22.
37 import android.support.v7.app.AppCompatDialogFragment;
38 import android.text.Editable;
39 import android.text.TextWatcher;
40 import android.view.KeyEvent;
41 import android.view.View;
42 import android.view.WindowManager;
43 import android.widget.AdapterView;
44 import android.widget.Button;
45 import android.widget.EditText;
46 import android.widget.ImageView;
47 import android.widget.RadioButton;
48 import android.widget.RadioGroup;
49 import android.widget.Spinner;
50 import android.widget.TextView;
51
52 import com.stoutner.privacybrowser.R;
53 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
54 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
55
56 public class EditBookmarkFolderDatabaseViewDialog extends AppCompatDialogFragment {
57     // Instantiate the constants.
58     public static final int HOME_FOLDER_DATABASE_ID = -1;
59
60     // Instantiate the class variables.
61     private EditBookmarkFolderDatabaseViewListener editBookmarkFolderDatabaseViewListener;
62     private BookmarksDatabaseHelper bookmarksDatabaseHelper;
63     private int folderDatabaseId;
64     private StringBuilder exceptFolders;
65     private String currentFolderName;
66     private int currentParentFolderDatabaseId;
67     private String currentDisplayOrder;
68     private RadioButton currentIconRadioButton;
69     private EditText nameEditText;
70     private Spinner folderSpinner;
71     private EditText displayOrderEditText;
72     private Button editButton;
73
74     // The public interface is used to send information back to the parent activity.
75     public interface EditBookmarkFolderDatabaseViewListener {
76         void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId);
77     }
78
79     public void onAttach(Context context) {
80         // Run the default commands.
81         super.onAttach(context);
82
83         // Get a handle for `EditBookmarkDatabaseViewListener` from `context`.
84         try {
85             editBookmarkFolderDatabaseViewListener = (EditBookmarkFolderDatabaseViewListener) context;
86         } catch(ClassCastException exception) {
87             throw new ClassCastException(context.toString() + " must implement EditBookmarkFolderDatabaseViewListener.");
88         }
89     }
90
91     // Store the database ID in the arguments bundle.
92     public static EditBookmarkFolderDatabaseViewDialog folderDatabaseId(int databaseId) {
93         // Create a bundle.
94         Bundle bundle = new Bundle();
95
96         // Store the bookmark database ID in the bundle.
97         bundle.putInt("Database ID", databaseId);
98
99         // Add the bundle to the dialog.
100         EditBookmarkFolderDatabaseViewDialog editBookmarkFolderDatabaseViewDialog = new EditBookmarkFolderDatabaseViewDialog();
101         editBookmarkFolderDatabaseViewDialog.setArguments(bundle);
102
103         // Return the new dialog.
104         return editBookmarkFolderDatabaseViewDialog;
105     }
106
107     @Override
108     public void onCreate(Bundle savedInstanceState) {
109         // Run the default commands.
110         super.onCreate(savedInstanceState);
111
112         // Remove the incorrect lint warning that `getInt()` might be null.
113         assert getArguments() != null;
114
115         // Store the bookmark database ID in the class variable.
116         folderDatabaseId = getArguments().getInt("Database ID");
117     }
118
119     // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
120     @SuppressLint("InflateParams")
121     @Override
122     @NonNull
123     public Dialog onCreateDialog(Bundle savedInstanceState) {
124         // 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`.
125         bookmarksDatabaseHelper = new BookmarksDatabaseHelper(getContext(), null, null, 0);
126
127         // Get a `Cursor` with the selected bookmark and move it to the first position.
128         Cursor folderCursor = bookmarksDatabaseHelper.getBookmarkCursor(folderDatabaseId);
129         folderCursor.moveToFirst();
130
131         // Use an alert dialog builder to create the alert dialog.
132         AlertDialog.Builder dialogBuilder;
133
134         // Set the style according to the theme.
135         if (MainWebViewActivity.darkTheme) {
136             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
137         } else {
138             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
139         }
140
141         // Set the title.
142         dialogBuilder.setTitle(R.string.edit_folder);
143
144         // Remove the incorrect lint warning that `getActivity()` might be null.
145         assert getActivity() != null;
146
147         // Set the view.  The parent view is `null` because it will be assigned by `AlertDialog`.
148         dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.edit_bookmark_folder_databaseview_dialog, null));
149
150         // Set the listener for the negative button.
151         dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
152             // Do nothing.  The `AlertDialog` will close automatically.
153         });
154
155         // Set the listener fo the positive button.
156         dialogBuilder.setPositiveButton(R.string.save, (DialogInterface dialog, int which) -> {
157             // Return the `DialogFragment` to the parent activity on save.
158             editBookmarkFolderDatabaseViewListener.onSaveBookmarkFolder(EditBookmarkFolderDatabaseViewDialog.this, folderDatabaseId);
159         });
160
161         // Create an alert dialog from the alert dialog builder.
162         final AlertDialog alertDialog = dialogBuilder.create();
163
164         // Remove the warning below that `getWindow()` might be null.
165         assert alertDialog.getWindow() != null;
166
167         // Disable screenshots if not allowed.
168         if (!MainWebViewActivity.allowScreenshots) {
169             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
170         }
171
172         // Set the keyboard to be hidden when the `AlertDialog` is first shown.  If this is not set, the `AlertDialog` will not shrink when the keyboard is displayed.
173         alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
174
175         // The alert dialog must be shown before items in the layout can be modified.
176         alertDialog.show();
177
178         // Get handles for the layout items.
179         TextView databaseIdTextView = alertDialog.findViewById(R.id.edit_folder_database_id_textview);
180         RadioGroup iconRadioGroup = alertDialog.findViewById(R.id.edit_folder_icon_radiogroup);
181         ImageView currentIconImageView = alertDialog.findViewById(R.id.edit_folder_current_icon_imageview);
182         ImageView newFavoriteIconImageView = alertDialog.findViewById(R.id.edit_folder_webpage_favorite_icon_imageview);
183         currentIconRadioButton = alertDialog.findViewById(R.id.edit_folder_current_icon_radiobutton);
184         nameEditText = alertDialog.findViewById(R.id.edit_folder_name_edittext);
185         folderSpinner = alertDialog.findViewById(R.id.edit_folder_parent_folder_spinner);
186         displayOrderEditText = alertDialog.findViewById(R.id.edit_folder_display_order_edittext);
187         editButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
188
189         // Store the current folder values.
190         currentFolderName = folderCursor.getString(folderCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
191         currentDisplayOrder = folderCursor.getString(folderCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER));
192         String parentFolder = folderCursor.getString(folderCursor.getColumnIndex(BookmarksDatabaseHelper.PARENT_FOLDER));
193
194         // Set the database ID.
195         databaseIdTextView.setText(String.valueOf(folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID))));
196
197         // Get the current favorite icon byte array from the `Cursor`.
198         byte[] currentIconByteArray = folderCursor.getBlob(folderCursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
199
200         // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
201         Bitmap currentIconBitmap = BitmapFactory.decodeByteArray(currentIconByteArray, 0, currentIconByteArray.length);
202
203         // Display `currentIconBitmap` in `edit_bookmark_current_icon`.
204         currentIconImageView.setImageBitmap(currentIconBitmap);
205
206         // Get a `Bitmap` of the favorite icon from `MainWebViewActivity` and display it in `edit_bookmark_web_page_favorite_icon`.
207         newFavoriteIconImageView.setImageBitmap(MainWebViewActivity.favoriteIconBitmap);
208
209         // Populate the folder name `EditText`.
210         nameEditText.setText(currentFolderName);
211
212         // Setup a `MatrixCursor` "Home Folder".
213         String[] matrixCursorColumnNames = {BookmarksDatabaseHelper._ID, BookmarksDatabaseHelper.BOOKMARK_NAME};
214         MatrixCursor matrixCursor = new MatrixCursor(matrixCursorColumnNames);
215         matrixCursor.addRow(new Object[]{HOME_FOLDER_DATABASE_ID, getString(R.string.home_folder)});
216
217         // Initialize a `StringBuilder` to track the folders not to display in the `Spinner` and populate it with the current folder.
218         exceptFolders = new StringBuilder(DatabaseUtils.sqlEscapeString(currentFolderName));
219
220         // Add all subfolders of the current folder to the list of folders not to display.
221         addSubfoldersToExceptFolders(currentFolderName);
222
223         // Get a `Cursor` with the list of all the folders.
224         Cursor foldersCursor = bookmarksDatabaseHelper.getFoldersCursorExcept(exceptFolders.toString());
225
226         // Combine `matrixCursor` and `foldersCursor`.
227         MergeCursor foldersMergeCursor = new MergeCursor(new Cursor[]{matrixCursor, foldersCursor});
228
229         // Remove the incorrect lint warning that `getContext()` might be null.
230         assert getContext() != null;
231
232         // Create a `ResourceCursorAdapter` for the `Spinner`.  `0` specifies no flags.;
233         ResourceCursorAdapter foldersCursorAdapter = new ResourceCursorAdapter(getContext(), R.layout.edit_bookmark_databaseview_spinner_item, foldersMergeCursor, 0) {
234             @Override
235             public void bindView(View view, Context context, Cursor cursor) {
236                 // Get a handle for the `Spinner` item `TextView`.
237                 TextView spinnerItemTextView = view.findViewById(R.id.spinner_item_textview);
238
239                 // Set the `TextView` to display the folder name.
240                 spinnerItemTextView.setText(cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME)));
241             }
242         };
243
244         // Set the `ResourceCursorAdapter` drop drown view resource.
245         foldersCursorAdapter.setDropDownViewResource(R.layout.edit_bookmark_databaseview_spinner_dropdown_item);
246
247         // Set the adapter for the folder `Spinner`.
248         folderSpinner.setAdapter(foldersCursorAdapter);
249
250         // Select the current folder in the `Spinner` if the bookmark isn't in the "Home Folder".
251         if (!parentFolder.equals("")) {
252             // Get the database ID of the parent folder.
253             int folderDatabaseId = bookmarksDatabaseHelper.getFolderDatabaseId(folderCursor.getString(folderCursor.getColumnIndex(BookmarksDatabaseHelper.PARENT_FOLDER)));
254
255             // Initialize `parentFolderPosition` and the iteration variable.
256             int parentFolderPosition = 0;
257             int i = 0;
258
259             // Find the parent folder position in folders `ResourceCursorAdapter`.
260             do {
261                 if (foldersCursorAdapter.getItemId(i) == folderDatabaseId) {
262                     // Store the current position for the parent folder.
263                     parentFolderPosition = i;
264                 } else {
265                     // Try the next entry.
266                     i++;
267                 }
268                 // Stop when the parent folder position is found or all the items in the `ResourceCursorAdapter` have been checked.
269             } while ((parentFolderPosition == 0) && (i < foldersCursorAdapter.getCount()));
270
271             // Select the parent folder in the `Spinner`.
272             folderSpinner.setSelection(parentFolderPosition);
273         }
274
275         // Store the current folder database ID.
276         currentParentFolderDatabaseId = (int) folderSpinner.getSelectedItemId();
277
278         // Populate the display order `EditText`.
279         displayOrderEditText.setText(String.valueOf(folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER))));
280
281         // Initially disable the edit button.
282         editButton.setEnabled(false);
283
284         // Update the edit button if the icon selection changes.
285         iconRadioGroup.setOnCheckedChangeListener((group, checkedId) -> {
286             // Update the edit button.
287             updateEditButton();
288         });
289
290         // Update the edit button if the bookmark name changes.
291         nameEditText.addTextChangedListener(new TextWatcher() {
292             @Override
293             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
294                 // Do nothing.
295             }
296
297             @Override
298             public void onTextChanged(CharSequence s, int start, int before, int count) {
299                 // Do nothing.
300             }
301
302             @Override
303             public void afterTextChanged(Editable s) {
304                 // Update the edit button.
305                 updateEditButton();
306             }
307         });
308
309         // Update the edit button if the folder changes.
310         folderSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
311             @Override
312             public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
313                 // Update the edit button.
314                 updateEditButton();
315             }
316
317             @Override
318             public void onNothingSelected(AdapterView<?> parent) {
319
320             }
321         });
322
323         // Update the edit button if the display order changes.
324         displayOrderEditText.addTextChangedListener(new TextWatcher() {
325             @Override
326             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
327                 // Do nothing.
328             }
329
330             @Override
331             public void onTextChanged(CharSequence s, int start, int before, int count) {
332                 // Do nothing.
333             }
334
335             @Override
336             public void afterTextChanged(Editable s) {
337                 // Update the edit button.
338                 updateEditButton();
339             }
340         });
341
342         // Allow the `enter` key on the keyboard to save the bookmark from the bookmark name `EditText`.
343         nameEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
344             // Save the bookmark if the event is a key-down on the "enter" button.
345             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) {  // The enter key was pressed and the edit button is enabled.
346                 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
347                 editBookmarkFolderDatabaseViewListener.onSaveBookmarkFolder(EditBookmarkFolderDatabaseViewDialog.this, folderDatabaseId);
348
349                 // Manually dismiss `alertDialog`.
350                 alertDialog.dismiss();
351
352                 // Consume the event.
353                 return true;
354             } else {  // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
355                 return false;
356             }
357         });
358
359         // Allow the "enter" key on the keyboard to save the bookmark from the display order `EditText`.
360         displayOrderEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
361             // Save the bookmark if the event is a key-down on the "enter" button.
362             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && editButton.isEnabled()) {  // The enter key was pressed and the edit button is enabled.
363                 // Trigger the `Listener` and return the `DialogFragment` to the parent activity.
364                 editBookmarkFolderDatabaseViewListener.onSaveBookmarkFolder(EditBookmarkFolderDatabaseViewDialog.this, folderDatabaseId);
365
366                 // Manually dismiss the `AlertDialog`.
367                 alertDialog.dismiss();
368
369                 // Consume the event.
370                 return true;
371             } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
372                 return false;
373             }
374         });
375
376         // `onCreateDialog` requires the return of an `AlertDialog`.
377         return alertDialog;
378     }
379
380     private void updateEditButton() {
381         // Get the values from the dialog.
382         String newFolderName = nameEditText.getText().toString();
383         int newParentFolderDatabaseId = (int) folderSpinner.getSelectedItemId();
384         String newDisplayOrder = displayOrderEditText.getText().toString();
385
386         // Get a cursor for the new folder name if it exists.
387         Cursor folderExistsCursor = bookmarksDatabaseHelper.getFolderCursor(newFolderName);
388
389         // Is the new folder name empty?
390         boolean folderNameNotEmpty = !newFolderName.isEmpty();
391
392         // Does the folder name already exist?
393         boolean folderNameAlreadyExists = (!newFolderName.equals(currentFolderName) && (folderExistsCursor.getCount() > 0));
394
395         // Has the favorite icon changed?
396         boolean iconChanged = !currentIconRadioButton.isChecked();
397
398         // Has the name been renamed?
399         boolean folderRenamed = (!newFolderName.equals(currentFolderName) && !folderNameAlreadyExists);
400
401         // Has the folder changed?
402         boolean parentFolderChanged = newParentFolderDatabaseId != currentParentFolderDatabaseId;
403
404         // Has the display order changed?
405         boolean displayOrderChanged = !newDisplayOrder.equals(currentDisplayOrder);
406
407         // Is the display order empty?
408         boolean displayOrderNotEmpty = !newDisplayOrder.isEmpty();
409
410         // Update the enabled status of the edit button.
411         editButton.setEnabled((iconChanged || folderRenamed || parentFolderChanged || displayOrderChanged) && folderNameNotEmpty && displayOrderNotEmpty);
412     }
413
414     private void addSubfoldersToExceptFolders(String folderName) {
415         // Get a `Cursor` will all the immediate subfolders.
416         Cursor subfoldersCursor = bookmarksDatabaseHelper.getSubfoldersCursor(folderName);
417
418         for (int i = 0; i < subfoldersCursor.getCount(); i++) {
419             // Move `subfolderCursor` to the current item.
420             subfoldersCursor.moveToPosition(i);
421
422             // Get the name of the subfolder.
423             String subfolderName = subfoldersCursor.getString(subfoldersCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
424
425             // Add the subfolder to `exceptFolders`.
426             exceptFolders.append(",");
427             exceptFolders.append(DatabaseUtils.sqlEscapeString(subfolderName));
428
429             // Run the same tasks for any subfolders of the subfolder.
430             addSubfoldersToExceptFolders(subfolderName);
431         }
432     }
433 }