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.net.Uri;
28 import android.os.Bundle;
29 import android.view.KeyEvent;
30 import android.view.LayoutInflater;
31 import android.view.View;
32 import android.view.WindowManager;
33 import android.widget.EditText;
34 import android.widget.TextView;
36 import androidx.annotation.NonNull;
37 import androidx.fragment.app.DialogFragment; // The AndroidX dialog fragment must be used or an error is produced on API <=22.
39 import com.stoutner.privacybrowser.R;
40 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
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 // Parse the filename from `contentDisposition`.
70 if (contentDisposition.contains("filename=\"")) { // The file name is contained in a string surrounded by `""`.
71 fileNameString = contentDisposition.substring(contentDisposition.indexOf("filename=\"") + 10, contentDisposition.indexOf("\"", contentDisposition.indexOf("filename=\"") + 10));
72 } else if (contentDisposition.contains("filename=") && ((contentDisposition.indexOf(";", contentDisposition.indexOf("filename=") + 9)) > 0 )) {
73 // The file name is contained in a string beginning with `filename=` and ending with `;`.
74 fileNameString = contentDisposition.substring(contentDisposition.indexOf("filename=") + 9, contentDisposition.indexOf(";", contentDisposition.indexOf("filename=") + 9));
75 } else if (contentDisposition.contains("filename=")) { // The file name is contained in a string beginning with `filename=` and proceeding to the end of `contentDisposition`.
76 fileNameString = contentDisposition.substring(contentDisposition.indexOf("filename=") + 9);
77 } else { // `contentDisposition` does not contain the filename, so use the last path segment of the URL.
78 Uri downloadUri = Uri.parse(urlString);
79 fileNameString = downloadUri.getLastPathSegment();
82 // Store the variables in the bundle.
83 argumentsBundle.putString("URL", urlString);
84 argumentsBundle.putString("File_Name", fileNameString);
85 argumentsBundle.putLong("File_Size", contentLength);
87 // Add the arguments bundle to this instance of `DownloadFileDialog`.
88 DownloadFileDialog thisDownloadFileDialog = new DownloadFileDialog();
89 thisDownloadFileDialog.setArguments(argumentsBundle);
90 return thisDownloadFileDialog;
95 // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
96 @SuppressLint("InflateParams")
97 public Dialog onCreateDialog(Bundle savedInstanceState) {
98 // Remove the warning below that `getArguments()` might be null.
99 assert getArguments() != null;
101 // Store the variables from the bundle.
102 String downloadUrl = getArguments().getString("URL");
103 String downloadFileName = getArguments().getString("File_Name");
104 long fileSizeLong = getArguments().getLong("File_Size");
106 // Initialize the file size string.
109 // Convert `fileSizeLong` to a String.
110 if (fileSizeLong == -1) { // We don't know the file size.
111 fileSize = getString(R.string.unknown_size);
112 } else { // Convert `fileSize` to MB and store it in `fileSizeString`. `%.3g` displays the three most significant digits.
113 fileSize = String.format(Locale.getDefault(), "%.3g", (float) fileSizeLong / 1048576) + " MB";
116 // Remove the warning below that `getActivity()` might be null;
117 assert getActivity() != null;
119 // Get the activity's layout inflater.
120 LayoutInflater layoutInflater = getActivity().getLayoutInflater();
122 // Use an alert dialog builder to create the alert dialog.
123 AlertDialog.Builder dialogBuilder;
125 // Set the style according to the theme.
126 if (MainWebViewActivity.darkTheme) {
127 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
129 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
133 dialogBuilder.setTitle(R.string.save_as);
135 // Set the view. The parent view is `null` because it will be assigned by `AlertDialog`.
136 dialogBuilder.setView(layoutInflater.inflate(R.layout.download_file_dialog, null));
138 // Set an listener on the negative button.
139 dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
140 // Do nothing if `Cancel` is clicked. The `Dialog` will automatically close.
143 // Set an listener on the positive button
144 dialogBuilder.setPositiveButton(R.string.download, (DialogInterface dialog, int which) -> {
145 // trigger `onDownloadFile()` and return the `DialogFragment` and the download URL to the parent activity.
146 downloadFileListener.onDownloadFile(DownloadFileDialog.this, downloadUrl);
149 // Create an alert dialog from the alert dialog builder`.
150 final AlertDialog alertDialog = dialogBuilder.create();
152 // Remove the warning below that `getWindow()` might be null.
153 assert alertDialog.getWindow() != null;
155 // Disable screenshots if not allowed.
156 if (!MainWebViewActivity.allowScreenshots) {
157 alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
160 // Show the keyboard when alert dialog is displayed on the screen.
161 alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
163 // We need to show `alertDialog` before we can modify the contents.
166 // Set the text for `downloadFileSizeTextView`.
167 TextView downloadFileSizeTextView = alertDialog.findViewById(R.id.download_file_size);
168 downloadFileSizeTextView.setText(fileSize);
170 // Set the text for `downloadFileNameTextView`.
171 EditText downloadFileNameTextView = alertDialog.findViewById(R.id.download_file_name);
172 downloadFileNameTextView.setText(downloadFileName);
174 // Allow the `enter` key on the keyboard to save the file from `downloadFileNameTextView`.
175 downloadFileNameTextView.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
176 // If the event is an `ACTION_DOWN` on the `enter` key, initiate the download.
177 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
178 // trigger `onDownloadFile()` and return the `DialogFragment` and the URL to the parent activity.
179 downloadFileListener.onDownloadFile(DownloadFileDialog.this, downloadUrl);
181 // Manually dismiss the alert dialog.
182 alertDialog.dismiss();
184 // Consume the event.
186 } else { // If any other key was pressed, do not consume the event.
191 // `onCreateDialog` requires the return of an `AlertDialog`.