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.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;
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;
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;
56 import java.io.BufferedReader;
57 import java.io.BufferedWriter;
58 import java.io.ByteArrayInputStream;
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;
68 public class LogcatActivity extends AppCompatActivity implements SaveLogcatDialog.SaveLogcatListener, StoragePermissionDialog.StoragePermissionDialogListener {
69 private String filePathString;
72 public void onCreate(Bundle savedInstanceState) {
73 // Get a handle for the shared preferences.
74 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
76 // Get the theme and screenshot preferences.
77 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
78 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
80 // Disable screenshots if not allowed.
81 if (!allowScreenshots) {
82 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
85 // Set the activity theme.
87 setTheme(R.style.PrivacyBrowserDark_SecondaryActivity);
89 setTheme(R.style.PrivacyBrowserLight_SecondaryActivity);
92 // Run the default commands.
93 super.onCreate(savedInstanceState);
95 // Set the content view.
96 setContentView(R.layout.logcat_coordinatorlayout);
98 // The AndroidX toolbar must be used until the minimum API is >= 21.
99 Toolbar toolbar = findViewById(R.id.logcat_toolbar);
100 setSupportActionBar(toolbar);
102 // Get a handle for the action bar.
103 ActionBar actionBar = getSupportActionBar();
105 // Remove the incorrect lint warning that the action bar might be null.
106 assert actionBar != null;
108 // Display the the back arrow in the action bar.
109 actionBar.setDisplayHomeAsUpEnabled(true);
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();
118 // Set the swipe to refresh color according to the theme.
120 swipeRefreshLayout.setColorSchemeResources(R.color.blue_600);
121 swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_800);
123 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
127 new GetLogcat(this).execute();
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);
140 public boolean onOptionsItemSelected(MenuItem menuItem) {
141 // Get the selected menu item ID.
142 int menuItemId = menuItem.getItemId();
144 // Run the commands that correlate to the selected menu item.
145 switch (menuItemId) {
147 // Get a handle for the clipboard manager.
148 ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
150 // Get a handle for the logcat text view.
151 TextView logcatTextView = findViewById(R.id.logcat_textview);
153 // Save the logcat in a ClipData.
154 ClipData logcatClipData = ClipData.newPlainText(getString(R.string.logcat), logcatTextView.getText());
156 // Remove the incorrect lint error that `clipboardManager.setPrimaryClip()` might produce a null pointer exception.
157 assert clipboardManager != null;
159 // Place the ClipData on the clipboard.
160 clipboardManager.setPrimaryClip(logcatClipData);
162 // Display a snackbar.
163 Snackbar.make(logcatTextView, R.string.logcat_copied, Snackbar.LENGTH_SHORT).show();
165 // Consume the event.
169 // Get a handle for the save alert dialog.
170 DialogFragment saveDialogFragment = new SaveLogcatDialog();
172 // Show the save alert dialog.
173 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_logcat));
175 // Consume the event.
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");
183 // Wait for the process to finish.
186 // Reload the logcat.
187 new GetLogcat(this).execute();
188 } catch (IOException|InterruptedException exception) {
192 // Consume the event.
196 // Don't consume the event.
197 return super.onOptionsItemSelected(menuItem);
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);
206 // Get the file path string.
207 filePathString = fileNameEditText.getText().toString();
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.
212 saveLogcat(filePathString);
213 } else { // The storage permission has not been granted.
214 // Get the external private directory `File`.
215 File externalPrivateDirectoryFile = getExternalFilesDir(null);
217 // Remove the incorrect lint error below that the file might be null.
218 assert externalPrivateDirectoryFile != null;
220 // Get the external private directory string.
221 String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
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.
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();
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);
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);
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.
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);
260 // Display an error snackbar.
261 Snackbar.make(logcatTextView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
265 private void saveLogcat(String fileNameString) {
266 // Get a handle for the logcat text view.
267 TextView logcatTextView = findViewById(R.id.logcat_textview);
270 // Get the logcat as a string.
271 String logcatString = logcatTextView.getText().toString();
273 // Create an input stream with the contents of the logcat.
274 InputStream logcatInputStream = new ByteArrayInputStream(logcatString.getBytes(StandardCharsets.UTF_8));
276 // Create a logcat buffered reader.
277 BufferedReader logcatBufferedReader = new BufferedReader(new InputStreamReader(logcatInputStream));
279 // Create a file from the file name string.
280 File saveFile = new File(fileNameString);
282 // Create a file buffered writer.
283 BufferedWriter fileBufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(saveFile)));
285 // Create a transfer string.
286 String transferString;
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);
293 // Append a line break.
294 fileBufferedWriter.append("\n");
297 // Close the buffered reader and writer.
298 logcatBufferedReader.close();
299 fileBufferedWriter.close();
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);
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();
312 // The activity result is called after browsing for a file in the save alert dialog.
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));
320 // Remove the incorrect lint error that the save dialog fragment might be null.
321 assert saveDialogFragment != null;
323 // Get a handle for the save dialog.
324 Dialog saveDialog = saveDialogFragment.getDialog();
326 // Get a handle for the file name edit text.
327 EditText fileNameEditText = saveDialog.findViewById(R.id.file_name_edittext);
329 // Get the file name URI.
330 Uri fileNameUri = data.getData();
332 // Remove the incorrect lint warning that the file name URI might be null.
333 assert fileNameUri != null;
335 // Get the raw file name path.
336 String rawFileNamePath = fileNameUri.getPath();
338 // Remove the incorrect lint warning that the file name path might be null.
339 assert rawFileNamePath != null;
341 // Check to see if the file name Path includes a valid storage location.
342 if (rawFileNamePath.contains(":")) { // The path is valid.
343 // Split the path into the initial content uri and the final path information.
344 String fileNameContentPath = rawFileNamePath.substring(0, rawFileNamePath.indexOf(":"));
345 String fileNameFinalPath = rawFileNamePath.substring(rawFileNamePath.indexOf(":") + 1);
347 // Create the file name path string.
350 // Construct the file name path.
351 switch (fileNameContentPath) {
352 // The documents home has a special content path.
353 case "/document/home":
354 fileNamePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) + "/" + fileNameFinalPath;
357 // Everything else for the primary user should be in `/document/primary`.
358 case "/document/primary":
359 fileNamePath = Environment.getExternalStorageDirectory() + "/" + fileNameFinalPath;
362 // Just in case, catch everything else and place it in the external storage directory.
364 fileNamePath = Environment.getExternalStorageDirectory() + "/" + fileNameFinalPath;
368 // Set the file name path as the text of the file name edit text.
369 fileNameEditText.setText(fileNamePath);
370 } else { // The path is invalid.
371 // Close the alert dialog.
372 saveDialog.dismiss();
374 // Get a handle for the logcat text view.
375 TextView logcatTextView = findViewById(R.id.logcat_textview);
377 // Display a snackbar with the error message.
378 Snackbar.make(logcatTextView, rawFileNamePath + " " + getString(R.string.invalid_location), Snackbar.LENGTH_INDEFINITE).show();
383 // `Void` does not declare any parameters. `Void` does not declare progress units. `String` contains the results.
384 private static class GetLogcat extends AsyncTask<Void, Void, String> {
385 // Create a weak reference to the calling activity.
386 private final WeakReference<Activity> activityWeakReference;
388 // Populate the weak reference to the calling activity.
389 GetLogcat(Activity activity) {
390 activityWeakReference = new WeakReference<>(activity);
394 protected String doInBackground(Void... parameters) {
395 // Get a handle for the activity.
396 Activity activity = activityWeakReference.get();
398 // Abort if the activity is gone.
399 if ((activity == null) || activity.isFinishing()) {
403 // Create a log string builder.
404 StringBuilder logStringBuilder = new StringBuilder();
407 // 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.
408 Process process = Runtime.getRuntime().exec("logcat -b all -v long -d");
410 // Wrap the logcat in a buffered reader.
411 BufferedReader logBufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
413 // Create a log transfer string.
414 String logTransferString;
416 // Use the log transfer string to copy the logcat from the buffered reader to the string builder.
417 while ((logTransferString = logBufferedReader.readLine()) != null) {
419 logStringBuilder.append(logTransferString);
421 // Append a line break.
422 logStringBuilder.append("\n");
425 // Close the buffered reader.
426 logBufferedReader.close();
427 } catch (IOException exception) {
431 // Return the logcat.
432 return logStringBuilder.toString();
435 // `onPostExecute()` operates on the UI thread.
437 protected void onPostExecute(String logcatString) {
438 // Get a handle for the activity.
439 Activity activity = activityWeakReference.get();
441 // Abort if the activity is gone.
442 if ((activity == null) || activity.isFinishing()) {
446 // Get handles for the views.
447 TextView logcatTextView = activity.findViewById(R.id.logcat_textview);
448 SwipeRefreshLayout swipeRefreshLayout = activity.findViewById(R.id.logcat_swiperefreshlayout);
450 // Display the logcat.
451 logcatTextView.setText(logcatString);
453 // Stop the swipe to refresh animation if it is displayed.
454 swipeRefreshLayout.setRefreshing(false);