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.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;
46 import androidx.annotation.NonNull;
47 import androidx.core.content.ContextCompat;
48 import androidx.fragment.app.DialogFragment;
49 import androidx.preference.PreferenceManager;
51 import com.stoutner.privacybrowser.R;
52 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
53 import com.stoutner.privacybrowser.asynctasks.GetUrlSize;
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 url, String userAgent, 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", url);
85 argumentsBundle.putString("user_agent", userAgent);
86 argumentsBundle.putBoolean("cookies_enabled", cookiesEnabled);
88 // Create a new instance of the save webpage dialog.
89 SaveDialog saveWebpageDialog = new SaveDialog();
91 // Add the arguments bundle to the new dialog.
92 saveWebpageDialog.setArguments(argumentsBundle);
94 // Return the new dialog.
95 return saveWebpageDialog;
98 // `@SuppressLint("InflateParams")` removes the warning about using null as the parent view group when inflating the alert dialog.
99 @SuppressLint("InflateParams")
102 public Dialog onCreateDialog(Bundle savedInstanceState) {
103 // Get a handle for the arguments.
104 Bundle arguments = getArguments();
106 // Remove the incorrect lint warning that the arguments might be null.
107 assert arguments != null;
109 // Get the arguments from the bundle.
110 int saveType = arguments.getInt("save_type");
111 String url = arguments.getString("url");
112 String userAgent = arguments.getString("user_agent");
113 boolean cookiesEnabled = arguments.getBoolean("cookies_enabled");
115 // Get a handle for the activity and the context.
116 Activity activity = getActivity();
117 Context context = getContext();
119 // Remove the incorrect lint warnings below that the activity and context might be null.
120 assert activity != null;
121 assert context != null;
123 // Get a handle for the shared preferences.
124 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
126 // Get the screenshot and theme preferences.
127 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
128 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
130 // Use an alert dialog builder to create the alert dialog.
131 AlertDialog.Builder dialogBuilder;
133 // Set the style and icon according to the theme.
136 dialogBuilder = new AlertDialog.Builder(activity, R.style.PrivacyBrowserAlertDialogDark);
138 // Set the icon according to the save type.
140 case StoragePermissionDialog.SAVE_URL:
141 dialogBuilder.setIcon(R.drawable.copy_enabled_dark);
144 case StoragePermissionDialog.SAVE_AS_ARCHIVE:
145 dialogBuilder.setIcon(R.drawable.dom_storage_cleared_dark);
148 case StoragePermissionDialog.SAVE_AS_IMAGE:
149 dialogBuilder.setIcon(R.drawable.images_enabled_dark);
154 dialogBuilder = new AlertDialog.Builder(activity, R.style.PrivacyBrowserAlertDialogLight);
156 // Set the icon according to the save type.
158 case StoragePermissionDialog.SAVE_URL:
159 dialogBuilder.setIcon(R.drawable.copy_enabled_light);
162 case StoragePermissionDialog.SAVE_AS_ARCHIVE:
163 dialogBuilder.setIcon(R.drawable.dom_storage_cleared_light);
166 case StoragePermissionDialog.SAVE_AS_IMAGE:
167 dialogBuilder.setIcon(R.drawable.images_enabled_light);
172 // Set the title according to the type.
174 case StoragePermissionDialog.SAVE_URL:
175 dialogBuilder.setTitle(R.string.save);
178 case StoragePermissionDialog.SAVE_AS_ARCHIVE:
179 dialogBuilder.setTitle(R.string.save_archive);
182 case StoragePermissionDialog.SAVE_AS_IMAGE:
183 dialogBuilder.setTitle(R.string.save_image);
187 // Set the view. The parent view is null because it will be assigned by the alert dialog.
188 dialogBuilder.setView(activity.getLayoutInflater().inflate(R.layout.save_dialog, null));
190 // Set the cancel button listener. Using `null` as the listener closes the dialog without doing anything else.
191 dialogBuilder.setNegativeButton(R.string.cancel, null);
193 // Set the save button listener.
194 dialogBuilder.setPositiveButton(R.string.save, (DialogInterface dialog, int which) -> {
195 // Return the dialog fragment to the parent activity.
196 saveWebpageListener.onSaveWebpage(saveType, this);
199 // Create an alert dialog from the builder.
200 AlertDialog alertDialog = dialogBuilder.create();
202 // Remove the incorrect lint warning below that the window might be null.
203 assert alertDialog.getWindow() != null;
205 // Disable screenshots if not allowed.
206 if (!allowScreenshots) {
207 alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
210 // The alert dialog must be shown before items in the layout can be modified.
213 // Get handles for the layout items.
214 EditText urlEditText = alertDialog.findViewById(R.id.url_edittext);
215 EditText fileNameEditText = alertDialog.findViewById(R.id.file_name_edittext);
216 Button browseButton = alertDialog.findViewById(R.id.browse_button);
217 TextView fileSizeTextView = alertDialog.findViewById(R.id.file_size_textview);
218 TextView fileExistsWarningTextView = alertDialog.findViewById(R.id.file_exists_warning_textview);
219 TextView storagePermissionTextView = alertDialog.findViewById(R.id.storage_permission_textview);
220 Button saveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
222 // Update the status of the save button whe the URL changes.
223 urlEditText.addTextChangedListener(new TextWatcher() {
225 public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
230 public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
235 public void afterTextChanged(Editable editable) {
236 // Cancel the get URL size AsyncTask if it is running.
237 if ((getUrlSize != null)) {
238 getUrlSize.cancel(true);
241 // Get the current URL to save.
242 String urlToSave = urlEditText.getText().toString();
244 // Wipe the file size text view.
245 fileSizeTextView.setText("");
247 // Get the file size for the current URL.
248 getUrlSize = new GetUrlSize(context, alertDialog, userAgent, cookiesEnabled).execute(urlToSave);
250 // Enable the save button if the URL and file name are populated.
251 saveButton.setEnabled(!urlToSave.isEmpty() && !fileNameEditText.getText().toString().isEmpty());
255 // Update the status of the save button when the file name changes.
256 fileNameEditText.addTextChangedListener(new TextWatcher() {
258 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
263 public void onTextChanged(CharSequence s, int start, int before, int count) {
268 public void afterTextChanged(Editable s) {
269 // Get the current file name.
270 String fileNameString = fileNameEditText.getText().toString();
272 // Convert the file name string to a file.
273 File file = new File(fileNameString);
275 // Check to see if the file exists.
277 // Show the file exists warning.
278 fileExistsWarningTextView.setVisibility(View.VISIBLE);
280 // Hide the file exists warning.
281 fileExistsWarningTextView.setVisibility(View.GONE);
284 // Enable the save button if the file name is populated.
285 saveButton.setEnabled(!fileNameString.isEmpty() && !urlEditText.getText().toString().isEmpty());
289 // Create a file name string.
290 String fileName = "";
292 // Set the file name according to the type.
294 case StoragePermissionDialog.SAVE_URL:
295 // Convert the URL to a URI.
296 Uri uri = Uri.parse(url);
298 // Get the last path segment.
299 String lastPathSegment = uri.getLastPathSegment();
301 // Use a default file name if the last path segment is null.
302 if (lastPathSegment == null) {
303 lastPathSegment = getString(R.string.file);
306 // Use the last path segment as the file name.
307 fileName = lastPathSegment;
310 case StoragePermissionDialog.SAVE_AS_ARCHIVE:
311 fileName = getString(R.string.webpage_mht);
314 case StoragePermissionDialog.SAVE_AS_IMAGE:
315 fileName = getString(R.string.webpage_png);
319 // Save the file name as the default file name. This must be final to be used in the lambda below.
320 final String defaultFileName = fileName;
322 // Create a string for the default file path.
323 String defaultFilePath;
325 // Set the default file path according to the storage permission state.
326 if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // The storage permission has been granted.
327 // Set the default file path to use the external public directory.
328 defaultFilePath = Environment.getExternalStorageDirectory() + "/" + defaultFileName;
330 // Hide the storage permission text view.
331 storagePermissionTextView.setVisibility(View.GONE);
332 } else { // The storage permission has not been granted.
333 // Set the default file path to use the external private directory.
334 defaultFilePath = context.getExternalFilesDir(null) + "/" + defaultFileName;
337 // Populate the edit texts.
338 urlEditText.setText(url);
339 fileNameEditText.setText(defaultFilePath);
341 // Move the cursor to the end of the default file path.
342 fileNameEditText.setSelection(defaultFilePath.length());
344 // Handle clicks on the browse button.
345 browseButton.setOnClickListener((View view) -> {
346 // Create the file picker intent.
347 Intent browseIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
349 // Set the intent MIME type to include all files so that everything is visible.
350 browseIntent.setType("*/*");
352 // Set the initial file name according to the type.
353 browseIntent.putExtra(Intent.EXTRA_TITLE, defaultFileName);
355 // Set the initial directory if the minimum API >= 26.
356 if (Build.VERSION.SDK_INT >= 26) {
357 browseIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
360 // Request a file that can be opened.
361 browseIntent.addCategory(Intent.CATEGORY_OPENABLE);
363 // Start the file picker. This must be started under `activity` so that the request code is returned correctly.
364 activity.startActivityForResult(browseIntent, MainWebViewActivity.BROWSE_SAVE_WEBPAGE_REQUEST_CODE);
367 // Return the alert dialog.