ferroui-native 0.3.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
//
// Created by Dan Walmsley on 04/05/2022.
//

#import <AppKit/AppKit.h>
#import <Cocoa/Cocoa.h>
#include "common.h"
#include "FrnView.h"
#include "menu.h"
#include "automation.h"
#include "cursor.h"
#include "ResizeScope.h"
#include "AutoFitContentView.h"
#import "WindowProtocol.h"
#import "WindowInterfaces.h"
#include "WindowBaseImpl.h"
#include "WindowImpl.h"
#include "FrnTextInputMethod.h"
#include "FrnView.h"
#include <algorithm>

@class AutoFitContentView;


// Activates the app, but defers until the run loop is running if it isn't yet.
// Windows are shown (and the app activated) from OnFrameworkInitializationCompleted,
// which runs before -[NSApplication run]. Activating that early yields a "degraded"
// activation: the app looks frontmost but the WindowServer never does a real
// become-active, which leaves the out-of-process file picker unable to receive
// clicks in its file list/sidebar until a manual app switch. Deferring makes the first
// activation a clean transition.
static void ActivateApplication() {
    if ([NSApp isRunning]) {
        [NSApp activateIgnoringOtherApps:YES];
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [NSApp activateIgnoringOtherApps:YES];
        });
    }
}

WindowBaseImpl::~WindowBaseImpl() {
    View = nullptr;
    Window = nullptr;
}

WindowBaseImpl::WindowBaseImpl(IFrnWindowBaseEvents *events, bool usePanel) : TopLevelImpl(events) {
    _children = std::list<ComObjectWeakPtr<WindowBaseImpl>>();
    _shown = false;
    _inResize = false;
    BaseEvents = events;

    lastPositionSet = { 0, 0 };
    hasPosition = false;
    lastSize = NSSize { 100, 100 };
    lastMaxSize = NSSize { CGFLOAT_MAX, CGFLOAT_MAX};
    lastMinSize = NSSize { 0, 0 };
    lastMenu = nullptr;

    CreateNSWindow(usePanel);

    StandardContainer = [[AutoFitContentView new] initWithContent:View];

    [Window setContentView:StandardContainer];
    [Window setBackingType:NSBackingStoreBuffered];
    [Window setContentMinSize:lastMinSize];
    [Window setContentMaxSize:lastMaxSize];
    [Window setOpaque:false];
}

NSWindow *WindowBaseImpl::GetNSWindow() {
    return Window;
}

HRESULT WindowBaseImpl::ObtainNSWindowHandleRetained(void **ret) {
    START_COM_CALL;

    if (ret == nullptr) {
        return E_POINTER;
    }

    *ret = (__bridge_retained void *) Window;

    return S_OK;
}

HRESULT WindowBaseImpl::Show(bool activate, bool isDialog) {
    START_COM_CALL;

    @autoreleasepool {
        [Window setContentSize:lastSize];

        if(hasPosition)
        {
            SetPosition(lastPositionSet);
        } else
        {
            [Window center];
        }

        // When showing a window, disallow fullscreen because if the window is being
        // shown while another window is fullscreen, macOS will briefly transition this
        // new window to fullscreen and then it will be transitioned back. This breaks
        // input events for a short time as described in this issue:
        //
        // upstream tracker issue OUTSYSTEMS-40
        //
        // We restore the collection behavior at the end of this method.
        auto collectionBehavior = [Window collectionBehavior];
        [Window setCollectionBehavior:collectionBehavior & ~NSWindowCollectionBehaviorFullScreenPrimary];

        UpdateAppearance();

        [Window invalidateShadow];

        if (ShouldTakeFocusOnShow() && activate) {
            [Window orderFront:Window];
            [Window makeKeyAndOrderFront:Window];
            [Window makeFirstResponder:View];
            ActivateApplication();
        } else {
            [Window orderFront:Window];
        }

        _shown = true;
        [Window setCollectionBehavior:collectionBehavior];

        // Ensure that we call needsDisplay = YES so that FrnView.updateLayer is called after the
        // window is shown: if the client is pumping messages during the window creation/show
        // process, it's possible that updateLayer gets called after the window is created but
        // before it's is shown.
        [View.layer setNeedsDisplay];

        return S_OK;
    }
}

