@windowkit/appkit 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/backend.mm CHANGED
@@ -1604,6 +1604,22 @@ static CALSurface* SurfaceFrom(Napi::Value v) {
1604
1604
  return s;
1605
1605
  }
1606
1606
 
1607
+ // A 2D surface's bitmap, for video.mm's writeVideoSurface: false, with a
1608
+ // JS error pending, when `v` is not a live surface handle.
1609
+ struct CALSurfaceBits {
1610
+ uint8_t* data;
1611
+ size_t width, height, bytesPerRow;
1612
+ };
1613
+ bool CALSurfaceBitmap(Napi::Value v, CALSurfaceBits* out) {
1614
+ CALSurface* s = SurfaceFrom(v);
1615
+ if (!s) return false;
1616
+ out->data = (uint8_t*)CGBitmapContextGetData(s->ctx);
1617
+ out->width = s->width;
1618
+ out->height = s->height;
1619
+ out->bytesPerRow = CGBitmapContextGetBytesPerRow(s->ctx);
1620
+ return true;
1621
+ }
1622
+
1607
1623
  // For the fire-and-forget drawing verbs: the context to draw into, or a
1608
1624
  // scratch bitmap when the surface is released (the error is already
1609
1625
  // pending; the stroke lands nowhere anyone looks).
@@ -1661,8 +1677,12 @@ static Napi::Value CreateSurface(const Napi::CallbackInfo& info) {
1661
1677
  // A surface this bridge draws into is named sRGB whatever it said before
1662
1678
  // (`keep` false): what is in it is what an sRGB context wrote. One it is
1663
1679
  // only handed to show (setLayerContentsIOSurface — a GL target, another
1664
- // process's buffer) keeps a space its producer named, and is taken to be
1665
- // sRGB, like everything else here, when it names none.
1680
+ // process's buffer, a video frame) keeps a space its producer named, and is
1681
+ // taken to be sRGB, like everything else here, when it names none. A video
1682
+ // frame says what it is the way CoreVideo writes a decoded buffer's
1683
+ // attachments onto its IOSurface — matrix, primaries, transfer function —
1684
+ // and is named the colour space those make (video.mm says why).
1685
+ bool CALNameVideoColorSpace(IOSurfaceRef ios);
1666
1686
  void CALNameSurfaceSRGB(IOSurfaceRef ios, bool keep) {
1667
1687
  static const CFPropertyListRef srgb = [] {
1668
1688
  CGColorSpaceRef cs = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
@@ -1678,6 +1698,8 @@ void CALNameSurfaceSRGB(IOSurfaceRef ios, bool keep) {
1678
1698
  CFRelease(named);
1679
1699
  return;
1680
1700
  }
1701
+ // a video frame's tags, named as the colour space they make (video.mm)
1702
+ if (CALNameVideoColorSpace(ios)) return;
1681
1703
  }
1682
1704
  IOSurfaceSetValue(ios, kIOSurfaceColorSpace, srgb);
1683
1705
  }
@@ -2259,6 +2281,278 @@ static Napi::Value ActivateMenuItemFn(const Napi::CallbackInfo& info) {
2259
2281
  });
2260
2282
  }
2261
2283
 
