]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/AddDomainDialog.java
87c336df1956dca016923a11ead759f0dbf337a9
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / AddDomainDialog.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.net.Uri;
29 import android.os.Bundle;
30 import android.preference.PreferenceManager;
31 import android.text.Editable;
32 import android.text.TextWatcher;
33 import android.view.KeyEvent;
34 import android.view.View;
35 import android.view.WindowManager;
36 import android.widget.Button;
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 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
45
46 public class AddDomainDialog extends DialogFragment {
47     // The public interface is used to send information back to the parent activity.
48     public interface AddDomainListener {
49         void onAddDomain(DialogFragment dialogFragment);
50     }
51
52     // The add domain listener is used in `onAttach()` and `onCreateDialog()`.
53     private AddDomainListener addDomainListener;
54
55     @Override
56     public void onAttach(@NonNull Context context) {
57         // Run the default commands.
58         super.onAttach(context);
59
60         // Get a handle for the listener from the launching context.
61         addDomainListener = (AddDomainListener) context;
62     }
63
64     public static AddDomainDialog addDomain(String url) {
65         // Create an arguments bundle.
66         Bundle argumentsBundle = new Bundle();
67
68         // Store the URL in the bundle.
69         argumentsBundle.putString("url", url);
70
71         // Create a new instance of the dialog.
72         AddDomainDialog addDomainDialog = new AddDomainDialog();
73
74         // Add the bundle to the dialog.
75         addDomainDialog.setArguments(argumentsBundle);
76
77         // Return the new dialog.
78         return addDomainDialog;
79     }
80
81     // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
82     @SuppressLint("InflateParams")
83     @Override
84     @NonNull
85     public Dialog onCreateDialog(Bundle savedInstanceState) {
86         // Get the arguments.
87         Bundle arguments = getArguments();
88
89         // Remove the incorrect lint warning below that the arguments might be null.
90         assert arguments != null;
91
92         // Get the URL from the bundle.
93         String url = arguments.getString("url");
94
95         // Use an alert dialog builder to create the alert dialog.
96         AlertDialog.Builder dialogBuilder;
97
98         // Get a handle for the shared preferences.
99         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
100
101         // Get the screenshot and theme preferences.
102         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
103         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
104
105         // Set the style according to the theme.
106         if (darkTheme) {
107             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
108         } else {
109             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
110         }
111
112         // Set the title.
113         dialogBuilder.setTitle(R.string.add_domain);
114
115         // Remove the incorrect lint warning below that `getActivity()` might be null.
116         assert getActivity() != null;
117
118         // Set the view.  The parent view is `null` because it will be assigned by the alert dialog.
119         dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.add_domain_dialog, null));
120
121         // Set a listener for the negative button.
122         dialogBuilder.setNegativeButton(R.string.cancel, (DialogInterface dialog, int which) -> {
123             // Do nothing.  The alert dialog will close automatically.
124         });
125
126         // Set a listener for the positive button.
127         dialogBuilder.setPositiveButton(R.string.add, (DialogInterface dialog, int which) -> {
128             // Return the dialog fragment to the parent activity on add.
129             addDomainListener.onAddDomain(this);
130         });
131
132         // Create an alert dialog from the builder.
133         final AlertDialog alertDialog = dialogBuilder.create();
134
135         // Remove the warning below that `getWindow()` might be null.
136         assert alertDialog.getWindow() != null;
137
138         // Disable screenshots if not allowed.
139         if (!allowScreenshots) {
140             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
141         }
142
143         // Show the keyboard when the alert dialog is displayed on the screen.
144         alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
145
146         // The alert dialog must be shown before the contents can be edited.
147         alertDialog.show();
148
149         // Initialize `domainsDatabaseHelper`.  The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
150         final DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(getContext(), null, null, 0);
151
152         // Get handles for the views in the alert dialog.
153         final EditText addDomainEditText = alertDialog.findViewById(R.id.domain_name_edittext);
154         final TextView domainNameAlreadyExistsTextView = alertDialog.findViewById(R.id.domain_name_already_exists_textview);
155         final Button addButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
156
157         //  Update the status of the warning text and the add button.
158         addDomainEditText.addTextChangedListener(new TextWatcher() {
159             @Override
160             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
161                 // Do nothing.
162             }
163
164             @Override
165             public void onTextChanged(CharSequence s, int start, int before, int count) {
166                 // Do nothing.
167             }
168
169             @Override
170             public void afterTextChanged(Editable s) {
171                 if (domainsDatabaseHelper.getCursorForDomainName(addDomainEditText.getText().toString()).getCount() >0) {  // The domain already exists.
172                     // Show the warning text.
173                     domainNameAlreadyExistsTextView.setVisibility(View.VISIBLE);
174
175                     // Disable the add button.
176                     addButton.setEnabled(false);
177                 } else {  // The domain do not yet exist.
178                     // Hide the warning text.
179                     domainNameAlreadyExistsTextView.setVisibility(View.GONE);
180
181                     // Enable the add button.
182                     addButton.setEnabled(true);
183                 }
184             }
185         });
186
187         // Convert the URL to a URI.
188         Uri currentUri = Uri.parse(url);
189
190         // Display the host in the add domain edit text.
191         addDomainEditText.setText(currentUri.getHost());
192
193         // Allow the enter key on the keyboard to create the domain from the add domain edit text.
194         addDomainEditText.setOnKeyListener((View view, int keyCode, KeyEvent event) -> {
195             // If the event is a key-down on the enter key, select the `PositiveButton` `Add`.
196             if ((keyCode == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN)) {
197                 // Trigger `addDomainListener` and return the dialog fragment to the parent activity.
198                 addDomainListener.onAddDomain(this);
199
200                 // Manually dismiss the alert dialog.
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         // Return the alert dialog.
211         return alertDialog;
212     }
213 }