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 {
46 private String downloadUrl;
47 private String downloadFileName;
48 private String fileSize;
50 public static DownloadFileDialog fromUrl(String urlString, String contentDisposition, long contentLength) {
51 // Create an arguments bundle.
52 Bundle argumentsBundle = new Bundle();
54 // Create a variable for the file name string.
55 String fileNameString;
57 // Parse `filename` from `contentDisposition`.
58 if (contentDisposition.contains("filename=\"")) { // The file name is contained in a string surrounded by `""`.
59 fileNameString = contentDisposition.substring(contentDisposition.indexOf("filename=\"") + 10, contentDisposition.indexOf("\"", contentDisposition.indexOf("filename=\"") + 10));
60 } 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 `;`.
61 fileNameString = contentDisposition.substring(contentDisposition.indexOf("filename=") + 9, contentDisposition.indexOf(";", contentDisposition.indexOf("filename=") + 9));
62 } else if (contentDisposition.contains("filename=")) { // The file name is contained in a string beginning with `filename=` and proceeding to the end of `contentDisposition`.
63 fileNameString = contentDisposition.substring(contentDisposition.indexOf("filename=") + 9, contentDisposition.length());
64 } else { // `contentDisposition` does not contain the filename, so use the last path segment of the URL.
65 Uri downloadUri = Uri.parse(urlString);
66 fileNameString = downloadUri.getLastPathSegment();
69 // Store the variables in the bundle.
70 argumentsBundle.putString("URL", urlString);
71 argumentsBundle.putString("File_Name", fileNameString);
72 argumentsBundle.putLong("File_Size", contentLength);
74 // Add the arguments bundle to this instance of `DownloadFileDialog`.
75 DownloadFileDialog thisDownloadFileDialog = new DownloadFileDialog();
76 thisDownloadFileDialog.setArguments(argumentsBundle);
77 return thisDownloadFileDialog;
81 public void onCreate(Bundle savedInstanceState) {
82 super.onCreate(savedInstanceState);
84 // Remove the warning below that `getArguments()` might be null.
85 assert getArguments() != null;
87 // Store the strings in the local class variables.
88 downloadUrl = getArguments().getString("URL");
89 downloadFileName = getArguments().getString("File_Name");
91 // Get the `File_Size`.
92 long fileSizeLong = getArguments().getLong("File_Size");
94 // Convert `fileSizeLong` to a String.
95 if (fileSizeLong == -1) { // We don't know the file size.
96 fileSize = getString(R.string.unknown_size);
97 } else { // Convert `fileSize` to MB and store it in `fileSizeString`. `%.3g` displays the three most significant digits.
98 fileSize = String.format(Locale.getDefault(), "%.3g", (float) fileSizeLong / 1048576) + " MB";
102 // The public interface is used to send information back to the parent activity.
103 public interface DownloadFileListener {
104 void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl);
107 // `downloadFileListener` is used in `onAttach()` and `onCreateDialog()`.
108 private DownloadFileListener downloadFileListener;
111 public void onAttach(Context context) {
112 super.onAttach(context);
114 // Check to make sure the parent activity implements the listener.
116 downloadFileListener = (DownloadFileListener) context;
117 } catch (ClassCastException exception) {
118 throw new ClassCastException(context.toString() + " must implement DownloadFileListener.");
124 // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
125 @SuppressLint("InflateParams")
126 public Dialog onCreateDialog(Bundle savedInstanceState) {
127 // Remove the warning below that `getActivity()` might be null;
128 assert getActivity() != null;
130 // Get the activity's layout inflater.
131 LayoutInflater layoutInflater = getActivity().getLayoutInflater();
133 // Use `AlertDialog.Builder` to create the `AlertDialog`.
134 AlertDialog.Builder dialogBuilder;
136 // Set the style according to the theme.
137 if (MainWebViewActivity.darkTheme) {
138 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
140 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
144 dialogBuilder.setTitle(R.string.save_as);
146 // Set the view. The parent view is `null` because it will be assigned by `AlertDialog`.
147 dialogBuilder.setView(layoutInflater.inflate(R.layout.download_file_dialog, null));
149 // Set an `onClick()` listener on the negative button.
150 dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
151 // Do nothing if `Cancel` is clicked. The `Dialog` will automatically close.
154 // Set an `onClick()` listener on the positive button
155 dialogBuilder.setPositiveButton(R.string.download, (DialogInterface dialog, int which) -> {
156 // trigger `onDownloadFile()` and return the `DialogFragment` and the download URL to the parent activity.
157 downloadFileListener.onDownloadFile(DownloadFileDialog.this, downloadUrl);
160 // Create an `AlertDialog` from the `AlertDialog.Builder`.
161 final AlertDialog alertDialog = dialogBuilder.create();
163 // Remove the warning below that `setSoftInputMode` might produce `java.lang.NullPointerException`.
164 assert alertDialog.getWindow() != null;
166 // Show the keyboard when `alertDialog` is displayed on the screen.
167 alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
169 // We need to show `alertDialog` before we can modify the contents.
172 // Set the text for `downloadFileSizeTextView`.
173 TextView downloadFileSizeTextView = alertDialog.findViewById(R.id.download_file_size);
174 downloadFileSizeTextView.setText(fileSize);
176 // Set the text for `downloadFileNameTextView`.
177 EditText downloadFileNameTextView = alertDialog.findViewById(R.id.download_file_name);
178 downloadFileNameTextView.setText(downloadFileName);
180 // Allow the `enter` key on the keyboard to save the file from `downloadFileNameTextView`.
181 downloadFileNameTextView.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
182 // If the event is an `ACTION_DOWN` on the `enter` key, initiate the download.
183 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
184 // trigger `onDownloadFile()` and return the `DialogFragment` and the URL to the parent activity.
185 downloadFileListener.onDownloadFile(DownloadFileDialog.this, downloadUrl);
187 // Manually dismiss the alert dialog.
188 alertDialog.dismiss();
190 // Consume the event.
192 } else { // If any other key was pressed, do not consume the event.
197 // `onCreateDialog` requires the return of an `AlertDialog`.