2 * Copyright © 2019-2020 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.View;
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;
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;
53 import com.stoutner.privacybrowser.R;
54 import com.stoutner.privacybrowser.dialogs.StoragePermissionDialog;
55 import com.stoutner.privacybrowser.dialogs.SaveLogcatDialog;
56 import com.stoutner.privacybrowser.helpers.FileNameHelper;
58 import java.io.BufferedReader;
59 import java.io.BufferedWriter;
60 import java.io.ByteArrayInputStream;
62 import java.io.FileOutputStream;
63 import java.io.IOException;
64 import java.io.InputStream;
65 import java.io.InputStreamReader;
66 import java.io.OutputStreamWriter;
67 import java.lang.ref.WeakReference;
68 import java.nio.charset.StandardCharsets;
70 public class LogcatActivity extends AppCompatActivity implements SaveLogcatDialog.SaveLogcatListener, StoragePermissionDialog.StoragePermissionDialogListener {
71 private String filePathString;
74 public void onCreate(Bundle savedInstanceState) {
75 // Get a handle for the shared preferences.
76 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
78 // Get the theme and screenshot preferences.
79 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
80 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
82 // Disable screenshots if not allowed.
83 if (!allowScreenshots) {
84 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
87 // Set the activity theme.
89 setTheme(R.style.PrivacyBrowserDark_SecondaryActivity);
91 setTheme(R.style.PrivacyBrowserLight_SecondaryActivity);
94 // Run the default commands.
95 super.onCreate(savedInstanceState);
97 // Set the content view.
98 setContentView(R.layout.logcat_coordinatorlayout);
100 // The AndroidX toolbar must be used until the minimum API is >= 21.
101 Toolbar toolbar = findViewById(R.id.logcat_toolbar);
102 setSupportActionBar(toolbar);
104 // Get a handle for the action bar.
105 ActionBar actionBar = getSupportActionBar();
107 // Remove the incorrect lint warning that the action bar might be null.
108 assert actionBar != null;
110 // Display the the back arrow in the action bar.
111 actionBar.setDisplayHomeAsUpEnabled(true);
113 // Implement swipe to refresh.
114 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.logcat_swiperefreshlayout);
115 swipeRefreshLayout.setOnRefreshListener(() -> {
116 // Get the current logcat.
117 new GetLogcat(this).execute();
120 // Set the swipe to refresh color according to the theme.
122 swipeRefreshLayout.setColorSchemeResources(R.color.blue_600);
123 swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_800);
125 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
129 new GetLogcat(this).execute();
133 public boolean onCreateOptionsMenu(Menu menu) {
134 // Inflate the menu. This adds items to the action bar.
135 getMenuInflater().inflate(R.menu.logcat_options_menu, menu);
142 public boolean onOptionsItemSelected(MenuItem menuItem) {
143 // Get the selected menu item ID.
144 int menuItemId = menuItem.getItemId();
146 // Run the commands that correlate to the selected menu item.
147 switch (menuItemId) {
149 // Get a handle for the clipboard manager.
150 ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
152 // Get a handle for the logcat text view.
153 TextView logcatTextView = findViewById(R.id.logcat_textview);
155 // Save the logcat in a ClipData.
156 ClipData logcatClipData = ClipData.newPlainText(getString(R.string.logcat), logcatTextView.getText());
158 // Remove the incorrect lint error that `clipboardManager.setPrimaryClip()` might produce a null pointer exception.
159 assert clipboardManager != null;
161 // Place the ClipData on the clipboard.
162 clipboardManager.setPrimaryClip(logcatClipData);
164 // Display a snackbar.
165 Snackbar.make(logcatTextView, R.string.logcat_copied, Snackbar.LENGTH_SHORT).show();
167 // Consume the event.
171 // Instantiate the save alert dialog.
172 DialogFragment saveDialogFragment = new SaveLogcatDialog();
174 // Show the save alert dialog.
175 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_logcat));
177 // Consume the event.
182 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
183 Process process = Runtime.getRuntime().exec("logcat -b all -c");
185 // Wait for the process to finish.
188 // Reload the logcat.
189 new GetLogcat(this).execute();
190 } catch (IOException|InterruptedException exception) {
194 // Consume the event.
198 // Don't consume the event.
199 return super.onOptionsItemSelected(menuItem);
204 public void onSaveLogcat(DialogFragment dialogFragment) {
205 // Get a handle for the dialog fragment.
206 Dialog dialog = dialogFragment.getDialog();
208 // Remove the lint warning below that the dialog fragment might be null.
209 assert dialog != null;
211 // Get a handle for the file name edit text.
212 EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
214 // Get the file path string.
215 filePathString = fileNameEditText.getText().toString();
217 // Check to see if the storage permission is needed.
218 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // The storage permission has been granted.
220 saveLogcat(filePathString);
221 } else { // The storage permission has not been granted.
222 // Get the external private directory `File`.
223 File externalPrivateDirectoryFile = getExternalFilesDir(null);
225 // Remove the incorrect lint error below that the file might be null.
226 assert externalPrivateDirectoryFile != null;
228 // Get the external private directory string.
229 String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
231 // Check to see if the file path is in the external private directory.
232 if (filePathString.startsWith(externalPrivateDirectory)) { // The file path is in the external private directory.
234 saveLogcat(filePathString);
235 } else { // The file path in in a public directory.
236 // Check if the user has previously denied the storage permission.
237 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
238 // Instantiate the storage permission alert dialog.
239 DialogFragment storagePermissionDialogFragment = StoragePermissionDialog.displayDialog(0);
241 // Show the storage permission alert dialog. The permission will be requested when the dialog is closed.
242 storagePermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.storage_permission));
243 } else { // Show the permission request directly.
244 // Request the write external storage permission. The logcat will be saved when it finishes.
245 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
253 public void onCloseStoragePermissionDialog(int type) {
254 // Request the write external storage permission. The logcat will be saved when it finishes.
255 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
259 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
260 // Check to see if the storage permission was granted. If the dialog was canceled the grant result will be empty.
261 if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) { // The storage permission was granted.
263 saveLogcat(filePathString);
264 } else { // The storage permission was not granted.
265 // Get a handle for the logcat text view.
266 TextView logcatTextView = findViewById(R.id.logcat_textview);
268 // Display an error snackbar.
269 Snackbar.make(logcatTextView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
273 private void saveLogcat(String fileNameString) {
274 // Get a handle for the logcat text view.
275 TextView logcatTextView = findViewById(R.id.logcat_textview);
278 // Get the logcat as a string.
279 String logcatString = logcatTextView.getText().toString();
281 // Create an input stream with the contents of the logcat.
282 InputStream logcatInputStream = new ByteArrayInputStream(logcatString.getBytes(StandardCharsets.UTF_8));
284 // Create a logcat buffered reader.
285 BufferedReader logcatBufferedReader = new BufferedReader(new InputStreamReader(logcatInputStream));
287 // Create a file from the file name string.
288 File saveFile = new File(fileNameString);
290 // Create a file buffered writer.
291 BufferedWriter fileBufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(saveFile)));
293 // Create a transfer string.
294 String transferString;
296 // Use the transfer string to copy the logcat from the buffered reader to the buffered writer.
297 while ((transferString = logcatBufferedReader.readLine()) != null) {
298 // Append the line to the buffered writer.
299 fileBufferedWriter.append(transferString);
301 // Append a line break.
302 fileBufferedWriter.append("\n");
305 // Close the buffered reader and writer.
306 logcatBufferedReader.close();
307 fileBufferedWriter.close();
309 // Add the file to the list of recent files. This doesn't currently work, but maybe it will someday.
310 MediaScannerConnection.scanFile(this, new String[] {fileNameString}, new String[] {"text/plain"}, null);
312 // Display a snackbar.
313 Snackbar.make(logcatTextView, getString(R.string.file_saved_successfully), Snackbar.LENGTH_SHORT).show();
314 } catch (Exception exception) {
315 // Display a snackbar with the error message.
316 Snackbar.make(logcatTextView, getString(R.string.save_failed) + " " + exception.toString(), Snackbar.LENGTH_INDEFINITE).show();
320 // The activity result is called after browsing for a file in the save alert dialog.
322 public void onActivityResult(int requestCode, int resultCode, Intent data) {
323 // Run the default commands.
324 super.onActivityResult(requestCode, resultCode, data);
326 // Don't do anything if the user pressed back from the file picker.
327 if (resultCode == Activity.RESULT_OK) {
328 // Get a handle for the save dialog fragment.
329 DialogFragment saveDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.save_logcat));
331 // Only update the file name if the dialog still exists.
332 if (saveDialogFragment != null) {
333 // Get a handle for the save dialog.
334 Dialog saveDialog = saveDialogFragment.getDialog();
336 // Remove the lint warning below that the save dialog might be null.
337 assert saveDialog != null;
339 // Get a handle for the dialog views.
340 EditText fileNameEditText = saveDialog.findViewById(R.id.file_name_edittext);
341 TextView fileExistsWarningTextView = saveDialog.findViewById(R.id.file_exists_warning_textview);
343 // Instantiate the file name helper.
344 FileNameHelper fileNameHelper = new FileNameHelper();
346 // Get the file name URI from the intent.
347 Uri fileNameUri= data.getData();
349 // Process the file name URI if it is not null.
350 if (fileNameUri != null) {
351 // Convert the file name URI to a file name path.
352 String fileNamePath = fileNameHelper.convertUriToFileNamePath(fileNameUri);
354 // Set the file name path as the text of the file name edit text.
355 fileNameEditText.setText(fileNamePath);
357 // Move the cursor to the end of the file name edit text.
358 fileNameEditText.setSelection(fileNamePath.length());
360 // Hide the file exists warning.
361 fileExistsWarningTextView.setVisibility(View.GONE);
367 // `Void` does not declare any parameters. `Void` does not declare progress units. `String` contains the results.
368 private static class GetLogcat extends AsyncTask<Void, Void, String> {
369 // Create a weak reference to the calling activity.
370 private final WeakReference<Activity> activityWeakReference;
372 // Populate the weak reference to the calling activity.
373 GetLogcat(Activity activity) {
374 activityWeakReference = new WeakReference<>(activity);
378 protected String doInBackground(Void... parameters) {
379 // Get a handle for the activity.
380 Activity activity = activityWeakReference.get();
382 // Abort if the activity is gone.
383 if ((activity == null) || activity.isFinishing()) {
387 // Create a log string builder.
388 StringBuilder logStringBuilder = new StringBuilder();
391 // 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.
392 Process process = Runtime.getRuntime().exec("logcat -b all -v long -d");
394 // Wrap the logcat in a buffered reader.
395 BufferedReader logBufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
397 // Create a log transfer string.
398 String logTransferString;
400 // Use the log transfer string to copy the logcat from the buffered reader to the string builder.
401 while ((logTransferString = logBufferedReader.readLine()) != null) {
403 logStringBuilder.append(logTransferString);
405 // Append a line break.
406 logStringBuilder.append("\n");
409 // Close the buffered reader.
410 logBufferedReader.close();
411 } catch (IOException exception) {
415 // Return the logcat.
416 return logStringBuilder.toString();
419 // `onPostExecute()` operates on the UI thread.
421 protected void onPostExecute(String logcatString) {
422 // Get a handle for the activity.
423 Activity activity = activityWeakReference.get();
425 // Abort if the activity is gone.
426 if ((activity == null) || activity.isFinishing()) {
430 // Get handles for the views.
431 TextView logcatTextView = activity.findViewById(R.id.logcat_textview);
432 SwipeRefreshLayout swipeRefreshLayout = activity.findViewById(R.id.logcat_swiperefreshlayout);
434 // Display the logcat.
435 logcatTextView.setText(logcatString);
437 // Stop the swipe to refresh animation if it is displayed.
438 swipeRefreshLayout.setRefreshing(false);