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