@ng-native/desktop 0.24.0 → 0.25.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.
@@ -1,5 +1,10 @@
1
1
  #import "scrollers.h"
2
2
 
3
+ #import <QuartzCore/QuartzCore.h>
4
+
5
+ #include <algorithm>
6
+ #include <cmath>
7
+
3
8
  ngn::ScrollerStyle NGNPreferredScrollerStyle() {
4
9
  return NSScroller.preferredScrollerStyle == NSScrollerStyleLegacy ? ngn::ScrollerStyle::Legacy
5
10
  : ngn::ScrollerStyle::Overlay;
@@ -32,12 +37,226 @@ float NGNLegacyScrollerWidth(BOOL thin) {
32
37
 
33
38
  @end
34
39
 
35
- @implementation NGNWheelScrollView
40
+ NSEvent *NGNMirroredScroll(NSEvent *event, BOOL x, BOOL y) {
41
+ if ((!x && !y) || event.CGEvent == nullptr) {
42
+ return event;
43
+ }
44
+ CGEventRef cg = CGEventCreateCopy(event.CGEvent);
45
+ // Setting the lines recomputes the other two from them, so all three are read first and set in
46
+ // this order. The points are read as a double, which keeps a trackpad's fractions.
47
+ auto negate = [cg](CGEventField lines, CGEventField fixed, CGEventField points) {
48
+ int64_t l = CGEventGetIntegerValueField(cg, lines);
49
+ double f = CGEventGetDoubleValueField(cg, fixed), p = CGEventGetDoubleValueField(cg, points);
50
+ CGEventSetIntegerValueField(cg, lines, -l);
51
+ CGEventSetDoubleValueField(cg, fixed, -f);
52
+ CGEventSetDoubleValueField(cg, points, -p);
53
+ };
54
+ if (y) {
55
+ negate(kCGScrollWheelEventDeltaAxis1, kCGScrollWheelEventFixedPtDeltaAxis1, kCGScrollWheelEventPointDeltaAxis1);
56
+ }
57
+ if (x) {
58
+ negate(kCGScrollWheelEventDeltaAxis2, kCGScrollWheelEventFixedPtDeltaAxis2, kCGScrollWheelEventPointDeltaAxis2);
59
+ }
60
+ NSEvent *mirrored = [NSEvent eventWithCGEvent:cg];
61
+ CFRelease(cg);
62
+ return mirrored != nil ? mirrored : event;
63
+ }
64
+
65
+ @implementation NGNWheelScrollView {
66
+ // The gesture under way goes up the responder chain: it began along an axis this view cannot
67
+ // scroll along.
68
+ BOOL _passing;
69
+ // A gesture's start with no deltas yet, held until an event says which axis it goes along.
70
+ NSEvent *_heldStart;
71
+ // The gesture under way ended in a page settling, so its momentum moves nothing.
72
+ BOOL _settling;
73
+ // A drag has begun and not yet ended: an end with no beginning (a touch that never moved) reports
74
+ // nothing and settles nothing.
75
+ BOOL _dragging;
76
+ NSPoint _velocity;
77
+ NSTimeInterval _lastWheel;
78
+ // When the deltas last moved: a drag held still before it ends was not flicked.
79
+ NSTimeInterval _lastMove;
80
+ // Moved on by each page settling, so only the latest one's end is reported.
81
+ uint64_t _settle;
82
+ BOOL _settleUnderway;
83
+ // A mouse's wheel queued a settling that has not run.
84
+ BOOL _settleQueued;
85
+ }
86
+
87
+ - (void)setPagingEnabled:(BOOL)pagingEnabled {
88
+ _pagingEnabled = pagingEnabled;
89
+ if (!pagingEnabled) {
90
+ [self dropSettle];
91
+ }
92
+ }
93
+
94
+ // Whether the content overflows the view along the axis the deltas mostly go along.
95
+ - (BOOL)scrollsAlong:(NSEvent *)event {
96
+ NSSize content = self.documentView.frame.size, view = self.contentView.bounds.size;
97
+ if (std::fabs(event.scrollingDeltaX) > std::fabs(event.scrollingDeltaY)) {
98
+ return content.width > view.width + 0.5;
99
+ }
100
+ return content.height > view.height + 0.5;
101
+ }
102
+
103
+ // Whether the view is drawn mirrored along each axis: an odd number of the layers above it scaled
104
+ // by a negative amount along it.
105
+ - (void)mirroredX:(BOOL *)x y:(BOOL *)y {
106
+ *x = NO;
107
+ *y = NO;
108
+ for (NSView *view = self; view != nil; view = view.superview) {
109
+ CATransform3D t = view.layer.transform;
110
+ *x ^= t.m11 < 0;
111
+ *y ^= t.m22 < 0;
112
+ }
113
+ }
114
+
36
115
  - (void)scrollWheel:(NSEvent *)event {
37
116
  if (self.scrollingDisabled) {
38
117
  [self.nextResponder scrollWheel:event];
39
118
  return;
40
119
  }
41
- [super scrollWheel:event];
120
+ NSEventPhase phase = event.phase, momentum = event.momentumPhase;
121
+ BOOL wheel = phase == NSEventPhaseNone && momentum == NSEventPhaseNone;
122
+ BOOL still = event.scrollingDeltaX == 0 && event.scrollingDeltaY == 0;
123
+ if (phase == NSEventPhaseMayBegin) {
124
+ _passing = NO;
125
+ _heldStart = nil;
126
+ } else if (phase == NSEventPhaseBegan && still) {
127
+ _heldStart = event;
128
+ _passing = NO;
129
+ // A settling the wheel queued waits until the gesture's direction says whose it is.
130
+ [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(settleOnPage) object:nil];
131
+ return;
132
+ } else if (phase == NSEventPhaseBegan || wheel || (_heldStart != nil && !still)) {
133
+ _passing = ![self scrollsAlong:event];
134
+ _settling = NO;
135
+ if (!wheel && _settleQueued) {
136
+ // A gesture this view takes settles itself; one that goes past leaves the wheel's to run.
137
+ if (_passing) {
138
+ [self queueSettle];
139
+ } else {
140
+ [self dropSettle];
141
+ }
142
+ }
143
+ }
144
+ if (_heldStart != nil && (!still || (phase != NSEventPhaseChanged && phase != NSEventPhaseStationary))) {
145
+ NSEvent *start = _heldStart;
146
+ _heldStart = nil;
147
+ [self scrollDecided:start];
148
+ }
149
+ [self scrollDecided:event];
42
150
  }
151
+
152
+ // An event of a gesture whose route is decided.
153
+ - (void)scrollDecided:(NSEvent *)event {
154
+ NSEventPhase phase = event.phase, momentum = event.momentumPhase;
155
+ BOOL wheel = phase == NSEventPhaseNone && momentum == NSEventPhaseNone;
156
+ if (_passing) {
157
+ [self.nextResponder scrollWheel:event];
158
+ return;
159
+ }
160
+ BOOL x, y;
161
+ [self mirroredX:&x y:&y];
162
+ NSEvent *scroll = NGNMirroredScroll(event, x, y);
163
+ if (momentum != NSEventPhaseNone && _settling) {
164
+ if (momentum == NSEventPhaseEnded || momentum == NSEventPhaseCancelled) {
165
+ _settling = NO;
166
+ }
167
+ return;
168
+ }
169
+ if (phase == NSEventPhaseBegan || phase == NSEventPhaseChanged || wheel) {
170
+ NSTimeInterval elapsed = std::max(scroll.timestamp - _lastWheel, 0.001);
171
+ _lastWheel = scroll.timestamp;
172
+ if (scroll.scrollingDeltaX != 0 || scroll.scrollingDeltaY != 0) {
173
+ // AppKit's deltas move the content; the offset goes the other way. A mouse's are in lines.
174
+ CGFloat across = scroll.hasPreciseScrollingDeltas ? 1 : self.horizontalLineScroll;
175
+ CGFloat down = scroll.hasPreciseScrollingDeltas ? 1 : self.verticalLineScroll;
176
+ _velocity = NSMakePoint(-scroll.scrollingDeltaX * across / (elapsed * 1000),
177
+ -scroll.scrollingDeltaY * down / (elapsed * 1000));
178
+ _lastMove = scroll.timestamp;
179
+ }
180
+ }
181
+ [super scrollWheel:scroll];
182
+ if (phase == NSEventPhaseBegan) {
183
+ _velocity = NSZeroPoint;
184
+ _dragging = YES;
185
+ [self report:NGNScrollPhaseDragBegan];
186
+ } else if ((phase == NSEventPhaseEnded || phase == NSEventPhaseCancelled) && _dragging) {
187
+ _dragging = NO;
188
+ // ponytail: a tenth of a second held still is no flick; tune here if it feels off.
189
+ if (scroll.timestamp - _lastMove > 0.1) {
190
+ _velocity = NSZeroPoint;
191
+ }
192
+ [self report:NGNScrollPhaseDragEnded];
193
+ if (self.pagingEnabled) {
194
+ _settling = YES;
195
+ [self settleOnPage];
196
+ }
197
+ } else if (momentum == NSEventPhaseBegan) {
198
+ [self report:NGNScrollPhaseMomentumBegan];
199
+ } else if (momentum == NSEventPhaseEnded || momentum == NSEventPhaseCancelled) {
200
+ [self report:NGNScrollPhaseMomentumEnded];
201
+ } else if (wheel && self.pagingEnabled) {
202
+ // A mouse's wheel has no end: the page settles once it stops turning.
203
+ [self queueSettle];
204
+ }
205
+ }
206
+
207
+ - (void)queueSettle {
208
+ [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(settleOnPage) object:nil];
209
+ [self performSelector:@selector(settleOnPage) withObject:nil afterDelay:0.2];
210
+ _settleQueued = YES;
211
+ }
212
+
213
+ - (void)dropSettle {
214
+ [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(settleOnPage) object:nil];
215
+ _settleQueued = NO;
216
+ }
217
+
218
+ - (void)report:(NGNScrollPhase)phase {
219
+ if (self.phaseChanged) {
220
+ self.phaseChanged(phase, _velocity);
221
+ }
222
+ }
223
+
224
+ // Animates to the page the drag points at (ngn::pagedOffset), reporting it as momentum.
225
+ - (void)settleOnPage {
226
+ _settleQueued = NO;
227
+ if (!self.pagingEnabled) {
228
+ return;
229
+ }
230
+ NSClipView *clip = self.contentView;
231
+ NSSize content = self.documentView.frame.size, view = clip.bounds.size;
232
+ NSPoint from = clip.bounds.origin;
233
+ NSPoint to = NSMakePoint(
234
+ ngn::pagedOffset(from.x, _velocity.x, view.width, content.width - view.width),
235
+ ngn::pagedOffset(from.y, _velocity.y, view.height, content.height - view.height));
236
+ _velocity = NSZeroPoint;
237
+ // One settling in front of another ends the first before the second begins.
238
+ if (_settleUnderway) {
239
+ [self report:NGNScrollPhaseMomentumEnded];
240
+ }
241
+ uint64_t settle = ++_settle;
242
+ _settleUnderway = YES;
243
+ [self report:NGNScrollPhaseMomentumBegan];
244
+ __weak NGNWheelScrollView *weakSelf = self;
245
+ [NSAnimationContext
246
+ runAnimationGroup:^(NSAnimationContext *context) {
247
+ context.duration = 0.25;
248
+ context.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
249
+ clip.animator.boundsOrigin = to;
250
+ }
251
+ completionHandler:^{
252
+ NGNWheelScrollView *strong = weakSelf;
253
+ if (strong == nil || strong->_settle != settle) {
254
+ return;
255
+ }
256
+ strong->_settleUnderway = NO;
257
+ [strong reflectScrolledClipView:clip];
258
+ [strong report:NGNScrollPhaseMomentumEnded];
259
+ }];
260
+ }
261
+
43
262
  @end
@@ -38,6 +38,10 @@
38
38
  - (void)placeAsWindows:(BOOL)window;
39
39
  // The split view is leaving: the window gets its surface back.
40
40
  - (void)uninstall;
41
+ // A screen above the one holding this split view covers it (`covered`), or it shows again: a
42
+ // window's split view gives the window its surface back while covered, so the screen in front
43
+ // shows, and takes the window again as its screen shows.
44
+ - (void)setScreenCovered:(BOOL)covered;
41
45
  @end
42
46
 
43
47
  // NgNativeSidebar and NgNativeSplitContent: filled by their container, not placed by Yoga.
@@ -1,4 +1,6 @@
1
1
  #import "split-view.h"
2
+
3
+ #include <optional>
2
4
  #import "test-launch.h"
3
5
 
4
6
  #import "surface-view.h"
@@ -169,6 +171,10 @@ NSWindow *NGNWindowOfSplit(NSView *surfaceView) {
169
171
  CGFloat _plainWidth;
170
172
  ngn::SidebarCollapse _collapse;
171
173
  std::string _autosave;
174
+ // The sidebar's width as a screen in front covered it, for when it takes the window again.
175
+ CGFloat _widthBeforeCover;
176
+ // What the app's `collapsed` asked for while no controller was there to take it.
177
+ std::optional<bool> _collapseWhileCovered;
172
178
  }
173
179
 
174
180
  + (ngn::InputSink *)input {
@@ -294,7 +300,7 @@ NSWindow *NGNWindowOfSplit(NSView *surfaceView) {
294
300
 
295
301
  - (void)viewDidMoveToWindow {
296
302
  [super viewDidMoveToWindow];
297
- if (_decided && _windows && _controller == nil && self.window != nil) {
303
+ if (_decided && _windows && _controller == nil && self.window != nil && ![self underCoveredScreen]) {
298
304
  [self build];
299
305
  }
300
306
  }
@@ -304,7 +310,9 @@ NSWindow *NGNWindowOfSplit(NSView *surfaceView) {
304
310
  return;
305
311
  }
306
312
  if (_windows) {
307
- [self installInWindow];
313
+ if (![self underCoveredScreen]) {
314
+ [self installInWindow];
315
+ }
308
316
  } else {
309
317
  [self buildPlain];
310
318
  }
@@ -369,13 +377,29 @@ NSWindow *NGNWindowOfSplit(NSView *surfaceView) {
369
377
  _controller.splitView.autosaveName = autosaveKey(_autosave);
370
378
  }
371
379
  BOOL restoring = [self hasAutosavedFrames];
380
+ // Installed again after a screen covered it: the sidebar stays collapsed if the app or the user
381
+ // had it so, unless the autosave restores the user's. After the divider is placed, which opens it.
382
+ std::optional<bool> collapse;
383
+ if (!restoring && p != nullptr && p->collapsed) {
384
+ collapse = true;
385
+ }
386
+ // The app asked while covered: that wins, autosave or not.
387
+ if (_collapseWhileCovered) {
388
+ collapse = *_collapseWhileCovered;
389
+ }
390
+ _collapseWhileCovered.reset();
372
391
  [_controller addSplitViewItem:_sidebarItem];
373
392
  [_controller addSplitViewItem:contentItem];
374
393
  window.contentViewController = _controller;
375
394
  [window setFrame:frame display:YES];
376
395
  if (!restoring) {
377
- [_controller.splitView setPosition:[self startingWidth] ofDividerAtIndex:0];
396
+ CGFloat width = _widthBeforeCover > 0 ? _widthBeforeCover : [self startingWidth];
397
+ [_controller.splitView setPosition:width ofDividerAtIndex:0];
398
+ }
399
+ if (collapse && *collapse != _sidebarItem.collapsed) {
400
+ _sidebarItem.collapsed = *collapse;
378
401
  }
402
+ _widthBeforeCover = 0;
379
403
  [_sidebarItem addObserver:self forKeyPath:@"collapsed" options:NSKeyValueObservingOptionNew context:nil];
380
404
  // A collapsed state the autosave restored is the user's: the app hears it.
381
405
  if (_sidebarItem.collapsed) {
@@ -429,6 +453,33 @@ NSWindow *NGNWindowOfSplit(NSView *surfaceView) {
429
453
  _ownWindow = nil;
430
454
  }
431
455
 
456
+ // Whether a screen above the one holding this split view covers it, however long ago.
457
+ - (BOOL)underCoveredScreen {
458
+ for (NSView *view = self.superview; view != nil; view = view.superview) {
459
+ if ([view isKindOfClass:NGNView.class] && ((NGNView *)view).covered) {
460
+ return YES;
461
+ }
462
+ }
463
+ return NO;
464
+ }
465
+
466
+ - (void)setScreenCovered:(BOOL)covered {
467
+ // Only a window's split view holds the window; a plain one stays in its screen.
468
+ if (!_windows) {
469
+ return;
470
+ }
471
+ if (covered) {
472
+ if (_controller != nil) {
473
+ // The divider's position: the sidebar pane's edge, whatever inset its view has in it.
474
+ NSArray<NSView *> *panes = _controller.splitView.arrangedSubviews;
475
+ _widthBeforeCover = _sidebarItem.collapsed || panes.count == 0 ? 0 : NSMaxX(panes[0].frame);
476
+ [self uninstall];
477
+ }
478
+ } else if (_decided && _controller == nil) {
479
+ [self build];
480
+ }
481
+ }
482
+
432
483
  - (void)dealloc {
433
484
  [self uninstall];
434
485
  }
@@ -452,6 +503,9 @@ NSWindow *NGNWindowOfSplit(NSView *surfaceView) {
452
503
  view.autosaveName = autosaveKey(_autosave);
453
504
  }
454
505
  if (auto collapsed = _collapse.propChanged(p->collapsed)) {
506
+ if (_windows && _controller == nil) {
507
+ _collapseWhileCovered = *collapsed;
508
+ }
455
509
  [self setToolkitCollapsed:*collapsed];
456
510
  }
457
511
  }
@@ -17,6 +17,8 @@ struct TextLine {
17
17
  CGPoint origin; // baseline origin, y measured from the top of the text box
18
18
  CGFloat width;
19
19
  bool rightToLeft{false}; // its paragraph runs right to left, so a justified last line is on the right
20
+ CGFloat top{0}; // the top of its line box, from the top of the text box
21
+ CGFloat height{0}; // its line box's height
20
22
  };
21
23
 
22
24
  struct TextLayout {
@@ -53,6 +55,10 @@ class CoreTextMeasurer final : public TextMeasurer {
53
55
  const facebook::react::AttributedString &text,
54
56
  const facebook::react::ParagraphAttributes &paragraph,
55
57
  facebook::react::Float maxWidth) const override;
58
+ facebook::react::LinesMeasurements lines(
59
+ const facebook::react::AttributedString &text,
60
+ const facebook::react::ParagraphAttributes &paragraph,
61
+ facebook::react::Float width) const override;
56
62
  };
57
63
 
58
64
  } // namespace ngn
@@ -276,6 +276,9 @@ void useFontLibrary(std::shared_ptr<const FontLibrary> library) {
276
276
  gFontLibrary = std::move(library);
277
277
  }
278
278
 
279
+ // A line through a range of text, in kCTUnderlineStyle's numbers, which Core Text does not draw.
280
+ static const CFStringRef kStrikethroughStyle = CFSTR("NGNStrikethroughStyle");
281
+
279
282
  CFAttributedStringRef makeAttributedString(const AttributedString &attributedString) {
280
283
  CFMutableAttributedStringRef out = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0);
281
284
  CFAttributedStringBeginEditing(out);
@@ -336,12 +339,35 @@ CFAttributedStringRef makeAttributedString(const AttributedString &attributedStr
336
339
  CFAttributedStringSetAttribute(out, range, kCTParagraphStyleAttributeName, style);
337
340
  CFRelease(style);
338
341
 
339
- if (a.textDecorationLineType == TextDecorationLineType::Underline ||
340
- a.textDecorationLineType == TextDecorationLineType::UnderlineStrikethrough) {
341
- int32_t single = kCTUnderlineStyleSingle;
342
- CFNumberRef n = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &single);
343
- CFAttributedStringSetAttribute(out, range, kCTUnderlineStyleAttributeName, n);
342
+ // Core Text draws an underline, in its style and colour; a line through is drawText's.
343
+ auto line = a.textDecorationLineType.value_or(TextDecorationLineType::None);
344
+ bool under = line == TextDecorationLineType::Underline || line == TextDecorationLineType::UnderlineStrikethrough;
345
+ bool through = line == TextDecorationLineType::Strikethrough || line == TextDecorationLineType::UnderlineStrikethrough;
346
+ if (under || through) {
347
+ auto decoration = a.textDecorationStyle.value_or(TextDecorationStyle::Solid);
348
+ int32_t style = decoration == TextDecorationStyle::Double ? kCTUnderlineStyleDouble : kCTUnderlineStyleSingle;
349
+ if (decoration == TextDecorationStyle::Dotted) {
350
+ style |= kCTUnderlinePatternDot;
351
+ } else if (decoration == TextDecorationStyle::Dashed) {
352
+ style |= kCTUnderlinePatternDash;
353
+ }
354
+ CFNumberRef n = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &style);
355
+ CFAttributedStringSetAttribute(out, range, under ? kCTUnderlineStyleAttributeName : kStrikethroughStyle, n);
356
+ if (under && through) {
357
+ CFAttributedStringSetAttribute(out, range, kStrikethroughStyle, n);
358
+ }
344
359
  CFRelease(n);
360
+ if (a.textDecorationColor) {
361
+ // Faded with the text, as its foreground is.
362
+ CGColorRef decorationColor = cgColor(a.textDecorationColor);
363
+ if (!std::isnan(a.opacity)) {
364
+ CGColorRef faded = CGColorCreateCopyWithAlpha(decorationColor, CGColorGetAlpha(decorationColor) * a.opacity);
365
+ CGColorRelease(decorationColor);
366
+ decorationColor = faded;
367
+ }
368
+ CFAttributedStringSetAttribute(out, range, kCTUnderlineColorAttributeName, decorationColor);
369
+ CGColorRelease(decorationColor);
370
+ }
345
371
  }
346
372
  CFRelease(font);
347
373
  }
@@ -429,7 +455,7 @@ TextLayout layoutText(
429
455
  if (fixed <= 0) {
430
456
  baseline = y + ascent;
431
457
  }
432
- layout.lines.push_back({line, CGPointMake(0, baseline), width, rightToLeftAt(layout.string, r.location, paragraph)});
458
+ layout.lines.push_back({line, CGPointMake(0, baseline), width, rightToLeftAt(layout.string, r.location, paragraph), y, height});
433
459
  widest = std::max(widest, width);
434
460
  y += height;
435
461
  at += count;
@@ -442,32 +468,91 @@ TextLayout layoutText(
442
468
  return layout;
443
469
  }
444
470
 
471
+ // Each run's line through, half its font's x-height above the baseline at `baseline`, the
472
+ // underline's thickness and in the underline's colour, or the text's: a double one is two lines,
473
+ // and a dotted or dashed one is stroked in that pattern.
474
+ static void drawStrikethroughs(CTLineRef line, CGContextRef context, CGPoint baseline) {
475
+ CFArrayRef runs = CTLineGetGlyphRuns(line);
476
+ for (CFIndex i = 0; i < CFArrayGetCount(runs); i++) {
477
+ auto run = (CTRunRef)CFArrayGetValueAtIndex(runs, i);
478
+ CFDictionaryRef attributes = CTRunGetAttributes(run);
479
+ auto styleNumber = (CFNumberRef)CFDictionaryGetValue(attributes, kStrikethroughStyle);
480
+ auto font = (CTFontRef)CFDictionaryGetValue(attributes, kCTFontAttributeName);
481
+ if (styleNumber == nullptr || font == nullptr) {
482
+ continue;
483
+ }
484
+ int32_t style = 0;
485
+ CFNumberGetValue(styleNumber, kCFNumberSInt32Type, &style);
486
+ auto color = (CGColorRef)CFDictionaryGetValue(attributes, kCTUnderlineColorAttributeName);
487
+ if (color == nullptr) {
488
+ color = (CGColorRef)CFDictionaryGetValue(attributes, kCTForegroundColorAttributeName);
489
+ }
490
+ // The run as drawn: its first glyph's position on the line and its advance, whatever direction
491
+ // the run or the line goes.
492
+ if (CTRunGetGlyphCount(run) == 0) {
493
+ continue;
494
+ }
495
+ CGPoint first = CGPointZero;
496
+ CTRunGetPositions(run, CFRangeMake(0, 1), &first);
497
+ CGFloat left = first.x;
498
+ CGFloat width = CTRunGetTypographicBounds(run, CFRangeMake(0, 0), nullptr, nullptr, nullptr);
499
+ CGFloat thickness = std::max<CGFloat>(CTFontGetUnderlineThickness(font), 1);
500
+ CGFloat middle = baseline.y - CTFontGetXHeight(font) / 2;
501
+ bool twice = (style & 0xff) == kCTUnderlineStyleDouble;
502
+ CGContextSaveGState(context);
503
+ if (color != nullptr) {
504
+ CGContextSetStrokeColorWithColor(context, color);
505
+ }
506
+ CGContextSetLineWidth(context, thickness);
507
+ if (style & kCTUnderlinePatternDot) {
508
+ CGFloat dots[] = {thickness, thickness * 2};
509
+ CGContextSetLineDash(context, 0, dots, 2);
510
+ } else if (style & kCTUnderlinePatternDash) {
511
+ CGFloat dashes[] = {thickness * 4, thickness * 2};
512
+ CGContextSetLineDash(context, 0, dashes, 2);
513
+ }
514
+ for (CGFloat y : twice ? std::vector<CGFloat>{middle - thickness, middle + thickness} : std::vector<CGFloat>{middle}) {
515
+ CGContextMoveToPoint(context, baseline.x + left, y);
516
+ CGContextAddLineToPoint(context, baseline.x + left + width, y);
517
+ }
518
+ CGContextStrokePath(context);
519
+ CGContextRestoreGState(context);
520
+ }
521
+ }
522
+
523
+ // How far right of the box's left edge a line starts: its paragraph's alignment in a box this wide.
524
+ static CGFloat lineOffset(const TextLayout &layout, const TextLine &l, CGFloat boxWidth) {
525
+ CFRange r = CTLineGetStringRange(l.line);
526
+ CTTextAlignment alignment = kCTTextAlignmentNatural;
527
+ CTParagraphStyleRef style = r.length > 0
528
+ ? (CTParagraphStyleRef)CFAttributedStringGetAttribute(
529
+ layout.string, r.location, kCTParagraphStyleAttributeName, nullptr)
530
+ : nullptr;
531
+ if (style != nullptr) {
532
+ CTParagraphStyleGetValueForSpecifier(style, kCTParagraphStyleSpecifierAlignment, sizeof(alignment), &alignment);
533
+ }
534
+ CGFloat x = 0;
535
+ if (alignment == kCTTextAlignmentCenter) {
536
+ x = (boxWidth - l.width) / 2;
537
+ } else if (alignment == kCTTextAlignmentRight) {
538
+ x = boxWidth - l.width;
539
+ } else if (alignment == kCTTextAlignmentJustified && l.rightToLeft) {
540
+ // A justified paragraph's last line follows the paragraph's direction.
541
+ x = boxWidth - l.width;
542
+ }
543
+ return x;
544
+ }
545
+
445
546
  void drawText(const TextLayout &layout, CGContextRef context, CGPoint origin, CGFloat boxWidth) {
446
547
  CGContextSaveGState(context);
447
548
  // The view is flipped; glyphs are drawn with an inverted text matrix rather than by flipping
448
549
  // the whole context, so line origins stay top-down.
449
550
  CGContextSetTextMatrix(context, CGAffineTransformMakeScale(1, -1));
450
551
  for (const auto &l : layout.lines) {
451
- CFRange r = CTLineGetStringRange(l.line);
452
- CTTextAlignment alignment = kCTTextAlignmentNatural;
453
- CTParagraphStyleRef style = r.length > 0
454
- ? (CTParagraphStyleRef)CFAttributedStringGetAttribute(
455
- layout.string, r.location, kCTParagraphStyleAttributeName, nullptr)
456
- : nullptr;
457
- if (style != nullptr) {
458
- CTParagraphStyleGetValueForSpecifier(style, kCTParagraphStyleSpecifierAlignment, sizeof(alignment), &alignment);
459
- }
460
- CGFloat x = 0;
461
- if (alignment == kCTTextAlignmentCenter) {
462
- x = (boxWidth - l.width) / 2;
463
- } else if (alignment == kCTTextAlignmentRight) {
464
- x = boxWidth - l.width;
465
- } else if (alignment == kCTTextAlignmentJustified && l.rightToLeft) {
466
- // A justified paragraph's last line follows the paragraph's direction.
467
- x = boxWidth - l.width;
468
- }
552
+ CGFloat x = lineOffset(layout, l, boxWidth);
469
553
  CGContextSetTextPosition(context, origin.x + x, origin.y + l.origin.y);
470
554
  CTLineDraw(l.line, context);
555
+ drawStrikethroughs(l.line, context, CGPointMake(origin.x + x, origin.y + l.origin.y));
471
556
  }
472
557
  CGContextRestoreGState(context);
473
558
  }
@@ -482,4 +567,42 @@ facebook::react::Size CoreTextMeasurer::measure(
482
567
  }
483
568
  }
484
569
 
570
+ LinesMeasurements CoreTextMeasurer::lines(
571
+ const AttributedString &text,
572
+ const ParagraphAttributes &paragraph,
573
+ facebook::react::Float width) const {
574
+ @autoreleasepool {
575
+ // The slack drawing gives the width Yoga rounded (NGNView's drawRect:), so the lines match.
576
+ auto layout = layoutText(text, paragraph, width + 0.5);
577
+ CFStringRef string = layout.string ? CFAttributedStringGetString(layout.string) : nullptr;
578
+ LinesMeasurements lines;
579
+ for (const auto &l : layout.lines) {
580
+ CGFloat ascent = 0, descent = 0, leading = 0;
581
+ CTLineGetTypographicBounds(l.line, &ascent, &descent, &leading);
582
+ CFRange range = CTLineGetStringRange(l.line);
583
+ NSString *lineText = string ? (__bridge NSString *)string : @"";
584
+ lineText = [lineText substringWithRange:NSMakeRange(range.location, range.length)];
585
+ CGFloat capHeight = 0, xHeight = 0;
586
+ CFArrayRef runs = CTLineGetGlyphRuns(l.line);
587
+ if (CFArrayGetCount(runs) > 0) {
588
+ auto font = (CTFontRef)CFDictionaryGetValue(
589
+ CTRunGetAttributes((CTRunRef)CFArrayGetValueAtIndex(runs, 0)), kCTFontAttributeName);
590
+ if (font != nullptr) {
591
+ capHeight = CTFontGetCapHeight(font);
592
+ xHeight = CTFontGetXHeight(font);
593
+ }
594
+ }
595
+ lines.emplace_back(
596
+ std::string(lineText.UTF8String),
597
+ facebook::react::Rect{{static_cast<Float>(lineOffset(layout, l, width)), static_cast<Float>(l.top)}, {static_cast<Float>(l.width), static_cast<Float>(l.height)}},
598
+ static_cast<Float>(descent),
599
+ static_cast<Float>(capHeight),
600
+ static_cast<Float>(l.origin.y - l.top),
601
+ static_cast<Float>(xHeight));
602
+ }
603
+ return lines;
604
+ }
605
+ }
606
+
485
607
  } // namespace ngn
608
+
@@ -19,6 +19,7 @@ include(${REACT_COMMON_DIR}/cmake-utils/internal/react-native-platform-selector.
19
19
  # read the core's desktop props.
20
20
  include_directories(BEFORE SYSTEM
21
21
  ${CMAKE_CURRENT_LIST_DIR}/../shim/view-platform
22
+ ${CMAKE_CURRENT_LIST_DIR}/../shim/text-platform
22
23
  ${CMAKE_CURRENT_LIST_DIR}/../core/include)
23
24
  include_directories(SYSTEM
24
25
  ${REACT_COMMON_DIR}/react/renderer/graphics/platform/cxx
@@ -73,6 +74,14 @@ add_library(yoga ALIAS yogacore)
73
74
  get_target_property(_tlm react_renderer_textlayoutmanager SOURCES)
74
75
  list(FILTER _tlm EXCLUDE REGEX "platform/cxx/react/renderer/textlayoutmanager/TextLayoutManager.cpp$")
75
76
  set_target_properties(react_renderer_textlayoutmanager PROPERTIES SOURCES "${_tlm}")
77
+ # Its header is the shim's (shim/text-platform), which declares measureLines, in front of the cxx
78
+ # platform's for the target and each one that links it (ParagraphShadowNode's). A directory of its
79
+ # own changes their compile commands, so a build or a compiler cache from before it compiles again.
80
+ foreach(_property INCLUDE_DIRECTORIES INTERFACE_INCLUDE_DIRECTORIES)
81
+ get_target_property(_dirs react_renderer_textlayoutmanager ${_property})
82
+ set_target_properties(react_renderer_textlayoutmanager PROPERTIES
83
+ ${_property} "${CMAKE_CURRENT_LIST_DIR}/../shim/text-platform;${_dirs}")
84
+ endforeach()
76
85
 
77
86
  # React Native's component codegen (FBReactNativeSpec), generated by scripts/fetch.sh.
78
87
  set(CODEGEN_DIR ${NGN_SOURCES}/codegen)
@@ -1,9 +1,29 @@
1
1
  # What the runtime half needs beyond the renderer: Hermes, built statically by
2
2
  # scripts/build-hermes.sh, and the one OpenSSL call React Native's dev-server helper makes.
3
3
 
4
+ if(IS_DIRECTORY "${NGN_HERMES_PREBUILT}")
5
+ # React Native's prebuilt Hermes on macOS: a dynamic framework, which the binary finds beside
6
+ # itself in a build and in Contents/Frameworks in a packaged app.
7
+ set(NGN_HERMES_FRAMEWORK ${NGN_HERMES_PREBUILT}/Library/Frameworks/macosx/hermesvm.framework)
8
+ set(NGN_HERMESC ${NGN_HERMES_PREBUILT}/bin/hermesc)
9
+ foreach(alias hermesvm libhermes)
10
+ add_library(hermes-engine::${alias} INTERFACE IMPORTED GLOBAL)
11
+ set_target_properties(hermes-engine::${alias} PROPERTIES
12
+ INTERFACE_LINK_LIBRARIES ${NGN_HERMES_FRAMEWORK}
13
+ INTERFACE_LINK_OPTIONS "LINKER:-rpath,@executable_path;LINKER:-rpath,@executable_path/../Frameworks")
14
+ endforeach()
15
+ include_directories(SYSTEM ${NGN_HERMES_PREBUILT}/include)
16
+ # Without the cache folder's absolute path, which CMake would add for the framework: the binary
17
+ # finds Hermes only beside itself or in its app's Frameworks, wherever it was built.
18
+ set(CMAKE_SKIP_BUILD_RPATH ON)
19
+ # The tests, which never ship, find it where it was fetched, whichever target built first.
20
+ get_filename_component(_hermes_frameworks ${NGN_HERMES_FRAMEWORK} DIRECTORY)
21
+ set(NGN_HERMES_TEST_RPATH "LINKER:-rpath,${_hermes_frameworks}")
22
+ else()
4
23
  if(NOT IS_DIRECTORY "${NGN_HERMES_BUILD}")
5
24
  message(FATAL_ERROR "NGN_HERMES_BUILD is not set to a directory; build through scripts/build.sh")
6
25
  endif()
26
+ set(NGN_HERMESC ${NGN_HERMES_BUILD}/bin/hermesc)
7
27
 
8
28
  # --- Hermes, static ------------------------------------------------------------------------------
9
29
  # React Native's CMakeLists link hermes-engine::hermesvm (0.87 and later) or ::libhermes (before).
@@ -24,6 +44,7 @@ foreach(alias hermesvm libhermes)
24
44
  endforeach()
25
45
  # React Native's hermes targets include <hermes/hermes.h> without a target that carries the path.
26
46
  include_directories(SYSTEM ${HERMES_SRC}/API ${HERMES_SRC}/public ${NGN_HERMES_BUILD}/lib/config)
47
+ endif()
27
48
 
28
49
  # --- OpenSSL::Crypto -----------------------------------------------------------------------------
29
50
  # ReactCxxPlatform's DevServerHelper hashes a device id with SHA256_Init/Update/Final and nothing
@@ -53,6 +53,11 @@ ScrollerVisibility scrollerVisibility(
53
53
  // The gutter the visible scrollers take: their width for legacy scrollers, nothing for overlay.
54
54
  ScrollerGutter scrollerGutter(ScrollerStyle style, float legacyWidth, const ScrollerVisibility &visibility);
55
55
 
56
+ // Where a scroll view with `pagingEnabled` settles along one axis when a drag ends at `offset`,
57
+ // moving at `velocity` (points a millisecond, positive further into the content): the nearest page,
58
+ // or the next one in the drag's direction when it was flicked, within [0, `max`].
59
+ float pagedOffset(float offset, float velocity, float page, float max);
60
+
56
61
  // `style` with `gutter` added to the padding Yoga reads for the right and bottom edges in
57
62
  // `direction`. A percentage or `auto` there is left alone.
58
63
  facebook::yoga::Style withGutter(