bool WindowBaseImpl::IsShown ()
{
    return _shown;
}

bool WindowBaseImpl::ShouldTakeFocusOnShow() {
    return true;
}

HRESULT WindowBaseImpl::ObtainNSWindowHandle(void **ret) {
    START_COM_CALL;

    if (ret == nullptr) {
        return E_POINTER;
    }

    *ret = (__bridge void *) Window;

    return S_OK;
}

HRESULT WindowBaseImpl::Hide() {
    START_COM_CALL;

    @autoreleasepool {
        if (Window != nullptr) {

            // If window is hidden without ending attached sheet first, it will stuck in "order out" state,
            // and block any new sheets from being attached.
            // Additionaly, we don't know if user would define any custom panels, so we only end/close file dialog sheets.
            auto attachedSheet = Window.attachedSheet;
            if (attachedSheet
                && ([attachedSheet isKindOfClass: [NSOpenPanel class]]
                    || [attachedSheet isKindOfClass: [NSSavePanel class]]))
            {
                [Window endSheet:attachedSheet];
                [attachedSheet close];
            }

            auto frame = [Window frame];

            FrnPoint point;
            point.X = frame.origin.x;
            point.Y = frame.origin.y + frame.size.height;

            lastPositionSet = ConvertPointY(point);
            hasPosition = true;
            [Window orderOut:Window];
        }

        return S_OK;
    }
}

HRESULT WindowBaseImpl::Activate() {
    START_COM_CALL;

    @autoreleasepool {
        if (Window != nullptr) {
            [Window makeKeyAndOrderFront:nil];
            ActivateApplication();
        }
    }

    return S_OK;
}

HRESULT WindowBaseImpl::SetTopMost(bool value) {
    START_COM_CALL;

    @autoreleasepool {
        _isTopmost = value;

        UpdateWindowLevel();

        return S_OK;
    }
}

NSWindowLevel WindowBaseImpl::GetBaseWindowLevel() {
    return _isTopmost ? NSFloatingWindowLevel : NSNormalWindowLevel;
}

void WindowBaseImpl::UpdateWindowLevel() {
    if (Window == nullptr)
        return;

    auto level = GetBaseWindowLevel();

    // An owned window must be able to come to the front of its owner.
    // TODO: It shouldn't be necessary if we used `addChildWindow` API.
    auto parent = Parent.tryGet();

    if (parent != nullptr && parent->Window != nullptr)
        level = std::max(level, [parent->Window level]);

    [Window setLevel:level];

    for (auto iterator = _children.begin(); iterator != _children.end(); iterator++) {
        auto child = (*iterator).tryGet();

        if (child != nullptr)
            child->UpdateWindowLevel();
    }
}

HRESULT WindowBaseImpl::Close() {
    START_COM_CALL;

    @autoreleasepool {
        if (Window != nullptr) {
            auto window = Window;
            Window = nullptr;

            try {
                // Seems to throw sometimes on application exit.
                [window close];
            }
            catch (NSException *) {}
        }

        return S_OK;
    }
}

HRESULT WindowBaseImpl::GetFrameSize(FrnSize *ret) {
    START_COM_CALL;

    @autoreleasepool {
        if (ret == nullptr)
            return E_POINTER;

        if(Window != nullptr && _shown){
            auto frame = [Window frame];
            ret->Width = frame.size.width;
            ret->Height = frame.size.height;
        }

        return S_OK;
    }
}

