forked from daar/GLPT
-
Notifications
You must be signed in to change notification settings - Fork 1
/
GLPT_Cocoa.inc
1498 lines (1305 loc) · 48.6 KB
/
GLPT_Cocoa.inc
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
const
GLPT_KEY_UNKNOWN = 0;
var
darwin_scancode_table: array[0..127] of GLPT_Scancode = (
{ 0 } GLPT_SCANCODE_A,
{ 1 } GLPT_SCANCODE_S,
{ 2 } GLPT_SCANCODE_D,
{ 3 } GLPT_SCANCODE_F,
{ 4 } GLPT_SCANCODE_H,
{ 5 } GLPT_SCANCODE_G,
{ 6 } GLPT_SCANCODE_Z,
{ 7 } GLPT_SCANCODE_X,
{ 8 } GLPT_SCANCODE_C,
{ 9 } GLPT_SCANCODE_V,
{ 10 } GLPT_SCANCODE_NONUSBACKSLASH, { GLPT_SCANCODE_NONUSBACKSLASH on ANSI and JIS keyboards (if this key would exist there), GLPT_SCANCODE_GRAVE on ISO. (The USB keyboard driver actually translates these usage codes to different virtual key codes depending on whether the keyboard is ISO/ANSI/JIS. That's why you have to help it identify the keyboard type when you plug in a PC USB keyboard. It's a historical thing - ADB keyboards are wired this way.) }
{ 11 } GLPT_SCANCODE_B,
{ 12 } GLPT_SCANCODE_Q,
{ 13 } GLPT_SCANCODE_W,
{ 14 } GLPT_SCANCODE_E,
{ 15 } GLPT_SCANCODE_R,
{ 16 } GLPT_SCANCODE_Y,
{ 17 } GLPT_SCANCODE_T,
{ 18 } GLPT_SCANCODE_1,
{ 19 } GLPT_SCANCODE_2,
{ 20 } GLPT_SCANCODE_3,
{ 21 } GLPT_SCANCODE_4,
{ 22 } GLPT_SCANCODE_6,
{ 23 } GLPT_SCANCODE_5,
{ 24 } GLPT_SCANCODE_EQUALS,
{ 25 } GLPT_SCANCODE_9,
{ 26 } GLPT_SCANCODE_7,
{ 27 } GLPT_SCANCODE_MINUS,
{ 28 } GLPT_SCANCODE_8,
{ 29 } GLPT_SCANCODE_0,
{ 30 } GLPT_SCANCODE_RIGHTBRACKET,
{ 31 } GLPT_SCANCODE_O,
{ 32 } GLPT_SCANCODE_U,
{ 33 } GLPT_SCANCODE_LEFTBRACKET,
{ 34 } GLPT_SCANCODE_I,
{ 35 } GLPT_SCANCODE_P,
{ 36 } GLPT_SCANCODE_RETURN,
{ 37 } GLPT_SCANCODE_L,
{ 38 } GLPT_SCANCODE_J,
{ 39 } GLPT_SCANCODE_APOSTROPHE,
{ 40 } GLPT_SCANCODE_K,
{ 41 } GLPT_SCANCODE_SEMICOLON,
{ 42 } GLPT_SCANCODE_BACKSLASH,
{ 43 } GLPT_SCANCODE_COMMA,
{ 44 } GLPT_SCANCODE_SLASH,
{ 45 } GLPT_SCANCODE_N,
{ 46 } GLPT_SCANCODE_M,
{ 47 } GLPT_SCANCODE_PERIOD,
{ 48 } GLPT_SCANCODE_TAB,
{ 49 } GLPT_SCANCODE_SPACE,
{ 50 } GLPT_SCANCODE_GRAVE, { GLPT_SCANCODE_GRAVE on ANSI and JIS keyboards, GLPT_SCANCODE_NONUSBACKSLASH on ISO (see comment about virtual key code 10 above) }
{ 51 } GLPT_SCANCODE_BACKSPACE,
{ 52 } GLPT_SCANCODE_KP_ENTER, { keyboard enter on portables }
{ 53 } GLPT_SCANCODE_ESCAPE,
{ 54 } GLPT_SCANCODE_RGUI,
{ 55 } GLPT_SCANCODE_LGUI,
{ 56 } GLPT_SCANCODE_LSHIFT,
{ 57 } GLPT_SCANCODE_CAPSLOCK,
{ 58 } GLPT_SCANCODE_LALT,
{ 59 } GLPT_SCANCODE_LCTRL,
{ 60 } GLPT_SCANCODE_RSHIFT,
{ 61 } GLPT_SCANCODE_RALT,
{ 62 } GLPT_SCANCODE_RCTRL,
{ 63 } GLPT_SCANCODE_RGUI, { fn on portables, acts as a hardware-level modifier already, so we don't generate events for it, also XK_Meta_R }
{ 64 } GLPT_SCANCODE_F17,
{ 65 } GLPT_SCANCODE_KP_PERIOD,
{ 66 } GLPT_SCANCODE_UNKNOWN, { unknown (unused?) }
{ 67 } GLPT_SCANCODE_KP_MULTIPLY,
{ 68 } GLPT_SCANCODE_UNKNOWN, { unknown (unused?) }
{ 69 } GLPT_SCANCODE_KP_PLUS,
{ 70 } GLPT_SCANCODE_UNKNOWN, { unknown (unused?) }
{ 71 } GLPT_SCANCODE_NUMLOCKCLEAR,
{ 72 } GLPT_SCANCODE_VOLUMEUP,
{ 73 } GLPT_SCANCODE_VOLUMEDOWN,
{ 74 } GLPT_SCANCODE_MUTE,
{ 75 } GLPT_SCANCODE_KP_DIVIDE,
{ 76 } GLPT_SCANCODE_KP_ENTER, { keypad enter on external keyboards, fn-return on portables }
{ 77 } GLPT_SCANCODE_UNKNOWN, { unknown (unused?) }
{ 78 } GLPT_SCANCODE_KP_MINUS,
{ 79 } GLPT_SCANCODE_F18,
{ 80 } GLPT_SCANCODE_F19,
{ 81 } GLPT_SCANCODE_KP_EQUALS,
{ 82 } GLPT_SCANCODE_KP_0,
{ 83 } GLPT_SCANCODE_KP_1,
{ 84 } GLPT_SCANCODE_KP_2,
{ 85 } GLPT_SCANCODE_KP_3,
{ 86 } GLPT_SCANCODE_KP_4,
{ 87 } GLPT_SCANCODE_KP_5,
{ 88 } GLPT_SCANCODE_KP_6,
{ 89 } GLPT_SCANCODE_KP_7,
{ 90 } GLPT_SCANCODE_UNKNOWN, { unknown (unused?) }
{ 91 } GLPT_SCANCODE_KP_8,
{ 92 } GLPT_SCANCODE_KP_9,
{ 93 } GLPT_SCANCODE_INTERNATIONAL3, { Cosmo_USB2ADB.c says "Yen (JIS)" }
{ 94 } GLPT_SCANCODE_INTERNATIONAL1, { Cosmo_USB2ADB.c says "Ro (JIS)" }
{ 95 } GLPT_SCANCODE_KP_COMMA, { Cosmo_USB2ADB.c says ", JIS only" }
{ 96 } GLPT_SCANCODE_F5,
{ 97 } GLPT_SCANCODE_F6,
{ 98 } GLPT_SCANCODE_F7,
{ 99 } GLPT_SCANCODE_F3,
{ 100 } GLPT_SCANCODE_F8,
{ 101 } GLPT_SCANCODE_F9,
{ 102 } GLPT_SCANCODE_LANG2, { Cosmo_USB2ADB.c says "Eisu" }
{ 103 } GLPT_SCANCODE_F11,
{ 104 } GLPT_SCANCODE_LANG1, { Cosmo_USB2ADB.c says "Kana" }
{ 105 } GLPT_SCANCODE_PRINTSCREEN, { On ADB keyboards, this key is labeled "F13/print screen". Problem: USB has different usage codes for these two functions. On Apple USB keyboards, the key is labeled "F13" and sends the F13 usage code (GLPT_SCANCODE_F13). I decided to use GLPT_SCANCODE_PRINTSCREEN here nevertheless since SDL applications are more likely to assume the presence of a print screen key than an F13 key. }
{ 106 } GLPT_SCANCODE_F16,
{ 107 } GLPT_SCANCODE_SCROLLLOCK, { F14/scroll lock, see comment about F13/print screen above }
{ 108 } GLPT_SCANCODE_UNKNOWN, { unknown (unused?) }
{ 109 } GLPT_SCANCODE_F10,
{ 110 } GLPT_SCANCODE_APPLICATION, { windows contextual menu key, fn-enter on portables }
{ 111 } GLPT_SCANCODE_F12,
{ 112 } GLPT_SCANCODE_UNKNOWN, { unknown (unused?) }
{ 113 } GLPT_SCANCODE_PAUSE, { F15/pause, see comment about F13/print screen above }
{ 114 } GLPT_SCANCODE_INSERT, { the key is actually labeled "help" on Apple keyboards, and works as such in Mac OS, but it sends the "insert" usage code even on Apple USB keyboards }
{ 115 } GLPT_SCANCODE_HOME,
{ 116 } GLPT_SCANCODE_PAGEUP,
{ 117 } GLPT_SCANCODE_DELETE,
{ 118 } GLPT_SCANCODE_F4,
{ 119 } GLPT_SCANCODE_END,
{ 120 } GLPT_SCANCODE_F2,
{ 121 } GLPT_SCANCODE_PAGEDOWN,
{ 122 } GLPT_SCANCODE_F1,
{ 123 } GLPT_SCANCODE_LEFT,
{ 124 } GLPT_SCANCODE_RIGHT,
{ 125 } GLPT_SCANCODE_DOWN,
{ 126 } GLPT_SCANCODE_UP,
{ 127 } GLPT_SCANCODE_POWER
);
// SDL_cocoakeyboard.m
(*
static void
UpdateKeymap(SDL_VideoData *data, SDL_bool send_event)
{
TISInputSourceRef key_layout;
const void *chr_data;
int i;
SDL_Scancode scancode;
SDL_Keycode keymap[SDL_NUM_SCANCODES];
/* See if the keymap needs to be updated */
key_layout = TISCopyCurrentKeyboardLayoutInputSource();
if (key_layout == data->key_layout) {
return;
}
data->key_layout = key_layout;
SDL_GetDefaultKeymap(keymap);
/* Try Unicode data first */
CFDataRef uchrDataRef = TISGetInputSourceProperty(key_layout, kTISPropertyUnicodeKeyLayoutData);
if (uchrDataRef) {
chr_data = CFDataGetBytePtr(uchrDataRef);
} else {
goto cleanup;
}
if (chr_data) {
UInt32 keyboard_type = LMGetKbdType();
OSStatus err;
for (i = 0; i < SDL_arraysize(darwin_scancode_table); i++) {
UniChar s[8];
UniCharCount len;
UInt32 dead_key_state;
/* Make sure this scancode is a valid character scancode */
scancode = darwin_scancode_table[i];
if (scancode == SDL_SCANCODE_UNKNOWN ||
(keymap[scancode] & SDLK_SCANCODE_MASK)) {
continue;
}
dead_key_state = 0;
err = UCKeyTranslate ((UCKeyboardLayout ) chr_data,
i, kUCKeyActionDown,
0, keyboard_type,
kUCKeyTranslateNoDeadKeysMask,
&dead_key_state, 8, &len, s);
if (err != noErr) {
continue;
}
if (len > 0 && s[0] != 0x10) {
keymap[scancode] = s[0];
}
}
SDL_SetKeymap(0, keymap, SDL_NUM_SCANCODES);
if (send_event) {
SDL_SendKeymapChangedEvent();
}
return;
}
cleanup:
CFRelease(key_layout);
}
*)
//#########################################################
// COCOA UTILS
//#########################################################
{$if FPC_FULLVERSION <= 30004}
type
objcbool = bool;
{$endif}
type
NSFileManager_Additions = objccategory external (NSFileManager)
function createDirectoryAtURL_withIntermediateDirectories_attributes_error (url: NSURL; createIntermediates: boolean; attributes: NSDictionary; error: NSErrorPtr): boolean; message 'createDirectoryAtURL:withIntermediateDirectories:attributes:error:'; { available in 10_7, 5_0 }
end;
function NSSTR(str: string): NSString; overload;
begin
result := NSString.stringWithCString_length(@str[1], length(str));
end;
//#########################################################
// COCOA WINDOWS
//#########################################################
type
TBorderlessWindow = objcclass (NSWindow)
public
function initWithContentRect_styleMask_backing_defer (contentRect: NSRect; aStyle: NSUInteger; bufferingType: NSBackingStoreType; flag: objcbool): id; override;
function initWithContentRect(contentRect: NSRect): id; message 'initWithContentRect:';
function canBecomeKeyWindow: objcbool; override;
function canBecomeMainWindow: objcbool; override;
procedure setKeepFullScreenAlways (newValue: boolean); message 'setKeepFullScreenAlways:';
procedure dealloc; override;
private
keepFullScreenAlways: boolean;
procedure screenParametersChanged (notification: NSNotification); message 'screenParametersChanged:';
end;
function TBorderlessWindow.canBecomeKeyWindow: objcbool;
begin
result := true;
end;
function TBorderlessWindow.canBecomeMainWindow: objcbool;
begin
result := true;
end;
procedure TBorderlessWindow.setKeepFullScreenAlways (newValue: boolean);
begin
orderFrontRegardless;
keepFullScreenAlways := newValue;
if keepFullScreenAlways then
setFrame_display(screen.frame, true);
end;
procedure TBorderlessWindow.screenParametersChanged (notification: NSNotification);
begin
if keepFullScreenAlways then
setFrame_display(NSScreen.mainScreen.frame, true);
end;
procedure TBorderlessWindow.dealloc;
begin
NSNotificationCenter.defaultCenter.removeObserver(self);
inherited dealloc;
end;
function TBorderlessWindow.initWithContentRect_styleMask_backing_defer (contentRect: NSRect; aStyle: NSUInteger; bufferingType: NSBackingStoreType; flag: objcbool): id;
begin
result := inherited initWithContentRect_styleMask_backing_defer(contentRect, aStyle, bufferingType, flag);
if result <> nil then
NSNotificationCenter(NSNotificationCenter.defaultCenter).addObserver_selector_name_object(result, objcselector('screenParametersChanged:'), NSApplicationDidChangeScreenParametersNotification, nil);
end;
function TBorderlessWindow.initWithContentRect(contentRect: NSRect): id;
begin
result := initWithContentRect_styleMask_backing_defer(contentRect, NSBorderlessWindowMask, NSBackingStoreBuffered, false);
if result <> nil then
begin
result.setMovableByWindowBackground(false);
//result.setBackgroundColor(NSColor.clearColor);
//result.setOpaque(false);
result.setHasShadow(false);
result.setExcludedFromWindowsMenu(true);
self := result;
end;
end;
type
TCocoaWindow = objcclass (TBorderlessWindow)
public
procedure close; override;
procedure becomeKeyWindow; override;
procedure resignKeyWindow; override;
procedure doCommandBySelector(aSelector: SEL); override;
private
ref: pGLPTwindow;
end;
procedure TCocoaWindow.close;
begin
ref^.shouldClose := true;
inherited;
end;
procedure TCocoaWindow.doCommandBySelector(aSelector: SEL);
begin
// do nothing to prevent beeping
end;
procedure TCocoaWindow.becomeKeyWindow;
var
params: GLPT_MessageParams;
begin
inherited;
FillChar(params, sizeof(params), 0);
glptPostMessage(ref, GLPT_MESSAGE_ACTIVATE, params);
end;
procedure TCocoaWindow.resignKeyWindow;
var
params: GLPT_MessageParams;
begin
inherited;
FillChar(params, sizeof(params), 0);
glptPostMessage(ref, GLPT_MESSAGE_DEACTIVATE, params);
end;
//#########################################################
// COCOA APP
//#########################################################
type
TCocoaApp = objcclass (NSApplication)
procedure poll; message 'poll';
end;
type
TCocoaAppDelegate = objcclass (NSObject, NSApplicationDelegateProtocol)
end;
function Cocoa_GetKeyboardShiftState: TShiftState; forward;
function Cocoa_GetTime: double; forward;
{$ifdef GLPT_GAMEPAD}
procedure Cocoa_PollDevices; forward;
{$endif}
procedure TCocoaApp.poll;
var
event: NSEvent;
params: GLPT_MessageParams;
win: pGLPTwindow = nil;
pool: NSAutoreleasePool;
keymap: GLPTKeymapArrayPtr;
begin
{$ifdef GLPT_GAMEPAD}
Cocoa_PollDevices;
{$endif}
pool := NSAutoreleasePool.alloc.init;
event := nextEventMatchingMask_untilDate_inMode_dequeue(NSAnyEventMask, nil, NSDefaultRunLoopMode, true);
if event <> nil then
begin
//writeln(event.description.utf8string);
if event.window <> nil then
win := TCocoaWindow(event.window).ref;
case event.type_ of
NSScrollWheel:
begin
params.mouse.x := Trunc(event.locationInWindow.x);
params.mouse.y := Trunc(event.window.contentView.frame.size.height - event.locationInWindow.y);
params.mouse.deltaX := event.deltaX;
params.mouse.deltaY := event.deltaY;
params.mouse.timestamp := Cocoa_GetTime;
params.mouse.shiftstate := Cocoa_GetKeyboardShiftState;
glptPostMessage(win, GLPT_MESSAGE_SCROLL, params);
end;
NSLeftMouseDragged, NSRightMouseDragged:
begin
params.mouse.x := Trunc(event.locationInWindow.x);
params.mouse.y := Trunc(event.window.contentView.frame.size.height - event.locationInWindow.y);
params.mouse.shiftstate := Cocoa_GetKeyboardShiftState;
params.mouse.timestamp := Cocoa_GetTime;
glptPostMessage(win, GLPT_MESSAGE_MOUSEMOVE, params);
end;
NSMouseMoved:
begin
params.mouse.x := Trunc(event.locationInWindow.x);
params.mouse.y := Trunc(event.window.contentView.frame.size.height - event.locationInWindow.y);
params.mouse.shiftstate := Cocoa_GetKeyboardShiftState;
params.mouse.timestamp := Cocoa_GetTime;
glptPostMessage(win, GLPT_MESSAGE_MOUSEMOVE, params);
end;
NSLeftMouseDown, NSRightMouseDown:
begin
params.mouse.x := Trunc(event.locationInWindow.x);
params.mouse.y := Trunc(event.window.contentView.frame.size.height - event.locationInWindow.y);
params.mouse.clicks := event.clickCount;
// ignore clicks outside of content view, which is probably the title bar
if (params.mouse.x > 0) and (params.mouse.y > 0) then
begin
params.mouse.shiftstate := Cocoa_GetKeyboardShiftState;
params.mouse.timestamp := Cocoa_GetTime;
case event.type_ of
NSLeftMouseDown:
params.mouse.buttons := GLPT_MOUSE_BUTTON_LEFT;
NSRightMouseDown:
params.mouse.buttons := GLPT_MOUSE_BUTTON_RIGHT;
end;
glptPostMessage(win, GLPT_MESSAGE_MOUSEDOWN, params);
end;
end;
NSLeftMouseUp, NSRightMouseUp:
begin
params.mouse.x := Trunc(event.locationInWindow.x);
params.mouse.y := Trunc(event.window.contentView.frame.size.height - event.locationInWindow.y);
params.mouse.shiftstate := Cocoa_GetKeyboardShiftState;
params.mouse.timestamp := Cocoa_GetTime;
case event.type_ of
NSLeftMouseUp:
params.mouse.buttons := GLPT_MOUSE_BUTTON_LEFT;
NSRightMouseUp:
params.mouse.buttons := GLPT_MOUSE_BUTTON_RIGHT;
end;
glptPostMessage(win, GLPT_MESSAGE_MOUSEUP, params);
end;
NSKeyDown, NSKeyUp:
begin
// todo: implement UpdateKeymap
keymap := @GLPT_default_keymap;
params.keyboard.scancode := darwin_scancode_table[event.keycode];
params.keyboard.keycode := keymap^[params.keyboard.scancode];
params.keyboard.shiftstate := Cocoa_GetKeyboardShiftState;
//writeln('scancode:',params.keyboard.scancode);
//writeln('keycode:',params.keyboard.keycode);
//writeln('keychar:',chr(params.keyboard.keycode));
//writeln('name:',GLPT_GetScancodeName(params.keyboard.scancode));
case event.type_ of
NSKeyDown:
glptPostMessage(win, GLPT_MESSAGE_KEYPRESS, params);
NSKeyUp:
glptPostMessage(win, GLPT_MESSAGE_KEYRELEASE, params);
end;
end;
otherwise
;
end;
sendEvent(event);
updateWindows;
end;
pool.release;
end;
//#########################################################
// COCOA OPENGL VIEW
//#########################################################
type
TOpenGLView = objcclass (NSView)
public
function initWithFrame(frameRect: NSRect): id; override;
function isOpaque: objcbool; override;
procedure viewDidMoveToWindow; override;
procedure mouseEntered(theEvent: NSEvent); override;
procedure mouseExited(theEvent: NSEvent); override;
procedure doCommandBySelector(aSelector: SEL); override;
procedure keyDown(theEvent: NSEvent); override;
procedure drawRect(dirtyRect: NSRect); override;
procedure dealloc; override;
procedure updateTrackingAreas; override;
private
openGLContext: NSOpenGLContext;
trackingArea: NSTrackingArea;
displayLink: CVDisplayLinkRef;
displayLinkSemaphore: pGLPT_Semaphore;
isLiveResizing: boolean;
function defaultPixelFormat: NSOpenGLPixelFormat; message 'defaultPixelFormat';
function windowRef: pGLPTwindow; message 'windowRef';
function glptContext: GLPT_Context; message 'glptContext';
procedure setupContext; message 'setupContext';
procedure frameChanged (sender: NSNotification); message 'frameChanged:';
procedure windowWillStartLiveResize (sender: NSNotification); message 'windowWillStartLiveResize:';
procedure windowDidEndLiveResize (sender: NSNotification); message 'windowDidEndLiveResize:';
procedure reshape; message 'reshape';
end;
// note: setValues_forParameter in RTL headers is parsed wrong
type
NSOpenGLContext_Fixed = objccategory external (NSOpenGLContext)
procedure setValues_forParameter_fixed (vals: pointer; param: NSOpenGLContextParameter); overload; message 'setValues:forParameter:';
end;
function TOpenGLView.windowRef: pGLPTwindow;
begin
result := TCocoaWindow(window).ref;
end;
procedure TOpenGLView.updateTrackingAreas;
begin
if trackingArea <> nil then
removeTrackingArea(trackingArea);
trackingArea := NSTrackingArea.alloc.initWithRect_options_owner_userInfo(bounds, NSTrackingMouseEnteredAndExited + NSTrackingActiveAlways, self, nil).autorelease;
addTrackingArea(trackingArea);
end;
procedure TOpenGLView.keyDown(theEvent: NSEvent);
begin
// do nothing to prevent beeping
end;
procedure TOpenGLView.doCommandBySelector(aSelector: SEL);
begin
// do nothing to prevent beeping
end;
procedure TOpenGLView.mouseEntered(theEvent: NSEvent);
var
params: GLPT_MessageParams;
begin
FillChar(params, sizeof(params), 0);
glptPostMessage(windowRef, GLPT_MESSAGE_MOUSEENTER, params);
end;
procedure TOpenGLView.mouseExited(theEvent: NSEvent);
var
params: GLPT_MessageParams;
begin
FillChar(params, sizeof(params), 0);
glptPostMessage(windowRef, GLPT_MESSAGE_MOUSEEXIT, params);
end;
function DisplayLinkOutputCallback (displayLink: CVDisplayLinkRef; inNow: CVTimeStampPtr; inOutputTime: CVTimeStampPtr; flagsIn: CVOptionFlags; var flagsOut: CVOptionFlags; displayLinkContext: pointer): CVReturn; cdecl;
begin
GLPT_SemaphorePost(TOpenGLView(displayLinkContext).displayLinkSemaphore);
result := 0;
end;
function TOpenGLView.glptContext: GLPT_Context;
begin
result := TCocoaWindow(window).ref^.context;
end;
procedure TOpenGLView.setupContext;
var
opacity: integer = 0;
pixelFormat: NSOpenGLPixelFormat;
begin
pixelFormat := defaultPixelFormat;
openGLContext := NSOpenGLContext.alloc.initWithFormat_shareContext(pixelFormat, nil);
if openGLContext = nil then
GLPTError(GLPT_ERROR_PLATFORM, 'invalid NSOpenGLContext');
openGLContext.makeCurrentContext;
openGLContext.setView(self);
{$if FPC_FULLVERSION > 30004}
setWantsBestResolutionOpenGLSurface(glptContext.bestResolution);
{$endif}
// enable vsync
if glptContext.vsync then
begin
displayLinkSemaphore := GLPT_CreateSemaphore(0);
CVDisplayLinkCreateWithActiveCGDisplays(displayLink);
CVDisplayLinkSetOutputCallback(displayLink, CVDisplayLinkOutputCallback(@DisplayLinkOutputCallback), self);
CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext(displayLink, openGLContext.CGLContextObj, pixelFormat.CGLPixelFormatObj);
CVDisplayLinkStart(displayLink);
end;
if not isOpaque then
openGLContext.setValues_forParameter_fixed(@opacity, NSOpenGLCPSurfaceOpacity);
end;
procedure TOpenGLView.viewDidMoveToWindow;
begin
inherited viewDidMoveToWindow;
if openGLContext = nil then
setupContext;
if window = nil then
openGLContext.clearDrawable;
end;
procedure TOpenGLView.frameChanged (sender: NSNotification);
begin
if not isLiveResizing and assigned(openGLContext) then
reshape;
end;
procedure TOpenGLView.windowWillStartLiveResize (sender: NSNotification);
begin
isLiveResizing := true;
end;
procedure TOpenGLView.windowDidEndLiveResize (sender: NSNotification);
begin
isLiveResizing := false;
reshape;
end;
procedure TOpenGLView.drawRect(dirtyRect: NSRect);
begin
openGLContext.flushBuffer;
end;
procedure TOpenGLView.reshape;
var
params: GLPT_MessageParams;
begin
openGLContext.update;
if window <> nil then
begin
params.rect.top := 0;
params.rect.left := 0;
params.rect.width := Trunc(bounds.size.width);
params.rect.height := Trunc(bounds.size.height);
glptPostMessage(windowRef, GLPT_MESSAGE_RESIZE, params);
end;
end;
function TOpenGLView.isOpaque: objcbool;
begin
// return false to make the view transparent
result := window.backgroundColor.alphaComponent > 0;
end;
function TOpenGLView.defaultPixelFormat: NSOpenGLPixelFormat;
function Inc (var i: integer): integer;
begin
i += 1;
result := i;
end;
var
attributes: array[0..32] of NSOpenGLPixelFormatAttribute;
i: integer = -1;
procedure Add(name: NSOpenGLPixelFormatAttribute; value: integer = -1);
begin
attributes[Inc(i)] := name;
if value <> -1 then
attributes[Inc(i)] := value;
end;
const
NSOpenGLPFAOpenGLProfile = 99 { available in 10_7 };
const
NSOpenGLProfileVersionLegacy = $1000 { available in 10_7 };
NSOpenGLProfileVersion3_2Core = $3200 { available in 10_7 };
NSOpenGLProfileVersion4_1Core = $4100 { available in 10_10 };
var
context: GLPT_Context;
begin
context := glptContext;
if context.doubleBuffer then
Add(NSOpenGLPFADoubleBuffer);
Add(NSOpenGLPFAColorSize, context.colorSize);
Add(NSOpenGLPFADepthSize, context.depthSize);
Add(NSOpenGLPFAStencilSize, context.stencilSize);
//Add(NSOpenGLPFAOffScreen, 1);
if context.multiSamples > 0 then
begin
Add(NSOpenGLPFAMultisample, 1);
Add(NSOpenGLPFASampleBuffers, 1);
Add(NSOpenGLPFASamples, context.multiSamples);
end;
// we can only specify "legacy" or "core" on mac and the system will decide what version we actually get
Add(NSOpenGLPFAOpenGLProfile);
if context.profile = GLPT_CONTEXT_PROFILE_LEGACY then
Add(NSOpenGLProfileVersionLegacy)
else if context.profile = GLPT_CONTEXT_PROFILE_CORE then
begin
if context.majorVersion = 3 then
Add(NSOpenGLProfileVersion3_2Core)
else if context.majorVersion = 4 then
Add(NSOpenGLProfileVersion4_1Core)
else
glptError(GLPT_ERROR_PLATFORM, 'invalid core profile major version');
end
else
glptError(GLPT_ERROR_PLATFORM, 'invalid context profile');
// terminate with 0
Add(0);
result := NSOpenGLPixelFormat.alloc.initWithAttributes(@attributes).autorelease;
if result = nil then
glptError(GLPT_ERROR_PLATFORM, 'invalid NSOpenGLPixelFormat');
end;
procedure TOpenGLView.dealloc;
begin
if displayLink <> nil then
CVDisplayLinkRelease(displayLink);
if displayLinkSemaphore <> nil then
GLPT_DestroySemaphore(displayLinkSemaphore);
inherited dealloc;
end;
function TOpenGLView.initWithFrame(frameRect: NSRect): id;
begin
result := inherited initWithFrame(frameRect);
if result <> nil then
begin
NSNotificationCenter.defaultCenter.addObserver_selector_name_object(result, objcselector('windowWillStartLiveResize:'), NSWindowWillStartLiveResizeNotification, nil);
NSNotificationCenter.defaultCenter.addObserver_selector_name_object(result, objcselector('windowDidEndLiveResize:'), NSWindowDidEndLiveResizeNotification, nil);
NSNotificationCenter.defaultCenter.addObserver_selector_name_object(result, objcselector('frameChanged:'), NSViewGlobalFrameDidChangeNotification, nil);
end;
end;
//#########################################################
// GLPT FUNCTIONS
//#########################################################
procedure Cocoa_Delay(ms: longint);
begin
NSThread.sleepForTimeInterval(ms/1000);
end;
procedure Cocoa_Delay(ms: double);
begin
NSThread.sleepForTimeInterval(ms);
end;
function Cocoa_GetTime: double;
begin
result := NSDate.date.timeIntervalSince1970;
end;
function Cocoa_Terminate: boolean;
begin
NSApp.terminate(nil);
exit(True);
end;
procedure Cocoa_DestroyWindow(var win: pGLPTwindow);
begin
win^.ref.close;
win^.ref := nil;
end;
function Cocoa_CreateWindow(win: pGLPTwindow; posx, posy, sizex, sizey: integer; title: PChar): boolean;
const
NSWindowCollectionBehaviorFullScreenPrimary = 1 shl 7 { available in 10_7 };
NSWindowCollectionBehaviorFullScreenAuxiliary = 1 shl 8 { available in 10_7 };
var
window: TCocoaWindow;
openGLView: TOpenGLView;
screen: NSScreen;
windowFlags: NSUInteger = 0;
flags: longint;
begin
flags := win^.flags;
if flags = GLPT_WINDOW_DEFAULT then
begin
windowFlags := NSTitledWindowMask + NSClosableWindowMask + NSMiniaturizableWindowMask + NSResizableWindowMask;
end
else
begin
if flags = (flags or GLPT_WINDOW_TITLED) then
windowFlags += NSTitledWindowMask;
if flags = (flags or GLPT_WINDOW_CLOSABLE) then
windowFlags += NSClosableWindowMask;
if flags = (flags or GLPT_WINDOW_MINIATURIZABLE) then
windowFlags += NSMiniaturizableWindowMask;
if flags = (flags or GLPT_WINDOW_RESIZABLE) then
windowFlags += NSResizableWindowMask;
if flags = (flags or GLPT_WINDOW_BORDERLESS) then
windowFlags := NSBorderlessWindowMask;
end;
if flags <> (flags or GLPT_WINDOW_FULLSCREEN) then
begin
screen := NSScreen.mainScreen;
if posx = GLPT_WINDOW_POS_CENTER then
posx := trunc(NSWidth(screen.frame)/2 - sizex/2);
if posy = GLPT_WINDOW_POS_CENTER then
posy := trunc(NSHeight(screen.frame)/2 - sizey/2);
window := TCocoaWindow.alloc.initWithContentRect_styleMask_backing_defer(NSMakeRect(posx, posy, sizex, sizey), windowFlags, NSBackingStoreBuffered, false);
window.setTitle(NSSTR(title));
end
else
begin
window := TCocoaWindow.alloc.initWithContentRect(NSMakeRect(posx, posy, sizex, sizey));
window.setKeepFullScreenAlways(true);
end;
window.ref := win;
openGLView := TOpenGLView.alloc.initWithFrame(window.contentView.bounds);
//openGLView.setWantsLayer(true);
window.setContentView(openGLView);
openGLView.release;
window.makeFirstResponder(openGLView);
window.setCollectionBehavior(NSWindowCollectionBehaviorFullScreenPrimary);
window.setAcceptsMouseMovedEvents(true);
window.makeKeyAndOrderFront(nil);
win^.glcontext := openGLView.openGLContext;
win^.ref := window;
exit(True);
end;
function Cocoa_MakeCurrent(win: pGLPTwindow): boolean;
begin
win^.glcontext.makeCurrentContext;
exit(True);
end;
procedure Cocoa_SwapBuffers(win: pGLPTwindow);
var
view: TOpenGLView;
begin
view := TOpenGLView(win^.ref.contentView);
if assigned(view.displayLinkSemaphore) then
GLPT_SemaphoreWait(view.displayLinkSemaphore);
// note: on 10.14 NSView.display was giving a black screen
// https://stackoverflow.com/questions/52938516/opengl-not-rendering-on-macos-mojave
win^.ref.contentView.setNeedsDisplay_(true);
end;
procedure Cocoa_GetFrameBufferSize(win: pGLPTwindow; out width, height: integer);
begin
width:= Trunc(win^.ref.contentView.bounds.size.width);
height:= Trunc(win^.ref.contentView.bounds.size.height);
end;
procedure Cocoa_PollEvents;
begin
NSApp.performSelectorOnMainThread_withObject_waitUntilDone(objcselector('poll'), nil, true);
end;
procedure Cocoa_GetDisplayCoords(var dr: GLPTRect);
var
screenFrame: NSRect;
begin
screenFrame := NSScreen.mainScreen.frame;
dr.top := Trunc(NSMinY(screenFrame));
dr.left := Trunc(NSMinX(screenFrame));
dr.bottom := Trunc(NSMaxY(screenFrame));
dr.right := Trunc(NSMaxX(screenFrame));
end;
function Cocoa_GetBasePath: string;
begin
result := NSBundle.mainBundle.resourcePath.UTF8String+'/';
end;
function Cocoa_GetPrefPath (org: string; app: string): string;
var
applicationSupport: NSURL;
folder: NSURL;
begin
applicationSupport := NSFileManager.defaultManager.URLForDirectory_inDomain_appropriateForURL_create_error(NSApplicationSupportDirectory, NSUserDomainMask, nil, false, nil);
result := applicationSupport.path.UTF8String+'/'+org+'/'+app+'/';
folder := NSURL.fileURLWithPath(NSSTR(result));
NSFileManager.defaultManager.createDirectoryAtURL_withIntermediateDirectories_attributes_error(folder, true, nil, nil);
end;
function Cocoa_GetKeyboardShiftState: TShiftState;
var
modifierFlags: NSUInteger;
begin
modifierFlags := NSApp.currentEvent.modifierFlags;
Result := [];
if modifierFlags = (modifierFlags or NSShiftKeyMask) then
Include(Result, ssShift);
if modifierFlags = (modifierFlags or NSControlKeyMask) then
Include(Result, ssCtrl);
if modifierFlags = (modifierFlags or NSAlternateKeyMask) then
Include(Result, ssAlt);
if modifierFlags = (modifierFlags or NSCommandKeyMask) then
Include(Result, ssSuper);
end;
procedure SetupMainMenu;
procedure AddMenu (menu: NSMenu);
var
menuItem: NSMenuItem;
begin
menuItem := NSMenuItem.alloc.initWithTitle_action_keyEquivalent(menu.title, nil, NSSTR('')).autorelease;
menuItem.setSubmenu(menu);
NSApp.mainMenu.addItem(menuItem);
end;
var
mainMenu: NSMenu;
appleMenu: NSMenu;
windowMenu: NSMenu;
begin
// main menu
mainMenu := NSMenu.alloc.init.autorelease;
NSApp.setMainMenu(mainMenu);
// apple menu
appleMenu := NSMenu.alloc.initWithTitle(NSSTR('')).autorelease;
appleMenu.addItemWithTitle_action_keyEquivalent(NSSTR('Quit '+NSProcessInfo.processInfo.processName.UTF8String), objcselector('terminate:'), NSSTR('q'));
AddMenu(appleMenu);
// window menu
windowMenu := NSMenu.alloc.initWithTitle(NSSTR('Window')).autorelease;
windowMenu.addItemWithTitle_action_keyEquivalent(NSSTR('Minimize'), objcselector('performMiniaturize:'), NSSTR('m'));
windowMenu.addItemWithTitle_action_keyEquivalent(NSSTR('Zoom'), objcselector('performZoom:'), NSSTR(''));
AddMenu(windowMenu);
end;
//#########################################################
// CONTROLLERS
//#########################################################
{$ifdef GLPT_GAMEPAD}
// https://stackoverflow.com/questions/2234364/how-to-detect-a-gamepad-button-press-on-osx-10-5-and-higher
var
HIDElementDeviceID: integer = 0;
type
HIDElementType = (hid_element_hat, hid_element_axis, hid_element_button);
HIDElementInfo = class
typ: HIDElementType;
ref: IOHIDElementRef;
cookie: IOHIDElementCookie;
usagePage: UInt32;
usage: UInt32;
min: SInt32;
max: SInt32;
mid: SInt32;
index: UInt16;
minReport: cint32;
maxReport: cint32;
deviceID: integer;
constructor Create(_type: HIDElementType);
end;
HIDElementHat = class (HIDElementInfo)
value: array[0..127] of SInt32;
end;
HIDElementAxis = class (HIDElementInfo)
value: array[0..127] of SInt32;
end;
HIDElementButton = class (HIDElementInfo)
value: array[0..127] of SInt32;
end;
HIDElementInfoList = specialize TFPGObjectList<HIDElementInfo>;
constructor HIDElementInfo.Create(_type: HIDElementType);
begin
typ := _type;
end;
// TODO: this information needs to be in the GLPT_MessageParams I think but not for now
type
HIDDeviceInfo = class
name: string;
guid: array[0..1] of UInt8;
hidDevice: IOHIDDeviceRef;
usagePage: SInt32;
usage: SInt32;
elements: HIDElementInfoList;
elementIndexes: array[HIDElementType] of UInt16;