]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/SaveWebpageImageDialog.java
Implement saving a webpage as an image. https://redmine.stoutner.com/issues/187
[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.preference.PreferenceManager;
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;
44
45 import androidx.annotation.NonNull;
46 import androidx.core.content.ContextCompat;
47 import androidx.fragment.app.DialogFragment;
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(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 shared preferences.
76         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
77
78         // Get the screenshot and theme preferences.
79         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
80         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
81
82         // Use an alert dialog builder to create the alert dialog.
83         AlertDialog.Builder dialogBuilder;
84
85         // Get a handle for the activity.
86         Activity activity  = getActivity();
87
88         // Remove the incorrect lint warning below that the activity might be null.
89         assert activity != null;
90
91         // Set the style according to the theme.
92         if (darkTheme) {
93             dialogBuilder = new AlertDialog.Builder(activity, R.style.PrivacyBrowserAlertDialogDark);
94         } else {
95             dialogBuilder = new AlertDialog.Builder(activity, R.style.PrivacyBrowserAlertDialogLight);
96         }
97
98         // Set the title.
99         dialogBuilder.setTitle(R.string.save_image);
100
101         // Set the icon according to the theme.
102         if (darkTheme) {
103             dialogBuilder.setIcon(R.drawable.images_enabled_dark);
104         } else {
105             dialogBuilder.setIcon(R.drawable.images_enabled_light);
106         }
107
108         // Set the view.  The parent view is null because it will be assigned by the alert dialog.
109         dialogBuilder.setView(activity.getLayoutInflater().inflate(R.layout.save_dialog, null));
110
111         // Set the cancel button listener.
112         dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
113             // Do nothing.  The alert dialog will close automatically.
114         });
115
116         // Set the save button listener.
117         dialogBuilder.setPositiveButton(R.string.save, (DialogInterface dialog, int which) -> {
118             // Return the dialog fragment to the parent activity.
119             saveWebpageImageListener.onSaveWebpageImage(this);
120         });
121
122         // Create an alert dialog from the builder.
123         AlertDialog alertDialog = dialogBuilder.create();
124
125         // Remove the incorrect lint warning below that `getWindows()` might be null.
126         assert alertDialog.getWindow() != null;
127
128         // Disable screenshots if not allowed.
129         if (!allowScreenshots) {
130             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
131         }
132
133         // The alert dialog must be shown before items in the layout can be modified.
134         alertDialog.show();
135
136         // Get handles for the layout items.
137         EditText fileNameEditText = alertDialog.findViewById(R.id.file_name_edittext);
138         Button browseButton = alertDialog.findViewById(R.id.browse_button);
139         TextView storagePermissionTextView = alertDialog.findViewById(R.id.storage_permission_textview);
140         Button saveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
141
142         // Create a string for the default file path.
143         String defaultFilePath;
144
145         // Get a handle for the context.
146         Context context = getContext();
147
148         // Remove the incorrect lint warning that context might be null.
149         assert context != null;
150
151         // Set the default file path according to the storage permission state.
152         if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {  // The storage permission has been granted.
153             // Set the default file path to use the external public directory.
154             defaultFilePath = Environment.getExternalStorageDirectory() + "/" + getString(R.string.webpage_png);
155         } else {  // The storage permission has not been granted.
156             // Set the default file path to use the external private directory.
157             defaultFilePath = context.getExternalFilesDir(null) + "/" + getString(R.string.webpage_png);
158         }
159
160         // Display the default file path.
161         fileNameEditText.setText(defaultFilePath);
162
163         // Update the status of the save button when the file name changes.
164         fileNameEditText.addTextChangedListener(new TextWatcher() {
165             @Override
166             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
167                 // Do nothing.
168             }
169
170             @Override
171             public void onTextChanged(CharSequence s, int start, int before, int count) {
172                 // Do nothing.
173             }
174
175             @Override
176             public void afterTextChanged(Editable s) {
177                 // // Enable the save button if a file name exists.
178                 saveButton.setEnabled(!fileNameEditText.getText().toString().isEmpty());
179             }
180         });
181
182         // Handle clicks on the browse button.
183         browseButton.setOnClickListener((View view) -> {
184             // Create the file picker intent.
185             Intent browseIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
186
187             // Set the intent MIME type to include all files so that everything is visible.
188             browseIntent.setType("*/*");
189
190             // Set the initial file name.
191             browseIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.webpage_png));
192
193             // Set the initial directory if the minimum API >= 26.
194             if (Build.VERSION.SDK_INT >= 26) {
195                 browseIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
196             }
197
198             // Request a file that can be opened.
199             browseIntent.addCategory(Intent.CATEGORY_OPENABLE);
200
201             // Start the file picker.  This must be started under `activity` so that the request code is returned correctly.
202             activity.startActivityForResult(browseIntent, MainWebViewActivity.BROWSE_SAVE_WEBPAGE_IMAGE_REQUEST_CODE);
203         });
204
205         // Hide the storage permission text view on API < 23 as permissions on older devices are automatically granted.
206         if (Build.VERSION.SDK_INT < 23) {
207             storagePermissionTextView.setVisibility(View.GONE);
208         }
209
210         // Return the alert dialog.
211         return alertDialog;
212     }
213 }