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