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