2 * Copyright 2016 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;
22 import android.annotation.SuppressLint;
23 import android.app.Dialog;
24 import android.content.Context;
25 import android.content.DialogInterface;
26 import android.net.Uri;
27 import android.os.Bundle;
28 import android.support.annotation.NonNull;
29 // `android.support.v7.app.AlertDialog` uses more of the horizontal screen real estate versus `android.app.AlertDialog's` smaller width.
30 import android.support.v7.app.AlertDialog;
31 // We have to use `AppCompatDialogFragment` instead of `DialogFragment` or an error is produced on API <=22.
32 import android.support.v7.app.AppCompatDialogFragment;
33 import android.view.KeyEvent;
34 import android.view.LayoutInflater;
35 import android.view.View;
36 import android.view.WindowManager;
37 import android.widget.EditText;
38 import android.widget.TextView;
40 import java.util.Locale;
42 public class DownloadFile extends AppCompatDialogFragment {
44 private String downloadUrl;
45 private String downloadFileName;
46 private String fileSize;
48 public static DownloadFile fromUrl(String urlString, String contentDisposition, long contentLength) {
49 // Create `argumentsBundle`.
50 Bundle argumentsBundle = new Bundle();
52 String fileNameString;
54 // Parse `filename` from `contentDisposition`.
55 if (contentDisposition.contains("filename=\"")) { // The file name is contained in a string surrounded by `""`.
56 fileNameString = contentDisposition.substring(contentDisposition.indexOf("filename=\"") + 10, contentDisposition.indexOf("\"", contentDisposition.indexOf("filename=\"") + 10));
57 } 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 `;`.
58 fileNameString = contentDisposition.substring(contentDisposition.indexOf("filename=") + 9, contentDisposition.indexOf(";", contentDisposition.indexOf("filename=") + 9));
59 } else if (contentDisposition.contains("filename=")) { // The file name is contained in a string beginning with `filename=` and proceeding to the end of `contentDisposition`.
60 fileNameString = contentDisposition.substring(contentDisposition.indexOf("filename=") + 9, contentDisposition.length());
61 } else { // `contentDisposition` does not contain the filename, so use the last path segment of the URL.
62 Uri downloadUri = Uri.parse(urlString);
63 fileNameString = downloadUri.getLastPathSegment();
66 // Store the variables in the `Bundle`.
67 argumentsBundle.putString("URL", urlString);
68 argumentsBundle.putString("File_Name", fileNameString);
69 argumentsBundle.putLong("File_Size", contentLength);
71 // Add `argumentsBundle` to this instance of `DownloadFile`.
72 DownloadFile thisDownloadFileDialog = new DownloadFile();
73 thisDownloadFileDialog.setArguments(argumentsBundle);
74 return thisDownloadFileDialog;
78 public void onCreate(Bundle savedInstanceState) {
79 super.onCreate(savedInstanceState);
81 // Store the strings in the local class variables.
82 downloadUrl = getArguments().getString("URL");
83 downloadFileName = getArguments().getString("File_Name");
85 // Get the `File_Size`.
86 long fileSizeLong = getArguments().getLong("File_Size");
88 // Convert `fileSizeLong` to a String.
89 if (fileSizeLong == -1) { // We don't know the file size.
90 fileSize = getString(R.string.unknown_size);
91 } else { // Convert `fileSize` to MB and store it in `fileSizeString`. `%.3g` displays the three most significant digits.
92 fileSize = String.format(Locale.getDefault(), "%.3g", (float) fileSizeLong / 1048576) + " MB";
96 // The public interface is used to send information back to the parent activity.
97 public interface DownloadFileListener {
98 void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl);
101 // `downloadFileListener` is used in `onAttach()` and `onCreateDialog()`.
102 private DownloadFileListener downloadFileListener;
105 public void onAttach(Context context) {
106 super.onAttach(context);
108 // Check to make sure the parent activity implements the listener.
110 downloadFileListener = (DownloadFileListener) context;
111 } catch (ClassCastException exception) {
112 throw new ClassCastException(context.toString() + " must implement DownloadFileListener.");
118 // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
119 @SuppressLint("InflateParams")
120 public Dialog onCreateDialog(Bundle savedInstanceState) {
121 // Get the activity's layout inflater.
122 LayoutInflater layoutInflater = getActivity().getLayoutInflater();
124 // Use `AlertDialog.Builder` to create the `AlertDialog`. `R.style.lightAlertDialog` formats the color of the button text.
125 AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.LightAlertDialog);
128 dialogBuilder.setTitle(R.string.save_as);
130 // Set the view. The parent view is `null` because it will be assigned by `AlertDialog`.
131 dialogBuilder.setView(layoutInflater.inflate(R.layout.download_file_dialog, null));
133 // Set an `onClick()` listener on the negative button.
134 dialogBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
136 public void onClick(DialogInterface dialog, int which) {
137 // Do nothing if `Cancel` is clicked. The `Dialog` will automatically close.
141 // Set an `onClick()` listener on the positive button
142 dialogBuilder.setPositiveButton(R.string.download, new DialogInterface.OnClickListener() {
144 public void onClick(DialogInterface dialog, int which) {
145 // trigger `onDownloadFile()` and return the `DialogFragment` and the download URL to the parent activity.
146 downloadFileListener.onDownloadFile(DownloadFile.this, downloadUrl);
150 // Create an `AlertDialog` from the `AlertDialog.Builder`.
151 final AlertDialog alertDialog = dialogBuilder.create();
153 // Remove the warning below that `setSoftInputMode` might produce `java.lang.NullPointerException`.
154 assert alertDialog.getWindow() != null;
156 // Show the keyboard when `alertDialog` is displayed on the screen.
157 alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
159 // We need to show `alertDialog` before we can modify the contents.
162 // Set the text for `downloadFileSizeTextView`.
163 TextView downloadFileSizeTextView = (TextView) alertDialog.findViewById(R.id.download_file_size);
164 assert downloadFileSizeTextView != null; // Remove the warning on the following line that `downloadFileSizeTextView` might be `null`.
165 downloadFileSizeTextView.setText(fileSize);
167 // Set the text for `downloadFileNameTextView`.
168 EditText downloadFileNameTextView = (EditText) alertDialog.findViewById(R.id.download_file_name);
169 assert downloadFileNameTextView != null; // Remove the warning on the following line that `downloadFileNameTextView` might be `null`.
170 downloadFileNameTextView.setText(downloadFileName);
172 // Allow the `enter` key on the keyboard to save the file from `downloadFileNameTextView`.
173 downloadFileNameTextView.setOnKeyListener(new View.OnKeyListener() {
175 public boolean onKey (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(DownloadFile.this, downloadUrl);
180 // Manually dismiss `alertDialog`.
181 alertDialog.dismiss();
182 // Consume the event.
184 } else { // If any other key was pressed, do not consume the event.
190 // `onCreateDialog` requires the return of an `AlertDialog`.