@windowkit/appkit 0.1.0 → 0.2.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@windowkit/appkit",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Retained-mode AppKit backend for Node.js: Core Animation (CALayer) layer trees, CoreText layout and drawing, IOSurface presentation, NSMenu, and native control bezels — the macOS half of react-x11.",
5
5
  "author": "Andrey Sidorov <andrey.sidorov@gmail.com>",
6
6
  "license": "MIT",
Binary file
package/src/backend.mm CHANGED
@@ -3,9 +3,10 @@
3
3
  // Everything here is mechanism, no policy: windows with delegates and
4
4
  // per-window event routing, an enriched event pump, CoreGraphics bitmap
5
5
  // surfaces with a canvas-shaped drawing API, a CoreText layout engine
6
- // (measure + draw + caret/hit geometry), pasteboard text, screen lists and
7
- // cursors. The retained-layer API stays in addon.mm; this file is what a
8
- // renderer paints and listens through.
6
+ // (measure + draw + caret/hit geometry) with glyph-level natives beside it
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.
9
10
  //
10
11
  // Coordinate rule, stated once: every point that crosses this boundary is
11
12
  // TOP-LEFT origin. Window frames and screen rects are top-left in global
@@ -1703,6 +1704,268 @@ static Napi::Value FontHasGlyph(const Napi::CallbackInfo& info) {
1703
1704
  return Napi::Boolean::New(info.Env(), ok);
1704
1705
  }
1705
1706
 
