]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/SaveWebpageDialog.java
Add a warning if a file will be overwritten. https://redmine.stoutner.com/issues/371
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / SaveWebpageDialog.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.os.Build;
33 import android.os.Bundle;
34 import android.os.Environment;
35 import android.provider.DocumentsContract;
36 import android.text.Editable;
37 import android.text.TextWatcher;
38 import android.view.View;
39 import android.view.WindowManager;
40 import android.widget.Button;
41 import android.widget.EditText;
42 import android.widget.TextView;
43
44 import androidx.annotation.NonNull;
45 import androidx.core.content.ContextCompat;
46 import androidx.fragment.app.DialogFragment;
47 import androidx.preference.PreferenceManager;
48
49 import com.stoutner.privacybrowser.R;
50 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
51
52 import java.io.File;
53
54 public class SaveWebpageDialog extends DialogFragment {
55     // Define the save webpage listener.
56     private SaveWebpageListener saveWebpageListener;
57
58     // The public interface is used to send information back to the parent activity.
59     public interface SaveWebpageListener {
60         void onSaveWebpage(int saveType, DialogFragment dialogFragment);
61     }
62
63     @Override
64     public void onAttach(@NonNull Context context) {
65         // Run the default commands.
66         super.onAttach(context);
67
68         // Get a handle for the save webpage listener from the launching context.
69         saveWebpageListener = (SaveWebpageListener) context;
70     }
71
72     public static SaveWebpageDialog saveWebpage(int saveType) {
73         // Create an arguments bundle.
74         Bundle argumentsBundle = new Bundle();
75
76         // Store the save type in the bundle.
77         argumentsBundle.putInt("save_type", saveType);
78
79         // Create a new instance of the save webpage dialog.
80         SaveWebpageDialog saveWebpageDialog = new SaveWebpageDialog();
81
82         // Add the arguments bundle to the new dialog.
83         saveWebpageDialog.setArguments(argumentsBundle);
84
85         // Return the new dialog.
86         return saveWebpageDialog;
87     }
88
89     // `@SuppressLint("InflateParams")` removes the warning about using null as the parent view group when inflating the alert dialog.
90     @SuppressLint("InflateParams")
91     @Override
92     @NonNull
93     public Dialog onCreateDialog(Bundle savedInstanceState) {
94         // Get a handle for the arguments.
95         Bundle arguments = getArguments();
96
97         // Remove the incorrect lint warning that the arguments might be null.
98         assert arguments != null;
99
100         // Get the save type.
101         int saveType = arguments.getInt("save_type");
102
103         // Get a handle for the activity and the context.
104         Activity activity = getActivity();
105         Context context = getContext();
106
107         // Remove the incorrect lint warnings below that the activity and context might be null.
108         assert activity != null;
109         assert context != null;
110
111         // Get a handle for the shared preferences.
112         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
113
114         // Get the screenshot and theme preferences.
115         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
116         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
117
118         // Use an alert dialog builder to create the alert dialog.
119         AlertDialog.Builder dialogBuilder;
120
121         // Set the style and icon according to the theme.
122         if (darkTheme) {
123             // Set the style.
124             dialogBuilder = new AlertDialog.Builder(activity, R.style.PrivacyBrowserAlertDialogDark);
125
126             // Set the icon according to the save type.
127             switch (saveType) {
128                 case StoragePermissionDialog.SAVE_ARCHIVE:
129                     dialogBuilder.setIcon(R.drawable.dom_storage_cleared_dark);
130                     break;
131
132                 case StoragePermissionDialog.SAVE_IMAGE:
133                     dialogBuilder.setIcon(R.drawable.images_enabled_dark);
134                     break;
135             }
136         } else {
137             // Set the style.
138             dialogBuilder = new AlertDialog.Builder(activity, R.style.PrivacyBrowserAlertDialogLight);
139
140             // Set the icon according to the save type.
141             switch (saveType) {
142                 case StoragePermissionDialog.SAVE_ARCHIVE:
143                     dialogBuilder.setIcon(R.drawable.dom_storage_cleared_light);
144                     break;
145
146                 case StoragePermissionDialog.SAVE_IMAGE:
147                     dialogBuilder.setIcon(R.drawable.images_enabled_light);
148                     break;
149             }
150         }
151
152         // Set the title according to the type.
153         switch (saveType) {
154             case StoragePermissionDialog.SAVE_ARCHIVE:
155                 dialogBuilder.setTitle(R.string.save_archive);
156                 break;
157
158             case StoragePermissionDialog.SAVE_IMAGE:
159                 dialogBuilder.setTitle(R.string.save_image);
160                 break;
161         }
162
163         // Set the view.  The parent view is null because it will be assigned by the alert dialog.
164         dialogBuilder.setView(activity.getLayoutInflater().inflate(R.layout.save_dialog, null));
165
166         // Set the cancel button listener.  Using `null` as the listener closes the dialog without doing anything else.
167         dialogBuilder.setNegativeButton(R.string.cancel, null);
168
169         // Set the save button listener.
170         dialogBuilder.setPositiveButton(R.string.save, (DialogInterface dialog, int which) -> {
171             // Return the dialog fragment to the parent activity.
172             saveWebpageListener.onSaveWebpage(saveType, this);
173         });
174
175         // Create an alert dialog from the builder.
176         AlertDialog alertDialog = dialogBuilder.create();
177
178         // Remove the incorrect lint warning below that the window might be null.
179         assert alertDialog.getWindow() != null;
180
181         // Disable screenshots if not allowed.
182         if (!allowScreenshots) {
183             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
184         }
185
186         // The alert dialog must be shown before items in the layout can be modified.
187         alertDialog.show();
188
189         // Get handles for the layout items.
190         EditText fileNameEditText = alertDialog.findViewById(R.id.file_name_edittext);
191         Button browseButton = alertDialog.findViewById(R.id.browse_button);
192         TextView fileExistsWarningTextView = alertDialog.findViewById(R.id.file_exists_warning_textview);
193         TextView storagePermissionTextView = alertDialog.findViewById(R.id.storage_permission_textview);
194         Button saveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
195
196         // Update the status of the save button when the file name changes.
197         fileNameEditText.addTextChangedListener(new TextWatcher() {
198             @Override
199             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
200                 // Do nothing.
201             }
202
203             @Override
204             public void onTextChanged(CharSequence s, int start, int before, int count) {
205                 // Do nothing.
206             }
207
208             @Override
209             public void afterTextChanged(Editable s) {
210                 // Get the current file name.
211                 String fileNameString = fileNameEditText.getText().toString();
212
213                 // Convert the file name string to a file.
214                 File file = new File(fileNameString);
215
216                 // Check to see if the file exists.
217                 if (file.exists()) {
218                     // Show the file exists warning.
219                     fileExistsWarningTextView.setVisibility(View.VISIBLE);
220                 } else {
221                     // Hide the file exists warning.
222                     fileExistsWarningTextView.setVisibility(View.GONE);
223                 }
224
225                 // Enable the save button if the file name is populated.
226                 saveButton.setEnabled(!fileNameString.isEmpty());
227             }
228         });
229
230         // Create a default file name string.
231         String defaultFileName = "";
232
233         // Set the default file name according to the type.
234         switch (saveType) {
235             case StoragePermissionDialog.SAVE_ARCHIVE:
236                 defaultFileName = getString(R.string.webpage_mht);
237                 break;
238
239             case StoragePermissionDialog.SAVE_IMAGE:
240                 defaultFileName = getString(R.string.webpage_png);
241                 break;
242         }
243
244         // Create a string for the default file path.
245         String defaultFilePath;
246
247         // Set the default file path according to the storage permission state.
248         if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {  // The storage permission has been granted.
249             // Set the default file path to use the external public directory.
250             defaultFilePath = Environment.getExternalStorageDirectory() + "/" + defaultFileName;
251
252             // Hide the storage permission text view.
253             storagePermissionTextView.setVisibility(View.GONE);
254         } else {  // The storage permission has not been granted.
255             // Set the default file path to use the external private directory.
256             defaultFilePath = context.getExternalFilesDir(null) + "/" + defaultFileName;
257         }
258
259         // Display the default file path.
260         fileNameEditText.setText(defaultFilePath);
261
262         // Move the cursor to the end of the default file path.
263         fileNameEditText.setSelection(defaultFilePath.length());
264
265         // Handle clicks on the browse button.
266         browseButton.setOnClickListener((View view) -> {
267             // Create the file picker intent.
268             Intent browseIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
269
270             // Set the intent MIME type to include all files so that everything is visible.
271             browseIntent.setType("*/*");
272
273             // Set the initial file name according to the type.
274             switch (saveType) {
275                 case StoragePermissionDialog.SAVE_ARCHIVE:
276                     browseIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.webpage_mht));
277                     break;
278
279                 case StoragePermissionDialog.OPEN:
280                     browseIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.webpage_png));
281                     break;
282             }
283
284             // Set the initial directory if the minimum API >= 26.
285             if (Build.VERSION.SDK_INT >= 26) {
286                 browseIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
287             }
288
289             // Request a file that can be opened.
290             browseIntent.addCategory(Intent.CATEGORY_OPENABLE);
291
292             // Start the file picker.  This must be started under `activity` so that the request code is returned correctly.
293             activity.startActivityForResult(browseIntent, MainWebViewActivity.BROWSE_SAVE_WEBPAGE_REQUEST_CODE);
294         });
295
296         // Return the alert dialog.
297         return alertDialog;
298     }
299 }