1 /*
2 * Copyright 2019 Google LLC
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7 #include "include/core/SkColor.h"
8 #include "include/core/SkFontStyle.h"
9 #include "include/core/SkPictureRecorder.h"
10 #include "include/core/SkString.h"
11
12 #include "modules/skparagraph/include/DartTypes.h"
13 #include "modules/skparagraph/include/Paragraph.h"
14 #include "modules/skparagraph/include/TextStyle.h"
15 #include "modules/skparagraph/include/TypefaceFontProvider.h"
16 #include "modules/skparagraph/src/ParagraphBuilderImpl.h"
17 #include "modules/skparagraph/src/ParagraphImpl.h"
18 #include "modules/skunicode/include/SkUnicode.h"
19
20 #if defined(SK_UNICODE_ICU_IMPLEMENTATION)
21 #include "modules/skunicode/include/SkUnicode_icu.h"
22 #endif
23 #if defined(SK_UNICODE_CLIENT_IMPLEMENTATION)
24 #include "modules/skunicode/include/SkUnicode_client.h"
25 #endif
26
27 #include <string>
28 #include <vector>
29
30 #include <emscripten.h>
31 #include <emscripten/bind.h>
32 #include "modules/canvaskit/WasmCommon.h"
33
34 using namespace emscripten;
35 using namespace skia_private;
36
37 namespace para = skia::textlayout;
38
39 // switch to ptrToSkColor4f (canvaskit_bindings.cpp)
toSkColor4f(WASMPointerF32 cPtr)40 SkColor4f toSkColor4f(WASMPointerF32 cPtr) {
41 float* fourFloats = reinterpret_cast<float*>(cPtr);
42 SkColor4f color = {fourFloats[0], fourFloats[1], fourFloats[2], fourFloats[3]};
43 return color;
44 }
45
46 struct SimpleFontStyle {
47 SkFontStyle::Slant slant;
48 SkFontStyle::Weight weight;
49 SkFontStyle::Width width;
50 };
51
52 // TODO(jlavrova, kjlubick) This should probably be created explicitly by the client
53 // (either one based on ICU data or a client explicitly made) and passed in to build().
get_unicode()54 static sk_sp<SkUnicode> get_unicode() {
55 // For code size reasons, we prefer to use the unicode implementation first
56 // over the full ICU version.
57 #if defined(SK_UNICODE_ICU_IMPLEMENTATION)
58 return SkUnicodes::ICU::Make();
59 #else
60 return nullptr;
61 #endif
62 }
63
64 struct SimpleTextStyle {
65 WASMPointerF32 colorPtr;
66 WASMPointerF32 foregroundColorPtr;
67 WASMPointerF32 backgroundColorPtr;
68 uint8_t decoration;
69 SkScalar decorationThickness;
70 WASMPointerF32 decorationColorPtr;
71 para::TextDecorationStyle decorationStyle;
72 para::TextBaseline textBaseline;
73 SkScalar fontSize;
74 SkScalar letterSpacing;
75 SkScalar wordSpacing;
76 SkScalar heightMultiplier;
77 bool halfLeading;
78 WASMPointerU8 localePtr;
79 int localeLen;
80 SimpleFontStyle fontStyle;
81
82 WASMPointerU8 fontFamiliesPtr;
83 int fontFamiliesLen;
84
85 int shadowLen;
86 WASMPointerF32 shadowColorsPtr;
87 WASMPointerF32 shadowOffsetsPtr;
88 WASMPointerF32 shadowBlurRadiiPtr;
89
90 int fontFeatureLen;
91 WASMPointerF32 fontFeatureNamesPtr;
92 WASMPointerF32 fontFeatureValuesPtr;
93
94 int fontVariationLen;
95 WASMPointerF32 fontVariationAxesPtr;
96 WASMPointerF32 fontVariationValuesPtr;
97 };
98
99 struct SimpleStrutStyle {
100 WASMPointerU32 fontFamiliesPtr;
101 int fontFamiliesLen;
102 SimpleFontStyle fontStyle;
103 SkScalar fontSize;
104 SkScalar heightMultiplier;
105 bool halfLeading;
106 SkScalar leading;
107 bool strutEnabled;
108 bool forceStrutHeight;
109 };
110
toStrutStyle(const SimpleStrutStyle & s)111 para::StrutStyle toStrutStyle(const SimpleStrutStyle& s) {
112 para::StrutStyle ss;
113
114 const char** fontFamilies = reinterpret_cast<const char**>(s.fontFamiliesPtr);
115 if (fontFamilies != nullptr) {
116 std::vector<SkString> ff;
117 for (int i = 0; i < s.fontFamiliesLen; i++) {
118 ff.emplace_back(fontFamilies[i]);
119 }
120 ss.setFontFamilies(ff);
121 }
122
123 SkFontStyle fs(s.fontStyle.weight, s.fontStyle.width, s.fontStyle.slant);
124 ss.setFontStyle(fs);
125
126 if (s.fontSize != -1) {
127 ss.setFontSize(s.fontSize);
128 }
129 if (s.heightMultiplier != -1) {
130 ss.setHeight(s.heightMultiplier);
131 ss.setHeightOverride(true);
132 }
133 ss.setHalfLeading(s.halfLeading);
134
135 if (s.leading != 0) {
136 ss.setLeading(s.leading);
137 }
138
139 ss.setStrutEnabled(s.strutEnabled);
140 ss.setForceStrutHeight(s.forceStrutHeight);
141
142 return ss;
143 }
144
toTextStyle(const SimpleTextStyle & s)145 para::TextStyle toTextStyle(const SimpleTextStyle& s) {
146 para::TextStyle ts;
147
148 // textstyle.color doesn't support a 4f color, however the foreground and background fields
149 // below do.
150 ts.setColor(toSkColor4f(s.colorPtr).toSkColor());
151
152 // It is functionally important that these paints be unset when no value was provided.
153 if (s.foregroundColorPtr) {
154 SkPaint p1;
155 p1.setColor4f(toSkColor4f(s.foregroundColorPtr));
156 ts.setForegroundColor(p1);
157 }
158
159 if (s.backgroundColorPtr) {
160 SkPaint p2;
161 p2.setColor4f(toSkColor4f(s.backgroundColorPtr));
162 ts.setBackgroundColor(p2);
163 }
164
165 if (s.fontSize != -1) {
166 ts.setFontSize(s.fontSize);
167 }
168 if (s.letterSpacing != 0) {
169 ts.setLetterSpacing(s.letterSpacing);
170 }
171 if (s.wordSpacing != 0) {
172 ts.setWordSpacing(s.wordSpacing);
173 }
174
175 if (s.heightMultiplier != -1) {
176 ts.setHeight(s.heightMultiplier);
177 ts.setHeightOverride(true);
178 }
179
180 ts.setHalfLeading(s.halfLeading);
181
182 ts.setDecoration(para::TextDecoration(s.decoration));
183 ts.setDecorationStyle(s.decorationStyle);
184 if (s.decorationThickness != 0) {
185 ts.setDecorationThicknessMultiplier(s.decorationThickness);
186 }
187 if (s.decorationColorPtr) {
188 ts.setDecorationColor(toSkColor4f(s.decorationColorPtr).toSkColor());
189 }
190
191 if (s.localeLen > 0) {
192 const char* localePtr = reinterpret_cast<const char*>(s.localePtr);
193 SkString lStr(localePtr, s.localeLen);
194 ts.setLocale(lStr);
195 }
196
197 const char** fontFamilies = reinterpret_cast<const char**>(s.fontFamiliesPtr);
198 if (fontFamilies != nullptr) {
199 std::vector<SkString> ff;
200 for (int i = 0; i < s.fontFamiliesLen; i++) {
201 ff.emplace_back(fontFamilies[i]);
202 }
203 ts.setFontFamilies(ff);
204 }
205
206 ts.setTextBaseline(s.textBaseline);
207
208 SkFontStyle fs(s.fontStyle.weight, s.fontStyle.width, s.fontStyle.slant);
209 ts.setFontStyle(fs);
210
211 if (s.shadowLen > 0) {
212 const SkColor4f* colors = reinterpret_cast<const SkColor4f*>(s.shadowColorsPtr);
213 const SkPoint* offsets = reinterpret_cast<const SkPoint*>(s.shadowOffsetsPtr);
214 const float* blurRadii = reinterpret_cast<const float*>(s.shadowBlurRadiiPtr);
215 for (int i = 0; i < s.shadowLen; i++) {
216 para::TextShadow shadow(colors[i].toSkColor(), offsets[i], blurRadii[i]);
217 ts.addShadow(shadow);
218 }
219 }
220
221
222 if (s.fontFeatureLen > 0) {
223 const char** fontFeatureNames = reinterpret_cast<const char**>(s.fontFeatureNamesPtr);
224 const int* fontFeatureValues = reinterpret_cast<const int*>(s.fontFeatureValuesPtr);
225 for (int i = 0; i < s.fontFeatureLen; i++) {
226 // Font features names are 4-character simple strings.
227 SkString name(fontFeatureNames[i], 4);
228 ts.addFontFeature(name, fontFeatureValues[i]);
229 }
230 }
231
232 if (s.fontVariationLen > 0) {
233 const char** fontVariationAxes = reinterpret_cast<const char**>(s.fontVariationAxesPtr);
234 const float* fontVariationValues = reinterpret_cast<const float*>(s.fontVariationValuesPtr);
235 std::vector<SkFontArguments::VariationPosition::Coordinate> coordinates;
236 for (int i = 0; i < s.fontVariationLen; i++) {
237 // Font variation axis tags are 4-character simple strings.
238 SkString axis(fontVariationAxes[i]);
239 if (axis.size() != 4) {
240 continue;
241 }
242 coordinates.push_back({
243 SkSetFourByteTag(axis[0], axis[1], axis[2], axis[3]),
244 fontVariationValues[i]
245 });
246 }
247 SkFontArguments::VariationPosition position = {
248 coordinates.data(),
249 static_cast<int>(coordinates.size())
250 };
251 ts.setFontArguments(SkFontArguments().setVariationDesignPosition(position));
252 }
253
254 return ts;
255 }
256
257 struct SimpleParagraphStyle {
258 bool disableHinting;
259 WASMPointerU8 ellipsisPtr;
260 size_t ellipsisLen;
261 SkScalar heightMultiplier;
262 size_t maxLines;
263 bool replaceTabCharacters;
264 para::TextAlign textAlign;
265 para::TextDirection textDirection;
266 para::TextHeightBehavior textHeightBehavior;
267 SimpleTextStyle textStyle;
268 SimpleStrutStyle strutStyle;
269 bool applyRoundingHack;
270 };
271
toParagraphStyle(const SimpleParagraphStyle & s)272 para::ParagraphStyle toParagraphStyle(const SimpleParagraphStyle& s) {
273 para::ParagraphStyle ps;
274 if (s.disableHinting) {
275 ps.turnHintingOff();
276 }
277
278 if (s.ellipsisLen > 0) {
279 const char* ellipsisPtr = reinterpret_cast<const char*>(s.ellipsisPtr);
280 SkString eStr(ellipsisPtr, s.ellipsisLen);
281 ps.setEllipsis(eStr);
282 }
283 ps.setTextAlign(s.textAlign);
284 ps.setTextDirection(s.textDirection);
285 auto ts = toTextStyle(s.textStyle);
286 ps.setTextStyle(ts);
287 auto ss = toStrutStyle(s.strutStyle);
288 ps.setStrutStyle(ss);
289 if (s.heightMultiplier != -1) {
290 ps.setHeight(s.heightMultiplier);
291 }
292 if (s.maxLines != 0) {
293 ps.setMaxLines(s.maxLines);
294 }
295 ps.setApplyRoundingHack(s.applyRoundingHack);
296 ps.setTextHeightBehavior(s.textHeightBehavior);
297 ps.setReplaceTabCharacters(s.replaceTabCharacters);
298 return ps;
299 }
300
301 struct SimpleTextBox {
302 SkRect rect;
303 // This isn't the most efficient way to represent this, but it is much easier to keep
304 // everything as floats when unpacking on the JS side.
305 // 0.0 = RTL, 1.0 = LTr
306 SkScalar direction;
307 };
308
TextBoxesToFloat32Array(std::vector<para::TextBox> boxes)309 Float32Array TextBoxesToFloat32Array(std::vector<para::TextBox> boxes) {
310 // Pack these text boxes into an array of n groups of 5 SkScalar (floats)
311 if (!boxes.size()) {
312 return emscripten::val::null();
313 }
314 SimpleTextBox* rects = new SimpleTextBox[boxes.size()];
315 for (size_t i = 0; i < boxes.size(); i++) {
316 rects[i].rect = boxes[i].rect;
317 if (boxes[i].direction == para::TextDirection::kRtl) {
318 rects[i].direction = 0;
319 } else {
320 rects[i].direction = 1;
321 }
322 }
323 float* fPtr = reinterpret_cast<float*>(rects);
324 // Of note: now that we have cast rects to float*, emscripten is smart enough to wrap this
325 // into a Float32Array for us.
326 return Float32Array(typed_memory_view(boxes.size() * 5, fPtr));
327 }
328
GetRectsForRange(para::Paragraph & self,unsigned start,unsigned end,para::RectHeightStyle heightStyle,para::RectWidthStyle widthStyle)329 Float32Array GetRectsForRange(para::Paragraph& self,
330 unsigned start,
331 unsigned end,
332 para::RectHeightStyle heightStyle,
333 para::RectWidthStyle widthStyle) {
334 std::vector<para::TextBox> boxes = self.getRectsForRange(start, end, heightStyle, widthStyle);
335 return TextBoxesToFloat32Array(boxes);
336 }
337
GetRectsForPlaceholders(para::Paragraph & self)338 Float32Array GetRectsForPlaceholders(para::Paragraph& self) {
339 std::vector<para::TextBox> boxes = self.getRectsForPlaceholders();
340 return TextBoxesToFloat32Array(boxes);
341 }
342
JSObjectFromLineMetrics(skia::textlayout::LineMetrics & metrics)343 JSObject JSObjectFromLineMetrics(skia::textlayout::LineMetrics& metrics) {
344 JSObject m = emscripten::val::object();
345 m.set("startIndex", metrics.fStartIndex);
346 m.set("endIndex", metrics.fEndIndex);
347 m.set("endExcludingWhitespaces", metrics.fEndExcludingWhitespaces);
348 m.set("endIncludingNewline", metrics.fEndIncludingNewline);
349 m.set("isHardBreak", metrics.fHardBreak);
350 m.set("ascent", metrics.fAscent);
351 m.set("descent", metrics.fDescent);
352 m.set("height", metrics.fHeight);
353 m.set("width", metrics.fWidth);
354 m.set("left", metrics.fLeft);
355 m.set("baseline", metrics.fBaseline);
356 m.set("lineNumber", metrics.fLineNumber);
357 return m;
358 }
359
JSObjectFromGlyphInfo(skia::textlayout::Paragraph::GlyphInfo & glyphInfo)360 JSObject JSObjectFromGlyphInfo(skia::textlayout::Paragraph::GlyphInfo& glyphInfo) {
361 JSObject object = emscripten::val::object();
362
363 JSObject range = emscripten::val::object();
364 range.set("start", glyphInfo.fGraphemeClusterTextRange.start);
365 range.set("end", glyphInfo.fGraphemeClusterTextRange.end);
366 object.set("graphemeClusterTextRange", range);
367
368 JSArray rect = emscripten::val::array();
369 rect.call<void>("push", glyphInfo.fGraphemeLayoutBounds.left());
370 rect.call<void>("push", glyphInfo.fGraphemeLayoutBounds.top());
371 rect.call<void>("push", glyphInfo.fGraphemeLayoutBounds.right());
372 rect.call<void>("push", glyphInfo.fGraphemeLayoutBounds.bottom());
373 object.set("graphemeLayoutBounds", rect);
374
375 object.set("dir", glyphInfo.fDirection == skia::textlayout::TextDirection::kRtl ? 0 : 1);
376 object.set("isEllipsis", glyphInfo.fIsEllipsis);
377 return object;
378 }
379
GetLineMetrics(para::Paragraph & self)380 JSArray GetLineMetrics(para::Paragraph& self) {
381 std::vector<skia::textlayout::LineMetrics> metrics;
382 self.getLineMetrics(metrics);
383 JSArray result = emscripten::val::array();
384 for (auto metric : metrics) {
385 result.call<void>("push", JSObjectFromLineMetrics(metric));
386 }
387 return result;
388 }
389
GetLineMetricsAt(para::Paragraph & self,size_t lineNumber)390 JSObject GetLineMetricsAt(para::Paragraph& self, size_t lineNumber) {
391 skia::textlayout::LineMetrics metrics;
392 return self.getLineMetricsAt(lineNumber, &metrics)
393 ? JSObjectFromLineMetrics(metrics)
394 : emscripten::val::null();
395 }
396
GetGlyphInfoAt(para::Paragraph & self,size_t index)397 JSObject GetGlyphInfoAt(para::Paragraph& self, size_t index) {
398 skia::textlayout::Paragraph::GlyphInfo glyphInfo;
399 return self.getGlyphInfoAtUTF16Offset(index, &glyphInfo)
400 ? JSObjectFromGlyphInfo(glyphInfo)
401 : emscripten::val::null();
402 }
403
GetClosestGlyphInfoAtCoordinate(para::Paragraph & self,SkScalar dx,SkScalar dy)404 JSObject GetClosestGlyphInfoAtCoordinate(para::Paragraph& self, SkScalar dx, SkScalar dy) {
405 skia::textlayout::Paragraph::GlyphInfo glyphInfo;
406 return self.getClosestUTF16GlyphInfoAt(dx, dy, &glyphInfo)
407 ? JSObjectFromGlyphInfo(glyphInfo)
408 : emscripten::val::null();
409 }
410
411 /*
412 * Returns Lines[]
413 */
GetShapedLines(para::Paragraph & self)414 JSArray GetShapedLines(para::Paragraph& self) {
415 struct LineAccumulate {
416 int lineNumber = -1; // deliberately -1 from starting value
417 uint32_t minOffset = 0xFFFFFFFF;
418 uint32_t maxOffset = 0;
419 float minAscent = 0;
420 float maxDescent = 0;
421 // not really accumulated, but definitely set
422 float baseline = 0;
423
424 void reset(int newLineNum) {
425 new (this) LineAccumulate;
426 this->lineNumber = newLineNum;
427 }
428 };
429
430 // where we accumulate our js output
431 JSArray jlines = emscripten::val::array();
432 JSObject jline = emscripten::val::null();
433 JSArray jruns = emscripten::val::null();
434 LineAccumulate accum;
435
436 self.visit([&](int lineNumber, const para::Paragraph::VisitorInfo* info) {
437 if (!info) {
438 if (!jline) return; // how???
439 // end of current line
440 JSObject range = emscripten::val::object();
441 range.set("first", accum.minOffset);
442 range.set("last", accum.maxOffset);
443 jline.set("textRange", range);
444
445 jline.set("top", accum.baseline + accum.minAscent);
446 jline.set("bottom", accum.baseline + accum.maxDescent);
447 jline.set("baseline", accum.baseline);
448 return;
449 }
450
451 if (lineNumber != accum.lineNumber) {
452 SkASSERT(lineNumber == accum.lineNumber + 1); // assume monotonic
453
454 accum.reset(lineNumber);
455 jruns = emscripten::val::array();
456
457 jline = emscripten::val::object();
458 jline.set("runs", jruns);
459 // will assign textRange and metrics on end-of-line signal
460
461 jlines.call<void>("push", jline);
462 }
463
464 // append the run
465 const int N = info->count; // glyphs
466 const int N1 = N + 1; // positions, offsets have 1 extra (trailing) slot
467
468 JSObject jrun = emscripten::val::object();
469
470 jrun.set("flags", info->flags);
471
472 jrun.set("typeface", info->font.refTypeface());
473 jrun.set("size", info->font.getSize());
474 if (info->font.getScaleX()) {
475 jrun.set("scaleX", info->font.getScaleX());
476 }
477
478 jrun.set("glyphs", MakeTypedArray(N, info->glyphs));
479 jrun.set("offsets", MakeTypedArray(N1, info->utf8Starts));
480
481 // we need to modify the positions, so make a temp copy
482 AutoSTMalloc<32, SkPoint> positions(N1);
483 for (int i = 0; i < N; ++i) {
484 positions.get()[i] = info->positions[i] + info->origin;
485 }
486 positions.get()[N] = { info->advanceX, positions.get()[N - 1].fY };
487 jrun.set("positions", MakeTypedArray(N1*2, (const float*)positions.get()));
488
489 jruns.call<void>("push", jrun);
490
491 // update accum
492 { SkFontMetrics fm;
493 info->font.getMetrics(&fm);
494
495 accum.minAscent = std::min(accum.minAscent, fm.fAscent);
496 accum.maxDescent = std::max(accum.maxDescent, fm.fDescent);
497 accum.baseline = info->origin.fY;
498
499 accum.minOffset = std::min(accum.minOffset, info->utf8Starts[0]);
500 accum.maxOffset = std::max(accum.maxOffset, info->utf8Starts[N]);
501 }
502
503 });
504 return jlines;
505 }
506
convertArrayU32(WASMPointerU32 array,size_t count)507 std::vector<SkUnicode::Position> convertArrayU32(WASMPointerU32 array, size_t count) {
508 std::vector<size_t> vec;
509 vec.resize(count);
510 SkUnicode::Position* data = reinterpret_cast<SkUnicode::Position*>(array);
511 std::memcpy(vec.data(), data, count * sizeof(size_t));
512 return vec;
513 }
514
UnresolvedCodepoints(para::Paragraph & self)515 JSArray UnresolvedCodepoints(para::Paragraph& self) {
516 JSArray result = emscripten::val::array();
517 for (auto cp : self.unresolvedCodepoints()) {
518 result.call<void>("push", cp);
519 }
520 return result;
521 }
522
EMSCRIPTEN_BINDINGS(Paragraph)523 EMSCRIPTEN_BINDINGS(Paragraph) {
524
525 class_<para::Paragraph>("Paragraph")
526 .function("didExceedMaxLines", ¶::Paragraph::didExceedMaxLines)
527 .function("getAlphabeticBaseline", ¶::Paragraph::getAlphabeticBaseline)
528 .function("getGlyphPositionAtCoordinate", ¶::Paragraph::getGlyphPositionAtCoordinate)
529 .function("getHeight", ¶::Paragraph::getHeight)
530 .function("getIdeographicBaseline", ¶::Paragraph::getIdeographicBaseline)
531 .function("getLineMetrics", &GetLineMetrics)
532 .function("getLineMetricsAt", &GetLineMetricsAt)
533 .function("getLineNumberAt", ¶::Paragraph::getLineNumberAt)
534 .function("getLongestLine", ¶::Paragraph::getLongestLine)
535 .function("getMaxIntrinsicWidth", ¶::Paragraph::getMaxIntrinsicWidth)
536 .function("getMaxWidth", ¶::Paragraph::getMaxWidth)
537 .function("getMinIntrinsicWidth", ¶::Paragraph::getMinIntrinsicWidth)
538 .function("getNumberOfLines", ¶::Paragraph::lineNumber)
539 .function("_getClosestGlyphInfoAtCoordinate", &GetClosestGlyphInfoAtCoordinate)
540 .function("_getGlyphInfoAt", &GetGlyphInfoAt)
541 .function("_getRectsForPlaceholders", &GetRectsForPlaceholders)
542 .function("_getRectsForRange", &GetRectsForRange)
543 .function("getShapedLines", &GetShapedLines)
544 .function("getWordBoundary", ¶::Paragraph::getWordBoundary)
545 .function("layout", ¶::Paragraph::layout)
546 .function("unresolvedCodepoints", &UnresolvedCodepoints);
547
548 class_<para::ParagraphBuilderImpl>("ParagraphBuilder")
549 .class_function(
550 "_Make",
551 optional_override([](SimpleParagraphStyle style, sk_sp<SkFontMgr> fontMgr)
552 -> std::unique_ptr<para::ParagraphBuilderImpl> {
553 auto fc = sk_make_sp<para::FontCollection>();
554 fc->setDefaultFontManager(fontMgr);
555 fc->enableFontFallback();
556 auto ps = toParagraphStyle(style);
557 auto pb = para::ParagraphBuilderImpl::make(ps, fc, get_unicode());
558 return std::unique_ptr<para::ParagraphBuilderImpl>(
559 static_cast<para::ParagraphBuilderImpl*>(pb.release()));
560 }),
561 allow_raw_pointers())
562 .class_function(
563 "_MakeFromFontProvider",
564 optional_override([](SimpleParagraphStyle style,
565 sk_sp<para::TypefaceFontProvider> fontProvider)
566 -> std::unique_ptr<para::ParagraphBuilderImpl> {
567 auto fc = sk_make_sp<para::FontCollection>();
568 fc->setDefaultFontManager(fontProvider);
569 fc->enableFontFallback();
570 auto ps = toParagraphStyle(style);
571 auto pb = para::ParagraphBuilderImpl::make(ps, fc, get_unicode());
572 return std::unique_ptr<para::ParagraphBuilderImpl>(
573 static_cast<para::ParagraphBuilderImpl*>(pb.release()));
574 }),
575 allow_raw_pointers())
576 .class_function(
577 "_MakeFromFontCollection",
578 optional_override([](SimpleParagraphStyle style,
579 sk_sp<para::FontCollection> fontCollection)
580 -> std::unique_ptr<para::ParagraphBuilderImpl> {
581 auto ps = toParagraphStyle(style);
582 auto pb = para::ParagraphBuilderImpl::make(ps, fontCollection, get_unicode());
583 return std::unique_ptr<para::ParagraphBuilderImpl>(
584 static_cast<para::ParagraphBuilderImpl*>(pb.release()));
585 }),
586 allow_raw_pointers())
587 .class_function(
588 "_ShapeText",
589 optional_override([](JSString jtext, JSArray jruns, float width) -> JSArray {
590 std::string textStorage = jtext.as<std::string>();
591 const char* text = textStorage.data();
592 size_t textCount = textStorage.size();
593
594 auto fc = sk_make_sp<para::FontCollection>();
595 fc->setDefaultFontManager(SkFontMgr::RefEmpty());
596 fc->enableFontFallback();
597
598 para::ParagraphStyle pstyle;
599 {
600 // For the most part this is ignored, since we set an explicit TextStyle
601 // for all of our text runs, but it is required by SkParagraph.
602 para::TextStyle style;
603 style.setFontFamilies({SkString("sans-serif")});
604 style.setFontSize(32);
605 pstyle.setTextStyle(style);
606 }
607
608 auto pb = para::ParagraphBuilder::make(pstyle, fc, get_unicode());
609
610 // tease apart the FontBlock runs
611 size_t runCount = jruns["length"].as<size_t>();
612 for (size_t i = 0; i < runCount; ++i) {
613 emscripten::val r = jruns[i];
614
615 para::TextStyle style;
616 style.setTypeface(r["typeface"].as< sk_sp<SkTypeface> >());
617 style.setFontSize(r["size"].as<float>());
618
619 const size_t subTextCount = r["length"].as<size_t>();
620 if (subTextCount > textCount) {
621 return emscripten::val("block runs exceed text length!");
622 }
623
624 pb->pushStyle(style);
625 pb->addText(text, subTextCount);
626 pb->pop();
627
628 text += subTextCount;
629 textCount -= subTextCount;
630 }
631 if (textCount != 0) {
632 return emscripten::val("Didn't have enough block runs to cover text");
633 }
634
635 auto pa = pb->Build();
636 pa->layout(width);
637
638 // workaround until this is fixed in SkParagraph
639 {
640 SkPictureRecorder rec;
641 pa->paint(rec.beginRecording({0,0,9999,9999}), 0, 0);
642 }
643 return GetShapedLines(*pa);
644 }),
645 allow_raw_pointers())
646 .class_function("RequiresClientICU", ¶::ParagraphBuilderImpl::RequiresClientICU)
647 .function("addText",
648 optional_override([](para::ParagraphBuilderImpl& self, std::string text) {
649 return self.addText(text.c_str(), text.length());
650 }))
651 .function("build", ¶::ParagraphBuilderImpl::Build, allow_raw_pointers())
652 .function("build", optional_override([](para::ParagraphBuilderImpl& self) {
653 #if defined(SK_UNICODE_CLIENT_IMPLEMENTATION)
654 auto [words, graphemeBreaks, lineBreaks] = self.getClientICUData();
655 auto text = self.getText();
656 sk_sp<SkUnicode> clientICU = SkUnicodes::Client::Make(text, words, graphemeBreaks, lineBreaks);
657 self.SetUnicode(clientICU);
658 #endif
659 return self.Build();
660 }), allow_raw_pointers())
661 .function("pop", ¶::ParagraphBuilderImpl::pop)
662 .function("reset", ¶::ParagraphBuilderImpl::Reset, allow_raw_pointers())
663 .function("_pushStyle", optional_override([](para::ParagraphBuilderImpl& self,
664 SimpleTextStyle textStyle) {
665 auto ts = toTextStyle(textStyle);
666 self.pushStyle(ts);
667 }))
668 // A method of pushing a textStyle with paints instead of colors for foreground and
669 // background. Since SimpleTextStyle is a value object, it cannot contain paints, which
670 // are not primitives. This binding is here to accept them. Any color that is specified
671 // in the textStyle is overridden.
672 .function("_pushPaintStyle",
673 optional_override([](para::ParagraphBuilderImpl& self,
674 SimpleTextStyle textStyle, SkPaint foreground,
675 SkPaint background) {
676 auto ts = toTextStyle(textStyle);
677 ts.setForegroundColor(foreground);
678 ts.setBackgroundColor(background);
679 self.pushStyle(ts);
680 }))
681 .function("_addPlaceholder", optional_override([](para::ParagraphBuilderImpl& self,
682 SkScalar width,
683 SkScalar height,
684 para::PlaceholderAlignment alignment,
685 para::TextBaseline baseline,
686 SkScalar offset) {
687 para::PlaceholderStyle ps(width, height, alignment, baseline, offset);
688 self.addPlaceholder(ps);
689 }))
690 .function("getText",
691 optional_override([](para::ParagraphBuilderImpl& self) -> JSString {
692 auto text = self.getText();
693 return emscripten::val(std::string(text.data(), text.size()).c_str());
694 }))
695 .function("_setWordsUtf8",
696 optional_override([](para::ParagraphBuilderImpl& self,
697 WASMPointerU32 clientWords, size_t wordsNum) {
698 #if defined(SK_UNICODE_CLIENT_IMPLEMENTATION)
699 self.setWordsUtf8(convertArrayU32(clientWords, wordsNum));
700 #endif
701 }))
702 .function("_setWordsUtf16",
703 optional_override([](para::ParagraphBuilderImpl& self,
704 WASMPointerU32 clientWords, size_t wordsNum) {
705 #if defined(SK_UNICODE_CLIENT_IMPLEMENTATION)
706 self.setWordsUtf16(convertArrayU32(clientWords, wordsNum));
707 #endif
708 }))
709 .function("_setGraphemeBreaksUtf8",
710 optional_override([](para::ParagraphBuilderImpl& self,
711 WASMPointerU32 clientGraphemes, size_t graphemesNum) {
712 #if defined(SK_UNICODE_CLIENT_IMPLEMENTATION)
713 self.setGraphemeBreaksUtf8(convertArrayU32(clientGraphemes, graphemesNum));
714 #endif
715 }))
716 .function("_setGraphemeBreaksUtf16",
717 optional_override([](para::ParagraphBuilderImpl& self,
718 WASMPointerU32 clientGraphemes, size_t graphemesNum) {
719 #if defined(SK_UNICODE_CLIENT_IMPLEMENTATION)
720 self.setGraphemeBreaksUtf16(convertArrayU32(clientGraphemes, graphemesNum));
721 #endif
722 }))
723 .function("_setLineBreaksUtf8",
724 optional_override([](para::ParagraphBuilderImpl& self,
725 WASMPointerU32 clientLineBreaks, size_t lineBreaksNum) {
726 #if defined(SK_UNICODE_CLIENT_IMPLEMENTATION)
727 SkUnicode::Position* lineBreakData = reinterpret_cast<SkUnicode::Position*>(clientLineBreaks);
728 std::vector<SkUnicode::LineBreakBefore> lineBreaks;
729 for (size_t i = 0; i < lineBreaksNum; i += 2) {
730 auto pos = lineBreakData[i];
731 auto breakType = lineBreakData[i+1];
732 if (breakType == 0) {
733 lineBreaks.emplace_back(pos, SkUnicode::LineBreakType::kSoftLineBreak);
734 } else {
735 lineBreaks.emplace_back(pos, SkUnicode::LineBreakType::kHardLineBreak);
736 }
737 }
738 self.setLineBreaksUtf8(std::move(lineBreaks));
739 #endif
740 }))
741 .function("_setLineBreaksUtf16",
742 optional_override([](para::ParagraphBuilderImpl& self,
743 WASMPointerU32 clientLineBreaks, size_t lineBreaksNum) {
744 #if defined(SK_UNICODE_CLIENT_IMPLEMENTATION)
745 SkUnicode::Position* lineBreakData = reinterpret_cast<SkUnicode::Position*>(clientLineBreaks);
746 std::vector<SkUnicode::LineBreakBefore> lineBreaks;
747 for (size_t i = 0; i < lineBreaksNum; i += 2) {
748 auto pos = lineBreakData[i];
749 auto breakType = lineBreakData[i+1];
750 if (breakType == 0) {
751 lineBreaks.emplace_back(pos, SkUnicode::LineBreakType::kSoftLineBreak);
752 } else {
753 lineBreaks.emplace_back(pos, SkUnicode::LineBreakType::kHardLineBreak);
754 }
755 }
756 self.setLineBreaksUtf16(std::move(lineBreaks));
757 #endif
758 }));
759
760 class_<para::TypefaceFontProvider, base<SkFontMgr>>("TypefaceFontProvider")
761 .smart_ptr<sk_sp<para::TypefaceFontProvider>>("sk_sp<TypefaceFontProvider>")
762 .class_function("Make", optional_override([]()-> sk_sp<para::TypefaceFontProvider> {
763 return sk_make_sp<para::TypefaceFontProvider>();
764 }))
765 .function("_registerFont", optional_override([](para::TypefaceFontProvider& self,
766 sk_sp<SkTypeface> typeface,
767 WASMPointerU8 familyPtr) {
768 const char* fPtr = reinterpret_cast<const char*>(familyPtr);
769 SkString fStr(fPtr);
770 self.registerTypeface(typeface, fStr);
771 }), allow_raw_pointers());
772
773 class_<para::FontCollection>("FontCollection")
774 .smart_ptr<sk_sp<para::FontCollection>>("sk_sp<FontCollection>")
775 .class_function("Make", optional_override([]()-> sk_sp<para::FontCollection> {
776 return sk_make_sp<para::FontCollection>();
777 }))
778 .function("setDefaultFontManager", optional_override([](para::FontCollection& self,
779 const sk_sp<para::TypefaceFontProvider>& fontManager) {
780 self.setDefaultFontManager(fontManager);
781 }), allow_raw_pointers())
782 .function("enableFontFallback", ¶::FontCollection::enableFontFallback);
783
784 // These value objects make it easier to send data across the wire.
785 value_object<para::PositionWithAffinity>("PositionWithAffinity")
786 .field("pos", ¶::PositionWithAffinity::position)
787 .field("affinity", ¶::PositionWithAffinity::affinity);
788
789 value_object<SimpleFontStyle>("FontStyle")
790 .field("slant", &SimpleFontStyle::slant)
791 .field("weight", &SimpleFontStyle::weight)
792 .field("width", &SimpleFontStyle::width);
793
794 value_object<SimpleParagraphStyle>("ParagraphStyle")
795 .field("disableHinting", &SimpleParagraphStyle::disableHinting)
796 .field("_ellipsisPtr", &SimpleParagraphStyle::ellipsisPtr)
797 .field("_ellipsisLen", &SimpleParagraphStyle::ellipsisLen)
798 .field("heightMultiplier", &SimpleParagraphStyle::heightMultiplier)
799 .field("maxLines", &SimpleParagraphStyle::maxLines)
800 .field("replaceTabCharacters", &SimpleParagraphStyle::replaceTabCharacters)
801 .field("textAlign", &SimpleParagraphStyle::textAlign)
802 .field("textDirection", &SimpleParagraphStyle::textDirection)
803 .field("textHeightBehavior", &SimpleParagraphStyle::textHeightBehavior)
804 .field("textStyle", &SimpleParagraphStyle::textStyle)
805 .field("strutStyle", &SimpleParagraphStyle::strutStyle)
806 .field("applyRoundingHack", &SimpleParagraphStyle::applyRoundingHack);
807
808 value_object<SimpleStrutStyle>("StrutStyle")
809 .field("_fontFamiliesPtr", &SimpleStrutStyle::fontFamiliesPtr)
810 .field("_fontFamiliesLen", &SimpleStrutStyle::fontFamiliesLen)
811 .field("strutEnabled", &SimpleStrutStyle::strutEnabled)
812 .field("fontSize", &SimpleStrutStyle::fontSize)
813 .field("fontStyle", &SimpleStrutStyle::fontStyle)
814 .field("heightMultiplier", &SimpleStrutStyle::heightMultiplier)
815 .field("halfLeading", &SimpleStrutStyle::halfLeading)
816 .field("leading", &SimpleStrutStyle::leading)
817 .field("forceStrutHeight", &SimpleStrutStyle::forceStrutHeight);
818
819 value_object<SimpleTextStyle>("TextStyle")
820 .field("_colorPtr", &SimpleTextStyle::colorPtr)
821 .field("_foregroundColorPtr", &SimpleTextStyle::foregroundColorPtr)
822 .field("_backgroundColorPtr", &SimpleTextStyle::backgroundColorPtr)
823 .field("decoration", &SimpleTextStyle::decoration)
824 .field("decorationThickness", &SimpleTextStyle::decorationThickness)
825 .field("_decorationColorPtr", &SimpleTextStyle::decorationColorPtr)
826 .field("decorationStyle", &SimpleTextStyle::decorationStyle)
827 .field("_fontFamiliesPtr", &SimpleTextStyle::fontFamiliesPtr)
828 .field("_fontFamiliesLen", &SimpleTextStyle::fontFamiliesLen)
829 .field("fontSize", &SimpleTextStyle::fontSize)
830 .field("letterSpacing", &SimpleTextStyle::letterSpacing)
831 .field("wordSpacing", &SimpleTextStyle::wordSpacing)
832 .field("heightMultiplier", &SimpleTextStyle::heightMultiplier)
833 .field("halfLeading", &SimpleTextStyle::halfLeading)
834 .field("_localePtr", &SimpleTextStyle::localePtr)
835 .field("_localeLen", &SimpleTextStyle::localeLen)
836 .field("fontStyle", &SimpleTextStyle::fontStyle)
837 .field("_shadowLen", &SimpleTextStyle::shadowLen)
838 .field("_shadowColorsPtr", &SimpleTextStyle::shadowColorsPtr)
839 .field("_shadowOffsetsPtr", &SimpleTextStyle::shadowOffsetsPtr)
840 .field("_shadowBlurRadiiPtr", &SimpleTextStyle::shadowBlurRadiiPtr)
841 .field("_fontFeatureLen", &SimpleTextStyle::fontFeatureLen)
842 .field("_fontFeatureNamesPtr", &SimpleTextStyle::fontFeatureNamesPtr)
843 .field("_fontFeatureValuesPtr", &SimpleTextStyle::fontFeatureValuesPtr)
844 .field("_fontVariationLen", &SimpleTextStyle::fontVariationLen)
845 .field("_fontVariationAxesPtr", &SimpleTextStyle::fontVariationAxesPtr)
846 .field("_fontVariationValuesPtr", &SimpleTextStyle::fontVariationValuesPtr);
847
848 // The U stands for unsigned - we can't bind a generic/template object, so we have to specify it
849 // with the type we are using.
850 // TODO(kjlubick) make this a typedarray.
851 value_object<para::SkRange<size_t>>("URange")
852 .field("start", ¶::SkRange<size_t>::start)
853 .field("end", ¶::SkRange<size_t>::end);
854
855 // TextDecoration should be a const because they can be combined
856 constant("NoDecoration", int(para::TextDecoration::kNoDecoration));
857 constant("UnderlineDecoration", int(para::TextDecoration::kUnderline));
858 constant("OverlineDecoration", int(para::TextDecoration::kOverline));
859 constant("LineThroughDecoration", int(para::TextDecoration::kLineThrough));
860 }
861