ferroui-native 0.2.0

The macOS platform of FerroUI: windows, input, clipboard, drag and drop, menus and Metal and OpenGL graphics over a native library
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
//
// Created by Dan Walmsley on 05/05/2022.
//

#import <AppKit/AppKit.h>
#import <Carbon/Carbon.h> /* For the TIS functions used to classify the keyboard input source. */
#include "FrnView.h"
#include "automation.h"
#import "WindowInterfaces.h"
#import "WindowImpl.h"

@implementation FrnView
{
    ComObjectWeakPtr<TopLevelImpl> _parent;
    NSTrackingArea* _area;
    FrnInputModifiers _modifierState;
    NSEvent* _lastMouseDownEvent;
    FrnPixelSize _lastPixelSize;
    NSObject<IRenderTarget>* _currentRenderTarget;
    FrnPlatformResizeReason _resizeReason;
    NSRect _cursorRect;
    NSMutableAttributedString* _text;
    NSRange _selectedRange;
    NSRange _markedRange;
    NSMutableArray* _accessibilityChildren;
    NSString* _keyboardInputSourceId;
    bool _keyboardInputSourceComposes;
}

- (void)onClosed
{
    @synchronized (self)
    {
        _parent = nullptr;
    }
}

- (NSEvent*) lastMouseDownEvent
{
    return _lastMouseDownEvent;
}

- (void) updateRenderTarget
{
    if(_currentRenderTarget) {
        FrnPixelSize size { MAX(_lastPixelSize.Width, 1), MAX(_lastPixelSize.Height, 1) };
        [_currentRenderTarget resize:size withScale:static_cast<float>([[self window] backingScaleFactor])];
        [self setNeedsDisplayInRect:[self frame]];
    }
}


-(void) setRenderTarget:(NSObject<IRenderTarget>*)target
{
    if([self layer])
    {
        [self layer].delegate = nil;
    }
    _currentRenderTarget = target;
    auto layer = [target layer];
    [self setLayer: layer];
    [layer setDelegate: self];
    layer.needsDisplayOnBoundsChange = YES;
    [self updateRenderTarget];
}

-(void)displayLayer: (CALayer*)layer
{
    [self updateLayer];
}

-(FrnView*)  initWithParent: (TopLevelImpl*) parent
{
    self = [super init];
    [self setWantsLayer:YES];
    [self setLayerContentsPlacement: NSViewLayerContentsPlacementTopLeft];

    [self setCanDrawSubviewsIntoLayer: NO];
    [self setLayerContentsRedrawPolicy: NSViewLayerContentsRedrawDuringViewResize];

    _parent = parent;

    // NSTrackingInVisibleRect makes AppKit follow the visible bounds of the view.
    // Because of this, the tracking area does not need to change on resize.
    // Do not remove and add the area again on each live-resize tick.
    // If you do, AppKit queues synthetic enter and exit events with stale locations.
    // These events corrupt the pointer position after a resize and force it to the top left.
    NSTrackingAreaOptions options = NSTrackingActiveAlways | NSTrackingMouseMoved |
        NSTrackingMouseEnteredAndExited | NSTrackingEnabledDuringMouseDrag | NSTrackingInVisibleRect;
    _area = [[NSTrackingArea alloc] initWithRect:NSZeroRect options:options owner:self userInfo:nullptr];
    [self addTrackingArea:_area];

    _lastPixelSize.Height = 100;
    _lastPixelSize.Width = 100;
    [self registerForDraggedTypes: @[@"public.data", GetFrnCustomDataType()]];

    _modifierState = FrnInputModifiersNone;
    
    _text = [[NSMutableAttributedString alloc] initWithString:@""];
    _markedRange = NSMakeRange(0, 0);
    _selectedRange = NSMakeRange(0, 0);
    
    return self;
}

- (BOOL)isFlipped
{
    return YES;
}

- (BOOL)wantsUpdateLayer
{
    return YES;
}

- (BOOL)isOpaque
{
    return YES;
}

- (BOOL)acceptsFirstResponder
{
    return true;
}

- (BOOL)acceptsFirstMouse:(NSEvent *)event
{
    return true;
}

- (BOOL)canBecomeKeyView
{
    return true;
}

-(void)setFrameSize:(NSSize)newSize
{
    [super setFrameSize:newSize];

    auto parent = _parent.tryGet();
    if (parent == nullptr)
    {
        return;
    }

    parent->UpdateCursor();

    auto fsize = [self convertSizeToBacking: [self frame].size];

    if(_lastPixelSize.Width != (int)fsize.width || _lastPixelSize.Height != (int)fsize.height)
    {
        _lastPixelSize.Width = (int)fsize.width;
        _lastPixelSize.Height = (int)fsize.height;
        [self updateRenderTarget];

        auto reason = [self inLiveResize] ? ResizeUser : _resizeReason;

        parent->TopLevelEvents->Resized(FromNSSize(newSize), reason);
    }
}

