]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/SaveLogcatDialog.java
Add a warning if a file will be overwritten. https://redmine.stoutner.com/issues/371
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / SaveLogcatDialog.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.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;  // The AndroidX dialog fragment is required or an error is produced on API <=22.  It is also required for the browse button to work correctly.
48
49 import com.stoutner.privacybrowser.R;
50
51 import java.io.File;
52
53 public class SaveLogcatDialog extends DialogFragment {
54     // Define the save logcat listener.
55     private SaveLogcatListener saveLogcatListener;
56
57     // The public interface is used to send information back to the parent activity.
58     public interface SaveLogcatListener {
59         void onSaveLogcat(DialogFragment dialogFragment);
60     }
61
62     @Override
63     public void onAttach(@NonNull Context context) {
64         // Run the default commands.
65         super.onAttach(context);
66
67         // Get a handle for save logcat listener from the launching context.
68         saveLogcatListener = (SaveLogcatListener) context;
69     }
70
71     // `@SuppressLing("InflateParams")` removes the warning about using null as the parent view group when inflating the alert dialog.
72     @SuppressLint("InflateParams")
73     @Override
74     @NonNull
75     public Dialog onCreateDialog(Bundle savedInstanceState) {
76         // Get a handle for the shared preferences.
77         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
78
79         // Get the screenshot and theme preferences.
80         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
81         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
82
83         // Use an alert dialog builder to create the alert dialog.
84         AlertDialog.Builder dialogBuilder;
85
86         // Get a handle for the activity.
87         Activity activity = getActivity();
88
89         // Remove the incorrect lint warning below that the activity might be null.
90         assert activity != null;
91
92         // Set the style according to the theme.
93         if (darkTheme) {
94             dialogBuilder = new AlertDialog.Builder(activity, R.style.PrivacyBrowserAlertDialogDark);
95         } else {
96             dialogBuilder = new AlertDialog.Builder(activity, R.style.PrivacyBrowserAlertDialogLight);
97         }
98
99         // Set the title.
100         dialogBuilder.setTitle(R.string.save_logcat);
101
102         // Set the icon according to the theme.
103         if (darkTheme) {
104             dialogBuilder.setIcon(R.drawable.save_dialog_dark);
105         } else {
106             dialogBuilder.setIcon(R.drawable.save_dialog_light);
107         }
108
109         // Set the view.  The parent view is null because it will be assigned by the alert dialog.
110         dialogBuilder.setView(activity.getLayoutInflater().inflate(R.layout.save_dialog, null));
111
112         // Set the cancel button listener.
113         dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
114             // Do nothing.  The alert dialog will close automatically.
115         });
116
117         // Set the save button listener.
118         dialogBuilder.setPositiveButton(R.string.save, (DialogInterface dialog, int which) -> {
119             // Return the dialog fragment to the parent activity.
120             saveLogcatListener.onSaveLogcat(this);
121         });
122
123         // Create an alert dialog from the builder.
124         AlertDialog alertDialog = dialogBuilder.create();
125
126         // Remove the incorrect lint warning below that `getWindow()` might be null.
127         assert alertDialog.getWindow() != null;
128
129         // Disable screenshots if not allowed.
130         if (!allowScreenshots) {
131             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
132         }
133
134         // The alert dialog must be shown before items in the layout can be modified.
135         alertDialog.show();
136
137         // Get handles for the layout items.
138         EditText fileNameEditText = alertDialog.findViewById(R.id.file_name_edittext);
139         Button browseButton = alertDialog.findViewById(R.id.browse_button);
140         TextView fileExistsWarningTextView = alertDialog.findViewById(R.id.file_exists_warning_textview);
141         TextView storagePermissionTextView = alertDialog.findViewById(R.id.storage_permission_textview);
142         Button saveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
143
144         // Update the status of the save button when the file name changes.
145         fileNameEditText.addTextChangedListener(new TextWatcher() {
146             @Override
147             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
148                 // Do nothing.
149             }
150
151             @Override
152             public void onTextChanged(CharSequence s, int start, int before, int count) {
153                 // Do nothing.
154             }
155
156             @Override
157             public void afterTextChanged(Editable s) {
158                 // Get the current file name.
159                 String fileNameString = fileNameEditText.getText().toString();
160
161                 // Convert the file name string to a file.
162                 File file = new File(fileNameString);
163
164                 // Check to see if the file exists.
165                 if (file.exists()) {
166                     // Show the file exists warning.
167                     fileExistsWarningTextView.setVisibility(View.VISIBLE);
168                 } else {
169                     // Hide the file exists warning.
170                     fileExistsWarningTextView.setVisibility(View.GONE);
171                 }
172
173                 // Enable the save button if the file name is populated.
174                 saveButton.setEnabled(!fileNameString.isEmpty());
175             }
176         });
177
178         // Create a string for the default file path.
179         String defaultFilePath;
180
181         // Get a handle for the context.
182         Context context = getContext();
183
184         // Remove the incorrect lint warning below that context might be null.
185         assert context != null;
186
187         // Set the default file path according to the storage permission state.
188         if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {  // The storage permission has been granted.
189             // Set the default file path to use the external public directory.
190             defaultFilePath = Environment.getExternalStorageDirectory() + "/" + getString(R.string.privacy_browser_logcat_txt);
191
192             // Hide the storage permission text view.
193             storagePermissionTextView.setVisibility(View.GONE);
194         } else {  // The storage permission has not been granted.
195             // Set the default file path to use the external private directory.
196             defaultFilePath = context.getExternalFilesDir(null) + "/" + getString(R.string.privacy_browser_logcat_txt);
197         }
198
199         // Display the default file path.
200         fileNameEditText.setText(defaultFilePath);
201
202         // Handle clicks on the browse button.
203         browseButton.setOnClickListener((View view) -> {
204             // Create the file picker intent.
205             Intent browseIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
206
207             // Set the intent MIME type to include all files so that everything is visible.
208             browseIntent.setType("*/*");
209
210             // Set the initial file name.
211             browseIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.privacy_browser_logcat_txt));
212
213             // Set the initial directory if the minimum API >= 26.
214             if (Build.VERSION.SDK_INT >= 26) {
215                 browseIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
216             }
217
218             // Request a file that can be opened.
219             browseIntent.addCategory(Intent.CATEGORY_OPENABLE);
220
221             // 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.
222             activity.startActivityForResult(browseIntent, 0);
223         });
224
225         // Return the alert dialog.
226         return alertDialog;
227     }
228 }