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 // The public constructor.
65 public static CreateHomeScreenShortcutDialog createDialog(String shortcutName, String urlString, Bitmap favoriteIconBitmap) {
66 // Create a favorite icon byte array output stream.
67 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
69 // 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).
70 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
72 // Convert the byte array output stream to a byte array.
73 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
75 // Create an arguments bundle.
76 Bundle argumentsBundle = new Bundle();
78 // Store the variables in the bundle.
79 argumentsBundle.putString("shortcut_name", shortcutName);
80 argumentsBundle.putString("url_string", urlString);
81 argumentsBundle.putByteArray("favorite_icon_byte_array", favoriteIconByteArray);
83 // Create a new instance of the dialog.
84 CreateHomeScreenShortcutDialog createHomeScreenShortcutDialog = new CreateHomeScreenShortcutDialog();
86 // Add the bundle to the dialog.
87 createHomeScreenShortcutDialog.setArguments(argumentsBundle);
89 // Return the new dialog.
90 return createHomeScreenShortcutDialog;
93 // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
94 @SuppressLint("InflateParams")
97 public Dialog onCreateDialog(Bundle savedInstanceState) {
99 Bundle arguments = getArguments();
101 // Remove the incorrect lint warning below that the arguments might be null.
102 assert arguments != null;
104 // Get the strings from the arguments.
105 String initialShortcutName = arguments.getString("shortcut_name");
106 String initialUrlString = arguments.getString("url_string");
108 // Get the favorite icon byte array.
109 byte[] favoriteIconByteArray = arguments.getByteArray("favorite_icon_byte_array");
111 // Remove the incorrect lint warning below that the favorite icon byte array might be null.
112 assert favoriteIconByteArray != null;
114 // Convert the favorite icon byte array to a bitmap and store it in a class variable.
115 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
117 // Get a handle for the shared preferences.
118 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
120 // Get the theme and screenshot preferences.
121 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
122 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
124 // Remove the incorrect lint warning below that the layout inflater might be null.
125 assert getActivity() != null;
127 // Get the activity's layout inflater.
128 LayoutInflater layoutInflater = getActivity().getLayoutInflater();
130 // Create a drawable version of the favorite icon.
131 Drawable favoriteIconDrawable = new BitmapDrawable(getResources(), favoriteIconBitmap);
133 // Use a builder to create the alert dialog.
134 AlertDialog.Builder dialogBuilder;
136 // Set the style according to the theme.
138 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
140 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
143 // Set the title and icon.
144 dialogBuilder.setTitle(R.string.create_shortcut);
145 dialogBuilder.setIcon(favoriteIconDrawable);
147 // Set the view. The parent view is null because it will be assigned by the alert dialog.
148 dialogBuilder.setView(layoutInflater.inflate(R.layout.create_home_screen_shortcut_dialog, null));
150 // Setup the close button. Using null closes the dialog without doing anything else.
151 dialogBuilder.setNegativeButton(R.string.cancel, null);
153 // Set an `onClick` listener on the create button.
154 dialogBuilder.setPositiveButton(R.string.create, (DialogInterface dialog, int which) -> {
155 // Create the home screen shortcut.
156 createHomeScreenShortcut(favoriteIconBitmap);
159 // Create an alert dialog from the alert dialog builder.
160 final AlertDialog alertDialog = dialogBuilder.create();
162 // Remove the warning below that `getWindow()` might be null.
163 assert alertDialog.getWindow() != null;
165 // Disable screenshots if not allowed.
166 if (allowScreenshots) {
167 alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
170 // The alert dialog must be shown before the contents may be edited.
173 // Get handles for the views.
174 shortcutNameEditText = alertDialog.findViewById(R.id.shortcut_name_edittext);
175 urlEditText = alertDialog.findViewById(R.id.url_edittext);
176 openWithPrivacyBrowserRadioButton = alertDialog.findViewById(R.id.open_with_privacy_browser_radiobutton);
177 Button createButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
179 // Populate the edit texts.
180 shortcutNameEditText.setText(initialShortcutName);
181 urlEditText.setText(initialUrlString);
183 // Add a text change listener to the shortcut name edit text.
184 shortcutNameEditText.addTextChangedListener(new TextWatcher() {
186 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
191 public void onTextChanged(CharSequence s, int start, int before, int count) {
196 public void afterTextChanged(Editable s) {
197 // Update the create button.
198 updateCreateButton(createButton);
202 // Add a text change listener to the URL edit text.
203 urlEditText.addTextChangedListener(new TextWatcher() {
205 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
210 public void onTextChanged(CharSequence s, int start, int before, int count) {
215 public void afterTextChanged(Editable s) {
216 // Update the create button.
217 updateCreateButton(createButton);
221 // Allow the enter key on the keyboard to create the shortcut when editing the name.
222 shortcutNameEditText.setOnKeyListener((View view, int keyCode, KeyEvent keyEvent) -> {
223 // Check to see if the enter key was pressed.
224 if ((keyEvent.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
225 // Check the status of the create button.
226 if (createButton.isEnabled()) { // The create button is enabled.
227 // Create the home screen shortcut.
228 createHomeScreenShortcut(favoriteIconBitmap);
230 // Manually dismiss the alert dialog.
231 alertDialog.dismiss();
233 // Consume the event.
235 } else { // The create button is disabled.
236 // Do not consume the event.
239 } else { // Some other key was pressed.
240 // Do not consume the event.
245 // Set the enter key on the keyboard to create the shortcut when editing the URL.
246 urlEditText.setOnKeyListener((View view, int keyCode, KeyEvent keyEvent) -> {
247 // Check to see if the enter key was pressed.
248 if ((keyEvent.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
249 // Check the status of the create button.
250 if (createButton.isEnabled()) { // The create button is enabled.
251 // Create the home screen shortcut.
252 createHomeScreenShortcut(favoriteIconBitmap);
254 // Manually dismiss the alert dialog.
255 alertDialog.dismiss();
257 // Consume the event.
259 } else { // The create button is disabled.
260 // Do not consume the event.
263 } else { // Some other key was pressed.
264 // Do not consume the event.
269 // Return the alert dialog.
273 private void updateCreateButton(Button createButton) {
274 // Get the contents of the edit texts.
275 String shortcutName = shortcutNameEditText.getText().toString();
276 String urlString = urlEditText.getText().toString();
278 // Enable the create button if both the shortcut name and the URL are not empty.
279 createButton.setEnabled(!shortcutName.isEmpty() && !urlString.isEmpty());
282 private void createHomeScreenShortcut(Bitmap favoriteIconBitmap) {
283 // Get a handle for the context.
284 Context context = getContext();
286 // Remove the incorrect lint warning below that the context might be null.
287 assert context != null;
289 // Get the strings from the edit texts.
290 String shortcutName = shortcutNameEditText.getText().toString();
291 String urlString = urlEditText.getText().toString();
293 // Convert the favorite icon bitmap to an icon. `IconCompat` must be used until the minimum API >= 26.
294 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
296 // Create a shortcut intent.
297 Intent shortcutIntent = new Intent(Intent.ACTION_VIEW);
299 // Check to see if the shortcut should open up Privacy Browser explicitly.
300 if (openWithPrivacyBrowserRadioButton.isChecked()) {
301 // Set the current application ID as the target package.
302 shortcutIntent.setPackage(BuildConfig.APPLICATION_ID);
305 // Add the URL to the intent.
306 shortcutIntent.setData(Uri.parse(urlString));
308 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
309 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(context, shortcutName);
311 // Add the required fields to the shortcut info builder.
312 shortcutInfoBuilder.setIcon(favoriteIcon);
313 shortcutInfoBuilder.setIntent(shortcutIntent);
314 shortcutInfoBuilder.setShortLabel(shortcutName);
316 // Add the shortcut to the home screen. `ShortcutManagerCompat` can be switched to `ShortcutManager` once the minimum API >= 26.
317 ShortcutManagerCompat.requestPinShortcut(context, shortcutInfoBuilder.build(), null);