1707
+ // --- glyph-level natives ---------------------------------------------------
1708
+ //
1709
+ // createLayout/drawLayout shape text at the line level. A renderer that
1710
+ // positions glyphs itself — a terminal grid, a tabular column — needs the
1711
+ // glyph, its advance, a face that covers what the base face does not, and
1712
+ // a way to draw a run of ids at positions of its own choosing without a
1713
+ // typesetter in the middle (ctxDrawGlyphs, beside drawLayout below).
1714
+ // Shaping — ligatures, kerning, bidi — stays the typesetter's job; a grid
1715
+ // renderer bypasses it on purpose.
1716
+
1717
+ // A font handle is an External over an NSFont (matchFont) or a CTFont
1718
+ // (cgFontWithSize and friends); the two are toll-free bridged, so one
1719
+ // accessor serves both.
1720
+ static CTFontRef BFontFrom(Napi::Value v) {
1721
+ return (CTFontRef)v.As<Napi::External<void>>().Data();
1722
+ }
1723
+
1724
+ static bool BCheckFontArg(const Napi::CallbackInfo& info, const char* fn) {
1725
+ if (info[0].IsExternal()) return true;
1726
+ Napi::TypeError::New(info.Env(), std::string(fn) + ": expected a font handle")
1727
+ .ThrowAsJavaScriptException();
1728
+ return false;
1729
+ }
1730
+
1731
+ // One code point -> its UTF-16 form. False for a surrogate or an
1732
+ // out-of-range value.
1733
+ static bool BUtf16ForCodepoint(uint32_t cp, unichar out[2], CFIndex* len) {
1734
+ if (cp > 0x10FFFF || (cp >= 0xD800 && cp <= 0xDFFF)) return false;
1735
+ if (cp < 0x10000) {
1736
+ out[0] = (unichar)cp;
1737
+ *len = 1;
1738
+ return true;
1739
+ }
1740
+ cp -= 0x10000;
1741
+ out[0] = (unichar)(0xD800 + (cp >> 10));
1742
+ out[1] = (unichar)(0xDC00 + (cp & 0x3FF));
1743
+ *len = 2;
1744
+ return true;
1745
+ }
1746
+
1747
+ // A code point argument: a number, or a string read for its first code
1748
+ // point. False when there is none.
1749
+ static bool BCodepointArg(Napi::Value v, uint32_t* cp) {
1750
+ if (v.IsNumber()) {
1751
+ double d = v.As<Napi::Number>().DoubleValue();
1752
+ if (!(d >= 0 && d <= 0x10FFFF)) return false; // NaN fails too
1753
+ *cp = (uint32_t)d;
1754
+ return true;
1755
+ }
1756
+ if (v.IsString()) {
1757
+ std::u16string s = v.As<Napi::String>().Utf16Value();
1758
+ if (s.empty()) return false;
1759
+ uint32_t hi = s[0];
1760
+ if (hi >= 0xD800 && hi <= 0xDBFF && s.size() > 1 && s[1] >= 0xDC00 &&
1761
+ s[1] <= 0xDFFF) {
1762
+ *cp = 0x10000 + ((hi - 0xD800) << 10) + ((uint32_t)s[1] - 0xDC00);
1763
+ } else {
1764
+ *cp = hi;
1765
+ }
1766
+ return true;
1767
+ }
1768
+ return false;
1769
+ }
1770
+
1771
+ // The glyph a face maps one code point to, 0 when it does not: glyph 0 is
1772
+ // .notdef in every sfnt and what CTFontGetGlyphsForCharacters answers for
1773
+ // an unmapped character. A non-BMP character is sparse — its glyph sits in
1774
+ // the high surrogate's slot and the low surrogate's slot is 0 by design,
1775
+ // which is not a failure.
1776
+ static CGGlyph BGlyphForCodepoint(CTFontRef font, uint32_t cp) {
1777
+ unichar buf[2];
1778
+ CFIndex len = 0;
1779
+ if (!BUtf16ForCodepoint(cp, buf, &len)) return 0;
1780
+ CGGlyph glyphs[2] = {0, 0};
1781
+ CTFontGetGlyphsForCharacters(font, buf, glyphs, len);
1782
+ return glyphs[0];
1783
+ }
1784
+
1785
+ // Glyph ids for a run. A Uint16Array is used in place (CGGlyph is a
1786
+ // uint16); any other array of numbers is copied into `store`.
1787
+ static const CGGlyph* BGlyphsArg(Napi::Value v, std::vector<CGGlyph>* store,
1788
+ size_t* count) {
1789
+ if (v.IsTypedArray() &&
1790
+ v.As<Napi::TypedArray>().TypedArrayType() == napi_uint16_array) {
1791
+ Napi::Uint16Array a = v.As<Napi::Uint16Array>();
1792
+ *count = a.ElementLength();
1793
+ return a.Data();
1794
+ }
1795
+ store->clear();
1796
+ size_t n = v.IsTypedArray() ? v.As<Napi::TypedArray>().ElementLength()
1797
+ : v.IsArray() ? v.As<Napi::Array>().Length()
1798
+ : 0;
1799
+ if (n > 0) {
1800
+ Napi::Object o = v.As<Napi::Object>();
1801
+ store->reserve(n);
1802
+ for (uint32_t i = 0; i < n; i++) {
1803
+ Napi::Value e = o.Get(i);
1804
+ store->push_back(
1805
+ e.IsNumber() ? (CGGlyph)e.As<Napi::Number>().Uint32Value() : 0);
1806
+ }
1807
+ }
1808
+ *count = store->size();
1809
+ return store->data();
1810
+ }
1811
+
1812
+ // Glyph origins for a run, x0,y0,x1,y1,… in canvas space, converted into
1813
+ // the frame CTFontDrawGlyphs reads: its positions are in TEXT space — the
1814
+ // text matrix applies to them, not only to the outlines (the trap WebKit's
1815
+ // fillVectorWithHorizontalGlyphPositions documents) — and the text matrix
1816
+ // here is the y-flip, so each origin's y is negated on the way in. A
1817
+ // Float64Array is read directly; any other array of numbers is accepted.
1818
+ static void BGlyphOriginsArg(Napi::Value v, std::vector<CGPoint>* out) {
1819
+ out->clear();
1820
+ if (v.IsTypedArray() &&
1821
+ v.As<Napi::TypedArray>().TypedArrayType() == napi_float64_array) {
1822
+ Napi::Float64Array a = v.As<Napi::Float64Array>();
1823
+ const double* d = a.Data();
1824
+ size_t n = a.ElementLength() / 2;
1825
+ out->reserve(n);
1826
+ for (size_t i = 0; i < n; i++)
1827
+ out->push_back(CGPointMake(d[2 * i], -d[2 * i + 1]));
1828
+ return;
1829
+ }
1830
+ size_t n = v.IsTypedArray() ? v.As<Napi::TypedArray>().ElementLength()
1831
+ : v.IsArray() ? v.As<Napi::Array>().Length()
1832
+ : 0;
1833
+ if (n < 2) return;
1834
+ Napi::Object o = v.As<Napi::Object>();
1835
+ out->reserve(n / 2);
1836
+ for (uint32_t i = 0; i + 1 < n; i += 2) {
1837
+ Napi::Value x = o.Get(i), y = o.Get(i + 1);
1838
+ out->push_back(
1839
+ CGPointMake(x.IsNumber() ? x.As<Napi::Number>().DoubleValue() : 0,
1840
+ -(y.IsNumber() ? y.As<Napi::Number>().DoubleValue() : 0)));
1841
+ }
1842
+ }
1843
+
1844
+ // fontGlyphForCodepoint(font, codepoint) -> glyph id | null
1845
+ // The answer fontHasGlyph throws away. null when the face does not map the
1846
+ // code point — the caller wants "not covered" as a branch (pick a fallback
1847
+ // face), not glyph 0 discovered on screen. `codepoint` is a number; a
1848
+ // string is read for its first code point.
1849
+ static Napi::Value FontGlyphForCodepoint(const Napi::CallbackInfo& info) {
1850
+ Napi::Env env = info.Env();
1851
+ if (!BCheckFontArg(info, "fontGlyphForCodepoint")) return env.Undefined();
1852
+ uint32_t cp = 0;
1853
+ if (!BCodepointArg(info[1], &cp)) return env.Null();
1854
+ CGGlyph g = BGlyphForCodepoint(BFontFrom(info[0]), cp);
1855
+ if (g == 0) return env.Null();
1856
+ return Napi::Number::New(env, (double)g);
1857
+ }
1858
+
1859
+ // fontGlyphAdvances(font, glyphs: Uint16Array) -> Float64Array
1860
+ // Horizontal advances, in points at the handle's size — what a monospace
1861
+ // grid reads its cell width from (the advance of "0").
1862
+ static Napi::Value FontGlyphAdvances(const Napi::CallbackInfo& info) {
1863
+ Napi::Env env = info.Env();
1864
+ if (!BCheckFontArg(info, "fontGlyphAdvances")) return env.Undefined();
1865
+ std::vector<CGGlyph> store;
1866
+ size_t count = 0;
1867
+ const CGGlyph* glyphs = BGlyphsArg(info[1], &store, &count);
1868
+ Napi::Float64Array out = Napi::Float64Array::New(env, count);
1869
+ if (count == 0) return out;
1870
+ std::vector<CGSize> advances(count);
1871
+ CTFontGetAdvancesForGlyphs(BFontFrom(info[0]), kCTFontOrientationHorizontal,
1872
+ glyphs, advances.data(), (CFIndex)count);
1873
+ for (size_t i = 0; i < count; i++) out[i] = advances[i].width;
1874
+ return out;
1875
+ }
1876
+
1877
+ // Code points a cmap rarely lists and the typesetter never draws: C0/C1
1878
+ // controls and Unicode's default ignorables (soft hyphen, joiners, bidi
1879
+ // controls, variation selectors, tags). Coverage checks skip them.
1880
+ static bool BIgnorableForCoverage(uint32_t cp) {
1881
+ if (cp < 0x20 || (cp >= 0x7F && cp <= 0x9F)) return true;
1882
+ switch (cp >> 16) {
1883
+ case 0x00:
1884
+ return cp == 0x00AD || cp == 0x034F || cp == 0x061C ||
1885
+ (cp >= 0x115F && cp <= 0x1160) ||
1886
+ (cp >= 0x17B4 && cp <= 0x17B5) ||
1887
+ (cp >= 0x180B && cp <= 0x180F) ||
1888
+ (cp >= 0x200B && cp <= 0x200F) ||
1889
+ (cp >= 0x202A && cp <= 0x202E) ||
1890
+ (cp >= 0x2060 && cp <= 0x206F) || cp == 0x3164 ||
1891
+ (cp >= 0xFE00 && cp <= 0xFE0F) || cp == 0xFEFF ||
1892
+ cp == 0xFFA0 || (cp >= 0xFFF0 && cp <= 0xFFF8);
1893
+ case 0x01:
1894
+ return (cp >= 0x1BCA0 && cp <= 0x1BCA3) ||
1895
+ (cp >= 0x1D173 && cp <= 0x1D17A);
1896
+ case 0x0E:
1897
+ return true;
1898
+ default:
1899
+ return false;
1900
+ }
1901
+ }
1902
+
1903
+ // Does the face's cmap map every code point of `s` that would be drawn?
1904
+ static bool BFontCovers(CTFontRef font, NSString* s) {
1905
+ NSUInteger n = s.length;
1906
+ if (n == 0) return true;
1907
+ std::vector<unichar> chars(n);
1908
+ [s getCharacters:chars.data() range:NSMakeRange(0, n)];
1909
+ std::vector<CGGlyph> glyphs(n, 0);
1910
+ CTFontGetGlyphsForCharacters(font, chars.data(), glyphs.data(), (CFIndex)n);
1911
+ for (NSUInteger i = 0; i < n; i++) {
1912
+ uint32_t cp = chars[i];
1913
+ bool pair = cp >= 0xD800 && cp <= 0xDBFF && i + 1 < n &&
1914
+ chars[i + 1] >= 0xDC00 && chars[i + 1] <= 0xDFFF;
1915
+ if (pair) cp = 0x10000 + ((cp - 0xD800) << 10) + (chars[i + 1] - 0xDC00);
1916
+ if (glyphs[i] == 0 && !BIgnorableForCoverage(cp)) return false;
1917
+ if (pair) i++; // the low surrogate's slot is 0 by design
1918
+ }
1919
+ return true;
1920
+ }
1921
+
1922
+ // fontFallbackFor(font, text) -> font handle | null
1923
+ // CTFontCreateForString over the font's cascade list: the face CoreText
1924
+ // would substitute for `text`, at the same size — box drawing in a font
1925
+ // that has none, CJK, emoji. Answers the handle itself when the face
1926
+ // already covers the text (`fallback === font` reads as "no substitution
1927
+ // needed") and null when nothing covers it. `text` may also be a code
1928
+ // point number.
1929
+ static Napi::Value FontFallbackFor(const Napi::CallbackInfo& info) {
1930
+ Napi::Env env = info.Env();
1931
+ if (!BCheckFontArg(info, "fontFallbackFor")) return env.Undefined();
1932
+ CTFontRef font = BFontFrom(info[0]);
1933
+ NSString* text = nil;
1934
+ if (info[1].IsString()) {
1935
+ text = BToNSString(info[1]);
1936
+ } else {
1937
+ uint32_t cp = 0;
1938
+ unichar buf[2];
1939
+ CFIndex len = 0;
1940
+ if (BCodepointArg(info[1], &cp) && BUtf16ForCodepoint(cp, buf, &len))
1941
+ text = [NSString stringWithCharacters:buf length:(NSUInteger)len];
1942
+ }
1943
+ if (!text) return env.Null();
1944
+ if (text.length == 0) return info[0];
1945
+ CTFontRef sub = CTFontCreateForString(font, (__bridge CFStringRef)text,
1946
+ CFRangeMake(0, (CFIndex)text.length));
1947
+ if (!sub) return env.Null();
1948
+ if (CFEqual(sub, font)) {
1949
+ // CoreText hands the font itself back both when it covers the text
1950
+ // and when nothing in the cascade does; the cmap tells the two apart.
1951
+ CFRelease(sub);
1952
+ return BFontCovers(font, text) ? info[0] : env.Null();
1953
+ }
1954
+ // LastResort is CoreText's own "nothing covers it": a box with the
1955
+ // block's name in it. The caller asked for that as a branch, not a glyph.
1956
+ CFStringRef ps = CTFontCopyPostScriptName(sub);
1957
+ bool lastResort =
1958
+ ps && CFStringCompare(ps, CFSTR("LastResort"), 0) == kCFCompareEqualTo;
1959
+ if (ps) CFRelease(ps);
1960
+ if (lastResort) {
1961
+ CFRelease(sub);
1962
+ return env.Null();
1963
+ }
1964
+ return Napi::External<void>::New(env, (void*)sub, [](Napi::Env, void* d) {
1965
+ CFRelease(d);
1966
+ });
1967
+ }
1968
+
1706
1969
  // --- direct font handles (custom faces that bypass registry matching) -----
