]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/HttpAuthenticationDialog.java
Make first-party cookies tab aware.
[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.Context;
26 import android.content.DialogInterface;
27 import android.content.SharedPreferences;
28 import android.os.Bundle;
29 import android.preference.PreferenceManager;
30 import android.text.SpannableStringBuilder;
31 import android.text.Spanned;
32 import android.text.style.ForegroundColorSpan;
33 import android.view.KeyEvent;
34 import android.view.LayoutInflater;
35 import android.view.View;
36 import android.view.WindowManager;
37 import android.widget.EditText;
38 import android.widget.TextView;
39
40 import androidx.annotation.NonNull;
41 import androidx.fragment.app.DialogFragment;  // The AndroidX dialog fragment must be used or an error is produced on API <=22.
42
43 import com.stoutner.privacybrowser.R;
44
45 public class HttpAuthenticationDialog extends DialogFragment{
46     // `httpAuthenticationListener` is used in `onAttach()` and `onCreateDialog()`
47     private HttpAuthenticationListener httpAuthenticationListener;
48
49     // The public interface is used to send information back to the parent activity.
50     public interface HttpAuthenticationListener {
51         void onHttpAuthenticationCancel();
52
53         void onHttpAuthenticationProceed(DialogFragment dialogFragment);
54     }
55
56     public void onAttach(Context context) {
57         super.onAttach(context);
58
59         // Get a handle for `httpAuthenticationListener` from `context`.
60         httpAuthenticationListener = (HttpAuthenticationListener) context;
61     }
62
63     public static HttpAuthenticationDialog displayDialog(String host, String realm) {
64         // Store the strings in a `Bundle`.
65         Bundle argumentsBundle = new Bundle();
66         argumentsBundle.putString("Host", host);
67         argumentsBundle.putString("Realm", realm);
68
69         // Add `argumentsBundle` to this instance of `HttpAuthenticationDialog`.
70         HttpAuthenticationDialog thisHttpAuthenticationDialog = new HttpAuthenticationDialog();
71         thisHttpAuthenticationDialog.setArguments(argumentsBundle);
72         return thisHttpAuthenticationDialog;
73     }
74
75     // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
76     @SuppressLint("InflateParams")
77     @Override
78     @NonNull
79     public Dialog onCreateDialog(Bundle savedInstanceState) {
80         // Remove the incorrect lint warnings that `getString()` might be null.
81         assert getArguments() != null;
82
83         // Get the host and realm variables from the bundle.
84         String httpAuthHost = getArguments().getString("Host");
85         String httpAuthRealm = getArguments().getString("Realm");
86
87         // Remove the incorrect lint warning that `getActivity()` might be null.
88         assert getActivity() != null;
89
90         // Get the activity's layout inflater.
91         LayoutInflater layoutInflater = getActivity().getLayoutInflater();
92
93         // Use an alert dialog builder to create the alert dialog.
94         AlertDialog.Builder dialogBuilder;
95
96         // Get a handle for the shared preferences.
97         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
98
99         // Get the screenshot and theme preferences.
100         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
101         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
102
103         // Set the style according to the theme.
104         if (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, (DialogInterface dialog, int which) -> {
126             // Call `onHttpAuthenticationCancel()` and return the `DialogFragment` to the parent activity.
127             httpAuthenticationListener.onHttpAuthenticationCancel();
128         });
129
130         // Setup the positive button.
131         dialogBuilder.setPositiveButton(R.string.proceed, (DialogInterface dialog, int which) -> {
132             // Call `onHttpAuthenticationProceed()` and return the `DialogFragment` to the parent activity.
133             httpAuthenticationListener.onHttpAuthenticationProceed(HttpAuthenticationDialog.this);
134         });
135
136         // Create an alert dialog from the alert dialog builder.
137         final AlertDialog alertDialog = dialogBuilder.create();
138
139         // Remove the warning below that `getWindow()` might be null.
140         assert alertDialog.getWindow() != null;
141
142         // Disable screenshots if not allowed.
143         if (!allowScreenshots) {
144             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
145         }
146
147         // Show the keyboard when the `AlertDialog` is displayed on the screen.
148         alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
149
150         // The alert dialog needs to be shown before the contents can be modified.
151         alertDialog.show();
152
153         // Get handles for the views in `alertDialog`.
154         TextView realmTextView = alertDialog.findViewById(R.id.http_authentication_realm);
155         TextView hostTextView = alertDialog.findViewById(R.id.http_authentication_host);
156         EditText usernameEditText = alertDialog.findViewById(R.id.http_authentication_username);
157         EditText passwordEditText = alertDialog.findViewById(R.id.http_authentication_password);
158
159         // Set the realm text.
160         realmTextView.setText(httpAuthRealm);
161
162         // Set the realm text color according to the theme.  The deprecated `.getColor()` must be used until API >= 23.
163         if (darkTheme) {
164             //noinspection deprecation
165             realmTextView.setTextColor(getResources().getColor(R.color.gray_300));
166         } else {
167             //noinspection deprecation
168             realmTextView.setTextColor(getResources().getColor(R.color.black));
169         }
170
171         // Initialize the host label and the `SpannableStringBuilder`.
172         String hostLabel = getString(R.string.host) + "  ";
173         SpannableStringBuilder hostStringBuilder = new SpannableStringBuilder(hostLabel + httpAuthHost);
174
175         // Create a blue `ForegroundColorSpan`.
176         ForegroundColorSpan blueColorSpan;
177
178         // Set `blueColorSpan` according to the theme.  The deprecated `getColor()` must be used until API >= 23.
179         if (darkTheme) {
180             //noinspection deprecation
181             blueColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.blue_400));
182         } else {
183             //noinspection deprecation
184             blueColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.blue_700));
185         }
186
187         // Setup the span to display the host name in blue.  `SPAN_INCLUSIVE_INCLUSIVE` allows the span to grow in either direction.
188         hostStringBuilder.setSpan(blueColorSpan, hostLabel.length(), hostStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
189
190         // Set the host text.
191         hostTextView.setText(hostStringBuilder);
192
193         // Allow the `enter` key on the keyboard to trigger `onHttpAuthenticationProceed` from `usernameEditText`.
194         usernameEditText.setOnKeyListener((View view, int keyCode, KeyEvent event) -> {
195             // If the event is a key-down on the `enter` key, call `onHttpAuthenticationProceed()`.
196             if ((keyCode == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN)) {
197                 // Trigger `onHttpAuthenticationProceed` and return the `DialogFragment` to the parent activity.
198                 httpAuthenticationListener.onHttpAuthenticationProceed(HttpAuthenticationDialog.this);
199
200                 // Manually dismiss the `AlertDialog`.
201                 alertDialog.dismiss();
202
203                 // Consume the event.
204                 return true;
205             } else {  // If any other key was pressed, do not consume the event.
206                 return false;
207             }
208         });
209
210         // Allow the `enter` key on the keyboard to trigger `onHttpAuthenticationProceed()` from `passwordEditText`.
211         passwordEditText.setOnKeyListener((View view, int keyCode, KeyEvent event) -> {
212             // If the event is a key-down on the `enter` key, call `onHttpAuthenticationProceed()`.
213             if ((keyCode == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN)) {
214                 // Trigger `onHttpAuthenticationProceed` and return the `DialogFragment` to the parent activity.
215                 httpAuthenticationListener.onHttpAuthenticationProceed(HttpAuthenticationDialog.this);
216
217                 // Manually dismiss the `AlertDialog`.
218                 alertDialog.dismiss();
219
220                 // Consume the event.
221                 return true;
222             } else {  // If any other key was pressed, do not consume the event.
223                 return false;
224             }
225         });
226
227         // `onCreateDialog()` requires the return of an `AlertDialog`.
228         return alertDialog;
229     }
230 }