- (void)updateLayer
{
    FrnInsidePotentialDeadlock deadlock;
    auto parent = _parent.tryGet();
    if (parent == nullptr)
    {
        return;
    }

    parent->TopLevelEvents->RunRenderPriorityJobs();

    parent = _parent.tryGet();
    if (parent == nullptr)
    {
        return;
    }

    parent->TopLevelEvents->Paint();
}

- (void)drawRect:(NSRect)dirtyRect
{
    return;
}

- (FrnPoint) translateLocalPoint:(FrnPoint)pt
{
    pt.Y = [self bounds].size.height - pt.Y;
    return pt;
}

- (void) viewDidChangeBackingProperties
{
    auto fsize = [self convertSizeToBacking: [self frame].size];
    _lastPixelSize.Width = (int)fsize.width;
    _lastPixelSize.Height = (int)fsize.height;
    [self updateRenderTarget];

    auto parent = _parent.tryGet();
    if(parent != nullptr)
    {
        parent->TopLevelEvents->ScalingChanged([[self window] backingScaleFactor]);
    }

    [super viewDidChangeBackingProperties];
}

- (bool) ignoreUserInput:(bool)trigerInputWhenDisabled
{
    auto parent = _parent.tryGet();
    if(parent == nullptr)
    {
        return TRUE;
    }
    
    id<FrnWindowProtocol> parentWindow = nullptr;

    if([[self window] conformsToProtocol:@protocol(FrnWindowProtocol)]){
        parentWindow = (id<FrnWindowProtocol>)[self window];
    }

    if(parentWindow != nullptr && ![parentWindow shouldTryToHandleEvents])
    {
        if(trigerInputWhenDisabled)
        {
            auto windowImpl = _parent.tryGetWithCast<WindowImpl>();
            
            if(windowImpl == nullptr){
                return FALSE;
            }
            
            windowImpl->WindowEvents->GotInputWhenDisabled();
        }

        return TRUE;
    }

    return FALSE;
}

static void ConvertTilt(NSPoint tilt, float* xTilt, float* yTilt)
{
    *xTilt =  tilt.x * 90;
    *yTilt = -tilt.y * 90;
}

- (void)mouseEvent:(NSEvent *)event withType:(FrnRawMouseEventType) type
{
    bool triggerInputWhenDisabled = type != Move && type != LeaveWindow;

    if([self ignoreUserInput: triggerInputWhenDisabled])
    {
        return;
    }

    // AppKit synthesizes enter and exit events for the tracked geometry.
    // They can have stale locations. Use the current pointer location instead.
    NSPoint eventLocation = event.type == NSEventTypeMouseEntered || event.type == NSEventTypeMouseExited
        ? [[self window] mouseLocationOutsideOfEventStream]
        : [event locationInWindow];

    auto viewLocation = [self convertPoint:NSMakePoint(0, 0) toView:nil];
    
    auto localPoint = NSMakePoint(eventLocation.x - viewLocation.x, viewLocation.y - eventLocation.y);
    
    auto point = ToFrnPoint(localPoint);
    FrnVector delta = { 0, 0};

    if(type == Wheel)
    {
        auto speed = 5;

        if([event hasPreciseScrollingDeltas])
        {
            speed = 50;
        }

        delta.X = [event scrollingDeltaX] / speed;
        delta.Y = [event scrollingDeltaY] / speed;

        if(delta.X == 0 && delta.Y == 0)
        {
            return;
        }
    }
    else if (type == Magnify)
    {
        delta.X = delta.Y = [event magnification];
    }
    else if (type == Rotate)
    {
        delta.X = delta.Y = [event rotation];
    }
    else if (type == Swipe)
    {
        delta.X = [event deltaX];
        delta.Y = [event deltaY];
    }

    float pressure = 0.5f;
    float xTilt = 0.0f;
    float yTilt = 0.0f;
    FrnPointerDeviceType pointerType = FrnPointerDeviceType::Mouse;

    switch (event.type)
    {
        case NSEventTypeLeftMouseDown:
        case NSEventTypeLeftMouseDragged:
        case NSEventTypeRightMouseDown:
        case NSEventTypeRightMouseDragged:
        case NSEventTypeOtherMouseDown:
        case NSEventTypeOtherMouseDragged:
            switch (event.subtype)
            {
                case NSEventSubtypeTabletPoint:
                    pointerType = FrnPointerDeviceType::Pen;
                    pressure = event.pressure;
                    ConvertTilt(event.tilt, &xTilt, &yTilt);
                    break;
                case NSEventSubtypeTabletProximity:
                    pointerType = FrnPointerDeviceType::Pen;
                    pressure = 0.0f;
                    break;
                default:
                    break;
            }
            break;
        case NSEventTypeLeftMouseUp:
        case NSEventTypeRightMouseUp:
        case NSEventTypeOtherMouseUp:
        case NSEventTypeMouseMoved:
            switch (event.subtype)
            {
                case NSEventSubtypeTabletPoint:
                    pointerType = FrnPointerDeviceType::Pen;
                    pressure = 0.0f;
                    ConvertTilt(event.tilt, &xTilt, &yTilt);
                    break;
                case NSEventSubtypeTabletProximity:
                    pointerType = FrnPointerDeviceType::Pen;
                    pressure = 0.0f;
                    break;
                default:
                    break;
            }
            break;
        default:
            break;
    }

    uint64_t timestamp = static_cast<uint64_t>([event timestamp] * 1000);
    auto modifiers = [self getModifiers:[event modifierFlags]];

    if(type != Move ||
            (
                    [self window] != nil &&
                            (
                                    [[self window] firstResponder] == nil
                                            || ![[[self window] firstResponder] isKindOfClass: [NSView class]]
                            )
            )
            )
    {
        auto windowBase = _parent.tryGetWithCast<WindowBaseImpl>();
        
        if(windowBase != nullptr){
            auto parent = windowBase->Parent.tryGet();
            
            if(parent != nullptr){
                auto parentWindow = parent->Window;
                
                if(parentWindow != nullptr)
                    [parentWindow makeFirstResponder:parent->View];
            }
        } else{
            [self becomeFirstResponder];
        }
    }

    if([self hasMarkedText] &&
       (type == LeftButtonDown || type == RightButtonDown || type == MiddleButtonDown ||
        type == XButton1Down || type == XButton2Down) &&
       [self inputContext] != nil)
    {
        [[self inputContext] handleEvent:event];
    }

    auto parent = _parent.tryGet();
    if(parent != nullptr)
    {
        parent->TopLevelEvents->RawMouseEvent(type, pointerType, timestamp, modifiers, point, delta, pressure, xTilt, yTilt);
    }

    // This handler is shared by all mouse event types. Only real mouse-moved
    // events must continue up the responder chain as mouseMoved:
    if (event.type == NSEventTypeMouseMoved)
        [super mouseMoved:event];
}