2284
+ // ---------------------------------------------------------------------------
2285
+ // pop-up menus — a menu that drops from a control in a window, the way an
2286
+ // NSPopUpButton's does: the chosen item placed over the control, the menu
2287
+ // at least the control's width, the current item checked. What a <select>
2288
+ // and a context menu want, and what a drawn menu can only imitate: its
2289
+ // vibrancy needs private API to reproduce, and its tracking (type-select,
2290
+ // the scroll arrows of a long menu, VoiceOver) is AppKit's.
2291
+ //
2292
+ // Run through an NSPopUpButtonCell that is never drawn, which is what a
2293
+ // browser does for a <select>: performClickWithFrame:inView: places and
2294
+ // tracks the menu exactly as the control would, over the frame given, in
2295
+ // the cell's font. Tracking is a modal loop, so the answer is a callback:
2296
+ // in pump mode it runs before the call returns, the thread having been
2297
+ // AppKit's for the length of the gesture; from a worker the menu is opened
2298
+ // from a callout of its own (CALOnUIModal) and answers through a
2299
+ // threadsafe function, and cancelPopUpMenu can end it.
2300
+ // ---------------------------------------------------------------------------
2301
+
2302
+ static Napi::Value BCommandAnswer(Napi::Env env, bool ok);
2303
+
2304
+ // An item's action records the choice rather than emitting `menu-activate`:
2305
+ // a pop-up answers its caller, once, and a dismissal is an answer too.
2306
+ @interface CALPopUpTarget : CALMenuTarget {
2307
+ @public
2308
+ bool picked_;
2309
+ NSInteger chosen_;
2310
+ }
2311
+ @end
2312
+ @implementation CALPopUpTarget
2313
+ - (void)activate:(NSMenuItem*)sender {
2314
+ picked_ = true;
2315
+ chosen_ = sender.tag;
2316
+ }
2317
+ @end
2318
+
2319
+ struct PopUpSpec {
2320
+ std::vector<MenuItemSpec> items;
2321
+ double frame[4] = {0, 0, 0, 0}; // the control: x, y, width, height
2322
+ bool hasSelected = false;
2323
+ NSInteger selected = 0;
2324
+ double fontSize = 0; // 0: the menu font's own size
2325
+ NSString* fontFamily = @""; // a family the system knows, or the menu font
2326
+ NSString* appearance = @""; // "light" | "dark" | "": the window's
2327
+ bool rtl = false;
2328
+ };
2329
+
2330
+ static PopUpSpec ParsePopUpSpec(Napi::Object o) {
2331
+ PopUpSpec s;
2332
+ Napi::Value items = o.Get("items");
2333
+ if (items.IsArray()) s.items = ParseMenuItems(items.As<Napi::Array>());
2334
+ Napi::Value frame = o.Get("frame");
2335
+ if (frame.IsArray()) {
2336
+ Napi::Array a = frame.As<Napi::Array>();
2337
+ for (uint32_t i = 0; i < 4 && i < a.Length(); i++) {
2338
+ Napi::Value v = a.Get(i);
2339
+ if (v.IsNumber()) s.frame[i] = v.As<Napi::Number>().DoubleValue();
2340
+ }
2341
+ }
2342
+ Napi::Value sel = o.Get("selected");
2343
+ if (sel.IsNumber()) {
2344
+ s.hasSelected = true;
2345
+ s.selected = (NSInteger)sel.As<Napi::Number>().Int64Value();
2346
+ }
2347
+ s.fontSize = BNumOr(o, "fontSize", 0);
2348
+ s.fontFamily = BStrOr(o, "fontFamily", @"");
2349
+ s.appearance = BStrOr(o, "appearance", @"");
2350
+ s.rtl = BBoolOr(o, "rtl", false);
2351
+ return s;
2352
+ }
2353
+
2354
+ // The family asked for when the system has it — a face it matched under
2355
+ // another name is not it — and the menu font at that size otherwise.
2356
+ static NSFont* PopUpFont(NSString* family, double size) {
2357
+ CGFloat sz = size > 0 ? size : [NSFont systemFontSize];
2358
+ if (family.length) {
2359
+ NSFontDescriptor* d = [NSFontDescriptor
2360
+ fontDescriptorWithFontAttributes:@{NSFontFamilyAttribute : family}];
2361
+ NSFont* f = [NSFont fontWithDescriptor:d size:sz];
2362
+ if (f && [f.familyName caseInsensitiveCompare:family] == NSOrderedSame) return f;
2363
+ }
2364
+ return [NSFont menuFontOfSize:size > 0 ? size : 0];
2365
+ }
2366
+
2367
+ // What a pop-up owes JS, hung on its menu: pump mode's callback, or a
2368
+ // worker's threadsafe function.
2369
+ @interface CALPopUpPending : NSObject {
2370
+ @public
2371
+ napi_env env_;
2372
+ Napi::FunctionReference cb_;
2373
+ bool threaded_;
2374
+ CALTsfn tsfn_;
2375
+ }
2376
+ @end
2377
+ @implementation CALPopUpPending
2378
+ @end
2379
+
2380
+ static char kPopUpPendingKey;
2381
+
2382
+ // The menu as the spec describes it, and the cell that will run it.
2383
+ static NSPopUpButtonCell* MakePopUp(const PopUpSpec& spec, CALPopUpTarget* target) {
2384
+ NSMenu* menu = BuildMenu(spec.items, target);
2385
+ NSFont* font = PopUpFont(spec.fontFamily, spec.fontSize);
2386
+ menu.font = font;
2387
+ if ([spec.appearance isEqualToString:@"dark"]) {
2388
+ menu.appearance = [NSAppearance appearanceNamed:NSAppearanceNameDarkAqua];
2389
+ } else if ([spec.appearance isEqualToString:@"light"]) {
2390
+ menu.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua];
2391
+ }
2392
+ if (spec.rtl) {
2393
+ menu.userInterfaceLayoutDirection = NSUserInterfaceLayoutDirectionRightToLeft;
2394
+ }
2395
+ NSPopUpButtonCell* cell = [[NSPopUpButtonCell alloc] initTextCell:@"" pullsDown:NO];
2396
+ cell.autoenablesItems = NO;
2397
+ cell.font = font;
2398
+ cell.menu = menu;
2399
+ NSInteger at = spec.hasSelected ? [menu indexOfItemWithTag:spec.selected] : -1;
2400
+ if (at >= 0) [cell selectItemAtIndex:at];
2401
+ else [cell selectItem:nil];
2402
+ return cell;
2403
+ }
2404
+
2405
+ // Track it over the control, on the UI thread, and say what was chosen.
2406
+ static CALValueBlock TrackPopUp(NSPopUpButtonCell* cell, CALPopUpTarget* target,
2407
+ NSWindow* win, const PopUpSpec& spec) {
2408
+ if (win && win.contentView) {
2409
+ NSView* view = win.contentView;
2410
+ double x = spec.frame[0], y = spec.frame[1];
2411
+ double w = spec.frame[2], h = spec.frame[3];
2412
+ // the frame is top-left, as every rect here is
2413
+ NSRect r = NSMakeRect(x, view.isFlipped ? y : view.bounds.size.height - y - h, w, h);
2414
+ [cell attachPopUpWithFrame:r inView:view];
2415
+ [cell performClickWithFrame:r inView:view];
2416
+ [cell dismissPopUp];
2417
+ }
2418
+ bool picked = target->picked_;
2419
+ double chosen = (double)target->chosen_;
2420
+ return ^Napi::Value(Napi::Env e) {
2421
+ return picked ? Napi::Value(Napi::Number::New(e, chosen)) : Napi::Value(e.Null());
2422
+ };
2423
+ }
2424
+
2425
+ // The one place a pop-up answers; the pending record comes off first.
2426
+ static void FinishPopUp(NSMenu* menu, CALValueBlock answer) {
2427
+ CALPopUpPending* p = objc_getAssociatedObject(menu, &kPopUpPendingKey);
2428
+ if (!p) return;
2429
+ objc_setAssociatedObject(menu, &kPopUpPendingKey, nil,
2430
+ OBJC_ASSOCIATION_RETAIN_NONATOMIC);
2431
+ if (p->threaded_) {
2432
+ CALReply(p->tsfn_, answer);
2433
+ return;
2434
+ }
2435
+ Napi::Env env(p->env_);
2436
+ Napi::HandleScope scope(env);
2437
+ Napi::Value result = answer(env);
2438
+ Napi::FunctionReference cb = std::move(p->cb_);
2439
+ cb.Call({result});
2440
+ }
2441
+
2442
+ // popUpMenu(win, spec, cb) -> menu handle
2443
+ // spec: { items, // setMainMenu's item vocabulary
2444
+ // frame: [x, y, w, h], // the control, in the window's content,
2445
+ // // top-left, points
2446
+ // selected?, // the id placed over the control, checked
2447
+ // fontSize?, fontFamily?,// the menu's font; the menu font otherwise
2448
+ // appearance?: 'light' | 'dark', rtl? }
2449
+ // cb(id | null) — the item chosen, or null for a menu dismissed
2450
+ static Napi::Value PopUpMenuFn(const Napi::CallbackInfo& info) {
2451
+ Napi::Env env = info.Env();
2452
+ if (!info[0].IsExternal() || !info[1].IsObject() || !info[2].IsFunction()) {
2453
+ Napi::TypeError::New(env, "popUpMenu(win, spec, cb): window handle, spec object and callback required")
2454
+ .ThrowAsJavaScriptException();
2455
+ return env.Undefined();
2456
+ }
2457
+ id owner = CALHandleTarget(info[0]);
2458
+ PopUpSpec spec = ParsePopUpSpec(info[1].As<Napi::Object>());
2459
+
2460
+ if (pthread_main_np()) {
2461
+ BEnsureApp();
2462
+ CALPopUpTarget* target = [CALPopUpTarget new];
2463
+ target->source_ = "popup";
2464
+ NSPopUpButtonCell* cell = MakePopUp(spec, target);
2465
+ CALPopUpPending* p = [CALPopUpPending new];
2466
+ p->env_ = (napi_env)env;
2467
+ p->cb_ = Napi::Persistent(info[2].As<Napi::Function>());
2468
+ p->threaded_ = false;
2469
+ objc_setAssociatedObject(cell.menu, &kPopUpPendingKey, p,
2470
+ OBJC_ASSOCIATION_RETAIN_NONATOMIC);
2471
+ Napi::Value handle = BWrapRetained(env, cell.menu);
2472
+ FinishPopUp(cell.menu, TrackPopUp(cell, target, owner ? CALResolve(owner) : nil, spec));
2473
+ return handle;
2474
+ }
2475
+
2476
+ CALHandle* h = CALNewHandle();
2477
+ Napi::Value handle = CALWrapHandle(env, h, false);
2478
+ CALTsfn tsfn = CALReplyTo(env, info[2].As<Napi::Function>(), "appkit:popUpMenu");
2479
+ CALOnUIModal(^{
2480
+ BEnsureApp();
2481
+ CALPopUpTarget* target = [CALPopUpTarget new];
2482
+ target->source_ = "popup";
2483
+ NSPopUpButtonCell* cell = MakePopUp(spec, target);
2484
+ CALPopUpPending* p = [CALPopUpPending new];
2485
+ p->threaded_ = true;
2486
+ p->tsfn_ = tsfn;
2487
+ objc_setAssociatedObject(cell.menu, &kPopUpPendingKey, p,
2488
+ OBJC_ASSOCIATION_RETAIN_NONATOMIC);
2489
+ h->object_ = cell.menu;
2490
+ FinishPopUp(cell.menu, TrackPopUp(cell, target, owner ? CALResolve(owner) : nil, spec));
2491
+ });
2492
+ return handle;
2493
+ }
2494
+
2495
+ // cancelPopUpMenu(menu) -> bool — end the tracking: the pop-up answers null.
2496
+ // A pop-up that has answered already is left alone.
2497
+ static Napi::Value CancelPopUpMenuFn(const Napi::CallbackInfo& info) {
2498
+ Napi::Env env = info.Env();
2499
+ if (!info[0].IsExternal()) {
2500
+ Napi::TypeError::New(env, "cancelPopUpMenu: menu handle required")
2501
+ .ThrowAsJavaScriptException();
2502
+ return env.Undefined();
2503
+ }
2504
+ id target = CALHandleTarget(info[0]);
2505
+ __block bool ok = false;
2506
+ CALOnUI(^{
2507
+ NSMenu* menu = CALResolve(target);
2508
+ if (!menu || !objc_getAssociatedObject(menu, &kPopUpPendingKey)) return;
2509
+ [menu cancelTrackingWithoutAnimation];
2510
+ ok = true;
2511
+ });
2512
+ return BCommandAnswer(env, ok);
2513
+ }
2514
+
2515
+ // popUpMenuInfo(menu, cb?) — an open pop-up as data, for tests: the tree in
2516
+ // mainMenuInfo's shape, its font and its appearance; null once it answered.
2517
+ static Napi::Value PopUpMenuInfoFn(const Napi::CallbackInfo& info) {
2518
+ id target = CALHandleTarget(info[0]);
2519
+ return CALAnswer(info, "popUpMenuInfo", ^CALValueBlock {
2520
+ NSMenu* menu = CALResolve(target);
2521
+ if (!menu || !objc_getAssociatedObject(menu, &kPopUpPendingKey)) {
2522
+ return ^Napi::Value(Napi::Env e) { return e.Null(); };
2523
+ }
2524
+ std::shared_ptr<MenuInfoData> data = MenuInfoOf(menu);
2525
+ std::string family = menu.font.familyName.UTF8String ?: "";
2526
+ double size = menu.font.pointSize;
2527
+ std::string appearance = menu.appearance.name.UTF8String ?: "";
2528
+ bool rtl = menu.userInterfaceLayoutDirection == NSUserInterfaceLayoutDirectionRightToLeft;
2529
+ return ^Napi::Value(Napi::Env e) {
2530
+ Napi::Object o = MenuInfoValue(e, *data);
2531
+ o.Set("fontFamily", family);
2532
+ o.Set("fontSize", size);
2533
+ o.Set("appearance", appearance);
2534
+ o.Set("rtl", rtl);
2535
+ return o;
2536
+ };
2537
+ });
2538
+ }
2539
+
2540
+ // activatePopUpMenuItem(menu, index, cb?) -> bool — choose an open pop-up's
2541
+ // item by index, the way tracking would, and end the tracking. For tests.
2542
+ static Napi::Value ActivatePopUpMenuItemFn(const Napi::CallbackInfo& info) {
2543
+ id target = CALHandleTarget(info[0]);
2544
+ NSInteger index = info.Length() > 1 && info[1].IsNumber()
2545
+ ? (NSInteger)info[1].As<Napi::Number>().Int64Value()
2546
+ : -1;
2547
+ return CALAnswer(info, "activatePopUpMenuItem", ^CALValueBlock {
2548
+ NSMenu* menu = CALResolve(target);
2549
+ bool ok = menu && objc_getAssociatedObject(menu, &kPopUpPendingKey) &&
2550
+ ActivateInMenu(menu, {index});
2551
+ if (ok) [menu cancelTrackingWithoutAnimation];
2552
+ return BoolAnswer(ok);
2553
+ });
2554
+ }
2555
+
2262
2556
  // ---------------------------------------------------------------------------
