From 974e55bd70648972c6481f1e8ae724b8b9a8f3d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tor=20Arne=20Vestb=C3=B8?= Date: Fri, 10 Jul 2020 15:47:54 +0200 Subject: [PATCH] macOS: Use Cocoa to map key events to possible shortcut key sequences For now we just verify that the Cocoa API produces the same keymaps as we get from Carbon. Once that's verified we can solidify the code. Change-Id: I0d2aa1bb0a006d29c0149e3ff2fd5299ba922326 Reviewed-by: Timur Pocheptsov --- .../platforms/cocoa/qcocoakeymapper.mm | 22 ++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/src/plugins/platforms/cocoa/qcocoakeymapper.mm b/src/plugins/platforms/cocoa/qcocoakeymapper.mm index 4f3e886a344..bcc5a9ef0ce 100644 --- a/src/plugins/platforms/cocoa/qcocoakeymapper.mm +++ b/src/plugins/platforms/cocoa/qcocoakeymapper.mm @@ -452,9 +452,6 @@ const QCocoaKeyMapper::KeyMap &QCocoaKeyMapper::keyMapForKey(VirtualKeyCode virt qCDebug(lcQpaKeyMapper, "Updating key map for virtual key = 0x%02x!", (uint)virtualKey); - UniCharCount maxStringLength = 10; - UniChar unicodeString[maxStringLength]; - for (int i = 0; i < 16; ++i) { Q_ASSERT(!i || keyMap[i] == 0); @@ -462,6 +459,8 @@ const QCocoaKeyMapper::KeyMap &QCocoaKeyMapper::keyMapForKey(VirtualKeyCode virt auto carbonModifiers = toCarbonModifiers(qtModifiers); const UInt32 modifierKeyState = (carbonModifiers >> 8) & 0xFF; + static const UniCharCount maxStringLength = 10; + static UniChar unicodeString[maxStringLength]; UniCharCount actualStringLength = 0; OSStatus err = UCKeyTranslate(m_keyboardLayoutFormat, virtualKey, kUCKeyActionDown, modifierKeyState, m_keyboardKind, OptionBits(0), @@ -471,6 +470,23 @@ const QCocoaKeyMapper::KeyMap &QCocoaKeyMapper::keyMapForKey(VirtualKeyCode virt if (err == noErr && actualStringLength) unicodeKey = QChar(unicodeString[0]); + if (@available(macOS 10.15, *)) { + // Until we've verified that the Cocoa API works as expected + // we first run the event through the Carbon APIs and then + // compare the results to Cocoa. + Q_ASSERT(NSApp.currentEvent); + Q_ASSERT(NSApp.currentEvent.type == NSEventTypeKeyDown); + auto cocoaModifiers = toCocoaModifiers(qtModifiers); + auto *charactersWithModifiers = [NSApp.currentEvent charactersByApplyingModifiers:cocoaModifiers]; + Q_ASSERT(charactersWithModifiers && charactersWithModifiers.length > 0); + auto cocoaUnicodeKey = QChar([charactersWithModifiers characterAtIndex:0]); + if (cocoaUnicodeKey != unicodeKey) { + qCWarning(lcQpaKeyMapper) << "Mismatch between Cocoa" << cocoaUnicodeKey + << "and Carbon" << unicodeKey << "for virtual key" << virtualKey + << "with" << qtModifiers; + } + } + int qtkey = toKeyCode(unicodeKey, virtualKey, qtModifiers); if (qtkey == Qt::Key_unknown) qtkey = unicodeKey.unicode();