ferroui-native 0.3.0-preview.1

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
//
// Created by Dan Walmsley on 06/05/2022.
//


#import <AppKit/AppKit.h>
#import "WindowProtocol.h"
#import "WindowBaseImpl.h"

#ifdef IS_NSPANEL
#define BASE_CLASS NSPanel
#define CLASS_NAME FrnPanel
#else
#define BASE_CLASS NSWindow
#define CLASS_NAME FrnWindow
#endif

#import <AppKit/AppKit.h>
#include "common.h"
#include "menu.h"
#include "automation.h"
#include "WindowBaseImpl.h"
#include "WindowImpl.h"
#include "FrnView.h"
#include "WindowInterfaces.h"
#include "FrnAutomationNode.h"
#include "FrnString.h"

@implementation CLASS_NAME
{
    ComObjectWeakPtr<WindowBaseImpl> _parent;
    bool _closed;
    bool _isEnabled;
    bool _canBecomeKeyWindow;
    bool _isExtended;
    bool _isTransitioningToFullScreen;
    bool _isTitlebarSession;
    FrnMenu* _menu;
    ComPtr<IFrnAutomationPeer> _automationPeer;
    FrnAutomationNode* _automationNode;
}

-(FrnView* _Nullable) view
{
    auto parent = _parent.tryGet();
    return parent ? parent->View : nullptr;
}

-(void) setIsExtended:(bool)value;
{
    _isExtended = value;
}

-(bool) isDialog
{
    auto parent = _parent.tryGet();
    return parent ? parent->IsModal() : false;
}

-(double) getExtendedTitleBarHeight
{
    if(_isExtended)
    {
        for (id subview in self.contentView.superview.subviews)
        {
            if ([subview isKindOfClass:NSClassFromString(@"NSTitlebarContainerView")])
            {
                NSView *titlebarView = [subview subviews][0];

                return (double)titlebarView.frame.size.height;
            }
        }

        return -1;
    }
    else
    {
        return 0;
    }
}

- (void)performClose:(id _Nullable )sender
{
    if([[self delegate] respondsToSelector:@selector(windowShouldClose:)])
    {
        if(![[self delegate] windowShouldClose:self]) return;
    }
    else if([self respondsToSelector:@selector(windowShouldClose:)])
    {
        if(![self windowShouldClose:self]) return;
    }

    [self close];
}

- (void)pollModalSession:(nonnull NSModalSession)session
{
    auto response = [NSApp runModalSession:session];

    if(response == NSModalResponseContinue)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self pollModalSession:session];
        });
    }
    else if (!_closed)
    {
        [self orderOut:self];
        [NSApp endModalSession:session];
    }
}

-(void) showWindowMenuWithAppMenu
{
    if(_menu != nullptr)
    {
        auto appMenuItem = ::GetAppMenuItem();

        if(appMenuItem != nullptr)
        {
            auto appMenu = [appMenuItem menu];

            [appMenu removeItem:appMenuItem];

            [_menu insertItem:appMenuItem atIndex:0];

            [_menu setHasGlobalMenuItem:true];
        }

        [NSApp setMenu:_menu];
    }
    else
    {
        [self showAppMenuOnly];
    }
}

-(void) showAppMenuOnly
{
    auto appMenuItem = ::GetAppMenuItem();

    if(appMenuItem != nullptr)
    {
        auto appMenu = ::GetAppMenu();

        [[appMenuItem menu] removeItem:appMenuItem];

        if(_menu != nullptr)
        {
            [_menu setHasGlobalMenuItem:false];
        }

        [appMenu->GetNative() addItem:appMenuItem];

        [NSApp setMenu:appMenu->GetNative()];
    }
}

-(void) applyMenu:(FrnMenu *_Nullable)menu
{
    if(menu == nullptr)
    {
        menu = [FrnMenu new];
    }

    _menu = menu;
}

-(CLASS_NAME*_Nonnull)  initWithParent: (WindowBaseImpl*_Nonnull) parent contentRect: (NSRect)contentRect styleMask: (NSWindowStyleMask)styleMask;
{
    // https://jameshfisher.com/2020/07/10/why-is-the-contentrect-of-my-nswindow-ignored/
    // create nswindow with specific contentRect, otherwise we wont be able to resize the window
    // until several ms after the window is physically on the screen.
    self = [super initWithContentRect:contentRect styleMask: styleMask backing:NSBackingStoreBuffered defer:false];

    [self setReleasedWhenClosed:false];
    _parent = parent;
    [self setDelegate:self];
    _closed = false;
    _isEnabled = true;

    [self setOpaque:NO];

    _isExtended = false;
    _isTransitioningToFullScreen = false;

    if(self.isDialog)
    {
        [self setCollectionBehavior:NSWindowCollectionBehaviorCanJoinAllSpaces|NSWindowCollectionBehaviorFullScreenAuxiliary];
    }

    return self;
}