- (BOOL) resignFirstResponder
{
    auto window = [self window];
    if (window != nullptr && window.keyWindow)
    {
        [self onLostFocus];
    }
    
    return YES;
}

- (void)viewWillMoveToWindow:(NSWindow *)newWindow
{
    auto oldWindow = [self window];
    if (oldWindow == newWindow)
    {
        // viewWillMoveToWindow can be called with the same window when the view hierarchy changes
        return;
    }

    if (oldWindow != nullptr)
    {
        [[NSNotificationCenter defaultCenter]
            removeObserver:self
            name:@"NSWindowDidResignKeyNotification"
            object: oldWindow];
    }

    if (newWindow != nullptr)
    {
        [[NSNotificationCenter defaultCenter]
            addObserver:self
            selector:@selector(windowDidResignKey:)
            name:@"NSWindowDidResignKeyNotification"
            object: newWindow];
    }
}

- (void)windowDidResignKey:(NSNotification*)notification
{
    auto window = [self window];
    if (window != nullptr && notification.object == window && [window firstResponder] == self)
    {
        [self onLostFocus];
    }
}

- (void)onLostFocus
{
    auto parent = _parent.tryGet();
    if (parent)
        parent->TopLevelEvents->LostFocus();
}

- (void)mouseMoved:(NSEvent *)event
{
    [self mouseEvent:event withType:Move];
}

- (void)mouseDown:(NSEvent *)event
{
    _lastMouseDownEvent = event;
    [self mouseEvent:event withType:LeftButtonDown];
}

- (void)otherMouseDown:(NSEvent *)event
{
    _lastMouseDownEvent = event;

    switch(event.buttonNumber)
    {
        case 2:
            [self mouseEvent:event withType:MiddleButtonDown];
            break;
        case 3:
            [self mouseEvent:event withType:XButton1Down];
            break;
        case 4:
            [self mouseEvent:event withType:XButton2Down];
            break;

        default:
            break;
    }
}

- (void)rightMouseDown:(NSEvent *)event
{
    _lastMouseDownEvent = event;
    [self mouseEvent:event withType:RightButtonDown];
}

- (void)mouseUp:(NSEvent *)event
{
    [self mouseEvent:event withType:LeftButtonUp];
}

- (void)otherMouseUp:(NSEvent *)event
{
    switch(event.buttonNumber)
    {
        case 2:
            [self mouseEvent:event withType:MiddleButtonUp];
            break;
        case 3:
            [self mouseEvent:event withType:XButton1Up];
            break;
        case 4:
            [self mouseEvent:event withType:XButton2Up];
            break;

        default:
            break;
    }
}

- (void)rightMouseUp:(NSEvent *)event
{
    [self mouseEvent:event withType:RightButtonUp];
}

- (void)mouseDragged:(NSEvent *)event
{
    [self mouseEvent:event withType:Move];
    [super mouseDragged:event];
}

