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