- (BOOL)windowShouldClose:(NSWindow *_Nonnull)sender
{
    auto window = _parent.tryGet().dynamicCast<WindowImpl>();

    if(window != nullptr)
    {
        return !window->WindowEvents->Closing();
    }

    return true;
}

- (void)windowDidChangeBackingProperties:(NSNotification *_Nonnull)notification
{
    [self backingScaleFactor];
}

- (void)windowWillClose:(NSNotification *_Nonnull)notification
{
    _closed = true;
    auto parent = _parent.tryGetWithCast<WindowBaseImpl>();
    if (parent)
    {
        auto window = parent.dynamicCast<WindowImpl>();
        if (window)
        {
            window->SetParent(nullptr);
        }
        
        parent->BaseEvents->Closed();
        [parent->View onClosed];
    }
}

// From chromium:
//
// > The delegate or the window class should implement this method so that
// > -[NSWindow isZoomed] can be then determined by whether or not the current
// > window frame is equal to the zoomed frame.
//
// If we don't implement this, then isZoomed always returns true for a non-
// resizable window ¯\_(ツ)_/¯
- (NSRect)windowWillUseStandardFrame:(NSWindow* _Nonnull)window
                        defaultFrame:(NSRect)newFrame {
  return newFrame;
}

-(BOOL)canBecomeKeyWindow
{
    if(_canBecomeKeyWindow && !_closed)
    {
        // If the window has a child window being shown as a dialog then don't allow it to become the key window.
        auto parent = _parent.tryGet().dynamicCast<WindowImpl>();
        
        if(parent != nullptr)
        {
            return parent->CanBecomeKeyWindow();
        }

        return true;
    }
    
    return false;
}

#ifndef IS_NSPANEL
-(BOOL)canBecomeMainWindow
{
    return true;
}
#endif

-(void)setCanBecomeKeyWindow:(bool)value
{
    _canBecomeKeyWindow = value;
}

-(bool)shouldTryToHandleEvents
{
    return _isEnabled;
}

-(void) setEnabled:(bool)enable
{
    _isEnabled = enable;
}

-(void)becomeKeyWindow
{
    [self showWindowMenuWithAppMenu];

    auto parent = _parent.tryGet();
    if(parent != nullptr)
    {
        parent->BaseEvents->Activated();
    }

    [super becomeKeyWindow];
}

- (void)windowDidBecomeKey:(NSNotification *_Nonnull)notification
{
    auto parent = _parent.tryGet();
    if (parent == nullptr)
        return;

    if (parent->View != nullptr)
        [parent->View setModifiers:NSEvent.modifierFlags];

    parent->BringToFront();
    
    dispatch_async(dispatch_get_main_queue(), ^{
        @try {
            [self invalidateShadow];
            auto parent = self->_parent.tryGet();
            if (parent != nullptr)
                parent->BringToFront();
        }
        @finally{
        }
    });
}

- (void)windowDidMiniaturize:(NSNotification *_Nonnull)notification
{
    auto parent = _parent.tryGetWithCast<IWindowStateChanged>();

    if(parent != nullptr)
    {
        parent->WindowStateChanged();
    }
}

- (void)windowDidDeminiaturize:(NSNotification *_Nonnull)notification
{
    auto parent = _parent.tryGetWithCast<IWindowStateChanged>();

    if(parent != nullptr)
    {
        parent->WindowStateChanged();
    }
}

- (void)windowDidResize:(NSNotification *_Nonnull)notification
{
    auto parent = _parent.tryGetWithCast<IWindowStateChanged>();

    if(parent != nullptr)
    {
        parent->WindowStateChanged();
    }
}

- (void)windowWillExitFullScreen:(NSNotification *_Nonnull)notification
{
    // Prepare the destination appearance before AppKit starts the exit animation.
    if (_isExtended)
        [self setTitlebarAppearsTransparent:true];

    auto parent = _parent.tryGetWithCast<IWindowStateChanged>();

    if(parent != nullptr)
    {
        parent->StartStateTransition();
    }
}

