2 * Copyright © 2019 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
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.
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.
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/>.
20 package com.stoutner.privacybrowser.activities;
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.view.Menu;
35 import android.view.MenuItem;
36 import android.view.WindowManager;
37 import android.widget.EditText;
38 import android.widget.TextView;
40 import androidx.annotation.NonNull;
41 import androidx.appcompat.app.ActionBar;
42 import androidx.appcompat.app.AppCompatActivity;
43 import androidx.appcompat.widget.Toolbar; // The AndroidX toolbar must be used until the minimum API is >= 21.
44 import androidx.core.app.ActivityCompat;
45 import androidx.core.content.ContextCompat;
46 import androidx.fragment.app.DialogFragment;
47 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
49 import com.google.android.material.snackbar.Snackbar;
50 import com.stoutner.privacybrowser.R;
51 import com.stoutner.privacybrowser.dialogs.StoragePermissionDialog;
52 import com.stoutner.privacybrowser.dialogs.SaveLogcatDialog;
54 import java.io.BufferedReader;
55 import java.io.BufferedWriter;
56 import java.io.ByteArrayInputStream;
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;
66 public class LogcatActivity extends AppCompatActivity implements SaveLogcatDialog.SaveLogcatListener, StoragePermissionDialog.StoragePermissionDialogListener {
67 private String filePathString;
70 public void onCreate(Bundle savedInstanceState) {
71 // Disable screenshots if not allowed.
72 if (!MainWebViewActivity.allowScreenshots) {
73 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
76 // Set the activity theme.
77 if (MainWebViewActivity.darkTheme) {
78 setTheme(R.style.PrivacyBrowserDark_SecondaryActivity);
80 setTheme(R.style.PrivacyBrowserLight_SecondaryActivity);
83 // Run the default commands.
84 super.onCreate(savedInstanceState);
86 // Set the content view.
87 setContentView(R.layout.logcat_coordinatorlayout);
89 // The AndroidX toolbar must be used until the minimum API is >= 21.
90 Toolbar toolbar = findViewById(R.id.logcat_toolbar);
91 setSupportActionBar(toolbar);
93 // Get a handle for the action bar.
94 ActionBar actionBar = getSupportActionBar();
96 // Remove the incorrect lint warning that the action bar might be null.
97 assert actionBar != null;
99 // Display the the back arrow in the action bar.
100 actionBar.setDisplayHomeAsUpEnabled(true);
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();
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);
114 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
118 new GetLogcat(this).execute();
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);
131 public boolean onOptionsItemSelected(MenuItem menuItem) {
132 // Get the selected menu item ID.
133 int menuItemId = menuItem.getItemId();
135 // Run the commands that correlate to the selected menu item.
136 switch (menuItemId) {
138 // Get a handle for the clipboard manager.
139 ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
141 // Get a handle for the logcat text view.
142 TextView logcatTextView = findViewById(R.id.logcat_textview);
144 // Save the logcat in a ClipData.
145 ClipData logcatClipData = ClipData.newPlainText(getString(R.string.logcat), logcatTextView.getText());
147 // Remove the incorrect lint error that `clipboardManager.setPrimaryClip()` might produce a null pointer exception.
148 assert clipboardManager != null;
150 // Place the ClipData on the clipboard.
151 clipboardManager.setPrimaryClip(logcatClipData);
153 // Display a snackbar.
154 Snackbar.make(logcatTextView, R.string.logcat_copied, Snackbar.LENGTH_SHORT).show();
156 // Consume the event.
160 // Get a handle for the save alert dialog.
161 DialogFragment saveDialogFragment = new SaveLogcatDialog();
163 // Show the save alert dialog.
164 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_logcat));
166 // Consume the event.
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");
174 // Wait for the process to finish.
177 // Reload the logcat.
178 new GetLogcat(this).execute();
179 } catch (IOException|InterruptedException exception) {
183 // Consume the event.
187 // Don't consume the event.
188 return super.onOptionsItemSelected(menuItem);
193 public void onSaveLogcat(DialogFragment dialogFragment) {
194 // Get a handle for the file name edit text.
195 EditText fileNameEditText = dialogFragment.getDialog().findViewById(R.id.file_name_edittext);
197 // Get the file path string.
198 filePathString = fileNameEditText.getText().toString();
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.
203 saveLogcat(filePathString);
204 } else { // The storage permission has not been granted.
205 // Get the external private directory `File`.
206 File externalPrivateDirectoryFile = getExternalFilesDir(null);
208 // Remove the incorrect lint error below that the file might be null.
209 assert externalPrivateDirectoryFile != null;
211 // Get the external private directory string.
212 String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
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.
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();
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);
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);
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.
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);
251 // Display an error snackbar.
252 Snackbar.make(logcatTextView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
256 private void saveLogcat(String fileNameString) {
257 // Get a handle for the logcat text view.
258 TextView logcatTextView = findViewById(R.id.logcat_textview);
261 // Get the logcat as a string.
262 String logcatString = logcatTextView.getText().toString();
264 // Create an input stream with the contents of the logcat.
265 InputStream logcatInputStream = new ByteArrayInputStream(logcatString.getBytes(StandardCharsets.UTF_8));
267 // Create a logcat buffered reader.
268 BufferedReader logcatBufferedReader = new BufferedReader(new InputStreamReader(logcatInputStream));
270 // Create a file from the file name string.
271 File saveFile = new File(fileNameString);
273 // Create a file buffered writer.
274 BufferedWriter fileBufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(saveFile)));
276 // Create a transfer string.
277 String transferString;
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);
284 // Append a line break.
285 fileBufferedWriter.append("\n");
288 // Close the buffered reader and writer.
289 logcatBufferedReader.close();
290 fileBufferedWriter.close();
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);
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();
303 // The activity result is called after browsing for a file in the save alert dialog.
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));
311 // Remove the incorrect lint error that the save dialog fragment might be null.
312 assert saveDialogFragment != null;
314 // Get a handle for the save dialog.
315 Dialog saveDialog = saveDialogFragment.getDialog();
317 // Get a handle for the file name edit text.
318 EditText fileNameEditText = saveDialog.findViewById(R.id.file_name_edittext);
320 // Get the file name URI.
321 Uri fileNameUri = data.getData();
323 // Remove the incorrect lint warning that the file name URI might be null.
324 assert fileNameUri != null;
326 // Get the raw file name path.
327 String rawFileNamePath = fileNameUri.getPath();
329 // Remove the incorrect lint warning that the file name path might be null.
330 assert rawFileNamePath != null;
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);
338 // Create the file name path string.
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;
348 // Everything else for the primary user should be in `/document/primary`.
349 case "/document/primary":
350 fileNamePath = Environment.getExternalStorageDirectory() + "/" + fileNameFinalPath;
353 // Just in case, catch everything else and place it in the external storage directory.
355 fileNamePath = Environment.getExternalStorageDirectory() + "/" + fileNameFinalPath;
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();
365 // Get a handle for the logcat text view.
366 TextView logcatTextView = findViewById(R.id.logcat_textview);
368 // Display a snackbar with the error message.
369 Snackbar.make(logcatTextView, rawFileNamePath + " " + getString(R.string.invalid_location), Snackbar.LENGTH_INDEFINITE).show();
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;
379 // Populate the weak reference to the calling activity.
380 GetLogcat(Activity activity) {
381 activityWeakReference = new WeakReference<>(activity);
385 protected String doInBackground(Void... parameters) {
386 // Get a handle for the activity.
387 Activity activity = activityWeakReference.get();
389 // Abort if the activity is gone.
390 if ((activity == null) || activity.isFinishing()) {
394 // Create a log string builder.
395 StringBuilder logStringBuilder = new StringBuilder();
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");
401 // Wrap the logcat in a buffered reader.
402 BufferedReader logBufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
404 // Create a log transfer string.
405 String logTransferString;
407 // Use the log transfer string to copy the logcat from the buffered reader to the string builder.
408 while ((logTransferString = logBufferedReader.readLine()) != null) {
410 logStringBuilder.append(logTransferString);
412 // Append a line break.
413 logStringBuilder.append("\n");
416 // Close the buffered reader.
417 logBufferedReader.close();
418 } catch (IOException exception) {
422 // Return the logcat.
423 return logStringBuilder.toString();
426 // `onPostExecute()` operates on the UI thread.
428 protected void onPostExecute(String logcatString) {
429 // Get a handle for the activity.
430 Activity activity = activityWeakReference.get();
432 // Abort if the activity is gone.
433 if ((activity == null) || activity.isFinishing()) {
437 // Get handles for the views.
438 TextView logcatTextView = activity.findViewById(R.id.logcat_textview);
439 SwipeRefreshLayout swipeRefreshLayout = activity.findViewById(R.id.logcat_swiperefreshlayout);
441 // Display the logcat.
442 logcatTextView.setText(logcatString);
444 // Stop the swipe to refresh animation if it is displayed.
445 swipeRefreshLayout.setRefreshing(false);