2 * Copyright © 2019-2020 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
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.
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.
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/>.
20 package com.stoutner.privacybrowser.dialogs;
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.AsyncTask;
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;
45 import androidx.annotation.NonNull;
46 import androidx.core.content.ContextCompat;
47 import androidx.fragment.app.DialogFragment;
48 import androidx.preference.PreferenceManager;
50 import com.stoutner.privacybrowser.R;
51 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
52 import com.stoutner.privacybrowser.asynctasks.GetUrlSize;
53 import com.stoutner.privacybrowser.helpers.DownloadLocationHelper;
57 public class SaveDialog extends DialogFragment {
58 // Define the save webpage listener.
59 private SaveWebpageListener saveWebpageListener;
61 // The public interface is used to send information back to the parent activity.
62 public interface SaveWebpageListener {
63 void onSaveWebpage(int saveType, DialogFragment dialogFragment);
66 // Define the get URL size AsyncTask. This allows previous instances of the task to be cancelled if a new one is run.
67 private AsyncTask getUrlSize;
70 public void onAttach(@NonNull Context context) {
71 // Run the default commands.
72 super.onAttach(context);
74 // Get a handle for the save webpage listener from the launching context.
75 saveWebpageListener = (SaveWebpageListener) context;
78 public static SaveDialog saveUrl(int saveType, String urlString, String fileSizeString, String contentDispositionFileNameString, String userAgentString, boolean cookiesEnabled) {
79 // Create an arguments bundle.
80 Bundle argumentsBundle = new Bundle();
82 // Store the arguments in the bundle.
83 argumentsBundle.putInt("save_type", saveType);
84 argumentsBundle.putString("url_string", urlString);
85 argumentsBundle.putString("file_size_string", fileSizeString);
86 argumentsBundle.putString("content_disposition_file_name_string", contentDispositionFileNameString);
87 argumentsBundle.putString("user_agent_string", userAgentString);
88 argumentsBundle.putBoolean("cookies_enabled", cookiesEnabled);
90 // Create a new instance of the save webpage dialog.
91 SaveDialog saveWebpageDialog = new SaveDialog();
93 // Add the arguments bundle to the new dialog.
94 saveWebpageDialog.setArguments(argumentsBundle);
96 // Return the new dialog.
97 return saveWebpageDialog;
100 // `@SuppressLint("InflateParams")` removes the warning about using null as the parent view group when inflating the alert dialog.
101 @SuppressLint("InflateParams")
104 public Dialog onCreateDialog(Bundle savedInstanceState) {
105 // Get a handle for the arguments.
106 Bundle arguments = getArguments();
108 // Remove the incorrect lint warning that the arguments might be null.
109 assert arguments != null;
111 // Get the arguments from the bundle.
112 int saveType = arguments.getInt("save_type");
113 String urlString = arguments.getString("url_string");
114 String fileSizeString = arguments.getString("file_size_string");
115 String contentDispositionFileNameString = arguments.getString("content_disposition_file_name_string");
116 String userAgentString = arguments.getString("user_agent_string");
117 boolean cookiesEnabled = arguments.getBoolean("cookies_enabled");
119 // Get a handle for the activity and the context.
120 Activity activity = getActivity();
121 Context context = getContext();
123 // Remove the incorrect lint warnings below that the activity and context might be null.
124 assert activity != null;
125 assert context != null;
127 // Get a handle for the shared preferences.
128 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
130 // Get the screenshot and theme preferences.
131 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
132 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
134 // Use an alert dialog builder to create the alert dialog.
135 AlertDialog.Builder dialogBuilder;
137 // Set the style and icon according to the theme.
140 dialogBuilder = new AlertDialog.Builder(activity, R.style.PrivacyBrowserAlertDialogDark);
142 // Set the icon according to the save type.
144 case StoragePermissionDialog.SAVE_URL:
145 dialogBuilder.setIcon(R.drawable.copy_enabled_dark);
148 case StoragePermissionDialog.SAVE_AS_ARCHIVE:
149 dialogBuilder.setIcon(R.drawable.dom_storage_cleared_dark);
152 case StoragePermissionDialog.SAVE_AS_IMAGE:
153 dialogBuilder.setIcon(R.drawable.images_enabled_dark);
158 dialogBuilder = new AlertDialog.Builder(activity, R.style.PrivacyBrowserAlertDialogLight);
160 // Set the icon according to the save type.
162 case StoragePermissionDialog.SAVE_URL:
163 dialogBuilder.setIcon(R.drawable.copy_enabled_light);
166 case StoragePermissionDialog.SAVE_AS_ARCHIVE:
167 dialogBuilder.setIcon(R.drawable.dom_storage_cleared_light);
170 case StoragePermissionDialog.SAVE_AS_IMAGE:
171 dialogBuilder.setIcon(R.drawable.images_enabled_light);
176 // Set the title according to the type.
178 case StoragePermissionDialog.SAVE_URL:
179 dialogBuilder.setTitle(R.string.save);
182 case StoragePermissionDialog.SAVE_AS_ARCHIVE:
183 dialogBuilder.setTitle(R.string.save_archive);
186 case StoragePermissionDialog.SAVE_AS_IMAGE:
187 dialogBuilder.setTitle(R.string.save_image);
191 // Set the view. The parent view is null because it will be assigned by the alert dialog.
192 dialogBuilder.setView(activity.getLayoutInflater().inflate(R.layout.save_dialog, null));
194 // Set the cancel button listener. Using `null` as the listener closes the dialog without doing anything else.
195 dialogBuilder.setNegativeButton(R.string.cancel, null);
197 // Set the save button listener.
198 dialogBuilder.setPositiveButton(R.string.save, (DialogInterface dialog, int which) -> {
199 // Return the dialog fragment to the parent activity.
200 saveWebpageListener.onSaveWebpage(saveType, this);
203 // Create an alert dialog from the builder.
204 AlertDialog alertDialog = dialogBuilder.create();
206 // Remove the incorrect lint warning below that the window might be null.
207 assert alertDialog.getWindow() != null;
209 // Disable screenshots if not allowed.
210 if (!allowScreenshots) {
211 alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
214 // The alert dialog must be shown before items in the layout can be modified.
217 // Get handles for the layout items.
218 EditText urlEditText = alertDialog.findViewById(R.id.url_edittext);
219 EditText fileNameEditText = alertDialog.findViewById(R.id.file_name_edittext);
220 Button browseButton = alertDialog.findViewById(R.id.browse_button);
221 TextView fileSizeTextView = alertDialog.findViewById(R.id.file_size_textview);
222 TextView fileExistsWarningTextView = alertDialog.findViewById(R.id.file_exists_warning_textview);
223 TextView storagePermissionTextView = alertDialog.findViewById(R.id.storage_permission_textview);
224 Button saveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
226 // Set the file size text view.
227 fileSizeTextView.setText(fileSizeString);
229 // Modify the layout based on the save type.
230 if (saveType == StoragePermissionDialog.SAVE_URL) { // A URL is being saved.
231 // Populate the URL edit text. This must be done before the text change listener is created below so that the file size isn't requested again.
232 urlEditText.setText(urlString);
234 // Update the file size and the status of the save button when the URL changes.
235 urlEditText.addTextChangedListener(new TextWatcher() {
237 public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
242 public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
247 public void afterTextChanged(Editable editable) {
248 // Cancel the get URL size AsyncTask if it is running.
249 if ((getUrlSize != null)) {
250 getUrlSize.cancel(true);
253 // Get the current URL to save.
254 String urlToSave = urlEditText.getText().toString();
256 // Wipe the file size text view.
257 fileSizeTextView.setText("");
259 // Get the file size for the current URL.
260 getUrlSize = new GetUrlSize(context, alertDialog, userAgentString, cookiesEnabled).execute(urlToSave);
262 // Enable the save button if the URL and file name are populated.
263 saveButton.setEnabled(!urlToSave.isEmpty() && !fileNameEditText.getText().toString().isEmpty());
266 } else { // An archive or an image is being saved.
267 // Hide the URL edit text and the file size text view.
268 urlEditText.setVisibility(View.GONE);
269 fileSizeTextView.setVisibility(View.GONE);
272 // Update the status of the save button when the file name changes.
273 fileNameEditText.addTextChangedListener(new TextWatcher() {
275 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
280 public void onTextChanged(CharSequence s, int start, int before, int count) {
285 public void afterTextChanged(Editable s) {
286 // Get the current file name.
287 String fileNameString = fileNameEditText.getText().toString();
289 // Convert the file name string to a file.
290 File file = new File(fileNameString);
292 // Check to see if the file exists.
294 // Show the file exists warning.
295 fileExistsWarningTextView.setVisibility(View.VISIBLE);
297 // Hide the file exists warning.
298 fileExistsWarningTextView.setVisibility(View.GONE);
301 // Enable the save button based on the save type.
302 if (saveType == StoragePermissionDialog.SAVE_URL) { // A URL is being saved.
303 // Enable the save button if the file name and the URL is populated.
304 saveButton.setEnabled(!fileNameString.isEmpty() && !urlEditText.getText().toString().isEmpty());
305 } else { // An archive or an image is being saved.
306 // Enable the save button if the file name is populated.
307 saveButton.setEnabled(!fileNameString.isEmpty());
312 // Create a file name string.
313 String fileName = "";
315 // Set the file name according to the type.
317 case StoragePermissionDialog.SAVE_URL:
318 // Use the file name from the content disposition.
319 fileName = contentDispositionFileNameString;
322 case StoragePermissionDialog.SAVE_AS_ARCHIVE:
323 // Use an archive name ending in `.mht`.
324 fileName = getString(R.string.webpage_mht);
327 case StoragePermissionDialog.SAVE_AS_IMAGE:
328 // Use a file name ending in `.png`.
329 fileName = getString(R.string.webpage_png);
333 // Save the file name as the default file name. This must be final to be used in the lambda below.
334 final String defaultFileName = fileName;
336 // Instantiate the download location helper.
337 DownloadLocationHelper downloadLocationHelper = new DownloadLocationHelper();
339 // Get the default file path.
340 String defaultFilePath = downloadLocationHelper.getDownloadLocation(context) + "/" + defaultFileName;
342 // Populate the file name edit text.
343 fileNameEditText.setText(defaultFilePath);
345 // Move the cursor to the end of the default file path.
346 fileNameEditText.setSelection(defaultFilePath.length());
348 // Handle clicks on the browse button.
349 browseButton.setOnClickListener((View view) -> {
350 // Create the file picker intent.
351 Intent browseIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
353 // Set the intent MIME type to include all files so that everything is visible.
354 browseIntent.setType("*/*");
356 // Set the initial file name according to the type.
357 browseIntent.putExtra(Intent.EXTRA_TITLE, defaultFileName);
359 // Set the initial directory if the minimum API >= 26.
360 if (Build.VERSION.SDK_INT >= 26) {
361 browseIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
364 // Request a file that can be opened.
365 browseIntent.addCategory(Intent.CATEGORY_OPENABLE);
367 // Start the file picker. This must be started under `activity` so that the request code is returned correctly.
368 activity.startActivityForResult(browseIntent, MainWebViewActivity.BROWSE_SAVE_WEBPAGE_REQUEST_CODE);
371 // Hide the storage permission text view if the permission has already been granted.
372 if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
373 storagePermissionTextView.setVisibility(View.GONE);
376 // Return the alert dialog.