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;
53 if (!contentDisposition.isEmpty()) { // Extract `fileNameString` from `contentDisposition` using the substring beginning after `filename="` and ending with the next `"`.
54 fileNameString = contentDisposition.substring(contentDisposition.indexOf("filename=\"") + 10, contentDisposition.indexOf("\"", contentDisposition.indexOf("filename=\"") + 10));
55 } else { // `contentDisposition` is empty, so use the last path segment of the URL as the file name.
56 Uri downloadUri = Uri.parse(urlString);
57 fileNameString = downloadUri.getLastPathSegment();
60 // Store the variables in the `Bundle`.
61 argumentsBundle.putString("URL", urlString);
62 argumentsBundle.putString("File_Name", fileNameString);
63 argumentsBundle.putLong("File_Size", contentLength);
65 // Add `argumentsBundle` to this instance of `DownloadFile`.
66 DownloadFile thisDownloadFileDialog = new DownloadFile();
67 thisDownloadFileDialog.setArguments(argumentsBundle);
68 return thisDownloadFileDialog;
72 public void onCreate(Bundle savedInstanceState) {
73 super.onCreate(savedInstanceState);
75 // Store the strings in the local class variables.
76 downloadUrl = getArguments().getString("URL");
77 downloadFileName = getArguments().getString("File_Name");
79 // Get the `File_Size`.
80 long fileSizeLong = getArguments().getLong("File_Size");
82 // Convert `fileSizeLong` to a String.
83 if (fileSizeLong == -1) { // We don't know the file size.
84 fileSize = getString(R.string.unknown_size);
85 } else { // Convert `fileSize` to MB and store it in `fileSizeString`. `%.3g` displays the three most significant digits.
86 fileSize = String.format(Locale.getDefault(), "%.3g", (float) fileSizeLong / 1048576) + " MB";
90 // The public interface is used to send information back to the parent activity.
91 public interface DownloadFileListener {
92 void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl);
95 // `downloadFileListener` is used in `onAttach()` and `onCreateDialog()`.
96 private DownloadFileListener downloadFileListener;
98 // Check to make sure tha the parent activity implements the listener.
100 public void onAttach(Context context) {
101 super.onAttach(context);
103 downloadFileListener = (DownloadFileListener) context;
104 } catch (ClassCastException exception) {
105 throw new ClassCastException(context.toString() + " must implement DownloadFileListener.");
109 // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
110 @SuppressLint("InflateParams")
113 public Dialog onCreateDialog(Bundle savedInstanceState) {
114 // Get the activity's layout inflater.
115 LayoutInflater layoutInflater = getActivity().getLayoutInflater();
117 // Use `AlertDialog.Builder` to create the `AlertDialog`. `R.style.lightAlertDialog` formats the color of the button text.
118 AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.LightAlertDialog);
119 dialogBuilder.setTitle(R.string.save_as);
120 // The parent view is `null` because it will be assigned by `AlertDialog`.
121 dialogBuilder.setView(layoutInflater.inflate(R.layout.download_file_dialog, null));
123 // Set an `onClick()` listener on the negative button.
124 dialogBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
126 public void onClick(DialogInterface dialog, int which) {
127 // Do nothing if `Cancel` is clicked.
131 // Set an `onClick()` listener on the positive button
132 dialogBuilder.setPositiveButton(R.string.download, new DialogInterface.OnClickListener() {
134 public void onClick(DialogInterface dialog, int which) {
135 // trigger `onDownloadFile()` and return the `DialogFragment` and the download URL to the parent activity.
136 downloadFileListener.onDownloadFile(DownloadFile.this, downloadUrl);
141 // Create an `AlertDialog` from the `AlertDialog.Builder`.
142 final AlertDialog alertDialog = dialogBuilder.create();
144 // Remove the warning below that `setSoftInputMode` might produce `java.lang.NullPointerException`.
145 assert alertDialog.getWindow() != null;
147 // Show the keyboard when `alertDialog` is displayed on the screen.
148 alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
150 // We need to show `alertDialog` before we can modify the contents.
153 // Set the text for `downloadFileSizeTextView`.
154 TextView downloadFileSizeTextView = (TextView) alertDialog.findViewById(R.id.download_file_size);
155 assert downloadFileSizeTextView != null; // Remove the warning on the following line that `downloadFileSizeTextView` might be `null`.
156 downloadFileSizeTextView.setText(fileSize);
158 // Set the text for `downloadFileNameTextView`.
159 EditText downloadFileNameTextView = (EditText) alertDialog.findViewById(R.id.download_file_name);
160 assert downloadFileNameTextView != null; // Remove the warning on the following line that `downloadFileNameTextView` might be `null`.
161 downloadFileNameTextView.setText(downloadFileName);
163 // Allow the `enter` key on the keyboard to save the file from `downloadFileNameTextView`.
164 downloadFileNameTextView.setOnKeyListener(new View.OnKeyListener() {
166 public boolean onKey (View v, int keyCode, KeyEvent event) {
167 // If the event is an `ACTION_DOWN` on the `enter` key, initiate the download.
168 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
169 // trigger `onDownloadFile()` and return the `DialogFragment` and the URL to the parent activity.
170 downloadFileListener.onDownloadFile(DownloadFile.this, downloadUrl);
171 // Manually dismiss `alertDialog`.
172 alertDialog.dismiss();
173 // Consume the event.
175 } else { // If any other key was pressed, do not consume the event.
182 // `onCreateDialog` requires the return of an `AlertDialog`.