@windowkit/appkit 0.25.0 → 0.27.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/README.md CHANGED
@@ -431,6 +431,22 @@ the bridge turns them over where the layer's space is flipped; `presentationValu
431
431
  'contentsGravity')` answers Core Animation's name, `bottomLeft` for a `topLeft` here.
432
432
  Any other name, or a value that is not one, is a `TypeError`, and nothing is applied.
433
433
 
434
+ **Contents rect and center.** `setLayerProps`' `contentsRect` is the part of a layer's
435
+ contents it shows, and `contentsCenter` the part that stretches when they are scaled to
436
+ bounds that are not their size — what is outside it keeps its size, at its edge of the
437
+ bounds. Both are rects in the unit square of the contents, `[x, y, width, height]`, named
438
+ as they look: `y` runs down from the window's top, where Core Animation's runs up from the
439
+ layer's least `y`, so the bridge turns them over where the layer's space is not flipped,
440
+ as it does gravities. `null` is the whole square, the default for both. Between them a
441
+ frame whose bounds outgrew it can be shown at its size with its last column and row
442
+ carried over the rest — the way a page continues past its edge, where a gravity either
443
+ stretches the frame or leaves a strip of whatever is under it: `contentsRect` crops an
444
+ axis the bounds shrank on, and `contentsCenter` names the last pixel. Name its middle, a
445
+ sliver of it: a centre a whole pixel wide stretches what the filter makes of it and the
446
+ pixel before it, a blend of the two, and Core Animation ignores a centre of no width.
447
+ Four finite numbers or `null`, or the call is a `TypeError` naming the key, and nothing is
448
+ applied.
449
+
434
450
  **`native.transformForms()`** — `['translate', 'rotate', 'scale', 'matrix', 'matrix3d']`:
435
451
  the forms a transform takes on its way in. A caller that hands over matrices
436
452
  feature-detects `matrix` here; before 0.19 an object holding one was read as no transform
@@ -746,6 +762,31 @@ one tree sets its text in the same place on both. Below 1 the same split takes r
746
762
  both sides and the glyphs overflow a short box evenly; `0` is a box of no height, as CSS's
747
763
  `line-height: 0` is. An absent multiplier is 1.
748
764
 
765
+ ## Text: justified lines
766
+
767
+ `createLayout`'s `justify` sets lines to fill `maxWidth`: what a line leaves of the width is
768
+ shared equally among its word separators, each space and no-break space before the white
769
+ space it ends on that much wider — the white space it ends on hangs and takes none. That is
770
+ CSS Text 3's `text-justify: auto` for the scripts that space their words, and it is how ntk
771
+ justifies on X11 and Wayland. It is bits:
772
+
773
+ - **`1`** — every line that goes on to another, CSS's `text-align: justify`;
774
+ - **`2`** — the paragraph's last line and each a forced break ends (a line feed, a carriage
775
+ return or a paragraph separator; a line separator, U+2028, is not one);
776
+ - **`3`** — every line.
777
+
778
+ A line with no separator, or no width to spare, keeps the place `align` gives it, and a line
779
+ an ellipsis ends is not justified. The lines are the ones the typesetter breaks at the
780
+ width; justifying moves no break, and a kept typesetter (`keep`, below) laid out again at
781
+ another width is broken and spaced again without shaping anything. A justified line is
782
+ `maxWidth` wide, its runs, carets (`layoutCaret`) and hit tests (`layoutIndexAt`) are where
783
+ the wider separators put them, and `drawLayout`, `drawLayoutGradient` and `layoutCoverage`
784
+ draw its glyphs there.
785
+
786
+ It is not `CTLineCreateJustifiedLine`. Once a line's spaces have taken some share of their
787
+ own advance, CoreText's justification spaces the letters too, where a browser widens
788
+ nothing but the separators; and it gives the space a line ends on no advance at all.
789
+
749
790
  ## Text: a layout's coverage
750
791
 
751
792
  - **`native.layoutCoverage(layout, pad?)`** — `{ width, height, data }`: how much of each
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@windowkit/appkit",
3
- "version": "0.25.0",
3
+ "version": "0.27.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",
@@ -43,7 +43,7 @@
43
43
  "install": "node scripts/install.js",
44
44
  "build": "node-gyp rebuild",
45
45
  "demo": "node demo/demo.js",
46
- "test": "node test/app-lifecycle.js && node test/animation.js && node test/layer-transform.js && node test/contents-gravity.js && node test/accessibility-display.js && node test/ignores-mouse-events.js && node test/popup-menu.js && node test/surface-blit.js && node test/surface-faded.js && node test/image-smoothing.js && node test/surface-colorspace.js && node test/video-surface.js && node test/player.js && node test/round-rect-xy.js && node test/clip-rule.js && node test/control-bezels.js && node test/text-features.js && node test/font-from-data.js && node test/text-coverage.js && node test/text-typesetter.js && node test/text-line-height.js && node test/text-line-width.js && node test/text-scale.js && node test/symbols.js && node test/eventkit-permissions.js && node test/calendars.js && node test/calendar-writes.js && node test/screencolor.js && node test/notifications.js && node test/threaded.js && node test/threaded-verbs.js && node test/threaded-frames.js && node test/threaded-resize.js && node test/ending-worker.js && node test/live-resize.js && node test/activation-policy.js"
46
+ "test": "node test/app-lifecycle.js && node test/animation.js && node test/layer-transform.js && node test/contents-gravity.js && node test/contents-center.js && node test/accessibility-display.js && node test/ignores-mouse-events.js && node test/popup-menu.js && node test/surface-blit.js && node test/surface-faded.js && node test/image-smoothing.js && node test/surface-colorspace.js && node test/video-surface.js && node test/player.js && node test/round-rect-xy.js && node test/clip-rule.js && node test/control-bezels.js && node test/text-features.js && node test/font-from-data.js && node test/text-coverage.js && node test/text-typesetter.js && node test/text-line-height.js && node test/text-line-width.js && node test/text-justify.js && node test/text-scale.js && node test/symbols.js && node test/eventkit-permissions.js && node test/calendars.js && node test/calendar-writes.js && node test/screencolor.js && node test/notifications.js && node test/threaded.js && node test/threaded-verbs.js && node test/threaded-frames.js && node test/threaded-resize.js && node test/ending-worker.js && node test/live-resize.js && node test/activation-policy.js"
47
47
  },
48
48
  "dependencies": {
49
49
  "node-addon-api": "^8.3.0"
Binary file
package/src/addon.mm CHANGED
@@ -585,6 +585,10 @@ struct LayerPropsSpec {
585
585
  CATransform3D transform = CATransform3DIdentity;
586
586
  bool hasGravity = false, badGravity = false;
587
587
  NSString* gravity = nil; // as named: the window's top is `top`
588
+ // unit rects as named: y down from the window's top (`CALUnitRect`)
589
+ bool hasContentsRect = false, hasContentsCenter = false;
590
+ const char* badUnitRect = nullptr; // the key of a value that is no unit rect
591
+ CGRect contentsRect = CGRectMake(0, 0, 1, 1), contentsCenter = CGRectMake(0, 0, 1, 1);
588
592
  };
589
593
 
590
594
  // `contentsGravity`: how a layer's contents sit in bounds that are not
@@ -626,6 +630,44 @@ static NSString* CALGravity(CALayer* L, NSString* name) {
626
630
  return kCAGravityResize;
627
631
  }
628
632
 
633
+ // `contentsRect` and `contentsCenter`, rects in the unit square of a layer's
634
+ // contents, [x, y, width, height]: four finite numbers, or null for the whole
635
+ // square, which is Core Animation's default for both. `contentsRect` is the
636
+ // part of the contents the layer shows. `contentsCenter` is the part that
637
+ // stretches when the contents are scaled to bounds that are not their size —
638
+ // what is outside it keeps its size, at its edge of the bounds — so a frame
639
+ // whose bounds outgrew it can be shown at its size with its last column and
640
+ // row carried over the rest, the way a page continues past its edge, where
641
+ // gravity alone either stretches it or leaves a strip of whatever is under
642
+ // it.
643
+ static bool UnitRectFrom(Napi::Value v, CGRect* out) {
644
+ if (v.IsNull() || v.IsUndefined()) {
645
+ *out = CGRectMake(0, 0, 1, 1);
646
+ return true;
647
+ }
648
+ if (!v.IsArray() || v.As<Napi::Array>().Length() != 4) return false;
649
+ Napi::Array a = v.As<Napi::Array>();
650
+ double c[4];
651
+ for (uint32_t i = 0; i < 4; i++) {
652
+ Napi::Value e = a.Get(i);
653
+ if (!e.IsNumber()) return false;
654
+ c[i] = e.As<Napi::Number>().DoubleValue();
655
+ if (!std::isfinite(c[i])) return false;
656
+ }
657
+ *out = CGRectMake(c[0], c[1], c[2], c[3]);
658
+ return true;
659
+ }
660
+
661
+ // A unit rect named as it looks, y down from the window's top, made Core
662
+ // Animation's on the UI thread, where the layer can say whether its space is
663
+ // flipped. CA's unit square is the layer's own space, as its gravities are
664
+ // (`CALGravity`): its least y is the window's top where the contents are
665
+ // flipped, under a window's geometry-flipped root, and the bottom elsewhere.
666
+ static CGRect CALUnitRect(CALayer* L, CGRect r) {
667
+ if (L.contentsAreFlipped) return r;
668
+ return CGRectMake(r.origin.x, 1 - r.origin.y - r.size.height, r.size.width, r.size.height);
669
+ }
670
+
629
671
  static LayerPropsSpec ParseLayerProps(Napi::Object o) {
630
672
  LayerPropsSpec s;
631
673
  if (o.Has("frame")) {
@@ -694,6 +736,12 @@ static LayerPropsSpec ParseLayerProps(Napi::Object o) {
694
736
  s.gravity = g.IsString() ? ToNSString(g) : nil;
695
737
  s.badGravity = !CALGravityKnown(s.gravity);
696
738
  }
739
+ if ((s.hasContentsRect = o.Has("contentsRect")) &&
740
+ !UnitRectFrom(o.Get("contentsRect"), &s.contentsRect))
741
+ s.badUnitRect = "contentsRect";
742
+ if ((s.hasContentsCenter = o.Has("contentsCenter")) &&
743
+ !UnitRectFrom(o.Get("contentsCenter"), &s.contentsCenter))
744
+ s.badUnitRect = "contentsCenter";
697
745
  return s;
698
746
  }
699
747
 
@@ -724,6 +772,8 @@ static void ApplyLayerProps(CALayer* L, const LayerPropsSpec& s) {
724
772
  L.contents = nil;
725
773
  }
726
774
  if (s.hasGravity) L.contentsGravity = CALGravity(L, s.gravity);
775
+ if (s.hasContentsRect) L.contentsRect = CALUnitRect(L, s.contentsRect);
776
+ if (s.hasContentsCenter) L.contentsCenter = CALUnitRect(L, s.contentsCenter);
727
777
  }
728
778
 
729
779
  static Napi::Value SetLayerProps(const Napi::CallbackInfo& info) {
@@ -734,6 +784,14 @@ static Napi::Value SetLayerProps(const Napi::CallbackInfo& info) {
734
784
  .ThrowAsJavaScriptException();
735
785
  return info.Env().Undefined();
736
786
  }
787
+ if (s.badUnitRect) {
788
+ Napi::TypeError::New(info.Env(),
789
+ std::string(s.badUnitRect) +
790
+ ": [x, y, width, height], four finite numbers in the unit "
791
+ "square of the contents, y down from the top, or null")
792
+ .ThrowAsJavaScriptException();
793
+ return info.Env().Undefined();
794
+ }
737
795
  if (s.badGravity) {
738
796
  Napi::TypeError::New(info.Env(),
739
797
  "contentsGravity: resize, resizeAspect, resizeAspectFill, center, "
package/src/backend.mm CHANGED
@@ -31,7 +31,7 @@
31
31
  #include <mutex>
32
32
  #include <string>
33
33
  #include <unordered_map>
34
- #include <vector>
34
+ #include <algorithm>
35
35
  #include <vector>
36
36
 
37
37
  #include "channel.h"
@@ -5593,8 +5593,41 @@ struct CALLine {
5593
5593
  // (BDrawGlyphsAtScale)
5594
5594
  bool bitmapsAtScale = false;
5595
5595
  std::vector<CALRun> runs;
5596
+ // A justified line (`justify`): its word separators' left edges and
5597
+ // widths as the typesetter set them, from the line's origin, in visual
5598
+ // order, and the room each was widened by. Everything to a separator's
5599
+ // right is that much further right, which every reader of the line adds
5600
+ // (JustifiedX) or takes away (UnjustifiedX).
5601
+ double justifyExtra = 0;
5602
+ std::vector<double> sepX, sepW;
5596
5603
  };
5597
5604
 
5605
+ // Where a point of a justified line is, `ux` as the typesetter set it: the
5606
+ // room of every separator left of it added. A caret at a separator's left
5607
+ // edge is before it, and one at its right edge after it.
5608
+ static double JustifiedX(const CALLine& L, double ux) {
5609
+ if (L.justifyExtra <= 0) return ux;
5610
+ size_t k = std::lower_bound(L.sepX.begin(), L.sepX.end(), ux - 1e-6) -
5611
+ L.sepX.begin();
5612
+ return ux + L.justifyExtra * (double)k;
5613
+ }
5614
+
5615
+ // The inverse, for a hit test: a point inside a widened separator is in it,
5616
+ // at its share of the separator's own advance.
5617
+ static double UnjustifiedX(const CALLine& L, double x) {
5618
+ if (L.justifyExtra <= 0) return x;
5619
+ const double e = L.justifyExtra;
5620
+ for (size_t i = 0; i < L.sepX.size(); i++) {
5621
+ const double left = L.sepX[i] + e * (double)i;
5622
+ if (x < left) return x - e * (double)i;
5623
+ const double width = L.sepW[i] + e;
5624
+ if (x < left + width) {
5625
+ return L.sepX[i] + (x - left) * (width > 0 ? L.sepW[i] / width : 0);
5626
+ }
5627
+ }
5628
+ return x - e * (double)L.sepX.size();
5629
+ }
5630
+
5598
5631
  struct CALLayout {
5599
5632
  std::vector<CALLine> lines;
5600
5633
  double width = 0, height = 0;
@@ -5778,10 +5811,67 @@ static long UnfitClusterRunsOn(CTTypesetterRef ts, NSString* text,
5778
5811
  return std::max(count, end - start);
5779
5812
  }
5780
5813
 
5814
+ // A line set to fill `free` more of its width (`justify`): what it leaves
5815
+ // shared equally among its word separators, the spaces and no-break spaces
5816
+ // before the white space it ends on, which hangs and takes none — CSS Text
5817
+ // 3's `text-justify: auto` for the scripts that space their words, as
5818
+ // ntk's layout sets it. Not CTLineCreateJustifiedLine: CoreText spaces the
5819
+ // letters too once a line's spaces have taken some share of their own
5820
+ // advance, where a browser widens nothing but its separators, and gives the
5821
+ // space a line ends on no advance at all. The line keeps the typesetter's
5822
+ // glyphs; where they are drawn, measured and hit is moved by the separators
5823
+ // left of them (JustifiedX). False where it has no separator.
5824
+ static bool JustifyLine(CALLine& L, NSString* text, long start, long end,
5825
+ double free, std::vector<long>* sepIdx) {
5826
+ long hang = end;
5827
+ while (hang > start) {
5828
+ unichar c = [text characterAtIndex:(NSUInteger)(hang - 1)];
5829
+ if (c != ' ' && c != '\t' && c != '\n' && c != '\r' && c != 0x2028 &&
5830
+ c != 0x2029)
5831
+ break;
5832
+ hang--;
5833
+ }
5834
+ std::vector<std::pair<double, double>> seps;
5835
+ std::vector<CGPoint> positions;
5836
+ CFArrayRef runs = CTLineGetGlyphRuns(L.line);
5837
+ for (CFIndex ri = 0; ri < CFArrayGetCount(runs); ri++) {
5838
+ CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runs, ri);
5839
+ const CFIndex count = CTRunGetGlyphCount(run);
5840
+ if (count <= 0) continue;
5841
+ std::vector<CFIndex> indices((size_t)count);
5842
+ CTRunGetStringIndices(run, CFRangeMake(0, 0), indices.data());
5843
+ BRunPositions(run, &positions);
5844
+ for (CFIndex g = 0; g < count; g++) {
5845
+ const long at = (long)indices[(size_t)g];
5846
+ if (at < start || at >= hang) continue;
5847
+ unichar c = [text characterAtIndex:(NSUInteger)at];
5848
+ if (c != ' ' && c != 0xA0) continue;
5849
+ // one glyph for the one character: a space shaped into anything else
5850
+ // is no separator to widen
5851
+ if ((g + 1 < count && indices[(size_t)g + 1] == indices[(size_t)g]) ||
5852
+ (g > 0 && indices[(size_t)g - 1] == indices[(size_t)g]))
5853
+ continue;
5854
+ const double w = CTRunGetTypographicBounds(run, CFRangeMake(g, 1),
5855
+ nullptr, nullptr, nullptr);
5856
+ seps.push_back({positions[(size_t)g].x, w});
5857
+ sepIdx->push_back(at);
5858
+ }
5859
+ }
5860
+ if (seps.empty()) return false;
5861
+ std::sort(seps.begin(), seps.end());
5862
+ L.justifyExtra = free / (double)seps.size();
5863
+ for (const auto& sep : seps) {
5864
+ L.sepX.push_back(sep.first);
5865
+ L.sepW.push_back(sep.second);
5866
+ }
5867
+ std::sort(sepIdx->begin(), sepIdx->end());
5868
+ return true;
5869
+ }
5870
+
5781
5871
  // createLayout({ spans: [{text, font (handle), color:[r,g,b,a]}],
5782
5872
  // maxWidth?, align: 0 left | 0.5 center | 1 right,
5783
5873
  // lineHeight?, maxLines?, ellipsis?, rtl?,
5784
- // keep?, typesetter?, packed? })
5874
+ // keep?, typesetter?, packed?, justify? })
5785
5875
  // -> { handle, width, height,
5786
5876
  // lines: [{x,y,width,height,baseline,descent,start,end,
5787
5877
  // runs:[{x,width,start,end,rtl}]}],
@@ -5796,6 +5886,16 @@ static long UnfitClusterRunsOn(CTTypesetterRef ts, NSString* text,
5796
5886
  // x, y, width, height, baseline, ascent, descent, start, end and how many
5797
5887
  // runs it has — and `runData`, five a run in line order — x, width, start,
5798
5888
  // end, and 1 when it runs right to left.
5889
+ //
5890
+ // `justify` sets lines to fill `maxWidth` at their word separators
5891
+ // (JustifyLine), as bits: 1 for every line that goes on to another, 2 for
5892
+ // the paragraph's last and each a forced break ends — a line feed, a
5893
+ // carriage return or a paragraph separator, and not a line separator. A
5894
+ // line an ellipsis ends is not justified, and one with no separator keeps
5895
+ // `align`'s place. Its width is then `maxWidth`, and its runs, its carets,
5896
+ // its hit tests and its drawing are where the wider separators put them.
5897
+ // The breaks are the typesetter's at the width: a kept typesetter (`keep`)
5898
+ // is broken and spaced again at another, and nothing is shaped.
5799
5899
  static Napi::Value CreateLayout(const Napi::CallbackInfo& info) {
5800
5900
  Napi::Env env = info.Env();
5801
5901
  Napi::Object o = info[0].As<Napi::Object>();
@@ -5812,6 +5912,7 @@ static Napi::Value CreateLayout(const Napi::CallbackInfo& info) {
5812
5912
  bool rtl = BBoolOr(o, "rtl", false);
5813
5913
  bool keep = BBoolOr(o, "keep", false);
5814
5914
  bool packed = BBoolOr(o, "packed", false);
5915
+ const int justify = (int)BNumOr(o, "justify", 0);
5815
5916
  if (ellipsis && maxLines <= 0) maxLines = 1;
5816
5917
 
5817
5918
  CALTypesetter* shaped = nullptr;
@@ -5906,13 +6007,28 @@ static Napi::Value CreateLayout(const Napi::CallbackInfo& info) {
5906
6007
  L.baseline = y + halfLeading + ascent;
5907
6008
  L.start = start;
5908
6009
  L.end = lineEnd;
6010
+ bool stops = false;
5909
6011
  if (lineEnd > start) {
5910
6012
  unichar last = [[as string] characterAtIndex:(NSUInteger)(lineEnd - 1)];
5911
6013
  L.hardBreak =
5912
6014
  last == '\n' || last == '\r' || last == 0x2028 || last == 0x2029;
6015
+ stops = last == '\n' || last == '\r' || last == 0x2029;
6016
+ }
6017
+ // the line's place in the paragraph, for `justify`: its last, which a
6018
+ // `maxLines` cut leaves no line, or one a forced break ends
6019
+ const int role = lineEnd >= total || stops ? 2 : 1;
6020
+ std::vector<long> sepIdx;
6021
+ double spread = 0;
6022
+ if (bounded && (justify & role) && !elided && maxWidth - lw > 0 &&
6023
+ JustifyLine(L, as.string, start, lineEnd, maxWidth - lw,
6024
+ &sepIdx)) {
6025
+ spread = maxWidth - lw;
6026
+ L.width = maxWidth;
5913
6027
  }
5914
6028
  if (bounded && flush > 0) {
5915
- L.x = CTLineGetPenOffsetForFlush(line, flush, maxWidth);
6029
+ // as wide as the width now, where it was justified
6030
+ L.x = CTLineGetPenOffsetForFlush(line, flush, maxWidth) -
6031
+ flush * spread;
5916
6032
  }
5917
6033
  // runs, for selection bands
5918
6034
  CFArrayRef runs = CTLineGetGlyphRuns(line);
@@ -5943,15 +6059,23 @@ static Napi::Value CreateLayout(const Napi::CallbackInfo& info) {
5943
6059
  }
5944
6060
  }
5945
6061
  CALRun R;
5946
- R.x = rx;
6062
+ R.x = JustifiedX(L, rx);
5947
6063
  R.width = rwidth;
5948
6064
  R.start = range.location;
5949
6065
  R.end = range.location + range.length;
6066
+ if (!sepIdx.empty()) {
6067
+ // and as much wider as its separators were widened
6068
+ const auto from =
6069
+ std::lower_bound(sepIdx.begin(), sepIdx.end(), (long)R.start);
6070
+ const auto to =
6071
+ std::lower_bound(sepIdx.begin(), sepIdx.end(), (long)R.end);
6072
+ R.width += L.justifyExtra * (double)(to - from);
6073
+ }
5950
6074
  R.rtl = (CTRunGetStatus(run) & kCTRunStatusRightToLeft) != 0;
5951
6075
  L.runs.push_back(R);
5952
6076
  }
5953
6077
  layout->lines.push_back(L);
5954
- layout->width = std::max(layout->width, lw);
6078
+ layout->width = std::max(layout->width, L.width);
5955
6079
  y += advance;
5956
6080
  lineIndex++;
5957
6081
  start = lineEnd;
@@ -6053,7 +6177,8 @@ static Napi::Value DrawLayout(const Napi::CallbackInfo& info) {
6053
6177
  CGContextSetTextMatrix(ctx, CGAffineTransformMakeScale(1, -1));
6054
6178
  std::vector<CGPoint> positions;
6055
6179
  for (const CALLine& L : layout->lines) {
6056
- if (!L.bitmapsAtScale) {
6180
+ const bool justified = L.justifyExtra > 0;
6181
+ if (!L.bitmapsAtScale && !justified) {
6057
6182
  CGContextSetTextPosition(ctx, x + L.x, y + L.baseline);
6058
6183
  CTLineDraw(L.line, ctx);
6059
6184
  continue;
@@ -6061,12 +6186,13 @@ static Napi::Value DrawLayout(const Napi::CallbackInfo& info) {
6061
6186
  // a line with a scaled face's bitmap glyphs in it is drawn a run at a
6062
6187
  // time, and a scaled run at its face's point size under a scaled CTM:
6063
6188
  // CTRunDraw, unlike CTLineDraw, does not draw through the font matrix
6064
- // either, outlines included
6189
+ // either, outlines included. A justified line is drawn a run at a time
6190
+ // too, each glyph where its line's separators move it (JustifiedX).
6065
6191
  CFArrayRef runs = CTLineGetGlyphRuns(L.line);
6066
6192
  for (CFIndex ri = 0; ri < CFArrayGetCount(runs); ri++) {
6067
6193
  CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runs, ri);
6068
6194
  CTFontRef font = BRunFont(run);
6069
- if (!font || BFontScale(font) == 1) {
6195
+ if (!font || (BFontScale(font) == 1 && !justified)) {
6070
6196
  CGContextSetTextPosition(ctx, x + L.x, y + L.baseline);
6071
6197
  CTRunDraw(run, ctx, CFRangeMake(0, 0));
6072
6198
  continue;
@@ -6076,6 +6202,9 @@ static Napi::Value DrawLayout(const Napi::CallbackInfo& info) {
6076
6202
  std::vector<CGGlyph> glyphs((size_t)count);
6077
6203
  CTRunGetGlyphs(run, CFRangeMake(0, 0), glyphs.data());
6078
6204
  BRunPositions(run, &positions);
6205
+ if (justified) {
6206
+ for (CGPoint& p : positions) p.x = JustifiedX(L, p.x);
6207
+ }
6079
6208
  CGContextSaveGState(ctx);
6080
6209
  CGColorRef ink = (CGColorRef)CFDictionaryGetValue(
6081
6210
  CTRunGetAttributes(run), kCTForegroundColorAttributeName);
@@ -6296,7 +6425,7 @@ static Napi::Value DrawLayoutGradient(const Napi::CallbackInfo& info) {
6296
6425
  BRunPositions(run, &positions);
6297
6426
  for (CFIndex g = 0; g < count; g++) {
6298
6427
  CGAffineTransform t = {1, 0, 0, -1,
6299
- x + L.x + positions[(size_t)g].x,
6428
+ x + L.x + JustifiedX(L, positions[(size_t)g].x),
6300
6429
  y + L.baseline - positions[(size_t)g].y};
6301
6430
  CGPathRef gp = CTFontCreatePathForGlyph(font, glyphs[(size_t)g], &t);
6302
6431
  if (gp) {
@@ -6572,7 +6701,7 @@ static Napi::Value LayoutCoverage(const Napi::CallbackInfo& info) {
6572
6701
  if (glyphs[g] == kCGFontIndexInvalid) continue;
6573
6702
  // positions are from the line's origin, y up; outlines are y up
6574
6703
  // from the glyph's origin, flipped here into canvas space
6575
- const double ox = pad + L.x + positions[g].x;
6704
+ const double ox = pad + L.x + JustifiedX(L, positions[g].x);
6576
6705
  const double oy = pad + L.baseline - positions[g].y;
6577
6706
  const CGAffineTransform t = {1, 0, 0, -1, ox, oy};
6578
6707
  CGPathRef outline = CTFontCreatePathForGlyph(font, glyphs[g], &t);
@@ -6667,8 +6796,8 @@ static Napi::Value LayoutIndexAt(const Napi::CallbackInfo& info) {
6667
6796
  break;
6668
6797
  }
6669
6798
  }
6670
- CFIndex idx =
6671
- CTLineGetStringIndexForPosition(pick->line, CGPointMake(x - pick->x, 0));
6799
+ CFIndex idx = CTLineGetStringIndexForPosition(
6800
+ pick->line, CGPointMake(UnjustifiedX(*pick, x - pick->x), 0));
6672
6801
  if (idx == kCFNotFound) idx = pick->end;
6673
6802
  // Trailing-newline aware, ntk's contract: a hit at or past the right edge
6674
6803
  // of a hard-wrapped line answers the end of its VISIBLE content. The index
@@ -6705,7 +6834,8 @@ static Napi::Value LayoutCaret(const Napi::CallbackInfo& info) {
6705
6834
  }
6706
6835
  }
6707
6836
  const CALLine* pick = &layout->lines[li];
6708
- double x = CTLineGetOffsetForStringIndex(pick->line, idx, NULL);
6837
+ double x =
6838
+ JustifiedX(*pick, CTLineGetOffsetForStringIndex(pick->line, idx, NULL));
6709
6839
  r.Set("x", pick->x + x);
6710
6840
  r.Set("y", pick->y);
6711
6841
  r.Set("height", pick->height);