]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/HttpAuthenticationDialog.java
4b68108987b22d62484d5ac0627c882c4832869a
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / HttpAuthenticationDialog.java
1 /*
2  * Copyright © 2017-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.annotation.SuppressLint;
23 import android.app.AlertDialog;
24 import android.app.Dialog;
25 import android.content.DialogInterface;
26 import android.content.SharedPreferences;
27 import android.os.Bundle;
28 import android.preference.PreferenceManager;
29 import android.text.SpannableStringBuilder;
30 import android.text.Spanned;
31 import android.text.style.ForegroundColorSpan;
32 import android.view.KeyEvent;
33 import android.view.LayoutInflater;
34 import android.view.View;
35 import android.view.Window;
36 import android.view.WindowManager;
37 import android.webkit.HttpAuthHandler;
38 import android.widget.EditText;
39 import android.widget.TextView;
40
41 import androidx.annotation.NonNull;
42 import androidx.fragment.app.DialogFragment;  // The AndroidX dialog fragment must be used or an error is produced on API <=22.
43
44 import com.stoutner.privacybrowser.R;
45 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
46 import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
47 import com.stoutner.privacybrowser.views.NestedScrollWebView;
48
49 public class HttpAuthenticationDialog extends DialogFragment{
50     // Define the class variables.
51     private EditText usernameEditText;
52     private EditText passwordEditText;
53
54     public static HttpAuthenticationDialog displayDialog(String host, String realm, long webViewFragmentId) {
55         // Create an arguments bundle.
56         Bundle argumentsBundle = new Bundle();
57
58         // Store the variables in the bundle.
59         argumentsBundle.putString("host", host);
60         argumentsBundle.putString("realm", realm);
61         argumentsBundle.putLong("webview_fragment_id", webViewFragmentId);
62
63         // Create a new instance of the HTTP authentication dialog.
64         HttpAuthenticationDialog thisHttpAuthenticationDialog = new HttpAuthenticationDialog();
65
66         // Add the arguments bundle to the new dialog.
67         thisHttpAuthenticationDialog.setArguments(argumentsBundle);
68
69         // Return the new dialog.
70         return thisHttpAuthenticationDialog;
71     }
72
73     // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
74     @SuppressLint("InflateParams")
75     @Override
76     @NonNull
77     public Dialog onCreateDialog(Bundle savedInstanceState) {
78         // Get a handle for the arguments.
79         Bundle arguments = getArguments();
80
81         // Remove the incorrect lint warning below that arguments might be null.
82         assert arguments != null;
83
84         // Get the variables from the bundle.
85         String httpAuthHost = arguments.getString("host");
86         String httpAuthRealm = arguments.getString("realm");
87         long webViewFragmentId = arguments.getLong("webview_fragment_id");
88
89         // Get the current position of this WebView fragment.
90         int webViewPosition = MainWebViewActivity.webViewPagerAdapter.getPositionForId(webViewFragmentId);
91
92         // Get the WebView tab fragment.
93         WebViewTabFragment webViewTabFragment = MainWebViewActivity.webViewPagerAdapter.getPageFragment(webViewPosition);
94
95         // Get the fragment view.
96         View fragmentView = webViewTabFragment.getView();
97
98         // Remove the incorrect lint warning below that the fragment view might be null.
99         assert fragmentView != null;
100
101         // Get a handle for the current WebView.
102         NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
103
104         // Get a handle for the HTTP authentication handler.
105         HttpAuthHandler httpAuthHandler = nestedScrollWebView.getHttpAuthHandler();
106
107         // Remove the incorrect lint warning that `getActivity()` might be null.
108         assert getActivity() != null;
109
110         // Get the activity's layout inflater.
111         LayoutInflater layoutInflater = getActivity().getLayoutInflater();
112
113         // Use an alert dialog builder to create the alert dialog.
114         AlertDialog.Builder dialogBuilder;
115
116         // Get a handle for the shared preferences.
117         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
118
119         // Get the screenshot and theme preferences.
120         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
121         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
122
123         // Set the style according to the theme.
124         if (darkTheme) {
125             // Set the dialog theme.
126             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
127
128             // Set the icon.
129             dialogBuilder.setIcon(R.drawable.lock_dark);
130         } else {
131             // Set the dialog theme.
132             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
133
134             // Set the icon.
135             dialogBuilder.setIcon(R.drawable.lock_light);
136         }
137
138         // Set the title.
139         dialogBuilder.setTitle(R.string.http_authentication);
140
141         // Set the layout.  The parent view is `null` because it will be assigned by `AlertDialog`.
142         dialogBuilder.setView(layoutInflater.inflate(R.layout.http_authentication_dialog, null));
143
144         // Setup the close button.
145         dialogBuilder.setNegativeButton(R.string.close, (DialogInterface dialog, int which) -> {
146             // Cancel the HTTP authentication request.
147             httpAuthHandler.cancel();
148
149             // Reset the HTTP authentication handler.
150             nestedScrollWebView.resetHttpAuthHandler();
151         });
152
153         // Setup the proceed button.
154         dialogBuilder.setPositiveButton(R.string.proceed, (DialogInterface dialog, int which) -> {
155             // Send the login information
156             login(httpAuthHandler);
157
158             // Reset the HTTP authentication handler.
159             nestedScrollWebView.resetHttpAuthHandler();
160         });
161
162         // Create an alert dialog from the alert dialog builder.
163         final AlertDialog alertDialog = dialogBuilder.create();
164
165         // Get the alert dialog window.
166         Window dialogWindow = alertDialog.getWindow();
167
168         // Remove the incorrect lint warning below that the dialog window might be null.
169         assert dialogWindow != null;
170
171         // Disable screenshots if not allowed.
172         if (!allowScreenshots) {
173             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
174         }
175
176         // Display the keyboard.
177         dialogWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
178
179         // The alert dialog needs to be shown before the contents can be modified.
180         alertDialog.show();
181
182         // Get handles for the views.
183         TextView realmTextView = alertDialog.findViewById(R.id.http_authentication_realm);
184         TextView hostTextView = alertDialog.findViewById(R.id.http_authentication_host);
185         usernameEditText = alertDialog.findViewById(R.id.http_authentication_username);
186         passwordEditText = alertDialog.findViewById(R.id.http_authentication_password);
187
188         // Set the realm text.
189         realmTextView.setText(httpAuthRealm);
190
191         // Set the realm text color according to the theme.  The deprecated `.getColor()` must be used until API >= 23.
192         if (darkTheme) {
193             realmTextView.setTextColor(getResources().getColor(R.color.gray_300));
194         } else {
195             realmTextView.setTextColor(getResources().getColor(R.color.black));
196         }
197
198         // Initialize the host label and the `SpannableStringBuilder`.
199         String hostLabel = getString(R.string.host) + "  ";
200         SpannableStringBuilder hostStringBuilder = new SpannableStringBuilder(hostLabel + httpAuthHost);
201
202         // Create a blue `ForegroundColorSpan`.
203         ForegroundColorSpan blueColorSpan;
204
205         // Set `blueColorSpan` according to the theme.  The deprecated `getColor()` must be used until API >= 23.
206         if (darkTheme) {
207             blueColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.blue_400));
208         } else {
209             blueColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.blue_700));
210         }
211
212         // Setup the span to display the host name in blue.  `SPAN_INCLUSIVE_INCLUSIVE` allows the span to grow in either direction.
213         hostStringBuilder.setSpan(blueColorSpan, hostLabel.length(), hostStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
214
215         // Set the host text.
216         hostTextView.setText(hostStringBuilder);
217
218         // Allow the `enter` key on the keyboard to trigger `onHttpAuthenticationProceed` from `usernameEditText`.
219         usernameEditText.setOnKeyListener((View view, int keyCode, KeyEvent event) -> {
220             // If the event is a key-down on the `enter` key, call `onHttpAuthenticationProceed()`.
221             if ((keyCode == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN)) {
222                 // Send the login information.
223                 login(httpAuthHandler);
224
225                 // Manually dismiss the alert dialog.
226                 alertDialog.dismiss();
227
228                 // Consume the event.
229                 return true;
230             } else {  // If any other key was pressed, do not consume the event.
231                 return false;
232             }
233         });
234
235         // Allow the `enter` key on the keyboard to trigger `onHttpAuthenticationProceed()` from `passwordEditText`.
236         passwordEditText.setOnKeyListener((View view, int keyCode, KeyEvent event) -> {
237             // If the event is a key-down on the `enter` key, call `onHttpAuthenticationProceed()`.
238             if ((keyCode == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN)) {
239                 // Send the login information.
240                 login(httpAuthHandler);
241
242                 // Manually dismiss the alert dialog.
243                 alertDialog.dismiss();
244
245                 // Consume the event.
246                 return true;
247             } else {  // If any other key was pressed, do not consume the event.
248                 return false;
249             }
250         });
251
252         // Return the alert dialog.
253         return alertDialog;
254     }
255
256     private void login(HttpAuthHandler httpAuthHandler) {
257         // Send the login information.
258         httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
259     }
260 }