@windowkit/appkit 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1072 @@
1
+ // @windowkit/appkit threaded.mm — threaded mode's core (windowkit/appkit#50,
2
+ // part of #49): the main thread parked in a real [NSApp run], a way in
3
+ // (commands), a way out (events), and the process's exit and signals.
4
+ //
5
+ // Pump mode stays the default. In it JS runs on the process main thread,
6
+ // which is also AppKit's, and drives AppKit through pump2() from a timer;
7
+ // every modal loop AppKit runs (live resize, menu tracking, a drag, runModal)
8
+ // runs inside that call and freezes Node until it ends. Threaded mode swaps
9
+ // the roles instead: the process main thread calls runMain() and stays in
10
+ // [NSApp run] for the life of the app, and the renderer's JS runs on a
11
+ // worker_threads Worker, where no AppKit loop can reach it.
12
+ //
13
+ // runMain() main thread only; returns the code requestExit gave,
14
+ // or null when the connected environment ended without
15
+ // asking
16
+ // connect(onEvents) from the renderer's thread: onEvents(batch), an array
17
+ // requestExit(code) any thread
18
+ // threaded() runMain is running
19
+ //
20
+ // Mechanism only. What the renderer does with a batch, a close request, a
21
+ // quit request or a SIGINT is its own call; nothing here decides policy.
22
+ //
23
+ // The command queue. A version-0 CFRunLoopSource on the main run loop, added
24
+ // in kCFRunLoopCommonModes, so NSEventTrackingRunLoopMode (live resize, menu
25
+ // tracking, drag sessions) and NSModalPanelRunLoopMode (runModal) drain it
26
+ // too — in the #49 probe 72 commands applied inside a menu's tracking and 75
27
+ // inside an NSAlert, 0.02 ms p50 from post to apply. The drain swaps the
28
+ // queue out under the lock before running anything (a version-0 source can
29
+ // be re-entered by a nested run loop) and applies the batch inside one
30
+ // CATransaction with implicit actions off. A command that starts a modal
31
+ // loop is run from a callout of its own after the drain (CALOnUIModal), so
32
+ // the rest of its batch never waits behind the gesture.
33
+ //
34
+ // The event channel. Producers build plain CALEvent records (channel.h);
35
+ // with the channel open they are appended to one queue, and the first
36
+ // append after a delivery makes one napi_call_threadsafe_function. The JS
37
+ // side swaps the queue out and hands the whole batch over as one array, so
38
+ // a renderer busy for 200 ms gets the events it missed together, not 200 ms
39
+ // of backlog one callback at a time. Consecutive mousemove in one window
40
+ // folds to the latest position before it crosses. A delivery runs in a
41
+ // callback scope, so a microtask queued inside onEvents runs right after it
42
+ // (react-x11#484's frozen microtasks do not exist in this mode).
43
+ //
44
+ // Exit. Only the main thread may end the process: requestExit stops [NSApp
45
+ // run], runMain returns the code, and the main thread's JS calls
46
+ // process.exit(code), which stops the worker in order. (The probe's first
47
+ // try, exit() on the UI thread with the worker still running, raced static
48
+ // destructors: "mutex lock failed: Invalid argument".) An environment that
49
+ // ends without asking — process.exit in a Worker ends only the worker, an
50
+ // uncaught error ends it too — finalizes the threadsafe function, and the
51
+ // finalizer ends the run so runMain returns null instead of parking the
52
+ // process for ever. Before the run loop is stopped, any menu tracking is
53
+ // cancelled and an app-modal loop stopped; [NSApp stop:] ends only the
54
+ // innermost loop, so the stop itself waits for the default mode.
55
+ //
56
+ // Signals. process.on('SIGINT') is never called inside a Worker, and the
57
+ // main thread's JS is parked. While runMain runs, SIGINT, SIGTERM and SIGHUP
58
+ // are ignored as signals and read through DISPATCH_SOURCE_TYPE_SIGNAL on the
59
+ // main queue (kqueue records a signal even when it is ignored); each arrives
60
+ // as a `signal { signal: 'SIGINT' }` event for the renderer to re-emit on
61
+ // its own process. With no environment connected there is nobody to ask,
62
+ // and the run ends with the shell's code for it, 128 + the signal number.
63
+
64
+ #include "channel.h"
65
+
66
+ #import <Cocoa/Cocoa.h>
67
+ #import <QuartzCore/QuartzCore.h>
68
+ #include <dispatch/dispatch.h>
69
+ #include <pthread.h>
70
+ #include <signal.h>
71
+
72
+ #include <algorithm>
73
+ #include <atomic>
74
+ #include <chrono>
75
+ #include <cmath>
76
+ #include <condition_variable>
77
+ #include <cstdio>
78
+ #include <memory>
79
+ #include <mutex>
80
+ #include <unordered_map>
81
+ #include <utility>
82
+ #include <vector>
83
+
84
+ // backend.mm: the application, the pump-mode callback, the held events, and
85
+ // what the run loop needs beyond pump mode (the event monitor, the polled
86
+ // pasteboard count)
87
+ void BEnsureApp();
88
+ bool CALApplyActivationPolicyOption(Napi::Env env, Napi::Value v);
89
+ bool CALHasBackendCb();
90
+ void CALPumpDeliver(const CALEvent& ev);
91
+ void CALReplayHeldEvents();
92
+ void CALBeginRunMode();
93
+ void CALEndRunMode();
94
+
95
+ // ---------------------------------------------------------------------------
96
+ // the event record
97
+ // ---------------------------------------------------------------------------
98
+
99
+ CALEvent::Field& CALEvent::Add(Field::Kind kind, const char* key) {
100
+ fields_.emplace_back();
101
+ Field& f = fields_.back();
102
+ f.kind = kind;
103
+ f.key = key;
104
+ return f;
105
+ }
106
+
107
+ CALEvent& CALEvent::Str(const char* key, const std::string& v) {
108
+ Add(Field::kStr, key).s = v;
109
+ return *this;
110
+ }
111
+ CALEvent& CALEvent::Str(const char* key, const char* v) {
112
+ Add(Field::kStr, key).s = v ? v : "";
113
+ return *this;
114
+ }
115
+ CALEvent& CALEvent::Num(const char* key, double v) {
116
+ Add(Field::kNum, key).n = v;
117
+ return *this;
118
+ }
119
+ CALEvent& CALEvent::Bool(const char* key, bool v) {
120
+ Add(Field::kBool, key).b = v;
121
+ return *this;
122
+ }
123
+ CALEvent& CALEvent::Null(const char* key) {
124
+ Add(Field::kNull, key);
125
+ return *this;
126
+ }
127
+ CALEvent& CALEvent::Strs(const char* key, std::vector<std::string> v) {
128
+ Add(Field::kStrs, key).list = std::move(v);
129
+ return *this;
130
+ }
131
+ CALEvent& CALEvent::Json(const char* key, const std::string& v) {
132
+ Add(Field::kJson, key).s = v;
133
+ return *this;
134
+ }
135
+ CALEvent& CALEvent::Handle(const char* key, CALValueBlock v) {
136
+ Add(Field::kHandle, key).handle = v;
137
+ return *this;
138
+ }
139
+
140
+ static Napi::Value ParseJson(Napi::Env env, const std::string& text) {
141
+ Napi::String s = Napi::String::New(env, text);
142
+ Napi::Object json = env.Global().Get("JSON").As<Napi::Object>();
143
+ Napi::Value v = json.Get("parse").As<Napi::Function>().Call(json, {s});
144
+ if (env.IsExceptionPending()) {
145
+ (void)env.GetAndClearPendingException();
146
+ return s;
147
+ }
148
+ return v;
149
+ }
150
+
151
+ Napi::Object CALEvent::ToObject(Napi::Env env) const {
152
+ Napi::Object o = Napi::Object::New(env);
153
+ for (const Field& f : fields_) {
154
+ switch (f.kind) {
155
+ case Field::kStr: o.Set(f.key, f.s); break;
156
+ case Field::kNum: o.Set(f.key, f.n); break;
157
+ case Field::kBool: o.Set(f.key, f.b); break;
158
+ case Field::kNull: o.Set(f.key, env.Null()); break;
159
+ case Field::kStrs: {
160
+ Napi::Array a = Napi::Array::New(env, f.list.size());
161
+ for (size_t i = 0; i < f.list.size(); i++) a.Set((uint32_t)i, f.list[i]);
162
+ o.Set(f.key, a);
163
+ break;
164
+ }
165
+ case Field::kJson: o.Set(f.key, ParseJson(env, f.s)); break;
166
+ case Field::kHandle:
167
+ o.Set(f.key, f.handle ? f.handle(env) : Napi::Value(env.Null()));
168
+ break;
169
+ }
170
+ }
171
+ return o;
172
+ }
173
+
174
+ // ---------------------------------------------------------------------------
175
+ // commands: into the main run loop
176
+ // ---------------------------------------------------------------------------
177
+
178
+ // The core's locks and queues are leaked on purpose, here and below: a
179
+ // thread that still emits or posts while the process exits (a
180
+ // UserNotifications or EventKit queue) must not find them destroyed — the
181
+ // #49 probe's "mutex lock failed: Invalid argument" abort.
182
+ static std::mutex& gCmdMu = *new std::mutex;
183
+ // A queued command. A frame batch committed with txCommit({ width, height })
184
+ // is tagged with the size it was painted at: what a window's resize
185
+ // handshake waits for (CALAwaitFrame).
186
+ struct Command {
187
+ dispatch_block_t block = nil;
188
+ bool sized = false;
189
+ double width = 0, height = 0;
190
+ };
191
+ static std::vector<Command>& gCmdQ = *new std::vector<Command>; // gCmdMu
192
+ // signalled on every post, for the handshake's bounded wait
193
+ static std::condition_variable& gCmdCv = *new std::condition_variable;
194
+ static CFRunLoopSourceRef gCmdSrc = nullptr;
195
+ static int gDrainDepth = 0; // the UI thread only
196
+
197
+ // Set as requestExit is called, from any thread; read by the UI thread.
198
+ static std::atomic<bool> gExitAsked{false};
199
+ static std::atomic<int> gExitCode{0};
200
+ static std::atomic<bool> gRunning{false};
201
+
202
+ // An NSException escaping a block would unwind through CFRunLoop's frames
203
+ // and take the rest of the batch (and the open transaction) with it.
204
+ static void RunGuarded(dispatch_block_t b) {
205
+ @try {
206
+ b();
207
+ } @catch (NSException* e) {
208
+ fprintf(stderr, "@windowkit/appkit: a UI-thread command raised %s: %s\n",
209
+ e.name.UTF8String, e.reason.UTF8String ?: "");
210
+ }
211
+ }
212
+
213
+ static void DrainCommands(void*) {
214
+ std::vector<Command> batch;
215
+ {
216
+ std::lock_guard<std::mutex> l(gCmdMu);
217
+ batch.swap(gCmdQ);
218
+ }
219
+ if (batch.empty()) return;
220
+ gDrainDepth++;
221
+ @autoreleasepool {
222
+ [CATransaction begin];
223
+ [CATransaction setDisableActions:YES];
224
+ for (const Command& c : batch) RunGuarded(c.block);
225
+ [CATransaction commit];
226
+ }
227
+ gDrainDepth--;
228
+ }
229
+
230
+ // Created by whichever thread needs it first; adding a source to another
231
+ // thread's run loop is allowed. Pump mode never posts, so the source sits
232
+ // idle there unless a worker does.
233
+ static void EnsureCommandSource() {
234
+ static std::once_flag once;
235
+ std::call_once(once, [] {
236
+ CFRunLoopSourceContext ctx = {};
237
+ ctx.perform = DrainCommands;
238
+ gCmdSrc = CFRunLoopSourceCreate(nullptr, 0, &ctx);
239
+ CFRunLoopAddSource(CFRunLoopGetMain(), gCmdSrc, kCFRunLoopCommonModes);
240
+ });
241
+ }
242
+
243
+ static void PostCommand(Command c) {
244
+ EnsureCommandSource();
245
+ {
246
+ std::lock_guard<std::mutex> l(gCmdMu);
247
+ gCmdQ.push_back(std::move(c));
248
+ }
249
+ gCmdCv.notify_all();
250
+ CFRunLoopSourceSignal(gCmdSrc);
251
+ CFRunLoopWakeUp(CFRunLoopGetMain());
252
+ }
253
+
254
+ static void Post(dispatch_block_t b) {
255
+ Command c;
256
+ c.block = b;
257
+ PostCommand(std::move(c));
258
+ }
259
+
260
+ // A block of its own on the main run loop, in the default mode: after the
261
+ // current drain, and only once no tracking or modal loop is running.
262
+ static void Defer(dispatch_block_t b) {
263
+ CFRunLoopPerformBlock(CFRunLoopGetMain(), kCFRunLoopDefaultMode, b);
264
+ CFRunLoopWakeUp(CFRunLoopGetMain());
265
+ }
266
+
267
+ void CALOnUI(dispatch_block_t block) {
268
+ if (pthread_main_np()) {
269
+ block();
270
+ return;
271
+ }
272
+ Post(block);
273
+ }
274
+
275
+ void CALOnUIModal(dispatch_block_t block) {
276
+ // a modal loop begun after an exit was asked for would hold the exit up
277
+ dispatch_block_t unlessExiting = ^{
278
+ if (!gExitAsked.load()) block();
279
+ };
280
+ if (!pthread_main_np()) {
281
+ Post(^{ Defer(unlessExiting); }); // through the queue, so it keeps its place
282
+ } else if (gDrainDepth > 0) {
283
+ Defer(unlessExiting);
284
+ } else {
285
+ block();
286
+ }
287
+ }
288
+
289
+ void CALPostFrame(dispatch_block_t block, bool sized, double width, double height) {
290
+ if (pthread_main_np()) {
291
+ block();
292
+ return;
293
+ }
294
+ Command c;
295
+ c.block = block;
296
+ c.sized = sized;
297
+ c.width = width;
298
+ c.height = height;
299
+ PostCommand(std::move(c));
300
+ }
301
+
302
+ // ---------------------------------------------------------------------------
303
+ // events: out to the connected environment
304
+ // ---------------------------------------------------------------------------
305
+
306
+ static std::mutex& gEvMu = *new std::mutex;
307
+ static std::vector<CALEvent>& gEvQ = *new std::vector<CALEvent>; // gEvMu
308
+ static napi_threadsafe_function gTsfn = nullptr; // gEvMu
309
+ static bool gWakePending = false; // gEvMu
310
+ static int gUIObjects = 0; // gEvMu
311
+ static std::atomic<bool> gConnected{false};
312
+ static bool gRefed = true; // the connected environment's thread only
313
+ static napi_env gConnectedEnv = nullptr; // gEvMu
314
+ static pthread_t gConnectedThread; // gEvMu, valid while gConnectedEnv is
315
+
316
+ bool CALThreaded() { return gRunning.load(); }
317
+ bool CALChannelOpen() { return gRunning.load() || gConnected.load(); }
318
+ bool CALListening() { return CALChannelOpen() || CALHasBackendCb(); }
319
+
320
+ // Called with gEvMu held, which also keeps the function alive for the call:
321
+ // the finalizer takes the same lock before the function is freed.
322
+ static void WakeLocked() {
323
+ if (!gTsfn || gWakePending) return;
324
+ if (napi_call_threadsafe_function(gTsfn, nullptr, napi_tsfn_nonblocking) ==
325
+ napi_ok)
326
+ gWakePending = true;
327
+ }
328
+
329
+ void CALEmit(CALEvent&& ev) {
330
+ if (CALChannelOpen()) {
331
+ std::lock_guard<std::mutex> l(gEvMu);
332
+ if (!gEvQ.empty() && ev.FoldsOnto(gEvQ.back()))
333
+ gEvQ.back() = std::move(ev);
334
+ else
335
+ gEvQ.push_back(std::move(ev));
336
+ WakeLocked();
337
+ return;
338
+ }
339
+ // pump mode calls JS inline, which only its own thread may do
340
+ if (pthread_main_np()) CALPumpDeliver(ev);
341
+ }
342
+
343
+ void CALUIObjectsChanged(int delta) {
344
+ std::lock_guard<std::mutex> l(gEvMu);
345
+ bool before = gUIObjects > 0;
346
+ gUIObjects = std::max(0, gUIObjects + delta);
347
+ bool now = gUIObjects > 0;
348
+ if (before == now) return;
349
+ // On the connected environment's own thread (a worker's createWindow2 or
350
+ // destroyWindow2) the reference is that thread's to change, now: a worker
351
+ // whose script ends right after making a window must still be held.
352
+ if (gTsfn && gConnectedEnv && pthread_equal(pthread_self(), gConnectedThread)) {
353
+ if (now != gRefed) {
354
+ if (now) napi_ref_threadsafe_function(gConnectedEnv, gTsfn);
355
+ else napi_unref_threadsafe_function(gConnectedEnv, gTsfn);
356
+ gRefed = now;
357
+ }
358
+ return;
359
+ }
360
+ WakeLocked(); // elsewhere the next delivery re-decides it
361
+ }
362
+
363
+ // Why it is asked is in channel.h; Node 18 on CI showed it as "FATAL ERROR:
364
+ // Error::ThrowAsJavaScriptException napi_throw" from DeliverBatch. Asked
365
+ // with a raw set on a scratch object, whose failure is only a status.
366
+ bool CALCanCallIntoJS(napi_env env) {
367
+ napi_value o, v;
368
+ if (napi_create_object(env, &o) != napi_ok) return false;
369
+ if (napi_get_boolean(env, true, &v) != napi_ok) return false;
370
+ return napi_set_named_property(env, o, "probe", v) == napi_ok;
371
+ }
372
+
373
+ // Left pending, an exception a threadsafe function's callback threw would
374
+ // not be the environment's uncaught exception: under Node's default N-API
375
+ // policy it is reported as a warning and the error dropped — and a worker
376
+ // whose parent is parked in runMain went on running with its window up
377
+ // (windowkit/appkit#62). Handed to napi_fatal_exception it is the uncaught
378
+ // exception under either policy: process.on('uncaughtException') sees it,
379
+ // and with no handler the environment ends, which ends the run.
380
+ void CALRaiseUncaughtIfPending(napi_env env) {
381
+ bool pending = false;
382
+ if (napi_is_exception_pending(env, &pending) != napi_ok || !pending) return;
383
+ napi_value err;
384
+ if (napi_get_and_clear_last_exception(env, &err) == napi_ok)
385
+ napi_fatal_exception(env, err);
386
+ }
387
+
388
+ void CALCallJS(napi_env env, napi_value cb,
389
+ std::initializer_list<napi_value> args) {
390
+ napi_value undefined;
391
+ if (napi_get_undefined(env, &undefined) != napi_ok) return;
392
+ napi_call_function(env, undefined, cb, args.size(), args.begin(), nullptr);
393
+ CALRaiseUncaughtIfPending(env);
394
+ }
395
+
396
+ // On the connected environment's thread.
397
+ static void DeliverBatch(napi_env env, napi_value cb, void*, void*) {
398
+ if (env == nullptr) return; // the function is being torn down
399
+ std::vector<CALEvent> batch;
400
+ {
401
+ std::lock_guard<std::mutex> l(gEvMu);
402
+ gWakePending = false;
403
+ batch.swap(gEvQ);
404
+ bool want = gUIObjects > 0;
405
+ if (gTsfn && want != gRefed) {
406
+ if (want) napi_ref_threadsafe_function(env, gTsfn);
407
+ else napi_unref_threadsafe_function(env, gTsfn);
408
+ gRefed = want;
409
+ }
410
+ }
411
+ // an environment on its way out gets nothing more: the batch goes with it
412
+ if (batch.empty() || !CALCanCallIntoJS(env)) return;
413
+ Napi::Env e(env);
414
+ Napi::HandleScope scope(e);
415
+ Napi::Array arr = Napi::Array::New(e, batch.size());
416
+ for (uint32_t i = 0; i < batch.size(); i++) arr.Set(i, batch[i].ToObject(e));
417
+ CALCallJS(env, cb, {arr});
418
+ }
419
+
420
+ static void StopRun();
421
+
422
+ // The environment the events went to is gone.
423
+ static void ChannelFinalize(napi_env, void*, void*) {
424
+ {
425
+ std::lock_guard<std::mutex> l(gEvMu);
426
+ gTsfn = nullptr;
427
+ gConnected = false;
428
+ gWakePending = false;
429
+ gConnectedEnv = nullptr;
430
+ }
431
+ CFRunLoopPerformBlock(CFRunLoopGetMain(), kCFRunLoopCommonModes, ^{
432
+ if (gRunning.load()) StopRun();
433
+ });
434
+ CFRunLoopWakeUp(CFRunLoopGetMain());
435
+ }
436
+
437
+ // connect(onEvents) — one environment at a time; whatever was emitted before
438
+ // it (the launch's URL, input that arrived while the worker started) is
439
+ // waiting in the queue and is its first batch.
440
+ static Napi::Value Connect(const Napi::CallbackInfo& info) {
441
+ Napi::Env env = info.Env();
442
+ if (!info[0].IsFunction()) {
443
+ Napi::TypeError::New(env, "connect(onEvents): a function is required")
444
+ .ThrowAsJavaScriptException();
445
+ return env.Undefined();
446
+ }
447
+ {
448
+ std::lock_guard<std::mutex> l(gEvMu);
449
+ if (gTsfn) {
450
+ Napi::Error::New(env, "connect: an environment is already connected")
451
+ .ThrowAsJavaScriptException();
452
+ return env.Undefined();
453
+ }
454
+ }
455
+ napi_threadsafe_function tsfn = nullptr;
456
+ napi_status st = napi_create_threadsafe_function(
457
+ env, info[0], nullptr, Napi::String::New(env, "appkit:events"), 0, 1,
458
+ nullptr, ChannelFinalize, nullptr, DeliverBatch, &tsfn);
459
+ if (st != napi_ok) {
460
+ Napi::Error::New(env, "connect: could not create the event channel")
461
+ .ThrowAsJavaScriptException();
462
+ return env.Undefined();
463
+ }
464
+ std::lock_guard<std::mutex> l(gEvMu);
465
+ gTsfn = tsfn;
466
+ gConnected = true;
467
+ gWakePending = false;
468
+ gRefed = true;
469
+ gConnectedEnv = env;
470
+ gConnectedThread = pthread_self();
471
+ if (gUIObjects == 0) {
472
+ napi_unref_threadsafe_function(env, tsfn);
473
+ gRefed = false;
474
+ }
475
+ if (!gEvQ.empty()) WakeLocked();
476
+ return env.Undefined();
477
+ }
478
+
479
+ // ---------------------------------------------------------------------------
480
+ // handles allocated at the call (windowkit/appkit#51)
481
+ // ---------------------------------------------------------------------------
482
+
483
+ @implementation CALHandle
484
+ - (void)dealloc {
485
+ // The object is the UI thread's to let go of, whichever thread drops the
486
+ // last reference to its handle (a worker's collector, usually): an
487
+ // NSWindow or a CALayer deallocated off the main thread is AppKit misuse.
488
+ id o = object_;
489
+ object_ = nil;
490
+ if (o && !pthread_main_np()) dispatch_async(dispatch_get_main_queue(), ^{ (void)o; });
491
+ }
492
+ @end
493
+
494
+ // id -> the weak reference an event's `handle` field resolves through, in
495
+ // the environment that holds the External. Leaked like the queues above.
496
+ struct RegisteredHandle {
497
+ napi_env env;
498
+ napi_ref ref;
499
+ };
500
+ static std::mutex& gHandleMu = *new std::mutex;
501
+ static std::unordered_map<uint64_t, RegisteredHandle>& gHandles =
502
+ *new std::unordered_map<uint64_t, RegisteredHandle>;
503
+ static std::atomic<uint64_t> gNextHandleId{1};
504
+
505
+ CALHandle* CALNewHandle() {
506
+ CALHandle* h = [CALHandle new];
507
+ h->id_ = gNextHandleId++;
508
+ return h;
509
+ }
510
+
511
+ Napi::Value CALWrapHandle(Napi::Env env, CALHandle* h, bool registered) {
512
+ uint64_t id = h->id_;
513
+ Napi::External<void> ext = Napi::External<void>::New(
514
+ env, (void*)CFBridgingRetain(h), [id, registered](Napi::Env env, void* data) {
515
+ if (registered) {
516
+ napi_ref ref = nullptr;
517
+ {
518
+ std::lock_guard<std::mutex> l(gHandleMu);
519
+ auto it = gHandles.find(id);
520
+ if (it != gHandles.end() && it->second.env == (napi_env)env) {
521
+ ref = it->second.ref;
522
+ gHandles.erase(it);
523
+ }
524
+ }
525
+ if (ref) napi_delete_reference(env, ref);
526
+ }
527
+ CFRelease(data);
528
+ });
529
+ if (registered) {
530
+ napi_ref ref = nullptr;
531
+ if (napi_create_reference(env, ext, 0, &ref) == napi_ok) {
532
+ std::lock_guard<std::mutex> l(gHandleMu);
533
+ gHandles[id] = {env, ref};
534
+ }
535
+ }
536
+ return ext;
537
+ }
538
+
539
+ CALEvent& CALEvent::HandleRef(const char* key, uint64_t id) {
540
+ return Handle(key, ^Napi::Value(Napi::Env env) {
541
+ // looked up on the delivering environment's thread, the only one that
542
+ // registers or finalizes its handles, so the reference cannot go away
543
+ // between the lookup and the read
544
+ napi_ref ref = nullptr;
545
+ {
546
+ std::lock_guard<std::mutex> l(gHandleMu);
547
+ auto it = gHandles.find(id);
548
+ if (it != gHandles.end() && it->second.env == (napi_env)env) ref = it->second.ref;
549
+ }
550
+ napi_value v = nullptr;
551
+ if (ref) napi_get_reference_value(env, ref, &v);
552
+ return v ? Napi::Value(env, v) : env.Null();
553
+ });
554
+ }
555
+
556
+ void CALPinHandle(Napi::Env env, uint64_t id, bool pin) {
557
+ napi_ref ref = nullptr;
558
+ {
559
+ std::lock_guard<std::mutex> l(gHandleMu);
560
+ auto it = gHandles.find(id);
561
+ if (it != gHandles.end() && it->second.env == (napi_env)env) ref = it->second.ref;
562
+ }
563
+ if (!ref) return;
564
+ uint32_t count = 0;
565
+ if (pin) napi_reference_ref(env, ref, &count);
566
+ else napi_reference_unref(env, ref, &count);
567
+ }
568
+
569
+ id CALHandleTarget(Napi::Value v) {
570
+ if (!v.IsExternal()) return nil;
571
+ void* d = v.As<Napi::External<void>>().Data();
572
+ return d ? (__bridge id)d : nil;
573
+ }
574
+
575
+ id CALResolve(id target) {
576
+ if ([target isKindOfClass:[CALHandle class]]) return ((CALHandle*)target)->object_;
577
+ return target;
578
+ }
579
+
580
+ // --- threadsafe functions used from other threads (channel.h) -----------------
581
+
582
+ struct CALTsfn::Life {
583
+ std::mutex mu;
584
+ // null once the reference is let go: answered, released, or the
585
+ // environment ending
586
+ napi_threadsafe_function f = nullptr;
587
+ // the function's finalizer frees the hook's box (a one-shot's); without
588
+ // one the hook does (a long-lived function's, finalized only after it)
589
+ bool finalizes = false;
590
+ };
591
+
592
+ // The environment's cleanup hook, run before the function's own: the
593
+ // reference its holder would have let go goes now, from the environment's
594
+ // thread — so Node that keeps a held function past teardown (#55877) frees
595
+ // it with the rest — and the holder finds the record marked.
596
+ void CALTsfn::EnvEnding(void* arg) {
597
+ auto* box = static_cast<std::shared_ptr<Life>*>(arg);
598
+ Life& life = **box;
599
+ bool finalizes;
600
+ {
601
+ std::lock_guard<std::mutex> l(life.mu);
602
+ if (life.f) napi_release_threadsafe_function(life.f, napi_tsfn_release);
603
+ life.f = nullptr;
604
+ finalizes = life.finalizes;
605
+ }
606
+ if (!finalizes) delete box;
607
+ }
608
+
609
+ // The function's finalizer, on its environment's thread: the hook is not
610
+ // needed any more (at teardown it has run already, and removing it is a
611
+ // no-op).
612
+ void CALTsfn::Finalized(napi_env env, void* arg) {
613
+ auto* box = static_cast<std::shared_ptr<Life>*>(arg);
614
+ napi_remove_env_cleanup_hook(env, EnvEnding, box);
615
+ {
616
+ std::lock_guard<std::mutex> l((*box)->mu);
617
+ (*box)->f = nullptr;
618
+ }
619
+ delete box;
620
+ }
621
+
622
+ CALTsfn CALTsfn::New(Napi::Env env, Napi::Function cb, const char* name) {
623
+ auto life = std::make_shared<Life>();
624
+ life->finalizes = true;
625
+ auto* box = new std::shared_ptr<Life>(life);
626
+ Napi::ThreadSafeFunction f = Napi::ThreadSafeFunction::New(
627
+ env, cb, name, 0, 1, [box](Napi::Env env) { Finalized(env, box); });
628
+ CALTsfn t;
629
+ if (!(napi_threadsafe_function)f) { // not made; the error is pending in env
630
+ delete box;
631
+ return t;
632
+ }
633
+ life->f = f;
634
+ // after the function's own hook, so it runs before it
635
+ napi_add_env_cleanup_hook(env, EnvEnding, box);
636
+ t.life_ = life;
637
+ return t;
638
+ }
639
+
640
+ CALTsfn CALTsfn::Watch(napi_env env, napi_threadsafe_function f) {
641
+ CALTsfn t;
642
+ if (!f) return t;
643
+ auto life = std::make_shared<Life>();
644
+ life->f = f;
645
+ napi_add_env_cleanup_hook(env, EnvEnding, new std::shared_ptr<Life>(life));
646
+ t.life_ = life;
647
+ return t;
648
+ }
649
+
650
+ bool CALTsfn::Use(
651
+ bool release,
652
+ const std::function<napi_status(napi_threadsafe_function)>& call) const {
653
+ if (!life_) return false;
654
+ std::lock_guard<std::mutex> l(life_->mu);
655
+ napi_threadsafe_function f = life_->f;
656
+ if (!f) return false;
657
+ napi_status st = call ? call(f) : napi_ok;
658
+ if (st == napi_closing) {
659
+ // the call let the reference go itself, and may have freed the function
660
+ life_->f = nullptr;
661
+ return false;
662
+ }
663
+ if (release) {
664
+ napi_release_threadsafe_function(f, napi_tsfn_release);
665
+ life_->f = nullptr;
666
+ }
667
+ return call && st == napi_ok;
668
+ }
669
+
670
+ // --- one-shot replies ---------------------------------------------------------
671
+
672
+ struct Reply {
673
+ CALValueBlock make;
674
+ };
675
+
676
+ CALTsfn CALReplyTo(Napi::Env env, Napi::Function cb, const char* name) {
677
+ return CALTsfn::New(env, cb, name);
678
+ }
679
+
680
+ void CALReply(const CALTsfn& tsfn, CALValueBlock make) {
681
+ Reply* r = new Reply{make};
682
+ bool queued = tsfn.Answer(r, [](Napi::Env env, Napi::Function cb, Reply* r) {
683
+ // an environment on its way out gets no answer (channel.h)
684
+ if (!CALCanCallIntoJS(env)) {
685
+ delete r;
686
+ return;
687
+ }
688
+ napi_value v = r->make(env);
689
+ delete r;
690
+ CALCallJS(env, cb, {v});
691
+ });
692
+ if (!queued) delete r;
693
+ }
694
+
695
+ Napi::Value CALAnswer(const Napi::CallbackInfo& info, const char* name,
696
+ CALValueBlock (^compute)(void), bool nested) {
697
+ Napi::Env env = info.Env();
698
+ Napi::Value last = info.Length() ? info[info.Length() - 1] : env.Undefined();
699
+ if (!last.IsFunction()) {
700
+ if (!pthread_main_np()) {
701
+ Napi::TypeError::New(env, std::string(name) +
702
+ ": off the main thread it answers through a "
703
+ "callback, its last argument")
704
+ .ThrowAsJavaScriptException();
705
+ return env.Undefined();
706
+ }
707
+ return compute()(env);
708
+ }
709
+ CALTsfn tsfn = CALReplyTo(env, last.As<Napi::Function>(), name);
710
+ dispatch_block_t work = ^{ CALReply(tsfn, compute()); };
711
+ if (nested) CALOnUIModal(work);
712
+ else CALOnUI(work);
713
+ return env.Undefined();
714
+ }
715
+
716
+ // ---------------------------------------------------------------------------
717
+ // the live-resize handshake (windowkit/appkit#53)
718
+ // ---------------------------------------------------------------------------
719
+ //
720
+ // windowDidResize: asks, on the UI thread, with the new content size: is a
721
+ // frame painted at this size queued? It waits on the queue's condition
722
+ // variable, never longer than `waitMs`, and then drains the queue inline —
723
+ // not through the run-loop source, which AppKit's resize tracking would not
724
+ // fire until the resize had committed without its frame (it calls the
725
+ // delegate outside any run-loop pass: the #49 probe read a NULL mode
726
+ // there). Drained inline, the frame lands in the same transaction as the
727
+ // window's new size. JS never waits on the UI thread, so this cannot
728
+ // deadlock: the worst case is the deadline, and then the last frame shows at
729
+ // the new size, the root layer's background filling the exposed edge.
730
+
731
+ static bool QueuedFrameAt(double w, double h) { // gCmdMu held
732
+ for (const Command& c : gCmdQ)
733
+ if (c.sized && std::fabs(c.width - w) < 0.5 && std::fabs(c.height - h) < 0.5)
734
+ return true;
735
+ return false;
736
+ }
737
+
738
+ bool CALAwaitFrame(double width, double height, double waitMs, double* waitedMs) {
739
+ auto t0 = std::chrono::steady_clock::now();
740
+ bool connected;
741
+ {
742
+ std::lock_guard<std::mutex> l(gEvMu);
743
+ connected = gTsfn != nullptr;
744
+ }
745
+ bool met = false;
746
+ if (connected && waitMs > 0) {
747
+ // The deadline is not the condition variable's own timeout: the kernel
748
+ // coalesces timers, and on a CI VM a 15 ms wait woke only as the worker's
749
+ // 60 ms setTimeout fired. A strict dispatch timer (zero leeway, the flag
750
+ // that asks the system not to coalesce it) ends the wait instead, and the
751
+ // timed wait below is only a backstop a second later.
752
+ auto expired = std::make_shared<std::atomic<bool>>(false);
753
+ dispatch_source_t timer = dispatch_source_create(
754
+ DISPATCH_SOURCE_TYPE_TIMER, 0, DISPATCH_TIMER_STRICT,
755
+ dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0));
756
+ dispatch_source_set_timer(
757
+ timer, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(waitMs * NSEC_PER_MSEC)),
758
+ DISPATCH_TIME_FOREVER, 0);
759
+ dispatch_source_set_event_handler(timer, ^{
760
+ {
761
+ std::lock_guard<std::mutex> l(gCmdMu);
762
+ expired->store(true);
763
+ }
764
+ gCmdCv.notify_all();
765
+ });
766
+ dispatch_resume(timer);
767
+ {
768
+ std::unique_lock<std::mutex> l(gCmdMu);
769
+ gCmdCv.wait_until(
770
+ l, t0 + std::chrono::microseconds((long long)(waitMs * 1000)) + std::chrono::seconds(1),
771
+ [&] { return QueuedFrameAt(width, height) || expired->load(); });
772
+ met = QueuedFrameAt(width, height);
773
+ }
774
+ dispatch_source_cancel(timer);
775
+ }
776
+ *waitedMs = std::chrono::duration<double, std::milli>(
777
+ std::chrono::steady_clock::now() - t0)
778
+ .count();
779
+ DrainCommands(nullptr);
780
+ return met;
781
+ }
782
+
783
+ // ---------------------------------------------------------------------------
784
+ // the run: runMain, requestExit, and what ends a run cleanly
785
+ // ---------------------------------------------------------------------------
786
+
787
+ // Menus being tracked right now, so an exit can cancel them. Every NSMenu
788
+ // posts these, the menu bar's and a pop-up's alike.
789
+ static NSMutableSet<NSMenu*>* gTrackingMenus = nil;
790
+ static id gMenuBeginObserver = nil, gMenuEndObserver = nil;
791
+
792
+ static void ObserveMenuTracking() {
793
+ gTrackingMenus = [NSMutableSet set];
794
+ NSNotificationCenter* nc = NSNotificationCenter.defaultCenter;
795
+ gMenuBeginObserver =
796
+ [nc addObserverForName:NSMenuDidBeginTrackingNotification
797
+ object:nil
798
+ queue:nil
799
+ usingBlock:^(NSNotification* n) {
800
+ if (n.object) [gTrackingMenus addObject:n.object];
801
+ }];
802
+ gMenuEndObserver =
803
+ [nc addObserverForName:NSMenuDidEndTrackingNotification
804
+ object:nil
805
+ queue:nil
806
+ usingBlock:^(NSNotification* n) {
807
+ if (n.object) [gTrackingMenus removeObject:n.object];
808
+ }];
809
+ }
810
+
811
+ static void StopObservingMenuTracking() {
812
+ NSNotificationCenter* nc = NSNotificationCenter.defaultCenter;
813
+ if (gMenuBeginObserver) [nc removeObserver:gMenuBeginObserver];
814
+ if (gMenuEndObserver) [nc removeObserver:gMenuEndObserver];
815
+ gMenuBeginObserver = gMenuEndObserver = nil;
816
+ gTrackingMenus = nil;
817
+ }
818
+
819
+ // An event for a loop waiting in nextEventMatchingMask: to wake on and then
820
+ // see the stop it was asked for. Dispatched, it means nothing to anyone.
821
+ static void PostWakeEvent() {
822
+ NSEvent* e = [NSEvent otherEventWithType:NSEventTypeApplicationDefined
823
+ location:NSZeroPoint
824
+ modifierFlags:0
825
+ timestamp:0
826
+ windowNumber:0
827
+ context:nil
828
+ subtype:0
829
+ data1:0
830
+ data2:0];
831
+ [NSApp postEvent:e atStart:YES];
832
+ }
833
+
834
+ void CALPostWakeEvent() { PostWakeEvent(); }
835
+
836
+ // On the UI thread. [NSApp stop:] ends the innermost loop only, and inside
837
+ // runModal it ends the modal session instead of the app, so any nested loop
838
+ // is ended first and the stop waits for the default mode — the main run.
839
+ // A drag session or a live resize cannot be ended from code; the stop
840
+ // waits for the button to come up.
841
+ static void StopRun() {
842
+ for (NSMenu* m in [gTrackingMenus copy]) [m cancelTrackingWithoutAnimation];
843
+ if (NSApp.modalWindow) [NSApp stopModalWithCode:NSModalResponseAbort];
844
+ PostWakeEvent();
845
+ Defer(^{
846
+ if (!gRunning.load()) return;
847
+ [NSApp stop:nil];
848
+ PostWakeEvent();
849
+ });
850
+ }
851
+
852
+ static const struct {
853
+ int signo;
854
+ const char* name;
855
+ } kForwardedSignals[] = {{SIGINT, "SIGINT"}, {SIGTERM, "SIGTERM"}, {SIGHUP, "SIGHUP"}};
856
+ static constexpr size_t kSignalCount = sizeof kForwardedSignals / sizeof kForwardedSignals[0];
857
+ static dispatch_source_t gSignalSources[kSignalCount];
858
+ static struct sigaction gPrevSignalAction[kSignalCount];
859
+
860
+ static void OnSignal(int signo, const char* name) {
861
+ bool connected;
862
+ {
863
+ std::lock_guard<std::mutex> l(gEvMu);
864
+ connected = gTsfn != nullptr;
865
+ }
866
+ if (connected) {
867
+ CALEmit(std::move(CALEvent("signal").Str("signal", name)));
868
+ return;
869
+ }
870
+ gExitCode = 128 + signo;
871
+ gExitAsked = true;
872
+ StopRun();
873
+ }
874
+
875
+ // Ignored as signals while the run lasts — Node's own SIGINT/SIGTERM handler
876
+ // would end the process from under the worker — and restored after. A child
877
+ // spawned meanwhile does not inherit the SIG_IGN: libuv resets every
878
+ // disposition in the child before exec.
879
+ static void ForwardSignals() {
880
+ for (size_t i = 0; i < kSignalCount; i++) {
881
+ int signo = kForwardedSignals[i].signo;
882
+ const char* name = kForwardedSignals[i].name;
883
+ struct sigaction ign = {};
884
+ ign.sa_handler = SIG_IGN;
885
+ sigemptyset(&ign.sa_mask);
886
+ sigaction(signo, &ign, &gPrevSignalAction[i]);
887
+ dispatch_source_t src = dispatch_source_create(
888
+ DISPATCH_SOURCE_TYPE_SIGNAL, (uintptr_t)signo, 0, dispatch_get_main_queue());
889
+ dispatch_source_set_event_handler(src, ^{ OnSignal(signo, name); });
890
+ dispatch_resume(src);
891
+ gSignalSources[i] = src;
892
+ }
893
+ }
894
+
895
+ static void StopForwardingSignals() {
896
+ for (size_t i = 0; i < kSignalCount; i++) {
897
+ if (!gSignalSources[i]) continue;
898
+ dispatch_source_cancel(gSignalSources[i]);
899
+ gSignalSources[i] = nil;
900
+ sigaction(kForwardedSignals[i].signo, &gPrevSignalAction[i], nullptr);
901
+ }
902
+ }
903
+
904
+ // runMain() — parks the process main thread in [NSApp run] until
905
+ // requestExit, a signal nobody is connected to hear, or the connected
906
+ // environment's end. -> the requested code, or null for the last.
907
+ static Napi::Value RunMain(const Napi::CallbackInfo& info) {
908
+ Napi::Env env = info.Env();
909
+ if (!pthread_main_np()) {
910
+ Napi::Error::New(env, "runMain: only the process main thread can run AppKit")
911
+ .ThrowAsJavaScriptException();
912
+ return env.Undefined();
913
+ }
914
+ if (gRunning.load()) {
915
+ Napi::Error::New(env, "runMain: already running").ThrowAsJavaScriptException();
916
+ return env.Undefined();
917
+ }
918
+ // runMain({ activationPolicy }) — the policy to launch with, for a
919
+ // launcher that knows it before the app's code has run (#64); a name
920
+ // nobody knows is a RangeError before anything launches
921
+ if (info.Length() > 0 && info[0].IsObject() &&
922
+ !CALApplyActivationPolicyOption(env, info[0].As<Napi::Object>().Get("activationPolicy")))
923
+ return env.Undefined();
924
+ // asked before there was a run to end
925
+ if (gExitAsked.exchange(false)) return Napi::Number::New(env, gExitCode.load());
926
+
927
+ BEnsureApp();
928
+ EnsureCommandSource();
929
+ ObserveMenuTracking();
930
+ ForwardSignals();
931
+ gRunning = true;
932
+ // what pump mode held back for a listener goes into the channel first
933
+ CALReplayHeldEvents();
934
+ CALBeginRunMode();
935
+ @autoreleasepool {
936
+ // A second finishLaunching inside -run sends applicationWillFinishLaunching:
937
+ // again but not applicationDidFinishLaunching: (measured on 15.2); the
938
+ // app delegate implements neither, and the launch's Apple Event was
939
+ // dispatched by the first.
940
+ [NSApp run];
941
+ }
942
+ CALEndRunMode();
943
+ StopForwardingSignals();
944
+ StopObservingMenuTracking();
945
+ gRunning = false;
946
+ if (gExitAsked.exchange(false)) return Napi::Number::New(env, gExitCode.load());
947
+ return env.Null();
948
+ }
949
+
950
+ // requestExit(code) — any thread. Ends [NSApp run]; runMain returns `code`.
951
+ // The process itself is ended by the main thread's JS with that code. Asked
952
+ // before runMain, runMain returns it at once.
953
+ static Napi::Value RequestExit(const Napi::CallbackInfo& info) {
954
+ Napi::Env env = info.Env();
955
+ int code = 0;
956
+ if (info.Length() > 0 && !info[0].IsUndefined()) {
957
+ if (!info[0].IsNumber()) {
958
+ Napi::TypeError::New(env, "requestExit(code): code must be a number")
959
+ .ThrowAsJavaScriptException();
960
+ return env.Undefined();
961
+ }
962
+ code = info[0].As<Napi::Number>().Int32Value();
963
+ }
964
+ gExitCode = code;
965
+ gExitAsked = true;
966
+ CALOnUI(^{ StopRun(); });
967
+ return env.Undefined();
968
+ }
969
+
970
+ static Napi::Value Threaded(const Napi::CallbackInfo& info) {
971
+ return Napi::Boolean::New(info.Env(), gRunning.load());
972
+ }
973
+
974
+ // ---------------------------------------------------------------------------
975
+ // test hooks: a command's round trip, and the nested loops it must survive
976
+ // ---------------------------------------------------------------------------
977
+
978
+ // pingUI(tag) — a command that answers `ui-pong { tag, mode, drained }` from
979
+ // the UI thread: `mode` is the run-loop mode it was applied in (null outside
980
+ // any), `drained` whether it came through the queue rather than inline. The
981
+ // round trip is a command's latency plus an event's.
982
+ static Napi::Value PingUI(const Napi::CallbackInfo& info) {
983
+ double tag = info.Length() > 0 && info[0].IsNumber()
984
+ ? info[0].As<Napi::Number>().DoubleValue()
985
+ : 0;
986
+ CALOnUI(^{
987
+ CALEvent ev("ui-pong");
988
+ ev.Num("tag", tag);
989
+ CFStringRef mode = CFRunLoopCopyCurrentMode(CFRunLoopGetMain());
990
+ if (mode) {
991
+ ev.Str("mode", ((__bridge NSString*)mode).UTF8String);
992
+ CFRelease(mode);
993
+ } else {
994
+ ev.Null("mode");
995
+ }
996
+ ev.Bool("drained", gDrainDepth > 0);
997
+ CALEmit(std::move(ev));
998
+ });
999
+ return info.Env().Undefined();
1000
+ }
1001
+
1002
+ static double NowMs() { return CFAbsoluteTimeGetCurrent() * 1000.0; }
1003
+
1004
+ static void RunNestedLoop(bool menu, double ms) {
1005
+ const char* kind = menu ? "menu" : "modal";
1006
+ double t0 = NowMs();
1007
+ CALEmit(std::move(CALEvent("modal-loop-begin").Str("kind", kind)));
1008
+ if (menu) {
1009
+ NSMenu* m = [[NSMenu alloc] initWithTitle:@"appkit"];
1010
+ [m addItemWithTitle:@"postModalLoop" action:nil keyEquivalent:@""];
1011
+ [m addItemWithTitle:@"ends by itself" action:nil keyEquivalent:@""];
1012
+ NSTimer* t = [NSTimer timerWithTimeInterval:ms / 1000.0
1013
+ repeats:NO
1014
+ block:^(NSTimer*) {
1015
+ [m cancelTrackingWithoutAnimation];
1016
+ }];
1017
+ [NSRunLoop.mainRunLoop addTimer:t forMode:NSRunLoopCommonModes];
1018
+ [m popUpMenuPositioningItem:nil atLocation:NSEvent.mouseLocation inView:nil];
1019
+ [t invalidate];
1020
+ } else {
1021
+ NSAlert* a = [NSAlert new];
1022
+ a.messageText = @"@windowkit/appkit postModalLoop";
1023
+ a.informativeText = @"A test's modal loop; it ends by itself.";
1024
+ [a addButtonWithTitle:@"OK"];
1025
+ NSTimer* t = [NSTimer timerWithTimeInterval:ms / 1000.0
1026
+ repeats:NO
1027
+ block:^(NSTimer*) {
1028
+ [NSApp stopModalWithCode:NSModalResponseAbort];
1029
+ PostWakeEvent();
1030
+ }];
1031
+ [NSRunLoop.mainRunLoop addTimer:t forMode:NSRunLoopCommonModes];
1032
+ [a runModal];
1033
+ [t invalidate];
1034
+ }
1035
+ CALEmit(std::move(
1036
+ CALEvent("modal-loop-end").Str("kind", kind).Num("ms", NowMs() - t0)));
1037
+ }
1038
+
1039
+ // postModalLoop('menu' | 'modal', ms) — for tests: one of AppKit's nested
1040
+ // loops on the UI thread for `ms`, then ended from a timer: a pop-up menu's
1041
+ // tracking (NSEventTrackingRunLoopMode) or an NSAlert's runModal
1042
+ // (NSModalPanelRunLoopMode). Started as a modal command, so it is also the
1043
+ // test of CALOnUIModal; `modal-loop-begin` / `modal-loop-end { ms }` bracket
1044
+ // it. In pump mode it runs inside the call, as any modal loop does there.
1045
+ static Napi::Value PostModalLoop(const Napi::CallbackInfo& info) {
1046
+ Napi::Env env = info.Env();
1047
+ std::string kind = info.Length() > 0 && info[0].IsString()
1048
+ ? info[0].As<Napi::String>().Utf8Value()
1049
+ : "";
1050
+ if (kind != "menu" && kind != "modal") {
1051
+ Napi::TypeError::New(env, "postModalLoop(kind, ms): kind is 'menu' or 'modal'")
1052
+ .ThrowAsJavaScriptException();
1053
+ return env.Undefined();
1054
+ }
1055
+ double ms = info.Length() > 1 && info[1].IsNumber()
1056
+ ? info[1].As<Napi::Number>().DoubleValue()
1057
+ : 500;
1058
+ bool menu = kind == "menu";
1059
+ CALOnUIModal(^{ RunNestedLoop(menu, ms); });
1060
+ return env.Undefined();
1061
+ }
1062
+
1063
+ void InitThreaded(Napi::Env env, Napi::Object exports) {
1064
+ #define TFN(js, fn) exports.Set(js, Napi::Function::New(env, fn))
1065
+ TFN("runMain", RunMain);
1066
+ TFN("connect", Connect);
1067
+ TFN("requestExit", RequestExit);
1068
+ TFN("threaded", Threaded);
1069
+ TFN("pingUI", PingUI);
1070
+ TFN("postModalLoop", PostModalLoop);
1071
+ #undef TFN
1072
+ }