2 * Copyright © 2016-2018 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.support.annotation.NonNull;
30 // We have to use `AppCompatDialogFragment` instead of `DialogFragment` or an error is produced on API <=22.
31 import android.support.v7.app.AppCompatDialogFragment;
32 import android.view.KeyEvent;
33 import android.view.LayoutInflater;
34 import android.view.View;
35 import android.view.WindowManager;
36 import android.widget.EditText;
37 import android.widget.TextView;
39 import com.stoutner.privacybrowser.R;
40 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
42 import java.util.Locale;
44 public class DownloadFileDialog extends AppCompatDialogFragment {
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(AppCompatDialogFragment 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 `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 )) { // The file name is contained in a string beginning with `filename=` and ending with `;`.
73 fileNameString = contentDisposition.substring(contentDisposition.indexOf("filename=") + 9, contentDisposition.indexOf(";", contentDisposition.indexOf("filename=") + 9));
74 } else if (contentDisposition.contains("filename=")) { // The file name is contained in a string beginning with `filename=` and proceeding to the end of `contentDisposition`.
75 fileNameString = contentDisposition.substring(contentDisposition.indexOf("filename=") + 9, contentDisposition.length());
76 } else { // `contentDisposition` does not contain the filename, so use the last path segment of the URL.
77 Uri downloadUri = Uri.parse(urlString);
78 fileNameString = downloadUri.getLastPathSegment();
81 // Store the variables in the bundle.
82 argumentsBundle.putString("URL", urlString);
83 argumentsBundle.putString("File_Name", fileNameString);
84 argumentsBundle.putLong("File_Size", contentLength);
86 // Add the arguments bundle to this instance of `DownloadFileDialog`.
87 DownloadFileDialog thisDownloadFileDialog = new DownloadFileDialog();
88 thisDownloadFileDialog.setArguments(argumentsBundle);
89 return thisDownloadFileDialog;
94 // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
95 @SuppressLint("InflateParams")
96 public Dialog onCreateDialog(Bundle savedInstanceState) {
97 // Remove the warning below that `getArguments()` might be null.
98 assert getArguments() != null;
100 // Store the variables from the bundle.
101 String downloadUrl = getArguments().getString("URL");
102 String downloadFileName = getArguments().getString("File_Name");
103 long fileSizeLong = getArguments().getLong("File_Size");
105 // Initialize the file size string.
108 // Convert `fileSizeLong` to a String.
109 if (fileSizeLong == -1) { // We don't know the file size.
110 fileSize = getString(R.string.unknown_size);
111 } else { // Convert `fileSize` to MB and store it in `fileSizeString`. `%.3g` displays the three most significant digits.
112 fileSize = String.format(Locale.getDefault(), "%.3g", (float) fileSizeLong / 1048576) + " MB";
115 // Remove the warning below that `getActivity()` might be null;
116 assert getActivity() != null;
118 // Get the activity's layout inflater.
119 LayoutInflater layoutInflater = getActivity().getLayoutInflater();
121 // Use an alert dialog builder to create the alert dialog.
122 AlertDialog.Builder dialogBuilder;
124 // Set the style according to the theme.
125 if (MainWebViewActivity.darkTheme) {
126 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
128 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
132 dialogBuilder.setTitle(R.string.save_as);
134 // Set the view. The parent view is `null` because it will be assigned by `AlertDialog`.
135 dialogBuilder.setView(layoutInflater.inflate(R.layout.download_file_dialog, null));
137 // Set an listener on the negative button.
138 dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
139 // Do nothing if `Cancel` is clicked. The `Dialog` will automatically close.
142 // Set an listener on the positive button
143 dialogBuilder.setPositiveButton(R.string.download, (DialogInterface dialog, int which) -> {
144 // trigger `onDownloadFile()` and return the `DialogFragment` and the download URL to the parent activity.
145 downloadFileListener.onDownloadFile(DownloadFileDialog.this, downloadUrl);
148 // Create an alert dialog from the alert dialog builder`.
149 final AlertDialog alertDialog = dialogBuilder.create();
151 // Remove the warning below that `getWindow()` might be null.
152 assert alertDialog.getWindow() != null;
154 // Disable screenshots if not allowed.
155 if (!MainWebViewActivity.allowScreenshots) {
156 alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
159 // Show the keyboard when alert dialog is displayed on the screen.
160 alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
162 // We need to show `alertDialog` before we can modify the contents.
165 // Set the text for `downloadFileSizeTextView`.
166 TextView downloadFileSizeTextView = alertDialog.findViewById(R.id.download_file_size);
167 downloadFileSizeTextView.setText(fileSize);
169 // Set the text for `downloadFileNameTextView`.
170 EditText downloadFileNameTextView = alertDialog.findViewById(R.id.download_file_name);
171 downloadFileNameTextView.setText(downloadFileName);
173 // Allow the `enter` key on the keyboard to save the file from `downloadFileNameTextView`.
174 downloadFileNameTextView.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
175 // If the event is an `ACTION_DOWN` on the `enter` key, initiate the download.
176 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
177 // trigger `onDownloadFile()` and return the `DialogFragment` and the URL to the parent activity.
178 downloadFileListener.onDownloadFile(DownloadFileDialog.this, downloadUrl);
180 // Manually dismiss the alert dialog.
181 alertDialog.dismiss();
183 // Consume the event.
185 } else { // If any other key was pressed, do not consume the event.
190 // `onCreateDialog` requires the return of an `AlertDialog`.