@windowkit/appkit 0.4.0 → 0.5.1

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.
package/src/backend.mm CHANGED
@@ -5,8 +5,8 @@
5
5
  // surfaces with a canvas-shaped drawing API, a CoreText layout engine
6
6
  // (measure + draw + caret/hit geometry) with glyph-level natives beside it
7
7
  // (ids, advances, fallback faces, glyph-run drawing), pasteboard text,
8
- // screen lists and cursors. The retained-layer API stays in addon.mm; this
9
- // file is what a renderer paints and listens through.
8
+ // drag and drop, screen lists and cursors. The retained-layer API stays in
9
+ // addon.mm; this file is what a renderer paints and listens through.
10
10
  //
11
11
  // Coordinate rule, stated once: every point that crosses this boundary is
12
12
  // TOP-LEFT origin. Window frames and screen rects are top-left in global
@@ -20,7 +20,9 @@
20
20
  #import <QuartzCore/QuartzCore.h>
21
21
  #import <CoreText/CoreText.h>
22
22
  #import <IOSurface/IOSurface.h>
23
+ #import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
23
24
  #include <objc/runtime.h>
25
+ #include <dlfcn.h>
24
26
 
25
27
  #include <cmath>
26
28
  #include <string>
@@ -67,15 +69,47 @@ static CGColorRef BMakeColor(Napi::Value v) {
67
69
  return CGColorCreateSRGB(r, g, b, al);
68
70
  }
69
71
 