- (void)otherMouseDragged:(NSEvent *)event
{
    [self mouseEvent:event withType:Move];
    [super otherMouseDragged:event];
}

- (void)rightMouseDragged:(NSEvent *)event
{
    [self mouseEvent:event withType:Move];
    [super rightMouseDragged:event];
}

- (void)scrollWheel:(NSEvent *)event
{
    [self mouseEvent:event withType:Wheel];
    [super scrollWheel:event];
}

- (void)magnifyWithEvent:(NSEvent *)event
{
    [self mouseEvent:event withType:Magnify];
    [super magnifyWithEvent:event];
}

- (void)rotateWithEvent:(NSEvent *)event
{
    [self mouseEvent:event withType:Rotate];
    [super rotateWithEvent:event];
}

- (void)swipeWithEvent:(NSEvent *)event
{
    [self mouseEvent:event withType:Swipe];
    [super swipeWithEvent:event];
}

- (void)mouseEntered:(NSEvent *)event
{
    // If the pointer is not inside the view, the enter event is false. Ignore it.
    NSPoint location = [self convertPoint:[[self window] mouseLocationOutsideOfEventStream] fromView:nil];
    if (NSPointInRect(location, self.bounds))
        [self mouseEvent:event withType:Move];
    [super mouseEntered:event];
}

- (void)mouseExited:(NSEvent *)event
{
    [self mouseEvent:event withType:LeaveWindow];
    [super mouseExited:event];
}

- (void) keyboardEvent: (NSEvent *) event withType: (FrnRawKeyEventType)type
{
    auto parent = _parent.tryGet();
    if([self ignoreUserInput: false] || parent == nullptr)
    {
        return;
    }

    auto scanCode = [event keyCode];
    auto key = VirtualKeyFromScanCode(scanCode, [event modifierFlags]);
    auto physicalKey = PhysicalKeyFromScanCode(scanCode);
    auto keySymbol = KeySymbolFromScanCode(scanCode, [event modifierFlags]);
    auto keySymbolUtf8 = keySymbol == nullptr ? nullptr : [keySymbol UTF8String];
    
    auto timestamp = static_cast<uint64_t>([event timestamp] * 1000);
    auto modifiers = [self getModifiers:[event modifierFlags]];

    parent->TopLevelEvents->RawKeyEvent(type, timestamp, modifiers, key, physicalKey, keySymbolUtf8);
}

- (void)setModifiers:(NSEventModifierFlags)modifierFlags
{
    _modifierState = [self getModifiers:modifierFlags];
}

- (void)flagsChanged:(NSEvent *)event
{
    auto newModifierState = [self getModifiers:[event modifierFlags]];

    bool isAltCurrentlyPressed = (_modifierState & Alt) == Alt;
    bool isControlCurrentlyPressed = (_modifierState & Control) == Control;
    bool isShiftCurrentlyPressed = (_modifierState & Shift) == Shift;
    bool isCommandCurrentlyPressed = (_modifierState & Windows) == Windows;

    bool isAltPressed = (newModifierState & Alt) == Alt;
    bool isControlPressed = (newModifierState & Control) == Control;
    bool isShiftPressed = (newModifierState & Shift) == Shift;
    bool isCommandPressed = (newModifierState & Windows) == Windows;

    if (isAltPressed && !isAltCurrentlyPressed)
    {
        [self keyboardEvent:event withType:KeyDown];
    }
    else if (isAltCurrentlyPressed && !isAltPressed)
    {
        [self keyboardEvent:event withType:KeyUp];
    }

    if (isControlPressed && !isControlCurrentlyPressed)
    {
        [self keyboardEvent:event withType:KeyDown];
    }
    else if (isControlCurrentlyPressed && !isControlPressed)
    {
        [self keyboardEvent:event withType:KeyUp];
    }

    if (isShiftPressed && !isShiftCurrentlyPressed)
    {
        [self keyboardEvent:event withType:KeyDown];
    }
    else if(isShiftCurrentlyPressed && !isShiftPressed)
    {
        [self keyboardEvent:event withType:KeyUp];
    }

    if(isCommandPressed && !isCommandCurrentlyPressed)
    {
        [self keyboardEvent:event withType:KeyDown];
    }
    else if(isCommandCurrentlyPressed && ! isCommandPressed)
    {
        [self keyboardEvent:event withType:KeyUp];
    }

    _modifierState = newModifierState;

    [[self inputContext] handleEvent:event];
    [super flagsChanged:event];
}

// The input mode an input method uses for direct alphanumeric typing. In this mode the input
// method passes keys straight through instead of composing, so keys must not be masked.
static CFStringRef const AlphanumericInputModeId = CFSTR("com.apple.inputmethod.Roman");

