1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import android.os.Parcel;
20import android.os.Parcelable;
21import android.util.Log;
22import android.util.SparseIntArray;
23import android.view.KeyCharacterMap;
24import android.view.KeyCharacterMap.KeyData;
25
26/**
27 * Contains constants for key events.
28 */
29public class KeyEvent implements Parcelable {
30    // key codes
31    public static final int KEYCODE_UNKNOWN         = 0;
32    public static final int KEYCODE_SOFT_LEFT       = 1;
33    public static final int KEYCODE_SOFT_RIGHT      = 2;
34    public static final int KEYCODE_HOME            = 3;
35    public static final int KEYCODE_BACK            = 4;
36    public static final int KEYCODE_CALL            = 5;
37    public static final int KEYCODE_ENDCALL         = 6;
38    public static final int KEYCODE_0               = 7;
39    public static final int KEYCODE_1               = 8;
40    public static final int KEYCODE_2               = 9;
41    public static final int KEYCODE_3               = 10;
42    public static final int KEYCODE_4               = 11;
43    public static final int KEYCODE_5               = 12;
44    public static final int KEYCODE_6               = 13;
45    public static final int KEYCODE_7               = 14;
46    public static final int KEYCODE_8               = 15;
47    public static final int KEYCODE_9               = 16;
48    public static final int KEYCODE_STAR            = 17;
49    public static final int KEYCODE_POUND           = 18;
50    public static final int KEYCODE_DPAD_UP         = 19;
51    public static final int KEYCODE_DPAD_DOWN       = 20;
52    public static final int KEYCODE_DPAD_LEFT       = 21;
53    public static final int KEYCODE_DPAD_RIGHT      = 22;
54    public static final int KEYCODE_DPAD_CENTER     = 23;
55    public static final int KEYCODE_VOLUME_UP       = 24;
56    public static final int KEYCODE_VOLUME_DOWN     = 25;
57    public static final int KEYCODE_POWER           = 26;
58    public static final int KEYCODE_CAMERA          = 27;
59    public static final int KEYCODE_CLEAR           = 28;
60    public static final int KEYCODE_A               = 29;
61    public static final int KEYCODE_B               = 30;
62    public static final int KEYCODE_C               = 31;
63    public static final int KEYCODE_D               = 32;
64    public static final int KEYCODE_E               = 33;
65    public static final int KEYCODE_F               = 34;
66    public static final int KEYCODE_G               = 35;
67    public static final int KEYCODE_H               = 36;
68    public static final int KEYCODE_I               = 37;
69    public static final int KEYCODE_J               = 38;
70    public static final int KEYCODE_K               = 39;
71    public static final int KEYCODE_L               = 40;
72    public static final int KEYCODE_M               = 41;
73    public static final int KEYCODE_N               = 42;
74    public static final int KEYCODE_O               = 43;
75    public static final int KEYCODE_P               = 44;
76    public static final int KEYCODE_Q               = 45;
77    public static final int KEYCODE_R               = 46;
78    public static final int KEYCODE_S               = 47;
79    public static final int KEYCODE_T               = 48;
80    public static final int KEYCODE_U               = 49;
81    public static final int KEYCODE_V               = 50;
82    public static final int KEYCODE_W               = 51;
83    public static final int KEYCODE_X               = 52;
84    public static final int KEYCODE_Y               = 53;
85    public static final int KEYCODE_Z               = 54;
86    public static final int KEYCODE_COMMA           = 55;
87    public static final int KEYCODE_PERIOD          = 56;
88    public static final int KEYCODE_ALT_LEFT        = 57;
89    public static final int KEYCODE_ALT_RIGHT       = 58;
90    public static final int KEYCODE_SHIFT_LEFT      = 59;
91    public static final int KEYCODE_SHIFT_RIGHT     = 60;
92    public static final int KEYCODE_TAB             = 61;
93    public static final int KEYCODE_SPACE           = 62;
94    public static final int KEYCODE_SYM             = 63;
95    public static final int KEYCODE_EXPLORER        = 64;
96    public static final int KEYCODE_ENVELOPE        = 65;
97    public static final int KEYCODE_ENTER           = 66;
98    public static final int KEYCODE_DEL             = 67;
99    public static final int KEYCODE_GRAVE           = 68;
100    public static final int KEYCODE_MINUS           = 69;
101    public static final int KEYCODE_EQUALS          = 70;
102    public static final int KEYCODE_LEFT_BRACKET    = 71;
103    public static final int KEYCODE_RIGHT_BRACKET   = 72;
104    public static final int KEYCODE_BACKSLASH       = 73;
105    public static final int KEYCODE_SEMICOLON       = 74;
106    public static final int KEYCODE_APOSTROPHE      = 75;
107    public static final int KEYCODE_SLASH           = 76;
108    public static final int KEYCODE_AT              = 77;
109    public static final int KEYCODE_NUM             = 78;
110    public static final int KEYCODE_HEADSETHOOK     = 79;
111    public static final int KEYCODE_FOCUS           = 80;   // *Camera* focus
112    public static final int KEYCODE_PLUS            = 81;
113    public static final int KEYCODE_MENU            = 82;
114    public static final int KEYCODE_NOTIFICATION    = 83;
115    public static final int KEYCODE_SEARCH          = 84;
116    public static final int KEYCODE_MEDIA_PLAY_PAUSE= 85;
117    public static final int KEYCODE_MEDIA_STOP      = 86;
118    public static final int KEYCODE_MEDIA_NEXT      = 87;
119    public static final int KEYCODE_MEDIA_PREVIOUS  = 88;
120    public static final int KEYCODE_MEDIA_REWIND    = 89;
121    public static final int KEYCODE_MEDIA_FAST_FORWARD = 90;
122    public static final int KEYCODE_MUTE            = 91;
123
124    // NOTE: If you add a new keycode here you must also add it to:
125    //  isSystem()
126    //  frameworks/base/include/ui/KeycodeLabels.h
127    //  tools/puppet_master/PuppetMaster/nav_keys.py
128    //  frameworks/base/core/res/res/values/attrs.xml
129    //  commands/monkey/Monkey.java
130    //  emulator?
131    //
132    //  Also Android currently does not reserve code ranges for vendor-
133    //  specific key codes.  If you have new key codes to have, you
134    //  MUST contribute a patch to the open source project to define
135    //  those new codes.  This is intended to maintain a consistent
136    //  set of key code definitions across all Android devices.
137
138    private static final int LAST_KEYCODE           = KEYCODE_MUTE;
139
140    /**
141     * @deprecated There are now more than MAX_KEYCODE keycodes.
142     * Use {@link #getMaxKeyCode()} instead.
143     */
144    @Deprecated
145    public static final int MAX_KEYCODE             = 84;
146
147    /**
148     * {@link #getAction} value: the key has been pressed down.
149     */
150    public static final int ACTION_DOWN             = 0;
151    /**
152     * {@link #getAction} value: the key has been released.
153     */
154    public static final int ACTION_UP               = 1;
155    /**
156     * {@link #getAction} value: multiple duplicate key events have
157     * occurred in a row, or a complex string is being delivered.  If the
158     * key code is not {#link {@link #KEYCODE_UNKNOWN} then the
159     * {#link {@link #getRepeatCount()} method returns the number of times
160     * the given key code should be executed.
161     * Otherwise, if the key code {@link #KEYCODE_UNKNOWN}, then
162     * this is a sequence of characters as returned by {@link #getCharacters}.
163     */
164    public static final int ACTION_MULTIPLE         = 2;
165
166    /**
167     * <p>This mask is used to check whether one of the ALT meta keys is pressed.</p>
168     *
169     * @see #isAltPressed()
170     * @see #getMetaState()
171     * @see #KEYCODE_ALT_LEFT
172     * @see #KEYCODE_ALT_RIGHT
173     */
174    public static final int META_ALT_ON = 0x02;
175
176    /**
177     * <p>This mask is used to check whether the left ALT meta key is pressed.</p>
178     *
179     * @see #isAltPressed()
180     * @see #getMetaState()
181     * @see #KEYCODE_ALT_LEFT
182     */
183    public static final int META_ALT_LEFT_ON = 0x10;
184
185    /**
186     * <p>This mask is used to check whether the right the ALT meta key is pressed.</p>
187     *
188     * @see #isAltPressed()
189     * @see #getMetaState()
190     * @see #KEYCODE_ALT_RIGHT
191     */
192    public static final int META_ALT_RIGHT_ON = 0x20;
193
194    /**
195     * <p>This mask is used to check whether one of the SHIFT meta keys is pressed.</p>
196     *
197     * @see #isShiftPressed()
198     * @see #getMetaState()
199     * @see #KEYCODE_SHIFT_LEFT
200     * @see #KEYCODE_SHIFT_RIGHT
201     */
202    public static final int META_SHIFT_ON = 0x1;
203
204    /**
205     * <p>This mask is used to check whether the left SHIFT meta key is pressed.</p>
206     *
207     * @see #isShiftPressed()
208     * @see #getMetaState()
209     * @see #KEYCODE_SHIFT_LEFT
210     */
211    public static final int META_SHIFT_LEFT_ON = 0x40;
212
213    /**
214     * <p>This mask is used to check whether the right SHIFT meta key is pressed.</p>
215     *
216     * @see #isShiftPressed()
217     * @see #getMetaState()
218     * @see #KEYCODE_SHIFT_RIGHT
219     */
220    public static final int META_SHIFT_RIGHT_ON = 0x80;
221
222    /**
223     * <p>This mask is used to check whether the SYM meta key is pressed.</p>
224     *
225     * @see #isSymPressed()
226     * @see #getMetaState()
227     */
228    public static final int META_SYM_ON = 0x4;
229
230    /**
231     * This mask is set if the device woke because of this key event.
232     */
233    public static final int FLAG_WOKE_HERE = 0x1;
234
235    /**
236     * This mask is set if the key event was generated by a software keyboard.
237     */
238    public static final int FLAG_SOFT_KEYBOARD = 0x2;
239
240    /**
241     * This mask is set if we don't want the key event to cause us to leave
242     * touch mode.
243     */
244    public static final int FLAG_KEEP_TOUCH_MODE = 0x4;
245
246    /**
247     * This mask is set if an event was known to come from a trusted part
248     * of the system.  That is, the event is known to come from the user,
249     * and could not have been spoofed by a third party component.
250     */
251    public static final int FLAG_FROM_SYSTEM = 0x8;
252
253    /**
254     * This mask is used for compatibility, to identify enter keys that are
255     * coming from an IME whose enter key has been auto-labelled "next" or
256     * "done".  This allows TextView to dispatch these as normal enter keys
257     * for old applications, but still do the appropriate action when
258     * receiving them.
259     */
260    public static final int FLAG_EDITOR_ACTION = 0x10;
261
262    /**
263     * When associated with up key events, this indicates that the key press
264     * has been canceled.  Typically this is used with virtual touch screen
265     * keys, where the user can slide from the virtual key area on to the
266     * display: in that case, the application will receive a canceled up
267     * event and should not perform the action normally associated with the
268     * key.  Note that for this to work, the application can not perform an
269     * action for a key until it receives an up or the long press timeout has
270     * expired.
271     */
272    public static final int FLAG_CANCELED = 0x20;
273
274    /**
275     * This key event was generated by a virtual (on-screen) hard key area.
276     * Typically this is an area of the touchscreen, outside of the regular
277     * display, dedicated to "hardware" buttons.
278     */
279    public static final int FLAG_VIRTUAL_HARD_KEY = 0x40;
280
281    /**
282     * This flag is set for the first key repeat that occurs after the
283     * long press timeout.
284     */
285    public static final int FLAG_LONG_PRESS = 0x80;
286
287    /**
288     * Set when a key event has {@link #FLAG_CANCELED} set because a long
289     * press action was executed while it was down.
290     */
291    public static final int FLAG_CANCELED_LONG_PRESS = 0x100;
292
293    /**
294     * Set for {@link #ACTION_UP} when this event's key code is still being
295     * tracked from its initial down.  That is, somebody requested that tracking
296     * started on the key down and a long press has not caused
297     * the tracking to be canceled.
298     */
299    public static final int FLAG_TRACKING = 0x200;
300
301    /**
302     * Private control to determine when an app is tracking a key sequence.
303     * @hide
304     */
305    public static final int FLAG_START_TRACKING = 0x40000000;
306
307    /**
308     * Returns the maximum keycode.
309     */
310    public static int getMaxKeyCode() {
311        return LAST_KEYCODE;
312    }
313
314    /**
315     * Get the character that is produced by putting accent on the character
316     * c.
317     * For example, getDeadChar('`', 'e') returns &egrave;.
318     */
319    public static int getDeadChar(int accent, int c) {
320        return KeyCharacterMap.getDeadChar(accent, c);
321    }
322
323    static final boolean DEBUG = false;
324    static final String TAG = "KeyEvent";
325
326    private int mMetaState;
327    private int mAction;
328    private int mKeyCode;
329    private int mScancode;
330    private int mRepeatCount;
331    private int mDeviceId;
332    private int mFlags;
333    private long mDownTime;
334    private long mEventTime;
335    private String mCharacters;
336
337    public interface Callback {
338        /**
339         * Called when a key down event has occurred.  If you return true,
340         * you can first call {@link KeyEvent#startTracking()
341         * KeyEvent.startTracking()} to have the framework track the event
342         * through its {@link #onKeyUp(int, KeyEvent)} and also call your
343         * {@link #onKeyLongPress(int, KeyEvent)} if it occurs.
344         *
345         * @param keyCode The value in event.getKeyCode().
346         * @param event Description of the key event.
347         *
348         * @return If you handled the event, return true.  If you want to allow
349         *         the event to be handled by the next receiver, return false.
350         */
351        boolean onKeyDown(int keyCode, KeyEvent event);
352
353        /**
354         * Called when a long press has occurred.  If you return true,
355         * the final key up will have {@link KeyEvent#FLAG_CANCELED} and
356         * {@link KeyEvent#FLAG_CANCELED_LONG_PRESS} set.  Note that in
357         * order to receive this callback, someone in the event change
358         * <em>must</em> return true from {@link #onKeyDown} <em>and</em>
359         * call {@link KeyEvent#startTracking()} on the event.
360         *
361         * @param keyCode The value in event.getKeyCode().
362         * @param event Description of the key event.
363         *
364         * @return If you handled the event, return true.  If you want to allow
365         *         the event to be handled by the next receiver, return false.
366         */
367        boolean onKeyLongPress(int keyCode, KeyEvent event);
368
369        /**
370         * Called when a key up event has occurred.
371         *
372         * @param keyCode The value in event.getKeyCode().
373         * @param event Description of the key event.
374         *
375         * @return If you handled the event, return true.  If you want to allow
376         *         the event to be handled by the next receiver, return false.
377         */
378        boolean onKeyUp(int keyCode, KeyEvent event);
379
380        /**
381         * Called when multiple down/up pairs of the same key have occurred
382         * in a row.
383         *
384         * @param keyCode The value in event.getKeyCode().
385         * @param count Number of pairs as returned by event.getRepeatCount().
386         * @param event Description of the key event.
387         *
388         * @return If you handled the event, return true.  If you want to allow
389         *         the event to be handled by the next receiver, return false.
390         */
391        boolean onKeyMultiple(int keyCode, int count, KeyEvent event);
392    }
393
394    /**
395     * Create a new key event.
396     *
397     * @param action Action code: either {@link #ACTION_DOWN},
398     * {@link #ACTION_UP}, or {@link #ACTION_MULTIPLE}.
399     * @param code The key code.
400     */
401    public KeyEvent(int action, int code) {
402        mAction = action;
403        mKeyCode = code;
404        mRepeatCount = 0;
405    }
406
407    /**
408     * Create a new key event.
409     *
410     * @param downTime The time (in {@link android.os.SystemClock#uptimeMillis})
411     * at which this key code originally went down.
412     * @param eventTime The time (in {@link android.os.SystemClock#uptimeMillis})
413     * at which this event happened.
414     * @param action Action code: either {@link #ACTION_DOWN},
415     * {@link #ACTION_UP}, or {@link #ACTION_MULTIPLE}.
416     * @param code The key code.
417     * @param repeat A repeat count for down events (> 0 if this is after the
418     * initial down) or event count for multiple events.
419     */
420    public KeyEvent(long downTime, long eventTime, int action,
421                    int code, int repeat) {
422        mDownTime = downTime;
423        mEventTime = eventTime;
424        mAction = action;
425        mKeyCode = code;
426        mRepeatCount = repeat;
427    }
428
429    /**
430     * Create a new key event.
431     *
432     * @param downTime The time (in {@link android.os.SystemClock#uptimeMillis})
433     * at which this key code originally went down.
434     * @param eventTime The time (in {@link android.os.SystemClock#uptimeMillis})
435     * at which this event happened.
436     * @param action Action code: either {@link #ACTION_DOWN},
437     * {@link #ACTION_UP}, or {@link #ACTION_MULTIPLE}.
438     * @param code The key code.
439     * @param repeat A repeat count for down events (> 0 if this is after the
440     * initial down) or event count for multiple events.
441     * @param metaState Flags indicating which meta keys are currently pressed.
442     */
443    public KeyEvent(long downTime, long eventTime, int action,
444                    int code, int repeat, int metaState) {
445        mDownTime = downTime;
446        mEventTime = eventTime;
447        mAction = action;
448        mKeyCode = code;
449        mRepeatCount = repeat;
450        mMetaState = metaState;
451    }
452
453    /**
454     * Create a new key event.
455     *
456     * @param downTime The time (in {@link android.os.SystemClock#uptimeMillis})
457     * at which this key code originally went down.
458     * @param eventTime The time (in {@link android.os.SystemClock#uptimeMillis})
459     * at which this event happened.
460     * @param action Action code: either {@link #ACTION_DOWN},
461     * {@link #ACTION_UP}, or {@link #ACTION_MULTIPLE}.
462     * @param code The key code.
463     * @param repeat A repeat count for down events (> 0 if this is after the
464     * initial down) or event count for multiple events.
465     * @param metaState Flags indicating which meta keys are currently pressed.
466     * @param device The device ID that generated the key event.
467     * @param scancode Raw device scan code of the event.
468     */
469    public KeyEvent(long downTime, long eventTime, int action,
470                    int code, int repeat, int metaState,
471                    int device, int scancode) {
472        mDownTime = downTime;
473        mEventTime = eventTime;
474        mAction = action;
475        mKeyCode = code;
476        mRepeatCount = repeat;
477        mMetaState = metaState;
478        mDeviceId = device;
479        mScancode = scancode;
480    }
481
482    /**
483     * Create a new key event.
484     *
485     * @param downTime The time (in {@link android.os.SystemClock#uptimeMillis})
486     * at which this key code originally went down.
487     * @param eventTime The time (in {@link android.os.SystemClock#uptimeMillis})
488     * at which this event happened.
489     * @param action Action code: either {@link #ACTION_DOWN},
490     * {@link #ACTION_UP}, or {@link #ACTION_MULTIPLE}.
491     * @param code The key code.
492     * @param repeat A repeat count for down events (> 0 if this is after the
493     * initial down) or event count for multiple events.
494     * @param metaState Flags indicating which meta keys are currently pressed.
495     * @param device The device ID that generated the key event.
496     * @param scancode Raw device scan code of the event.
497     * @param flags The flags for this key event
498     */
499    public KeyEvent(long downTime, long eventTime, int action,
500                    int code, int repeat, int metaState,
501                    int device, int scancode, int flags) {
502        mDownTime = downTime;
503        mEventTime = eventTime;
504        mAction = action;
505        mKeyCode = code;
506        mRepeatCount = repeat;
507        mMetaState = metaState;
508        mDeviceId = device;
509        mScancode = scancode;
510        mFlags = flags;
511    }
512
513    /**
514     * Create a new key event for a string of characters.  The key code,
515     * action, and repeat could will automatically be set to
516     * {@link #KEYCODE_UNKNOWN}, {@link #ACTION_MULTIPLE}, and 0 for you.
517     *
518     * @param time The time (in {@link android.os.SystemClock#uptimeMillis})
519     * at which this event occured.
520     * @param characters The string of characters.
521     * @param device The device ID that generated the key event.
522     * @param flags The flags for this key event
523     */
524    public KeyEvent(long time, String characters, int device, int flags) {
525        mDownTime = time;
526        mEventTime = time;
527        mCharacters = characters;
528        mAction = ACTION_MULTIPLE;
529        mKeyCode = KEYCODE_UNKNOWN;
530        mRepeatCount = 0;
531        mDeviceId = device;
532        mFlags = flags;
533    }
534
535    /**
536     * Make an exact copy of an existing key event.
537     */
538    public KeyEvent(KeyEvent origEvent) {
539        mDownTime = origEvent.mDownTime;
540        mEventTime = origEvent.mEventTime;
541        mAction = origEvent.mAction;
542        mKeyCode = origEvent.mKeyCode;
543        mRepeatCount = origEvent.mRepeatCount;
544        mMetaState = origEvent.mMetaState;
545        mDeviceId = origEvent.mDeviceId;
546        mScancode = origEvent.mScancode;
547        mFlags = origEvent.mFlags;
548        mCharacters = origEvent.mCharacters;
549    }
550
551    /**
552     * Copy an existing key event, modifying its time and repeat count.
553     *
554     * @deprecated Use {@link #changeTimeRepeat(KeyEvent, long, int)}
555     * instead.
556     *
557     * @param origEvent The existing event to be copied.
558     * @param eventTime The new event time
559     * (in {@link android.os.SystemClock#uptimeMillis}) of the event.
560     * @param newRepeat The new repeat count of the event.
561     */
562    @Deprecated
563    public KeyEvent(KeyEvent origEvent, long eventTime, int newRepeat) {
564        mDownTime = origEvent.mDownTime;
565        mEventTime = eventTime;
566        mAction = origEvent.mAction;
567        mKeyCode = origEvent.mKeyCode;
568        mRepeatCount = newRepeat;
569        mMetaState = origEvent.mMetaState;
570        mDeviceId = origEvent.mDeviceId;
571        mScancode = origEvent.mScancode;
572        mFlags = origEvent.mFlags;
573        mCharacters = origEvent.mCharacters;
574    }
575
576    /**
577     * Create a new key event that is the same as the given one, but whose
578     * event time and repeat count are replaced with the given value.
579     *
580     * @param event The existing event to be copied.  This is not modified.
581     * @param eventTime The new event time
582     * (in {@link android.os.SystemClock#uptimeMillis}) of the event.
583     * @param newRepeat The new repeat count of the event.
584     */
585    public static KeyEvent changeTimeRepeat(KeyEvent event, long eventTime,
586            int newRepeat) {
587        return new KeyEvent(event, eventTime, newRepeat);
588    }
589
590    /**
591     * Create a new key event that is the same as the given one, but whose
592     * event time and repeat count are replaced with the given value.
593     *
594     * @param event The existing event to be copied.  This is not modified.
595     * @param eventTime The new event time
596     * (in {@link android.os.SystemClock#uptimeMillis}) of the event.
597     * @param newRepeat The new repeat count of the event.
598     * @param newFlags New flags for the event, replacing the entire value
599     * in the original event.
600     */
601    public static KeyEvent changeTimeRepeat(KeyEvent event, long eventTime,
602            int newRepeat, int newFlags) {
603        KeyEvent ret = new KeyEvent(event);
604        ret.mEventTime = eventTime;
605        ret.mRepeatCount = newRepeat;
606        ret.mFlags = newFlags;
607        return ret;
608    }
609
610    /**
611     * Copy an existing key event, modifying its action.
612     *
613     * @param origEvent The existing event to be copied.
614     * @param action The new action code of the event.
615     */
616    private KeyEvent(KeyEvent origEvent, int action) {
617        mDownTime = origEvent.mDownTime;
618        mEventTime = origEvent.mEventTime;
619        mAction = action;
620        mKeyCode = origEvent.mKeyCode;
621        mRepeatCount = origEvent.mRepeatCount;
622        mMetaState = origEvent.mMetaState;
623        mDeviceId = origEvent.mDeviceId;
624        mScancode = origEvent.mScancode;
625        mFlags = origEvent.mFlags;
626        // Don't copy mCharacters, since one way or the other we'll lose it
627        // when changing the action.
628    }
629
630    /**
631     * Create a new key event that is the same as the given one, but whose
632     * action is replaced with the given value.
633     *
634     * @param event The existing event to be copied.  This is not modified.
635     * @param action The new action code of the event.
636     */
637    public static KeyEvent changeAction(KeyEvent event, int action) {
638        return new KeyEvent(event, action);
639    }
640
641    /**
642     * Create a new key event that is the same as the given one, but whose
643     * flags are replaced with the given value.
644     *
645     * @param event The existing event to be copied.  This is not modified.
646     * @param flags The new flags constant.
647     */
648    public static KeyEvent changeFlags(KeyEvent event, int flags) {
649        event = new KeyEvent(event);
650        event.mFlags = flags;
651        return event;
652    }
653
654    /**
655     * Don't use in new code, instead explicitly check
656     * {@link #getAction()}.
657     *
658     * @return If the action is ACTION_DOWN, returns true; else false.
659     *
660     * @deprecated
661     * @hide
662     */
663    @Deprecated public final boolean isDown() {
664        return mAction == ACTION_DOWN;
665    }
666
667    /**
668     * Is this a system key?  System keys can not be used for menu shortcuts.
669     *
670     * TODO: this information should come from a table somewhere.
671     * TODO: should the dpad keys be here?  arguably, because they also shouldn't be menu shortcuts
672     */
673    public final boolean isSystem() {
674        switch (mKeyCode) {
675        case KEYCODE_MENU:
676        case KEYCODE_SOFT_RIGHT:
677        case KEYCODE_HOME:
678        case KEYCODE_BACK:
679        case KEYCODE_CALL:
680        case KEYCODE_ENDCALL:
681        case KEYCODE_VOLUME_UP:
682        case KEYCODE_VOLUME_DOWN:
683        case KEYCODE_MUTE:
684        case KEYCODE_POWER:
685        case KEYCODE_HEADSETHOOK:
686        case KEYCODE_MEDIA_PLAY_PAUSE:
687        case KEYCODE_MEDIA_STOP:
688        case KEYCODE_MEDIA_NEXT:
689        case KEYCODE_MEDIA_PREVIOUS:
690        case KEYCODE_MEDIA_REWIND:
691        case KEYCODE_MEDIA_FAST_FORWARD:
692        case KEYCODE_CAMERA:
693        case KEYCODE_FOCUS:
694        case KEYCODE_SEARCH:
695            return true;
696        default:
697            return false;
698        }
699    }
700
701
702    /**
703     * <p>Returns the state of the meta keys.</p>
704     *
705     * @return an integer in which each bit set to 1 represents a pressed
706     *         meta key
707     *
708     * @see #isAltPressed()
709     * @see #isShiftPressed()
710     * @see #isSymPressed()
711     * @see #META_ALT_ON
712     * @see #META_SHIFT_ON
713     * @see #META_SYM_ON
714     */
715    public final int getMetaState() {
716        return mMetaState;
717    }
718
719    /**
720     * Returns the flags for this key event.
721     *
722     * @see #FLAG_WOKE_HERE
723     */
724    public final int getFlags() {
725        return mFlags;
726    }
727
728    /**
729     * Returns true if this key code is a modifier key.
730     *
731     * @return whether the provided keyCode is one of
732     * {@link #KEYCODE_SHIFT_LEFT} {@link #KEYCODE_SHIFT_RIGHT},
733     * {@link #KEYCODE_ALT_LEFT}, {@link #KEYCODE_ALT_RIGHT}
734     * or {@link #KEYCODE_SYM}.
735     */
736    public static boolean isModifierKey(int keyCode) {
737        return keyCode == KEYCODE_SHIFT_LEFT || keyCode == KEYCODE_SHIFT_RIGHT
738                || keyCode == KEYCODE_ALT_LEFT || keyCode == KEYCODE_ALT_RIGHT
739                || keyCode == KEYCODE_SYM;
740    }
741
742    /**
743     * <p>Returns the pressed state of the ALT meta key.</p>
744     *
745     * @return true if the ALT key is pressed, false otherwise
746     *
747     * @see #KEYCODE_ALT_LEFT
748     * @see #KEYCODE_ALT_RIGHT
749     * @see #META_ALT_ON
750     */
751    public final boolean isAltPressed() {
752        return (mMetaState & META_ALT_ON) != 0;
753    }
754
755    /**
756     * <p>Returns the pressed state of the SHIFT meta key.</p>
757     *
758     * @return true if the SHIFT key is pressed, false otherwise
759     *
760     * @see #KEYCODE_SHIFT_LEFT
761     * @see #KEYCODE_SHIFT_RIGHT
762     * @see #META_SHIFT_ON
763     */
764    public final boolean isShiftPressed() {
765        return (mMetaState & META_SHIFT_ON) != 0;
766    }
767
768    /**
769     * <p>Returns the pressed state of the SYM meta key.</p>
770     *
771     * @return true if the SYM key is pressed, false otherwise
772     *
773     * @see #KEYCODE_SYM
774     * @see #META_SYM_ON
775     */
776    public final boolean isSymPressed() {
777        return (mMetaState & META_SYM_ON) != 0;
778    }
779
780    /**
781     * Retrieve the action of this key event.  May be either
782     * {@link #ACTION_DOWN}, {@link #ACTION_UP}, or {@link #ACTION_MULTIPLE}.
783     *
784     * @return The event action: ACTION_DOWN, ACTION_UP, or ACTION_MULTIPLE.
785     */
786    public final int getAction() {
787        return mAction;
788    }
789
790    /**
791     * For {@link #ACTION_UP} events, indicates that the event has been
792     * canceled as per {@link #FLAG_CANCELED}.
793     */
794    public final boolean isCanceled() {
795        return (mFlags&FLAG_CANCELED) != 0;
796    }
797
798    /**
799     * Call this during {@link Callback#onKeyDown} to have the system track
800     * the key through its final up (possibly including a long press).  Note
801     * that only one key can be tracked at a time -- if another key down
802     * event is received while a previous one is being tracked, tracking is
803     * stopped on the previous event.
804     */
805    public final void startTracking() {
806        mFlags |= FLAG_START_TRACKING;
807    }
808
809    /**
810     * For {@link #ACTION_UP} events, indicates that the event is still being
811     * tracked from its initial down event as per
812     * {@link #FLAG_TRACKING}.
813     */
814    public final boolean isTracking() {
815        return (mFlags&FLAG_TRACKING) != 0;
816    }
817
818    /**
819     * For {@link #ACTION_DOWN} events, indicates that the event has been
820     * canceled as per {@link #FLAG_LONG_PRESS}.
821     */
822    public final boolean isLongPress() {
823        return (mFlags&FLAG_LONG_PRESS) != 0;
824    }
825
826    /**
827     * Retrieve the key code of the key event.  This is the physical key that
828     * was pressed, <em>not</em> the Unicode character.
829     *
830     * @return The key code of the event.
831     */
832    public final int getKeyCode() {
833        return mKeyCode;
834    }
835
836    /**
837     * For the special case of a {@link #ACTION_MULTIPLE} event with key
838     * code of {@link #KEYCODE_UNKNOWN}, this is a raw string of characters
839     * associated with the event.  In all other cases it is null.
840     *
841     * @return Returns a String of 1 or more characters associated with
842     * the event.
843     */
844    public final String getCharacters() {
845        return mCharacters;
846    }
847
848    /**
849     * Retrieve the hardware key id of this key event.  These values are not
850     * reliable and vary from device to device.
851     *
852     * {@more}
853     * Mostly this is here for debugging purposes.
854     */
855    public final int getScanCode() {
856        return mScancode;
857    }
858
859    /**
860     * Retrieve the repeat count of the event.  For both key up and key down
861     * events, this is the number of times the key has repeated with the first
862     * down starting at 0 and counting up from there.  For multiple key
863     * events, this is the number of down/up pairs that have occurred.
864     *
865     * @return The number of times the key has repeated.
866     */
867    public final int getRepeatCount() {
868        return mRepeatCount;
869    }
870
871    /**
872     * Retrieve the time of the most recent key down event,
873     * in the {@link android.os.SystemClock#uptimeMillis} time base.  If this
874     * is a down event, this will be the same as {@link #getEventTime()}.
875     * Note that when chording keys, this value is the down time of the
876     * most recently pressed key, which may <em>not</em> be the same physical
877     * key of this event.
878     *
879     * @return Returns the most recent key down time, in the
880     * {@link android.os.SystemClock#uptimeMillis} time base
881     */
882    public final long getDownTime() {
883        return mDownTime;
884    }
885
886    /**
887     * Retrieve the time this event occurred,
888     * in the {@link android.os.SystemClock#uptimeMillis} time base.
889     *
890     * @return Returns the time this event occurred,
891     * in the {@link android.os.SystemClock#uptimeMillis} time base.
892     */
893    public final long getEventTime() {
894        return mEventTime;
895    }
896
897    /**
898     * Return the id for the keyboard that this event came from.  A device
899     * id of 0 indicates the event didn't come from a physical device and
900     * maps to the default keymap.  The other numbers are arbitrary and
901     * you shouldn't depend on the values.
902     *
903     * @see KeyCharacterMap#load
904     */
905    public final int getDeviceId() {
906        return mDeviceId;
907    }
908
909    /**
910     * Renamed to {@link #getDeviceId}.
911     *
912     * @hide
913     * @deprecated
914     */
915    public final int getKeyboardDevice() {
916        return mDeviceId;
917    }
918
919    /**
920     * Get the primary character for this key.  In other words, the label
921     * that is physically printed on it.
922     */
923    public char getDisplayLabel() {
924        return KeyCharacterMap.load(mDeviceId).getDisplayLabel(mKeyCode);
925    }
926
927    /**
928     * <p>
929     * Returns the Unicode character that the key would produce.
930     * </p><p>
931     * Returns 0 if the key is not one that is used to type Unicode
932     * characters.
933     * </p><p>
934     * If the return value has bit
935     * {@link KeyCharacterMap#COMBINING_ACCENT}
936     * set, the key is a "dead key" that should be combined with another to
937     * actually produce a character -- see {@link #getDeadChar} --
938     * after masking with
939     * {@link KeyCharacterMap#COMBINING_ACCENT_MASK}.
940     * </p>
941     */
942    public int getUnicodeChar() {
943        return getUnicodeChar(mMetaState);
944    }
945
946    /**
947     * <p>
948     * Returns the Unicode character that the key would produce.
949     * </p><p>
950     * Returns 0 if the key is not one that is used to type Unicode
951     * characters.
952     * </p><p>
953     * If the return value has bit
954     * {@link KeyCharacterMap#COMBINING_ACCENT}
955     * set, the key is a "dead key" that should be combined with another to
956     * actually produce a character -- see {@link #getDeadChar} -- after masking
957     * with {@link KeyCharacterMap#COMBINING_ACCENT_MASK}.
958     * </p>
959     */
960    public int getUnicodeChar(int meta) {
961        return KeyCharacterMap.load(mDeviceId).get(mKeyCode, meta);
962    }
963
964    /**
965     * Get the characters conversion data for the key event..
966     *
967     * @param results a {@link KeyData} that will be filled with the results.
968     *
969     * @return whether the key was mapped or not.  If the key was not mapped,
970     *         results is not modified.
971     */
972    public boolean getKeyData(KeyData results) {
973        return KeyCharacterMap.load(mDeviceId).getKeyData(mKeyCode, results);
974    }
975
976    /**
977     * The same as {@link #getMatch(char[],int) getMatch(chars, 0)}.
978     */
979    public char getMatch(char[] chars) {
980        return getMatch(chars, 0);
981    }
982
983    /**
984     * If one of the chars in the array can be generated by the keyCode of this
985     * key event, return the char; otherwise return '\0'.
986     * @param chars the characters to try to find
987     * @param modifiers the modifier bits to prefer.  If any of these bits
988     *                  are set, if there are multiple choices, that could
989     *                  work, the one for this modifier will be set.
990     */
991    public char getMatch(char[] chars, int modifiers) {
992        return KeyCharacterMap.load(mDeviceId).getMatch(mKeyCode, chars, modifiers);
993    }
994
995    /**
996     * Gets the number or symbol associated with the key.  The character value
997     * is returned, not the numeric value.  If the key is not a number, but is
998     * a symbol, the symbol is retuned.
999     */
1000    public char getNumber() {
1001        return KeyCharacterMap.load(mDeviceId).getNumber(mKeyCode);
1002    }
1003
1004    /**
1005     * Does the key code of this key produce a glyph?
1006     */
1007    public boolean isPrintingKey() {
1008        return KeyCharacterMap.load(mDeviceId).isPrintingKey(mKeyCode);
1009    }
1010
1011    /**
1012     * @deprecated Use {@link #dispatch(Callback, DispatcherState, Object)} instead.
1013     */
1014    @Deprecated
1015    public final boolean dispatch(Callback receiver) {
1016        return dispatch(receiver, null, null);
1017    }
1018
1019    /**
1020     * Deliver this key event to a {@link Callback} interface.  If this is
1021     * an ACTION_MULTIPLE event and it is not handled, then an attempt will
1022     * be made to deliver a single normal event.
1023     *
1024     * @param receiver The Callback that will be given the event.
1025     * @param state State information retained across events.
1026     * @param target The target of the dispatch, for use in tracking.
1027     *
1028     * @return The return value from the Callback method that was called.
1029     */
1030    public final boolean dispatch(Callback receiver, DispatcherState state,
1031            Object target) {
1032        switch (mAction) {
1033            case ACTION_DOWN: {
1034                mFlags &= ~FLAG_START_TRACKING;
1035                if (DEBUG) Log.v(TAG, "Key down to " + target + " in " + state
1036                        + ": " + this);
1037                boolean res = receiver.onKeyDown(mKeyCode, this);
1038                if (state != null) {
1039                    if (res && mRepeatCount == 0 && (mFlags&FLAG_START_TRACKING) != 0) {
1040                        if (DEBUG) Log.v(TAG, "  Start tracking!");
1041                        state.startTracking(this, target);
1042                    } else if (isLongPress() && state.isTracking(this)) {
1043                        try {
1044                            if (receiver.onKeyLongPress(mKeyCode, this)) {
1045                                if (DEBUG) Log.v(TAG, "  Clear from long press!");
1046                                state.performedLongPress(this);
1047                                res = true;
1048                            }
1049                        } catch (AbstractMethodError e) {
1050                        }
1051                    }
1052                }
1053                return res;
1054            }
1055            case ACTION_UP:
1056                if (DEBUG) Log.v(TAG, "Key up to " + target + " in " + state
1057                        + ": " + this);
1058                if (state != null) {
1059                    state.handleUpEvent(this);
1060                }
1061                return receiver.onKeyUp(mKeyCode, this);
1062            case ACTION_MULTIPLE:
1063                final int count = mRepeatCount;
1064                final int code = mKeyCode;
1065                if (receiver.onKeyMultiple(code, count, this)) {
1066                    return true;
1067                }
1068                if (code != KeyEvent.KEYCODE_UNKNOWN) {
1069                    mAction = ACTION_DOWN;
1070                    mRepeatCount = 0;
1071                    boolean handled = receiver.onKeyDown(code, this);
1072                    if (handled) {
1073                        mAction = ACTION_UP;
1074                        receiver.onKeyUp(code, this);
1075                    }
1076                    mAction = ACTION_MULTIPLE;
1077                    mRepeatCount = count;
1078                    return handled;
1079                }
1080                return false;
1081        }
1082        return false;
1083    }
1084
1085    /**
1086     * Use with {@link KeyEvent#dispatch(Callback, DispatcherState, Object)}
1087     * for more advanced key dispatching, such as long presses.
1088     */
1089    public static class DispatcherState {
1090        int mDownKeyCode;
1091        Object mDownTarget;
1092        SparseIntArray mActiveLongPresses = new SparseIntArray();
1093
1094        /**
1095         * Reset back to initial state.
1096         */
1097        public void reset() {
1098            if (DEBUG) Log.v(TAG, "Reset: " + this);
1099            mDownKeyCode = 0;
1100            mDownTarget = null;
1101            mActiveLongPresses.clear();
1102        }
1103
1104        /**
1105         * Stop any tracking associated with this target.
1106         */
1107        public void reset(Object target) {
1108            if (mDownTarget == target) {
1109                if (DEBUG) Log.v(TAG, "Reset in " + target + ": " + this);
1110                mDownKeyCode = 0;
1111                mDownTarget = null;
1112            }
1113        }
1114
1115        /**
1116         * Start tracking the key code associated with the given event.  This
1117         * can only be called on a key down.  It will allow you to see any
1118         * long press associated with the key, and will result in
1119         * {@link KeyEvent#isTracking} return true on the long press and up
1120         * events.
1121         *
1122         * <p>This is only needed if you are directly dispatching events, rather
1123         * than handling them in {@link Callback#onKeyDown}.
1124         */
1125        public void startTracking(KeyEvent event, Object target) {
1126            if (event.getAction() != ACTION_DOWN) {
1127                throw new IllegalArgumentException(
1128                        "Can only start tracking on a down event");
1129            }
1130            if (DEBUG) Log.v(TAG, "Start trackingt in " + target + ": " + this);
1131            mDownKeyCode = event.getKeyCode();
1132            mDownTarget = target;
1133        }
1134
1135        /**
1136         * Return true if the key event is for a key code that is currently
1137         * being tracked by the dispatcher.
1138         */
1139        public boolean isTracking(KeyEvent event) {
1140            return mDownKeyCode == event.getKeyCode();
1141        }
1142
1143        /**
1144         * Keep track of the given event's key code as having performed an
1145         * action with a long press, so no action should occur on the up.
1146         * <p>This is only needed if you are directly dispatching events, rather
1147         * than handling them in {@link Callback#onKeyLongPress}.
1148         */
1149        public void performedLongPress(KeyEvent event) {
1150            mActiveLongPresses.put(event.getKeyCode(), 1);
1151        }
1152
1153        /**
1154         * Handle key up event to stop tracking.  This resets the dispatcher state,
1155         * and updates the key event state based on it.
1156         * <p>This is only needed if you are directly dispatching events, rather
1157         * than handling them in {@link Callback#onKeyUp}.
1158         */
1159        public void handleUpEvent(KeyEvent event) {
1160            final int keyCode = event.getKeyCode();
1161            if (DEBUG) Log.v(TAG, "Handle key up " + event + ": " + this);
1162            int index = mActiveLongPresses.indexOfKey(keyCode);
1163            if (index >= 0) {
1164                if (DEBUG) Log.v(TAG, "  Index: " + index);
1165                event.mFlags |= FLAG_CANCELED | FLAG_CANCELED_LONG_PRESS;
1166                mActiveLongPresses.removeAt(index);
1167            }
1168            if (mDownKeyCode == keyCode) {
1169                if (DEBUG) Log.v(TAG, "  Tracking!");
1170                event.mFlags |= FLAG_TRACKING;
1171                mDownKeyCode = 0;
1172                mDownTarget = null;
1173            }
1174        }
1175    }
1176
1177    public String toString() {
1178        return "KeyEvent{action=" + mAction + " code=" + mKeyCode
1179            + " repeat=" + mRepeatCount
1180            + " meta=" + mMetaState + " scancode=" + mScancode
1181            + " mFlags=" + mFlags + "}";
1182    }
1183
1184    public static final Parcelable.Creator<KeyEvent> CREATOR
1185            = new Parcelable.Creator<KeyEvent>() {
1186        public KeyEvent createFromParcel(Parcel in) {
1187            return new KeyEvent(in);
1188        }
1189
1190        public KeyEvent[] newArray(int size) {
1191            return new KeyEvent[size];
1192        }
1193    };
1194
1195    public int describeContents() {
1196        return 0;
1197    }
1198
1199    public void writeToParcel(Parcel out, int flags) {
1200        out.writeInt(mAction);
1201        out.writeInt(mKeyCode);
1202        out.writeInt(mRepeatCount);
1203        out.writeInt(mMetaState);
1204        out.writeInt(mDeviceId);
1205        out.writeInt(mScancode);
1206        out.writeInt(mFlags);
1207        out.writeLong(mDownTime);
1208        out.writeLong(mEventTime);
1209    }
1210
1211    private KeyEvent(Parcel in) {
1212        mAction = in.readInt();
1213        mKeyCode = in.readInt();
1214        mRepeatCount = in.readInt();
1215        mMetaState = in.readInt();
1216        mDeviceId = in.readInt();
1217        mScancode = in.readInt();
1218        mFlags = in.readInt();
1219        mDownTime = in.readLong();
1220        mEventTime = in.readLong();
1221    }
1222}
1223