- (void)windowDidExitFullScreen:(NSNotification *_Nonnull)notification
{
    auto parent = _parent.tryGetWithCast<IWindowStateChanged>();

    if(parent != nullptr)
    {
        parent->EndStateTransition();

        if(parent->Decorations() != SystemDecorationsFull && parent->WindowState() == Maximized)
        {
            NSRect screenRect = [[self screen] visibleFrame];
            [self setFrame:screenRect display:YES];
        }

        if(parent->WindowState() == Minimized)
        {
            [self miniaturize:nullptr];
        }

        parent->WindowStateChanged();
    }
}

- (void)windowWillEnterFullScreen:(NSNotification *_Nonnull)notification
{
    _isTransitioningToFullScreen = true;
    auto parent = _parent.tryGetWithCast<IWindowStateChanged>();

    if(parent != nullptr)
    {
        parent->StartStateTransition();
    }
}

- (void)windowDidEnterFullScreen:(NSNotification *_Nonnull)notification
{
    _isTransitioningToFullScreen = false;
    auto parent = _parent.tryGetWithCast<IWindowStateChanged>();

    if(parent != nullptr)
    {
        parent->EndStateTransition();
        parent->WindowStateChanged();
    }
}

- (BOOL)windowShouldZoom:(NSWindow *_Nonnull)window toFrame:(NSRect)newFrame
{
    auto parent = _parent.tryGet();
    return parent ? parent->CanZoom() : false;
}

-(void)windowDidResignKey:(NSNotification* _Nonnull)notification
{
    auto parent = _parent.tryGet();
    if(parent)
        parent->BaseEvents->Deactivated();

    [self showAppMenuOnly];
    
    [self invalidateShadow];
}

- (void)windowDidMove:(NSNotification *_Nonnull)notification
{
    FrnPoint position;

    auto parent = _parent.tryGet();
    if(parent != nullptr)
    {
        auto window = parent.dynamicCast<WindowImpl>();
        if(window != nullptr)
        {
            if(!window->IsShown())
            {
                return;
            }

            // Don't adjust window state during fullscreen transitions
            // as this can interfere with proper decoration restoration
            if(!window->IsTransitioningWindowState())
            {
                // If the window has been moved into a position where it's "zoomed"
                // Then it should be set as Maximized.
                if (window->WindowState() != Maximized && window->IsZoomed())
                {
                    window->SetWindowState(Maximized, false);
                }
                // We should only return the window state to normal if
                // the internal window state is maximized, and macOS says
                // the window is no longer zoomed (I.E, the user has moved it)
                // Stage Manager will "move" the window when repositioning it
                // So if the window was "maximized" before, it should stay maximized
                else if(window->WindowState() == Maximized && !window->IsZoomed())
                {
                    // If we're moving the window while maximized,
                    // we need to let macOS handle if it should be resized
                    // And not handle it ourselves.
                    window->SetWindowState(Normal, false);
                }
            }
        }

        parent->GetPosition(&position);
        parent->BaseEvents->PositionChanged(position);
    }
}

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

- (NSView*) findRootView:(NSView*)view
{
    while (true) {
        auto parent = [view superview];
        if(parent == nil)
            return view;
        view = parent;
    }
}

- (BOOL)isPointInTitlebar:(NSPoint)windowPoint
{
    auto parent = _parent.tryGetWithCast<WindowImpl>();
    if (!parent || !_isExtended) {
        return NO;
    }
    
    FrnView* view = parent->View;
    NSPoint viewPoint = [view convertPoint:windowPoint fromView:nil];
    double titlebarHeight = [self getExtendedTitleBarHeight];
    
    // Check if click is in titlebar area (top portion of view)
    if (viewPoint.y <= titlebarHeight) {
        // Verify we're actually in a toolbar-related area
        NSView* hitView = [[self findRootView:view] hitTest:windowPoint];
        if (hitView) {
            NSString* hitViewClass = [hitView className];
            if ([hitViewClass containsString:@"Toolbar"] || [hitViewClass containsString:@"Titlebar"]) {
                return YES;
            }
        }
    }
    return NO;
}