70
- static void BEnsureApp() {
71
- static bool inited = false;
72
- if (inited) return;
72
+ // ---------------------------------------------------------------------------
73
+ // the application: one bootstrap for both faces of the addon. addon.mm's
74
+ // EnsureApp calls BEnsureApp (not static for that reason), so NSApplication
75
+ // is set up exactly once, whichever entry point (initApp, createWindow,
76
+ // createWindow2, a control bezel) comes first, and the app delegate it
77
+ // dispatches to is in place for finishLaunching.
78
+ //
79
+ // The activation policy has to be decided before finishLaunching: a Regular
80
+ // launch registers a Dock tile, and an agent app that flips to Accessory
81
+ // afterwards has already flashed its icon. `initApp({ activationPolicy })`
82
+ // and setActivationPolicy therefore feed gActivationPolicy when the app is
83
+ // not launched yet, and go through -[NSApplication setActivationPolicy:]
84
+ // once it is (any policy may be set at runtime since 10.9).
85
+ // ---------------------------------------------------------------------------
86
+
87
+ static NSApplicationActivationPolicy gActivationPolicy =
88
+ NSApplicationActivationPolicyRegular;
89
+ static bool gAppLaunched = false;
90
+ static NSMenu* gDockMenu = nil; // applicationDockMenu: answer; setDockMenu
91
+
92
+ static void BInstallAppDelegate(); // the app lifecycle section, below
93
+ static void BInstallAccessibilityObserver(); // the accessibility section, below
94
+
95
+ void BEnsureApp() {
96
+ if (gAppLaunched) return;
73
97
  @autoreleasepool {
74
98
  [NSApplication sharedApplication];
75
- [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
99
+ [NSApp setActivationPolicy:gActivationPolicy];
100
+ // A react-x11 window has no tab semantics. Left on, AppKit persists
101
+ // "show tab bar" per process name (under bun the key lives in the `bun`
102
+ // defaults domain) and grows a 28pt bar into the titlebar of every
103
+ // window we create (windowkit/appkit#12).
104
+ NSWindow.allowsAutomaticWindowTabbing = NO;
105
+ // Before finishLaunching, never after: the Apple Event this process was
106
+ // launched for (a URL, a document) is dispatched inside that call, and
107
+ // a delegate installed a line later would never hear of it.
108
+ BInstallAppDelegate();
109
+ BInstallAccessibilityObserver();
76
110
  [NSApp finishLaunching];
77
111
  }
78
- inited = true;
112
+ gAppLaunched = true;
79
113
  }
80
114
 
81
115
  // The top of the primary screen, for global coordinate flips. The primary
@@ -86,6 +120,18 @@ static CGFloat PrimaryScreenTop() {
86
120
  return primary ? NSMaxY(primary.frame) : 0;
87
121
  }
88
122
 
123
+ // The content view's rect in screen coordinates, Cocoa (bottom-left) space.
124
+ // The renderer draws into the content view, so this — not the rect the style
125
+ // mask implies — is what getWindowFrame and the geometry events report. The
126
+ // two differ while the titlebar holds an accessory (a tab bar, most often):
127
+ // the accessory takes its height out of the content view without moving the
128
+ // window frame, and no windowDidResize fires for it (windowkit/appkit#12).
129
+ static NSRect ContentViewScreenRect(NSWindow* win) {
130
+ NSView* cv = win.contentView;
131
+ if (!cv) return [win contentRectForFrameRect:win.frame];
132
+ return [win convertRectToScreen:[cv convertRect:cv.bounds toView:nil]];
133
+ }
134
+
89
135
  // ---------------------------------------------------------------------------
90
136
  // the event callback (backend flavour — richer payloads than addon.mm's)
91
137
  // ---------------------------------------------------------------------------
@@ -101,6 +147,209 @@ static void EmitToJS(Napi::Env env, Napi::Object ev) {
101
147
  gBackendCb.Call({ev});
102
148
  }
103
149
 
150
+ // The same callback, for the faces in other files: notifications.mm hands
151
+ // the UNUserNotificationCenter delegate's responses through here.
152
+ bool CALHasBackendCb() { return HasBackendCb(); }
153
+ void CALEmitBackendEvent(Napi::Env env, Napi::Object ev) { EmitToJS(env, ev); }
154
+
155
+ // ---------------------------------------------------------------------------
156
+ // app lifecycle: what the OS asks the application as a whole
157
+ // ---------------------------------------------------------------------------
158
+ //
159
+ // A URL for a scheme the bundle registers (kInternetEventClass/kAEGetURL),
160
+ // a document handed over by the Finder (kCoreEventClass/kAEOpenDocuments),
161
+ // a second launch of a running app (kAEReopenApplication) and Quit from the
162
+ // Dock, the app menu or a logout (kAEQuitApplication) all reach the process
163
+ // as Apple Events, which AppKit turns into NSApplicationDelegate calls. The
164
+ // delegate forwards them as backend events and decides nothing itself, the
165
+ // same rule windowShouldClose follows:
166
+ //
167
+ // app-open-urls { urls: [string] } scheme URLs as sent, documents
168
+ // as file:// URLs
169
+ // app-reopen { hasVisibleWindows } the Dock tile clicked again
170
+ // app-quit-request {} terminate: was asked for; the
171
+ // renderer exits or vetoes
172
+ //
173
+ // Two timing facts shape the code. Launch Services delivers the launching
174
+ // event inside finishLaunching, so the delegate goes in before that call
175
+ // (BEnsureApp). And initApp() runs before setBackendEventCallback(), so
176
+ // whatever arrives with nobody listening is held here and replayed on the
177
+ // first pump that has a listener, in arrival order, ahead of that pump's
178
+ // NSEvents. Registering the scheme itself (CFBundleURLTypes) is an
179
+ // Info.plist matter for the app bundle, not runtime code.
180
+
181
+ enum class AppEventKind { OpenURLs, Reopen, QuitRequest };
182
+
183
+ struct PendingAppEvent {
184
+ explicit PendingAppEvent(AppEventKind k) : kind(k) {}
185
+ AppEventKind kind;
186
+ std::vector<std::string> urls; // OpenURLs
187
+ bool hasVisibleWindows = false; // Reopen
188
+ };
189
+ static std::vector<PendingAppEvent> gPendingAppEvents;
190
+
191
+ static Napi::Object AppEventObject(Napi::Env env, const PendingAppEvent& p) {
192
+ Napi::Object ev = Napi::Object::New(env);
193
+ switch (p.kind) {
194
+ case AppEventKind::OpenURLs: {
195
+ ev.Set("type", "app-open-urls");
196
+ Napi::Array urls = Napi::Array::New(env, p.urls.size());
197
+ for (size_t i = 0; i < p.urls.size(); i++)
198
+ urls.Set((uint32_t)i, p.urls[i]);
199
+ ev.Set("urls", urls);
200
+ break;
201
+ }
202
+ case AppEventKind::Reopen:
203
+ ev.Set("type", "app-reopen");
204
+ ev.Set("hasVisibleWindows", p.hasVisibleWindows);
205
+ break;
206
+ case AppEventKind::QuitRequest:
207
+ ev.Set("type", "app-quit-request");
208
+ break;
209
+ }
210
+ return ev;
211
+ }
212
+
213
+ // Now if JS is listening, else held for the pump that finds it listening.
214
+ static void EmitAppEvent(PendingAppEvent&& p) {
215
+ if (!HasBackendCb()) {
216
+ gPendingAppEvents.push_back(std::move(p));
217
+ return;
218
+ }
219
+ Napi::Env env = gBackendCb.Env();
220
+ Napi::HandleScope scope(env);
221
+ EmitToJS(env, AppEventObject(env, p));
222
+ }
223
+
224
+ static void FlushPendingAppEvents(Napi::Env env) {
225
+ if (gPendingAppEvents.empty() || !HasBackendCb()) return;
226
+ // moved out first: a handler may pump, and pumping may hold more
227
+ std::vector<PendingAppEvent> held = std::move(gPendingAppEvents);
228
+ gPendingAppEvents.clear();
229
+ for (const PendingAppEvent& p : held) {
230
+ Napi::HandleScope scope(env);
231
+ EmitToJS(env, AppEventObject(env, p));
232
+ }
233
+ }
234
+
235
+ @interface CALAppDelegate : NSObject <NSApplicationDelegate>
236
+ @end
237
+ @implementation CALAppDelegate
238
+ // One entry point for both Apple Events since 10.13 (NSApplication.h: every
239
+ // CFBundleURLTypes URL and every document type without an NSDocument class
240
+ // comes here, and application:openFiles: is then never called). No
241
+ // replyToOpenOrPrint: is owed on this path; that is openFiles:' contract.
242
+ - (void)application:(NSApplication*)app openURLs:(NSArray<NSURL*>*)urls {
243
+ (void)app;
244
+ PendingAppEvent p(AppEventKind::OpenURLs);
245
+ for (NSURL* u in urls) {
246
+ NSString* s = u.absoluteString;
247
+ if (s) p.urls.push_back(s.UTF8String);
248
+ }
249
+ if (!p.urls.empty()) EmitAppEvent(std::move(p));
250
+ }
251
+ - (BOOL)applicationShouldHandleReopen:(NSApplication*)app
252
+ hasVisibleWindows:(BOOL)flag {
253
+ (void)app;
254
+ PendingAppEvent p(AppEventKind::Reopen);
255
+ p.hasVisibleWindows = flag;
256
+ EmitAppEvent(std::move(p));
257
+ return NO; // what a second launch means is the renderer's call
258
+ }
259
+ // With nobody listening the OS default stands and the process ends here,
260
+ // as it always has. With a listener the request is theirs to act on, and
261
+ // quitting is a process.exit on their side. Never NSTerminateLater: AppKit
262
+ // would spin its own run loop waiting for the reply, and this process is
263
+ // pumped from JS, not run by AppKit.
264
+ - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)app {
265
+ (void)app;
266
+ if (!HasBackendCb()) return NSTerminateNow;
267
+ EmitAppEvent(PendingAppEvent(AppEventKind::QuitRequest));
268
+ return NSTerminateCancel;
269
+ }
270
+ // The Dock tile's menu (right-click or press-and-hold), asked for on every
271
+ // open; the spec behind it comes from setDockMenu in the menu section.
272
+ - (NSMenu*)applicationDockMenu:(NSApplication*)app {
273
+ (void)app;
274
+ return gDockMenu;
275
+ }
276
+ @end
277
+
278
+ // NSApp.delegate is unretained; this is the retain.
279
+ static CALAppDelegate* gAppDelegate = nil;
280
+
281
+ static void BInstallAppDelegate() {
282
+ if (!gAppDelegate) gAppDelegate = [CALAppDelegate new];
283
+ NSApp.delegate = gAppDelegate;
284
+ }
285
+
286
+ // ---------------------------------------------------------------------------
287
+ // accessibility display options: reduce motion and its siblings
288
+ // ---------------------------------------------------------------------------
289
+ //
290
+ // System Settings › Accessibility › Display, as NSWorkspace reports it
291
+ // (windowkit/appkit#31). The query answers synchronously; a change arrives as
292
+ // a backend event from NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification,
293
+ // which AppKit posts on the main thread as the pump runs the run loop. Nothing
294
+ // is held for a listener that is not there yet: a setting is a fact rather
295
+ // than a message, so a renderer reads it when it installs its callback and
296
+ // hears of changes from then on. Mechanism only — what a renderer does with
297
+ // reduceMotion (react-x11: loops never start, transitions still run) is its
298
+ // own call.
299
+
300
+ static Napi::Object AccessibilityDisplayOptions(Napi::Env env) {
301
+ NSWorkspace* ws = NSWorkspace.sharedWorkspace;
302
+ Napi::Object o = Napi::Object::New(env);
303
+ o.Set("reduceMotion", (bool)ws.accessibilityDisplayShouldReduceMotion);
304
+ o.Set("reduceTransparency", (bool)ws.accessibilityDisplayShouldReduceTransparency);
305
+ o.Set("increaseContrast", (bool)ws.accessibilityDisplayShouldIncreaseContrast);
306
+ o.Set("differentiateWithoutColor",
307
+ (bool)ws.accessibilityDisplayShouldDifferentiateWithoutColor);
308
+ o.Set("invertColors", (bool)ws.accessibilityDisplayShouldInvertColors);
309
+ return o;
310
+ }
311
+
312
+ // accessibilityDisplayOptions() -> { reduceMotion, reduceTransparency,
313
+ // increaseContrast, differentiateWithoutColor, invertColors }
314
+ static Napi::Value AccessibilityDisplayOptionsFn(const Napi::CallbackInfo& info) {
315
+ return AccessibilityDisplayOptions(info.Env());
316
+ }
317
+
318
+ // The observer is installed once, with the app (BEnsureApp), so it is in
319
+ // place before any callback could be. Its block runs on the main queue,
320
+ // which the main run loop drains inside a pump — where a call into JS is
321
+ // legal, the same place a window delegate's methods fire.
322
+ static id gAccessibilityObserver = nil;
323
+
324
+ static void BInstallAccessibilityObserver() {
325
+ if (gAccessibilityObserver) return;
326
+ gAccessibilityObserver = [NSWorkspace.sharedWorkspace.notificationCenter
327
+ addObserverForName:NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification
328
+ object:nil
329
+ queue:NSOperationQueue.mainQueue
330
+ usingBlock:^(NSNotification* n) {
331
+ (void)n;
332
+ if (!HasBackendCb()) return;
333
+ Napi::Env env = gBackendCb.Env();
334
+ Napi::HandleScope scope(env);
335
+ Napi::Object ev = AccessibilityDisplayOptions(env);
336
+ ev.Set("type", "accessibility-display-changed");
337
+ EmitToJS(env, ev);
338
+ }];
339
+ }
340
+
341
+ // postAccessibilityDisplayChange() — the notification the system would post,
342
+ // posted from here through the same centre, so the observer path can be
343
+ // exercised without touching the user's settings. Test-only, like
344
+ // postAppleEvent; the values it carries are whatever the settings are.
345
+ static Napi::Value PostAccessibilityDisplayChange(const Napi::CallbackInfo& info) {
346
+ BEnsureApp();
347
+ [NSWorkspace.sharedWorkspace.notificationCenter
348
+ postNotificationName:NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification
349
+ object:NSWorkspace.sharedWorkspace];
350
+ return info.Env().Undefined();
351
+ }
352
+
104
353
  // Window bookkeeping: delegate + view need to reach the JS callback with the
105
354
  // window's number attached, and windowShouldClose needs to answer NO while
106
355
  // telling JS. One delegate class serves every window.
@@ -128,7 +377,7 @@ static void EmitWindowGeometry(Napi::Env env, NSWindow* win, const char* type,
128
377
  if (!HasBackendCb()) return;
129
378
  Napi::HandleScope scope(env);
130
379
  Napi::Object ev = WindowEvent(env, win, type);
131
- NSRect content = [win contentRectForFrameRect:win.frame];
380
+ NSRect content = ContentViewScreenRect(win);
132
381
  ev.Set("width", content.size.width);
133
382
  ev.Set("height", content.size.height);
134
383
  ev.Set("x", content.origin.x);
@@ -196,6 +445,16 @@ static char kDelegateKey;
196
445
  @interface CALBackendView : NSView {
197
446
  @public
198
447
  NSTrackingArea* tracking_;
448
+ // drag and drop (its own section below): the env the callbacks run in,
449
+ // the destination's standing answer, the source's masks and provider,
450
+ // and the press a session is begun from
451
+ napi_env env_;
452
+ bool dropAccept_;
453
+ NSString* dropOp_; // nil: the conventional operation for the source's mask
454
+ NSDragOperation sourceMask_, sourceMaskOutside_;
455
+ BOOL ignoreModifiers_;
456
+ NSEvent* lastPress_;
457
+ id dragProvider_;
199
458
  }
200
459
  @end
201
460
  @implementation CALBackendView
@@ -285,6 +544,9 @@ static Napi::Value CreateWindow2(const Napi::CallbackInfo& info) {
285
544
  }
286
545
  win.releasedWhenClosed = NO;
287
546
  win.acceptsMouseMovedEvents = YES;
547
+ // Never a tab bar, whatever an earlier process left in the defaults
548
+ // domain (see BEnsureApp).
549
+ win.tabbingMode = NSWindowTabbingModeDisallowed;
288
550
  if (o.Has("title") && o.Get("title").IsString())
289
551
  win.title = BToNSString(o.Get("title"));
290
552
  if (o.Has("level") && o.Get("level").IsString()) {
@@ -299,6 +561,7 @@ static Napi::Value CreateWindow2(const Napi::CallbackInfo& info) {
299
561
  }
300
562
 
301
563
  CALBackendView* view = [[CALBackendView alloc] initWithFrame:rect];
564
+ view->env_ = (napi_env)env;
302
565
  CALayer* root = [CALayer layer];
303
566
  root.geometryFlipped = YES;
304
567
  [view setLayer:root];
@@ -363,7 +626,7 @@ static Napi::Value SetWindowTitle(const Napi::CallbackInfo& info) {
363
626
  // x/y are the content's top-left in global top-left coordinates, points.
364
627
  static Napi::Value SetWindowFrame(const Napi::CallbackInfo& info) {
365
628
  NSWindow* win = BDeref<NSWindow*>(info[0]);
366
- NSRect content = [win contentRectForFrameRect:win.frame];
629
+ NSRect content = ContentViewScreenRect(win);
367
630
  double topY = PrimaryScreenTop() - (content.origin.y + content.size.height);
368
631
  double x = info[1].IsNumber() ? info[1].As<Napi::Number>().DoubleValue()
369
632
  : content.origin.x;
@@ -384,7 +647,7 @@ static Napi::Value SetWindowFrame(const Napi::CallbackInfo& info) {
384
647
  static Napi::Value GetWindowFrame(const Napi::CallbackInfo& info) {
385
648
  Napi::Env env = info.Env();
386
649
  NSWindow* win = BDeref<NSWindow*>(info[0]);
387
- NSRect content = [win contentRectForFrameRect:win.frame];
650
+ NSRect content = ContentViewScreenRect(win);
388
651
  Napi::Object r = Napi::Object::New(env);
389
652
  r.Set("x", content.origin.x);
390
653
  r.Set("y", PrimaryScreenTop() - (content.origin.y + content.size.height));
@@ -410,8 +673,13 @@ static Napi::Value SetWindowMinMax(const Napi::CallbackInfo& info) {
410
673
  return info.Env().Undefined();
411
674
  }
412
675
 
676
+ static void CancelPanelSheetsOn(NSWindow* win);
677
+
413
678
  static Napi::Value DestroyWindow2(const Napi::CallbackInfo& info) {
414
679
  NSWindow* win = BDeref<NSWindow*>(info[0]);
680
+ // A sheet whose owner goes away ends without telling its completion
681
+ // handler; answer it as a cancel first so no callback is left waiting.
682
+ CancelPanelSheetsOn(win);
415
683
  win.delegate = nil;
416
684
  objc_setAssociatedObject(win, &kDelegateKey, nil,
417
685
  OBJC_ASSOCIATION_RETAIN_NONATOMIC);
@@ -420,16 +688,107 @@ static Napi::Value DestroyWindow2(const Napi::CallbackInfo& info) {
420
688
  return info.Env().Undefined();
421
689
  }
422
690
 
691
+ // initApp lives in the app presence section: it takes { activationPolicy }.
692
+
423
693
  static Napi::Value ActivateApp(const Napi::CallbackInfo& info) {
424
694
  BEnsureApp();
425
695
  [NSApp activateIgnoringOtherApps:YES];
426
696
  return info.Env().Undefined();
427
697
  }
428
698
 
699
+ // postAppleEvent('open-url', 'scheme://…')
700
+ // postAppleEvent('open-documents', ['/path', …])
701
+ // postAppleEvent('reopen')
702
+ // postAppleEvent('quit')
703
+ // The Apple Event Launch Services would send, built here and dispatched
704
+ // through NSAppleEventManager as if it had just been dequeued, so AppKit's
705
+ // own handler and then the app delegate run on it exactly as for a real
706
+ // one. For tests, like postMouseEvent and postKeyEvent. (An AESendMessage
707
+ // to the sending process is short-circuited to this same dispatch by the
708
+ // Apple Event Manager, minus a spurious errAETimeout on kAEOpenDocuments,
709
+ // whose AppKit handler suspends the event to reply later.) No Automation
710
+ // permission is involved: nothing leaves the process.
711
+ static Napi::Value PostAppleEvent(const Napi::CallbackInfo& info) {
712
+ Napi::Env env = info.Env();
713
+ BEnsureApp();
714
+ if (!info[0].IsString()) {
715
+ Napi::TypeError::New(env, "postAppleEvent: kind must be a string")
716
+ .ThrowAsJavaScriptException();
717
+ return env.Undefined();
718
+ }
719
+ std::string kind = info[0].As<Napi::String>().Utf8Value();
720
+ @autoreleasepool {
721
+ NSAppleEventDescriptor* target =
722
+ [NSAppleEventDescriptor currentProcessDescriptor];
723
+ AEEventClass cls;
724
+ AEEventID id;
725
+ NSAppleEventDescriptor* direct = nil;
726
+ if (kind == "open-url") {
727
+ if (!info[1].IsString()) {
728
+ Napi::TypeError::New(env, "postAppleEvent('open-url', url): url must be a string")
729
+ .ThrowAsJavaScriptException();
730
+ return env.Undefined();
731
+ }
732
+ cls = kInternetEventClass;
733
+ id = kAEGetURL;
734
+ direct = [NSAppleEventDescriptor descriptorWithString:BToNSString(info[1])];
735
+ } else if (kind == "open-documents") {
736
+ if (!info[1].IsArray()) {
737
+ Napi::TypeError::New(env, "postAppleEvent('open-documents', paths): paths must be an array")
738
+ .ThrowAsJavaScriptException();
739
+ return env.Undefined();
740
+ }
741
+ cls = kCoreEventClass;
742
+ id = kAEOpenDocuments;
743
+ direct = [NSAppleEventDescriptor listDescriptor];
744
+ Napi::Array paths = info[1].As<Napi::Array>();
745
+ for (uint32_t i = 0; i < paths.Length(); i++) {
746
+ NSURL* url = [NSURL fileURLWithPath:BToNSString(paths.Get(i))];
747
+ [direct insertDescriptor:[NSAppleEventDescriptor descriptorWithFileURL:url]
748
+ atIndex:0]; // 0 appends
749
+ }
750
+ } else if (kind == "reopen") {
751
+ cls = kCoreEventClass;
752
+ id = kAEReopenApplication;
753
+ } else if (kind == "quit") {
754
+ cls = kCoreEventClass;
755
+ id = kAEQuitApplication;
756
+ } else {
757
+ Napi::TypeError::New(env, "postAppleEvent: unknown kind '" + kind + "'")
758
+ .ThrowAsJavaScriptException();
759
+ return env.Undefined();
760
+ }
761
+ NSAppleEventDescriptor* ev =
762
+ [NSAppleEventDescriptor appleEventWithEventClass:cls
763
+ eventID:id
764
+ targetDescriptor:target
765
+ returnID:kAutoGenerateReturnID
766
+ transactionID:kAnyTransactionID];
767
+ if (direct) [ev setParamDescriptor:direct forKeyword:keyDirectObject];
768
+ AppleEvent reply = {typeNull, NULL};
769
+ // the refCon reaches raw C handlers only; AppKit's are Objective-C
770
+ // methods looked up by class and id, but the parameter is non-null
771
+ static char refCon;
772
+ OSErr err = [[NSAppleEventManager sharedAppleEventManager]
773
+ dispatchRawAppleEvent:ev.aeDesc
774
+ withRawReply:&reply
775
+ handlerRefCon:(SRefCon)&refCon];
776
+ AEDisposeDesc(&reply);
777
+ if (err != noErr) {
778
+ Napi::Error::New(env, "postAppleEvent: dispatch failed (" +
779
+ std::to_string((int)err) + ")")
780
+ .ThrowAsJavaScriptException();
781
+ }
782
+ }
783
+ return env.Undefined();
784
+ }
785
+
429
786
  // ---------------------------------------------------------------------------
430
787
  // pump2: the enriched event stream
431
788
  // ---------------------------------------------------------------------------
432
789
 
790
+ static bool StatusWindowEvent(NSEvent* e);
791
+
433
792
  static void DispatchEvent2(Napi::Env env, NSEvent* e) {
434
793
  if (!HasBackendCb()) return;
435
794
  const char* type = nullptr;
@@ -453,7 +812,15 @@ static void DispatchEvent2(Napi::Env env, NSEvent* e) {
453
812
  case NSEventTypeFlagsChanged: type = "flagschanged"; key = true; break;
454
813
  default: return;
455
814
  }
456
- if ((mouse || crossing) && !e.window) return;
815
+ if ((mouse || crossing) && (!e.window || StatusWindowEvent(e))) return;
816
+ // The press a drag session is begun from (beginDrag): the latest
817
+ // left-button down or drag in the window, recorded before JS sees it so a
818
+ // beginDrag from inside this very callback has it.
819
+ if ((e.type == NSEventTypeLeftMouseDown ||
820
+ e.type == NSEventTypeLeftMouseDragged) &&
821
+ [e.window.contentView isKindOfClass:[CALBackendView class]]) {
822
+ ((CALBackendView*)e.window.contentView)->lastPress_ = e;
823
+ }
457
824
 
458
825
  Napi::HandleScope scope(env);
459
826
  Napi::Object ev = Napi::Object::New(env);
@@ -525,15 +892,29 @@ static void DispatchEvent2(Napi::Env env, NSEvent* e) {
525
892
  static Napi::Value SetBackendEventCallback(const Napi::CallbackInfo& info) {
526
893
  if (info[0].IsFunction()) {
527
894
  gBackendCb = Napi::Persistent(info[0].As<Napi::Function>());
895
+ // A static reference is destructed after the Node environment is gone;
896
+ // deleting it then is a segfault at exit on Node 18. Replacing or
897
+ // clearing it (Reset, above and in the move-assign) still frees the old
898
+ // reference while the environment is alive.
899
+ gBackendCb.SuppressDestruct();
528
900
  } else {
529
901
  gBackendCb.Reset();
530
902
  }
531
903
  return info.Env().Undefined();
532
904
  }
533
905
 
906
+ // notifications.mm: responses that arrived before a listener was installed
907
+ void CALNotificationsReplayHeld(Napi::Env env);
908
+
534
909
  static Napi::Value Pump2(const Napi::CallbackInfo& info) {
535
910
  Napi::Env env = info.Env();
536
911
  BEnsureApp();
912
+ // what came before the callback did, ahead of this tick's input so the
913
+ // renderer hears of it first: the launch's URL (or a Dock click), then a
914
+ // notification acted on before the callback existed (one that launched
915
+ // the app, say)
916
+ FlushPendingAppEvents(env);
917
+ CALNotificationsReplayHeld(env);
537
918
  @autoreleasepool {
538
919
  while (true) {
539
920
  NSEvent* e = [NSApp nextEventMatchingMask:NSEventMaskAny
@@ -861,6 +1242,7 @@ static NSString* BStrOr(Napi::Object o, const char* k, NSString* d);
861
1242
  @interface CALMenuTarget : NSObject {
862
1243
  @public
863
1244
  napi_env env_;
1245
+ const char* source_; // "main" | "dock": which menu tree the item is in
864
1246
  }
865
1247
  - (void)activate:(NSMenuItem*)sender;
866
1248
  @end
@@ -871,15 +1253,31 @@ static NSString* BStrOr(Napi::Object o, const char* k, NSString* d);
871
1253
  Napi::Object ev = Napi::Object::New(env);
872
1254
  ev.Set("type", "menu-activate");
873
1255
  ev.Set("id", (double)sender.tag);
1256
+ // ids are the caller's; the two trees may allocate them independently
1257
+ ev.Set("menu", source_);
874
1258
  EmitToJS(env, ev);
875
1259
  }
876
1260
  @end
877
1261
 
878
- static CALMenuTarget* gMenuTarget = nil;
1262
+ // One target per menu tree, so an activation says which tree it came from.
1263
+ static CALMenuTarget* gMenuTarget = nil; // NSApp.mainMenu
1264
+ static CALMenuTarget* gDockMenuTarget = nil; // the Dock menu
1265
+ static CALMenuTarget* gStatusMenuTarget = nil; // status-item (tray) menus
879
1266
 
880
- static NSMenu* BuildMenuFrom(Napi::Env env, Napi::Array items);
1267
+ static CALMenuTarget* MenuTargetFor(Napi::Env env,
1268
+ CALMenuTarget* __strong* slot,
1269
+ const char* source) {
1270
+ if (!*slot) *slot = [CALMenuTarget new];
1271
+ (*slot)->env_ = env;
1272
+ (*slot)->source_ = source;
1273
+ return *slot;
1274
+ }
881
1275
 
882
- static NSMenuItem* BuildMenuItem(Napi::Env env, Napi::Object o) {
1276
+ static NSMenu* BuildMenuFrom(Napi::Env env, Napi::Array items,
1277
+ CALMenuTarget* target);
1278
+
1279
+ static NSMenuItem* BuildMenuItem(Napi::Env env, Napi::Object o,
1280
+ CALMenuTarget* target) {
883
1281
  if (BBoolOr(o, "separator", false)) return [NSMenuItem separatorItem];
884
1282
  NSMenuItem* it = [[NSMenuItem alloc] initWithTitle:BStrOr(o, "title", @"")
885
1283
  action:nil
@@ -921,20 +1319,21 @@ static NSMenuItem* BuildMenuItem(Napi::Env env, Napi::Object o) {
921
1319
  if (o.Has("items")) {
922
1320
  Napi::Value v = o.Get("items");
923
1321
  if (v.IsArray() && v.As<Napi::Array>().Length() > 0) {
924
- NSMenu* sub = BuildMenuFrom(env, v.As<Napi::Array>());
1322
+ NSMenu* sub = BuildMenuFrom(env, v.As<Napi::Array>(), target);
925
1323
  sub.title = it.title;
926
1324
  it.submenu = sub;
927
1325
  hasChildren = true;
928
1326
  }
929
1327
  }
930
1328
  if (!hasChildren) {
931
- it.target = gMenuTarget;
1329
+ it.target = target;
932
1330
  it.action = @selector(activate:);
933
1331
  }
934
1332
  return it;
935
1333
  }
936
1334
 
937
- static NSMenu* BuildMenuFrom(Napi::Env env, Napi::Array items) {
1335
+ static NSMenu* BuildMenuFrom(Napi::Env env, Napi::Array items,
1336
+ CALMenuTarget* target) {
938
1337
  NSMenu* m = [[NSMenu alloc] initWithTitle:@""];
939
1338
  // we own enabled/hidden; AppKit's validation would grey everything whose
940
1339
  // target it cannot interrogate
@@ -942,7 +1341,7 @@ static NSMenu* BuildMenuFrom(Napi::Env env, Napi::Array items) {
942
1341
  for (uint32_t i = 0; i < items.Length(); i++) {
943
1342
  Napi::Value v = items.Get(i);
944
1343
  if (!v.IsObject()) continue;
945
- [m addItem:BuildMenuItem(env, v.As<Napi::Object>())];
1344
+ [m addItem:BuildMenuItem(env, v.As<Napi::Object>(), target)];
946
1345
  }
947
1346
  return m;
948
1347
  }
@@ -952,8 +1351,7 @@ static NSMenu* BuildMenuFrom(Napi::Env env, Napi::Array items) {
952
1351
  static Napi::Value SetMainMenuFn(const Napi::CallbackInfo& info) {
953
1352
  Napi::Env env = info.Env();
954
1353
  BEnsureApp();
955
- if (!gMenuTarget) gMenuTarget = [CALMenuTarget new];
956
- gMenuTarget->env_ = env;
1354
+ CALMenuTarget* target = MenuTargetFor(env, &gMenuTarget, "main");
957
1355
  Napi::Array spec = info[0].As<Napi::Array>();
958
1356
  NSMenu* main = [[NSMenu alloc] initWithTitle:@"MainMenu"];
959
1357
  main.autoenablesItems = NO;
@@ -967,7 +1365,7 @@ static Napi::Value SetMainMenuFn(const Napi::CallbackInfo& info) {
967
1365
  keyEquivalent:@""];
968
1366
  Napi::Value items = m.Get("items");
969
1367
  NSMenu* sub = items.IsArray()
970
- ? BuildMenuFrom(env, items.As<Napi::Array>())
1368
+ ? BuildMenuFrom(env, items.As<Napi::Array>(), target)
971
1369
  : [[NSMenu alloc] initWithTitle:title];
972
1370
  sub.autoenablesItems = NO;
973
1371
  sub.title = title;
@@ -1008,27 +1406,932 @@ static Napi::Value MainMenuInfoFn(const Napi::CallbackInfo& info) {
1008
1406
  return MenuInfo(env, main);
1009
1407
  }
1010
1408
 
1011
- // activateMenuItem([i, j, ...]) — walk the installed bar by index and fire
1012
- // the leaf's action, the way tracking would. For tests.
1013
- static Napi::Value ActivateMenuItemFn(const Napi::CallbackInfo& info) {
1014
- Napi::Env env = info.Env();
1015
- Napi::Array path = info[0].As<Napi::Array>();
1016
- NSMenu* menu = [NSApp mainMenu];
1017
- if (!menu) return Napi::Boolean::New(env, false);
1409
+ // Walk a menu tree by index and fire the leaf's action the way tracking
1410
+ // would (shared by the main menu and status item test hooks).
1411
+ static bool ActivateInMenu(NSMenu* menu, Napi::Array path) {
1412
+ if (!menu || path.Length() == 0) return false;
1018
1413
  for (uint32_t d = 0; d + 1 < path.Length(); d++) {
1019
1414
  NSInteger i = (NSInteger)path.Get(d).As<Napi::Number>().Int64Value();
1020
- if (i < 0 || i >= menu.numberOfItems) return Napi::Boolean::New(env, false);
1415
+ if (i < 0 || i >= menu.numberOfItems) return false;
1021
1416
  menu = [menu itemAtIndex:i].submenu;
1022
- if (!menu) return Napi::Boolean::New(env, false);
1417
+ if (!menu) return false;
1023
1418
  }
1024
1419
  NSInteger leaf = (NSInteger)
1025
1420
  path.Get(path.Length() - 1).As<Napi::Number>().Int64Value();
1026
- if (leaf < 0 || leaf >= menu.numberOfItems)
1027
- return Napi::Boolean::New(env, false);
1421
+ if (leaf < 0 || leaf >= menu.numberOfItems) return false;
1028
1422
  [menu performActionForItemAtIndex:leaf];
1423
+ return true;
1424
+ }
1425
+
1426
+ // activateMenuItem([i, j, ...]) — walk the installed bar by index and fire
1427
+ // the leaf's action, the way tracking would. For tests.
1428
+ static Napi::Value ActivateMenuItemFn(const Napi::CallbackInfo& info) {
1429
+ Napi::Env env = info.Env();
1430
+ if (!info[0].IsArray()) return Napi::Boolean::New(env, false);
1431
+ return Napi::Boolean::New(
1432
+ env, ActivateInMenu([NSApp mainMenu], info[0].As<Napi::Array>()));
1433
+ }
1434
+
1435
+ // ---------------------------------------------------------------------------
1436
+ // status items — NSStatusItem, the menu-bar extra (the "tray"). The cocoa
1437
+ // counterpart of the freedesktop StatusNotifierItem: an icon or a title in
1438
+ // the system status bar, a tooltip, and either a menu or clicks. The menu
1439
+ // is the same item spec setMainMenu takes, so the tray, the menu bar and a
1440
+ // Linux panel share one authoring model; activations arrive as the same
1441
+ // `menu-activate` events. Without a menu a click is the renderer's to
1442
+ // answer: it arrives as `status-item-click` with the button's screen rect,
1443
+ // which is the anchor a custom popup wants.
1444
+ //
1445
+ // Lifetime is explicit. The handle retains the NSStatusItem, and the item's
1446
+ // target keeps the handle alive until removeStatusItem, so an item stays in
1447
+ // the bar exactly as long as JS says — AppKit would otherwise drop it the
1448
+ // moment the last reference went.
1449
+ // ---------------------------------------------------------------------------
1450
+
1451
+ @interface CALStatusItemTarget : NSObject {
1452
+ @public
1453
+ napi_env env_;
1454
+ // the JS handle: events carry this very object, so `ev.statusItem ===
1455
+ // item` holds and a renderer can key a Map on it
1456
+ Napi::Reference<Napi::Value> handle_;
1457
+ NSStatusItem* __weak item_;
1458
+ }
1459
+ - (void)click:(id)sender;
1460
+ @end
1461
+
1462
+ static char kStatusTargetKey;
1463
+ static NSMapTable<NSNumber*, NSStatusItem*>* gStatusWindows = nil; // number -> item (weak)
1464
+
1465
+ static CALStatusItemTarget* StatusTargetOf(NSStatusItem* item) {
1466
+ return objc_getAssociatedObject(item, &kStatusTargetKey);
1467
+ }
1468
+
1469
+ // The status bar hosts each item in a window of its own. Its raw mouse
1470
+ // events are noise to a renderer (a foreign windowNumber with no tree
1471
+ // behind it); remember the windows so the pump can skip them — and so it
1472
+ // can answer the one click AppKit's button ignores (below).
1473
+ static void RememberStatusWindow(NSWindow* win, NSStatusItem* item) {
1474
+ if (!win) return;
1475
+ if (!gStatusWindows) gStatusWindows = [NSMapTable strongToWeakObjectsMapTable];
1476
+ [gStatusWindows setObject:item forKey:@(win.windowNumber)];
1477
+ }
1478
+
1479
+ // The button's rect in global top-left coordinates, points.
1480
+ static void SetStatusButtonFrame(Napi::Object ev, NSStatusBarButton* btn) {
1481
+ if (!btn.window) return;
1482
+ NSRect r = [btn.window convertRectToScreen:[btn convertRect:btn.bounds
1483
+ toView:nil]];
1484
+ ev.Set("x", r.origin.x);
1485
+ ev.Set("y", PrimaryScreenTop() - (r.origin.y + r.size.height));
1486
+ ev.Set("width", r.size.width);
1487
+ ev.Set("height", r.size.height);
1488
+ }
1489
+
1490
+ static void EmitStatusItemClick(CALStatusItemTarget* t, const char* kind,
1491
+ NSEvent* e) {
1492
+ NSStatusItem* item = t->item_;
1493
+ if (!item || !HasBackendCb()) return;
1494
+ Napi::Env env(t->env_);
1495
+ Napi::HandleScope scope(env);
1496
+ Napi::Object ev = Napi::Object::New(env);
1497
+ ev.Set("type", "status-item-click");
1498
+ ev.Set("statusItem", t->handle_.Value());
1499
+ ev.Set("kind", kind);
1500
+ NSEventModifierFlags f = e ? e.modifierFlags : NSEvent.modifierFlags;
1501
+ ev.Set("shift", (bool)(f & NSEventModifierFlagShift));
1502
+ ev.Set("control", (bool)(f & NSEventModifierFlagControl));
1503
+ ev.Set("option", (bool)(f & NSEventModifierFlagOption));
1504
+ ev.Set("command", (bool)(f & NSEventModifierFlagCommand));
1505
+ ev.Set("clickCount", (double)(e ? e.clickCount : 1));
1506
+ SetStatusButtonFrame(ev, item.button);
1507
+ EmitToJS(env, ev);
1508
+ }
1509
+
1510
+ // Called by the pump for every mouse event that has a window: true when
1511
+ // the window is a status item's (the event is then not for JS). NSButton
1512
+ // tracks the left button, NSStatusBarButton adds the right; neither looks
1513
+ // at the middle one, so a middle mouse-up over the button is answered
1514
+ // here — with or without a menu, since AppKit opens the menu for neither.
1515
+ static bool StatusWindowEvent(NSEvent* e) {
1516
+ if (!gStatusWindows) return false;
1517
+ NSStatusItem* item = [gStatusWindows objectForKey:@(e.window.windowNumber)];
1518
+ if (!item) return false;
1519
+ if (e.type == NSEventTypeOtherMouseUp && e.buttonNumber == 2) {
1520
+ NSStatusBarButton* btn = item.button;
1521
+ NSRect r = [btn convertRect:btn.bounds toView:nil];
1522
+ CALStatusItemTarget* t = StatusTargetOf(item);
1523
+ if (t && NSPointInRect(e.locationInWindow, r))
1524
+ EmitStatusItemClick(t, "middle", e);
1525
+ }
1526
+ return true;
1527
+ }
1528
+
1529
+ @implementation CALStatusItemTarget
1530
+ - (void)click:(id)sender {
1531
+ (void)sender;
1532
+ // the button sends on left and right mouse-up; the event says which
1533
+ NSEvent* e = NSApp.currentEvent;
1534
+ bool right = e && (e.type == NSEventTypeRightMouseUp ||
1535
+ e.type == NSEventTypeRightMouseDown);
1536
+ EmitStatusItemClick(self, right ? "right" : "left", e);
1537
+ }
1538
+ @end
1539
+
1540
+ static CGFloat StatusLengthFrom(Napi::Value v, CGFloat d) {
1541
+ if (v.IsNumber()) return v.As<Napi::Number>().DoubleValue();
1542
+ if (v.IsString()) {
1543
+ std::string s = v.As<Napi::String>().Utf8Value();
1544
+ if (s == "square") return NSSquareStatusItemLength;
1545
+ if (s == "variable") return NSVariableStatusItemLength;
1546
+ }
1547
+ return d;
1548
+ }
1549
+
1550
+ // `image`: an SF Symbol name (a template by nature — it follows the bar's
1551
+ // light/dark), a surface handle (its bitmap, at its scale), or encoded
1552
+ // image bytes (PNG and friends). Template by default so a bitmap icon
1553
+ // adapts the way a symbol does; `imageTemplate: false` keeps its colours.
1554
+ // `imageSize: [w, h]` sets the size in points.
1555
+ static NSImage* StatusImageFrom(Napi::Object o) {
1556
+ Napi::Value v = o.Get("image");
1557
+ NSImage* img = nil;
1558
+ if (v.IsString()) {
1559
+ img = [NSImage imageWithSystemSymbolName:BToNSString(v)
1560
+ accessibilityDescription:nil];
1561
+ } else if (v.IsBuffer()) {
1562
+ Napi::Buffer<uint8_t> buf = v.As<Napi::Buffer<uint8_t>>();
1563
+ img = [[NSImage alloc]
1564
+ initWithData:[NSData dataWithBytes:buf.Data() length:buf.Length()]];
1565
+ } else if (v.IsExternal()) {
1566
+ CALSurface* s = SurfaceFrom(v);
1567
+ if (!s) return nil; // released: the error is pending
1568
+ CGImageRef cg = CGBitmapContextCreateImage(s->ctx);
1569
+ img = [[NSImage alloc]
1570
+ initWithCGImage:cg
1571
+ size:NSMakeSize(s->width / s->scale, s->height / s->scale)];
1572
+ CGImageRelease(cg);
1573
+ } else {
1574
+ return nil;
1575
+ }
1576
+ if (!img) return nil;
1577
+ if (o.Has("imageSize") && o.Get("imageSize").IsArray()) {
1578
+ Napi::Array sz = o.Get("imageSize").As<Napi::Array>();
1579
+ if (sz.Length() >= 2)
1580
+ img.size = NSMakeSize(sz.Get(0u).As<Napi::Number>().DoubleValue(),
1581
+ sz.Get(1u).As<Napi::Number>().DoubleValue());
1582
+ }
1583
+ [img setTemplate:BBoolOr(o, "imageTemplate", true)];
1584
+ return img;
1585
+ }
1586
+
1587
+ // Only the keys present are touched: createStatusItem and setStatusItem
1588
+ // share this, so a patch is a create with fewer keys.
1589
+ static void ApplyStatusItemProps(NSStatusItem* item, Napi::Object o) {
1590
+ NSStatusBarButton* btn = item.button;
1591
+ if (o.Has("image")) btn.image = StatusImageFrom(o);
1592
+ if (o.Has("title")) btn.title = BStrOr(o, "title", @"");
1593
+ if (o.Has("tooltip")) {
1594
+ NSString* tip = BStrOr(o, "tooltip", @"");
1595
+ btn.toolTip = tip.length ? tip : nil;
1596
+ }
1597
+ if (o.Has("length")) item.length = StatusLengthFrom(o.Get("length"), item.length);
1598
+ if (o.Has("visible")) item.visible = BBoolOr(o, "visible", true);
1599
+ // image alone, title alone, or the image leading the title
1600
+ bool hasImage = btn.image != nil, hasTitle = btn.title.length > 0;
1601
+ btn.imagePosition = hasImage && hasTitle ? NSImageLeft
1602
+ : hasImage ? NSImageOnly
1603
+ : NSNoImage;
1604
+ }
1605
+
1606
+ // createStatusItem({ image, title, tooltip, length, visible,
1607
+ // imageTemplate, imageSize }) -> handle
1608
+ // length: 'variable' (default) | 'square' | points.
1609
+ static Napi::Value CreateStatusItem(const Napi::CallbackInfo& info) {
1610
+ Napi::Env env = info.Env();
1611
+ BEnsureApp();
1612
+ Napi::Object o = info.Length() > 0 && info[0].IsObject()
1613
+ ? info[0].As<Napi::Object>()
1614
+ : Napi::Object::New(env);
1615
+ NSStatusItem* item;
1616
+ Napi::Value handle;
1617
+ @autoreleasepool {
1618
+ CGFloat len = o.Has("length")
1619
+ ? StatusLengthFrom(o.Get("length"), NSVariableStatusItemLength)
1620
+ : NSVariableStatusItemLength;
1621
+ item = [[NSStatusBar systemStatusBar] statusItemWithLength:len];
1622
+ CALStatusItemTarget* target = [CALStatusItemTarget new];
1623
+ target->env_ = (napi_env)env;
1624
+ target->item_ = item;
1625
+ objc_setAssociatedObject(item, &kStatusTargetKey, target,
1626
+ OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1627
+ NSStatusBarButton* btn = item.button;
1628
+ btn.target = target;
1629
+ btn.action = @selector(click:);
1630
+ [btn sendActionOn:(NSEventMaskLeftMouseUp | NSEventMaskRightMouseUp)];
1631
+ RememberStatusWindow(btn.window, item);
1632
+ // AppKit remembers an item's visibility across launches in user defaults
1633
+ // under an autosave name it generates by creation order ("Item-0"), so
1634
+ // an item hidden when the last process ended would come back hidden.
1635
+ // Visibility is the renderer's to decide: assert it at creation.
1636
+ item.visible = BBoolOr(o, "visible", true);
1637
+ ApplyStatusItemProps(item, o);
1638
+ handle = BWrapRetained(env, item);
1639
+ target->handle_ = Napi::Reference<Napi::Value>::New(handle, 1);
1640
+ }
1641
+ return handle;
1642
+ }
1643
+
1644
+ // The item behind a handle, or nil when it was removed: every verb after
1645
+ // removeStatusItem is a no-op, never a crash.
1646
+ static NSStatusItem* StatusItemFrom(Napi::Value v) {
1647
+ if (!v.IsExternal()) {
1648
+ Napi::TypeError::New(v.Env(), "expected a status item handle")
1649
+ .ThrowAsJavaScriptException();
1650
+ return nil;
1651
+ }
1652
+ NSStatusItem* item = BDeref<NSStatusItem*>(v);
1653
+ return StatusTargetOf(item) ? item : nil;
1654
+ }
1655
+
1656
+ // setStatusItem(item, { image, title, tooltip, length, visible, ... })
1657
+ static Napi::Value SetStatusItem(const Napi::CallbackInfo& info) {
1658
+ Napi::Env env = info.Env();
1659
+ NSStatusItem* item = StatusItemFrom(info[0]);
1660
+ if (!item || !info[1].IsObject()) return env.Undefined();
1661
+ @autoreleasepool {
1662
+ ApplyStatusItemProps(item, info[1].As<Napi::Object>());
1663
+ RememberStatusWindow(item.button.window, item);
1664
+ }
1665
+ return env.Undefined();
1666
+ }
1667
+
1668
+ // setStatusItemMenu(item, items | null) — items in setMainMenu's item
1669
+ // vocabulary (title, id, enabled, checked, key, iconName, items, ...);
1670
+ // activations arrive as `menu-activate` with `menu: 'status'`. With a
1671
+ // menu, a click tracks it and the button's action stays silent; null
1672
+ // returns the item to click events.
1673
+ static Napi::Value SetStatusItemMenu(const Napi::CallbackInfo& info) {
1674
+ Napi::Env env = info.Env();
1675
+ NSStatusItem* item = StatusItemFrom(info[0]);
1676
+ if (!item) return env.Undefined();
1677
+ Napi::Value spec = info.Length() > 1 ? info[1] : env.Null();
1678
+ @autoreleasepool {
1679
+ if (spec.IsArray()) {
1680
+ CALMenuTarget* target =
1681
+ MenuTargetFor(env, &gStatusMenuTarget, "status");
1682
+ item.menu = BuildMenuFrom(env, spec.As<Napi::Array>(), target);
1683
+ } else {
1684
+ item.menu = nil;
1685
+ }
1686
+ }
1687
+ return env.Undefined();
1688
+ }
1689
+
1690
+ static Napi::Value RemoveStatusItem(const Napi::CallbackInfo& info) {
1691
+ Napi::Env env = info.Env();
1692
+ NSStatusItem* item = StatusItemFrom(info[0]);
1693
+ if (!item) return env.Undefined();
1694
+ @autoreleasepool {
1695
+ CALStatusItemTarget* target = StatusTargetOf(item);
1696
+ item.button.target = nil;
1697
+ item.button.action = nil;
1698
+ item.menu = nil;
1699
+ [[NSStatusBar systemStatusBar] removeStatusItem:item];
1700
+ objc_setAssociatedObject(item, &kStatusTargetKey, nil,
1701
+ OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1702
+ target->item_ = nil;
1703
+ target->handle_.Reset(); // the handle may now be collected
1704
+ }
1705
+ return env.Undefined();
1706
+ }
1707
+
1708
+ // statusItemInfo(item) — the item as data, for tests: what the bar shows,
1709
+ // its menu in mainMenuInfo's shape, and the button's screen rect. Null
1710
+ // once removed.
1711
+ static Napi::Value StatusItemInfo(const Napi::CallbackInfo& info) {
1712
+ Napi::Env env = info.Env();
1713
+ NSStatusItem* item = StatusItemFrom(info[0]);
1714
+ if (!item) return env.Null();
1715
+ NSStatusBarButton* btn = item.button;
1716
+ Napi::Object r = Napi::Object::New(env);
1717
+ r.Set("title", btn.title.UTF8String);
1718
+ r.Set("tooltip", btn.toolTip ? btn.toolTip.UTF8String : "");
1719
+ r.Set("visible", (bool)item.visible);
1720
+ r.Set("hasImage", btn.image != nil);
1721
+ r.Set("imageTemplate", btn.image != nil && [btn.image isTemplate]);
1722
+ if (btn.image) {
1723
+ r.Set("imageWidth", btn.image.size.width);
1724
+ r.Set("imageHeight", btn.image.size.height);
1725
+ }
1726
+ if (item.length == NSVariableStatusItemLength) r.Set("length", "variable");
1727
+ else if (item.length == NSSquareStatusItemLength) r.Set("length", "square");
1728
+ else r.Set("length", item.length);
1729
+ r.Set("menu", item.menu ? MenuInfo(env, item.menu) : env.Null());
1730
+ if (btn.window) r.Set("windowNumber", (double)btn.window.windowNumber);
1731
+ SetStatusButtonFrame(r, btn);
1732
+ return r;
1733
+ }
1734
+
1735
+ // activateStatusItemMenuItem(item, [i, j, ...]) — for tests; a real click
1736
+ // would track the menu in a modal loop nobody can dismiss from a script.
1737
+ static Napi::Value ActivateStatusItemMenuItem(const Napi::CallbackInfo& info) {
1738
+ Napi::Env env = info.Env();
1739
+ NSStatusItem* item = StatusItemFrom(info[0]);
1740
+ if (!item || !info[1].IsArray()) return Napi::Boolean::New(env, false);
1741
+ return Napi::Boolean::New(env,
1742
+ ActivateInMenu(item.menu, info[1].As<Napi::Array>()));
1743
+ }
1744
+
1745
+ // Two things have to happen before a mouse event posted into an item's
1746
+ // window is delivered rather than dropped: AppKit's first pass through
1747
+ // nextEventMatchingMask: (whatever it sets up there, an event queued
1748
+ // before it is lost), and the status bar server's reply that places the
1749
+ // window and orders it in — on a hosted CI VM the latter takes longer
1750
+ // than one pass. The test hooks take at least one pass here and then wait
1751
+ // for the window to be on glass, for at most `timeout` seconds; nothing
1752
+ // is dequeued or dispatched.
1753
+ static bool WaitForStatusWindow(NSWindow* win, NSTimeInterval timeout) {
1754
+ NSDate* deadline = [NSDate dateWithTimeIntervalSinceNow:timeout];
1755
+ NSDate* until = [NSDate distantPast];
1756
+ while (true) {
1757
+ [NSApp nextEventMatchingMask:0
1758
+ untilDate:until
1759
+ inMode:NSDefaultRunLoopMode
1760
+ dequeue:NO];
1761
+ if (win.isVisible && WindowOnGlass(win)) return true;
1762
+ if (deadline.timeIntervalSinceNow <= 0) return false;
1763
+ until = [NSDate dateWithTimeIntervalSinceNow:0.01];
1764
+ }
1765
+ }
1766
+
1767
+ // clickStatusItem(item, 'left' | 'right' | 'middle') — for tests: a real
1768
+ // press-and-release posted into the item's own window, so the button's
1769
+ // tracking and sendActionOn: path (or the pump's middle-click path) is
1770
+ // what fires. Declines a left or right click while a menu is set: that
1771
+ // click would open the menu and never return. Pump afterwards; the event
1772
+ // arrives through the backend callback like a user's click.
1773
+ static Napi::Value ClickStatusItem(const Napi::CallbackInfo& info) {
1774
+ Napi::Env env = info.Env();
1775
+ NSStatusItem* item = StatusItemFrom(info[0]);
1776
+ if (!item) return Napi::Boolean::New(env, false);
1777
+ std::string kind = info.Length() > 1 && info[1].IsString()
1778
+ ? info[1].As<Napi::String>().Utf8Value()
1779
+ : "left";
1780
+ if (item.menu && kind != "middle") return Napi::Boolean::New(env, false);
1781
+ NSStatusBarButton* btn = item.button;
1782
+ NSWindow* win = btn.window;
1783
+ if (!win) return Napi::Boolean::New(env, false);
1784
+ WaitForStatusWindow(win, 2.0);
1785
+ RememberStatusWindow(win, item);
1786
+ NSEventType down = NSEventTypeLeftMouseDown, up = NSEventTypeLeftMouseUp;
1787
+ if (kind == "right") {
1788
+ down = NSEventTypeRightMouseDown; up = NSEventTypeRightMouseUp;
1789
+ } else if (kind == "middle") {
1790
+ down = NSEventTypeOtherMouseDown; up = NSEventTypeOtherMouseUp;
1791
+ }
1792
+ NSRect r = [btn convertRect:btn.bounds toView:nil];
1793
+ NSPoint p = NSMakePoint(NSMidX(r), NSMidY(r));
1794
+ NSTimeInterval now = [NSProcessInfo processInfo].systemUptime;
1795
+ for (NSEventType t : {down, up}) {
1796
+ NSEvent* e = [NSEvent mouseEventWithType:t
1797
+ location:p
1798
+ modifierFlags:0
1799
+ timestamp:now
1800
+ windowNumber:win.windowNumber
1801
+ context:nil
1802
+ eventNumber:0
1803
+ clickCount:1
1804
+ pressure:t == down ? 1 : 0];
1805
+ if (kind == "middle") {
1806
+ // mouseEventWithType: leaves the button number at 0 for the "other"
1807
+ // types; the middle button is number 2, which only the CGEvent
1808
+ // underneath can say
1809
+ CGEventRef cg = CGEventCreateCopy(e.CGEvent);
1810
+ CGEventSetIntegerValueField(cg, kCGMouseEventButtonNumber, 2);
1811
+ NSEvent* e2 = [NSEvent eventWithCGEvent:cg];
1812
+ CFRelease(cg);
1813
+ if (e2) e = e2;
1814
+ }
1815
+ [NSApp postEvent:e atStart:NO];
1816
+ }
1817
+ return Napi::Boolean::New(env, true);
1818
+ }
1819
+
1820
+ // snapshotStatusItem(item, file) — the item's window as the WindowServer
1821
+ // composited it, to PNG (our own window: no screen-recording permission
1822
+ // needed, unlike `screencapture -l` from another process). For tests.
1823
+ static Napi::Value SnapshotStatusItem(const Napi::CallbackInfo& info) {
1824
+ Napi::Env env = info.Env();
1825
+ NSStatusItem* item = StatusItemFrom(info[0]);
1826
+ NSWindow* win = item ? item.button.window : nil;
1827
+ if (!win || !info[1].IsString()) return Napi::Boolean::New(env, false);
1828
+ WaitForStatusWindow(win, 2.0);
1829
+ #pragma clang diagnostic push
1830
+ #pragma clang diagnostic ignored "-Wdeprecated-declarations"
1831
+ CGImageRef img = CGWindowListCreateImage(
1832
+ CGRectNull, kCGWindowListOptionIncludingWindow,
1833
+ (CGWindowID)win.windowNumber,
1834
+ (CGWindowImageOption)(kCGWindowImageBoundsIgnoreFraming |
1835
+ kCGWindowImageBestResolution));
1836
+ #pragma clang diagnostic pop
1837
+ if (!img) return Napi::Boolean::New(env, false);
1838
+ NSURL* url = [NSURL fileURLWithPath:BToNSString(info[1])];
1839
+ CGImageDestinationRef dst = CGImageDestinationCreateWithURL(
1840
+ (__bridge CFURLRef)url, CFSTR("public.png"), 1, NULL);
1841
+ bool ok = false;
1842
+ if (dst) {
1843
+ CGImageDestinationAddImage(dst, img, NULL);
1844
+ ok = CGImageDestinationFinalize(dst);
1845
+ CFRelease(dst);
1846
+ }
1847
+ CGImageRelease(img);
1848
+ return Napi::Boolean::New(env, ok);
1849
+ }
1850
+
1851
+ // setDockMenu(items | null) — the menu behind a right-click (or a press-
1852
+ // and-hold) on the Dock tile. `items` is one menu's worth of the item
1853
+ // vocabulary setMainMenu takes: {id, title, enabled, hidden, checked,
1854
+ // separator, iconName, iconData, items}. Activations arrive as
1855
+ // `menu-activate` with `menu: 'dock'`. The Dock asks the delegate for the
1856
+ // menu every time it opens it, so a new spec shows on the next click; null
1857
+ // removes the menu (the Dock then shows only its own entries).
1858
+ static Napi::Value SetDockMenuFn(const Napi::CallbackInfo& info) {
1859
+ Napi::Env env = info.Env();
1860
+ BEnsureApp();
1861
+ Napi::Value v = info[0];
1862
+ if (v.IsNull() || v.IsUndefined()) {
1863
+ gDockMenu = nil;
1864
+ return env.Undefined();
1865
+ }
1866
+ if (!v.IsArray()) {
1867
+ Napi::TypeError::New(env, "setDockMenu: expected an array of items or null")
1868
+ .ThrowAsJavaScriptException();
1869
+ return env.Undefined();
1870
+ }
1871
+ CALMenuTarget* target = MenuTargetFor(env, &gDockMenuTarget, "dock");
1872
+ gDockMenu = BuildMenuFrom(env, v.As<Napi::Array>(), target);
1873
+ return env.Undefined();
1874
+ }
1875
+
1876
+ // The menu the Dock would get: through the delegate, so the test exercises
1877
+ // the wiring the Dock uses, not the variable behind it.
1878
+ static NSMenu* DockMenuViaDelegate() {
1879
+ id<NSApplicationDelegate> d = NSApp.delegate;
1880
+ if (![d respondsToSelector:@selector(applicationDockMenu:)]) return nil;
1881
+ return [d applicationDockMenu:NSApp];
1882
+ }
1883
+
1884
+ // dockMenuInfo() — the installed Dock menu as data (null when none). Tests.
1885
+ static Napi::Value DockMenuInfoFn(const Napi::CallbackInfo& info) {
1886
+ Napi::Env env = info.Env();
1887
+ BEnsureApp();
1888
+ NSMenu* m = DockMenuViaDelegate();
1889
+ if (!m) return env.Null();
1890
+ return MenuInfo(env, m);
1891
+ }
1892
+
1893
+ // activateDockMenuItem([i, j, ...]) — through the Dock menu.
1894
+ static Napi::Value ActivateDockMenuItemFn(const Napi::CallbackInfo& info) {
1895
+ Napi::Env env = info.Env();
1896
+ BEnsureApp();
1897
+ if (!info[0].IsArray()) return Napi::Boolean::New(env, false);
1898
+ return Napi::Boolean::New(
1899
+ env, ActivateInMenu(DockMenuViaDelegate(), info[0].As<Napi::Array>()));
1900
+ }
1901
+
1902
+ // ---------------------------------------------------------------------------
1903
+ // app presence: what the user sees of the process outside its windows — the
1904
+ // Dock tile (badge, bounce, menu, whether there is one) and the name the
1905
+ // Dock, the ⌘-Tab switcher and the menu bar print for it. Mechanism only:
1906
+ // the counts, the reasons and the timing are the renderer's.
1907
+ // ---------------------------------------------------------------------------
1908
+
1909
+ static bool PolicyFromName(const std::string& s,
1910
+ NSApplicationActivationPolicy* out) {
1911
+ if (s == "regular") *out = NSApplicationActivationPolicyRegular;
1912
+ else if (s == "accessory") *out = NSApplicationActivationPolicyAccessory;
1913
+ else if (s == "prohibited") *out = NSApplicationActivationPolicyProhibited;
1914
+ else return false;
1915
+ return true;
1916
+ }
1917
+
1918
+ static const char* PolicyName(NSApplicationActivationPolicy p) {
1919
+ switch (p) {
1920
+ case NSApplicationActivationPolicyRegular: return "regular";
1921
+ case NSApplicationActivationPolicyAccessory: return "accessory";
1922
+ case NSApplicationActivationPolicyProhibited: return "prohibited";
1923
+ }
1924
+ return "regular";
1925
+ }
1926
+
1927
+ // Before launch the policy is what the app launches with (no Dock tile ever
1928
+ // registers for an agent); after launch it is a live switch.
1929
+ static bool ApplyActivationPolicy(NSApplicationActivationPolicy p) {
1930
+ if (!gAppLaunched) {
1931
+ gActivationPolicy = p;
1932
+ BEnsureApp();
1933
+ return true;
1934
+ }
1935
+ return [NSApp setActivationPolicy:p];
1936
+ }
1937
+
1938
+ // Reads `activationPolicy` off an options object; throws on an unknown name.
1939
+ // Returns false when it threw.
1940
+ static bool ApplyPolicyOption(Napi::Env env, Napi::Value v) {
1941
+ if (v.IsUndefined() || v.IsNull()) return true;
1942
+ NSApplicationActivationPolicy p;
1943
+ if (!v.IsString() || !PolicyFromName(v.As<Napi::String>().Utf8Value(), &p)) {
1944
+ Napi::RangeError::New(
1945
+ env, "activationPolicy: expected 'regular' | 'accessory' | 'prohibited'")
1946
+ .ThrowAsJavaScriptException();
1947
+ return false;
1948
+ }
1949
+ ApplyActivationPolicy(p);
1950
+ return true;
1951
+ }
1952
+
1953
+ // initApp({ activationPolicy? }) — the NSApplication, its activation policy
1954
+ // and the app delegate (open-URL / open-file, reopen, quit and Dock-menu
1955
+ // routing; see the app lifecycle section). Idempotent; every other entry
1956
+ // point calls it implicitly, but a renderer that wants the launching URL
1957
+ // calls it first thing and installs its callback next, before the first
1958
+ // pump. The policy option is honoured on any call: before launch it decides
1959
+ // how the app launches, afterwards it switches live.
1960
+ static Napi::Value InitAppFn(const Napi::CallbackInfo& info) {
1961
+ Napi::Env env = info.Env();
1962
+ if (info.Length() > 0 && info[0].IsObject()) {
1963
+ Napi::Object o = info[0].As<Napi::Object>();
1964
+ if (!ApplyPolicyOption(env, o.Get("activationPolicy"))) return env.Undefined();
1965
+ }
1966
+ BEnsureApp();
1967
+ return env.Undefined();
1968
+ }
1969
+
1970
+ // setActivationPolicy('regular' | 'accessory' | 'prohibited') -> bool
1971
+ // 'regular': Dock tile, menu bar, ⌘-Tab entry. 'accessory': none of those,
1972
+ // windows still work (LSUIElement — menu-bar and agent apps). 'prohibited':
1973
+ // no UI at all. Returns what AppKit answers (true on every supported macOS).
1974
+ static Napi::Value SetActivationPolicyFn(const Napi::CallbackInfo& info) {
1975
+ Napi::Env env = info.Env();
1976
+ NSApplicationActivationPolicy p;
1977
+ if (!info[0].IsString() ||
1978
+ !PolicyFromName(info[0].As<Napi::String>().Utf8Value(), &p)) {
1979
+ Napi::RangeError::New(
1980
+ env, "setActivationPolicy: expected 'regular' | 'accessory' | 'prohibited'")
1981
+ .ThrowAsJavaScriptException();
1982
+ return env.Undefined();
1983
+ }
1984
+ return Napi::Boolean::New(env, ApplyActivationPolicy(p));
1985
+ }
1986
+
1987
+ // setDockBadge(label | null) — NSDockTile.badgeLabel: the red pill on the
1988
+ // Dock tile (an unread count, usually). A number is stringified; null or
1989
+ // undefined clears. Shows only while the tile exists (policy 'regular').
1990
+ static Napi::Value SetDockBadgeFn(const Napi::CallbackInfo& info) {
1991
+ Napi::Env env = info.Env();
1992
+ BEnsureApp();
1993
+ Napi::Value v = info[0];
1994
+ if (v.IsNull() || v.IsUndefined()) {
1995
+ NSApp.dockTile.badgeLabel = nil;
1996
+ } else if (v.IsString() || v.IsNumber()) {
1997
+ NSApp.dockTile.badgeLabel = BToNSString(v.ToString());
1998
+ } else {
1999
+ Napi::TypeError::New(env, "setDockBadge: expected a string, a number or null")
2000
+ .ThrowAsJavaScriptException();
2001
+ }
2002
+ return env.Undefined();
2003
+ }
2004
+
2005
+ // requestUserAttention('informational' | 'critical') -> requestId
2006
+ // The Dock bounce, _NET_WM_STATE_DEMANDS_ATTENTION's counterpart:
2007
+ // 'informational' bounces once, 'critical' keeps bouncing until the app is
2008
+ // activated. AppKit ignores the request while the app is active (the id it
2009
+ // returns then is still safe to cancel; appInfo().active says which case a
2010
+ // caller is in). Anything else as the type is a RangeError.
2011
+ static Napi::Value RequestUserAttentionFn(const Napi::CallbackInfo& info) {
2012
+ Napi::Env env = info.Env();
2013
+ BEnsureApp();
2014
+ NSRequestUserAttentionType type;
2015
+ std::string s = info[0].IsString() ? info[0].As<Napi::String>().Utf8Value() : "";
2016
+ if (s == "informational") type = NSInformationalRequest;
2017
+ else if (s == "critical") type = NSCriticalRequest;
2018
+ else {
2019
+ Napi::RangeError::New(
2020
+ env, "requestUserAttention: expected 'informational' | 'critical'")
2021
+ .ThrowAsJavaScriptException();
2022
+ return env.Undefined();
2023
+ }
2024
+ return Napi::Number::New(env, (double)[NSApp requestUserAttention:type]);
2025
+ }
2026
+
2027
+ // cancelUserAttention(requestId) — stop a bounce early (the message was
2028
+ // read some other way); a request that already ended is a no-op.
2029
+ static Napi::Value CancelUserAttentionFn(const Napi::CallbackInfo& info) {
2030
+ Napi::Env env = info.Env();
2031
+ if (!info[0].IsNumber()) {
2032
+ Napi::TypeError::New(env, "cancelUserAttention: expected the request id")
2033
+ .ThrowAsJavaScriptException();
2034
+ return env.Undefined();
2035
+ }
2036
+ BEnsureApp();
2037
+ [NSApp cancelUserAttentionRequest:(NSInteger)info[0].As<Napi::Number>().Int64Value()];
2038
+ return env.Undefined();
2039
+ }
2040
+
2041
+ // setAppName(name) -> bool — the name the Dock tile, the ⌘-Tab switcher,
2042
+ // Force Quit and the application menu print for this process.
2043
+ //
2044
+ // A bundled app gets that name from its Info.plist and keeps it: when the
2045
+ // main bundle declares CFBundleName or CFBundleDisplayName this is a no-op
2046
+ // answering false. An unbundled process (`node`, `bun`) is registered with
2047
+ // LaunchServices under its executable name, and the only way to change that
2048
+ // record from inside is the private LaunchServices call WebKit, Chromium
2049
+ // and the JDK's -Xdock:name use: _LSSetApplicationInformationItem with
2050
+ // _kLSDisplayNameKey on the process's own ASN. It is looked up at runtime,
2051
+ // so a macOS that drops it makes this answer false rather than fail to
2052
+ // load. NSRunningApplication.localizedName reads the same record back
2053
+ // (appInfo().name).
2054
+ typedef CFTypeRef (*CALLSGetCurrentApplicationASN)(void);
2055
+ typedef OSStatus (*CALLSSetApplicationInformationItem)(int, CFTypeRef,
2056
+ CFStringRef, CFStringRef,
2057
+ CFDictionaryRef*);
2058
+
2059
+ static bool BundleDeclaresName() {
2060
+ NSBundle* b = [NSBundle mainBundle];
2061
+ return [b objectForInfoDictionaryKey:@"CFBundleDisplayName"] != nil ||
2062
+ [b objectForInfoDictionaryKey:@"CFBundleName"] != nil;
2063
+ }
2064
+
2065
+ static bool SetLaunchServicesDisplayName(NSString* name) {
2066
+ void* h = dlopen(
2067
+ "/System/Library/Frameworks/CoreServices.framework/CoreServices",
2068
+ RTLD_LAZY);
2069
+ if (!h) return false;
2070
+ auto getASN = (CALLSGetCurrentApplicationASN)dlsym(
2071
+ h, "_LSGetCurrentApplicationASN");
2072
+ auto setItem = (CALLSSetApplicationInformationItem)dlsym(
2073
+ h, "_LSSetApplicationInformationItem");
2074
+ auto key = (CFStringRef*)dlsym(h, "_kLSDisplayNameKey");
2075
+ if (!getASN || !setItem || !key || !*key) return false;
2076
+ CFTypeRef asn = getASN();
2077
+ if (!asn) return false;
2078
+ // -2: the "current session" LSSessionID WebKit passes here
2079
+ return setItem(-2, asn, *key, (__bridge CFStringRef)name, NULL) == noErr;
2080
+ }
2081
+
2082
+ static Napi::Value SetAppNameFn(const Napi::CallbackInfo& info) {
2083
+ Napi::Env env = info.Env();
2084
+ if (!info[0].IsString()) {
2085
+ Napi::TypeError::New(env, "setAppName: expected a string")
2086
+ .ThrowAsJavaScriptException();
2087
+ return env.Undefined();
2088
+ }
2089
+ BEnsureApp();
2090
+ if (BundleDeclaresName()) return Napi::Boolean::New(env, false);
2091
+ return Napi::Boolean::New(env,
2092
+ SetLaunchServicesDisplayName(BToNSString(info[0])));
2093
+ }
2094
+
2095
+ // appInfo() -> { activationPolicy, name, dockBadge, active } — the presence
2096
+ // state read back from AppKit and LaunchServices, for tests and for a
2097
+ // renderer deciding whether a bounce would even be seen.
2098
+ static Napi::Value AppInfoFn(const Napi::CallbackInfo& info) {
2099
+ Napi::Env env = info.Env();
2100
+ BEnsureApp();
2101
+ Napi::Object r = Napi::Object::New(env);
2102
+ r.Set("activationPolicy", PolicyName(NSApp.activationPolicy));
2103
+ NSString* name = NSRunningApplication.currentApplication.localizedName;
2104
+ if (name) r.Set("name", name.UTF8String);
2105
+ else r.Set("name", env.Null());
2106
+ NSString* badge = NSApp.dockTile.badgeLabel;
2107
+ if (badge.length) r.Set("dockBadge", badge.UTF8String);
2108
+ else r.Set("dockBadge", env.Null());
2109
+ r.Set("active", (bool)NSApp.isActive);
2110
+ return r;
2111
+ }
2112
+
2113
+ // ---------------------------------------------------------------------------
2114
+ // file panels — NSOpenPanel / NSSavePanel, the real thing rather than an
2115
+ // osascript process: owned by our NSApplication, a sheet on the window that
2116
+ // asked, a cancel that reads as a cancel. Two presentations: with a window
2117
+ // handle the panel is a sheet (beginSheetModalForWindow:), the pump keeps
2118
+ // running and the answer arrives through the completion handler on a later
2119
+ // tick; with no window it is app-modal (runModal), which parks this thread
2120
+ // in AppKit's modal loop until the panel is dismissed, so the callback runs
2121
+ // before the call returns. Both end in cb(result), null meaning cancel.
2122
+ // Filters are UTType identifiers — extension/MIME resolution is the
2123
+ // renderer's policy; contentTypeFor() asks the OS's own type database on its
2124
+ // behalf so nothing is dropped the way AppleScript's `of type` dropped MIME.
2125
+ // ---------------------------------------------------------------------------
2126
+
2127
+ // What a presented panel owes JS: the callback and the env to call it with.
2128
+ // Hung on the panel itself so cancelPanel can tell an open panel from one
2129
+ // that has already answered.
2130
+ @interface CALPanelPending : NSObject {
2131
+ @public
2132
+ napi_env env_;
2133
+ Napi::FunctionReference cb_;
2134
+ bool open_; // NSOpenPanel answers paths[], NSSavePanel answers a path
2135
+ }
2136
+ @end
2137
+ @implementation CALPanelPending
2138
+ @end
2139
+
2140
+ static char kPanelPendingKey;
2141
+
2142
+ static Napi::Value PanelResult(Napi::Env env, NSSavePanel* panel, bool open,
2143
+ NSModalResponse r) {
2144
+ if (r != NSModalResponseOK) return env.Null();
2145
+ if (open) {
2146
+ NSArray<NSURL*>* urls = ((NSOpenPanel*)panel).URLs;
2147
+ Napi::Array a = Napi::Array::New(env, urls.count);
2148
+ for (NSUInteger i = 0; i < urls.count; i++)
2149
+ a.Set((uint32_t)i, Napi::String::New(env, urls[i].path.UTF8String));
2150
+ return a;
2151
+ }
2152
+ NSURL* u = panel.URL;
2153
+ return u ? Napi::Value(Napi::String::New(env, u.path.UTF8String))
2154
+ : Napi::Value(env.Null());
2155
+ }
2156
+
2157
+ // The one place a panel answers. The pending record comes off first, so a
2158
+ // second answer (or a cancelPanel from inside the callback) finds nothing.
2159
+ static void FinishPanel(NSSavePanel* panel, NSModalResponse r) {
2160
+ CALPanelPending* p = objc_getAssociatedObject(panel, &kPanelPendingKey);
2161
+ if (!p) return;
2162
+ objc_setAssociatedObject(panel, &kPanelPendingKey, nil,
2163
+ OBJC_ASSOCIATION_RETAIN_NONATOMIC);
2164
+ Napi::Env env(p->env_);
2165
+ Napi::HandleScope scope(env);
2166
+ Napi::Value result = PanelResult(env, panel, p->open_, r);
2167
+ Napi::FunctionReference cb = std::move(p->cb_);
2168
+ cb.Call({result});
2169
+ }
2170
+
2171
+ // A path, or a file: URL for callers that already hold one.
2172
+ static NSURL* PanelURLArg(Napi::Value v) {
2173
+ if (!v.IsString()) return nil;
2174
+ NSString* s = BToNSString(v);
2175
+ if ([s hasPrefix:@"file:"]) return [NSURL URLWithString:s];
2176
+ return s.length ? [NSURL fileURLWithPath:s] : nil;
2177
+ }
2178
+
2179
+ // The spec keys both panels share.
2180
+ static void ConfigurePanel(NSSavePanel* panel, Napi::Object o) {
2181
+ if (o.Has("title") && o.Get("title").IsString())
2182
+ panel.title = BToNSString(o.Get("title"));
2183
+ if (o.Has("message") && o.Get("message").IsString())
2184
+ panel.message = BToNSString(o.Get("message"));
2185
+ if (o.Has("prompt") && o.Get("prompt").IsString())
2186
+ panel.prompt = BToNSString(o.Get("prompt"));
2187
+ if (o.Has("directoryURL")) {
2188
+ NSURL* u = PanelURLArg(o.Get("directoryURL"));
2189
+ if (u) panel.directoryURL = u;
2190
+ }
2191
+ if (o.Has("canCreateDirectories"))
2192
+ panel.canCreateDirectories =
2193
+ BBoolOr(o, "canCreateDirectories", panel.canCreateDirectories);
2194
+ if (o.Has("allowedContentTypes") && o.Get("allowedContentTypes").IsArray()) {
2195
+ Napi::Array ids = o.Get("allowedContentTypes").As<Napi::Array>();
2196
+ NSMutableArray<UTType*>* types = [NSMutableArray array];
2197
+ for (uint32_t i = 0; i < ids.Length(); i++) {
2198
+ Napi::Value v = ids.Get(i);
2199
+ if (!v.IsString()) continue;
2200
+ UTType* t = [UTType typeWithIdentifier:BToNSString(v)];
2201
+ if (t) [types addObject:t];
2202
+ }
2203
+ // A list the OS recognises nothing of is no filter at all, the same as
2204
+ // passing none: a panel that admits nothing helps nobody.
2205
+ if (types.count) panel.allowedContentTypes = types;
2206
+ }
2207
+ }
2208
+
2209
+ // openPanel(spec, cb) / savePanel(spec, cb) -> panel handle
2210
+ // spec: { window?, // handle: sheet on it; absent: app-modal
2211
+ // title?, message?, prompt?, // prompt = confirm button label
2212
+ // directoryURL?, // path or file: URL, where it opens
2213
+ // allowedContentTypes?: [UTType id], // absent/empty: any
2214
+ // canCreateDirectories?,
2215
+ // directory?, multiple?, // open: folders not files; several
2216
+ // nameFieldStringValue? } // save: the proposed name
2217
+ // cb(paths | null) for open, cb(path | null) for save; null is cancel.
2218
+ static Napi::Value PresentPanel(const Napi::CallbackInfo& info, bool open) {
2219
+ Napi::Env env = info.Env();
2220
+ if (!info[0].IsObject() || !info[1].IsFunction()) {
2221
+ Napi::TypeError::New(env, open ? "openPanel(spec, cb): spec object and callback required"
2222
+ : "savePanel(spec, cb): spec object and callback required")
2223
+ .ThrowAsJavaScriptException();
2224
+ return env.Undefined();
2225
+ }
2226
+ Napi::Object o = info[0].As<Napi::Object>();
2227
+ NSWindow* owner = nil;
2228
+ if (o.Has("window")) {
2229
+ Napi::Value w = o.Get("window");
2230
+ if (w.IsExternal()) {
2231
+ owner = BDeref<NSWindow*>(w);
2232
+ } else if (!w.IsNull() && !w.IsUndefined()) {
2233
+ Napi::TypeError::New(env, "window must be a window handle")
2234
+ .ThrowAsJavaScriptException();
2235
+ return env.Undefined();
2236
+ }
2237
+ }
2238
+ BEnsureApp();
2239
+
2240
+ NSSavePanel* panel;
2241
+ if (open) {
2242
+ NSOpenPanel* op = [NSOpenPanel openPanel];
2243
+ bool dirs = BBoolOr(o, "directory", false);
2244
+ op.canChooseDirectories = dirs;
2245
+ op.canChooseFiles = !dirs;
2246
+ op.allowsMultipleSelection = BBoolOr(o, "multiple", false);
2247
+ panel = op;
2248
+ } else {
2249
+ panel = [NSSavePanel savePanel];
2250
+ if (o.Has("nameFieldStringValue") &&
2251
+ o.Get("nameFieldStringValue").IsString())
2252
+ panel.nameFieldStringValue = BToNSString(o.Get("nameFieldStringValue"));
2253
+ }
2254
+ ConfigurePanel(panel, o);
2255
+
2256
+ CALPanelPending* p = [CALPanelPending new];
2257
+ p->env_ = (napi_env)env;
2258
+ p->cb_ = Napi::Persistent(info[1].As<Napi::Function>());
2259
+ p->open_ = open;
2260
+ objc_setAssociatedObject(panel, &kPanelPendingKey, p,
2261
+ OBJC_ASSOCIATION_RETAIN_NONATOMIC);
2262
+ Napi::Value handle = BWrapRetained(env, panel);
2263
+
2264
+ if (owner) {
2265
+ [panel beginSheetModalForWindow:owner
2266
+ completionHandler:^(NSModalResponse r) {
2267
+ FinishPanel(panel, r);
2268
+ }];
2269
+ } else {
2270
+ NSModalResponse r = [panel runModal];
2271
+ FinishPanel(panel, r);
2272
+ }
2273
+ return handle;
2274
+ }
2275
+
2276
+ static Napi::Value OpenPanelFn(const Napi::CallbackInfo& info) {
2277
+ return PresentPanel(info, true);
2278
+ }
2279
+
2280
+ static Napi::Value SavePanelFn(const Napi::CallbackInfo& info) {
2281
+ return PresentPanel(info, false);
2282
+ }
2283
+
2284
+ // cancelPanel(panel) -> bool — dismiss a sheet that is still up; its
2285
+ // callback then gets null. False when the panel has already answered.
2286
+ // (An app-modal panel cannot be reached from here: the thread that would
2287
+ // call this is inside runModal.)
2288
+ static Napi::Value CancelPanelFn(const Napi::CallbackInfo& info) {
2289
+ Napi::Env env = info.Env();
2290
+ if (!info[0].IsExternal()) {
2291
+ Napi::TypeError::New(env, "cancelPanel: panel handle required")
2292
+ .ThrowAsJavaScriptException();
2293
+ return env.Undefined();
2294
+ }
2295
+ NSSavePanel* panel = BDeref<NSSavePanel*>(info[0]);
2296
+ if (!objc_getAssociatedObject(panel, &kPanelPendingKey))
2297
+ return Napi::Boolean::New(env, false);
2298
+ [panel cancel:nil];
1029
2299
  return Napi::Boolean::New(env, true);
1030
2300
  }
1031
2301
 
2302
+ // Every panel sheet still up on `win`, answered null. Called before the
2303
+ // window is torn down.
2304
+ static void CancelPanelSheetsOn(NSWindow* win) {
2305
+ for (NSWindow* sheet in [win.sheets copy]) {
2306
+ if (objc_getAssociatedObject(sheet, &kPanelPendingKey))
2307
+ [(NSSavePanel*)sheet cancel:nil];
2308
+ }
2309
+ }
2310
+
2311
+ // contentTypeFor({ extension } | { mime }) -> UTType identifier, or null.
2312
+ // The OS's own database: 'png' -> 'public.png', 'application/json' ->
2313
+ // 'public.json'; an extension nothing has declared still yields a dynamic
2314
+ // type ('dyn.…') that matches exactly that extension in a panel.
2315
+ static Napi::Value ContentTypeForFn(const Napi::CallbackInfo& info) {
2316
+ Napi::Env env = info.Env();
2317
+ if (!info[0].IsObject()) {
2318
+ Napi::TypeError::New(env, "contentTypeFor({ extension } | { mime })")
2319
+ .ThrowAsJavaScriptException();
2320
+ return env.Undefined();
2321
+ }
2322
+ Napi::Object o = info[0].As<Napi::Object>();
2323
+ UTType* t = nil;
2324
+ if (o.Has("extension") && o.Get("extension").IsString()) {
2325
+ NSString* ext = BToNSString(o.Get("extension"));
2326
+ if ([ext hasPrefix:@"."]) ext = [ext substringFromIndex:1];
2327
+ if (ext.length) t = [UTType typeWithFilenameExtension:ext];
2328
+ } else if (o.Has("mime") && o.Get("mime").IsString()) {
2329
+ t = [UTType typeWithMIMEType:BToNSString(o.Get("mime"))];
2330
+ }
2331
+ return t ? Napi::Value(Napi::String::New(env, t.identifier.UTF8String))
2332
+ : Napi::Value(env.Null());
2333
+ }
2334
+
1032
2335
  // ---------------------------------------------------------------------------
1033
2336
  // native control bezels — NSCell/NSControl rendered offscreen (the WebKit/
1034
2337
  // Gecko form-control technique), measured and drawn in one vocabulary so the
@@ -2938,6 +4241,725 @@ static Napi::Value InvalidateWindowShadow(const Napi::CallbackInfo& info) {
2938
4241
  return info.Env().Undefined();
2939
4242
  }
2940
4243
 
4244
+ // ---------------------------------------------------------------------------
4245
+ // drag and drop — NSDraggingDestination on the hosting view, NSDraggingSource
4246
+ // from it (windowkit/appkit#16). Mechanism only. AppKit asks its questions
4247
+ // synchronously — may this drop land, and with which operation? — and the
4248
+ // view answers them from a response JS sets during the callback for that
4249
+ // very question (the callback runs inside draggingEntered:/draggingUpdated:,
4250
+ // so a setDropResponse in a drag-enter handler is the answer to that
4251
+ // draggingEntered:). Every phase is reported through the backend callback
4252
+ // with the window's number attached, like every other window event. Type
4253
+ // names cross this boundary as pasteboard types — UTIs such as
4254
+ // public.utf8-plain-text, public.file-url, public.png, and the legacy
4255
+ // NSPasteboardType strings AppKit still hands out — and the MIME vocabulary
4256
+ // stays the renderer's; pasteboardTypeForMIME is the OS's own table for it.
4257
+ // ---------------------------------------------------------------------------
4258
+
4259
+ static const struct {
4260
+ const char* name;
4261
+ NSDragOperation op;
4262
+ } kDragOps[] = {
4263
+ {"copy", NSDragOperationCopy}, {"link", NSDragOperationLink},
4264
+ {"generic", NSDragOperationGeneric}, {"private", NSDragOperationPrivate},
4265
+ {"move", NSDragOperationMove}, {"delete", NSDragOperationDelete},
4266
+ };
4267
+
4268
+ static NSDragOperation DragOpFromName(const std::string& name) {
4269
+ for (const auto& d : kDragOps)
4270
+ if (name == d.name) return d.op;
4271
+ return NSDragOperationNone;
4272
+ }
4273
+
4274
+ static const char* DragOpName(NSDragOperation op) {
4275
+ for (const auto& d : kDragOps)
4276
+ if (op == d.op) return d.name;
4277
+ return op == NSDragOperationNone ? "none" : "generic";
4278
+ }
4279
+
4280
+ // ['copy', 'move'] or a raw NSDragOperation mask; absent means copy.
4281
+ static NSDragOperation DragMaskFrom(Napi::Value v) {
4282
+ if (v.IsNumber()) return (NSDragOperation)v.As<Napi::Number>().Uint32Value();
4283
+ if (!v.IsArray()) return NSDragOperationCopy;
4284
+ Napi::Array a = v.As<Napi::Array>();
4285
+ NSDragOperation mask = NSDragOperationNone;
4286
+ for (uint32_t i = 0; i < a.Length(); i++) {
4287
+ Napi::Value e = a.Get(i);
4288
+ if (e.IsString()) mask |= DragOpFromName(e.As<Napi::String>().Utf8Value());
4289
+ }
4290
+ return mask;
4291
+ }
4292
+
4293
+ static Napi::Array DragOpsOfMask(Napi::Env env, NSDragOperation mask) {
4294
+ Napi::Array out = Napi::Array::New(env);
4295
+ uint32_t n = 0;
4296
+ for (const auto& d : kDragOps)
4297
+ if (mask & d.op) out.Set(n++, d.name);
4298
+ return out;
4299
+ }
4300
+
4301
+ // The operation a destination answers when JS accepted without naming one:
4302
+ // the conventional order over what the source allows. An explicit
4303
+ // `operation` is returned as given, whether or not the source offered it.
4304
+ static NSDragOperation DragDefaultOp(NSDragOperation mask) {
4305
+ static const NSDragOperation prefer[] = {
4306
+ NSDragOperationCopy, NSDragOperationMove, NSDragOperationLink,
4307
+ NSDragOperationGeneric, NSDragOperationPrivate, NSDragOperationDelete};
4308
+ for (NSDragOperation op : prefer)
4309
+ if (mask & op) return op;
4310
+ return NSDragOperationGeneric;
4311
+ }
4312
+
4313
+ // The pasteboard of the drag most recently over one of our windows — what
4314
+ // dragItems / dragItemData read. AppKit hands each destination method its
4315
+ // own NSDraggingInfo and forbids keeping it; the pasteboard underneath is
4316
+ // the drag pasteboard, which outlives the call.
4317
+ static NSPasteboard* gDragPasteboard = nil;
4318
+ // postDragEvent's private pasteboard; released when the next one replaces it.
4319
+ static NSPasteboard* gPostedPasteboard = nil;
4320
+
4321
+ // The hosting view of a createWindow2 window, or nil with a TypeError
4322
+ // pending: these verbs belong to the backend surface, and addon.mm's windows
4323
+ // host a CALHostView that has none of this.
4324
+ static CALBackendView* BackendViewArg(Napi::Value v, const char* fn) {
4325
+ if (v.IsExternal()) {
4326
+ NSWindow* win = BDeref<NSWindow*>(v);
4327
+ if ([win.contentView isKindOfClass:[CALBackendView class]])
4328
+ return (CALBackendView*)win.contentView;
4329
+ }
4330
+ Napi::TypeError::New(v.Env(),
4331
+ std::string(fn) + ": expected a createWindow2 window")
4332
+ .ThrowAsJavaScriptException();
4333
+ return nil;
4334
+ }
4335
+
4336
+ // A JS value onto a pasteboard item: a string as a string (AppKit encodes
4337
+ // it for the type — UTF-8 for public.utf8-plain-text, the URL string for
4338
+ // public.file-url), bytes as bytes, anything else stringified. null writes
4339
+ // nothing.
4340
+ static void WritePasteboardValue(NSPasteboardItem* item, NSString* type,
4341
+ Napi::Value v) {
4342
+ if (v.IsNull() || v.IsUndefined()) return;
4343
+ if (v.IsString()) {
4344
+ [item setString:BToNSString(v) forType:type];
4345
+ return;
4346
+ }
4347
+ const void* bytes = nullptr;
4348
+ size_t len = 0;
4349
+ if (v.IsBuffer()) {
4350
+ Napi::Buffer<uint8_t> b = v.As<Napi::Buffer<uint8_t>>();
4351
+ bytes = b.Data();
4352
+ len = b.Length();
4353
+ } else if (v.IsTypedArray()) {
4354
+ Napi::TypedArray a = v.As<Napi::TypedArray>();
4355
+ bytes = (const uint8_t*)a.ArrayBuffer().Data() + a.ByteOffset();
4356
+ len = a.ByteLength();
4357
+ } else if (v.IsArrayBuffer()) {
4358
+ Napi::ArrayBuffer a = v.As<Napi::ArrayBuffer>();
4359
+ bytes = a.Data();
4360
+ len = a.ByteLength();
4361
+ } else {
4362
+ [item setString:BToNSString(v.ToString()) forType:type];
4363
+ return;
4364
+ }
4365
+ [item setData:[NSData dataWithBytes:bytes length:len] forType:type];
4366
+ }
4367
+
4368
+ // The source side's lazy payloads: a representation whose value was null is
4369
+ // promised, and AppKit asks for it here — on this thread, inside the pump or
4370
+ // the session's own tracking — when a consumer actually reads it. The
4371
+ // answer is `provide(type, itemIndex)`'s return value, written like any
4372
+ // other.
4373
+ @interface CALDragProvider : NSObject <NSPasteboardItemDataProvider> {
4374
+ @public
4375
+ napi_env env_;
4376
+ Napi::FunctionReference fn_;
4377
+ NSArray<NSPasteboardItem*>* items_;
4378
+ }
4379
+ @end
4380
+ @implementation CALDragProvider
4381
+ - (void)pasteboard:(NSPasteboard*)pb
4382
+ item:(NSPasteboardItem*)item
4383
+ provideDataForType:(NSPasteboardType)type {
4384
+ (void)pb;
4385
+ if (fn_.IsEmpty()) return;
4386
+ Napi::Env env(env_);
4387
+ Napi::HandleScope scope(env);
4388
+ NSUInteger idx = [items_ indexOfObjectIdenticalTo:item];
4389
+ Napi::Value v = fn_.Call(
4390
+ {Napi::String::New(env, type.UTF8String),
4391
+ Napi::Number::New(env, idx == NSNotFound ? -1 : (double)idx)});
4392
+ if (env.IsExceptionPending()) return;
4393
+ WritePasteboardValue(item, type, v);
4394
+ }
4395
+ - (void)pasteboardFinishedWithDataProvider:(NSPasteboard*)pb {
4396
+ (void)pb;
4397
+ fn_.Reset();
4398
+ items_ = nil;
4399
+ }
4400
+ @end
4401
+
4402
+ // items: [{ [type]: string | bytes | null }, ...] — one entry per dragging
4403
+ // item, its keys the representations that item offers (react-x11's dragData
4404
+ // shape; a drag of three files is three entries of one public.file-url
4405
+ // each, which is how Finder reads them). A bare object is one item. null
4406
+ // promises the representation through `provide`; without a provider it is
4407
+ // dropped.
4408
+ static NSArray<NSPasteboardItem*>* BuildPasteboardItems(
4409
+ Napi::Env env, Napi::Value spec, CALDragProvider* provider) {
4410
+ NSMutableArray<NSPasteboardItem*>* items = [NSMutableArray array];
4411
+ Napi::Array arr;
4412
+ if (spec.IsArray()) {
4413
+ arr = spec.As<Napi::Array>();
4414
+ } else {
4415
+ arr = Napi::Array::New(env, 1);
4416
+ arr.Set(0u, spec);
4417
+ }
4418
+ for (uint32_t i = 0; i < arr.Length(); i++) {
4419
+ Napi::Value v = arr.Get(i);
4420
+ if (!v.IsObject()) continue;
4421
+ Napi::Object o = v.As<Napi::Object>();
4422
+ NSPasteboardItem* item = [[NSPasteboardItem alloc] init];
4423
+ NSMutableArray<NSString*>* lazy = [NSMutableArray array];
4424
+ Napi::Array keys = o.GetPropertyNames();
4425
+ for (uint32_t k = 0; k < keys.Length(); k++) {
4426
+ Napi::Value key = keys.Get(k);
4427
+ if (!key.IsString()) continue;
4428
+ NSString* type = BToNSString(key);
4429
+ Napi::Value val = o.Get(key);
4430
+ if (val.IsNull() || val.IsUndefined()) {
4431
+ if (provider) [lazy addObject:type];
4432
+ } else {
4433
+ WritePasteboardValue(item, type, val);
4434
+ }
4435
+ }
4436
+ if (lazy.count) [item setDataProvider:provider forTypes:lazy];
4437
+ [items addObject:item];
4438
+ }
4439
+ return items;
4440
+ }
4441
+
4442
+ // The drag image, from either bitmap this addon deals in: `surface`, a
4443
+ // surface handle (the renderer's own paint, its scale known), or `image`, a
4444
+ // CGImage External — or the {image, width, height, scale} object
4445
+ // text.render / controls.render answer, taken whole.
4446
+ static NSImage* DragImageFrom(Napi::Object o, double* w, double* h) {
4447
+ Napi::Value sv = o.Get("surface");
4448
+ if (sv.IsExternal()) {
4449
+ CALSurface* s = SurfaceFrom(sv); // a released handle throws, as everywhere
4450
+ if (!s) return nil;
4451
+ double scale = s->scale > 0 ? s->scale : 1;
4452
+ CGImageRef cg = CGBitmapContextCreateImage(s->ctx);
4453
+ if (!cg) return nil;
4454
+ *w = s->width / scale;
4455
+ *h = s->height / scale;
4456
+ NSImage* img = [[NSImage alloc] initWithCGImage:cg size:NSMakeSize(*w, *h)];
4457
+ CGImageRelease(cg);
4458
+ return img;
4459
+ }
4460
+ Napi::Value iv = o.Get("image");
4461
+ double scale = BNumOr(o, "imageScale", 1);
4462
+ if (iv.IsObject() && !iv.IsExternal()) {
4463
+ Napi::Object r = iv.As<Napi::Object>();
4464
+ scale = BNumOr(r, "scale", scale);
4465
+ iv = r.Get("image");
4466
+ }
4467
+ if (!iv.IsExternal()) return nil;
4468
+ CGImageRef cg = (CGImageRef)iv.As<Napi::External<void>>().Data();
4469
+ *w = CGImageGetWidth(cg) / scale;
4470
+ *h = CGImageGetHeight(cg) / scale;
4471
+ return [[NSImage alloc] initWithCGImage:cg size:NSMakeSize(*w, *h)];
4472
+ }
4473
+
4474
+ // The shared payload of the destination events: where (content view,
4475
+ // top-left; and global top-left as gx/gy, like a mouse event), what the
4476
+ // pasteboard carries, and what the source allows. `types` is the union over
4477
+ // the pasteboard's items; `itemCount` says how many items carry them —
4478
+ // a Finder drag of three files is three items of one public.file-url each,
4479
+ // read per item through dragItemString. `local` is a drag begun by one of
4480
+ // our own windows (beginDrag), whose number then follows.
4481
+ static void EmitDragInfo(Napi::Env env, CALBackendView* view,
4482
+ const char* type, id<NSDraggingInfo> info) {
4483
+ if (!HasBackendCb()) return;
4484
+ Napi::HandleScope scope(env);
4485
+ NSWindow* win = view.window;
4486
+ Napi::Object ev = WindowEvent(env, win, type);
4487
+ if (info) {
4488
+ NSPoint loc = info.draggingLocation;
4489
+ NSPoint p = [view convertPoint:loc fromView:nil]; // the view is flipped
4490
+ ev.Set("x", p.x);
4491
+ ev.Set("y", p.y);
4492
+ NSRect r = [win convertRectToScreen:NSMakeRect(loc.x, loc.y, 0, 0)];
4493
+ ev.Set("gx", r.origin.x);
4494
+ ev.Set("gy", PrimaryScreenTop() - r.origin.y);
4495
+ NSPasteboard* pb = info.draggingPasteboard;
4496
+ Napi::Array types = Napi::Array::New(env);
4497
+ uint32_t n = 0;
4498
+ for (NSString* t in pb.types) types.Set(n++, t.UTF8String);
4499
+ ev.Set("types", types);
4500
+ ev.Set("itemCount", (double)pb.pasteboardItems.count);
4501
+ NSDragOperation mask = info.draggingSourceOperationMask;
4502
+ ev.Set("sourceMask", (double)mask);
4503
+ ev.Set("operations", DragOpsOfMask(env, mask));
4504
+ id src = info.draggingSource;
4505
+ bool local = [src isKindOfClass:[CALBackendView class]];
4506
+ ev.Set("local", local);
4507
+ if (local)
4508
+ ev.Set("sourceWindowNumber",
4509
+ (double)((CALBackendView*)src).window.windowNumber);
4510
+ ev.Set("sequence", (double)info.draggingSequenceNumber);
4511
+ }
4512
+ EmitToJS(env, ev);
4513
+ }
4514
+
4515
+ // The source side's events: the pointer in global top-left coordinates,
4516
+ // and for the end, the operation the destination performed ('none' when
4517
+ // nothing took the drop) with `dropped` as its boolean.
4518
+ static void EmitDragSession(Napi::Env env, CALBackendView* view,
4519
+ const char* type, NSPoint screenPoint,
4520
+ const char* operation) {
4521
+ if (!HasBackendCb()) return;
4522
+ Napi::HandleScope scope(env);
4523
+ Napi::Object ev = WindowEvent(env, view.window, type);
4524
+ ev.Set("x", screenPoint.x);
4525
+ ev.Set("y", PrimaryScreenTop() - screenPoint.y);
4526
+ if (operation) {
4527
+ ev.Set("operation", operation);
4528
+ ev.Set("dropped", strcmp(operation, "none") != 0);
4529
+ }
4530
+ EmitToJS(env, ev);
4531
+ }
4532
+
4533
+ @interface CALBackendView (DragAndDrop) <NSDraggingSource>
4534
+ @end
4535
+ @implementation CALBackendView (DragAndDrop)
4536
+
4537
+ // --- destination ----------------------------------------------------------
4538
+
4539
+ - (NSDragOperation)dropAnswer:(id<NSDraggingInfo>)info {
4540
+ if (!dropAccept_) return NSDragOperationNone;
4541
+ if (dropOp_) return DragOpFromName(dropOp_.UTF8String);
4542
+ return DragDefaultOp(info.draggingSourceOperationMask);
4543
+ }
4544
+ - (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender {
4545
+ gDragPasteboard = sender.draggingPasteboard;
4546
+ // a yes left over from the previous drag must not answer this one
4547
+ dropAccept_ = false;
4548
+ dropOp_ = nil;
4549
+ EmitDragInfo(Napi::Env(env_), self, "drag-enter", sender);
4550
+ return [self dropAnswer:sender];
4551
+ }
4552
+ - (NSDragOperation)draggingUpdated:(id<NSDraggingInfo>)sender {
4553
+ gDragPasteboard = sender.draggingPasteboard;
4554
+ EmitDragInfo(Napi::Env(env_), self, "drag-over", sender);
4555
+ return [self dropAnswer:sender];
4556
+ }
4557
+ - (void)draggingExited:(nullable id<NSDraggingInfo>)sender {
4558
+ EmitDragInfo(Napi::Env(env_), self, "drag-exit", sender);
4559
+ }
4560
+ - (BOOL)prepareForDragOperation:(id<NSDraggingInfo>)sender {
4561
+ (void)sender;
4562
+ return dropAccept_;
4563
+ }
4564
+ - (BOOL)performDragOperation:(id<NSDraggingInfo>)sender {
4565
+ gDragPasteboard = sender.draggingPasteboard;
4566
+ EmitDragInfo(Napi::Env(env_), self, "drag-perform", sender);
4567
+ return dropAccept_; // JS may withdraw it, having looked at the payload
4568
+ }
4569
+ // One drag-over per pointer position, not a timer's worth.
4570
+ - (BOOL)wantsPeriodicDraggingUpdates { return NO; }
4571
+
4572
+ // --- source ---------------------------------------------------------------
4573
+
4574
+ - (NSDragOperation)draggingSession:(NSDraggingSession*)session
4575
+ sourceOperationMaskForDraggingContext:(NSDraggingContext)context {
4576
+ (void)session;
4577
+ return context == NSDraggingContextOutsideApplication ? sourceMaskOutside_
4578
+ : sourceMask_;
4579
+ }
4580
+ - (BOOL)ignoreModifierKeysForDraggingSession:(NSDraggingSession*)session {
4581
+ (void)session;
4582
+ return ignoreModifiers_;
4583
+ }
4584
+ - (void)draggingSession:(NSDraggingSession*)session
4585
+ willBeginAtPoint:(NSPoint)screenPoint {
4586
+ (void)session;
4587
+ EmitDragSession(Napi::Env(env_), self, "drag-session-began", screenPoint,
4588
+ nullptr);
4589
+ }
4590
+ - (void)draggingSession:(NSDraggingSession*)session
4591
+ movedToPoint:(NSPoint)screenPoint {
4592
+ (void)session;
4593
+ EmitDragSession(Napi::Env(env_), self, "drag-session-moved", screenPoint,
4594
+ nullptr);
4595
+ }
4596
+ - (void)draggingSession:(NSDraggingSession*)session
4597
+ endedAtPoint:(NSPoint)screenPoint
4598
+ operation:(NSDragOperation)operation {
4599
+ (void)session;
4600
+ EmitDragSession(Napi::Env(env_), self, "drag-session-ended", screenPoint,
4601
+ DragOpName(operation));
4602
+ }
4603
+ @end
4604
+
4605
+ // registerDropTypes(win, types) — registerForDraggedTypes: on the hosting
4606
+ // view; an empty list unregisters. Until this is called a window takes no
4607
+ // drops and sees no drag events: AppKit routes a drag only to views
4608
+ // registered for a type it carries.
4609
+ static Napi::Value RegisterDropTypes(const Napi::CallbackInfo& info) {
4610
+ Napi::Env env = info.Env();
4611
+ CALBackendView* view = BackendViewArg(info[0], "registerDropTypes");
4612
+ if (!view) return env.Undefined();
4613
+ view->env_ = env;
4614
+ NSMutableArray<NSString*>* types = [NSMutableArray array];
4615
+ if (info[1].IsArray()) {
4616
+ Napi::Array a = info[1].As<Napi::Array>();
4617
+ for (uint32_t i = 0; i < a.Length(); i++)
4618
+ if (a.Get(i).IsString()) [types addObject:BToNSString(a.Get(i))];
4619
+ }
4620
+ [view unregisterDraggedTypes]; // replace, never accumulate
4621
+ if (types.count) [view registerForDraggedTypes:types];
4622
+ return env.Undefined();
4623
+ }
4624
+
4625
+ // setDropResponse(win, { accept, operation? }) — the view's answer for the
4626
+ // drag in flight. Set during a drag-enter or drag-over callback it answers
4627
+ // that question; it stays in force for the drag-over events that follow
4628
+ // until changed, and resets to a refusal when a new drag enters. Set during
4629
+ // drag-perform, `accept: false` withdraws the drop. `operation` is one of
4630
+ // copy | move | link | generic | private | delete; absent, the conventional
4631
+ // choice among what the source allows.
4632
+ static Napi::Value SetDropResponse(const Napi::CallbackInfo& info) {
4633
+ Napi::Env env = info.Env();
4634
+ CALBackendView* view = BackendViewArg(info[0], "setDropResponse");
4635
+ if (!view) return env.Undefined();
4636
+ Napi::Object o = info[1].IsObject() ? info[1].As<Napi::Object>()
4637
+ : Napi::Object::New(env);
4638
+ view->dropAccept_ = BBoolOr(o, "accept", false);
4639
+ NSString* op = BStrOr(o, "operation", nil);
4640
+ view->dropOp_ = op.length ? op : nil;
4641
+ return env.Undefined();
4642
+ }
4643
+
4644
+ static NSPasteboard* CurrentDragPasteboard() {
4645
+ return gDragPasteboard
4646
+ ?: [NSPasteboard pasteboardWithName:NSPasteboardNameDrag];
4647
+ }
4648
+
4649
+ // dragItems() -> [{ types: [...] }] — the items of the drag over (or just
4650
+ // dropped on) one of our windows, each with the representations it offers.
4651
+ // dragItemData(index, type) -> Buffer | null and dragItemString(index,
4652
+ // type) -> string | null read one. Read during the drag-perform callback:
4653
+ // the payload is the source's promise, and a source is free to withdraw it
4654
+ // once its session has ended.
4655
+ static Napi::Value DragItems(const Napi::CallbackInfo& info) {
4656
+ Napi::Env env = info.Env();
4657
+ Napi::Array out = Napi::Array::New(env);
4658
+ uint32_t n = 0;
4659
+ for (NSPasteboardItem* item in CurrentDragPasteboard().pasteboardItems) {
4660
+ Napi::Object o = Napi::Object::New(env);
4661
+ Napi::Array types = Napi::Array::New(env);
4662
+ uint32_t k = 0;
4663
+ for (NSString* t in item.types) types.Set(k++, t.UTF8String);
4664
+ o.Set("types", types);
4665
+ out.Set(n++, o);
4666
+ }
4667
+ return out;
4668
+ }
4669
+
4670
+ static NSPasteboardItem* DragItemArg(Napi::Value v) {
4671
+ NSArray<NSPasteboardItem*>* items = CurrentDragPasteboard().pasteboardItems;
4672
+ if (!v.IsNumber()) return nil;
4673
+ double i = v.As<Napi::Number>().DoubleValue();
4674
+ if (!(i >= 0 && i < (double)items.count)) return nil;
4675
+ return items[(NSUInteger)i];
4676
+ }
4677
+
4678
+ static Napi::Value DragItemData(const Napi::CallbackInfo& info) {
4679
+ Napi::Env env = info.Env();
4680
+ NSPasteboardItem* item = DragItemArg(info[0]);
4681
+ if (!item || !info[1].IsString()) return env.Null();
4682
+ NSData* d = [item dataForType:BToNSString(info[1])];
4683
+ if (!d) return env.Null();
4684
+ return Napi::Buffer<uint8_t>::Copy(env, (const uint8_t*)d.bytes, d.length);
4685
+ }
4686
+
4687
+ static Napi::Value DragItemString(const Napi::CallbackInfo& info) {
4688
+ Napi::Env env = info.Env();
4689
+ NSPasteboardItem* item = DragItemArg(info[0]);
4690
+ if (!item || !info[1].IsString()) return env.Null();
4691
+ NSString* s = [item stringForType:BToNSString(info[1])];
4692
+ if (!s) return env.Null();
4693
+ return Napi::String::New(env, s.UTF8String);
4694
+ }
4695
+
4696
+ // beginDrag(win, { x, y, items, provide?, operations?, operationsOutside?,
4697
+ // ignoreModifiers?, slideBack?,
4698
+ // surface | image, imageScale?, imageX?, imageY?,
4699
+ // imageWidth?, imageHeight? }) -> bool
4700
+ // Begin a dragging session from the press in flight. x/y is the press in
4701
+ // the window's content coordinates; the session is begun from the real
4702
+ // mouse-down (or drag) event when the pointer is still down in this window,
4703
+ // which is what a renderer's threshold logic calls from, and from an event
4704
+ // synthesised at x/y otherwise. `operations` is what the source allows
4705
+ // (['copy'] default), `operationsOutside` the same for other applications
4706
+ // when it differs; `ignoreModifiers` stops AppKit turning Option/Command
4707
+ // into copy/link; `slideBack` (default true) animates a refused drop home.
4708
+ // The image sits at imageX/imageY (content coordinates, top-left), centred
4709
+ // on the press by default, at its own size unless imageWidth/imageHeight
4710
+ // say otherwise; with no image the drag shows nothing. Returns whether a
4711
+ // session began. The session runs on AppKit's own tracking from here; JS
4712
+ // hears drag-session-began / -moved / -ended, and the pointer's own
4713
+ // mousemove/mouseup do not arrive while it runs — the ended event is the
4714
+ // release.
4715
+ static Napi::Value BeginDrag(const Napi::CallbackInfo& info) {
4716
+ Napi::Env env = info.Env();
4717
+ CALBackendView* view = BackendViewArg(info[0], "beginDrag");
4718
+ if (!view) return env.Undefined();
4719
+ if (!info[1].IsObject()) {
4720
+ Napi::TypeError::New(env, "beginDrag: expected an options object")
4721
+ .ThrowAsJavaScriptException();
4722
+ return env.Undefined();
4723
+ }
4724
+ Napi::Object o = info[1].As<Napi::Object>();
4725
+ view->env_ = env;
4726
+
4727
+ NSEvent* press = view->lastPress_;
4728
+ if (press && press.window != view.window) press = nil;
4729
+ double x = BNumOr(o, "x", NAN), y = BNumOr(o, "y", NAN);
4730
+ if (std::isnan(x) || std::isnan(y)) {
4731
+ if (!press) {
4732
+ Napi::TypeError::New(env, "beginDrag: x and y are required without a press in flight")
4733
+ .ThrowAsJavaScriptException();
4734
+ return env.Undefined();
4735
+ }
4736
+ NSPoint p = [view convertPoint:press.locationInWindow fromView:nil];
4737
+ x = p.x;
4738
+ y = p.y;
4739
+ }
4740
+ if (!press) {
4741
+ NSPoint wp = [view convertPoint:NSMakePoint(x, y) toView:nil];
4742
+ press = [NSEvent mouseEventWithType:NSEventTypeLeftMouseDown
4743
+ location:wp
4744
+ modifierFlags:0
4745
+ timestamp:NSProcessInfo.processInfo.systemUptime
4746
+ windowNumber:view.window.windowNumber
4747
+ context:nil
4748
+ eventNumber:0
4749
+ clickCount:1
4750
+ pressure:1];
4751
+ }
4752
+
4753
+ CALDragProvider* provider = nil;
4754
+ Napi::Value provide = o.Get("provide");
4755
+ if (provide.IsFunction()) {
4756
+ provider = [[CALDragProvider alloc] init];
4757
+ provider->env_ = env;
4758
+ provider->fn_ = Napi::Persistent(provide.As<Napi::Function>());
4759
+ }
4760
+ NSArray<NSPasteboardItem*>* pbItems =
4761
+ BuildPasteboardItems(env, o.Get("items"), provider);
4762
+ if (provider) provider->items_ = pbItems;
4763
+ if (pbItems.count == 0) {
4764
+ Napi::TypeError::New(env, "beginDrag: items must name at least one item")
4765
+ .ThrowAsJavaScriptException();
4766
+ return env.Undefined();
4767
+ }
4768
+
4769
+ double w = 0, h = 0;
4770
+ NSImage* img = DragImageFrom(o, &w, &h);
4771
+ if (env.IsExceptionPending()) return env.Undefined();
4772
+ if (o.Has("imageWidth")) w = BNumOr(o, "imageWidth", w);
4773
+ if (o.Has("imageHeight")) h = BNumOr(o, "imageHeight", h);
4774
+ double ix = BNumOr(o, "imageX", x - w / 2), iy = BNumOr(o, "imageY", y - h / 2);
4775
+ if (!img) {
4776
+ img = [[NSImage alloc] initWithSize:NSMakeSize(1, 1)];
4777
+ w = h = 1;
4778
+ ix = x;
4779
+ iy = y;
4780
+ }
4781
+ // the view is flipped, so a top-left frame is what setDraggingFrame: takes
4782
+ NSRect frame = NSMakeRect(ix, iy, w, h);
4783
+ NSMutableArray<NSDraggingItem*>* dragItems = [NSMutableArray array];
4784
+ for (NSPasteboardItem* item in pbItems) {
4785
+ NSDraggingItem* di = [[NSDraggingItem alloc] initWithPasteboardWriter:item];
4786
+ [di setDraggingFrame:frame contents:img];
4787
+ [dragItems addObject:di];
4788
+ }
4789
+
4790
+ view->sourceMask_ = DragMaskFrom(o.Get("operations"));
4791
+ view->sourceMaskOutside_ = o.Has("operationsOutside")
4792
+ ? DragMaskFrom(o.Get("operationsOutside"))
4793
+ : view->sourceMask_;
4794
+ view->ignoreModifiers_ = BBoolOr(o, "ignoreModifiers", false);
4795
+ view->dragProvider_ = provider; // alive for as long as the pasteboard may ask
4796
+
4797
+ NSDraggingSession* session = [view beginDraggingSessionWithItems:dragItems
4798
+ event:press
4799
+ source:view];
4800
+ if (!session) return Napi::Boolean::New(env, false);
4801
+ session.animatesToStartingPositionsOnCancelOrFail =
4802
+ BBoolOr(o, "slideBack", true);
4803
+ return Napi::Boolean::New(env, true);
4804
+ }
4805
+
4806
+ // A dragging info of our own, for postDragEvent: what AppKit would build
4807
+ // for a drag from another application, over a private pasteboard.
4808
+ @interface CALPostedDragInfo : NSObject <NSDraggingInfo> {
4809
+ @public
4810
+ NSWindow* window_;
4811
+ NSPasteboard* pasteboard_;
4812
+ NSPoint location_;
4813
+ NSDragOperation mask_;
4814
+ id source_;
4815
+ NSInteger sequence_;
4816
+ NSDraggingFormation formation_;
4817
+ BOOL animates_;
4818
+ NSInteger valid_;
4819
+ }
4820
+ @end
4821
+ @implementation CALPostedDragInfo
4822
+ #pragma clang diagnostic push
4823
+ #pragma clang diagnostic ignored "-Wdeprecated-implementations"
4824
+ - (NSWindow*)draggingDestinationWindow { return window_; }
4825
+ - (NSDragOperation)draggingSourceOperationMask { return mask_; }
4826
+ - (NSPoint)draggingLocation { return location_; }
4827
+ - (NSPoint)draggedImageLocation { return location_; }
4828
+ - (NSImage*)draggedImage { return nil; }
4829
+ - (NSPasteboard*)draggingPasteboard { return pasteboard_; }
4830
+ - (id)draggingSource { return source_; }
4831
+ - (NSInteger)draggingSequenceNumber { return sequence_; }
4832
+ - (void)slideDraggedImageTo:(NSPoint)screenPoint { (void)screenPoint; }
4833
+ - (NSArray<NSString*>*)namesOfPromisedFilesDroppedAtDestination:(NSURL*)url {
4834
+ (void)url;
4835
+ return nil;
4836
+ }
4837
+ #pragma clang diagnostic pop
4838
+ - (NSDraggingFormation)draggingFormation { return formation_; }
4839
+ - (void)setDraggingFormation:(NSDraggingFormation)f { formation_ = f; }
4840
+ - (BOOL)animatesToDestination { return animates_; }
4841
+ - (void)setAnimatesToDestination:(BOOL)a { animates_ = a; }
4842
+ - (NSInteger)numberOfValidItemsForDrop { return valid_; }
4843
+ - (void)setNumberOfValidItemsForDrop:(NSInteger)n { valid_ = n; }
4844
+ - (void)enumerateDraggingItemsWithOptions:(NSDraggingItemEnumerationOptions)opts
4845
+ forView:(NSView*)view
4846
+ classes:(NSArray<Class>*)classes
4847
+ searchOptions:(NSDictionary<NSPasteboardReadingOptionKey, id>*)options
4848
+ usingBlock:(void (^)(NSDraggingItem*, NSInteger, BOOL*))block {
4849
+ (void)opts;
4850
+ (void)view;
4851
+ (void)classes;
4852
+ (void)options;
4853
+ (void)block;
4854
+ }
4855
+ - (NSSpringLoadingHighlight)springLoadingHighlight {
4856
+ return NSSpringLoadingHighlightNone;
4857
+ }
4858
+ - (void)resetSpringLoading {}
4859
+ @end
4860
+
4861
+ // postDragEvent(win, phase, { x, y, items, operations?, local? })
4862
+ // Drive the view's NSDraggingDestination methods with a dragging info of
4863
+ // our own, the way AppKit does for a drag from another application — the
4864
+ // drag-and-drop counterpart of postMouseEvent, for tests. phase 'enter' and
4865
+ // 'over' answer the operation the view returned ('none' when it refused);
4866
+ // 'exit' answers nothing; 'drop' runs prepare + perform + conclude as
4867
+ // AppKit sequences them and answers whether the drop was taken. x/y are
4868
+ // content coordinates, `items` has beginDrag's shape (read on enter, and
4869
+ // again on any later phase that names it), `operations` is the pretend
4870
+ // source's mask (copy default), and `local: true` names this window's own
4871
+ // view as the source.
4872
+ static Napi::Value PostDragEvent(const Napi::CallbackInfo& info) {
4873
+ Napi::Env env = info.Env();
4874
+ CALBackendView* view = BackendViewArg(info[0], "postDragEvent");
4875
+ if (!view) return env.Undefined();
4876
+ view->env_ = env;
4877
+ std::string phase = info[1].IsString() ? info[1].As<Napi::String>().Utf8Value() : "";
4878
+ Napi::Object o = info.Length() > 2 && info[2].IsObject()
4879
+ ? info[2].As<Napi::Object>()
4880
+ : Napi::Object::New(env);
4881
+
4882
+ // one pasteboard per drag: a new one on enter, its contents whatever
4883
+ // `items` the latest phase named (a drag's payload is fixed in AppKit,
4884
+ // but a test may want to say it once, at the drop)
4885
+ static NSInteger sequence = 0;
4886
+ if (phase == "enter" || !gPostedPasteboard) {
4887
+ if (gPostedPasteboard) [gPostedPasteboard releaseGlobally];
4888
+ gPostedPasteboard = [NSPasteboard pasteboardWithUniqueName];
4889
+ sequence++;
4890
+ }
4891
+ if (phase == "enter" || o.Has("items")) {
4892
+ [gPostedPasteboard clearContents];
4893
+ [gPostedPasteboard writeObjects:BuildPasteboardItems(env, o.Get("items"), nil)];
4894
+ }
4895
+ CALPostedDragInfo* di = [[CALPostedDragInfo alloc] init];
4896
+ di->window_ = view.window;
4897
+ di->pasteboard_ = gPostedPasteboard;
4898
+ di->location_ = [view convertPoint:NSMakePoint(BNumOr(o, "x", 0), BNumOr(o, "y", 0)) toView:nil];
4899
+ di->mask_ = DragMaskFrom(o.Get("operations"));
4900
+ di->source_ = BBoolOr(o, "local", false) ? view : nil;
4901
+ di->sequence_ = sequence;
4902
+ di->formation_ = NSDraggingFormationDefault;
4903
+ di->valid_ = (NSInteger)gPostedPasteboard.pasteboardItems.count;
4904
+
4905
+ if (phase == "enter")
4906
+ return Napi::String::New(env, DragOpName([view draggingEntered:di]));
4907
+ if (phase == "over")
4908
+ return Napi::String::New(env, DragOpName([view draggingUpdated:di]));
4909
+ if (phase == "exit") {
4910
+ [view draggingExited:di];
4911
+ return env.Undefined();
4912
+ }
4913
+ if (phase == "drop") {
4914
+ bool taken = [view prepareForDragOperation:di] && [view performDragOperation:di];
4915
+ if (taken && [view respondsToSelector:@selector(concludeDragOperation:)])
4916
+ [view concludeDragOperation:di];
4917
+ return Napi::Boolean::New(env, taken);
4918
+ }
4919
+ Napi::TypeError::New(env, "postDragEvent: phase must be enter | over | exit | drop")
4920
+ .ThrowAsJavaScriptException();
4921
+ return env.Undefined();
4922
+ }
4923
+
4924
+ // pasteboardTypeForMIME(mime) -> UTI — the OS's own MIME <-> UTI table
4925
+ // (UniformTypeIdentifiers), so a renderer's transfer vocabulary maps
4926
+ // through the table Finder and Mail read rather than a copy kept in JS. A
4927
+ // MIME type no declared type claims gets a dynamic identifier (dyn.a…),
4928
+ // which is still a working pasteboard type: it encodes the MIME type, so
4929
+ // any process asking the same question gets the same string.
4930
+ // pasteboardTypeInfo(uti) -> { identifier, mime, extension, description,
4931
+ // dynamic, declared } | null reads the table the other way.
4932
+ static Napi::Value PasteboardTypeForMIME(const Napi::CallbackInfo& info) {
4933
+ Napi::Env env = info.Env();
4934
+ if (!info[0].IsString()) return env.Null();
4935
+ UTType* t = [UTType typeWithMIMEType:BToNSString(info[0])];
4936
+ if (!t) return env.Null();
4937
+ return Napi::String::New(env, t.identifier.UTF8String);
4938
+ }
4939
+
4940
+ static Napi::Value PasteboardTypeInfo(const Napi::CallbackInfo& info) {
4941
+ Napi::Env env = info.Env();
4942
+ if (!info[0].IsString()) return env.Null();
4943
+ UTType* t = [UTType typeWithIdentifier:BToNSString(info[0])];
4944
+ if (!t) return env.Null();
4945
+ Napi::Object r = Napi::Object::New(env);
4946
+ r.Set("identifier", t.identifier.UTF8String);
4947
+ r.Set("mime", t.preferredMIMEType
4948
+ ? Napi::Value(Napi::String::New(env, t.preferredMIMEType.UTF8String))
4949
+ : Napi::Value(env.Null()));
4950
+ r.Set("extension",
4951
+ t.preferredFilenameExtension
4952
+ ? Napi::Value(Napi::String::New(env, t.preferredFilenameExtension.UTF8String))
4953
+ : Napi::Value(env.Null()));
4954
+ r.Set("description",
4955
+ t.localizedDescription
4956
+ ? Napi::Value(Napi::String::New(env, t.localizedDescription.UTF8String))
4957
+ : Napi::Value(env.Null()));
4958
+ r.Set("dynamic", (bool)t.isDynamic);
4959
+ r.Set("declared", (bool)t.isDeclared);
4960
+ return r;
4961
+ }
4962
+
2941
4963
  // ---------------------------------------------------------------------------
2942
4964
  // registration (called from addon.mm's Init)
2943
4965
  // ---------------------------------------------------------------------------
@@ -3028,10 +5050,44 @@ void InitBackend(Napi::Env env, Napi::Object exports) {
3028
5050
  BFN("setMainMenu", SetMainMenuFn);
3029
5051
  BFN("mainMenuInfo", MainMenuInfoFn);
3030
5052
  BFN("activateMenuItem", ActivateMenuItemFn);
5053
+ BFN("createStatusItem", CreateStatusItem);
5054
+ BFN("setStatusItem", SetStatusItem);
5055
+ BFN("setStatusItemMenu", SetStatusItemMenu);
5056
+ BFN("removeStatusItem", RemoveStatusItem);
5057
+ BFN("statusItemInfo", StatusItemInfo);
5058
+ BFN("activateStatusItemMenuItem", ActivateStatusItemMenuItem);
5059
+ BFN("clickStatusItem", ClickStatusItem);
5060
+ BFN("snapshotStatusItem", SnapshotStatusItem);
5061
+ BFN("openPanel", OpenPanelFn);
5062
+ BFN("savePanel", SavePanelFn);
5063
+ BFN("cancelPanel", CancelPanelFn);
5064
+ BFN("contentTypeFor", ContentTypeForFn);
5065
+ BFN("setDockMenu", SetDockMenuFn);
5066
+ BFN("dockMenuInfo", DockMenuInfoFn);
5067
+ BFN("activateDockMenuItem", ActivateDockMenuItemFn);
5068
+ BFN("initApp", InitAppFn);
5069
+ BFN("setActivationPolicy", SetActivationPolicyFn);
5070
+ BFN("setDockBadge", SetDockBadgeFn);
5071
+ BFN("requestUserAttention", RequestUserAttentionFn);
5072
+ BFN("cancelUserAttention", CancelUserAttentionFn);
5073
+ BFN("setAppName", SetAppNameFn);
5074
+ BFN("appInfo", AppInfoFn);
3031
5075
  BFN("measureControl", MeasureControl);
3032
5076
  BFN("drawControlIntoSurface", DrawControlIntoSurface);
3033
5077
  BFN("listScreens", ListScreens);
5078
+ BFN("accessibilityDisplayOptions", AccessibilityDisplayOptionsFn);
5079
+ BFN("postAccessibilityDisplayChange", PostAccessibilityDisplayChange);
3034
5080
  BFN("setCursor", SetCursorFn);
3035
5081
  BFN("postKeyEvent", PostKeyEvent);
5082
+ BFN("postAppleEvent", PostAppleEvent);
5083
+ BFN("registerDropTypes", RegisterDropTypes);
5084
+ BFN("setDropResponse", SetDropResponse);
5085
+ BFN("dragItems", DragItems);
5086
+ BFN("dragItemData", DragItemData);
5087
+ BFN("dragItemString", DragItemString);
5088
+ BFN("beginDrag", BeginDrag);
5089
+ BFN("postDragEvent", PostDragEvent);
5090
+ BFN("pasteboardTypeForMIME", PasteboardTypeForMIME);
5091
+ BFN("pasteboardTypeInfo", PasteboardTypeInfo);
3036
5092
  #undef BFN
3037
5093
  }