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