2 * Copyright © 2016-2021 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 // Remove the incorrect lint warning below that the blocklist versions might be null.
105 assert blocklistVersions != null;
107 // Set the content view.
108 setContentView(R.layout.about_coordinatorlayout);
110 // Get handles for the views.
111 Toolbar toolbar = findViewById(R.id.about_toolbar);
112 TabLayout aboutTabLayout = findViewById(R.id.about_tablayout);
113 ViewPager aboutViewPager = findViewById(R.id.about_viewpager);
115 // Set the action bar. `SupportActionBar` must be used until the minimum API is >= 21.
116 setSupportActionBar(toolbar);
118 // Get a handle for the action bar.
119 final ActionBar actionBar = getSupportActionBar();
121 // Remove the incorrect lint warning that the action bar might be null.
122 assert actionBar != null; //
124 // Display the home arrow on action bar.
125 actionBar.setDisplayHomeAsUpEnabled(true);
127 // Initialize the about pager adapter.
128 aboutPagerAdapter = new AboutPagerAdapter(getSupportFragmentManager(), getApplicationContext(), blocklistVersions);
130 // Setup the ViewPager.
131 aboutViewPager.setAdapter(aboutPagerAdapter);
133 // Keep all the tabs in memory. This prevents the memory usage updater from running multiple times.
134 aboutViewPager.setOffscreenPageLimit(10);
136 // Connect the tab layout to the view pager.
137 aboutTabLayout.setupWithViewPager(aboutViewPager);
141 public void onSave(int saveType, DialogFragment dialogFragment) {
142 // Get a handle for the dialog.
143 Dialog dialog = dialogFragment.getDialog();
145 // Remove the lint warning below that the dialog might be null.
146 assert dialog != null;
148 // Get a handle for the file name edit text.
149 EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
151 // Get the file path string.
152 filePathString = fileNameEditText.getText().toString();
154 // Get a handle for the about version linear layout.
155 aboutVersionLinearLayout = findViewById(R.id.about_version_linearlayout);
157 // check to see if the storage permission is needed.
158 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // The storage permission has been granted.
159 // Save the file according to the type.
161 case SaveDialog.SAVE_ABOUT_VERSION_TEXT:
162 // Save the about version text.
163 saveAsText(filePathString);
166 case SaveDialog.SAVE_ABOUT_VERSION_IMAGE:
167 // Save the about version image.
168 new SaveAboutVersionImage(this, this, filePathString, aboutVersionLinearLayout).execute();
172 // Reset the file path string.
174 } else { // The storage permission has not been granted.
175 // Get the external private directory file.
176 File externalPrivateDirectoryFile = getExternalFilesDir(null);
178 // Remove the incorrect lint error below that the file might be null.
179 assert externalPrivateDirectoryFile != null;
181 // Get the external private directory string.
182 String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
184 // Check to see if the file path is in the external private directory.
185 if (filePathString.startsWith(externalPrivateDirectory)) { // The file path is in the external private directory.
186 // Save the webpage according to the type.
188 case SaveDialog.SAVE_ABOUT_VERSION_TEXT:
189 // Save the about version text.
190 saveAsText(filePathString);
193 case SaveDialog.SAVE_ABOUT_VERSION_IMAGE:
194 // Save the about version image.
195 new SaveAboutVersionImage(this, this, filePathString, aboutVersionLinearLayout).execute();
199 // Reset the file path string.
201 } else { // The file path is in a public directory.
202 // Check if the user has previously denied the storage permission.
203 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
204 // Declare a storage permission dialog fragment.
205 DialogFragment storagePermissionDialogFragment;
207 // Instantiate the storage permission alert dialog according to the type.
208 if (saveType == SaveDialog.SAVE_ABOUT_VERSION_TEXT) {
209 storagePermissionDialogFragment = StoragePermissionDialog.displayDialog(StoragePermissionDialog.SAVE_TEXT);
211 storagePermissionDialogFragment = StoragePermissionDialog.displayDialog(StoragePermissionDialog.SAVE_IMAGE);
214 // Show the storage permission alert dialog. The permission will be requested when the dialog is closed.
215 storagePermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.storage_permission));
216 } else { // Show the permission request directly.
218 case SaveDialog.SAVE_ABOUT_VERSION_TEXT:
219 // Request the write external storage permission. The text will be saved when it finishes.
220 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, StoragePermissionDialog.SAVE_TEXT);
223 case SaveDialog.SAVE_ABOUT_VERSION_IMAGE:
224 // Request the write external storage permission. The image will be saved when it finishes.
225 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, StoragePermissionDialog.SAVE_IMAGE);
235 public void onCloseStoragePermissionDialog(int requestType) {
236 // Request the write external storage permission according to the request type. About version will be saved when it finishes.
237 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestType);
241 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
242 //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).
243 if (grantResults.length > 0) {
244 // Check to see if the storage permission was granted. If the dialog was canceled the grant results will be empty.
245 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // The storage permission was granted.
246 switch (requestCode) {
247 case StoragePermissionDialog.SAVE_TEXT:
248 // Save the about version text.
249 saveAsText(filePathString);
252 case StoragePermissionDialog.SAVE_IMAGE:
253 // Save the about version image.
254 new SaveAboutVersionImage(this, this, filePathString, aboutVersionLinearLayout).execute();
257 } else{ // the storage permission was not granted.
258 // Display an error snackbar.
259 Snackbar.make(aboutVersionLinearLayout, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
262 // Reset the file path string.
267 // The activity result is called after browsing for a file in the save alert dialog.
269 public void onActivityResult(int requestCode, int resultCode, Intent data) {
270 // Run the default commands.
271 super.onActivityResult(requestCode, resultCode, data);
273 // Only do something if the user didn't press back from the file picker.
274 if (resultCode == Activity.RESULT_OK) {
275 // Get a handle for the save dialog fragment.
276 DialogFragment saveDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.save_dialog));
278 // Only update the file name if the dialog still exists.
279 if (saveDialogFragment != null) {
280 // Get a handle for the save dialog.
281 Dialog saveDialog = saveDialogFragment.getDialog();
283 // Remove the lint warning below that the dialog might be null.
284 assert saveDialog != null;
286 // Get a handle for the dialog view.
287 EditText fileNameEditText = saveDialog.findViewById(R.id.file_name_edittext);
288 TextView fileExistsWarningTextView = saveDialog.findViewById(R.id.file_exists_warning_textview);
290 // Get the file name URI from the intent.
291 Uri fileNameUri = data.getData();
293 // Process the file name URI if it is not null.
294 if (fileNameUri != null) {
295 // Instantiate a file name helper.
296 FileNameHelper fileNameHelper = new FileNameHelper();
298 // Convert the file name URI to a file name path.
299 String fileNamePath = fileNameHelper.convertUriToFileNamePath(fileNameUri);
301 // Set the file name path as the text of the file nam edit text.
302 fileNameEditText.setText(fileNamePath);
304 // Move the cursor to the end of the file name edit text.
305 fileNameEditText.setSelection(fileNamePath.length());
307 // Hid ethe file exists warning.
308 fileExistsWarningTextView.setVisibility(View.GONE);
314 private void saveAsText(String fileNameString) {
316 // Get a handle for the about about version fragment.
317 AboutVersionFragment aboutVersionFragment = (AboutVersionFragment) aboutPagerAdapter.getTabFragment(0);
319 // Get the about version text.
320 String aboutVersionString = aboutVersionFragment.getAboutVersionString();
322 // Create an input stream with the contents of about version.
323 InputStream aboutVersionInputStream = new ByteArrayInputStream(aboutVersionString.getBytes(StandardCharsets.UTF_8));
325 // Create an about version buffered reader.
326 BufferedReader aboutVersionBufferedReader = new BufferedReader(new InputStreamReader(aboutVersionInputStream));
328 // Create a file from the file name string.
329 File saveFile = new File(fileNameString);
331 // Delete the file if it already exists.
332 if (saveFile.exists()) {
333 //noinspection ResultOfMethodCallIgnored
337 // Create a file buffered writer.
338 BufferedWriter fileBufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(saveFile)));
340 // Create a transfer string.
341 String transferString;
343 // Use the transfer string to copy the about version text from the buffered reader to the buffered writer.
344 while ((transferString = aboutVersionBufferedReader.readLine()) != null) {
345 // Append the line to the buffered writer.
346 fileBufferedWriter.append(transferString);
348 // Append a line break.
349 fileBufferedWriter.append("\n");
352 // Close the buffered reader and writer.
353 aboutVersionBufferedReader.close();
354 fileBufferedWriter.close();
356 // Add the file to the list of recent files. This doesn't currently work, but maybe it will someday.
357 MediaScannerConnection.scanFile(this, new String[] {fileNameString}, new String[] {"text/plain"}, null);
359 // Create an about version saved snackbar.
360 Snackbar aboutVersionSavedSnackbar = Snackbar.make(aboutVersionLinearLayout, getString(R.string.file_saved) + " " + fileNameString, Snackbar.LENGTH_SHORT);
362 // Add an open option to the snackbar.
363 aboutVersionSavedSnackbar.setAction(R.string.open, (View view) -> {
364 // Get a file for the file name string.
365 File file = new File(fileNameString);
367 // Declare a file URI variable.
370 // Get the URI for the file according to the Android version.
371 if (Build.VERSION.SDK_INT >= 24) { // Use a file provider.
372 fileUri = FileProvider.getUriForFile(this, getString(R.string.file_provider), file);
373 } else { // Get the raw file path URI.
374 fileUri = Uri.fromFile(file);
377 // Get a handle for the content resolver.
378 ContentResolver contentResolver = getContentResolver();
380 // Create an open intent with `ACTION_VIEW`.
381 Intent openIntent = new Intent(Intent.ACTION_VIEW);
383 // Set the URI and the MIME type.
384 openIntent.setDataAndType(fileUri, contentResolver.getType(fileUri));
386 // Allow the app to read the file URI.
387 openIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
390 startActivity(Intent.createChooser(openIntent, getString(R.string.open)));
393 // Show the about version saved snackbar.
394 aboutVersionSavedSnackbar.show();
395 } catch (Exception exception) {
396 // Display a snackbar with the error message.
397 Snackbar.make(aboutVersionLinearLayout, getString(R.string.error_saving_file) + " " + exception.toString(), Snackbar.LENGTH_INDEFINITE).show();