File: WindowCocoa.mm

package info (click to toggle)
pd-vstplugin 0.6.2-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,008 kB
  • sloc: cpp: 22,794; lisp: 2,860; makefile: 37; sh: 26
file content (566 lines) | stat: -rw-r--r-- 17,038 bytes parent folder | download
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
#import "WindowCocoa.h"

#include "PluginDesc.h"
#include "Log.h"

#if __has_feature(objc_arc)
#error This file must be compiled without ARC!
#endif

#include <atomic>
#include <iostream>
#include <dispatch/dispatch.h>

// CocoaEditorWindow

@implementation CocoaEditorWindow {}

- (void)setOwner:(vst::IWindow *)owner {
    owner_ = owner;
}

- (BOOL)windowShouldClose:(id)sender {
    LOG_DEBUG("Cocoa: window should close");
    static_cast<vst::Cocoa::Window *>(owner_)->onClose();
    return YES;
}

- (NSSize)windowWillResize:(NSWindow *)sender toSize:(NSSize)frameSize {
    LOG_DEBUG("Cocoa: window will resize");
    return frameSize;
}

- (void)windowDidResize:(NSNotification *)notification {
    // LATER verify size
    // get content size from frame size
    NSRect contentRect = [self contentRectForFrameRect:[self frame]];
    // resize editor
    static_cast<vst::Cocoa::Window *>(owner_)->onResize(
        contentRect.size.width, contentRect.size.height);
    LOG_DEBUG("Cocoa: window did resize");
}

- (void)windowDidMiniaturize:(NSNotification *)notification {
    LOG_DEBUG("Cocoa: window miniaturized");
}
- (void)windowDidDeminiaturize:(NSNotification *)notification {
    LOG_DEBUG("Cocoa: window deminiaturized");
}
- (void)windowDidMove:(NSNotification *)notification {
    LOG_DEBUG("Cocoa: window did move");
}
- (void)updateEditor {
    static_cast<vst::Cocoa::Window *>(owner_)->updateEditor();
}
- (BOOL)performKeyEquivalent:(NSEvent *)event {
    if (event.type == NSKeyDown){
        if (event.modifierFlags & NSCommandKeyMask){
            auto chars = event.charactersIgnoringModifiers.UTF8String;
            if (chars[0] == 'w'){
                LOG_DEBUG("Cocoa: Cmd+W");
                [self performClose:nil];
                return TRUE;
            }
        }
    }
    return FALSE;
}

@end

// EventLoopProxy

@implementation EventLoopProxy
- (id)initWithOwner:(vst::Cocoa::EventLoop*)owner {
    self = [super init];
    if (!self) return nil;

    owner_ = owner;
    return self;
}

- (void)poll {
    owner_->doPoll();
}
@end

