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