2 * Copyright © 2016-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.SharedPreferences;
28 import android.net.Uri;
29 import android.os.Bundle;
30 import android.preference.PreferenceManager;
31 import android.view.KeyEvent;
32 import android.view.View;
33 import android.view.WindowManager;
34 import android.widget.EditText;
35 import android.widget.TextView;
37 import androidx.annotation.NonNull;
38 import androidx.fragment.app.DialogFragment; // The AndroidX dialog fragment must be used or an error is produced on API <=22.
40 import com.stoutner.privacybrowser.R;
42 import java.util.Locale;
44 public class DownloadFileDialog extends DialogFragment {
45 // `downloadFileListener` is used in `onAttach()` and `onCreateDialog()`.
46 private DownloadFileListener downloadFileListener;
48 // The public interface is used to send information back to the parent activity.
49 public interface DownloadFileListener {
50 void onDownloadFile(DialogFragment dialogFragment, String downloadUrl);
54 public void onAttach(Context context) {
55 // Run the default commands.
56 super.onAttach(context);
58 // Get a handle for `DownloadFileListener` from the launching context.
59 downloadFileListener = (DownloadFileListener) context;
62 public static DownloadFileDialog fromUrl(String urlString, String contentDisposition, long contentLength) {
63 // Create an arguments bundle.
64 Bundle argumentsBundle = new Bundle();
66 // Create a variable for the file name string.
67 String fileNameString;
69 // Get the index of the end of `filename=` from the file name string.
70 int fileNameIndex = contentDisposition.indexOf("filename=") + 9;
72 // Parse the filename from `contentDisposition`.
73 if (contentDisposition.contains("filename=\"")) { // The file name is contained in a string surrounded by `""`.
74 fileNameString = contentDisposition.substring(contentDisposition.indexOf("filename=\"") + 10, contentDisposition.indexOf("\"", contentDisposition.indexOf("filename=\"") + 10));
75 } else if (contentDisposition.contains("filename=") && ((contentDisposition.indexOf(";", fileNameIndex)) > 0 )) {
76 // The file name is contained in a string beginning with `filename=` and ending with `;`.
77 fileNameString = contentDisposition.substring(fileNameIndex, contentDisposition.indexOf(";", fileNameIndex));
78 } else if (contentDisposition.contains("filename=")) { // The file name is contained in a string beginning with `filename=` and proceeding to the end of `contentDisposition`.
79 fileNameString = contentDisposition.substring(fileNameIndex);
80 } else { // `contentDisposition` does not contain the filename, so use the last path segment of the URL.
81 Uri downloadUri = Uri.parse(urlString);
82 fileNameString = downloadUri.getLastPathSegment();
85 // Store the variables in the bundle.
86 argumentsBundle.putString("URL", urlString);
87 argumentsBundle.putString("File_Name", fileNameString);
88 argumentsBundle.putLong("File_Size", contentLength);
90 // Add the arguments bundle to this instance of `DownloadFileDialog`.
91 DownloadFileDialog thisDownloadFileDialog = new DownloadFileDialog();
92 thisDownloadFileDialog.setArguments(argumentsBundle);
93 return thisDownloadFileDialog;
98 // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
99 @SuppressLint("InflateParams")
100 public Dialog onCreateDialog(Bundle savedInstanceState) {
101 // Remove the warning below that `getArguments()` might be null.
102 assert getArguments() != null;
104 // Store the variables from the bundle.
105 String downloadUrl = getArguments().getString("URL");
106 String downloadFileName = getArguments().getString("File_Name");
107 long fileSizeLong = getArguments().getLong("File_Size");
109 // Initialize the file size string.
112 // Convert `fileSizeLong` to a String.
113 if (fileSizeLong == -1) { // We don't know the file size.
114 fileSize = getString(R.string.unknown_size);
115 } else { // Convert `fileSize` to MB and store it in `fileSizeString`. `%.3g` displays the three most significant digits.
116 fileSize = String.format(Locale.getDefault(), "%.3g", (float) fileSizeLong / 1048576) + " MB";
119 // Get a handle for the shared preferences.
120 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
122 // Get the screenshot and theme preferences.
123 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
124 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
126 // Use an alert dialog builder to create the alert dialog.
127 AlertDialog.Builder dialogBuilder;
129 // Set the style according to the theme.
131 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
133 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
137 dialogBuilder.setTitle(R.string.save_as);
139 // Set the icon according to the theme.
141 dialogBuilder.setIcon(R.drawable.save_dialog_dark);
143 dialogBuilder.setIcon(R.drawable.save_dialog_light);
146 // Remove the warning below that `getActivity()` might be null;
147 assert getActivity() != null;
149 // Set the view. The parent view is `null` because it will be assigned by `AlertDialog`.
150 dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.download_file_dialog, null));
152 // Set an listener on the negative button.
153 dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
154 // Do nothing if `Cancel` is clicked. The `Dialog` will automatically close.
157 // Set an listener on the positive button
158 dialogBuilder.setPositiveButton(R.string.download, (DialogInterface dialog, int which) -> {
159 // trigger `onDownloadFile()` and return the `DialogFragment` and the download URL to the parent activity.
160 downloadFileListener.onDownloadFile(DownloadFileDialog.this, downloadUrl);
163 // Create an alert dialog from the alert dialog builder`.
164 final AlertDialog alertDialog = dialogBuilder.create();
166 // Remove the warning below that `getWindow()` might be null.
167 assert alertDialog.getWindow() != null;
169 // Disable screenshots if not allowed.
170 if (!allowScreenshots) {
171 alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
174 // Show the keyboard when alert dialog is displayed on the screen.
175 alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
177 // We need to show `alertDialog` before we can modify the contents.
180 // Set the text for `downloadFileSizeTextView`.
181 TextView downloadFileSizeTextView = alertDialog.findViewById(R.id.download_file_size);
182 downloadFileSizeTextView.setText(fileSize);
184 // Set the text for `downloadFileNameTextView`.
185 EditText downloadFileNameTextView = alertDialog.findViewById(R.id.download_file_name);
186 downloadFileNameTextView.setText(downloadFileName);
188 // Allow the `enter` key on the keyboard to save the file from `downloadFileNameTextView`.
189 downloadFileNameTextView.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
190 // If the event is an `ACTION_DOWN` on the `enter` key, initiate the download.
191 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
192 // trigger `onDownloadFile()` and return the `DialogFragment` and the URL to the parent activity.
193 downloadFileListener.onDownloadFile(DownloadFileDialog.this, downloadUrl);
195 // Manually dismiss the alert dialog.
196 alertDialog.dismiss();
198 // Consume the event.
200 } else { // If any other key was pressed, do not consume the event.
205 // `onCreateDialog` requires the return of an `AlertDialog`.