]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateBookmarkFolderDialog.java
Use the Content-Disposition header to get file names for downloads. https://redmine...
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / CreateBookmarkFolderDialog.java
1 /*
2  * Copyright © 2016-2019 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.content.SharedPreferences;
28 import android.database.Cursor;
29 import android.graphics.Bitmap;
30 import android.graphics.BitmapFactory;
31 import android.os.Bundle;
32 import android.preference.PreferenceManager;
33 import android.text.Editable;
34 import android.text.TextWatcher;
35 import android.view.KeyEvent;
36 import android.view.View;
37 import android.view.Window;
38 import android.view.WindowManager;
39 import android.widget.Button;
40 import android.widget.EditText;
41 import android.widget.ImageView;
42
43 import androidx.annotation.NonNull;
44 import androidx.fragment.app.DialogFragment;  // The AndroidX dialog fragment must be used or an error is produced on API <=22.
45
46 import com.stoutner.privacybrowser.R;
47 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
48
49 import java.io.ByteArrayOutputStream;
50
51 public class CreateBookmarkFolderDialog extends DialogFragment {
52     // The public interface is used to send information back to the parent activity.
53     public interface CreateBookmarkFolderListener {
54         void onCreateBookmarkFolder(DialogFragment dialogFragment, Bitmap favoriteIconBitmap);
55     }
56
57     // `createBookmarkFolderListener` is used in `onAttach()` and `onCreateDialog`.
58     private CreateBookmarkFolderListener createBookmarkFolderListener;
59
60     public void onAttach(@NonNull Context context) {
61         super.onAttach(context);
62
63         // Get a handle for `createBookmarkFolderListener` from the launching context.
64         createBookmarkFolderListener = (CreateBookmarkFolderListener) context;
65     }
66
67     public static CreateBookmarkFolderDialog createBookmarkFolder(Bitmap favoriteIconBitmap) {
68         // Create a favorite icon byte array output stream.
69         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
70
71         // Convert the favorite icon to a PNG and place it in the byte array output stream.  `0` is for lossless compression (the only option for a PNG).
72         favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
73
74         // Convert the byte array output stream to a byte array.
75         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
76
77         // Create an arguments bundle.
78         Bundle argumentsBundle = new Bundle();
79
80         // Store the favorite icon in the bundle.
81         argumentsBundle.putByteArray("favorite_icon_byte_array", favoriteIconByteArray);
82
83         // Create a new instance of the dialog.
84         CreateBookmarkFolderDialog createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
85
86         // Add the bundle to the dialog.
87         createBookmarkFolderDialog.setArguments(argumentsBundle);
88
89         // Return the new dialog.
90         return createBookmarkFolderDialog;
91     }
92
93     // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
94     @SuppressLint("InflateParams")
95     @Override
96     @NonNull
97     public Dialog onCreateDialog(Bundle savedInstanceState) {
98         // Get the arguments.
99         Bundle arguments = getArguments();
100
101         // Remove the incorrect lint warning below that the arguments might be null.
102         assert arguments != null;
103
104         // Get the favorite icon byte array.
105         byte[] favoriteIconByteArray = arguments.getByteArray("favorite_icon_byte_array");
106
107         // Remove the incorrect lint warning below that the favorite icon byte array might be null.
108         assert favoriteIconByteArray != null;
109
110         // Convert the favorite icon byte array to a bitmap.
111         Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
112
113         // Use an alert dialog builder to create the alert dialog.
114         AlertDialog.Builder dialogBuilder;
115
116         // Get a handle for the shared preferences.
117         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
118
119         // Get the screenshot and theme preferences.
120         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
121         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
122
123         // Set the style according to the theme.
124         if (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.create_folder);
132
133         // Remove the warning below that `getLayoutInflater()` might be null.
134         assert getActivity() != null;
135
136         // Set the view.  The parent view is null because it will be assigned by the alert dialog.
137         dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.create_bookmark_folder_dialog, null));
138
139         // Set an `onClick()` 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 an `onClick()` listener fo the positive button.
145         dialogBuilder.setPositiveButton(R.string.create, (DialogInterface dialog, int which) -> {
146             // Return the `DialogFragment` to the parent activity on create.
147             createBookmarkFolderListener.onCreateBookmarkFolder(this, favoriteIconBitmap);
148         });
149
150
151         // Create an alert dialog from the `AlertDialog.Builder`.
152         final AlertDialog alertDialog = dialogBuilder.create();
153
154         // Get the alert dialog window.
155         Window dialogWindow = alertDialog.getWindow();
156
157         // Remove the incorrect lint warning below that the dialog window might be null.
158         assert dialogWindow != null;
159
160         // Disable screenshots if not allowed.
161         if (!allowScreenshots) {
162             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
163         }
164
165         // Display the keyboard.
166         dialogWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
167
168         // The alert dialog must be shown before items in the alert dialog can be modified.
169         alertDialog.show();
170
171         // Get handles for the views in the dialog.
172         final Button createButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
173         EditText folderNameEditText = alertDialog.findViewById(R.id.create_folder_name_edittext);
174         ImageView webPageIconImageView = alertDialog.findViewById(R.id.create_folder_web_page_icon);
175
176         // Initially disable the create button.
177         createButton.setEnabled(false);
178
179         // Initialize the database helper.  The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
180         final BookmarksDatabaseHelper bookmarksDatabaseHelper = new BookmarksDatabaseHelper(getContext(), null, null, 0);
181
182         // Enable the create button if the new folder name is unique.
183         folderNameEditText.addTextChangedListener(new TextWatcher() {
184             @Override
185             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
186                 // Do nothing.
187             }
188
189             @Override
190             public void onTextChanged(CharSequence s, int start, int before, int count) {
191                 // Do nothing.
192             }
193
194             @Override
195             public void afterTextChanged(Editable s) {
196                 // Convert the current text to a string.
197                 String folderName = s.toString();
198
199                 // Check if a folder with the name already exists.
200                 Cursor folderExistsCursor = bookmarksDatabaseHelper.getFolder(folderName);
201
202                 // Enable the create button if the new folder name is not empty and doesn't already exist.
203                 createButton.setEnabled(!folderName.isEmpty() && (folderExistsCursor.getCount() == 0));
204             }
205         });
206
207         // Set the enter key on the keyboard to create the folder from the edit text.
208         folderNameEditText.setOnKeyListener((View view, int keyCode, KeyEvent keyEvent) -> {
209             // If the key event is a key-down on the `enter` key create the bookmark folder.
210             if ((keyEvent.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && createButton.isEnabled()) {  // The enter key was pressed and the create button is enabled.
211                 // Trigger the create bookmark folder listener and return the dialog fragment to the parent activity.
212                 createBookmarkFolderListener.onCreateBookmarkFolder(this, favoriteIconBitmap);
213
214                 // Manually dismiss the alert dialog.
215                 alertDialog.dismiss();
216
217                 // Consume the event.
218                 return true;
219             } else {  // If any other key was pressed, or if the create button is currently disabled, do not consume the event.
220                 return false;
221             }
222         });
223
224         // Display the current favorite icon.
225         webPageIconImageView.setImageBitmap(favoriteIconBitmap);
226
227         // Return the alert dialog.
228         return alertDialog;
229     }
230 }