• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2007 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.view;
18 
19 import android.annotation.NonNull;
20 import android.annotation.Nullable;
21 import android.compat.annotation.UnsupportedAppUsage;
22 import android.hardware.input.InputManagerGlobal;
23 import android.os.Build;
24 import android.os.Parcel;
25 import android.os.Parcelable;
26 import android.text.method.MetaKeyKeyListener;
27 import android.util.AndroidRuntimeException;
28 import android.util.SparseIntArray;
29 
30 import com.android.internal.annotations.VisibleForTesting;
31 
32 import java.text.Normalizer;
33 
34 /**
35  * Describes the keys provided by a keyboard device and their associated labels.
36  */
37 public class KeyCharacterMap implements Parcelable {
38     /**
39      * The id of the device's primary built in keyboard is always 0.
40      *
41      * @deprecated This constant should no longer be used because there is no
42      * guarantee that a device has a built-in keyboard that can be used for
43      * typing text.  There might not be a built-in keyboard, the built-in keyboard
44      * might be a {@link #NUMERIC} or {@link #SPECIAL_FUNCTION} keyboard, or there
45      * might be multiple keyboards installed including external keyboards.
46      * When interpreting key presses received from the framework, applications should
47      * use the device id specified in the {@link KeyEvent} received.
48      * When synthesizing key presses for delivery elsewhere or when translating key presses
49      * from unknown keyboards, applications should use the special {@link #VIRTUAL_KEYBOARD}
50      * device id.
51      */
52     @Deprecated
53     public static final int BUILT_IN_KEYBOARD = 0;
54 
55     /**
56      * The id of a generic virtual keyboard with a full layout that can be used to
57      * synthesize key events.  Typically used with {@link #getEvents}.
58      */
59     public static final int VIRTUAL_KEYBOARD = -1;
60 
61     /**
62      * A numeric (12-key) keyboard.
63      * <p>
64      * A numeric keyboard supports text entry using a multi-tap approach.
65      * It may be necessary to tap a key multiple times to generate the desired letter
66      * or symbol.
67      * </p><p>
68      * This type of keyboard is generally designed for thumb typing.
69      * </p>
70      */
71     public static final int NUMERIC = 1;
72 
73     /**
74      * A keyboard with all the letters, but with more than one letter per key.
75      * <p>
76      * This type of keyboard is generally designed for thumb typing.
77      * </p>
78      */
79     public static final int PREDICTIVE = 2;
80 
81     /**
82      * A keyboard with all the letters, and maybe some numbers.
83      * <p>
84      * An alphabetic keyboard supports text entry directly but may have a condensed
85      * layout with a small form factor.  In contrast to a {@link #FULL full keyboard}, some
86      * symbols may only be accessible using special on-screen character pickers.
87      * In addition, to improve typing speed and accuracy, the framework provides
88      * special affordances for alphabetic keyboards such as auto-capitalization
89      * and toggled / locked shift and alt keys.
90      * </p><p>
91      * This type of keyboard is generally designed for thumb typing.
92      * </p>
93      */
94     public static final int ALPHA = 3;
95 
96     /**
97      * A full PC-style keyboard.
98      * <p>
99      * A full keyboard behaves like a PC keyboard.  All symbols are accessed directly
100      * by pressing keys on the keyboard without on-screen support or affordances such
101      * as auto-capitalization.
102      * </p><p>
103      * This type of keyboard is generally designed for full two hand typing.
104      * </p>
105      */
106     public static final int FULL = 4;
107 
108     /**
109      * A keyboard that is only used to control special functions rather than for typing.
110      * <p>
111      * A special function keyboard consists only of non-printing keys such as
112      * HOME and POWER that are not actually used for typing.
113      * </p>
114      */
115     public static final int SPECIAL_FUNCTION = 5;
116 
117     /**
118      * This private-use character is used to trigger Unicode character
119      * input by hex digits.
120      */
121     public static final char HEX_INPUT = '\uEF00';
122 
123     /**
124      * This private-use character is used to bring up a character picker for
125      * miscellaneous symbols.
126      */
127     public static final char PICKER_DIALOG_INPUT = '\uEF01';
128 
129     /**
130      * Modifier keys may be chorded with character keys.
131      *
132      * @see #getModifierBehavior()
133      */
134     public static final int MODIFIER_BEHAVIOR_CHORDED = 0;
135 
136     /**
137      * Modifier keys may be chorded with character keys or they may toggle
138      * into latched or locked states when pressed independently.
139      *
140      * @see #getModifierBehavior()
141      */
142     public static final int MODIFIER_BEHAVIOR_CHORDED_OR_TOGGLED = 1;
143 
144     /*
145      * This bit will be set in the return value of {@link #get(int, int)} if the
146      * key is a "dead key."
147      */
148     public static final int COMBINING_ACCENT = 0x80000000;
149 
150     /**
151      * Mask the return value from {@link #get(int, int)} with this value to get
152      * a printable representation of the accent character of a "dead key."
153      */
154     public static final int COMBINING_ACCENT_MASK = 0x7FFFFFFF;
155 
156     /* Characters used to display placeholders for dead keys. */
157     private static final int ACCENT_ACUTE = '\u00B4';
158     private static final int ACCENT_BREVE = '\u02D8';
159     private static final int ACCENT_CARON = '\u02C7';
160     private static final int ACCENT_CEDILLA = '\u00B8';
161     private static final int ACCENT_CIRCUMFLEX = '\u02C6';
162     private static final int ACCENT_COMMA_ABOVE = '\u1FBD';
163     private static final int ACCENT_COMMA_ABOVE_RIGHT = '\u02BC';
164     private static final int ACCENT_DOT_ABOVE = '\u02D9';
165     private static final int ACCENT_DOT_BELOW = '.'; // approximate
166     private static final int ACCENT_DOUBLE_ACUTE = '\u02DD';
167     private static final int ACCENT_GRAVE = '\u02CB';
168     private static final int ACCENT_HOOK_ABOVE = '\u02C0';
169     private static final int ACCENT_HORN = '\''; // approximate
170     private static final int ACCENT_MACRON = '\u00AF';
171     private static final int ACCENT_MACRON_BELOW = '\u02CD';
172     private static final int ACCENT_OGONEK = '\u02DB';
173     private static final int ACCENT_REVERSED_COMMA_ABOVE = '\u02BD';
174     private static final int ACCENT_RING_ABOVE = '\u02DA';
175     private static final int ACCENT_STROKE = '-'; // approximate
176     private static final int ACCENT_TILDE = '\u02DC';
177     private static final int ACCENT_TURNED_COMMA_ABOVE = '\u02BB';
178     private static final int ACCENT_UMLAUT = '\u00A8';
179     private static final int ACCENT_VERTICAL_LINE_ABOVE = '\u02C8';
180     private static final int ACCENT_VERTICAL_LINE_BELOW = '\u02CC';
181     private static final int ACCENT_APOSTROPHE = '\'';
182     private static final int ACCENT_QUOTATION_MARK = '"';
183 
184     /* Legacy dead key display characters used in previous versions of the API.
185      * We still support these characters by mapping them to their non-legacy version. */
186     private static final int ACCENT_GRAVE_LEGACY = '`';
187     private static final int ACCENT_CIRCUMFLEX_LEGACY = '^';
188     private static final int ACCENT_TILDE_LEGACY = '~';
189 
190     private static final int CHAR_SPACE = ' ';
191 
192     /**
193      * Maps Unicode combining diacritical to display-form dead key.
194      */
195     private static final SparseIntArray sCombiningToAccent = new SparseIntArray();
196     private static final SparseIntArray sAccentToCombining = new SparseIntArray();
197     static {
198         addCombining('\u0300', ACCENT_GRAVE);
199         addCombining('\u0301', ACCENT_ACUTE);
200         addCombining('\u0302', ACCENT_CIRCUMFLEX);
201         addCombining('\u0303', ACCENT_TILDE);
202         addCombining('\u0304', ACCENT_MACRON);
203         addCombining('\u0306', ACCENT_BREVE);
204         addCombining('\u0307', ACCENT_DOT_ABOVE);
205         addCombining('\u0308', ACCENT_UMLAUT);
206         addCombining('\u0309', ACCENT_HOOK_ABOVE);
207         addCombining('\u030A', ACCENT_RING_ABOVE);
208         addCombining('\u030B', ACCENT_DOUBLE_ACUTE);
209         addCombining('\u030C', ACCENT_CARON);
210         //addCombining('\u030F', ACCENT_DOUBLE_GRAVE);
211         //addCombining('\u0310', ACCENT_CANDRABINDU);
212         //addCombining('\u0311', ACCENT_INVERTED_BREVE);
213         addCombining('\u0312', ACCENT_TURNED_COMMA_ABOVE);
214         addCombining('\u0313', ACCENT_COMMA_ABOVE);
215         addCombining('\u0314', ACCENT_REVERSED_COMMA_ABOVE);
216         addCombining('\u0315', ACCENT_COMMA_ABOVE_RIGHT);
217         addCombining('\u031B', ACCENT_HORN);
218         addCombining('\u0323', ACCENT_DOT_BELOW);
219         //addCombining('\u0326', ACCENT_COMMA_BELOW);
220         addCombining('\u0327', ACCENT_CEDILLA);
221         addCombining('\u0328', ACCENT_OGONEK);
222         addCombining('\u0329', ACCENT_VERTICAL_LINE_BELOW);
223         addCombining('\u0331', ACCENT_MACRON_BELOW);
224         addCombining('\u0335', ACCENT_STROKE);
225         //addCombining('\u0342', ACCENT_PERISPOMENI);
226         //addCombining('\u0344', ACCENT_DIALYTIKA_TONOS);
227         //addCombining('\u0345', ACCENT_YPOGEGRAMMENI);
228 
229         // One-way mappings to equivalent preferred accents.
230         sCombiningToAccent.append('\u0340', ACCENT_GRAVE);
231         sCombiningToAccent.append('\u0341', ACCENT_ACUTE);
232         sCombiningToAccent.append('\u0343', ACCENT_COMMA_ABOVE);
233         sCombiningToAccent.append('\u030D', ACCENT_APOSTROPHE);
234         sCombiningToAccent.append('\u030E', ACCENT_QUOTATION_MARK);
235 
236         // One-way legacy mappings to preserve compatibility with older applications.
sAccentToCombining.append(ACCENT_GRAVE_LEGACY, '\\u0300')237         sAccentToCombining.append(ACCENT_GRAVE_LEGACY, '\u0300');
sAccentToCombining.append(ACCENT_CIRCUMFLEX_LEGACY, '\\u0302')238         sAccentToCombining.append(ACCENT_CIRCUMFLEX_LEGACY, '\u0302');
sAccentToCombining.append(ACCENT_TILDE_LEGACY, '\\u0303')239         sAccentToCombining.append(ACCENT_TILDE_LEGACY, '\u0303');
240 
241         // One-way mappings to use the preferred accent
sAccentToCombining.append(ACCENT_APOSTROPHE, '\\u0301')242         sAccentToCombining.append(ACCENT_APOSTROPHE, '\u0301');
sAccentToCombining.append(ACCENT_QUOTATION_MARK, '\\u0308')243         sAccentToCombining.append(ACCENT_QUOTATION_MARK, '\u0308');
244     }
245 
addCombining(int combining, int accent)246     private static void addCombining(int combining, int accent) {
247         sCombiningToAccent.append(combining, accent);
248         sAccentToCombining.append(accent, combining);
249     }
250 
251     /**
252      * Maps combinations of (display-form) combining key and second character
253      * to combined output character.
254      * These mappings are derived from the Unicode NFC tables as needed.
255      */
256     private static final SparseIntArray sDeadKeyCache = new SparseIntArray();
257     private static final StringBuilder sDeadKeyBuilder = new StringBuilder();
258     static {
259         // Non-standard decompositions.
260         // Stroke modifier for Finnish multilingual keyboard and others.
addDeadKey(ACCENT_STROKE, 'D', '\\u0110')261         addDeadKey(ACCENT_STROKE, 'D', '\u0110');
addDeadKey(ACCENT_STROKE, 'G', '\\u01e4')262         addDeadKey(ACCENT_STROKE, 'G', '\u01e4');
addDeadKey(ACCENT_STROKE, 'H', '\\u0126')263         addDeadKey(ACCENT_STROKE, 'H', '\u0126');
addDeadKey(ACCENT_STROKE, 'I', '\\u0197')264         addDeadKey(ACCENT_STROKE, 'I', '\u0197');
addDeadKey(ACCENT_STROKE, 'L', '\\u0141')265         addDeadKey(ACCENT_STROKE, 'L', '\u0141');
addDeadKey(ACCENT_STROKE, 'O', '\\u00d8')266         addDeadKey(ACCENT_STROKE, 'O', '\u00d8');
addDeadKey(ACCENT_STROKE, 'T', '\\u0166')267         addDeadKey(ACCENT_STROKE, 'T', '\u0166');
addDeadKey(ACCENT_STROKE, 'd', '\\u0111')268         addDeadKey(ACCENT_STROKE, 'd', '\u0111');
addDeadKey(ACCENT_STROKE, 'g', '\\u01e5')269         addDeadKey(ACCENT_STROKE, 'g', '\u01e5');
addDeadKey(ACCENT_STROKE, 'h', '\\u0127')270         addDeadKey(ACCENT_STROKE, 'h', '\u0127');
addDeadKey(ACCENT_STROKE, 'i', '\\u0268')271         addDeadKey(ACCENT_STROKE, 'i', '\u0268');
addDeadKey(ACCENT_STROKE, 'l', '\\u0142')272         addDeadKey(ACCENT_STROKE, 'l', '\u0142');
addDeadKey(ACCENT_STROKE, 'o', '\\u00f8')273         addDeadKey(ACCENT_STROKE, 'o', '\u00f8');
addDeadKey(ACCENT_STROKE, 't', '\\u0167')274         addDeadKey(ACCENT_STROKE, 't', '\u0167');
275     }
276 
addDeadKey(int accent, int c, int result)277     private static void addDeadKey(int accent, int c, int result) {
278         final int combining = sAccentToCombining.get(accent);
279         if (combining == 0) {
280             throw new IllegalStateException("Invalid dead key declaration.");
281         }
282         final int combination = (combining << 16) | c;
283         sDeadKeyCache.put(combination, result);
284     }
285 
286     public static final @android.annotation.NonNull Parcelable.Creator<KeyCharacterMap> CREATOR =
287             new Parcelable.Creator<KeyCharacterMap>() {
288         public KeyCharacterMap createFromParcel(Parcel in) {
289             return new KeyCharacterMap(in);
290         }
291         public KeyCharacterMap[] newArray(int size) {
292             return new KeyCharacterMap[size];
293         }
294     };
295 
296     private long mPtr;
297 
nativeReadFromParcel(Parcel in)298     private static native long nativeReadFromParcel(Parcel in);
nativeWriteToParcel(long ptr, Parcel out)299     private static native void nativeWriteToParcel(long ptr, Parcel out);
nativeDispose(long ptr)300     private static native void nativeDispose(long ptr);
301 
nativeGetCharacter(long ptr, int keyCode, int metaState)302     private static native char nativeGetCharacter(long ptr, int keyCode, int metaState);
nativeGetFallbackAction(long ptr, int keyCode, int metaState, FallbackAction outFallbackAction)303     private static native boolean nativeGetFallbackAction(long ptr, int keyCode, int metaState,
304             FallbackAction outFallbackAction);
nativeGetNumber(long ptr, int keyCode)305     private static native char nativeGetNumber(long ptr, int keyCode);
nativeGetMatch(long ptr, int keyCode, char[] chars, int metaState)306     private static native char nativeGetMatch(long ptr, int keyCode, char[] chars, int metaState);
nativeGetDisplayLabel(long ptr, int keyCode)307     private static native char nativeGetDisplayLabel(long ptr, int keyCode);
nativeGetKeyboardType(long ptr)308     private static native int nativeGetKeyboardType(long ptr);
nativeGetEvents(long ptr, char[] chars)309     private static native KeyEvent[] nativeGetEvents(long ptr, char[] chars);
nativeObtainEmptyKeyCharacterMap(int deviceId)310     private static native KeyCharacterMap nativeObtainEmptyKeyCharacterMap(int deviceId);
nativeEquals(long ptr1, long ptr2)311     private static native boolean nativeEquals(long ptr1, long ptr2);
312 
nativeApplyOverlay(long ptr, String layoutDescriptor, String overlay)313     private static native void nativeApplyOverlay(long ptr, String layoutDescriptor,
314             String overlay);
nativeGetMappedKey(long ptr, int scanCode)315     private static native int nativeGetMappedKey(long ptr, int scanCode);
316 
KeyCharacterMap(Parcel in)317     private KeyCharacterMap(Parcel in) {
318         if (in == null) {
319             throw new IllegalArgumentException("parcel must not be null");
320         }
321         mPtr = nativeReadFromParcel(in);
322         if (mPtr == 0) {
323             throw new RuntimeException("Could not read KeyCharacterMap from parcel.");
324         }
325     }
326 
327     // Called from native
328     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
KeyCharacterMap(long ptr)329     private KeyCharacterMap(long ptr) {
330         mPtr = ptr;
331     }
332 
333     @Override
finalize()334     protected void finalize() throws Throwable {
335         if (mPtr != 0) {
336             nativeDispose(mPtr);
337             mPtr = 0;
338         }
339     }
340 
341     /**
342      * Obtain empty key character map
343      * @param deviceId The input device ID
344      * @return The KeyCharacterMap object
345      * @hide
346      */
347     @VisibleForTesting
348     @Nullable
obtainEmptyMap(int deviceId)349     public static KeyCharacterMap obtainEmptyMap(int deviceId) {
350         return nativeObtainEmptyKeyCharacterMap(deviceId);
351     }
352 
353     /**
354      * Loads the key character maps for the keyboard with the specified device id.
355      *
356      * @param deviceId The device id of the keyboard.
357      * @return The associated key character map.
358      * @throws {@link UnavailableException} if the key character map
359      * could not be loaded because it was malformed or the default key character map
360      * is missing from the system.
361      */
load(int deviceId)362     public static KeyCharacterMap load(int deviceId) {
363         final InputManagerGlobal im = InputManagerGlobal.getInstance();
364         InputDevice inputDevice = im.getInputDevice(deviceId);
365         if (inputDevice == null) {
366             inputDevice = im.getInputDevice(VIRTUAL_KEYBOARD);
367             if (inputDevice == null) {
368                 throw new UnavailableException(
369                         "Could not load key character map for device " + deviceId);
370             }
371         }
372         return inputDevice.getKeyCharacterMap();
373     }
374 
375     /**
376      * Loads the key character map with applied KCM overlay.
377      *
378      * @param layoutDescriptor descriptor of the applied overlay KCM
379      * @param overlay          string describing the overlay KCM
380      * @return The resultant key character map.
381      * @throws {@link UnavailableException} if the key character map
382      *                could not be loaded because it was malformed or the default key character map
383      *                is missing from the system.
384      * @hide
385      */
load(@onNull String layoutDescriptor, @NonNull String overlay)386     public static KeyCharacterMap load(@NonNull String layoutDescriptor, @NonNull String overlay) {
387         KeyCharacterMap kcm = KeyCharacterMap.load(VIRTUAL_KEYBOARD);
388         kcm.applyOverlay(layoutDescriptor, overlay);
389         return kcm;
390     }
391 
applyOverlay(@onNull String layoutDescriptor, @NonNull String overlay)392     private void applyOverlay(@NonNull String layoutDescriptor, @NonNull String overlay) {
393         nativeApplyOverlay(mPtr, layoutDescriptor, overlay);
394     }
395 
396     /**
397      * Gets the mapped key for the provided scan code. Returns the provided default if no mapping
398      * found in the KeyCharacterMap.
399      *
400      * @hide
401      */
getMappedKeyOrDefault(int scanCode, int defaultKeyCode)402     public int getMappedKeyOrDefault(int scanCode, int defaultKeyCode) {
403         int keyCode = nativeGetMappedKey(mPtr, scanCode);
404         return keyCode == KeyEvent.KEYCODE_UNKNOWN ? defaultKeyCode : keyCode;
405     }
406 
407     /**
408      * Gets the Unicode character generated by the specified key and meta
409      * key state combination.
410      * <p>
411      * Returns the Unicode character that the specified key would produce
412      * when the specified meta bits (see {@link MetaKeyKeyListener})
413      * were active.
414      * </p><p>
415      * Returns 0 if the key is not one that is used to type Unicode
416      * characters.
417      * </p><p>
418      * If the return value has bit {@link #COMBINING_ACCENT} set, the
419      * key is a "dead key" that should be combined with another to
420      * actually produce a character -- see {@link #getDeadChar} --
421      * after masking with {@link #COMBINING_ACCENT_MASK}.
422      * </p>
423      *
424      * @param keyCode The key code.
425      * @param metaState The meta key modifier state.
426      * @return The associated character or combining accent, or 0 if none.
427      */
get(int keyCode, int metaState)428     public int get(int keyCode, int metaState) {
429         metaState = KeyEvent.normalizeMetaState(metaState);
430         char ch = nativeGetCharacter(mPtr, keyCode, metaState);
431 
432         int map = sCombiningToAccent.get(ch);
433         if (map != 0) {
434             return map | COMBINING_ACCENT;
435         } else {
436             return ch;
437         }
438     }
439 
440     /**
441      * Gets the fallback action to perform if the application does not
442      * handle the specified key.
443      * <p>
444      * When an application does not handle a particular key, the system may
445      * translate the key to an alternate fallback key (specified in the
446      * fallback action) and dispatch it to the application.
447      * The event containing the fallback key is flagged
448      * with {@link KeyEvent#FLAG_FALLBACK}.
449      * </p>
450      *
451      * @param keyCode The key code.
452      * @param metaState The meta key modifier state.
453      * @return The fallback action, or null if none.  Remember to recycle the fallback action.
454      *
455      * @hide
456      */
getFallbackAction(int keyCode, int metaState)457     public FallbackAction getFallbackAction(int keyCode, int metaState) {
458         FallbackAction action = FallbackAction.obtain();
459         metaState = KeyEvent.normalizeMetaState(metaState);
460         if (nativeGetFallbackAction(mPtr, keyCode, metaState, action)) {
461             action.metaState = KeyEvent.normalizeMetaState(action.metaState);
462             return action;
463         }
464         action.recycle();
465         return null;
466     }
467 
468     /**
469      * Gets the number or symbol associated with the key.
470      * <p>
471      * The character value is returned, not the numeric value.
472      * If the key is not a number, but is a symbol, the symbol is retuned.
473      * </p><p>
474      * This method is intended to to support dial pads and other numeric or
475      * symbolic entry on keyboards where certain keys serve dual function
476      * as alphabetic and symbolic keys.  This method returns the number
477      * or symbol associated with the key independent of whether the user
478      * has pressed the required modifier.
479      * </p><p>
480      * For example, on one particular keyboard the keys on the top QWERTY row generate
481      * numbers when ALT is pressed such that ALT-Q maps to '1'.  So for that keyboard
482      * when {@link #getNumber} is called with {@link KeyEvent#KEYCODE_Q} it returns '1'
483      * so that the user can type numbers without pressing ALT when it makes sense.
484      * </p>
485      *
486      * @param keyCode The key code.
487      * @return The associated numeric or symbolic character, or 0 if none.
488      */
getNumber(int keyCode)489     public char getNumber(int keyCode) {
490         return nativeGetNumber(mPtr, keyCode);
491     }
492 
493     /**
494      * Gets the first character in the character array that can be generated
495      * by the specified key code.
496      * <p>
497      * This is a convenience function that returns the same value as
498      * {@link #getMatch(int,char[],int) getMatch(keyCode, chars, 0)}.
499      * </p>
500      *
501      * @param keyCode The keycode.
502      * @param chars The array of matching characters to consider.
503      * @return The matching associated character, or 0 if none.
504      * @throws {@link IllegalArgumentException} if the passed array of characters is null.
505      */
getMatch(int keyCode, char[] chars)506     public char getMatch(int keyCode, char[] chars) {
507         return getMatch(keyCode, chars, 0);
508     }
509 
510     /**
511      * Gets the first character in the character array that can be generated
512      * by the specified key code.  If there are multiple choices, prefers
513      * the one that would be generated with the specified meta key modifier state.
514      *
515      * @param keyCode The key code.
516      * @param chars The array of matching characters to consider.
517      * @param metaState The preferred meta key modifier state.
518      * @return The matching associated character, or 0 if none.
519      * @throws {@link IllegalArgumentException} if the passed array of characters is null.
520      */
getMatch(int keyCode, char[] chars, int metaState)521     public char getMatch(int keyCode, char[] chars, int metaState) {
522         if (chars == null) {
523             throw new IllegalArgumentException("chars must not be null.");
524         }
525 
526         metaState = KeyEvent.normalizeMetaState(metaState);
527         return nativeGetMatch(mPtr, keyCode, chars, metaState);
528     }
529 
530     /**
531      * Gets the primary character for this key.
532      * In other words, the label that is physically printed on it.
533      *
534      * @param keyCode The key code.
535      * @return The display label character, or 0 if none (eg. for non-printing keys).
536      */
getDisplayLabel(int keyCode)537     public char getDisplayLabel(int keyCode) {
538         return nativeGetDisplayLabel(mPtr, keyCode);
539     }
540 
541     /**
542      * Get the character that is produced by combining the dead key producing accent
543      * with the key producing character c.
544      * For example, getDeadChar('`', 'e') returns &egrave;.
545      * getDeadChar('^', ' ') returns '^' and getDeadChar('^', '^') returns '^'.
546      *
547      * @param accent The accent character.  eg. '`'
548      * @param c The basic character.
549      * @return The combined character, or 0 if the characters cannot be combined.
550      */
getDeadChar(int accent, int c)551     public static int getDeadChar(int accent, int c) {
552         if (c == accent || CHAR_SPACE == c) {
553             // The same dead character typed twice or a dead character followed by a
554             // space should both produce the non-combining version of the combining char.
555             // In this case we don't even need to compute the combining character.
556             return accent;
557         }
558 
559         int combining = sAccentToCombining.get(accent);
560         if (combining == 0) {
561             return 0;
562         }
563 
564         final int combination = (combining << 16) | c;
565         int combined;
566         synchronized (sDeadKeyCache) {
567             combined = sDeadKeyCache.get(combination, -1);
568             if (combined == -1) {
569                 sDeadKeyBuilder.setLength(0);
570                 sDeadKeyBuilder.append((char)c);
571                 sDeadKeyBuilder.append((char)combining);
572                 String result = Normalizer.normalize(sDeadKeyBuilder, Normalizer.Form.NFC);
573                 combined = result.codePointCount(0, result.length()) == 1
574                         ? result.codePointAt(0) : 0;
575                 sDeadKeyCache.put(combination, combined);
576             }
577         }
578         return combined;
579     }
580 
581     /**
582      * Get the combining character that corresponds with the provided accent.
583      *
584      * @param accent The accent character.  eg. '`'
585      * @return The combining character
586      * @hide
587      */
getCombiningChar(int accent)588     public static int getCombiningChar(int accent) {
589         return sAccentToCombining.get(accent);
590     }
591 
592     /**
593      * Describes the character mappings associated with a key.
594      *
595      * @deprecated instead use {@link KeyCharacterMap#getDisplayLabel(int)},
596      * {@link KeyCharacterMap#getNumber(int)} and {@link KeyCharacterMap#get(int, int)}.
597      */
598     @Deprecated
599     public static class KeyData {
600         public static final int META_LENGTH = 4;
601 
602         /**
603          * The display label (see {@link #getDisplayLabel}).
604          */
605         public char displayLabel;
606         /**
607          * The "number" value (see {@link #getNumber}).
608          */
609         public char number;
610         /**
611          * The character that will be generated in various meta states
612          * (the same ones used for {@link #get} and defined as
613          * {@link KeyEvent#META_SHIFT_ON} and {@link KeyEvent#META_ALT_ON}).
614          *      <table>
615          *          <tr><th>Index</th><th align="left">Value</th></tr>
616          *          <tr><td>0</td><td>no modifiers</td></tr>
617          *          <tr><td>1</td><td>caps</td></tr>
618          *          <tr><td>2</td><td>alt</td></tr>
619          *          <tr><td>3</td><td>caps + alt</td></tr>
620          *      </table>
621          */
622         public char[] meta = new char[META_LENGTH];
623     }
624 
625     /**
626      * Get the character conversion data for a given key code.
627      *
628      * @param keyCode The keyCode to query.
629      * @param results A {@link KeyData} instance that will be filled with the results.
630      * @return True if the key was mapped.  If the key was not mapped, results is not modified.
631      *
632      * @deprecated instead use {@link KeyCharacterMap#getDisplayLabel(int)},
633      * {@link KeyCharacterMap#getNumber(int)} or {@link KeyCharacterMap#get(int, int)}.
634      */
635     @Deprecated
getKeyData(int keyCode, KeyData results)636     public boolean getKeyData(int keyCode, KeyData results) {
637         if (results.meta.length < KeyData.META_LENGTH) {
638             throw new IndexOutOfBoundsException(
639                     "results.meta.length must be >= " + KeyData.META_LENGTH);
640         }
641 
642         char displayLabel = nativeGetDisplayLabel(mPtr, keyCode);
643         if (displayLabel == 0) {
644             return false;
645         }
646 
647         results.displayLabel = displayLabel;
648         results.number = nativeGetNumber(mPtr, keyCode);
649         results.meta[0] = nativeGetCharacter(mPtr, keyCode, 0);
650         results.meta[1] = nativeGetCharacter(mPtr, keyCode, KeyEvent.META_SHIFT_ON);
651         results.meta[2] = nativeGetCharacter(mPtr, keyCode, KeyEvent.META_ALT_ON);
652         results.meta[3] = nativeGetCharacter(mPtr, keyCode,
653                 KeyEvent.META_ALT_ON | KeyEvent.META_SHIFT_ON);
654         return true;
655     }
656 
657     /**
658      * Get an array of KeyEvent objects that if put into the input stream
659      * could plausibly generate the provided sequence of characters.  It is
660      * not guaranteed that the sequence is the only way to generate these
661      * events or that it is optimal.
662      * <p>
663      * This function is primarily offered for instrumentation and testing purposes.
664      * It may fail to map characters to key codes.  In particular, the key character
665      * map for the {@link #BUILT_IN_KEYBOARD built-in keyboard} device id may be empty.
666      * Consider using the key character map associated with the
667      * {@link #VIRTUAL_KEYBOARD virtual keyboard} device id instead.
668      * </p><p>
669      * For robust text entry, do not use this function.  Instead construct a
670      * {@link KeyEvent} with action code {@link KeyEvent#ACTION_MULTIPLE} that contains
671      * the desired string using {@link KeyEvent#KeyEvent(long, String, int, int)}.
672      * </p>
673      *
674      * @param chars The sequence of characters to generate.
675      * @return An array of {@link KeyEvent} objects, or null if the given char array
676      *         can not be generated using the current key character map.
677      * @throws {@link IllegalArgumentException} if the passed array of characters is null.
678      */
getEvents(char[] chars)679     public KeyEvent[] getEvents(char[] chars) {
680         if (chars == null) {
681             throw new IllegalArgumentException("chars must not be null.");
682         }
683         return nativeGetEvents(mPtr, chars);
684     }
685 
686     /**
687      * Returns true if the specified key produces a glyph.
688      *
689      * @param keyCode The key code.
690      * @return True if the key is a printing key.
691      */
isPrintingKey(int keyCode)692     public boolean isPrintingKey(int keyCode) {
693         int type = Character.getType(nativeGetDisplayLabel(mPtr, keyCode));
694 
695         switch (type)
696         {
697             case Character.SPACE_SEPARATOR:
698             case Character.LINE_SEPARATOR:
699             case Character.PARAGRAPH_SEPARATOR:
700             case Character.CONTROL:
701             case Character.FORMAT:
702                 return false;
703             default:
704                 return true;
705         }
706     }
707 
708     /**
709      * Gets the keyboard type.
710      * Returns {@link #NUMERIC}, {@link #PREDICTIVE}, {@link #ALPHA}, {@link #FULL}
711      * or {@link #SPECIAL_FUNCTION}.
712      * <p>
713      * Different keyboard types have different semantics.  Refer to the documentation
714      * associated with the keyboard type constants for details.
715      * </p>
716      *
717      * @return The keyboard type.
718      */
getKeyboardType()719     public int getKeyboardType() {
720         return nativeGetKeyboardType(mPtr);
721     }
722 
723     /**
724      * Gets a constant that describes the behavior of this keyboard's modifier keys
725      * such as {@link KeyEvent#KEYCODE_SHIFT_LEFT}.
726      * <p>
727      * Currently there are two behaviors that may be combined:
728      * </p>
729      * <ul>
730      * <li>Chorded behavior: When the modifier key is pressed together with one or more
731      * character keys, the keyboard inserts the modified keys and
732      * then resets the modifier state when the modifier key is released.</li>
733      * <li>Toggled behavior: When the modifier key is pressed and released on its own
734      * it first toggles into a latched state.  When latched, the modifier will apply
735      * to next character key that is pressed and will then reset itself to the initial state.
736      * If the modifier is already latched and the modifier key is pressed and release on
737      * its own again, then it toggles into a locked state.  When locked, the modifier will
738      * apply to all subsequent character keys that are pressed until unlocked by pressing
739      * the modifier key on its own one more time to reset it to the initial state.
740      * Toggled behavior is useful for small profile keyboards designed for thumb typing.
741      * </ul>
742      * <p>
743      * This function currently returns {@link #MODIFIER_BEHAVIOR_CHORDED} when the
744      * {@link #getKeyboardType() keyboard type} is {@link #FULL} or {@link #SPECIAL_FUNCTION} and
745      * {@link #MODIFIER_BEHAVIOR_CHORDED_OR_TOGGLED} otherwise.
746      * In the future, the function may also take into account global keyboard
747      * accessibility settings, other user preferences, or new device capabilities.
748      * </p>
749      *
750      * @return The modifier behavior for this keyboard.
751      *
752      * @see #MODIFIER_BEHAVIOR_CHORDED
753      * @see #MODIFIER_BEHAVIOR_CHORDED_OR_TOGGLED
754      */
getModifierBehavior()755     public int getModifierBehavior() {
756         switch (getKeyboardType()) {
757             case FULL:
758             case SPECIAL_FUNCTION:
759                 return MODIFIER_BEHAVIOR_CHORDED;
760             default:
761                 return MODIFIER_BEHAVIOR_CHORDED_OR_TOGGLED;
762         }
763     }
764 
765     /**
766      * Queries the framework about whether any physical keys exist on any currently attached input
767      * devices that are capable of producing the given key code.
768      *
769      * @param keyCode The key code to query.
770      * @return True if at least one attached keyboard supports the specified key code.
771      */
deviceHasKey(int keyCode)772     public static boolean deviceHasKey(int keyCode) {
773         return InputManagerGlobal.getInstance().deviceHasKeys(new int[] { keyCode })[0];
774     }
775 
776     /**
777      * Queries the framework about whether any physical keys exist on any currently attached input
778      * devices that are capable of producing the given array of key codes.
779      *
780      * @param keyCodes The array of key codes to query.
781      * @return A new array of the same size as the key codes array whose elements
782      * are set to true if at least one attached keyboard supports the corresponding key code
783      * at the same index in the key codes array.
784      */
deviceHasKeys(int[] keyCodes)785     public static boolean[] deviceHasKeys(int[] keyCodes) {
786         return InputManagerGlobal.getInstance().deviceHasKeys(keyCodes);
787     }
788 
789     @Override
writeToParcel(Parcel out, int flags)790     public void writeToParcel(Parcel out, int flags) {
791         if (out == null) {
792             throw new IllegalArgumentException("parcel must not be null");
793         }
794         nativeWriteToParcel(mPtr, out);
795     }
796 
797     @Override
describeContents()798     public int describeContents() {
799         return 0;
800     }
801 
802     @Override
equals(Object obj)803     public boolean equals(Object obj) {
804         if (obj == null || !(obj instanceof KeyCharacterMap)) {
805             return false;
806         }
807         KeyCharacterMap peer = (KeyCharacterMap) obj;
808         if (mPtr == 0 || peer.mPtr == 0) {
809             return mPtr == peer.mPtr;
810         }
811         return nativeEquals(mPtr, peer.mPtr);
812     }
813 
814     /**
815      * Thrown by {@link KeyCharacterMap#load} when a key character map could not be loaded.
816      */
817     public static class UnavailableException extends AndroidRuntimeException {
UnavailableException(String msg)818         public UnavailableException(String msg) {
819             super(msg);
820         }
821     }
822 
823     /**
824      * Specifies a substitute key code and meta state as a fallback action
825      * for an unhandled key.
826      * @hide
827      */
828     public static final class FallbackAction {
829         private static final int MAX_RECYCLED = 10;
830         private static final Object sRecycleLock = new Object();
831         private static FallbackAction sRecycleBin;
832         private static int sRecycledCount;
833 
834         private FallbackAction next;
835 
836         @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
837         public int keyCode;
838         @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
839         public int metaState;
840 
FallbackAction()841         private FallbackAction() {
842         }
843 
obtain()844         public static FallbackAction obtain() {
845             final FallbackAction target;
846             synchronized (sRecycleLock) {
847                 if (sRecycleBin == null) {
848                     target = new FallbackAction();
849                 } else {
850                     target = sRecycleBin;
851                     sRecycleBin = target.next;
852                     sRecycledCount--;
853                     target.next = null;
854                 }
855             }
856             return target;
857         }
858 
recycle()859         public void recycle() {
860             synchronized (sRecycleLock) {
861                 if (sRecycledCount < MAX_RECYCLED) {
862                     next = sRecycleBin;
863                     sRecycleBin = this;
864                     sRecycledCount += 1;
865                 } else {
866                     next = null;
867                 }
868             }
869         }
870     }
871 }
872