michael@0: michael@0: /* michael@0: * Copyright 2006 The Android Open Source Project michael@0: * michael@0: * Use of this source code is governed by a BSD-style license that can be michael@0: * found in the LICENSE file. michael@0: */ michael@0: michael@0: #include "SkAdvancedTypefaceMetrics.h" michael@0: #include "SkBase64.h" michael@0: #include "SkColorPriv.h" michael@0: #include "SkData.h" michael@0: #include "SkDescriptor.h" michael@0: #include "SkFontDescriptor.h" michael@0: #include "SkFontHost.h" michael@0: #include "SkGlyph.h" michael@0: #include "SkHRESULT.h" michael@0: #include "SkMaskGamma.h" michael@0: #include "SkOTTable_maxp.h" michael@0: #include "SkOTTable_name.h" michael@0: #include "SkOTUtils.h" michael@0: #include "SkPath.h" michael@0: #include "SkSFNTHeader.h" michael@0: #include "SkStream.h" michael@0: #include "SkString.h" michael@0: #include "SkTemplates.h" michael@0: #include "SkThread.h" michael@0: #include "SkTypeface_win.h" michael@0: #include "SkTypefaceCache.h" michael@0: #include "SkUtils.h" michael@0: michael@0: #include "SkTypes.h" michael@0: #include michael@0: #include michael@0: #include michael@0: michael@0: static void (*gEnsureLOGFONTAccessibleProc)(const LOGFONT&); michael@0: michael@0: void SkTypeface_SetEnsureLOGFONTAccessibleProc(void (*proc)(const LOGFONT&)) { michael@0: gEnsureLOGFONTAccessibleProc = proc; michael@0: } michael@0: michael@0: static void call_ensure_accessible(const LOGFONT& lf) { michael@0: if (gEnsureLOGFONTAccessibleProc) { michael@0: gEnsureLOGFONTAccessibleProc(lf); michael@0: } michael@0: } michael@0: michael@0: /////////////////////////////////////////////////////////////////////////////// michael@0: michael@0: // always packed xxRRGGBB michael@0: typedef uint32_t SkGdiRGB; michael@0: michael@0: // define this in your Makefile or .gyp to enforce AA requests michael@0: // which GDI ignores at small sizes. This flag guarantees AA michael@0: // for rotated text, regardless of GDI's notions. michael@0: //#define SK_ENFORCE_ROTATED_TEXT_AA_ON_WINDOWS michael@0: michael@0: static bool isLCD(const SkScalerContext::Rec& rec) { michael@0: return SkMask::kLCD16_Format == rec.fMaskFormat || michael@0: SkMask::kLCD32_Format == rec.fMaskFormat; michael@0: } michael@0: michael@0: static bool bothZero(SkScalar a, SkScalar b) { michael@0: return 0 == a && 0 == b; michael@0: } michael@0: michael@0: // returns false if there is any non-90-rotation or skew michael@0: static bool isAxisAligned(const SkScalerContext::Rec& rec) { michael@0: return 0 == rec.fPreSkewX && michael@0: (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) || michael@0: bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1])); michael@0: } michael@0: michael@0: static bool needToRenderWithSkia(const SkScalerContext::Rec& rec) { michael@0: #ifdef SK_ENFORCE_ROTATED_TEXT_AA_ON_WINDOWS michael@0: // What we really want to catch is when GDI will ignore the AA request and give michael@0: // us BW instead. Smallish rotated text is one heuristic, so this code is just michael@0: // an approximation. We shouldn't need to do this for larger sizes, but at those michael@0: // sizes, the quality difference gets less and less between our general michael@0: // scanconverter and GDI's. michael@0: if (SkMask::kA8_Format == rec.fMaskFormat && !isAxisAligned(rec)) { michael@0: return true; michael@0: } michael@0: #endif michael@0: return rec.getHinting() == SkPaint::kNo_Hinting || rec.getHinting() == SkPaint::kSlight_Hinting; michael@0: } michael@0: michael@0: using namespace skia_advanced_typeface_metrics_utils; michael@0: michael@0: static void tchar_to_skstring(const TCHAR t[], SkString* s) { michael@0: #ifdef UNICODE michael@0: size_t sSize = WideCharToMultiByte(CP_UTF8, 0, t, -1, NULL, 0, NULL, NULL); michael@0: s->resize(sSize); michael@0: WideCharToMultiByte(CP_UTF8, 0, t, -1, s->writable_str(), sSize, NULL, NULL); michael@0: #else michael@0: s->set(t); michael@0: #endif michael@0: } michael@0: michael@0: static void dcfontname_to_skstring(HDC deviceContext, const LOGFONT& lf, SkString* familyName) { michael@0: int fontNameLen; //length of fontName in TCHARS. michael@0: if (0 == (fontNameLen = GetTextFace(deviceContext, 0, NULL))) { michael@0: call_ensure_accessible(lf); michael@0: if (0 == (fontNameLen = GetTextFace(deviceContext, 0, NULL))) { michael@0: fontNameLen = 0; michael@0: } michael@0: } michael@0: michael@0: SkAutoSTArray fontName(fontNameLen+1); michael@0: if (0 == GetTextFace(deviceContext, fontNameLen, fontName.get())) { michael@0: call_ensure_accessible(lf); michael@0: if (0 == GetTextFace(deviceContext, fontNameLen, fontName.get())) { michael@0: fontName[0] = 0; michael@0: } michael@0: } michael@0: michael@0: tchar_to_skstring(fontName.get(), familyName); michael@0: } michael@0: michael@0: static void make_canonical(LOGFONT* lf) { michael@0: lf->lfHeight = -64; michael@0: lf->lfQuality = CLEARTYPE_QUALITY;//PROOF_QUALITY; michael@0: lf->lfCharSet = DEFAULT_CHARSET; michael@0: // lf->lfClipPrecision = 64; michael@0: } michael@0: michael@0: static SkTypeface::Style get_style(const LOGFONT& lf) { michael@0: unsigned style = 0; michael@0: if (lf.lfWeight >= FW_BOLD) { michael@0: style |= SkTypeface::kBold; michael@0: } michael@0: if (lf.lfItalic) { michael@0: style |= SkTypeface::kItalic; michael@0: } michael@0: return static_cast(style); michael@0: } michael@0: michael@0: static void setStyle(LOGFONT* lf, SkTypeface::Style style) { michael@0: lf->lfWeight = (style & SkTypeface::kBold) != 0 ? FW_BOLD : FW_NORMAL ; michael@0: lf->lfItalic = ((style & SkTypeface::kItalic) != 0); michael@0: } michael@0: michael@0: static inline FIXED SkFixedToFIXED(SkFixed x) { michael@0: return *(FIXED*)(&x); michael@0: } michael@0: static inline SkFixed SkFIXEDToFixed(FIXED x) { michael@0: return *(SkFixed*)(&x); michael@0: } michael@0: michael@0: static inline FIXED SkScalarToFIXED(SkScalar x) { michael@0: return SkFixedToFIXED(SkScalarToFixed(x)); michael@0: } michael@0: michael@0: static inline SkScalar SkFIXEDToScalar(FIXED x) { michael@0: return SkFixedToScalar(SkFIXEDToFixed(x)); michael@0: } michael@0: michael@0: static unsigned calculateGlyphCount(HDC hdc, const LOGFONT& lf) { michael@0: TEXTMETRIC textMetric; michael@0: if (0 == GetTextMetrics(hdc, &textMetric)) { michael@0: textMetric.tmPitchAndFamily = TMPF_VECTOR; michael@0: call_ensure_accessible(lf); michael@0: GetTextMetrics(hdc, &textMetric); michael@0: } michael@0: michael@0: if (!(textMetric.tmPitchAndFamily & TMPF_VECTOR)) { michael@0: return textMetric.tmLastChar; michael@0: } michael@0: michael@0: // The 'maxp' table stores the number of glyphs at offset 4, in 2 bytes. michael@0: uint16_t glyphs; michael@0: if (GDI_ERROR != GetFontData(hdc, SkOTTableMaximumProfile::TAG, 4, &glyphs, sizeof(glyphs))) { michael@0: return SkEndian_SwapBE16(glyphs); michael@0: } michael@0: michael@0: // Binary search for glyph count. michael@0: static const MAT2 mat2 = {{0, 1}, {0, 0}, {0, 0}, {0, 1}}; michael@0: int32_t max = SK_MaxU16 + 1; michael@0: int32_t min = 0; michael@0: GLYPHMETRICS gm; michael@0: while (min < max) { michael@0: int32_t mid = min + ((max - min) / 2); michael@0: if (GetGlyphOutlineW(hdc, mid, GGO_METRICS | GGO_GLYPH_INDEX, &gm, 0, michael@0: NULL, &mat2) == GDI_ERROR) { michael@0: max = mid; michael@0: } else { michael@0: min = mid + 1; michael@0: } michael@0: } michael@0: SkASSERT(min == max); michael@0: return min; michael@0: } michael@0: michael@0: static unsigned calculateUPEM(HDC hdc, const LOGFONT& lf) { michael@0: TEXTMETRIC textMetric; michael@0: if (0 == GetTextMetrics(hdc, &textMetric)) { michael@0: textMetric.tmPitchAndFamily = TMPF_VECTOR; michael@0: call_ensure_accessible(lf); michael@0: GetTextMetrics(hdc, &textMetric); michael@0: } michael@0: michael@0: if (!(textMetric.tmPitchAndFamily & TMPF_VECTOR)) { michael@0: return textMetric.tmMaxCharWidth; michael@0: } michael@0: michael@0: OUTLINETEXTMETRIC otm; michael@0: unsigned int otmRet = GetOutlineTextMetrics(hdc, sizeof(otm), &otm); michael@0: if (0 == otmRet) { michael@0: call_ensure_accessible(lf); michael@0: otmRet = GetOutlineTextMetrics(hdc, sizeof(otm), &otm); michael@0: } michael@0: michael@0: return (0 == otmRet) ? 0 : otm.otmEMSquare; michael@0: } michael@0: michael@0: class LogFontTypeface : public SkTypeface { michael@0: public: michael@0: LogFontTypeface(SkTypeface::Style style, SkFontID fontID, const LOGFONT& lf, bool serializeAsStream = false) : michael@0: SkTypeface(style, fontID, false), fLogFont(lf), fSerializeAsStream(serializeAsStream) { michael@0: michael@0: // If the font has cubic outlines, it will not be rendered with ClearType. michael@0: HFONT font = CreateFontIndirect(&lf); michael@0: michael@0: HDC deviceContext = ::CreateCompatibleDC(NULL); michael@0: HFONT savefont = (HFONT)SelectObject(deviceContext, font); michael@0: michael@0: TEXTMETRIC textMetric; michael@0: if (0 == GetTextMetrics(deviceContext, &textMetric)) { michael@0: call_ensure_accessible(lf); michael@0: if (0 == GetTextMetrics(deviceContext, &textMetric)) { michael@0: textMetric.tmPitchAndFamily = TMPF_TRUETYPE; michael@0: } michael@0: } michael@0: if (deviceContext) { michael@0: ::SelectObject(deviceContext, savefont); michael@0: ::DeleteDC(deviceContext); michael@0: } michael@0: if (font) { michael@0: ::DeleteObject(font); michael@0: } michael@0: michael@0: // The fixed pitch bit is set if the font is *not* fixed pitch. michael@0: this->setIsFixedPitch((textMetric.tmPitchAndFamily & TMPF_FIXED_PITCH) == 0); michael@0: michael@0: // Used a logfont on a memory context, should never get a device font. michael@0: // Therefore all TMPF_DEVICE will be PostScript (cubic) fonts. michael@0: fCanBeLCD = !((textMetric.tmPitchAndFamily & TMPF_VECTOR) && michael@0: (textMetric.tmPitchAndFamily & TMPF_DEVICE)); michael@0: } michael@0: michael@0: LOGFONT fLogFont; michael@0: bool fSerializeAsStream; michael@0: bool fCanBeLCD; michael@0: michael@0: static LogFontTypeface* Create(const LOGFONT& lf) { michael@0: SkTypeface::Style style = get_style(lf); michael@0: SkFontID fontID = SkTypefaceCache::NewFontID(); michael@0: return new LogFontTypeface(style, fontID, lf); michael@0: } michael@0: michael@0: static void EnsureAccessible(const SkTypeface* face) { michael@0: call_ensure_accessible(static_cast(face)->fLogFont); michael@0: } michael@0: michael@0: protected: michael@0: virtual SkStream* onOpenStream(int* ttcIndex) const SK_OVERRIDE; michael@0: virtual SkScalerContext* onCreateScalerContext(const SkDescriptor*) const SK_OVERRIDE; michael@0: virtual void onFilterRec(SkScalerContextRec*) const SK_OVERRIDE; michael@0: virtual SkAdvancedTypefaceMetrics* onGetAdvancedTypefaceMetrics( michael@0: SkAdvancedTypefaceMetrics::PerGlyphInfo, michael@0: const uint32_t*, uint32_t) const SK_OVERRIDE; michael@0: virtual void onGetFontDescriptor(SkFontDescriptor*, bool*) const SK_OVERRIDE; michael@0: virtual int onCharsToGlyphs(const void* chars, Encoding encoding, michael@0: uint16_t glyphs[], int glyphCount) const SK_OVERRIDE; michael@0: virtual int onCountGlyphs() const SK_OVERRIDE; michael@0: virtual int onGetUPEM() const SK_OVERRIDE; michael@0: virtual SkTypeface::LocalizedStrings* onCreateFamilyNameIterator() const SK_OVERRIDE; michael@0: virtual int onGetTableTags(SkFontTableTag tags[]) const SK_OVERRIDE; michael@0: virtual size_t onGetTableData(SkFontTableTag, size_t offset, michael@0: size_t length, void* data) const SK_OVERRIDE; michael@0: }; michael@0: michael@0: class FontMemResourceTypeface : public LogFontTypeface { michael@0: public: michael@0: /** michael@0: * Takes ownership of fontMemResource. michael@0: */ michael@0: FontMemResourceTypeface(SkTypeface::Style style, SkFontID fontID, const LOGFONT& lf, HANDLE fontMemResource) : michael@0: LogFontTypeface(style, fontID, lf, true), fFontMemResource(fontMemResource) { michael@0: } michael@0: michael@0: HANDLE fFontMemResource; michael@0: michael@0: /** michael@0: * The created FontMemResourceTypeface takes ownership of fontMemResource. michael@0: */ michael@0: static FontMemResourceTypeface* Create(const LOGFONT& lf, HANDLE fontMemResource) { michael@0: SkTypeface::Style style = get_style(lf); michael@0: SkFontID fontID = SkTypefaceCache::NewFontID(); michael@0: return new FontMemResourceTypeface(style, fontID, lf, fontMemResource); michael@0: } michael@0: michael@0: protected: michael@0: virtual void weak_dispose() const SK_OVERRIDE { michael@0: RemoveFontMemResourceEx(fFontMemResource); michael@0: //SkTypefaceCache::Remove(this); michael@0: INHERITED::weak_dispose(); michael@0: } michael@0: michael@0: private: michael@0: typedef LogFontTypeface INHERITED; michael@0: }; michael@0: michael@0: static const LOGFONT& get_default_font() { michael@0: static LOGFONT gDefaultFont; michael@0: return gDefaultFont; michael@0: } michael@0: michael@0: static bool FindByLogFont(SkTypeface* face, SkTypeface::Style requestedStyle, void* ctx) { michael@0: LogFontTypeface* lface = static_cast(face); michael@0: const LOGFONT* lf = reinterpret_cast(ctx); michael@0: michael@0: return lface && michael@0: get_style(lface->fLogFont) == requestedStyle && michael@0: !memcmp(&lface->fLogFont, lf, sizeof(LOGFONT)); michael@0: } michael@0: michael@0: /** michael@0: * This guy is public. It first searches the cache, and if a match is not found, michael@0: * it creates a new face. michael@0: */ michael@0: SkTypeface* SkCreateTypefaceFromLOGFONT(const LOGFONT& origLF) { michael@0: LOGFONT lf = origLF; michael@0: make_canonical(&lf); michael@0: SkTypeface* face = SkTypefaceCache::FindByProcAndRef(FindByLogFont, &lf); michael@0: if (NULL == face) { michael@0: face = LogFontTypeface::Create(lf); michael@0: SkTypefaceCache::Add(face, get_style(lf)); michael@0: } michael@0: return face; michael@0: } michael@0: michael@0: /** michael@0: * The created SkTypeface takes ownership of fontMemResource. michael@0: */ michael@0: SkTypeface* SkCreateFontMemResourceTypefaceFromLOGFONT(const LOGFONT& origLF, HANDLE fontMemResource) { michael@0: LOGFONT lf = origLF; michael@0: make_canonical(&lf); michael@0: FontMemResourceTypeface* face = FontMemResourceTypeface::Create(lf, fontMemResource); michael@0: SkTypefaceCache::Add(face, get_style(lf), false); michael@0: return face; michael@0: } michael@0: michael@0: /** michael@0: * This guy is public michael@0: */ michael@0: void SkLOGFONTFromTypeface(const SkTypeface* face, LOGFONT* lf) { michael@0: if (NULL == face) { michael@0: *lf = get_default_font(); michael@0: } else { michael@0: *lf = static_cast(face)->fLogFont; michael@0: } michael@0: } michael@0: michael@0: // Construct Glyph to Unicode table. michael@0: // Unicode code points that require conjugate pairs in utf16 are not michael@0: // supported. michael@0: // TODO(arthurhsu): Add support for conjugate pairs. It looks like that may michael@0: // require parsing the TTF cmap table (platform 4, encoding 12) directly instead michael@0: // of calling GetFontUnicodeRange(). michael@0: static void populate_glyph_to_unicode(HDC fontHdc, const unsigned glyphCount, michael@0: SkTDArray* glyphToUnicode) { michael@0: DWORD glyphSetBufferSize = GetFontUnicodeRanges(fontHdc, NULL); michael@0: if (!glyphSetBufferSize) { michael@0: return; michael@0: } michael@0: michael@0: SkAutoTDeleteArray glyphSetBuffer(new BYTE[glyphSetBufferSize]); michael@0: GLYPHSET* glyphSet = michael@0: reinterpret_cast(glyphSetBuffer.get()); michael@0: if (GetFontUnicodeRanges(fontHdc, glyphSet) != glyphSetBufferSize) { michael@0: return; michael@0: } michael@0: michael@0: glyphToUnicode->setCount(glyphCount); michael@0: memset(glyphToUnicode->begin(), 0, glyphCount * sizeof(SkUnichar)); michael@0: for (DWORD i = 0; i < glyphSet->cRanges; ++i) { michael@0: // There is no guarantee that within a Unicode range, the corresponding michael@0: // glyph id in a font file are continuous. So, even if we have ranges, michael@0: // we can't just use the first and last entry of the range to compute michael@0: // result. We need to enumerate them one by one. michael@0: int count = glyphSet->ranges[i].cGlyphs; michael@0: SkAutoTArray chars(count + 1); michael@0: chars[count] = 0; // termintate string michael@0: SkAutoTArray glyph(count); michael@0: for (USHORT j = 0; j < count; ++j) { michael@0: chars[j] = glyphSet->ranges[i].wcLow + j; michael@0: } michael@0: GetGlyphIndicesW(fontHdc, chars.get(), count, glyph.get(), michael@0: GGI_MARK_NONEXISTING_GLYPHS); michael@0: // If the glyph ID is valid, and the glyph is not mapped, then we will michael@0: // fill in the char id into the vector. If the glyph is mapped already, michael@0: // skip it. michael@0: // TODO(arthurhsu): better improve this. e.g. Get all used char ids from michael@0: // font cache, then generate this mapping table from there. It's michael@0: // unlikely to have collisions since glyph reuse happens mostly for michael@0: // different Unicode pages. michael@0: for (USHORT j = 0; j < count; ++j) { michael@0: if (glyph[j] != 0xffff && glyph[j] < glyphCount && michael@0: (*glyphToUnicode)[glyph[j]] == 0) { michael@0: (*glyphToUnicode)[glyph[j]] = chars[j]; michael@0: } michael@0: } michael@0: } michael@0: } michael@0: michael@0: ////////////////////////////////////////////////////////////////////////////////////// michael@0: michael@0: static int alignTo32(int n) { michael@0: return (n + 31) & ~31; michael@0: } michael@0: michael@0: struct MyBitmapInfo : public BITMAPINFO { michael@0: RGBQUAD fMoreSpaceForColors[1]; michael@0: }; michael@0: michael@0: class HDCOffscreen { michael@0: public: michael@0: HDCOffscreen() { michael@0: fFont = 0; michael@0: fDC = 0; michael@0: fBM = 0; michael@0: fBits = NULL; michael@0: fWidth = fHeight = 0; michael@0: fIsBW = false; michael@0: } michael@0: michael@0: ~HDCOffscreen() { michael@0: if (fDC) { michael@0: DeleteDC(fDC); michael@0: } michael@0: if (fBM) { michael@0: DeleteObject(fBM); michael@0: } michael@0: } michael@0: michael@0: void init(HFONT font, const XFORM& xform) { michael@0: fFont = font; michael@0: fXform = xform; michael@0: } michael@0: michael@0: const void* draw(const SkGlyph&, bool isBW, size_t* srcRBPtr); michael@0: michael@0: private: michael@0: HDC fDC; michael@0: HBITMAP fBM; michael@0: HFONT fFont; michael@0: XFORM fXform; michael@0: void* fBits; // points into fBM michael@0: int fWidth; michael@0: int fHeight; michael@0: bool fIsBW; michael@0: }; michael@0: michael@0: const void* HDCOffscreen::draw(const SkGlyph& glyph, bool isBW, michael@0: size_t* srcRBPtr) { michael@0: // Can we share the scalercontext's fDDC, so we don't need to create michael@0: // a separate fDC here? michael@0: if (0 == fDC) { michael@0: fDC = CreateCompatibleDC(0); michael@0: if (0 == fDC) { michael@0: return NULL; michael@0: } michael@0: SetGraphicsMode(fDC, GM_ADVANCED); michael@0: SetBkMode(fDC, TRANSPARENT); michael@0: SetTextAlign(fDC, TA_LEFT | TA_BASELINE); michael@0: SelectObject(fDC, fFont); michael@0: michael@0: COLORREF color = 0x00FFFFFF; michael@0: SkDEBUGCODE(COLORREF prev =) SetTextColor(fDC, color); michael@0: SkASSERT(prev != CLR_INVALID); michael@0: } michael@0: michael@0: if (fBM && (fIsBW != isBW || fWidth < glyph.fWidth || fHeight < glyph.fHeight)) { michael@0: DeleteObject(fBM); michael@0: fBM = 0; michael@0: } michael@0: fIsBW = isBW; michael@0: michael@0: fWidth = SkMax32(fWidth, glyph.fWidth); michael@0: fHeight = SkMax32(fHeight, glyph.fHeight); michael@0: michael@0: int biWidth = isBW ? alignTo32(fWidth) : fWidth; michael@0: michael@0: if (0 == fBM) { michael@0: MyBitmapInfo info; michael@0: sk_bzero(&info, sizeof(info)); michael@0: if (isBW) { michael@0: RGBQUAD blackQuad = { 0, 0, 0, 0 }; michael@0: RGBQUAD whiteQuad = { 0xFF, 0xFF, 0xFF, 0 }; michael@0: info.bmiColors[0] = blackQuad; michael@0: info.bmiColors[1] = whiteQuad; michael@0: } michael@0: info.bmiHeader.biSize = sizeof(info.bmiHeader); michael@0: info.bmiHeader.biWidth = biWidth; michael@0: info.bmiHeader.biHeight = fHeight; michael@0: info.bmiHeader.biPlanes = 1; michael@0: info.bmiHeader.biBitCount = isBW ? 1 : 32; michael@0: info.bmiHeader.biCompression = BI_RGB; michael@0: if (isBW) { michael@0: info.bmiHeader.biClrUsed = 2; michael@0: } michael@0: fBM = CreateDIBSection(fDC, &info, DIB_RGB_COLORS, &fBits, 0, 0); michael@0: if (0 == fBM) { michael@0: return NULL; michael@0: } michael@0: SelectObject(fDC, fBM); michael@0: } michael@0: michael@0: // erase michael@0: size_t srcRB = isBW ? (biWidth >> 3) : (fWidth << 2); michael@0: size_t size = fHeight * srcRB; michael@0: memset(fBits, 0, size); michael@0: michael@0: XFORM xform = fXform; michael@0: xform.eDx = (float)-glyph.fLeft; michael@0: xform.eDy = (float)-glyph.fTop; michael@0: SetWorldTransform(fDC, &xform); michael@0: michael@0: uint16_t glyphID = glyph.getGlyphID(); michael@0: BOOL ret = ExtTextOutW(fDC, 0, 0, ETO_GLYPH_INDEX, NULL, reinterpret_cast(&glyphID), 1, NULL); michael@0: GdiFlush(); michael@0: if (0 == ret) { michael@0: return NULL; michael@0: } michael@0: *srcRBPtr = srcRB; michael@0: // offset to the start of the image michael@0: return (const char*)fBits + (fHeight - glyph.fHeight) * srcRB; michael@0: } michael@0: michael@0: ////////////////////////////////////////////////////////////////////////////// michael@0: #define BUFFERSIZE (1 << 13) michael@0: michael@0: class SkScalerContext_GDI : public SkScalerContext { michael@0: public: michael@0: SkScalerContext_GDI(SkTypeface*, const SkDescriptor* desc); michael@0: virtual ~SkScalerContext_GDI(); michael@0: michael@0: // Returns true if the constructor was able to complete all of its michael@0: // initializations (which may include calling GDI). michael@0: bool isValid() const; michael@0: michael@0: protected: michael@0: virtual unsigned generateGlyphCount() SK_OVERRIDE; michael@0: virtual uint16_t generateCharToGlyph(SkUnichar uni) SK_OVERRIDE; michael@0: virtual void generateAdvance(SkGlyph* glyph) SK_OVERRIDE; michael@0: virtual void generateMetrics(SkGlyph* glyph) SK_OVERRIDE; michael@0: virtual void generateImage(const SkGlyph& glyph) SK_OVERRIDE; michael@0: virtual void generatePath(const SkGlyph& glyph, SkPath* path) SK_OVERRIDE; michael@0: virtual void generateFontMetrics(SkPaint::FontMetrics* mX, michael@0: SkPaint::FontMetrics* mY) SK_OVERRIDE; michael@0: michael@0: private: michael@0: DWORD getGDIGlyphPath(const SkGlyph& glyph, UINT flags, michael@0: SkAutoSTMalloc* glyphbuf); michael@0: michael@0: HDCOffscreen fOffscreen; michael@0: /** fGsA is the non-rotational part of total matrix without the text height scale. michael@0: * Used to find the magnitude of advances. michael@0: */ michael@0: MAT2 fGsA; michael@0: /** The total matrix without the textSize. */ michael@0: MAT2 fMat22; michael@0: /** Scales font to EM size. */ michael@0: MAT2 fHighResMat22; michael@0: HDC fDDC; michael@0: HFONT fSavefont; michael@0: HFONT fFont; michael@0: SCRIPT_CACHE fSC; michael@0: int fGlyphCount; michael@0: michael@0: /** The total matrix which also removes EM scale. */ michael@0: SkMatrix fHiResMatrix; michael@0: /** fG_inv is the inverse of the rotational part of the total matrix. michael@0: * Used to set the direction of advances. michael@0: */ michael@0: SkMatrix fG_inv; michael@0: enum Type { michael@0: kTrueType_Type, kBitmap_Type, kLine_Type michael@0: } fType; michael@0: TEXTMETRIC fTM; michael@0: }; michael@0: michael@0: static FIXED float2FIXED(float x) { michael@0: return SkFixedToFIXED(SkFloatToFixed(x)); michael@0: } michael@0: michael@0: static BYTE compute_quality(const SkScalerContext::Rec& rec) { michael@0: switch (rec.fMaskFormat) { michael@0: case SkMask::kBW_Format: michael@0: return NONANTIALIASED_QUALITY; michael@0: case SkMask::kLCD16_Format: michael@0: case SkMask::kLCD32_Format: michael@0: return CLEARTYPE_QUALITY; michael@0: default: michael@0: if (rec.fFlags & SkScalerContext::kGenA8FromLCD_Flag) { michael@0: return CLEARTYPE_QUALITY; michael@0: } else { michael@0: return ANTIALIASED_QUALITY; michael@0: } michael@0: } michael@0: } michael@0: michael@0: SkScalerContext_GDI::SkScalerContext_GDI(SkTypeface* rawTypeface, michael@0: const SkDescriptor* desc) michael@0: : SkScalerContext(rawTypeface, desc) michael@0: , fDDC(0) michael@0: , fSavefont(0) michael@0: , fFont(0) michael@0: , fSC(0) michael@0: , fGlyphCount(-1) michael@0: { michael@0: LogFontTypeface* typeface = reinterpret_cast(rawTypeface); michael@0: michael@0: fDDC = ::CreateCompatibleDC(NULL); michael@0: if (!fDDC) { michael@0: return; michael@0: } michael@0: SetGraphicsMode(fDDC, GM_ADVANCED); michael@0: SetBkMode(fDDC, TRANSPARENT); michael@0: michael@0: SkPoint h = SkPoint::Make(SK_Scalar1, 0); michael@0: // A is the total matrix. michael@0: SkMatrix A; michael@0: fRec.getSingleMatrix(&A); michael@0: A.mapPoints(&h, 1); michael@0: michael@0: // Find the Given's matrix [[c, -s],[s, c]] which rotates the baseline vector h michael@0: // (where the baseline is mapped to) to the positive horizontal axis. michael@0: const SkScalar& a = h.fX; michael@0: const SkScalar& b = h.fY; michael@0: SkScalar c, s; michael@0: if (0 == b) { michael@0: c = SkDoubleToScalar(_copysign(SK_Scalar1, a)); michael@0: s = 0; michael@0: } else if (0 == a) { michael@0: c = 0; michael@0: s = SkDoubleToScalar(-_copysign(SK_Scalar1, b)); michael@0: } else if (SkScalarAbs(b) > SkScalarAbs(a)) { michael@0: SkScalar t = a / b; michael@0: SkScalar u = SkDoubleToScalar(_copysign(SkScalarSqrt(SK_Scalar1 + t*t), b)); michael@0: s = -1 / u; michael@0: c = -s * t; michael@0: } else { michael@0: SkScalar t = b / a; michael@0: SkScalar u = SkDoubleToScalar(_copysign(SkScalarSqrt(SK_Scalar1 + t*t), a)); michael@0: c = 1 / u; michael@0: s = -c * t; michael@0: } michael@0: michael@0: // G is the Given's Matrix for A (rotational matrix such that GA[0][1] == 0). michael@0: SkMatrix G; michael@0: G.setAll(c, -s, 0, michael@0: s, c, 0, michael@0: 0, 0, SkScalarToPersp(SK_Scalar1)); michael@0: michael@0: // GA is the matrix A with rotation removed. michael@0: SkMatrix GA(G); michael@0: GA.preConcat(A); michael@0: michael@0: // realTextSize is the actual device size we want (as opposed to the size the user requested). michael@0: // gdiTextSide is the size we request from GDI. michael@0: // If the scale is negative, this means the matrix will do the flip anyway. michael@0: SkScalar realTextSize = SkScalarAbs(GA.get(SkMatrix::kMScaleY)); michael@0: SkScalar gdiTextSize = SkScalarRoundToScalar(realTextSize); michael@0: if (gdiTextSize == 0) { michael@0: gdiTextSize = SK_Scalar1; michael@0: } michael@0: michael@0: // When not hinting, remove only the gdiTextSize scale which will be applied by GDI. michael@0: // When GDI hinting, remove the entire Y scale to prevent 'subpixel' metrics. michael@0: SkScalar scale = (fRec.getHinting() == SkPaint::kNo_Hinting || michael@0: fRec.getHinting() == SkPaint::kSlight_Hinting) michael@0: ? SkScalarInvert(gdiTextSize) michael@0: : SkScalarInvert(realTextSize); michael@0: michael@0: // sA is the total matrix A without the textSize (so GDI knows the text size separately). michael@0: // When this matrix is used with GetGlyphOutline, no further processing is needed. michael@0: SkMatrix sA(A); michael@0: sA.preScale(scale, scale); //remove text size michael@0: michael@0: // GsA is the non-rotational part of A without the text height scale. michael@0: // This is what is used to find the magnitude of advances. michael@0: SkMatrix GsA(GA); michael@0: GsA.preScale(scale, scale); //remove text size, G is rotational so reorders with the scale. michael@0: michael@0: fGsA.eM11 = SkScalarToFIXED(GsA.get(SkMatrix::kMScaleX)); michael@0: fGsA.eM12 = SkScalarToFIXED(-GsA.get(SkMatrix::kMSkewY)); // This should be ~0. michael@0: fGsA.eM21 = SkScalarToFIXED(-GsA.get(SkMatrix::kMSkewX)); michael@0: fGsA.eM22 = SkScalarToFIXED(GsA.get(SkMatrix::kMScaleY)); michael@0: michael@0: // fG_inv is G inverse, which is fairly simple since G is 2x2 rotational. michael@0: fG_inv.setAll(G.get(SkMatrix::kMScaleX), -G.get(SkMatrix::kMSkewX), G.get(SkMatrix::kMTransX), michael@0: -G.get(SkMatrix::kMSkewY), G.get(SkMatrix::kMScaleY), G.get(SkMatrix::kMTransY), michael@0: G.get(SkMatrix::kMPersp0), G.get(SkMatrix::kMPersp1), G.get(SkMatrix::kMPersp2)); michael@0: michael@0: LOGFONT lf = typeface->fLogFont; michael@0: lf.lfHeight = -SkScalarTruncToInt(gdiTextSize); michael@0: lf.lfQuality = compute_quality(fRec); michael@0: fFont = CreateFontIndirect(&lf); michael@0: if (!fFont) { michael@0: return; michael@0: } michael@0: michael@0: fSavefont = (HFONT)SelectObject(fDDC, fFont); michael@0: michael@0: if (0 == GetTextMetrics(fDDC, &fTM)) { michael@0: call_ensure_accessible(lf); michael@0: if (0 == GetTextMetrics(fDDC, &fTM)) { michael@0: fTM.tmPitchAndFamily = TMPF_TRUETYPE; michael@0: } michael@0: } michael@0: michael@0: XFORM xform; michael@0: if (fTM.tmPitchAndFamily & TMPF_VECTOR) { michael@0: // Used a logfont on a memory context, should never get a device font. michael@0: // Therefore all TMPF_DEVICE will be PostScript fonts. michael@0: michael@0: // If TMPF_VECTOR is set, one of TMPF_TRUETYPE or TMPF_DEVICE means that michael@0: // we have an outline font. Otherwise we have a vector FON, which is michael@0: // scalable, but not an outline font. michael@0: // This was determined by testing with Type1 PFM/PFB and michael@0: // OpenTypeCFF OTF, as well as looking at Wine bugs and sources. michael@0: if (fTM.tmPitchAndFamily & (TMPF_TRUETYPE | TMPF_DEVICE)) { michael@0: // Truetype or PostScript. michael@0: fType = SkScalerContext_GDI::kTrueType_Type; michael@0: } else { michael@0: // Stroked FON. michael@0: fType = SkScalerContext_GDI::kLine_Type; michael@0: } michael@0: michael@0: // fPost2x2 is column-major, left handed (y down). michael@0: // XFORM 2x2 is row-major, left handed (y down). michael@0: xform.eM11 = SkScalarToFloat(sA.get(SkMatrix::kMScaleX)); michael@0: xform.eM12 = SkScalarToFloat(sA.get(SkMatrix::kMSkewY)); michael@0: xform.eM21 = SkScalarToFloat(sA.get(SkMatrix::kMSkewX)); michael@0: xform.eM22 = SkScalarToFloat(sA.get(SkMatrix::kMScaleY)); michael@0: xform.eDx = 0; michael@0: xform.eDy = 0; michael@0: michael@0: // MAT2 is row major, right handed (y up). michael@0: fMat22.eM11 = float2FIXED(xform.eM11); michael@0: fMat22.eM12 = float2FIXED(-xform.eM12); michael@0: fMat22.eM21 = float2FIXED(-xform.eM21); michael@0: fMat22.eM22 = float2FIXED(xform.eM22); michael@0: michael@0: if (needToRenderWithSkia(fRec)) { michael@0: this->forceGenerateImageFromPath(); michael@0: } michael@0: michael@0: // Create a hires matrix if we need linear metrics. michael@0: if (this->isSubpixel()) { michael@0: OUTLINETEXTMETRIC otm; michael@0: UINT success = GetOutlineTextMetrics(fDDC, sizeof(otm), &otm); michael@0: if (0 == success) { michael@0: call_ensure_accessible(lf); michael@0: success = GetOutlineTextMetrics(fDDC, sizeof(otm), &otm); michael@0: } michael@0: if (0 != success) { michael@0: SkScalar upem = SkIntToScalar(otm.otmEMSquare); michael@0: michael@0: SkScalar gdiTextSizeToEMScale = upem / gdiTextSize; michael@0: fHighResMat22.eM11 = float2FIXED(gdiTextSizeToEMScale); michael@0: fHighResMat22.eM12 = float2FIXED(0); michael@0: fHighResMat22.eM21 = float2FIXED(0); michael@0: fHighResMat22.eM22 = float2FIXED(gdiTextSizeToEMScale); michael@0: michael@0: SkScalar removeEMScale = SkScalarInvert(upem); michael@0: fHiResMatrix = A; michael@0: fHiResMatrix.preScale(removeEMScale, removeEMScale); michael@0: } michael@0: } michael@0: michael@0: } else { michael@0: // Assume bitmap michael@0: fType = SkScalerContext_GDI::kBitmap_Type; michael@0: michael@0: xform.eM11 = 1.0f; michael@0: xform.eM12 = 0.0f; michael@0: xform.eM21 = 0.0f; michael@0: xform.eM22 = 1.0f; michael@0: xform.eDx = 0.0f; michael@0: xform.eDy = 0.0f; michael@0: michael@0: // fPost2x2 is column-major, left handed (y down). michael@0: // MAT2 is row major, right handed (y up). michael@0: fMat22.eM11 = SkScalarToFIXED(fRec.fPost2x2[0][0]); michael@0: fMat22.eM12 = SkScalarToFIXED(-fRec.fPost2x2[1][0]); michael@0: fMat22.eM21 = SkScalarToFIXED(-fRec.fPost2x2[0][1]); michael@0: fMat22.eM22 = SkScalarToFIXED(fRec.fPost2x2[1][1]); michael@0: } michael@0: michael@0: fOffscreen.init(fFont, xform); michael@0: } michael@0: michael@0: SkScalerContext_GDI::~SkScalerContext_GDI() { michael@0: if (fDDC) { michael@0: ::SelectObject(fDDC, fSavefont); michael@0: ::DeleteDC(fDDC); michael@0: } michael@0: if (fFont) { michael@0: ::DeleteObject(fFont); michael@0: } michael@0: if (fSC) { michael@0: ::ScriptFreeCache(&fSC); michael@0: } michael@0: } michael@0: michael@0: bool SkScalerContext_GDI::isValid() const { michael@0: return fDDC && fFont; michael@0: } michael@0: michael@0: unsigned SkScalerContext_GDI::generateGlyphCount() { michael@0: if (fGlyphCount < 0) { michael@0: fGlyphCount = calculateGlyphCount( michael@0: fDDC, static_cast(this->getTypeface())->fLogFont); michael@0: } michael@0: return fGlyphCount; michael@0: } michael@0: michael@0: uint16_t SkScalerContext_GDI::generateCharToGlyph(SkUnichar utf32) { michael@0: uint16_t index = 0; michael@0: WCHAR utf16[2]; michael@0: // TODO(ctguil): Support characters that generate more than one glyph. michael@0: if (SkUTF16_FromUnichar(utf32, (uint16_t*)utf16) == 1) { michael@0: // Type1 fonts fail with uniscribe API. Use GetGlyphIndices for plane 0. michael@0: michael@0: /** Real documentation for GetGlyphIndiciesW: michael@0: * michael@0: * When GGI_MARK_NONEXISTING_GLYPHS is not specified and a character does not map to a michael@0: * glyph, then the 'default character's glyph is returned instead. The 'default character' michael@0: * is available in fTM.tmDefaultChar. FON fonts have a default character, and there exists michael@0: * a usDefaultChar in the 'OS/2' table, version 2 and later. If there is no michael@0: * 'default character' specified by the font, then often the first character found is used. michael@0: * michael@0: * When GGI_MARK_NONEXISTING_GLYPHS is specified and a character does not map to a glyph, michael@0: * then the glyph 0xFFFF is used. In Windows XP and earlier, Bitmap/Vector FON usually use michael@0: * glyph 0x1F instead ('Terminal' appears to be special, returning 0xFFFF). michael@0: * Type1 PFM/PFB, TT, OT TT, OT CFF all appear to use 0xFFFF, even on XP. michael@0: */ michael@0: DWORD result = GetGlyphIndicesW(fDDC, utf16, 1, &index, GGI_MARK_NONEXISTING_GLYPHS); michael@0: if (result == GDI_ERROR michael@0: || 0xFFFF == index michael@0: || (0x1F == index && michael@0: (fType == SkScalerContext_GDI::kBitmap_Type || michael@0: fType == SkScalerContext_GDI::kLine_Type) michael@0: /*&& winVer < Vista */) michael@0: ) michael@0: { michael@0: index = 0; michael@0: } michael@0: } else { michael@0: // Use uniscribe to detemine glyph index for non-BMP characters. michael@0: static const int numWCHAR = 2; michael@0: static const int maxItems = 2; michael@0: // MSDN states that this can be NULL, but some things don't work then. michael@0: SCRIPT_CONTROL sc = { 0 }; michael@0: // Add extra item to SCRIPT_ITEM to work around a bug (now documented). michael@0: // https://bugzilla.mozilla.org/show_bug.cgi?id=366643 michael@0: SCRIPT_ITEM si[maxItems + 1]; michael@0: int numItems; michael@0: HRZM(ScriptItemize(utf16, numWCHAR, maxItems, &sc, NULL, si, &numItems), michael@0: "Could not itemize character."); michael@0: michael@0: // Sometimes ScriptShape cannot find a glyph for a non-BMP and returns 2 space glyphs. michael@0: static const int maxGlyphs = 2; michael@0: SCRIPT_VISATTR vsa[maxGlyphs]; michael@0: WORD outGlyphs[maxGlyphs]; michael@0: WORD logClust[numWCHAR]; michael@0: int numGlyphs; michael@0: HRZM(ScriptShape(fDDC, &fSC, utf16, numWCHAR, maxGlyphs, &si[0].a, michael@0: outGlyphs, logClust, vsa, &numGlyphs), michael@0: "Could not shape character."); michael@0: if (1 == numGlyphs) { michael@0: index = outGlyphs[0]; michael@0: } michael@0: } michael@0: return index; michael@0: } michael@0: michael@0: void SkScalerContext_GDI::generateAdvance(SkGlyph* glyph) { michael@0: this->generateMetrics(glyph); michael@0: } michael@0: michael@0: void SkScalerContext_GDI::generateMetrics(SkGlyph* glyph) { michael@0: SkASSERT(fDDC); michael@0: michael@0: if (fType == SkScalerContext_GDI::kBitmap_Type || fType == SkScalerContext_GDI::kLine_Type) { michael@0: SIZE size; michael@0: WORD glyphs = glyph->getGlyphID(0); michael@0: if (0 == GetTextExtentPointI(fDDC, &glyphs, 1, &size)) { michael@0: glyph->fWidth = SkToS16(fTM.tmMaxCharWidth); michael@0: } else { michael@0: glyph->fWidth = SkToS16(size.cx); michael@0: } michael@0: glyph->fHeight = SkToS16(size.cy); michael@0: michael@0: glyph->fTop = SkToS16(-fTM.tmAscent); michael@0: // Bitmap FON cannot underhang, but vector FON may. michael@0: // There appears no means of determining underhang of vector FON. michael@0: glyph->fLeft = SkToS16(0); michael@0: glyph->fAdvanceX = SkIntToFixed(glyph->fWidth); michael@0: glyph->fAdvanceY = 0; michael@0: michael@0: // Vector FON will transform nicely, but bitmap FON do not. michael@0: if (fType == SkScalerContext_GDI::kLine_Type) { michael@0: SkRect bounds = SkRect::MakeXYWH(glyph->fLeft, glyph->fTop, michael@0: glyph->fWidth, glyph->fHeight); michael@0: SkMatrix m; michael@0: m.setAll(SkFIXEDToScalar(fMat22.eM11), -SkFIXEDToScalar(fMat22.eM21), 0, michael@0: -SkFIXEDToScalar(fMat22.eM12), SkFIXEDToScalar(fMat22.eM22), 0, michael@0: 0, 0, SkScalarToPersp(SK_Scalar1)); michael@0: m.mapRect(&bounds); michael@0: bounds.roundOut(); michael@0: glyph->fLeft = SkScalarTruncToInt(bounds.fLeft); michael@0: glyph->fTop = SkScalarTruncToInt(bounds.fTop); michael@0: glyph->fWidth = SkScalarTruncToInt(bounds.width()); michael@0: glyph->fHeight = SkScalarTruncToInt(bounds.height()); michael@0: } michael@0: michael@0: // Apply matrix to advance. michael@0: glyph->fAdvanceY = SkFixedMul(-SkFIXEDToFixed(fMat22.eM12), glyph->fAdvanceX); michael@0: glyph->fAdvanceX = SkFixedMul(SkFIXEDToFixed(fMat22.eM11), glyph->fAdvanceX); michael@0: michael@0: return; michael@0: } michael@0: michael@0: UINT glyphId = glyph->getGlyphID(0); michael@0: michael@0: GLYPHMETRICS gm; michael@0: sk_bzero(&gm, sizeof(gm)); michael@0: michael@0: DWORD status = GetGlyphOutlineW(fDDC, glyphId, GGO_METRICS | GGO_GLYPH_INDEX, &gm, 0, NULL, &fMat22); michael@0: if (GDI_ERROR == status) { michael@0: LogFontTypeface::EnsureAccessible(this->getTypeface()); michael@0: status = GetGlyphOutlineW(fDDC, glyphId, GGO_METRICS | GGO_GLYPH_INDEX, &gm, 0, NULL, &fMat22); michael@0: if (GDI_ERROR == status) { michael@0: glyph->zeroMetrics(); michael@0: return; michael@0: } michael@0: } michael@0: michael@0: bool empty = false; michael@0: // The black box is either the embedded bitmap size or the outline extent. michael@0: // It is 1x1 if nothing is to be drawn, but will also be 1x1 if something very small michael@0: // is to be drawn, like a '.'. We need to outset '.' but do not wish to outset ' '. michael@0: if (1 == gm.gmBlackBoxX && 1 == gm.gmBlackBoxY) { michael@0: // If GetGlyphOutline with GGO_NATIVE returns 0, we know there was no outline. michael@0: DWORD bufferSize = GetGlyphOutlineW(fDDC, glyphId, GGO_NATIVE | GGO_GLYPH_INDEX, &gm, 0, NULL, &fMat22); michael@0: empty = (0 == bufferSize); michael@0: } michael@0: michael@0: glyph->fTop = SkToS16(-gm.gmptGlyphOrigin.y); michael@0: glyph->fLeft = SkToS16(gm.gmptGlyphOrigin.x); michael@0: if (empty) { michael@0: glyph->fWidth = 0; michael@0: glyph->fHeight = 0; michael@0: } else { michael@0: // Outset, since the image may bleed out of the black box. michael@0: // For embedded bitmaps the black box should be exact. michael@0: // For outlines we need to outset by 1 in all directions for bleed. michael@0: // For ClearType we need to outset by 2 for bleed. michael@0: glyph->fWidth = gm.gmBlackBoxX + 4; michael@0: glyph->fHeight = gm.gmBlackBoxY + 4; michael@0: glyph->fTop -= 2; michael@0: glyph->fLeft -= 2; michael@0: } michael@0: glyph->fAdvanceX = SkIntToFixed(gm.gmCellIncX); michael@0: glyph->fAdvanceY = SkIntToFixed(gm.gmCellIncY); michael@0: glyph->fRsbDelta = 0; michael@0: glyph->fLsbDelta = 0; michael@0: michael@0: if (this->isSubpixel()) { michael@0: sk_bzero(&gm, sizeof(gm)); michael@0: status = GetGlyphOutlineW(fDDC, glyphId, GGO_METRICS | GGO_GLYPH_INDEX, &gm, 0, NULL, &fHighResMat22); michael@0: if (GDI_ERROR != status) { michael@0: SkPoint advance; michael@0: fHiResMatrix.mapXY(SkIntToScalar(gm.gmCellIncX), SkIntToScalar(gm.gmCellIncY), &advance); michael@0: glyph->fAdvanceX = SkScalarToFixed(advance.fX); michael@0: glyph->fAdvanceY = SkScalarToFixed(advance.fY); michael@0: } michael@0: } else if (!isAxisAligned(this->fRec)) { michael@0: status = GetGlyphOutlineW(fDDC, glyphId, GGO_METRICS | GGO_GLYPH_INDEX, &gm, 0, NULL, &fGsA); michael@0: if (GDI_ERROR != status) { michael@0: SkPoint advance; michael@0: fG_inv.mapXY(SkIntToScalar(gm.gmCellIncX), SkIntToScalar(gm.gmCellIncY), &advance); michael@0: glyph->fAdvanceX = SkScalarToFixed(advance.fX); michael@0: glyph->fAdvanceY = SkScalarToFixed(advance.fY); michael@0: } michael@0: } michael@0: } michael@0: michael@0: static const MAT2 gMat2Identity = {{0, 1}, {0, 0}, {0, 0}, {0, 1}}; michael@0: void SkScalerContext_GDI::generateFontMetrics(SkPaint::FontMetrics* mx, SkPaint::FontMetrics* my) { michael@0: if (!(mx || my)) { michael@0: return; michael@0: } michael@0: michael@0: if (mx) { michael@0: sk_bzero(mx, sizeof(*mx)); michael@0: } michael@0: if (my) { michael@0: sk_bzero(my, sizeof(*my)); michael@0: } michael@0: michael@0: SkASSERT(fDDC); michael@0: michael@0: #ifndef SK_GDI_ALWAYS_USE_TEXTMETRICS_FOR_FONT_METRICS michael@0: if (fType == SkScalerContext_GDI::kBitmap_Type || fType == SkScalerContext_GDI::kLine_Type) { michael@0: #endif michael@0: if (mx) { michael@0: mx->fTop = SkIntToScalar(-fTM.tmAscent); michael@0: mx->fAscent = SkIntToScalar(-fTM.tmAscent); michael@0: mx->fDescent = SkIntToScalar(fTM.tmDescent); michael@0: mx->fBottom = SkIntToScalar(fTM.tmDescent); michael@0: mx->fLeading = SkIntToScalar(fTM.tmExternalLeading); michael@0: } michael@0: michael@0: if (my) { michael@0: my->fTop = SkIntToScalar(-fTM.tmAscent); michael@0: my->fAscent = SkIntToScalar(-fTM.tmAscent); michael@0: my->fDescent = SkIntToScalar(fTM.tmDescent); michael@0: my->fBottom = SkIntToScalar(fTM.tmDescent); michael@0: my->fLeading = SkIntToScalar(fTM.tmExternalLeading); michael@0: my->fAvgCharWidth = SkIntToScalar(fTM.tmAveCharWidth); michael@0: my->fMaxCharWidth = SkIntToScalar(fTM.tmMaxCharWidth); michael@0: my->fXMin = 0; michael@0: my->fXMax = my->fMaxCharWidth; michael@0: //my->fXHeight = 0; michael@0: } michael@0: #ifndef SK_GDI_ALWAYS_USE_TEXTMETRICS_FOR_FONT_METRICS michael@0: return; michael@0: } michael@0: #endif michael@0: michael@0: OUTLINETEXTMETRIC otm; michael@0: michael@0: uint32_t ret = GetOutlineTextMetrics(fDDC, sizeof(otm), &otm); michael@0: if (0 == ret) { michael@0: LogFontTypeface::EnsureAccessible(this->getTypeface()); michael@0: ret = GetOutlineTextMetrics(fDDC, sizeof(otm), &otm); michael@0: } michael@0: if (0 == ret) { michael@0: return; michael@0: } michael@0: michael@0: if (mx) { michael@0: mx->fTop = SkIntToScalar(-otm.otmrcFontBox.left); michael@0: mx->fAscent = SkIntToScalar(-otm.otmAscent); michael@0: mx->fDescent = SkIntToScalar(-otm.otmDescent); michael@0: mx->fBottom = SkIntToScalar(otm.otmrcFontBox.right); michael@0: mx->fLeading = SkIntToScalar(otm.otmLineGap); michael@0: mx->fUnderlineThickness = SkIntToScalar(otm.otmsUnderscoreSize); michael@0: mx->fUnderlinePosition = -SkIntToScalar(otm.otmsUnderscorePosition); michael@0: michael@0: mx->fFlags |= SkPaint::FontMetrics::kUnderlineThinknessIsValid_Flag; michael@0: mx->fFlags |= SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag; michael@0: } michael@0: michael@0: if (my) { michael@0: #ifndef SK_GDI_ALWAYS_USE_TEXTMETRICS_FOR_FONT_METRICS michael@0: my->fTop = SkIntToScalar(-otm.otmrcFontBox.top); michael@0: my->fAscent = SkIntToScalar(-otm.otmAscent); michael@0: my->fDescent = SkIntToScalar(-otm.otmDescent); michael@0: my->fBottom = SkIntToScalar(-otm.otmrcFontBox.bottom); michael@0: my->fLeading = SkIntToScalar(otm.otmLineGap); michael@0: my->fAvgCharWidth = SkIntToScalar(otm.otmTextMetrics.tmAveCharWidth); michael@0: my->fMaxCharWidth = SkIntToScalar(otm.otmTextMetrics.tmMaxCharWidth); michael@0: my->fXMin = SkIntToScalar(otm.otmrcFontBox.left); michael@0: my->fXMax = SkIntToScalar(otm.otmrcFontBox.right); michael@0: my->fUnderlineThickness = SkIntToScalar(otm.otmsUnderscoreSize); michael@0: my->fUnderlinePosition = -SkIntToScalar(otm.otmsUnderscorePosition); michael@0: michael@0: my->fFlags |= SkPaint::FontMetrics::kUnderlineThinknessIsValid_Flag; michael@0: my->fFlags |= SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag; michael@0: #endif michael@0: my->fXHeight = SkIntToScalar(otm.otmsXHeight); michael@0: michael@0: GLYPHMETRICS gm; michael@0: sk_bzero(&gm, sizeof(gm)); michael@0: DWORD len = GetGlyphOutlineW(fDDC, 'x', GGO_METRICS, &gm, 0, 0, &gMat2Identity); michael@0: if (len != GDI_ERROR && gm.gmBlackBoxY > 0) { michael@0: my->fXHeight = SkIntToScalar(gm.gmBlackBoxY); michael@0: } michael@0: } michael@0: } michael@0: michael@0: //////////////////////////////////////////////////////////////////////////////////////// michael@0: michael@0: #define SK_SHOW_TEXT_BLIT_COVERAGE 0 michael@0: michael@0: static void build_power_table(uint8_t table[], float ee) { michael@0: for (int i = 0; i < 256; i++) { michael@0: float x = i / 255.f; michael@0: x = sk_float_pow(x, ee); michael@0: int xx = SkScalarRoundToInt(x * 255); michael@0: table[i] = SkToU8(xx); michael@0: } michael@0: } michael@0: michael@0: /** michael@0: * This will invert the gamma applied by GDI (gray-scale antialiased), so we michael@0: * can get linear values. michael@0: * michael@0: * GDI grayscale appears to use a hard-coded gamma of 2.3. michael@0: * michael@0: * GDI grayscale appears to draw using the black and white rasterizer at four michael@0: * times the size and then downsamples to compute the coverage mask. As a michael@0: * result there are only seventeen total grays. This lack of fidelity means michael@0: * that shifting into other color spaces is imprecise. michael@0: */ michael@0: static const uint8_t* getInverseGammaTableGDI() { michael@0: // Since build_power_table is idempotent, many threads can build gTableGdi michael@0: // simultaneously. michael@0: michael@0: // Microsoft Specific: michael@0: // Making gInited volatile provides read-aquire and write-release in vc++. michael@0: // In VS2012, see compiler option /volatile:(ms|iso). michael@0: // Replace with C++11 atomics when possible. michael@0: static volatile bool gInited; michael@0: static uint8_t gTableGdi[256]; michael@0: if (gInited) { michael@0: // Need a L/L (read) barrier (full acquire not needed). If gInited is observed michael@0: // true then gTableGdi is observable, but it must be requested. michael@0: } else { michael@0: build_power_table(gTableGdi, 2.3f); michael@0: // Need a S/S (write) barrier (full release not needed) here so that this michael@0: // write to gInited becomes observable after gTableGdi. michael@0: gInited = true; michael@0: } michael@0: return gTableGdi; michael@0: } michael@0: michael@0: /** michael@0: * This will invert the gamma applied by GDI ClearType, so we can get linear michael@0: * values. michael@0: * michael@0: * GDI ClearType uses SPI_GETFONTSMOOTHINGCONTRAST / 1000 as the gamma value. michael@0: * If this value is not specified, the default is a gamma of 1.4. michael@0: */ michael@0: static const uint8_t* getInverseGammaTableClearType() { michael@0: // We don't expect SPI_GETFONTSMOOTHINGCONTRAST to ever change, so building michael@0: // gTableClearType with build_power_table is effectively idempotent. michael@0: michael@0: // Microsoft Specific: michael@0: // Making gInited volatile provides read-aquire and write-release in vc++. michael@0: // In VS2012, see compiler option /volatile:(ms|iso). michael@0: // Replace with C++11 atomics when possible. michael@0: static volatile bool gInited; michael@0: static uint8_t gTableClearType[256]; michael@0: if (gInited) { michael@0: // Need a L/L (read) barrier (acquire not needed). If gInited is observed michael@0: // true then gTableClearType is observable, but it must be requested. michael@0: } else { michael@0: UINT level = 0; michael@0: if (!SystemParametersInfo(SPI_GETFONTSMOOTHINGCONTRAST, 0, &level, 0) || !level) { michael@0: // can't get the data, so use a default michael@0: level = 1400; michael@0: } michael@0: build_power_table(gTableClearType, level / 1000.0f); michael@0: // Need a S/S (write) barrier (release not needed) here so that this michael@0: // write to gInited becomes observable after gTableClearType. michael@0: gInited = true; michael@0: } michael@0: return gTableClearType; michael@0: } michael@0: michael@0: #include "SkColorPriv.h" michael@0: michael@0: //Cannot assume that the input rgb is gray due to possible setting of kGenA8FromLCD_Flag. michael@0: template michael@0: static inline uint8_t rgb_to_a8(SkGdiRGB rgb, const uint8_t* table8) { michael@0: U8CPU r = (rgb >> 16) & 0xFF; michael@0: U8CPU g = (rgb >> 8) & 0xFF; michael@0: U8CPU b = (rgb >> 0) & 0xFF; michael@0: return sk_apply_lut_if(SkComputeLuminance(r, g, b), table8); michael@0: } michael@0: michael@0: template michael@0: static inline uint16_t rgb_to_lcd16(SkGdiRGB rgb, const uint8_t* tableR, michael@0: const uint8_t* tableG, michael@0: const uint8_t* tableB) { michael@0: U8CPU r = sk_apply_lut_if((rgb >> 16) & 0xFF, tableR); michael@0: U8CPU g = sk_apply_lut_if((rgb >> 8) & 0xFF, tableG); michael@0: U8CPU b = sk_apply_lut_if((rgb >> 0) & 0xFF, tableB); michael@0: #if SK_SHOW_TEXT_BLIT_COVERAGE michael@0: r = SkMax32(r, 10); g = SkMax32(g, 10); b = SkMax32(b, 10); michael@0: #endif michael@0: return SkPack888ToRGB16(r, g, b); michael@0: } michael@0: michael@0: template michael@0: static inline SkPMColor rgb_to_lcd32(SkGdiRGB rgb, const uint8_t* tableR, michael@0: const uint8_t* tableG, michael@0: const uint8_t* tableB) { michael@0: U8CPU r = sk_apply_lut_if((rgb >> 16) & 0xFF, tableR); michael@0: U8CPU g = sk_apply_lut_if((rgb >> 8) & 0xFF, tableG); michael@0: U8CPU b = sk_apply_lut_if((rgb >> 0) & 0xFF, tableB); michael@0: #if SK_SHOW_TEXT_BLIT_COVERAGE michael@0: r = SkMax32(r, 10); g = SkMax32(g, 10); b = SkMax32(b, 10); michael@0: #endif michael@0: return SkPackARGB32(0xFF, r, g, b); michael@0: } michael@0: michael@0: // Is this GDI color neither black nor white? If so, we have to keep this michael@0: // image as is, rather than smashing it down to a BW mask. michael@0: // michael@0: // returns int instead of bool, since we don't want/have to pay to convert michael@0: // the zero/non-zero value into a bool michael@0: static int is_not_black_or_white(SkGdiRGB c) { michael@0: // same as (but faster than) michael@0: // c &= 0x00FFFFFF; michael@0: // return 0 == c || 0x00FFFFFF == c; michael@0: return (c + (c & 1)) & 0x00FFFFFF; michael@0: } michael@0: michael@0: static bool is_rgb_really_bw(const SkGdiRGB* src, int width, int height, size_t srcRB) { michael@0: for (int y = 0; y < height; ++y) { michael@0: for (int x = 0; x < width; ++x) { michael@0: if (is_not_black_or_white(src[x])) { michael@0: return false; michael@0: } michael@0: } michael@0: src = SkTAddOffset(src, srcRB); michael@0: } michael@0: return true; michael@0: } michael@0: michael@0: // gdi's bitmap is upside-down, so we reverse dst walking in Y michael@0: // whenever we copy it into skia's buffer michael@0: static void rgb_to_bw(const SkGdiRGB* SK_RESTRICT src, size_t srcRB, michael@0: const SkGlyph& glyph) { michael@0: const int width = glyph.fWidth; michael@0: const size_t dstRB = (width + 7) >> 3; michael@0: uint8_t* SK_RESTRICT dst = (uint8_t*)((char*)glyph.fImage + (glyph.fHeight - 1) * dstRB); michael@0: michael@0: int byteCount = width >> 3; michael@0: int bitCount = width & 7; michael@0: michael@0: // adjust srcRB to skip the values in our byteCount loop, michael@0: // since we increment src locally there michael@0: srcRB -= byteCount * 8 * sizeof(SkGdiRGB); michael@0: michael@0: for (int y = 0; y < glyph.fHeight; ++y) { michael@0: if (byteCount > 0) { michael@0: for (int i = 0; i < byteCount; ++i) { michael@0: unsigned byte = 0; michael@0: byte |= src[0] & (1 << 7); michael@0: byte |= src[1] & (1 << 6); michael@0: byte |= src[2] & (1 << 5); michael@0: byte |= src[3] & (1 << 4); michael@0: byte |= src[4] & (1 << 3); michael@0: byte |= src[5] & (1 << 2); michael@0: byte |= src[6] & (1 << 1); michael@0: byte |= src[7] & (1 << 0); michael@0: dst[i] = byte; michael@0: src += 8; michael@0: } michael@0: } michael@0: if (bitCount > 0) { michael@0: unsigned byte = 0; michael@0: unsigned mask = 0x80; michael@0: for (int i = 0; i < bitCount; i++) { michael@0: byte |= src[i] & mask; michael@0: mask >>= 1; michael@0: } michael@0: dst[byteCount] = byte; michael@0: } michael@0: src = SkTAddOffset(src, srcRB); michael@0: dst -= dstRB; michael@0: } michael@0: #if SK_SHOW_TEXT_BLIT_COVERAGE michael@0: if (glyph.fWidth > 0 && glyph.fHeight > 0) { michael@0: uint8_t* first = (uint8_t*)glyph.fImage; michael@0: uint8_t* last = (uint8_t*)((char*)glyph.fImage + glyph.fHeight * dstRB - 1); michael@0: *first |= 1 << 7; michael@0: *last |= bitCount == 0 ? 1 : 1 << (8 - bitCount); michael@0: } michael@0: #endif michael@0: } michael@0: michael@0: template michael@0: static void rgb_to_a8(const SkGdiRGB* SK_RESTRICT src, size_t srcRB, michael@0: const SkGlyph& glyph, const uint8_t* table8) { michael@0: const size_t dstRB = glyph.rowBytes(); michael@0: const int width = glyph.fWidth; michael@0: uint8_t* SK_RESTRICT dst = (uint8_t*)((char*)glyph.fImage + (glyph.fHeight - 1) * dstRB); michael@0: michael@0: for (int y = 0; y < glyph.fHeight; y++) { michael@0: for (int i = 0; i < width; i++) { michael@0: dst[i] = rgb_to_a8(src[i], table8); michael@0: #if SK_SHOW_TEXT_BLIT_COVERAGE michael@0: dst[i] = SkMax32(dst[i], 10); michael@0: #endif michael@0: } michael@0: src = SkTAddOffset(src, srcRB); michael@0: dst -= dstRB; michael@0: } michael@0: } michael@0: michael@0: template michael@0: static void rgb_to_lcd16(const SkGdiRGB* SK_RESTRICT src, size_t srcRB, const SkGlyph& glyph, michael@0: const uint8_t* tableR, const uint8_t* tableG, const uint8_t* tableB) { michael@0: const size_t dstRB = glyph.rowBytes(); michael@0: const int width = glyph.fWidth; michael@0: uint16_t* SK_RESTRICT dst = (uint16_t*)((char*)glyph.fImage + (glyph.fHeight - 1) * dstRB); michael@0: michael@0: for (int y = 0; y < glyph.fHeight; y++) { michael@0: for (int i = 0; i < width; i++) { michael@0: dst[i] = rgb_to_lcd16(src[i], tableR, tableG, tableB); michael@0: } michael@0: src = SkTAddOffset(src, srcRB); michael@0: dst = (uint16_t*)((char*)dst - dstRB); michael@0: } michael@0: } michael@0: michael@0: template michael@0: static void rgb_to_lcd32(const SkGdiRGB* SK_RESTRICT src, size_t srcRB, const SkGlyph& glyph, michael@0: const uint8_t* tableR, const uint8_t* tableG, const uint8_t* tableB) { michael@0: const size_t dstRB = glyph.rowBytes(); michael@0: const int width = glyph.fWidth; michael@0: uint32_t* SK_RESTRICT dst = (uint32_t*)((char*)glyph.fImage + (glyph.fHeight - 1) * dstRB); michael@0: michael@0: for (int y = 0; y < glyph.fHeight; y++) { michael@0: for (int i = 0; i < width; i++) { michael@0: dst[i] = rgb_to_lcd32(src[i], tableR, tableG, tableB); michael@0: } michael@0: src = SkTAddOffset(src, srcRB); michael@0: dst = (uint32_t*)((char*)dst - dstRB); michael@0: } michael@0: } michael@0: michael@0: static inline unsigned clamp255(unsigned x) { michael@0: SkASSERT(x <= 256); michael@0: return x - (x >> 8); michael@0: } michael@0: michael@0: void SkScalerContext_GDI::generateImage(const SkGlyph& glyph) { michael@0: SkASSERT(fDDC); michael@0: michael@0: const bool isBW = SkMask::kBW_Format == fRec.fMaskFormat; michael@0: const bool isAA = !isLCD(fRec); michael@0: michael@0: size_t srcRB; michael@0: const void* bits = fOffscreen.draw(glyph, isBW, &srcRB); michael@0: if (NULL == bits) { michael@0: LogFontTypeface::EnsureAccessible(this->getTypeface()); michael@0: bits = fOffscreen.draw(glyph, isBW, &srcRB); michael@0: if (NULL == bits) { michael@0: sk_bzero(glyph.fImage, glyph.computeImageSize()); michael@0: return; michael@0: } michael@0: } michael@0: michael@0: if (!isBW) { michael@0: const uint8_t* table; michael@0: //The offscreen contains a GDI blit if isAA and kGenA8FromLCD_Flag is not set. michael@0: //Otherwise the offscreen contains a ClearType blit. michael@0: if (isAA && !(fRec.fFlags & SkScalerContext::kGenA8FromLCD_Flag)) { michael@0: table = getInverseGammaTableGDI(); michael@0: } else { michael@0: table = getInverseGammaTableClearType(); michael@0: } michael@0: //Note that the following cannot really be integrated into the michael@0: //pre-blend, since we may not be applying the pre-blend; when we aren't michael@0: //applying the pre-blend it means that a filter wants linear anyway. michael@0: //Other code may also be applying the pre-blend, so we'd need another michael@0: //one with this and one without. michael@0: SkGdiRGB* addr = (SkGdiRGB*)bits; michael@0: for (int y = 0; y < glyph.fHeight; ++y) { michael@0: for (int x = 0; x < glyph.fWidth; ++x) { michael@0: int r = (addr[x] >> 16) & 0xFF; michael@0: int g = (addr[x] >> 8) & 0xFF; michael@0: int b = (addr[x] >> 0) & 0xFF; michael@0: addr[x] = (table[r] << 16) | (table[g] << 8) | table[b]; michael@0: } michael@0: addr = SkTAddOffset(addr, srcRB); michael@0: } michael@0: } michael@0: michael@0: int width = glyph.fWidth; michael@0: size_t dstRB = glyph.rowBytes(); michael@0: if (isBW) { michael@0: const uint8_t* src = (const uint8_t*)bits; michael@0: uint8_t* dst = (uint8_t*)((char*)glyph.fImage + (glyph.fHeight - 1) * dstRB); michael@0: for (int y = 0; y < glyph.fHeight; y++) { michael@0: memcpy(dst, src, dstRB); michael@0: src += srcRB; michael@0: dst -= dstRB; michael@0: } michael@0: #if SK_SHOW_TEXT_BLIT_COVERAGE michael@0: if (glyph.fWidth > 0 && glyph.fHeight > 0) { michael@0: int bitCount = width & 7; michael@0: uint8_t* first = (uint8_t*)glyph.fImage; michael@0: uint8_t* last = (uint8_t*)((char*)glyph.fImage + glyph.fHeight * dstRB - 1); michael@0: *first |= 1 << 7; michael@0: *last |= bitCount == 0 ? 1 : 1 << (8 - bitCount); michael@0: } michael@0: #endif michael@0: } else if (isAA) { michael@0: // since the caller may require A8 for maskfilters, we can't check for BW michael@0: // ... until we have the caller tell us that explicitly michael@0: const SkGdiRGB* src = (const SkGdiRGB*)bits; michael@0: if (fPreBlend.isApplicable()) { michael@0: rgb_to_a8(src, srcRB, glyph, fPreBlend.fG); michael@0: } else { michael@0: rgb_to_a8(src, srcRB, glyph, fPreBlend.fG); michael@0: } michael@0: } else { // LCD16 michael@0: const SkGdiRGB* src = (const SkGdiRGB*)bits; michael@0: if (is_rgb_really_bw(src, width, glyph.fHeight, srcRB)) { michael@0: rgb_to_bw(src, srcRB, glyph); michael@0: ((SkGlyph*)&glyph)->fMaskFormat = SkMask::kBW_Format; michael@0: } else { michael@0: if (SkMask::kLCD16_Format == glyph.fMaskFormat) { michael@0: if (fPreBlend.isApplicable()) { michael@0: rgb_to_lcd16(src, srcRB, glyph, michael@0: fPreBlend.fR, fPreBlend.fG, fPreBlend.fB); michael@0: } else { michael@0: rgb_to_lcd16(src, srcRB, glyph, michael@0: fPreBlend.fR, fPreBlend.fG, fPreBlend.fB); michael@0: } michael@0: } else { michael@0: SkASSERT(SkMask::kLCD32_Format == glyph.fMaskFormat); michael@0: if (fPreBlend.isApplicable()) { michael@0: rgb_to_lcd32(src, srcRB, glyph, michael@0: fPreBlend.fR, fPreBlend.fG, fPreBlend.fB); michael@0: } else { michael@0: rgb_to_lcd32(src, srcRB, glyph, michael@0: fPreBlend.fR, fPreBlend.fG, fPreBlend.fB); michael@0: } michael@0: } michael@0: } michael@0: } michael@0: } michael@0: michael@0: class GDIGlyphbufferPointIter { michael@0: public: michael@0: GDIGlyphbufferPointIter(const uint8_t* glyphbuf, DWORD total_size) michael@0: : fHeaderIter(glyphbuf, total_size), fCurveIter(), fPointIter() michael@0: { } michael@0: michael@0: POINTFX const * next() { michael@0: nextHeader: michael@0: if (!fCurveIter.isSet()) { michael@0: const TTPOLYGONHEADER* header = fHeaderIter.next(); michael@0: if (NULL == header) { michael@0: return NULL; michael@0: } michael@0: fCurveIter.set(header); michael@0: const TTPOLYCURVE* curve = fCurveIter.next(); michael@0: if (NULL == curve) { michael@0: return NULL; michael@0: } michael@0: fPointIter.set(curve); michael@0: return &header->pfxStart; michael@0: } michael@0: michael@0: const POINTFX* nextPoint = fPointIter.next(); michael@0: if (NULL == nextPoint) { michael@0: const TTPOLYCURVE* curve = fCurveIter.next(); michael@0: if (NULL == curve) { michael@0: fCurveIter.set(); michael@0: goto nextHeader; michael@0: } else { michael@0: fPointIter.set(curve); michael@0: } michael@0: nextPoint = fPointIter.next(); michael@0: } michael@0: return nextPoint; michael@0: } michael@0: michael@0: WORD currentCurveType() { michael@0: return fPointIter.fCurveType; michael@0: } michael@0: michael@0: private: michael@0: /** Iterates over all of the polygon headers in a glyphbuf. */ michael@0: class GDIPolygonHeaderIter { michael@0: public: michael@0: GDIPolygonHeaderIter(const uint8_t* glyphbuf, DWORD total_size) michael@0: : fCurPolygon(reinterpret_cast(glyphbuf)) michael@0: , fEndPolygon(SkTAddOffset(glyphbuf, total_size)) michael@0: { } michael@0: michael@0: const TTPOLYGONHEADER* next() { michael@0: if (fCurPolygon >= fEndPolygon) { michael@0: return NULL; michael@0: } michael@0: const TTPOLYGONHEADER* thisPolygon = fCurPolygon; michael@0: fCurPolygon = SkTAddOffset(fCurPolygon, fCurPolygon->cb); michael@0: return thisPolygon; michael@0: } michael@0: private: michael@0: const TTPOLYGONHEADER* fCurPolygon; michael@0: const TTPOLYGONHEADER* fEndPolygon; michael@0: }; michael@0: michael@0: /** Iterates over all of the polygon curves in a polygon header. */ michael@0: class GDIPolygonCurveIter { michael@0: public: michael@0: GDIPolygonCurveIter() : fCurCurve(NULL), fEndCurve(NULL) { } michael@0: michael@0: GDIPolygonCurveIter(const TTPOLYGONHEADER* curPolygon) michael@0: : fCurCurve(SkTAddOffset(curPolygon, sizeof(TTPOLYGONHEADER))) michael@0: , fEndCurve(SkTAddOffset(curPolygon, curPolygon->cb)) michael@0: { } michael@0: michael@0: bool isSet() { return fCurCurve != NULL; } michael@0: michael@0: void set(const TTPOLYGONHEADER* curPolygon) { michael@0: fCurCurve = SkTAddOffset(curPolygon, sizeof(TTPOLYGONHEADER)); michael@0: fEndCurve = SkTAddOffset(curPolygon, curPolygon->cb); michael@0: } michael@0: void set() { michael@0: fCurCurve = NULL; michael@0: fEndCurve = NULL; michael@0: } michael@0: michael@0: const TTPOLYCURVE* next() { michael@0: if (fCurCurve >= fEndCurve) { michael@0: return NULL; michael@0: } michael@0: const TTPOLYCURVE* thisCurve = fCurCurve; michael@0: fCurCurve = SkTAddOffset(fCurCurve, size_of_TTPOLYCURVE(*fCurCurve)); michael@0: return thisCurve; michael@0: } michael@0: private: michael@0: size_t size_of_TTPOLYCURVE(const TTPOLYCURVE& curve) { michael@0: return 2*sizeof(WORD) + curve.cpfx*sizeof(POINTFX); michael@0: } michael@0: const TTPOLYCURVE* fCurCurve; michael@0: const TTPOLYCURVE* fEndCurve; michael@0: }; michael@0: michael@0: /** Iterates over all of the polygon points in a polygon curve. */ michael@0: class GDIPolygonCurvePointIter { michael@0: public: michael@0: GDIPolygonCurvePointIter() : fCurveType(0), fCurPoint(NULL), fEndPoint(NULL) { } michael@0: michael@0: GDIPolygonCurvePointIter(const TTPOLYCURVE* curPolygon) michael@0: : fCurveType(curPolygon->wType) michael@0: , fCurPoint(&curPolygon->apfx[0]) michael@0: , fEndPoint(&curPolygon->apfx[curPolygon->cpfx]) michael@0: { } michael@0: michael@0: bool isSet() { return fCurPoint != NULL; } michael@0: michael@0: void set(const TTPOLYCURVE* curPolygon) { michael@0: fCurveType = curPolygon->wType; michael@0: fCurPoint = &curPolygon->apfx[0]; michael@0: fEndPoint = &curPolygon->apfx[curPolygon->cpfx]; michael@0: } michael@0: void set() { michael@0: fCurPoint = NULL; michael@0: fEndPoint = NULL; michael@0: } michael@0: michael@0: const POINTFX* next() { michael@0: if (fCurPoint >= fEndPoint) { michael@0: return NULL; michael@0: } michael@0: const POINTFX* thisPoint = fCurPoint; michael@0: ++fCurPoint; michael@0: return thisPoint; michael@0: } michael@0: michael@0: WORD fCurveType; michael@0: private: michael@0: const POINTFX* fCurPoint; michael@0: const POINTFX* fEndPoint; michael@0: }; michael@0: michael@0: GDIPolygonHeaderIter fHeaderIter; michael@0: GDIPolygonCurveIter fCurveIter; michael@0: GDIPolygonCurvePointIter fPointIter; michael@0: }; michael@0: michael@0: static void sk_path_from_gdi_path(SkPath* path, const uint8_t* glyphbuf, DWORD total_size) { michael@0: const uint8_t* cur_glyph = glyphbuf; michael@0: const uint8_t* end_glyph = glyphbuf + total_size; michael@0: michael@0: while (cur_glyph < end_glyph) { michael@0: const TTPOLYGONHEADER* th = (TTPOLYGONHEADER*)cur_glyph; michael@0: michael@0: const uint8_t* end_poly = cur_glyph + th->cb; michael@0: const uint8_t* cur_poly = cur_glyph + sizeof(TTPOLYGONHEADER); michael@0: michael@0: path->moveTo(SkFixedToScalar( SkFIXEDToFixed(th->pfxStart.x)), michael@0: SkFixedToScalar(-SkFIXEDToFixed(th->pfxStart.y))); michael@0: michael@0: while (cur_poly < end_poly) { michael@0: const TTPOLYCURVE* pc = (const TTPOLYCURVE*)cur_poly; michael@0: michael@0: if (pc->wType == TT_PRIM_LINE) { michael@0: for (uint16_t i = 0; i < pc->cpfx; i++) { michael@0: path->lineTo(SkFixedToScalar( SkFIXEDToFixed(pc->apfx[i].x)), michael@0: SkFixedToScalar(-SkFIXEDToFixed(pc->apfx[i].y))); michael@0: } michael@0: } michael@0: michael@0: if (pc->wType == TT_PRIM_QSPLINE) { michael@0: for (uint16_t u = 0; u < pc->cpfx - 1; u++) { // Walk through points in spline michael@0: POINTFX pnt_b = pc->apfx[u]; // B is always the current point michael@0: POINTFX pnt_c = pc->apfx[u+1]; michael@0: michael@0: if (u < pc->cpfx - 2) { // If not on last spline, compute C michael@0: pnt_c.x = SkFixedToFIXED(SkFixedAve(SkFIXEDToFixed(pnt_b.x), michael@0: SkFIXEDToFixed(pnt_c.x))); michael@0: pnt_c.y = SkFixedToFIXED(SkFixedAve(SkFIXEDToFixed(pnt_b.y), michael@0: SkFIXEDToFixed(pnt_c.y))); michael@0: } michael@0: michael@0: path->quadTo(SkFixedToScalar( SkFIXEDToFixed(pnt_b.x)), michael@0: SkFixedToScalar(-SkFIXEDToFixed(pnt_b.y)), michael@0: SkFixedToScalar( SkFIXEDToFixed(pnt_c.x)), michael@0: SkFixedToScalar(-SkFIXEDToFixed(pnt_c.y))); michael@0: } michael@0: } michael@0: // Advance past this TTPOLYCURVE. michael@0: cur_poly += sizeof(WORD) * 2 + sizeof(POINTFX) * pc->cpfx; michael@0: } michael@0: cur_glyph += th->cb; michael@0: path->close(); michael@0: } michael@0: } michael@0: michael@0: #define move_next_expected_hinted_point(iter, pElem) do {\ michael@0: pElem = iter.next(); \ michael@0: if (NULL == pElem) return false; \ michael@0: } while(0) michael@0: michael@0: // It is possible for the hinted and unhinted versions of the same path to have michael@0: // a different number of points due to GDI's handling of flipped points. michael@0: // If this is detected, this will return false. michael@0: static bool sk_path_from_gdi_paths(SkPath* path, const uint8_t* glyphbuf, DWORD total_size, michael@0: GDIGlyphbufferPointIter hintedYs) { michael@0: const uint8_t* cur_glyph = glyphbuf; michael@0: const uint8_t* end_glyph = glyphbuf + total_size; michael@0: michael@0: POINTFX const * hintedPoint; michael@0: michael@0: while (cur_glyph < end_glyph) { michael@0: const TTPOLYGONHEADER* th = (TTPOLYGONHEADER*)cur_glyph; michael@0: michael@0: const uint8_t* end_poly = cur_glyph + th->cb; michael@0: const uint8_t* cur_poly = cur_glyph + sizeof(TTPOLYGONHEADER); michael@0: michael@0: move_next_expected_hinted_point(hintedYs, hintedPoint); michael@0: path->moveTo(SkFixedToScalar( SkFIXEDToFixed(th->pfxStart.x)), michael@0: SkFixedToScalar(-SkFIXEDToFixed(hintedPoint->y))); michael@0: michael@0: while (cur_poly < end_poly) { michael@0: const TTPOLYCURVE* pc = (const TTPOLYCURVE*)cur_poly; michael@0: michael@0: if (pc->wType == TT_PRIM_LINE) { michael@0: for (uint16_t i = 0; i < pc->cpfx; i++) { michael@0: move_next_expected_hinted_point(hintedYs, hintedPoint); michael@0: path->lineTo(SkFixedToScalar( SkFIXEDToFixed(pc->apfx[i].x)), michael@0: SkFixedToScalar(-SkFIXEDToFixed(hintedPoint->y))); michael@0: } michael@0: } michael@0: michael@0: if (pc->wType == TT_PRIM_QSPLINE) { michael@0: POINTFX currentPoint = pc->apfx[0]; michael@0: move_next_expected_hinted_point(hintedYs, hintedPoint); michael@0: // only take the hinted y if it wasn't flipped michael@0: if (hintedYs.currentCurveType() == TT_PRIM_QSPLINE) { michael@0: currentPoint.y = hintedPoint->y; michael@0: } michael@0: for (uint16_t u = 0; u < pc->cpfx - 1; u++) { // Walk through points in spline michael@0: POINTFX pnt_b = currentPoint;//pc->apfx[u]; // B is always the current point michael@0: POINTFX pnt_c = pc->apfx[u+1]; michael@0: move_next_expected_hinted_point(hintedYs, hintedPoint); michael@0: // only take the hinted y if it wasn't flipped michael@0: if (hintedYs.currentCurveType() == TT_PRIM_QSPLINE) { michael@0: pnt_c.y = hintedPoint->y; michael@0: } michael@0: currentPoint.x = pnt_c.x; michael@0: currentPoint.y = pnt_c.y; michael@0: michael@0: if (u < pc->cpfx - 2) { // If not on last spline, compute C michael@0: pnt_c.x = SkFixedToFIXED(SkFixedAve(SkFIXEDToFixed(pnt_b.x), michael@0: SkFIXEDToFixed(pnt_c.x))); michael@0: pnt_c.y = SkFixedToFIXED(SkFixedAve(SkFIXEDToFixed(pnt_b.y), michael@0: SkFIXEDToFixed(pnt_c.y))); michael@0: } michael@0: michael@0: path->quadTo(SkFixedToScalar( SkFIXEDToFixed(pnt_b.x)), michael@0: SkFixedToScalar(-SkFIXEDToFixed(pnt_b.y)), michael@0: SkFixedToScalar( SkFIXEDToFixed(pnt_c.x)), michael@0: SkFixedToScalar(-SkFIXEDToFixed(pnt_c.y))); michael@0: } michael@0: } michael@0: // Advance past this TTPOLYCURVE. michael@0: cur_poly += sizeof(WORD) * 2 + sizeof(POINTFX) * pc->cpfx; michael@0: } michael@0: cur_glyph += th->cb; michael@0: path->close(); michael@0: } michael@0: return true; michael@0: } michael@0: michael@0: DWORD SkScalerContext_GDI::getGDIGlyphPath(const SkGlyph& glyph, UINT flags, michael@0: SkAutoSTMalloc* glyphbuf) michael@0: { michael@0: GLYPHMETRICS gm; michael@0: michael@0: DWORD total_size = GetGlyphOutlineW(fDDC, glyph.fID, flags, &gm, BUFFERSIZE, glyphbuf->get(), &fMat22); michael@0: // Sometimes GetGlyphOutlineW returns a number larger than BUFFERSIZE even if BUFFERSIZE > 0. michael@0: // It has been verified that this does not involve a buffer overrun. michael@0: if (GDI_ERROR == total_size || total_size > BUFFERSIZE) { michael@0: // GDI_ERROR because the BUFFERSIZE was too small, or because the data was not accessible. michael@0: // When the data is not accessable GetGlyphOutlineW fails rather quickly, michael@0: // so just try to get the size. If that fails then ensure the data is accessible. michael@0: total_size = GetGlyphOutlineW(fDDC, glyph.fID, flags, &gm, 0, NULL, &fMat22); michael@0: if (GDI_ERROR == total_size) { michael@0: LogFontTypeface::EnsureAccessible(this->getTypeface()); michael@0: total_size = GetGlyphOutlineW(fDDC, glyph.fID, flags, &gm, 0, NULL, &fMat22); michael@0: if (GDI_ERROR == total_size) { michael@0: SkASSERT(false); michael@0: return 0; michael@0: } michael@0: } michael@0: michael@0: glyphbuf->reset(total_size); michael@0: michael@0: DWORD ret = GetGlyphOutlineW(fDDC, glyph.fID, flags, &gm, total_size, glyphbuf->get(), &fMat22); michael@0: if (GDI_ERROR == ret) { michael@0: LogFontTypeface::EnsureAccessible(this->getTypeface()); michael@0: ret = GetGlyphOutlineW(fDDC, glyph.fID, flags, &gm, total_size, glyphbuf->get(), &fMat22); michael@0: if (GDI_ERROR == ret) { michael@0: SkASSERT(false); michael@0: return 0; michael@0: } michael@0: } michael@0: } michael@0: return total_size; michael@0: } michael@0: michael@0: void SkScalerContext_GDI::generatePath(const SkGlyph& glyph, SkPath* path) { michael@0: SkASSERT(&glyph && path); michael@0: SkASSERT(fDDC); michael@0: michael@0: path->reset(); michael@0: michael@0: // Out of all the fonts on a typical Windows box, michael@0: // 25% of glyphs require more than 2KB. michael@0: // 1% of glyphs require more than 4KB. michael@0: // 0.01% of glyphs require more than 8KB. michael@0: // 8KB is less than 1% of the normal 1MB stack on Windows. michael@0: // Note that some web fonts glyphs require more than 20KB. michael@0: //static const DWORD BUFFERSIZE = (1 << 13); michael@0: michael@0: //GDI only uses hinted outlines when axis aligned. michael@0: UINT format = GGO_NATIVE | GGO_GLYPH_INDEX; michael@0: if (fRec.getHinting() == SkPaint::kNo_Hinting || fRec.getHinting() == SkPaint::kSlight_Hinting){ michael@0: format |= GGO_UNHINTED; michael@0: } michael@0: SkAutoSTMalloc glyphbuf(BUFFERSIZE); michael@0: DWORD total_size = getGDIGlyphPath(glyph, format, &glyphbuf); michael@0: if (0 == total_size) { michael@0: return; michael@0: } michael@0: michael@0: if (fRec.getHinting() != SkPaint::kSlight_Hinting) { michael@0: sk_path_from_gdi_path(path, glyphbuf, total_size); michael@0: } else { michael@0: //GDI only uses hinted outlines when axis aligned. michael@0: UINT format = GGO_NATIVE | GGO_GLYPH_INDEX; michael@0: michael@0: SkAutoSTMalloc hintedGlyphbuf(BUFFERSIZE); michael@0: DWORD hinted_total_size = getGDIGlyphPath(glyph, format, &hintedGlyphbuf); michael@0: if (0 == hinted_total_size) { michael@0: return; michael@0: } michael@0: michael@0: if (!sk_path_from_gdi_paths(path, glyphbuf, total_size, michael@0: GDIGlyphbufferPointIter(hintedGlyphbuf, hinted_total_size))) michael@0: { michael@0: path->reset(); michael@0: sk_path_from_gdi_path(path, glyphbuf, total_size); michael@0: } michael@0: } michael@0: } michael@0: michael@0: static void logfont_for_name(const char* familyName, LOGFONT* lf) { michael@0: sk_bzero(lf, sizeof(LOGFONT)); michael@0: #ifdef UNICODE michael@0: // Get the buffer size needed first. michael@0: size_t str_len = ::MultiByteToWideChar(CP_UTF8, 0, familyName, michael@0: -1, NULL, 0); michael@0: // Allocate a buffer (str_len already has terminating null michael@0: // accounted for). michael@0: wchar_t *wideFamilyName = new wchar_t[str_len]; michael@0: // Now actually convert the string. michael@0: ::MultiByteToWideChar(CP_UTF8, 0, familyName, -1, michael@0: wideFamilyName, str_len); michael@0: ::wcsncpy(lf->lfFaceName, wideFamilyName, LF_FACESIZE - 1); michael@0: delete [] wideFamilyName; michael@0: lf->lfFaceName[LF_FACESIZE-1] = L'\0'; michael@0: #else michael@0: ::strncpy(lf->lfFaceName, familyName, LF_FACESIZE - 1); michael@0: lf->lfFaceName[LF_FACESIZE - 1] = '\0'; michael@0: #endif michael@0: } michael@0: michael@0: void LogFontTypeface::onGetFontDescriptor(SkFontDescriptor* desc, michael@0: bool* isLocalStream) const { michael@0: // Get the actual name of the typeface. The logfont may not know this. michael@0: HFONT font = CreateFontIndirect(&fLogFont); michael@0: michael@0: HDC deviceContext = ::CreateCompatibleDC(NULL); michael@0: HFONT savefont = (HFONT)SelectObject(deviceContext, font); michael@0: michael@0: SkString familyName; michael@0: dcfontname_to_skstring(deviceContext, fLogFont, &familyName); michael@0: michael@0: if (deviceContext) { michael@0: ::SelectObject(deviceContext, savefont); michael@0: ::DeleteDC(deviceContext); michael@0: } michael@0: if (font) { michael@0: ::DeleteObject(font); michael@0: } michael@0: michael@0: desc->setFamilyName(familyName.c_str()); michael@0: *isLocalStream = this->fSerializeAsStream; michael@0: } michael@0: michael@0: static bool getWidthAdvance(HDC hdc, int gId, int16_t* advance) { michael@0: // Initialize the MAT2 structure to the identify transformation matrix. michael@0: static const MAT2 mat2 = {SkScalarToFIXED(1), SkScalarToFIXED(0), michael@0: SkScalarToFIXED(0), SkScalarToFIXED(1)}; michael@0: int flags = GGO_METRICS | GGO_GLYPH_INDEX; michael@0: GLYPHMETRICS gm; michael@0: if (GDI_ERROR == GetGlyphOutline(hdc, gId, flags, &gm, 0, NULL, &mat2)) { michael@0: return false; michael@0: } michael@0: SkASSERT(advance); michael@0: *advance = gm.gmCellIncX; michael@0: return true; michael@0: } michael@0: michael@0: SkAdvancedTypefaceMetrics* LogFontTypeface::onGetAdvancedTypefaceMetrics( michael@0: SkAdvancedTypefaceMetrics::PerGlyphInfo perGlyphInfo, michael@0: const uint32_t* glyphIDs, michael@0: uint32_t glyphIDsCount) const { michael@0: LOGFONT lf = fLogFont; michael@0: SkAdvancedTypefaceMetrics* info = NULL; michael@0: michael@0: HDC hdc = CreateCompatibleDC(NULL); michael@0: HFONT font = CreateFontIndirect(&lf); michael@0: HFONT savefont = (HFONT)SelectObject(hdc, font); michael@0: HFONT designFont = NULL; michael@0: michael@0: const char stem_chars[] = {'i', 'I', '!', '1'}; michael@0: int16_t min_width; michael@0: unsigned glyphCount; michael@0: michael@0: // To request design units, create a logical font whose height is specified michael@0: // as unitsPerEm. michael@0: OUTLINETEXTMETRIC otm; michael@0: unsigned int otmRet = GetOutlineTextMetrics(hdc, sizeof(otm), &otm); michael@0: if (0 == otmRet) { michael@0: call_ensure_accessible(lf); michael@0: otmRet = GetOutlineTextMetrics(hdc, sizeof(otm), &otm); michael@0: } michael@0: if (!otmRet || !GetTextFace(hdc, LF_FACESIZE, lf.lfFaceName)) { michael@0: goto Error; michael@0: } michael@0: lf.lfHeight = -SkToS32(otm.otmEMSquare); michael@0: designFont = CreateFontIndirect(&lf); michael@0: SelectObject(hdc, designFont); michael@0: if (!GetOutlineTextMetrics(hdc, sizeof(otm), &otm)) { michael@0: goto Error; michael@0: } michael@0: glyphCount = calculateGlyphCount(hdc, fLogFont); michael@0: michael@0: info = new SkAdvancedTypefaceMetrics; michael@0: info->fEmSize = otm.otmEMSquare; michael@0: info->fMultiMaster = false; michael@0: info->fLastGlyphID = SkToU16(glyphCount - 1); michael@0: info->fStyle = 0; michael@0: tchar_to_skstring(lf.lfFaceName, &info->fFontName); michael@0: michael@0: if (perGlyphInfo & SkAdvancedTypefaceMetrics::kToUnicode_PerGlyphInfo) { michael@0: populate_glyph_to_unicode(hdc, glyphCount, &(info->fGlyphToUnicode)); michael@0: } michael@0: michael@0: if (glyphCount > 0 && michael@0: (otm.otmTextMetrics.tmPitchAndFamily & TMPF_TRUETYPE)) { michael@0: info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font; michael@0: } else { michael@0: info->fType = SkAdvancedTypefaceMetrics::kOther_Font; michael@0: info->fItalicAngle = 0; michael@0: info->fAscent = 0; michael@0: info->fDescent = 0; michael@0: info->fStemV = 0; michael@0: info->fCapHeight = 0; michael@0: info->fBBox = SkIRect::MakeEmpty(); michael@0: goto ReturnInfo; michael@0: } michael@0: michael@0: // If this bit is clear the font is a fixed pitch font. michael@0: if (!(otm.otmTextMetrics.tmPitchAndFamily & TMPF_FIXED_PITCH)) { michael@0: info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style; michael@0: } michael@0: if (otm.otmTextMetrics.tmItalic) { michael@0: info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style; michael@0: } michael@0: if (otm.otmTextMetrics.tmPitchAndFamily & FF_ROMAN) { michael@0: info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style; michael@0: } else if (otm.otmTextMetrics.tmPitchAndFamily & FF_SCRIPT) { michael@0: info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style; michael@0: } michael@0: michael@0: // The main italic angle of the font, in tenths of a degree counterclockwise michael@0: // from vertical. michael@0: info->fItalicAngle = otm.otmItalicAngle / 10; michael@0: info->fAscent = SkToS16(otm.otmTextMetrics.tmAscent); michael@0: info->fDescent = SkToS16(-otm.otmTextMetrics.tmDescent); michael@0: // TODO(ctguil): Use alternate cap height calculation. michael@0: // MSDN says otmsCapEmHeight is not support but it is returning a value on michael@0: // my Win7 box. michael@0: info->fCapHeight = otm.otmsCapEmHeight; michael@0: info->fBBox = michael@0: SkIRect::MakeLTRB(otm.otmrcFontBox.left, otm.otmrcFontBox.top, michael@0: otm.otmrcFontBox.right, otm.otmrcFontBox.bottom); michael@0: michael@0: // Figure out a good guess for StemV - Min width of i, I, !, 1. michael@0: // This probably isn't very good with an italic font. michael@0: min_width = SHRT_MAX; michael@0: info->fStemV = 0; michael@0: for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) { michael@0: ABC abcWidths; michael@0: if (GetCharABCWidths(hdc, stem_chars[i], stem_chars[i], &abcWidths)) { michael@0: int16_t width = abcWidths.abcB; michael@0: if (width > 0 && width < min_width) { michael@0: min_width = width; michael@0: info->fStemV = min_width; michael@0: } michael@0: } michael@0: } michael@0: michael@0: // If bit 1 is set, the font may not be embedded in a document. michael@0: // If bit 1 is clear, the font can be embedded. michael@0: // If bit 2 is set, the embedding is read-only. michael@0: if (otm.otmfsType & 0x1) { michael@0: info->fType = SkAdvancedTypefaceMetrics::kNotEmbeddable_Font; michael@0: } else if (perGlyphInfo & michael@0: SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo) { michael@0: if (info->fStyle & SkAdvancedTypefaceMetrics::kFixedPitch_Style) { michael@0: appendRange(&info->fGlyphWidths, 0); michael@0: info->fGlyphWidths->fAdvance.append(1, &min_width); michael@0: finishRange(info->fGlyphWidths.get(), 0, michael@0: SkAdvancedTypefaceMetrics::WidthRange::kDefault); michael@0: } else { michael@0: info->fGlyphWidths.reset( michael@0: getAdvanceData(hdc, michael@0: glyphCount, michael@0: glyphIDs, michael@0: glyphIDsCount, michael@0: &getWidthAdvance)); michael@0: } michael@0: } michael@0: michael@0: Error: michael@0: ReturnInfo: michael@0: SelectObject(hdc, savefont); michael@0: DeleteObject(designFont); michael@0: DeleteObject(font); michael@0: DeleteDC(hdc); michael@0: michael@0: return info; michael@0: } michael@0: michael@0: //Dummy representation of a Base64 encoded GUID from create_unique_font_name. michael@0: #define BASE64_GUID_ID "XXXXXXXXXXXXXXXXXXXXXXXX" michael@0: //Length of GUID representation from create_id, including NULL terminator. michael@0: #define BASE64_GUID_ID_LEN SK_ARRAY_COUNT(BASE64_GUID_ID) michael@0: michael@0: SK_COMPILE_ASSERT(BASE64_GUID_ID_LEN < LF_FACESIZE, GUID_longer_than_facesize); michael@0: michael@0: /** michael@0: NameID 6 Postscript names cannot have the character '/'. michael@0: It would be easier to hex encode the GUID, but that is 32 bytes, michael@0: and many systems have issues with names longer than 28 bytes. michael@0: The following need not be any standard base64 encoding. michael@0: The encoded value is never decoded. michael@0: */ michael@0: static const char postscript_safe_base64_encode[] = michael@0: "ABCDEFGHIJKLMNOPQRSTUVWXYZ" michael@0: "abcdefghijklmnopqrstuvwxyz" michael@0: "0123456789-_="; michael@0: michael@0: /** michael@0: Formats a GUID into Base64 and places it into buffer. michael@0: buffer should have space for at least BASE64_GUID_ID_LEN characters. michael@0: The string will always be null terminated. michael@0: XXXXXXXXXXXXXXXXXXXXXXXX0 michael@0: */ michael@0: static void format_guid_b64(const GUID& guid, char* buffer, size_t bufferSize) { michael@0: SkASSERT(bufferSize >= BASE64_GUID_ID_LEN); michael@0: size_t written = SkBase64::Encode(&guid, sizeof(guid), buffer, postscript_safe_base64_encode); michael@0: SkASSERT(written < LF_FACESIZE); michael@0: buffer[written] = '\0'; michael@0: } michael@0: michael@0: /** michael@0: Creates a Base64 encoded GUID and places it into buffer. michael@0: buffer should have space for at least BASE64_GUID_ID_LEN characters. michael@0: The string will always be null terminated. michael@0: XXXXXXXXXXXXXXXXXXXXXXXX0 michael@0: */ michael@0: static HRESULT create_unique_font_name(char* buffer, size_t bufferSize) { michael@0: GUID guid = {}; michael@0: if (FAILED(CoCreateGuid(&guid))) { michael@0: return E_UNEXPECTED; michael@0: } michael@0: format_guid_b64(guid, buffer, bufferSize); michael@0: michael@0: return S_OK; michael@0: } michael@0: michael@0: /** michael@0: Introduces a font to GDI. On failure will return NULL. The returned handle michael@0: should eventually be passed to RemoveFontMemResourceEx. michael@0: */ michael@0: static HANDLE activate_font(SkData* fontData) { michael@0: DWORD numFonts = 0; michael@0: //AddFontMemResourceEx just copies the data, but does not specify const. michael@0: HANDLE fontHandle = AddFontMemResourceEx(const_cast(fontData->data()), michael@0: static_cast(fontData->size()), michael@0: 0, michael@0: &numFonts); michael@0: michael@0: if (fontHandle != NULL && numFonts < 1) { michael@0: RemoveFontMemResourceEx(fontHandle); michael@0: return NULL; michael@0: } michael@0: michael@0: return fontHandle; michael@0: } michael@0: michael@0: static SkTypeface* create_from_stream(SkStream* stream) { michael@0: // Create a unique and unpredictable font name. michael@0: // Avoids collisions and access from CSS. michael@0: char familyName[BASE64_GUID_ID_LEN]; michael@0: const int familyNameSize = SK_ARRAY_COUNT(familyName); michael@0: if (FAILED(create_unique_font_name(familyName, familyNameSize))) { michael@0: return NULL; michael@0: } michael@0: michael@0: // Change the name of the font. michael@0: SkAutoTUnref rewrittenFontData(SkOTUtils::RenameFont(stream, familyName, familyNameSize-1)); michael@0: if (NULL == rewrittenFontData.get()) { michael@0: return NULL; michael@0: } michael@0: michael@0: // Register the font with GDI. michael@0: HANDLE fontReference = activate_font(rewrittenFontData.get()); michael@0: if (NULL == fontReference) { michael@0: return NULL; michael@0: } michael@0: michael@0: // Create the typeface. michael@0: LOGFONT lf; michael@0: logfont_for_name(familyName, &lf); michael@0: michael@0: return SkCreateFontMemResourceTypefaceFromLOGFONT(lf, fontReference); michael@0: } michael@0: michael@0: SkStream* LogFontTypeface::onOpenStream(int* ttcIndex) const { michael@0: *ttcIndex = 0; michael@0: michael@0: const DWORD kTTCTag = michael@0: SkEndian_SwapBE32(SkSetFourByteTag('t', 't', 'c', 'f')); michael@0: LOGFONT lf = fLogFont; michael@0: michael@0: HDC hdc = ::CreateCompatibleDC(NULL); michael@0: HFONT font = CreateFontIndirect(&lf); michael@0: HFONT savefont = (HFONT)SelectObject(hdc, font); michael@0: michael@0: SkMemoryStream* stream = NULL; michael@0: DWORD tables[2] = {kTTCTag, 0}; michael@0: for (int i = 0; i < SK_ARRAY_COUNT(tables); i++) { michael@0: DWORD bufferSize = GetFontData(hdc, tables[i], 0, NULL, 0); michael@0: if (bufferSize == GDI_ERROR) { michael@0: call_ensure_accessible(lf); michael@0: bufferSize = GetFontData(hdc, tables[i], 0, NULL, 0); michael@0: } michael@0: if (bufferSize != GDI_ERROR) { michael@0: stream = new SkMemoryStream(bufferSize); michael@0: if (GetFontData(hdc, tables[i], 0, (void*)stream->getMemoryBase(), bufferSize)) { michael@0: break; michael@0: } else { michael@0: delete stream; michael@0: stream = NULL; michael@0: } michael@0: } michael@0: } michael@0: michael@0: SelectObject(hdc, savefont); michael@0: DeleteObject(font); michael@0: DeleteDC(hdc); michael@0: michael@0: return stream; michael@0: } michael@0: michael@0: static void bmpCharsToGlyphs(HDC hdc, const WCHAR* bmpChars, int count, uint16_t* glyphs, michael@0: bool Ox1FHack) michael@0: { michael@0: DWORD result = GetGlyphIndicesW(hdc, bmpChars, count, glyphs, GGI_MARK_NONEXISTING_GLYPHS); michael@0: if (GDI_ERROR == result) { michael@0: for (int i = 0; i < count; ++i) { michael@0: glyphs[i] = 0; michael@0: } michael@0: return; michael@0: } michael@0: michael@0: if (Ox1FHack) { michael@0: for (int i = 0; i < count; ++i) { michael@0: if (0xFFFF == glyphs[i] || 0x1F == glyphs[i]) { michael@0: glyphs[i] = 0; michael@0: } michael@0: } michael@0: } else { michael@0: for (int i = 0; i < count; ++i) { michael@0: if (0xFFFF == glyphs[i]){ michael@0: glyphs[i] = 0; michael@0: } michael@0: } michael@0: } michael@0: } michael@0: michael@0: static uint16_t nonBmpCharToGlyph(HDC hdc, SCRIPT_CACHE* scriptCache, const WCHAR utf16[2]) { michael@0: uint16_t index = 0; michael@0: // Use uniscribe to detemine glyph index for non-BMP characters. michael@0: static const int numWCHAR = 2; michael@0: static const int maxItems = 2; michael@0: // MSDN states that this can be NULL, but some things don't work then. michael@0: SCRIPT_CONTROL scriptControl = { 0 }; michael@0: // Add extra item to SCRIPT_ITEM to work around a bug (now documented). michael@0: // https://bugzilla.mozilla.org/show_bug.cgi?id=366643 michael@0: SCRIPT_ITEM si[maxItems + 1]; michael@0: int numItems; michael@0: HRZM(ScriptItemize(utf16, numWCHAR, maxItems, &scriptControl, NULL, si, &numItems), michael@0: "Could not itemize character."); michael@0: michael@0: // Sometimes ScriptShape cannot find a glyph for a non-BMP and returns 2 space glyphs. michael@0: static const int maxGlyphs = 2; michael@0: SCRIPT_VISATTR vsa[maxGlyphs]; michael@0: WORD outGlyphs[maxGlyphs]; michael@0: WORD logClust[numWCHAR]; michael@0: int numGlyphs; michael@0: HRZM(ScriptShape(hdc, scriptCache, utf16, numWCHAR, maxGlyphs, &si[0].a, michael@0: outGlyphs, logClust, vsa, &numGlyphs), michael@0: "Could not shape character."); michael@0: if (1 == numGlyphs) { michael@0: index = outGlyphs[0]; michael@0: } michael@0: return index; michael@0: } michael@0: michael@0: class SkAutoHDC { michael@0: public: michael@0: SkAutoHDC(const LOGFONT& lf) michael@0: : fHdc(::CreateCompatibleDC(NULL)) michael@0: , fFont(::CreateFontIndirect(&lf)) michael@0: , fSavefont((HFONT)SelectObject(fHdc, fFont)) michael@0: { } michael@0: ~SkAutoHDC() { michael@0: SelectObject(fHdc, fSavefont); michael@0: DeleteObject(fFont); michael@0: DeleteDC(fHdc); michael@0: } michael@0: operator HDC() { return fHdc; } michael@0: private: michael@0: HDC fHdc; michael@0: HFONT fFont; michael@0: HFONT fSavefont; michael@0: }; michael@0: #define SkAutoHDC(...) SK_REQUIRE_LOCAL_VAR(SkAutoHDC) michael@0: michael@0: int LogFontTypeface::onCharsToGlyphs(const void* chars, Encoding encoding, michael@0: uint16_t userGlyphs[], int glyphCount) const michael@0: { michael@0: SkAutoHDC hdc(fLogFont); michael@0: michael@0: TEXTMETRIC tm; michael@0: if (0 == GetTextMetrics(hdc, &tm)) { michael@0: call_ensure_accessible(fLogFont); michael@0: if (0 == GetTextMetrics(hdc, &tm)) { michael@0: tm.tmPitchAndFamily = TMPF_TRUETYPE; michael@0: } michael@0: } michael@0: bool Ox1FHack = !(tm.tmPitchAndFamily & TMPF_VECTOR) /*&& winVer < Vista */; michael@0: michael@0: SkAutoSTMalloc<256, uint16_t> scratchGlyphs; michael@0: uint16_t* glyphs; michael@0: if (userGlyphs != NULL) { michael@0: glyphs = userGlyphs; michael@0: } else { michael@0: glyphs = scratchGlyphs.reset(glyphCount); michael@0: } michael@0: michael@0: SCRIPT_CACHE sc = 0; michael@0: switch (encoding) { michael@0: case SkTypeface::kUTF8_Encoding: { michael@0: static const int scratchCount = 256; michael@0: WCHAR scratch[scratchCount]; michael@0: int glyphIndex = 0; michael@0: const char* currentUtf8 = reinterpret_cast(chars); michael@0: SkUnichar currentChar; michael@0: if (glyphCount) { michael@0: currentChar = SkUTF8_NextUnichar(¤tUtf8); michael@0: } michael@0: while (glyphIndex < glyphCount) { michael@0: // Try a run of bmp. michael@0: int glyphsLeft = SkTMin(glyphCount - glyphIndex, scratchCount); michael@0: int runLength = 0; michael@0: while (runLength < glyphsLeft && currentChar <= 0xFFFF) { michael@0: scratch[runLength] = static_cast(currentChar); michael@0: ++runLength; michael@0: if (runLength < glyphsLeft) { michael@0: currentChar = SkUTF8_NextUnichar(¤tUtf8); michael@0: } michael@0: } michael@0: if (runLength) { michael@0: bmpCharsToGlyphs(hdc, scratch, runLength, &glyphs[glyphIndex], Ox1FHack); michael@0: glyphIndex += runLength; michael@0: } michael@0: michael@0: // Try a run of non-bmp. michael@0: while (glyphIndex < glyphCount && currentChar > 0xFFFF) { michael@0: SkUTF16_FromUnichar(currentChar, reinterpret_cast(scratch)); michael@0: glyphs[glyphIndex] = nonBmpCharToGlyph(hdc, &sc, scratch); michael@0: ++glyphIndex; michael@0: if (glyphIndex < glyphCount) { michael@0: currentChar = SkUTF8_NextUnichar(¤tUtf8); michael@0: } michael@0: } michael@0: } michael@0: break; michael@0: } michael@0: case SkTypeface::kUTF16_Encoding: { michael@0: int glyphIndex = 0; michael@0: const WCHAR* currentUtf16 = reinterpret_cast(chars); michael@0: while (glyphIndex < glyphCount) { michael@0: // Try a run of bmp. michael@0: int glyphsLeft = glyphCount - glyphIndex; michael@0: int runLength = 0; michael@0: while (runLength < glyphsLeft && !SkUTF16_IsHighSurrogate(currentUtf16[runLength])) { michael@0: ++runLength; michael@0: } michael@0: if (runLength) { michael@0: bmpCharsToGlyphs(hdc, currentUtf16, runLength, &glyphs[glyphIndex], Ox1FHack); michael@0: glyphIndex += runLength; michael@0: currentUtf16 += runLength; michael@0: } michael@0: michael@0: // Try a run of non-bmp. michael@0: while (glyphIndex < glyphCount && SkUTF16_IsHighSurrogate(*currentUtf16)) { michael@0: glyphs[glyphIndex] = nonBmpCharToGlyph(hdc, &sc, currentUtf16); michael@0: ++glyphIndex; michael@0: currentUtf16 += 2; michael@0: } michael@0: } michael@0: break; michael@0: } michael@0: case SkTypeface::kUTF32_Encoding: { michael@0: static const int scratchCount = 256; michael@0: WCHAR scratch[scratchCount]; michael@0: int glyphIndex = 0; michael@0: const uint32_t* utf32 = reinterpret_cast(chars); michael@0: while (glyphIndex < glyphCount) { michael@0: // Try a run of bmp. michael@0: int glyphsLeft = SkTMin(glyphCount - glyphIndex, scratchCount); michael@0: int runLength = 0; michael@0: while (runLength < glyphsLeft && utf32[glyphIndex + runLength] <= 0xFFFF) { michael@0: scratch[runLength] = static_cast(utf32[glyphIndex + runLength]); michael@0: ++runLength; michael@0: } michael@0: if (runLength) { michael@0: bmpCharsToGlyphs(hdc, scratch, runLength, &glyphs[glyphIndex], Ox1FHack); michael@0: glyphIndex += runLength; michael@0: } michael@0: michael@0: // Try a run of non-bmp. michael@0: while (glyphIndex < glyphCount && utf32[glyphIndex] > 0xFFFF) { michael@0: SkUTF16_FromUnichar(utf32[glyphIndex], reinterpret_cast(scratch)); michael@0: glyphs[glyphIndex] = nonBmpCharToGlyph(hdc, &sc, scratch); michael@0: ++glyphIndex; michael@0: } michael@0: } michael@0: break; michael@0: } michael@0: default: michael@0: SK_CRASH(); michael@0: } michael@0: michael@0: if (sc) { michael@0: ::ScriptFreeCache(&sc); michael@0: } michael@0: michael@0: for (int i = 0; i < glyphCount; ++i) { michael@0: if (0 == glyphs[i]) { michael@0: return i; michael@0: } michael@0: } michael@0: return glyphCount; michael@0: } michael@0: michael@0: int LogFontTypeface::onCountGlyphs() const { michael@0: HDC hdc = ::CreateCompatibleDC(NULL); michael@0: HFONT font = CreateFontIndirect(&fLogFont); michael@0: HFONT savefont = (HFONT)SelectObject(hdc, font); michael@0: michael@0: unsigned int glyphCount = calculateGlyphCount(hdc, fLogFont); michael@0: michael@0: SelectObject(hdc, savefont); michael@0: DeleteObject(font); michael@0: DeleteDC(hdc); michael@0: michael@0: return glyphCount; michael@0: } michael@0: michael@0: int LogFontTypeface::onGetUPEM() const { michael@0: HDC hdc = ::CreateCompatibleDC(NULL); michael@0: HFONT font = CreateFontIndirect(&fLogFont); michael@0: HFONT savefont = (HFONT)SelectObject(hdc, font); michael@0: michael@0: unsigned int upem = calculateUPEM(hdc, fLogFont); michael@0: michael@0: SelectObject(hdc, savefont); michael@0: DeleteObject(font); michael@0: DeleteDC(hdc); michael@0: michael@0: return upem; michael@0: } michael@0: michael@0: SkTypeface::LocalizedStrings* LogFontTypeface::onCreateFamilyNameIterator() const { michael@0: SkTypeface::LocalizedStrings* nameIter = michael@0: SkOTUtils::LocalizedStrings_NameTable::CreateForFamilyNames(*this); michael@0: if (NULL == nameIter) { michael@0: SkString familyName; michael@0: this->getFamilyName(&familyName); michael@0: SkString language("und"); //undetermined michael@0: nameIter = new SkOTUtils::LocalizedStrings_SingleName(familyName, language); michael@0: } michael@0: return nameIter; michael@0: } michael@0: michael@0: int LogFontTypeface::onGetTableTags(SkFontTableTag tags[]) const { michael@0: SkSFNTHeader header; michael@0: if (sizeof(header) != this->onGetTableData(0, 0, sizeof(header), &header)) { michael@0: return 0; michael@0: } michael@0: michael@0: int numTables = SkEndian_SwapBE16(header.numTables); michael@0: michael@0: if (tags) { michael@0: size_t size = numTables * sizeof(SkSFNTHeader::TableDirectoryEntry); michael@0: SkAutoSTMalloc<0x20, SkSFNTHeader::TableDirectoryEntry> dir(numTables); michael@0: if (size != this->onGetTableData(0, sizeof(header), size, dir.get())) { michael@0: return 0; michael@0: } michael@0: michael@0: for (int i = 0; i < numTables; ++i) { michael@0: tags[i] = SkEndian_SwapBE32(dir[i].tag); michael@0: } michael@0: } michael@0: return numTables; michael@0: } michael@0: michael@0: size_t LogFontTypeface::onGetTableData(SkFontTableTag tag, size_t offset, michael@0: size_t length, void* data) const michael@0: { michael@0: LOGFONT lf = fLogFont; michael@0: michael@0: HDC hdc = ::CreateCompatibleDC(NULL); michael@0: HFONT font = CreateFontIndirect(&lf); michael@0: HFONT savefont = (HFONT)SelectObject(hdc, font); michael@0: michael@0: tag = SkEndian_SwapBE32(tag); michael@0: if (NULL == data) { michael@0: length = 0; michael@0: } michael@0: DWORD bufferSize = GetFontData(hdc, tag, (DWORD) offset, data, (DWORD) length); michael@0: if (bufferSize == GDI_ERROR) { michael@0: call_ensure_accessible(lf); michael@0: bufferSize = GetFontData(hdc, tag, (DWORD) offset, data, (DWORD) length); michael@0: } michael@0: michael@0: SelectObject(hdc, savefont); michael@0: DeleteObject(font); michael@0: DeleteDC(hdc); michael@0: michael@0: return bufferSize == GDI_ERROR ? 0 : bufferSize; michael@0: } michael@0: michael@0: SkScalerContext* LogFontTypeface::onCreateScalerContext(const SkDescriptor* desc) const { michael@0: SkScalerContext_GDI* ctx = SkNEW_ARGS(SkScalerContext_GDI, michael@0: (const_cast(this), desc)); michael@0: if (!ctx->isValid()) { michael@0: SkDELETE(ctx); michael@0: ctx = NULL; michael@0: } michael@0: return ctx; michael@0: } michael@0: michael@0: void LogFontTypeface::onFilterRec(SkScalerContextRec* rec) const { michael@0: if (rec->fFlags & SkScalerContext::kLCD_BGROrder_Flag || michael@0: rec->fFlags & SkScalerContext::kLCD_Vertical_Flag) michael@0: { michael@0: rec->fMaskFormat = SkMask::kA8_Format; michael@0: rec->fFlags |= SkScalerContext::kGenA8FromLCD_Flag; michael@0: } michael@0: michael@0: unsigned flagsWeDontSupport = SkScalerContext::kDevKernText_Flag | michael@0: SkScalerContext::kForceAutohinting_Flag | michael@0: SkScalerContext::kEmbeddedBitmapText_Flag | michael@0: SkScalerContext::kEmbolden_Flag | michael@0: SkScalerContext::kLCD_BGROrder_Flag | michael@0: SkScalerContext::kLCD_Vertical_Flag; michael@0: rec->fFlags &= ~flagsWeDontSupport; michael@0: michael@0: SkPaint::Hinting h = rec->getHinting(); michael@0: switch (h) { michael@0: case SkPaint::kNo_Hinting: michael@0: break; michael@0: case SkPaint::kSlight_Hinting: michael@0: // Only do slight hinting when axis aligned. michael@0: // TODO: re-enable slight hinting when FontHostTest can pass. michael@0: //if (!isAxisAligned(*rec)) { michael@0: h = SkPaint::kNo_Hinting; michael@0: //} michael@0: break; michael@0: case SkPaint::kNormal_Hinting: michael@0: case SkPaint::kFull_Hinting: michael@0: // TODO: need to be able to distinguish subpixel positioned glyphs michael@0: // and linear metrics. michael@0: //rec->fFlags &= ~SkScalerContext::kSubpixelPositioning_Flag; michael@0: h = SkPaint::kNormal_Hinting; michael@0: break; michael@0: default: michael@0: SkDEBUGFAIL("unknown hinting"); michael@0: } michael@0: //TODO: if this is a bitmap font, squash hinting and subpixel. michael@0: rec->setHinting(h); michael@0: michael@0: // turn this off since GDI might turn A8 into BW! Need a bigger fix. michael@0: #if 0 michael@0: // Disable LCD when rotated, since GDI's output is ugly michael@0: if (isLCD(*rec) && !isAxisAligned(*rec)) { michael@0: rec->fMaskFormat = SkMask::kA8_Format; michael@0: } michael@0: #endif michael@0: michael@0: if (!fCanBeLCD && isLCD(*rec)) { michael@0: rec->fMaskFormat = SkMask::kA8_Format; michael@0: rec->fFlags &= ~SkScalerContext::kGenA8FromLCD_Flag; michael@0: } michael@0: } michael@0: michael@0: /////////////////////////////////////////////////////////////////////////////// michael@0: michael@0: #include "SkFontMgr.h" michael@0: #include "SkDataTable.h" michael@0: michael@0: static bool valid_logfont_for_enum(const LOGFONT& lf) { michael@0: // TODO: Vector FON is unsupported and should not be listed. michael@0: return michael@0: // Ignore implicit vertical variants. michael@0: lf.lfFaceName[0] && lf.lfFaceName[0] != '@' michael@0: michael@0: // DEFAULT_CHARSET is used to get all fonts, but also implies all michael@0: // character sets. Filter assuming all fonts support ANSI_CHARSET. michael@0: && ANSI_CHARSET == lf.lfCharSet michael@0: ; michael@0: } michael@0: michael@0: /** An EnumFontFamExProc implementation which interprets builderParam as michael@0: * an SkTDArray* and appends logfonts which michael@0: * pass the valid_logfont_for_enum predicate. michael@0: */ michael@0: static int CALLBACK enum_family_proc(const LOGFONT* lf, const TEXTMETRIC*, michael@0: DWORD fontType, LPARAM builderParam) { michael@0: if (valid_logfont_for_enum(*lf)) { michael@0: SkTDArray* array = (SkTDArray*)builderParam; michael@0: *array->append() = *(ENUMLOGFONTEX*)lf; michael@0: } michael@0: return 1; // non-zero means continue michael@0: } michael@0: michael@0: static SkFontStyle compute_fontstyle(const LOGFONT& lf) { michael@0: return SkFontStyle(lf.lfWeight, SkFontStyle::kNormal_Width, michael@0: lf.lfItalic ? SkFontStyle::kItalic_Slant michael@0: : SkFontStyle::kUpright_Slant); michael@0: } michael@0: michael@0: class SkFontStyleSetGDI : public SkFontStyleSet { michael@0: public: michael@0: SkFontStyleSetGDI(const TCHAR familyName[]) { michael@0: LOGFONT lf; michael@0: sk_bzero(&lf, sizeof(lf)); michael@0: lf.lfCharSet = DEFAULT_CHARSET; michael@0: _tcscpy_s(lf.lfFaceName, familyName); michael@0: michael@0: HDC hdc = ::CreateCompatibleDC(NULL); michael@0: ::EnumFontFamiliesEx(hdc, &lf, enum_family_proc, (LPARAM)&fArray, 0); michael@0: ::DeleteDC(hdc); michael@0: } michael@0: michael@0: virtual int count() SK_OVERRIDE { michael@0: return fArray.count(); michael@0: } michael@0: michael@0: virtual void getStyle(int index, SkFontStyle* fs, SkString* styleName) SK_OVERRIDE { michael@0: if (fs) { michael@0: *fs = compute_fontstyle(fArray[index].elfLogFont); michael@0: } michael@0: if (styleName) { michael@0: const ENUMLOGFONTEX& ref = fArray[index]; michael@0: // For some reason, ENUMLOGFONTEX and LOGFONT disagree on their type in the michael@0: // non-unicode version. michael@0: // ENUMLOGFONTEX uses BYTE michael@0: // LOGFONT uses CHAR michael@0: // Here we assert they that the style name is logically the same (size) as michael@0: // a TCHAR, so we can use the same converter function. michael@0: SkASSERT(sizeof(TCHAR) == sizeof(ref.elfStyle[0])); michael@0: tchar_to_skstring((const TCHAR*)ref.elfStyle, styleName); michael@0: } michael@0: } michael@0: michael@0: virtual SkTypeface* createTypeface(int index) SK_OVERRIDE { michael@0: return SkCreateTypefaceFromLOGFONT(fArray[index].elfLogFont); michael@0: } michael@0: michael@0: virtual SkTypeface* matchStyle(const SkFontStyle& pattern) SK_OVERRIDE { michael@0: // todo: michael@0: return SkCreateTypefaceFromLOGFONT(fArray[0].elfLogFont); michael@0: } michael@0: michael@0: private: michael@0: SkTDArray fArray; michael@0: }; michael@0: michael@0: class SkFontMgrGDI : public SkFontMgr { michael@0: public: michael@0: SkFontMgrGDI() { michael@0: LOGFONT lf; michael@0: sk_bzero(&lf, sizeof(lf)); michael@0: lf.lfCharSet = DEFAULT_CHARSET; michael@0: michael@0: HDC hdc = ::CreateCompatibleDC(NULL); michael@0: ::EnumFontFamiliesEx(hdc, &lf, enum_family_proc, (LPARAM)&fLogFontArray, 0); michael@0: ::DeleteDC(hdc); michael@0: } michael@0: michael@0: protected: michael@0: virtual int onCountFamilies() const SK_OVERRIDE { michael@0: return fLogFontArray.count(); michael@0: } michael@0: michael@0: virtual void onGetFamilyName(int index, SkString* familyName) const SK_OVERRIDE { michael@0: SkASSERT((unsigned)index < (unsigned)fLogFontArray.count()); michael@0: tchar_to_skstring(fLogFontArray[index].elfLogFont.lfFaceName, familyName); michael@0: } michael@0: michael@0: virtual SkFontStyleSet* onCreateStyleSet(int index) const SK_OVERRIDE { michael@0: SkASSERT((unsigned)index < (unsigned)fLogFontArray.count()); michael@0: return SkNEW_ARGS(SkFontStyleSetGDI, (fLogFontArray[index].elfLogFont.lfFaceName)); michael@0: } michael@0: michael@0: virtual SkFontStyleSet* onMatchFamily(const char familyName[]) const SK_OVERRIDE { michael@0: if (NULL == familyName) { michael@0: familyName = ""; // do we need this check??? michael@0: } michael@0: LOGFONT lf; michael@0: logfont_for_name(familyName, &lf); michael@0: return SkNEW_ARGS(SkFontStyleSetGDI, (lf.lfFaceName)); michael@0: } michael@0: michael@0: virtual SkTypeface* onMatchFamilyStyle(const char familyName[], michael@0: const SkFontStyle& fontstyle) const SK_OVERRIDE { michael@0: // could be in base impl michael@0: SkAutoTUnref sset(this->matchFamily(familyName)); michael@0: return sset->matchStyle(fontstyle); michael@0: } michael@0: michael@0: virtual SkTypeface* onMatchFaceStyle(const SkTypeface* familyMember, michael@0: const SkFontStyle& fontstyle) const SK_OVERRIDE { michael@0: // could be in base impl michael@0: SkString familyName; michael@0: ((LogFontTypeface*)familyMember)->getFamilyName(&familyName); michael@0: return this->matchFamilyStyle(familyName.c_str(), fontstyle); michael@0: } michael@0: michael@0: virtual SkTypeface* onCreateFromStream(SkStream* stream, int ttcIndex) const SK_OVERRIDE { michael@0: return create_from_stream(stream); michael@0: } michael@0: michael@0: virtual SkTypeface* onCreateFromData(SkData* data, int ttcIndex) const SK_OVERRIDE { michael@0: // could be in base impl michael@0: SkAutoTUnref stream(SkNEW_ARGS(SkMemoryStream, (data))); michael@0: return this->createFromStream(stream); michael@0: } michael@0: michael@0: virtual SkTypeface* onCreateFromFile(const char path[], int ttcIndex) const SK_OVERRIDE { michael@0: // could be in base impl michael@0: SkAutoTUnref stream(SkStream::NewFromFile(path)); michael@0: return this->createFromStream(stream); michael@0: } michael@0: michael@0: virtual SkTypeface* onLegacyCreateTypeface(const char familyName[], michael@0: unsigned styleBits) const SK_OVERRIDE { michael@0: LOGFONT lf; michael@0: if (NULL == familyName) { michael@0: lf = get_default_font(); michael@0: } else { michael@0: logfont_for_name(familyName, &lf); michael@0: } michael@0: setStyle(&lf, (SkTypeface::Style)styleBits); michael@0: return SkCreateTypefaceFromLOGFONT(lf); michael@0: } michael@0: michael@0: private: michael@0: SkTDArray fLogFontArray; michael@0: }; michael@0: michael@0: /////////////////////////////////////////////////////////////////////////////// michael@0: michael@0: SkFontMgr* SkFontMgr_New_GDI() { michael@0: return SkNEW(SkFontMgrGDI); michael@0: }