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