]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateBookmarkDialog.java
Handle the options menu.
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / CreateBookmarkDialog.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.graphics.Bitmap;
29 import android.graphics.BitmapFactory;
30 import android.graphics.drawable.BitmapDrawable;
31 import android.graphics.drawable.Drawable;
32 import android.os.Bundle;
33 import android.preference.PreferenceManager;
34 import android.view.KeyEvent;
35 import android.view.View;
36 import android.view.WindowManager;
37 import android.widget.EditText;
38
39 import androidx.annotation.NonNull;
40 import androidx.fragment.app.DialogFragment;  // The AndroidX dialog fragment must be used or an error is produced on API <=22.
41
42 import com.stoutner.privacybrowser.R;
43
44 import java.io.ByteArrayOutputStream;
45
46 public class CreateBookmarkDialog extends DialogFragment {
47     // Create the class variables.
48     String url;
49     String title;
50     Bitmap favoriteIconBitmap;
51
52     // The public interface is used to send information back to the parent activity.
53     public interface CreateBookmarkListener {
54         void onCreateBookmark(DialogFragment dialogFragment);
55     }
56
57     // The create bookmark listener is initialized in `onAttach()` and used in `onCreateDialog()`.
58     private CreateBookmarkListener createBookmarkListener;
59
60     public void onAttach(Context context) {
61         // Run the default commands.
62         super.onAttach(context);
63
64         // Get a handle for `CreateBookmarkListener` from the launching context.
65         createBookmarkListener = (CreateBookmarkListener) context;
66     }
67
68     public static CreateBookmarkDialog createBookmark(String url, String title, Bitmap favoriteIconBitmap) {
69         // Scale the favorite icon bitmap down if it is larger than 256 x 256.  Filtering uses bilinear interpolation.
70         if ((favoriteIconBitmap.getHeight() > 256) || (favoriteIconBitmap.getWidth() > 256)) {
71             favoriteIconBitmap = Bitmap.createScaledBitmap(favoriteIconBitmap, 256, 256, true);
72         }
73
74         // Create a favorite icon byte array output stream.
75         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
76
77         // 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).
78         favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
79
80         // Convert the byte array output stream to a byte array.
81         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
82
83         // Create a bundle.
84         Bundle bundle = new Bundle();
85
86         // Store the variables in the bundle
87         bundle.putString("url", url);
88         bundle.putString("title", title);
89         bundle.putByteArray("favorite_icon_byte_array", favoriteIconByteArray);
90
91         // Create a new instance of the dialog.
92         CreateBookmarkDialog createBookmarkDialog = new CreateBookmarkDialog();
93
94         // Add the bundle to the dialog.
95         createBookmarkDialog.setArguments(bundle);
96
97         // Return the new dialog.
98         return createBookmarkDialog;
99     }
100
101     @Override
102     public void onCreate(Bundle savedInstanceState) {
103         // Run the default commands.
104         super.onCreate(savedInstanceState);
105
106         // Get the arguments.
107         Bundle arguments = getArguments();
108
109         // Remove the incorrect lint warning below that the arguments might be null.
110         assert arguments != null;
111
112         // Store the contents of the arguments in class variables.
113         url = arguments.getString("url");
114         title = arguments.getString("title");
115
116         // Get the favorite icon byte array.
117         byte[] favoriteIconByteArray = arguments.getByteArray("favorite_icon_byte_array");
118
119         // Remove the incorrect lint warning below that the favorite icon byte array might be null.
120         assert favoriteIconByteArray != null;
121
122         // Convert the favorite icon byte array to a bitmap and store it in a class variable.
123         favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
124     }
125
126     // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
127     @SuppressLint("InflateParams")
128     @Override
129     @NonNull
130     public Dialog onCreateDialog(Bundle savedInstanceState) {
131         // Get a handle for the shared preferences.
132         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
133
134         // Get the theme and screenshot preferences.
135         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
136         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
137
138         // Create a drawable version of the favorite icon.
139         Drawable favoriteIconDrawable = new BitmapDrawable(getResources(), favoriteIconBitmap);
140
141         // Use an alert dialog builder to create the alert dialog.
142         AlertDialog.Builder dialogBuilder;
143
144         // Set the style according to the theme.
145         if (darkTheme) {
146             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
147         } else {
148             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
149         }
150
151         // Set the title and icon.
152         dialogBuilder.setTitle(R.string.create_bookmark);
153         dialogBuilder.setIcon(favoriteIconDrawable);
154
155         // Remove the warning below that `getLayoutInflater()` might be null.
156         assert getActivity() != null;
157
158         // Set the view.  The parent view is `null` because it will be assigned by the `AlertDialog`.
159         dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.create_bookmark_dialog, null));
160
161         // Set an `onClick()` listener for the negative button.
162         dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
163             // Do nothing.  The `AlertDialog` will close automatically.
164         });
165
166         // Set an `onClick()` listener for the positive button.
167         dialogBuilder.setPositiveButton(R.string.create, (DialogInterface dialog, int which) -> {
168             // Return the `DialogFragment` to the parent activity.
169             createBookmarkListener.onCreateBookmark(CreateBookmarkDialog.this);
170         });
171
172         // Create an `AlertDialog` from the `AlertDialog.Builder`.
173         final AlertDialog alertDialog = dialogBuilder.create();
174
175         // Remove the warning below that `getWindow()` might be null.
176         assert alertDialog.getWindow() != null;
177
178         // Disable screenshots if not allowed.
179         if (!allowScreenshots) {
180             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
181         }
182
183         // Show the keyboard when the `AlertDialog` is displayed on the screen.
184         alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
185
186         // The alert dialog needs to be shown before `setOnKeyListener()` can be called.
187         alertDialog.show();
188
189         // Get a handle for `create_bookmark_name_edittext`.
190         EditText createBookmarkNameEditText = alertDialog.findViewById(R.id.create_bookmark_name_edittext);
191
192         // Set the current `WebView` title as the text for `create_bookmark_name_edittext`.
193         createBookmarkNameEditText.setText(title);
194
195         // Allow the `enter` key on the keyboard to create the bookmark from `create_bookmark_name_edittext`.
196         createBookmarkNameEditText.setOnKeyListener((View view, int keyCode, KeyEvent event) -> {
197             // If the event is a key-down on the `enter` key, select the `PositiveButton` `Create`.
198             if ((keyCode == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN)) {
199                 // Trigger `createBookmarkListener` and return the `DialogFragment` to the parent activity.
200                 createBookmarkListener.onCreateBookmark(CreateBookmarkDialog.this);
201
202                 // Manually dismiss the `AlertDialog`.
203                 alertDialog.dismiss();
204
205                 // Consume the event.
206                 return true;
207             } else {  // If any other key was pressed, do not consume the event.
208                 return false;
209             }
210         });
211
212         // Set the formattedUrlString as the initial text of `create_bookmark_url_edittext`.
213         EditText createBookmarkUrlEditText = alertDialog.findViewById(R.id.create_bookmark_url_edittext);
214         createBookmarkUrlEditText.setText(url);
215
216         // Allow the `enter` key on the keyboard to create the bookmark from `create_bookmark_url_edittext`.
217         createBookmarkUrlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
218             // If the event is a key-down on the "enter" key, select the PositiveButton "Create".
219             if ((keyCode == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN)) {
220                 // Trigger `createBookmarkListener` and return the DialogFragment to the parent activity.
221                 createBookmarkListener.onCreateBookmark(CreateBookmarkDialog.this);
222
223                 // Manually dismiss the `AlertDialog`.
224                 alertDialog.dismiss();
225
226                 // Consume the event.
227                 return true;
228             } else { // If any other key was pressed, do not consume the event.
229                 return false;
230             }
231         });
232
233         // Return the alert dialog.
234         return alertDialog;
235     }
236 }