- (void)sendEvent:(NSEvent *_Nonnull)event
{
    if (event.type == NSEventTypeLeftMouseDown) {
        _isTitlebarSession = [self isPointInTitlebar:event.locationInWindow];
    }
    
    [super sendEvent:event];

    auto parent = _parent.tryGetWithCast<WindowImpl>();
    /// This is to detect non-client clicks. This can only be done on Windows... not popups, hence the dynamic_cast.
    if(parent)
    {
        switch(event.type)
        {
            case NSEventTypeLeftMouseDown:
            {
                FrnView* view = parent->View;
                NSPoint windowPoint = [event locationInWindow];
                NSPoint viewPoint = [view convertPoint:windowPoint fromView:nil];
                
                auto targetView = [[self findRootView:view] hitTest: windowPoint];
                if(targetView)
                {
                    auto targetViewClass = [targetView className];
                    if([targetViewClass containsString: @"_NSThemeWidget"])
                        return;
                }
                
                if (!NSPointInRect(viewPoint, view.bounds))
                {
                    auto frnPoint = ToFrnPoint(windowPoint);
                    auto point = [self translateLocalPoint:frnPoint];
                    FrnVector delta = { 0, 0 };

                    parent->BaseEvents->RawMouseEvent(NonClientLeftButtonDown, FrnPointerDeviceType::Mouse, static_cast<uint64>([event timestamp] * 1000), FrnInputModifiersNone, point, delta, .5f, .0f, .0f);
                }
                
                if(!_isTransitioningToFullScreen)
                {
                    parent->BringToFront();
                }
            }
            break;

            case NSEventTypeLeftMouseDragged:
            case NSEventTypeMouseMoved:
            case NSEventTypeLeftMouseUp:
            {
                // Usually NSToolbar events are passed natively to FrnView when the mouse is inside the control.
                // When a drag operation started in NSToolbar leaves the control region, the view does not get any 
                // events. We will detect this scenario and pass events ourselves. 
                
                if(!_isTitlebarSession || [self isPointInTitlebar:event.locationInWindow]) 
                    break;

                FrnView* view = parent->View;
                
                if(!view) 
                    break;
                
                if(event.type == NSEventTypeLeftMouseDragged)
                {
                    [view mouseDragged:event];
                }
                else if(event.type == NSEventTypeMouseMoved)
                {
                    [view mouseMoved:event];
                }
                else if(event.type == NSEventTypeLeftMouseUp)
                {
                    [view mouseUp:event];
                }
            }
            break;

            case NSEventTypeMouseEntered:
            {
                parent->UpdateCursor();
            }
                break;

            case NSEventTypeMouseExited:
            {
                [[NSCursor arrowCursor] set];
            }
                break;

            default:
                break;
        }
        
        if(event.type == NSEventTypeLeftMouseUp) {
            _isTitlebarSession = NO;
        }
    }
}

- (void)disconnectParent {
    _parent = nullptr;
}

- (id _Nullable) accessibilityFocusedUIElement
{
    auto automationPeer = [self automationPeer];
    if (automationPeer == nullptr || !automationPeer->IsRootProvider())
        return nil;

    auto focusedPeer = automationPeer->RootProvider_GetFocus();
    if (focusedPeer == nullptr)
        return nil;

    return [FrnAccessibilityElement acquire:focusedPeer];
}

- (NSString * _Nullable) accessibilityIdentifier
{
    auto automationPeer = [self automationPeer];
    if (automationPeer == nullptr)
        return nil;

    return GetNSStringAndRelease(automationPeer->GetAutomationId());
}

- (IFrnAutomationPeer* _Nullable) automationPeer
{
    auto parent = _parent.tryGet();
    if (parent && _automationPeer == nullptr)
    {
        auto peer = parent->BaseEvents->GetAutomationPeer();
        if (peer != nullptr)
        {
            _automationPeer = peer;
            _automationNode = new FrnAutomationNode(self);
            _automationPeer->SetNode(_automationNode);
        }
    }

    return _automationPeer;
}

- (void)raiseChildrenChanged
{
    auto parent = _parent.tryGet();
    if(parent)
        [parent->View raiseAccessibilityChildrenChanged];
}

- (void)raiseFocusChanged
{
    id focused = [self accessibilityFocusedUIElement];
    NSAccessibilityPostNotification(focused, NSAccessibilityFocusedUIElementChangedNotification);
}

- (void)raisePropertyChanged:(FrnAutomationProperty)property
{
    switch (property)
    {
        case AutomationPeer_Name:
            NSAccessibilityPostNotification(self, NSAccessibilityTitleChangedNotification);
            break;
        case AutomationPeer_BoundingRectangle:
            NSAccessibilityPostNotification(self, NSAccessibilityMovedNotification);
            NSAccessibilityPostNotification(self, NSAccessibilityResizedNotification);
            break;
        default:
            break;
    }
}

@end