]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateHomeScreenShortcutDialog.java
Add the URL to the create homescreen shortcut dialog. https://redmine.stoutner.com...
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / CreateHomeScreenShortcutDialog.java
1 /*
2  * Copyright © 2015-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.Intent;
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.net.Uri;
33 import android.os.Bundle;
34 import android.text.Editable;
35 import android.text.TextWatcher;
36 import android.view.KeyEvent;
37 import android.view.LayoutInflater;
38 import android.view.View;
39 import android.view.WindowManager;
40 import android.widget.Button;
41 import android.widget.EditText;
42
43 import androidx.annotation.NonNull;
44 // `ShortcutInfoCompat`, `ShortcutManagerCompat`, and `IconCompat` can be switched to the non-compat versions once API >= 26.
45 import androidx.core.content.pm.ShortcutInfoCompat;
46 import androidx.core.content.pm.ShortcutManagerCompat;
47 import androidx.core.graphics.drawable.IconCompat;
48 import androidx.fragment.app.DialogFragment;  // The AndroidX dialog fragment must be used or an error is produced on API <=22.
49
50 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
51 import com.stoutner.privacybrowser.R;
52
53 import java.io.ByteArrayOutputStream;
54
55 public class CreateHomeScreenShortcutDialog extends DialogFragment {
56     // Create the class variables.
57     private String initialShortcutName;
58     private String initialUrlString;
59     private Bitmap favoriteIconBitmap;
60     private EditText shortcutNameEditText;
61     private EditText urlEditText;
62     private Button createButton;
63
64     public static CreateHomeScreenShortcutDialog createDialog(String shortcutName, String urlString, Bitmap favoriteIconBitmap) {
65         // Create a favorite icon byte array output stream.
66         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
67
68         // 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).
69         favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
70
71         // Convert the byte array output stream to a byte array.
72         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
73
74         // Create a bundle.
75         Bundle bundle = new Bundle();
76
77         // Store the variables in the bundle.
78         bundle.putString("shortcut_name", shortcutName);
79         bundle.putString("url_string", urlString);
80         bundle.putByteArray("favorite_icon_byte_array", favoriteIconByteArray);
81
82         // Create a new instance of the dialog.
83         CreateHomeScreenShortcutDialog createHomeScreenShortcutDialog = new CreateHomeScreenShortcutDialog();
84
85         // Add the bundle to the dialog.
86         createHomeScreenShortcutDialog.setArguments(bundle);
87
88         // Return the new dialog.
89         return createHomeScreenShortcutDialog;
90     }
91
92     @Override
93     public void onCreate(Bundle savedInstanceState) {
94         // Run the default commands.
95         super.onCreate(savedInstanceState);
96
97         // Get the arguments.
98         Bundle arguments = getArguments();
99
100         // Remove the incorrect lint warning that the arguments might be null.
101         assert arguments != null;
102
103         // Store the strings in class variables.
104         initialShortcutName = arguments.getString("shortcut_name");
105         initialUrlString = arguments.getString("url_string");
106
107         // Get the favorite icon byte array.
108         byte[] favoriteIconByteArray = arguments.getByteArray("favorite_icon_byte_array");
109
110         // Remove the incorrect lint warning below that the favorite icon byte array might be null.
111         assert favoriteIconByteArray != null;
112
113         // Convert the favorite icon byte array to a bitmap and store it in a class variable.
114         favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
115     }
116
117     // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
118     @SuppressLint("InflateParams")
119     @Override
120     @NonNull
121     public Dialog onCreateDialog(Bundle savedInstanceState) {
122         // Remove the incorrect lint warning below that `getLayoutInflater()` might be null.
123         assert getActivity() != null;
124
125         // Get the activity's layout inflater.
126         LayoutInflater layoutInflater = getActivity().getLayoutInflater();
127
128         // Create a drawable version of the favorite icon.
129         Drawable favoriteIconDrawable = new BitmapDrawable(getResources(), favoriteIconBitmap);
130
131         // Use a builder to create the alert dialog.
132         AlertDialog.Builder dialogBuilder;
133
134         // Set the style according to the theme.
135         if (MainWebViewActivity.darkTheme) {
136             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
137         } else {
138             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
139         }
140
141         // Set the title and icon.
142         dialogBuilder.setTitle(R.string.create_shortcut);
143         dialogBuilder.setIcon(favoriteIconDrawable);
144
145         // Set the view.  The parent view is null because it will be assigned by the alert dialog.
146         dialogBuilder.setView(layoutInflater.inflate(R.layout.create_home_screen_shortcut_dialog, null));
147
148         // Setup the close button.  Using null closes the dialog without doing anything else.
149         dialogBuilder.setNegativeButton(R.string.cancel, null);
150
151         // Set an `onClick` listener on the create button.
152         dialogBuilder.setPositiveButton(R.string.create, (DialogInterface dialog, int which) -> {
153             // Create the home screen shortcut.
154             createHomeScreenShortcut();
155         });
156
157         // Create an alert dialog from the alert dialog builder.
158         final AlertDialog alertDialog = dialogBuilder.create();
159
160         // Remove the warning below that `getWindow()` might be null.
161         assert alertDialog.getWindow() != null;
162
163         // Disable screenshots if not allowed.
164         if (!MainWebViewActivity.allowScreenshots) {
165             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
166         }
167
168         // The alert dialog must be shown before the contents may be edited.
169         alertDialog.show();
170
171         // Get a handle for the edit texts.
172         shortcutNameEditText = alertDialog.findViewById(R.id.shortcut_name_edittext);
173         urlEditText = alertDialog.findViewById(R.id.url_edittext);
174
175         // Populate the edit texts.
176         shortcutNameEditText.setText(initialShortcutName);
177         urlEditText.setText(initialUrlString);
178
179         // Get a handle for the create button.
180         createButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
181
182         // Add a text change listener to the shortcut name edit text.
183         shortcutNameEditText.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                 // Update the create button.
197                 updateCreateButton();
198             }
199         });
200
201         // Add a text change listener to the URL edit text.
202         urlEditText.addTextChangedListener(new TextWatcher() {
203             @Override
204             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
205                 // Do nothing.
206             }
207
208             @Override
209             public void onTextChanged(CharSequence s, int start, int before, int count) {
210                 // Do nothing.
211             }
212
213             @Override
214             public void afterTextChanged(Editable s) {
215                 // Update the create button.
216                 updateCreateButton();
217             }
218         });
219
220         // Allow the enter key on the keyboard to create the shortcut when editing the name.
221         shortcutNameEditText.setOnKeyListener((View view, int keyCode, KeyEvent keyEvent) -> {
222             // Check to see if the enter key was pressed.
223             if ((keyEvent.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
224                 // Check the status of the create button.
225                 if (createButton.isEnabled()) {  // The create button is enabled.
226                     // Create the home screen shortcut.
227                     createHomeScreenShortcut();
228
229                     // Manually dismiss the alert dialog.
230                     alertDialog.dismiss();
231
232                     // Consume the event.
233                     return true;
234                 } else {  // The create button is disabled.
235                     // Do not consume the event.
236                     return false;
237                 }
238             } else {  // Some other key was pressed.
239                 // Do not consume the event.
240                 return false;
241             }
242         });
243
244         // Set the enter key on the keyboard to create the shortcut when editing the URL.
245         urlEditText.setOnKeyListener((View view, int keyCode, KeyEvent keyEvent) -> {
246             // Check to see if the enter key was pressed.
247             if ((keyEvent.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
248                 // Check the status of the create button.
249                 if (createButton.isEnabled()) {  // The create button is enabled.
250                     // Create the home screen shortcut.
251                     createHomeScreenShortcut();
252
253                     // Manually dismiss the alert dialog.
254                     alertDialog.dismiss();
255
256                     // Consume the event.
257                     return true;
258                 } else {  // The create button is disabled.
259                     // Do not consume the event.
260                     return false;
261                 }
262             } else {  // Some other key was pressed.
263                 // Do not consume the event.
264                 return false;
265             }
266         });
267
268         // Return the alert dialog.
269         return alertDialog;
270     }
271
272     private void updateCreateButton() {
273         // Get the contents of the edit texts.
274         String shortcutName = shortcutNameEditText.getText().toString();
275         String urlString = urlEditText.getText().toString();
276
277         // Enable the create button if both the shortcut name and the URL are not empty.
278         createButton.setEnabled(!shortcutName.isEmpty() && !urlString.isEmpty());
279     }
280
281     private void createHomeScreenShortcut() {
282         // Get a handle for the context.
283         Context context = getContext();
284
285         // Remove the incorrect lint warning below that the context might be null.
286         assert context != null;
287
288         // Get the strings from the edit texts.
289         String shortcutName = shortcutNameEditText.getText().toString();
290         String urlString = urlEditText.getText().toString();
291
292         // Convert the favorite icon bitmap to an icon.  `IconCompat` must be used until the minimum API >= 26.
293         IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
294
295         // Setup the shortcut intent.
296         Intent shortcutIntent = new Intent(Intent.ACTION_VIEW);
297         shortcutIntent.setData(Uri.parse(urlString));
298
299         // Create a shortcut info builder.  The shortcut name becomes the shortcut ID.
300         ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(context, shortcutName);
301
302         // Add the required fields to the shortcut info builder.
303         shortcutInfoBuilder.setIcon(favoriteIcon);
304         shortcutInfoBuilder.setIntent(shortcutIntent);
305         shortcutInfoBuilder.setShortLabel(shortcutName);
306
307         // Add the shortcut to the home screen.  `ShortcutManagerCompat` can be switched to `ShortcutManager` once the minimum API >= 26.
308         ShortcutManagerCompat.requestPinShortcut(context, shortcutInfoBuilder.build(), null);
309     }
310 }