1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim:expandtab:shiftwidth=4:tabstop=4:
4 /* This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
8 #include "mozilla/Logging.h"
10 #include "nsGtkKeyUtils.h"
12 #include <gdk/gdkkeysyms.h>
17 #include <gdk/gdkkeysyms-compat.h>
18 #include <X11/XKBlib.h>
19 #include "X11UndefineNone.h"
20 #include "IMContextWrapper.h"
21 #include "WidgetUtils.h"
22 #include "WidgetUtilsGtk.h"
23 #include "keysym2ucs.h"
24 #include "nsContentUtils.h"
25 #include "nsGtkUtils.h"
26 #include "nsIBidiKeyboard.h"
27 #include "nsPrintfCString.h"
28 #include "nsReadableUtils.h"
29 #include "nsServiceManagerUtils.h"
32 #include "mozilla/ArrayUtils.h"
33 #include "mozilla/MouseEvents.h"
34 #include "mozilla/TextEventDispatcher.h"
35 #include "mozilla/TextEvents.h"
38 # include <sys/mman.h>
39 # include "nsWaylandDisplay.h"
45 LazyLogModule
gKeymapWrapperLog("KeymapWrapperWidgets");
47 #define IS_ASCII_ALPHABETICAL(key) \
48 ((('a' <= key) && (key <= 'z')) || (('A' <= key) && (key <= 'Z')))
50 #define MOZ_MODIFIER_KEYS "MozKeymapWrapper"
52 KeymapWrapper
* KeymapWrapper::sInstance
= nullptr;
53 guint
KeymapWrapper::sLastRepeatableHardwareKeyCode
= 0;
54 Time
KeymapWrapper::sLastRepeatableKeyTime
= 0;
55 KeymapWrapper::RepeatState
KeymapWrapper::sRepeatState
=
56 KeymapWrapper::NOT_PRESSED
;
58 static const char* GetBoolName(bool aBool
) { return aBool
? "TRUE" : "FALSE"; }
60 static const char* GetStatusName(nsEventStatus aStatus
) {
62 case nsEventStatus_eConsumeDoDefault
:
63 return "nsEventStatus_eConsumeDoDefault";
64 case nsEventStatus_eConsumeNoDefault
:
65 return "nsEventStatus_eConsumeNoDefault";
66 case nsEventStatus_eIgnore
:
67 return "nsEventStatus_eIgnore";
68 case nsEventStatus_eSentinel
:
69 return "nsEventStatus_eSentinel";
71 return "Illegal value";
75 static const nsCString
GetKeyLocationName(uint32_t aLocation
) {
77 case eKeyLocationLeft
:
78 return "KEY_LOCATION_LEFT"_ns
;
79 case eKeyLocationRight
:
80 return "KEY_LOCATION_RIGHT"_ns
;
81 case eKeyLocationStandard
:
82 return "KEY_LOCATION_STANDARD"_ns
;
83 case eKeyLocationNumpad
:
84 return "KEY_LOCATION_NUMPAD"_ns
;
86 return nsPrintfCString("Unknown (0x%04X)", aLocation
);
90 static const nsCString
GetCharacterCodeName(char16_t aChar
) {
93 return "NULL (0x0000)"_ns
;
95 return "BACKSPACE (0x0008)"_ns
;
97 return "CHARACTER TABULATION (0x0009)"_ns
;
99 return "LINE FEED (0x000A)"_ns
;
101 return "LINE TABULATION (0x000B)"_ns
;
103 return "FORM FEED (0x000C)"_ns
;
105 return "CARRIAGE RETURN (0x000D)"_ns
;
107 return "CANCEL (0x0018)"_ns
;
109 return "ESCAPE (0x001B)"_ns
;
111 return "SPACE (0x0020)"_ns
;
113 return "DELETE (0x007F)"_ns
;
115 return "NO-BREAK SPACE (0x00A0)"_ns
;
117 return "SOFT HYPHEN (0x00AD)"_ns
;
119 return "EN QUAD (0x2000)"_ns
;
121 return "EM QUAD (0x2001)"_ns
;
123 return "EN SPACE (0x2002)"_ns
;
125 return "EM SPACE (0x2003)"_ns
;
127 return "THREE-PER-EM SPACE (0x2004)"_ns
;
129 return "FOUR-PER-EM SPACE (0x2005)"_ns
;
131 return "SIX-PER-EM SPACE (0x2006)"_ns
;
133 return "FIGURE SPACE (0x2007)"_ns
;
135 return "PUNCTUATION SPACE (0x2008)"_ns
;
137 return "THIN SPACE (0x2009)"_ns
;
139 return "HAIR SPACE (0x200A)"_ns
;
141 return "ZERO WIDTH SPACE (0x200B)"_ns
;
143 return "ZERO WIDTH NON-JOINER (0x200C)"_ns
;
145 return "ZERO WIDTH JOINER (0x200D)"_ns
;
147 return "LEFT-TO-RIGHT MARK (0x200E)"_ns
;
149 return "RIGHT-TO-LEFT MARK (0x200F)"_ns
;
151 return "PARAGRAPH SEPARATOR (0x2029)"_ns
;
153 return "LEFT-TO-RIGHT EMBEDDING (0x202A)"_ns
;
155 return "RIGHT-TO-LEFT EMBEDDING (0x202B)"_ns
;
157 return "LEFT-TO-RIGHT OVERRIDE (0x202D)"_ns
;
159 return "RIGHT-TO-LEFT OVERRIDE (0x202E)"_ns
;
161 return "NARROW NO-BREAK SPACE (0x202F)"_ns
;
163 return "MEDIUM MATHEMATICAL SPACE (0x205F)"_ns
;
165 return "WORD JOINER (0x2060)"_ns
;
167 return "LEFT-TO-RIGHT ISOLATE (0x2066)"_ns
;
169 return "RIGHT-TO-LEFT ISOLATE (0x2067)"_ns
;
171 return "IDEOGRAPHIC SPACE (0x3000)"_ns
;
173 return "ZERO WIDTH NO-BREAK SPACE (0xFEFF)"_ns
;
175 if (aChar
< ' ' || (aChar
>= 0x80 && aChar
< 0xA0)) {
176 return nsPrintfCString("control (0x%04X)", aChar
);
178 if (NS_IS_HIGH_SURROGATE(aChar
)) {
179 return nsPrintfCString("high surrogate (0x%04X)", aChar
);
181 if (NS_IS_LOW_SURROGATE(aChar
)) {
182 return nsPrintfCString("low surrogate (0x%04X)", aChar
);
184 return nsPrintfCString("'%s' (0x%04X)",
185 NS_ConvertUTF16toUTF8(nsAutoString(aChar
)).get(),
191 static const nsCString
GetCharacterCodeNames(const char16_t
* aChars
,
197 result
.AssignLiteral("\"");
198 StringJoinAppend(result
, ", "_ns
, Span
{aChars
, aLength
},
199 [](nsACString
& dest
, const char16_t charValue
) {
200 dest
.Append(GetCharacterCodeName(charValue
));
202 result
.AppendLiteral("\"");
206 static const nsCString
GetCharacterCodeNames(const nsAString
& aString
) {
207 return GetCharacterCodeNames(aString
.BeginReading(), aString
.Length());
210 /* static */ const char* KeymapWrapper::GetModifierName(Modifier aModifier
) {
235 return "NotModifier";
237 return "InvalidValue";
241 /* static */ KeymapWrapper::Modifier
KeymapWrapper::GetModifierForGDKKeyval(
243 switch (aGdkKeyval
) {
248 case GDK_Scroll_Lock
:
269 case GDK_ISO_Level3_Shift
:
270 case GDK_Mode_switch
:
272 case GDK_ISO_Level5_Shift
:
279 guint
KeymapWrapper::GetModifierMask(Modifier aModifier
) const {
282 return GDK_LOCK_MASK
;
284 return mModifierMasks
[INDEX_NUM_LOCK
];
286 return mModifierMasks
[INDEX_SCROLL_LOCK
];
288 return GDK_SHIFT_MASK
;
290 return GDK_CONTROL_MASK
;
292 return mModifierMasks
[INDEX_ALT
];
294 return mModifierMasks
[INDEX_SUPER
];
296 return mModifierMasks
[INDEX_HYPER
];
298 return mModifierMasks
[INDEX_META
];
300 return mModifierMasks
[INDEX_LEVEL3
];
302 return mModifierMasks
[INDEX_LEVEL5
];
308 KeymapWrapper::ModifierKey
* KeymapWrapper::GetModifierKey(
309 guint aHardwareKeycode
) {
310 for (uint32_t i
= 0; i
< mModifierKeys
.Length(); i
++) {
311 ModifierKey
& key
= mModifierKeys
[i
];
312 if (key
.mHardwareKeycode
== aHardwareKeycode
) {
320 KeymapWrapper
* KeymapWrapper::GetInstance() {
326 sInstance
= new KeymapWrapper();
331 void KeymapWrapper::Shutdown() {
338 KeymapWrapper::KeymapWrapper()
339 : mInitialized(false),
340 mGdkKeymap(gdk_keymap_get_default()),
341 mXKBBaseEventCode(0),
342 mOnKeysChangedSignalHandle(0),
343 mOnDirectionChangedSignalHandle(0) {
344 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
345 ("%p Constructor, mGdkKeymap=%p", this, mGdkKeymap
));
347 g_object_ref(mGdkKeymap
);
349 if (GdkIsX11Display()) {
356 void KeymapWrapper::Init() {
362 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
363 ("%p Init, mGdkKeymap=%p", this, mGdkKeymap
));
365 mModifierKeys
.Clear();
366 memset(mModifierMasks
, 0, sizeof(mModifierMasks
));
368 if (GdkIsX11Display()) {
369 InitBySystemSettingsX11();
373 InitBySystemSettingsWayland();
377 gdk_window_add_filter(nullptr, FilterEvents
, this);
379 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
380 ("%p Init, CapsLock=0x%X, NumLock=0x%X, "
381 "ScrollLock=0x%X, Level3=0x%X, Level5=0x%X, "
382 "Shift=0x%X, Ctrl=0x%X, Alt=0x%X, Meta=0x%X, Super=0x%X, Hyper=0x%X",
383 this, GetModifierMask(CAPS_LOCK
), GetModifierMask(NUM_LOCK
),
384 GetModifierMask(SCROLL_LOCK
), GetModifierMask(LEVEL3
),
385 GetModifierMask(LEVEL5
), GetModifierMask(SHIFT
),
386 GetModifierMask(CTRL
), GetModifierMask(ALT
), GetModifierMask(META
),
387 GetModifierMask(SUPER
), GetModifierMask(HYPER
)));
390 void KeymapWrapper::InitXKBExtension() {
391 PodZero(&mKeyboardState
);
393 int xkbMajorVer
= XkbMajorVersion
;
394 int xkbMinorVer
= XkbMinorVersion
;
395 if (!XkbLibraryVersion(&xkbMajorVer
, &xkbMinorVer
)) {
396 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
397 ("%p InitXKBExtension failed due to failure of "
398 "XkbLibraryVersion()",
403 Display
* display
= gdk_x11_display_get_xdisplay(gdk_display_get_default());
405 // XkbLibraryVersion() set xkbMajorVer and xkbMinorVer to that of the
406 // library, which may be newer than what is required of the server in
407 // XkbQueryExtension(), so these variables should be reset to
408 // XkbMajorVersion and XkbMinorVersion before the XkbQueryExtension call.
409 xkbMajorVer
= XkbMajorVersion
;
410 xkbMinorVer
= XkbMinorVersion
;
411 int opcode
, baseErrorCode
;
412 if (!XkbQueryExtension(display
, &opcode
, &mXKBBaseEventCode
, &baseErrorCode
,
413 &xkbMajorVer
, &xkbMinorVer
)) {
414 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
415 ("%p InitXKBExtension failed due to failure of "
416 "XkbQueryExtension(), display=0x%p",
421 if (!XkbSelectEventDetails(display
, XkbUseCoreKbd
, XkbStateNotify
,
422 XkbModifierStateMask
, XkbModifierStateMask
)) {
423 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
424 ("%p InitXKBExtension failed due to failure of "
425 "XkbSelectEventDetails() for XModifierStateMask, display=0x%p",
430 if (!XkbSelectEventDetails(display
, XkbUseCoreKbd
, XkbControlsNotify
,
431 XkbPerKeyRepeatMask
, XkbPerKeyRepeatMask
)) {
432 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
433 ("%p InitXKBExtension failed due to failure of "
434 "XkbSelectEventDetails() for XkbControlsNotify, display=0x%p",
439 if (!XGetKeyboardControl(display
, &mKeyboardState
)) {
440 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
441 ("%p InitXKBExtension failed due to failure of "
442 "XGetKeyboardControl(), display=0x%p",
447 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
448 ("%p InitXKBExtension, Succeeded", this));
451 void KeymapWrapper::InitBySystemSettingsX11() {
452 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
453 ("%p InitBySystemSettingsX11, mGdkKeymap=%p", this, mGdkKeymap
));
455 if (!mOnKeysChangedSignalHandle
) {
456 mOnKeysChangedSignalHandle
= g_signal_connect(
457 mGdkKeymap
, "keys-changed", (GCallback
)OnKeysChanged
, this);
459 if (!mOnDirectionChangedSignalHandle
) {
460 mOnDirectionChangedSignalHandle
= g_signal_connect(
461 mGdkKeymap
, "direction-changed", (GCallback
)OnDirectionChanged
, this);
464 Display
* display
= gdk_x11_display_get_xdisplay(gdk_display_get_default());
468 XDisplayKeycodes(display
, &min_keycode
, &max_keycode
);
470 int keysyms_per_keycode
= 0;
472 XGetKeyboardMapping(display
, min_keycode
, max_keycode
- min_keycode
+ 1,
473 &keysyms_per_keycode
);
475 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
476 ("%p InitBySystemSettings, "
477 "Failed due to null xkeymap",
482 XModifierKeymap
* xmodmap
= XGetModifierMapping(display
);
484 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
485 ("%p InitBySystemSettings, "
486 "Failed due to null xmodmap",
491 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
492 ("%p InitBySystemSettings, min_keycode=%d, "
493 "max_keycode=%d, keysyms_per_keycode=%d, max_keypermod=%d",
494 this, min_keycode
, max_keycode
, keysyms_per_keycode
,
495 xmodmap
->max_keypermod
));
497 // The modifiermap member of the XModifierKeymap structure contains 8 sets
498 // of max_keypermod KeyCodes, one for each modifier in the order Shift,
499 // Lock, Control, Mod1, Mod2, Mod3, Mod4, and Mod5.
500 // Only nonzero KeyCodes have meaning in each set, and zero KeyCodes are
503 // Note that two or more modifiers may use one modifier flag. E.g.,
504 // on Ubuntu 10.10, Alt and Meta share the Mod1 in default settings.
505 // And also Super and Hyper share the Mod4. In such cases, we need to
506 // decide which modifier flag means one of DOM modifiers.
508 // mod[0] is Modifier introduced by Mod1.
510 int32_t foundLevel
[5];
511 for (uint32_t i
= 0; i
< ArrayLength(mod
); i
++) {
512 mod
[i
] = NOT_MODIFIER
;
513 foundLevel
[i
] = INT32_MAX
;
515 const uint32_t map_size
= 8 * xmodmap
->max_keypermod
;
516 for (uint32_t i
= 0; i
< map_size
; i
++) {
517 KeyCode keycode
= xmodmap
->modifiermap
[i
];
518 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
519 ("%p InitBySystemSettings, "
520 " i=%d, keycode=0x%08X",
522 if (!keycode
|| keycode
< min_keycode
|| keycode
> max_keycode
) {
526 ModifierKey
* modifierKey
= GetModifierKey(keycode
);
528 modifierKey
= mModifierKeys
.AppendElement(ModifierKey(keycode
));
532 xkeymap
+ (keycode
- min_keycode
) * keysyms_per_keycode
;
533 const uint32_t bit
= i
/ xmodmap
->max_keypermod
;
534 modifierKey
->mMask
|= 1 << bit
;
536 // We need to know the meaning of Mod1, Mod2, Mod3, Mod4 and Mod5.
537 // Let's skip if current map is for others.
542 const int32_t modIndex
= bit
- 3;
543 for (int32_t j
= 0; j
< keysyms_per_keycode
; j
++) {
544 Modifier modifier
= GetModifierForGDKKeyval(syms
[j
]);
545 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
546 ("%p InitBySystemSettings, "
547 " Mod%d, j=%d, syms[j]=%s(0x%lX), modifier=%s",
548 this, modIndex
+ 1, j
, gdk_keyval_name(syms
[j
]), syms
[j
],
549 GetModifierName(modifier
)));
553 // Don't overwrite the stored information with
559 // Ignore the modifiers defined in GDK spec. They shouldn't
560 // be mapped to Mod1-5 because they must not work on native
564 // If new modifier is found in higher level than stored
565 // value, we don't need to overwrite it.
566 if (j
> foundLevel
[modIndex
]) {
569 // If new modifier is more important than stored value,
570 // we should overwrite it with new modifier.
571 if (j
== foundLevel
[modIndex
]) {
572 mod
[modIndex
] = std::min(modifier
, mod
[modIndex
]);
575 foundLevel
[modIndex
] = j
;
576 mod
[modIndex
] = modifier
;
582 for (uint32_t i
= 0; i
< COUNT_OF_MODIFIER_INDEX
; i
++) {
588 case INDEX_SCROLL_LOCK
:
589 modifier
= SCROLL_LOCK
;
610 MOZ_CRASH("All indexes must be handled here");
612 for (uint32_t j
= 0; j
< ArrayLength(mod
); j
++) {
613 if (modifier
== mod
[j
]) {
614 mModifierMasks
[i
] |= 1 << (j
+ 3);
619 XFreeModifiermap(xmodmap
);
624 void KeymapWrapper::SetModifierMask(xkb_keymap
* aKeymap
,
625 ModifierIndex aModifierIndex
,
626 const char* aModifierName
) {
627 static auto sXkbKeymapModGetIndex
=
628 (xkb_mod_index_t(*)(struct xkb_keymap
*, const char*))dlsym(
629 RTLD_DEFAULT
, "xkb_keymap_mod_get_index");
631 xkb_mod_index_t index
= sXkbKeymapModGetIndex(aKeymap
, aModifierName
);
632 if (index
!= XKB_MOD_INVALID
) {
633 mModifierMasks
[aModifierIndex
] = (1 << index
);
637 void KeymapWrapper::SetModifierMasks(xkb_keymap
* aKeymap
) {
638 KeymapWrapper
* keymapWrapper
= GetInstance();
640 // This mapping is derived from get_xkb_modifiers() at gdkkeys-wayland.c
641 keymapWrapper
->SetModifierMask(aKeymap
, INDEX_NUM_LOCK
, XKB_MOD_NAME_NUM
);
642 keymapWrapper
->SetModifierMask(aKeymap
, INDEX_ALT
, XKB_MOD_NAME_ALT
);
643 keymapWrapper
->SetModifierMask(aKeymap
, INDEX_META
, "Meta");
644 keymapWrapper
->SetModifierMask(aKeymap
, INDEX_SUPER
, "Super");
645 keymapWrapper
->SetModifierMask(aKeymap
, INDEX_HYPER
, "Hyper");
647 keymapWrapper
->SetModifierMask(aKeymap
, INDEX_SCROLL_LOCK
, "ScrollLock");
648 keymapWrapper
->SetModifierMask(aKeymap
, INDEX_LEVEL3
, "Level3");
649 keymapWrapper
->SetModifierMask(aKeymap
, INDEX_LEVEL5
, "Level5");
651 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
652 ("%p KeymapWrapper::SetModifierMasks, CapsLock=0x%X, NumLock=0x%X, "
653 "ScrollLock=0x%X, Level3=0x%X, Level5=0x%X, "
654 "Shift=0x%X, Ctrl=0x%X, Alt=0x%X, Meta=0x%X, Super=0x%X, Hyper=0x%X",
655 keymapWrapper
, keymapWrapper
->GetModifierMask(CAPS_LOCK
),
656 keymapWrapper
->GetModifierMask(NUM_LOCK
),
657 keymapWrapper
->GetModifierMask(SCROLL_LOCK
),
658 keymapWrapper
->GetModifierMask(LEVEL3
),
659 keymapWrapper
->GetModifierMask(LEVEL5
),
660 keymapWrapper
->GetModifierMask(SHIFT
),
661 keymapWrapper
->GetModifierMask(CTRL
),
662 keymapWrapper
->GetModifierMask(ALT
),
663 keymapWrapper
->GetModifierMask(META
),
664 keymapWrapper
->GetModifierMask(SUPER
),
665 keymapWrapper
->GetModifierMask(HYPER
)));
668 /* This keymap routine is derived from weston-2.0.0/clients/simple-im.c
670 static void keyboard_handle_keymap(void* data
, struct wl_keyboard
* wl_keyboard
,
671 uint32_t format
, int fd
, uint32_t size
) {
672 KeymapWrapper::ResetKeyboard();
674 if (format
!= WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1
) {
679 char* mapString
= (char*)mmap(NULL
, size
, PROT_READ
, MAP_SHARED
, fd
, 0);
680 if (mapString
== MAP_FAILED
) {
685 static auto sXkbContextNew
=
686 (struct xkb_context
* (*)(enum xkb_context_flags
))
687 dlsym(RTLD_DEFAULT
, "xkb_context_new");
688 static auto sXkbKeymapNewFromString
=
689 (struct xkb_keymap
* (*)(struct xkb_context
*, const char*,
690 enum xkb_keymap_format
,
691 enum xkb_keymap_compile_flags
))
692 dlsym(RTLD_DEFAULT
, "xkb_keymap_new_from_string");
694 struct xkb_context
* xkb_context
= sXkbContextNew(XKB_CONTEXT_NO_FLAGS
);
695 struct xkb_keymap
* keymap
=
696 sXkbKeymapNewFromString(xkb_context
, mapString
, XKB_KEYMAP_FORMAT_TEXT_V1
,
697 XKB_KEYMAP_COMPILE_NO_FLAGS
);
699 munmap(mapString
, size
);
703 NS_WARNING("keyboard_handle_keymap(): Failed to compile keymap!\n");
707 KeymapWrapper::SetModifierMasks(keymap
);
709 static auto sXkbKeymapUnRef
=
710 (void (*)(struct xkb_keymap
*))dlsym(RTLD_DEFAULT
, "xkb_keymap_unref");
711 sXkbKeymapUnRef(keymap
);
713 static auto sXkbContextUnref
=
714 (void (*)(struct xkb_context
*))dlsym(RTLD_DEFAULT
, "xkb_context_unref");
715 sXkbContextUnref(xkb_context
);
718 static void keyboard_handle_enter(void* data
, struct wl_keyboard
* keyboard
,
719 uint32_t serial
, struct wl_surface
* surface
,
720 struct wl_array
* keys
) {}
721 static void keyboard_handle_leave(void* data
, struct wl_keyboard
* keyboard
,
722 uint32_t serial
, struct wl_surface
* surface
) {
724 static void keyboard_handle_key(void* data
, struct wl_keyboard
* keyboard
,
725 uint32_t serial
, uint32_t time
, uint32_t key
,
727 static void keyboard_handle_modifiers(void* data
, struct wl_keyboard
* keyboard
,
728 uint32_t serial
, uint32_t mods_depressed
,
729 uint32_t mods_latched
,
730 uint32_t mods_locked
, uint32_t group
) {}
732 static const struct wl_keyboard_listener keyboard_listener
= {
733 keyboard_handle_keymap
, keyboard_handle_enter
, keyboard_handle_leave
,
734 keyboard_handle_key
, keyboard_handle_modifiers
,
737 static void seat_handle_capabilities(void* data
, struct wl_seat
* seat
,
739 static wl_keyboard
* keyboard
= nullptr;
741 if ((caps
& WL_SEAT_CAPABILITY_KEYBOARD
) && !keyboard
) {
742 keyboard
= wl_seat_get_keyboard(seat
);
743 wl_keyboard_add_listener(keyboard
, &keyboard_listener
, nullptr);
744 } else if (!(caps
& WL_SEAT_CAPABILITY_KEYBOARD
) && keyboard
) {
745 wl_keyboard_destroy(keyboard
);
750 static const struct wl_seat_listener seat_listener
= {
751 seat_handle_capabilities
,
754 static void gdk_registry_handle_global(void* data
, struct wl_registry
* registry
,
755 uint32_t id
, const char* interface
,
757 if (strcmp(interface
, "wl_seat") == 0) {
759 WaylandRegistryBind
<wl_seat
>(registry
, id
, &wl_seat_interface
, 1);
760 wl_seat_add_listener(seat
, &seat_listener
, data
);
764 static void gdk_registry_handle_global_remove(void* data
,
765 struct wl_registry
* registry
,
768 static const struct wl_registry_listener keyboard_registry_listener
= {
769 gdk_registry_handle_global
, gdk_registry_handle_global_remove
};
771 void KeymapWrapper::InitBySystemSettingsWayland() {
772 wl_display
* display
= WaylandDisplayGetWLDisplay();
773 wl_registry_add_listener(wl_display_get_registry(display
),
774 &keyboard_registry_listener
, this);
778 KeymapWrapper::~KeymapWrapper() {
779 gdk_window_remove_filter(nullptr, FilterEvents
, this);
780 if (mOnKeysChangedSignalHandle
) {
781 g_signal_handler_disconnect(mGdkKeymap
, mOnKeysChangedSignalHandle
);
783 if (mOnDirectionChangedSignalHandle
) {
784 g_signal_handler_disconnect(mGdkKeymap
, mOnDirectionChangedSignalHandle
);
786 g_object_unref(mGdkKeymap
);
787 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
, ("%p Destructor", this));
791 GdkFilterReturn
KeymapWrapper::FilterEvents(GdkXEvent
* aXEvent
,
794 XEvent
* xEvent
= static_cast<XEvent
*>(aXEvent
);
795 switch (xEvent
->type
) {
797 // If the key doesn't support auto repeat, ignore the event because
798 // even if such key (e.g., Shift) is pressed during auto repeat of
799 // anoter key, it doesn't stop the auto repeat.
800 KeymapWrapper
* self
= static_cast<KeymapWrapper
*>(aData
);
801 if (!self
->IsAutoRepeatableKey(xEvent
->xkey
.keycode
)) {
804 if (sRepeatState
== NOT_PRESSED
) {
805 sRepeatState
= FIRST_PRESS
;
806 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
807 ("FilterEvents(aXEvent={ type=KeyPress, "
808 "xkey={ keycode=0x%08X, state=0x%08X, time=%lu } }, "
809 "aGdkEvent={ state=0x%08X }), "
810 "detected first keypress",
811 xEvent
->xkey
.keycode
, xEvent
->xkey
.state
, xEvent
->xkey
.time
,
812 reinterpret_cast<GdkEventKey
*>(aGdkEvent
)->state
));
813 } else if (sLastRepeatableHardwareKeyCode
== xEvent
->xkey
.keycode
) {
814 if (sLastRepeatableKeyTime
== xEvent
->xkey
.time
&&
815 sLastRepeatableHardwareKeyCode
==
817 GetWaitingSynthesizedKeyPressHardwareKeyCode()) {
818 // On some environment, IM may generate duplicated KeyPress event
819 // without any special state flags. In such case, we shouldn't
820 // treat the event as "repeated".
821 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
822 ("FilterEvents(aXEvent={ type=KeyPress, "
823 "xkey={ keycode=0x%08X, state=0x%08X, time=%lu } }, "
824 "aGdkEvent={ state=0x%08X }), "
825 "igored keypress since it must be synthesized by IME",
826 xEvent
->xkey
.keycode
, xEvent
->xkey
.state
, xEvent
->xkey
.time
,
827 reinterpret_cast<GdkEventKey
*>(aGdkEvent
)->state
));
830 sRepeatState
= REPEATING
;
831 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
832 ("FilterEvents(aXEvent={ type=KeyPress, "
833 "xkey={ keycode=0x%08X, state=0x%08X, time=%lu } }, "
834 "aGdkEvent={ state=0x%08X }), "
835 "detected repeating keypress",
836 xEvent
->xkey
.keycode
, xEvent
->xkey
.state
, xEvent
->xkey
.time
,
837 reinterpret_cast<GdkEventKey
*>(aGdkEvent
)->state
));
839 // If a different key is pressed while another key is pressed,
840 // auto repeat system repeats only the last pressed key.
841 // So, setting new keycode and setting repeat state as first key
842 // press should work fine.
843 sRepeatState
= FIRST_PRESS
;
844 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
845 ("FilterEvents(aXEvent={ type=KeyPress, "
846 "xkey={ keycode=0x%08X, state=0x%08X, time=%lu } }, "
847 "aGdkEvent={ state=0x%08X }), "
848 "detected different keypress",
849 xEvent
->xkey
.keycode
, xEvent
->xkey
.state
, xEvent
->xkey
.time
,
850 reinterpret_cast<GdkEventKey
*>(aGdkEvent
)->state
));
852 sLastRepeatableHardwareKeyCode
= xEvent
->xkey
.keycode
;
853 sLastRepeatableKeyTime
= xEvent
->xkey
.time
;
857 if (sLastRepeatableHardwareKeyCode
!= xEvent
->xkey
.keycode
) {
858 // This case means the key release event is caused by
859 // a non-repeatable key such as Shift or a repeatable key that
860 // was pressed before sLastRepeatableHardwareKeyCode was
864 sRepeatState
= NOT_PRESSED
;
865 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
866 ("FilterEvents(aXEvent={ type=KeyRelease, "
867 "xkey={ keycode=0x%08X, state=0x%08X, time=%lu } }, "
868 "aGdkEvent={ state=0x%08X }), "
869 "detected key release",
870 xEvent
->xkey
.keycode
, xEvent
->xkey
.state
, xEvent
->xkey
.time
,
871 reinterpret_cast<GdkEventKey
*>(aGdkEvent
)->state
));
875 // At moving focus, we should reset keyboard repeat state.
876 // Strictly, this causes incorrect behavior. However, this
877 // correctness must be enough for web applications.
878 sRepeatState
= NOT_PRESSED
;
882 KeymapWrapper
* self
= static_cast<KeymapWrapper
*>(aData
);
883 if (xEvent
->type
!= self
->mXKBBaseEventCode
) {
886 XkbEvent
* xkbEvent
= (XkbEvent
*)xEvent
;
887 if (xkbEvent
->any
.xkb_type
!= XkbControlsNotify
||
888 !(xkbEvent
->ctrls
.changed_ctrls
& XkbPerKeyRepeatMask
)) {
891 if (!XGetKeyboardControl(xkbEvent
->any
.display
, &self
->mKeyboardState
)) {
892 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
893 ("%p FilterEvents failed due to failure "
894 "of XGetKeyboardControl(), display=0x%p",
895 self
, xkbEvent
->any
.display
));
901 return GDK_FILTER_CONTINUE
;
904 static void ResetBidiKeyboard() {
905 // Reset the bidi keyboard settings for the new GdkKeymap
906 nsCOMPtr
<nsIBidiKeyboard
> bidiKeyboard
= nsContentUtils::GetBidiKeyboard();
908 bidiKeyboard
->Reset();
910 WidgetUtils::SendBidiKeyboardInfoToContent();
914 void KeymapWrapper::ResetKeyboard() {
915 sInstance
->mInitialized
= false;
920 void KeymapWrapper::OnKeysChanged(GdkKeymap
* aGdkKeymap
,
921 KeymapWrapper
* aKeymapWrapper
) {
922 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
923 ("OnKeysChanged, aGdkKeymap=%p, aKeymapWrapper=%p", aGdkKeymap
,
926 MOZ_ASSERT(sInstance
== aKeymapWrapper
,
927 "This instance must be the singleton instance");
929 // We cannot reintialize here becasue we don't have GdkWindow which is using
930 // the GdkKeymap. We'll reinitialize it when next GetInstance() is called.
935 void KeymapWrapper::OnDirectionChanged(GdkKeymap
* aGdkKeymap
,
936 KeymapWrapper
* aKeymapWrapper
) {
938 // A lot of diretion-changed signal might be fired on switching bidi
939 // keyboard when using both ibus (with arabic layout) and fcitx (with IME).
940 // See https://github.com/fcitx/fcitx/issues/257
942 // Also, when using ibus, switching to IM might not cause this signal.
943 // See https://github.com/ibus/ibus/issues/1848
945 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
946 ("OnDirectionChanged, aGdkKeymap=%p, aKeymapWrapper=%p", aGdkKeymap
,
953 guint
KeymapWrapper::GetCurrentModifierState() {
954 GdkModifierType modifiers
;
955 gdk_display_get_pointer(gdk_display_get_default(), nullptr, nullptr, nullptr,
957 return static_cast<guint
>(modifiers
);
961 bool KeymapWrapper::AreModifiersCurrentlyActive(Modifiers aModifiers
) {
962 guint modifierState
= GetCurrentModifierState();
963 return AreModifiersActive(aModifiers
, modifierState
);
967 bool KeymapWrapper::AreModifiersActive(Modifiers aModifiers
,
968 guint aModifierState
) {
969 NS_ENSURE_TRUE(aModifiers
, false);
971 KeymapWrapper
* keymapWrapper
= GetInstance();
972 for (uint32_t i
= 0; i
< sizeof(Modifier
) * 8 && aModifiers
; i
++) {
973 Modifier modifier
= static_cast<Modifier
>(1 << i
);
974 if (!(aModifiers
& modifier
)) {
977 if (!(aModifierState
& keymapWrapper
->GetModifierMask(modifier
))) {
980 aModifiers
&= ~modifier
;
986 uint32_t KeymapWrapper::ComputeCurrentKeyModifiers() {
987 return ComputeKeyModifiers(GetCurrentModifierState());
991 uint32_t KeymapWrapper::ComputeKeyModifiers(guint aModifierState
) {
992 KeymapWrapper
* keymapWrapper
= GetInstance();
994 uint32_t keyModifiers
= 0;
995 // DOM Meta key should be TRUE only on Mac. We need to discuss this
997 if (keymapWrapper
->AreModifiersActive(SHIFT
, aModifierState
)) {
998 keyModifiers
|= MODIFIER_SHIFT
;
1000 if (keymapWrapper
->AreModifiersActive(CTRL
, aModifierState
)) {
1001 keyModifiers
|= MODIFIER_CONTROL
;
1003 if (keymapWrapper
->AreModifiersActive(ALT
, aModifierState
)) {
1004 keyModifiers
|= MODIFIER_ALT
;
1006 if (keymapWrapper
->AreModifiersActive(META
, aModifierState
)) {
1007 keyModifiers
|= MODIFIER_META
;
1009 if (keymapWrapper
->AreModifiersActive(SUPER
, aModifierState
) ||
1010 keymapWrapper
->AreModifiersActive(HYPER
, aModifierState
)) {
1011 keyModifiers
|= MODIFIER_OS
;
1013 if (keymapWrapper
->AreModifiersActive(LEVEL3
, aModifierState
) ||
1014 keymapWrapper
->AreModifiersActive(LEVEL5
, aModifierState
)) {
1015 keyModifiers
|= MODIFIER_ALTGRAPH
;
1017 if (keymapWrapper
->AreModifiersActive(CAPS_LOCK
, aModifierState
)) {
1018 keyModifiers
|= MODIFIER_CAPSLOCK
;
1020 if (keymapWrapper
->AreModifiersActive(NUM_LOCK
, aModifierState
)) {
1021 keyModifiers
|= MODIFIER_NUMLOCK
;
1023 if (keymapWrapper
->AreModifiersActive(SCROLL_LOCK
, aModifierState
)) {
1024 keyModifiers
|= MODIFIER_SCROLLLOCK
;
1026 return keyModifiers
;
1030 guint
KeymapWrapper::ConvertWidgetModifierToGdkState(
1031 nsIWidget::Modifiers aNativeModifiers
) {
1032 if (!aNativeModifiers
) {
1035 struct ModifierMapEntry
{
1036 nsIWidget::Modifiers mWidgetModifier
;
1039 // TODO: Currently, we don't treat L/R of each modifier on Linux.
1040 // TODO: No proper native modifier for Level5.
1041 static constexpr ModifierMapEntry sModifierMap
[] = {
1042 {nsIWidget::CAPS_LOCK
, Modifier::CAPS_LOCK
},
1043 {nsIWidget::NUM_LOCK
, Modifier::NUM_LOCK
},
1044 {nsIWidget::SHIFT_L
, Modifier::SHIFT
},
1045 {nsIWidget::SHIFT_R
, Modifier::SHIFT
},
1046 {nsIWidget::CTRL_L
, Modifier::CTRL
},
1047 {nsIWidget::CTRL_R
, Modifier::CTRL
},
1048 {nsIWidget::ALT_L
, Modifier::ALT
},
1049 {nsIWidget::ALT_R
, Modifier::ALT
},
1050 {nsIWidget::ALTGRAPH
, Modifier::LEVEL3
},
1051 {nsIWidget::COMMAND_L
, Modifier::SUPER
},
1052 {nsIWidget::COMMAND_R
, Modifier::SUPER
}};
1055 KeymapWrapper
* instance
= GetInstance();
1056 for (const ModifierMapEntry
& entry
: sModifierMap
) {
1057 if (aNativeModifiers
& entry
.mWidgetModifier
) {
1058 state
|= instance
->GetModifierMask(entry
.mModifier
);
1065 void KeymapWrapper::InitInputEvent(WidgetInputEvent
& aInputEvent
,
1066 guint aModifierState
) {
1067 KeymapWrapper
* keymapWrapper
= GetInstance();
1069 aInputEvent
.mModifiers
= ComputeKeyModifiers(aModifierState
);
1071 // Don't log this method for non-important events because e.g., eMouseMove is
1072 // just noisy and there is no reason to log it.
1073 bool doLog
= aInputEvent
.mMessage
!= eMouseMove
;
1075 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Debug
,
1076 ("%p InitInputEvent, aModifierState=0x%08X, "
1077 "aInputEvent={ mMessage=%s, mModifiers=0x%04X (Shift: %s, "
1078 "Control: %s, Alt: %s, "
1079 "Meta: %s, OS: %s, AltGr: %s, "
1080 "CapsLock: %s, NumLock: %s, ScrollLock: %s })",
1081 keymapWrapper
, aModifierState
, ToChar(aInputEvent
.mMessage
),
1082 aInputEvent
.mModifiers
,
1083 GetBoolName(aInputEvent
.mModifiers
& MODIFIER_SHIFT
),
1084 GetBoolName(aInputEvent
.mModifiers
& MODIFIER_CONTROL
),
1085 GetBoolName(aInputEvent
.mModifiers
& MODIFIER_ALT
),
1086 GetBoolName(aInputEvent
.mModifiers
& MODIFIER_META
),
1087 GetBoolName(aInputEvent
.mModifiers
& MODIFIER_OS
),
1088 GetBoolName(aInputEvent
.mModifiers
& MODIFIER_ALTGRAPH
),
1089 GetBoolName(aInputEvent
.mModifiers
& MODIFIER_CAPSLOCK
),
1090 GetBoolName(aInputEvent
.mModifiers
& MODIFIER_NUMLOCK
),
1091 GetBoolName(aInputEvent
.mModifiers
& MODIFIER_SCROLLLOCK
)));
1094 switch (aInputEvent
.mClass
) {
1095 case eMouseEventClass
:
1096 case eMouseScrollEventClass
:
1097 case eWheelEventClass
:
1098 case eDragEventClass
:
1099 case eSimpleGestureEventClass
:
1105 WidgetMouseEventBase
& mouseEvent
= *aInputEvent
.AsMouseEventBase();
1106 mouseEvent
.mButtons
= 0;
1107 if (aModifierState
& GDK_BUTTON1_MASK
) {
1108 mouseEvent
.mButtons
|= MouseButtonsFlag::ePrimaryFlag
;
1110 if (aModifierState
& GDK_BUTTON3_MASK
) {
1111 mouseEvent
.mButtons
|= MouseButtonsFlag::eSecondaryFlag
;
1113 if (aModifierState
& GDK_BUTTON2_MASK
) {
1114 mouseEvent
.mButtons
|= MouseButtonsFlag::eMiddleFlag
;
1119 gKeymapWrapperLog
, LogLevel::Debug
,
1120 ("%p InitInputEvent, aInputEvent has mButtons, "
1121 "aInputEvent.mButtons=0x%04X (Left: %s, Right: %s, Middle: %s, "
1122 "4th (BACK): %s, 5th (FORWARD): %s)",
1123 keymapWrapper
, mouseEvent
.mButtons
,
1124 GetBoolName(mouseEvent
.mButtons
& MouseButtonsFlag::ePrimaryFlag
),
1125 GetBoolName(mouseEvent
.mButtons
& MouseButtonsFlag::eSecondaryFlag
),
1126 GetBoolName(mouseEvent
.mButtons
& MouseButtonsFlag::eMiddleFlag
),
1127 GetBoolName(mouseEvent
.mButtons
& MouseButtonsFlag::e4thFlag
),
1128 GetBoolName(mouseEvent
.mButtons
& MouseButtonsFlag::e5thFlag
)));
1133 uint32_t KeymapWrapper::ComputeDOMKeyCode(const GdkEventKey
* aGdkKeyEvent
) {
1134 // If the keyval indicates it's a modifier key, we should use unshifted
1135 // key's modifier keyval.
1136 guint keyval
= aGdkKeyEvent
->keyval
;
1137 if (GetModifierForGDKKeyval(keyval
)) {
1138 // But if the keyval without modifiers isn't a modifier key, we
1139 // shouldn't use it. E.g., Japanese keyboard layout's
1140 // Shift + Eisu-Toggle key is CapsLock. This is an actual rare case,
1141 // Windows uses different keycode for a physical key for different
1143 guint keyvalWithoutModifier
= GetGDKKeyvalWithoutModifier(aGdkKeyEvent
);
1144 if (GetModifierForGDKKeyval(keyvalWithoutModifier
)) {
1145 keyval
= keyvalWithoutModifier
;
1147 // Note that the modifier keycode and activating or deactivating
1148 // modifier flag may be mismatched, but it's okay. If a DOM key
1149 // event handler is testing a keydown event, it's more likely being
1150 // used to test which key is being pressed than to test which
1151 // modifier will become active. So, if we computed DOM keycode
1152 // from modifier flag which were changing by the physical key, then
1153 // there would be no other way for the user to generate the original
1155 uint32_t DOMKeyCode
= GetDOMKeyCodeFromKeyPairs(keyval
);
1156 NS_ASSERTION(DOMKeyCode
, "All modifier keys must have a DOM keycode");
1160 // If the key isn't printable, let's look at the key pairs.
1161 uint32_t charCode
= GetCharCodeFor(aGdkKeyEvent
);
1163 // Note that any key may be a function key because of some unusual keyboard
1164 // layouts. I.e., even if the pressed key is a printable key of en-US
1165 // keyboard layout, we should expose the function key's keyCode value to
1166 // web apps because web apps should handle the keydown/keyup events as
1167 // inputted by usual keyboard layout. For example, Hatchak keyboard
1168 // maps Tab key to "Digit3" key and Level3 Shift makes it "Backspace".
1169 // In this case, we should expose DOM_VK_BACK_SPACE (8).
1170 uint32_t DOMKeyCode
= GetDOMKeyCodeFromKeyPairs(keyval
);
1172 // XXX If DOMKeyCode is a function key's keyCode value, it might be
1173 // better to consume necessary modifiers. For example, if there is
1174 // no Control Pad section on keyboard like notebook, Delete key is
1175 // available only with Level3 Shift+"Backspace" key if using Hatchak.
1176 // If web apps accept Delete key operation only when no modifiers are
1177 // active, such users cannot use Delete key to do it. However,
1178 // Chromium doesn't consume such necessary modifiers. So, our default
1179 // behavior should keep not touching modifiers for compatibility, but
1180 // it might be better to add a pref to consume necessary modifiers.
1183 // If aGdkKeyEvent cannot be mapped to a DOM keyCode value, we should
1184 // refer keyCode value without modifiers because web apps should be
1185 // able to identify the key as far as possible.
1186 guint keyvalWithoutModifier
= GetGDKKeyvalWithoutModifier(aGdkKeyEvent
);
1187 return GetDOMKeyCodeFromKeyPairs(keyvalWithoutModifier
);
1190 // printable numpad keys should be resolved here.
1192 case GDK_KP_Multiply
:
1193 return NS_VK_MULTIPLY
;
1196 case GDK_KP_Separator
:
1197 return NS_VK_SEPARATOR
;
1198 case GDK_KP_Subtract
:
1199 return NS_VK_SUBTRACT
;
1200 case GDK_KP_Decimal
:
1201 return NS_VK_DECIMAL
;
1203 return NS_VK_DIVIDE
;
1205 return NS_VK_NUMPAD0
;
1207 return NS_VK_NUMPAD1
;
1209 return NS_VK_NUMPAD2
;
1211 return NS_VK_NUMPAD3
;
1213 return NS_VK_NUMPAD4
;
1215 return NS_VK_NUMPAD5
;
1217 return NS_VK_NUMPAD6
;
1219 return NS_VK_NUMPAD7
;
1221 return NS_VK_NUMPAD8
;
1223 return NS_VK_NUMPAD9
;
1226 KeymapWrapper
* keymapWrapper
= GetInstance();
1228 // Ignore all modifier state except NumLock.
1230 (aGdkKeyEvent
->state
& keymapWrapper
->GetModifierMask(NUM_LOCK
));
1232 // Basically, we should use unmodified character for deciding our keyCode.
1233 uint32_t unmodifiedChar
= keymapWrapper
->GetCharCodeFor(
1234 aGdkKeyEvent
, baseState
, aGdkKeyEvent
->group
);
1235 if (IsBasicLatinLetterOrNumeral(unmodifiedChar
)) {
1236 // If the unmodified character is an ASCII alphabet or an ASCII
1237 // numeric, it's the best hint for deciding our keyCode.
1238 return WidgetUtils::ComputeKeyCodeFromChar(unmodifiedChar
);
1241 // If the unmodified character is not an ASCII character, that means we
1242 // couldn't find the hint. We should reset it.
1243 if (!IsPrintableASCIICharacter(unmodifiedChar
)) {
1247 // Retry with shifted keycode.
1248 guint shiftState
= (baseState
| keymapWrapper
->GetModifierMask(SHIFT
));
1249 uint32_t shiftedChar
= keymapWrapper
->GetCharCodeFor(aGdkKeyEvent
, shiftState
,
1250 aGdkKeyEvent
->group
);
1251 if (IsBasicLatinLetterOrNumeral(shiftedChar
)) {
1252 // A shifted character can be an ASCII alphabet on Hebrew keyboard
1253 // layout. And also shifted character can be an ASCII numeric on
1254 // AZERTY keyboad layout. Then, it's a good hint for deciding our
1256 return WidgetUtils::ComputeKeyCodeFromChar(shiftedChar
);
1259 // If the shifted unmodified character isn't an ASCII character, we should
1261 if (!IsPrintableASCIICharacter(shiftedChar
)) {
1265 // If current keyboard layout isn't ASCII alphabet inputtable layout,
1266 // look for ASCII alphabet inputtable keyboard layout. If the key
1267 // inputs an ASCII alphabet or an ASCII numeric, we should use it
1268 // for deciding our keyCode.
1269 uint32_t unmodCharLatin
= 0;
1270 uint32_t shiftedCharLatin
= 0;
1271 if (!keymapWrapper
->IsLatinGroup(aGdkKeyEvent
->group
)) {
1272 gint minGroup
= keymapWrapper
->GetFirstLatinGroup();
1273 if (minGroup
>= 0) {
1275 keymapWrapper
->GetCharCodeFor(aGdkKeyEvent
, baseState
, minGroup
);
1276 if (IsBasicLatinLetterOrNumeral(unmodCharLatin
)) {
1277 // If the unmodified character is an ASCII alphabet or
1278 // an ASCII numeric, we should use it for the keyCode.
1279 return WidgetUtils::ComputeKeyCodeFromChar(unmodCharLatin
);
1281 // If the unmodified character in the alternative ASCII capable
1282 // keyboard layout isn't an ASCII character, that means we couldn't
1283 // find the hint. We should reset it.
1284 if (!IsPrintableASCIICharacter(unmodCharLatin
)) {
1288 keymapWrapper
->GetCharCodeFor(aGdkKeyEvent
, shiftState
, minGroup
);
1289 if (IsBasicLatinLetterOrNumeral(shiftedCharLatin
)) {
1290 // If the shifted character is an ASCII alphabet or an ASCII
1291 // numeric, we should use it for the keyCode.
1292 return WidgetUtils::ComputeKeyCodeFromChar(shiftedCharLatin
);
1294 // If the shifted unmodified character in the alternative ASCII
1295 // capable keyboard layout isn't an ASCII character, we should
1297 if (!IsPrintableASCIICharacter(shiftedCharLatin
)) {
1298 shiftedCharLatin
= 0;
1303 // If the key itself or with Shift state on active keyboard layout produces
1304 // an ASCII punctuation character, we should decide keyCode value with it.
1305 if (unmodifiedChar
|| shiftedChar
) {
1306 return WidgetUtils::ComputeKeyCodeFromChar(unmodifiedChar
? unmodifiedChar
1310 // If the key itself or with Shift state on alternative ASCII capable
1311 // keyboard layout produces an ASCII punctuation character, we should
1312 // decide keyCode value with it. Note that We've returned 0 for long
1313 // time if keyCode isn't for an alphabet keys or a numeric key even in
1314 // alternative ASCII capable keyboard layout because we decided that we
1315 // should avoid setting same keyCode value to 2 or more keys since active
1316 // keyboard layout may have a key to input the punctuation with different
1317 // key. However, setting keyCode to 0 makes some web applications which
1318 // are aware of neither KeyboardEvent.key nor KeyboardEvent.code not work
1319 // with Firefox when user selects non-ASCII capable keyboard layout such
1320 // as Russian and Thai. So, if alternative ASCII capable keyboard layout
1321 // has keyCode value for the key, we should use it. In other words, this
1322 // behavior means that non-ASCII capable keyboard layout overrides some
1323 // keys' keyCode value only if the key produces ASCII character by itself
1324 // or with Shift key.
1325 if (unmodCharLatin
|| shiftedCharLatin
) {
1326 return WidgetUtils::ComputeKeyCodeFromChar(
1327 unmodCharLatin
? unmodCharLatin
: shiftedCharLatin
);
1330 // Otherwise, let's decide keyCode value from the hardware_keycode
1331 // value on major keyboard layout.
1332 CodeNameIndex code
= ComputeDOMCodeNameIndex(aGdkKeyEvent
);
1333 return WidgetKeyboardEvent::GetFallbackKeyCodeOfPunctuationKey(code
);
1336 KeyNameIndex
KeymapWrapper::ComputeDOMKeyNameIndex(
1337 const GdkEventKey
* aGdkKeyEvent
) {
1338 switch (aGdkKeyEvent
->keyval
) {
1339 #define NS_NATIVE_KEY_TO_DOM_KEY_NAME_INDEX(aNativeKey, aKeyNameIndex) \
1341 return aKeyNameIndex;
1343 #include "NativeKeyToDOMKeyName.h"
1345 #undef NS_NATIVE_KEY_TO_DOM_KEY_NAME_INDEX
1351 return KEY_NAME_INDEX_Unidentified
;
1355 CodeNameIndex
KeymapWrapper::ComputeDOMCodeNameIndex(
1356 const GdkEventKey
* aGdkKeyEvent
) {
1357 switch (aGdkKeyEvent
->hardware_keycode
) {
1358 #define NS_NATIVE_KEY_TO_DOM_CODE_NAME_INDEX(aNativeKey, aCodeNameIndex) \
1360 return aCodeNameIndex;
1362 #include "NativeKeyToDOMCodeName.h"
1364 #undef NS_NATIVE_KEY_TO_DOM_CODE_NAME_INDEX
1370 return CODE_NAME_INDEX_UNKNOWN
;
1374 bool KeymapWrapper::DispatchKeyDownOrKeyUpEvent(nsWindow
* aWindow
,
1375 GdkEventKey
* aGdkKeyEvent
,
1376 bool aIsProcessedByIME
,
1377 bool* aIsCancelled
) {
1378 MOZ_ASSERT(aIsCancelled
, "aIsCancelled must not be nullptr");
1380 *aIsCancelled
= false;
1382 if (aGdkKeyEvent
->type
== GDK_KEY_PRESS
&& aGdkKeyEvent
->keyval
== GDK_Tab
&&
1383 AreModifiersActive(CTRL
| ALT
, aGdkKeyEvent
->state
)) {
1384 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
1385 (" DispatchKeyDownOrKeyUpEvent(), didn't dispatch keyboard events "
1386 "because it's Ctrl + Alt + Tab"));
1390 EventMessage message
=
1391 aGdkKeyEvent
->type
== GDK_KEY_PRESS
? eKeyDown
: eKeyUp
;
1392 WidgetKeyboardEvent
keyEvent(true, message
, aWindow
);
1393 KeymapWrapper::InitKeyEvent(keyEvent
, aGdkKeyEvent
, aIsProcessedByIME
);
1394 return DispatchKeyDownOrKeyUpEvent(aWindow
, keyEvent
, aIsCancelled
);
1398 bool KeymapWrapper::DispatchKeyDownOrKeyUpEvent(
1399 nsWindow
* aWindow
, WidgetKeyboardEvent
& aKeyboardEvent
,
1400 bool* aIsCancelled
) {
1401 MOZ_ASSERT(aIsCancelled
, "aIsCancelled must not be nullptr");
1403 *aIsCancelled
= false;
1405 RefPtr
<TextEventDispatcher
> dispatcher
= aWindow
->GetTextEventDispatcher();
1406 nsresult rv
= dispatcher
->BeginNativeInputTransaction();
1407 if (NS_WARN_IF(NS_FAILED(rv
))) {
1408 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Error
,
1409 (" DispatchKeyDownOrKeyUpEvent(), stopped dispatching %s event "
1410 "because of failed to initialize TextEventDispatcher",
1411 ToChar(aKeyboardEvent
.mMessage
)));
1415 nsEventStatus status
= nsEventStatus_eIgnore
;
1416 bool dispatched
= dispatcher
->DispatchKeyboardEvent(
1417 aKeyboardEvent
.mMessage
, aKeyboardEvent
, status
, nullptr);
1418 *aIsCancelled
= (status
== nsEventStatus_eConsumeNoDefault
);
1423 bool KeymapWrapper::MaybeDispatchContextMenuEvent(nsWindow
* aWindow
,
1424 const GdkEventKey
* aEvent
) {
1425 KeyNameIndex keyNameIndex
= ComputeDOMKeyNameIndex(aEvent
);
1427 // Shift+F10 and ContextMenu should cause eContextMenu event.
1428 if (keyNameIndex
!= KEY_NAME_INDEX_F10
&&
1429 keyNameIndex
!= KEY_NAME_INDEX_ContextMenu
) {
1433 WidgetMouseEvent
contextMenuEvent(true, eContextMenu
, aWindow
,
1434 WidgetMouseEvent::eReal
,
1435 WidgetMouseEvent::eContextMenuKey
);
1437 contextMenuEvent
.mRefPoint
= LayoutDeviceIntPoint(0, 0);
1438 contextMenuEvent
.AssignEventTime(aWindow
->GetWidgetEventTime(aEvent
->time
));
1439 contextMenuEvent
.mClickCount
= 1;
1440 KeymapWrapper::InitInputEvent(contextMenuEvent
, aEvent
->state
);
1442 if (contextMenuEvent
.IsControl() || contextMenuEvent
.IsMeta() ||
1443 contextMenuEvent
.IsAlt()) {
1447 // If the key is ContextMenu, then an eContextMenu mouse event is
1448 // dispatched regardless of the state of the Shift modifier. When it is
1449 // pressed without the Shift modifier, a web page can prevent the default
1450 // context menu action. When pressed with the Shift modifier, the web page
1451 // cannot prevent the default context menu action.
1452 // (PresShell::HandleEventInternal() sets mOnlyChromeDispatch to true.)
1454 // If the key is F10, it needs Shift state because Shift+F10 is well-known
1455 // shortcut key on Linux. However, eContextMenu with Shift state is
1456 // special. It won't fire "contextmenu" event in the web content for
1457 // blocking web page to prevent its default. Therefore, this combination
1458 // should work same as ContextMenu key.
1459 // XXX Should we allow to block web page to prevent its default with
1460 // Ctrl+Shift+F10 or Alt+Shift+F10 instead?
1461 if (keyNameIndex
== KEY_NAME_INDEX_F10
) {
1462 if (!contextMenuEvent
.IsShift()) {
1465 contextMenuEvent
.mModifiers
&= ~MODIFIER_SHIFT
;
1468 aWindow
->DispatchInputEvent(&contextMenuEvent
);
1473 void KeymapWrapper::HandleKeyPressEvent(nsWindow
* aWindow
,
1474 GdkEventKey
* aGdkKeyEvent
) {
1475 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
1476 ("HandleKeyPressEvent(aWindow=%p, aGdkKeyEvent={ type=%s, "
1477 "keyval=%s(0x%X), state=0x%08X, hardware_keycode=0x%08X, "
1478 "time=%u, is_modifier=%s })",
1480 ((aGdkKeyEvent
->type
== GDK_KEY_PRESS
) ? "GDK_KEY_PRESS"
1481 : "GDK_KEY_RELEASE"),
1482 gdk_keyval_name(aGdkKeyEvent
->keyval
), aGdkKeyEvent
->keyval
,
1483 aGdkKeyEvent
->state
, aGdkKeyEvent
->hardware_keycode
,
1484 aGdkKeyEvent
->time
, GetBoolName(aGdkKeyEvent
->is_modifier
)));
1486 // if we are in the middle of composing text, XIM gets to see it
1487 // before mozilla does.
1488 // FYI: Don't dispatch keydown event before notifying IME of the event
1489 // because IME may send a key event synchronously and consume the
1491 bool IMEWasEnabled
= false;
1492 KeyHandlingState handlingState
= KeyHandlingState::eNotHandled
;
1493 RefPtr
<IMContextWrapper
> imContext
= aWindow
->GetIMContext();
1495 IMEWasEnabled
= imContext
->IsEnabled();
1496 handlingState
= imContext
->OnKeyEvent(aWindow
, aGdkKeyEvent
);
1497 if (handlingState
== KeyHandlingState::eHandled
) {
1498 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
1499 (" HandleKeyPressEvent(), the event was handled by "
1500 "IMContextWrapper"));
1505 // work around for annoying things.
1506 if (aGdkKeyEvent
->keyval
== GDK_Tab
&&
1507 AreModifiersActive(CTRL
| ALT
, aGdkKeyEvent
->state
)) {
1508 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
1509 (" HandleKeyPressEvent(), didn't dispatch keyboard events "
1510 "because it's Ctrl + Alt + Tab"));
1514 // Dispatch keydown event always. At auto repeating, we should send
1515 // KEYDOWN -> KEYPRESS -> KEYDOWN -> KEYPRESS ... -> KEYUP
1516 // However, old distributions (e.g., Ubuntu 9.10) sent native key
1517 // release event, so, on such platform, the DOM events will be:
1518 // KEYDOWN -> KEYPRESS -> KEYUP -> KEYDOWN -> KEYPRESS -> KEYUP...
1520 bool isKeyDownCancelled
= false;
1521 if (handlingState
== KeyHandlingState::eNotHandled
) {
1522 if (DispatchKeyDownOrKeyUpEvent(aWindow
, aGdkKeyEvent
, false,
1523 &isKeyDownCancelled
) &&
1524 (MOZ_UNLIKELY(aWindow
->IsDestroyed()) || isKeyDownCancelled
)) {
1525 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
1526 (" HandleKeyPressEvent(), dispatched eKeyDown event and "
1527 "stopped handling the event because %s",
1528 aWindow
->IsDestroyed() ? "the window has been destroyed"
1529 : "the event was consumed"));
1532 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
1533 (" HandleKeyPressEvent(), dispatched eKeyDown event and "
1534 "it wasn't consumed"));
1535 handlingState
= KeyHandlingState::eNotHandledButEventDispatched
;
1538 // If a keydown event handler causes to enable IME, i.e., it moves
1539 // focus from IME unusable content to IME usable editor, we should
1540 // send the native key event to IME for the first input on the editor.
1541 imContext
= aWindow
->GetIMContext();
1542 if (!IMEWasEnabled
&& imContext
&& imContext
->IsEnabled()) {
1543 // Notice our keydown event was already dispatched. This prevents
1544 // unnecessary DOM keydown event in the editor.
1545 handlingState
= imContext
->OnKeyEvent(aWindow
, aGdkKeyEvent
, true);
1546 if (handlingState
== KeyHandlingState::eHandled
) {
1547 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
1548 (" HandleKeyPressEvent(), the event was handled by "
1549 "IMContextWrapper which was enabled by the preceding eKeyDown "
1555 // Look for specialized app-command keys
1556 switch (aGdkKeyEvent
->keyval
) {
1558 aWindow
->DispatchCommandEvent(nsGkAtoms::Back
);
1559 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
1560 (" HandleKeyPressEvent(), dispatched \"Back\" command event"));
1563 aWindow
->DispatchCommandEvent(nsGkAtoms::Forward
);
1564 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
1565 (" HandleKeyPressEvent(), dispatched \"Forward\" command "
1570 aWindow
->DispatchCommandEvent(nsGkAtoms::Reload
);
1573 aWindow
->DispatchCommandEvent(nsGkAtoms::Stop
);
1574 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
1575 (" HandleKeyPressEvent(), dispatched \"Stop\" command event"));
1578 aWindow
->DispatchCommandEvent(nsGkAtoms::Search
);
1579 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
1580 (" HandleKeyPressEvent(), dispatched \"Search\" command event"));
1583 aWindow
->DispatchCommandEvent(nsGkAtoms::Bookmarks
);
1584 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
1585 (" HandleKeyPressEvent(), dispatched \"Bookmarks\" command "
1589 aWindow
->DispatchCommandEvent(nsGkAtoms::Home
);
1592 case GDK_F16
: // F16, F20, F18, F14 are old keysyms for Copy Cut Paste Undo
1593 aWindow
->DispatchContentCommandEvent(eContentCommandCopy
);
1594 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
1595 (" HandleKeyPressEvent(), dispatched \"Copy\" content command "
1600 aWindow
->DispatchContentCommandEvent(eContentCommandCut
);
1601 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
1602 (" HandleKeyPressEvent(), dispatched \"Cut\" content command "
1607 aWindow
->DispatchContentCommandEvent(eContentCommandPaste
);
1608 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
1609 (" HandleKeyPressEvent(), dispatched \"Paste\" content command "
1613 aWindow
->DispatchContentCommandEvent(eContentCommandRedo
);
1617 aWindow
->DispatchContentCommandEvent(eContentCommandUndo
);
1618 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
1619 (" HandleKeyPressEvent(), dispatched \"Undo\" content command "
1626 // before we dispatch a key, check if it's the context menu key.
1627 // If so, send a context menu key event instead.
1628 if (MaybeDispatchContextMenuEvent(aWindow
, aGdkKeyEvent
)) {
1629 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
1630 (" HandleKeyPressEvent(), stopped dispatching eKeyPress event "
1631 "because eContextMenu event was dispatched"));
1635 RefPtr
<TextEventDispatcher
> textEventDispatcher
=
1636 aWindow
->GetTextEventDispatcher();
1637 nsresult rv
= textEventDispatcher
->BeginNativeInputTransaction();
1638 if (NS_WARN_IF(NS_FAILED(rv
))) {
1639 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Error
,
1640 (" HandleKeyPressEvent(), stopped dispatching eKeyPress event "
1641 "because of failed to initialize TextEventDispatcher"));
1645 // If the character code is in the BMP, send the key press event.
1646 // Otherwise, send a compositionchange event with the equivalent UTF-16
1648 // TODO: Investigate other browser's behavior in this case because
1649 // this hack is odd for UI Events.
1650 WidgetKeyboardEvent
keypressEvent(true, eKeyPress
, aWindow
);
1651 KeymapWrapper::InitKeyEvent(keypressEvent
, aGdkKeyEvent
, false);
1652 nsEventStatus status
= nsEventStatus_eIgnore
;
1653 if (keypressEvent
.mKeyNameIndex
!= KEY_NAME_INDEX_USE_STRING
||
1654 keypressEvent
.mKeyValue
.Length() == 1) {
1655 if (textEventDispatcher
->MaybeDispatchKeypressEvents(keypressEvent
, status
,
1657 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
1658 (" HandleKeyPressEvent(), dispatched eKeyPress event "
1660 GetStatusName(status
)));
1662 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
1663 (" HandleKeyPressEvent(), didn't dispatch eKeyPress event "
1665 GetStatusName(status
)));
1668 WidgetEventTime eventTime
= aWindow
->GetWidgetEventTime(aGdkKeyEvent
->time
);
1669 textEventDispatcher
->CommitComposition(status
, &keypressEvent
.mKeyValue
,
1671 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
1672 (" HandleKeyPressEvent(), dispatched a set of composition "
1678 bool KeymapWrapper::HandleKeyReleaseEvent(nsWindow
* aWindow
,
1679 GdkEventKey
* aGdkKeyEvent
) {
1680 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
1681 ("HandleKeyReleaseEvent(aWindow=%p, aGdkKeyEvent={ type=%s, "
1682 "keyval=%s(0x%X), state=0x%08X, hardware_keycode=0x%08X, "
1683 "time=%u, is_modifier=%s })",
1685 ((aGdkKeyEvent
->type
== GDK_KEY_PRESS
) ? "GDK_KEY_PRESS"
1686 : "GDK_KEY_RELEASE"),
1687 gdk_keyval_name(aGdkKeyEvent
->keyval
), aGdkKeyEvent
->keyval
,
1688 aGdkKeyEvent
->state
, aGdkKeyEvent
->hardware_keycode
,
1689 aGdkKeyEvent
->time
, GetBoolName(aGdkKeyEvent
->is_modifier
)));
1691 RefPtr
<IMContextWrapper
> imContext
= aWindow
->GetIMContext();
1693 KeyHandlingState handlingState
=
1694 imContext
->OnKeyEvent(aWindow
, aGdkKeyEvent
);
1695 if (handlingState
!= KeyHandlingState::eNotHandled
) {
1696 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
1697 (" HandleKeyReleaseEvent(), the event was handled by "
1698 "IMContextWrapper"));
1703 bool isCancelled
= false;
1704 if (NS_WARN_IF(!DispatchKeyDownOrKeyUpEvent(aWindow
, aGdkKeyEvent
, false,
1706 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Error
,
1707 (" HandleKeyReleaseEvent(), didn't dispatch eKeyUp event"));
1711 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
1712 (" HandleKeyReleaseEvent(), dispatched eKeyUp event "
1714 GetBoolName(isCancelled
)));
1719 void KeymapWrapper::InitKeyEvent(WidgetKeyboardEvent
& aKeyEvent
,
1720 GdkEventKey
* aGdkKeyEvent
,
1721 bool aIsProcessedByIME
) {
1723 !aIsProcessedByIME
|| aKeyEvent
.mMessage
!= eKeyPress
,
1724 "If the key event is handled by IME, keypress event shouldn't be fired");
1726 KeymapWrapper
* keymapWrapper
= GetInstance();
1728 aKeyEvent
.mCodeNameIndex
= ComputeDOMCodeNameIndex(aGdkKeyEvent
);
1729 MOZ_ASSERT(aKeyEvent
.mCodeNameIndex
!= CODE_NAME_INDEX_USE_STRING
);
1730 aKeyEvent
.mKeyNameIndex
=
1731 aIsProcessedByIME
? KEY_NAME_INDEX_Process
1732 : keymapWrapper
->ComputeDOMKeyNameIndex(aGdkKeyEvent
);
1733 if (aKeyEvent
.mKeyNameIndex
== KEY_NAME_INDEX_Unidentified
) {
1734 uint32_t charCode
= GetCharCodeFor(aGdkKeyEvent
);
1736 charCode
= keymapWrapper
->GetUnmodifiedCharCodeFor(aGdkKeyEvent
);
1739 aKeyEvent
.mKeyNameIndex
= KEY_NAME_INDEX_USE_STRING
;
1740 MOZ_ASSERT(aKeyEvent
.mKeyValue
.IsEmpty(),
1741 "Uninitialized mKeyValue must be empty");
1742 AppendUCS4ToUTF16(charCode
, aKeyEvent
.mKeyValue
);
1746 if (aIsProcessedByIME
) {
1747 aKeyEvent
.mKeyCode
= NS_VK_PROCESSKEY
;
1748 } else if (aKeyEvent
.mKeyNameIndex
!= KEY_NAME_INDEX_USE_STRING
||
1749 aKeyEvent
.mMessage
!= eKeyPress
) {
1750 aKeyEvent
.mKeyCode
= ComputeDOMKeyCode(aGdkKeyEvent
);
1752 aKeyEvent
.mKeyCode
= 0;
1755 // NOTE: The state of given key event indicates adjacent state of
1756 // modifier keys. E.g., even if the event is Shift key press event,
1757 // the bit for Shift is still false. By the same token, even if the
1758 // event is Shift key release event, the bit for Shift is still true.
1759 // Unfortunately, gdk_keyboard_get_modifiers() returns current modifier
1760 // state. It means if there're some pending modifier key press or
1761 // key release events, the result isn't what we want.
1762 guint modifierState
= aGdkKeyEvent
->state
;
1763 GdkDisplay
* gdkDisplay
= gdk_display_get_default();
1764 if (aGdkKeyEvent
->is_modifier
&& GdkIsX11Display(gdkDisplay
)) {
1765 Display
* display
= gdk_x11_display_get_xdisplay(gdkDisplay
);
1766 if (XEventsQueued(display
, QueuedAfterReading
)) {
1768 XPeekEvent(display
, &nextEvent
);
1769 if (nextEvent
.type
== keymapWrapper
->mXKBBaseEventCode
) {
1770 XkbEvent
* XKBEvent
= (XkbEvent
*)&nextEvent
;
1771 if (XKBEvent
->any
.xkb_type
== XkbStateNotify
) {
1772 XkbStateNotifyEvent
* stateNotifyEvent
=
1773 (XkbStateNotifyEvent
*)XKBEvent
;
1774 modifierState
&= ~0xFF;
1775 modifierState
|= stateNotifyEvent
->lookup_mods
;
1780 InitInputEvent(aKeyEvent
, modifierState
);
1782 switch (aGdkKeyEvent
->keyval
) {
1789 aKeyEvent
.mLocation
= eKeyLocationLeft
;
1798 aKeyEvent
.mLocation
= eKeyLocationRight
;
1823 case GDK_KP_Prior
: // same as GDK_KP_Page_Up
1824 case GDK_KP_Next
: // same as GDK_KP_Page_Down
1830 case GDK_KP_Multiply
:
1832 case GDK_KP_Separator
:
1833 case GDK_KP_Subtract
:
1834 case GDK_KP_Decimal
:
1836 aKeyEvent
.mLocation
= eKeyLocationNumpad
;
1840 aKeyEvent
.mLocation
= eKeyLocationStandard
;
1844 // The transformations above and in gdk for the keyval are not invertible
1845 // so link to the GdkEvent (which will vanish soon after return from the
1846 // event callback) to give plugins access to hardware_keycode and state.
1847 // (An XEvent would be nice but the GdkEvent is good enough.)
1848 aKeyEvent
.mPluginEvent
.Copy(*aGdkKeyEvent
);
1849 aKeyEvent
.mTime
= aGdkKeyEvent
->time
;
1850 aKeyEvent
.mNativeKeyEvent
= static_cast<void*>(aGdkKeyEvent
);
1851 aKeyEvent
.mIsRepeat
=
1852 sRepeatState
== REPEATING
&&
1853 aGdkKeyEvent
->hardware_keycode
== sLastRepeatableHardwareKeyCode
;
1856 gKeymapWrapperLog
, LogLevel::Info
,
1857 ("%p InitKeyEvent, modifierState=0x%08X "
1858 "aKeyEvent={ mMessage=%s, isShift=%s, isControl=%s, "
1859 "isAlt=%s, isMeta=%s , mKeyCode=0x%02X, mCharCode=%s, "
1860 "mKeyNameIndex=%s, mKeyValue=%s, mCodeNameIndex=%s, mCodeValue=%s, "
1861 "mLocation=%s, mIsRepeat=%s }",
1862 keymapWrapper
, modifierState
, ToChar(aKeyEvent
.mMessage
),
1863 GetBoolName(aKeyEvent
.IsShift()), GetBoolName(aKeyEvent
.IsControl()),
1864 GetBoolName(aKeyEvent
.IsAlt()), GetBoolName(aKeyEvent
.IsMeta()),
1866 GetCharacterCodeName(static_cast<char16_t
>(aKeyEvent
.mCharCode
)).get(),
1867 ToString(aKeyEvent
.mKeyNameIndex
).get(),
1868 GetCharacterCodeNames(aKeyEvent
.mKeyValue
).get(),
1869 ToString(aKeyEvent
.mCodeNameIndex
).get(),
1870 GetCharacterCodeNames(aKeyEvent
.mCodeValue
).get(),
1871 GetKeyLocationName(aKeyEvent
.mLocation
).get(),
1872 GetBoolName(aKeyEvent
.mIsRepeat
)));
1876 uint32_t KeymapWrapper::GetCharCodeFor(const GdkEventKey
* aGdkKeyEvent
) {
1877 // Anything above 0xf000 is considered a non-printable
1878 // Exception: directly encoded UCS characters
1879 if (aGdkKeyEvent
->keyval
> 0xf000 &&
1880 (aGdkKeyEvent
->keyval
& 0xff000000) != 0x01000000) {
1881 // Keypad keys are an exception: they return a value different
1882 // from their non-keypad equivalents, but mozilla doesn't distinguish.
1883 switch (aGdkKeyEvent
->keyval
) {
1888 case GDK_KP_Multiply
:
1892 case GDK_KP_Separator
:
1894 case GDK_KP_Subtract
:
1896 case GDK_KP_Decimal
:
1921 return 0; // non-printables
1925 static const long MAX_UNICODE
= 0x10FFFF;
1927 // we're supposedly printable, let's try to convert
1928 long ucs
= keysym2ucs(aGdkKeyEvent
->keyval
);
1929 if ((ucs
!= -1) && (ucs
< MAX_UNICODE
)) {
1933 // I guess we couldn't convert
1937 uint32_t KeymapWrapper::GetCharCodeFor(const GdkEventKey
* aGdkKeyEvent
,
1938 guint aModifierState
, gint aGroup
) {
1940 if (!gdk_keymap_translate_keyboard_state(
1941 mGdkKeymap
, aGdkKeyEvent
->hardware_keycode
,
1942 GdkModifierType(aModifierState
), aGroup
, &keyval
, nullptr, nullptr,
1946 GdkEventKey tmpEvent
= *aGdkKeyEvent
;
1947 tmpEvent
.state
= aModifierState
;
1948 tmpEvent
.keyval
= keyval
;
1949 tmpEvent
.group
= aGroup
;
1950 return GetCharCodeFor(&tmpEvent
);
1953 uint32_t KeymapWrapper::GetUnmodifiedCharCodeFor(
1954 const GdkEventKey
* aGdkKeyEvent
) {
1955 guint state
= aGdkKeyEvent
->state
&
1956 (GetModifierMask(SHIFT
) | GetModifierMask(CAPS_LOCK
) |
1957 GetModifierMask(NUM_LOCK
) | GetModifierMask(SCROLL_LOCK
) |
1958 GetModifierMask(LEVEL3
) | GetModifierMask(LEVEL5
));
1960 GetCharCodeFor(aGdkKeyEvent
, GdkModifierType(state
), aGdkKeyEvent
->group
);
1964 // If no character is mapped to the key when Level3 Shift or Level5 Shift
1965 // is active, let's return a character which is inputted by the key without
1966 // Level3 nor Level5 Shift.
1967 guint stateWithoutAltGraph
=
1968 state
& ~(GetModifierMask(LEVEL3
) | GetModifierMask(LEVEL5
));
1969 if (state
== stateWithoutAltGraph
) {
1972 return GetCharCodeFor(aGdkKeyEvent
, GdkModifierType(stateWithoutAltGraph
),
1973 aGdkKeyEvent
->group
);
1976 gint
KeymapWrapper::GetKeyLevel(GdkEventKey
* aGdkKeyEvent
) {
1978 if (!gdk_keymap_translate_keyboard_state(
1979 mGdkKeymap
, aGdkKeyEvent
->hardware_keycode
,
1980 GdkModifierType(aGdkKeyEvent
->state
), aGdkKeyEvent
->group
, nullptr,
1981 nullptr, &level
, nullptr)) {
1987 gint
KeymapWrapper::GetFirstLatinGroup() {
1991 if (gdk_keymap_get_entries_for_keyval(mGdkKeymap
, GDK_a
, &keys
, &count
)) {
1992 // find the minimum number group for latin inputtable layout
1993 for (gint i
= 0; i
< count
&& minGroup
!= 0; ++i
) {
1994 if (keys
[i
].level
!= 0 && keys
[i
].level
!= 1) {
1997 if (minGroup
>= 0 && keys
[i
].group
> minGroup
) {
2000 minGroup
= keys
[i
].group
;
2007 bool KeymapWrapper::IsLatinGroup(guint8 aGroup
) {
2010 bool result
= false;
2011 if (gdk_keymap_get_entries_for_keyval(mGdkKeymap
, GDK_a
, &keys
, &count
)) {
2012 for (gint i
= 0; i
< count
; ++i
) {
2013 if (keys
[i
].level
!= 0 && keys
[i
].level
!= 1) {
2016 if (keys
[i
].group
== aGroup
) {
2026 bool KeymapWrapper::IsAutoRepeatableKey(guint aHardwareKeyCode
) {
2027 uint8_t indexOfArray
= aHardwareKeyCode
/ 8;
2028 MOZ_ASSERT(indexOfArray
< ArrayLength(mKeyboardState
.auto_repeats
),
2030 char bitMask
= 1 << (aHardwareKeyCode
% 8);
2031 return (mKeyboardState
.auto_repeats
[indexOfArray
] & bitMask
) != 0;
2035 bool KeymapWrapper::IsBasicLatinLetterOrNumeral(uint32_t aCharCode
) {
2036 return (aCharCode
>= 'a' && aCharCode
<= 'z') ||
2037 (aCharCode
>= 'A' && aCharCode
<= 'Z') ||
2038 (aCharCode
>= '0' && aCharCode
<= '9');
2042 guint
KeymapWrapper::GetGDKKeyvalWithoutModifier(
2043 const GdkEventKey
* aGdkKeyEvent
) {
2044 KeymapWrapper
* keymapWrapper
= GetInstance();
2046 (aGdkKeyEvent
->state
& keymapWrapper
->GetModifierMask(NUM_LOCK
));
2048 if (!gdk_keymap_translate_keyboard_state(
2049 keymapWrapper
->mGdkKeymap
, aGdkKeyEvent
->hardware_keycode
,
2050 GdkModifierType(state
), aGdkKeyEvent
->group
, &keyval
, nullptr,
2051 nullptr, nullptr)) {
2058 uint32_t KeymapWrapper::GetDOMKeyCodeFromKeyPairs(guint aGdkKeyval
) {
2059 switch (aGdkKeyval
) {
2061 return NS_VK_CANCEL
;
2065 case GDK_ISO_Left_Tab
:
2070 return NS_VK_RETURN
;
2073 case GDK_Shift_Lock
:
2077 return NS_VK_CONTROL
;
2085 // Assume that Super or Hyper is always mapped to physical Win key.
2092 // GTK's AltGraph key is similar to Mac's Option (Alt) key. However,
2093 // unfortunately, browsers on Mac are using NS_VK_ALT for it even though
2094 // it's really different from Alt key on Windows.
2095 // On the other hand, GTK's AltGrapsh keys are really different from
2096 // Alt key. However, there is no AltGrapsh key on Windows. On Windows,
2097 // both Ctrl and Alt keys are pressed internally when AltGr key is
2098 // pressed. For some languages' users, AltGraph key is important, so,
2099 // web applications on such locale may want to know AltGraph key press.
2100 // Therefore, we should map AltGr keycode for them only on GTK.
2101 case GDK_ISO_Level3_Shift
:
2102 case GDK_ISO_Level5_Shift
:
2103 // We assume that Mode_switch is always used for level3 shift.
2104 case GDK_Mode_switch
:
2110 return NS_VK_CAPS_LOCK
;
2112 case GDK_Kana_Shift
:
2115 return NS_VK_HANGUL
;
2116 // case GDK_XXX: return NS_VK_JUNJA;
2117 // case GDK_XXX: return NS_VK_FINAL;
2118 case GDK_Hangul_Hanja
:
2123 return NS_VK_ESCAPE
;
2125 return NS_VK_CONVERT
;
2127 return NS_VK_NONCONVERT
;
2128 // case GDK_XXX: return NS_VK_ACCEPT;
2129 // case GDK_XXX: return NS_VK_MODECHANGE;
2131 return NS_VK_PAGE_UP
;
2133 return NS_VK_PAGE_DOWN
;
2147 return NS_VK_SELECT
;
2151 return NS_VK_EXECUTE
;
2153 return NS_VK_INSERT
;
2155 return NS_VK_DELETE
;
2168 case GDK_KP_Page_Up
:
2169 return NS_VK_PAGE_UP
;
2170 // Not sure what these are
2171 // case GDK_KP_Prior: return NS_VK_;
2172 // case GDK_KP_Next: return NS_VK_;
2174 return NS_VK_CLEAR
; // Num-unlocked 5
2175 case GDK_KP_Page_Down
:
2176 return NS_VK_PAGE_DOWN
;
2182 return NS_VK_INSERT
;
2184 return NS_VK_DELETE
;
2186 return NS_VK_RETURN
;
2189 return NS_VK_NUM_LOCK
;
2190 case GDK_Scroll_Lock
:
2191 return NS_VK_SCROLL_LOCK
;
2243 // context menu key, keysym 0xff67, typically keycode 117 on 105-key
2244 // (Microsoft) x86 keyboards, located between right 'Windows' key and
2247 return NS_VK_CONTEXT_MENU
;
2253 case GDK_3270_CursorSelect
:
2255 case GDK_3270_ExSelect
:
2257 case GDK_3270_EraseEOF
:
2261 // case GDK_XXX: return NS_VK_ZOOM;
2265 // map Sun Keyboard special keysyms on to NS_VK keys
2267 // Sun F11 key generates SunF36(0x1005ff10) keysym
2270 // Sun F12 key generates SunF37(0x1005ff11) keysym
2278 void KeymapWrapper::WillDispatchKeyboardEvent(WidgetKeyboardEvent
& aKeyEvent
,
2279 GdkEventKey
* aGdkKeyEvent
) {
2280 GetInstance()->WillDispatchKeyboardEventInternal(aKeyEvent
, aGdkKeyEvent
);
2283 void KeymapWrapper::WillDispatchKeyboardEventInternal(
2284 WidgetKeyboardEvent
& aKeyEvent
, GdkEventKey
* aGdkKeyEvent
) {
2285 if (!aGdkKeyEvent
) {
2286 // If aGdkKeyEvent is nullptr, we're trying to dispatch a fake keyboard
2287 // event in such case, we don't need to set alternative char codes.
2288 // So, we don't need to do nothing here. This case is typically we're
2289 // dispatching eKeyDown or eKeyUp event during composition.
2293 uint32_t charCode
= GetCharCodeFor(aGdkKeyEvent
);
2295 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
2296 ("%p WillDispatchKeyboardEventInternal, "
2297 "mKeyCode=0x%02X, charCode=0x%08X",
2298 this, aKeyEvent
.mKeyCode
, aKeyEvent
.mCharCode
));
2302 // The mCharCode was set from mKeyValue. However, for example, when Ctrl key
2303 // is pressed, its value should indicate an ASCII character for backward
2304 // compatibility rather than inputting character without the modifiers.
2305 // Therefore, we need to modify mCharCode value here.
2306 aKeyEvent
.SetCharCode(charCode
);
2308 gint level
= GetKeyLevel(aGdkKeyEvent
);
2309 if (level
!= 0 && level
!= 1) {
2310 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
2311 ("%p WillDispatchKeyboardEventInternal, "
2312 "mKeyCode=0x%02X, mCharCode=0x%08X, level=%d",
2313 this, aKeyEvent
.mKeyCode
, aKeyEvent
.mCharCode
, level
));
2318 aGdkKeyEvent
->state
& ~(GetModifierMask(SHIFT
) | GetModifierMask(CTRL
) |
2319 GetModifierMask(ALT
) | GetModifierMask(META
) |
2320 GetModifierMask(SUPER
) | GetModifierMask(HYPER
));
2322 // We shold send both shifted char and unshifted char, all keyboard layout
2323 // users can use all keys. Don't change event.mCharCode. On some keyboard
2324 // layouts, Ctrl/Alt/Meta keys are used for inputting some characters.
2325 AlternativeCharCode
altCharCodes(0, 0);
2326 // unshifted charcode of current keyboard layout.
2327 altCharCodes
.mUnshiftedCharCode
=
2328 GetCharCodeFor(aGdkKeyEvent
, baseState
, aGdkKeyEvent
->group
);
2329 bool isLatin
= (altCharCodes
.mUnshiftedCharCode
<= 0xFF);
2330 // shifted charcode of current keyboard layout.
2331 altCharCodes
.mShiftedCharCode
= GetCharCodeFor(
2332 aGdkKeyEvent
, baseState
| GetModifierMask(SHIFT
), aGdkKeyEvent
->group
);
2333 isLatin
= isLatin
&& (altCharCodes
.mShiftedCharCode
<= 0xFF);
2334 if (altCharCodes
.mUnshiftedCharCode
|| altCharCodes
.mShiftedCharCode
) {
2335 aKeyEvent
.mAlternativeCharCodes
.AppendElement(altCharCodes
);
2338 bool needLatinKeyCodes
= !isLatin
;
2339 if (!needLatinKeyCodes
) {
2341 (IS_ASCII_ALPHABETICAL(altCharCodes
.mUnshiftedCharCode
) !=
2342 IS_ASCII_ALPHABETICAL(altCharCodes
.mShiftedCharCode
));
2345 // If current keyboard layout can input Latin characters, we don't need
2346 // more information.
2347 if (!needLatinKeyCodes
) {
2348 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
2349 ("%p WillDispatchKeyboardEventInternal, "
2350 "mKeyCode=0x%02X, mCharCode=0x%08X, level=%d, altCharCodes={ "
2351 "mUnshiftedCharCode=0x%08X, mShiftedCharCode=0x%08X }",
2352 this, aKeyEvent
.mKeyCode
, aKeyEvent
.mCharCode
, level
,
2353 altCharCodes
.mUnshiftedCharCode
, altCharCodes
.mShiftedCharCode
));
2357 // Next, find Latin inputtable keyboard layout.
2358 gint minGroup
= GetFirstLatinGroup();
2360 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
2361 ("%p WillDispatchKeyboardEventInternal, "
2362 "Latin keyboard layout isn't found: "
2363 "mKeyCode=0x%02X, mCharCode=0x%08X, level=%d, "
2364 "altCharCodes={ mUnshiftedCharCode=0x%08X, "
2365 "mShiftedCharCode=0x%08X }",
2366 this, aKeyEvent
.mKeyCode
, aKeyEvent
.mCharCode
, level
,
2367 altCharCodes
.mUnshiftedCharCode
, altCharCodes
.mShiftedCharCode
));
2371 AlternativeCharCode
altLatinCharCodes(0, 0);
2372 uint32_t unmodifiedCh
= aKeyEvent
.IsShift() ? altCharCodes
.mShiftedCharCode
2373 : altCharCodes
.mUnshiftedCharCode
;
2375 // unshifted charcode of found keyboard layout.
2376 uint32_t ch
= GetCharCodeFor(aGdkKeyEvent
, baseState
, minGroup
);
2377 altLatinCharCodes
.mUnshiftedCharCode
=
2378 IsBasicLatinLetterOrNumeral(ch
) ? ch
: 0;
2379 // shifted charcode of found keyboard layout.
2380 ch
= GetCharCodeFor(aGdkKeyEvent
, baseState
| GetModifierMask(SHIFT
),
2382 altLatinCharCodes
.mShiftedCharCode
= IsBasicLatinLetterOrNumeral(ch
) ? ch
: 0;
2383 if (altLatinCharCodes
.mUnshiftedCharCode
||
2384 altLatinCharCodes
.mShiftedCharCode
) {
2385 aKeyEvent
.mAlternativeCharCodes
.AppendElement(altLatinCharCodes
);
2387 // If the mCharCode is not Latin, and the level is 0 or 1, we should
2388 // replace the mCharCode to Latin char if Alt and Meta keys are not
2389 // pressed. (Alt should be sent the localized char for accesskey
2390 // like handling of Web Applications.)
2391 ch
= aKeyEvent
.IsShift() ? altLatinCharCodes
.mShiftedCharCode
2392 : altLatinCharCodes
.mUnshiftedCharCode
;
2393 if (ch
&& !(aKeyEvent
.IsAlt() || aKeyEvent
.IsMeta()) &&
2394 charCode
== unmodifiedCh
) {
2395 aKeyEvent
.SetCharCode(ch
);
2398 MOZ_LOG(gKeymapWrapperLog
, LogLevel::Info
,
2399 ("%p WillDispatchKeyboardEventInternal, "
2400 "mKeyCode=0x%02X, mCharCode=0x%08X, level=%d, minGroup=%d, "
2401 "altCharCodes={ mUnshiftedCharCode=0x%08X, "
2402 "mShiftedCharCode=0x%08X } "
2403 "altLatinCharCodes={ mUnshiftedCharCode=0x%08X, "
2404 "mShiftedCharCode=0x%08X }",
2405 this, aKeyEvent
.mKeyCode
, aKeyEvent
.mCharCode
, level
, minGroup
,
2406 altCharCodes
.mUnshiftedCharCode
, altCharCodes
.mShiftedCharCode
,
2407 altLatinCharCodes
.mUnshiftedCharCode
,
2408 altLatinCharCodes
.mShiftedCharCode
));
2411 } // namespace widget
2412 } // namespace mozilla