]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateBookmarkFolderDialog.java
Ghost the create folder dialog create button if the folder name already exists. ...
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / CreateBookmarkFolderDialog.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.os.Bundle;
29 import android.support.annotation.NonNull;
30 // We have to use `AppCompatDialogFragment` instead of `DialogFragment` or an error is produced on API <=22.
31 import android.support.v7.app.AppCompatDialogFragment;
32 import android.text.Editable;
33 import android.text.TextWatcher;
34 import android.view.KeyEvent;
35 import android.view.View;
36 import android.view.WindowManager;
37 import android.widget.Button;
38 import android.widget.EditText;
39 import android.widget.ImageView;
40
41 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
42 import com.stoutner.privacybrowser.R;
43 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
44
45 public class CreateBookmarkFolderDialog extends AppCompatDialogFragment {
46     // The public interface is used to send information back to the parent activity.
47     public interface CreateBookmarkFolderListener {
48         void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment);
49     }
50
51     // `createBookmarkFolderListener` is used in `onAttach()` and `onCreateDialog`.
52     private CreateBookmarkFolderListener createBookmarkFolderListener;
53
54     public void onAttach(Context context) {
55         super.onAttach(context);
56
57         // Get a handle for `createBookmarkFolderListener` from `context`.
58         try {
59             createBookmarkFolderListener = (CreateBookmarkFolderListener) context;
60         } catch(ClassCastException exception) {
61             throw new ClassCastException(context.toString() + " must implement CreateBookmarkFolderListener.");
62         }
63     }
64
65     // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
66     @SuppressLint("InflateParams")
67     @Override
68     @NonNull
69     public Dialog onCreateDialog(Bundle savedInstanceState) {
70         // Use `AlertDialog.Builder` to create the `AlertDialog`.
71         AlertDialog.Builder dialogBuilder;
72
73         // Set the style according to the theme.
74         if (MainWebViewActivity.darkTheme) {
75             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
76         } else {
77             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
78         }
79
80         // Set the title.
81         dialogBuilder.setTitle(R.string.create_folder);
82
83         // Set the view.  The parent view is `null` because it will be assigned by the `AlertDialog`.
84         dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.create_bookmark_folder_dialog, null));
85
86         // Set an `onClick()` listener for the negative button.
87         dialogBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
88             @Override
89             public void onClick(DialogInterface dialog, int which) {
90                 // Do nothing.  The `AlertDialog` will close automatically.
91             }
92         });
93
94         // Set an `onClick()` listener fo the positive button.
95         dialogBuilder.setPositiveButton(R.string.create, new DialogInterface.OnClickListener() {
96             @Override
97             public void onClick(DialogInterface dialog, int which) {
98                 // Return the `DialogFragment` to the parent activity on create.
99                 createBookmarkFolderListener.onCreateBookmarkFolder(CreateBookmarkFolderDialog.this);
100             }
101         });
102
103
104         // Create an `AlertDialog` from the `AlertDialog.Builder`.
105         final AlertDialog alertDialog = dialogBuilder.create();
106
107         // Remove the warning below that `setSoftInputMode` might produce `java.lang.NullPointerException`.
108         assert alertDialog.getWindow() != null;
109
110         // Show the keyboard when the `Dialog` is displayed on the screen.
111         alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
112
113         // The `AlertDialog` must be shown before items in the alert dialog can be modified.
114         alertDialog.show();
115
116         // 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`.
117         final BookmarksDatabaseHelper bookmarksDatabaseHelper = new BookmarksDatabaseHelper(getContext(), null, null, 0);
118
119         // Get a handle for the create button.
120         final Button createButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
121         EditText folderNameEditText = (EditText) alertDialog.findViewById(R.id.create_folder_name_edittext);
122
123         // Initially disable the create button.
124         createButton.setEnabled(false);
125
126         // Enable the create button if the new folder name is unique.
127         folderNameEditText.addTextChangedListener(new TextWatcher() {
128             @Override
129             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
130                 // Do nothing.
131             }
132
133             @Override
134             public void onTextChanged(CharSequence s, int start, int before, int count) {
135                 // Do nothing.
136             }
137
138             @Override
139             public void afterTextChanged(Editable s) {
140                 // Convert the current text to a string.
141                 String folderName = s.toString();
142
143                 // Check if a folder with the name already exists.
144                 Cursor folderExistsCursor = bookmarksDatabaseHelper.getFolderCursor(folderName);
145
146                 // Enable the create button if the new folder name is not empty and doesn't already exist.
147                 createButton.setEnabled(!folderName.isEmpty() && (folderExistsCursor.getCount() == 0));
148             }
149         });
150
151         // Allow the `enter` key on the keyboard to create the folder from `create_folder_name_edittext`.
152         folderNameEditText.setOnKeyListener(new View.OnKeyListener() {
153             public boolean onKey(View v, int keyCode, KeyEvent event) {
154                 // If the event is a key-down on the `enter` key, select the `PositiveButton` `Create`.
155                 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && createButton.isEnabled()) {  // The enter key was pressed and the create button is enabled.
156                     // Trigger `createBookmarkFolderListener` and return the `DialogFragment` to the parent activity.
157                     createBookmarkFolderListener.onCreateBookmarkFolder(CreateBookmarkFolderDialog.this);
158                     // Manually dismiss the `AlertDialog`.
159                     alertDialog.dismiss();
160                     // Consume the event.
161                     return true;
162                 } else {  // If any other key was pressed, or if the create button is currently disabled, do not consume the event.
163                     return false;
164                 }
165             }
166         });
167
168         // Display the current favorite icon.
169         ImageView webPageIconImageView = (ImageView) alertDialog.findViewById(R.id.create_folder_web_page_icon);
170         webPageIconImageView.setImageBitmap(MainWebViewActivity.favoriteIconBitmap);
171
172         // `onCreateDialog()` requires the return of an `AlertDialog`.
173         return alertDialog;
174     }
175 }