blob: 9c2b41d44cddecf8482caee211cfe6ec2e5d6c14 [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
bungemanb374d6a2014-09-17 07:48:59 -070015#include "SkDWrite.h"
bungeman51daa252014-06-05 13:38:45 -070016#include "SkDWriteFontFileStream.h"
17#include "SkFontDescriptor.h"
18#include "SkFontStream.h"
19#include "SkOTTable_head.h"
20#include "SkOTTable_hhea.h"
21#include "SkOTTable_OS_2.h"
22#include "SkOTTable_post.h"
23#include "SkScalerContext.h"
24#include "SkScalerContext_win_dw.h"
25#include "SkTypeface_win_dw.h"
bungeman51daa252014-06-05 13:38:45 -070026#include "SkUtils.h"
27
bungemanb374d6a2014-09-17 07:48:59 -070028void DWriteFontTypeface::onGetFamilyName(SkString* familyName) const {
29 SkTScopedComPtr<IDWriteLocalizedStrings> familyNames;
30 HRV(fDWriteFontFamily->GetFamilyNames(&familyNames));
31
32 sk_get_locale_string(familyNames.get(), NULL/*fMgr->fLocaleName.get()*/, familyName);
33}
34
bungeman51daa252014-06-05 13:38:45 -070035void DWriteFontTypeface::onGetFontDescriptor(SkFontDescriptor* desc,
36 bool* isLocalStream) const {
37 // Get the family name.
bungeman5e7b4f92014-08-25 10:16:01 -070038 SkTScopedComPtr<IDWriteLocalizedStrings> familyNames;
39 HRV(fDWriteFontFamily->GetFamilyNames(&familyNames));
bungeman51daa252014-06-05 13:38:45 -070040
bungeman51daa252014-06-05 13:38:45 -070041 SkString utf8FamilyName;
bungemanb374d6a2014-09-17 07:48:59 -070042 sk_get_locale_string(familyNames.get(), NULL/*fMgr->fLocaleName.get()*/, &utf8FamilyName);
bungeman51daa252014-06-05 13:38:45 -070043
44 desc->setFamilyName(utf8FamilyName.c_str());
45 *isLocalStream = SkToBool(fDWriteFontFileLoader.get());
46}
47
48static SkUnichar next_utf8(const void** chars) {
49 return SkUTF8_NextUnichar((const char**)chars);
50}
51
52static SkUnichar next_utf16(const void** chars) {
53 return SkUTF16_NextUnichar((const uint16_t**)chars);
54}
55
56static SkUnichar next_utf32(const void** chars) {
57 const SkUnichar** uniChars = (const SkUnichar**)chars;
58 SkUnichar uni = **uniChars;
59 *uniChars += 1;
60 return uni;
61}
62
63typedef SkUnichar (*EncodingProc)(const void**);
64
65static EncodingProc find_encoding_proc(SkTypeface::Encoding enc) {
66 static const EncodingProc gProcs[] = {
67 next_utf8, next_utf16, next_utf32
68 };
69 SkASSERT((size_t)enc < SK_ARRAY_COUNT(gProcs));
70 return gProcs[enc];
71}
72
73int DWriteFontTypeface::onCharsToGlyphs(const void* chars, Encoding encoding,
74 uint16_t glyphs[], int glyphCount) const
75{
76 if (NULL == glyphs) {
77 EncodingProc next_ucs4_proc = find_encoding_proc(encoding);
78 for (int i = 0; i < glyphCount; ++i) {
79 const SkUnichar c = next_ucs4_proc(&chars);
80 BOOL exists;
81 fDWriteFont->HasCharacter(c, &exists);
82 if (!exists) {
83 return i;
84 }
85 }
86 return glyphCount;
87 }
88
89 switch (encoding) {
90 case SkTypeface::kUTF8_Encoding:
91 case SkTypeface::kUTF16_Encoding: {
92 static const int scratchCount = 256;
93 UINT32 scratch[scratchCount];
94 EncodingProc next_ucs4_proc = find_encoding_proc(encoding);
95 for (int baseGlyph = 0; baseGlyph < glyphCount; baseGlyph += scratchCount) {
96 int glyphsLeft = glyphCount - baseGlyph;
97 int limit = SkTMin(glyphsLeft, scratchCount);
98 for (int i = 0; i < limit; ++i) {
99 scratch[i] = next_ucs4_proc(&chars);
100 }
101 fDWriteFontFace->GetGlyphIndices(scratch, limit, &glyphs[baseGlyph]);
102 }
103 break;
104 }
105 case SkTypeface::kUTF32_Encoding: {
106 const UINT32* utf32 = reinterpret_cast<const UINT32*>(chars);
107 fDWriteFontFace->GetGlyphIndices(utf32, glyphCount, glyphs);
108 break;
109 }
110 default:
111 SK_CRASH();
112 }
113
114 for (int i = 0; i < glyphCount; ++i) {
115 if (0 == glyphs[i]) {
116 return i;
117 }
118 }
119 return glyphCount;
120}
121
122int DWriteFontTypeface::onCountGlyphs() const {
123 return fDWriteFontFace->GetGlyphCount();
124}
125
126int DWriteFontTypeface::onGetUPEM() const {
127 DWRITE_FONT_METRICS metrics;
128 fDWriteFontFace->GetMetrics(&metrics);
129 return metrics.designUnitsPerEm;
130}
131
132class LocalizedStrings_IDWriteLocalizedStrings : public SkTypeface::LocalizedStrings {
133public:
134 /** Takes ownership of the IDWriteLocalizedStrings. */
135 explicit LocalizedStrings_IDWriteLocalizedStrings(IDWriteLocalizedStrings* strings)
136 : fIndex(0), fStrings(strings)
137 { }
138
139 virtual bool next(SkTypeface::LocalizedString* localizedString) SK_OVERRIDE {
140 if (fIndex >= fStrings->GetCount()) {
141 return false;
142 }
143
144 // String
bungeman5e7b4f92014-08-25 10:16:01 -0700145 UINT32 stringLen;
146 HRBM(fStrings->GetStringLength(fIndex, &stringLen), "Could not get string length.");
bungeman51daa252014-06-05 13:38:45 -0700147
bungeman5e7b4f92014-08-25 10:16:01 -0700148 SkSMallocWCHAR wString(stringLen+1);
149 HRBM(fStrings->GetString(fIndex, wString.get(), stringLen+1), "Could not get string.");
bungeman51daa252014-06-05 13:38:45 -0700150
bungeman5e7b4f92014-08-25 10:16:01 -0700151 HRB(sk_wchar_to_skstring(wString.get(), stringLen, &localizedString->fString));
bungeman51daa252014-06-05 13:38:45 -0700152
153 // Locale
bungeman5e7b4f92014-08-25 10:16:01 -0700154 UINT32 localeLen;
155 HRBM(fStrings->GetLocaleNameLength(fIndex, &localeLen), "Could not get locale length.");
bungeman51daa252014-06-05 13:38:45 -0700156
bungeman5e7b4f92014-08-25 10:16:01 -0700157 SkSMallocWCHAR wLocale(localeLen+1);
158 HRBM(fStrings->GetLocaleName(fIndex, wLocale.get(), localeLen+1), "Could not get locale.");
bungeman51daa252014-06-05 13:38:45 -0700159
bungeman5e7b4f92014-08-25 10:16:01 -0700160 HRB(sk_wchar_to_skstring(wLocale.get(), localeLen, &localizedString->fLanguage));
bungeman51daa252014-06-05 13:38:45 -0700161
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);
bsalomon49f085d2014-09-05 13:34:00 -0700204 if (data) {
bungeman51daa252014-06-05 13:38:45 -0700205 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
bungemanaace9972014-08-25 07:14:02 -0700307 SkTDArray<SkUnichar>(glyphToUni, maxGlyph + 1).swap(*glyphToUnicode);
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
bungeman5e7b4f92014-08-25 10:16:01 -0700352 UINT32 familyNameLen;
353 hr = familyNames->GetStringLength(0, &familyNameLen);
bungeman51daa252014-06-05 13:38:45 -0700354
bungeman5e7b4f92014-08-25 10:16:01 -0700355 SkSMallocWCHAR familyName(familyNameLen+1);
356 hr = familyNames->GetString(0, familyName.get(), familyNameLen+1);
bungeman51daa252014-06-05 13:38:45 -0700357
bungeman5e7b4f92014-08-25 10:16:01 -0700358 hr = sk_wchar_to_skstring(familyName.get(), familyNameLen, &info->fFontName);
bungeman51daa252014-06-05 13:38:45 -0700359
360 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kToUnicode_PerGlyphInfo) {
361 populate_glyph_to_unicode(fDWriteFontFace.get(), glyphCount, &(info->fGlyphToUnicode));
362 }
363
364 DWRITE_FONT_FACE_TYPE fontType = fDWriteFontFace->GetType();
365 if (fontType == DWRITE_FONT_FACE_TYPE_TRUETYPE ||
366 fontType == DWRITE_FONT_FACE_TYPE_TRUETYPE_COLLECTION) {
367 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
368 } else {
369 info->fType = SkAdvancedTypefaceMetrics::kOther_Font;
370 info->fItalicAngle = 0;
371 info->fAscent = dwfm.ascent;;
372 info->fDescent = dwfm.descent;
373 info->fStemV = 0;
374 info->fCapHeight = dwfm.capHeight;
375 info->fBBox = SkIRect::MakeEmpty();
376 return info;
377 }
378
379 AutoTDWriteTable<SkOTTableHead> headTable(fDWriteFontFace.get());
380 AutoTDWriteTable<SkOTTablePostScript> postTable(fDWriteFontFace.get());
381 AutoTDWriteTable<SkOTTableHorizontalHeader> hheaTable(fDWriteFontFace.get());
382 AutoTDWriteTable<SkOTTableOS2> os2Table(fDWriteFontFace.get());
383 if (!headTable.fExists || !postTable.fExists || !hheaTable.fExists || !os2Table.fExists) {
384 info->fItalicAngle = 0;
385 info->fAscent = dwfm.ascent;;
386 info->fDescent = dwfm.descent;
387 info->fStemV = 0;
388 info->fCapHeight = dwfm.capHeight;
389 info->fBBox = SkIRect::MakeEmpty();
390 return info;
391 }
392
393 //There exist CJK fonts which set the IsFixedPitch and Monospace bits,
394 //but have full width, latin half-width, and half-width kana.
395 bool fixedWidth = (postTable->isFixedPitch &&
396 (1 == SkEndian_SwapBE16(hheaTable->numberOfHMetrics)));
397 //Monospace
398 if (fixedWidth) {
399 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
400 }
401 //Italic
402 if (os2Table->version.v0.fsSelection.field.Italic) {
403 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
404 }
405 //Script
406 if (SkPanose::FamilyType::Script == os2Table->version.v0.panose.bFamilyType.value) {
407 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
408 //Serif
409 } else if (SkPanose::FamilyType::TextAndDisplay == os2Table->version.v0.panose.bFamilyType.value &&
410 SkPanose::Data::TextAndDisplay::SerifStyle::Triangle <= os2Table->version.v0.panose.data.textAndDisplay.bSerifStyle.value &&
411 SkPanose::Data::TextAndDisplay::SerifStyle::NoFit != os2Table->version.v0.panose.data.textAndDisplay.bSerifStyle.value) {
412 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
413 }
414
415 info->fItalicAngle = SkEndian_SwapBE32(postTable->italicAngle) >> 16;
416
417 info->fAscent = SkToS16(dwfm.ascent);
418 info->fDescent = SkToS16(dwfm.descent);
419 info->fCapHeight = SkToS16(dwfm.capHeight);
420
421 info->fBBox = SkIRect::MakeLTRB((int32_t)SkEndian_SwapBE16((uint16_t)headTable->xMin),
422 (int32_t)SkEndian_SwapBE16((uint16_t)headTable->yMax),
423 (int32_t)SkEndian_SwapBE16((uint16_t)headTable->xMax),
424 (int32_t)SkEndian_SwapBE16((uint16_t)headTable->yMin));
425
426 //TODO: is this even desired? It seems PDF only wants this value for Type1
427 //fonts, and we only get here for TrueType fonts.
428 info->fStemV = 0;
429 /*
430 // Figure out a good guess for StemV - Min width of i, I, !, 1.
431 // This probably isn't very good with an italic font.
432 int16_t min_width = SHRT_MAX;
433 info->fStemV = 0;
434 char stem_chars[] = {'i', 'I', '!', '1'};
435 for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
436 ABC abcWidths;
437 if (GetCharABCWidths(hdc, stem_chars[i], stem_chars[i], &abcWidths)) {
438 int16_t width = abcWidths.abcB;
439 if (width > 0 && width < min_width) {
440 min_width = width;
441 info->fStemV = min_width;
442 }
443 }
444 }
445 */
446
vandebo0f9bad02014-06-19 11:05:39 -0700447 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo) {
bungeman51daa252014-06-05 13:38:45 -0700448 if (fixedWidth) {
449 appendRange(&info->fGlyphWidths, 0);
450 int16_t advance;
451 getWidthAdvance(fDWriteFontFace.get(), 1, &advance);
452 info->fGlyphWidths->fAdvance.append(1, &advance);
453 finishRange(info->fGlyphWidths.get(), 0,
454 SkAdvancedTypefaceMetrics::WidthRange::kDefault);
455 } else {
456 info->fGlyphWidths.reset(
457 getAdvanceData(fDWriteFontFace.get(),
458 glyphCount,
459 glyphIDs,
460 glyphIDsCount,
461 getWidthAdvance));
462 }
463 }
464
465 return info;
466}