]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/SaveDialog.java
Add share, copy, and save options to About > Version. https://redmine.stoutner.com...
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / SaveDialog.java
1 /*
2  * Copyright © 2016-2020 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.Dialog;
26 import android.content.Context;
27 import android.content.DialogInterface;
28 import android.content.Intent;
29 import android.content.SharedPreferences;
30 import android.content.pm.PackageManager;
31 import android.content.res.Configuration;
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.appcompat.app.AlertDialog;
47 import androidx.core.content.ContextCompat;
48 import androidx.fragment.app.DialogFragment;
49
50 import com.stoutner.privacybrowser.R;
51 import com.stoutner.privacybrowser.helpers.DownloadLocationHelper;
52
53 import java.io.File;
54
55 public class SaveDialog extends DialogFragment {
56     // Declare the save listener.
57     private SaveListener saveListener;
58
59     // The public interface is used to send information back to the parent activity.
60     public interface SaveListener {
61         void onSave(int saveType, DialogFragment dialogFragment);
62     }
63
64     // Declare the class constants.
65     public static final int SAVE_LOGCAT = 0;
66     public static final int SAVE_ABOUT_VERSION_TEXT = 1;
67     public static final int SAVE_ABOUT_VERSION_IMAGE = 2;
68     private static final String SAVE_TYPE = "save_type";
69
70     // Declare the class variables.
71     String fileName;
72
73     @Override
74     public void onAttach(@NonNull Context context) {
75         // Run the default commands.
76         super.onAttach(context);
77
78         // Get a handle for save listener from the launching context.
79         saveListener = (SaveListener) context;
80     }
81
82     public static SaveDialog save(int saveType) {
83         // Create an arguments bundle.
84         Bundle argumentsBundle = new Bundle();
85
86         // Store the arguments in the bundle.
87         argumentsBundle.putInt(SAVE_TYPE, saveType);
88
89         // Create a new instance of the save dialog.
90         SaveDialog saveDialog = new SaveDialog();
91
92         // Add the arguments bundle to the dialog.
93         saveDialog.setArguments(argumentsBundle);
94
95         // Return the new dialog.
96         return saveDialog;
97     }
98
99     // `@SuppressLint("InflateParams")` removes the warning about using null as the parent view group when inflating the alert dialog.
100     @SuppressLint("InflateParams")
101     @Override
102     @NonNull
103     public Dialog onCreateDialog(Bundle savedInstanceState) {
104         // Get a handle for the arguments.
105         Bundle arguments = getArguments();
106
107         // Remove the incorrect lint warning that the arguments might be null.
108         assert arguments != null;
109
110         // Get the arguments from the bundle.
111         int saveType = arguments.getInt(SAVE_TYPE);
112
113         // Get a handle for the activity and the context.
114         Activity activity = requireActivity();
115         Context context = requireContext();
116
117         // Use an alert dialog builder to create the alert dialog.
118         AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context, R.style.PrivacyBrowserAlertDialog);
119
120         // Get the current theme status.
121         int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
122
123         // Set the title and icon according to the type.
124         switch (saveType) {
125             case SAVE_LOGCAT:
126                 // Set the title.
127                 dialogBuilder.setTitle(R.string.save_logcat);
128
129                 // Set the icon according to the theme.
130                 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
131                     dialogBuilder.setIcon(R.drawable.save_dialog_day);
132                 } else {
133                     dialogBuilder.setIcon(R.drawable.save_dialog_night);
134                 }
135                 break;
136
137             case SAVE_ABOUT_VERSION_TEXT:
138                 // Set the title.
139                 dialogBuilder.setTitle(R.string.save_text);
140
141                 // Set the icon according to the theme.
142                 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
143                     dialogBuilder.setIcon(R.drawable.save_text_blue_day);
144                 } else {
145                     dialogBuilder.setIcon(R.drawable.save_text_blue_night);
146                 }
147                 break;
148
149             case SAVE_ABOUT_VERSION_IMAGE:
150                 // Set the title.
151                 dialogBuilder.setTitle(R.string.save_image);
152
153                 // Set the icon according to the theme.
154                 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
155                     dialogBuilder.setIcon(R.drawable.images_enabled_day);
156                 } else {
157                     dialogBuilder.setIcon(R.drawable.images_enabled_night);
158                 }
159                 break;
160         }
161
162         // Set the view.  The parent view is null because it will be assigned by the alert dialog.
163         dialogBuilder.setView(activity.getLayoutInflater().inflate(R.layout.save_dialog, null));
164
165         // Set the cancel button listener.  Using `null` as the listener closes the dialog without doing anything else.
166         dialogBuilder.setNegativeButton(R.string.cancel, null);
167
168         // Set the save button listener.
169         dialogBuilder.setPositiveButton(R.string.save, (DialogInterface dialog, int which) -> {
170             // Return the dialog fragment to the parent activity.
171             saveListener.onSave(saveType, this);
172         });
173
174         // Create an alert dialog from the builder.
175         AlertDialog alertDialog = dialogBuilder.create();
176
177         // Remove the incorrect lint warning below that `getWindow()` might be null.
178         assert alertDialog.getWindow() != null;
179
180         // Get a handle for the shared preferences.
181         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
182
183         // Get the screenshot preference.
184         boolean allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false);
185
186         // Disable screenshots if not allowed.
187         if (!allowScreenshots) {
188             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
189         }
190
191         // The alert dialog must be shown before items in the layout can be modified.
192         alertDialog.show();
193
194         // Get handles for the layout items.
195         EditText fileNameEditText = alertDialog.findViewById(R.id.file_name_edittext);
196         Button browseButton = alertDialog.findViewById(R.id.browse_button);
197         TextView fileExistsWarningTextView = alertDialog.findViewById(R.id.file_exists_warning_textview);
198         TextView storagePermissionTextView = alertDialog.findViewById(R.id.storage_permission_textview);
199         Button saveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
200
201         // Remove the incorrect lint warnings below that the views might be null.
202         assert fileNameEditText != null;
203         assert browseButton != null;
204         assert fileExistsWarningTextView != null;
205         assert storagePermissionTextView != null;
206
207         // Update the status of the save button when the file name changes.
208         fileNameEditText.addTextChangedListener(new TextWatcher() {
209             @Override
210             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
211                 // Do nothing.
212             }
213
214             @Override
215             public void onTextChanged(CharSequence s, int start, int before, int count) {
216                 // Do nothing.
217             }
218
219             @Override
220             public void afterTextChanged(Editable s) {
221                 // Get the current file name.
222                 String fileNameString = fileNameEditText.getText().toString();
223
224                 // Convert the file name string to a file.
225                 File file = new File(fileNameString);
226
227                 // Check to see if the file exists.
228                 if (file.exists()) {
229                     // Show the file exists warning.
230                     fileExistsWarningTextView.setVisibility(View.VISIBLE);
231                 } else {
232                     // Hide the file exists warning.
233                     fileExistsWarningTextView.setVisibility(View.GONE);
234                 }
235
236                 // Enable the save button if the file name is populated.
237                 saveButton.setEnabled(!fileNameString.isEmpty());
238             }
239         });
240
241         // Set the file name according to the type.
242         switch (saveType) {
243             case SAVE_LOGCAT:
244                 // Use a file name ending in `.txt`.
245                 fileName = getString(R.string.privacy_browser_logcat_txt);
246                 break;
247
248             case SAVE_ABOUT_VERSION_TEXT:
249                 // Use a file name ending in `.txt`.
250                 fileName = getString(R.string.privacy_browser_version_txt);
251                 break;
252
253             case SAVE_ABOUT_VERSION_IMAGE:
254                 // Use a file name ending in `.png`.
255                 fileName = getString(R.string.privacy_browser_version_png);
256                 break;
257         }
258
259         // Instantiate the download location helper.
260         DownloadLocationHelper downloadLocationHelper = new DownloadLocationHelper();
261
262         // Get the default file path.
263         String defaultFilePath = downloadLocationHelper.getDownloadLocation(context) + "/" + fileName;
264
265         // Display the default file path.
266         fileNameEditText.setText(defaultFilePath);
267
268         // Hide the storage permission text view if the permission has already been granted.
269         if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
270             storagePermissionTextView.setVisibility(View.GONE);
271         }
272
273         // Handle clicks on the browse button.
274         browseButton.setOnClickListener((View view) -> {
275             // Create the file picker intent.
276             Intent browseIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
277
278             // Set the intent MIME type to include all files so that everything is visible.
279             browseIntent.setType("*/*");
280
281             // Set the initial file name.
282             browseIntent.putExtra(Intent.EXTRA_TITLE, fileName);
283
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());
287             }
288
289             // Request a file that can be opened.
290             browseIntent.addCategory(Intent.CATEGORY_OPENABLE);
291
292             // Launch the file picker.  There is only one `startActivityForResult()`, so the request code is simply set to 0, but it must be run under `activity` so the request code is correct.
293             activity.startActivityForResult(browseIntent, 0);
294         });
295
296         // Return the alert dialog.
297         return alertDialog;
298     }
299 }