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.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;
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;
50 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 import com.stoutner.privacybrowser.helpers.FileNameHelper;
57 import java.io.BufferedReader;
58 import java.io.BufferedWriter;
59 import java.io.ByteArrayInputStream;
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;
69 public class LogcatActivity extends AppCompatActivity implements SaveLogcatDialog.SaveLogcatListener, StoragePermissionDialog.StoragePermissionDialogListener {
70 private String filePathString;
73 public void onCreate(Bundle savedInstanceState) {
74 // Get a handle for the shared preferences.
75 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
77 // Get the theme and screenshot preferences.
78 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
79 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
81 // Disable screenshots if not allowed.
82 if (!allowScreenshots) {
83 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
86 // Set the activity theme.
88 setTheme(R.style.PrivacyBrowserDark_SecondaryActivity);
90 setTheme(R.style.PrivacyBrowserLight_SecondaryActivity);
93 // Run the default commands.
94 super.onCreate(savedInstanceState);
96 // Set the content view.
97 setContentView(R.layout.logcat_coordinatorlayout);
99 // The AndroidX toolbar must be used until the minimum API is >= 21.
100 Toolbar toolbar = findViewById(R.id.logcat_toolbar);
101 setSupportActionBar(toolbar);
103 // Get a handle for the action bar.
104 ActionBar actionBar = getSupportActionBar();
106 // Remove the incorrect lint warning that the action bar might be null.
107 assert actionBar != null;
109 // Display the the back arrow in the action bar.
110 actionBar.setDisplayHomeAsUpEnabled(true);
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();
119 // Set the swipe to refresh color according to the theme.
121 swipeRefreshLayout.setColorSchemeResources(R.color.blue_600);
122 swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_800);
124 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
128 new GetLogcat(this).execute();
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);
141 public boolean onOptionsItemSelected(MenuItem menuItem) {
142 // Get the selected menu item ID.
143 int menuItemId = menuItem.getItemId();
145 // Run the commands that correlate to the selected menu item.
146 switch (menuItemId) {
148 // Get a handle for the clipboard manager.
149 ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
151 // Get a handle for the logcat text view.
152 TextView logcatTextView = findViewById(R.id.logcat_textview);
154 // Save the logcat in a ClipData.
155 ClipData logcatClipData = ClipData.newPlainText(getString(R.string.logcat), logcatTextView.getText());
157 // Remove the incorrect lint error that `clipboardManager.setPrimaryClip()` might produce a null pointer exception.
158 assert clipboardManager != null;
160 // Place the ClipData on the clipboard.
161 clipboardManager.setPrimaryClip(logcatClipData);
163 // Display a snackbar.
164 Snackbar.make(logcatTextView, R.string.logcat_copied, Snackbar.LENGTH_SHORT).show();
166 // Consume the event.
170 // Instantiate the save alert dialog.
171 DialogFragment saveDialogFragment = new SaveLogcatDialog();
173 // Show the save alert dialog.
174 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_logcat));
176 // Consume the event.
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");
184 // Wait for the process to finish.
187 // Reload the logcat.
188 new GetLogcat(this).execute();
189 } catch (IOException|InterruptedException exception) {
193 // Consume the event.
197 // Don't consume the event.
198 return super.onOptionsItemSelected(menuItem);
203 public void onSaveLogcat(DialogFragment dialogFragment) {
204 // Get a handle for the dialog fragment.
205 Dialog dialog = dialogFragment.getDialog();
207 // Remove the lint warning below that the dialog fragment might be null.
208 assert dialog != null;
210 // Get a handle for the file name edit text.
211 EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
213 // Get the file path string.
214 filePathString = fileNameEditText.getText().toString();
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.
219 saveLogcat(filePathString);
220 } else { // The storage permission has not been granted.
221 // Get the external private directory `File`.
222 File externalPrivateDirectoryFile = getExternalFilesDir(null);
224 // Remove the incorrect lint error below that the file might be null.
225 assert externalPrivateDirectoryFile != null;
227 // Get the external private directory string.
228 String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
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.
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);
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);
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);
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.
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);
267 // Display an error snackbar.
268 Snackbar.make(logcatTextView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
272 private void saveLogcat(String fileNameString) {
273 // Get a handle for the logcat text view.
274 TextView logcatTextView = findViewById(R.id.logcat_textview);
277 // Get the logcat as a string.
278 String logcatString = logcatTextView.getText().toString();
280 // Create an input stream with the contents of the logcat.
281 InputStream logcatInputStream = new ByteArrayInputStream(logcatString.getBytes(StandardCharsets.UTF_8));
283 // Create a logcat buffered reader.
284 BufferedReader logcatBufferedReader = new BufferedReader(new InputStreamReader(logcatInputStream));
286 // Create a file from the file name string.
287 File saveFile = new File(fileNameString);
289 // Create a file buffered writer.
290 BufferedWriter fileBufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(saveFile)));
292 // Create a transfer string.
293 String transferString;
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);
300 // Append a line break.
301 fileBufferedWriter.append("\n");
304 // Close the buffered reader and writer.
305 logcatBufferedReader.close();
306 fileBufferedWriter.close();
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);
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();
319 // The activity result is called after browsing for a file in the save alert dialog.
321 public void onActivityResult(int requestCode, int resultCode, Intent data) {
322 // Run the default commands.
323 super.onActivityResult(requestCode, resultCode, data);
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));
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();
335 // Remove the lint warning below that the save dialog might be null.
336 assert saveDialog != null;
338 // Get a handle for the file name edit text.
339 EditText fileNameEditText = saveDialog.findViewById(R.id.file_name_edittext);
341 // Instantiate the file name helper.
342 FileNameHelper fileNameHelper = new FileNameHelper();
344 // Get the file name URI from the intent.
345 Uri fileNameUri= data.getData();
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);
352 // Set the file name path as the text of the file name edit text.
353 fileNameEditText.setText(fileNamePath);
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;
364 // Populate the weak reference to the calling activity.
365 GetLogcat(Activity activity) {
366 activityWeakReference = new WeakReference<>(activity);
370 protected String doInBackground(Void... parameters) {
371 // Get a handle for the activity.
372 Activity activity = activityWeakReference.get();
374 // Abort if the activity is gone.
375 if ((activity == null) || activity.isFinishing()) {
379 // Create a log string builder.
380 StringBuilder logStringBuilder = new StringBuilder();
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");
386 // Wrap the logcat in a buffered reader.
387 BufferedReader logBufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
389 // Create a log transfer string.
390 String logTransferString;
392 // Use the log transfer string to copy the logcat from the buffered reader to the string builder.
393 while ((logTransferString = logBufferedReader.readLine()) != null) {
395 logStringBuilder.append(logTransferString);
397 // Append a line break.
398 logStringBuilder.append("\n");
401 // Close the buffered reader.
402 logBufferedReader.close();
403 } catch (IOException exception) {
407 // Return the logcat.
408 return logStringBuilder.toString();
411 // `onPostExecute()` operates on the UI thread.
413 protected void onPostExecute(String logcatString) {
414 // Get a handle for the activity.
415 Activity activity = activityWeakReference.get();
417 // Abort if the activity is gone.
418 if ((activity == null) || activity.isFinishing()) {
422 // Get handles for the views.
423 TextView logcatTextView = activity.findViewById(R.id.logcat_textview);
424 SwipeRefreshLayout swipeRefreshLayout = activity.findViewById(R.id.logcat_swiperefreshlayout);
426 // Display the logcat.
427 logcatTextView.setText(logcatString);
429 // Stop the swipe to refresh animation if it is displayed.
430 swipeRefreshLayout.setRefreshing(false);