]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/OpenDialog.java
Add a warning if a file will be overwritten. https://redmine.stoutner.com/issues/371
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / OpenDialog.java
1 /*
2  * Copyright © 2019-2020 Soren Stoutner <soren@stoutner.com>.
3  *
4  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 package com.stoutner.privacybrowser.dialogs;
21
22 import android.Manifest;
23 import android.annotation.SuppressLint;
24 import android.app.Activity;
25 import android.app.AlertDialog;
26 import android.app.Dialog;
27 import android.content.Context;
28 import android.content.DialogInterface;
29 import android.content.Intent;
30 import android.content.SharedPreferences;
31 import android.content.pm.PackageManager;
32 import android.os.Build;
33 import android.os.Bundle;
34 import android.os.Environment;
35 import android.provider.DocumentsContract;
36 import android.text.Editable;
37 import android.text.TextWatcher;
38 import android.view.View;
39 import android.view.WindowManager;
40 import android.widget.Button;
41 import android.widget.EditText;
42 import android.widget.TextView;
43
44 import androidx.annotation.NonNull;
45 import androidx.core.content.ContextCompat;
46 import androidx.fragment.app.DialogFragment;
47 import androidx.preference.PreferenceManager;
48
49 import com.stoutner.privacybrowser.R;
50 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
51
52 import java.io.File;
53
54 public class OpenDialog extends DialogFragment {
55     // Define the open listener.
56     private OpenListener openListener;
57
58     // The public interface is used to send information back to the parent activity.
59     public interface OpenListener {
60         void onOpen(DialogFragment dialogFragment);
61     }
62
63     @Override
64     public void onAttach(@NonNull Context context) {
65         // Run the default commands.
66         super.onAttach(context);
67
68         // Get a handle for the open listener from the launching context.
69         openListener = (OpenListener) context;
70     }
71
72     // `@SuppressLint("InflateParams")` removes the warning about using null as the parent view group when inflating the alert dialog.
73     @SuppressLint("InflateParams")
74     @Override
75     @NonNull
76     public Dialog onCreateDialog(Bundle savedInstanceState) {
77         // Get a handle for the activity and the context.
78         Activity activity = getActivity();
79         Context context = getContext();
80
81         // Remove the incorrect lint warnings below that the activity and the context might be null.
82         assert activity != null;
83         assert context != null;
84
85         // Get a handle for the shared preferences.
86         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
87
88         // Get the screenshot and theme preferences.
89         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
90         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
91
92         // Use an alert dialog builder to create the alert dialog.
93         AlertDialog.Builder dialogBuilder;
94
95         // Set the style and icon according to the theme.
96         if (darkTheme) {
97             // Set the style.
98             dialogBuilder = new AlertDialog.Builder(activity, R.style.PrivacyBrowserAlertDialogDark);
99
100             // Set the icon.
101             dialogBuilder.setIcon(R.drawable.proxy_enabled_dark);
102         } else {
103             // Set the style.
104             dialogBuilder = new AlertDialog.Builder(activity, R.style.PrivacyBrowserAlertDialogLight);
105
106             // Set the icon.
107             dialogBuilder.setIcon(R.drawable.proxy_enabled_light);
108         }
109
110         // Set the title.
111         dialogBuilder.setTitle(R.string.open);
112
113         // Set the view.  The parent view is null because it will be assigned by the alert dialog.
114         dialogBuilder.setView(activity.getLayoutInflater().inflate(R.layout.open_dialog, null));
115
116         // Set the cancel button listener.  Using `null` as the listener closes the dialog without doing anything else.
117         dialogBuilder.setNegativeButton(R.string.cancel, null);
118
119         // Set the open button listener.
120         dialogBuilder.setPositiveButton(R.string.open, (DialogInterface dialog, int which) -> {
121             // Return the dialog fragment to the parent activity.
122             openListener.onOpen(this);
123         });
124
125         // Create an alert dialog from the builder.
126         AlertDialog alertDialog = dialogBuilder.create();
127
128         // Remove the incorrect lint warning below that the window might be null.
129         assert alertDialog.getWindow() != null;
130
131         // Disable screenshots if not allowed.
132         if (!allowScreenshots) {
133             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
134         }
135
136         // The alert dialog must be shown before items in the layout can be modified.
137         alertDialog.show();
138
139         // Get handles for the layout items.
140         EditText fileNameEditText = alertDialog.findViewById(R.id.file_name_edittext);
141         Button browseButton = alertDialog.findViewById(R.id.browse_button);
142         TextView fileDoesNotExistTextView = alertDialog.findViewById(R.id.file_does_not_exist_textview);
143         TextView storagePermissionTextView = alertDialog.findViewById(R.id.storage_permission_textview);
144         Button openButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
145
146         // Create a string for the default file path.
147         String defaultFilePath;
148
149         // Update the status of the open button when the file name changes.
150         fileNameEditText.addTextChangedListener(new TextWatcher() {
151             @Override
152             public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
153                 // Do nothing.
154             }
155
156             @Override
157             public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
158                 // Do nothing.
159             }
160
161             @Override
162             public void afterTextChanged(Editable editable) {
163                 // Get the current file name.
164                 String fileNameString = fileNameEditText.getText().toString();
165
166                 // Convert the file name string to a file.
167                 File file = new File(fileNameString);
168
169                 // Check to see if the file exists.
170                 if (file.exists()) {  // The file exists.
171                     // Hide the notification that the file does not exist.
172                     fileDoesNotExistTextView.setVisibility(View.GONE);
173
174                     // Enable the open button.
175                     openButton.setEnabled(true);
176                 } else {  // The file does not exist.
177                     // Show the notification that the file does not exist.
178                     fileDoesNotExistTextView.setVisibility(View.VISIBLE);
179
180                     // Disable the open button.
181                     openButton.setEnabled(false);
182                 }
183             }
184         });
185
186         // Set the default file path according to the storage permission state.
187         if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {  // The storage permission has been granted.
188             // Set the default file path to use the external public directory.
189             defaultFilePath = Environment.getExternalStorageDirectory() + "/";
190
191             // Hide the storage permission text view.
192             storagePermissionTextView.setVisibility(View.GONE);
193         } else {  // The storage permission has not been granted.
194             // Set the default file path to use the external private directory.
195             defaultFilePath = context.getExternalFilesDir(null) + "/";
196         }
197
198         // Display the default file path.
199         fileNameEditText.setText(defaultFilePath);
200
201         // Move the cursor to the end of the default file path.
202         fileNameEditText.setSelection(defaultFilePath.length());
203
204         // Handle clicks on the browse button.
205         browseButton.setOnClickListener((View view) -> {
206             // Create the file picker intent.
207             Intent browseIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
208
209             // Set the intent MIME type to include all files so that everything is visible.
210             browseIntent.setType("*/*");
211
212             // Set the initial directory if the minimum API >= 26.
213             if (Build.VERSION.SDK_INT >= 26) {
214                 browseIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
215             }
216
217             // Start the file picker.  This must be started under `activity` to that the request code is returned correctly.
218             activity.startActivityForResult(browseIntent, MainWebViewActivity.BROWSE_OPEN_REQUEST_CODE);
219         });
220
221         // Return the alert dialog.
222         return alertDialog;
223     }
224 }