]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/AddDomainDialog.java
Don't allow duplicate domains to be created in domain settings. Implements https...
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / AddDomainDialog.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.net.Uri;
28 import android.os.Bundle;
29 // We have to use `AppCompatDialogFragment` instead of `DialogFragment` or an error is produced on API <= 22.
30 import android.support.annotation.NonNull;
31 import android.support.v7.app.AppCompatDialogFragment;
32 import android.text.Editable;
33 import android.text.TextWatcher;
34 import android.view.KeyEvent;
35 import android.view.View;
36 import android.view.WindowManager;
37 import android.widget.Button;
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 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
44
45 public class AddDomainDialog extends AppCompatDialogFragment {
46     // The public interface is used to send information back to the parent activity.
47     public interface AddDomainListener {
48         void onAddDomain(AppCompatDialogFragment dialogFragment);
49     }
50
51     // `addDomainListener` is used in `onAttach()` and `onCreateDialog()`.
52     private AddDomainListener addDomainListener;
53
54
55     public void onAttach(Context context) {
56         super.onAttach(context);
57
58         // Get a handle for `AddDomainListener` from `context`.
59         try {
60             addDomainListener = (AddDomainListener) context;
61         } catch(ClassCastException exception) {
62             throw new ClassCastException(context.toString() + " must implement `AddDomainListener`.");
63         }
64     }
65
66     // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
67     @SuppressLint("InflateParams")
68     @Override
69     @NonNull
70     public Dialog onCreateDialog(Bundle savedInstanceState) {
71         // Use `AlertDialog.Builder` to create the `AlertDialog`.
72         AlertDialog.Builder dialogBuilder;
73
74         // Set the style according to the theme.
75         if (MainWebViewActivity.darkTheme) {
76             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
77         } else {
78             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
79         }
80
81         // Set the title.
82         dialogBuilder.setTitle(R.string.add_domain);
83
84         // Set the view.  The parent view is `null` because it will be assigned by the `AlertDialog`.
85         dialogBuilder.setView(getActivity().getLayoutInflater().inflate(R.layout.add_domain_dialog, null));
86
87         // Set an `onClick()` listener for the negative button.
88         dialogBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
89             @Override
90             public void onClick(DialogInterface dialog, int which) {
91                 // Do nothing.  The `AlertDialog` will close automatically.
92             }
93         });
94
95         // Set an `onClick()` listener for the positive button.
96         dialogBuilder.setPositiveButton(R.string.add, new DialogInterface.OnClickListener() {
97             @Override
98             public void onClick(DialogInterface dialog, int which) {
99                 // Return the `DialogFragment` to the parent activity on add.
100                 addDomainListener.onAddDomain(AddDomainDialog.this);
101             }
102         });
103
104         // Create an `AlertDialog` from the `AlertDialog.Builder`.
105         final AlertDialog alertDialog = dialogBuilder.create();
106
107         // Remove the warning below the `setSoftInputMode` might produce `java.lang.NullPointerException`.
108         assert alertDialog.getWindow() != null;
109
110         // Show the keyboard when the `AlertDialog` is displayed on the screen.
111         alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
112
113         // The `AlertDialog` must be shown before the contents can be edited.
114         alertDialog.show();
115
116         // Initialize `domainsDatabaseHelper`.  The two `nulls` do not specify the database name or a `CursorFactory`.  The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
117         final DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(getContext(), null, null, 0);
118
119         // Get handles for the views in `alertDialog`.
120         final EditText addDomainEditText = (EditText) alertDialog.findViewById(R.id.domain_name_edittext);
121         final TextView domainNameAlreadyExistsTextView = (TextView) alertDialog.findViewById(R.id.domain_name_already_exists_textview);
122         final Button addButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
123
124         //  Update the status of the warning text and the `add` button.
125         addDomainEditText.addTextChangedListener(new TextWatcher() {
126             @Override
127             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
128                 // Do nothing.
129             }
130
131             @Override
132             public void onTextChanged(CharSequence s, int start, int before, int count) {
133                 // Do nothing.
134             }
135
136             @Override
137             public void afterTextChanged(Editable s) {
138                 if (domainsDatabaseHelper.getCursorForDomainName(addDomainEditText.getText().toString()).getCount() >0) {  // The domain already exists.
139                     // Show the warning text.
140                     domainNameAlreadyExistsTextView.setVisibility(View.VISIBLE);
141
142                     // Disable the `add` button.
143                     addButton.setEnabled(false);
144                 } else {  // The domain do not yet exist.
145                     // Hide the warning text.
146                     domainNameAlreadyExistsTextView.setVisibility(View.GONE);
147
148                     // Enable the `add` button.
149                     addButton.setEnabled(true);
150                 }
151             }
152         });
153
154         // Get the current domain from `formattedUrlString`.
155         Uri currentUri = Uri.parse(MainWebViewActivity.formattedUrlString);
156         addDomainEditText.setText(currentUri.getHost());
157
158         // Allow the `enter` key on the keyboard to create the domain from `add_domain_edittext`.
159         addDomainEditText.setOnKeyListener(new View.OnKeyListener() {
160             public boolean onKey(View view, int keyCode, KeyEvent event) {
161                 // If the event is a key-down on the `enter` key, select the `PositiveButton` `Add`.
162                 if ((keyCode == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN)) {
163                     // Trigger `addDomainListener` and return the `DialogFragment` to the parent activity.
164                     addDomainListener.onAddDomain(AddDomainDialog.this);
165                     // Manually dismiss the `AlertDialog`.
166                     alertDialog.dismiss();
167                     // Consume the event.
168                     return true;
169                 } else { // If any other key was pressed, do not consume the event.
170                     return false;
171                 }
172             }
173         });
174
175         // `onCreateDialog()` requires the return of an `AlertDialog`.
176         return alertDialog;
177     }
178 }