1 /*
2  * Copyright (C) 2006 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 android.text.method;
18 
19 import android.text.AutoText;
20 import android.text.Editable;
21 import android.text.NoCopySpan;
22 import android.text.Selection;
23 import android.text.Spannable;
24 import android.text.TextUtils;
25 import android.text.method.TextKeyListener.Capitalize;
26 import android.util.SparseArray;
27 import android.view.KeyCharacterMap;
28 import android.view.KeyEvent;
29 import android.view.View;
30 
31 /**
32  * This is the standard key listener for alphabetic input on qwerty
33  * keyboards.  You should generally not need to instantiate this yourself;
34  * TextKeyListener will do it for you.
35  * <p></p>
36  * As for all implementations of {@link KeyListener}, this class is only concerned
37  * with hardware keyboards.  Software input methods have no obligation to trigger
38  * the methods in this class.
39  */
40 public class QwertyKeyListener extends BaseKeyListener {
41     private static QwertyKeyListener[] sInstance =
42         new QwertyKeyListener[Capitalize.values().length * 2];
43     private static QwertyKeyListener sFullKeyboardInstance;
44 
45     private Capitalize mAutoCap;
46     private boolean mAutoText;
47     private boolean mFullKeyboard;
48 
QwertyKeyListener(Capitalize cap, boolean autoText, boolean fullKeyboard)49     private QwertyKeyListener(Capitalize cap, boolean autoText, boolean fullKeyboard) {
50         mAutoCap = cap;
51         mAutoText = autoText;
52         mFullKeyboard = fullKeyboard;
53     }
54 
QwertyKeyListener(Capitalize cap, boolean autoText)55     public QwertyKeyListener(Capitalize cap, boolean autoText) {
56         this(cap, autoText, false);
57     }
58 
59     /**
60      * Returns a new or existing instance with the specified capitalization
61      * and correction properties.
62      */
getInstance(boolean autoText, Capitalize cap)63     public static QwertyKeyListener getInstance(boolean autoText, Capitalize cap) {
64         int off = cap.ordinal() * 2 + (autoText ? 1 : 0);
65 
66         if (sInstance[off] == null) {
67             sInstance[off] = new QwertyKeyListener(cap, autoText);
68         }
69 
70         return sInstance[off];
71     }
72 
73     /**
74      * Gets an instance of the listener suitable for use with full keyboards.
75      * Disables auto-capitalization, auto-text and long-press initiated on-screen
76      * character pickers.
77      */
getInstanceForFullKeyboard()78     public static QwertyKeyListener getInstanceForFullKeyboard() {
79         if (sFullKeyboardInstance == null) {
80             sFullKeyboardInstance = new QwertyKeyListener(Capitalize.NONE, false, true);
81         }
82         return sFullKeyboardInstance;
83     }
84 
getInputType()85     public int getInputType() {
86         return makeTextContentType(mAutoCap, mAutoText);
87     }
88 
onKeyDown(View view, Editable content, int keyCode, KeyEvent event)89     public boolean onKeyDown(View view, Editable content,
90                              int keyCode, KeyEvent event) {
91         int selStart, selEnd;
92         int pref = 0;
93 
94         if (view != null) {
95             pref = TextKeyListener.getInstance().getPrefs(view.getContext());
96         }
97 
98         {
99             int a = Selection.getSelectionStart(content);
100             int b = Selection.getSelectionEnd(content);
101 
102             selStart = Math.min(a, b);
103             selEnd = Math.max(a, b);
104 
105             if (selStart < 0 || selEnd < 0) {
106                 selStart = selEnd = 0;
107                 Selection.setSelection(content, 0, 0);
108             }
109         }
110 
111         int activeStart = content.getSpanStart(TextKeyListener.ACTIVE);
112         int activeEnd = content.getSpanEnd(TextKeyListener.ACTIVE);
113 
114         // QWERTY keyboard normal case
115 
116         int i = event.getUnicodeChar(getMetaState(content, event));
117 
118         if (!mFullKeyboard) {
119             int count = event.getRepeatCount();
120             if (count > 0 && selStart == selEnd && selStart > 0) {
121                 char c = content.charAt(selStart - 1);
122 
123                 if ((c == i || c == Character.toUpperCase(i)) && view != null) {
124                     if (showCharacterPicker(view, content, c, false, count)) {
125                         resetMetaState(content);
126                         return true;
127                     }
128                 }
129             }
130         }
131 
132         if (i == KeyCharacterMap.PICKER_DIALOG_INPUT) {
133             if (view != null) {
134                 showCharacterPicker(view, content,
135                                     KeyCharacterMap.PICKER_DIALOG_INPUT, true, 1);
136             }
137             resetMetaState(content);
138             return true;
139         }
140 
141         if (i == KeyCharacterMap.HEX_INPUT) {
142             int start;
143 
144             if (selStart == selEnd) {
145                 start = selEnd;
146 
147                 while (start > 0 && selEnd - start < 4 &&
148                        Character.digit(content.charAt(start - 1), 16) >= 0) {
149                     start--;
150                 }
151             } else {
152                 start = selStart;
153             }
154 
155             int ch = -1;
156             try {
157                 String hex = TextUtils.substring(content, start, selEnd);
158                 ch = Integer.parseInt(hex, 16);
159             } catch (NumberFormatException nfe) { }
160 
161             if (ch >= 0) {
162                 selStart = start;
163                 Selection.setSelection(content, selStart, selEnd);
164                 i = ch;
165             } else {
166                 i = 0;
167             }
168         }
169 
170         if (i != 0) {
171             boolean dead = false;
172 
173             if ((i & KeyCharacterMap.COMBINING_ACCENT) != 0) {
174                 dead = true;
175                 i = i & KeyCharacterMap.COMBINING_ACCENT_MASK;
176             }
177 
178             if (activeStart == selStart && activeEnd == selEnd) {
179                 boolean replace = false;
180 
181                 if (selEnd - selStart - 1 == 0) {
182                     char accent = content.charAt(selStart);
183                     int composed = event.getDeadChar(accent, i);
184 
185                     // Prevent a dead key repetition from inserting
186                     if (i == composed && event.getRepeatCount() > 0) {
187                         return true;
188                     }
189 
190                     if (composed != 0) {
191                         i = composed;
192                         replace = true;
193                         dead = false;
194                     }
195                 }
196 
197                 if (!replace) {
198                     Selection.setSelection(content, selEnd);
199                     content.removeSpan(TextKeyListener.ACTIVE);
200                     selStart = selEnd;
201                 }
202             }
203 
204             if ((pref & TextKeyListener.AUTO_CAP) != 0
205                     && Character.isLowerCase(i)
206                     && TextKeyListener.shouldCap(mAutoCap, content, selStart)) {
207                 int where = content.getSpanEnd(TextKeyListener.CAPPED);
208                 int flags = content.getSpanFlags(TextKeyListener.CAPPED);
209 
210                 if (where == selStart && (((flags >> 16) & 0xFFFF) == i)) {
211                     content.removeSpan(TextKeyListener.CAPPED);
212                 } else {
213                     flags = i << 16;
214                     i = Character.toUpperCase(i);
215 
216                     if (selStart == 0)
217                         content.setSpan(TextKeyListener.CAPPED, 0, 0,
218                                         Spannable.SPAN_MARK_MARK | flags);
219                     else
220                         content.setSpan(TextKeyListener.CAPPED,
221                                         selStart - 1, selStart,
222                                         Spannable.SPAN_EXCLUSIVE_EXCLUSIVE |
223                                         flags);
224                 }
225             }
226 
227             if (selStart != selEnd) {
228                 Selection.setSelection(content, selEnd);
229             }
230             content.setSpan(OLD_SEL_START, selStart, selStart,
231                             Spannable.SPAN_MARK_MARK);
232 
233             content.replace(selStart, selEnd, String.valueOf((char) i));
234 
235             int oldStart = content.getSpanStart(OLD_SEL_START);
236             selEnd = Selection.getSelectionEnd(content);
237 
238             if (oldStart < selEnd) {
239                 content.setSpan(TextKeyListener.LAST_TYPED,
240                                 oldStart, selEnd,
241                                 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
242 
243                 if (dead) {
244                     Selection.setSelection(content, oldStart, selEnd);
245                     content.setSpan(TextKeyListener.ACTIVE, oldStart, selEnd,
246                         Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
247                 }
248             }
249 
250             adjustMetaAfterKeypress(content);
251 
252             // potentially do autotext replacement if the character
253             // that was typed was an autotext terminator
254 
255             if ((pref & TextKeyListener.AUTO_TEXT) != 0 && mAutoText &&
256                 (i == ' ' || i == '\t' || i == '\n' ||
257                  i == ',' || i == '.' || i == '!' || i == '?' ||
258                  i == '"' || Character.getType(i) == Character.END_PUNCTUATION) &&
259                  content.getSpanEnd(TextKeyListener.INHIBIT_REPLACEMENT)
260                      != oldStart) {
261                 int x;
262 
263                 for (x = oldStart; x > 0; x--) {
264                     char c = content.charAt(x - 1);
265                     if (c != '\'' && !Character.isLetter(c)) {
266                         break;
267                     }
268                 }
269 
270                 String rep = getReplacement(content, x, oldStart, view);
271 
272                 if (rep != null) {
273                     Replaced[] repl = content.getSpans(0, content.length(),
274                                                      Replaced.class);
275                     for (int a = 0; a < repl.length; a++)
276                         content.removeSpan(repl[a]);
277 
278                     char[] orig = new char[oldStart - x];
279                     TextUtils.getChars(content, x, oldStart, orig, 0);
280 
281                     content.setSpan(new Replaced(orig), x, oldStart,
282                                     Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
283                     content.replace(x, oldStart, rep);
284                 }
285             }
286 
287             // Replace two spaces by a period and a space.
288 
289             if ((pref & TextKeyListener.AUTO_PERIOD) != 0 && mAutoText) {
290                 selEnd = Selection.getSelectionEnd(content);
291                 if (selEnd - 3 >= 0) {
292                     if (content.charAt(selEnd - 1) == ' ' &&
293                         content.charAt(selEnd - 2) == ' ') {
294                         char c = content.charAt(selEnd - 3);
295 
296                         for (int j = selEnd - 3; j > 0; j--) {
297                             if (c == '"' ||
298                                 Character.getType(c) == Character.END_PUNCTUATION) {
299                                 c = content.charAt(j - 1);
300                             } else {
301                                 break;
302                             }
303                         }
304 
305                         if (Character.isLetter(c) || Character.isDigit(c)) {
306                             content.replace(selEnd - 2, selEnd - 1, ".");
307                         }
308                     }
309                 }
310             }
311 
312             return true;
313         } else if (keyCode == KeyEvent.KEYCODE_DEL
314                 && (event.hasNoModifiers() || event.hasModifiers(KeyEvent.META_ALT_ON))
315                 && selStart == selEnd) {
316             // special backspace case for undoing autotext
317 
318             int consider = 1;
319 
320             // if backspacing over the last typed character,
321             // it undoes the autotext prior to that character
322             // (unless the character typed was newline, in which
323             // case this behavior would be confusing)
324 
325             if (content.getSpanEnd(TextKeyListener.LAST_TYPED) == selStart) {
326                 if (content.charAt(selStart - 1) != '\n')
327                     consider = 2;
328             }
329 
330             Replaced[] repl = content.getSpans(selStart - consider, selStart,
331                                              Replaced.class);
332 
333             if (repl.length > 0) {
334                 int st = content.getSpanStart(repl[0]);
335                 int en = content.getSpanEnd(repl[0]);
336                 String old = new String(repl[0].mText);
337 
338                 content.removeSpan(repl[0]);
339 
340                 // only cancel the autocomplete if the cursor is at the end of
341                 // the replaced span (or after it, because the user is
342                 // backspacing over the space after the word, not the word
343                 // itself).
344                 if (selStart >= en) {
345                     content.setSpan(TextKeyListener.INHIBIT_REPLACEMENT,
346                                     en, en, Spannable.SPAN_POINT_POINT);
347                     content.replace(st, en, old);
348 
349                     en = content.getSpanStart(TextKeyListener.INHIBIT_REPLACEMENT);
350                     if (en - 1 >= 0) {
351                         content.setSpan(TextKeyListener.INHIBIT_REPLACEMENT,
352                                         en - 1, en,
353                                         Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
354                     } else {
355                         content.removeSpan(TextKeyListener.INHIBIT_REPLACEMENT);
356                     }
357                     adjustMetaAfterKeypress(content);
358                 } else {
359                     adjustMetaAfterKeypress(content);
360                     return super.onKeyDown(view, content, keyCode, event);
361                 }
362 
363                 return true;
364             }
365         } else if (keyCode == KeyEvent.KEYCODE_ESCAPE && event.hasNoModifiers()) {
366             // If user is in the process of composing with a dead key, and
367             // presses Escape, cancel it. We need special handling because
368             // the Escape key will not produce a Unicode character
369             if (activeStart == selStart && activeEnd == selEnd) {
370                 Selection.setSelection(content, selEnd);
371                 content.removeSpan(TextKeyListener.ACTIVE);
372                 return true;
373             }
374         }
375 
376         return super.onKeyDown(view, content, keyCode, event);
377     }
378 
getReplacement(CharSequence src, int start, int end, View view)379     private String getReplacement(CharSequence src, int start, int end,
380                                   View view) {
381         int len = end - start;
382         boolean changecase = false;
383 
384         String replacement = AutoText.get(src, start, end, view);
385 
386         if (replacement == null) {
387             String key = TextUtils.substring(src, start, end).toLowerCase();
388             replacement = AutoText.get(key, 0, end - start, view);
389             changecase = true;
390 
391             if (replacement == null)
392                 return null;
393         }
394 
395         int caps = 0;
396 
397         if (changecase) {
398             for (int j = start; j < end; j++) {
399                 if (Character.isUpperCase(src.charAt(j)))
400                     caps++;
401             }
402         }
403 
404         String out;
405 
406         if (caps == 0)
407             out = replacement;
408         else if (caps == 1)
409             out = toTitleCase(replacement);
410         else if (caps == len)
411             out = replacement.toUpperCase();
412         else
413             out = toTitleCase(replacement);
414 
415         if (out.length() == len &&
416             TextUtils.regionMatches(src, start, out, 0, len))
417             return null;
418 
419         return out;
420     }
421 
422     /**
423      * Marks the specified region of <code>content</code> as having
424      * contained <code>original</code> prior to AutoText replacement.
425      * Call this method when you have done or are about to do an
426      * AutoText-style replacement on a region of text and want to let
427      * the same mechanism (the user pressing DEL immediately after the
428      * change) undo the replacement.
429      *
430      * @param content the Editable text where the replacement was made
431      * @param start the start of the replaced region
432      * @param end the end of the replaced region; the location of the cursor
433      * @param original the text to be restored if the user presses DEL
434      */
markAsReplaced(Spannable content, int start, int end, String original)435     public static void markAsReplaced(Spannable content, int start, int end,
436                                       String original) {
437         Replaced[] repl = content.getSpans(0, content.length(), Replaced.class);
438         for (int a = 0; a < repl.length; a++) {
439             content.removeSpan(repl[a]);
440         }
441 
442         int len = original.length();
443         char[] orig = new char[len];
444         original.getChars(0, len, orig, 0);
445 
446         content.setSpan(new Replaced(orig), start, end,
447                         Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
448     }
449 
450     private static SparseArray<String> PICKER_SETS =
451                         new SparseArray<String>();
452     static {
453         PICKER_SETS.put('A', "\u00C0\u00C1\u00C2\u00C4\u00C6\u00C3\u00C5\u0104\u0100");
454         PICKER_SETS.put('C', "\u00C7\u0106\u010C");
455         PICKER_SETS.put('D', "\u010E");
456         PICKER_SETS.put('E', "\u00C8\u00C9\u00CA\u00CB\u0118\u011A\u0112");
457         PICKER_SETS.put('G', "\u011E");
458         PICKER_SETS.put('L', "\u0141");
459         PICKER_SETS.put('I', "\u00CC\u00CD\u00CE\u00CF\u012A\u0130");
460         PICKER_SETS.put('N', "\u00D1\u0143\u0147");
461         PICKER_SETS.put('O', "\u00D8\u0152\u00D5\u00D2\u00D3\u00D4\u00D6\u014C");
462         PICKER_SETS.put('R', "\u0158");
463         PICKER_SETS.put('S', "\u015A\u0160\u015E");
464         PICKER_SETS.put('T', "\u0164");
465         PICKER_SETS.put('U', "\u00D9\u00DA\u00DB\u00DC\u016E\u016A");
466         PICKER_SETS.put('Y', "\u00DD\u0178");
467         PICKER_SETS.put('Z', "\u0179\u017B\u017D");
468         PICKER_SETS.put('a', "\u00E0\u00E1\u00E2\u00E4\u00E6\u00E3\u00E5\u0105\u0101");
469         PICKER_SETS.put('c', "\u00E7\u0107\u010D");
470         PICKER_SETS.put('d', "\u010F");
471         PICKER_SETS.put('e', "\u00E8\u00E9\u00EA\u00EB\u0119\u011B\u0113");
472         PICKER_SETS.put('g', "\u011F");
473         PICKER_SETS.put('i', "\u00EC\u00ED\u00EE\u00EF\u012B\u0131");
474         PICKER_SETS.put('l', "\u0142");
475         PICKER_SETS.put('n', "\u00F1\u0144\u0148");
476         PICKER_SETS.put('o', "\u00F8\u0153\u00F5\u00F2\u00F3\u00F4\u00F6\u014D");
477         PICKER_SETS.put('r', "\u0159");
478         PICKER_SETS.put('s', "\u00A7\u00DF\u015B\u0161\u015F");
479         PICKER_SETS.put('t', "\u0165");
480         PICKER_SETS.put('u', "\u00F9\u00FA\u00FB\u00FC\u016F\u016B");
481         PICKER_SETS.put('y', "\u00FD\u00FF");
482         PICKER_SETS.put('z', "\u017A\u017C\u017E");
PICKER_SETS.put(KeyCharacterMap.PICKER_DIALOG_INPUT, R)483         PICKER_SETS.put(KeyCharacterMap.PICKER_DIALOG_INPUT,
484                              "\u2026\u00A5\u2022\u00AE\u00A9\u00B1[]{}\\|");
485         PICKER_SETS.put('/', "\\");
486 
487         // From packages/inputmethods/LatinIME/res/xml/kbd_symbols.xml
488 
489         PICKER_SETS.put('1', "\u00b9\u00bd\u2153\u00bc\u215b");
490         PICKER_SETS.put('2', "\u00b2\u2154");
491         PICKER_SETS.put('3', "\u00b3\u00be\u215c");
492         PICKER_SETS.put('4', "\u2074");
493         PICKER_SETS.put('5', "\u215d");
494         PICKER_SETS.put('7', "\u215e");
495         PICKER_SETS.put('0', "\u207f\u2205");
496         PICKER_SETS.put('$', "\u00a2\u00a3\u20ac\u00a5\u20a3\u20a4\u20b1");
497         PICKER_SETS.put('%', "\u2030");
498         PICKER_SETS.put('*', "\u2020\u2021");
499         PICKER_SETS.put('-', "\u2013\u2014");
500         PICKER_SETS.put('+', "\u00b1");
501         PICKER_SETS.put('(', "[{<");
502         PICKER_SETS.put(')', "]}>");
503         PICKER_SETS.put('!', "\u00a1");
504         PICKER_SETS.put('"', "\u201c\u201d\u00ab\u00bb\u02dd");
505         PICKER_SETS.put('?', "\u00bf");
506         PICKER_SETS.put(',', "\u201a\u201e");
507 
508         // From packages/inputmethods/LatinIME/res/xml/kbd_symbols_shift.xml
509 
510         PICKER_SETS.put('=', "\u2260\u2248\u221e");
511         PICKER_SETS.put('<', "\u2264\u00ab\u2039");
512         PICKER_SETS.put('>', "\u2265\u00bb\u203a");
513     };
514 
showCharacterPicker(View view, Editable content, char c, boolean insert, int count)515     private boolean showCharacterPicker(View view, Editable content, char c,
516                                         boolean insert, int count) {
517         String set = PICKER_SETS.get(c);
518         if (set == null) {
519             return false;
520         }
521 
522         if (count == 1) {
523             new CharacterPickerDialog(view.getContext(),
524                                       view, content, set, insert).show();
525         }
526 
527         return true;
528     }
529 
toTitleCase(String src)530     private static String toTitleCase(String src) {
531         return Character.toUpperCase(src.charAt(0)) + src.substring(1);
532     }
533 
534     /* package */ static class Replaced implements NoCopySpan
535     {
Replaced(char[] text)536         public Replaced(char[] text) {
537             mText = text;
538         }
539 
540         private char[] mText;
541     }
542 }
543 
544