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 // 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;
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();
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);
75 // Convert the byte array output stream to a byte array.
76 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
79 Bundle bundle = new Bundle();
81 // Store the variables in the bundle.
82 bundle.putString("shortcut_name", shortcutName);
83 bundle.putString("url_string", urlString);
84 bundle.putByteArray("favorite_icon_byte_array", favoriteIconByteArray);
86 // Create a new instance of the dialog.
87 CreateHomeScreenShortcutDialog createHomeScreenShortcutDialog = new CreateHomeScreenShortcutDialog();
89 // Add the bundle to the dialog.
90 createHomeScreenShortcutDialog.setArguments(bundle);
92 // Return the new dialog.
93 return createHomeScreenShortcutDialog;
97 public void onCreate(Bundle savedInstanceState) {
98 // Run the default commands.
99 super.onCreate(savedInstanceState);
101 // Get the arguments.
102 Bundle arguments = getArguments();
104 // Remove the incorrect lint warning below that the arguments might be null.
105 assert arguments != null;
107 // Store the strings in class variables.
108 initialShortcutName = arguments.getString("shortcut_name");
109 initialUrlString = arguments.getString("url_string");
111 // Get the favorite icon byte array.
112 byte[] favoriteIconByteArray = arguments.getByteArray("favorite_icon_byte_array");
114 // Remove the incorrect lint warning below that the favorite icon byte array might be null.
115 assert favoriteIconByteArray != null;
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);
121 // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
122 @SuppressLint("InflateParams")
125 public Dialog onCreateDialog(Bundle savedInstanceState) {
126 // Get a handle for the shared preferences.
127 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
129 // Get the theme and screenshot preferences.
130 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
131 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
133 // Remove the incorrect lint warning below that the layout inflater might be null.
134 assert getActivity() != null;
136 // Get the activity's layout inflater.
137 LayoutInflater layoutInflater = getActivity().getLayoutInflater();
139 // Create a drawable version of the favorite icon.
140 Drawable favoriteIconDrawable = new BitmapDrawable(getResources(), favoriteIconBitmap);
142 // Use a builder to create the alert dialog.
143 AlertDialog.Builder dialogBuilder;
145 // Set the style according to the theme.
147 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
149 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
152 // Set the title and icon.
153 dialogBuilder.setTitle(R.string.create_shortcut);
154 dialogBuilder.setIcon(favoriteIconDrawable);
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));
159 // Setup the close button. Using null closes the dialog without doing anything else.
160 dialogBuilder.setNegativeButton(R.string.cancel, null);
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();
168 // Create an alert dialog from the alert dialog builder.
169 final AlertDialog alertDialog = dialogBuilder.create();
171 // Remove the warning below that `getWindow()` might be null.
172 assert alertDialog.getWindow() != null;
174 // Disable screenshots if not allowed.
175 if (allowScreenshots) {
176 alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
179 // The alert dialog must be shown before the contents may be edited.
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);
188 // Populate the edit texts.
189 shortcutNameEditText.setText(initialShortcutName);
190 urlEditText.setText(initialUrlString);
192 // Add a text change listener to the shortcut name edit text.
193 shortcutNameEditText.addTextChangedListener(new TextWatcher() {
195 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
200 public void onTextChanged(CharSequence s, int start, int before, int count) {
205 public void afterTextChanged(Editable s) {
206 // Update the create button.
207 updateCreateButton();
211 // Add a text change listener to the URL edit text.
212 urlEditText.addTextChangedListener(new TextWatcher() {
214 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
219 public void onTextChanged(CharSequence s, int start, int before, int count) {
224 public void afterTextChanged(Editable s) {
225 // Update the create button.
226 updateCreateButton();
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();
239 // Manually dismiss the alert dialog.
240 alertDialog.dismiss();
242 // Consume the event.
244 } else { // The create button is disabled.
245 // Do not consume the event.
248 } else { // Some other key was pressed.
249 // Do not consume the event.
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();
263 // Manually dismiss the alert dialog.
264 alertDialog.dismiss();
266 // Consume the event.
268 } else { // The create button is disabled.
269 // Do not consume the event.
272 } else { // Some other key was pressed.
273 // Do not consume the event.
278 // Return the alert dialog.
282 private void updateCreateButton() {
283 // Get the contents of the edit texts.
284 String shortcutName = shortcutNameEditText.getText().toString();
285 String urlString = urlEditText.getText().toString();
287 // Enable the create button if both the shortcut name and the URL are not empty.
288 createButton.setEnabled(!shortcutName.isEmpty() && !urlString.isEmpty());
291 private void createHomeScreenShortcut() {
292 // Get a handle for the context.
293 Context context = getContext();
295 // Remove the incorrect lint warning below that the context might be null.
296 assert context != null;
298 // Get the strings from the edit texts.
299 String shortcutName = shortcutNameEditText.getText().toString();
300 String urlString = urlEditText.getText().toString();
302 // Convert the favorite icon bitmap to an icon. `IconCompat` must be used until the minimum API >= 26.
303 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
305 // Create a shortcut intent.
306 Intent shortcutIntent = new Intent(Intent.ACTION_VIEW);
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);
314 // Add the URL to the intent.
315 shortcutIntent.setData(Uri.parse(urlString));
317 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
318 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(context, shortcutName);
320 // Add the required fields to the shortcut info builder.
321 shortcutInfoBuilder.setIcon(favoriteIcon);
322 shortcutInfoBuilder.setIntent(shortcutIntent);
323 shortcutInfoBuilder.setShortLabel(shortcutName);
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);