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.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;
44 import androidx.annotation.NonNull;
45 import androidx.core.content.ContextCompat;
46 import androidx.fragment.app.DialogFragment;
47 import androidx.preference.PreferenceManager;
49 import com.stoutner.privacybrowser.R;
50 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
54 public class SaveWebpageDialog extends DialogFragment {
55 // Define the save webpage listener.
56 private SaveWebpageListener saveWebpageListener;
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);
64 public void onAttach(@NonNull Context context) {
65 // Run the default commands.
66 super.onAttach(context);
68 // Get a handle for the save webpage listener from the launching context.
69 saveWebpageListener = (SaveWebpageListener) context;
72 public static SaveWebpageDialog saveWebpage(int saveType) {
73 // Create an arguments bundle.
74 Bundle argumentsBundle = new Bundle();
76 // Store the save type in the bundle.
77 argumentsBundle.putInt("save_type", saveType);
79 // Create a new instance of the save webpage dialog.
80 SaveWebpageDialog saveWebpageDialog = new SaveWebpageDialog();
82 // Add the arguments bundle to the new dialog.
83 saveWebpageDialog.setArguments(argumentsBundle);
85 // Return the new dialog.
86 return saveWebpageDialog;
89 // `@SuppressLint("InflateParams")` removes the warning about using null as the parent view group when inflating the alert dialog.
90 @SuppressLint("InflateParams")
93 public Dialog onCreateDialog(Bundle savedInstanceState) {
94 // Get a handle for the arguments.
95 Bundle arguments = getArguments();
97 // Remove the incorrect lint warning that the arguments might be null.
98 assert arguments != null;
100 // Get the save type.
101 int saveType = arguments.getInt("save_type");
103 // Get a handle for the activity and the context.
104 Activity activity = getActivity();
105 Context context = getContext();
107 // Remove the incorrect lint warnings below that the activity and context might be null.
108 assert activity != null;
109 assert context != null;
111 // Get a handle for the shared preferences.
112 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
114 // Get the screenshot and theme preferences.
115 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
116 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
118 // Use an alert dialog builder to create the alert dialog.
119 AlertDialog.Builder dialogBuilder;
121 // Set the style and icon according to the theme.
124 dialogBuilder = new AlertDialog.Builder(activity, R.style.PrivacyBrowserAlertDialogDark);
126 // Set the icon according to the save type.
128 case StoragePermissionDialog.SAVE_ARCHIVE:
129 dialogBuilder.setIcon(R.drawable.dom_storage_cleared_dark);
132 case StoragePermissionDialog.SAVE_IMAGE:
133 dialogBuilder.setIcon(R.drawable.images_enabled_dark);
138 dialogBuilder = new AlertDialog.Builder(activity, R.style.PrivacyBrowserAlertDialogLight);
140 // Set the icon according to the save type.
142 case StoragePermissionDialog.SAVE_ARCHIVE:
143 dialogBuilder.setIcon(R.drawable.dom_storage_cleared_light);
146 case StoragePermissionDialog.SAVE_IMAGE:
147 dialogBuilder.setIcon(R.drawable.images_enabled_light);
152 // Set the title according to the type.
154 case StoragePermissionDialog.SAVE_ARCHIVE:
155 dialogBuilder.setTitle(R.string.save_archive);
158 case StoragePermissionDialog.SAVE_IMAGE:
159 dialogBuilder.setTitle(R.string.save_image);
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));
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);
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);
175 // Create an alert dialog from the builder.
176 AlertDialog alertDialog = dialogBuilder.create();
178 // Remove the incorrect lint warning below that the window might be null.
179 assert alertDialog.getWindow() != null;
181 // Disable screenshots if not allowed.
182 if (!allowScreenshots) {
183 alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
186 // The alert dialog must be shown before items in the layout can be modified.
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);
196 // Update the status of the save button when the file name changes.
197 fileNameEditText.addTextChangedListener(new TextWatcher() {
199 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
204 public void onTextChanged(CharSequence s, int start, int before, int count) {
209 public void afterTextChanged(Editable s) {
210 // Get the current file name.
211 String fileNameString = fileNameEditText.getText().toString();
213 // Convert the file name string to a file.
214 File file = new File(fileNameString);
216 // Check to see if the file exists.
218 // Show the file exists warning.
219 fileExistsWarningTextView.setVisibility(View.VISIBLE);
221 // Hide the file exists warning.
222 fileExistsWarningTextView.setVisibility(View.GONE);
225 // Enable the save button if the file name is populated.
226 saveButton.setEnabled(!fileNameString.isEmpty());
230 // Create a default file name string.
231 String defaultFileName = "";
233 // Set the default file name according to the type.
235 case StoragePermissionDialog.SAVE_ARCHIVE:
236 defaultFileName = getString(R.string.webpage_mht);
239 case StoragePermissionDialog.SAVE_IMAGE:
240 defaultFileName = getString(R.string.webpage_png);
244 // Create a string for the default file path.
245 String defaultFilePath;
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;
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;
259 // Display the default file path.
260 fileNameEditText.setText(defaultFilePath);
262 // Move the cursor to the end of the default file path.
263 fileNameEditText.setSelection(defaultFilePath.length());
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);
270 // Set the intent MIME type to include all files so that everything is visible.
271 browseIntent.setType("*/*");
273 // Set the initial file name according to the type.
275 case StoragePermissionDialog.SAVE_ARCHIVE:
276 browseIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.webpage_mht));
279 case StoragePermissionDialog.OPEN:
280 browseIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.webpage_png));
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());
289 // Request a file that can be opened.
290 browseIntent.addCategory(Intent.CATEGORY_OPENABLE);
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);
296 // Return the alert dialog.