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