namespace vst {

namespace UIThread {

static std::atomic<bool> gRunning{false};

void setup(){
    Cocoa::EventLoop::instance();
}

void run() {
    // this doesn't work...
    // [NSApp run];
    // Kudos to https://www.cocoawithlove.com/2009/01/demystifying-nsapplication-by.html
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

    [NSApp finishLaunching];
    gRunning = true;

    while (gRunning) {
        [pool release];
        pool = [[NSAutoreleasePool alloc] init];
        NSEvent* event = [NSApp nextEventMatchingMask:NSAnyEventMask
                                            untilDate:[NSDate distantFuture]
                                               inMode:NSDefaultRunLoopMode
                                              dequeue:YES];
        if (event) {
            [NSApp sendEvent:event];
            [NSApp updateWindows];
        }
    }
    [pool release];
}

void quit() {
    // break from event loop instead of [NSApp terminate:nil]
    gRunning = false;
    // send dummy event to wake up event loop
    NSEvent* event = [NSEvent otherEventWithType:NSApplicationDefined
                                        location:NSMakePoint(0, 0)
                                   modifierFlags:0
                                       timestamp:0
                                    windowNumber:0
                                         context:nil
                                         subtype:0
                                           data1:0
                                           data2:0];
    [NSApp postEvent:event atStart:NO];
}

// NB: this check must *not* implicitly create the event loop!
// In fact, this is actually called inside the EventLoop constructor!
bool isCurrentThread() {
    return [NSThread isMainThread];
}

bool available() {
    return Cocoa::EventLoop::instance().available();
}

void poll(){
    // only on the main thread!
    if (isCurrentThread()){
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
        while (true) {
            NSEvent *event = [NSApp
                nextEventMatchingMask:NSAnyEventMask
                untilDate:nil
                inMode:NSDefaultRunLoopMode
                dequeue:YES];
            if (event){
                [NSApp sendEvent:event];
                [NSApp updateWindows];
                // LOG_DEBUG("got event: " << [event type]);
            } else {
                break;
            }
        }
        [pool release];
    }
}

bool sync(){
    return callSync([](void *){}, nullptr);
}

bool callSync(Callback cb, void *user){
    return Cocoa::EventLoop::instance().callSync(cb, user);
}

bool callAsync(Callback cb, void *user){
    return Cocoa::EventLoop::instance().callAsync(cb, user);
}

int32_t addPollFunction(PollFunction fn, void *context){
    return Cocoa::EventLoop::instance().addPollFunction(fn, context);
}

void removePollFunction(int32_t handle){
    return Cocoa::EventLoop::instance().removePollFunction(handle);
}

} // UIThread

namespace Cocoa {

/*////////////////////// EventLoop ////////////////////*/

EventLoop& EventLoop::instance(){
    static EventLoop e;
    return e;
}

EventLoop::EventLoop(){
    // NOTE: somehow we must access NSApp only once in the beginning to check
    // for its existence (why?), that's why we cache the result in 'haveNSApp_'.
    if (UIThread::isCurrentThread()){
        // create NSApplication in this thread (= main thread)
        // check if someone already created NSApp (just out of curiousity)
        if (NSApp != nullptr){
            LOG_WARNING("Cocoa: NSApp already initialized!");
        } else {
            // NSApp will automatically point to the NSApplication singleton
            [NSApplication sharedApplication];
            LOG_DEBUG("Cocoa: init event loop (polling)");
        }
        haveNSApp_ = true;
    } else {
        // we don't run on the main thread and expect the host app
        // to create NSApp and run the event loop.
        haveNSApp_ = (NSApp != nullptr);
        if (!haveNSApp_){
            LOG_WARNING("The host application doesn't have a UI thread (yet?), so I can't show the VST GUI editor.");
            return; // done
        }
        LOG_DEBUG("Cocoa: init event loop");
    }

    proxy_ = [[EventLoopProxy alloc] initWithOwner:this];

    LOG_DEBUG("Cocoa: UI thread ready");
}

EventLoop::~EventLoop(){
    if (haveNSApp_) {
        if (timer_) {
            [timer_ invalidate];
            timer_ = nil;
        }
        [proxy_ release];
    }
}

bool EventLoop::callSync(UIThread::Callback cb, void *user){
    if (haveNSApp_){
        if (UIThread::isCurrentThread()){
            cb(user); // we're on the main thread
        } else {
            auto queue = dispatch_get_main_queue();
            dispatch_sync_f(queue, user, cb);
        }
        return true;
    } else {
        LOG_DEBUG("Cocoa: callSync() failed - no NSApp");
        return false;
    }
}

bool EventLoop::callAsync(UIThread::Callback cb, void *user){
    if (haveNSApp_){
        if (UIThread::isCurrentThread()){
            cb(user); // we're on the main thread
        } else {
            auto queue = dispatch_get_main_queue();
            dispatch_async_f(queue, user, cb);
        }
        return true;
    } else {
        LOG_DEBUG("Cocoa: callAsync() failed - no NSApp");
        return false;
    }
}

void EventLoop::startPolling() {
    if (timer_) {
        LOG_ERROR("EventLoop: poll function timer already installed!");
        return;
    }
    timer_ = [NSTimer scheduledTimerWithTimeInterval:(updateIntervalMillis * 0.001)
                target:proxy_
                selector:@selector(poll)
                userInfo:nil
                repeats:YES];
}

void EventLoop::stopPolling() {
    if (timer_) {
        [timer_ invalidate];
        timer_ = nil;
    }
}

/*///////////////// Window ///////////////////////*/

std::atomic<int> Window::numWindows_{0};

Window::Window(IPlugin& plugin)
    : plugin_(&plugin) {}

Window::~Window(){
    if (window_){
    #if 1
        // will implicitly call onClose()!
        [window_ performClose:nil];
    #else
        // cache window before it is set to NULL in onClose()
        auto window = window_;
        onClose();
        [window close];
    #endif
    }
    LOG_DEBUG("Cocoa: destroyed Window");
}

bool Window::canResize() const {
    return plugin_->info().editorResizable();
}

void Window::open(){
    UIThread::callAsync([](void *x){
        static_cast<Window *>(x)->doOpen();
    }, this);
}

// to be called on the main thread
void Window::doOpen(){
    if (window_){
        // just bring to top
        [NSApp activateIgnoringOtherApps:YES];
        [window_ makeKeyAndOrderFront:nil];
        LOG_DEBUG("Cocoa: restore");
        return;
    }

    NSRect frame = NSMakeRect(0, 0, 200, 200);
    NSUInteger style = NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask;
    if (canResize()) {
        style |= NSResizableWindowMask;
        LOG_DEBUG("Cocoa: can resize");
    }
    window_ = [[CocoaEditorWindow alloc] initWithContentRect:frame
                styleMask:style
                backing:NSBackingStoreBuffered
                defer:NO];
    if (window_){
        [window_ setOwner:this];
        [[NSNotificationCenter defaultCenter] addObserver:window_ selector:@selector(windowDidResize:)
                name:NSWindowDidResizeNotification object:window_];
        
        // set window title
        NSString *title = @(plugin_->info().name.c_str());
        [window_ setTitle:title];
        LOG_DEBUG("Cocoa: created Window");

        // set window coordinates
        loading_ = true;
        bool didOpen = false;
        if (rect_.valid()){
            LOG_DEBUG("Cocoa: restore editor rect");
        } else {
            // get window dimensions from plugin
            Rect r;
            if (!plugin_->getEditorRect(r)){
                // HACK for plugins which don't report the window size
                // without the editor being opened
                LOG_DEBUG("Cocoa: couldn't get editor rect!");
                plugin_->openEditor(getHandle());
                plugin_->getEditorRect(r);
                didOpen = true;
            }
            LOG_DEBUG("Cocoa: editor size " << r.w << " * " << r.h);
            // only adjust position initially!
            if (!rect_.valid()){
                adjustPos_ = true;
            }
            rect_.w = r.w;
            rect_.h = r.h;
            adjustSize_ = true;
        }
        loading_ = false;

        updateFrame();

        if (!didOpen){
            plugin_->openEditor(getHandle());
        }

        timer_ = [NSTimer scheduledTimerWithTimeInterval:(EventLoop::updateIntervalMillis * 0.001)
                    target:window_
                    selector:@selector(updateEditor)
                    userInfo:nil
                    repeats:YES];

        if (numWindows_.fetch_add(1) == 0){
            // first Window: transform process into foreground application.
            // This is necessariy so we can table cycle the Window(s)
            // and access them from the dock.
            // NOTE: we have to do this *before* bringing the window to the top
            ProcessSerialNumber psn = {0, kCurrentProcess};
            TransformProcessType(&psn, kProcessTransformToForegroundApplication);
        }

        // bring to top
        [NSApp activateIgnoringOtherApps:YES];
        [window_ makeKeyAndOrderFront:nil];

        LOG_DEBUG("Cocoa: opened Window");
    }
}

void Window::close(){
    EventLoop::instance().callAsync([](void *x){
        auto window = static_cast<Window *>(x)->window_;
        // will implicitly call onClose()!
        [window performClose:nil];
    }, this);
}

// to be called on the main thread
void Window::onClose(){
    if (window_){
        [[NSNotificationCenter defaultCenter] removeObserver:window_ name:NSWindowDidResizeNotification object:window_];

        [timer_ invalidate];
        timer_ = nil;

        plugin_->closeEditor();

        // cache actual position and size
        auto pos = window_.frame.origin;
        rect_.x = pos.x;
        rect_.y = pos.y;
        adjustPos_ = false; // !
        LOG_DEBUG("Cocoa: cache pos: " << rect_.x << ", " << rect_.y);

        auto size = window_.frame.size;
        rect_.w = size.width;
        rect_.h = size.height;
        adjustSize_ = false; // !
        LOG_DEBUG("Cocoa: cache size: " << rect_.w << ", " << rect_.h);

        window_ = nullptr;

        if (numWindows_.fetch_sub(1) == 1){
            // last Window: transform back into background application
            ProcessSerialNumber psn = {0, kCurrentProcess};
            TransformProcessType(&psn, kProcessTransformToUIElementApplication);
        }

        LOG_DEBUG("Cocoa: closed Window");
    }
}

void Window::updateEditor(){
    plugin_->updateEditor();
}

void * Window::getHandle(){
    return window_ ? [window_ contentView] : nullptr;
}

void Window::updateFrame(){
    // first adjust size, because we need it to adjust pos!
    if (adjustSize_){
        LOG_DEBUG("Cocoa: adjust size: want size " << rect_.w << ", " << rect_.h);
        NSRect content = NSMakeRect(rect_.x, rect_.y, rect_.w, rect_.h);
        NSRect frame = [window_  frameRectForContentRect:content];
        rect_.w = frame.size.width;
        rect_.h = frame.size.height;
        LOG_DEBUG("Cocoa: real size " << rect_.w << ", " << rect_.h);
        adjustSize_ = false;
    }
    if (adjustPos_){
        LOG_DEBUG("Cocoa: adjust pos: want pos " << rect_.x << ", " << rect_.y);
        // first move the window to the given x coordinate
        [window_ setFrameOrigin:NSMakePoint(rect_.x, rect_.y)];
        // then obtain the screen height.
        auto screenHeight = window_.screen.frame.size.height;
        LOG_DEBUG("Cocoa: screen height: " << screenHeight);
        // finally flip y coordinate
        // (don't use the actual frame height yet!)
        rect_.y = screenHeight - (rect_.y + rect_.h);
        LOG_DEBUG("real pos " << rect_.x << ", " << rect_.y);
        adjustPos_ = false;
    }
    LOG_DEBUG("Cocoa: update frame");
    LOG_DEBUG("x: " << rect_.x << ", y: " << rect_.y
              << ", w: " << rect_.w << ", h: " << rect_.h);
    NSRect frame = NSMakeRect(rect_.x, rect_.y, rect_.w, rect_.h);
    [window_ setFrame:frame display:YES];
}

void Window::setPos(int x, int y){
    EventLoop::instance().callAsync([](void *user){
        auto cmd = static_cast<Command *>(user);
        auto owner = cmd->owner;
        owner->rect_.x = cmd->x;
        owner->rect_.y = cmd->y;
        owner->adjustPos_ = true; // !
        if (owner->getHandle()){
            owner->updateFrame();
        }
        delete cmd;
    }, new Command { this, x, y });
}

void Window::setSize(int w, int h){
    LOG_DEBUG("Cocoa: setSize: " << w << ", " << h);
    if (w > 0 && h > 0){
        EventLoop::instance().callAsync([](void *user){
            auto cmd = static_cast<Command *>(user);
            auto owner = cmd->owner;
            // only if we can resize!
            if (owner->canResize()){
                // if the window is visible, cache real position
                // and adjust y coordinate for height difference!
                if (owner->getHandle()){
                    auto frame = owner->window_.frame;
                    NSRect rect = [owner->window_  contentRectForFrameRect:frame];
                    auto& pos = frame.origin;
                    owner->rect_.x = pos.x;
                    owner->rect_.y = pos.y - (cmd->y - rect.size.height);
                }
                owner->rect_.w = cmd->x;
                owner->rect_.h = cmd->y;
                owner->adjustSize_ = true;
                if (owner->getHandle()){
                    owner->updateFrame();
                }
            }
            delete cmd;
        }, new Command { this, w, h });
    }
}

void Window::onResize(int w, int h){
    LOG_DEBUG("Cocoa: onResize");
    if (!loading_){
        plugin_->resizeEditor(w, h);
        rect_.w = w;
        rect_.h = h;
        adjustSize_ = true; // !
    }
}

void Window::resize(int w, int h){
    LOG_DEBUG("Cocoa: resized by plugin: " << w << ", " << h);
    if (!loading_){
        // cache real position and adjust y coordinate for height difference!
        // the window is visible, so rect_ should already be adjusted.
        auto pos = window_.frame.origin;
        LOG_DEBUG("Cocoa: current pos: " << pos.x << ", " << pos.y);
        NSRect rect = [window_  contentRectForFrameRect:window_.frame];
        rect_.x = pos.x;
        rect_.y = pos.y - (h - rect.size.height);
        // update and adjust size
        rect_.w = w;
        rect_.h = h;
        adjustSize_ = true;
        updateFrame();
    }
}

} // Cocoa

IWindow::ptr IWindow::create(IPlugin &plugin){
    return std::make_unique<Cocoa::Window>(plugin);
}

} // vst