2 * Copyright © 2016-2017 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;
41 import java.util.Locale;
43 public class DownloadFileDialog extends AppCompatDialogFragment {
45 private String downloadUrl;
46 private String downloadFileName;
47 private String fileSize;
49 public static DownloadFileDialog fromUrl(String urlString, String contentDisposition, long contentLength) {
50 // Create `argumentsBundle`.
51 Bundle argumentsBundle = new Bundle();
53 String fileNameString;
55 // Parse `filename` from `contentDisposition`.
56 if (contentDisposition.contains("filename=\"")) { // The file name is contained in a string surrounded by `""`.
57 fileNameString = contentDisposition.substring(contentDisposition.indexOf("filename=\"") + 10, contentDisposition.indexOf("\"", contentDisposition.indexOf("filename=\"") + 10));
58 } 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 `;`.
59 fileNameString = contentDisposition.substring(contentDisposition.indexOf("filename=") + 9, contentDisposition.indexOf(";", contentDisposition.indexOf("filename=") + 9));
60 } else if (contentDisposition.contains("filename=")) { // The file name is contained in a string beginning with `filename=` and proceeding to the end of `contentDisposition`.
61 fileNameString = contentDisposition.substring(contentDisposition.indexOf("filename=") + 9, contentDisposition.length());
62 } else { // `contentDisposition` does not contain the filename, so use the last path segment of the URL.
63 Uri downloadUri = Uri.parse(urlString);
64 fileNameString = downloadUri.getLastPathSegment();
67 // Store the variables in the `Bundle`.
68 argumentsBundle.putString("URL", urlString);
69 argumentsBundle.putString("File_Name", fileNameString);
70 argumentsBundle.putLong("File_Size", contentLength);
72 // Add `argumentsBundle` to this instance of `DownloadFileDialog`.
73 DownloadFileDialog thisDownloadFileDialog = new DownloadFileDialog();
74 thisDownloadFileDialog.setArguments(argumentsBundle);
75 return thisDownloadFileDialog;
79 public void onCreate(Bundle savedInstanceState) {
80 super.onCreate(savedInstanceState);
82 // Store the strings in the local class variables.
83 downloadUrl = getArguments().getString("URL");
84 downloadFileName = getArguments().getString("File_Name");
86 // Get the `File_Size`.
87 long fileSizeLong = getArguments().getLong("File_Size");
89 // Convert `fileSizeLong` to a String.
90 if (fileSizeLong == -1) { // We don't know the file size.
91 fileSize = getString(R.string.unknown_size);
92 } else { // Convert `fileSize` to MB and store it in `fileSizeString`. `%.3g` displays the three most significant digits.
93 fileSize = String.format(Locale.getDefault(), "%.3g", (float) fileSizeLong / 1048576) + " MB";
97 // The public interface is used to send information back to the parent activity.
98 public interface DownloadFileListener {
99 void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl);
102 // `downloadFileListener` is used in `onAttach()` and `onCreateDialog()`.
103 private DownloadFileListener downloadFileListener;
106 public void onAttach(Context context) {
107 super.onAttach(context);
109 // Check to make sure the parent activity implements the listener.
111 downloadFileListener = (DownloadFileListener) context;
112 } catch (ClassCastException exception) {
113 throw new ClassCastException(context.toString() + " must implement DownloadFileListener.");
119 // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
120 @SuppressLint("InflateParams")
121 public Dialog onCreateDialog(Bundle savedInstanceState) {
122 // Get the activity's layout inflater.
123 LayoutInflater layoutInflater = getActivity().getLayoutInflater();
125 // Use `AlertDialog.Builder` to create the `AlertDialog`. `R.style.lightAlertDialog` formats the color of the button text.
126 AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.LightAlertDialog);
129 dialogBuilder.setTitle(R.string.save_as);
131 // Set the view. The parent view is `null` because it will be assigned by `AlertDialog`.
132 dialogBuilder.setView(layoutInflater.inflate(R.layout.download_file_dialog, null));
134 // Set an `onClick()` listener on the negative button.
135 dialogBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
137 public void onClick(DialogInterface dialog, int which) {
138 // Do nothing if `Cancel` is clicked. The `Dialog` will automatically close.
142 // Set an `onClick()` listener on the positive button
143 dialogBuilder.setPositiveButton(R.string.download, new DialogInterface.OnClickListener() {
145 public void onClick(DialogInterface dialog, int which) {
146 // trigger `onDownloadFile()` and return the `DialogFragment` and the download URL to the parent activity.
147 downloadFileListener.onDownloadFile(DownloadFileDialog.this, downloadUrl);
151 // Create an `AlertDialog` from the `AlertDialog.Builder`.
152 final AlertDialog alertDialog = dialogBuilder.create();
154 // Remove the warning below that `setSoftInputMode` might produce `java.lang.NullPointerException`.
155 assert alertDialog.getWindow() != null;
157 // Show the keyboard when `alertDialog` is displayed on the screen.
158 alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
160 // We need to show `alertDialog` before we can modify the contents.
163 // Set the text for `downloadFileSizeTextView`.
164 TextView downloadFileSizeTextView = (TextView) alertDialog.findViewById(R.id.download_file_size);
165 downloadFileSizeTextView.setText(fileSize);
167 // Set the text for `downloadFileNameTextView`.
168 EditText downloadFileNameTextView = (EditText) alertDialog.findViewById(R.id.download_file_name);
169 downloadFileNameTextView.setText(downloadFileName);
171 // Allow the `enter` key on the keyboard to save the file from `downloadFileNameTextView`.
172 downloadFileNameTextView.setOnKeyListener(new View.OnKeyListener() {
174 public boolean onKey (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);
179 // Manually dismiss `alertDialog`.
180 alertDialog.dismiss();
181 // Consume the event.
183 } else { // If any other key was pressed, do not consume the event.
189 // `onCreateDialog` requires the return of an `AlertDialog`.