summaryrefslogtreecommitdiffstats
path: root/src/com/android/settings/blacklist/EntryEditDialogFragment.java
blob: 11c9909e344025887eb0883675872d575cdbb358 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.settings.blacklist;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds;
import android.provider.Telephony.Blacklist;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.ArrowKeyMovementMethod;
import android.text.method.DialerKeyListener;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;

import android.widget.Spinner;
import android.widget.Toast;
import com.android.internal.telephony.util.BlacklistUtils;
import com.android.settings.R;
import com.google.i18n.phonenumbers.PhoneNumberUtil;

import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;

public class EntryEditDialogFragment extends DialogFragment
    implements TextWatcher, DialogInterface.OnClickListener {

    private EditText mEditText;
    private ImageButton mContactPickButton;
    private CheckBox mBlockCalls;
    private CheckBox mBlockMessages;
    private Button mOkButton;
    private Spinner mCountryCode;

    private static final String[] BLACKLIST_PROJECTION = {
        Blacklist.NUMBER, Blacklist.PHONE_MODE, Blacklist.MESSAGE_MODE
    };
    private static final String[] NUMBER_PROJECTION = {
        CommonDataKinds.Phone.NUMBER
    };
    private static final int COLUMN_NUMBER = 0;
    private static final int COLUMN_PHONE = 1;
    private static final int COLUMN_MESSAGE = 2;

    private static final int REQUEST_CODE_PICKER = 1;

    private static final String DIALOG_STATE = "blacklist_edit_state";
    private static final String STATE_NUMBER = "number";
    private static final String STATE_PHONE = "phone";
    private static final String STATE_MESSAGE = "message";
    private static final String STATE_EDIT_ENABLED = "edit_enabled";
    private static final String STATE_COUNTRY_CODE = "edit_country_code";

    private static final String DELETE_CONFIRM_FRAGMENT_TAG = "delete_confirm";

    public static EntryEditDialogFragment newInstance(long id) {
        Bundle args = new Bundle();
        args.putLong("id", id);

        EntryEditDialogFragment fragment = new EntryEditDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public EntryEditDialogFragment() {
        super();
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        long id = getEntryId();
        Bundle dialogState = savedInstanceState != null
                ? savedInstanceState.getBundle(DIALOG_STATE) : null;

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
                .setTitle(R.string.blacklist_edit_dialog_title)
                .setPositiveButton(android.R.string.ok, this)
                .setNegativeButton(android.R.string.cancel, null)
                .setView(createDialogView(id, dialogState));

        if (id >= 0) {
            builder.setNeutralButton(R.string.blacklist_button_delete, this);
        }

        return builder.create();
    }

    @Override
    public void onStart() {
        super.onStart();

        AlertDialog dialog = (AlertDialog) getDialog();
        Button neutralButton = dialog.getButton(DialogInterface.BUTTON_NEUTRAL);
        neutralButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager fragMan = getChildFragmentManager();
                if (fragMan.findFragmentByTag(DELETE_CONFIRM_FRAGMENT_TAG) == null) {
                    DeleteConfirmationFragment.newInstance()
                            .show(fragMan, DELETE_CONFIRM_FRAGMENT_TAG);
                }
            }
        });

        updateOkButtonState();
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        if (which == DialogInterface.BUTTON_POSITIVE) {
            updateBlacklistEntry();
        }
    }

    private void onDeleteConfirmResult(boolean confirmed) {
        if (confirmed) {
            Uri uri = ContentUris.withAppendedId(Blacklist.CONTENT_URI, getEntryId());
            getActivity().getContentResolver().delete(uri, null, null);
            dismiss();
        }
    }

    private long getEntryId() {
        return getArguments().getLong("id", -1);
    }

    private static String getLocaleCountry() {
        final String country = Locale.getDefault().getCountry();
        if (TextUtils.isEmpty(country)) {
            return null;
        }
        return country.toUpperCase();
    }

    private void populateCountryCodes(View view, Bundle savedState) {
        PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
        // Get all supported country codes
        Set<String> countryCodes = new HashSet<String>();
        for (String region : phoneUtil.getSupportedRegions()) {
            countryCodes.add(String.valueOf(phoneUtil.getCountryCodeForRegion(region)));
        }
        List<String> entries = new ArrayList<String>(countryCodes);
        Collections.sort(entries, new Comparator<String>() {
            @Override
            public int compare(String lhs, String rhs) {
                return Integer.parseInt(lhs) - Integer.parseInt(rhs);
            }
        });

        // If regex is supported, insert regex character
        if (BlacklistUtils.isBlacklistRegexEnabled(getContext())) {
            entries.add(0, "*");
        }

        // Set current country code as selected position
        int selectedIndex = 0;
        if (savedState == null) {
            String country = getLocaleCountry();
            int currentCode = phoneUtil.getCountryCodeForRegion(country);
            selectedIndex = entries.indexOf(String.valueOf(currentCode));
        } else {
            selectedIndex = savedState.getInt(STATE_COUNTRY_CODE);
        }

        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getContext(),
                android.R.layout.simple_spinner_item, entries);
        arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mCountryCode.setAdapter(arrayAdapter);
        mCountryCode.setSelection(selectedIndex);

        // Ensure we make the layout visible
        View parent = view.findViewById(R.id.country_code_layout);
        parent.setVisibility(View.VISIBLE);
    }

    private View createDialogView(long id, Bundle savedState) {
        final Activity activity = getActivity();
        final LayoutInflater inflater = (LayoutInflater)
                activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View view = inflater.inflate(R.layout.dialog_blacklist_edit_entry, null);

        mEditText = (EditText) view.findViewById(R.id.number_edit);
        mEditText.setMovementMethod(ArrowKeyMovementMethod.getInstance());
        mEditText.setKeyListener(DialerKeyListener.getInstance());
        mEditText.addTextChangedListener(this);

        mCountryCode = (Spinner) view.findViewById(R.id.number_country_code);

        mContactPickButton = (ImageButton) view.findViewById(R.id.select_contact);
        mContactPickButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent contactListIntent = new Intent(Intent.ACTION_PICK);
                contactListIntent.setType(CommonDataKinds.Phone.CONTENT_TYPE);

                startActivityForResult(contactListIntent, REQUEST_CODE_PICKER, null);
            }
        });

        mBlockCalls = (CheckBox) view.findViewById(R.id.incoming_calls);
        mBlockMessages = (CheckBox) view.findViewById(R.id.incoming_messages);

        if (savedState != null) {
            mEditText.setText(savedState.getCharSequence(STATE_NUMBER));
            mEditText.setEnabled(savedState.getBoolean(STATE_EDIT_ENABLED));
            mBlockCalls.setChecked(savedState.getBoolean(STATE_PHONE));
            mBlockMessages.setChecked(savedState.getBoolean(STATE_MESSAGE));
        } else if (id >= 0) {
            Uri uri = ContentUris.withAppendedId(Blacklist.CONTENT_URI, id);
            Cursor cursor = activity.getContentResolver().query(uri,
                    BLACKLIST_PROJECTION, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                mEditText.setText(cursor.getString(COLUMN_NUMBER));
                mEditText.setEnabled(false);
                mBlockCalls.setChecked(cursor.getInt(COLUMN_PHONE) != 0);
                mBlockMessages.setChecked(cursor.getInt(COLUMN_MESSAGE) != 0);
            } else {
                id = -1;
            }
            if (cursor != null) {
                cursor.close();
            }
        }

        if (id < 0) {
            // defaults
            mEditText.setText("");
            mBlockCalls.setChecked(true);
            mBlockMessages.setChecked(true);
            mEditText.setEnabled(true);
        }

        // Only populate country codes if new entry
        if (id < 0 || savedState != null && mEditText.isEnabled()) {
            populateCountryCodes(view, savedState);
        }

        // Mirror contacts selector to state of editText
        mContactPickButton.setEnabled(mEditText.isEnabled());
        return view;
    }

    private void updateBlacklistEntry() {
        String plusSymbol = getString(R.string.blacklist_country_code_plus);
        String number = plusSymbol + mCountryCode.getSelectedItem()
                + mEditText.getText().toString();
        int flags = 0;
        int valid = BlacklistUtils.BLOCK_CALLS | BlacklistUtils.BLOCK_MESSAGES;
        if (mBlockCalls.isChecked()) {
            flags = flags | BlacklistUtils.BLOCK_CALLS;
        }
        if (mBlockMessages.isChecked()) {
            flags = flags | BlacklistUtils.BLOCK_MESSAGES;
        }
        // Since BlacklistProvider enforces validity for a number to be added
        // we should alert the user if and when it gets rejected
        if (!BlacklistUtils.addOrUpdate(getActivity(), number, flags, valid)) {
            Toast.makeText(getActivity(), getString(R.string.blacklist_bad_number_add),
                    Toast.LENGTH_LONG).show();
        }
    }

    private void updateOkButtonState() {
        if (mOkButton == null) {
            AlertDialog dialog = (AlertDialog) getDialog();
            if (dialog != null) {
                mOkButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
            }
        }

        boolean validInput = false;
        String input = mEditText.getText().toString();
        if (!TextUtils.isEmpty(input)) {
            Pair<String, Boolean> normalizeResult =
                    BlacklistUtils.isValidBlacklistInput(getActivity(), input);
            if (normalizeResult.second) {
                validInput = true;
            }
        }

        if (!validInput && !TextUtils.isEmpty(input)) {
            mEditText.setError(getString(R.string.wifi_error));
        } else {
            mEditText.setError(null);
        }

        if (mOkButton != null) {
            mOkButton.setEnabled(validInput);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle state) {
        super.onSaveInstanceState(state);

        Bundle dialogState = new Bundle();
        dialogState.putCharSequence(STATE_NUMBER, mEditText.getText());
        dialogState.putBoolean(STATE_PHONE, mBlockCalls.isChecked());
        dialogState.putBoolean(STATE_MESSAGE, mBlockMessages.isChecked());
        dialogState.putBoolean(STATE_EDIT_ENABLED, mEditText.isEnabled());
        dialogState.putInt(STATE_COUNTRY_CODE, mCountryCode.getSelectedItemPosition());
        state.putBundle(DIALOG_STATE, dialogState);
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void afterTextChanged(Editable s) {
        updateOkButtonState();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode != REQUEST_CODE_PICKER) {
            super.onActivityResult(requestCode, resultCode, data);
            return;
        }

        if (resultCode == Activity.RESULT_OK) {
            Cursor cursor = getActivity().getContentResolver().query(data.getData(),
                    NUMBER_PROJECTION, null, null, null);
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    mEditText.setText(cursor.getString(COLUMN_NUMBER));
                }
                cursor.close();
            }
        }
    }

    public static class DeleteConfirmationFragment extends DialogFragment
            implements DialogInterface.OnClickListener {
        public DeleteConfirmationFragment() {
        }

        public static DialogFragment newInstance() {
            return new DeleteConfirmationFragment();
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            AlertDialog dialog = new AlertDialog.Builder(getActivity())
                    .setTitle(R.string.remove_blacklist_number_title)
                    .setMessage(R.string.remove_blacklist_entry)
                    .setPositiveButton(R.string.yes, this)
                    .setNegativeButton(R.string.no, this)
                    .create();

            return dialog;
        }

        @Override
        public void onClick(DialogInterface dialog, int which) {
            EntryEditDialogFragment parent = (EntryEditDialogFragment) getParentFragment();
            parent.onDeleteConfirmResult(which == DialogInterface.BUTTON_POSITIVE);
        }
    }
}