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