-
Notifications
You must be signed in to change notification settings - Fork 1
/
osx.c
1276 lines (1026 loc) · 31.4 KB
/
osx.c
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <mach/mach.h>
#include <mach/mach_time.h>
#include <CoreGraphics/CGEvent.h>
#include <CoreGraphics/CGDirectDisplay.h>
#include <IOKit/hidsystem/event_status_driver.h>
/*
* Because unfortunately I can't currently figure out how to get just
* Pasteboard.h (which is in HIServices within ApplicationServices). Sigh.
*/
#include <Carbon/Carbon.h>
#include "types.h"
#include "misc.h"
#include "platform.h"
#include "osx-keycodes.h"
#include "events.h"
#if CGFLOAT_IS_DOUBLE
#define cground lround
#else
#define cground lroundf
#endif
/*
* Selected from:
* https://developer.apple.com/Library/mac/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html
*/
#define PLAINTEXT CFSTR("public.utf8-plain-text")
static mach_timebase_info_data_t mach_timebase;
static PasteboardRef clipboard;
static struct rectangle screen_dimensions = {
.x = { .min = 0, .max = 0, },
.y = { .min = 0, .max = 0, },
};
struct xypoint screen_center;
static mousepos_handler_t* mousepos_handler;
static uint64_t double_click_threshold_us;
static CGEventFlags modflags;
#define MEDIAN(x, y) ((x) + (((y)-(x)) / 2))
struct gamma_table {
CGGammaValue* red;
CGGammaValue* green;
CGGammaValue* blue;
uint32_t numents;
};
struct displayinfo {
CGDirectDisplayID id;
struct rectangle bounds;
struct gamma_table orig_gamma;
struct gamma_table alt_gamma;
};
struct displayinfo* displays;
static uint32_t num_displays;
static void setup_gamma_table(struct gamma_table* gt, uint32_t size)
{
gt->numents = size;
gt->red = xmalloc(size * sizeof(*gt->red));
gt->green = xmalloc(size * sizeof(*gt->green));
gt->blue = xmalloc(size * sizeof(*gt->blue));
}
static void clear_gamma_table(struct gamma_table* gt)
{
xfree(gt->red);
xfree(gt->green);
xfree(gt->blue);
memset(gt, 0, sizeof(*gt));
}
static void init_display(struct displayinfo* d, CGDirectDisplayID id)
{
uint32_t numents;
CGError cgerr;
CGRect bounds;
d->id = id;
setup_gamma_table(&d->orig_gamma, CGDisplayGammaTableCapacity(d->id));
setup_gamma_table(&d->alt_gamma, d->orig_gamma.numents);
cgerr = CGGetDisplayTransferByTable(d->id, d->orig_gamma.numents, d->orig_gamma.red,
d->orig_gamma.green, d->orig_gamma.blue, &numents);
if (cgerr) {
initerr("CGGetDisplayTransferByTable() failed (%d)\n", cgerr);
initerr("brightness adjustment will be disabled\n");
clear_gamma_table(&d->orig_gamma);
clear_gamma_table(&d->alt_gamma);
} else if (numents != d->orig_gamma.numents) {
initerr("CGGetDisplayTransferByTable() behaves strangely: %u != %u\n",
numents, d->orig_gamma.numents);
assert(numents < d->orig_gamma.numents);
d->orig_gamma.numents = numents;
d->alt_gamma.numents = numents;
}
bounds = CGDisplayBounds(d->id);
d->bounds.x.min = CGRectGetMinX(bounds);
d->bounds.x.max = CGRectGetMaxX(bounds);
d->bounds.y.min = CGRectGetMinY(bounds);
d->bounds.y.max = CGRectGetMaxY(bounds);
if (d->bounds.x.min < screen_dimensions.x.min)
screen_dimensions.x.min = d->bounds.x.min;
if (d->bounds.x.max > screen_dimensions.x.max)
screen_dimensions.x.max = d->bounds.x.max;
if (d->bounds.y.min < screen_dimensions.y.min)
screen_dimensions.y.min = d->bounds.y.min;
if (d->bounds.y.max > screen_dimensions.y.max)
screen_dimensions.y.max = d->bounds.y.max;
}
/*
* HACK: More API stupidity from Apple means you can't hide the cursor if
* you're not the foreground application...unless you know their secret
* handshake to allow doing that, which requires calling these undeclared,
* undocumented functions.
*
* References:
* http://lists.apple.com/archives/carbon-dev/2006/Jan/msg00555.html
* http://stackoverflow.com/questions/3885896/globally-hiding-cursor-from-background-app
*/
typedef int CGSConnectionID;
extern void CGSSetConnectionProperty(CGSConnectionID, CGSConnectionID, CFStringRef, CFBooleanRef);
extern CGSConnectionID _CGSDefaultConnection(void);
/* "128 displays oughta be enough for anyone..." */
#define MAX_DISPLAYS 128
int platform_init(struct kvmap* params, mousepos_handler_t* mouse_handler)
{
CGDirectDisplayID displayids[MAX_DISPLAYS];
CGError cgerr;
OSStatus status;
uint32_t i;
kern_return_t kr;
NXEventHandle nxevh;
kr = mach_timebase_info(&mach_timebase);
if (kr != KERN_SUCCESS) {
initerr("mach_timebase_info() failed: %s\n", mach_error_string(kr));
return -1;
}
nxevh = NXOpenEventStatus();
double_click_threshold_us = NXClickTime(nxevh) * 1000000;
NXCloseEventStatus(nxevh);
cgerr = CGGetOnlineDisplayList(ARR_LEN(displayids), displayids,
&num_displays);
if (cgerr) {
initerr("CGGetOnlineDisplayList() failed (%d)\n", cgerr);
return -1;
}
displays = xmalloc(num_displays * sizeof(*displays));
/* Initialize to "normal" gamma */
CGDisplayRestoreColorSyncSettings();
for (i = 0; i < num_displays; i++)
init_display(&displays[i], displayids[i]);
screen_center.x = MEDIAN(screen_dimensions.x.min, screen_dimensions.x.max);
screen_center.y = MEDIAN(screen_dimensions.y.min, screen_dimensions.y.max);
status = PasteboardCreate(kPasteboardClipboard, &clipboard);
if (status != noErr) {
initerr("PasteboardCreate() failed (%d)\n", status);
return -1;
}
osx_keycodes_init();
if (opmode == MASTER)
CGSSetConnectionProperty(_CGSDefaultConnection(), _CGSDefaultConnection(),
CFSTR("SetsCursorInBackground"), kCFBooleanTrue);
mousepos_handler = mouse_handler;
return 0;
}
void platform_exit(void)
{
uint32_t i;
osx_keycodes_exit();
CFRelease(clipboard);
CGDisplayRestoreColorSyncSettings();
for (i = 0; i < num_displays; i++) {
clear_gamma_table(&displays[i].orig_gamma);
clear_gamma_table(&displays[i].alt_gamma);
}
}
/*
* There are, as far as I can see, two approaches to setting up global
* hotkeys. One approach uses a global event tap and sniffs keyboard events
* searching for one that matches a bound hotkey (this is the one that's
* currently implemented and in use). The other involves calling
* InstallApplicationEventHandler() and RegisterEventHotKey() -- to get the
* callbacks set up with these, however, we'd apparently need to use
* RunApplicationEventLoop() instead of CFRunLoops. That API is deprecated,
* however (the declaration of RunApplicationEventLoop() is #ifdef'd out on
* 64-bit builds in the system headers, though the symbol is still present in
* the libraries so a manual declaration seems to work), and furthermore I
* don't know how (or if it's possible) to integrate the two different event
* loops, so I've stuck with the CFRunLoop/CGEventTap approach. The
* pre-filtered direct callbacks provided by the RegisterEventHotKey()
* approach seems much nicer than manually filtering them out of the stream of
* all global keystrokes, so though I've left some vestiges of that code
* around "just in case"...
*/
#define EVENTTAP_HOTKEYS
struct osxhotkey {
CGKeyCode keycode;
CGEventFlags modmask;
hotkey_callback_t callback;
void* arg;
#ifndef EVENTTAP_HOTKEYS
EventHotKeyRef evref;
#endif
};
static struct osxhotkey* hotkeys;
static unsigned int num_hotkeys;
struct hotkey_context {
uint32_t modmask;
};
static struct osxhotkey* find_hotkey(uint32_t keycode, uint32_t modmask)
{
struct osxhotkey* hk;
for (hk = hotkeys; hk < hotkeys + num_hotkeys; hk++) {
if (hk->keycode == keycode && hk->modmask == modmask) {
return hk;
}
}
return NULL;
}
static struct osxhotkey* do_hotkey(uint32_t keycode, uint32_t modmask)
{
struct hotkey_context hkctx = { .modmask = modmask, };
struct osxhotkey* hk = find_hotkey(keycode, modmask);
if (hk)
hk->callback(&hkctx, hk->arg);
return hk;
}
#ifndef EVENTTAP_HOTKEYS
static EventHandlerUPP hotkey_handler_upp;
static EventHandlerRef hotkey_handlerref;
static OSStatus hotkey_handler_fn(EventHandlerCallRef next, EventRef ev, void* arg)
{
EventHotKeyID hkid;
OSStatus status;
struct osxhotkey* hk;
struct hotkey_context ctx;
status = GetEventParameter(ev, kEventParamDirectObject, typeEventHotKeyID,
NULL, sizeof(hkid), NULL, &hkid);
if (status) {
errlog("GetEventParameter() failed in hotkey_handler_fn()\n");
abort();
}
if (hkid.id >= num_hotkeys) {
errlog("Out-of-bounds hotkey ID in hotkey_handler_fn()\n");
abort();
}
hk = &hotkeys[hkid.id];
ctx.modmask = hk->modmask;
hk->callback(&ctx, hk->arg);
return noErr;
}
#endif
int bind_hotkey(const char* keystr, hotkey_callback_t cb, void* arg)
{
CGKeyCode kc;
CGEventFlags modmask;
struct osxhotkey* hk;
#ifndef EVENTTAP_HOTKEYS
EventTypeSpec evtype;
EventHotKeyID hkid = { .signature = 'enth', .id = num_hotkeys, };
#endif
if (parse_keystring(keystr, &kc, &modmask))
return -1;
for (hk = hotkeys; hk < hotkeys + num_hotkeys; hk++) {
if (hk->modmask == modmask && hk->keycode == kc) {
initerr("hotkey '%s' conflicts with an earlier hotkey binding\n",
keystr);
return -1;
}
}
#ifndef EVENTTAP_HOTKEYS
if (!num_hotkeys) {
hotkey_handler_upp = NewEventHandlerUPP(hotkey_handler_fn);
evtype.eventClass = kEventClassKeyboard;
evtype.eventKind = kEventHotKeyPressed;
InstallApplicationEventHandler(hotkey_handler_upp, 1, &evtype, NULL,
&hotkey_handlerref);
}
#endif
hotkeys = xrealloc(hotkeys, ++num_hotkeys * sizeof(*hotkeys));
hk = &hotkeys[num_hotkeys-1];
hk->keycode = kc;
hk->modmask = modmask;
hk->callback = cb;
hk->arg = arg;
#ifndef EVENTTAP_HOTKEYS
/*
* NOTE: if this is to be used, hk->modmask will need to be a mask of
* cmdKey and friends, not kCGEventFlagMask* as it is now.
*/
RegisterEventHotKey(hk->keycode, hk->modmask, hkid, GetApplicationEventTarget(),
kEventHotKeyExclusive, &hk->evref);
#endif
return 0;
}
keycode_t* get_current_modifiers(void)
{
return modmask_to_etkeycodes(modflags);
}
keycode_t* get_hotkey_modifiers(hotkey_context_t ctx)
{
return modmask_to_etkeycodes(ctx->modmask);
}
uint64_t get_microtime(void)
{
uint64_t t = mach_absolute_time();
return ((t * mach_timebase.numer) / mach_timebase.denom) / 1000;
}
void get_screen_dimensions(struct rectangle* d)
{
*d = screen_dimensions;
}
static void set_gamma_table(CGDirectDisplayID disp, const struct gamma_table* gt)
{
CGError err;
if (!gt->numents)
return;
err = CGSetDisplayTransferByTable(disp, gt->numents, gt->red, gt->green, gt->blue);
if (err)
errlog("CGSetDisplayTransferByTable() failed (%d)\n", err);
}
/*
* The identity macro (ahem), for use as 'defloat' in MAKE_GAMMA_SCALE_FN,
* because CGGammaValue is a float to start with.
*/
#define id(x) x
static MAKE_GAMMA_SCALE_FN(gamma_scale, CGGammaValue, id);
static void scale_gamma_table(const struct gamma_table* from, struct gamma_table* to,
float scale)
{
uint32_t i;
assert(from->numents == to->numents);
for (i = 0; i < to->numents; i++) {
to->red[i] = gamma_scale(from->red, from->numents, i, scale);
to->green[i] = gamma_scale(from->green, from->numents, i, scale);
to->blue[i] = gamma_scale(from->blue, from->numents, i, scale);
}
}
void set_display_brightness(float f)
{
uint32_t i;
for (i = 0; i < num_displays; i++) {
scale_gamma_table(&displays[i].orig_gamma, &displays[i].alt_gamma, f);
set_gamma_table(displays[i].id, &displays[i].alt_gamma);
}
}
static inline int32_t cgfloat_to_i32(CGFloat f)
{
if (f > INT32_MAX || f < INT32_MIN) {
errlog("out-of-range CGFloat: %g\n", f);
abort();
}
return cground(f);
}
static CGPoint get_mousepos_cgpoint(void)
{
CGPoint cgpt;
CGEventRef ev = CGEventCreate(NULL);
if (!ev) {
errlog("CGEventCreate failed\n");
abort();
}
cgpt = CGEventGetLocation(ev);
CFRelease(ev);
return cgpt;
}
#define NO_MOUSEBUTTON 0
static int get_pt_display(CGPoint pt, CGDirectDisplayID* d)
{
uint32_t numdisplays;
CGError err;
err = CGGetDisplaysWithPoint(pt, !!d, d, &numdisplays);
if (err) {
errlog("CGGetDisplaysWithPoint() failed: %d\n", err);
abort();
}
return !!numdisplays;
}
static void post_mouseevent(CGPoint cgpt, CGEventType type, CGMouseButton button)
{
CGDirectDisplayID disp;
CGPoint curpos;
CGRect bounds;
CGEventRef ev;
if (!get_pt_display(cgpt, &disp)) {
curpos = get_mousepos_cgpoint();
if (!get_pt_display(curpos, &disp)) {
vinfo("mouse position (%g,%g) off any display?\n", curpos.x, curpos.y);
disp = CGMainDisplayID();
}
}
/*
* Why the subtraction of 0.1 on the max-bound checks here? Stupidly
* enough, without them OSX's pointer-at-edge-of-screen detection
* breaks (your auto-hiding Dock won't pop up, for example).
*
* Try as I might, I still have yet to see *any* sense whatsoever in
* tracking the mouse position in floating point. Whither sanity,
* Apple? WTF?
*/
bounds = CGDisplayBounds(disp);
if (cgpt.x < CGRectGetMinX(bounds))
cgpt.x = CGRectGetMinX(bounds);
if (cgpt.x > CGRectGetMaxX(bounds))
cgpt.x = CGRectGetMaxX(bounds) - 0.1;
if (cgpt.y < CGRectGetMinY(bounds))
cgpt.y = CGRectGetMinY(bounds);
if (cgpt.y > CGRectGetMaxY(bounds))
cgpt.y = CGRectGetMaxY(bounds) - 0.1;
ev = CGEventCreateMouseEvent(NULL, type, cgpt, button);
if (!ev) {
errlog("CGEventCreateMouseEvent failed\n");
abort();
}
CGEventSetFlags(ev, modflags|kCGEventFlagMaskNonCoalesced);
CGEventPost(kCGHIDEventTap, ev);
CFRelease(ev);
}
struct xypoint get_mousepos(void)
{
struct xypoint pt;
CGPoint cgpt = get_mousepos_cgpoint();
pt.x = cgfloat_to_i32(cgpt.x);
pt.y = cgfloat_to_i32(cgpt.y);
return pt;
}
static inline int mouse_button_held(CGMouseButton btn)
{
return CGEventSourceButtonState(kCGEventSourceStateCombinedSessionState, btn);
}
static uint64_t last_mouse_move;
static void set_mousepos_cgpoint(CGPoint cgpt)
{
post_mouseevent(cgpt, kCGEventMouseMoved, NO_MOUSEBUTTON);
last_mouse_move = get_microtime();
}
void set_mousepos(struct xypoint pt)
{
set_mousepos_cgpoint(CGPointMake((CGFloat)pt.x, (CGFloat)pt.y));
}
/* Variant of set_mousepos() that doesn't trigger additional events */
static void set_mousepos_silent(struct xypoint pt)
{
CGPoint cgpt = { .x = (CGFloat)pt.x, .y = (CGFloat)pt.y, };
CGWarpMouseCursorPosition(cgpt);
}
void move_mousepos(int32_t dx, int32_t dy)
{
CGPoint pt = get_mousepos_cgpoint();
pt.x += dx;
pt.y += dy;
/* Sigh...why can't Quartz figure this out by itself? */
if (mouse_button_held(kCGMouseButtonLeft))
post_mouseevent(pt, kCGEventLeftMouseDragged, kCGMouseButtonLeft);
else if (mouse_button_held(kCGMouseButtonRight))
post_mouseevent(pt, kCGEventRightMouseDragged, kCGMouseButtonRight);
else if (mouse_button_held(kCGMouseButtonCenter))
post_mouseevent(pt, kCGEventOtherMouseDragged, kCGMouseButtonCenter);
else
set_mousepos_cgpoint(pt);
}
struct click_history {
uint64_t last_press;
uint64_t last_release;
int count;
};
static struct click_history click_histories[MB__MAX_+1];
/*
* 1: single-click, 2: double-click, 3: triple-click.
*
* See kCGMouseEventClickState:
* https://developer.apple.com/library/mac/documentation/Carbon/Reference/QuartzEventServicesRef/Reference/reference.html#jumpTo_71
*/
static int64_t click_type(mousebutton_t btn, pressrel_t pr)
{
int64_t type;
uint64_t now_us = get_microtime();
struct click_history* hist = &click_histories[btn];
uint64_t* prev = (pr == PR_PRESS) ? &hist->last_press : &hist->last_release;
/*
* This may look sort of weird, but it's my best approximation of what
* Apple seems (empirically) to be doing with real-native-hardware
* clicks (at least for now).
*/
if ((now_us - *prev) > double_click_threshold_us || last_mouse_move > *prev) {
hist->count = 1;
type = (pr == PR_PRESS) ? 1 : 0;
} else if (pr == PR_PRESS) {
hist->count++;
type = hist->count > 3 ? 2 : hist->count;
} else {
type = hist->count;
}
*prev = now_us;
return type;
}
void do_clickevent(mousebutton_t button, pressrel_t pr)
{
int32_t scrollamt;
CGEventRef ev;
/* superfluous initializations to silence warnings from dumb old compilers */
CGEventType cgtype = kCGEventNull;
CGMouseButton cgbtn = kCGMouseButtonLeft;
switch (button) {
case MB_LEFT:
cgtype = (pr == PR_PRESS) ? kCGEventLeftMouseDown : kCGEventLeftMouseUp;
cgbtn = kCGMouseButtonLeft;
break;
case MB_CENTER:
/*
* kCGEventCenterMouse{Up,Down} don't exist...
*
* Having the button encoded in both the event type and also
* separately in another argument seems like pretty crappy API
* design to me, especially when the values available for the
* two don't match up. Sigh.
*/
cgtype = (pr == PR_PRESS) ? kCGEventOtherMouseDown : kCGEventOtherMouseUp;
cgbtn = kCGMouseButtonCenter;
break;
case MB_RIGHT:
cgtype = (pr == PR_PRESS) ? kCGEventRightMouseDown : kCGEventRightMouseUp;
cgbtn = kCGMouseButtonRight;
break;
case MB_SCROLLUP:
case MB_SCROLLDOWN:
if (pr == PR_RELEASE)
return;
scrollamt = (button == MB_SCROLLDOWN) ? -1 : 1;
break;
default:
warn("unhandled click event button %u\n", button);
return;
}
if (button == MB_SCROLLUP || button == MB_SCROLLDOWN)
ev = CGEventCreateScrollWheelEvent(NULL, kCGScrollEventUnitLine, 1, scrollamt);
else {
ev = CGEventCreateMouseEvent(NULL, cgtype, get_mousepos_cgpoint(), cgbtn);
if (ev)
CGEventSetIntegerValueField(ev, kCGMouseEventClickState,
click_type(button, pr));
}
if (!ev) {
errlog("CGEventCreateMouseEvent failed\n");
abort();
}
CGEventSetFlags(ev, modflags|kCGEventFlagMaskNonCoalesced);
CGEventPost(kCGHIDEventTap, ev);
CFRelease(ev);
}
static CGEventFlags key_eventflag(CGKeyCode cgk)
{
switch (cgk) {
case kVK_Control:
case kVK_RightControl:
return kCGEventFlagMaskControl;
case kVK_Shift:
case kVK_RightShift:
return kCGEventFlagMaskShift;
case kVK_Option:
case kVK_RightOption:
return kCGEventFlagMaskAlternate;
case kVK_Command:
return kCGEventFlagMaskCommand;
default:
return 0;
}
}
void do_keyevent(keycode_t key, pressrel_t pr)
{
CGEventRef ev;
CGKeyCode cgkc;
CGEventFlags flags;
cgkc = etkeycode_to_cgkeycode(key);
if (cgkc == kVK_NULL) {
warn("keycode %u not mapped\n", key);
return;
}
if (is_modifier_key(key)) {
flags = key_eventflag(cgkc);
if (pr == PR_PRESS)
modflags |= flags;
else
modflags &= ~flags;
ev = CGEventCreate(NULL);
if (!ev) {
errlog("CGEventCreate() failed\n");
abort();
}
CGEventSetType(ev, kCGEventFlagsChanged);
CGEventSetFlags(ev, modflags);
CFRelease(ev);
}
ev = CGEventCreateKeyboardEvent(NULL, cgkc, pr == PR_PRESS);
if (!ev) {
errlog("CGEventCreateKeyboardEvent() failed\n");
abort();
}
flags = modflags;
if (is_keypad_key(key))
flags |= kCGEventFlagMaskNumericPad;
CGEventSetFlags(ev, flags);
CGEventPost(kCGHIDEventTap, ev);
CFRelease(ev);
}
char* get_clipboard_text(void)
{
OSStatus status;
PasteboardItemID itemid;
CFDataRef data;
char* txt;
size_t len;
/*
* To avoid error -25130 (badPasteboardSyncErr):
*
* "The pasteboard has been modified and must be synchronized before
* use."
*/
PasteboardSynchronize(clipboard);
status = PasteboardGetItemIdentifier(clipboard, 1, &itemid);
if (status != noErr) {
errlog("PasteboardGetItemIdentifier(1) failed (%d)\n", status);
return xstrdup("");
}
status = PasteboardCopyItemFlavorData(clipboard, itemid, PLAINTEXT, &data);
if (status != noErr) {
errlog("PasteboardCopyItemFlavorData(PLAINTEXT) failed (%d)\n", status);
return xstrdup("");
}
len = CFDataGetLength(data);
txt = xmalloc(len+1);
memcpy(txt, CFDataGetBytePtr(data), len);
txt[len] = '\0';
CFRelease(data);
return txt;
}
int set_clipboard_text(const char* text)
{
OSStatus status;
CFDataRef data;
int ret = 0;
data = CFDataCreate(NULL, (UInt8*)text, strlen(text));
if (!data) {
errlog("CFDataCreate() failed\n");
return -1;
}
/*
* To avoid error -25135 (notPasteboardOwnerErr):
*
* "The application did not clear the pasteboard before attempting to
* add flavor data."
*/
PasteboardClear(clipboard);
status = PasteboardPutItemFlavor(clipboard, (PasteboardItemID)data,
PLAINTEXT, data, 0);
if (status != noErr) {
errlog("PasteboardPutItemFlavor() failed (%d)\n", status);
ret = -1;
}
CFRelease(data);
return ret;
}
static struct xypoint saved_mousepos;
int grab_inputs(void)
{
saved_mousepos = get_mousepos();
if (CGDisplayHideCursor(kCGDirectMainDisplay) != kCGErrorSuccess)
return 1;
if (CGAssociateMouseAndMouseCursorPosition(false) != kCGErrorSuccess) {
CGDisplayShowCursor(kCGDirectMainDisplay);
return 1;
}
return 0;
}
void ungrab_inputs(int restore_mousepos)
{
CGAssociateMouseAndMouseCursorPosition(true);
if (restore_mousepos)
set_mousepos_silent(saved_mousepos);
CGDisplayShowCursor(kCGDirectMainDisplay);
}
struct fdmon_ctx {
int fd;
fdmon_callback_t readcb, writecb;
void* arg;
uint32_t flags;
int refcount;
CFFileDescriptorRef fdref;
CFRunLoopSourceRef rlsrc;
};
static void fdmon_ref(struct fdmon_ctx* ctx)
{
assert(ctx->refcount > 0);
ctx->refcount += 1;
}
static void fdmon_unref(struct fdmon_ctx* ctx)
{
assert(ctx->refcount > 0);
ctx->refcount -= 1;
if (ctx->refcount)
return;
CFFileDescriptorDisableCallBacks(ctx->fdref, kCFFileDescriptorReadCallBack
|kCFFileDescriptorWriteCallBack);
CFRunLoopRemoveSource(CFRunLoopGetMain(), ctx->rlsrc, kCFRunLoopCommonModes);
CFRunLoopSourceInvalidate(ctx->rlsrc);
CFFileDescriptorInvalidate(ctx->fdref);
CFRelease(ctx->fdref);
CFRelease(ctx->rlsrc);
xfree(ctx);
}
static void fdmon_set_enabled_callbacks(struct fdmon_ctx* ctx)
{
CFOptionFlags cf_en = 0, cf_dis = 0;
if (ctx->flags & FM_READ)
cf_en |= kCFFileDescriptorReadCallBack;
else
cf_dis |= kCFFileDescriptorReadCallBack;
if (ctx->flags & FM_WRITE)
cf_en |= kCFFileDescriptorWriteCallBack;
else
cf_dis |= kCFFileDescriptorWriteCallBack;
if (cf_en)
CFFileDescriptorEnableCallBacks(ctx->fdref, cf_en);
if (cf_dis)
CFFileDescriptorDisableCallBacks(ctx->fdref, cf_dis);
}
static void fdmon_callback(CFFileDescriptorRef fdref, CFOptionFlags types, void* arg)
{
struct fdmon_ctx* ctx = arg;
/* Callbacks could free ctx, so grab a reference here */
fdmon_ref(ctx);
if (types & kCFFileDescriptorReadCallBack)
ctx->readcb(ctx, ctx->arg);
if (types & kCFFileDescriptorWriteCallBack)
ctx->writecb(ctx, ctx->arg);
/* Callbacks are one-shot only; re-enable the next one(s) here */
fdmon_set_enabled_callbacks(ctx);
fdmon_unref(ctx);
}
struct fdmon_ctx* fdmon_register_fd(int fd, fdmon_callback_t readcb,
fdmon_callback_t writecb, void* arg)
{
CFFileDescriptorContext fdctx = {
.version = 0,
.retain = NULL,
.release = NULL,
.copyDescription = NULL,
};
struct fdmon_ctx* ctx = xmalloc(sizeof(*ctx));
fdctx.info = ctx;
ctx->fd = fd;
ctx->readcb = readcb;
ctx->writecb = writecb;
ctx->arg = arg;
ctx->flags = 0;
ctx->refcount = 1;
ctx->fdref = CFFileDescriptorCreate(kCFAllocatorDefault, ctx->fd, false,
fdmon_callback, &fdctx);
if (!ctx->fdref) {
errlog("CFFileDescriptorCreate() failed\n");
abort();
}
ctx->rlsrc = CFFileDescriptorCreateRunLoopSource(kCFAllocatorDefault,
ctx->fdref, 0);
if (!ctx->rlsrc) {
errlog("CFFileDescriptorCreateRunLoopSource() failed\n");
abort();
}
CFRunLoopAddSource(CFRunLoopGetMain(), ctx->rlsrc, kCFRunLoopCommonModes);
return ctx;
}
void fdmon_unregister(struct fdmon_ctx* ctx)
{
fdmon_unmonitor(ctx, FM_READ|FM_WRITE);
fdmon_unref(ctx);
}
void fdmon_monitor(struct fdmon_ctx* ctx, uint32_t flags)
{
if (flags & ~(FM_READ|FM_WRITE)) {
errlog("invalid fdmon flags: %u\n", flags);
abort();
}
ctx->flags |= flags;
fdmon_set_enabled_callbacks(ctx);
}
void fdmon_unmonitor(struct fdmon_ctx* ctx, uint32_t flags)
{
if (flags & ~(FM_READ|FM_WRITE)) {
errlog("invalid fdmon flags: %u\n", flags);
abort();
}
ctx->flags &= ~flags;
fdmon_set_enabled_callbacks(ctx);
}
struct timerinfo {
CFRunLoopTimerRef timer;
void (*cbfn)(void* arg);
void* cbarg;
void (*cbarg_dtor)(void*);
};
static void free_timerinfo(struct timerinfo* ti)
{
if (ti->cbarg_dtor)
ti->cbarg_dtor(ti->cbarg);
xfree(ti);
}
static void timer_callback(CFRunLoopTimerRef timer, void* info)
{
struct timerinfo* ti = info;
ti->cbfn(ti->cbarg);
CFRunLoopRemoveTimer(CFRunLoopGetMain(), ti->timer, kCFRunLoopCommonModes);
CFRelease(ti->timer);
free_timerinfo(ti);
}