HRESULT WindowBaseImpl::SetMinMaxSize(FrnSize minSize, FrnSize maxSize) {
    START_COM_CALL;

    @autoreleasepool {
        lastMinSize = ToNSSize(minSize);
        lastMaxSize = ToNSSize(maxSize);

        if(Window != nullptr) {
            [Window setContentMinSize:lastMinSize];
            [Window setContentMaxSize:lastMaxSize];
        }

        return S_OK;
    }
}

HRESULT WindowBaseImpl::Resize(double x, double y, FrnPlatformResizeReason reason) {
    if (_inResize) {
        return S_OK;
    }

    _inResize = true;

    START_COM_CALL;
    auto resizeBlock = ResizeScope(View, reason);

    @autoreleasepool {
        auto maxSize = lastMaxSize;
        auto minSize = lastMinSize;

        if (x < minSize.width) {
            x = minSize.width;
        }

        if (y < minSize.height) {
            y = minSize.height;
        }

        if (x > maxSize.width) {
            x = maxSize.width;
        }

        if (y > maxSize.height) {
            y = maxSize.height;
        }

        @try {
            if(x != lastSize.width || y != lastSize.height)
            {
                if (!_shown) {
                    auto screenSize = [Window screen].visibleFrame.size;

                    if (x > screenSize.width) {
                        x = screenSize.width;
                    }

                    if (y > screenSize.height) {
                        y = screenSize.height;
                    }
                }

                lastSize = NSSize{x, y};

                SetClientSize(lastSize);
                [Window invalidateShadow];
            }
        }
        @finally {
            _inResize = false;
        }

        return S_OK;
    }
}

HRESULT WindowBaseImpl::SetMainMenu(IFrnMenu *menu) {
    START_COM_CALL;

    auto nativeMenu = dynamic_cast<FrnAppMenu *>(menu);

    lastMenu = nativeMenu->GetNative();

    if(Window != nullptr) {
        [GetWindowProtocol() applyMenu:lastMenu];

        if ([Window isKeyWindow]) {
            [GetWindowProtocol() showWindowMenuWithAppMenu];
        }
    }

    return S_OK;
}

HRESULT WindowBaseImpl::BeginMoveDrag() {
    START_COM_CALL;

    @autoreleasepool {
        auto lastEvent = [View lastMouseDownEvent];

        if (lastEvent == nullptr) {
            // A press that begins inside an embedded native view (for example a webview hosted
            // through NativeControlHost) is consumed by that view and never delivered to the
            // Ferro view, so no mouse-down is recorded; fall back to the event the
            // application is tracking right now, provided it is a left-button press or drag
            // that belongs to this window.
            auto currentEvent = [NSApp currentEvent];

            if (currentEvent != nullptr && [currentEvent window] == Window &&
                ([currentEvent type] == NSEventTypeLeftMouseDown ||
                 [currentEvent type] == NSEventTypeLeftMouseDragged)) {
                lastEvent = currentEvent;
            }
        }

        if (lastEvent == nullptr) {
            return S_OK;
        }

        [Window performWindowDragWithEvent:lastEvent];

        return S_OK;
    }
}

HRESULT WindowBaseImpl::BeginResizeDrag(__attribute__((unused)) FrnWindowEdge edge) {
    START_COM_CALL;

    return S_OK;
}

HRESULT WindowBaseImpl::GetPosition(FrnPoint *ret) {
    START_COM_CALL;

    @autoreleasepool {
        if (ret == nullptr) {
            return E_POINTER;
        }

        if(Window != nullptr) {
            auto frame = [Window frame];

            ret->X = frame.origin.x;
            ret->Y = frame.origin.y + frame.size.height;

            *ret = ConvertPointY(*ret);
        } else
        {
            *ret = lastPositionSet;
        }

        return S_OK;
    }
}

HRESULT WindowBaseImpl::SetPosition(FrnPoint point) {
    START_COM_CALL;

    @autoreleasepool {
        lastPositionSet = point;
        hasPosition = true;

        if(Window != nullptr) {
            [Window setFrameTopLeftPoint:ToNSPoint(ConvertPointY(point))];
        }

        return S_OK;
    }
}

