]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/HttpAuthenticationDialog.java
Enable HTTP authentication. Implements https://redmine.stoutner.com/issues/52.
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / HttpAuthenticationDialog.java
1 /*
2  * Copyright © 2017 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.Context;
26 import android.content.DialogInterface;
27 import android.os.Bundle;
28 import android.support.annotation.NonNull;
29 // `AppCompatDialogFragment` is used instead of `DialogFragment` to avoid an error on API <=22.
30 import android.support.v7.app.AppCompatDialogFragment;
31 import android.text.SpannableStringBuilder;
32 import android.text.Spanned;
33 import android.text.style.ForegroundColorSpan;
34 import android.view.KeyEvent;
35 import android.view.LayoutInflater;
36 import android.view.View;
37 import android.view.WindowManager;
38 import android.widget.EditText;
39 import android.widget.TextView;
40
41 import com.stoutner.privacybrowser.R;
42 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
43
44 public class HttpAuthenticationDialog extends AppCompatDialogFragment{
45
46     // The private variables are used in `onCreate()` and `onCreateDialog()`.
47     private String httpAuthHost;
48     private String httpAuthRealm;
49
50     public static HttpAuthenticationDialog displayDialog(String host, String realm) {
51         // Store the strings in a `Bundle`.
52         Bundle argumentsBundle = new Bundle();
53         argumentsBundle.putString("Host", host);
54         argumentsBundle.putString("Realm", realm);
55
56         // Add `argumentsBundle` to this instance of `HttpAuthenticationDialog`.
57         HttpAuthenticationDialog thisHttpAuthenticationDialog = new HttpAuthenticationDialog();
58         thisHttpAuthenticationDialog.setArguments(argumentsBundle);
59         return thisHttpAuthenticationDialog;
60     }
61
62     @Override
63     public void onCreate(Bundle savedInstanceState) {
64         super.onCreate(savedInstanceState);
65
66         // Save the host and realm in class variables.
67         httpAuthHost = getArguments().getString("Host");
68         httpAuthRealm = getArguments().getString("Realm");
69     }
70
71     // The public interface is used to send information back to the parent activity.
72     public interface HttpAuthenticationListener {
73         void onHttpAuthenticationCancel();
74
75         void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment);
76     }
77
78     // `httpAuthenticationListener` is used in `onAttach()` and `onCreateDialog()`
79     private HttpAuthenticationListener httpAuthenticationListener;
80
81     public void onAttach(Context context) {
82         super.onAttach(context);
83
84         // Get a handle for `httpAuthenticationListener` from `context`.
85         try {
86             httpAuthenticationListener = (HttpAuthenticationListener) context;
87         } catch(ClassCastException exception) {
88             throw new ClassCastException(context.toString() + " must implement `HttpAuthenticationListener`.");
89         }
90     }
91
92     // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
93     @SuppressLint("InflateParams")
94     @Override
95     @NonNull
96     public Dialog onCreateDialog(Bundle savedInstanceState) {
97         // Get the activity's layout inflater.
98         LayoutInflater layoutInflater = getActivity().getLayoutInflater();
99
100         // Use `AlertDialog.Builder` to create the `AlertDialog`.
101         AlertDialog.Builder dialogBuilder;
102
103         // Set the style according to the theme.
104         if (MainWebViewActivity.darkTheme) {
105             // Set the dialog theme.
106             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
107
108             // Set the icon.
109             dialogBuilder.setIcon(R.drawable.lock_dark);
110         } else {
111             // Set the dialog theme.
112             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
113
114             // Set the icon.
115             dialogBuilder.setIcon(R.drawable.lock_light);
116         }
117
118         // Set the title.
119         dialogBuilder.setTitle(R.string.http_authentication);
120
121         // Set the layout.  The parent view is `null` because it will be assigned by `AlertDialog`.
122         dialogBuilder.setView(layoutInflater.inflate(R.layout.http_authentication_dialog, null));
123
124         // Setup the negative button.
125         dialogBuilder.setNegativeButton(R.string.close, new DialogInterface.OnClickListener() {
126             @Override
127             public void onClick(DialogInterface dialog, int which) {
128                 // Call `onHttpAuthenticationCancel()` and return the `DialogFragment` to the parent activity.
129                 httpAuthenticationListener.onHttpAuthenticationCancel();
130             }
131         });
132
133         // Setup the positive button.
134         dialogBuilder.setPositiveButton(R.string.proceed, new DialogInterface.OnClickListener() {
135             @Override
136             public void onClick(DialogInterface dialog, int which) {
137                 // Call `onHttpAuthenticationProceed()` and return the `DialogFragment` to the parent activity.
138                 httpAuthenticationListener.onHttpAuthenticationProceed(HttpAuthenticationDialog.this);
139             }
140         });
141
142         // Create an `AlertDialog` from the `AlertDialog.Builder`.
143         final AlertDialog alertDialog = dialogBuilder.create();
144
145         // Remove the warning below that `setSoftInputMode` might produce `java.lang.NullPointerException`.
146         assert alertDialog.getWindow() != null;
147
148         // Show the keyboard when the `AlertDialog` is displayed on the screen.
149         alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
150
151         // The `AlertDialog` needs to be shown before `setOnKeyListener()` can be called.
152         alertDialog.show();
153
154         // Get handles for the views in `alertDialog`.
155         TextView realmTextView = (TextView) alertDialog.findViewById(R.id.http_authentication_realm);
156         TextView hostTextView = (TextView) alertDialog.findViewById(R.id.http_authentication_host);
157         EditText usernameEditText = (EditText) alertDialog.findViewById(R.id.http_authentication_username);
158         EditText passwordEditText = (EditText) alertDialog.findViewById(R.id.http_authentication_password);
159
160         // Set the realm text.
161         realmTextView.setText(httpAuthRealm);
162
163         // Set the realm text color according to the theme.  The deprecated `.getColor()` must be used until API >= 23.
164         if (MainWebViewActivity.darkTheme) {
165             //noinspection deprecation
166             realmTextView.setTextColor(getResources().getColor(R.color.gray_300));
167         } else {
168             //noinspection deprecation
169             realmTextView.setTextColor(getResources().getColor(R.color.black));
170         }
171
172         // Initialize the host label and the `SpannableStringBuilder`.
173         String hostLabel = getString(R.string.host) + "  ";
174         SpannableStringBuilder hostStringBuilder = new SpannableStringBuilder(hostLabel + httpAuthHost);
175
176         // Create a blue `ForegroundColorSpan`.
177         ForegroundColorSpan blueColorSpan;
178
179         // Set `blueColorSpan` according to the theme.  The deprecated `getColor()` must be used until API >= 23.
180         if (MainWebViewActivity.darkTheme) {
181             //noinspection deprecation
182             blueColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.blue_400));
183         } else {
184             //noinspection deprecation
185             blueColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.blue_700));
186         }
187
188         // Setup the span to display the host name in blue.  `SPAN_INCLUSIVE_INCLUSIVE` allows the span to grow in either direction.
189         hostStringBuilder.setSpan(blueColorSpan, hostLabel.length(), hostStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
190
191         // Set the host text.
192         hostTextView.setText(hostStringBuilder);
193
194         // Allow the `enter` key on the keyboard to trigger `onHttpAuthenticationProceed` from `usernameEditText`.
195         usernameEditText.setOnKeyListener(new View.OnKeyListener() {
196             public boolean onKey(View view, int keyCode, KeyEvent event) {
197                 // If the event is a key-down on the `enter` key, call `onHttpAuthenticationProceed()`.
198                 if ((keyCode == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN)) {
199                     // Trigger `onHttpAuthenticationProceed` and return the `DialogFragment` to the parent activity.
200                     httpAuthenticationListener.onHttpAuthenticationProceed(HttpAuthenticationDialog.this);
201
202                     // Manually dismiss the `AlertDialog`.
203                     alertDialog.dismiss();
204
205                     // Consume the event.
206                     return true;
207                 } else {  // If any other key was pressed, do not consume the event.
208                     return false;
209                 }
210             }
211         });
212
213         // Allow the `enter` key on the keyboard to trigger `onHttpAuthenticationProceed()` from `passwordEditText`.
214         passwordEditText.setOnKeyListener(new View.OnKeyListener() {
215             public boolean onKey(View view, int keyCode, KeyEvent event) {
216                 // If the event is a key-down on the `enter` key, call `onHttpAuthenticationProceed()`.
217                 if ((keyCode == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN)) {
218                     // Trigger `onHttpAuthenticationProceed` and return the `DialogFragment` to the parent activity.
219                     httpAuthenticationListener.onHttpAuthenticationProceed(HttpAuthenticationDialog.this);
220
221                     // Manually dismiss the `AlertDialog`.
222                     alertDialog.dismiss();
223
224                     // Consume the event.
225                     return true;
226                 } else {  // If any other key was pressed, do not consume the event.
227                     return false;
228                 }
229             }
230         });
231
232         // `onCreateDialog()` requires the return of an `AlertDialog`.
233         return alertDialog;
234     }
235 }