blob: 2387def0a8998f133a5f84e09f88735482c75bea [file] [log] [blame]
bungeman51daa252014-06-05 13:38:45 -07001/*
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
bungemandf2ec352014-08-20 12:21:32 -07008#include "SkTypes.h"
9// SkTypes will include Windows.h, which will pull in all of the GDI defines.
10// GDI #defines GetGlyphIndices to GetGlyphIndicesA or GetGlyphIndicesW, but
11// IDWriteFontFace has a method called GetGlyphIndices. Since this file does
12// not use GDI, undefing GetGlyphIndices makes things less confusing.
13#undef GetGlyphIndices
14
bungeman51daa252014-06-05 13:38:45 -070015#include "SkDWriteFontFileStream.h"
16#include "SkFontDescriptor.h"
17#include "SkFontStream.h"
18#include "SkOTTable_head.h"
19#include "SkOTTable_hhea.h"
20#include "SkOTTable_OS_2.h"
21#include "SkOTTable_post.h"
22#include "SkScalerContext.h"
23#include "SkScalerContext_win_dw.h"
24#include "SkTypeface_win_dw.h"
bungeman51daa252014-06-05 13:38:45 -070025#include "SkUtils.h"
26
27void DWriteFontTypeface::onGetFontDescriptor(SkFontDescriptor* desc,
28 bool* isLocalStream) const {
29 // Get the family name.
30 SkTScopedComPtr<IDWriteLocalizedStrings> dwFamilyNames;
31 HRV(fDWriteFontFamily->GetFamilyNames(&dwFamilyNames));
32
33 UINT32 dwFamilyNamesLength;
34 HRV(dwFamilyNames->GetStringLength(0, &dwFamilyNamesLength));
35
36 SkSMallocWCHAR dwFamilyNameChar(dwFamilyNamesLength+1);
37 HRV(dwFamilyNames->GetString(0, dwFamilyNameChar.get(), dwFamilyNamesLength+1));
38
39 SkString utf8FamilyName;
40 HRV(sk_wchar_to_skstring(dwFamilyNameChar.get(), &utf8FamilyName));
41
42 desc->setFamilyName(utf8FamilyName.c_str());
43 *isLocalStream = SkToBool(fDWriteFontFileLoader.get());
44}
45
46static SkUnichar next_utf8(const void** chars) {
47 return SkUTF8_NextUnichar((const char**)chars);
48}
49
50static SkUnichar next_utf16(const void** chars) {
51 return SkUTF16_NextUnichar((const uint16_t**)chars);
52}
53
54static SkUnichar next_utf32(const void** chars) {
55 const SkUnichar** uniChars = (const SkUnichar**)chars;
56 SkUnichar uni = **uniChars;
57 *uniChars += 1;
58 return uni;
59}
60
61typedef SkUnichar (*EncodingProc)(const void**);
62
63static EncodingProc find_encoding_proc(SkTypeface::Encoding enc) {
64 static const EncodingProc gProcs[] = {
65 next_utf8, next_utf16, next_utf32
66 };
67 SkASSERT((size_t)enc < SK_ARRAY_COUNT(gProcs));
68 return gProcs[enc];
69}
70
71int DWriteFontTypeface::onCharsToGlyphs(const void* chars, Encoding encoding,
72 uint16_t glyphs[], int glyphCount) const
73{
74 if (NULL == glyphs) {
75 EncodingProc next_ucs4_proc = find_encoding_proc(encoding);
76 for (int i = 0; i < glyphCount; ++i) {
77 const SkUnichar c = next_ucs4_proc(&chars);
78 BOOL exists;
79 fDWriteFont->HasCharacter(c, &exists);
80 if (!exists) {
81 return i;
82 }
83 }
84 return glyphCount;
85 }
86
87 switch (encoding) {
88 case SkTypeface::kUTF8_Encoding:
89 case SkTypeface::kUTF16_Encoding: {
90 static const int scratchCount = 256;
91 UINT32 scratch[scratchCount];
92 EncodingProc next_ucs4_proc = find_encoding_proc(encoding);
93 for (int baseGlyph = 0; baseGlyph < glyphCount; baseGlyph += scratchCount) {
94 int glyphsLeft = glyphCount - baseGlyph;
95 int limit = SkTMin(glyphsLeft, scratchCount);
96 for (int i = 0; i < limit; ++i) {
97 scratch[i] = next_ucs4_proc(&chars);
98 }
99 fDWriteFontFace->GetGlyphIndices(scratch, limit, &glyphs[baseGlyph]);
100 }
101 break;
102 }
103 case SkTypeface::kUTF32_Encoding: {
104 const UINT32* utf32 = reinterpret_cast<const UINT32*>(chars);
105 fDWriteFontFace->GetGlyphIndices(utf32, glyphCount, glyphs);
106 break;
107 }
108 default:
109 SK_CRASH();
110 }
111
112 for (int i = 0; i < glyphCount; ++i) {
113 if (0 == glyphs[i]) {
114 return i;
115 }
116 }
117 return glyphCount;
118}
119
120int DWriteFontTypeface::onCountGlyphs() const {
121 return fDWriteFontFace->GetGlyphCount();
122}
123
124int DWriteFontTypeface::onGetUPEM() const {
125 DWRITE_FONT_METRICS metrics;
126 fDWriteFontFace->GetMetrics(&metrics);
127 return metrics.designUnitsPerEm;
128}
129
130class LocalizedStrings_IDWriteLocalizedStrings : public SkTypeface::LocalizedStrings {
131public:
132 /** Takes ownership of the IDWriteLocalizedStrings. */
133 explicit LocalizedStrings_IDWriteLocalizedStrings(IDWriteLocalizedStrings* strings)
134 : fIndex(0), fStrings(strings)
135 { }
136
137 virtual bool next(SkTypeface::LocalizedString* localizedString) SK_OVERRIDE {
138 if (fIndex >= fStrings->GetCount()) {
139 return false;
140 }
141
142 // String
143 UINT32 stringLength;
144 HRBM(fStrings->GetStringLength(fIndex, &stringLength), "Could not get string length.");
145 stringLength += 1;
146
147 SkSMallocWCHAR wString(stringLength);
148 HRBM(fStrings->GetString(fIndex, wString.get(), stringLength), "Could not get string.");
149
150 HRB(sk_wchar_to_skstring(wString.get(), &localizedString->fString));
151
152 // Locale
153 UINT32 localeLength;
154 HRBM(fStrings->GetLocaleNameLength(fIndex, &localeLength), "Could not get locale length.");
155 localeLength += 1;
156
157 SkSMallocWCHAR wLocale(localeLength);
158 HRBM(fStrings->GetLocaleName(fIndex, wLocale.get(), localeLength), "Could not get locale.");
159
160 HRB(sk_wchar_to_skstring(wLocale.get(), &localizedString->fLanguage));
161
162 ++fIndex;
163 return true;
164 }
165
166private:
167 UINT32 fIndex;
168 SkTScopedComPtr<IDWriteLocalizedStrings> fStrings;
169};
170
171SkTypeface::LocalizedStrings* DWriteFontTypeface::onCreateFamilyNameIterator() const {
172 SkTScopedComPtr<IDWriteLocalizedStrings> familyNames;
173 HRNM(fDWriteFontFamily->GetFamilyNames(&familyNames), "Could not obtain family names.");
174
175 return new LocalizedStrings_IDWriteLocalizedStrings(familyNames.release());
176}
177
178int DWriteFontTypeface::onGetTableTags(SkFontTableTag tags[]) const {
179 DWRITE_FONT_FACE_TYPE type = fDWriteFontFace->GetType();
180 if (type != DWRITE_FONT_FACE_TYPE_CFF &&
181 type != DWRITE_FONT_FACE_TYPE_TRUETYPE &&
182 type != DWRITE_FONT_FACE_TYPE_TRUETYPE_COLLECTION)
183 {
184 return 0;
185 }
186
187 int ttcIndex;
188 SkAutoTUnref<SkStream> stream(this->openStream(&ttcIndex));
189 return stream.get() ? SkFontStream::GetTableTags(stream, ttcIndex, tags) : 0;
190}
191
192size_t DWriteFontTypeface::onGetTableData(SkFontTableTag tag, size_t offset,
193 size_t length, void* data) const
194{
195 AutoDWriteTable table(fDWriteFontFace.get(), SkEndian_SwapBE32(tag));
196 if (!table.fExists) {
197 return 0;
198 }
199
200 if (offset > table.fSize) {
201 return 0;
202 }
203 size_t size = SkTMin(length, table.fSize - offset);
204 if (NULL != data) {
205 memcpy(data, table.fData + offset, size);
206 }
207
208 return size;
209}
210
211SkStream* DWriteFontTypeface::onOpenStream(int* ttcIndex) const {
212 *ttcIndex = fDWriteFontFace->GetIndex();
213
214 UINT32 numFiles;
215 HRNM(fDWriteFontFace->GetFiles(&numFiles, NULL),
216 "Could not get number of font files.");
217 if (numFiles != 1) {
218 return NULL;
219 }
220
221 SkTScopedComPtr<IDWriteFontFile> fontFile;
222 HRNM(fDWriteFontFace->GetFiles(&numFiles, &fontFile), "Could not get font files.");
223
224 const void* fontFileKey;
225 UINT32 fontFileKeySize;
226 HRNM(fontFile->GetReferenceKey(&fontFileKey, &fontFileKeySize),
227 "Could not get font file reference key.");
228
229 SkTScopedComPtr<IDWriteFontFileLoader> fontFileLoader;
230 HRNM(fontFile->GetLoader(&fontFileLoader), "Could not get font file loader.");
231
232 SkTScopedComPtr<IDWriteFontFileStream> fontFileStream;
233 HRNM(fontFileLoader->CreateStreamFromKey(fontFileKey, fontFileKeySize,
234 &fontFileStream),
235 "Could not create font file stream.");
236
237 return SkNEW_ARGS(SkDWriteFontFileStream, (fontFileStream.get()));
238}
239
240SkScalerContext* DWriteFontTypeface::onCreateScalerContext(const SkDescriptor* desc) const {
241 return SkNEW_ARGS(SkScalerContext_DW, (const_cast<DWriteFontTypeface*>(this), desc));
242}
243
244void DWriteFontTypeface::onFilterRec(SkScalerContext::Rec* rec) const {
245 if (rec->fFlags & SkScalerContext::kLCD_BGROrder_Flag ||
246 rec->fFlags & SkScalerContext::kLCD_Vertical_Flag)
247 {
248 rec->fMaskFormat = SkMask::kA8_Format;
249 }
250
bungeman41078062014-07-07 08:16:37 -0700251 unsigned flagsWeDontSupport = SkScalerContext::kVertical_Flag |
252 SkScalerContext::kDevKernText_Flag |
bungeman51daa252014-06-05 13:38:45 -0700253 SkScalerContext::kForceAutohinting_Flag |
254 SkScalerContext::kEmbolden_Flag |
255 SkScalerContext::kLCD_BGROrder_Flag |
256 SkScalerContext::kLCD_Vertical_Flag;
257 rec->fFlags &= ~flagsWeDontSupport;
258
259 SkPaint::Hinting h = rec->getHinting();
260 // DirectWrite does not provide for hinting hints.
261 h = SkPaint::kSlight_Hinting;
262 rec->setHinting(h);
263
264#if SK_FONT_HOST_USE_SYSTEM_SETTINGS
265 IDWriteFactory* factory = get_dwrite_factory();
266 if (factory != NULL) {
267 SkTScopedComPtr<IDWriteRenderingParams> defaultRenderingParams;
268 if (SUCCEEDED(factory->CreateRenderingParams(&defaultRenderingParams))) {
269 float gamma = defaultRenderingParams->GetGamma();
270 rec->setDeviceGamma(gamma);
271 rec->setPaintGamma(gamma);
272
273 rec->setContrast(defaultRenderingParams->GetEnhancedContrast());
274 }
275 }
276#endif
277}
278
279///////////////////////////////////////////////////////////////////////////////
280//PDF Support
281
282using namespace skia_advanced_typeface_metrics_utils;
283
284// Construct Glyph to Unicode table.
285// Unicode code points that require conjugate pairs in utf16 are not
286// supported.
bungeman51daa252014-06-05 13:38:45 -0700287// TODO(bungeman): This never does what anyone wants.
288// What is really wanted is the text to glyphs mapping
289static void populate_glyph_to_unicode(IDWriteFontFace* fontFace,
290 const unsigned glyphCount,
291 SkTDArray<SkUnichar>* glyphToUnicode) {
292 HRESULT hr = S_OK;
293
294 //Do this like free type instead
bungemandf2ec352014-08-20 12:21:32 -0700295 SkAutoTMalloc<SkUnichar> glyphToUni(glyphCount);
296 int maxGlyph = -1;
bungeman51daa252014-06-05 13:38:45 -0700297 for (UINT32 c = 0; c < 0x10FFFF; ++c) {
298 UINT16 glyph;
299 hr = fontFace->GetGlyphIndices(&c, 1, &glyph);
bungemandf2ec352014-08-20 12:21:32 -0700300 SkASSERT(glyph < glyphCount);
301 if (0 < glyph) {
302 maxGlyph = SkTMax(static_cast<int>(glyph), maxGlyph);
303 glyphToUni[glyph] = c;
bungeman51daa252014-06-05 13:38:45 -0700304 }
305 }
306
bungemandf2ec352014-08-20 12:21:32 -0700307 glyphToUnicode->swap(SkTDArray<SkUnichar>(glyphToUni, maxGlyph + 1));
bungeman51daa252014-06-05 13:38:45 -0700308}
309
310static bool getWidthAdvance(IDWriteFontFace* fontFace, int gId, int16_t* advance) {
311 SkASSERT(advance);
312
313 UINT16 glyphId = gId;
314 DWRITE_GLYPH_METRICS gm;
315 HRESULT hr = fontFace->GetDesignGlyphMetrics(&glyphId, 1, &gm);
316
317 if (FAILED(hr)) {
318 *advance = 0;
319 return false;
320 }
321
322 *advance = gm.advanceWidth;
323 return true;
324}
325
326SkAdvancedTypefaceMetrics* DWriteFontTypeface::onGetAdvancedTypefaceMetrics(
327 SkAdvancedTypefaceMetrics::PerGlyphInfo perGlyphInfo,
328 const uint32_t* glyphIDs,
329 uint32_t glyphIDsCount) const {
330
331 SkAdvancedTypefaceMetrics* info = NULL;
332
333 HRESULT hr = S_OK;
334
335 const unsigned glyphCount = fDWriteFontFace->GetGlyphCount();
336
337 DWRITE_FONT_METRICS dwfm;
338 fDWriteFontFace->GetMetrics(&dwfm);
339
340 info = new SkAdvancedTypefaceMetrics;
341 info->fEmSize = dwfm.designUnitsPerEm;
bungeman51daa252014-06-05 13:38:45 -0700342 info->fLastGlyphID = SkToU16(glyphCount - 1);
343 info->fStyle = 0;
vandebo0f9bad02014-06-19 11:05:39 -0700344 info->fFlags = SkAdvancedTypefaceMetrics::kEmpty_FontFlag;
bungeman51daa252014-06-05 13:38:45 -0700345
bungeman6d867d42014-06-17 10:48:04 -0700346 // SkAdvancedTypefaceMetrics::fFontName is in theory supposed to be
347 // the PostScript name of the font. However, due to the way it is currently
348 // used, it must actually be a family name.
bungeman51daa252014-06-05 13:38:45 -0700349 SkTScopedComPtr<IDWriteLocalizedStrings> familyNames;
bungeman51daa252014-06-05 13:38:45 -0700350 hr = fDWriteFontFamily->GetFamilyNames(&familyNames);
bungeman51daa252014-06-05 13:38:45 -0700351
352 UINT32 familyNameLength;
353 hr = familyNames->GetStringLength(0, &familyNameLength);
354
bungeman6d867d42014-06-17 10:48:04 -0700355 UINT32 size = familyNameLength+1;
bungeman51daa252014-06-05 13:38:45 -0700356 SkSMallocWCHAR wFamilyName(size);
357 hr = familyNames->GetString(0, wFamilyName.get(), size);
bungeman51daa252014-06-05 13:38:45 -0700358
359 hr = sk_wchar_to_skstring(wFamilyName.get(), &info->fFontName);
360
361 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kToUnicode_PerGlyphInfo) {
362 populate_glyph_to_unicode(fDWriteFontFace.get(), glyphCount, &(info->fGlyphToUnicode));
363 }
364
365 DWRITE_FONT_FACE_TYPE fontType = fDWriteFontFace->GetType();
366 if (fontType == DWRITE_FONT_FACE_TYPE_TRUETYPE ||
367 fontType == DWRITE_FONT_FACE_TYPE_TRUETYPE_COLLECTION) {
368 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
369 } else {
370 info->fType = SkAdvancedTypefaceMetrics::kOther_Font;
371 info->fItalicAngle = 0;
372 info->fAscent = dwfm.ascent;;
373 info->fDescent = dwfm.descent;
374 info->fStemV = 0;
375 info->fCapHeight = dwfm.capHeight;
376 info->fBBox = SkIRect::MakeEmpty();
377 return info;
378 }
379
380 AutoTDWriteTable<SkOTTableHead> headTable(fDWriteFontFace.get());
381 AutoTDWriteTable<SkOTTablePostScript> postTable(fDWriteFontFace.get());
382 AutoTDWriteTable<SkOTTableHorizontalHeader> hheaTable(fDWriteFontFace.get());
383 AutoTDWriteTable<SkOTTableOS2> os2Table(fDWriteFontFace.get());
384 if (!headTable.fExists || !postTable.fExists || !hheaTable.fExists || !os2Table.fExists) {
385 info->fItalicAngle = 0;
386 info->fAscent = dwfm.ascent;;
387 info->fDescent = dwfm.descent;
388 info->fStemV = 0;
389 info->fCapHeight = dwfm.capHeight;
390 info->fBBox = SkIRect::MakeEmpty();
391 return info;
392 }
393
394 //There exist CJK fonts which set the IsFixedPitch and Monospace bits,
395 //but have full width, latin half-width, and half-width kana.
396 bool fixedWidth = (postTable->isFixedPitch &&
397 (1 == SkEndian_SwapBE16(hheaTable->numberOfHMetrics)));
398 //Monospace
399 if (fixedWidth) {
400 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
401 }
402 //Italic
403 if (os2Table->version.v0.fsSelection.field.Italic) {
404 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
405 }
406 //Script
407 if (SkPanose::FamilyType::Script == os2Table->version.v0.panose.bFamilyType.value) {
408 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
409 //Serif
410 } else if (SkPanose::FamilyType::TextAndDisplay == os2Table->version.v0.panose.bFamilyType.value &&
411 SkPanose::Data::TextAndDisplay::SerifStyle::Triangle <= os2Table->version.v0.panose.data.textAndDisplay.bSerifStyle.value &&
412 SkPanose::Data::TextAndDisplay::SerifStyle::NoFit != os2Table->version.v0.panose.data.textAndDisplay.bSerifStyle.value) {
413 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
414 }
415
416 info->fItalicAngle = SkEndian_SwapBE32(postTable->italicAngle) >> 16;
417
418 info->fAscent = SkToS16(dwfm.ascent);
419 info->fDescent = SkToS16(dwfm.descent);
420 info->fCapHeight = SkToS16(dwfm.capHeight);
421
422 info->fBBox = SkIRect::MakeLTRB((int32_t)SkEndian_SwapBE16((uint16_t)headTable->xMin),
423 (int32_t)SkEndian_SwapBE16((uint16_t)headTable->yMax),
424 (int32_t)SkEndian_SwapBE16((uint16_t)headTable->xMax),
425 (int32_t)SkEndian_SwapBE16((uint16_t)headTable->yMin));
426
427 //TODO: is this even desired? It seems PDF only wants this value for Type1
428 //fonts, and we only get here for TrueType fonts.
429 info->fStemV = 0;
430 /*
431 // Figure out a good guess for StemV - Min width of i, I, !, 1.
432 // This probably isn't very good with an italic font.
433 int16_t min_width = SHRT_MAX;
434 info->fStemV = 0;
435 char stem_chars[] = {'i', 'I', '!', '1'};
436 for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
437 ABC abcWidths;
438 if (GetCharABCWidths(hdc, stem_chars[i], stem_chars[i], &abcWidths)) {
439 int16_t width = abcWidths.abcB;
440 if (width > 0 && width < min_width) {
441 min_width = width;
442 info->fStemV = min_width;
443 }
444 }
445 }
446 */
447
vandebo0f9bad02014-06-19 11:05:39 -0700448 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo) {
bungeman51daa252014-06-05 13:38:45 -0700449 if (fixedWidth) {
450 appendRange(&info->fGlyphWidths, 0);
451 int16_t advance;
452 getWidthAdvance(fDWriteFontFace.get(), 1, &advance);
453 info->fGlyphWidths->fAdvance.append(1, &advance);
454 finishRange(info->fGlyphWidths.get(), 0,
455 SkAdvancedTypefaceMetrics::WidthRange::kDefault);
456 } else {
457 info->fGlyphWidths.reset(
458 getAdvanceData(fDWriteFontFace.get(),
459 glyphCount,
460 glyphIDs,
461 glyphIDsCount,
462 getWidthAdvance));
463 }
464 }
465
466 return info;
467}