]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/CreateHomeScreenShortcutDialog.java
Add support for I2P and custom proxies. https://redmine.stoutner.com/issues/355
[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.Dialog;
24 import android.content.Context;
25 import android.content.DialogInterface;
26 import android.content.Intent;
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.net.Uri;
33 import android.os.Bundle;
34 import android.preference.PreferenceManager;
35 import android.text.Editable;
36 import android.text.TextWatcher;
37 import android.view.KeyEvent;
38 import android.view.LayoutInflater;
39 import android.view.View;
40 import android.view.WindowManager;
41 import android.widget.Button;
42 import android.widget.EditText;
43 import android.widget.RadioButton;
44
45 import androidx.annotation.NonNull;
46 import androidx.appcompat.app.AlertDialog;
47 import androidx.core.content.pm.ShortcutInfoCompat;
48 import androidx.core.content.pm.ShortcutManagerCompat;
49 import androidx.core.graphics.drawable.IconCompat;
50 import androidx.fragment.app.DialogFragment;
51
52 import com.stoutner.privacybrowser.BuildConfig;
53 import com.stoutner.privacybrowser.R;
54
55 import java.io.ByteArrayOutputStream;
56
57 public class CreateHomeScreenShortcutDialog extends DialogFragment {
58     // Define the class variables.
59     private EditText shortcutNameEditText;
60     private EditText urlEditText;
61     private RadioButton openWithPrivacyBrowserRadioButton;
62
63     // The public constructor.
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 an arguments bundle.
75         Bundle argumentsBundle = new Bundle();
76
77         // Store the variables in the bundle.
78         argumentsBundle.putString("shortcut_name", shortcutName);
79         argumentsBundle.putString("url_string", urlString);
80         argumentsBundle.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(argumentsBundle);
87
88         // Return the new dialog.
89         return createHomeScreenShortcutDialog;
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 strings from the arguments.
104         String initialShortcutName = arguments.getString("shortcut_name");
105         String 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         Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
115
116         // Get a handle for the shared preferences.
117         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
118
119         // Get the theme and screenshot preferences.
120         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
121         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
122
123         // Remove the incorrect lint warning below that the layout inflater might be null.
124         assert getActivity() != null;
125
126         // Get the activity's layout inflater.
127         LayoutInflater layoutInflater = getActivity().getLayoutInflater();
128
129         // Create a drawable version of the favorite icon.
130         Drawable favoriteIconDrawable = new BitmapDrawable(getResources(), favoriteIconBitmap);
131
132         // Use a builder to create the alert dialog.
133         AlertDialog.Builder dialogBuilder;
134
135         // Set the style according to the theme.
136         if (darkTheme) {
137             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
138         } else {
139             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
140         }
141
142         // Set the title and icon.
143         dialogBuilder.setTitle(R.string.create_shortcut);
144         dialogBuilder.setIcon(favoriteIconDrawable);
145
146         // Set the view.  The parent view is null because it will be assigned by the alert dialog.
147         dialogBuilder.setView(layoutInflater.inflate(R.layout.create_home_screen_shortcut_dialog, null));
148
149         // Setup the close button.  Using null closes the dialog without doing anything else.
150         dialogBuilder.setNegativeButton(R.string.cancel, null);
151
152         // Set an `onClick` listener on the create button.
153         dialogBuilder.setPositiveButton(R.string.create, (DialogInterface dialog, int which) -> {
154             // Create the home screen shortcut.
155             createHomeScreenShortcut(favoriteIconBitmap);
156         });
157
158         // Create an alert dialog from the alert dialog builder.
159         final AlertDialog alertDialog = dialogBuilder.create();
160
161         // Remove the warning below that `getWindow()` might be null.
162         assert alertDialog.getWindow() != null;
163
164         // Disable screenshots if not allowed.
165         if (allowScreenshots) {
166             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
167         }
168
169         // The alert dialog must be shown before the contents may be edited.
170         alertDialog.show();
171
172         // Get handles for the views.
173         shortcutNameEditText = alertDialog.findViewById(R.id.shortcut_name_edittext);
174         urlEditText = alertDialog.findViewById(R.id.url_edittext);
175         openWithPrivacyBrowserRadioButton = alertDialog.findViewById(R.id.open_with_privacy_browser_radiobutton);
176         Button createButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
177
178         // Populate the edit texts.
179         shortcutNameEditText.setText(initialShortcutName);
180         urlEditText.setText(initialUrlString);
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(createButton);
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(createButton);
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(favoriteIconBitmap);
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(favoriteIconBitmap);
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(Button createButton) {
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(Bitmap favoriteIconBitmap) {
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         // Create a shortcut intent.
296         Intent shortcutIntent = new Intent(Intent.ACTION_VIEW);
297
298         // Check to see if the shortcut should open up Privacy Browser explicitly.
299         if (openWithPrivacyBrowserRadioButton.isChecked()) {
300             // Set the current application ID as the target package.
301             shortcutIntent.setPackage(BuildConfig.APPLICATION_ID);
302         }
303
304         // Add the URL to the intent.
305         shortcutIntent.setData(Uri.parse(urlString));
306
307         // Create a shortcut info builder.  The shortcut name becomes the shortcut ID.
308         ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(context, shortcutName);
309
310         // Add the required fields to the shortcut info builder.
311         shortcutInfoBuilder.setIcon(favoriteIcon);
312         shortcutInfoBuilder.setIntent(shortcutIntent);
313         shortcutInfoBuilder.setShortLabel(shortcutName);
314
315         // Add the shortcut to the home screen.  `ShortcutManagerCompat` can be switched to `ShortcutManager` once the minimum API >= 26.
316         ShortcutManagerCompat.requestPinShortcut(context, shortcutInfoBuilder.build(), null);
317     }
318 }