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