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