]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/DownloadFile.java
627335df711dc8c5528999c01b6091c5d7d10e01
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / DownloadFile.java
1 /**
2  * Copyright 2016 Soren Stoutner <soren@stoutner.com>.
3  *
4  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 package com.stoutner.privacybrowser;
21
22 import android.annotation.SuppressLint;
23 import android.app.Dialog;
24 import android.app.DialogFragment;
25 import android.content.Context;
26 import android.content.DialogInterface;
27 import android.net.Uri;
28 import android.os.Bundle;
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 import android.view.KeyEvent;
32 import android.view.LayoutInflater;
33 import android.view.View;
34 import android.view.WindowManager;
35 import android.widget.EditText;
36 import android.widget.TextView;
37
38 import java.util.Locale;
39
40 public class DownloadFile extends DialogFragment {
41
42     private String downloadUrl;
43     private String downloadFileName;
44     private String fileSize;
45
46     public static DownloadFile fromUrl(String urlString, String contentDisposition, long contentLength) {
47         // Create `argumentsBundle`.
48         Bundle argumentsBundle = new Bundle();
49
50         String fileNameString;
51         if (!contentDisposition.isEmpty()) {  // Extract `fileNameString` from `contentDisposition` using the substring beginning after `filename="` and ending one character before the end of `contentDisposition`.
52             fileNameString = contentDisposition.substring(contentDisposition.indexOf("filename=\"") + 10, contentDisposition.length() - 1);
53         } else {  // `contentDisposition` is empty, so use the last path segment of the URL as the file name.
54             Uri downloadUri = Uri.parse(urlString);
55             fileNameString = downloadUri.getLastPathSegment();
56         }
57
58         // Convert `contentLength` to MB and store it in `fileSizeString`.  `%.3g` displays the three most significant digits.
59         String fileSizeString = String.format(Locale.getDefault(), "%.3g", (float) contentLength / 1048576) + " MB";
60
61         // Store the variables in the `Bundle`.
62         argumentsBundle.putString("URL", urlString);
63         argumentsBundle.putString("File_Name", fileNameString);
64         argumentsBundle.putString("File_Size", fileSizeString);
65
66         // Add `argumentsBundle` to this instance of `DownloadFile`.
67         DownloadFile thisDownloadFileDialog = new DownloadFile();
68         thisDownloadFileDialog.setArguments(argumentsBundle);
69         return thisDownloadFileDialog;
70     }
71
72     @Override
73     public void onCreate(Bundle savedInstanceState) {
74         super.onCreate(savedInstanceState);
75
76         // Store the strings in the local class variables.
77         downloadUrl = getArguments().getString("URL");
78         downloadFileName = getArguments().getString("File_Name");
79         fileSize = getArguments().getString("File_Size");
80     }
81
82     // The public interface is used to send information back to the parent activity.
83     public interface DownloadFileListener {
84         void onDownloadFile(DialogFragment dialogFragment, String downloadUrl);
85     }
86
87     // `downloadFileListener` is used in `onAttach()` and `onCreateDialog()`.
88     private DownloadFileListener downloadFileListener;
89
90     // Check to make sure tha the parent activity implements the listener.
91     @Override
92     public void onAttach(Context context) {
93         super.onAttach(context);
94         try {
95             downloadFileListener = (DownloadFileListener) context;
96         } catch (ClassCastException exception) {
97             throw new ClassCastException(context.toString() + " must implement DownloadFileListener.");
98         }
99     }
100
101     // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
102     @SuppressLint("InflateParams")
103     @Override
104     public Dialog onCreateDialog(Bundle savedInstanceState) {
105         // Get the activity's layout inflater.
106         LayoutInflater layoutInflater = getActivity().getLayoutInflater();
107
108         // Use `AlertDialog.Builder` to create the `AlertDialog`.  `R.style.lightAlertDialog` formats the color of the button text.
109         AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.LightAlertDialog);
110         dialogBuilder.setTitle(R.string.save_as);
111         // The parent view is `null` because it will be assigned by `AlertDialog`.
112         dialogBuilder.setView(layoutInflater.inflate(R.layout.download_file_dialog, null));
113
114         // Set an `onClick()` listener on the negative button.
115         dialogBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
116             @Override
117             public void onClick(DialogInterface dialog, int which) {
118                 // Do nothing if `Cancel` is clicked.
119             }
120         });
121
122         // Set an `onClick()` listener on the positive button
123         dialogBuilder.setPositiveButton(R.string.download, new DialogInterface.OnClickListener() {
124             @Override
125             public void onClick(DialogInterface dialog, int which) {
126                 // trigger `onDownloadFile()` and return the `DialogFragment` and the download URL to the parent activity.
127                 downloadFileListener.onDownloadFile(DownloadFile.this, downloadUrl);
128             }
129         });
130
131
132         // Create an `AlertDialog` from the `AlertDialog.Builder`.
133         final AlertDialog alertDialog = dialogBuilder.create();
134
135         // Remove the warning below that `setSoftInputMode` might produce `java.lang.NullPointerException`.
136         assert alertDialog.getWindow() != null;
137
138         // Show the keyboard when `alertDialog` is displayed on the screen.
139         alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
140
141         // We need to show `alertDialog` before we can modify the contents.
142         alertDialog.show();
143
144         // Set the text for `downloadFileSizeTextView`.
145         TextView downloadFileSizeTextView = (TextView) alertDialog.findViewById(R.id.download_file_size);
146         assert downloadFileSizeTextView != null;  // Remove the warning on the following line that `downloadFileSizeTextView` might be `null`.
147         downloadFileSizeTextView.setText(fileSize);
148
149         // Set the text for `downloadFileNameTextView`.
150         EditText downloadFileNameTextView = (EditText) alertDialog.findViewById(R.id.download_file_name);
151         assert downloadFileNameTextView != null;  // Remove the warning on the following line that `downloadFileNameTextView` might be `null`.
152         downloadFileNameTextView.setText(downloadFileName);
153
154         // Allow the `enter` key on the keyboard to save the file from `downloadFileNameTextView`.
155         downloadFileNameTextView.setOnKeyListener(new View.OnKeyListener() {
156             @Override
157             public boolean onKey (View v, int keyCode, KeyEvent event) {
158                 // If the event is an `ACTION_DOWN` on the `enter` key, initiate the download.
159                 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
160                     // trigger `onDownloadFile()` and return the `DialogFragment` and the URL to the parent activity.
161                     downloadFileListener.onDownloadFile(DownloadFile.this, downloadUrl);
162                     // Manually dismiss `alertDialog`.
163                     alertDialog.dismiss();
164                     // Consume the event.
165                     return true;
166                 } else {  // If any other key was pressed, do not consume the event.
167                     return false;
168                 }
169             }
170         });
171
172
173         // `onCreateDialog` requires the return of an `AlertDialog`.
174         return alertDialog;
175     }
176 }