]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/SaveLogcatDialog.java
c73cfdc6ecd6fe897bc71401d573bdb051769f72
[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.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 SaveLogcatDialog extends DialogFragment {
56     // Define the save logcat listener.
57     private SaveLogcatListener saveLogcatListener;
58
59     // The public interface is used to send information back to the parent activity.
60     public interface SaveLogcatListener {
61         void onSaveLogcat(DialogFragment dialogFragment);
62     }
63
64     @Override
65     public void onAttach(@NonNull Context context) {
66         // Run the default commands.
67         super.onAttach(context);
68
69         // Get a handle for save logcat listener from the launching context.
70         saveLogcatListener = (SaveLogcatListener) context;
71     }
72
73     // `@SuppressLing("InflateParams")` removes the warning about using null as the parent view group when inflating the alert dialog.
74     @SuppressLint("InflateParams")
75     @Override
76     @NonNull
77     public Dialog onCreateDialog(Bundle savedInstanceState) {
78         // Get a handle for the activity and the context.
79         Activity activity = requireActivity();
80         Context context = requireContext();
81
82         // Use an alert dialog builder to create the alert dialog.
83         AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context, R.style.PrivacyBrowserAlertDialog);
84         // Set the title.
85         dialogBuilder.setTitle(R.string.save_logcat);
86
87         // Get the current theme status.
88         int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
89
90         // Set the icon according to the theme.
91         if (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES) {
92             dialogBuilder.setIcon(R.drawable.save_dialog_night);
93         } else {
94             dialogBuilder.setIcon(R.drawable.save_dialog_day);
95         }
96
97         // Set the view.  The parent view is null because it will be assigned by the alert dialog.
98         dialogBuilder.setView(activity.getLayoutInflater().inflate(R.layout.save_logcat_dialog, null));
99
100         // Set the cancel button listener.
101         dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
102             // Do nothing.  The alert dialog will close automatically.
103         });
104
105         // Set the save button listener.
106         dialogBuilder.setPositiveButton(R.string.save, (DialogInterface dialog, int which) -> {
107             // Return the dialog fragment to the parent activity.
108             saveLogcatListener.onSaveLogcat(this);
109         });
110
111         // Create an alert dialog from the builder.
112         AlertDialog alertDialog = dialogBuilder.create();
113
114         // Remove the incorrect lint warning below that `getWindow()` might be null.
115         assert alertDialog.getWindow() != null;
116
117         // Get a handle for the shared preferences.
118         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
119
120         // Get the screenshot preference.
121         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
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 fileExistsWarningTextView = alertDialog.findViewById(R.id.file_exists_warning_textview);
135         TextView storagePermissionTextView = alertDialog.findViewById(R.id.storage_permission_textview);
136         Button saveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
137
138         // Remove the incorrect lint warnings below that the views might be null.
139         assert fileNameEditText != null;
140         assert browseButton != null;
141         assert fileExistsWarningTextView != null;
142         assert storagePermissionTextView != null;
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         // Instantiate the download location helper.
179         DownloadLocationHelper downloadLocationHelper = new DownloadLocationHelper();
180
181         // Get the default file path.
182         String defaultFilePath = downloadLocationHelper.getDownloadLocation(context) + "/" + getString(R.string.privacy_browser_logcat_txt);
183
184         // Display the default file path.
185         fileNameEditText.setText(defaultFilePath);
186
187         // Hide the storage permission text view if the permission has already been granted.
188         if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
189             storagePermissionTextView.setVisibility(View.GONE);
190         }
191
192         // Handle clicks on the browse button.
193         browseButton.setOnClickListener((View view) -> {
194             // Create the file picker intent.
195             Intent browseIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
196
197             // Set the intent MIME type to include all files so that everything is visible.
198             browseIntent.setType("*/*");
199
200             // Set the initial file name.
201             browseIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.privacy_browser_logcat_txt));
202
203             // Set the initial directory if the minimum API >= 26.
204             if (Build.VERSION.SDK_INT >= 26) {
205                 browseIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
206             }
207
208             // Request a file that can be opened.
209             browseIntent.addCategory(Intent.CATEGORY_OPENABLE);
210
211             // 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.
212             activity.startActivityForResult(browseIntent, 0);
213         });
214
215         // Return the alert dialog.
216         return alertDialog;
217     }
218 }