]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/DownloadFileDialog.java
Add setting to disable screenshots. https://redmine.stoutner.com/issues/266
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / DownloadFileDialog.java
1 /*
2  * Copyright © 2016-2018 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.dialogs;
21
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;
38
39 import com.stoutner.privacybrowser.R;
40 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
41
42 import java.util.Locale;
43
44 public class DownloadFileDialog extends AppCompatDialogFragment {
45
46     private String downloadUrl;
47     private String downloadFileName;
48     private String fileSize;
49
50     public static DownloadFileDialog fromUrl(String urlString, String contentDisposition, long contentLength) {
51         // Create an arguments bundle.
52         Bundle argumentsBundle = new Bundle();
53
54         // Create a variable for the file name string.
55         String fileNameString;
56
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();
67         }
68
69         // Store the variables in the bundle.
70         argumentsBundle.putString("URL", urlString);
71         argumentsBundle.putString("File_Name", fileNameString);
72         argumentsBundle.putLong("File_Size", contentLength);
73
74         // Add the arguments bundle to this instance of `DownloadFileDialog`.
75         DownloadFileDialog thisDownloadFileDialog = new DownloadFileDialog();
76         thisDownloadFileDialog.setArguments(argumentsBundle);
77         return thisDownloadFileDialog;
78     }
79
80     @Override
81     public void onCreate(Bundle savedInstanceState) {
82         super.onCreate(savedInstanceState);
83
84         // Remove the warning below that `getArguments()` might be null.
85         assert getArguments() != null;
86
87         // Store the strings in the local class variables.
88         downloadUrl = getArguments().getString("URL");
89         downloadFileName = getArguments().getString("File_Name");
90
91         // Get the `File_Size`.
92         long fileSizeLong = getArguments().getLong("File_Size");
93
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";
99         }
100     }
101
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);
105     }
106
107     // `downloadFileListener` is used in `onAttach()` and `onCreateDialog()`.
108     private DownloadFileListener downloadFileListener;
109
110     @Override
111     public void onAttach(Context context) {
112         super.onAttach(context);
113
114         // Check to make sure the parent activity implements the listener.
115         try {
116             downloadFileListener = (DownloadFileListener) context;
117         } catch (ClassCastException exception) {
118             throw new ClassCastException(context.toString() + " must implement DownloadFileListener.");
119         }
120     }
121
122     @Override
123     @NonNull
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;
129
130         // Get the activity's layout inflater.
131         LayoutInflater layoutInflater = getActivity().getLayoutInflater();
132
133         // Use an alert dialog builder to create the alert dialog.
134         AlertDialog.Builder dialogBuilder;
135
136         // Set the style according to the theme.
137         if (MainWebViewActivity.darkTheme) {
138             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
139         } else {
140             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
141         }
142
143         // Set the title.
144         dialogBuilder.setTitle(R.string.save_as);
145
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));
148
149         // Set an 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.
152         });
153
154         // Set an 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);
158         });
159
160         // Create an alert dialog from the alert dialog builder`.
161         final AlertDialog alertDialog = dialogBuilder.create();
162
163         // Remove the warning below that `getWindow()` might be null.
164         assert alertDialog.getWindow() != null;
165
166         // Disable screenshots if not allowed.
167         if (!MainWebViewActivity.allowScreenshots) {
168             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
169         }
170
171         // Show the keyboard when alert dialog is displayed on the screen.
172         alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
173
174         // We need to show `alertDialog` before we can modify the contents.
175         alertDialog.show();
176
177         // Set the text for `downloadFileSizeTextView`.
178         TextView downloadFileSizeTextView = alertDialog.findViewById(R.id.download_file_size);
179         downloadFileSizeTextView.setText(fileSize);
180
181         // Set the text for `downloadFileNameTextView`.
182         EditText downloadFileNameTextView = alertDialog.findViewById(R.id.download_file_name);
183         downloadFileNameTextView.setText(downloadFileName);
184
185         // Allow the `enter` key on the keyboard to save the file from `downloadFileNameTextView`.
186         downloadFileNameTextView.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
187             // If the event is an `ACTION_DOWN` on the `enter` key, initiate the download.
188             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
189                 // trigger `onDownloadFile()` and return the `DialogFragment` and the URL to the parent activity.
190                 downloadFileListener.onDownloadFile(DownloadFileDialog.this, downloadUrl);
191
192                 // Manually dismiss the alert dialog.
193                 alertDialog.dismiss();
194
195                 // Consume the event.
196                 return true;
197             } else {  // If any other key was pressed, do not consume the event.
198                 return false;
199             }
200         });
201
202         // `onCreateDialog` requires the return of an `AlertDialog`.
203         return alertDialog;
204     }
205 }