2 * Copyright © 2016-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.ContentResolver;
26 import android.content.Intent;
27 import android.content.SharedPreferences;
28 import android.content.pm.PackageManager;
29 import android.media.MediaScannerConnection;
30 import android.net.Uri;
31 import android.os.Build;
32 import android.os.Bundle;
33 import android.preference.PreferenceManager;
34 import android.view.View;
35 import android.view.WindowManager;
36 import android.widget.EditText;
37 import android.widget.LinearLayout;
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;
44 import androidx.core.app.ActivityCompat;
45 import androidx.core.content.ContextCompat;
46 import androidx.core.content.FileProvider;
47 import androidx.fragment.app.DialogFragment;
48 import androidx.viewpager.widget.ViewPager;
50 import com.google.android.material.snackbar.Snackbar;
51 import com.google.android.material.tabs.TabLayout;
53 import com.stoutner.privacybrowser.adapters.AboutPagerAdapter;
54 import com.stoutner.privacybrowser.R;
55 import com.stoutner.privacybrowser.asynctasks.SaveAboutVersionImage;
56 import com.stoutner.privacybrowser.dialogs.SaveDialog;
57 import com.stoutner.privacybrowser.dialogs.StoragePermissionDialog;
58 import com.stoutner.privacybrowser.fragments.AboutVersionFragment;
59 import com.stoutner.privacybrowser.helpers.FileNameHelper;
61 import java.io.BufferedReader;
62 import java.io.BufferedWriter;
63 import java.io.ByteArrayInputStream;
65 import java.io.FileOutputStream;
66 import java.io.InputStream;
67 import java.io.InputStreamReader;
68 import java.io.OutputStreamWriter;
69 import java.nio.charset.StandardCharsets;
71 public class AboutActivity extends AppCompatActivity implements SaveDialog.SaveListener, StoragePermissionDialog.StoragePermissionDialogListener {
72 // Declare the class variables.
73 private String filePathString;
74 private AboutPagerAdapter aboutPagerAdapter;
76 // Declare the class views.
77 private LinearLayout aboutVersionLinearLayout;
80 protected void onCreate(Bundle savedInstanceState) {
81 // Get a handle for the shared preferences.
82 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
84 // Get the screenshot preference.
85 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
87 // Disable screenshots if not allowed.
88 if (!allowScreenshots) {
89 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
93 setTheme(R.style.PrivacyBrowser);
95 // Run the default commands.
96 super.onCreate(savedInstanceState);
98 // Get the intent that launched the activity.
99 Intent launchingIntent = getIntent();
101 // Store the blocklist versions.
102 String[] blocklistVersions = launchingIntent.getStringArrayExtra("blocklist_versions");
104 // Set the content view.
105 setContentView(R.layout.about_coordinatorlayout);
107 // Get handles for the views.
108 Toolbar toolbar = findViewById(R.id.about_toolbar);
109 TabLayout aboutTabLayout = findViewById(R.id.about_tablayout);
110 ViewPager aboutViewPager = findViewById(R.id.about_viewpager);
112 // Set the action bar. `SupportActionBar` must be used until the minimum API is >= 21.
113 setSupportActionBar(toolbar);
115 // Get a handle for the action bar.
116 final ActionBar actionBar = getSupportActionBar();
118 // Remove the incorrect lint warning that the action bar might be null.
119 assert actionBar != null; //
121 // Display the home arrow on action bar.
122 actionBar.setDisplayHomeAsUpEnabled(true);
124 // Initialize the about pager adapter.
125 aboutPagerAdapter = new AboutPagerAdapter(getSupportFragmentManager(), getApplicationContext(), blocklistVersions);
127 // Setup the ViewPager.
128 aboutViewPager.setAdapter(aboutPagerAdapter);
130 // Keep all the tabs in memory. This prevents the memory usage updater from running multiple times.
131 aboutViewPager.setOffscreenPageLimit(10);
133 // Connect the tab layout to the view pager.
134 aboutTabLayout.setupWithViewPager(aboutViewPager);
138 public void onSave(int saveType, DialogFragment dialogFragment) {
139 // Get a handle for the dialog.
140 Dialog dialog = dialogFragment.getDialog();
142 // Remove the lint warning below that the dialog might be null.
143 assert dialog != null;
145 // Get a handle for the file name edit text.
146 EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
148 // Get the file path string.
149 filePathString = fileNameEditText.getText().toString();
151 // Get a handle for the about version linear layout.
152 aboutVersionLinearLayout = findViewById(R.id.about_version_linearlayout);
154 // check to see if the storage permission is needed.
155 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // The storage permission has been granted.
156 // Save the file according to the type.
158 case SaveDialog.SAVE_ABOUT_VERSION_TEXT:
159 // Save the about version text.
160 saveAsText(filePathString);
163 case SaveDialog.SAVE_ABOUT_VERSION_IMAGE:
164 // Save the about version image.
165 new SaveAboutVersionImage(this, this, filePathString, aboutVersionLinearLayout).execute();
169 // Reset the file path string.
171 } else { // The storage permission has not been granted.
172 // Get the external private directory file.
173 File externalPrivateDirectoryFile = getExternalFilesDir(null);
175 // Remove the incorrect lint error below that the file might be null.
176 assert externalPrivateDirectoryFile != null;
178 // Get the external private directory string.
179 String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
181 // Check to see if the file path is in the external private directory.
182 if (filePathString.startsWith(externalPrivateDirectory)) { // The file path is in the external private directory.
183 // Save the webpage according to the type.
185 case SaveDialog.SAVE_ABOUT_VERSION_TEXT:
186 // Save the about version text.
187 saveAsText(filePathString);
190 case SaveDialog.SAVE_ABOUT_VERSION_IMAGE:
191 // Save the about version image.
192 new SaveAboutVersionImage(this, this, filePathString, aboutVersionLinearLayout).execute();
196 // Reset the file path string.
198 } else { // The file path is in a public directory.
199 // Check if the user has previously denied the storage permission.
200 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
201 // Declare a storage permission dialog fragment.
202 DialogFragment storagePermissionDialogFragment;
204 // Instantiate the storage permission alert dialog according to the type.
205 if (saveType == SaveDialog.SAVE_ABOUT_VERSION_TEXT) {
206 storagePermissionDialogFragment = StoragePermissionDialog.displayDialog(StoragePermissionDialog.SAVE_TEXT);
208 storagePermissionDialogFragment = StoragePermissionDialog.displayDialog(StoragePermissionDialog.SAVE_IMAGE);
211 // Show the storage permission alert dialog. The permission will be requested when the dialog is closed.
212 storagePermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.storage_permission));
213 } else { // Show the permission request directly.
215 case SaveDialog.SAVE_ABOUT_VERSION_TEXT:
216 // Request the write external storage permission. The text will be saved when it finishes.
217 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, StoragePermissionDialog.SAVE_TEXT);
220 case SaveDialog.SAVE_ABOUT_VERSION_IMAGE:
221 // Request the write external storage permission. The image will be saved when it finishes.
222 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, StoragePermissionDialog.SAVE_IMAGE);
232 public void onCloseStoragePermissionDialog(int requestType) {
233 // Request the write external storage permission according to the request type. About version will be saved when it finishes.
234 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestType);
238 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
239 //Only process the results if they exist (this method is triggered when a dialog is presented the first time for an app, but no grant results are included).
240 if (grantResults.length > 0) {
241 // Check to see if the storage permission was granted. If the dialog was canceled the grant results will be empty.
242 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // The storage permission was granted.
243 switch (requestCode) {
244 case StoragePermissionDialog.SAVE_TEXT:
245 // Save the about version text.
246 saveAsText(filePathString);
249 case StoragePermissionDialog.SAVE_IMAGE:
250 // Save the about version image.
251 new SaveAboutVersionImage(this, this, filePathString, aboutVersionLinearLayout).execute();
254 } else{ // the storage permission was not granted.
255 // Display an error snackbar.
256 Snackbar.make(aboutVersionLinearLayout, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
259 // Reset the file path string.
264 // The activity result is called after browsing for a file in the save alert dialog.
266 public void onActivityResult(int requestCode, int resultCode, Intent data) {
267 // Run the default commands.
268 super.onActivityResult(requestCode, resultCode, data);
270 // Only do something if the user didn't press back from the file picker.
271 if (resultCode == Activity.RESULT_OK) {
272 // Get a handle for the save dialog fragment.
273 DialogFragment saveDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.save_dialog));
275 // Only update the file name if the dialog still exists.
276 if (saveDialogFragment != null) {
277 // Get a handle for the save dialog.
278 Dialog saveDialog = saveDialogFragment.getDialog();
280 // Remove the lint warning below that the dialog might be null.
281 assert saveDialog != null;
283 // Get a handle for the dialog view.
284 EditText fileNameEditText = saveDialog.findViewById(R.id.file_name_edittext);
285 TextView fileExistsWarningTextView = saveDialog.findViewById(R.id.file_exists_warning_textview);
287 // Get the file name URI from the intent.
288 Uri fileNameUri = data.getData();
290 // Process the file name URI if it is not null.
291 if (fileNameUri != null) {
292 // Instantiate a file name helper.
293 FileNameHelper fileNameHelper = new FileNameHelper();
295 // Convert the file name URI to a file name path.
296 String fileNamePath = fileNameHelper.convertUriToFileNamePath(fileNameUri);
298 // Set the file name path as the text of the file nam edit text.
299 fileNameEditText.setText(fileNamePath);
301 // Move the cursor to the end of the file name edit text.
302 fileNameEditText.setSelection(fileNamePath.length());
304 // Hid ethe file exists warning.
305 fileExistsWarningTextView.setVisibility(View.GONE);
311 private void saveAsText(String fileNameString) {
313 // Get a handle for the about about version fragment.
314 AboutVersionFragment aboutVersionFragment = (AboutVersionFragment) aboutPagerAdapter.getTabFragment(0);
316 // Get the about version text.
317 String aboutVersionString = aboutVersionFragment.getAboutVersionString();
319 // Create an input stream with the contents of about version.
320 InputStream aboutVersionInputStream = new ByteArrayInputStream(aboutVersionString.getBytes(StandardCharsets.UTF_8));
322 // Create an about version buffered reader.
323 BufferedReader aboutVersionBufferedReader = new BufferedReader(new InputStreamReader(aboutVersionInputStream));
325 // Create a file from the file name string.
326 File saveFile = new File(fileNameString);
328 // Delete the file if it already exists.
329 if (saveFile.exists()) {
330 //noinspection ResultOfMethodCallIgnored
334 // Create a file buffered writer.
335 BufferedWriter fileBufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(saveFile)));
337 // Create a transfer string.
338 String transferString;
340 // Use the transfer string to copy the about version text from the buffered reader to the buffered writer.
341 while ((transferString = aboutVersionBufferedReader.readLine()) != null) {
342 // Append the line to the buffered writer.
343 fileBufferedWriter.append(transferString);
345 // Append a line break.
346 fileBufferedWriter.append("\n");
349 // Close the buffered reader and writer.
350 aboutVersionBufferedReader.close();
351 fileBufferedWriter.close();
353 // Add the file to the list of recent files. This doesn't currently work, but maybe it will someday.
354 MediaScannerConnection.scanFile(this, new String[] {fileNameString}, new String[] {"text/plain"}, null);
356 // Create an about version saved snackbar.
357 Snackbar aboutVersionSavedSnackbar = Snackbar.make(aboutVersionLinearLayout, getString(R.string.file_saved) + " " + fileNameString, Snackbar.LENGTH_SHORT);
359 // Add an open option to the snackbar.
360 aboutVersionSavedSnackbar.setAction(R.string.open, (View view) -> {
361 // Get a file for the file name string.
362 File file = new File(fileNameString);
364 // Declare a file URI variable.
367 // Get the URI for the file according to the Android version.
368 if (Build.VERSION.SDK_INT >= 24) { // Use a file provider.
369 fileUri = FileProvider.getUriForFile(this, getString(R.string.file_provider), file);
370 } else { // Get the raw file path URI.
371 fileUri = Uri.fromFile(file);
374 // Get a handle for the content resolver.
375 ContentResolver contentResolver = getContentResolver();
377 // Create an open intent with `ACTION_VIEW`.
378 Intent openIntent = new Intent(Intent.ACTION_VIEW);
380 // Set the URI and the MIME type.
381 openIntent.setDataAndType(fileUri, contentResolver.getType(fileUri));
383 // Allow the app to read the file URI.
384 openIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
387 startActivity(Intent.createChooser(openIntent, getString(R.string.open)));
390 // Show the about version saved snackbar.
391 aboutVersionSavedSnackbar.show();
392 } catch (Exception exception) {
393 // Display a snackbar with the error message.
394 Snackbar.make(aboutVersionLinearLayout, getString(R.string.error_saving_file) + " " + exception.toString(), Snackbar.LENGTH_INDEFINITE).show();