]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/DownloadFile.java
0a1d1dcab81a713c2a0b7f090f85f109453867e6
[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 with the next `"`.
52             fileNameString = contentDisposition.substring(contentDisposition.indexOf("filename=\"") + 10, contentDisposition.indexOf("\"", contentDisposition.indexOf("filename=\"") + 10));
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         // Store the variables in the `Bundle`.
59         argumentsBundle.putString("URL", urlString);
60         argumentsBundle.putString("File_Name", fileNameString);
61         argumentsBundle.putLong("File_Size", contentLength);
62
63         // Add `argumentsBundle` to this instance of `DownloadFile`.
64         DownloadFile thisDownloadFileDialog = new DownloadFile();
65         thisDownloadFileDialog.setArguments(argumentsBundle);
66         return thisDownloadFileDialog;
67     }
68
69     @Override
70     public void onCreate(Bundle savedInstanceState) {
71         super.onCreate(savedInstanceState);
72
73         // Store the strings in the local class variables.
74         downloadUrl = getArguments().getString("URL");
75         downloadFileName = getArguments().getString("File_Name");
76
77         // Get the `File_Size`.
78         long fileSizeLong = getArguments().getLong("File_Size");
79
80         // Convert `fileSizeLong` to a String.
81         if (fileSizeLong == -1) {  // We don't know the file size.
82             fileSize = getString(R.string.unknown_size);
83         } else {  // Convert `fileSize` to MB and store it in `fileSizeString`.  `%.3g` displays the three most significant digits.
84             fileSize = String.format(Locale.getDefault(), "%.3g", (float) fileSizeLong / 1048576) + " MB";
85         }
86     }
87
88     // The public interface is used to send information back to the parent activity.
89     public interface DownloadFileListener {
90         void onDownloadFile(DialogFragment dialogFragment, String downloadUrl);
91     }
92
93     // `downloadFileListener` is used in `onAttach()` and `onCreateDialog()`.
94     private DownloadFileListener downloadFileListener;
95
96     // Check to make sure tha the parent activity implements the listener.
97     @Override
98     public void onAttach(Context context) {
99         super.onAttach(context);
100         try {
101             downloadFileListener = (DownloadFileListener) context;
102         } catch (ClassCastException exception) {
103             throw new ClassCastException(context.toString() + " must implement DownloadFileListener.");
104         }
105     }
106
107     // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
108     @SuppressLint("InflateParams")
109     @Override
110     public Dialog onCreateDialog(Bundle savedInstanceState) {
111         // Get the activity's layout inflater.
112         LayoutInflater layoutInflater = getActivity().getLayoutInflater();
113
114         // Use `AlertDialog.Builder` to create the `AlertDialog`.  `R.style.lightAlertDialog` formats the color of the button text.
115         AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.LightAlertDialog);
116         dialogBuilder.setTitle(R.string.save_as);
117         // The parent view is `null` because it will be assigned by `AlertDialog`.
118         dialogBuilder.setView(layoutInflater.inflate(R.layout.download_file_dialog, null));
119
120         // Set an `onClick()` listener on the negative button.
121         dialogBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
122             @Override
123             public void onClick(DialogInterface dialog, int which) {
124                 // Do nothing if `Cancel` is clicked.
125             }
126         });
127
128         // Set an `onClick()` listener on the positive button
129         dialogBuilder.setPositiveButton(R.string.download, new DialogInterface.OnClickListener() {
130             @Override
131             public void onClick(DialogInterface dialog, int which) {
132                 // trigger `onDownloadFile()` and return the `DialogFragment` and the download URL to the parent activity.
133                 downloadFileListener.onDownloadFile(DownloadFile.this, downloadUrl);
134             }
135         });
136
137
138         // Create an `AlertDialog` from the `AlertDialog.Builder`.
139         final AlertDialog alertDialog = dialogBuilder.create();
140
141         // Remove the warning below that `setSoftInputMode` might produce `java.lang.NullPointerException`.
142         assert alertDialog.getWindow() != null;
143
144         // Show the keyboard when `alertDialog` is displayed on the screen.
145         alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
146
147         // We need to show `alertDialog` before we can modify the contents.
148         alertDialog.show();
149
150         // Set the text for `downloadFileSizeTextView`.
151         TextView downloadFileSizeTextView = (TextView) alertDialog.findViewById(R.id.download_file_size);
152         assert downloadFileSizeTextView != null;  // Remove the warning on the following line that `downloadFileSizeTextView` might be `null`.
153         downloadFileSizeTextView.setText(fileSize);
154
155         // Set the text for `downloadFileNameTextView`.
156         EditText downloadFileNameTextView = (EditText) alertDialog.findViewById(R.id.download_file_name);
157         assert downloadFileNameTextView != null;  // Remove the warning on the following line that `downloadFileNameTextView` might be `null`.
158         downloadFileNameTextView.setText(downloadFileName);
159
160         // Allow the `enter` key on the keyboard to save the file from `downloadFileNameTextView`.
161         downloadFileNameTextView.setOnKeyListener(new View.OnKeyListener() {
162             @Override
163             public boolean onKey (View v, int keyCode, KeyEvent event) {
164                 // If the event is an `ACTION_DOWN` on the `enter` key, initiate the download.
165                 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
166                     // trigger `onDownloadFile()` and return the `DialogFragment` and the URL to the parent activity.
167                     downloadFileListener.onDownloadFile(DownloadFile.this, downloadUrl);
168                     // Manually dismiss `alertDialog`.
169                     alertDialog.dismiss();
170                     // Consume the event.
171                     return true;
172                 } else {  // If any other key was pressed, do not consume the event.
173                     return false;
174                 }
175             }
176         });
177
178
179         // `onCreateDialog` requires the return of an `AlertDialog`.
180         return alertDialog;
181     }
182 }