1707
1970
 
1708
1971
  static double CssWeightOfCTFont(CTFontRef ct) {
@@ -2148,6 +2411,46 @@ static Napi::Value DrawLayout(const Napi::CallbackInfo& info) {
2148
2411
  return info.Env().Undefined();
2149
2412
  }
2150
2413
 
2414
+ // ctxDrawGlyphs(surface, runs) — CTFontDrawGlyphs per run, no typesetter
2415
+ // in the middle.
2416
+ // runs: [{ font, glyphs: Uint16Array, positions: Float64Array x0,y0,… }]
2417
+ // Positions are canvas space (y down), one baseline origin per glyph; a
2418
+ // run draws min(glyphs, positions) of them. Honours the surface CTM and
2419
+ // clip like every other ctx verb and paints with the current fill colour,
2420
+ // so one call covers every run of one colour — the batch a terminal
2421
+ // renderer produces (one call per foreground colour per frame). The base
2422
+ // CTM is y-flipped for canvas semantics and glyph outlines are y-up, so
2423
+ // the text matrix flips them back, as in drawLayout; the positions ride
2424
+ // through that same matrix, hence the y negation in BGlyphOriginsArg.
2425
+ static Napi::Value CtxDrawGlyphs(const Napi::CallbackInfo& info) {
2426
+ CALSurface* s = SurfaceFrom(info[0]);
2427
+ if (!info[1].IsArray()) return info.Env().Undefined();
2428
+ Napi::Array runs = info[1].As<Napi::Array>();
2429
+ CGContextRef ctx = s->ctx;
2430
+ CGContextSaveGState(ctx);
2431
+ CGContextSetTextMatrix(ctx, CGAffineTransformMakeScale(1, -1));
2432
+ CGContextSetTextDrawingMode(ctx, kCGTextFill);
2433
+ std::vector<CGGlyph> glyphStore;
2434
+ std::vector<CGPoint> positionStore;
2435
+ for (uint32_t i = 0; i < runs.Length(); i++) {
2436
+ Napi::Value rv = runs.Get(i);
2437
+ if (!rv.IsObject()) continue;
2438
+ Napi::Object run = rv.As<Napi::Object>();
2439
+ Napi::Value fv = run.Get("font");
2440
+ if (!fv.IsExternal()) continue;
2441
+ size_t nGlyphs = 0;
2442
+ const CGGlyph* glyphs =
2443
+ BGlyphsArg(run.Get("glyphs"), &glyphStore, &nGlyphs);
2444
+ BGlyphOriginsArg(run.Get("positions"), &positionStore);
2445
+ size_t count = std::min(nGlyphs, positionStore.size());
2446
+ if (count == 0) continue;
2447
+ CTFontDrawGlyphs(BFontFrom(fv), glyphs, positionStore.data(),
2448
+ (CFIndex)count, ctx);
2449
+ }
2450
+ CGContextRestoreGState(ctx);
2451
+ return info.Env().Undefined();
2452
+ }
2453
+
2151
2454
  // drawLayoutGradient(surface, layoutHandle, x, y, x0, y0, x1, y1,
2152
2455
  // stops [offset,r,g,b,a,...])
2153
2456
  // The glyph outlines become the clip and a linear gradient fills through
@@ -2484,6 +2787,9 @@ void InitBackend(Napi::Env env, Napi::Object exports) {
2484
2787
  BFN("matchFont", MatchFont);
2485
2788
  BFN("fontMetrics", FontMetrics);
2486
2789
  BFN("fontHasGlyph", FontHasGlyph);
2790
+ BFN("fontGlyphForCodepoint", FontGlyphForCodepoint);
2791
+ BFN("fontGlyphAdvances", FontGlyphAdvances);
2792
+ BFN("fontFallbackFor", FontFallbackFor);
2487
2793
  BFN("fontFromData", FontFromData);
2488
2794
  BFN("cgFontWithSize", CgFontWithSize);
2489
2795
  BFN("fontByPostScriptName", FontByPostScriptName);
@@ -2494,6 +2800,7 @@ void InitBackend(Napi::Env env, Napi::Object exports) {
2494
2800
  BFN("loadFontData", LoadFontData);
2495
2801
  BFN("createLayout", CreateLayout);
2496
2802
  BFN("drawLayout", DrawLayout);
2803
+ BFN("ctxDrawGlyphs", CtxDrawGlyphs);
2497
2804
  BFN("layoutIndexAt", LayoutIndexAt);
2498
2805
  BFN("layoutCaret", LayoutCaret);
2499
2806
  BFN("pasteboardWriteText", PbWriteTextFn);