@geastack/apple 0.2.33 → 0.2.35

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.
@@ -18,7 +18,9 @@
18
18
  #include "press_bridge.h"
19
19
 
20
20
  #include "ui/tree_internal.h"
21
+ #include "ui/internal.h"
21
22
  #include "ui/node_model.h"
23
+ #include "ui/style_values.h"
22
24
 
23
25
  #include "events.h"
24
26
 
@@ -126,8 +128,11 @@ static void geaRetireNativeView(NSView *view) {
126
128
  const NSRect measured = [self.attributedStringValue boundingRectWithSize:NSMakeSize(content.size.width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading];
127
129
  content.origin.y += std::max<CGFloat>(0, (content.size.height - measured.size.height) / 2);
128
130
  }
129
- [self.attributedStringValue drawWithRect:content
130
- options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading];
131
+ // `text-overflow: ellipsis` (applyTextProps sets truncatesLastVisibleLine):
132
+ // the truncating-tail paragraph only cuts with "…" when drawing asks for it.
133
+ NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
134
+ if (self.truncatesLastVisibleLine) options |= NSStringDrawingTruncatesLastVisibleLine;
135
+ [self.attributedStringValue drawWithRect:content options:options];
131
136
  }
132
137
  @end
133
138
 
@@ -557,7 +562,9 @@ static void geaEmitRootCancellation(const gea::embedded::ui::NodeHandle &owner,i
557
562
  auto &inputTree=gea::embedded::ui::Tree::instance();
558
563
  for(int i=0;i<inputTree.nodeCount();++i)if(std::strcmp(inputTree.getAttribute(i,"data-gea-inputs"),"true")==0){customInputs=true;break;}
559
564
  if(customInputs)[root.window makeFirstResponder:root];
560
- else if(root.window.firstResponder!=root.window)[root.window makeFirstResponder:nil];
565
+ // The root keeps the keyboard (Escape, arrows, shortcuts reach the app's
566
+ // key listeners); a root that takes no keys hands it to the window.
567
+ else if(root.window.firstResponder!=root)[root.window makeFirstResponder:[root acceptsFirstResponder]?root:nil];
561
568
 
562
569
  // Mouse-down: hit-test now, remember the node so the move and up
563
570
  // phases dispatch to the same target even if the cursor drifts.
@@ -1359,6 +1366,8 @@ CGColorRef createStyleCGColor(gea::embedded::ui::style_color_t color, uint8_t al
1359
1366
  return faded;
1360
1367
  }
1361
1368
 
1369
+ bool needsEdgeBorders(const gea::embedded::ui::ComputedStyle &style);
1370
+
1362
1371
  // border-radius. Uniform circular radii stay on layer.cornerRadius (the cheap
1363
1372
  // path every already-correct app takes); elliptical or per-corner radii get a
1364
1373
  // CAShapeLayer, because cornerRadius is one scalar and physically cannot say
@@ -1368,7 +1377,9 @@ void applyCornerRadius(NSView *view, const gea::embedded::ui::Node &node, CGFloa
1368
1377
  bool blurred)
1369
1378
  {
1370
1379
  const ResolvedRadii radii = resolveRadii(node, w, h);
1371
- const CGFloat borderWidth = static_cast<CGFloat>(std::max(0, static_cast<int>(node.style.border_width)));
1380
+ // Dashed/dotted and per-side borders are applyEdgeBorders' strokes.
1381
+ const CGFloat borderWidth = needsEdgeBorders(node.style)
1382
+ ? 0 : static_cast<CGFloat>(std::max(0, static_cast<int>(node.style.border_width)));
1372
1383
 
1373
1384
  if (radii.uniform) {
1374
1385
  dropShapeLayer(view, &kShapeMaskKey);
@@ -1474,6 +1485,176 @@ void applyCornerRadius(NSView *view, const gea::embedded::ui::Node &node, CGFloa
1474
1485
  }
1475
1486
  }
1476
1487
 
1488
+ // CSS borders the layer's own uniform `borderWidth` cannot draw: dashed or
1489
+ // dotted `border-style`, and per-side widths or colors (`border-bottom: 1px
1490
+ // dashed #0a4a20`). Up to four CAShapeLayer strokes, one per side, or one
1491
+ // stroke along the rounded border box when every side matches and a corner is
1492
+ // rounded. applyViewStyle and applyCornerRadius leave the border to these.
1493
+ char kBorderEdgeKeys[4];
1494
+
1495
+ bool needsEdgeBorders(const gea::embedded::ui::ComputedStyle &style)
1496
+ {
1497
+ using namespace gea::embedded::ui;
1498
+ return hasBrokenBorderStyle(style) || hasSideBorder(style) || (hasAnyBorder(style) && borderColorsDiffer(style));
1499
+ }
1500
+
1501
+ CAShapeLayer *edgeBorderLayer(NSView *view, int side)
1502
+ {
1503
+ CAShapeLayer *layer = cachedShapeLayer(view, &kBorderEdgeKeys[side]);
1504
+ if (!layer.actions[@"lineWidth"]) {
1505
+ NSMutableDictionary *actions = [layer.actions mutableCopy] ?: [NSMutableDictionary dictionary];
1506
+ for (NSString *key in @[ @"lineWidth", @"lineDashPattern", @"lineDashPhase", @"lineCap", @"frame" ])
1507
+ actions[key] = [NSNull null];
1508
+ layer.actions = actions;
1509
+ }
1510
+ if (layer.superlayer != view.layer) [view.layer addSublayer:layer];
1511
+ return layer;
1512
+ }
1513
+
1514
+ // Browser-like dash geometry for a stroke of `length` px drawn `width` px wide:
1515
+ // dashed = dashes of 3x the width (at least 4px) with equal gaps, dotted =
1516
+ // width-sized dots (round once they are 3px or more). The gap stretches so the
1517
+ // stroke starts and ends on a dash, as Chrome does along each edge. `closed`
1518
+ // strokes (a rounded border box) instead divide the perimeter evenly.
1519
+ void applyDashPattern(CAShapeLayer *layer, int style, CGFloat width, CGFloat length, bool closed)
1520
+ {
1521
+ using gea::embedded::ui::kBorderStyleDotted;
1522
+ layer.lineCap = kCALineCapButt;
1523
+ layer.lineDashPhase = 0;
1524
+ if (length <= 0 || width <= 0) { layer.lineDashPattern = nil; return; }
1525
+ const bool dotted = style == kBorderStyleDotted;
1526
+ const bool round = dotted && width >= 3;
1527
+ const CGFloat dash = dotted ? (round ? 0 : width) : std::max<CGFloat>(4, 3 * width);
1528
+ const CGFloat mark = dotted ? width : dash; // painted length of one dash/dot
1529
+ const CGFloat gap = dotted ? width : dash;
1530
+ if (round) layer.lineCap = kCALineCapRound;
1531
+ CGFloat period;
1532
+ if (closed) {
1533
+ const CGFloat count = std::max<CGFloat>(1, std::round(length / (mark + gap)));
1534
+ period = length / count;
1535
+ } else {
1536
+ // Open edges: n marks with n-1 stretched gaps. Round dots are centred,
1537
+ // so the stroke passed in is already shortened by one dot diameter.
1538
+ const CGFloat span = round ? length : length - mark;
1539
+ const CGFloat count = std::floor(span / (mark + gap));
1540
+ if (count < 1) { layer.lineDashPattern = nil; return; } // too short: one solid run
1541
+ period = span / count;
1542
+ }
1543
+ layer.lineDashPattern = @[ @(dash), @(std::max<CGFloat>(0.01, period - dash)) ];
1544
+ }
1545
+
1546
+ // Perimeter of the rounded border box a closed stroke follows (Ramanujan's
1547
+ // approximation for each quarter ellipse).
1548
+ CGFloat roundedRectPerimeter(CGFloat w, CGFloat h, const CGFloat rx[4], const CGFloat ry[4])
1549
+ {
1550
+ CGFloat total = 2 * (w + h);
1551
+ for (int i = 0; i < 4; ++i) {
1552
+ const CGFloat a = rx[i], b = ry[i];
1553
+ if (a <= 0 || b <= 0) continue;
1554
+ const CGFloat quarter = M_PI * (3 * (a + b) - std::sqrt((3 * a + b) * (a + 3 * b))) / 4;
1555
+ total += quarter - a - b;
1556
+ }
1557
+ return total;
1558
+ }
1559
+
1560
+ void applyEdgeBorders(NSView *view, const gea::embedded::ui::Node &node, CGFloat w, CGFloat h)
1561
+ {
1562
+ using namespace gea::embedded::ui;
1563
+ const ComputedStyle &style = node.style;
1564
+ if (!needsEdgeBorders(style) || w <= 0 || h <= 0) {
1565
+ for (int side = 0; side < 4; ++side) dropShapeLayer(view, &kBorderEdgeKeys[side]);
1566
+ return;
1567
+ }
1568
+ CGFloat widths[4];
1569
+ int styles[4];
1570
+ bool uniform = true;
1571
+ for (int side = 0; side < 4; ++side) {
1572
+ widths[side] = std::max(0, computedBorderWidth(style, side));
1573
+ styles[side] = borderSideStyle(style, side);
1574
+ if (styles[side] >= 1 && styles[side] <= 4) styles[side] = 0; // relief draws flat here
1575
+ if (side > 0 && (widths[side] != widths[0] || styles[side] != styles[0] ||
1576
+ borderPaintColor(style, side) != borderPaintColor(style, 0) ||
1577
+ borderPaintAlpha(style, side) != borderPaintAlpha(style, 0))) uniform = false;
1578
+ }
1579
+ const ResolvedRadii radii = resolveRadii(node, w, h);
1580
+ bool rounded = false;
1581
+ for (int i = 0; i < 4; ++i) rounded |= radii.rx[i] > 0 && radii.ry[i] > 0;
1582
+ const bool flipped = view.isFlipped;
1583
+ const CGRect bounds = CGRectMake(0, 0, w, h);
1584
+
1585
+ if (uniform && rounded) {
1586
+ // One stroke along the border box, inset by half the width so it stays
1587
+ // inside it (CSS borders paint inside the box).
1588
+ for (int side = 1; side < 4; ++side) dropShapeLayer(view, &kBorderEdgeKeys[side]);
1589
+ if (widths[0] <= 0) { dropShapeLayer(view, &kBorderEdgeKeys[0]); return; }
1590
+ CAShapeLayer *stroke = edgeBorderLayer(view, 0);
1591
+ stroke.frame = bounds;
1592
+ const CGFloat inset = widths[0] * 0.5;
1593
+ CGFloat rx[4], ry[4];
1594
+ for (int i = 0; i < 4; ++i) {
1595
+ rx[i] = std::max<CGFloat>(0, radii.rx[i] - inset);
1596
+ ry[i] = std::max<CGFloat>(0, radii.ry[i] - inset);
1597
+ }
1598
+ const CGRect rect = CGRectInset(bounds, inset, inset);
1599
+ CGPathRef path = createRoundedRectPath(rect, rx, ry, flipped);
1600
+ stroke.path = path;
1601
+ CGPathRelease(path);
1602
+ stroke.fillColor = nil;
1603
+ CGColorRef color = createStyleCGColor(borderPaintColor(style, 0), borderPaintAlpha(style, 0));
1604
+ stroke.strokeColor = color;
1605
+ CGColorRelease(color);
1606
+ stroke.lineWidth = widths[0];
1607
+ if (styles[0] == kBorderStyleDashed || styles[0] == kBorderStyleDotted)
1608
+ applyDashPattern(stroke, styles[0], widths[0], roundedRectPerimeter(rect.size.width, rect.size.height, rx, ry), true);
1609
+ else
1610
+ stroke.lineDashPattern = nil;
1611
+ return;
1612
+ }
1613
+
1614
+ // One straight stroke per side. Top and bottom span the full width; left
1615
+ // and right run between them, so a corner is painted once.
1616
+ const auto layerY = [&](CGFloat cssY) { return flipped ? cssY : h - cssY; };
1617
+ for (int side = 0; side < 4; ++side) {
1618
+ const CGFloat width = widths[side];
1619
+ if (width <= 0) { dropShapeLayer(view, &kBorderEdgeKeys[side]); continue; }
1620
+ CGFloat x0, y0, x1, y1;
1621
+ const CGFloat half = width * 0.5;
1622
+ switch (side) {
1623
+ case 0: x0 = 0; x1 = w; y0 = y1 = half; break;
1624
+ case 2: x0 = 0; x1 = w; y0 = y1 = h - half; break;
1625
+ case 1: x0 = x1 = w - half; y0 = widths[0]; y1 = h - widths[2]; break;
1626
+ default: x0 = x1 = half; y0 = widths[0]; y1 = h - widths[2]; break;
1627
+ }
1628
+ const bool horizontal = side == 0 || side == 2;
1629
+ CGFloat length = horizontal ? x1 - x0 : y1 - y0;
1630
+ if (length <= 0) { dropShapeLayer(view, &kBorderEdgeKeys[side]); continue; }
1631
+ const int lineStyle = styles[side];
1632
+ // Round dots sit inside the edge: shorten the stroke by a dot diameter.
1633
+ if (lineStyle == kBorderStyleDotted && width >= 3 && length > width) {
1634
+ if (horizontal) { x0 += half; x1 -= half; } else { y0 += half; y1 -= half; }
1635
+ length -= width;
1636
+ }
1637
+ CAShapeLayer *stroke = edgeBorderLayer(view, side);
1638
+ stroke.frame = bounds;
1639
+ CGMutablePathRef path = CGPathCreateMutable();
1640
+ CGPathMoveToPoint(path, NULL, x0, layerY(y0));
1641
+ CGPathAddLineToPoint(path, NULL, x1, layerY(y1));
1642
+ stroke.path = path;
1643
+ CGPathRelease(path);
1644
+ stroke.fillColor = nil;
1645
+ CGColorRef color = createStyleCGColor(borderPaintColor(style, side), borderPaintAlpha(style, side));
1646
+ stroke.strokeColor = color;
1647
+ CGColorRelease(color);
1648
+ stroke.lineWidth = width;
1649
+ if (lineStyle == kBorderStyleDashed || lineStyle == kBorderStyleDotted)
1650
+ applyDashPattern(stroke, lineStyle, width, length, false);
1651
+ else {
1652
+ stroke.lineDashPattern = nil;
1653
+ stroke.lineCap = kCALineCapButt;
1654
+ }
1655
+ }
1656
+ }
1657
+
1477
1658
  // filter: blur(<n>px). CALayer.filters applies Core Image to the layer AND its
1478
1659
  // sublayers, which is CSS `filter`'s scope (the element plus its subtree).
1479
1660
  // NSView refuses to route CIFilters into its backing layer unless
@@ -1582,6 +1763,257 @@ void applyBoxShadow(NSView *view, const gea::embedded::ui::Node &node, CGFloat w
1582
1763
  shadow.shadowOpacity = rare.box_shadow_alpha / 255.0;
1583
1764
  }
1584
1765
 
1766
+ // CSS `background-image: radial-gradient(...)`, with `background-size` tiling,
1767
+ // `background-position` and `background-repeat` — e.g. a dot field:
1768
+ // background: radial-gradient(circle, #03140a 1px, transparent 1.4px) 0 0 / 14px 14px, #000;
1769
+ // The engine has already parsed the layer into RareStyle (stops in permille of
1770
+ // the radius, or absolute centi-px with kRadialGradientPxStops) and resolves
1771
+ // the placement per layer (StyleValues::backgroundPlacement); this only
1772
+ // rasterises it. One tile is drawn with CoreGraphics at the backing scale and
1773
+ // cached by its parameters, the tiles are composed into one bitmap for the
1774
+ // painting area, and that bitmap is the contents of a sublayer sitting above
1775
+ // the background colour (view.layer.backgroundColor) and below the inset
1776
+ // shadow, borders and children — the CSS paint order. The composed bitmap is
1777
+ // rebuilt only when its key (gradient, placement, area, scale) changes.
1778
+ char kBackgroundImageKey; // CALayer showing the composed background image
1779
+ char kBackgroundImageTagKey; // NSString key of what that layer currently shows
1780
+
1781
+ void unpackStyleColor(gea::embedded::ui::style_color_t color, uint8_t alpha, CGFloat out[4])
1782
+ {
1783
+ int r, g, b, a;
1784
+ gea::framework::graphics::pixel::unpackNative8(color, &r, &g, &b, &a);
1785
+ out[0] = r / 255.0;
1786
+ out[1] = g / 255.0;
1787
+ out[2] = b / 255.0;
1788
+ out[3] = alpha / 255.0;
1789
+ }
1790
+
1791
+ CGImageRef createRadialGradientTile(const gea::embedded::ui::RareStyle &r, int tileW, int tileH, CGFloat scale)
1792
+ {
1793
+ using namespace gea::embedded::ui;
1794
+ const size_t pw = static_cast<size_t>(std::ceil(tileW * scale));
1795
+ const size_t ph = static_cast<size_t>(std::ceil(tileH * scale));
1796
+ if (pw == 0 || ph == 0 || pw > 8192 || ph > 8192) return nullptr;
1797
+ CGColorSpaceRef srgb = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
1798
+ CGContextRef ctx = CGBitmapContextCreate(nullptr, pw, ph, 8, 0, srgb,
1799
+ kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
1800
+ if (!ctx) { CGColorSpaceRelease(srgb); return nullptr; }
1801
+
1802
+ // CSS interpolates gradient colours premultiplied (so `#03140a` fading to
1803
+ // `transparent` keeps its hue); CGGradient interpolates straight colour.
1804
+ // Sample the premultiplied ramp and hand CG the unpremultiplied samples.
1805
+ CGFloat from[4], to[4];
1806
+ unpackStyleColor(r.bg_radial_gradient_from_color, r.bg_radial_gradient_from_alpha, from);
1807
+ unpackStyleColor(r.bg_radial_gradient_to_color, r.bg_radial_gradient_to_alpha, to);
1808
+ constexpr int kSamples = 17;
1809
+ CGFloat components[kSamples * 4];
1810
+ CGFloat locations[kSamples];
1811
+ for (int i = 0; i < kSamples; ++i) {
1812
+ const CGFloat t = static_cast<CGFloat>(i) / (kSamples - 1);
1813
+ const CGFloat a = from[3] + (to[3] - from[3]) * t;
1814
+ for (int c = 0; c < 3; ++c) {
1815
+ const CGFloat premultiplied = from[c] * from[3] + (to[c] * to[3] - from[c] * from[3]) * t;
1816
+ components[i * 4 + c] = a > 0 ? std::min<CGFloat>(1, premultiplied / a) : 0;
1817
+ }
1818
+ components[i * 4 + 3] = a;
1819
+ locations[i] = t;
1820
+ }
1821
+ CGGradientRef gradient = CGGradientCreateWithColorComponents(srgb, components, locations, kSamples);
1822
+
1823
+ // Draw in CSS px with y growing downward, so the tile's first row is its top.
1824
+ CGContextScaleCTM(ctx, scale, scale);
1825
+ CGContextTranslateCTM(ctx, 0, tileH);
1826
+ CGContextScaleCTM(ctx, 1, -1);
1827
+ const CGFloat cx = tileW * r.bg_radial_gradient_cx / 1000.0;
1828
+ const CGFloat cy = tileH * r.bg_radial_gradient_cy / 1000.0;
1829
+ CGFloat startRadius, endRadius, aspect;
1830
+ if (r.bg_radial_gradient_units & kRadialGradientPxStops) {
1831
+ // Absolute stops: distances from the centre along the x radius.
1832
+ startRadius = r.bg_radial_gradient_from_stop / 100.0;
1833
+ endRadius = r.bg_radial_gradient_stop / 100.0;
1834
+ aspect = (r.bg_radial_gradient_units & kRadialGradientCircle) || r.bg_radial_gradient_rx <= 0
1835
+ ? 1.0 : (static_cast<CGFloat>(tileH) * r.bg_radial_gradient_ry) / (static_cast<CGFloat>(tileW) * r.bg_radial_gradient_rx);
1836
+ } else {
1837
+ // Radius-relative stops, radii as the engine rasteriser derives them.
1838
+ const CGFloat radiusX = std::max<CGFloat>(1, tileW * r.bg_radial_gradient_rx / 1000.0);
1839
+ const CGFloat radiusY = std::max<CGFloat>(1, tileH * r.bg_radial_gradient_ry / 1000.0);
1840
+ startRadius = radiusX * std::min<int>(r.bg_radial_gradient_from_stop, r.bg_radial_gradient_stop) / 1000.0;
1841
+ endRadius = radiusX * r.bg_radial_gradient_stop / 1000.0;
1842
+ aspect = radiusY / radiusX;
1843
+ }
1844
+ endRadius = std::max<CGFloat>(endRadius, startRadius + 0.001);
1845
+ CGContextTranslateCTM(ctx, cx, cy);
1846
+ CGContextScaleCTM(ctx, 1, std::max<CGFloat>(aspect, 0.001));
1847
+ CGContextDrawRadialGradient(ctx, gradient, CGPointZero, startRadius, CGPointZero, endRadius,
1848
+ kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
1849
+ CGGradientRelease(gradient);
1850
+ CGImageRef image = CGBitmapContextCreateImage(ctx);
1851
+ CGContextRelease(ctx);
1852
+ CGColorSpaceRelease(srgb);
1853
+ return image;
1854
+ }
1855
+
1856
+ // Tiles are shared across views (a dot field and a chart grid reuse theirs
1857
+ // every frame); the key is everything the tile's pixels depend on.
1858
+ CGImageRef cachedRadialGradientTile(const gea::embedded::ui::RareStyle &r, int tileW, int tileH, CGFloat scale)
1859
+ {
1860
+ static NSCache<NSString *, id> *tiles = [] {
1861
+ NSCache *cache = [[NSCache alloc] init];
1862
+ cache.countLimit = 64;
1863
+ return cache;
1864
+ }();
1865
+ NSString *key = [NSString stringWithFormat:@"%x/%u>%x/%u|%u-%u|%u|%d,%d,%d,%d|%dx%d@%.2f",
1866
+ static_cast<unsigned>(r.bg_radial_gradient_from_color), r.bg_radial_gradient_from_alpha,
1867
+ static_cast<unsigned>(r.bg_radial_gradient_to_color), r.bg_radial_gradient_to_alpha,
1868
+ r.bg_radial_gradient_from_stop, r.bg_radial_gradient_stop, r.bg_radial_gradient_units,
1869
+ r.bg_radial_gradient_cx, r.bg_radial_gradient_cy, r.bg_radial_gradient_rx, r.bg_radial_gradient_ry,
1870
+ tileW, tileH, scale];
1871
+ id cached = [tiles objectForKey:key];
1872
+ if (cached) return (__bridge CGImageRef)cached;
1873
+ CGImageRef tile = createRadialGradientTile(r, tileW, tileH, scale);
1874
+ if (!tile) return nullptr;
1875
+ [tiles setObject:(__bridge_transfer id)tile forKey:key];
1876
+ return (__bridge CGImageRef)[tiles objectForKey:key];
1877
+ }
1878
+
1879
+ void dropBackgroundImage(NSView *view)
1880
+ {
1881
+ CALayer *layer = objc_getAssociatedObject(view, &kBackgroundImageKey);
1882
+ if (!layer) return;
1883
+ [layer removeFromSuperlayer];
1884
+ objc_setAssociatedObject(view, &kBackgroundImageKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1885
+ }
1886
+
1887
+ void applyBackgroundImage(NSView *view, const gea::embedded::ui::Node &node, int w, int h)
1888
+ {
1889
+ using namespace gea::embedded::ui;
1890
+ const RareStyle &r = rstyle(node.style);
1891
+ if (!r.bg_radial_gradient || w <= 0 || h <= 0 || [view isKindOfClass:[NSVisualEffectView class]]) {
1892
+ dropBackgroundImage(view);
1893
+ return;
1894
+ }
1895
+ const Tree &tree = Tree::instance();
1896
+ const std::ptrdiff_t index = &node - tree.nodes();
1897
+ const int nodeId = index >= 0 && index < tree.nodeCount() ? static_cast<int>(index) : -1;
1898
+ const int layerIndex = r.bg_radial_gradient_layer;
1899
+ // Everything below is in CSS px relative to the border box, y downward.
1900
+ const BackgroundPlacement p = StyleValues::backgroundPlacement(node.style, nodeId, layerIndex, 0, 0, w, h);
1901
+ int clipX = 0, clipY = 0, clipW = w, clipH = h;
1902
+ const int clip = StyleValues::backgroundClip(node.style, layerIndex);
1903
+ if (clip == 1 || clip == 2) {
1904
+ int inset[4];
1905
+ for (int i = 0; i < 4; ++i)
1906
+ inset[i] = computedBorderWidth(node.style, i) + (clip == 2 ? std::max<int>(0, node.style.padding[i]) : 0);
1907
+ clipX += inset[3]; clipY += inset[0];
1908
+ clipW -= inset[1] + inset[3]; clipH -= inset[0] + inset[2];
1909
+ }
1910
+ if (p.width <= 0 || p.height <= 0 || clipW <= 0 || clipH <= 0) {
1911
+ dropBackgroundImage(view);
1912
+ return;
1913
+ }
1914
+
1915
+ CGFloat scale = view.window.backingScaleFactor;
1916
+ if (scale <= 0) scale = NSScreen.mainScreen.backingScaleFactor;
1917
+ if (scale <= 0) scale = 2;
1918
+
1919
+ CALayer *layer = objc_getAssociatedObject(view, &kBackgroundImageKey);
1920
+ if (!layer) {
1921
+ layer = [CALayer layer];
1922
+ layer.actions = @{
1923
+ @"contents" : [NSNull null],
1924
+ @"bounds" : [NSNull null],
1925
+ @"position" : [NSNull null],
1926
+ @"frame" : [NSNull null],
1927
+ @"transform" : [NSNull null],
1928
+ @"hidden" : [NSNull null],
1929
+ };
1930
+ layer.contentsGravity = kCAGravityResize;
1931
+ objc_setAssociatedObject(view, &kBackgroundImageKey, layer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1932
+ }
1933
+ // Above a shape layer that paints the background colour (applyCornerRadius'
1934
+ // blurred path), else the bottom-most sublayer: under the inset shadow,
1935
+ // the border strokes and every child view.
1936
+ CALayer *fill = objc_getAssociatedObject(view, &kShapeFillKey);
1937
+ const bool fillBelow = fill && fill.superlayer == view.layer;
1938
+ NSArray<CALayer *> *sublayers = view.layer.sublayers;
1939
+ const NSUInteger want = fillBelow ? [sublayers indexOfObject:fill] + 1 : 0;
1940
+ if (layer.superlayer != view.layer || want >= sublayers.count || sublayers[want] != layer) {
1941
+ [layer removeFromSuperlayer];
1942
+ if (fillBelow) [view.layer insertSublayer:layer above:fill];
1943
+ else [view.layer insertSublayer:layer atIndex:0];
1944
+ }
1945
+ const bool flipped = view.isFlipped;
1946
+ layer.frame = CGRectMake(clipX, flipped ? clipY : h - clipY - clipH, clipW, clipH);
1947
+ layer.contentsScale = scale;
1948
+ // The bitmap's first row is the area's top. A layer whose ancestors flip
1949
+ // geometry renders its contents flipped; undo that so the top stays up.
1950
+ layer.affineTransform = layer.contentsAreFlipped ? CGAffineTransformMakeScale(1, -1) : CGAffineTransformIdentity;
1951
+
1952
+ NSString *tag = [NSString stringWithFormat:@"%x/%u>%x/%u|%u-%u|%u|%d,%d,%d,%d|tile %d,%d %dx%d r%d,%d area %d,%d %dx%d|clip %d,%d %dx%d@%.2f",
1953
+ static_cast<unsigned>(r.bg_radial_gradient_from_color), r.bg_radial_gradient_from_alpha,
1954
+ static_cast<unsigned>(r.bg_radial_gradient_to_color), r.bg_radial_gradient_to_alpha,
1955
+ r.bg_radial_gradient_from_stop, r.bg_radial_gradient_stop, r.bg_radial_gradient_units,
1956
+ r.bg_radial_gradient_cx, r.bg_radial_gradient_cy, r.bg_radial_gradient_rx, r.bg_radial_gradient_ry,
1957
+ p.x, p.y, p.width, p.height, p.repeatX, p.repeatY, p.areaX, p.areaY, p.areaWidth, p.areaHeight,
1958
+ clipX, clipY, clipW, clipH, scale];
1959
+ if ([tag isEqualToString:objc_getAssociatedObject(layer, &kBackgroundImageTagKey)]) return;
1960
+
1961
+ CGImageRef tile = cachedRadialGradientTile(r, p.width, p.height, scale);
1962
+ const size_t pw = static_cast<size_t>(std::ceil(clipW * scale));
1963
+ const size_t ph = static_cast<size_t>(std::ceil(clipH * scale));
1964
+ CGColorSpaceRef srgb = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
1965
+ CGContextRef ctx = tile && pw <= 16384 && ph <= 16384
1966
+ ? CGBitmapContextCreate(nullptr, pw, ph, 8, 0, srgb, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big)
1967
+ : nullptr;
1968
+ CGColorSpaceRelease(srgb);
1969
+ if (!ctx) {
1970
+ layer.contents = nil;
1971
+ objc_setAssociatedObject(layer, &kBackgroundImageTagKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1972
+ return;
1973
+ }
1974
+ CGContextSetInterpolationQuality(ctx, kCGInterpolationNone);
1975
+ CGContextScaleCTM(ctx, scale, scale);
1976
+ // CSS coordinates of the painting area: y downward, origin at the clip box.
1977
+ CGContextTranslateCTM(ctx, 0, clipH);
1978
+ CGContextScaleCTM(ctx, 1, -1);
1979
+ CGContextTranslateCTM(ctx, -clipX, -clipY);
1980
+
1981
+ // Tile placement per axis, as the engine's display list records it
1982
+ // (view.cpp recordPlacedBackgrounds): repeat / round tile from the
1983
+ // positioned image outward, no-repeat paints once, space spreads whole tiles.
1984
+ struct Axis { double start, step; int count; };
1985
+ auto axis = [](int position, int size, int mode, int area, int areaSize, int clipStart, int clipSize) -> Axis {
1986
+ if (mode == 1) return {static_cast<double>(position), static_cast<double>(size), 1};
1987
+ if (mode == 3) {
1988
+ const int count = areaSize / size;
1989
+ if (count < 2) return {static_cast<double>(position), static_cast<double>(size), 1};
1990
+ return {static_cast<double>(area), static_cast<double>(areaSize - size) / (count - 1), count};
1991
+ }
1992
+ const int start = position + static_cast<int>(std::floor(static_cast<double>(clipStart - position) / size)) * size;
1993
+ return {static_cast<double>(start), static_cast<double>(size), (clipStart + clipSize - start + size - 1) / size};
1994
+ };
1995
+ const Axis ax = axis(p.x, p.width, p.repeatX, p.areaX, p.areaWidth, clipX, clipW);
1996
+ const Axis ay = axis(p.y, p.height, p.repeatY, p.areaY, p.areaHeight, clipY, clipH);
1997
+ for (int row = 0; row < ay.count; ++row) {
1998
+ for (int col = 0; col < ax.count; ++col) {
1999
+ const double tx = ax.start + col * ax.step, ty = ay.start + row * ay.step;
2000
+ if (tx >= clipX + clipW || ty >= clipY + clipH || tx + p.width <= clipX || ty + p.height <= clipY) continue;
2001
+ // The tile bitmap is top-row-first; the CTM is y-down, so flip it
2002
+ // back locally to draw it upright.
2003
+ CGContextSaveGState(ctx);
2004
+ CGContextTranslateCTM(ctx, tx, ty + p.height);
2005
+ CGContextScaleCTM(ctx, 1, -1);
2006
+ CGContextDrawImage(ctx, CGRectMake(0, 0, p.width, p.height), tile);
2007
+ CGContextRestoreGState(ctx);
2008
+ }
2009
+ }
2010
+ CGImageRef composed = CGBitmapContextCreateImage(ctx);
2011
+ CGContextRelease(ctx);
2012
+ layer.contents = (__bridge id)composed;
2013
+ CGImageRelease(composed);
2014
+ objc_setAssociatedObject(layer, &kBackgroundImageTagKey, tag, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
2015
+ }
2016
+
1585
2017
  void applyViewStyle(NSView *view, const gea::embedded::ui::Node &node,
1586
2018
  int parentAbsX, int parentAbsY, int parentHeight)
1587
2019
  {
@@ -1632,7 +2064,8 @@ void applyViewStyle(NSView *view, const gea::embedded::ui::Node &node,
1632
2064
  view.hidden = (node.style.display == 1 || node.style.visibility != 0);
1633
2065
 
1634
2066
  // Border (border_alpha carries the CSS alpha, same as bg_alpha above).
1635
- if (node.style.border_width > 0) {
2067
+ // Dashed/dotted and per-side borders are drawn by applyEdgeBorders below.
2068
+ if (node.style.border_width > 0 && !needsEdgeBorders(node.style)) {
1636
2069
  view.layer.borderWidth = node.style.border_width;
1637
2070
  CGColor *bc = gea::macos::nativeToCGColor(node.style.border_color);
1638
2071
  if (node.style.border_alpha != 255) {
@@ -1653,7 +2086,9 @@ void applyViewStyle(NSView *view, const gea::embedded::ui::Node &node,
1653
2086
  // both are set above.
1654
2087
  const bool nodeIsBlurred = gea::embedded::ui::rstyle(node.style).filter_blur_radius > 0;
1655
2088
  applyCornerRadius(view, node, w, h, nodeIsBlurred);
2089
+ applyEdgeBorders(view, node, w, h);
1656
2090
  applyBoxShadow(view, node, w, h);
2091
+ applyBackgroundImage(view, node, w, h);
1657
2092
 
1658
2093
  // Rotation. transform_rotate is stored as TENTHS of degrees (see
1659
2094
  // style.cpp's numericRotateTenths — `degrees * 10`). CSS rotate is
@@ -1713,6 +2148,19 @@ NSMutableDictionary *textAttributes(NSFont *font, NSColor *color, int textDecora
1713
2148
  return attrs;
1714
2149
  }
1715
2150
 
2151
+ // The string a text node draws: its authored text with CSS text-transform and
2152
+ // white-space collapsing applied by the engine's own TextRenderer::prepareText,
2153
+ // which is exactly what the measurement hook was handed. Node::text stays the
2154
+ // authored string.
2155
+ NSString *displayText(const gea::embedded::ui::Node &node)
2156
+ {
2157
+ if (node.text.empty()) return @"";
2158
+ std::string storage;
2159
+ const char *text = gea::embedded::ui::TextRenderer::prepareText(node.text.c_str(), node.style.text_transform,
2160
+ node.style.white_space, storage);
2161
+ return [NSString stringWithUTF8String:text ? text : ""] ?: @"";
2162
+ }
2163
+
1716
2164
  bool attributedStringHasTextDecoration(NSAttributedString *value)
1717
2165
  {
1718
2166
  if (!value || value.length == 0) return false;
@@ -1722,7 +2170,8 @@ bool attributedStringHasTextDecoration(NSAttributedString *value)
1722
2170
 
1723
2171
  void applyTextProps(NSTextField *tf, const gea::embedded::ui::Node &node, int nodeId)
1724
2172
  {
1725
- NSString *raw = [NSString stringWithUTF8String:(node.text.empty() ? "" : node.text.c_str())];
2173
+ NSString *raw = displayText(node);
2174
+ const CGFloat kern = gea::macos::letterSpacingKern(node.style.letter_spacing);
1726
2175
  NSFont *font = gea::macos::fontForId(node.style.font_id, node.style.font_size, node.style.font_weight, node.style.font_stretch);
1727
2176
  NSColor *color = gea::macos::nativeToNSColor(node.style.text_color);
1728
2177
  GeaTextCell *cell = (GeaTextCell *)tf.cell;
@@ -1744,7 +2193,29 @@ void applyTextProps(NSTextField *tf, const gea::embedded::ui::Node &node, int no
1744
2193
  NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
1745
2194
  const CGFloat contentWidth = node.layout.width - cell.contentInsets.left - cell.contentInsets.right;
1746
2195
  const CGFloat availableWidth = node.layout.width > 0 ? std::max<CGFloat>(0, contentWidth) : CGFLOAT_MAX;
1747
- paragraph.lineBreakMode = gea::macos::lineBreakModeForText(raw, font, availableWidth);
2196
+ // `white-space: nowrap` keeps the text on one line; with `text-overflow:
2197
+ // ellipsis` AppKit cuts it with "…" where it meets the box's edge, as a
2198
+ // browser does. Either may sit on the text itself or on the element that
2199
+ // holds it (a `<div class>` whose only child is the text).
2200
+ const auto &textTree = gea::embedded::ui::Tree::instance();
2201
+ const gea::embedded::ui::Node *holder = node.parent >= 0 ? &textTree.node(node.parent) : nullptr;
2202
+ const bool noWrap = node.style.white_space == 1 || (holder && holder->style.white_space == 1);
2203
+ const bool ellipsis = noWrap && (node.style.text_overflow == 1 || (holder && holder->style.text_overflow == 1));
2204
+ paragraph.lineBreakMode = ellipsis ? NSLineBreakByTruncatingTail
2205
+ : noWrap ? NSLineBreakByClipping
2206
+ : gea::macos::lineBreakModeForText(raw, font, availableWidth, kern);
2207
+ tf.cell.wraps = !noWrap;
2208
+ tf.cell.truncatesLastVisibleLine = ellipsis;
2209
+ tf.lineBreakMode = paragraph.lineBreakMode;
2210
+ // A nowrap line keeps its full width in layout and overflows the element
2211
+ // holding it; the ellipsis belongs at that element's content edge, so the
2212
+ // field ends there (applyViewStyle already placed it at layout width).
2213
+ if (ellipsis && holder && node.style.text_overflow != 1) {
2214
+ const int holderRight = holder->layout.x + holder->layout.width - holder->style.padding[1] -
2215
+ gea::embedded::ui::computedBorderWidth(holder->style, 1);
2216
+ const CGFloat fitted = std::max(0, std::min<int>(node.layout.width, holderRight - node.layout.x));
2217
+ if (tf.frame.size.width != fitted) [tf setFrameSize:NSMakeSize(fitted, tf.frame.size.height)];
2218
+ }
1748
2219
  paragraph.alignment = alignment;
1749
2220
  if (node.style.line_height > 0) {
1750
2221
  paragraph.minimumLineHeight = node.style.line_height;
@@ -1754,6 +2225,19 @@ void applyTextProps(NSTextField *tf, const gea::embedded::ui::Node &node, int no
1754
2225
  color,
1755
2226
  node.style.text_decoration);
1756
2227
  attrs[NSParagraphStyleAttributeName] = paragraph;
2228
+ // A fixed line height taller than the font: AppKit sets the baseline at the
2229
+ // bottom of the line (all the extra space above the glyphs), CSS splits it
2230
+ // as half-leading above and below -- as the engine's own text layout does.
2231
+ // Raise each line by that half so text sits centred in its line box.
2232
+ if (node.style.line_height > 0) {
2233
+ NSFont *drawn = attrs[NSFontAttributeName];
2234
+ const CGFloat content = drawn.ascender - drawn.descender + drawn.leading;
2235
+ const CGFloat halfLeading = (node.style.line_height - content) / 2;
2236
+ if (halfLeading > 0) attrs[NSBaselineOffsetAttributeName] = @(halfLeading);
2237
+ }
2238
+ // CSS letter-spacing: the same kern the measurement hook applied, so the
2239
+ // drawn run is exactly as wide as the box layout gave it.
2240
+ if (kern != 0) attrs[NSKernAttributeName] = @(kern);
1757
2241
  NSAttributedString *attributed = [[NSAttributedString alloc] initWithString:raw attributes:attrs];
1758
2242
  if (![tf.attributedStringValue isEqualToAttributedString:attributed]) {
1759
2243
  tf.attributedStringValue = attributed;
@@ -2057,7 +2541,7 @@ void applyButtonProps(NSButton *btn, const gea::embedded::ui::Node &node, int no
2057
2541
  for (int child = node.first_child; child >= 0; child = tree.node(child).next_sibling) {
2058
2542
  const Node &cn = tree.node(child);
2059
2543
  if (cn.type == NodeType::Text && !cn.text.empty()) {
2060
- title = [NSString stringWithUTF8String:cn.text.c_str()];
2544
+ title = displayText(cn);
2061
2545
  break;
2062
2546
  }
2063
2547
  }
@@ -2076,7 +2560,7 @@ void applyButtonProps(NSButton *btn, const gea::embedded::ui::Node &node, int no
2076
2560
  stack.pop_back();
2077
2561
  const Node &cn = tree.node(id);
2078
2562
  if (cn.type == NodeType::Text && !cn.text.empty()) {
2079
- [parts addObject:[NSString stringWithUTF8String:cn.text.c_str()] ?: @""];
2563
+ [parts addObject:displayText(cn)];
2080
2564
  }
2081
2565
  std::vector<int> children;
2082
2566
  for (int child = cn.first_child; child >= 0; child = tree.node(child).next_sibling) children.push_back(child);
@@ -2099,11 +2583,12 @@ void applyButtonProps(NSButton *btn, const gea::embedded::ui::Node &node, int no
2099
2583
  : [NSColor labelColor];
2100
2584
  NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
2101
2585
  paragraph.alignment = NSTextAlignmentCenter;
2102
- NSDictionary *attrs = @{
2586
+ NSMutableDictionary *attrs = [NSMutableDictionary dictionaryWithDictionary:@{
2103
2587
  NSFontAttributeName: font ?: [NSFont systemFontOfSize:[NSFont systemFontSize]],
2104
2588
  NSForegroundColorAttributeName: color,
2105
2589
  NSParagraphStyleAttributeName: paragraph,
2106
- };
2590
+ }];
2591
+ if (node.style.letter_spacing != 0) attrs[NSKernAttributeName] = @(gea::macos::letterSpacingKern(node.style.letter_spacing));
2107
2592
  NSAttributedString *attributed = [[NSAttributedString alloc] initWithString:title attributes:attrs];
2108
2593
  if (![btn.attributedTitle isEqualToAttributedString:attributed]) btn.attributedTitle = attributed;
2109
2594
  } else {
@@ -2395,7 +2880,7 @@ void appendInlineRuns(NSMutableAttributedString *out, int nodeId,
2395
2880
  const Node &node = tree.node(nodeId);
2396
2881
  if (node.type == NodeType::Text) {
2397
2882
  if (node.text.empty()) return;
2398
- NSString *str = [NSString stringWithUTF8String:node.text.c_str()] ?: @"";
2883
+ NSString *str = displayText(node);
2399
2884
  NSColor *col = parentColor;
2400
2885
  NSFont *font = parentFont;
2401
2886
  // Text node style is already resolved by the framework's CSS cascade
@@ -2408,6 +2893,7 @@ void appendInlineRuns(NSMutableAttributedString *out, int nodeId,
2408
2893
  NSFont *resolved = gea::macos::fontForId(node.style.font_id, node.style.font_size, node.style.font_weight, node.style.font_stretch);
2409
2894
  if (resolved) font = resolved;
2410
2895
  NSMutableDictionary *attrs = textAttributes(font, col, node.style.text_decoration);
2896
+ if (node.style.letter_spacing != 0) attrs[NSKernAttributeName] = @(gea::macos::letterSpacingKern(node.style.letter_spacing));
2411
2897
  [out appendAttributedString:[[NSAttributedString alloc] initWithString:str attributes:attrs]];
2412
2898
  return;
2413
2899
  }
@@ -2498,6 +2984,9 @@ void syncRecursive(int nodeId, NSView *parent, int parentAbsX, int parentAbsY, i
2498
2984
  if (nodeId < 0 || nodeId >= tree.nodeCount()) return;
2499
2985
  const Node &node = tree.node(nodeId);
2500
2986
  if (isStructuralNodeType(node.type)) return;
2987
+ // A `<window>` subtree renders into its own NSWindow (macos_windows.mm),
2988
+ // never inline; left unvisited, any view it had here is swept.
2989
+ if (isDetachedRoot(node)) return;
2501
2990
 
2502
2991
  NSNumber *key = @(nodeId);
2503
2992
  [unseen removeObject:key];
@@ -2566,6 +3055,81 @@ MacosRenderer &MacosRenderer::instance()
2566
3055
  return r;
2567
3056
  }
2568
3057
 
3058
+ namespace {
3059
+ const char *wheelPhaseName(NSEventPhase phase)
3060
+ {
3061
+ if (phase & NSEventPhaseMayBegin) return "mayBegin";
3062
+ if (phase & NSEventPhaseBegan) return "began";
3063
+ if (phase & (NSEventPhaseChanged | NSEventPhaseStationary)) return "changed";
3064
+ if (phase & NSEventPhaseEnded) return "ended";
3065
+ if (phase & NSEventPhaseCancelled) return "cancelled";
3066
+ return "";
3067
+ }
3068
+ // The node a trackpad gesture began over. Like browsers' wheel-transaction
3069
+ // latching, every later event of that gesture (and its momentum tail) targets
3070
+ // it even after the content scrolled a different row under the pointer.
3071
+ gea::framework::events::EventTarget g_wheelLatch;
3072
+ } // namespace
3073
+
3074
+ bool dispatchWheelEvent(NSEvent *event, NSWindow *window, CGPoint locationInWindow)
3075
+ {
3076
+ using gea::framework::events::PointerEvent;
3077
+ using gea::framework::events::PointerEventType;
3078
+ auto &tree = gea::embedded::ui::Tree::instance();
3079
+ // No `wheel` listener anywhere: AppKit's own scrolling, untouched.
3080
+ if (!event || event.type != NSEventTypeScrollWheel || !tree.hasListenersForType("wheel")) return false;
3081
+ NSView *content = window.contentView;
3082
+ if (!content) return false;
3083
+ NSView *frame = content.superview;
3084
+ NSView *hit = [content hitTest:frame ? [frame convertPoint:locationInWindow fromView:nil] : NSPoint(locationInWindow)];
3085
+ // Tree coordinates come from the Gea root that owns the hit view, exactly
3086
+ // as GeaRootClickBridge computes them for presses.
3087
+ NSView *root = nil;
3088
+ GeaRootClickBridge *bridge = nil;
3089
+ for (NSView *v = hit; v; v = v.superview) {
3090
+ if ((bridge = objc_getAssociatedObject(v, "gea.root_click_bridge"))) { root = v; break; }
3091
+ }
3092
+ if (!root) return false;
3093
+ const NSPoint inRoot = [root convertPoint:locationInWindow fromView:nil];
3094
+ const int x = static_cast<int>(std::lround(inRoot.x)) + bridge.originX;
3095
+ const int y = static_cast<int>(std::lround(root.bounds.size.height - inRoot.y)) + bridge.originY;
3096
+
3097
+ const NSEventPhase phase = event.phase;
3098
+ const NSEventPhase momentum = event.momentumPhase;
3099
+ int target = nodeIdForView(hit);
3100
+ if (phase & (NSEventPhaseMayBegin | NSEventPhaseBegan)) {
3101
+ g_wheelLatch = gea::framework::events::EventTarget(target);
3102
+ } else if ((phase != NSEventPhaseNone || momentum != NSEventPhaseNone) && g_wheelLatch.valid()) {
3103
+ target = g_wheelLatch.id();
3104
+ }
3105
+ if (target < 0 || target >= tree.nodeCount()) return false;
3106
+
3107
+ PointerEvent ev{};
3108
+ ev.type = PointerEventType::Wheel;
3109
+ ev.targetId = target;
3110
+ ev.x = ev.clientX = ev.pageX = ev.screenX = x;
3111
+ ev.y = ev.clientY = ev.pageY = ev.screenY = y;
3112
+ // AppKit reports how the CONTENT moves (positive scrollingDeltaY = content
3113
+ // moves down); the web reports where the VIEWPORT goes (positive deltaY =
3114
+ // scroll toward what is below). Invert, as Safari and Chrome do. A notched
3115
+ // mouse wheel reports lines; NSScrollView's default line is 10pt.
3116
+ const double scale = event.hasPreciseScrollingDeltas ? 1.0 : 10.0;
3117
+ ev.deltaX = -event.scrollingDeltaX * scale;
3118
+ ev.deltaY = -event.scrollingDeltaY * scale;
3119
+ ev.deltaMode = 0;
3120
+ ev.wheelPhase = wheelPhaseName(phase);
3121
+ ev.momentumPhase = wheelPhaseName(momentum);
3122
+ const NSEventModifierFlags flags = event.modifierFlags;
3123
+ ev.altKey = (flags & NSEventModifierFlagOption) != 0;
3124
+ ev.ctrlKey = (flags & NSEventModifierFlagControl) != 0;
3125
+ ev.metaKey = (flags & NSEventModifierFlagCommand) != 0;
3126
+ ev.shiftKey = (flags & NSEventModifierFlagShift) != 0;
3127
+ ev.bubbles = true;
3128
+ ev.cancelable = true;
3129
+ tree.dispatchEvent(ev);
3130
+ return static_cast<bool>(ev.defaultPrevented);
3131
+ }
3132
+
2569
3133
  namespace {
2570
3134
  // Install the centralized press/click handler on a root container once.
2571
3135
  // Idempotent via an associated object so repeated sync passes don't stack
@@ -2591,6 +3155,39 @@ void ensureRootClickBridge(NSView *parentForRoot, int originX, int originY)
2591
3155
  gr.delegate = bridge;
2592
3156
  [parentForRoot addGestureRecognizer:gr];
2593
3157
  }
3158
+ // One app-wide scroll monitor delivers `wheel` before AppKit routes the
3159
+ // event to the view under the pointer (and up to its NSScrollView). A
3160
+ // listener's preventDefault() drops the event; otherwise it continues
3161
+ // unchanged, so native scrolling and momentum are untouched.
3162
+ //
3163
+ // A trackpad gesture's `began` event is held back until the gesture's first
3164
+ // moving event, as browsers decide a wheel transaction on its first event:
3165
+ // AppKit latches the whole gesture to the scroll view that sees `began`, so
3166
+ // a listener that calls preventDefault() as soon as it can tell the swipe is
3167
+ // its own (a row sliding sideways) would otherwise still have the list
3168
+ // scrolling under it. When that first moving event is not prevented, the
3169
+ // held `began` is delivered first and scrolling proceeds untouched.
3170
+ static NSEvent *heldBegan = nil;
3171
+ static id wheelMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskScrollWheel
3172
+ handler:^NSEvent *(NSEvent *event) {
3173
+ const bool prevented = dispatchWheelEvent(event, event.window, event.locationInWindow);
3174
+ const NSEventPhase phase = event.phase;
3175
+ if (phase & NSEventPhaseBegan) {
3176
+ heldBegan = nil;
3177
+ if (prevented) return nil;
3178
+ if (!gea::embedded::ui::Tree::instance().hasListenersForType("wheel")) return event;
3179
+ heldBegan = event;
3180
+ return nil;
3181
+ }
3182
+ NSEvent *held = heldBegan;
3183
+ heldBegan = nil;
3184
+ if (prevented) return nil;
3185
+ // Local monitors run as events are dequeued; sending the held event to
3186
+ // its window directly does not come back through this monitor.
3187
+ if (held && phase != NSEventPhaseNone) [held.window sendEvent:held];
3188
+ return event;
3189
+ }];
3190
+ (void)wheelMonitor;
2594
3191
  bridge.originX = originX;
2595
3192
  bridge.originY = originY;
2596
3193
  }
@@ -2662,6 +3259,71 @@ void MacosRenderer::syncPanes(NSArray *paneViews, const int *rootNodeIds)
2662
3259
  }
2663
3260
  }
2664
3261
 
3262
+ void MacosRenderer::syncRoots(const SyncRoot *roots, unsigned long count)
3263
+ {
3264
+ const GeaSyncDepthScope syncScope;
3265
+ using namespace gea::embedded::ui;
3266
+ Tree &tree = Tree::instance();
3267
+ NSMutableSet<NSNumber *> *unseen = [NSMutableSet setWithArray:[nodeIdToView() allKeys]];
3268
+ std::vector<int> kept;
3269
+ for (unsigned long i = 0; i < count; i++) {
3270
+ const SyncRoot &root = roots[i];
3271
+ NSView *view = root.view;
3272
+ if (!view || root.node < 0 || root.node >= tree.nodeCount()) continue;
3273
+ if (root.keep) {
3274
+ kept.push_back(root.node);
3275
+ continue;
3276
+ }
3277
+ if (root.focusRoot >= 0) {
3278
+ GeaNativeBinding *binding = objc_getAssociatedObject(view, "gea.focus_root_binding");
3279
+ if (!binding || !gea::framework::identity::current(root.focusRoot, binding->owner) || binding->nodeId != root.focusRoot) {
3280
+ geaClearFocusedView(view);
3281
+ objc_setAssociatedObject(view, "gea.focus_root_binding", [[GeaNativeBinding alloc] initWithNode:root.focusRoot],
3282
+ OBJC_ASSOCIATION_RETAIN_NONATOMIC);
3283
+ }
3284
+ }
3285
+ ensureRootClickBridge(view, root.originX, root.originY);
3286
+ syncRecursive(root.node, view, root.originX, root.originY, static_cast<int>(view.bounds.size.height), unseen);
3287
+ }
3288
+ // A kept root's views were not visited; they are not gone.
3289
+ if (!kept.empty()) {
3290
+ NSMutableArray<NSNumber *> *stillThere = [NSMutableArray array];
3291
+ for (NSNumber *key in unseen) {
3292
+ const int nodeId = key.intValue;
3293
+ for (int id = nodeId, left = tree.nodeCount(); left > 0 && id >= 0 && id < tree.nodeCount(); --left, id = tree.node(id).parent) {
3294
+ if (std::find(kept.begin(), kept.end(), id) != kept.end()) {
3295
+ [stillThere addObject:key];
3296
+ break;
3297
+ }
3298
+ }
3299
+ }
3300
+ for (NSNumber *key in stillThere) [unseen removeObject:key];
3301
+ }
3302
+ for (NSNumber *gone in unseen) {
3303
+ NSView *v = nodeIdToView()[gone];
3304
+ geaRetireNativeView(v);
3305
+ [v removeFromSuperview];
3306
+ [nodeIdToView() removeObjectForKey:gone];
3307
+ }
3308
+ }
3309
+
3310
+ int nodeAtWindowPoint(NSWindow *window, CGPoint locationInWindow, int *treeX, int *treeY)
3311
+ {
3312
+ NSView *content = window.contentView;
3313
+ if (!content) return -1;
3314
+ NSView *frame = content.superview;
3315
+ NSView *hit = [content hitTest:frame ? [frame convertPoint:locationInWindow fromView:nil] : NSPoint(locationInWindow)];
3316
+ for (NSView *v = hit; v; v = v.superview) {
3317
+ GeaRootClickBridge *bridge = objc_getAssociatedObject(v, "gea.root_click_bridge");
3318
+ if (!bridge) continue;
3319
+ const NSPoint inRoot = [v convertPoint:locationInWindow fromView:nil];
3320
+ if (treeX) *treeX = static_cast<int>(std::lround(inRoot.x)) + bridge.originX;
3321
+ if (treeY) *treeY = static_cast<int>(std::lround(v.bounds.size.height - inRoot.y)) + bridge.originY;
3322
+ return nodeIdForView(hit);
3323
+ }
3324
+ return -1;
3325
+ }
3326
+
2665
3327
  void MacosRenderer::teardown()
2666
3328
  {
2667
3329
  for (NSView *v in [nodeIdToView() allValues]) {
@@ -2671,6 +3333,10 @@ void MacosRenderer::teardown()
2671
3333
  [nodeIdToView() removeAllObjects];
2672
3334
  }
2673
3335
 
3336
+ // macos_windows.mm defines the real one; renderer-only builds (the native
3337
+ // harness tests) have no hosted windows to focus.
3338
+ extern "C" __attribute__((weak)) bool gea_macos_focus_hosted_window(int) { return false; }
3339
+
2674
3340
  void nativeRootFocusChanged(NSView*view,bool focused,int node){
2675
3341
  if(!focused){geaNativeFocusEnded(view);return;}
2676
3342
  GeaNativeBinding*root=objc_getAssociatedObject(view,"gea.focus_root_binding");
@@ -2683,6 +3349,9 @@ void nativeRootFocusChanged(NSView*view,bool focused,int node){
2683
3349
  static gea::embedded::ui::NativeFocusResult requestFocusNode(gea::embedded::ui::NodeHandle node,bool focus){
2684
3350
  using namespace gea::embedded::ui;
2685
3351
  if(![NSThread isMainThread]||!node.valid()||!node.isConnected())return NativeFocusResult::refused;
3352
+ // `el.focus()` on a `<window>` brings its window to the front, as
3353
+ // window.focus() does in a browser. It never becomes the active input.
3354
+ if(Tree::instance().isDetachedRoot(node.id())){if(focus)gea_macos_focus_hosted_window(node.id());return NativeFocusResult::refused;}
2686
3355
  if(!focus){if(!geaFocused.node.valid()||geaFocused.node.identity()!=node.identity())return NativeFocusResult::accepted;NSView*view=geaFocused.view;if(!geaOwnsResponder(view)){geaNativeFocusEnded(view);return NativeFocusResult::accepted;}const BOOL accepted=[view.window makeFirstResponder:nil];if(accepted)geaNativeFocusEnded(view);return accepted?NativeFocusResult::accepted:NativeFocusResult::refused;}
2687
3356
  NSView*view=nodeIdToView()[@(node.id())];if(!view||!geaViewBindingCurrent(view,node.id())||!geaControlAdmitted(view,node.id()))return NativeFocusResult::refused;
2688
3357
  NSView*responder=view;