2 * Copyright © 2015-2019 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
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.
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.
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/>.
20 package com.stoutner.privacybrowser.dialogs;
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;
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.
53 import com.stoutner.privacybrowser.BuildConfig;
54 import com.stoutner.privacybrowser.R;
56 import java.io.ByteArrayOutputStream;
58 public class CreateHomeScreenShortcutDialog extends DialogFragment {
59 // Define the class variables.
60 private EditText shortcutNameEditText;
61 private EditText urlEditText;
62 private RadioButton openWithPrivacyBrowserRadioButton;
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();
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);
71 // Convert the byte array output stream to a byte array.
72 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
74 // Create an arguments bundle.
75 Bundle argumentsBundle = new Bundle();
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);
82 // Create a new instance of the dialog.
83 CreateHomeScreenShortcutDialog createHomeScreenShortcutDialog = new CreateHomeScreenShortcutDialog();
85 // Add the bundle to the dialog.
86 createHomeScreenShortcutDialog.setArguments(argumentsBundle);
88 // Return the new dialog.
89 return createHomeScreenShortcutDialog;
92 // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
93 @SuppressLint("InflateParams")
96 public Dialog onCreateDialog(Bundle savedInstanceState) {
98 Bundle arguments = getArguments();
100 // Remove the incorrect lint warning below that the arguments might be null.
101 assert arguments != null;
103 // Get the strings from the arguments.
104 String initialShortcutName = arguments.getString("shortcut_name");
105 String initialUrlString = arguments.getString("url_string");
107 // Get the favorite icon byte array.
108 byte[] favoriteIconByteArray = arguments.getByteArray("favorite_icon_byte_array");
110 // Remove the incorrect lint warning below that the favorite icon byte array might be null.
111 assert favoriteIconByteArray != null;
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);
116 // Get a handle for the shared preferences.
117 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
119 // Get the theme and screenshot preferences.
120 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
121 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
123 // Remove the incorrect lint warning below that the layout inflater might be null.
124 assert getActivity() != null;
126 // Get the activity's layout inflater.
127 LayoutInflater layoutInflater = getActivity().getLayoutInflater();
129 // Create a drawable version of the favorite icon.
130 Drawable favoriteIconDrawable = new BitmapDrawable(getResources(), favoriteIconBitmap);
132 // Use a builder to create the alert dialog.
133 AlertDialog.Builder dialogBuilder;
135 // Set the style according to the theme.
137 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
139 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
142 // Set the title and icon.
143 dialogBuilder.setTitle(R.string.create_shortcut);
144 dialogBuilder.setIcon(favoriteIconDrawable);
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));
149 // Setup the close button. Using null closes the dialog without doing anything else.
150 dialogBuilder.setNegativeButton(R.string.cancel, null);
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);
158 // Create an alert dialog from the alert dialog builder.
159 final AlertDialog alertDialog = dialogBuilder.create();
161 // Remove the warning below that `getWindow()` might be null.
162 assert alertDialog.getWindow() != null;
164 // Disable screenshots if not allowed.
165 if (allowScreenshots) {
166 alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
169 // The alert dialog must be shown before the contents may be edited.
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);
178 // Populate the edit texts.
179 shortcutNameEditText.setText(initialShortcutName);
180 urlEditText.setText(initialUrlString);
182 // Add a text change listener to the shortcut name edit text.
183 shortcutNameEditText.addTextChangedListener(new TextWatcher() {
185 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
190 public void onTextChanged(CharSequence s, int start, int before, int count) {
195 public void afterTextChanged(Editable s) {
196 // Update the create button.
197 updateCreateButton(createButton);
201 // Add a text change listener to the URL edit text.
202 urlEditText.addTextChangedListener(new TextWatcher() {
204 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
209 public void onTextChanged(CharSequence s, int start, int before, int count) {
214 public void afterTextChanged(Editable s) {
215 // Update the create button.
216 updateCreateButton(createButton);
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);
229 // Manually dismiss the alert dialog.
230 alertDialog.dismiss();
232 // Consume the event.
234 } else { // The create button is disabled.
235 // Do not consume the event.
238 } else { // Some other key was pressed.
239 // Do not consume the event.
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);
253 // Manually dismiss the alert dialog.
254 alertDialog.dismiss();
256 // Consume the event.
258 } else { // The create button is disabled.
259 // Do not consume the event.
262 } else { // Some other key was pressed.
263 // Do not consume the event.
268 // Return the alert dialog.
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();
277 // Enable the create button if both the shortcut name and the URL are not empty.
278 createButton.setEnabled(!shortcutName.isEmpty() && !urlString.isEmpty());
281 private void createHomeScreenShortcut(Bitmap favoriteIconBitmap) {
282 // Get a handle for the context.
283 Context context = getContext();
285 // Remove the incorrect lint warning below that the context might be null.
286 assert context != null;
288 // Get the strings from the edit texts.
289 String shortcutName = shortcutNameEditText.getText().toString();
290 String urlString = urlEditText.getText().toString();
292 // Convert the favorite icon bitmap to an icon. `IconCompat` must be used until the minimum API >= 26.
293 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
295 // Create a shortcut intent.
296 Intent shortcutIntent = new Intent(Intent.ACTION_VIEW);
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);
304 // Add the URL to the intent.
305 shortcutIntent.setData(Uri.parse(urlString));
307 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
308 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(context, shortcutName);
310 // Add the required fields to the shortcut info builder.
311 shortcutInfoBuilder.setIcon(favoriteIcon);
312 shortcutInfoBuilder.setIntent(shortcutIntent);
313 shortcutInfoBuilder.setShortLabel(shortcutName);
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);