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.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;
55 public class SaveWebpageDialog extends DialogFragment {
56 // Define the save webpage listener.
57 private SaveWebpageListener saveWebpageListener;
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);
65 public void onAttach(@NonNull Context context) {
66 // Run the default commands.
67 super.onAttach(context);
69 // Get a handle for the save webpage listener from the launching context.
70 saveWebpageListener = (SaveWebpageListener) context;
73 public static SaveWebpageDialog saveUrl(int saveType, String url) {
74 // Create an arguments bundle.
75 Bundle argumentsBundle = new Bundle();
77 // Store the arguments in the bundle.
78 argumentsBundle.putInt("save_type", saveType);
79 argumentsBundle.putString("url", url);
81 // Create a new instance of the save webpage dialog.
82 SaveWebpageDialog saveWebpageDialog = new SaveWebpageDialog();
84 // Add the arguments bundle to the new dialog.
85 saveWebpageDialog.setArguments(argumentsBundle);
87 // Return the new dialog.
88 return saveWebpageDialog;
91 // `@SuppressLint("InflateParams")` removes the warning about using null as the parent view group when inflating the alert dialog.
92 @SuppressLint("InflateParams")
95 public Dialog onCreateDialog(Bundle savedInstanceState) {
96 // Get a handle for the arguments.
97 Bundle arguments = getArguments();
99 // Remove the incorrect lint warning that the arguments might be null.
100 assert arguments != null;
102 // Get the arguments from the bundle.
103 int saveType = arguments.getInt("save_type");
104 String url = arguments.getString("url");
106 // Get a handle for the activity and the context.
107 Activity activity = getActivity();
108 Context context = getContext();
110 // Remove the incorrect lint warnings below that the activity and context might be null.
111 assert activity != null;
112 assert context != null;
114 // Get a handle for the shared preferences.
115 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
117 // Get the screenshot and theme preferences.
118 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
119 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
121 // Use an alert dialog builder to create the alert dialog.
122 AlertDialog.Builder dialogBuilder;
124 // Set the style and icon according to the theme.
127 dialogBuilder = new AlertDialog.Builder(activity, R.style.PrivacyBrowserAlertDialogDark);
129 // Set the icon according to the save type.
131 case StoragePermissionDialog.SAVE:
132 dialogBuilder.setIcon(R.drawable.copy_enabled_dark);
135 case StoragePermissionDialog.SAVE_AS_ARCHIVE:
136 dialogBuilder.setIcon(R.drawable.dom_storage_cleared_dark);
139 case StoragePermissionDialog.SAVE_AS_IMAGE:
140 dialogBuilder.setIcon(R.drawable.images_enabled_dark);
145 dialogBuilder = new AlertDialog.Builder(activity, R.style.PrivacyBrowserAlertDialogLight);
147 // Set the icon according to the save type.
149 case StoragePermissionDialog.SAVE:
150 dialogBuilder.setIcon(R.drawable.copy_enabled_light);
153 case StoragePermissionDialog.SAVE_AS_ARCHIVE:
154 dialogBuilder.setIcon(R.drawable.dom_storage_cleared_light);
157 case StoragePermissionDialog.SAVE_AS_IMAGE:
158 dialogBuilder.setIcon(R.drawable.images_enabled_light);
163 // Set the title according to the type.
165 case StoragePermissionDialog.SAVE:
166 dialogBuilder.setTitle(R.string.save);
169 case StoragePermissionDialog.SAVE_AS_ARCHIVE:
170 dialogBuilder.setTitle(R.string.save_archive);
173 case StoragePermissionDialog.SAVE_AS_IMAGE:
174 dialogBuilder.setTitle(R.string.save_image);
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));
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);
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);
190 // Create an alert dialog from the builder.
191 AlertDialog alertDialog = dialogBuilder.create();
193 // Remove the incorrect lint warning below that the window might be null.
194 assert alertDialog.getWindow() != null;
196 // Disable screenshots if not allowed.
197 if (!allowScreenshots) {
198 alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
201 // The alert dialog must be shown before items in the layout can be modified.
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);
212 // Update the status of the save button whe the URL changes.
213 urlEditText.addTextChangedListener(new TextWatcher() {
215 public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
220 public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
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());
231 // Update the status of the save button when the file name changes.
232 fileNameEditText.addTextChangedListener(new TextWatcher() {
234 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
239 public void onTextChanged(CharSequence s, int start, int before, int count) {
244 public void afterTextChanged(Editable s) {
245 // Get the current file name.
246 String fileNameString = fileNameEditText.getText().toString();
248 // Convert the file name string to a file.
249 File file = new File(fileNameString);
251 // Check to see if the file exists.
253 // Show the file exists warning.
254 fileExistsWarningTextView.setVisibility(View.VISIBLE);
256 // Hide the file exists warning.
257 fileExistsWarningTextView.setVisibility(View.GONE);
260 // Enable the save button if the file name is populated.
261 saveButton.setEnabled(!fileNameString.isEmpty() && !urlEditText.getText().toString().isEmpty());
265 // Create a file name string.
266 String fileName = "";
268 // Set the file name according to the type.
270 case StoragePermissionDialog.SAVE:
271 // Convert the URL to a URI.
272 Uri uri = Uri.parse(url);
274 // Get the last path segment.
275 String lastPathSegment = uri.getLastPathSegment();
277 // Use a default file name if the last path segment is null.
278 if (lastPathSegment == null) {
279 lastPathSegment = getString(R.string.file);
282 // Use the last path segment as the file name.
283 fileName = lastPathSegment;
286 case StoragePermissionDialog.SAVE_AS_ARCHIVE:
287 fileName = getString(R.string.webpage_mht);
290 case StoragePermissionDialog.SAVE_AS_IMAGE:
291 fileName = getString(R.string.webpage_png);
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;
298 // Create a string for the default file path.
299 String defaultFilePath;
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;
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;
313 // Populate the edit texts.
314 urlEditText.setText(url);
315 fileNameEditText.setText(defaultFilePath);
317 // Move the cursor to the end of the default file path.
318 fileNameEditText.setSelection(defaultFilePath.length());
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);
325 // Set the intent MIME type to include all files so that everything is visible.
326 browseIntent.setType("*/*");
328 // Set the initial file name according to the type.
329 browseIntent.putExtra(Intent.EXTRA_TITLE, defaultFileName);
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());
336 // Request a file that can be opened.
337 browseIntent.addCategory(Intent.CATEGORY_OPENABLE);
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);
343 // Return the alert dialog.