]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/SaveDialog.java
9b599b531ede15447a445ffcd0f61804efc3d6bd
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / SaveDialog.java
1 /*
2  * Copyright © 2019-2020 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.Manifest;
23 import android.annotation.SuppressLint;
24 import android.app.Activity;
25 import android.app.AlertDialog;
26 import android.app.Dialog;
27 import android.content.Context;
28 import android.content.DialogInterface;
29 import android.content.Intent;
30 import android.content.SharedPreferences;
31 import android.content.pm.PackageManager;
32 import android.net.Uri;
33 import android.os.AsyncTask;
34 import android.os.Build;
35 import android.os.Bundle;
36 import android.os.Environment;
37 import android.provider.DocumentsContract;
38 import android.text.Editable;
39 import android.text.TextWatcher;
40 import android.view.View;
41 import android.view.WindowManager;
42 import android.widget.Button;
43 import android.widget.EditText;
44 import android.widget.TextView;
45
46 import androidx.annotation.NonNull;
47 import androidx.core.content.ContextCompat;
48 import androidx.fragment.app.DialogFragment;
49 import androidx.preference.PreferenceManager;
50
51 import com.stoutner.privacybrowser.R;
52 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
53 import com.stoutner.privacybrowser.asynctasks.GetUrlSize;
54 import com.stoutner.privacybrowser.helpers.DownloadLocationHelper;
55
56 import java.io.File;
57
58 public class SaveDialog extends DialogFragment {
59     // Define the save webpage listener.
60     private SaveWebpageListener saveWebpageListener;
61
62     // The public interface is used to send information back to the parent activity.
63     public interface SaveWebpageListener {
64         void onSaveWebpage(int saveType, DialogFragment dialogFragment);
65     }
66
67     // Define the get URL size AsyncTask.  This allows previous instances of the task to be cancelled if a new one is run.
68     private AsyncTask getUrlSize;
69
70     @Override
71     public void onAttach(@NonNull Context context) {
72         // Run the default commands.
73         super.onAttach(context);
74
75         // Get a handle for the save webpage listener from the launching context.
76         saveWebpageListener = (SaveWebpageListener) context;
77     }
78
79     public static SaveDialog saveUrl(int saveType, String url, String userAgent, boolean cookiesEnabled) {
80         // Create an arguments bundle.
81         Bundle argumentsBundle = new Bundle();
82
83         // Store the arguments in the bundle.
84         argumentsBundle.putInt("save_type", saveType);
85         argumentsBundle.putString("url", url);
86         argumentsBundle.putString("user_agent", userAgent);
87         argumentsBundle.putBoolean("cookies_enabled", cookiesEnabled);
88
89         // Create a new instance of the save webpage dialog.
90         SaveDialog saveWebpageDialog = new SaveDialog();
91
92         // Add the arguments bundle to the new dialog.
93         saveWebpageDialog.setArguments(argumentsBundle);
94
95         // Return the new dialog.
96         return saveWebpageDialog;
97     }
98
99     // `@SuppressLint("InflateParams")` removes the warning about using null as the parent view group when inflating the alert dialog.
100     @SuppressLint("InflateParams")
101     @Override
102     @NonNull
103     public Dialog onCreateDialog(Bundle savedInstanceState) {
104         // Get a handle for the arguments.
105         Bundle arguments = getArguments();
106
107         // Remove the incorrect lint warning that the arguments might be null.
108         assert arguments != null;
109
110         // Get the arguments from the bundle.
111         int saveType = arguments.getInt("save_type");
112         String url = arguments.getString("url");
113         String userAgent = arguments.getString("user_agent");
114         boolean cookiesEnabled = arguments.getBoolean("cookies_enabled");
115
116         // Get a handle for the activity and the context.
117         Activity activity = getActivity();
118         Context context = getContext();
119
120         // Remove the incorrect lint warnings below that the activity and context might be null.
121         assert activity != null;
122         assert context != null;
123
124         // Get a handle for the shared preferences.
125         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
126
127         // Get the screenshot and theme preferences.
128         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
129         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
130
131         // Use an alert dialog builder to create the alert dialog.
132         AlertDialog.Builder dialogBuilder;
133
134         // Set the style and icon according to the theme.
135         if (darkTheme) {
136             // Set the style.
137             dialogBuilder = new AlertDialog.Builder(activity, R.style.PrivacyBrowserAlertDialogDark);
138
139             // Set the icon according to the save type.
140             switch (saveType) {
141                 case StoragePermissionDialog.SAVE_URL:
142                     dialogBuilder.setIcon(R.drawable.copy_enabled_dark);
143                     break;
144
145                 case StoragePermissionDialog.SAVE_AS_ARCHIVE:
146                     dialogBuilder.setIcon(R.drawable.dom_storage_cleared_dark);
147                     break;
148
149                 case StoragePermissionDialog.SAVE_AS_IMAGE:
150                     dialogBuilder.setIcon(R.drawable.images_enabled_dark);
151                     break;
152             }
153         } else {
154             // Set the style.
155             dialogBuilder = new AlertDialog.Builder(activity, R.style.PrivacyBrowserAlertDialogLight);
156
157             // Set the icon according to the save type.
158             switch (saveType) {
159                 case StoragePermissionDialog.SAVE_URL:
160                     dialogBuilder.setIcon(R.drawable.copy_enabled_light);
161                     break;
162
163                 case StoragePermissionDialog.SAVE_AS_ARCHIVE:
164                     dialogBuilder.setIcon(R.drawable.dom_storage_cleared_light);
165                     break;
166
167                 case StoragePermissionDialog.SAVE_AS_IMAGE:
168                     dialogBuilder.setIcon(R.drawable.images_enabled_light);
169                     break;
170             }
171         }
172
173         // Set the title according to the type.
174         switch (saveType) {
175             case StoragePermissionDialog.SAVE_URL:
176                 dialogBuilder.setTitle(R.string.save);
177                 break;
178
179             case StoragePermissionDialog.SAVE_AS_ARCHIVE:
180                 dialogBuilder.setTitle(R.string.save_archive);
181                 break;
182
183             case StoragePermissionDialog.SAVE_AS_IMAGE:
184                 dialogBuilder.setTitle(R.string.save_image);
185                 break;
186         }
187
188         // Set the view.  The parent view is null because it will be assigned by the alert dialog.
189         dialogBuilder.setView(activity.getLayoutInflater().inflate(R.layout.save_dialog, null));
190
191         // Set the cancel button listener.  Using `null` as the listener closes the dialog without doing anything else.
192         dialogBuilder.setNegativeButton(R.string.cancel, null);
193
194         // Set the save button listener.
195         dialogBuilder.setPositiveButton(R.string.save, (DialogInterface dialog, int which) -> {
196             // Return the dialog fragment to the parent activity.
197             saveWebpageListener.onSaveWebpage(saveType, this);
198         });
199
200         // Create an alert dialog from the builder.
201         AlertDialog alertDialog = dialogBuilder.create();
202
203         // Remove the incorrect lint warning below that the window might be null.
204         assert alertDialog.getWindow() != null;
205
206         // Disable screenshots if not allowed.
207         if (!allowScreenshots) {
208             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
209         }
210
211         // The alert dialog must be shown before items in the layout can be modified.
212         alertDialog.show();
213
214         // Get handles for the layout items.
215         EditText urlEditText = alertDialog.findViewById(R.id.url_edittext);
216         EditText fileNameEditText = alertDialog.findViewById(R.id.file_name_edittext);
217         Button browseButton = alertDialog.findViewById(R.id.browse_button);
218         TextView fileSizeTextView = alertDialog.findViewById(R.id.file_size_textview);
219         TextView fileExistsWarningTextView = alertDialog.findViewById(R.id.file_exists_warning_textview);
220         TextView storagePermissionTextView = alertDialog.findViewById(R.id.storage_permission_textview);
221         Button saveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
222
223         // Modify the layout based on the save type.
224         if (saveType == StoragePermissionDialog.SAVE_URL) {  // A URL is being saved.
225             // Update the status of the save button whe the URL changes.
226             urlEditText.addTextChangedListener(new TextWatcher() {
227                 @Override
228                 public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
229                     // Do nothing.
230                 }
231
232                 @Override
233                 public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
234                     // Do nothing.
235                 }
236
237                 @Override
238                 public void afterTextChanged(Editable editable) {
239                     // Cancel the get URL size AsyncTask if it is running.
240                     if ((getUrlSize != null)) {
241                         getUrlSize.cancel(true);
242                     }
243
244                     // Get the current URL to save.
245                     String urlToSave = urlEditText.getText().toString();
246
247                     // Wipe the file size text view.
248                     fileSizeTextView.setText("");
249
250                     // Get the file size for the current URL.
251                     getUrlSize = new GetUrlSize(context, alertDialog, userAgent, cookiesEnabled).execute(urlToSave);
252
253                     // Enable the save button if the URL and file name are populated.
254                     saveButton.setEnabled(!urlToSave.isEmpty() && !fileNameEditText.getText().toString().isEmpty());
255                 }
256             });
257
258             // Populate the URL edit text.
259             urlEditText.setText(url);
260         } else {  // An archive or an image is being saved.
261             // Hide the URL edit text and the file size text view.
262             urlEditText.setVisibility(View.GONE);
263             fileSizeTextView.setVisibility(View.GONE);
264         }
265
266         // Update the status of the save button when the file name changes.
267         fileNameEditText.addTextChangedListener(new TextWatcher() {
268             @Override
269             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
270                 // Do nothing.
271             }
272
273             @Override
274             public void onTextChanged(CharSequence s, int start, int before, int count) {
275                 // Do nothing.
276             }
277
278             @Override
279             public void afterTextChanged(Editable s) {
280                 // Get the current file name.
281                 String fileNameString = fileNameEditText.getText().toString();
282
283                 // Convert the file name string to a file.
284                 File file = new File(fileNameString);
285
286                 // Check to see if the file exists.
287                 if (file.exists()) {
288                     // Show the file exists warning.
289                     fileExistsWarningTextView.setVisibility(View.VISIBLE);
290                 } else {
291                     // Hide the file exists warning.
292                     fileExistsWarningTextView.setVisibility(View.GONE);
293                 }
294
295                 // Enable the save button based on the save type.
296                 if (saveType == StoragePermissionDialog.SAVE_URL) {  // A URL is being saved.
297                     // Enable the save button if the file name and the URL is populated.
298                     saveButton.setEnabled(!fileNameString.isEmpty() && !urlEditText.getText().toString().isEmpty());
299                 } else {  // An archive or an image is being saved.
300                     // Enable the save button if the file name is populated.
301                     saveButton.setEnabled(!fileNameString.isEmpty());
302                 }
303             }
304         });
305
306         // Create a file name string.
307         String fileName = "";
308
309         // Set the file name according to the type.
310         switch (saveType) {
311             case StoragePermissionDialog.SAVE_URL:
312                 // Convert the URL to a URI.
313                 Uri uri = Uri.parse(url);
314
315                 // Get the last path segment.
316                 String lastPathSegment = uri.getLastPathSegment();
317
318                 // Use a default file name if the last path segment is null.
319                 if (lastPathSegment == null) {
320                     lastPathSegment = getString(R.string.file);
321                 }
322
323                 // Use the last path segment as the file name.
324                 fileName = lastPathSegment;
325                 break;
326
327             case StoragePermissionDialog.SAVE_AS_ARCHIVE:
328                 fileName = getString(R.string.webpage_mht);
329                 break;
330
331             case StoragePermissionDialog.SAVE_AS_IMAGE:
332                 fileName = getString(R.string.webpage_png);
333                 break;
334         }
335
336         // Save the file name as the default file name.  This must be final to be used in the lambda below.
337         final String defaultFileName = fileName;
338
339         // Instantiate the download location helper.
340         DownloadLocationHelper downloadLocationHelper = new DownloadLocationHelper();
341
342         // Get the default file path.
343         String defaultFilePath = downloadLocationHelper.getDownloadLocation(context) + "/" + defaultFileName;
344
345         // Hide the storage permission text view if the permission has already been granted.
346         if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
347             storagePermissionTextView.setVisibility(View.GONE);
348         }
349
350         // Populate the file name edit text.
351         fileNameEditText.setText(defaultFilePath);
352
353         // Move the cursor to the end of the default file path.
354         fileNameEditText.setSelection(defaultFilePath.length());
355
356         // Handle clicks on the browse button.
357         browseButton.setOnClickListener((View view) -> {
358             // Create the file picker intent.
359             Intent browseIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
360
361             // Set the intent MIME type to include all files so that everything is visible.
362             browseIntent.setType("*/*");
363
364             // Set the initial file name according to the type.
365             browseIntent.putExtra(Intent.EXTRA_TITLE, defaultFileName);
366
367             // Set the initial directory if the minimum API >= 26.
368             if (Build.VERSION.SDK_INT >= 26) {
369                 browseIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
370             }
371
372             // Request a file that can be opened.
373             browseIntent.addCategory(Intent.CATEGORY_OPENABLE);
374
375             // Start the file picker.  This must be started under `activity` so that the request code is returned correctly.
376             activity.startActivityForResult(browseIntent, MainWebViewActivity.BROWSE_SAVE_WEBPAGE_REQUEST_CODE);
377         });
378
379         // Return the alert dialog.
380         return alertDialog;
381     }
382 }