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.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;
43 import androidx.annotation.NonNull;
44 // `ShortcutInfoCompat`, `ShortcutManagerCompat`, and `IconCompat` can be switched to the non-compat versions once API >= 26.
45 import androidx.core.content.pm.ShortcutInfoCompat;
46 import androidx.core.content.pm.ShortcutManagerCompat;
47 import androidx.core.graphics.drawable.IconCompat;
48 import androidx.fragment.app.DialogFragment; // The AndroidX dialog fragment must be used or an error is produced on API <=22.
50 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
51 import com.stoutner.privacybrowser.R;
53 import java.io.ByteArrayOutputStream;
55 public class CreateHomeScreenShortcutDialog extends DialogFragment {
56 // Create the class variables.
57 private String initialShortcutName;
58 private String initialUrlString;
59 private Bitmap favoriteIconBitmap;
60 private EditText shortcutNameEditText;
61 private EditText urlEditText;
62 private Button createButton;
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();
75 Bundle bundle = new Bundle();
77 // Store the variables in the bundle.
78 bundle.putString("shortcut_name", shortcutName);
79 bundle.putString("url_string", urlString);
80 bundle.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(bundle);
88 // Return the new dialog.
89 return createHomeScreenShortcutDialog;
93 public void onCreate(Bundle savedInstanceState) {
94 // Run the default commands.
95 super.onCreate(savedInstanceState);
98 Bundle arguments = getArguments();
100 // Remove the incorrect lint warning that the arguments might be null.
101 assert arguments != null;
103 // Store the strings in class variables.
104 initialShortcutName = arguments.getString("shortcut_name");
105 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 favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
117 // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
118 @SuppressLint("InflateParams")
121 public Dialog onCreateDialog(Bundle savedInstanceState) {
122 // Remove the incorrect lint warning below that `getLayoutInflater()` might be null.
123 assert getActivity() != null;
125 // Get the activity's layout inflater.
126 LayoutInflater layoutInflater = getActivity().getLayoutInflater();
128 // Create a drawable version of the favorite icon.
129 Drawable favoriteIconDrawable = new BitmapDrawable(getResources(), favoriteIconBitmap);
131 // Use a builder to create the alert dialog.
132 AlertDialog.Builder dialogBuilder;
134 // Set the style according to the theme.
135 if (MainWebViewActivity.darkTheme) {
136 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
138 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
141 // Set the title and icon.
142 dialogBuilder.setTitle(R.string.create_shortcut);
143 dialogBuilder.setIcon(favoriteIconDrawable);
145 // Set the view. The parent view is null because it will be assigned by the alert dialog.
146 dialogBuilder.setView(layoutInflater.inflate(R.layout.create_home_screen_shortcut_dialog, null));
148 // Setup the close button. Using null closes the dialog without doing anything else.
149 dialogBuilder.setNegativeButton(R.string.cancel, null);
151 // Set an `onClick` listener on the create button.
152 dialogBuilder.setPositiveButton(R.string.create, (DialogInterface dialog, int which) -> {
153 // Create the home screen shortcut.
154 createHomeScreenShortcut();
157 // Create an alert dialog from the alert dialog builder.
158 final AlertDialog alertDialog = dialogBuilder.create();
160 // Remove the warning below that `getWindow()` might be null.
161 assert alertDialog.getWindow() != null;
163 // Disable screenshots if not allowed.
164 if (!MainWebViewActivity.allowScreenshots) {
165 alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
168 // The alert dialog must be shown before the contents may be edited.
171 // Get a handle for the edit texts.
172 shortcutNameEditText = alertDialog.findViewById(R.id.shortcut_name_edittext);
173 urlEditText = alertDialog.findViewById(R.id.url_edittext);
175 // Populate the edit texts.
176 shortcutNameEditText.setText(initialShortcutName);
177 urlEditText.setText(initialUrlString);
179 // Get a handle for the create button.
180 createButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
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();
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();
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();
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();
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() {
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() {
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 // Setup the shortcut intent.
296 Intent shortcutIntent = new Intent(Intent.ACTION_VIEW);
297 shortcutIntent.setData(Uri.parse(urlString));
299 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
300 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(context, shortcutName);
302 // Add the required fields to the shortcut info builder.
303 shortcutInfoBuilder.setIcon(favoriteIcon);
304 shortcutInfoBuilder.setIntent(shortcutIntent);
305 shortcutInfoBuilder.setShortLabel(shortcutName);
307 // Add the shortcut to the home screen. `ShortcutManagerCompat` can be switched to `ShortcutManager` once the minimum API >= 26.
308 ShortcutManagerCompat.requestPinShortcut(context, shortcutInfoBuilder.build(), null);