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