2 * Copyright © 2016-2017 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
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.
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.
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/>.
20 package com.stoutner.privacybrowser.dialogs;
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.IdRes;
32 import android.support.annotation.NonNull;
33 // `AppCompatDialogFragment` is required instead of `DialogFragment` or an error is produced on API <=22.
34 import android.support.v7.app.AppCompatDialogFragment;
35 import android.text.Editable;
36 import android.text.TextWatcher;
37 import android.view.KeyEvent;
38 import android.view.View;
39 import android.view.WindowManager;
40 import android.widget.Button;
41 import android.widget.EditText;
42 import android.widget.ImageView;
43 import android.widget.RadioButton;
44 import android.widget.RadioGroup;
46 import com.stoutner.privacybrowser.R;
47 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
48 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
50 public class EditBookmarkFolderDialog extends AppCompatDialogFragment {
51 // The public interface is used to send information back to the parent activity.
52 public interface EditBookmarkFolderListener {
53 void onSaveEditBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId);
56 // Instantiate the class variables.
57 private EditBookmarkFolderListener editBookmarkFolderListener;
58 private int selectedFolderDatabaseId;
60 public void onAttach(Context context) {
61 // Run the default commands.
62 super.onAttach(context);
64 // Get a handle for `EditFolderListener` from `parentActivity`.
66 editBookmarkFolderListener = (EditBookmarkFolderListener) context;
67 } catch(ClassCastException exception) {
68 throw new ClassCastException(context.toString() + " must implement EditBookmarkFolderListener.");
72 // Store the database ID in the arguments bundle.
73 public static EditBookmarkFolderDialog folderDatabaseId(int databaseId) {
75 Bundle bundle = new Bundle();
77 // Store the folder database ID in the bundle.
78 bundle.putInt("Database ID", databaseId);
80 // Add the bundle to the dialog.
81 EditBookmarkFolderDialog editBookmarkFolderDialog = new EditBookmarkFolderDialog();
82 editBookmarkFolderDialog.setArguments(bundle);
84 // Return the new dialog.
85 return editBookmarkFolderDialog;
89 public void onCreate(Bundle savedInstanceState) {
90 // Run the default commands.
91 super.onCreate(savedInstanceState);
93 // Store the folder database ID in the class variable.
94 selectedFolderDatabaseId = getArguments().getInt("Database ID");
97 // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
98 @SuppressLint("InflateParams")
101 public Dialog onCreateDialog(Bundle savedInstanceState) {
102 // 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`.
103 final BookmarksDatabaseHelper bookmarksDatabaseHelper = new BookmarksDatabaseHelper(getContext(), null, null, 0);
105 // Get a `Cursor` with the selected folder and move it to the first position.
106 Cursor folderCursor = bookmarksDatabaseHelper.getBookmarkCursor(selectedFolderDatabaseId);
107 folderCursor.moveToFirst();
109 // Use `AlertDialog.Builder` to create the `AlertDialog`.
110 AlertDialog.Builder dialogBuilder;
112 // Set the style according to the theme.
113 if (MainWebViewActivity.darkTheme) {
114 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
116 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
120 dialogBuilder.setTitle(R.string.edit_folder);
122 // Set the view. The parent view is `null` because it will be assigned by `AlertDialog`.
123 dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.edit_bookmark_folder_dialog, null));
125 // Set an `onClick()` listener for the negative button.
126 dialogBuilder.setNegativeButton(R.string.cancel, new Dialog.OnClickListener() {
128 public void onClick(DialogInterface dialog, int which) {
129 // Do nothing. The `AlertDialog` will close automatically.
133 // Set the `onClick()` listener fo the positive button.
134 dialogBuilder.setPositiveButton(R.string.save, new Dialog.OnClickListener() {
136 public void onClick(DialogInterface dialog, int which) {
137 // Return the `DialogFragment` to the parent activity on save.
138 editBookmarkFolderListener.onSaveEditBookmarkFolder(EditBookmarkFolderDialog.this, selectedFolderDatabaseId);
142 // Create an `AlertDialog` from the `AlertDialog.Builder`.
143 final AlertDialog alertDialog = dialogBuilder.create();
145 // Remove the warning below that `setSoftInputMode` might produce `java.lang.NullPointerException`.
146 assert alertDialog.getWindow() != null;
148 // Show the keyboard when the `Dialog` is displayed on the screen.
149 alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
151 // The `AlertDialog` must be shown before items in the layout can be modified.
154 // Get handles for layout items in the `AlertDialog`.
155 final Button editButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
156 final RadioButton currentIconRadioButton = (RadioButton) alertDialog.findViewById(R.id.edit_folder_current_icon_radiobutton);
157 RadioGroup iconRadioGroup = (RadioGroup) alertDialog.findViewById(R.id.edit_folder_icon_radio_group);
159 // Initially disable the edit button.
160 editButton.setEnabled(false);
162 // Get the current favorite icon byte array from the `Cursor`.
163 byte[] currentIconByteArray = folderCursor.getBlob(folderCursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
164 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
165 Bitmap currentIconBitmap = BitmapFactory.decodeByteArray(currentIconByteArray, 0, currentIconByteArray.length);
166 // Display `currentIconBitmap` in `edit_folder_current_icon`.
167 ImageView currentIconImageView = (ImageView) alertDialog.findViewById(R.id.edit_folder_current_icon);
168 currentIconImageView.setImageBitmap(currentIconBitmap);
170 // Get a `Bitmap` of the favorite icon from `MainWebViewActivity` and display it in `edit_folder_web_page_favorite_icon`.
171 ImageView webPageFavoriteIconImageView = (ImageView) alertDialog.findViewById(R.id.edit_folder_web_page_favorite_icon);
172 webPageFavoriteIconImageView.setImageBitmap(MainWebViewActivity.favoriteIconBitmap);
174 // Get the current folder name.
175 final String currentFolderName = folderCursor.getString(folderCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
177 // Display the current folder name in `edit_folder_name_edittext`.
178 final EditText folderNameEditText = (EditText) alertDialog.findViewById(R.id.edit_folder_name_edittext);
179 folderNameEditText.setText(currentFolderName);
181 // Update the status of the edit button when the folder name is changed.
182 folderNameEditText.addTextChangedListener(new TextWatcher() {
184 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
189 public void onTextChanged(CharSequence s, int start, int before, int count) {
194 public void afterTextChanged(Editable s) {
195 // Convert the current text to a string.
196 String newFolderName = s.toString();
198 // Get a cursor for the new folder name if it exists.
199 Cursor folderExistsCursor = bookmarksDatabaseHelper.getFolderCursor(newFolderName);
201 // Is the new folder name empty?
202 boolean folderNameEmpty = newFolderName.isEmpty();
204 // Does the folder name already exist?
205 boolean folderNameAlreadyExists = (!newFolderName.equals(currentFolderName) && (folderExistsCursor.getCount() > 0));
207 // Has the folder been renamed?
208 boolean folderRenamed = (!newFolderName.equals(currentFolderName) && !folderNameAlreadyExists);
210 // Has the favorite icon changed?
211 boolean iconChanged = (!currentIconRadioButton.isChecked() && !folderNameAlreadyExists);
213 // Enable the create button if something has been edited and the new folder name is valid.
214 editButton.setEnabled(!folderNameEmpty && (folderRenamed || iconChanged));
218 // Update the status of the edit button when the icon is changed.
219 iconRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
221 public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
222 // Get the new folder name.
223 String newFolderName = folderNameEditText.getText().toString();
225 // Get a cursor for the new folder name if it exists.
226 Cursor folderExistsCursor = bookmarksDatabaseHelper.getFolderCursor(newFolderName);
228 // Is the new folder name empty?
229 boolean folderNameEmpty = newFolderName.isEmpty();
231 // Does the folder name already exist?
232 boolean folderNameAlreadyExists = (!newFolderName.equals(currentFolderName) && (folderExistsCursor.getCount() > 0));
234 // Has the folder been renamed?
235 boolean folderRenamed = (!newFolderName.equals(currentFolderName) && !folderNameAlreadyExists);
237 // Has the favorite icon changed?
238 boolean iconChanged = (!currentIconRadioButton.isChecked() && !folderNameAlreadyExists);
240 // Enable the create button if something has been edited and the new folder name is valid.
241 editButton.setEnabled(!folderNameEmpty && (folderRenamed || iconChanged));
245 // Allow the `enter` key on the keyboard to save the bookmark from `edit_bookmark_name_edittext`.
246 folderNameEditText.setOnKeyListener(new View.OnKeyListener() {
247 public boolean onKey(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.onSaveEditBookmarkFolder(EditBookmarkFolderDialog.this, selectedFolderDatabaseId);
253 // Manually dismiss the `AlertDialog`.
254 alertDialog.dismiss();
256 // Consume the event.
258 } else { // If any other key was pressed, or if the edit button is currently disabled, do not consume the event.
264 // `onCreateDialog` requires the return of an `AlertDialog`.