Debian Codegraph @

src/ports/SkTypeface_fontations.cpp

raw
1 /*
2 * Copyright 2023 Google Inc.
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/ports/SkTypeface_fontations.h"
8
9 #include "include/codec/SkCodec.h"
10 #include "include/core/SkBitmap.h"
11 #include "include/core/SkCanvas.h"
12 #include "include/core/SkData.h"
13 #include "include/core/SkFontMetrics.h"
14 #include "include/core/SkImage.h"
15 #include "include/core/SkPictureRecorder.h"
16 #include "include/core/SkStream.h"
17 #include "include/effects/SkGradient.h"
18 #include "include/private/base/SkMutex.h"
19 #include "src/base/SkScopeExit.h"
20 #include "src/codec/SkCodecPriv.h"
21 #include "src/core/SkFontDescriptor.h"
22 #include "src/core/SkFontPriv.h"
23 #include "src/ports/SkTypeface_fontations_priv.h"
24 #include "src/ports/fontations/src/skpath_bridge.h"
25
26 namespace {
27
28 template <typename T> rust::Slice<T> toSlice(SkSpan<T> span) {
29 return rust::Slice<T>(span.data(), span.size());
30 }
31
32 static void check_png() {
33 SkASSERTF(SkCodecs::HasDecoder("png"),
34 "No PNG decoder registered. A call to SkCodecs::Register is necessary.");
35 }
36
37 [[maybe_unused]] static inline const constexpr bool kSkShowTextBlitCoverage = false;
38
39 sk_sp<const SkData> streamToData(const std::unique_ptr<SkStreamAsset>& font_data) {
40 if (!font_data) {
41 return SkData::MakeEmpty();
42 }
43 // TODO(drott): Remove this once SkData::MakeFromStream is able to do this itself.
44 if (font_data->getData()) {
45 return font_data->getData();
46 }
47 if (font_data->getMemoryBase() && font_data->getLength()) {
48 return SkData::MakeWithCopy(font_data->getMemoryBase(), font_data->getLength());
49 }
50 font_data->rewind();
51 return SkData::MakeFromStream(font_data.get(), font_data->getLength());
52 }
53
54 rust::Box<::fontations_ffi::BridgeFontRef> make_bridge_font_ref(sk_sp<const SkData> fontData,
55 uint32_t index) {
56 rust::Slice<const uint8_t> slice{fontData->bytes(), fontData->size()};
57 return fontations_ffi::make_font_ref(slice, index);
58 }
59
60 static_assert(sizeof(fontations_ffi::SkiaDesignCoordinate) ==
61 sizeof(SkFontArguments::VariationPosition::Coordinate) &&
62 sizeof(fontations_ffi::SkiaDesignCoordinate::axis) ==
63 sizeof(SkFontArguments::VariationPosition::Coordinate::axis) &&
64 sizeof(fontations_ffi::SkiaDesignCoordinate::value) ==
65 sizeof(SkFontArguments::VariationPosition::Coordinate::value) &&
66 offsetof(fontations_ffi::SkiaDesignCoordinate, axis) ==
67 offsetof(SkFontArguments::VariationPosition::Coordinate, axis) &&
68 offsetof(fontations_ffi::SkiaDesignCoordinate, value) ==
69 offsetof(SkFontArguments::VariationPosition::Coordinate, value) &&
70 "Struct fontations_ffi::SkiaDesignCoordinate must match "
71 "SkFontArguments::VariationPosition::Coordinate.");
72
73 rust::Box<fontations_ffi::BridgeNormalizedCoords> make_normalized_coords(
74 fontations_ffi::BridgeFontRef const& bridgeFontRef,
75 const SkFontArguments::VariationPosition& variationPosition) {
76 // Cast is safe because of static_assert matching the structs above.
77 rust::Slice<const fontations_ffi::SkiaDesignCoordinate> coordinates(
78 reinterpret_cast<const fontations_ffi::SkiaDesignCoordinate*>(
79 variationPosition.coordinates),
80 variationPosition.coordinateCount);
81 return resolve_into_normalized_coords(bridgeFontRef, coordinates);
82 }
83
84 SkMatrix SkMatrixFromFontationsTransform(const fontations_ffi::Transform& transformArg) {
85 return SkMatrix::MakeAll(transformArg.xx,
86 -transformArg.xy,
87 transformArg.dx,
88 -transformArg.yx,
89 transformArg.yy,
90 -transformArg.dy,
91 0.f,
92 0.f,
93 1.0f);
94 }
95
96 bool isLCD(const SkScalerContextRec& rec) { return SkMask::kLCD16_Format == rec.fMaskFormat; }
97
98 bool bothZero(SkScalar a, SkScalar b) { return 0 == a && 0 == b; }
99
100 bool isAxisAligned(const SkScalerContextRec& rec) {
101 return 0 == rec.fPreSkewX && (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
102 bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
103 }
104
105 } // namespace
106
107 sk_sp<SkTypeface> SkTypeface_Make_Fontations(std::unique_ptr<SkStreamAsset> fontData,
108 const SkFontArguments& args) {
109 return SkTypeface_Fontations::MakeFromStream(std::move(fontData), args);
110 }
111
112 sk_sp<SkTypeface> SkTypeface_Make_Fontations(sk_sp<const SkData> fontData,
113 const SkFontArguments& args) {
114 return SkTypeface_Fontations::MakeFromData(std::move(fontData), args);
115 }
116
117 static_assert(
118 sizeof(fontations_ffi::PaletteOverride) == sizeof(SkFontArguments::Palette::Override) &&
119 sizeof(fontations_ffi::PaletteOverride::index) ==
120 sizeof(SkFontArguments::Palette::Override::index) &&
121 sizeof(fontations_ffi::PaletteOverride::color_8888) ==
122 sizeof(SkFontArguments::Palette::Override::color),
123 "Struct fontations_ffi::PaletteOverride must match SkFontArguments::Palette::Override.");
124
125 SkTypeface_Fontations::SkTypeface_Fontations(
126 sk_sp<const SkData> fontData,
127 const SkFontStyle& style,
128 uint32_t ttcIndex,
129 rust::Box<fontations_ffi::BridgeFontRef>&& fontRef,
130 rust::Box<fontations_ffi::BridgeMappingIndex>&& mappingIndex,
131 rust::Box<fontations_ffi::BridgeNormalizedCoords>&& normalizedCoords,
132 rust::Box<fontations_ffi::BridgeOutlineCollection>&& outlines,
133 rust::Box<fontations_ffi::BridgeGlyphStyles>&& glyphStyles,
134 rust::Vec<uint32_t>&& palette)
135 : SkTypeface(style, true)
136 , fFontData(std::move(fontData))
137 , fTtcIndex(ttcIndex)
138 , fBridgeFontRef(std::move(fontRef))
139 , fMappingIndex(std::move(mappingIndex))
140 , fBridgeNormalizedCoords(std::move(normalizedCoords))
141 , fOutlines(std::move(outlines))
142 , fGlyphStyles(std::move(glyphStyles))
143 , fPalette(std::move(palette)) {}
144
145 sk_sp<SkTypeface> SkTypeface_Fontations::MakeFromStream(std::unique_ptr<SkStreamAsset> stream,
146 const SkFontArguments& args) {
147 return MakeFromData(streamToData(stream), args);
148 }
149
150 sk_sp<SkTypeface> SkTypeface_Fontations::MakeFromData(sk_sp<const SkData> data,
151 const SkFontArguments& args) {
152 uint32_t ttcIndex = args.getCollectionIndex() & 0xFFFF;
153 rust::Box<fontations_ffi::BridgeFontRef> bridgeFontRef = make_bridge_font_ref(data, ttcIndex);
154 if (!fontations_ffi::font_ref_is_valid(*bridgeFontRef)) {
155 return nullptr;
156 }
157
158 rust::Box<fontations_ffi::BridgeMappingIndex> mappingIndex =
159 fontations_ffi::make_mapping_index(*bridgeFontRef);
160
161 SkFontArguments::VariationPosition variationPosition = args.getVariationDesignPosition();
162 std::unique_ptr<SkFontArguments::VariationPosition::Coordinate[]> concatenatedCoords = nullptr;
163 // Handle FreeType behaviour of upper 15 bits of collection index
164 // representing a named instance choice. If so, prepopulate the variation
165 // coordinates with the values from the named instance and append the user
166 // coordinates after that so they can override the named instance's
167 // coordinates.
168 if (args.getCollectionIndex() & 0xFFFF0000) {
169 size_t numNamedInstanceCoords =
170 fontations_ffi::coordinates_for_shifted_named_instance_index(
171 *bridgeFontRef,
172 args.getCollectionIndex(),
173 rust::cxxbridge1::Slice<fontations_ffi::SkiaDesignCoordinate>());
174 concatenatedCoords.reset(
175 new SkFontArguments::VariationPosition::Coordinate
176 [numNamedInstanceCoords + variationPosition.coordinateCount]);
177
178 rust::cxxbridge1::Slice<fontations_ffi::SkiaDesignCoordinate> targetSlice(
179 reinterpret_cast<fontations_ffi::SkiaDesignCoordinate*>(concatenatedCoords.get()),
180 numNamedInstanceCoords);
181 size_t retrievedNamedInstanceCoords =
182 fontations_ffi::coordinates_for_shifted_named_instance_index(
183 *bridgeFontRef, args.getCollectionIndex(), targetSlice);
184 if (numNamedInstanceCoords != retrievedNamedInstanceCoords) {
185 return nullptr;
186 }
187 for (int i = 0; i < variationPosition.coordinateCount; ++i) {
188 concatenatedCoords[numNamedInstanceCoords + i] = variationPosition.coordinates[i];
189 }
190 variationPosition.coordinateCount += numNamedInstanceCoords;
191 variationPosition.coordinates = concatenatedCoords.get();
192 }
193
194 rust::Box<fontations_ffi::BridgeNormalizedCoords> normalizedCoords =
195 make_normalized_coords(*bridgeFontRef, variationPosition);
196 SkFontStyle style;
197 fontations_ffi::BridgeFontStyle fontStyle;
198 if (fontations_ffi::get_font_style(*bridgeFontRef, *normalizedCoords, fontStyle)) {
199 style = SkFontStyle(fontStyle.weight,
200 fontStyle.width,
201 static_cast<SkFontStyle::Slant>(fontStyle.slant));
202 }
203 rust::Box<fontations_ffi::BridgeOutlineCollection> outlines =
204 fontations_ffi::get_outline_collection(*bridgeFontRef);
205
206 // Container for precomputed work for autohinting, see Skrifa's GlyphStyles.
207 rust::Box<fontations_ffi::BridgeGlyphStyles> glyphStyles =
208 fontations_ffi::get_bridge_glyph_styles();
209
210 rust::Slice<const fontations_ffi::PaletteOverride> paletteOverrides(
211 reinterpret_cast<const ::fontations_ffi::PaletteOverride*>(args.getPalette().overrides),
212 args.getPalette().overrideCount);
213 rust::Vec<uint32_t> palette =
214 resolve_palette(*bridgeFontRef, args.getPalette().index, paletteOverrides);
215
216 return sk_sp<SkTypeface>(new SkTypeface_Fontations(data,
217 style,
218 ttcIndex,
219 std::move(bridgeFontRef),
220 std::move(mappingIndex),
221 std::move(normalizedCoords),
222 std::move(outlines),
223 std::move(glyphStyles),
224 std::move(palette)));
225 }
226
227 namespace sk_fontations {
228
229 AxisWrapper::AxisWrapper(SkFontParameters::Variation::Axis axisArray[], size_t axisCount)
230 : fAxisArray(axisArray), fAxisCount(axisCount) {}
231
232 bool AxisWrapper::populate_axis(
233 size_t i, uint32_t axisTag, float min, float def, float max, bool hidden) {
234 if (i >= fAxisCount) {
235 return false;
236 }
237 SkFontParameters::Variation::Axis& axis = fAxisArray[i];
238 axis.tag = axisTag;
239 axis.min = min;
240 axis.def = def;
241 axis.max = max;
242 axis.setHidden(hidden);
243 return true;
244 }
245
246 size_t AxisWrapper::size() const { return fAxisCount; }
247
248 } // namespace sk_fontations
249
250 int SkTypeface_Fontations::onGetUPEM() const {
251 return fontations_ffi::units_per_em_or_zero(*fBridgeFontRef);
252 }
253
254 void SkTypeface_Fontations::onGetFamilyName(SkString* familyName) const {
255 rust::String readFamilyName = fontations_ffi::family_name(*fBridgeFontRef);
256 *familyName = SkString(readFamilyName.data(), readFamilyName.size());
257 }
258
259 bool SkTypeface_Fontations::onGetPostScriptName(SkString* postscriptName) const {
260 rust::String readPsName;
261 if (fontations_ffi::postscript_name(*fBridgeFontRef, readPsName)) {
262 if (postscriptName) {
263 *postscriptName = SkString(readPsName.data(), readPsName.size());
264 }
265 return true;
266 }
267
268 return false;
269 }
270
271 bool SkTypeface_Fontations::onGlyphMaskNeedsCurrentColor() const {
272 fGlyphMasksMayNeedCurrentColorOnce([this] {
273 static constexpr SkFourByteTag COLRTag = SkSetFourByteTag('C', 'O', 'L', 'R');
274 fGlyphMasksMayNeedCurrentColor = this->getTableSize(COLRTag) > 0;
275 });
276 return fGlyphMasksMayNeedCurrentColor;
277 }
278
279 void SkTypeface_Fontations::onCharsToGlyphs(SkSpan<const SkUnichar> chars,
280 SkSpan<SkGlyphID> glyphs) const {
281 SkASSERT(chars.size() == glyphs.size());
282 rust::Slice<const uint32_t> codepointSlice{reinterpret_cast<const uint32_t*>(chars.data()),
283 chars.size()};
284 fontations_ffi::lookup_glyph_or_zero(*fBridgeFontRef, *fMappingIndex,
285 codepointSlice, toSlice(glyphs));
286 }
287 int SkTypeface_Fontations::onCountGlyphs() const {
288 return fontations_ffi::num_glyphs(*fBridgeFontRef);
289 }
290
291 void SkTypeface_Fontations::getGlyphToUnicodeMap(SkSpan<SkUnichar> codepointForGlyphMap) const {
292 size_t numGlyphs = std::min(SkToSizeT(onCountGlyphs()), codepointForGlyphMap.size());
293 rust::Slice<uint32_t> codepointForGlyphSlice
294 {reinterpret_cast<uint32_t*>(codepointForGlyphMap.data()), numGlyphs};
295 fontations_ffi::fill_glyph_to_unicode_map(*fBridgeFontRef, codepointForGlyphSlice);
296 }
297
298 void SkTypeface_Fontations::onFilterRec(SkScalerContextRec* rec) const {
299 rec->useStrokeForFakeBold();
300
301 // See https://issues.skia.org/issues/396360753
302 // We would like Fontations anti-aliasing on a surface with unknown pixel geometry to
303 // look like the FreeType backend in order to avoid perceived regressions
304 // in sharpness, so we ignore SkScalerContext::kGenA8FromLCD_Flag in fRec.fFlags.
305 rec->fFlags &= ~SkScalerContext::kGenA8FromLCD_Flag;
306
307 // Opportunistic hinting downgrades copied from SkFontHost_FreeType.cpp
308 SkFontHinting h = rec->getHinting();
309 if (SkFontHinting::kFull == h && !isLCD(*rec)) {
310 // Collapse full->normal hinting if we're not doing LCD.
311 h = SkFontHinting::kNormal;
312 }
313
314 // Rotated text looks bad with hinting, so we disable it as needed.
315 if (!isAxisAligned(*rec)) {
316 h = SkFontHinting::kNone;
317 }
318 rec->setHinting(h);
319 }
320
321 class SkrifaLocalizedStrings : public SkTypeface::LocalizedStrings {
322 public:
323 SkrifaLocalizedStrings(
324 rust::Box<::fontations_ffi::BridgeLocalizedStrings> bridge_localized_strings)
325 : fBridgeLocalizedStrings(std::move(bridge_localized_strings)) {}
326 bool next(SkTypeface::LocalizedString* localized_string) override {
327 fontations_ffi::BridgeLocalizedName localizedName;
328 if (!fontations_ffi::localized_name_next(*fBridgeLocalizedStrings, localizedName)) {
329 return false;
330 }
331 localized_string->fString =
332 SkString(localizedName.string.data(), localizedName.string.size());
333 localized_string->fLanguage =
334 SkString(localizedName.language.data(), localizedName.language.size());
335 return true;
336 }
337
338 private:
339 rust::Box<::fontations_ffi::BridgeLocalizedStrings> fBridgeLocalizedStrings;
340 };
341
342 SkTypeface::LocalizedStrings* SkTypeface_Fontations::onCreateFamilyNameIterator() const {
343 return new SkrifaLocalizedStrings(fontations_ffi::get_localized_strings(*fBridgeFontRef));
344 }
345
346 class SkFontationsScalerContext : public SkScalerContext {
347 public:
348 SkFontationsScalerContext(const SkTypeface_Fontations& realTypeface,
349 const SkScalerContextEffects& effects,
350 const SkDescriptor* desc,
351 SkTypeface& proxyTypeface)
352 : SkScalerContext(proxyTypeface, effects, desc) // proxyTypeface owns the realTypeface
353 , fBridgeFontRef(realTypeface.getBridgeFontRef())
354 , fBridgeNormalizedCoords(realTypeface.getBridgeNormalizedCoords())
355 , fOutlines(realTypeface.getOutlines())
356 , fGlyphStyles(realTypeface.getGlyphStyles())
357 , fMappingIndex(realTypeface.getMappingIndex())
358 , fPalette(realTypeface.getPalette())
359 , fHintingInstance(fontations_ffi::no_hinting_instance()) {
360 using AutoHinting = fontations_ffi::AutoHintingControl;
361
362 fRec.computeMatrices(
363 SkScalerContextRec::PreMatrixScale::kVertical, &fScale, &fRemainingMatrix);
364
365 fDoLinearMetrics = this->isLinearMetrics();
366
367 // See below for the exception for SkFontHinting::kSlight.
368 bool forceAutoHinting = SkToBool(fRec.fFlags & kForceAutohinting_Flag);
369 AutoHinting autoHintingControl = forceAutoHinting ? AutoHinting::ForceForGlyfAndCff
370 : AutoHinting::Fallback;
371
372 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
373 // On Android, match the FreeType backend and disable autohinting completely
374 // unless the force flag is set.
375 if (!forceAutoHinting)
376 autoHintingControl = AutoHinting::ForceOff;
377 #endif
378
379 // Hinting-reliant fonts exist that display incorrect contours when not executing their
380 // hinting instructions. Detect those and force-enable hinting for them.
381 if (fontations_ffi::hinting_reliant(fOutlines)) {
382 fHintingInstance = fontations_ffi::make_mono_hinting_instance(
383 fOutlines, fScale.y(), fBridgeNormalizedCoords);
384 fDoLinearMetrics = false;
385 } else {
386 if (SkMask::kBW_Format == fRec.fMaskFormat) {
387 if (fRec.getHinting() == SkFontHinting::kNone) {
388 fHintingInstance = fontations_ffi::no_hinting_instance();
389 fDoLinearMetrics = true;
390 } else {
391 fHintingInstance = fontations_ffi::make_mono_hinting_instance(
392 fOutlines, fScale.y(), fBridgeNormalizedCoords);
393 fDoLinearMetrics = false;
394 }
395 } else {
396 switch (fRec.getHinting()) {
397 case SkFontHinting::kNone:
398 fHintingInstance = fontations_ffi::no_hinting_instance();
399 fDoLinearMetrics = true;
400 break;
401 case SkFontHinting::kSlight:
402 // Unhinted metrics.
403 if (autoHintingControl != AutoHinting::ForceForGlyfAndCff &&
404 autoHintingControl != AutoHinting::ForceOff)
405 {
406 autoHintingControl = AutoHinting::ForceForGlyf;
407 }
408 fHintingInstance = fontations_ffi::make_hinting_instance(
409 fOutlines,
410 fGlyphStyles,
411 fScale.y(),
412 fBridgeNormalizedCoords,
413 true /* do_light_hinting */,
414 false /* do_lcd_antialiasing */,
415 false /* lcd_orientation_vertical */,
416 autoHintingControl);
417 fDoLinearMetrics = true;
418 break;
419 case SkFontHinting::kNormal:
420 // No hinting to subpixel coordinates.
421 fHintingInstance = fontations_ffi::make_hinting_instance(
422 fOutlines,
423 fGlyphStyles,
424 fScale.y(),
425 fBridgeNormalizedCoords,
426 false /* do_light_hinting */,
427 false /* do_lcd_antialiasing */,
428 false /* lcd_orientation_vertical */,
429 autoHintingControl);
430 break;
431 case SkFontHinting::kFull:
432 // Attempt to make use of hinting to subpixel coordinates.
433 fHintingInstance = fontations_ffi::make_hinting_instance(
434 fOutlines,
435 fGlyphStyles,
436 fScale.y(),
437 fBridgeNormalizedCoords,
438 false /* do_light_hinting */,
439 isLCD(fRec) /* do_lcd_antialiasing */,
440 SkToBool(fRec.fFlags &
441 SkScalerContext::
442 kLCD_Vertical_Flag) /* lcd_orientation_vertical */,
443 autoHintingControl);
444 }
445 }
446 }
447 }
448
449 std::optional<SkScalar> getContourHeightForLetter(SkUnichar letter) {
450 SkGlyphID glyphId;
451 rust::Slice<const uint32_t> codepointSlice{reinterpret_cast<const uint32_t*>(&letter), 1};
452 rust::Slice<uint16_t> glyphSlice{reinterpret_cast<uint16_t*>(&glyphId), 1};
453 fontations_ffi::lookup_glyph_or_zero(fBridgeFontRef, fMappingIndex,
454 codepointSlice, glyphSlice);
455 if (!glyphId) {
456 return {};
457 }
458 fontations_ffi::BridgeScalerMetrics scalerMetrics;
459 if (auto glyphPath = generatePathForGlyphId(glyphId, fScale.y(),
460 *fHintingInstance, scalerMetrics)) {
461 return glyphPath->getBounds().height();
462 }
463 return {};
464 }
465
466 // yScale is only used if hintinInstance is set to Unhinted,
467 // otherwise the size is controlled by the configured hintingInstance.
468 // hintingInstance argument is needed as COLRv1 drawing performs unhinted,
469 // unscaled path retrieval.
470 std::optional<SkPath> generatePathForGlyphId(uint16_t glyphId,
471 float yScale,
472 const fontations_ffi::BridgeHintingInstance& hintingInstance,
473 fontations_ffi::BridgeScalerMetrics& scalerMetrics) {
474 // See https://crbug.com/390889644 - while SkScalerContexts are single-thread
475 // in general, generateYScalePathForGlyphId() can be called from a COLRv1
476 // SkDrawable as well (see generateDrawable()). For this reason access to the
477 // path extraction array needs to be made thread-safe here.
478 SkAutoMutexExclusive l(fPathMutex);
479 // Keep allocations in check. The rust side pre-allocates a fixed amount,
480 // and afer leaving this function, we shrink to the same amount.
481 SK_AT_SCOPE_EXIT(fontations_ffi::shrink_verbs_points_if_needed(fPathVerbs, fPathPoints));
482
483 if (!fontations_ffi::get_path_verbs_points(fOutlines,
484 glyphId,
485 yScale,
486 fBridgeNormalizedCoords,
487 hintingInstance,
488 fPathVerbs,
489 fPathPoints,
490 scalerMetrics)) {
491 return {};
492 }
493
494 // See https://issues.skia.org/345178242 for details:
495 // The FreeType backend performs a path simplification here based on the
496 // equivalent of what we have here as scalerMetrics.has_overlaps
497 // Since PathOps::Simplify fails or at times produces incorrect simplified
498 // contours, skip that step here.
499 return SkPath::Make({reinterpret_cast<const SkPoint*>(fPathPoints.data()),
500 fPathPoints.size()},
501 fPathVerbs,
502 {},
503 SkPathFillType::kWinding);
504 }
505
506 protected:
507 struct ScalerContextBits {
508 using value_type = uint16_t;
509 static const constexpr value_type PATH = 1;
510 static const constexpr value_type COLRv0 = 2;
511 static const constexpr value_type COLRv1 = 3;
512 static const constexpr value_type BITMAP = 4;
513 };
514
515 GlyphMetrics generateMetrics(const SkGlyph& glyph, SkArenaAlloc*) override {
516 GlyphMetrics mx(glyph.maskFormat());
517
518 bool has_colrv1_glyph = false;
519 bool has_colrv0_glyph = false;
520 bool has_bitmap_glyph = false;
521 if (fontations_ffi::has_any_color_table(fBridgeFontRef)) {
522 has_colrv1_glyph = fontations_ffi::has_colrv1_glyph(fBridgeFontRef, glyph.getGlyphID());
523 has_colrv0_glyph = fontations_ffi::has_colrv0_glyph(fBridgeFontRef, glyph.getGlyphID());
524 has_bitmap_glyph = fontations_ffi::has_bitmap_glyph(fBridgeFontRef, glyph.getGlyphID());
525 }
526
527 // Local overrides for color fonts etc. may alter the request for linear metrics.
528 bool doLinearMetrics = fDoLinearMetrics;
529
530 if (has_bitmap_glyph) {
531 // Bitmap advance metrics can originate from different strike sizes in the bitmap
532 // font and are thus not linearly scaling with font size.
533 doLinearMetrics = false;
534 }
535 if (has_colrv0_glyph || has_colrv1_glyph) {
536 // We prefer color vector glyphs, and hinting is disabled for those.
537 doLinearMetrics = true;
538 }
539
540 float x_advance = 0.0f;
541 x_advance = fontations_ffi::unhinted_advance_width_or_zero(
542 fBridgeFontRef, fScale.y(), fBridgeNormalizedCoords, glyph.getGlyphID());
543 if (!doLinearMetrics) {
544 fontations_ffi::BridgeScalerMetrics scalerMetrics;
545 if (auto generatedPath = generatePathImpl(glyph.getGlyphID(),
546 scalerMetrics)) {
547 mx.generatedPath = std::move(*generatedPath);
548
549 if (scalerMetrics.has_adjusted_advance) {
550 // FreeType rounds the advance to full pixels when in hinting modes.
551 // Match FreeType and round here.
552 // See
553 // * https://gitlab.freedesktop.org/freetype/freetype/-/blob/57617782464411201ce7bbc93b086c1b4d7d84a5/src/autofit/afloader.c#L422
554 // * https://gitlab.freedesktop.org/freetype/freetype/-/blob/57617782464411201ce7bbc93b086c1b4d7d84a5/src/truetype/ttgload.c#L823
555 float hinted_advance = roundf(scalerMetrics.adjusted_advance);
556 // TODO(drott): Remove this workaround for fontations returning 0
557 // for a space glyph without contours, compare
558 // https://github.com/googlefonts/fontations/issues/905
559 if (hinted_advance != x_advance && hinted_advance != 0) {
560 x_advance = hinted_advance;
561 }
562 }
563 }
564 }
565 mx.advance = fRemainingMatrix.mapPoint({x_advance, 0});
566
567 if (has_colrv1_glyph || has_colrv0_glyph) {
568 mx.extraBits = has_colrv1_glyph ? ScalerContextBits::COLRv1 : ScalerContextBits::COLRv0;
569 mx.maskFormat = SkMask::kARGB32_Format;
570 mx.neverRequestPath = true;
571
572 fontations_ffi::ClipBox clipBox;
573 if (has_colrv1_glyph && fontations_ffi::get_colrv1_clip_box(fBridgeFontRef,
574 fBridgeNormalizedCoords,
575 glyph.getGlyphID(),
576 fScale.y(),
577 clipBox)) {
578 // Flip y.
579 SkRect boundsRect = SkRect::MakeLTRB(
580 clipBox.x_min, -clipBox.y_max, clipBox.x_max, -clipBox.y_min);
581
582 if (!fRemainingMatrix.isIdentity()) {
583 boundsRect = fRemainingMatrix.mapRect(boundsRect);
584 }
585
586 boundsRect.roundOut(&mx.bounds);
587
588 } else {
589 uint16_t upem = fontations_ffi::units_per_em_or_zero(fBridgeFontRef);
590 if (upem == 0) {
591 mx.bounds = SkRect::MakeEmpty();
592 } else {
593 SkMatrix fullTransform = fRec.getSingleMatrix();
594 fullTransform.preScale(1.f / upem, 1.f / upem);
595
596 sk_fontations::BoundsPainter boundsPainter(*this, fullTransform, upem);
597 bool result = fontations_ffi::draw_colr_glyph(fBridgeFontRef,
598 fBridgeNormalizedCoords,
599 glyph.getGlyphID(),
600 boundsPainter);
601 if (result) {
602 boundsPainter.getBoundingBox().roundOut(&mx.bounds);
603 } else {
604 mx.bounds = SkRect::MakeEmpty();
605 }
606 }
607 }
608 } else if (has_bitmap_glyph) {
609 mx.maskFormat = SkMask::kARGB32_Format;
610 mx.neverRequestPath = true;
611 mx.extraBits = ScalerContextBits::BITMAP;
612
613 rust::cxxbridge1::Box<fontations_ffi::BridgeBitmapGlyph> bitmap_glyph =
614 fontations_ffi::bitmap_glyph(fBridgeFontRef, glyph.getGlyphID(), fScale.y());
615 rust::cxxbridge1::Slice<const uint8_t> png_data =
616 fontations_ffi::png_data(*bitmap_glyph);
617
618 if (png_data.empty()) {
619 return mx;
620 }
621
622 const fontations_ffi::BitmapMetrics bitmapMetrics =
623 fontations_ffi::bitmap_metrics(*bitmap_glyph);
624
625 sk_sp<SkImage> img = SkImages::DeferredFromEncodedData(
626 SkData::MakeWithoutCopy(png_data.data(), png_data.size()));
627 if (!img) {
628 check_png();
629 return mx;
630 }
631
632 SkImageInfo info = img->imageInfo();
633
634 SkRect bounds = SkRect::Make(info.bounds());
635 SkMatrix matrix = fRemainingMatrix;
636
637 // We deal with two scale factors here: Scaling from font units to
638 // device pixels, and scaling the embedded PNG from its number of
639 // rows to a specific size, depending on the ppem values in the
640 // bitmap glyph information.
641 float imageToSize = fScale.y() / bitmapMetrics.ppem_y;
642 float fontUnitsToSize = fScale.y() /
643 fontations_ffi::units_per_em_or_zero(fBridgeFontRef);
644
645 // The offset from origin is given in font units, so requires a
646 // different scale factor than the scaling of the image.
647 matrix.preTranslate( bitmapMetrics.bearing_x * fontUnitsToSize,
648 -bitmapMetrics.bearing_y * fontUnitsToSize);
649 matrix.preScale(imageToSize, imageToSize);
650 matrix.preTranslate( bitmapMetrics.inner_bearing_x,
651 -bitmapMetrics.inner_bearing_y);
652
653 // For sbix bitmap glyphs, the origin is the bottom left of the image.
654 float heightAdjustment =
655 bitmapMetrics.placement_origin_bottom_left ? bounds.height() : 0;
656 matrix.preTranslate(0, -heightAdjustment);
657
658 if (this->isSubpixel()) {
659 matrix.postTranslate(SkFixedToScalar(glyph.getSubXFixed()),
660 SkFixedToScalar(glyph.getSubYFixed()));
661 }
662 matrix.mapRect(&bounds);
663 mx.bounds = SkRect::Make(bounds.roundOut());
664
665 if (SkIsFinite(bitmapMetrics.advance)) {
666 mx.advance = matrix.mapVector(bitmapMetrics.advance, 0);
667 }
668 } else {
669 mx.extraBits = ScalerContextBits::PATH;
670 mx.computeFromPath = true;
671 }
672 return mx;
673 }
674
675 void generatePngImage(const SkGlyph& glyph, void* imageBuffer) {
676 SkASSERT(glyph.maskFormat() == SkMask::kARGB32_Format);
677 SkBitmap dstBitmap;
678 dstBitmap.installPixels(
679 SkImageInfo::Make(
680 glyph.width(), glyph.height(), kN32_SkColorType, kPremul_SkAlphaType),
681 imageBuffer,
682 glyph.rowBytes());
683
684 SkCanvas canvas(dstBitmap);
685
686 canvas.translate(-glyph.left(), -glyph.top());
687
688 rust::cxxbridge1::Box<fontations_ffi::BridgeBitmapGlyph> bitmap_glyph =
689 fontations_ffi::bitmap_glyph(fBridgeFontRef, glyph.getGlyphID(), fScale.y());
690 rust::cxxbridge1::Slice<const uint8_t> png_data = fontations_ffi::png_data(*bitmap_glyph);
691 SkASSERT(png_data.size());
692
693 sk_sp<SkImage> glyph_image = SkImages::DeferredFromEncodedData(
694 SkData::MakeWithoutCopy(png_data.data(), png_data.size()));
695 if (!glyph_image) {
696 check_png();
697 return;
698 }
699
700 canvas.clear(SK_ColorTRANSPARENT);
701 canvas.concat(fRemainingMatrix);
702
703 if (this->isSubpixel()) {
704 canvas.translate(SkFixedToScalar(glyph.getSubXFixed()),
705 SkFixedToScalar(glyph.getSubYFixed()));
706 }
707 const fontations_ffi::BitmapMetrics bitmapMetrics =
708 fontations_ffi::bitmap_metrics(*bitmap_glyph);
709
710 // We need two different scale factors here, one for font units to size,
711 // one for scaling the embedded PNG, see generateMetrics() for details.
712 SkScalar imageScaleFactor = fScale.y() / bitmapMetrics.ppem_y;
713
714 float fontUnitsToSize = fScale.y() / fontations_ffi::units_per_em_or_zero(fBridgeFontRef);
715 canvas.translate( bitmapMetrics.bearing_x * fontUnitsToSize,
716 -bitmapMetrics.bearing_y * fontUnitsToSize);
717 canvas.scale(imageScaleFactor, imageScaleFactor);
718 canvas.translate( bitmapMetrics.inner_bearing_x,
719 -bitmapMetrics.inner_bearing_y);
720
721 float heightAdjustment =
722 bitmapMetrics.placement_origin_bottom_left ? glyph_image->height() : 0;
723
724 canvas.translate(0, -heightAdjustment);
725
726 SkSamplingOptions sampling(SkFilterMode::kLinear, SkMipmapMode::kNearest);
727 canvas.drawImage(glyph_image, 0, 0, sampling);
728 }
729
730 void generateImage(const SkGlyph& glyph, void* imageBuffer) override {
731 ScalerContextBits::value_type format = glyph.extraBits();
732 if (format == ScalerContextBits::PATH) {
733 this->generateImageFromPath(glyph, imageBuffer);
734 } else if (format == ScalerContextBits::COLRv1 || format == ScalerContextBits::COLRv0) {
735 SkASSERT(glyph.maskFormat() == SkMask::kARGB32_Format);
736 SkBitmap dstBitmap;
737 dstBitmap.installPixels(
738 SkImageInfo::Make(
739 glyph.width(), glyph.height(), kN32_SkColorType, kPremul_SkAlphaType),
740 imageBuffer,
741 glyph.rowBytes());
742
743 SkCanvas canvas(dstBitmap);
744 if constexpr (kSkShowTextBlitCoverage) {
745 canvas.clear(0x33FF0000);
746 } else {
747 canvas.clear(SK_ColorTRANSPARENT);
748 }
749 canvas.translate(-glyph.left(), -glyph.top());
750
751 drawCOLRGlyph(glyph, fRec.fForegroundColor, &canvas);
752 } else if (format == ScalerContextBits::BITMAP) {
753 generatePngImage(glyph, imageBuffer);
754 } else {
755 SK_ABORT("Bad format");
756 }
757 }
758
759 std::optional<GeneratedPath> generatePathImpl(SkGlyphID glyphId,
760 fontations_ffi::BridgeScalerMetrics& scalerMetrics) {
761 if (auto path = generatePathForGlyphId(glyphId, fScale.y(),
762 *fHintingInstance, scalerMetrics)) {
763 if (auto newpath = path->tryMakeTransform(fRemainingMatrix)) {
764 return {{
765 *newpath,
766 !fRemainingMatrix.isIdentity()
767 }};
768 }
769 }
770 return {};
771 }
772
773 // For hinted glyphs, generateMetrics provides a shortcut to set a generated path on
774 // SkGlyph - so this method will not be called when a path has already been set.
775 std::optional<GeneratedPath> generatePath(const SkGlyph& glyph) override {
776 SkASSERT(glyph.extraBits() == ScalerContextBits::PATH);
777 fontations_ffi::BridgeScalerMetrics scalerMetrics;
778 return generatePathImpl(glyph.getGlyphID(), scalerMetrics);
779 }
780
781 bool drawCOLRGlyph(const SkGlyph& glyph, SkColor foregroundColor, SkCanvas* canvas) {
782 uint16_t upem = fontations_ffi::units_per_em_or_zero(fBridgeFontRef);
783 if (upem == 0) {
784 return false;
785 }
786
787 SkMatrix scalerMatrix = fRec.getSingleMatrix();
788 SkAutoCanvasRestore autoRestore(canvas, true /* doSave */);
789
790 // Scale down so that COLR operations can happen in glyph coordinates.
791 SkMatrix upemToPpem = SkMatrix::Scale(1.f / upem, 1.f / upem);
792 scalerMatrix.preConcat(upemToPpem);
793 canvas->concat(scalerMatrix);
794 SkPaint defaultPaint;
795 defaultPaint.setColor(SK_ColorRED);
796 sk_fontations::ColorPainter colorPainter(*this, *canvas, fPalette, foregroundColor,
797 SkMask::kBW_Format != fRec.fMaskFormat, upem);
798 bool result = fontations_ffi::draw_colr_glyph(
799 fBridgeFontRef, fBridgeNormalizedCoords, glyph.getGlyphID(), colorPainter);
800 return result;
801 }
802
803 sk_sp<SkDrawable> generateDrawable(const SkGlyph& glyph) override {
804 struct GlyphDrawable : public SkDrawable {
805 SkFontationsScalerContext* fSelf;
806 SkGlyph fGlyph;
807 GlyphDrawable(SkFontationsScalerContext* self, const SkGlyph& glyph)
808 : fSelf(self), fGlyph(glyph) {}
809 SkRect onGetBounds() override { return fGlyph.rect(); }
810 size_t onApproximateBytesUsed() override { return sizeof(GlyphDrawable); }
811 void maybeShowTextBlitCoverage(SkCanvas* canvas) {
812 if constexpr (kSkShowTextBlitCoverage) {
813 SkPaint paint;
814 paint.setColor(0x3300FF00);
815 paint.setStyle(SkPaint::kFill_Style);
816 canvas->drawRect(this->onGetBounds(), paint);
817 }
818 }
819 };
820 struct ColrGlyphDrawable : public GlyphDrawable {
821 using GlyphDrawable::GlyphDrawable;
822 void onDraw(SkCanvas* canvas) override {
823 this->maybeShowTextBlitCoverage(canvas);
824 fSelf->drawCOLRGlyph(fGlyph, fSelf->fRec.fForegroundColor, canvas);
825 }
826 };
827 ScalerContextBits::value_type format = glyph.extraBits();
828 if (format == ScalerContextBits::COLRv1 || format == ScalerContextBits::COLRv0) {
829 return sk_sp<SkDrawable>(new ColrGlyphDrawable(this, glyph));
830 }
831 return nullptr;
832 }
833
834 void generateFontMetrics(SkFontMetrics* out_metrics) override {
835 fontations_ffi::Metrics metrics =
836 fontations_ffi::get_skia_metrics(fBridgeFontRef, fScale.y(), fBridgeNormalizedCoords);
837 out_metrics->fTop = -metrics.top;
838 out_metrics->fAscent = -metrics.ascent;
839 out_metrics->fDescent = -metrics.descent;
840 out_metrics->fBottom = -metrics.bottom;
841 out_metrics->fLeading = metrics.leading;
842 out_metrics->fAvgCharWidth = metrics.avg_char_width;
843 out_metrics->fMaxCharWidth = metrics.max_char_width;
844 out_metrics->fXMin = metrics.x_min;
845 out_metrics->fXMax = metrics.x_max;
846 out_metrics->fXHeight = -metrics.x_height;
847 out_metrics->fCapHeight = -metrics.cap_height;
848 out_metrics->fFlags = 0;
849
850 // Cap height synthesis.
851 if (!out_metrics->fCapHeight) {
852 if (auto height = getContourHeightForLetter('H')) {
853 out_metrics->fCapHeight = *height;
854 } else {
855 out_metrics->fCapHeight = metrics.ascent;
856 }
857 }
858
859 if (!out_metrics->fXHeight) {
860 if (auto xHeight = getContourHeightForLetter('x')) {
861 out_metrics->fXHeight = *xHeight;
862 } else {
863 out_metrics->fXHeight = metrics.ascent;
864 }
865 }
866
867 if (fontations_ffi::table_data(fBridgeFontRef,
868 SkSetFourByteTag('f', 'v', 'a', 'r'),
869 0,
870 rust::Slice<uint8_t>())) {
871 out_metrics->fFlags |= SkFontMetrics::kBoundsInvalid_Flag;
872 }
873 auto setMetric = [](float& dstMetric, const float srcMetric,
874 uint32_t& flags, const SkFontMetrics::FontMetricsFlags flag)
875 {
876 if (std::isnan(srcMetric)) {
877 dstMetric = 0;
878 } else {
879 dstMetric = srcMetric;
880 flags |= flag;
881 }
882 };
883 setMetric(out_metrics->fUnderlinePosition, -metrics.underline_position,
884 out_metrics->fFlags, SkFontMetrics::kUnderlinePositionIsValid_Flag);
885 setMetric(out_metrics->fUnderlineThickness, metrics.underline_thickness,
886 out_metrics->fFlags, SkFontMetrics::kUnderlineThicknessIsValid_Flag);
887
888 setMetric(out_metrics->fStrikeoutPosition, -metrics.strikeout_position,
889 out_metrics->fFlags, SkFontMetrics::kStrikeoutPositionIsValid_Flag);
890 setMetric(out_metrics->fStrikeoutThickness, metrics.strikeout_thickness,
891 out_metrics->fFlags, SkFontMetrics::kStrikeoutThicknessIsValid_Flag);
892 }
893
894 private:
895 SkVector fScale;
896 SkMatrix fRemainingMatrix;
897 sk_sp<SkData> fFontData = nullptr;
898 const fontations_ffi::BridgeFontRef& fBridgeFontRef;
899 const fontations_ffi::BridgeNormalizedCoords& fBridgeNormalizedCoords;
900 const fontations_ffi::BridgeOutlineCollection& fOutlines;
901 const fontations_ffi::BridgeGlyphStyles& fGlyphStyles;
902 const fontations_ffi::BridgeMappingIndex& fMappingIndex;
903 const SkSpan<const SkColor> fPalette;
904 rust::Box<fontations_ffi::BridgeHintingInstance> fHintingInstance;
905 bool fDoLinearMetrics = false;
906 // Keeping the path extraction target buffers around significantly avoids
907 // allocation churn.
908 SkMutex fPathMutex;
909 rust::Vec<uint8_t> fPathVerbs;
910 rust::Vec<fontations_ffi::FfiPoint> fPathPoints;
911
912 friend class sk_fontations::ColorPainter;
913 };
914
915 std::unique_ptr<SkStreamAsset> SkTypeface_Fontations::onOpenStream(int* ttcIndex) const {
916 *ttcIndex = fTtcIndex;
917 return std::make_unique<SkMemoryStream>(fFontData);
918 }
919
920 sk_sp<SkTypeface> SkTypeface_Fontations::onMakeClone(const SkFontArguments& args) const {
921 // Matching DWrite implementation, return self if ttc index mismatches.
922 if (fTtcIndex != SkTo<uint32_t>(args.getCollectionIndex())) {
923 return sk_ref_sp(this);
924 }
925
926 int numAxes = onGetVariationDesignPosition({});
927 auto fusedDesignPosition =
928 std::make_unique<SkFontArguments::VariationPosition::Coordinate[]>(numAxes);
929 int retrievedAxes = onGetVariationDesignPosition({fusedDesignPosition.get(), (size_t)numAxes});
930 if (numAxes != retrievedAxes) {
931 return nullptr;
932 }
933
934 // We know the internally retrieved axes are normalized, contain a value for every possible
935 // axis, other axes do not exist, so we only need to override any of those.
936 for (int i = 0; i < numAxes; ++i) {
937 const SkFontArguments::VariationPosition& argPosition = args.getVariationDesignPosition();
938 for (int j = 0; j < argPosition.coordinateCount; ++j) {
939 if (fusedDesignPosition[i].axis == argPosition.coordinates[j].axis) {
940 fusedDesignPosition[i].value = argPosition.coordinates[j].value;
941 }
942 }
943 }
944
945 SkFontArguments fusedArgs;
946 fusedArgs.setVariationDesignPosition({fusedDesignPosition.get(), SkToInt(numAxes)});
947 fusedArgs.setPalette(args.getPalette());
948
949 rust::cxxbridge1::Box<fontations_ffi::BridgeNormalizedCoords> normalized_args =
950 make_normalized_coords(*fBridgeFontRef, fusedArgs.getVariationDesignPosition());
951
952 if (!fontations_ffi::normalized_coords_equal(*normalized_args, *fBridgeNormalizedCoords)) {
953 return MakeFromData(fFontData, fusedArgs);
954 }
955
956 // TODO(skbug.com/330149870): Palette differences are not fused, see DWrite backend impl.
957 rust::Slice<const fontations_ffi::PaletteOverride> argPaletteOverrides(
958 reinterpret_cast<const fontations_ffi::PaletteOverride*>(args.getPalette().overrides),
959 args.getPalette().overrideCount);
960 rust::Vec<uint32_t> newPalette =
961 resolve_palette(*fBridgeFontRef, args.getPalette().index, argPaletteOverrides);
962
963 if (fPalette.size() != newPalette.size() ||
964 memcmp(fPalette.data(), newPalette.data(), fPalette.size() * sizeof(fPalette[0]))) {
965 return MakeFromData(fFontData, fusedArgs);
966 }
967
968 return sk_ref_sp(this);
969 }
970
971 std::unique_ptr<SkScalerContext> SkTypeface_Fontations::onCreateScalerContext(
972 const SkScalerContextEffects& effects, const SkDescriptor* desc) const {
973 return this->onCreateScalerContextAsProxyTypeface(effects, desc, nullptr);
974 }
975
976 std::unique_ptr<SkScalerContext> SkTypeface_Fontations::onCreateScalerContextAsProxyTypeface(
977 const SkScalerContextEffects& effects,
978 const SkDescriptor* desc,
979 SkTypeface* proxyTypeface) const {
980 return std::make_unique<SkFontationsScalerContext>(
981 *this,
982 effects,
983 desc,
984 proxyTypeface ? *proxyTypeface : *const_cast<SkTypeface_Fontations*>(this));
985 }
986
987 std::unique_ptr<SkAdvancedTypefaceMetrics> SkTypeface_Fontations::onGetAdvancedMetrics() const {
988 std::unique_ptr<SkAdvancedTypefaceMetrics> info(new SkAdvancedTypefaceMetrics);
989
990 if (!fontations_ffi::is_embeddable(*fBridgeFontRef)) {
991 info->fFlags |= SkAdvancedTypefaceMetrics::kNotEmbeddable_FontFlag;
992 }
993
994 if (!fontations_ffi::is_subsettable(*fBridgeFontRef)) {
995 info->fFlags |= SkAdvancedTypefaceMetrics::kNotSubsettable_FontFlag;
996 }
997
998 if (fontations_ffi::table_data(
999 *fBridgeFontRef, SkSetFourByteTag('f', 'v', 'a', 'r'), 0, rust::Slice<uint8_t>())) {
1000 info->fFlags |= SkAdvancedTypefaceMetrics::kVariable_FontFlag;
1001 }
1002
1003 switch (fontations_ffi::outline_format(*fOutlines)) {
1004 case fontations_ffi::OutlineFormat::Glyf:
1005 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
1006 break;
1007 case fontations_ffi::OutlineFormat::Cff:
1008 info->fType = SkAdvancedTypefaceMetrics::kCFF_Font;
1009 break;
1010 default:
1011 // leave info->fType SkAdvancedTypefaceMetrics::kOther;
1012 break;
1013 }
1014
1015 // Metrics information.
1016 fontations_ffi::Metrics metrics =
1017 fontations_ffi::get_unscaled_metrics(*fBridgeFontRef, *fBridgeNormalizedCoords);
1018 info->fAscent = metrics.ascent;
1019 info->fDescent = metrics.descent;
1020 info->fCapHeight = metrics.cap_height;
1021
1022 info->fBBox = SkIRect::MakeLTRB((int32_t)metrics.x_min,
1023 (int32_t)metrics.top,
1024 (int32_t)metrics.x_max,
1025 (int32_t)metrics.bottom);
1026
1027 // Style information.
1028 if (fontations_ffi::is_fixed_pitch(*fBridgeFontRef)) {
1029 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
1030 }
1031
1032 fontations_ffi::BridgeFontStyle fontStyle;
1033 if (fontations_ffi::get_font_style(*fBridgeFontRef, *fBridgeNormalizedCoords, fontStyle)) {
1034 if (fontStyle.slant == SkFontStyle::Slant::kItalic_Slant) {
1035 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
1036 }
1037 }
1038
1039 if (fontations_ffi::is_serif_style(*fBridgeFontRef)) {
1040 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
1041 } else if (fontations_ffi::is_script_style(*fBridgeFontRef)) {
1042 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
1043 }
1044
1045 info->fItalicAngle = fontations_ffi::italic_angle(*fBridgeFontRef);
1046
1047 return info;
1048 }
1049
1050 void SkTypeface_Fontations::onGetFontDescriptor(SkFontDescriptor* desc, bool* serialize) const {
1051 SkString familyName;
1052 onGetFamilyName(&familyName);
1053 desc->setFamilyName(familyName.c_str());
1054 desc->setStyle(this->fontStyle());
1055 desc->setFactoryId(FactoryId);
1056
1057 // TODO: keep the index to emit here
1058 desc->setPaletteIndex(0);
1059 SkSpan<const SkColor> palette = getPalette();
1060 // TODO: omit override when palette[n] == CPAL[paletteIndex][n]
1061 size_t paletteOverrideCount = palette.size();
1062 auto overrides = desc->setPaletteEntryOverrides(paletteOverrideCount);
1063 for (size_t i = 0; i < paletteOverrideCount; ++i) {
1064 overrides[i] = {(uint16_t)i, palette[i]};
1065 }
1066
1067 *serialize = true;
1068 }
1069
1070 size_t SkTypeface_Fontations::onGetTableData(SkFontTableTag tag,
1071 size_t offset,
1072 size_t length,
1073 void* data) const {
1074 rust::Slice<uint8_t> dataSlice;
1075 if (data) {
1076 dataSlice = rust::Slice<uint8_t>(reinterpret_cast<uint8_t*>(data), length);
1077 }
1078 size_t copied = fontations_ffi::table_data(*fBridgeFontRef, tag, offset, dataSlice);
1079 // If data is nullptr, the Rust side doesn't see a length limit.
1080 return std::min(copied, length);
1081 }
1082
1083 int SkTypeface_Fontations::onGetTableTags(SkSpan<SkFontTableTag> tags) const {
1084 uint16_t numTables = fontations_ffi::table_tags(*fBridgeFontRef, rust::Slice<uint32_t>());
1085 if (tags.empty()) {
1086 return numTables;
1087 }
1088 const size_t n = std::min<size_t>(numTables, tags.size());
1089 return fontations_ffi::table_tags(*fBridgeFontRef, toSlice(tags.first(n)));
1090 }
1091
1092 int SkTypeface_Fontations::onGetVariationDesignPosition(
1093 SkSpan<SkFontArguments::VariationPosition::Coordinate> coordinates) const {
1094 rust::Slice<fontations_ffi::SkiaDesignCoordinate> copyToCoordinates;
1095 if (!coordinates.empty()) {
1096 copyToCoordinates = rust::Slice<fontations_ffi::SkiaDesignCoordinate>(
1097 reinterpret_cast<fontations_ffi::SkiaDesignCoordinate*>(coordinates.data()),
1098 coordinates.size());
1099 }
1100 return fontations_ffi::variation_position(*fBridgeNormalizedCoords, copyToCoordinates);
1101 }
1102
1103 int SkTypeface_Fontations::onGetVariationDesignParameters(
1104 SkSpan<SkFontParameters::Variation::Axis> parameters) const {
1105 sk_fontations::AxisWrapper axisWrapper(parameters.data(), parameters.size());
1106 return fontations_ffi::populate_axes(*fBridgeFontRef, axisWrapper);
1107 }
1108
1109 namespace sk_fontations {
1110
1111 namespace {
1112
1113 const uint16_t kForegroundColorPaletteIndex = 0xFFFF;
1114
1115 void populateStopsAndColors(std::vector<SkScalar>& dest_stops,
1116 std::vector<SkColor4f>& dest_colors,
1117 const SkSpan<const SkColor>& palette,
1118 SkColor foregroundColor,
1119 fontations_ffi::BridgeColorStops& color_stops) {
1120 SkASSERT(dest_stops.size() == 0);
1121 SkASSERT(dest_colors.size() == 0);
1122 size_t num_color_stops = fontations_ffi::num_color_stops(color_stops);
1123 dest_stops.reserve(num_color_stops);
1124 dest_colors.reserve(num_color_stops);
1125
1126 fontations_ffi::ColorStop color_stop;
1127 while (fontations_ffi::next_color_stop(color_stops, color_stop)) {
1128 dest_stops.push_back(color_stop.stop);
1129 SkColor4f dest_color;
1130 if (color_stop.palette_index == kForegroundColorPaletteIndex) {
1131 dest_color = SkColor4f::FromColor(foregroundColor);
1132 } else {
1133 dest_color = SkColor4f::FromColor(palette[color_stop.palette_index]);
1134 }
1135 dest_color.fA *= color_stop.alpha;
1136 dest_colors.push_back(dest_color);
1137 }
1138 }
1139
1140 SkColor4f lerpSkColor(SkColor4f c0, SkColor4f c1, float t) {
1141 // Due to the floating point calculation in the caller, when interpolating between very
1142 // narrow stops, we may get values outside the interpolation range, guard against these.
1143 if (t < 0) {
1144 return c0;
1145 }
1146 if (t > 1) {
1147 return c1;
1148 }
1149
1150 const auto c0_4f = skvx::float4::Load(c0.vec());
1151 const auto c1_4f = skvx::float4::Load(c1.vec());
1152 const auto c_4f = c0_4f + (c1_4f - c0_4f) * t;
1153
1154 SkColor4f l;
1155 c_4f.store(l.vec());
1156 return l;
1157 }
1158
1159 enum TruncateStops { TruncateStart, TruncateEnd };
1160
1161 // Truncate a vector of color stops at a previously computed stop position and insert at that
1162 // position the color interpolated between the surrounding stops.
1163 void truncateToStopInterpolating(SkScalar zeroRadiusStop,
1164 std::vector<SkColor4f>& colors,
1165 std::vector<SkScalar>& stops,
1166 TruncateStops truncateStops) {
1167 if (stops.size() <= 1u || zeroRadiusStop < stops.front() || stops.back() < zeroRadiusStop) {
1168 return;
1169 }
1170
1171 size_t afterIndex =
1172 (truncateStops == TruncateStart)
1173 ? std::lower_bound(stops.begin(), stops.end(), zeroRadiusStop) - stops.begin()
1174 : std::upper_bound(stops.begin(), stops.end(), zeroRadiusStop) - stops.begin();
1175
1176 const float t =
1177 (zeroRadiusStop - stops[afterIndex - 1]) / (stops[afterIndex] - stops[afterIndex - 1]);
1178 SkColor4f lerpColor = lerpSkColor(colors[afterIndex - 1], colors[afterIndex], t);
1179
1180 if (truncateStops == TruncateStart) {
1181 stops.erase(stops.begin(), stops.begin() + afterIndex);
1182 colors.erase(colors.begin(), colors.begin() + afterIndex);
1183 stops.insert(stops.begin(), 0);
1184 colors.insert(colors.begin(), lerpColor);
1185 } else {
1186 stops.erase(stops.begin() + afterIndex, stops.end());
1187 colors.erase(colors.begin() + afterIndex, colors.end());
1188 stops.insert(stops.end(), 1);
1189 colors.insert(colors.end(), lerpColor);
1190 }
1191 }
1192
1193 // https://learn.microsoft.com/en-us/typography/opentype/spec/colr#format-32-paintcomposite
1194 inline SkBlendMode ToSkBlendMode(uint16_t colrV1CompositeMode) {
1195 switch (colrV1CompositeMode) {
1196 case 0:
1197 return SkBlendMode::kClear;
1198 case 1:
1199 return SkBlendMode::kSrc;
1200 case 2:
1201 return SkBlendMode::kDst;
1202 case 3:
1203 return SkBlendMode::kSrcOver;
1204 case 4:
1205 return SkBlendMode::kDstOver;
1206 case 5:
1207 return SkBlendMode::kSrcIn;
1208 case 6:
1209 return SkBlendMode::kDstIn;
1210 case 7:
1211 return SkBlendMode::kSrcOut;
1212 case 8:
1213 return SkBlendMode::kDstOut;
1214 case 9:
1215 return SkBlendMode::kSrcATop;
1216 case 10:
1217 return SkBlendMode::kDstATop;
1218 case 11:
1219 return SkBlendMode::kXor;
1220 case 12:
1221 return SkBlendMode::kPlus;
1222 case 13:
1223 return SkBlendMode::kScreen;
1224 case 14:
1225 return SkBlendMode::kOverlay;
1226 case 15:
1227 return SkBlendMode::kDarken;
1228 case 16:
1229 return SkBlendMode::kLighten;
1230 case 17:
1231 return SkBlendMode::kColorDodge;
1232 case 18:
1233 return SkBlendMode::kColorBurn;
1234 case 19:
1235 return SkBlendMode::kHardLight;
1236 case 20:
1237 return SkBlendMode::kSoftLight;
1238 case 21:
1239 return SkBlendMode::kDifference;
1240 case 22:
1241 return SkBlendMode::kExclusion;
1242 case 23:
1243 return SkBlendMode::kMultiply;
1244 case 24:
1245 return SkBlendMode::kHue;
1246 case 25:
1247 return SkBlendMode::kSaturation;
1248 case 26:
1249 return SkBlendMode::kColor;
1250 case 27:
1251 return SkBlendMode::kLuminosity;
1252 default:
1253 return SkBlendMode::kDst;
1254 }
1255 }
1256
1257 inline SkTileMode ToSkTileMode(uint8_t extendMode) {
1258 switch (extendMode) {
1259 case 1:
1260 return SkTileMode::kRepeat;
1261 case 2:
1262 return SkTileMode::kMirror;
1263 default:
1264 return SkTileMode::kClamp;
1265 }
1266 }
1267 } // namespace
1268
1269 ColorPainter::ColorPainter(SkFontationsScalerContext& scaler_context,
1270 SkCanvas& canvas,
1271 SkSpan<const SkColor> palette,
1272 SkColor foregroundColor,
1273 bool antialias,
1274 uint16_t upem)
1275 : fScalerContext(scaler_context)
1276 , fCanvas(canvas)
1277 , fPalette(palette)
1278 , fForegroundColor(foregroundColor)
1279 , fAntialias(antialias)
1280 , fUpem(upem) {}
1281
1282 void ColorPainter::push_transform(const fontations_ffi::Transform& transform_arg) {
1283 fCanvas.save();
1284 fCanvas.concat(SkMatrixFromFontationsTransform(transform_arg));
1285 }
1286
1287 void ColorPainter::pop_transform() { fCanvas.restore(); }
1288
1289 void ColorPainter::push_clip_glyph(uint16_t glyph_id) {
1290 fCanvas.save();
1291 fontations_ffi::BridgeScalerMetrics scalerMetrics;
1292 auto path = fScalerContext.generatePathForGlyphId(glyph_id, fUpem,
1293 *fontations_ffi::no_hinting_instance(),
1294 scalerMetrics);
1295 fCanvas.clipPath(path.has_value() ? *path : SkPath(), fAntialias);
1296 }
1297
1298 void ColorPainter::push_clip_rectangle(float x_min, float y_min, float x_max, float y_max) {
1299 fCanvas.save();
1300 SkRect clipRect = SkRect::MakeLTRB(x_min, -y_min, x_max, -y_max);
1301 fCanvas.clipRect(clipRect, fAntialias);
1302 }
1303
1304 void ColorPainter::pop_clip() { fCanvas.restore(); }
1305
1306 void ColorPainter::configure_solid_paint(uint16_t palette_index, float alpha, SkPaint& paint) {
1307 paint.setAntiAlias(fAntialias);
1308 SkColor4f color;
1309 if (palette_index == kForegroundColorPaletteIndex) {
1310 color = SkColor4f::FromColor(fForegroundColor);
1311 } else {
1312 color = SkColor4f::FromColor(fPalette[palette_index]);
1313 }
1314 color.fA *= alpha;
1315 paint.setShader(nullptr);
1316 paint.setColor(color);
1317 }
1318
1319 void ColorPainter::fill_solid(uint16_t palette_index, float alpha) {
1320 SkPaint paint;
1321 configure_solid_paint(palette_index, alpha, paint);
1322 fCanvas.drawPaint(paint);
1323 }
1324
1325 void ColorPainter::fill_glyph_solid(uint16_t glyph_id, uint16_t palette_index, float alpha) {
1326 fontations_ffi::BridgeScalerMetrics scalerMetrics;
1327 if (auto path = fScalerContext.generatePathForGlyphId(glyph_id, fUpem,
1328 *fontations_ffi::no_hinting_instance(),
1329 scalerMetrics)) {
1330 SkPaint paint;
1331 configure_solid_paint(palette_index, alpha, paint);
1332 fCanvas.drawPath(*path, paint);
1333 }
1334 }
1335
1336 void ColorPainter::configure_linear_paint(const fontations_ffi::FillLinearParams& linear_params,
1337 fontations_ffi::BridgeColorStops& bridge_stops,
1338 uint8_t extend_mode,
1339 SkPaint& paint,
1340 SkMatrix* paintTransform) {
1341 paint.setAntiAlias(fAntialias);
1342
1343 std::vector<SkScalar> stops;
1344 std::vector<SkColor4f> colors;
1345
1346 populateStopsAndColors(stops, colors, fPalette, fForegroundColor, bridge_stops);
1347
1348 if (stops.size() == 1) {
1349 paint.setColor(colors[0]);
1350 return;
1351 }
1352
1353 SkPoint linePositions[2] = {
1354 SkPoint::Make(SkFloatToScalar(linear_params.x0), -SkFloatToScalar(linear_params.y0)),
1355 SkPoint::Make(SkFloatToScalar(linear_params.x1), -SkFloatToScalar(linear_params.y1))};
1356 SkTileMode tileMode = ToSkTileMode(extend_mode);
1357
1358 sk_sp<SkShader> shader(SkShaders::LinearGradient(
1359 linePositions,
1360 {{colors, stops, tileMode},
1361 SkGradient::Interpolation{SkGradient::Interpolation::InPremul::kNo,
1362 SkGradient::Interpolation::ColorSpace::kSRGB,
1363 SkGradient::Interpolation::HueMethod::kShorter}},
1364 paintTransform));
1365
1366 SkASSERT(shader);
1367 // An opaque color is needed to ensure the gradient is not modulated by alpha.
1368 paint.setColor(SK_ColorBLACK);
1369 paint.setShader(shader);
1370 }
1371
1372 void ColorPainter::fill_linear(const fontations_ffi::FillLinearParams& linear_params,
1373 fontations_ffi::BridgeColorStops& bridge_stops,
1374 uint8_t extend_mode) {
1375 SkPaint paint;
1376
1377 configure_linear_paint(linear_params, bridge_stops, extend_mode, paint);
1378
1379 fCanvas.drawPaint(paint);
1380 }
1381
1382 void ColorPainter::fill_glyph_linear(uint16_t glyph_id,
1383 const fontations_ffi::Transform& transform,
1384 const fontations_ffi::FillLinearParams& linear_params,
1385 fontations_ffi::BridgeColorStops& bridge_stops,
1386 uint8_t extend_mode) {
1387 fontations_ffi::BridgeScalerMetrics scalerMetrics;
1388 if (auto path = fScalerContext.generatePathForGlyphId(glyph_id, fUpem,
1389 *fontations_ffi::no_hinting_instance(),
1390 scalerMetrics)) {
1391 SkPaint paint;
1392 SkMatrix paintTransform = SkMatrixFromFontationsTransform(transform);
1393 configure_linear_paint(linear_params, bridge_stops, extend_mode, paint, &paintTransform);
1394 fCanvas.drawPath(*path, paint);
1395 }
1396 }
1397
1398 void ColorPainter::configure_radial_paint(
1399 const fontations_ffi::FillRadialParams& fill_radial_params,
1400 fontations_ffi::BridgeColorStops& bridge_stops,
1401 uint8_t extend_mode,
1402 SkPaint& paint,
1403 SkMatrix* paintTransform) {
1404 paint.setAntiAlias(fAntialias);
1405
1406 SkPoint start = SkPoint::Make(fill_radial_params.x0, -fill_radial_params.y0);
1407 SkPoint end = SkPoint::Make(fill_radial_params.x1, -fill_radial_params.y1);
1408
1409 float startRadius = fill_radial_params.r0;
1410 float endRadius = fill_radial_params.r1;
1411
1412 std::vector<SkScalar> stops;
1413 std::vector<SkColor4f> colors;
1414
1415 populateStopsAndColors(stops, colors, fPalette, fForegroundColor, bridge_stops);
1416
1417 // Draw single color if there's only one stop.
1418 if (stops.size() == 1) {
1419 paint.setColor(colors[0]);
1420 fCanvas.drawPaint(paint);
1421 return;
1422 }
1423
1424 SkTileMode tileMode = ToSkTileMode(extend_mode);
1425
1426 // For negative radii, interpolation is needed to prepare parameters suitable
1427 // for invoking the shader. Implementation below as resolution discussed in
1428 // https://github.com/googlefonts/colr-gradients-spec/issues/367.
1429 // Truncate to manually interpolated color for tile mode clamp, otherwise
1430 // calculate positive projected circles.
1431 if (startRadius < 0 || endRadius < 0) {
1432 if (startRadius == endRadius && startRadius < 0) {
1433 paint.setColor(SK_ColorTRANSPARENT);
1434 // return true;
1435 return;
1436 }
1437
1438 if (tileMode == SkTileMode::kClamp) {
1439 SkVector startToEnd = end - start;
1440 SkScalar radiusDiff = endRadius - startRadius;
1441 SkScalar zeroRadiusStop = 0.f;
1442 TruncateStops truncateSide = TruncateStart;
1443 if (startRadius < 0) {
1444 truncateSide = TruncateStart;
1445
1446 // Compute color stop position where radius is = 0. After the scaling
1447 // of stop positions to the normal 0,1 range that we have done above,
1448 // the size of the radius as a function of the color stops is: r(x) = r0
1449 // + x*(r1-r0) Solving this function for r(x) = 0, we get: x = -r0 /
1450 // (r1-r0)
1451 zeroRadiusStop = -startRadius / (endRadius - startRadius);
1452 startRadius = 0.f;
1453 SkVector startEndDiff = end - start;
1454 startEndDiff.scale(zeroRadiusStop);
1455 start = start + startEndDiff;
1456 }
1457
1458 if (endRadius < 0) {
1459 truncateSide = TruncateEnd;
1460 zeroRadiusStop = -startRadius / (endRadius - startRadius);
1461 endRadius = 0.f;
1462 SkVector startEndDiff = end - start;
1463 startEndDiff.scale(1 - zeroRadiusStop);
1464 end = end - startEndDiff;
1465 }
1466
1467 if (!(startRadius == 0 && endRadius == 0)) {
1468 truncateToStopInterpolating(zeroRadiusStop, colors, stops, truncateSide);
1469 } else {
1470 // If both radii have become negative and where clamped to 0, we need to
1471 // produce a single color cone, otherwise the shader colors the whole
1472 // plane in a single color when two radii are specified as 0.
1473 if (radiusDiff > 0) {
1474 end = start + startToEnd;
1475 endRadius = radiusDiff;
1476 colors.erase(colors.begin(), colors.end() - 1);
1477 stops.erase(stops.begin(), stops.end() - 1);
1478 } else {
1479 start -= startToEnd;
1480 startRadius = -radiusDiff;
1481 colors.erase(colors.begin() + 1, colors.end());
1482 stops.erase(stops.begin() + 1, stops.end());
1483 }
1484 }
1485 } else {
1486 if (startRadius < 0 || endRadius < 0) {
1487 auto roundIntegerMultiple = [](SkScalar factorZeroCrossing, SkTileMode tileMode) {
1488 int roundedMultiple = factorZeroCrossing > 0 ? ceilf(factorZeroCrossing)
1489 : floorf(factorZeroCrossing) - 1;
1490 if (tileMode == SkTileMode::kMirror && roundedMultiple % 2 != 0) {
1491 roundedMultiple += roundedMultiple < 0 ? -1 : 1;
1492 }
1493 return roundedMultiple;
1494 };
1495
1496 SkVector startToEnd = end - start;
1497 SkScalar radiusDiff = endRadius - startRadius;
1498 SkScalar factorZeroCrossing = (startRadius / (startRadius - endRadius));
1499 bool inRange = 0.f <= factorZeroCrossing && factorZeroCrossing <= 1.0f;
1500 SkScalar direction = inRange && radiusDiff < 0 ? -1.0f : 1.0f;
1501 SkScalar circleProjectionFactor =
1502 roundIntegerMultiple(factorZeroCrossing * direction, tileMode);
1503 startToEnd.scale(circleProjectionFactor);
1504 startRadius += circleProjectionFactor * radiusDiff;
1505 endRadius += circleProjectionFactor * radiusDiff;
1506 start += startToEnd;
1507 end += startToEnd;
1508 }
1509 }
1510 }
1511
1512 // An opaque color is needed to ensure the gradient is not modulated by alpha.
1513 paint.setColor(SK_ColorBLACK);
1514
1515 paint.setShader(SkShaders::TwoPointConicalGradient(
1516 start, startRadius, end, endRadius,
1517 {{colors, stops, tileMode},
1518 SkGradient::Interpolation{SkGradient::Interpolation::InPremul::kNo,
1519 SkGradient::Interpolation::ColorSpace::kSRGB,
1520 SkGradient::Interpolation::HueMethod::kShorter}},
1521 paintTransform));
1522 }
1523
1524 void ColorPainter::fill_radial(const fontations_ffi::FillRadialParams& fill_radial_params,
1525 fontations_ffi::BridgeColorStops& bridge_stops,
1526 uint8_t extend_mode) {
1527 SkPaint paint;
1528
1529 configure_radial_paint(fill_radial_params, bridge_stops, extend_mode, paint);
1530
1531 fCanvas.drawPaint(paint);
1532 }
1533
1534 void ColorPainter::fill_glyph_radial(uint16_t glyph_id,
1535 const fontations_ffi::Transform& transform,
1536 const fontations_ffi::FillRadialParams& fill_radial_params,
1537 fontations_ffi::BridgeColorStops& bridge_stops,
1538 uint8_t extend_mode) {
1539 fontations_ffi::BridgeScalerMetrics scalerMetrics;
1540 if (auto path = fScalerContext.generatePathForGlyphId(glyph_id, fUpem,
1541 *fontations_ffi::no_hinting_instance(),
1542 scalerMetrics)) {
1543 SkPaint paint;
1544 SkMatrix paintTransform = SkMatrixFromFontationsTransform(transform);
1545 configure_radial_paint(fill_radial_params, bridge_stops, extend_mode, paint, &paintTransform);
1546 fCanvas.drawPath(*path, paint);
1547 }
1548 }
1549
1550 void ColorPainter::configure_sweep_paint(const fontations_ffi::FillSweepParams& sweep_params,
1551 fontations_ffi::BridgeColorStops& bridge_stops,
1552 uint8_t extend_mode,
1553 SkPaint& paint,
1554 SkMatrix* paintTransform) {
1555 paint.setAntiAlias(fAntialias);
1556
1557 SkPoint center = SkPoint::Make(sweep_params.x0, -sweep_params.y0);
1558
1559 std::vector<SkScalar> stops;
1560 std::vector<SkColor4f> colors;
1561
1562 populateStopsAndColors(stops, colors, fPalette, fForegroundColor, bridge_stops);
1563
1564 if (stops.size() == 1) {
1565 paint.setColor(colors[0]);
1566 fCanvas.drawPaint(paint);
1567 return;
1568 }
1569
1570 // An opaque color is needed to ensure the gradient is not modulated by alpha.
1571 paint.setColor(SK_ColorBLACK);
1572 SkTileMode tileMode = ToSkTileMode(extend_mode);
1573
1574 paint.setColor(SK_ColorBLACK);
1575 paint.setShader(SkShaders::SweepGradient(
1576 center, sweep_params.start_angle, sweep_params.end_angle,
1577 {{colors, stops, tileMode},
1578 SkGradient::Interpolation{SkGradient::Interpolation::InPremul::kNo,
1579 SkGradient::Interpolation::ColorSpace::kSRGB,
1580 SkGradient::Interpolation::HueMethod::kShorter}},
1581 paintTransform));
1582 }
1583
1584 void ColorPainter::fill_sweep(const fontations_ffi::FillSweepParams& sweep_params,
1585 fontations_ffi::BridgeColorStops& bridge_stops,
1586 uint8_t extend_mode) {
1587 SkPaint paint;
1588
1589 configure_sweep_paint(sweep_params, bridge_stops, extend_mode, paint);
1590
1591 fCanvas.drawPaint(paint);
1592 }
1593
1594 void ColorPainter::fill_glyph_sweep(uint16_t glyph_id,
1595 const fontations_ffi::Transform& transform,
1596 const fontations_ffi::FillSweepParams& sweep_params,
1597 fontations_ffi::BridgeColorStops& bridge_stops,
1598 uint8_t extend_mode) {
1599 fontations_ffi::BridgeScalerMetrics scalerMetrics;
1600 if (auto path = fScalerContext.generatePathForGlyphId(glyph_id, fUpem,
1601 *fontations_ffi::no_hinting_instance(),
1602 scalerMetrics)) {
1603 SkPaint paint;
1604 SkMatrix paintTransform = SkMatrixFromFontationsTransform(transform);
1605 configure_sweep_paint(sweep_params, bridge_stops, extend_mode, paint, &paintTransform);
1606 fCanvas.drawPath(*path, paint);
1607 }
1608 }
1609
1610 void ColorPainter::push_layer(uint8_t compositeMode) {
1611 SkPaint paint;
1612 paint.setBlendMode(ToSkBlendMode(compositeMode));
1613 fCanvas.saveLayer(nullptr, &paint);
1614 }
1615
1616 void ColorPainter::pop_layer() { fCanvas.restore(); }
1617
1618 BoundsPainter::BoundsPainter(SkFontationsScalerContext& scaler_context,
1619 SkMatrix initialTransfom,
1620 uint16_t upem)
1621 : fScalerContext(scaler_context)
1622 , fMatrixStack({initialTransfom})
1623 , fUpem(upem)
1624 , fBounds(SkRect::MakeEmpty()) {}
1625
1626 SkRect BoundsPainter::getBoundingBox() { return fBounds; }
1627
1628 // fontations_ffi::ColorPainter interface.
1629 void BoundsPainter::push_transform(const fontations_ffi::Transform& transform_arg) {
1630 SkMatrix newTop(fMatrixStack.back());
1631 newTop.preConcat(SkMatrixFromFontationsTransform(transform_arg));
1632 fMatrixStack.push_back(newTop);
1633 }
1634 void BoundsPainter::pop_transform() {
1635 fMatrixStack.pop_back();
1636 }
1637
1638 void BoundsPainter::push_clip_glyph(uint16_t glyph_id) {
1639 fontations_ffi::BridgeScalerMetrics scalerMetrics;
1640 if (auto path = fScalerContext.generatePathForGlyphId(glyph_id, fUpem,
1641 *fontations_ffi::no_hinting_instance(),
1642 scalerMetrics)) {
1643 if (auto newpath = path->tryMakeTransform(fMatrixStack.back())) {
1644 fBounds.join(newpath->getBounds());
1645 }
1646 }
1647 }
1648
1649 void BoundsPainter::push_clip_rectangle(float x_min, float y_min, float x_max, float y_max) {
1650 const SkRect clipRect = SkRect::MakeLTRB(x_min, -y_min, x_max, -y_max);
1651 fBounds.join(fMatrixStack.back().mapRect(clipRect));
1652 }
1653
1654 void BoundsPainter::fill_glyph_solid(uint16_t glyph_id, uint16_t, float) {
1655 push_clip_glyph(glyph_id);
1656 pop_clip();
1657 }
1658
1659 void BoundsPainter::fill_glyph_radial(uint16_t glyph_id,
1660 const fontations_ffi::Transform&,
1661 const fontations_ffi::FillRadialParams&,
1662 fontations_ffi::BridgeColorStops&,
1663 uint8_t) {
1664 push_clip_glyph(glyph_id);
1665 pop_clip();
1666 }
1667 void BoundsPainter::fill_glyph_linear(uint16_t glyph_id,
1668 const fontations_ffi::Transform&,
1669 const fontations_ffi::FillLinearParams&,
1670 fontations_ffi::BridgeColorStops&,
1671 uint8_t) {
1672 push_clip_glyph(glyph_id);
1673 pop_clip();
1674 }
1675
1676 void BoundsPainter::fill_glyph_sweep(uint16_t glyph_id,
1677 const fontations_ffi::Transform&,
1678 const fontations_ffi::FillSweepParams&,
1679 fontations_ffi::BridgeColorStops&,
1680 uint8_t) {
1681 push_clip_glyph(glyph_id);
1682 pop_clip();
1683 }
1684
1685 } // namespace sk_fontations