1 /*
2  * Copyright (C) 2012 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.dialer.dialpad;
18 
19 import android.telephony.PhoneNumberUtils;
20 import android.text.Spanned;
21 import android.text.method.DialerKeyListener;
22 
23 /**
24  * {@link DialerKeyListener} with Unicode support. Converts any Unicode(e.g. Arabic) characters
25  * that represent digits into digits before filtering the results so that we can support
26  * pasted digits from Unicode languages.
27  */
28 public class UnicodeDialerKeyListener extends DialerKeyListener {
29     public static final UnicodeDialerKeyListener INSTANCE = new UnicodeDialerKeyListener();
30 
31     @Override
filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend)32     public CharSequence filter(CharSequence source, int start, int end,
33             Spanned dest, int dstart, int dend) {
34         final String converted = PhoneNumberUtils.convertKeypadLettersToDigits(
35                 PhoneNumberUtils.replaceUnicodeDigits(source.toString()));
36         // PhoneNumberUtils.replaceUnicodeDigits performs a character for character replacement,
37         // so we can assume that start and end positions should remain unchanged.
38         CharSequence result = super.filter(converted, start, end, dest, dstart, dend);
39         if (result == null) {
40             if (source.equals(converted)) {
41                 // There was no conversion or filtering performed. Just return null according to
42                 // the behavior of DialerKeyListener.
43                 return null;
44             } else {
45                 // filter returns null if the charsequence is to be returned unchanged/unfiltered.
46                 // But in this case we do want to return a modified character string (even if
47                 // none of the characters in the modified string are filtered). So if
48                 // result == null we return the unfiltered but converted numeric string instead.
49                 return converted.subSequence(start, end);
50             }
51         }
52         return result;
53     }
54 }
55