static bool InputSourceComposes(TISInputSourceRef source)
{
    // A plain keyboard layout never composes. Dead keys are not driven by the input source, they
    // show up as a composition in progress and are covered by hasMarkedText.
    auto type = static_cast<CFStringRef>(TISGetInputSourceProperty(source, kTISPropertyInputSourceType));

    if(type == nullptr || CFEqual(type, kTISTypeKeyboardLayout))
    {
        return false;
    }

    auto mode = static_cast<CFStringRef>(TISGetInputSourceProperty(source, kTISPropertyInputModeID));

    return mode == nullptr || !CFEqual(mode, AlphanumericInputModeId);
}

// Whether this keystroke could be the one that starts a composition. Only a key that produces a
// printable character can, and masking any of the others would stop controls like TextBox from
// reacting to them at all.
static bool CanStartComposition(NSString* keySymbol, NSEventModifierFlags modifierFlags)
{
    // No symbol at all: the arrows, the function keys, Home, End and friends.
    if(keySymbol == nullptr || [keySymbol length] == 0)
    {
        return false;
    }

    // KeySymbolFromScanCode deliberately reports the control character for Backspace, Enter, Tab
    // and Escape, and Forward Delete reports DEL (0x7F), so a symbol alone does not mean the key
    // produces text. Those keys edit or cancel, they never start a composition.
    auto firstChar = [keySymbol characterAtIndex:0];

    if(firstChar < 0x20 || firstChar == 0x7F)
    {
        return false;
    }

    // Command and Control combinations are shortcuts, which an input method does not consume.
    return (modifierFlags & (NSEventModifierFlagCommand | NSEventModifierFlagControl)) == 0;
}

// Returns true when the input source with the given id is an input method that can start a
// composition, as opposed to a plain keyboard layout or an input method in alphanumeric mode.
static bool KeyboardInputSourceComposes(NSString* sourceId)
{
    NSDictionary* filter = @{ (__bridge NSString*)kTISPropertyInputSourceID: sourceId };

    // Include every installed source, not just the enabled ones: an input method mode can be
    // selected without being listed as enabled, and failing to find it would classify a
    // composing input method as a plain layout.
    auto sources = TISCreateInputSourceList((__bridge CFDictionaryRef)filter, true);

    if(sources == nullptr)
    {
        return false;
    }

    auto composes = CFArrayGetCount(sources) > 0 &&
        InputSourceComposes((TISInputSourceRef)CFArrayGetValueAtIndex(sources, 0));

    CFRelease(sources);

    return composes;
}

// Whether the currently selected keyboard input source is a composing input method. The result
// is cached per input source id, since this is queried for every key down.
- (bool)isComposingInputSourceSelected
{
    auto inputContext = [self inputContext];

    if(inputContext == nullptr)
    {
        return false;
    }

    NSString* sourceId = [inputContext selectedKeyboardInputSource];

    if(sourceId == nullptr)
    {
        return false;
    }

    if(![sourceId isEqualToString:_keyboardInputSourceId])
    {
        _keyboardInputSourceId = sourceId;
        _keyboardInputSourceComposes = KeyboardInputSourceComposes(sourceId);
    }

    return _keyboardInputSourceComposes;
}

- (void)keyDown:(NSEvent *)event
{
    auto parent = _parent.tryGet();
    if([self ignoreUserInput: false] || parent == nullptr)
    {
        return;
    }

    auto timestamp = static_cast<uint64_t>([event timestamp] * 1000);

    auto scanCode = [event keyCode];
    auto physicalKey = PhysicalKeyFromScanCode(scanCode);
    auto keySymbol = KeySymbolFromScanCode(scanCode, [event modifierFlags]);
    auto keySymbolUtf8 = keySymbol == nullptr ? nullptr : [keySymbol UTF8String];

    auto modifiers = [self getModifiers:[event modifierFlags]];

    // The keystroke belongs to the input method when a composition is already in progress, since
    // it then selects a candidate, commits or cancels it. It also belongs to the input method
    // when a character key is typed into a text input client while a composing input method is
    // selected, because that keystroke may be the one that starts the composition and we cannot
    // know that before the input context has seen it.
    //
    // In both cases mask the key the way Win32 reports VK_PROCESSKEY, so that user code still
    // observes a KeyDown but no KeyGesture can match it. The physical key and the key symbol
    // keep their real values, so the underlying key remains recoverable.
    //
    // Both cases require an active client: without one the input context is never consulted, so
    // marked text left over from a composition that lost its client mid-way must not mask keys.
    auto imeProcessed = parent->InputMethod->IsActive() &&
        ([self hasMarkedText] ||
         (CanStartComposition(keySymbol, [event modifierFlags]) &&
          [self isComposingInputSourceSelected]));

    auto key = imeProcessed
        ? FrnKeyImeProcessed
        : VirtualKeyFromScanCode(scanCode, [event modifierFlags]);

    // A KeyDown is always raised before the input context sees the event, otherwise the
    // input context silently consumes printable keys (space, letters, digits) and user code
    // never gets a chance to react to them.
    auto handled = parent->TopLevelEvents->RawKeyEvent(KeyDown, timestamp, modifiers, key, physicalKey, keySymbolUtf8);

    if(handled)
    {
        // User code has handled the event, so no text may be produced from it.
        return;
    }

    if(parent->InputMethod->IsActive())
    {
        // Let the input context produce the text or drive the composition.
        [[self inputContext] handleEvent:event];
    }
    else if(keySymbol != nullptr && key != FrnKeyEnter)
    {
        parent->TopLevelEvents->RawTextInputEvent(timestamp, keySymbolUtf8);
    }
}

