Debian Codegraph @

src/ports/SkTypeface_win_dw.cpp

raw
1 /*
2 * Copyright 2014 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 "src/utils/win/SkDWriteNTDDI_VERSION.h"
8
9 #include "include/core/SkTypes.h"
10 #if defined(SK_BUILD_FOR_WIN)
11
12 #include "src/base/SkLeanWindows.h"
13
14 // SkLeanWindows will include Windows.h, which will pull in all of the GDI defines.
15 // GDI #defines GetGlyphIndices to GetGlyphIndicesA or GetGlyphIndicesW, but
16 // IDWriteFontFace has a method called GetGlyphIndices. Since this file does
17 // not use GDI, undefing GetGlyphIndices makes things less confusing.
18 #undef GetGlyphIndices
19
20 #include "include/core/SkData.h"
21 #include "include/core/SkFontTypes.h"
22 #include "include/private/base/SkTo.h"
23 #include "src/core/SkFontDescriptor.h"
24 #include "src/core/SkFontStream.h"
25 #include "src/core/SkScalerContext.h"
26 #include "src/ports/SkScalerContext_win_dw.h"
27 #include "src/ports/SkTypeface_win_dw.h"
28 #include "src/sfnt/SkOTTable_OS_2.h"
29 #include "src/sfnt/SkOTTable_fvar.h"
30 #include "src/sfnt/SkOTTable_head.h"
31 #include "src/sfnt/SkOTTable_hhea.h"
32 #include "src/sfnt/SkOTTable_post.h"
33 #include "src/sfnt/SkOTUtils.h"
34 #include "src/utils/win/SkDWrite.h"
35 #include "src/utils/win/SkDWriteFontFileStream.h"
36
37 using namespace skia_private;
38
39 SkFontStyle DWriteFontTypeface::GetStyle(IDWriteFont* font, IDWriteFontFace* fontFace) {
40 int weight = font->GetWeight();
41 int width = font->GetStretch();
42 SkFontStyle::Slant slant = SkFontStyle::kUpright_Slant;
43 switch (font->GetStyle()) {
44 case DWRITE_FONT_STYLE_NORMAL: slant = SkFontStyle::kUpright_Slant; break;
45 case DWRITE_FONT_STYLE_OBLIQUE: slant = SkFontStyle::kOblique_Slant; break;
46 case DWRITE_FONT_STYLE_ITALIC: slant = SkFontStyle::kItalic_Slant; break;
47 default: SkASSERT(false); break;
48 }
49
50 [&weight, &width, &slant, fontFace]() -> void {
51 SkTScopedComPtr<IDWriteFontFace5> fontFace5;
52 if (FAILED(fontFace->QueryInterface(&fontFace5))) {
53 return;
54 }
55 if (!fontFace5->HasVariations()) {
56 return;
57 }
58
59 UINT32 fontAxisCount = fontFace5->GetFontAxisValueCount();
60 SkTScopedComPtr<IDWriteFontResource> fontResource;
61 HRV(fontFace5->GetFontResource(&fontResource));
62
63 AutoSTMalloc<8, DWRITE_FONT_AXIS_VALUE> fontAxisValue(fontAxisCount);
64 HRV(fontFace5->GetFontAxisValues(fontAxisValue.get(), fontAxisCount));
65 for (UINT32 axisIndex = 0; axisIndex < fontAxisCount; ++axisIndex) {
66 if (fontAxisValue[axisIndex].axisTag == DWRITE_FONT_AXIS_TAG_WEIGHT) {
67 weight = fontAxisValue[axisIndex].value;
68 }
69 if (fontAxisValue[axisIndex].axisTag == DWRITE_FONT_AXIS_TAG_WIDTH) {
70 SkScalar wdthValue = fontAxisValue[axisIndex].value;
71 width = SkFontDescriptor::SkFontStyleWidthForWidthAxisValue(wdthValue);
72 }
73 if (fontAxisValue[axisIndex].axisTag == DWRITE_FONT_AXIS_TAG_SLANT &&
74 slant != SkFontStyle::kItalic_Slant)
75 {
76 if (fontAxisValue[axisIndex].value == 0) {
77 slant = SkFontStyle::kUpright_Slant;
78 } else {
79 slant = SkFontStyle::kOblique_Slant;
80 }
81 }
82 }
83 }();
84 return SkFontStyle(weight, width, slant);
85 }
86
87 sk_sp<DWriteFontTypeface> DWriteFontTypeface::Make(
88 IDWriteFactory* factory,
89 IDWriteFontFace* fontFace,
90 IDWriteFont* font,
91 IDWriteFontFamily* fontFamily,
92 sk_sp<Loaders> loaders,
93 const SkFontArguments::Palette& palette)
94 {
95 return sk_sp<DWriteFontTypeface>(new DWriteFontTypeface(
96 GetStyle(font, fontFace), factory, fontFace, font, fontFamily, std::move(loaders), palette));
97 }
98
99 HRESULT DWriteFontTypeface::initializePalette() {
100 if (!fIsColorFont) {
101 return S_OK;
102 }
103
104 UINT32 dwPaletteCount = fDWriteFontFace2->GetColorPaletteCount();
105 if (dwPaletteCount == 0) {
106 return S_OK;
107 }
108
109 // Treat out of range palette index values as 0. Still apply overrides.
110 // https://www.w3.org/TR/css-fonts-4/#base-palette-desc
111 UINT32 basePaletteIndex = 0;
112 if (SkTFitsIn<UINT32>(fRequestedPalette.index) &&
113 SkTo<UINT32>(fRequestedPalette.index) < dwPaletteCount)
114 {
115 basePaletteIndex = fRequestedPalette.index;
116 }
117
118 UINT32 dwPaletteEntryCount = fDWriteFontFace2->GetPaletteEntryCount();
119 AutoSTMalloc<8, DWRITE_COLOR_F> dwPaletteEntry(dwPaletteEntryCount);
120 HRM(fDWriteFontFace2->GetPaletteEntries(basePaletteIndex,
121 0, dwPaletteEntryCount,
122 dwPaletteEntry),
123 "Could not retrieve palette entries.");
124
125 fPalette.reset(new SkColor[dwPaletteEntryCount]);
126 fDWPalette.reset(new DWRITE_COLOR_F[dwPaletteEntryCount]);
127 for (UINT32 i = 0; i < dwPaletteEntryCount; ++i) {
128 fPalette[i] = SkColorSetARGB(sk_float_round2int(dwPaletteEntry[i].a * 255),
129 sk_float_round2int(dwPaletteEntry[i].r * 255),
130 sk_float_round2int(dwPaletteEntry[i].g * 255),
131 sk_float_round2int(dwPaletteEntry[i].b * 255));
132 fDWPalette[i] = dwPaletteEntry[i];
133 }
134
135 for (int i = 0; i < fRequestedPalette.overrideCount; ++i) {
136 const SkFontArguments::Palette::Override& paletteOverride = fRequestedPalette.overrides[i];
137 if (SkTFitsIn<UINT32>(paletteOverride.index) &&
138 SkTo<UINT32>(paletteOverride.index) < dwPaletteEntryCount)
139 {
140 fPalette[paletteOverride.index] = paletteOverride.color;
141
142 // Avoid brace initialization as DWRITE_COLOR_F can be defined as four floats
143 // (dxgitype.h, d3d9types.h) or four unions of two floats (dwrite_2.h, d3dtypes.h).
144 // The type changed in Direct3D 10, but the change does not appear to be documented.
145 const SkColor4f skColor = SkColor4f::FromColor(paletteOverride.color);
146 DWRITE_COLOR_F& dwColor = fDWPalette[paletteOverride.index];
147 dwColor.r = skColor.fR;
148 dwColor.g = skColor.fG;
149 dwColor.b = skColor.fB;
150 dwColor.a = skColor.fA;
151 }
152 }
153 fPaletteEntryCount = dwPaletteEntryCount;
154
155 return S_OK;
156 }
157
158 DWriteFontTypeface::DWriteFontTypeface(const SkFontStyle& style,
159 IDWriteFactory* factory,
160 IDWriteFontFace* fontFace,
161 IDWriteFont* font,
162 IDWriteFontFamily* fontFamily,
163 sk_sp<Loaders> loaders,
164 const SkFontArguments::Palette& palette)
165 : SkTypeface(style, false)
166 , fFactory(SkRefComPtr(factory))
167 , fDWriteFontFamily(SkRefComPtr(fontFamily))
168 , fDWriteFont(SkRefComPtr(font))
169 , fDWriteFontFace(SkRefComPtr(fontFace))
170 , fRequestedPaletteEntryOverrides(palette.overrideCount
171 ? (SkFontArguments::Palette::Override*)memcpy(
172 new SkFontArguments::Palette::Override[palette.overrideCount],
173 palette.overrides,
174 palette.overrideCount * sizeof(palette.overrides[0]))
175 : nullptr)
176 , fRequestedPalette{palette.index,
177 fRequestedPaletteEntryOverrides.get(), palette.overrideCount }
178 , fPaletteEntryCount(0)
179 , fLoaders(std::move(loaders))
180 {
181 if (!SUCCEEDED(fDWriteFontFace->QueryInterface(&fDWriteFontFace1))) {
182 // IUnknown::QueryInterface states that if it fails, punk will be set to nullptr.
183 // http://blogs.msdn.com/b/oldnewthing/archive/2004/03/26/96777.aspx
184 SkASSERT_RELEASE(nullptr == fDWriteFontFace1.get());
185 }
186 if (!SUCCEEDED(fDWriteFontFace->QueryInterface(&fDWriteFontFace2))) {
187 SkASSERT_RELEASE(nullptr == fDWriteFontFace2.get());
188 }
189 if (!SUCCEEDED(fDWriteFontFace->QueryInterface(&fDWriteFontFace3))) {
190 SkASSERT_RELEASE(nullptr == fDWriteFontFace3.get());
191 }
192 if (!SUCCEEDED(fDWriteFontFace->QueryInterface(&fDWriteFontFace4))) {
193 SkASSERT_RELEASE(nullptr == fDWriteFontFace4.get());
194 }
195 if (!SUCCEEDED(fDWriteFontFace->QueryInterface(&fDWriteFontFace5))) {
196 SkASSERT_RELEASE(nullptr == fDWriteFontFace5.get());
197 }
198 #if DWRITE_CORE || (defined(NTDDI_WIN11_ZN) && NTDDI_VERSION >= NTDDI_WIN11_ZN)
199 if (!SUCCEEDED(fDWriteFontFace->QueryInterface(&fDWriteFontFace7))) {
200 SkASSERT_RELEASE(nullptr == fDWriteFontFace7/*.get()*/);
201 }
202 #endif
203 if (!SUCCEEDED(fFactory->QueryInterface(&fFactory2))) {
204 SkASSERT_RELEASE(nullptr == fFactory2.get());
205 }
206
207 if (fDWriteFontFace1 && fDWriteFontFace1->IsMonospacedFont()) {
208 this->setIsFixedPitch(true);
209 }
210
211 fIsColorFont = fFactory2 && fDWriteFontFace2 && fDWriteFontFace2->IsColorFont();
212 this->initializePalette();
213 }
214
215 DWriteFontTypeface::~DWriteFontTypeface() {
216 #if DWRITE_CORE || (defined(NTDDI_WIN11_ZN) && NTDDI_VERSION >= NTDDI_WIN11_ZN)
217 if (fDWriteFontFace7) {
218 fDWriteFontFace7->Release();
219 }
220 #endif
221 }
222
223 DWriteFontTypeface::Loaders::~Loaders() {
224 // Don't return if any fail, just keep going to free up as much as possible.
225 HRESULT hr;
226
227 hr = fFactory->UnregisterFontCollectionLoader(fDWriteFontCollectionLoader.get());
228 if (FAILED(hr)) {
229 SK_TRACEHR(hr, "FontCollectionLoader");
230 }
231
232 hr = fFactory->UnregisterFontFileLoader(fDWriteFontFileLoader.get());
233 if (FAILED(hr)) {
234 SK_TRACEHR(hr, "FontFileLoader");
235 }
236 }
237
238 void DWriteFontTypeface::onGetFamilyName(SkString* familyName) const {
239 SkTScopedComPtr<IDWriteLocalizedStrings> familyNames;
240 if (fDWriteFontFace3) {
241 HRV(fDWriteFontFace3->GetFamilyNames(&familyNames));
242 } else {
243 HRV(fDWriteFontFamily->GetFamilyNames(&familyNames));
244 }
245
246 sk_get_locale_string(familyNames.get(), nullptr/*fMgr->fLocaleName.get()*/, familyName);
247 }
248
249 bool DWriteFontTypeface::onGetPostScriptName(SkString* skPostScriptName) const {
250 SkString localSkPostScriptName;
251 SkTScopedComPtr<IDWriteLocalizedStrings> postScriptNames;
252 BOOL exists = FALSE;
253 // Prefer to retrieve information directly from the face when available
254 if (fDWriteFontFace3) {
255 if (FAILED(fDWriteFontFace3->GetInformationalStrings(
256 DWRITE_INFORMATIONAL_STRING_POSTSCRIPT_NAME,
257 &postScriptNames,
258 &exists)) ||
259 !exists ||
260 FAILED(sk_get_locale_string(postScriptNames.get(), nullptr, &localSkPostScriptName)))
261 {
262 return false;
263 }
264 } else {
265 if (FAILED(fDWriteFont->GetInformationalStrings(
266 DWRITE_INFORMATIONAL_STRING_POSTSCRIPT_NAME,
267 &postScriptNames,
268 &exists)) ||
269 !exists ||
270 FAILED(sk_get_locale_string(postScriptNames.get(), nullptr, &localSkPostScriptName)))
271 {
272 return false;
273 }
274 }
275 if (skPostScriptName) {
276 *skPostScriptName = localSkPostScriptName;
277 }
278 return true;
279 }
280
281 int DWriteFontTypeface::onGetResourceName(SkString* resourceName) const {
282 UINT32 numFiles = 0;
283 HRZM(fDWriteFontFace->GetFiles(&numFiles, nullptr),
284 "Could not get number of font files.");
285 if (numFiles < 1 || !resourceName) {
286 return numFiles;
287 }
288
289 auto fontFiles = std::make_unique<SkTScopedComPtr<IDWriteFontFile>[]>(numFiles);
290 HR_GENERAL(fDWriteFontFace->GetFiles(&numFiles, &fontFiles[0]),
291 "Could not get font files.", numFiles);
292
293 IDWriteFontFile* fontFile = fontFiles[0].get();
294 const void* fontFileKey;
295 UINT32 fontFileKeySize;
296 HR_GENERAL(fontFile->GetReferenceKey(&fontFileKey, &fontFileKeySize),
297 "Could not get font file reference key.", numFiles);
298
299 SkTScopedComPtr<IDWriteFontFileLoader> fontFileLoader;
300 HR_GENERAL(fontFile->GetLoader(&fontFileLoader),
301 "Could not get font file loader.", numFiles);
302
303 SkTScopedComPtr<IDWriteLocalFontFileLoader> localFontFileLoader;
304 HR_GENERAL(fontFileLoader->QueryInterface(&localFontFileLoader),
305 nullptr, numFiles);
306
307 UINT32 fontFilePathLen;
308 HR_GENERAL(localFontFileLoader->GetFilePathLengthFromKey(fontFileKey, fontFileKeySize,
309 &fontFilePathLen),
310 "Could not get file path length.", numFiles);
311
312 SkSMallocWCHAR fontFilePath(static_cast<size_t>(fontFilePathLen)+1);
313 HR_GENERAL(localFontFileLoader->GetFilePathFromKey(fontFileKey, fontFileKeySize,
314 fontFilePath, fontFilePathLen+1),
315 "Could not get file path.", numFiles);
316
317 SkString localResourceName;
318 HR_GENERAL(sk_wchar_to_skstring(fontFilePath.get(), fontFilePathLen, &localResourceName),
319 nullptr, numFiles);
320 *resourceName = std::move(localResourceName);
321
322 return numFiles;
323 }
324
325 void DWriteFontTypeface::onGetFontDescriptor(SkFontDescriptor* desc,
326 bool* serialize) const {
327 // Get the family name.
328 SkTScopedComPtr<IDWriteLocalizedStrings> familyNames;
329 if (fDWriteFontFace3) {
330 HRV(fDWriteFontFace3->GetFamilyNames(&familyNames));
331 } else {
332 HRV(fDWriteFontFamily->GetFamilyNames(&familyNames));
333 }
334
335 SkString utf8FamilyName;
336 sk_get_locale_string(familyNames.get(), nullptr/*fMgr->fLocaleName.get()*/, &utf8FamilyName);
337
338 desc->setFamilyName(utf8FamilyName.c_str());
339 desc->setStyle(this->fontStyle());
340
341 desc->setPaletteIndex(fRequestedPalette.index);
342 sk_careful_memcpy(desc->setPaletteEntryOverrides(fRequestedPalette.overrideCount),
343 fRequestedPalette.overrides,
344 fRequestedPalette.overrideCount * sizeof(fRequestedPalette.overrides[0]));
345
346 desc->setSyntheticBold(this->isSyntheticBold());
347 desc->setSyntheticOblique(this->isSyntheticOblique());
348
349 desc->setFactoryId(FactoryId);
350 *serialize = SkToBool(fLoaders);
351 }
352
353 void DWriteFontTypeface::onCharsToGlyphs(SkSpan<const SkUnichar> uni,
354 SkSpan<SkGlyphID> glyphs) const {
355 SkASSERT(uni.size() == glyphs.size());
356 fDWriteFontFace->GetGlyphIndices((const UINT32*)uni.data(), uni.size(), glyphs.data());
357 }
358
359 int DWriteFontTypeface::onCountGlyphs() const {
360 return fDWriteFontFace->GetGlyphCount();
361 }
362
363 void DWriteFontTypeface::getPostScriptGlyphNames(SkString*) const {}
364
365 int DWriteFontTypeface::onGetUPEM() const {
366 DWRITE_FONT_METRICS metrics;
367 fDWriteFontFace->GetMetrics(&metrics);
368 return metrics.designUnitsPerEm;
369 }
370
371 class LocalizedStrings_IDWriteLocalizedStrings : public SkTypeface::LocalizedStrings {
372 public:
373 /** Takes ownership of the IDWriteLocalizedStrings. */
374 explicit LocalizedStrings_IDWriteLocalizedStrings(IDWriteLocalizedStrings* strings)
375 : fIndex(0), fStrings(strings)
376 { }
377
378 bool next(SkTypeface::LocalizedString* localizedString) override {
379 if (fIndex >= fStrings->GetCount()) {
380 return false;
381 }
382
383 // String
384 UINT32 stringLen;
385 HRBM(fStrings->GetStringLength(fIndex, &stringLen), "Could not get string length.");
386
387 SkSMallocWCHAR wString(static_cast<size_t>(stringLen)+1);
388 HRBM(fStrings->GetString(fIndex, wString.get(), stringLen+1), "Could not get string.");
389
390 HRB(sk_wchar_to_skstring(wString.get(), stringLen, &localizedString->fString));
391
392 // Locale
393 UINT32 localeLen;
394 HRBM(fStrings->GetLocaleNameLength(fIndex, &localeLen), "Could not get locale length.");
395
396 SkSMallocWCHAR wLocale(static_cast<size_t>(localeLen)+1);
397 HRBM(fStrings->GetLocaleName(fIndex, wLocale.get(), localeLen+1), "Could not get locale.");
398
399 HRB(sk_wchar_to_skstring(wLocale.get(), localeLen, &localizedString->fLanguage));
400
401 ++fIndex;
402 return true;
403 }
404
405 private:
406 UINT32 fIndex;
407 SkTScopedComPtr<IDWriteLocalizedStrings> fStrings;
408 };
409
410 SkTypeface::LocalizedStrings* DWriteFontTypeface::onCreateFamilyNameIterator() const {
411 sk_sp<SkTypeface::LocalizedStrings> nameIter =
412 SkOTUtils::LocalizedStrings_NameTable::MakeForFamilyNames(*this);
413 if (!nameIter) {
414 SkTScopedComPtr<IDWriteLocalizedStrings> familyNames;
415 if (fDWriteFontFace3) {
416 HRNM(fDWriteFontFace3->GetFamilyNames(&familyNames),
417 "Could not obtain family names from font face.");
418 } else {
419 HRNM(fDWriteFontFamily->GetFamilyNames(&familyNames),
420 "Could not obtain family names from font family.");
421 }
422 nameIter = sk_make_sp<LocalizedStrings_IDWriteLocalizedStrings>(familyNames.release());
423 }
424 return nameIter.release();
425 }
426
427 bool DWriteFontTypeface::onGlyphMaskNeedsCurrentColor() const {
428 return fDWriteFontFace2 && fDWriteFontFace2->GetColorPaletteCount() > 0;
429 }
430
431 int DWriteFontTypeface::onGetVariationDesignPosition(
432 SkSpan<SkFontArguments::VariationPosition::Coordinate> coordinates) const
433 {
434 if (!fDWriteFontFace5) {
435 return -1;
436 }
437
438 // Return 0 if the font is not variable font.
439 if (!fDWriteFontFace5->HasVariations()) {
440 return 0;
441 }
442
443 UINT32 fontAxisCount = fDWriteFontFace5->GetFontAxisValueCount();
444 SkTScopedComPtr<IDWriteFontResource> fontResource;
445 HR_GENERAL(fDWriteFontFace5->GetFontResource(&fontResource), nullptr, -1);
446 UINT32 variableAxisCount = 0;
447 for (UINT32 i = 0; i < fontAxisCount; ++i) {
448 if (fontResource->GetFontAxisAttributes(i) & DWRITE_FONT_AXIS_ATTRIBUTES_VARIABLE) {
449 ++variableAxisCount;
450 }
451 }
452
453 if (coordinates.size() < variableAxisCount) {
454 return SkTo<int>(variableAxisCount);
455 }
456
457 AutoSTMalloc<8, DWRITE_FONT_AXIS_VALUE> fontAxisValue(fontAxisCount);
458 HR_GENERAL(fDWriteFontFace5->GetFontAxisValues(fontAxisValue.get(), fontAxisCount), nullptr,-1);
459 UINT32 coordIndex = 0;
460 for (UINT32 axisIndex = 0; axisIndex < fontAxisCount; ++axisIndex) {
461 if (fontResource->GetFontAxisAttributes(axisIndex) & DWRITE_FONT_AXIS_ATTRIBUTES_VARIABLE) {
462 coordinates[coordIndex].axis = SkEndian_SwapBE32(fontAxisValue[axisIndex].axisTag);
463 coordinates[coordIndex].value = fontAxisValue[axisIndex].value;
464 ++coordIndex;
465 }
466 }
467
468 SkASSERT(coordIndex == variableAxisCount);
469 return SkTo<int>(variableAxisCount);
470 }
471
472 int DWriteFontTypeface::onGetVariationDesignParameters(
473 SkSpan<SkFontParameters::Variation::Axis> parameters) const
474 {
475 if (!fDWriteFontFace5) {
476 return -1;
477 }
478
479 // Return 0 if the font is not variable font.
480 if (!fDWriteFontFace5->HasVariations()) {
481 return 0;
482 }
483
484 UINT32 fontAxisCount = fDWriteFontFace5->GetFontAxisValueCount();
485 SkTScopedComPtr<IDWriteFontResource> fontResource;
486 HR_GENERAL(fDWriteFontFace5->GetFontResource(&fontResource), nullptr, -1);
487 int variableAxisCount = 0;
488 for (UINT32 i = 0; i < fontAxisCount; ++i) {
489 if (fontResource->GetFontAxisAttributes(i) & DWRITE_FONT_AXIS_ATTRIBUTES_VARIABLE) {
490 variableAxisCount++;
491 }
492 }
493
494 if (parameters.size() < (unsigned)variableAxisCount) {
495 return variableAxisCount;
496 }
497
498 AutoSTMalloc<8, DWRITE_FONT_AXIS_RANGE> fontAxisRange(fontAxisCount);
499 HR_GENERAL(fontResource->GetFontAxisRanges(fontAxisRange.get(), fontAxisCount), nullptr, -1);
500 AutoSTMalloc<8, DWRITE_FONT_AXIS_VALUE> fontAxisDefaultValue(fontAxisCount);
501 HR_GENERAL(fontResource->GetDefaultFontAxisValues(fontAxisDefaultValue.get(), fontAxisCount),
502 nullptr, -1);
503 UINT32 coordIndex = 0;
504
505 for (UINT32 axisIndex = 0; axisIndex < fontAxisCount; ++axisIndex) {
506 if (fontResource->GetFontAxisAttributes(axisIndex) & DWRITE_FONT_AXIS_ATTRIBUTES_VARIABLE) {
507 parameters[coordIndex].tag = SkEndian_SwapBE32(fontAxisDefaultValue[axisIndex].axisTag);
508 parameters[coordIndex].min = fontAxisRange[axisIndex].minValue;
509 parameters[coordIndex].def = fontAxisDefaultValue[axisIndex].value;
510 parameters[coordIndex].max = fontAxisRange[axisIndex].maxValue;
511 parameters[coordIndex].setHidden(fontResource->GetFontAxisAttributes(axisIndex) &
512 DWRITE_FONT_AXIS_ATTRIBUTES_HIDDEN);
513 ++coordIndex;
514 }
515 }
516
517 return variableAxisCount;
518 }
519
520 bool DWriteFontTypeface::onIsSyntheticBold() const {
521 return fDWriteFontFace->GetSimulations() & DWRITE_FONT_SIMULATIONS_BOLD;
522 }
523
524 bool DWriteFontTypeface::onIsSyntheticOblique() const {
525 return fDWriteFontFace->GetSimulations() & DWRITE_FONT_SIMULATIONS_OBLIQUE;
526 }
527
528 int DWriteFontTypeface::onGetTableTags(SkSpan<SkFontTableTag> tags) const {
529 DWRITE_FONT_FACE_TYPE type = fDWriteFontFace->GetType();
530 if (type != DWRITE_FONT_FACE_TYPE_CFF &&
531 type != DWRITE_FONT_FACE_TYPE_TRUETYPE &&
532 type != DWRITE_FONT_FACE_TYPE_TRUETYPE_COLLECTION)
533 {
534 return 0;
535 }
536
537 int ttcIndex;
538 std::unique_ptr<SkStreamAsset> stream = this->openStream(&ttcIndex);
539 return stream.get() ? SkFontStream::GetTableTags(stream.get(), ttcIndex, tags) : 0;
540 }
541
542 size_t DWriteFontTypeface::onGetTableData(SkFontTableTag tag, size_t offset,
543 size_t length, void* data) const
544 {
545 AutoDWriteTable table(fDWriteFontFace.get(), SkEndian_SwapBE32(tag));
546 if (!table.fExists) {
547 return 0;
548 }
549
550 if (offset > table.fSize) {
551 return 0;
552 }
553 size_t size = std::min(length, table.fSize - offset);
554 if (data) {
555 memcpy(data, table.fData + offset, size);
556 }
557
558 return size;
559 }
560
561 sk_sp<SkData> DWriteFontTypeface::onCopyTableData(SkFontTableTag tag) const {
562 const uint8_t* data;
563 UINT32 size;
564 void* lock;
565 BOOL exists;
566 fDWriteFontFace->TryGetFontTable(SkEndian_SwapBE32(tag),
567 reinterpret_cast<const void**>(&data), &size, &lock, &exists);
568 if (!exists) {
569 return nullptr;
570 }
571 struct Context {
572 Context(void* lock, IDWriteFontFace* face) : fLock(lock), fFontFace(SkRefComPtr(face)) {}
573 ~Context() { fFontFace->ReleaseFontTable(fLock); }
574 void* fLock;
575 SkTScopedComPtr<IDWriteFontFace> fFontFace;
576 };
577 return SkData::MakeWithProc(data, size,
578 [](const void*, void* ctx) { delete (Context*)ctx; },
579 new Context(lock, fDWriteFontFace.get()));
580 }
581
582 sk_sp<SkTypeface> DWriteFontTypeface::onMakeClone(const SkFontArguments& args) const {
583 // Skip if the current face index does not match the ttcIndex
584 if (fDWriteFontFace->GetIndex() != SkTo<UINT32>(args.getCollectionIndex())) {
585 return sk_ref_sp(this);
586 }
587
588 // Any "don't care" resolve to existing
589 DWRITE_FONT_SIMULATIONS originalSimulations = fDWriteFontFace->GetSimulations();
590 DWRITE_FONT_SIMULATIONS requestedSimulations = originalSimulations;
591 if (args.getSyntheticBold().has_value()) {
592 if (args.getSyntheticBold().value()) {
593 requestedSimulations |= DWRITE_FONT_SIMULATIONS_BOLD;
594 } else {
595 requestedSimulations &= ~DWRITE_FONT_SIMULATIONS_BOLD;
596 }
597 }
598 if (args.getSyntheticOblique().has_value()) {
599 if (args.getSyntheticOblique().value()) {
600 requestedSimulations |= DWRITE_FONT_SIMULATIONS_OBLIQUE;
601 } else {
602 requestedSimulations &= ~DWRITE_FONT_SIMULATIONS_OBLIQUE;
603 }
604 }
605
606 if (fDWriteFontFace5 && fDWriteFontFace5->HasVariations()) {
607 UINT32 fontAxisCount = fDWriteFontFace5->GetFontAxisValueCount();
608 UINT32 argsCoordCount = args.getVariationDesignPosition().coordinateCount;
609 AutoSTMalloc<8, DWRITE_FONT_AXIS_VALUE> fontAxisValue(fontAxisCount);
610 HRN(fDWriteFontFace5->GetFontAxisValues(fontAxisValue.get(), fontAxisCount));
611
612 for (UINT32 fontIndex = 0; fontIndex < fontAxisCount; ++fontIndex) {
613 for (UINT32 argsIndex = 0; argsIndex < argsCoordCount; ++argsIndex) {
614 if (SkEndian_SwapBE32(fontAxisValue[fontIndex].axisTag) ==
615 args.getVariationDesignPosition().coordinates[argsIndex].axis) {
616 fontAxisValue[fontIndex].value =
617 args.getVariationDesignPosition().coordinates[argsIndex].value;
618 }
619 }
620 }
621 SkTScopedComPtr<IDWriteFontResource> fontResource;
622 HRN(fDWriteFontFace5->GetFontResource(&fontResource));
623 SkTScopedComPtr<IDWriteFontFace5> newFontFace5;
624 HRN(fontResource->CreateFontFace(requestedSimulations,
625 fontAxisValue.get(),
626 fontAxisCount,
627 &newFontFace5));
628
629 SkTScopedComPtr<IDWriteFontFace> newFontFace;
630 HRN(newFontFace5->QueryInterface(&newFontFace));
631 return DWriteFontTypeface::Make(fFactory.get(),
632 newFontFace.get(),
633 fDWriteFont.get(),
634 fDWriteFontFamily.get(),
635 fLoaders,
636 args.getPalette());
637 }
638
639 // If a simulations have changed, a new DirectWrite font will need to be created.
640 if (fDWriteFontFace3 && requestedSimulations != originalSimulations) {
641 SkTScopedComPtr<IDWriteFontFaceReference> fontReference;
642 HRN(fDWriteFontFace3->GetFontFaceReference(&fontReference));
643 SkTScopedComPtr<IDWriteFontFace3> newFontFace3;
644 HRN(fontReference->CreateFontFaceWithSimulations(requestedSimulations, &newFontFace3));
645 if (newFontFace3) {
646 SkTScopedComPtr<IDWriteFontFace> newFontFace;
647 HRN(newFontFace3->QueryInterface(&newFontFace));
648 return DWriteFontTypeface::Make(fFactory.get(),
649 newFontFace.get(),
650 fDWriteFont.get(),
651 fDWriteFontFamily.get(),
652 fLoaders,
653 args.getPalette());
654 }
655 }
656
657 // If the palette args have changed, a new font will need to be created.
658 if (args.getPalette().index != fRequestedPalette.index ||
659 args.getPalette().overrideCount != fRequestedPalette.overrideCount ||
660 memcmp(args.getPalette().overrides, fRequestedPalette.overrides,
661 fRequestedPalette.overrideCount * sizeof(fRequestedPalette.overrides[0])))
662 {
663 return DWriteFontTypeface::Make(fFactory.get(),
664 fDWriteFontFace.get(),
665 fDWriteFont.get(),
666 fDWriteFontFamily.get(),
667 fLoaders,
668 args.getPalette());
669 }
670
671 return sk_ref_sp(this);
672 }
673
674 std::unique_ptr<SkStreamAsset> DWriteFontTypeface::onOpenStream(int* ttcIndex) const {
675 *ttcIndex = fDWriteFontFace->GetIndex();
676
677 UINT32 numFiles = 0;
678 HRNM(fDWriteFontFace->GetFiles(&numFiles, nullptr),
679 "Could not get number of font files.");
680 if (numFiles != 1) {
681 return nullptr;
682 }
683
684 SkTScopedComPtr<IDWriteFontFile> fontFile;
685 HRNM(fDWriteFontFace->GetFiles(&numFiles, &fontFile), "Could not get font files.");
686
687 const void* fontFileKey;
688 UINT32 fontFileKeySize;
689 HRNM(fontFile->GetReferenceKey(&fontFileKey, &fontFileKeySize),
690 "Could not get font file reference key.");
691
692 SkTScopedComPtr<IDWriteFontFileLoader> fontFileLoader;
693 HRNM(fontFile->GetLoader(&fontFileLoader), "Could not get font file loader.");
694
695 SkTScopedComPtr<IDWriteFontFileStream> fontFileStream;
696 HRNM(fontFileLoader->CreateStreamFromKey(fontFileKey, fontFileKeySize,
697 &fontFileStream),
698 "Could not create font file stream.");
699
700 return std::unique_ptr<SkStreamAsset>(new SkDWriteFontFileStream(fontFileStream.get()));
701 }
702
703 std::unique_ptr<SkScalerContext> DWriteFontTypeface::onCreateScalerContext(
704 const SkScalerContextEffects& effects, const SkDescriptor* desc) const
705 {
706 return std::make_unique<SkScalerContext_DW>(
707 *const_cast<DWriteFontTypeface*>(this), effects, desc);
708 }
709
710 void DWriteFontTypeface::onFilterRec(SkScalerContextRec* rec) const {
711 rec->useStrokeForFakeBold();
712
713 if (rec->fFlags & SkScalerContext::kLCD_Vertical_Flag) {
714 rec->fMaskFormat = SkMask::kA8_Format;
715 rec->fFlags |= SkScalerContext::kGenA8FromLCD_Flag;
716 }
717
718 unsigned flagsWeDontSupport = SkScalerContext::kForceAutohinting_Flag |
719 SkScalerContext::kEmbolden_Flag |
720 SkScalerContext::kLCD_Vertical_Flag;
721 rec->fFlags &= ~flagsWeDontSupport;
722
723 SkFontHinting h = rec->getHinting();
724 // DirectWrite2 allows for hinting to be turned off. Force everything else to normal.
725 if (h != SkFontHinting::kNone || !fFactory2 || !fDWriteFontFace2) {
726 h = SkFontHinting::kNormal;
727 }
728 rec->setHinting(h);
729
730 #if defined(SK_FONT_HOST_USE_SYSTEM_SETTINGS)
731 IDWriteFactory* factory = sk_get_dwrite_factory();
732 if (factory != nullptr) {
733 SkTScopedComPtr<IDWriteRenderingParams> defaultRenderingParams;
734 if (SUCCEEDED(factory->CreateRenderingParams(&defaultRenderingParams))) {
735 float gamma = defaultRenderingParams->GetGamma();
736 rec->setDeviceGamma(gamma);
737 rec->setContrast(defaultRenderingParams->GetEnhancedContrast());
738 }
739 }
740 #endif
741 }
742
743 ///////////////////////////////////////////////////////////////////////////////
744 //PDF Support
745
746 static void glyph_to_unicode_map(IDWriteFontFace* fontFace, DWRITE_UNICODE_RANGE range,
747 UINT32* remainingGlyphCount, UINT32 numGlyphs,
748 SkUnichar* glyphToUnicode)
749 {
750 constexpr const int batchSize = 128;
751 UINT32 codepoints[batchSize];
752 UINT16 glyphs[batchSize];
753 for (UINT32 c = range.first; c <= range.last && *remainingGlyphCount != 0; c += batchSize) {
754 UINT32 numBatchedCodePoints = std::min<UINT32>(range.last - c + 1, batchSize);
755 for (UINT32 i = 0; i < numBatchedCodePoints; ++i) {
756 codepoints[i] = c + i;
757 }
758 HRVM(fontFace->GetGlyphIndices(codepoints, numBatchedCodePoints, glyphs),
759 "Failed to get glyph indexes.");
760 for (UINT32 i = 0; i < numBatchedCodePoints; ++i) {
761 UINT16 glyph = glyphs[i];
762 // Intermittent DW bug on Windows 10. See crbug.com/470146.
763 if (glyph >= numGlyphs) {
764 return;
765 }
766 if (0 < glyph && glyphToUnicode[glyph] == 0) {
767 glyphToUnicode[glyph] = c + i; // Always use lowest-index unichar.
768 --*remainingGlyphCount;
769 }
770 }
771 }
772 }
773
774 void DWriteFontTypeface::getGlyphToUnicodeMap(SkSpan<SkUnichar> glyphToUnicode) const {
775 IDWriteFontFace* face = fDWriteFontFace.get();
776 UINT32 numGlyphs = std::min<UINT32>(face->GetGlyphCount(), glyphToUnicode.size());
777 sk_bzero(glyphToUnicode.data(), glyphToUnicode.size_bytes());
778 UINT32 remainingGlyphCount = numGlyphs;
779
780 if (fDWriteFontFace1) {
781 IDWriteFontFace1* face1 = fDWriteFontFace1.get();
782 UINT32 numRanges = 0;
783 HRESULT hr = face1->GetUnicodeRanges(0, nullptr, &numRanges);
784 if (hr != E_NOT_SUFFICIENT_BUFFER && FAILED(hr)) {
785 HRVM(hr, "Failed to get number of ranges.");
786 }
787 std::unique_ptr<DWRITE_UNICODE_RANGE[]> ranges(new DWRITE_UNICODE_RANGE[numRanges]);
788 HRVM(face1->GetUnicodeRanges(numRanges, ranges.get(), &numRanges), "Failed to get ranges.");
789 for (UINT32 i = 0; i < numRanges; ++i) {
790 glyph_to_unicode_map(face1, ranges[i], &remainingGlyphCount, numGlyphs,
791 glyphToUnicode.data());
792 }
793 } else {
794 glyph_to_unicode_map(face, {0, 0x10FFFF}, &remainingGlyphCount, numGlyphs,
795 glyphToUnicode.data());
796 }
797 }
798
799 std::unique_ptr<SkAdvancedTypefaceMetrics> DWriteFontTypeface::onGetAdvancedMetrics() const {
800
801 std::unique_ptr<SkAdvancedTypefaceMetrics> info(nullptr);
802
803 DWRITE_FONT_METRICS dwfm;
804 fDWriteFontFace->GetMetrics(&dwfm);
805
806 info.reset(new SkAdvancedTypefaceMetrics);
807
808 info->fAscent = SkToS16(dwfm.ascent);
809 info->fDescent = SkToS16(dwfm.descent);
810 info->fCapHeight = SkToS16(dwfm.capHeight);
811
812 DWRITE_FONT_FACE_TYPE fontType = fDWriteFontFace->GetType();
813 if (fontType == DWRITE_FONT_FACE_TYPE_TRUETYPE ||
814 fontType == DWRITE_FONT_FACE_TYPE_TRUETYPE_COLLECTION)
815 {
816 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
817 } else if (fontType == DWRITE_FONT_FACE_TYPE_CFF ||
818 fontType == DWRITE_FONT_FACE_TYPE_OPENTYPE_COLLECTION)
819 {
820 info->fType = SkAdvancedTypefaceMetrics::kCFF_Font;
821 } else {
822 return info;
823 }
824
825 // Simulated fonts aren't really OpenType fonts.
826 if (fDWriteFontFace->GetSimulations() != DWRITE_FONT_SIMULATIONS_NONE) {
827 info->fType = SkAdvancedTypefaceMetrics::kOther_Font;
828 }
829
830 AutoTDWriteTable<SkOTTableHead> headTable(fDWriteFontFace.get());
831 AutoTDWriteTable<SkOTTablePostScript> postTable(fDWriteFontFace.get());
832 AutoTDWriteTable<SkOTTableHorizontalHeader> hheaTable(fDWriteFontFace.get());
833 AutoTDWriteTable<SkOTTableOS2> os2Table(fDWriteFontFace.get());
834 if (!headTable.fExists || !postTable.fExists || !hheaTable.fExists || !os2Table.fExists) {
835 return info;
836 }
837
838 SkOTUtils::SetAdvancedTypefaceFlags(os2Table->version.v4.fsType, info.get());
839
840 // There are versions of DirectWrite which support named instances for system variation fonts,
841 // but no means to indicate that such a typeface is a variation.
842 AutoTDWriteTable<SkOTTableFontVariations> fvarTable(fDWriteFontFace.get());
843 if (fvarTable.fExists) {
844 info->fFlags |= SkAdvancedTypefaceMetrics::kVariable_FontFlag;
845 }
846
847 //There exist CJK fonts which set the IsFixedPitch and Monospace bits,
848 //but have full width, latin half-width, and half-width kana.
849 bool fixedWidth = (postTable->isFixedPitch &&
850 (1 == SkEndian_SwapBE16(hheaTable->numberOfHMetrics)));
851 //Monospace
852 if (fixedWidth) {
853 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
854 }
855 //Italic
856 if (os2Table->version.v0.fsSelection.field.Italic) {
857 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
858 }
859 //Serif
860 using SerifStyle = SkPanose::Data::TextAndDisplay::SerifStyle;
861 SerifStyle serifStyle = os2Table->version.v0.panose.data.textAndDisplay.bSerifStyle;
862 if (SkPanose::FamilyType::TextAndDisplay == os2Table->version.v0.panose.bFamilyType) {
863 if (SerifStyle::Cove == serifStyle ||
864 SerifStyle::ObtuseCove == serifStyle ||
865 SerifStyle::SquareCove == serifStyle ||
866 SerifStyle::ObtuseSquareCove == serifStyle ||
867 SerifStyle::Square == serifStyle ||
868 SerifStyle::Thin == serifStyle ||
869 SerifStyle::Bone == serifStyle ||
870 SerifStyle::Exaggerated == serifStyle ||
871 SerifStyle::Triangle == serifStyle)
872 {
873 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
874 }
875 //Script
876 } else if (SkPanose::FamilyType::Script == os2Table->version.v0.panose.bFamilyType) {
877 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
878 }
879
880 info->fItalicAngle = SkEndian_SwapBE32(postTable->italicAngle) >> 16;
881
882 info->fBBox = SkIRect::MakeLTRB((int32_t)SkEndian_SwapBE16((uint16_t)headTable->xMin),
883 (int32_t)SkEndian_SwapBE16((uint16_t)headTable->yMax),
884 (int32_t)SkEndian_SwapBE16((uint16_t)headTable->xMax),
885 (int32_t)SkEndian_SwapBE16((uint16_t)headTable->yMin));
886 return info;
887 }
888
889 class StreamFontFileLoader : public IDWriteFontFileLoader {
890 public:
891 // IUnknown methods
892 SK_STDMETHODIMP QueryInterface(REFIID iid, void** ppvObject) override;
893 SK_STDMETHODIMP_(ULONG) AddRef() override;
894 SK_STDMETHODIMP_(ULONG) Release() override;
895
896 // IDWriteFontFileLoader methods
897 SK_STDMETHODIMP CreateStreamFromKey(
898 void const* fontFileReferenceKey,
899 UINT32 fontFileReferenceKeySize,
900 IDWriteFontFileStream** fontFileStream) override;
901
902 // Takes ownership of stream.
903 static HRESULT Create(std::unique_ptr<SkStreamAsset> stream,
904 StreamFontFileLoader** streamFontFileLoader) {
905 *streamFontFileLoader = new StreamFontFileLoader(std::move(stream));
906 if (nullptr == *streamFontFileLoader) {
907 return E_OUTOFMEMORY;
908 }
909 return S_OK;
910 }
911
912 private:
913 StreamFontFileLoader(std::unique_ptr<SkStreamAsset> stream)
914 : fStream(std::move(stream)), fRefCount(1)
915 {}
916 virtual ~StreamFontFileLoader() { }
917
918 std::unique_ptr<SkStreamAsset> fStream;
919 ULONG fRefCount;
920 };
921
922 SK_STDMETHODIMP StreamFontFileLoader::QueryInterface(REFIID iid, void** ppvObject) {
923 if (iid == IID_IUnknown || iid == __uuidof(IDWriteFontFileLoader)) {
924 *ppvObject = this;
925 AddRef();
926 return S_OK;
927 } else {
928 *ppvObject = nullptr;
929 return E_NOINTERFACE;
930 }
931 }
932
933 SK_STDMETHODIMP_(ULONG) StreamFontFileLoader::AddRef() {
934 return InterlockedIncrement(&fRefCount);
935 }
936
937 SK_STDMETHODIMP_(ULONG) StreamFontFileLoader::Release() {
938 ULONG newCount = InterlockedDecrement(&fRefCount);
939 if (0 == newCount) {
940 delete this;
941 }
942 return newCount;
943 }
944
945 SK_STDMETHODIMP StreamFontFileLoader::CreateStreamFromKey(
946 void const* fontFileReferenceKey,
947 UINT32 fontFileReferenceKeySize,
948 IDWriteFontFileStream** fontFileStream)
949 {
950 SkTScopedComPtr<SkDWriteFontFileStreamWrapper> stream;
951 HR(SkDWriteFontFileStreamWrapper::Create(fStream->duplicate().release(), &stream));
952 *fontFileStream = stream.release();
953 return S_OK;
954 }
955
956 class StreamFontFileEnumerator : public IDWriteFontFileEnumerator {
957 public:
958 // IUnknown methods
959 SK_STDMETHODIMP QueryInterface(REFIID iid, void** ppvObject) override;
960 SK_STDMETHODIMP_(ULONG) AddRef() override;
961 SK_STDMETHODIMP_(ULONG) Release() override;
962
963 // IDWriteFontFileEnumerator methods
964 SK_STDMETHODIMP MoveNext(BOOL* hasCurrentFile) override;
965 SK_STDMETHODIMP GetCurrentFontFile(IDWriteFontFile** fontFile) override;
966
967 static HRESULT Create(IDWriteFactory* factory, IDWriteFontFileLoader* fontFileLoader,
968 StreamFontFileEnumerator** streamFontFileEnumerator) {
969 *streamFontFileEnumerator = new StreamFontFileEnumerator(factory, fontFileLoader);
970 if (nullptr == *streamFontFileEnumerator) {
971 return E_OUTOFMEMORY;
972 }
973 return S_OK;
974 }
975 private:
976 StreamFontFileEnumerator(IDWriteFactory* factory, IDWriteFontFileLoader* fontFileLoader);
977 virtual ~StreamFontFileEnumerator() { }
978
979 ULONG fRefCount;
980
981 SkTScopedComPtr<IDWriteFactory> fFactory;
982 SkTScopedComPtr<IDWriteFontFile> fCurrentFile;
983 SkTScopedComPtr<IDWriteFontFileLoader> fFontFileLoader;
984 bool fHasNext;
985 };
986
987 StreamFontFileEnumerator::StreamFontFileEnumerator(IDWriteFactory* factory,
988 IDWriteFontFileLoader* fontFileLoader)
989 : fRefCount(1)
990 , fFactory(SkRefComPtr(factory))
991 , fCurrentFile()
992 , fFontFileLoader(SkRefComPtr(fontFileLoader))
993 , fHasNext(true)
994 { }
995
996 SK_STDMETHODIMP StreamFontFileEnumerator::QueryInterface(REFIID iid, void** ppvObject) {
997 if (iid == IID_IUnknown || iid == __uuidof(IDWriteFontFileEnumerator)) {
998 *ppvObject = this;
999 AddRef();
1000 return S_OK;
1001 } else {
1002 *ppvObject = nullptr;
1003 return E_NOINTERFACE;
1004 }
1005 }
1006
1007 SK_STDMETHODIMP_(ULONG) StreamFontFileEnumerator::AddRef() {
1008 return InterlockedIncrement(&fRefCount);
1009 }
1010
1011 SK_STDMETHODIMP_(ULONG) StreamFontFileEnumerator::Release() {
1012 ULONG newCount = InterlockedDecrement(&fRefCount);
1013 if (0 == newCount) {
1014 delete this;
1015 }
1016 return newCount;
1017 }
1018
1019 SK_STDMETHODIMP StreamFontFileEnumerator::MoveNext(BOOL* hasCurrentFile) {
1020 *hasCurrentFile = FALSE;
1021
1022 if (!fHasNext) {
1023 return S_OK;
1024 }
1025 fHasNext = false;
1026
1027 UINT32 fontFileReferenceKey = 0;
1028 HR(fFactory->CreateCustomFontFileReference(
1029 &fontFileReferenceKey, //cannot be nullptr
1030 sizeof(fontFileReferenceKey), //even if this is 0
1031 fFontFileLoader.get(),
1032 &fCurrentFile));
1033
1034 *hasCurrentFile = TRUE;
1035 return S_OK;
1036 }
1037
1038 SK_STDMETHODIMP StreamFontFileEnumerator::GetCurrentFontFile(IDWriteFontFile** fontFile) {
1039 if (fCurrentFile.get() == nullptr) {
1040 *fontFile = nullptr;
1041 return E_FAIL;
1042 }
1043
1044 *fontFile = SkRefComPtr(fCurrentFile.get());
1045 return S_OK;
1046 }
1047
1048 class StreamFontCollectionLoader : public IDWriteFontCollectionLoader {
1049 public:
1050 // IUnknown methods
1051 SK_STDMETHODIMP QueryInterface(REFIID iid, void** ppvObject) override;
1052 SK_STDMETHODIMP_(ULONG) AddRef() override;
1053 SK_STDMETHODIMP_(ULONG) Release() override;
1054
1055 // IDWriteFontCollectionLoader methods
1056 SK_STDMETHODIMP CreateEnumeratorFromKey(
1057 IDWriteFactory* factory,
1058 void const* collectionKey,
1059 UINT32 collectionKeySize,
1060 IDWriteFontFileEnumerator** fontFileEnumerator) override;
1061
1062 static HRESULT Create(IDWriteFontFileLoader* fontFileLoader,
1063 StreamFontCollectionLoader** streamFontCollectionLoader) {
1064 *streamFontCollectionLoader = new StreamFontCollectionLoader(fontFileLoader);
1065 if (nullptr == *streamFontCollectionLoader) {
1066 return E_OUTOFMEMORY;
1067 }
1068 return S_OK;
1069 }
1070 private:
1071 StreamFontCollectionLoader(IDWriteFontFileLoader* fontFileLoader)
1072 : fRefCount(1)
1073 , fFontFileLoader(SkRefComPtr(fontFileLoader))
1074 { }
1075 virtual ~StreamFontCollectionLoader() { }
1076
1077 ULONG fRefCount;
1078 SkTScopedComPtr<IDWriteFontFileLoader> fFontFileLoader;
1079 };
1080
1081 SK_STDMETHODIMP StreamFontCollectionLoader::QueryInterface(REFIID iid, void** ppvObject) {
1082 if (iid == IID_IUnknown || iid == __uuidof(IDWriteFontCollectionLoader)) {
1083 *ppvObject = this;
1084 AddRef();
1085 return S_OK;
1086 } else {
1087 *ppvObject = nullptr;
1088 return E_NOINTERFACE;
1089 }
1090 }
1091
1092 SK_STDMETHODIMP_(ULONG) StreamFontCollectionLoader::AddRef() {
1093 return InterlockedIncrement(&fRefCount);
1094 }
1095
1096 SK_STDMETHODIMP_(ULONG) StreamFontCollectionLoader::Release() {
1097 ULONG newCount = InterlockedDecrement(&fRefCount);
1098 if (0 == newCount) {
1099 delete this;
1100 }
1101 return newCount;
1102 }
1103
1104 template <typename T> class [[nodiscard]] SkAutoIDWriteUnregister {
1105 public:
1106 SkAutoIDWriteUnregister(IDWriteFactory* factory, T* unregister)
1107 : fFactory(factory), fUnregister(unregister)
1108 { }
1109 SkAutoIDWriteUnregister(const SkAutoIDWriteUnregister&) = delete;
1110 SkAutoIDWriteUnregister& operator=(const SkAutoIDWriteUnregister&) = delete;
1111 SkAutoIDWriteUnregister(SkAutoIDWriteUnregister&&) = delete;
1112 SkAutoIDWriteUnregister& operator=(SkAutoIDWriteUnregister&&) = delete;
1113
1114 ~SkAutoIDWriteUnregister() {
1115 if (fUnregister) {
1116 unregister(fFactory, fUnregister);
1117 }
1118 }
1119
1120 T* release() {
1121 T* old = fUnregister;
1122 fUnregister = nullptr;
1123 return old;
1124 }
1125
1126 private:
1127 HRESULT unregister(IDWriteFactory* factory, IDWriteFontFileLoader* unregister) {
1128 return factory->UnregisterFontFileLoader(unregister);
1129 }
1130
1131 HRESULT unregister(IDWriteFactory* factory, IDWriteFontCollectionLoader* unregister) {
1132 return factory->UnregisterFontCollectionLoader(unregister);
1133 }
1134
1135 IDWriteFactory* fFactory;
1136 T* fUnregister;
1137 };
1138
1139 SK_STDMETHODIMP StreamFontCollectionLoader::CreateEnumeratorFromKey(
1140 IDWriteFactory* factory,
1141 void const* collectionKey,
1142 UINT32 collectionKeySize,
1143 IDWriteFontFileEnumerator** fontFileEnumerator)
1144 {
1145 SkTScopedComPtr<StreamFontFileEnumerator> enumerator;
1146 HR(StreamFontFileEnumerator::Create(factory, fFontFileLoader.get(), &enumerator));
1147 *fontFileEnumerator = enumerator.release();
1148 return S_OK;
1149 }
1150
1151 static HRESULT apply_fontargument_variation(SkTScopedComPtr<IDWriteFontFace>& fontFace,
1152 const SkFontArguments& args)
1153 {
1154 SkTScopedComPtr<IDWriteFontFace5> fontFace5;
1155 if (FAILED(fontFace->QueryInterface(&fontFace5)) || !fontFace5->HasVariations()) {
1156 return S_OK;
1157 }
1158
1159 UINT32 fontAxisCount = fontFace5->GetFontAxisValueCount();
1160 UINT32 argsCoordCount = args.getVariationDesignPosition().coordinateCount;
1161 AutoSTMalloc<8, DWRITE_FONT_AXIS_VALUE> variation(fontAxisCount);
1162 SkTScopedComPtr<IDWriteFontResource> fontResource;
1163 HR(fontFace5->GetFontResource(&fontResource));
1164 HR(fontResource->GetDefaultFontAxisValues(variation, fontAxisCount));
1165
1166 for (UINT32 fontAxisIndex = 0; fontAxisIndex < fontAxisCount; ++fontAxisIndex) {
1167 DWRITE_FONT_AXIS_VALUE& fontCoordinate = variation[fontAxisIndex];
1168
1169 for (UINT32 argsCoordIndex = argsCoordCount; argsCoordIndex --> 0;) {
1170 const SkFontArguments::VariationPosition::Coordinate& argsCoordinate =
1171 args.getVariationDesignPosition().coordinates[argsCoordIndex];
1172 if (SkEndian_SwapBE32(fontCoordinate.axisTag) == argsCoordinate.axis) {
1173 fontCoordinate.value = argsCoordinate.value;
1174 break;
1175 }
1176 }
1177 }
1178
1179 SkTScopedComPtr<IDWriteFontFace5> fontFace5_Out;
1180 HR(fontResource->CreateFontFace(DWRITE_FONT_SIMULATIONS_NONE,
1181 variation.get(), fontAxisCount,
1182 &fontFace5_Out));
1183 fontFace.reset();
1184 HR(fontFace5_Out->QueryInterface(&fontFace));
1185
1186 return S_OK;
1187 }
1188
1189 sk_sp<SkTypeface> DWriteFontTypeface::MakeFromStream(std::unique_ptr<SkStreamAsset> stream,
1190 const SkFontArguments& args) {
1191 // TODO: do we need to use some user provided factory?
1192 IDWriteFactory* factory = sk_get_dwrite_factory();
1193 if (nullptr == factory) {
1194 return nullptr;
1195 }
1196
1197 SkTScopedComPtr<StreamFontFileLoader> fontFileLoader;
1198 HRN(StreamFontFileLoader::Create(std::move(stream), &fontFileLoader));
1199 HRN(factory->RegisterFontFileLoader(fontFileLoader.get()));
1200 SkAutoIDWriteUnregister<StreamFontFileLoader> autoUnregisterFontFileLoader(
1201 factory, fontFileLoader.get());
1202
1203 SkTScopedComPtr<StreamFontCollectionLoader> fontCollectionLoader;
1204 HRN(StreamFontCollectionLoader::Create(fontFileLoader.get(), &fontCollectionLoader));
1205 HRN(factory->RegisterFontCollectionLoader(fontCollectionLoader.get()));
1206 SkAutoIDWriteUnregister<StreamFontCollectionLoader> autoUnregisterFontCollectionLoader(
1207 factory, fontCollectionLoader.get());
1208
1209 SkTScopedComPtr<IDWriteFontCollection> fontCollection;
1210 HRN(factory->CreateCustomFontCollection(fontCollectionLoader.get(), nullptr, 0,
1211 &fontCollection));
1212
1213 struct BestMatch {
1214 UINT32 familyIndex = 0;
1215 UINT32 fontIndex = 0;
1216 int distance = 0;
1217 };
1218 std::optional<BestMatch> bestMatch;
1219
1220 // R is the request (known), A is the actual (for each font).
1221 // Value is distance from match.
1222 // As with CSS3 Oblique matches tighter than Weight.
1223 // "Don't care" prefers no simulation.
1224 static constexpr uint8_t simulationDistances[9][4] = {
1225 // R\A ob oB Ob OB
1226 {/*--*/ 0, 1, 2, 3},
1227 {/*-b*/ 0, 1, 2, 3},
1228 {/*-B*/ 2, 0, 3, 1},
1229 {/*o-*/ 0, 1, 2, 3},
1230 {/*ob*/ 0, 1, 2, 3},
1231 {/*oB*/ 1, 0, 3, 2},
1232 {/*O-*/ 2, 3, 0, 1},
1233 {/*Ob*/ 2, 3, 0, 1},
1234 {/*OB*/ 3, 2, 1, 0},
1235 };
1236 size_t simulationRequestIndex = 0;
1237 if (args.getSyntheticBold().has_value()) {
1238 simulationRequestIndex += args.getSyntheticBold().value() ? 2 : 1;
1239 }
1240 if (args.getSyntheticOblique().has_value()) {
1241 simulationRequestIndex += args.getSyntheticOblique().value() ? 2 * 3 : 1 * 3;
1242 }
1243 const uint8_t (&actualSimulationDistances)[4] = simulationDistances[simulationRequestIndex];
1244
1245 // Find the first non-simulated font which has the given ttc index.
1246 UINT32 familyCount = fontCollection->GetFontFamilyCount();
1247 for (UINT32 familyIndex = 0; familyIndex < familyCount; ++familyIndex) {
1248 SkTScopedComPtr<IDWriteFontFamily> fontFamily;
1249 HRN(fontCollection->GetFontFamily(familyIndex, &fontFamily));
1250
1251 UINT32 fontCount = fontFamily->GetFontCount();
1252 for (UINT32 fontIndex = 0; fontIndex < fontCount; ++fontIndex) {
1253 SkTScopedComPtr<IDWriteFont> font;
1254 HRN(fontFamily->GetFont(fontIndex, &font));
1255
1256 SkTScopedComPtr<IDWriteFontFace> fontFace;
1257 HRN(font->CreateFontFace(&fontFace));
1258 int faceIndex = fontFace->GetIndex();
1259 int ttcIndex = args.getCollectionIndex();
1260
1261 // Skip if the current face index does not match the ttcIndex
1262 if (faceIndex != ttcIndex) {
1263 continue;
1264 }
1265
1266 // Find match the lowest distance from the request.
1267 const uint8_t distance = actualSimulationDistances[font->GetSimulations() & 0x3];
1268 if (bestMatch.has_value()) {
1269 if (distance < bestMatch->distance) {
1270 bestMatch = {familyIndex, fontIndex, distance};
1271 }
1272 } else {
1273 bestMatch = {familyIndex, fontIndex, distance};
1274 }
1275 }
1276 }
1277 if (bestMatch.has_value()) {
1278 SkTScopedComPtr<IDWriteFontFamily> fontFamily;
1279 HRN(fontCollection->GetFontFamily(bestMatch->familyIndex, &fontFamily));
1280
1281 SkTScopedComPtr<IDWriteFont> font;
1282 HRN(fontFamily->GetFont(bestMatch->fontIndex, &font));
1283
1284 SkTScopedComPtr<IDWriteFontFace> fontFace;
1285 HRN(font->CreateFontFace(&fontFace));
1286
1287 apply_fontargument_variation(fontFace, args);
1288
1289 return DWriteFontTypeface::Make(
1290 factory, fontFace.get(), font.get(), fontFamily.get(),
1291 sk_make_sp<DWriteFontTypeface::Loaders>(
1292 factory,
1293 autoUnregisterFontFileLoader.release(),
1294 autoUnregisterFontCollectionLoader.release()),
1295 args.getPalette());
1296 }
1297
1298 return nullptr;
1299 }
1300
1301 #endif//defined(SK_BUILD_FOR_WIN)