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