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