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
|
/**************************************************************************/
/* godot_content_view.mm */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#include "godot_content_view.h"
#include "display_server_macos.h"
#include "key_mapping_macos.h"
#include "main/main.h"
@implementation GodotContentLayerDelegate
- (id)init {
self = [super init];
window_id = DisplayServer::INVALID_WINDOW_ID;
return self;
}
- (void)setWindowID:(DisplayServerMacOS::WindowID)wid {
window_id = wid;
}
- (void)displayLayer:(CALayer *)layer {
DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
if (OS::get_singleton()->get_main_loop() && ds->get_is_resizing()) {
Main::force_redraw();
if (!Main::is_iterating()) { // Avoid cyclic loop.
Main::iteration();
}
}
}
@end
@implementation GodotContentView
- (void)setFrameSize:(NSSize)newSize {
DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
if (ds && ds->has_window(window_id)) {
DisplayServerMacOS::WindowData &wd = ds->get_window(window_id);
NSRect frameRect = [wd.window_object frame];
if (wd.fs_transition || wd.initial_size) {
self.layerContentsPlacement = NSViewLayerContentsPlacementScaleAxesIndependently;
wd.initial_size = false;
} else {
bool left = (wd.last_frame_rect.origin.x != frameRect.origin.x);
bool bottom = (wd.last_frame_rect.origin.y != frameRect.origin.y);
bool right = (wd.last_frame_rect.origin.x + wd.last_frame_rect.size.width != frameRect.origin.x + frameRect.size.width);
bool top = (wd.last_frame_rect.origin.y + wd.last_frame_rect.size.height != frameRect.origin.y + frameRect.size.height);
if (left && top) {
self.layerContentsPlacement = NSViewLayerContentsPlacementBottomRight;
} else if (left && bottom) {
self.layerContentsPlacement = NSViewLayerContentsPlacementTopRight;
} else if (left) {
self.layerContentsPlacement = NSViewLayerContentsPlacementRight;
} else if (right && top) {
self.layerContentsPlacement = NSViewLayerContentsPlacementBottomLeft;
} else if (right && bottom) {
self.layerContentsPlacement = NSViewLayerContentsPlacementTopLeft;
} else if (right) {
self.layerContentsPlacement = NSViewLayerContentsPlacementLeft;
}
}
wd.last_frame_rect = frameRect;
}
[super setFrameSize:newSize];
[self.layer setNeedsDisplay]; // Force "drawRect" call.
}
- (void)updateLayerDelegate {
self.layer.delegate = layer_delegate;
self.layer.autoresizingMask = kCALayerHeightSizable | kCALayerWidthSizable;
self.layer.needsDisplayOnBoundsChange = YES;
}
- (id)init {
self = [super init];
layer_delegate = [[GodotContentLayerDelegate alloc] init];
window_id = DisplayServer::INVALID_WINDOW_ID;
tracking_area = nil;
ime_input_event_in_progress = false;
mouse_down_control = false;
ignore_momentum_scroll = false;
last_pen_inverted = false;
[self updateTrackingAreas];
self.layerContentsRedrawPolicy = NSViewLayerContentsRedrawDuringViewResize;
self.layerContentsPlacement = NSViewLayerContentsPlacementTopLeft;
if (@available(macOS 10.13, *)) {
[self registerForDraggedTypes:[NSArray arrayWithObject:NSPasteboardTypeFileURL]];
#if !defined(__aarch64__) // Do not build deprectead 10.13 code on ARM.
} else {
[self registerForDraggedTypes:[NSArray arrayWithObject:NSFilenamesPboardType]];
#endif
}
marked_text = [[NSMutableAttributedString alloc] init];
return self;
}
- (void)setWindowID:(DisplayServerMacOS::WindowID)wid {
window_id = wid;
[layer_delegate setWindowID:window_id];
}
// MARK: Backing Layer
- (CALayer *)makeBackingLayer {
return [[CAMetalLayer class] layer];
}
- (void)updateLayer {
DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
ds->window_update(window_id);
[super updateLayer];
}
- (BOOL)wantsUpdateLayer {
return YES;
}
- (BOOL)isOpaque {
return YES;
}
// MARK: IME
- (BOOL)hasMarkedText {
return (marked_text.length > 0);
}
- (NSRange)markedRange {
return NSMakeRange(0, marked_text.length);
}
- (NSRange)selectedRange {
static const NSRange kEmptyRange = { NSNotFound, 0 };
return kEmptyRange;
}
- (void)setMarkedText:(id)aString selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange {
if ([aString isKindOfClass:[NSAttributedString class]]) {
marked_text = [[NSMutableAttributedString alloc] initWithAttributedString:aString];
} else {
marked_text = [[NSMutableAttributedString alloc] initWithString:aString];
}
if (marked_text.length == 0) {
[self unmarkText];
return;
}
DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
if (!ds || !ds->has_window(window_id)) {
return;
}
DisplayServerMacOS::WindowData &wd = ds->get_window(window_id);
if (wd.im_active) {
ime_input_event_in_progress = true;
ds->update_im_text(Point2i(selectedRange.location, selectedRange.length), String::utf8([[marked_text mutableString] UTF8String]));
}
}
- (void)doCommandBySelector:(SEL)aSelector {
[self tryToPerform:aSelector with:self];
}
- (void)unmarkText {
ime_input_event_in_progress = false;
[[marked_text mutableString] setString:@""];
DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
if (!ds || !ds->has_window(window_id)) {
return;
}
DisplayServerMacOS::WindowData &wd = ds->get_window(window_id);
if (wd.im_active) {
ds->update_im_text(Point2i(), String());
}
}
- (NSArray *)validAttributesForMarkedText {
return [NSArray array];
}
- (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange {
return nil;
}
- (NSUInteger)characterIndexForPoint:(NSPoint)aPoint {
return 0;
}
- (NSRect)firstRectForCharacterRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange {
DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
if (!ds || !ds->has_window(window_id)) {
return NSMakeRect(0, 0, 0, 0);
}
DisplayServerMacOS::WindowData &wd = ds->get_window(window_id);
const NSRect content_rect = [wd.window_view frame];
const float scale = ds->screen_get_max_scale();
NSRect point_in_window_rect = NSMakeRect(wd.im_position.x / scale, content_rect.size.height - (wd.im_position.y / scale) - 1, 0, 0);
NSPoint point_on_screen = [wd.window_object convertRectToScreen:point_in_window_rect].origin;
return NSMakeRect(point_on_screen.x, point_on_screen.y, 0, 0);
}
- (void)cancelComposition {
[self unmarkText];
[[NSTextInputContext currentInputContext] discardMarkedText];
}
- (void)insertText:(id)aString {
[self insertText:aString replacementRange:NSMakeRange(0, 0)];
}
- (void)insertText:(id)aString replacementRange:(NSRange)replacementRange {
NSEvent *event = [NSApp currentEvent];
NSString *characters;
if ([aString isKindOfClass:[NSAttributedString class]]) {
characters = [aString string];
} else {
characters = (NSString *)aString;
}
NSCharacterSet *ctrl_chars = [NSCharacterSet controlCharacterSet];
NSCharacterSet *wsnl_chars = [NSCharacterSet whitespaceAndNewlineCharacterSet];
if ([characters rangeOfCharacterFromSet:ctrl_chars].length && [characters rangeOfCharacterFromSet:wsnl_chars].length == 0) {
[[NSTextInputContext currentInputContext] discardMarkedText];
[self cancelComposition];
return;
}
DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
if (!ds || !ds->has_window(window_id)) {
[self cancelComposition];
return;
}
Char16String text;
text.resize([characters length] + 1);
[characters getCharacters:(unichar *)text.ptrw() range:NSMakeRange(0, [characters length])];
String u32text;
u32text.parse_utf16(text.ptr(), text.length());
for (int i = 0; i < u32text.length(); i++) {
const char32_t codepoint = u32text[i];
if ((codepoint & 0xFF00) == 0xF700) {
continue;
}
DisplayServerMacOS::KeyEvent ke;
ke.window_id = window_id;
ke.macos_state = [event modifierFlags];
ke.pressed = true;
ke.echo = false;
ke.raw = false; // IME input event.
ke.keycode = Key::NONE;
ke.physical_keycode = Key::NONE;
ke.unicode = codepoint;
ds->push_to_key_event_buffer(ke);
}
[self cancelComposition];
}
// MARK: Drag and drop
- (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender {
return NSDragOperationCopy;
}
- (NSDragOperation)draggingUpdated:(id<NSDraggingInfo>)sender {
return NSDragOperationCopy;
}
- (BOOL)performDragOperation:(id<NSDraggingInfo>)sender {
DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
if (!ds || !ds->has_window(window_id)) {
return NO;
}
DisplayServerMacOS::WindowData &wd = ds->get_window(window_id);
if (!wd.drop_files_callback.is_null()) {
Vector<String> files;
NSPasteboard *pboard = [sender draggingPasteboard];
if (@available(macOS 10.13, *)) {
NSArray *items = pboard.pasteboardItems;
for (NSPasteboardItem *item in items) {
NSString *url = [item stringForType:NSPasteboardTypeFileURL];
NSString *file = [NSURL URLWithString:url].path;
files.push_back(String::utf8([file UTF8String]));
}
#if !defined(__aarch64__) // Do not build deprectead 10.13 code on ARM.
} else {
NSArray *filenames = [pboard propertyListForType:NSFilenamesPboardType];
for (NSString *file in filenames) {
files.push_back(String::utf8([file UTF8String]));
}
#endif
}
Variant v = files;
Variant *vp = &v;
Variant ret;
Callable::CallError ce;
wd.drop_files_callback.callp((const Variant **)&vp, 1, ret, ce);
}
return NO;
}
// MARK: Focus
- (BOOL)canBecomeKeyView {
DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
if (!ds || !ds->has_window(window_id)) {
return YES;
}
DisplayServerMacOS::WindowData &wd = ds->get_window(window_id);
return !wd.no_focus && !wd.is_popup;
}
- (BOOL)acceptsFirstResponder {
return YES;
}
// MARK: Mouse
- (void)cursorUpdate:(NSEvent *)event {
DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
if (!ds) {
return;
}
ds->cursor_update_shape();
}
- (void)processMouseEvent:(NSEvent *)event index:(MouseButton)index pressed:(bool)pressed {
DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
if (!ds || !ds->has_window(window_id)) {
return;
}
DisplayServerMacOS::WindowData &wd = ds->get_window(window_id);
BitField<MouseButtonMask> last_button_state = ds->mouse_get_button_state();
MouseButtonMask mask = mouse_button_to_mask(index);
if (pressed) {
last_button_state.set_flag(mask);
} else {
last_button_state.clear_flag(mask);
}
ds->mouse_set_button_state(last_button_state);
Ref<InputEventMouseButton> mb;
mb.instantiate();
mb->set_window_id(window_id);
ds->update_mouse_pos(wd, [event locationInWindow]);
ds->get_key_modifier_state([event modifierFlags], mb);
mb->set_button_index(index);
mb->set_pressed(pressed);
mb->set_position(wd.mouse_pos);
mb->set_global_position(wd.mouse_pos);
mb->set_button_mask(last_button_state);
if (index == MouseButton::LEFT && pressed) {
mb->set_double_click([event clickCount] == 2);
}
Input::get_singleton()->parse_input_event(mb);
}
- (void)mouseDown:(NSEvent *)event {
if (([event modifierFlags] & NSEventModifierFlagControl)) {
mouse_down_control = true;
[self processMouseEvent:event index:MouseButton::RIGHT pressed:true];
} else {
mouse_down_control = false;
[self processMouseEvent:event index:MouseButton::LEFT pressed:true];
}
}
- (void)mouseDragged:(NSEvent *)event {
[self mouseMoved:event];
}
- (void)mouseUp:(NSEvent *)event {
if (mouse_down_control) {
[self processMouseEvent:event index:MouseButton::RIGHT pressed:false];
} else {
[self processMouseEvent:event index:MouseButton::LEFT pressed:false];
}
}
- (void)mouseMoved:(NSEvent *)event {
DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
if (!ds || !ds->has_window(window_id)) {
return;
}
DisplayServerMacOS::WindowData &wd = ds->get_window(window_id);
NSPoint delta = NSMakePoint([event deltaX], [event deltaY]);
NSPoint mpos = [event locationInWindow];
if (ds->update_mouse_wrap(wd, delta, mpos, [event timestamp])) {
return;
}
Ref<InputEventMouseMotion> mm;
mm.instantiate();
mm->set_window_id(window_id);
mm->set_button_mask(ds->mouse_get_button_state());
ds->update_mouse_pos(wd, mpos);
mm->set_position(wd.mouse_pos);
mm->set_pressure([event pressure]);
NSEventSubtype subtype = [event subtype];
if (subtype == NSEventSubtypeTabletPoint) {
const NSPoint p = [event tilt];
mm->set_tilt(Vector2(p.x, -p.y));
mm->set_pen_inverted(last_pen_inverted);
} else if (subtype == NSEventSubtypeTabletProximity) {
// Check if using the eraser end of pen only on proximity event.
last_pen_inverted = [event pointingDeviceType] == NSPointingDeviceTypeEraser;
mm->set_pen_inverted(last_pen_inverted);
}
mm->set_global_position(wd.mouse_pos);
mm->set_velocity(Input::get_singleton()->get_last_mouse_velocity());
const Vector2i relativeMotion = Vector2i(delta.x, delta.y) * ds->screen_get_max_scale();
mm->set_relative(relativeMotion);
ds->get_key_modifier_state([event modifierFlags], mm);
Input::get_singleton()->parse_input_event(mm);
}
- (void)rightMouseDown:(NSEvent *)event {
[self processMouseEvent:event index:MouseButton::RIGHT pressed:true];
}
- (void)rightMouseDragged:(NSEvent *)event {
[self mouseMoved:event];
}
- (void)rightMouseUp:(NSEvent *)event {
[self processMouseEvent:event index:MouseButton::RIGHT pressed:false];
}
- (void)otherMouseDown:(NSEvent *)event {
if ((int)[event buttonNumber] == 2) {
[self processMouseEvent:event index:MouseButton::MIDDLE pressed:true];
} else if ((int)[event buttonNumber] == 3) {
[self processMouseEvent:event index:MouseButton::MB_XBUTTON1 pressed:true];
} else if ((int)[event buttonNumber] == 4) {
[self processMouseEvent:event index:MouseButton::MB_XBUTTON2 pressed:true];
} else {
return;
}
}
- (void)otherMouseDragged:(NSEvent *)event {
[self mouseMoved:event];
}
- (void)otherMouseUp:(NSEvent *)event {
if ((int)[event buttonNumber] == 2) {
[self processMouseEvent:event index:MouseButton::MIDDLE pressed:false];
} else if ((int)[event buttonNumber] == 3) {
[self processMouseEvent:event index:MouseButton::MB_XBUTTON1 pressed:false];
} else if ((int)[event buttonNumber] == 4) {
[self processMouseEvent:event index:MouseButton::MB_XBUTTON2 pressed:false];
} else {
return;
}
}
- (void)mouseExited:(NSEvent *)event {
DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
if (!ds || !ds->has_window(window_id)) {
return;
}
DisplayServerMacOS::WindowData &wd = ds->get_window(window_id);
if (ds->mouse_get_mode() != DisplayServer::MOUSE_MODE_CAPTURED) {
ds->send_window_event(wd, DisplayServerMacOS::WINDOW_EVENT_MOUSE_EXIT);
}
}
- (void)mouseEntered:(NSEvent *)event {
DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
if (!ds || !ds->has_window(window_id)) {
return;
}
DisplayServerMacOS::WindowData &wd = ds->get_window(window_id);
if (ds->mouse_get_mode() != DisplayServer::MOUSE_MODE_CAPTURED) {
ds->send_window_event(wd, DisplayServerMacOS::WINDOW_EVENT_MOUSE_ENTER);
}
ds->cursor_update_shape();
}
- (void)magnifyWithEvent:(NSEvent *)event {
DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
if (!ds || !ds->has_window(window_id)) {
return;
}
DisplayServerMacOS::WindowData &wd = ds->get_window(window_id);
Ref<InputEventMagnifyGesture> ev;
ev.instantiate();
ev->set_window_id(window_id);
ds->get_key_modifier_state([event modifierFlags], ev);
ds->update_mouse_pos(wd, [event locationInWindow]);
ev->set_position(wd.mouse_pos);
ev->set_factor([event magnification] + 1.0);
Input::get_singleton()->parse_input_event(ev);
}
- (void)updateTrackingAreas {
if (tracking_area != nil) {
[self removeTrackingArea:tracking_area];
}
NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited | NSTrackingActiveInKeyWindow | NSTrackingCursorUpdate | NSTrackingInVisibleRect;
tracking_area = [[NSTrackingArea alloc] initWithRect:[self bounds] options:options owner:self userInfo:nil];
[self addTrackingArea:tracking_area];
[super updateTrackingAreas];
}
// MARK: Keyboard
- (void)keyDown:(NSEvent *)event {
DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
if (!ds || !ds->has_window(window_id)) {
return;
}
DisplayServerMacOS::WindowData &wd = ds->get_window(window_id);
ignore_momentum_scroll = true;
// Ignore all input if IME input is in progress.
if (!ime_input_event_in_progress) {
NSString *characters = [event characters];
NSUInteger length = [characters length];
if (!wd.im_active && length > 0 && keycode_has_unicode(KeyMappingMacOS::remap_key([event keyCode], [event modifierFlags]))) {
// Fallback unicode character handler used if IME is not active.
Char16String text;
text.resize([characters length] + 1);
[characters getCharacters:(unichar *)text.ptrw() range:NSMakeRange(0, [characters length])];
String u32text;
u32text.parse_utf16(text.ptr(), text.length());
for (int i = 0; i < u32text.length(); i++) {
const char32_t codepoint = u32text[i];
DisplayServerMacOS::KeyEvent ke;
ke.window_id = window_id;
ke.macos_state = [event modifierFlags];
ke.pressed = true;
ke.echo = [event isARepeat];
ke.keycode = KeyMappingMacOS::remap_key([event keyCode], [event modifierFlags]);
ke.physical_keycode = KeyMappingMacOS::translate_key([event keyCode]);
ke.raw = true;
ke.unicode = codepoint;
ds->push_to_key_event_buffer(ke);
}
} else {
DisplayServerMacOS::KeyEvent ke;
ke.window_id = window_id;
ke.macos_state = [event modifierFlags];
ke.pressed = true;
ke.echo = [event isARepeat];
ke.keycode = KeyMappingMacOS::remap_key([event keyCode], [event modifierFlags]);
ke.physical_keycode = KeyMappingMacOS::translate_key([event keyCode]);
ke.raw = false;
ke.unicode = 0;
ds->push_to_key_event_buffer(ke);
}
}
// Pass events to IME handler
if (wd.im_active) {
[self interpretKeyEvents:[NSArray arrayWithObject:event]];
}
}
- (void)flagsChanged:(NSEvent *)event {
DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
if (!ds || !ds->has_window(window_id)) {
return;
}
ignore_momentum_scroll = true;
// Ignore all input if IME input is in progress
if (!ime_input_event_in_progress) {
DisplayServerMacOS::KeyEvent ke;
ke.window_id = window_id;
ke.echo = false;
ke.raw = true;
int key = [event keyCode];
int mod = [event modifierFlags];
if (key == 0x36 || key == 0x37) {
if (mod & NSEventModifierFlagCommand) {
mod &= ~NSEventModifierFlagCommand;
ke.pressed = true;
} else {
ke.pressed = false;
}
} else if (key == 0x38 || key == 0x3c) {
if (mod & NSEventModifierFlagShift) {
mod &= ~NSEventModifierFlagShift;
ke.pressed = true;
} else {
ke.pressed = false;
}
} else if (key == 0x3a || key == 0x3d) {
if (mod & NSEventModifierFlagOption) {
mod &= ~NSEventModifierFlagOption;
ke.pressed = true;
} else {
ke.pressed = false;
}
} else if (key == 0x3b || key == 0x3e) {
if (mod & NSEventModifierFlagControl) {
mod &= ~NSEventModifierFlagControl;
ke.pressed = true;
} else {
ke.pressed = false;
}
} else {
return;
}
ke.macos_state = mod;
ke.keycode = KeyMappingMacOS::remap_key(key, mod);
ke.physical_keycode = KeyMappingMacOS::translate_key(key);
ke.unicode = 0;
ds->push_to_key_event_buffer(ke);
}
}
- (void)keyUp:(NSEvent *)event {
DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
if (!ds || !ds->has_window(window_id)) {
return;
}
DisplayServerMacOS::WindowData &wd = ds->get_window(window_id);
// Ignore all input if IME input is in progress.
if (!ime_input_event_in_progress) {
NSString *characters = [event characters];
NSUInteger length = [characters length];
// Fallback unicode character handler used if IME is not active.
if (!wd.im_active && length > 0 && keycode_has_unicode(KeyMappingMacOS::remap_key([event keyCode], [event modifierFlags]))) {
Char16String text;
text.resize([characters length] + 1);
[characters getCharacters:(unichar *)text.ptrw() range:NSMakeRange(0, [characters length])];
String u32text;
u32text.parse_utf16(text.ptr(), text.length());
for (int i = 0; i < u32text.length(); i++) {
const char32_t codepoint = u32text[i];
DisplayServerMacOS::KeyEvent ke;
ke.window_id = window_id;
ke.macos_state = [event modifierFlags];
ke.pressed = false;
ke.echo = [event isARepeat];
ke.keycode = KeyMappingMacOS::remap_key([event keyCode], [event modifierFlags]);
ke.physical_keycode = KeyMappingMacOS::translate_key([event keyCode]);
ke.raw = true;
ke.unicode = codepoint;
ds->push_to_key_event_buffer(ke);
}
} else {
DisplayServerMacOS::KeyEvent ke;
ke.window_id = window_id;
ke.macos_state = [event modifierFlags];
ke.pressed = false;
ke.echo = [event isARepeat];
ke.keycode = KeyMappingMacOS::remap_key([event keyCode], [event modifierFlags]);
ke.physical_keycode = KeyMappingMacOS::translate_key([event keyCode]);
ke.raw = true;
ke.unicode = 0;
ds->push_to_key_event_buffer(ke);
}
}
}
// MARK: Scroll and pan
- (void)processScrollEvent:(NSEvent *)event button:(MouseButton)button factor:(double)factor {
DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
if (!ds || !ds->has_window(window_id)) {
return;
}
DisplayServerMacOS::WindowData &wd = ds->get_window(window_id);
MouseButtonMask mask = mouse_button_to_mask(button);
BitField<MouseButtonMask> last_button_state = ds->mouse_get_button_state();
Ref<InputEventMouseButton> sc;
sc.instantiate();
sc->set_window_id(window_id);
ds->get_key_modifier_state([event modifierFlags], sc);
sc->set_button_index(button);
sc->set_factor(factor);
sc->set_pressed(true);
sc->set_position(wd.mouse_pos);
sc->set_global_position(wd.mouse_pos);
last_button_state.set_flag(mask);
sc->set_button_mask(last_button_state);
ds->mouse_set_button_state(last_button_state);
Input::get_singleton()->parse_input_event(sc);
sc.instantiate();
sc->set_window_id(window_id);
sc->set_button_index(button);
sc->set_factor(factor);
sc->set_pressed(false);
sc->set_position(wd.mouse_pos);
sc->set_global_position(wd.mouse_pos);
last_button_state.clear_flag(mask);
sc->set_button_mask(last_button_state);
ds->mouse_set_button_state(last_button_state);
Input::get_singleton()->parse_input_event(sc);
}
- (void)processPanEvent:(NSEvent *)event dx:(double)dx dy:(double)dy {
DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
if (!ds || !ds->has_window(window_id)) {
return;
}
DisplayServerMacOS::WindowData &wd = ds->get_window(window_id);
Ref<InputEventPanGesture> pg;
pg.instantiate();
pg->set_window_id(window_id);
ds->get_key_modifier_state([event modifierFlags], pg);
pg->set_position(wd.mouse_pos);
pg->set_delta(Vector2(-dx, -dy));
Input::get_singleton()->parse_input_event(pg);
}
- (void)scrollWheel:(NSEvent *)event {
DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
if (!ds || !ds->has_window(window_id)) {
return;
}
DisplayServerMacOS::WindowData &wd = ds->get_window(window_id);
ds->update_mouse_pos(wd, [event locationInWindow]);
double delta_x = [event scrollingDeltaX];
double delta_y = [event scrollingDeltaY];
if ([event hasPreciseScrollingDeltas]) {
delta_x *= 0.03;
delta_y *= 0.03;
}
if ([event momentumPhase] != NSEventPhaseNone) {
if (ignore_momentum_scroll) {
return;
}
} else {
ignore_momentum_scroll = false;
}
if ([event phase] != NSEventPhaseNone || [event momentumPhase] != NSEventPhaseNone) {
[self processPanEvent:event dx:delta_x dy:delta_y];
} else {
if (fabs(delta_x)) {
[self processScrollEvent:event button:(0 > delta_x ? MouseButton::WHEEL_RIGHT : MouseButton::WHEEL_LEFT) factor:fabs(delta_x * 0.3)];
}
if (fabs(delta_y)) {
[self processScrollEvent:event button:(0 < delta_y ? MouseButton::WHEEL_UP : MouseButton::WHEEL_DOWN) factor:fabs(delta_y * 0.3)];
}
}
}
@end
|