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;
42 import android.widget.RadioButton;
44 import androidx.annotation.NonNull;
45 // `ShortcutInfoCompat`, `ShortcutManagerCompat`, and `IconCompat` can be switched to the non-compat versions once the minimum API >= 26.
46 import androidx.core.content.pm.ShortcutInfoCompat;
47 import androidx.core.content.pm.ShortcutManagerCompat;
48 import androidx.core.graphics.drawable.IconCompat;
49 import androidx.fragment.app.DialogFragment; // The AndroidX dialog fragment must be used or an error is produced on API <=22.
51 import com.stoutner.privacybrowser.BuildConfig;
52 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
53 import com.stoutner.privacybrowser.R;
55 import java.io.ByteArrayOutputStream;
57 public class CreateHomeScreenShortcutDialog extends DialogFragment {
58 // Create the class variables.
59 private String initialShortcutName;
60 private String initialUrlString;
61 private Bitmap favoriteIconBitmap;
62 private EditText shortcutNameEditText;
63 private EditText urlEditText;
64 private RadioButton openWithPrivacyBrowserRadioButton;
65 private Button createButton;
67 public static CreateHomeScreenShortcutDialog createDialog(String shortcutName, String urlString, Bitmap favoriteIconBitmap) {
68 // Create a favorite icon byte array output stream.
69 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
71 // 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).
72 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
74 // Convert the byte array output stream to a byte array.
75 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
78 Bundle bundle = new Bundle();
80 // Store the variables in the bundle.
81 bundle.putString("shortcut_name", shortcutName);
82 bundle.putString("url_string", urlString);
83 bundle.putByteArray("favorite_icon_byte_array", favoriteIconByteArray);
85 // Create a new instance of the dialog.
86 CreateHomeScreenShortcutDialog createHomeScreenShortcutDialog = new CreateHomeScreenShortcutDialog();
88 // Add the bundle to the dialog.
89 createHomeScreenShortcutDialog.setArguments(bundle);
91 // Return the new dialog.
92 return createHomeScreenShortcutDialog;
96 public void onCreate(Bundle savedInstanceState) {
97 // Run the default commands.
98 super.onCreate(savedInstanceState);
100 // Get the arguments.
101 Bundle arguments = getArguments();
103 // Remove the incorrect lint warning that the arguments might be null.
104 assert arguments != null;
106 // Store the strings in class variables.
107 initialShortcutName = arguments.getString("shortcut_name");
108 initialUrlString = arguments.getString("url_string");
110 // Get the favorite icon byte array.
111 byte[] favoriteIconByteArray = arguments.getByteArray("favorite_icon_byte_array");
113 // Remove the incorrect lint warning below that the favorite icon byte array might be null.
114 assert favoriteIconByteArray != null;
116 // Convert the favorite icon byte array to a bitmap and store it in a class variable.
117 favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
120 // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
121 @SuppressLint("InflateParams")
124 public Dialog onCreateDialog(Bundle savedInstanceState) {
125 // Remove the incorrect lint warning below that `getLayoutInflater()` might be null.
126 assert getActivity() != null;
128 // Get the activity's layout inflater.
129 LayoutInflater layoutInflater = getActivity().getLayoutInflater();
131 // Create a drawable version of the favorite icon.
132 Drawable favoriteIconDrawable = new BitmapDrawable(getResources(), favoriteIconBitmap);
134 // Use a builder to create the alert dialog.
135 AlertDialog.Builder dialogBuilder;
137 // Set the style according to the theme.
138 if (MainWebViewActivity.darkTheme) {
139 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
141 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
144 // Set the title and icon.
145 dialogBuilder.setTitle(R.string.create_shortcut);
146 dialogBuilder.setIcon(favoriteIconDrawable);
148 // Set the view. The parent view is null because it will be assigned by the alert dialog.
149 dialogBuilder.setView(layoutInflater.inflate(R.layout.create_home_screen_shortcut_dialog, null));
151 // Setup the close button. Using null closes the dialog without doing anything else.
152 dialogBuilder.setNegativeButton(R.string.cancel, null);
154 // Set an `onClick` listener on the create button.
155 dialogBuilder.setPositiveButton(R.string.create, (DialogInterface dialog, int which) -> {
156 // Create the home screen shortcut.
157 createHomeScreenShortcut();
160 // Create an alert dialog from the alert dialog builder.
161 final AlertDialog alertDialog = dialogBuilder.create();
163 // Remove the warning below that `getWindow()` might be null.
164 assert alertDialog.getWindow() != null;
166 // Disable screenshots if not allowed.
167 if (!MainWebViewActivity.allowScreenshots) {
168 alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
171 // The alert dialog must be shown before the contents may be edited.
174 // Get handles for the views.
175 shortcutNameEditText = alertDialog.findViewById(R.id.shortcut_name_edittext);
176 urlEditText = alertDialog.findViewById(R.id.url_edittext);
177 openWithPrivacyBrowserRadioButton = alertDialog.findViewById(R.id.open_with_privacy_browser_radiobutton);
178 createButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
180 // Populate the edit texts.
181 shortcutNameEditText.setText(initialShortcutName);
182 urlEditText.setText(initialUrlString);
184 // Add a text change listener to the shortcut name edit text.
185 shortcutNameEditText.addTextChangedListener(new TextWatcher() {
187 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
192 public void onTextChanged(CharSequence s, int start, int before, int count) {
197 public void afterTextChanged(Editable s) {
198 // Update the create button.
199 updateCreateButton();
203 // Add a text change listener to the URL edit text.
204 urlEditText.addTextChangedListener(new TextWatcher() {
206 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
211 public void onTextChanged(CharSequence s, int start, int before, int count) {
216 public void afterTextChanged(Editable s) {
217 // Update the create button.
218 updateCreateButton();
222 // Allow the enter key on the keyboard to create the shortcut when editing the name.
223 shortcutNameEditText.setOnKeyListener((View view, int keyCode, KeyEvent keyEvent) -> {
224 // Check to see if the enter key was pressed.
225 if ((keyEvent.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
226 // Check the status of the create button.
227 if (createButton.isEnabled()) { // The create button is enabled.
228 // Create the home screen shortcut.
229 createHomeScreenShortcut();
231 // Manually dismiss the alert dialog.
232 alertDialog.dismiss();
234 // Consume the event.
236 } else { // The create button is disabled.
237 // Do not consume the event.
240 } else { // Some other key was pressed.
241 // Do not consume the event.
246 // Set the enter key on the keyboard to create the shortcut when editing the URL.
247 urlEditText.setOnKeyListener((View view, int keyCode, KeyEvent keyEvent) -> {
248 // Check to see if the enter key was pressed.
249 if ((keyEvent.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
250 // Check the status of the create button.
251 if (createButton.isEnabled()) { // The create button is enabled.
252 // Create the home screen shortcut.
253 createHomeScreenShortcut();
255 // Manually dismiss the alert dialog.
256 alertDialog.dismiss();
258 // Consume the event.
260 } else { // The create button is disabled.
261 // Do not consume the event.
264 } else { // Some other key was pressed.
265 // Do not consume the event.
270 // Return the alert dialog.
274 private void updateCreateButton() {
275 // Get the contents of the edit texts.
276 String shortcutName = shortcutNameEditText.getText().toString();
277 String urlString = urlEditText.getText().toString();
279 // Enable the create button if both the shortcut name and the URL are not empty.
280 createButton.setEnabled(!shortcutName.isEmpty() && !urlString.isEmpty());
283 private void createHomeScreenShortcut() {
284 // Get a handle for the context.
285 Context context = getContext();
287 // Remove the incorrect lint warning below that the context might be null.
288 assert context != null;
290 // Get the strings from the edit texts.
291 String shortcutName = shortcutNameEditText.getText().toString();
292 String urlString = urlEditText.getText().toString();
294 // Convert the favorite icon bitmap to an icon. `IconCompat` must be used until the minimum API >= 26.
295 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
297 // Create a shortcut intent.
298 Intent shortcutIntent = new Intent(Intent.ACTION_VIEW);
300 // Check to see if the shortcut should open up Privacy Browser explicitly.
301 if (openWithPrivacyBrowserRadioButton.isChecked()) {
302 // Set the current application ID as the target package.
303 shortcutIntent.setPackage(BuildConfig.APPLICATION_ID);
306 // Add the URL to the intent.
307 shortcutIntent.setData(Uri.parse(urlString));
309 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
310 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(context, shortcutName);
312 // Add the required fields to the shortcut info builder.
313 shortcutInfoBuilder.setIcon(favoriteIcon);
314 shortcutInfoBuilder.setIntent(shortcutIntent);
315 shortcutInfoBuilder.setShortLabel(shortcutName);
317 // Add the shortcut to the home screen. `ShortcutManagerCompat` can be switched to `ShortcutManager` once the minimum API >= 26.
318 ShortcutManagerCompat.requestPinShortcut(context, shortcutInfoBuilder.build(), null);