]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/DownloadFileDialog.java
eb2b0ebf827cdbf7678e15529fd131a59667c585
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / DownloadFileDialog.java
1 /*
2  * Copyright © 2016-2019 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.content.SharedPreferences;
28 import android.net.Uri;
29 import android.os.Bundle;
30 import android.preference.PreferenceManager;
31 import android.view.KeyEvent;
32 import android.view.View;
33 import android.view.WindowManager;
34 import android.widget.EditText;
35 import android.widget.TextView;
36
37 import androidx.annotation.NonNull;
38 import androidx.fragment.app.DialogFragment;  // The AndroidX dialog fragment must be used or an error is produced on API <=22.
39
40 import com.stoutner.privacybrowser.R;
41
42 import java.util.Locale;
43
44 public class DownloadFileDialog extends DialogFragment {
45     // `downloadFileListener` is used in `onAttach()` and `onCreateDialog()`.
46     private DownloadFileListener downloadFileListener;
47
48     // The public interface is used to send information back to the parent activity.
49     public interface DownloadFileListener {
50         void onDownloadFile(DialogFragment dialogFragment, String downloadUrl);
51     }
52
53     @Override
54     public void onAttach(Context context) {
55         // Run the default commands.
56         super.onAttach(context);
57
58         // Get a handle for `DownloadFileListener` from the launching context.
59         downloadFileListener = (DownloadFileListener) context;
60     }
61
62     public static DownloadFileDialog fromUrl(String urlString, String contentDisposition, long contentLength) {
63         // Create an arguments bundle.
64         Bundle argumentsBundle = new Bundle();
65
66         // Create a variable for the file name string.
67         String fileNameString;
68
69         // Get the index of the end of `filename=` from the file name string.
70         int fileNameIndex = contentDisposition.indexOf("filename=") + 9;
71
72         // Parse the filename from `contentDisposition`.
73         if (contentDisposition.contains("filename=\"")) {  // The file name is contained in a string surrounded by `""`.
74             fileNameString = contentDisposition.substring(contentDisposition.indexOf("filename=\"") + 10, contentDisposition.indexOf("\"", contentDisposition.indexOf("filename=\"") + 10));
75         } else if (contentDisposition.contains("filename=") && ((contentDisposition.indexOf(";", fileNameIndex)) > 0 )) {
76             // The file name is contained in a string beginning with `filename=` and ending with `;`.
77             fileNameString = contentDisposition.substring(fileNameIndex, contentDisposition.indexOf(";", fileNameIndex));
78         } else if (contentDisposition.contains("filename=")) {  // The file name is contained in a string beginning with `filename=` and proceeding to the end of `contentDisposition`.
79             fileNameString = contentDisposition.substring(fileNameIndex);
80         } else {  // `contentDisposition` does not contain the filename, so use the last path segment of the URL.
81             Uri downloadUri = Uri.parse(urlString);
82             fileNameString = downloadUri.getLastPathSegment();
83         }
84
85         // Store the variables in the bundle.
86         argumentsBundle.putString("URL", urlString);
87         argumentsBundle.putString("File_Name", fileNameString);
88         argumentsBundle.putLong("File_Size", contentLength);
89
90         // Add the arguments bundle to this instance of `DownloadFileDialog`.
91         DownloadFileDialog thisDownloadFileDialog = new DownloadFileDialog();
92         thisDownloadFileDialog.setArguments(argumentsBundle);
93         return thisDownloadFileDialog;
94     }
95
96     @Override
97     @NonNull
98     // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
99     @SuppressLint("InflateParams")
100     public Dialog onCreateDialog(Bundle savedInstanceState) {
101         // Remove the warning below that `getArguments()` might be null.
102         assert getArguments() != null;
103
104         // Store the variables from the bundle.
105         String downloadUrl = getArguments().getString("URL");
106         String downloadFileName = getArguments().getString("File_Name");
107         long fileSizeLong = getArguments().getLong("File_Size");
108
109         // Initialize the file size string.
110         String fileSize;
111
112         // Convert `fileSizeLong` to a String.
113         if (fileSizeLong == -1) {  // We don't know the file size.
114             fileSize = getString(R.string.unknown_size);
115         } else {  // Convert `fileSize` to MB and store it in `fileSizeString`.  `%.3g` displays the three most significant digits.
116             fileSize = String.format(Locale.getDefault(), "%.3g", (float) fileSizeLong / 1048576) + " MB";
117         }
118
119         // Get a handle for the shared preferences.
120         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
121
122         // Get the screenshot and theme preferences.
123         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
124         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
125
126         // Use an alert dialog builder to create the alert dialog.
127         AlertDialog.Builder dialogBuilder;
128
129         // Set the style according to the theme.
130         if (darkTheme) {
131             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
132         } else {
133             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
134         }
135
136         // Set the title.
137         dialogBuilder.setTitle(R.string.save_as);
138
139         // Set the icon according to the theme.
140         if (darkTheme) {
141             dialogBuilder.setIcon(R.drawable.save_dialog_dark);
142         } else {
143             dialogBuilder.setIcon(R.drawable.save_dialog_light);
144         }
145
146         // Remove the warning below that `getActivity()` might be null;
147         assert getActivity() != null;
148
149         // Set the view.  The parent view is `null` because it will be assigned by `AlertDialog`.
150         dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.download_file_dialog, null));
151
152         // Set an listener on the negative button.
153         dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
154             // Do nothing if `Cancel` is clicked.  The `Dialog` will automatically close.
155         });
156
157         // Set an listener on the positive button
158         dialogBuilder.setPositiveButton(R.string.download, (DialogInterface dialog, int which) -> {
159             // trigger `onDownloadFile()` and return the `DialogFragment` and the download URL to the parent activity.
160             downloadFileListener.onDownloadFile(DownloadFileDialog.this, downloadUrl);
161         });
162
163         // Create an alert dialog from the alert dialog builder`.
164         final AlertDialog alertDialog = dialogBuilder.create();
165
166         // Remove the warning below that `getWindow()` might be null.
167         assert alertDialog.getWindow() != null;
168
169         // Disable screenshots if not allowed.
170         if (!allowScreenshots) {
171             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
172         }
173
174         // Show the keyboard when alert dialog is displayed on the screen.
175         alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
176
177         // We need to show `alertDialog` before we can modify the contents.
178         alertDialog.show();
179
180         // Set the text for `downloadFileSizeTextView`.
181         TextView downloadFileSizeTextView = alertDialog.findViewById(R.id.download_file_size);
182         downloadFileSizeTextView.setText(fileSize);
183
184         // Set the text for `downloadFileNameTextView`.
185         EditText downloadFileNameTextView = alertDialog.findViewById(R.id.download_file_name);
186         downloadFileNameTextView.setText(downloadFileName);
187
188         // Allow the `enter` key on the keyboard to save the file from `downloadFileNameTextView`.
189         downloadFileNameTextView.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
190             // If the event is an `ACTION_DOWN` on the `enter` key, initiate the download.
191             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
192                 // trigger `onDownloadFile()` and return the `DialogFragment` and the URL to the parent activity.
193                 downloadFileListener.onDownloadFile(DownloadFileDialog.this, downloadUrl);
194
195                 // Manually dismiss the alert dialog.
196                 alertDialog.dismiss();
197
198                 // Consume the event.
199                 return true;
200             } else {  // If any other key was pressed, do not consume the event.
201                 return false;
202             }
203         });
204
205         // `onCreateDialog` requires the return of an `AlertDialog`.
206         return alertDialog;
207     }
208 }