2263
2557
  // status items — NSStatusItem, the menu-bar extra (the "tray"). The cocoa
2264
2558
  // counterpart of the freedesktop StatusNotifierItem: an icon or a title in
@@ -4377,7 +4671,60 @@ static NSFontWeight FontWeightFromCss(double weight) {
4377
4671
  return NSFontWeightBlack;
4378
4672
  }
4379
4673
 
4380
- // matchFont({ families: [..], size, weight (100-900), italic }) -> font handle
4674
+ // --- a font at a display's scale ---------------------------------------------
4675
+ //
4676
+ // A size here is in the caller's pixels, and on a Retina display those are
4677
+ // device pixels: a 13px label is 26. A font made at 26 is a 26pt font to
4678
+ // CoreText, which reads some of a face's data by point size — the optical
4679
+ // size and tracking San Francisco is set at, the tracking Apple Color Emoji's
4680
+ // trak table adds below 29pt — so the label was set as SF is at 26pt, 8%
4681
+ // narrower than AppKit sets it at 13, and a 19px emoji was 1em wide where it
4682
+ // is 23pt at 19pt. Faces with no such data measure the same either way.
4683
+ //
4684
+ // So a font may be made at a `scale`: at size / scale points, under a matrix
4685
+ // that scales it by `scale`. CoreText reads the face at its point size and
4686
+ // answers in the caller's pixels — metrics, advances, bounds, a line's width,
4687
+ // a caret's offset — through the matrix. Two things it does not take through
4688
+ // it, and every reader of them here goes through the helpers below: a run's
4689
+ // glyph origins, which are in text space, before the font matrix
4690
+ // (BRunPositions); and a bitmap glyph, which CoreText draws at the font's
4691
+ // point size whatever its matrix (BDrawGlyphsAtScale). A copy of a scaled
4692
+ // font — another size, variations, features, a fallback face — keeps the
4693
+ // scale. A font made without one has the identity matrix, and nothing here
4694
+ // changes for it.
4695
+
4696
+ /** The scale a font was made at: its matrix's, or 1. */
4697
+ static double BFontScale(CTFontRef font) {
4698
+ if (!font) return 1;
4699
+ const CGAffineTransform m = CTFontGetMatrix(font);
4700
+ return m.a > 0 && m.a == m.d && m.b == 0 && m.c == 0 && m.tx == 0 &&
4701
+ m.ty == 0
4702
+ ? m.a
4703
+ : 1;
4704
+ }
4705
+
4706
+ /** A scale argument: a finite number above 0, else 1. */
4707
+ static double BScaleOf(Napi::Value v) {
4708
+ if (!v.IsNumber()) return 1;
4709
+ const double scale = v.As<Napi::Number>().DoubleValue();
4710
+ return scale > 0 && std::isfinite(scale) ? scale : 1;
4711
+ }
4712
+
4713
+ /** `font` (owned, released) as the same face under the matrix of `scale`,
4714
+ * at the point size it already has. */
4715
+ static CTFontRef BAtScale(CTFontRef font, double scale) {
4716
+ if (!font || scale == 1) return font;
4717
+ const CGAffineTransform m = CGAffineTransformMakeScale(scale, scale);
4718
+ CTFontRef scaled = CTFontCreateCopyWithAttributes(font, 0, &m, NULL);
4719
+ if (!scaled) return font;
4720
+ CFRelease(font);
4721
+ return scaled;
4722
+ }
4723
+
4724
+ // matchFont({ families: [..], size, weight (100-900), italic, scale? })
4725
+ // -> font handle
4726
+ // `size` is in the caller's pixels; `scale`, the display's, makes the font
4727
+ // at size / scale points under a matrix of `scale` (see above).
4381
4728
  static NSFont* ResolveFamily(NSString* family, double size, double weight,
4382
4729
  bool italic) {
4383
4730
  NSFontWeight w = FontWeightFromCss(weight);
@@ -4439,7 +4786,8 @@ static NSFont* ResolveFamily(NSString* family, double size, double weight,
4439
4786
  static Napi::Value MatchFont(const Napi::CallbackInfo& info) {
4440
4787
  Napi::Env env = info.Env();
4441
4788
  Napi::Object o = info[0].As<Napi::Object>();
4442
- double size = BNumOr(o, "size", 14);
4789
+ const double scale = BScaleOf(o.Get("scale"));
4790
+ double size = BNumOr(o, "size", 14) / scale;
4443
4791
  double weight = BNumOr(o, "weight", 400);
4444
4792
  bool italic = BBoolOr(o, "italic", false);
4445
4793
  NSFont* font = nil;
@@ -4454,9 +4802,18 @@ static Napi::Value MatchFont(const Napi::CallbackInfo& info) {
4454
4802
  NSFontWeight w = weight >= 550 ? NSFontWeightSemibold : NSFontWeightRegular;
4455
4803
  font = [NSFont systemFontOfSize:size weight:w];
4456
4804
  }
4805
+ if (scale != 1 && font) {
4806
+ CTFontRef scaled =
4807
+ BAtScale((CTFontRef)CFBridgingRetain(font), scale);
4808
+ font = (__bridge_transfer NSFont*)scaled;
4809
+ }
4457
4810
  return BWrapRetained(env, font);
4458
4811
  }
4459
4812
 
4813
+ // fontMetrics(font) -> { ascent, descent, leading, capHeight, xHeight, size,
4814
+ // familyName, postScriptName }
4815
+ // In the caller's pixels, a scaled font's included: `size` is the one the
4816
+ // font was asked for.
4460
4817
  static Napi::Value FontMetrics(const Napi::CallbackInfo& info) {
4461
4818
  Napi::Env env = info.Env();
4462
4819
  NSFont* font = BDeref<NSFont*>(info[0]);
@@ -4467,7 +4824,7 @@ static Napi::Value FontMetrics(const Napi::CallbackInfo& info) {
4467
4824
  r.Set("leading", CTFontGetLeading(ct));
4468
4825
  r.Set("capHeight", CTFontGetCapHeight(ct));
4469
4826
  r.Set("xHeight", CTFontGetXHeight(ct));
4470
- r.Set("size", CTFontGetSize(ct));
4827
+ r.Set("size", CTFontGetSize(ct) * BFontScale(ct));
4471
4828
  r.Set("familyName", font.familyName ? font.familyName.UTF8String : "");
4472
4829
  r.Set("postScriptName", font.fontName.UTF8String);
4473
4830
  return r;
@@ -4511,6 +4868,71 @@ static bool BCheckFontArg(const Napi::CallbackInfo& info, const char* fn) {
4511
4868
  return false;
4512
4869
  }
4513
4870
 
4871
+ static CTFontRef BRunFont(CTRunRef run) {
4872
+ return (CTFontRef)CFDictionaryGetValue(CTRunGetAttributes(run),
4873
+ kCTFontAttributeName);
4874
+ }
4875
+
4876
+ // A run's glyph origins from its line's origin, y up, in the caller's pixels.
4877
+ // CTRunGetPositions answers in text space, before the font matrix, where
4878
+ // everything else CoreText measures of a scaled font has the matrix applied;
4879
+ // so a scaled run's origins are multiplied by its scale here. A line set in
4880
+ // faces of one scale, which is every line a caller makes, is in one space.
4881
+ static void BRunPositions(CTRunRef run, std::vector<CGPoint>* out) {
4882
+ const CFIndex count = CTRunGetGlyphCount(run);
4883
+ out->resize(count > 0 ? (size_t)count : 0);
4884
+ if (count <= 0) return;
4885
+ CTRunGetPositions(run, CFRangeMake(0, 0), out->data());
4886
+ const double scale = BFontScale(BRunFont(run));
4887
+ if (scale == 1) return;
4888
+ for (CGPoint& p : *out) {
4889
+ p.x *= scale;
4890
+ p.y *= scale;
4891
+ }
4892
+ }
4893
+
4894
+ // A scaled font as its point-size face: the same font with the identity
4895
+ // matrix. Kept, because a terminal draws its runs every frame. +1.
4896
+ static CTFontRef BAtPointSize(CTFontRef font) {
4897
+ static NSCache* kept = [[NSCache alloc] init];
4898
+ id key = (__bridge id)font;
4899
+ id hit = [kept objectForKey:key];
4900
+ if (!hit) {
4901
+ const CGAffineTransform identity = CGAffineTransformIdentity;
4902
+ CTFontRef plain = CTFontCreateCopyWithAttributes(font, 0, &identity, NULL);
4903
+ if (!plain) return (CTFontRef)CFRetain(font);
4904
+ hit = (__bridge_transfer id)plain;
4905
+ [kept setObject:hit forKey:key];
4906
+ }
4907
+ return (CTFontRef)CFBridgingRetain(hit);
4908
+ }
4909
+
4910
+ // A scaled font's glyphs drawn the way AppKit draws text to a Retina backing
4911
+ // store: the face at its point size, under a CTM scaled by the scale. Drawn
4912
+ // through the font's matrix instead, an outline came out right and a bitmap
4913
+ // glyph — Apple Color Emoji's — at the font's point size, so an emoji was
4914
+ // half its size at 2x. `origins` are from `at`, in the caller's pixels, y up,
4915
+ // as BRunPositions answers them; `at` is in the context's user space, and the
4916
+ // text matrix is the y-flip every draw here sets.
4917
+ static void BDrawGlyphsAtScale(CGContextRef ctx, CTFontRef font,
4918
+ const CGGlyph* glyphs, const CGPoint* origins,
4919
+ size_t count, CGPoint at) {
4920
+ if (count == 0) return;
4921
+ const double scale = BFontScale(font);
4922
+ std::vector<CGPoint> points(count);
4923
+ for (size_t i = 0; i < count; i++) {
4924
+ points[i] = CGPointMake(origins[i].x / scale, origins[i].y / scale);
4925
+ }
4926
+ CTFontRef plain = BAtPointSize(font);
4927
+ CGContextSaveGState(ctx);
4928
+ CGContextTranslateCTM(ctx, at.x, at.y);
4929
+ CGContextScaleCTM(ctx, scale, scale);
4930
+ CGContextSetTextMatrix(ctx, CGAffineTransformMakeScale(1, -1));
4931
+ CTFontDrawGlyphs(plain, glyphs, points.data(), (CFIndex)count, ctx);
4932
+ CGContextRestoreGState(ctx);
4933
+ CFRelease(plain);
4934
+ }
4935
+
4514
4936
  // One code point -> its UTF-16 form. False for a surrogate or an
4515
4937
  // out-of-range value.
4516
4938
  static bool BUtf16ForCodepoint(uint32_t cp, unichar out[2], CFIndex* len) {
@@ -4755,7 +5177,8 @@ static Napi::Value FontFallbackFor(const Napi::CallbackInfo& info) {
4755
5177
  // substitution — fontFallbackFor's answer, a fontShapeText run's font — has
4756
5178
  // no family to re-match by, and asking the cascade again at the new size is
4757
5179
  // a different question with a possibly different answer. This is how such a
4758
- // face answers metrics and advances at every size, as itself.
5180
+ // face answers metrics and advances at every size, as itself. `size` is in
5181
+ // the caller's pixels, and a scaled font's copy keeps its scale.
4759
5182
  static Napi::Value FontWithSize(const Napi::CallbackInfo& info) {
4760
5183
  Napi::Env env = info.Env();
4761
5184
  if (!BCheckFontArg(info, "fontWithSize")) return env.Undefined();
@@ -4765,8 +5188,11 @@ static Napi::Value FontWithSize(const Napi::CallbackInfo& info) {
4765
5188
  .ThrowAsJavaScriptException();
4766
5189
  return env.Undefined();
4767
5190
  }
4768
- CTFontRef sized = CTFontCreateCopyWithAttributes(BFontFrom(info[0]),
4769
- (CGFloat)size, NULL, NULL);
5191
+ CTFontRef font = BFontFrom(info[0]);
5192
+ const double scale = BFontScale(font);
5193
+ const CGAffineTransform m = CGAffineTransformMakeScale(scale, scale);
5194
+ CTFontRef sized =
5195
+ CTFontCreateCopyWithAttributes(font, (CGFloat)(size / scale), &m, NULL);
4770
5196
  if (!sized) return env.Null();
4771
5197
  return Napi::External<void>::New(env, (void*)sized, [](Napi::Env, void* d) {
4772
5198
  CFRelease(d);
@@ -4822,7 +5248,7 @@ static Napi::Value FontShapeText(const Napi::CallbackInfo& info) {
4822
5248
  std::vector<CGPoint> positions((size_t)count);
4823
5249
  std::vector<CGSize> advances((size_t)count);
4824
5250
  CTRunGetGlyphs(run, CFRangeMake(0, 0), glyphs.data());
4825
- CTRunGetPositions(run, CFRangeMake(0, 0), positions.data());
5251
+ BRunPositions(run, &positions);
4826
5252
  CTRunGetAdvances(run, CFRangeMake(0, 0), advances.data());
4827
5253
  CFDictionaryRef rattrs = CTRunGetAttributes(run);
4828
5254
  CTFontRef rfont =
@@ -4920,27 +5346,33 @@ static Napi::Value FontFromData(const Napi::CallbackInfo& info) {
4920
5346
  return r;
4921
5347
  }
4922
5348
 
4923
- // cgFontWithSize(cgExternal, size) -> CTFont handle (what layouts take)
5349
+ // cgFontWithSize(cgExternal, size, scale?) -> CTFont handle (what layouts
5350
+ // take), at a scale as matchFont makes one
4924
5351
  static Napi::Value CgFontWithSize(const Napi::CallbackInfo& info) {
4925
5352
  Napi::Env env = info.Env();
4926
5353
  CGFontRef cg = (CGFontRef)info[0].As<Napi::External<void>>().Data();
4927
5354
  double size = info[1].As<Napi::Number>().DoubleValue();
4928
- CTFontRef ct = CTFontCreateWithGraphicsFont(cg, size, NULL, NULL);
5355
+ const double scale = BScaleOf(info[2]);
5356
+ const CGAffineTransform m = CGAffineTransformMakeScale(scale, scale);
5357
+ CTFontRef ct = CTFontCreateWithGraphicsFont(cg, size / scale,
5358
+ scale == 1 ? NULL : &m, NULL);
4929
5359
  if (!ct) return env.Null();
4930
5360
  return Napi::External<void>::New(env, (void*)ct, [](Napi::Env, void* d) {
4931
5361
  CFRelease(d);
4932
5362
  });
4933
5363
  }
4934
5364
 
4935
- // fontByPostScriptName(name, size) -> CTFont handle or null. Exact: a
4936
- // fallback answer (a substituted face) reads as null so the caller can try
4937
- // the next route.
5365
+ // fontByPostScriptName(name, size, scale?) -> CTFont handle or null, at a
5366
+ // scale as matchFont makes one. Exact: a fallback answer (a substituted
5367
+ // face) reads as null so the caller can try the next route.
4938
5368
  static Napi::Value FontByPostScriptName(const Napi::CallbackInfo& info) {
4939
5369
  Napi::Env env = info.Env();
4940
5370
  NSString* name = BToNSString(info[0]);
4941
5371
  double size = info[1].As<Napi::Number>().DoubleValue();
4942
- CTFontRef ct =
4943
- CTFontCreateWithName((__bridge CFStringRef)name, size, NULL);
5372
+ const double scale = BScaleOf(info[2]);
5373
+ const CGAffineTransform m = CGAffineTransformMakeScale(scale, scale);
5374
+ CTFontRef ct = CTFontCreateWithName((__bridge CFStringRef)name,
5375
+ size / scale, scale == 1 ? NULL : &m);
4944
5376
  if (!ct) return env.Null();
4945
5377
  CFStringRef got = CTFontCopyPostScriptName(ct);
4946
5378
  bool exact = got && [(__bridge NSString*)got isEqualToString:name];
@@ -5132,6 +5564,9 @@ struct CALLine {
5132
5564
  descent = 0;
5133
5565
  long start = 0, end = 0; // UTF-16 units
5134
5566
  bool hardBreak = false; // the line ends with a newline it owns
5567
+ // a run of bitmap glyphs in a scaled face, which drawLayout draws apart
5568
+ // (BDrawGlyphsAtScale)
5569
+ bool bitmapsAtScale = false;
5135
5570
  std::vector<CALRun> runs;
5136
5571
  };
5137
5572
 
@@ -5473,6 +5908,14 @@ static Napi::Value CreateLayout(const Napi::CallbackInfo& info) {
5473
5908
  CTRunGetPositions(run, CFRangeMake(0, 1), &first);
5474
5909
  rx = first.x;
5475
5910
  }
5911
+ // in text space, before a scaled face's matrix (BRunPositions)
5912
+ CTFontRef rfont = BRunFont(run);
5913
+ const double rscale = BFontScale(rfont);
5914
+ rx *= rscale;
5915
+ if (rscale != 1 &&
5916
+ (CTFontGetSymbolicTraits(rfont) & kCTFontTraitColorGlyphs)) {
5917
+ L.bitmapsAtScale = true;
5918
+ }
5476
5919
  }
5477
5920
  CALRun R;
5478
5921
  R.x = rx;
@@ -5583,9 +6026,40 @@ static Napi::Value DrawLayout(const Napi::CallbackInfo& info) {
5583
6026
  // per glyph run. Standard recipe: flip the text matrix, position each
5584
6027
  // line at its baseline in the flipped space.
5585
6028
  CGContextSetTextMatrix(ctx, CGAffineTransformMakeScale(1, -1));
6029
+ std::vector<CGPoint> positions;
5586
6030
  for (const CALLine& L : layout->lines) {
5587
- CGContextSetTextPosition(ctx, x + L.x, y + L.baseline);
5588
- CTLineDraw(L.line, ctx);
6031
+ if (!L.bitmapsAtScale) {
6032
+ CGContextSetTextPosition(ctx, x + L.x, y + L.baseline);
6033
+ CTLineDraw(L.line, ctx);
6034
+ continue;
6035
+ }
6036
+ // a line with a scaled face's bitmap glyphs in it is drawn a run at a
6037
+ // time, and a scaled run at its face's point size under a scaled CTM:
6038
+ // CTRunDraw, unlike CTLineDraw, does not draw through the font matrix
6039
+ // either, outlines included
6040
+ CFArrayRef runs = CTLineGetGlyphRuns(L.line);
6041
+ for (CFIndex ri = 0; ri < CFArrayGetCount(runs); ri++) {
6042
+ CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runs, ri);
6043
+ CTFontRef font = BRunFont(run);
6044
+ if (!font || BFontScale(font) == 1) {
6045
+ CGContextSetTextPosition(ctx, x + L.x, y + L.baseline);
6046
+ CTRunDraw(run, ctx, CFRangeMake(0, 0));
6047
+ continue;
6048
+ }
6049
+ const CFIndex count = CTRunGetGlyphCount(run);
6050
+ if (count <= 0) continue;
6051
+ std::vector<CGGlyph> glyphs((size_t)count);
6052
+ CTRunGetGlyphs(run, CFRangeMake(0, 0), glyphs.data());
6053
+ BRunPositions(run, &positions);
6054
+ CGContextSaveGState(ctx);
6055
+ CGColorRef ink = (CGColorRef)CFDictionaryGetValue(
6056
+ CTRunGetAttributes(run), kCTForegroundColorAttributeName);
6057
+ if (ink) CGContextSetFillColorWithColor(ctx, ink);
6058
+ BDrawGlyphsAtScale(ctx, font, glyphs.data(), positions.data(),
6059
+ (size_t)count,
6060
+ CGPointMake(x + L.x, y + L.baseline));
6061
+ CGContextRestoreGState(ctx);
6062
+ }
5589
6063
  }
5590
6064
  CGContextRestoreGState(ctx);
5591
6065
  return info.Env().Undefined();
@@ -5625,8 +6099,14 @@ static Napi::Value CtxDrawGlyphs(const Napi::CallbackInfo& info) {
5625
6099
  BGlyphOriginsArg(run.Get("positions"), &positionStore);
5626
6100
  size_t count = std::min(nGlyphs, positionStore.size());
5627
6101
  if (count == 0) continue;
5628
- CTFontDrawGlyphs(BFontFrom(fv), glyphs, positionStore.data(),
5629
- (CFIndex)count, ctx);
6102
+ CTFontRef font = BFontFrom(fv);
6103
+ if (BFontScale(font) != 1) {
6104
+ // the origins are the caller's pixels, in text space through the flip
6105
+ BDrawGlyphsAtScale(ctx, font, glyphs, positionStore.data(), count,
6106
+ CGPointZero);
6107
+ continue;
6108
+ }
6109
+ CTFontDrawGlyphs(font, glyphs, positionStore.data(), (CFIndex)count, ctx);
5630
6110
  }
5631
6111
  CGContextRestoreGState(ctx);
5632
6112
  return info.Env().Undefined();
@@ -5788,7 +6268,7 @@ static Napi::Value DrawLayoutGradient(const Napi::CallbackInfo& info) {
5788
6268
  std::vector<CGGlyph> glyphs((size_t)count);
5789
6269
  std::vector<CGPoint> positions((size_t)count);
5790
6270
  CTRunGetGlyphs(run, CFRangeMake(0, 0), glyphs.data());
5791
- CTRunGetPositions(run, CFRangeMake(0, 0), positions.data());
6271
+ BRunPositions(run, &positions);
5792
6272
  for (CFIndex g = 0; g < count; g++) {
5793
6273
  CGAffineTransform t = {1, 0, 0, -1,
5794
6274
  x + L.x + positions[(size_t)g].x,
@@ -6061,7 +6541,7 @@ static Napi::Value LayoutCoverage(const Napi::CallbackInfo& info) {
6061
6541
  glyphs.resize((size_t)count);
6062
6542
  positions.resize((size_t)count);
6063
6543
  CTRunGetGlyphs(run, CFRangeMake(0, 0), glyphs.data());
6064
- CTRunGetPositions(run, CFRangeMake(0, 0), positions.data());
6544
+ BRunPositions(run, &positions);
6065
6545
  for (size_t g = 0; g < (size_t)count; g++) {
6066
6546
  // a glyph shaping deleted, such as a ligature's second half
6067
6547
  if (glyphs[g] == kCGFontIndexInvalid) continue;
@@ -6106,6 +6586,11 @@ static Napi::Value LayoutCoverage(const Napi::CallbackInfo& info) {
6106
6586
  CGContextSetGrayFillColor(ctx, 0, 1);
6107
6587
  CGContextSetTextMatrix(ctx, CGAffineTransformMakeScale(1, -1));
6108
6588
  for (const DrawnGlyph& d : drawn) {
6589
+ if (BFontScale(d.font) != 1) {
6590
+ const CGPoint here = CGPointZero;
6591
+ BDrawGlyphsAtScale(ctx, d.font, &d.glyph, &here, 1, d.origin);
6592
+ continue;
6593
+ }
6109
6594
  // CTFontDrawGlyphs reads positions in text space, through the flip
6110
6595
  const CGPoint at = CGPointMake(d.origin.x, -d.origin.y);
6111
6596
  CTFontDrawGlyphs(d.font, &d.glyph, &at, 1, ctx);
@@ -7367,6 +7852,10 @@ void InitBackend(Napi::Env env, Napi::Object exports) {
7367
7852
  BFN("setDockMenu", SetDockMenuFn);
7368
7853
  BFN("dockMenuInfo", DockMenuInfoFn);
7369
7854
  BFN("activateDockMenuItem", ActivateDockMenuItemFn);
7855
+ BFN("popUpMenu", PopUpMenuFn);
7856
+ BFN("cancelPopUpMenu", CancelPopUpMenuFn);
7857
+ BFN("popUpMenuInfo", PopUpMenuInfoFn);
7858
+ BFN("activatePopUpMenuItem", ActivatePopUpMenuItemFn);
7370
7859
  BFN("initApp", InitAppFn);
7371
7860
  BFN("setActivationPolicy", SetActivationPolicyFn);
7372
7861
  BFN("setDockBadge", SetDockBadgeFn);