2 * Copyright © 2019 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;
52 public class SaveWebpageDialog extends DialogFragment {
53 // Define the save webpage listener.
54 private SaveWebpageListener saveWebpageListener;
56 // The public interface is used to send information back to the parent activity.
57 public interface SaveWebpageListener {
58 void onSaveWebpage(int saveType, DialogFragment dialogFragment);
62 public void onAttach(@NonNull Context context) {
63 // Run the default commands.
64 super.onAttach(context);
66 // Get a handle for the save webpage listener from the launching context.
67 saveWebpageListener = (SaveWebpageListener) context;
70 public static SaveWebpageDialog saveWebpage(int saveType) {
71 // Create an arguments bundle.
72 Bundle argumentsBundle = new Bundle();
74 // Store the save type in the bundle.
75 argumentsBundle.putInt("save_type", saveType);
77 // Create a new instance of the save webpage dialog.
78 SaveWebpageDialog saveWebpageDialog = new SaveWebpageDialog();
80 // Add the arguments bundle to the new dialog.
81 saveWebpageDialog.setArguments(argumentsBundle);
83 // Return the new dialog.
84 return saveWebpageDialog;
87 // `@SuppressLint("InflateParams")` removes the warning about using null as the parent view group when inflating the alert dialog.
88 @SuppressLint("InflateParams")
91 public Dialog onCreateDialog(Bundle savedInstanceState) {
92 // Get a handle for the arguments.
93 Bundle arguments = getArguments();
95 // Remove the incorrect lint warning that the arguments might be null.
96 assert arguments != null;
99 int saveType = arguments.getInt("save_type");
101 // Get a handle for the activity and the context.
102 Activity activity = getActivity();
103 Context context = getContext();
105 // Remove the incorrect lint warnings below that the activity and context might be null.
106 assert activity != null;
107 assert context != null;
109 // Get a handle for the shared preferences.
110 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
112 // Get the screenshot and theme preferences.
113 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
114 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
116 // Use an alert dialog builder to create the alert dialog.
117 AlertDialog.Builder dialogBuilder;
119 // Set the style and icon according to the theme.
122 dialogBuilder = new AlertDialog.Builder(activity, R.style.PrivacyBrowserAlertDialogDark);
124 // Set the icon according to the save type.
126 case StoragePermissionDialog.SAVE_ARCHIVE:
127 dialogBuilder.setIcon(R.drawable.dom_storage_cleared_dark);
130 case StoragePermissionDialog.SAVE_IMAGE:
131 dialogBuilder.setIcon(R.drawable.images_enabled_dark);
136 dialogBuilder = new AlertDialog.Builder(activity, R.style.PrivacyBrowserAlertDialogLight);
138 // Set the icon according to the save type.
140 case StoragePermissionDialog.SAVE_ARCHIVE:
141 dialogBuilder.setIcon(R.drawable.dom_storage_cleared_light);
144 case StoragePermissionDialog.SAVE_IMAGE:
145 dialogBuilder.setIcon(R.drawable.images_enabled_light);
150 // Set the title according to the type.
152 case StoragePermissionDialog.SAVE_ARCHIVE:
153 dialogBuilder.setTitle(R.string.save_archive);
156 case StoragePermissionDialog.SAVE_IMAGE:
157 dialogBuilder.setTitle(R.string.save_image);
161 // Set the view. The parent view is null because it will be assigned by the alert dialog.
162 dialogBuilder.setView(activity.getLayoutInflater().inflate(R.layout.save_dialog, null));
164 // Set the cancel button listener. Using `null` as the listener closes the dialog without doing anything else.
165 dialogBuilder.setNegativeButton(R.string.cancel, null);
167 // Set the save button listener.
168 dialogBuilder.setPositiveButton(R.string.save, (DialogInterface dialog, int which) -> {
169 // Return the dialog fragment to the parent activity.
170 saveWebpageListener.onSaveWebpage(saveType, this);
173 // Create an alert dialog from the builder.
174 AlertDialog alertDialog = dialogBuilder.create();
176 // Remove the incorrect lint warning below that the window might be null.
177 assert alertDialog.getWindow() != null;
179 // Disable screenshots if not allowed.
180 if (!allowScreenshots) {
181 alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
184 // The alert dialog must be shown before items in the layout can be modified.
187 // Get handles for the layout items.
188 EditText fileNameEditText = alertDialog.findViewById(R.id.file_name_edittext);
189 Button browseButton = alertDialog.findViewById(R.id.browse_button);
190 TextView storagePermissionTextView = alertDialog.findViewById(R.id.storage_permission_textview);
191 Button saveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
193 // Create a default file name string.
194 String defaultFileName = "";
196 // Set the default file name according to the type.
198 case StoragePermissionDialog.SAVE_ARCHIVE:
199 defaultFileName = getString(R.string.webpage_mht);
202 case StoragePermissionDialog.SAVE_IMAGE:
203 defaultFileName = getString(R.string.webpage_png);
207 // Create a string for the default file path.
208 String defaultFilePath;
210 // Set the default file path according to the storage permission state.
211 if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // The storage permission has been granted.
212 // Set the default file path to use the external public directory.
213 defaultFilePath = Environment.getExternalStorageDirectory() + "/" + defaultFileName;
214 } else { // The storage permission has not been granted.
215 // Set the default file path to use the external private directory.
216 defaultFilePath = context.getExternalFilesDir(null) + "/" + defaultFileName;
219 // Display the default file path.
220 fileNameEditText.setText(defaultFilePath);
222 // Move the cursor to the end of the default file path.
223 fileNameEditText.setSelection(defaultFilePath.length());
225 // Update the status of the save button when the file name changes.
226 fileNameEditText.addTextChangedListener(new TextWatcher() {
228 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
233 public void onTextChanged(CharSequence s, int start, int before, int count) {
238 public void afterTextChanged(Editable s) {
239 // Enable the save button if a file name exists.
240 saveButton.setEnabled(!fileNameEditText.getText().toString().isEmpty());
244 // Handle clicks on the browse button.
245 browseButton.setOnClickListener((View view) -> {
246 // Create the file picker intent.
247 Intent browseIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
249 // Set the intent MIME type to include all files so that everything is visible.
250 browseIntent.setType("*/*");
252 // Set the initial file name according to the type.
254 case StoragePermissionDialog.SAVE_ARCHIVE:
255 browseIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.webpage_mht));
258 case StoragePermissionDialog.OPEN:
259 browseIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.webpage_png));
263 // Set the initial directory if the minimum API >= 26.
264 if (Build.VERSION.SDK_INT >= 26) {
265 browseIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
268 // Request a file that can be opened.
269 browseIntent.addCategory(Intent.CATEGORY_OPENABLE);
271 // Start the file picker. This must be started under `activity` so that the request code is returned correctly.
272 activity.startActivityForResult(browseIntent, MainWebViewActivity.BROWSE_SAVE_WEBPAGE_REQUEST_CODE);
275 // Hide the storage permission text view on API < 23 as permissions on older devices are automatically granted.
276 if (Build.VERSION.SDK_INT < 23 || (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
277 storagePermissionTextView.setVisibility(View.GONE);
280 // Return the alert dialog.