]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/LogcatActivity.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 / activities / LogcatActivity.java
1 /*
2  * Copyright © 2019-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.activities;
21
22 import android.Manifest;
23 import android.app.Activity;
24 import android.app.Dialog;
25 import android.content.ClipData;
26 import android.content.ClipboardManager;
27 import android.content.Intent;
28 import android.content.SharedPreferences;
29 import android.content.pm.PackageManager;
30 import android.media.MediaScannerConnection;
31 import android.net.Uri;
32 import android.os.AsyncTask;
33 import android.os.Bundle;
34 import android.preference.PreferenceManager;
35 import android.view.Menu;
36 import android.view.MenuItem;
37 import android.view.View;
38 import android.view.WindowManager;
39 import android.widget.EditText;
40 import android.widget.TextView;
41
42 import androidx.annotation.NonNull;
43 import androidx.appcompat.app.ActionBar;
44 import androidx.appcompat.app.AppCompatActivity;
45 import androidx.appcompat.widget.Toolbar;
46 import androidx.core.app.ActivityCompat;
47 import androidx.core.content.ContextCompat;
48 import androidx.fragment.app.DialogFragment;
49 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
50
51 import com.google.android.material.snackbar.Snackbar;
52
53 import com.stoutner.privacybrowser.R;
54 import com.stoutner.privacybrowser.dialogs.StoragePermissionDialog;
55 import com.stoutner.privacybrowser.dialogs.SaveLogcatDialog;
56 import com.stoutner.privacybrowser.helpers.FileNameHelper;
57
58 import java.io.BufferedReader;
59 import java.io.BufferedWriter;
60 import java.io.ByteArrayInputStream;
61 import java.io.File;
62 import java.io.FileOutputStream;
63 import java.io.IOException;
64 import java.io.InputStream;
65 import java.io.InputStreamReader;
66 import java.io.OutputStreamWriter;
67 import java.lang.ref.WeakReference;
68 import java.nio.charset.StandardCharsets;
69
70 public class LogcatActivity extends AppCompatActivity implements SaveLogcatDialog.SaveLogcatListener, StoragePermissionDialog.StoragePermissionDialogListener {
71     private String filePathString;
72
73     @Override
74     public void onCreate(Bundle savedInstanceState) {
75         // Get a handle for the shared preferences.
76         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
77
78         // Get the theme and screenshot preferences.
79         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
80         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
81
82         // Disable screenshots if not allowed.
83         if (!allowScreenshots) {
84             getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
85         }
86
87         // Set the activity theme.
88         if (darkTheme) {
89             setTheme(R.style.PrivacyBrowserDark_SecondaryActivity);
90         } else {
91             setTheme(R.style.PrivacyBrowserLight_SecondaryActivity);
92         }
93
94         // Run the default commands.
95         super.onCreate(savedInstanceState);
96
97         // Set the content view.
98         setContentView(R.layout.logcat_coordinatorlayout);
99
100         // The AndroidX toolbar must be used until the minimum API is >= 21.
101         Toolbar toolbar = findViewById(R.id.logcat_toolbar);
102         setSupportActionBar(toolbar);
103
104         // Get a handle for the action bar.
105         ActionBar actionBar = getSupportActionBar();
106
107         // Remove the incorrect lint warning that the action bar might be null.
108         assert actionBar != null;
109
110         // Display the the back arrow in the action bar.
111         actionBar.setDisplayHomeAsUpEnabled(true);
112
113         // Implement swipe to refresh.
114         SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.logcat_swiperefreshlayout);
115         swipeRefreshLayout.setOnRefreshListener(() -> {
116             // Get the current logcat.
117             new GetLogcat(this).execute();
118         });
119
120         // Set the swipe to refresh color according to the theme.
121         if (darkTheme) {
122             swipeRefreshLayout.setColorSchemeResources(R.color.blue_600);
123             swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_800);
124         } else {
125             swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
126         }
127
128         // Get the logcat.
129         new GetLogcat(this).execute();
130     }
131
132     @Override
133     public boolean onCreateOptionsMenu(Menu menu) {
134         // Inflate the menu.  This adds items to the action bar.
135         getMenuInflater().inflate(R.menu.logcat_options_menu, menu);
136
137         // Display the menu.
138         return true;
139     }
140
141     @Override
142     public boolean onOptionsItemSelected(MenuItem menuItem) {
143         // Get the selected menu item ID.
144         int menuItemId = menuItem.getItemId();
145
146         // Run the commands that correlate to the selected menu item.
147         switch (menuItemId) {
148             case R.id.copy:
149                 // Get a handle for the clipboard manager.
150                 ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
151
152                 // Get a handle for the logcat text view.
153                 TextView logcatTextView = findViewById(R.id.logcat_textview);
154
155                 // Save the logcat in a ClipData.
156                 ClipData logcatClipData = ClipData.newPlainText(getString(R.string.logcat), logcatTextView.getText());
157
158                 // Remove the incorrect lint error that `clipboardManager.setPrimaryClip()` might produce a null pointer exception.
159                 assert clipboardManager != null;
160
161                 // Place the ClipData on the clipboard.
162                 clipboardManager.setPrimaryClip(logcatClipData);
163
164                 // Display a snackbar.
165                 Snackbar.make(logcatTextView, R.string.logcat_copied, Snackbar.LENGTH_SHORT).show();
166
167                 // Consume the event.
168                 return true;
169
170             case R.id.save:
171                 // Instantiate the save alert dialog.
172                 DialogFragment saveDialogFragment = new SaveLogcatDialog();
173
174                 // Show the save alert dialog.
175                 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_logcat));
176
177                 // Consume the event.
178                 return true;
179
180             case R.id.clear:
181                 try {
182                     // Clear the logcat.  `-c` clears the logcat.  `-b all` clears all the buffers (instead of just crash, main, and system).
183                     Process process = Runtime.getRuntime().exec("logcat -b all -c");
184
185                     // Wait for the process to finish.
186                     process.waitFor();
187
188                     // Reload the logcat.
189                     new GetLogcat(this).execute();
190                 } catch (IOException|InterruptedException exception) {
191                     // Do nothing.
192                 }
193
194                 // Consume the event.
195                 return true;
196
197             default:
198                 // Don't consume the event.
199                 return super.onOptionsItemSelected(menuItem);
200         }
201     }
202
203     @Override
204     public void onSaveLogcat(DialogFragment dialogFragment) {
205         // Get a handle for the dialog fragment.
206         Dialog dialog = dialogFragment.getDialog();
207
208         // Remove the lint warning below that the dialog fragment might be null.
209         assert dialog != null;
210
211         // Get a handle for the file name edit text.
212         EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
213
214         // Get the file path string.
215         filePathString = fileNameEditText.getText().toString();
216
217         // Check to see if the storage permission is needed.
218         if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {  // The storage permission has been granted.
219             // Save the logcat.
220             saveLogcat(filePathString);
221         } else {  // The storage permission has not been granted.
222             // Get the external private directory `File`.
223             File externalPrivateDirectoryFile = getExternalFilesDir(null);
224
225             // Remove the incorrect lint error below that the file might be null.
226             assert externalPrivateDirectoryFile != null;
227
228             // Get the external private directory string.
229             String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
230
231             // Check to see if the file path is in the external private directory.
232             if (filePathString.startsWith(externalPrivateDirectory)) {  // The file path is in the external private directory.
233                 // Save the logcat.
234                 saveLogcat(filePathString);
235             } else {  // The file path in in a public directory.
236                 // Check if the user has previously denied the storage permission.
237                 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
238                     // Instantiate the storage permission alert dialog.
239                     DialogFragment storagePermissionDialogFragment = StoragePermissionDialog.displayDialog(0);
240
241                     // Show the storage permission alert dialog.  The permission will be requested when the dialog is closed.
242                     storagePermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.storage_permission));
243                 } else {  // Show the permission request directly.
244                     // Request the write external storage permission.  The logcat will be saved when it finishes.
245                     ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
246
247                 }
248             }
249         }
250     }
251
252     @Override
253     public void onCloseStoragePermissionDialog(int type) {
254         // Request the write external storage permission.  The logcat will be saved when it finishes.
255         ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
256     }
257
258     @Override
259     public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
260         // Check to see if the storage permission was granted.  If the dialog was canceled the grant result will be empty.
261         if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {  // The storage permission was granted.
262             // Save the logcat.
263             saveLogcat(filePathString);
264         } else {  // The storage permission was not granted.
265             // Get a handle for the logcat text view.
266             TextView logcatTextView = findViewById(R.id.logcat_textview);
267
268             // Display an error snackbar.
269             Snackbar.make(logcatTextView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
270         }
271     }
272
273     private void saveLogcat(String fileNameString) {
274         // Get a handle for the logcat text view.
275         TextView logcatTextView = findViewById(R.id.logcat_textview);
276
277         try {
278             // Get the logcat as a string.
279             String logcatString = logcatTextView.getText().toString();
280
281             // Create an input stream with the contents of the logcat.
282             InputStream logcatInputStream = new ByteArrayInputStream(logcatString.getBytes(StandardCharsets.UTF_8));
283
284             // Create a logcat buffered reader.
285             BufferedReader logcatBufferedReader = new BufferedReader(new InputStreamReader(logcatInputStream));
286
287             // Create a file from the file name string.
288             File saveFile = new File(fileNameString);
289
290             // Create a file buffered writer.
291             BufferedWriter fileBufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(saveFile)));
292
293             // Create a transfer string.
294             String transferString;
295
296             // Use the transfer string to copy the logcat from the buffered reader to the buffered writer.
297             while ((transferString = logcatBufferedReader.readLine()) != null) {
298                 // Append the line to the buffered writer.
299                 fileBufferedWriter.append(transferString);
300
301                 // Append a line break.
302                 fileBufferedWriter.append("\n");
303             }
304
305             // Close the buffered reader and writer.
306             logcatBufferedReader.close();
307             fileBufferedWriter.close();
308
309             // Add the file to the list of recent files.  This doesn't currently work, but maybe it will someday.
310             MediaScannerConnection.scanFile(this, new String[] {fileNameString}, new String[] {"text/plain"}, null);
311
312             // Display a snackbar.
313             Snackbar.make(logcatTextView, getString(R.string.file_saved_successfully), Snackbar.LENGTH_SHORT).show();
314         } catch (Exception exception) {
315             // Display a snackbar with the error message.
316             Snackbar.make(logcatTextView, getString(R.string.save_failed) + "  " + exception.toString(), Snackbar.LENGTH_INDEFINITE).show();
317         }
318     }
319
320     // The activity result is called after browsing for a file in the save alert dialog.
321     @Override
322     public void onActivityResult(int requestCode, int resultCode, Intent data) {
323         // Run the default commands.
324         super.onActivityResult(requestCode, resultCode, data);
325
326         // Don't do anything if the user pressed back from the file picker.
327         if (resultCode == Activity.RESULT_OK) {
328             // Get a handle for the save dialog fragment.
329             DialogFragment saveDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.save_logcat));
330
331             // Only update the file name if the dialog still exists.
332             if (saveDialogFragment != null) {
333                 // Get a handle for the save dialog.
334                 Dialog saveDialog = saveDialogFragment.getDialog();
335
336                 // Remove the lint warning below that the save dialog might be null.
337                 assert saveDialog != null;
338
339                 // Get a handle for the dialog views.
340                 EditText fileNameEditText = saveDialog.findViewById(R.id.file_name_edittext);
341                 TextView fileExistsWarningTextView = saveDialog.findViewById(R.id.file_exists_warning_textview);
342
343                 // Instantiate the file name helper.
344                 FileNameHelper fileNameHelper = new FileNameHelper();
345
346                 // Get the file name URI from the intent.
347                 Uri fileNameUri= data.getData();
348
349                 // Process the file name URI if it is not null.
350                 if (fileNameUri != null) {
351                     // Convert the file name URI to a file name path.
352                     String fileNamePath = fileNameHelper.convertUriToFileNamePath(fileNameUri);
353
354                     // Set the file name path as the text of the file name edit text.
355                     fileNameEditText.setText(fileNamePath);
356
357                     // Move the cursor to the end of the file name edit text.
358                     fileNameEditText.setSelection(fileNamePath.length());
359
360                     // Hide the file exists warning.
361                     fileExistsWarningTextView.setVisibility(View.GONE);
362                 }
363             }
364         }
365     }
366
367     // `Void` does not declare any parameters.  `Void` does not declare progress units.  `String` contains the results.
368     private static class GetLogcat extends AsyncTask<Void, Void, String> {
369         // Create a weak reference to the calling activity.
370         private final WeakReference<Activity> activityWeakReference;
371
372         // Populate the weak reference to the calling activity.
373         GetLogcat(Activity activity) {
374             activityWeakReference = new WeakReference<>(activity);
375         }
376
377         @Override
378         protected String doInBackground(Void... parameters) {
379             // Get a handle for the activity.
380             Activity activity = activityWeakReference.get();
381
382             // Abort if the activity is gone.
383             if ((activity == null) || activity.isFinishing()) {
384                 return "";
385             }
386
387             // Create a log string builder.
388             StringBuilder logStringBuilder = new StringBuilder();
389
390             try {
391                 // Get the logcat.  `-b all` gets all the buffers (instead of just crash, main, and system).  `-v long` produces more complete information.  `-d` dumps the logcat and exits.
392                 Process process = Runtime.getRuntime().exec("logcat -b all -v long -d");
393
394                 // Wrap the logcat in a buffered reader.
395                 BufferedReader logBufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
396
397                 // Create a log transfer string.
398                 String logTransferString;
399
400                 // Use the log transfer string to copy the logcat from the buffered reader to the string builder.
401                 while ((logTransferString = logBufferedReader.readLine()) != null) {
402                     // Append a line.
403                     logStringBuilder.append(logTransferString);
404
405                     // Append a line break.
406                     logStringBuilder.append("\n");
407                 }
408
409                 // Close the buffered reader.
410                 logBufferedReader.close();
411             } catch (IOException exception) {
412                 // Do nothing.
413             }
414
415             // Return the logcat.
416             return logStringBuilder.toString();
417         }
418
419         // `onPostExecute()` operates on the UI thread.
420         @Override
421         protected void onPostExecute(String logcatString) {
422             // Get a handle for the activity.
423             Activity activity = activityWeakReference.get();
424
425             // Abort if the activity is gone.
426             if ((activity == null) || activity.isFinishing()) {
427                 return;
428             }
429
430             // Get handles for the views.
431             TextView logcatTextView = activity.findViewById(R.id.logcat_textview);
432             SwipeRefreshLayout swipeRefreshLayout = activity.findViewById(R.id.logcat_swiperefreshlayout);
433
434             // Display the logcat.
435             logcatTextView.setText(logcatString);
436
437             // Stop the swipe to refresh animation if it is displayed.
438             swipeRefreshLayout.setRefreshing(false);
439         }
440     }
441 }