1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
|
// Copyright 2010-2021 The Mumble Developers. All rights reserved.
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file at the root of the
// Mumble source tree or at <https://www.mumble.info/LICENSE>.
#import <AppKit/AppKit.h>
#import <Carbon/Carbon.h>
#include "GlobalShortcut_macx.h"
#ifdef USE_OVERLAY
# include "OverlayClient.h"
#endif
#define MOD_OFFSET 0x10000
#define MOUSE_OFFSET 0x20000
GlobalShortcutEngine *GlobalShortcutEngine::platformInit() {
return new GlobalShortcutMac();
}
CGEventRef GlobalShortcutMac::callback(CGEventTapProxy proxy, CGEventType type,
CGEventRef event, void *udata) {
GlobalShortcutMac *gs = reinterpret_cast<GlobalShortcutMac *>(udata);
unsigned int keycode;
bool suppress = false;
bool forward = false;
bool down = false;
int64_t repeat = 0;
Q_UNUSED(proxy);
switch (type) {
case kCGEventLeftMouseDown:
case kCGEventRightMouseDown:
case kCGEventOtherMouseDown:
down = true;
case kCGEventLeftMouseUp:
case kCGEventRightMouseUp:
case kCGEventOtherMouseUp: {
keycode = static_cast<unsigned int>(CGEventGetIntegerValueField(event, kCGMouseEventButtonNumber));
suppress = gs->handleButton(MOUSE_OFFSET+keycode, down);
/* Suppressing "the" mouse button is probably not a good idea :-) */
if (keycode == 0)
suppress = false;
forward = !suppress;
break;
}
case kCGEventMouseMoved:
case kCGEventLeftMouseDragged:
case kCGEventRightMouseDragged:
case kCGEventOtherMouseDragged: {
#ifdef USE_OVERLAY
if (Global::get().ocIntercept) {
int64_t dx = CGEventGetIntegerValueField(event, kCGMouseEventDeltaX);
int64_t dy = CGEventGetIntegerValueField(event, kCGMouseEventDeltaY);
Global::get().ocIntercept->iMouseX = qBound<int>(0, Global::get().ocIntercept->iMouseX + static_cast<int>(dx), Global::get().ocIntercept->uiWidth - 1);
Global::get().ocIntercept->iMouseY = qBound<int>(0, Global::get().ocIntercept->iMouseY + static_cast<int>(dy), Global::get().ocIntercept->uiHeight - 1);
QMetaObject::invokeMethod(Global::get().ocIntercept, "updateMouse", Qt::QueuedConnection);
forward = true;
}
#endif
break;
}
case kCGEventScrollWheel:
forward = true;
break;
case kCGEventKeyDown:
down = true;
case kCGEventKeyUp:
repeat = CGEventGetIntegerValueField(event, kCGKeyboardEventAutorepeat);
if (! repeat) {
keycode = static_cast<unsigned int>(CGEventGetIntegerValueField(event, kCGKeyboardEventKeycode));
suppress = gs->handleButton(keycode, down);
}
forward = true;
break;
case kCGEventFlagsChanged: {
CGEventFlags f = CGEventGetFlags(event);
// Dump active event taps on Ctrl+Alt+Cmd.
CGEventFlags ctrlAltCmd = static_cast<CGEventFlags>(kCGEventFlagMaskControl|kCGEventFlagMaskAlternate|kCGEventFlagMaskCommand);
if ((f & ctrlAltCmd) == ctrlAltCmd)
gs->dumpEventTaps();
suppress = gs->handleModButton(f);
forward = !suppress;
break;
}
case kCGEventTapDisabledByTimeout:
qWarning("GlobalShortcutMac: EventTap disabled by timeout. Re-enabling.");
/*
* On Snow Leopard, we get this event type quite often. It disables our event
* tap completely. Possible Apple bug.
*
* For now, simply call CGEventTapEnable() to enable our event tap again.
*
* See: http://lists.apple.com/archives/quartz-dev/2009/Sep/msg00007.html
*/
CGEventTapEnable(gs->port, true);
break;
case kCGEventTapDisabledByUserInput:
break;
default:
break;
}
#ifdef USE_OVERLAY
if (forward && Global::get().ocIntercept) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSEvent *evt = [[NSEvent eventWithCGEvent:event] retain];
QMetaObject::invokeMethod(gs, "forwardEvent", Qt::QueuedConnection, Q_ARG(void *, evt));
[pool release];
return nullptr;
}
#endif
return suppress ? nullptr : event;
}
GlobalShortcutMac::GlobalShortcutMac()
: loop(nullptr)
, port(nullptr)
, modmask(static_cast<CGEventFlags>(0)) {
#ifndef QT_NO_DEBUG
qWarning("GlobalShortcutMac: Debug build detected. Disabling shortcut engine.");
return;
#endif
CGEventMask evmask = CGEventMaskBit(kCGEventLeftMouseDown) |
CGEventMaskBit(kCGEventLeftMouseUp) |
CGEventMaskBit(kCGEventRightMouseDown) |
CGEventMaskBit(kCGEventRightMouseUp) |
CGEventMaskBit(kCGEventOtherMouseDown) |
CGEventMaskBit(kCGEventOtherMouseUp) |
CGEventMaskBit(kCGEventKeyDown) |
CGEventMaskBit(kCGEventKeyUp) |
CGEventMaskBit(kCGEventFlagsChanged) |
CGEventMaskBit(kCGEventMouseMoved) |
CGEventMaskBit(kCGEventLeftMouseDragged) |
CGEventMaskBit(kCGEventRightMouseDragged) |
CGEventMaskBit(kCGEventOtherMouseDragged) |
CGEventMaskBit(kCGEventScrollWheel);
port = CGEventTapCreate(kCGSessionEventTap,
kCGTailAppendEventTap,
kCGEventTapOptionDefault, // active filter (not only a listener)
evmask,
GlobalShortcutMac::callback,
this);
if (! port) {
qWarning("GlobalShortcutMac: Unable to create EventTap. Global Shortcuts will not be available.");
return;
}
kbdLayout = nullptr;
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1050
# if MAC_OS_X_VERSION_MIN_REQUIRED < 1050
if (TISCopyCurrentKeyboardInputSource && TISGetInputSourceProperty)
# endif
{
TISInputSourceRef inputSource = TISCopyCurrentKeyboardInputSource();
if (inputSource) {
CFDataRef data = static_cast<CFDataRef>(TISGetInputSourceProperty(inputSource, kTISPropertyUnicodeKeyLayoutData));
if (data)
kbdLayout = reinterpret_cast<UCKeyboardLayout *>(const_cast<UInt8 *>(CFDataGetBytePtr(data)));
}
}
#endif
#ifndef __LP64__
if (! kbdLayout) {
SInt16 currentKeyScript = GetScriptManagerVariable(smKeyScript);
SInt16 lastKeyLayoutID = GetScriptVariable(currentKeyScript, smScriptKeys);
Handle handle = GetResource('uchr', lastKeyLayoutID);
if (handle)
kbdLayout = reinterpret_cast<UCKeyboardLayout *>(*handle);
}
#endif
if (! kbdLayout)
qWarning("GlobalShortcutMac: No keyboard layout mapping available. Unable to perform key translation.");
start(QThread::TimeCriticalPriority);
}
GlobalShortcutMac::~GlobalShortcutMac() {
#ifndef QT_NO_DEBUG
return;
#endif
if (loop) {
CFRunLoopStop(loop);
loop = nullptr;
wait();
}
}
void GlobalShortcutMac::dumpEventTaps() {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
uint32_t ntaps = 0;
CGEventTapInformation table[64];
if (CGGetEventTapList(20, table, &ntaps) == kCGErrorSuccess) {
qWarning("--- Installed Event Taps ---");
for (uint32_t i = 0; i < ntaps; i++) {
CGEventTapInformation *info = &table[i];
NSString *processName = nil;
NSRunningApplication *app = [NSRunningApplication runningApplicationWithProcessIdentifier: info->processBeingTapped];
if (app) {
processName = [app localizedName];
}
qWarning("{");
qWarning(" eventTapID: %u", info->eventTapID);
qWarning(" tapPoint: 0x%x", info->tapPoint);
qWarning(" options = 0x%x", info->options);
qWarning(" eventsOfInterest = 0x%llx", info->eventsOfInterest);
qWarning(" tappingProcess = %i (%s)", info->tappingProcess, [processName UTF8String]);
qWarning(" processBeingTapped = %i", info->processBeingTapped);
qWarning(" enabled = %s", info->enabled ? "true":"false");
qWarning(" minUsecLatency = %.2f", info->minUsecLatency);
qWarning(" avgUsecLatency = %.2f", info->avgUsecLatency);
qWarning(" maxUsecLatency = %.2f", info->maxUsecLatency);
qWarning("}");
}
qWarning("--- End of Event Taps ---");
}
[pool release];
}
void GlobalShortcutMac::forwardEvent(void *evt) {
NSEvent *event = (NSEvent *)evt;
#ifdef USE_OVERLAY
SEL sel = nil;
if (! Global::get().ocIntercept) {
[event release];
return;
}
QWidget *vp = Global::get().ocIntercept->qgv.viewport();
NSView *view = (NSView *) vp->winId();
switch ([event type]) {
case NSLeftMouseDown:
sel = @selector(mouseDown:);
break;
case NSLeftMouseUp:
sel = @selector(mouseUp:);
break;
case NSLeftMouseDragged:
sel = @selector(mouseDragged:);
break;
case NSRightMouseDown:
sel = @selector(rightMouseDown:);
break;
case NSRightMouseUp:
sel = @selector(rightMouseUp:);
break;
case NSRightMouseDragged:
sel = @selector(rightMouseDragged:);
break;
case NSOtherMouseDown:
sel = @selector(otherMouseDown:);
break;
case NSOtherMouseUp:
sel = @selector(otherMouseUp:);
break;
case NSOtherMouseDragged:
sel = @selector(otherMouseDragged:);
break;
case NSMouseEntered:
sel = @selector(mouseEntered:);
break;
case NSMouseExited:
sel = @selector(mouseExited:);
break;
case NSMouseMoved:
sel = @selector(mouseMoved:);
break;
default:
// Ignore the rest. We only care about mouse events.
break;
}
if (sel) {
NSPoint p; p.x = (CGFloat) Global::get().ocIntercept->iMouseX;
p.y = (CGFloat) (Global::get().ocIntercept->uiHeight - Global::get().ocIntercept->iMouseY);
NSEvent *mouseEvent = [NSEvent mouseEventWithType:[event type] location:p modifierFlags:[event modifierFlags] timestamp:[event timestamp]
windowNumber:0 context:nil eventNumber:[event eventNumber] clickCount:[event clickCount]
pressure:[event pressure]];
if ([view respondsToSelector:sel])
[view performSelector:sel withObject:mouseEvent];
[event release];
return;
}
switch ([event type]) {
case NSKeyDown:
sel = @selector(keyDown:);
break;
case NSKeyUp:
sel = @selector(keyUp:);
break;
case NSFlagsChanged:
sel = @selector(flagsChanged:);
break;
case NSScrollWheel:
sel = @selector(scrollWheel:);
break;
default:
break;
}
if (sel) {
if ([view respondsToSelector:sel])
[view performSelector:sel withObject:event];
}
#endif
[event release];
}
void GlobalShortcutMac::run() {
loop = CFRunLoopGetCurrent();
CFRunLoopSourceRef src = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, port, 0);
CFRunLoopAddSource(loop, src, kCFRunLoopCommonModes);
CFRunLoopRun();
}
void GlobalShortcutMac::needRemap() {
remap();
}
bool GlobalShortcutMac::handleModButton(const CGEventFlags newmask) {
bool down;
bool suppress = false;
#define MOD_CHANGED(mask, btn) do { \
if ((newmask & mask) != (modmask & mask)) { \
down = newmask & mask; \
suppress = handleButton(MOD_OFFSET+btn, down); \
modmask = newmask; \
return suppress; \
}} while (0)
MOD_CHANGED(kCGEventFlagMaskAlphaShift, 0);
MOD_CHANGED(kCGEventFlagMaskShift, 1);
MOD_CHANGED(kCGEventFlagMaskControl, 2);
MOD_CHANGED(kCGEventFlagMaskAlternate, 3);
MOD_CHANGED(kCGEventFlagMaskCommand, 4);
MOD_CHANGED(kCGEventFlagMaskHelp, 5);
MOD_CHANGED(kCGEventFlagMaskSecondaryFn, 6);
MOD_CHANGED(kCGEventFlagMaskNumericPad, 7);
return false;
}
QString GlobalShortcutMac::translateMouseButton(const unsigned int keycode) const {
return QString::fromLatin1("%1").arg(keycode - MOUSE_OFFSET + 1);
}
QString GlobalShortcutMac::translateModifierKey(const unsigned int keycode) const {
unsigned int key = keycode - MOD_OFFSET;
switch (key) {
case 0:
return QLatin1String("Caps Lock");
case 1:
return QLatin1String("Shift");
case 2:
return QLatin1String("Control");
case 3:
return QLatin1String("Alt/Option");
case 4:
return QLatin1String("Command");
case 5:
return QLatin1String("Help");
case 6:
return QLatin1String("Fn");
case 7:
return QLatin1String("Num Lock");
}
return QString::fromLatin1("Modifier %1").arg(key);
}
QString GlobalShortcutMac::translateKeyName(const unsigned int keycode) const {
UInt32 junk = 0;
UniCharCount len = 64;
UniChar unicodeString[len];
if (! kbdLayout)
return QString();
OSStatus err = UCKeyTranslate(kbdLayout, static_cast<UInt16>(keycode),
kUCKeyActionDisplay, 0, LMGetKbdType(),
kUCKeyTranslateNoDeadKeysBit, &junk,
len, &len, unicodeString);
if (err != noErr)
return QString();
if (len == 1) {
switch (unicodeString[0]) {
case '\t':
return QLatin1String("Tab");
case '\r':
return QLatin1String("Enter");
case '\b':
return QLatin1String("Backspace");
case '\e':
return QLatin1String("Escape");
case ' ':
return QLatin1String("Space");
case 28:
return QLatin1String("Left");
case 29:
return QLatin1String("Right");
case 30:
return QLatin1String("Up");
case 31:
return QLatin1String("Down");
}
if (unicodeString[0] < ' ') {
qWarning("GlobalShortcutMac: Unknown translation for keycode %u: %u", keycode, unicodeString[0]);
return QString();
}
}
return QString(reinterpret_cast<const QChar *>(unicodeString), len).toUpper();
}
GlobalShortcutMac::ButtonInfo GlobalShortcutMac::buttonInfo(const QVariant &v) {
bool ok;
unsigned int key = v.toUInt(&ok);
if (!ok) {
return ButtonInfo();
}
ButtonInfo info;
if (key >= MOUSE_OFFSET) {
info.device = tr("Mouse");
info.devicePrefix = QLatin1String("M");
info.name = translateMouseButton(key);
return info;
} else {
info.device = tr("Keyboard");
info.name = key >= MOD_OFFSET ? translateModifierKey(key) : translateKeyName(key);
if (!info.name.isEmpty()) {
return info;
}
}
info.name = QString::number(key);
return info;
}
void GlobalShortcutMac::setEnabled(bool b) {
// Since Mojave, passing nullptr to CGEventTapEnable() segfaults.
if (port) {
CGEventTapEnable(port, b);
}
}
bool GlobalShortcutMac::enabled() {
if (!port) {
return false;
}
return CGEventTapIsEnabled(port);
}
bool GlobalShortcutMac::canSuppress() {
return true;
}
bool GlobalShortcutMac::canDisable() {
return true;
}
#undef MOD_OFFSET
#undef MOUSE_OFFSET
#undef MOD_CHANGED
|