HRESULT WindowBaseImpl::SetTransparencyMode(FrnWindowTransparencyMode mode) {
    START_COM_CALL;

    [Window setBackgroundColor: (mode != Transparent ? [NSColor windowBackgroundColor] : [NSColor clearColor])];
    [StandardContainer ShowBlur: mode == Blur];

    return S_OK;
}

HRESULT WindowBaseImpl::SetFrameThemeVariant(FrnPlatformThemeVariant variant) {
    START_COM_CALL;

    NSAppearanceName appearanceName;
    if (@available(macOS 10.14, *))
    {
        appearanceName = variant == FrnPlatformThemeVariant::Dark ? NSAppearanceNameDarkAqua : NSAppearanceNameAqua;
    }
    else
    {
        appearanceName = variant == FrnPlatformThemeVariant::Dark ? NSAppearanceNameVibrantDark : NSAppearanceNameAqua;
    }

    [Window setAppearance: [NSAppearance appearanceNamed: appearanceName]];

    return S_OK;
}

bool WindowBaseImpl::IsModal() {
    return false;
}

void WindowBaseImpl::UpdateAppearance() {
    [Window setStyleMask:CalculateStyleMask()];
}

void WindowBaseImpl::SetClientSize(NSSize size){
    [Window setContentSize:lastSize];
}

void WindowBaseImpl::CleanNSWindow() {
    if(Window != nullptr) {
        [GetWindowProtocol() disconnectParent];
        [Window close];
        Window = nullptr;
    }
}

void WindowBaseImpl::CreateNSWindow(bool usePanel) {
    // Anchor the content rect to the primary screen's origin. It's usually at (0,0), but can be offset while the
    // display server is mid-reconfiguration. This ensures the window is always on a proper screen.
    // See upstream issues 18895
    NSPoint origin = NSZeroPoint;
    NSArray<NSScreen*>* screens = [NSScreen screens];
    if (screens.count > 0)
        origin = screens.firstObject.frame.origin;

    NSRect contentRect = NSRect { origin.x, origin.y, lastSize };

    if (usePanel) {
        Window = [[FrnPanel alloc] initWithParent:this contentRect:contentRect styleMask:NSWindowStyleMaskBorderless];
        [Window setHidesOnDeactivate:false];
    } else {
        Window = [[FrnWindow alloc] initWithParent:this contentRect:contentRect styleMask:NSWindowStyleMaskBorderless];
    }
}

id <FrnWindowProtocol> WindowBaseImpl::GetWindowProtocol() {
    if(Window == nullptr)
    {
        return nullptr;
    }

    return (id <FrnWindowProtocol>) Window;
}

void WindowBaseImpl::BringToFront()
{
    // do nothing.
}

HRESULT WindowBaseImpl::SetParent(IFrnWindowBase *parent) {
    START_COM_CALL;

    @autoreleasepool {

        auto oldParent = Parent.tryGet();

        if(oldParent != nullptr)
        {
            oldParent->_children.remove(this);
        }

        auto cparent = dynamic_cast<WindowImpl *>(parent);

        Parent = cparent;

        if(cparent != nullptr && Window != nullptr){
            // If one tries to show a child window with a minimized parent window, then the parent window will be
            // restored but macOS isn't kind enough to *tell* us that, so the window will be left in a non-interactive
            // state. Detect this and explicitly restore the parent window ourselves to avoid this situation.
            if (cparent->WindowState() == Minimized)
                cparent->SetWindowState(Normal);

            [Window setCollectionBehavior:NSWindowCollectionBehaviorFullScreenAuxiliary];

            cparent->_children.push_back(this);

            UpdateAppearance();
        }

        UpdateWindowLevel();

        return S_OK;
    }
}