- (void)keyUp:(NSEvent *)event
{
    [self keyboardEvent:event withType:KeyUp];
    [super keyUp:event];
}

- (void) doCommandBySelector:(SEL)selector{
    // -keyDown: already raised a KeyDown for this event before handing it to the input
    // context, so nothing is left to do here. The method still has to be implemented:
    // falling back to NSResponder would perform the default action and emit a system beep.
}

- (FrnInputModifiers)getModifiers:(NSEventModifierFlags)mod
{
    unsigned int rv = 0;

    if (mod & NSEventModifierFlagControl)
        rv |= Control;
    if (mod & NSEventModifierFlagShift)
        rv |= Shift;
    if (mod & NSEventModifierFlagOption)
        rv |= Alt;
    if (mod & NSEventModifierFlagCommand)
        rv |= Windows;

    NSUInteger pressedButtons = [NSEvent pressedMouseButtons];
        
    if (pressedButtons & (1 << 0))  // Left mouse button
        rv |= LeftMouseButton;
    if (pressedButtons & (1 << 1))  // Right mouse button
        rv |= RightMouseButton;
    if (pressedButtons & (1 << 2))  // Middle mouse button
        rv |= MiddleMouseButton;
    if (pressedButtons & (1 << 3))  // X1 button
        rv |= XButton1MouseButton;
    if (pressedButtons & (1 << 4))  // X2 button
        rv |= XButton2MouseButton;

    return (FrnInputModifiers)rv;
}

// Clamps a range so that it can never be used to index outside of _text.
// Ranges reaching us from AppKit or from the managed side are not guaranteed to be valid.
- (NSRange)clampRangeToText:(NSRange)range
{
    if (range.location == NSNotFound)
        return NSMakeRange(NSNotFound, 0);

    NSUInteger length = _text.length;

    if (range.location > length)
        return NSMakeRange(length, 0);

    // Avoids the overflow of location + length that a plain bounds check would have.
    return NSMakeRange(range.location, MIN(range.length, length - range.location));
}

- (BOOL)hasMarkedText
{
    return _markedRange.location != NSNotFound && _markedRange.length > 0;
}

- (NSRange)markedRange
{
    // From the docs: returns {NSNotFound, 0} if there is no marked range.
    if (![self hasMarkedText])
        return NSMakeRange(NSNotFound, 0);

    // The preedit isn't necessarily part of the surrounding text we got from the managed side,
    // so only the location is clamped here. An overlong length is handled by
    // attributedSubstringForProposedRange:actualRange:, as the docs require.
    return NSMakeRange(MIN(_markedRange.location, _text.length), _markedRange.length);
}

- (NSRange)selectedRange
{
    return [self clampRangeToText:_selectedRange];
}

- (void)setMarkedText:(id)string selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange
{
    NSString* markedText;

    if([string isKindOfClass:[NSAttributedString class]])
    {
        markedText = [string string];
    }
    else
    {
        markedText = (NSString*) string;
    }

    if (markedText == nil)
    {
        markedText = @"";
    }

    auto parent = _parent.tryGet();

    // Delete any replaced range
    auto finalReplacementRange = [self clampRangeToText:replacementRange];

    if (finalReplacementRange.location != NSNotFound && parent != nullptr && parent->InputMethod->IsActive())
    {
        parent->InputMethod->Client->SelectInSurroundingText((int)finalReplacementRange.location, (int)(finalReplacementRange.location + finalReplacementRange.length));
        uint64_t timestamp = static_cast<uint64_t>([NSDate timeIntervalSinceReferenceDate] * 1000);
        parent->TopLevelEvents->RawKeyEvent(KeyDown, timestamp, FrnInputModifiersNone, FrnKeyBack, FrnPhysicalKeyNone, "\b");
        parent->TopLevelEvents->RawKeyEvent(KeyUp, timestamp, FrnInputModifiersNone, FrnKeyBack, FrnPhysicalKeyNone, "\b");
    }

    auto markedLocation = [self selectedRange].location;

    _markedRange = NSMakeRange(markedLocation == NSNotFound ? 0 : markedLocation, [markedText length]);

    if (parent != nullptr && parent->InputMethod->IsActive())
    {
        const char* utf8MarkedText = [markedText UTF8String];
        parent->InputMethod->Client->SetPreeditText((char*)(utf8MarkedText != nullptr ? utf8MarkedText : ""));
    }
}

