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