]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/SaveWebpageImageDialog.java
Allow specifying any font size. https://redmine.stoutner.com/issues/504
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / SaveWebpageImageDialog.java
1 /*
2  * Copyright © 2019 Soren Stoutner <soren@stoutner.com>.
3  *
4  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 package com.stoutner.privacybrowser.dialogs;
21
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;
43
44 import androidx.annotation.NonNull;
45 import androidx.core.content.ContextCompat;
46 import androidx.fragment.app.DialogFragment;
47 import androidx.preference.PreferenceManager;
48
49 import com.stoutner.privacybrowser.R;
50 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
51
52 public class SaveWebpageImageDialog extends DialogFragment {
53     // Define the save webpage image listener.
54     private SaveWebpageImageListener saveWebpageImageListener;
55
56     // The public interface is used to send information back to the parent activity.
57     public interface SaveWebpageImageListener {
58         void onSaveWebpageImage(DialogFragment dialogFragment);
59     }
60
61     @Override
62     public void onAttach(@NonNull Context context) {
63         // Run the default commands.
64         super.onAttach(context);
65
66         // Get a handle for the save webpage image listener from the launching context.
67         saveWebpageImageListener = (SaveWebpageImageListener) context;
68     }
69
70     // `@SuppressLing("InflateParams")` removes the warning about using null as the parent view group when inflating the alert dialog.
71     @SuppressLint("InflateParams")
72     @Override
73     @NonNull
74     public Dialog onCreateDialog(Bundle savedInstanceState) {
75         // Get a handle for the activity and the context.
76         Activity activity = getActivity();
77         Context context = getContext();
78
79         // Remove the incorrect lint warnings below that the activity and context might be null.
80         assert activity != null;
81         assert context != null;
82
83         // Get a handle for the shared preferences.
84         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
85
86         // Get the screenshot and theme preferences.
87         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
88         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
89
90         // Use an alert dialog builder to create the alert dialog.
91         AlertDialog.Builder dialogBuilder;
92
93         // Set the style and icon according to the theme.
94         if (darkTheme) {
95             dialogBuilder = new AlertDialog.Builder(activity, R.style.PrivacyBrowserAlertDialogDark);
96             dialogBuilder.setIcon(R.drawable.images_enabled_dark);
97         } else {
98             dialogBuilder = new AlertDialog.Builder(activity, R.style.PrivacyBrowserAlertDialogLight);
99             dialogBuilder.setIcon(R.drawable.images_enabled_light);
100         }
101
102         // Set the title.
103         dialogBuilder.setTitle(R.string.save_image);
104
105         // Set the view.  The parent view is null because it will be assigned by the alert dialog.
106         dialogBuilder.setView(activity.getLayoutInflater().inflate(R.layout.save_dialog, null));
107
108         // Set the cancel button listener.  Using `null` as the listener closes the dialog without doing anything else.
109         dialogBuilder.setNegativeButton(R.string.cancel, null);
110
111         // Set the save button listener.
112         dialogBuilder.setPositiveButton(R.string.save, (DialogInterface dialog, int which) -> {
113             // Return the dialog fragment to the parent activity.
114             saveWebpageImageListener.onSaveWebpageImage(this);
115         });
116
117         // Create an alert dialog from the builder.
118         AlertDialog alertDialog = dialogBuilder.create();
119
120         // Remove the incorrect lint warning below that `getWindow()` might be null.
121         assert alertDialog.getWindow() != null;
122
123         // Disable screenshots if not allowed.
124         if (!allowScreenshots) {
125             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
126         }
127
128         // The alert dialog must be shown before items in the layout can be modified.
129         alertDialog.show();
130
131         // Get handles for the layout items.
132         EditText fileNameEditText = alertDialog.findViewById(R.id.file_name_edittext);
133         Button browseButton = alertDialog.findViewById(R.id.browse_button);
134         TextView storagePermissionTextView = alertDialog.findViewById(R.id.storage_permission_textview);
135         Button saveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
136
137         // Create a string for the default file path.
138         String defaultFilePath;
139
140         // Set the default file path according to the storage permission state.
141         if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {  // The storage permission has been granted.
142             // Set the default file path to use the external public directory.
143             defaultFilePath = Environment.getExternalStorageDirectory() + "/" + getString(R.string.webpage_png);
144         } else {  // The storage permission has not been granted.
145             // Set the default file path to use the external private directory.
146             defaultFilePath = context.getExternalFilesDir(null) + "/" + getString(R.string.webpage_png);
147         }
148
149         // Display the default file path.
150         fileNameEditText.setText(defaultFilePath);
151
152         // Update the status of the save button when the file name changes.
153         fileNameEditText.addTextChangedListener(new TextWatcher() {
154             @Override
155             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
156                 // Do nothing.
157             }
158
159             @Override
160             public void onTextChanged(CharSequence s, int start, int before, int count) {
161                 // Do nothing.
162             }
163
164             @Override
165             public void afterTextChanged(Editable s) {
166                 // // Enable the save button if a file name exists.
167                 saveButton.setEnabled(!fileNameEditText.getText().toString().isEmpty());
168             }
169         });
170
171         // Handle clicks on the browse button.
172         browseButton.setOnClickListener((View view) -> {
173             // Create the file picker intent.
174             Intent browseIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
175
176             // Set the intent MIME type to include all files so that everything is visible.
177             browseIntent.setType("*/*");
178
179             // Set the initial file name.
180             browseIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.webpage_png));
181
182             // Set the initial directory if the minimum API >= 26.
183             if (Build.VERSION.SDK_INT >= 26) {
184                 browseIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
185             }
186
187             // Request a file that can be opened.
188             browseIntent.addCategory(Intent.CATEGORY_OPENABLE);
189
190             // Start the file picker.  This must be started under `activity` so that the request code is returned correctly.
191             activity.startActivityForResult(browseIntent, MainWebViewActivity.BROWSE_SAVE_WEBPAGE_IMAGE_REQUEST_CODE);
192         });
193
194         // Hide the storage permission text view on API < 23 as permissions on older devices are automatically granted.
195         if (Build.VERSION.SDK_INT < 23) {
196             storagePermissionTextView.setVisibility(View.GONE);
197         }
198
199         // Return the alert dialog.
200         return alertDialog;
201     }
202 }