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