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