- (void)unmarkText
{
    auto parent = _parent.tryGet();
    if(parent != nullptr && parent->InputMethod->IsActive()){
        parent->InputMethod->Client->SetPreeditText(nullptr);
    }

    auto selectionLocation = [self selectedRange].location;

    _markedRange = NSMakeRange(selectionLocation == NSNotFound ? 0 : selectionLocation, 0);

    if([self inputContext]) {
        [[self inputContext] discardMarkedText];
    }
}

- (NSArray<NSString *> *)validAttributesForMarkedText
{
    return [NSArray new];
}

- (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)range actualRange:(NSRangePointer)actualRange
{
    // From the docs: an implementation of this method should be prepared for aRange to be out of bounds.
    // In this case, you should return the intersection of the document's range and aRange.
    // If the location of aRange is completely outside of the document's range, return nil.
    // actualRange is an out parameter: it is uninitialized on entry and must only be written to.
    NSRange docRange = NSMakeRange(0, _text.length);
    NSRange finalRange = NSIntersectionRange(range, docRange);

    if (finalRange.length == 0)
    {
        if (actualRange) {
            *actualRange = NSMakeRange(NSNotFound, 0);
        }

        return nil;
    }

    if (actualRange) {
        *actualRange = finalRange;
    }

    return [_text attributedSubstringFromRange:finalRange];
}

- (void)insertText:(id)string replacementRange:(NSRange)replacementRange
{
    auto parent = _parent.tryGet();
    if(parent == nullptr){
        return;
    }

    NSString* text;

    if([string isKindOfClass:[NSAttributedString class]])
    {
        text = [string string];
    }
    else
    {
        text = (NSString*) string;
    }

    if (text == nil)
    {
        text = @"";
    }

    auto finalReplacementRange = [self clampRangeToText:replacementRange];

    if (finalReplacementRange.location != NSNotFound &&
        ![self hasMarkedText] &&
        parent->InputMethod->IsActive())
    {
        parent->InputMethod->Client->SelectInSurroundingText((int)finalReplacementRange.location, (int)(finalReplacementRange.location + finalReplacementRange.length));
    }

    [self unmarkText];

    uint64_t timestamp = static_cast<uint64_t>([NSDate timeIntervalSinceReferenceDate] * 1000);

    const char* utf8Text = [text UTF8String];

    parent->TopLevelEvents->RawTextInputEvent(timestamp, utf8Text != nullptr ? utf8Text : "");
}

- (NSUInteger)characterIndexForPoint:(NSPoint)point
{
    return NSNotFound;
}

- (NSRect)firstRectForCharacterRange:(NSRange)range actualRange:(NSRangePointer)actualRange
{
    // actualRange is an out parameter: it is uninitialized on entry and must only be written to.
    // We only ever report a single rect, so the requested range is echoed back clamped to the document.
    if (actualRange) {
        *actualRange = [self clampRangeToText:range];
    }

    auto parent = _parent.tryGet();
    if(parent == nullptr || !parent->InputMethod->IsActive()){
        return NSZeroRect;
    }

    return _cursorRect;
}

- (NSDragOperation)triggerFrnDragEvent: (FrnDragEventType) type info: (id <NSDraggingInfo>)info
{
    NSPoint eventLocation = [info draggingLocation];
    auto viewLocation = [self convertPoint:NSMakePoint(0, 0) toView:nil];
    auto localPoint = NSMakePoint(eventLocation.x - viewLocation.x, viewLocation.y - eventLocation.y);
    auto point = ToFrnPoint(localPoint);
    auto modifiers = [self getModifiers:[[NSApp currentEvent] modifierFlags]];
    NSDragOperation nsop = [info draggingSourceOperationMask];

    auto effects = ConvertDragDropEffects(nsop);
    auto parent = _parent.tryGet();
    if (!parent)
      return NSDragOperationNone;
    int reffects = (int)parent->TopLevelEvents
            ->DragEvent(type, point, modifiers, effects,
                    CreateClipboard([info draggingPasteboard]),
                    GetFrnDataObjectHandleFromDraggingInfo(info));

    NSDragOperation ret = static_cast<NSDragOperation>(0);

    // Ensure that the managed part didn't add any new effects
    reffects = (int)effects & reffects;

    // OSX requires exactly one operation
    if((reffects & (int)FrnDragDropEffects::Copy) != 0)
        ret = NSDragOperationCopy;
    else if((reffects & (int)FrnDragDropEffects::Move) != 0)
        ret = NSDragOperationMove;
    else if((reffects & (int)FrnDragDropEffects::Link) != 0)
        ret = NSDragOperationLink;
    if(ret == 0)
        ret = NSDragOperationNone;
    return ret;
}

- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
{
    return [self triggerFrnDragEvent: FrnDragEventType::Enter info:sender];
}

- (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
{
    return [self triggerFrnDragEvent: FrnDragEventType::Over info:sender];
}

- (void)draggingExited:(id <NSDraggingInfo>)sender
{
    [self triggerFrnDragEvent: FrnDragEventType::Leave info:sender];
}

- (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender
{
    return [self triggerFrnDragEvent: FrnDragEventType::Over info:sender] != NSDragOperationNone;
}

- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
{
    return [self triggerFrnDragEvent: FrnDragEventType::Drop info:sender] != NSDragOperationNone;
}

- (void)concludeDragOperation:(nullable id <NSDraggingInfo>)sender
{

}

- (FrnPlatformResizeReason)getResizeReason
{
    return _resizeReason;
}

- (void)setResizeReason:(FrnPlatformResizeReason)reason
{
    _resizeReason = reason;
}

- (NSArray *)accessibilityChildren
{
    if (_accessibilityChildren == nil)
        [self recalculateAccessibiltyChildren];
    return _accessibilityChildren;
}

- (id _Nullable) accessibilityHitTest:(NSPoint)point
{
    if (![[self window] isKindOfClass:[FrnWindow class]])
        return self;

    auto window = (FrnWindow*)[self window];
    auto peer = [window automationPeer];

    if (peer == nullptr || !peer->IsRootProvider())
        return nil;

    auto clientPoint = [window convertPointFromScreen:point];
    auto localPoint = [self translateLocalPoint:ToFrnPoint(clientPoint)];
    auto hit = peer->RootProvider_GetPeerFromPoint(localPoint);
    return [FrnAccessibilityElement acquire:hit];
}

- (void)raiseAccessibilityChildrenChanged
{
    auto changed = _accessibilityChildren ? [NSMutableSet setWithArray:_accessibilityChildren] : [NSMutableSet set];

    [self recalculateAccessibiltyChildren];

    if (_accessibilityChildren)
        [changed addObjectsFromArray:_accessibilityChildren];

    NSAccessibilityPostNotificationWithUserInfo(
        self,
        NSAccessibilityLayoutChangedNotification,
        @{ NSAccessibilityUIElementsKey: [changed allObjects]});
}

- (void)recalculateAccessibiltyChildren
{
    _accessibilityChildren = [[NSMutableArray alloc] init];

    if (![[self window] isKindOfClass:[FrnWindow class]])
    {
        return;
    }

    // The accessibility children of the Window are exposed as children
    // of the FrnView.
    auto window = (FrnWindow*)[self window];
    auto peer = [window automationPeer];
    if (peer == nullptr)
    {
        return;
    }
    auto childPeers = peer->GetChildren();
    auto childCount = childPeers != nullptr ? childPeers->GetCount() : 0;

    if (childCount > 0)
    {
        for (int i = 0; i < childCount; ++i)
        {
            IFrnAutomationPeer* child;

            if (childPeers->Get(i, &child) == S_OK)
            {
                id element = [FrnAccessibilityElement acquire:child];
                [_accessibilityChildren addObject:element];
            }
        }
    }
}

- (void) setText:(NSString *)text{
    [[_text mutableString] setString:text != nil ? text : @""];

    // The document changed, so the stored ranges can now point outside of it.
    _selectedRange = [self clampRangeToText:_selectedRange];

    if (_markedRange.location != NSNotFound)
    {
        _markedRange = NSMakeRange(MIN(_markedRange.location, _text.length), _markedRange.length);
    }
}

- (void) setSelection:(int)start :(int)end{
    if (end < start)
    {
        auto temp = start;
        start = end;
        end = temp;
    }

    auto length = (int)_text.length;

    start = MAX(0, MIN(start, length));
    end = MAX(start, MIN(end, length));

    _selectedRange = NSMakeRange((NSUInteger)start, (NSUInteger)(end - start));
}

- (void) resetInputMethod{
    auto parent = _parent.tryGet();

    if(parent != nullptr && parent->InputMethod->IsActive()){
        parent->InputMethod->Client->SetPreeditText(nullptr);
    }

    _markedRange = NSMakeRange(_selectedRange.location, 0);

    if([self inputContext]) {
        [[self inputContext] discardMarkedText];
    }
}

- (void) setCursorRect:(FrnRect)rect{
    NSRect cursorRect = ToNSRect(rect);
    NSRect windowRectOnScreen = [[self window] convertRectToScreen:self.frame];
    
    windowRectOnScreen.size = cursorRect.size;
    windowRectOnScreen.origin = NSMakePoint(windowRectOnScreen.origin.x + cursorRect.origin.x, windowRectOnScreen.origin.y + self.frame.size.height - cursorRect.origin.y - cursorRect.size.height);
    
    _cursorRect = windowRectOnScreen;
    
    if([self inputContext]) {
        [[self inputContext] invalidateCharacterCoordinates];
    }
}

@end