• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  *     * Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *     * Redistributions in binary form must reproduce the above
11  * copyright notice, this list of conditions and the following disclaimer
12  * in the documentation and/or other materials provided with the
13  * distribution.
14  *     * Neither the name of Google Inc. nor the names of its
15  * contributors may be used to endorse or promote products derived from
16  * this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30 
31 #include "config.h"
32 #include "platform/fonts/SimpleFontData.h"
33 
34 #include <unicode/normlzr.h>
35 #include "SkPaint.h"
36 #include "SkPath.h"
37 #include "SkTypeface.h"
38 #include "SkTypes.h"
39 #include "SkUtils.h"
40 #include "platform/fonts/FontDescription.h"
41 #include "platform/fonts/GlyphPage.h"
42 #include "platform/fonts/VDMXParser.h"
43 #include "platform/geometry/FloatRect.h"
44 #include "wtf/unicode/Unicode.h"
45 
46 namespace WebCore {
47 
48 // This is the largest VDMX table which we'll try to load and parse.
49 static const size_t maxVDMXTableSize = 1024 * 1024; // 1 MB
50 
platformInit()51 void SimpleFontData::platformInit()
52 {
53     if (!m_platformData.size()) {
54         m_fontMetrics.reset();
55         m_avgCharWidth = 0;
56         m_maxCharWidth = 0;
57         return;
58     }
59 
60     SkPaint paint;
61     SkPaint::FontMetrics metrics;
62 
63     m_platformData.setupPaint(&paint);
64     paint.getFontMetrics(&metrics);
65     SkTypeface* face = paint.getTypeface();
66     ASSERT(face);
67 
68     int vdmxAscent = 0, vdmxDescent = 0;
69     bool isVDMXValid = false;
70 
71 #if OS(LINUX) || OS(ANDROID)
72     // Manually digging up VDMX metrics is only applicable when bytecode hinting using FreeType.
73     // With GDI, the metrics will already have taken this into account (as needed).
74     // With DirectWrite or CoreText, no bytecode hinting is ever done.
75     // This code should be pushed into FreeType (hinted font metrics).
76     static const uint32_t vdmxTag = SkSetFourByteTag('V', 'D', 'M', 'X');
77     int pixelSize = m_platformData.size() + 0.5;
78     if (!paint.isAutohinted()
79         &&    (paint.getHinting() == SkPaint::kFull_Hinting
80             || paint.getHinting() == SkPaint::kNormal_Hinting))
81     {
82         size_t vdmxSize = face->getTableSize(vdmxTag);
83         if (vdmxSize && vdmxSize < maxVDMXTableSize) {
84             uint8_t* vdmxTable = (uint8_t*) fastMalloc(vdmxSize);
85             if (vdmxTable
86                 && face->getTableData(vdmxTag, 0, vdmxSize, vdmxTable) == vdmxSize
87                 && parseVDMX(&vdmxAscent, &vdmxDescent, vdmxTable, vdmxSize, pixelSize))
88                 isVDMXValid = true;
89             fastFree(vdmxTable);
90         }
91     }
92 #endif
93 
94     float ascent;
95     float descent;
96 
97     // Beware those who step here: This code is designed to match Win32 font
98     // metrics *exactly* (except the adjustment of ascent/descent on Linux/Android).
99     if (isVDMXValid) {
100         ascent = vdmxAscent;
101         descent = -vdmxDescent;
102     } else {
103         ascent = SkScalarRoundToInt(-metrics.fAscent);
104         descent = SkScalarRoundToInt(metrics.fDescent);
105 #if OS(LINUX) || OS(ANDROID)
106         // When subpixel positioning is enabled, if the descent is rounded down, the descent part
107         // of the glyph may be truncated when displayed in a 'overflow: hidden' container.
108         // To avoid that, borrow 1 unit from the ascent when possible.
109         // FIXME: This can be removed if sub-pixel ascent/descent is supported.
110         if (platformData().fontRenderStyle().useSubpixelPositioning && descent < SkScalarToFloat(metrics.fDescent) && ascent >= 1) {
111             ++descent;
112             --ascent;
113         }
114 #endif
115     }
116 
117     m_fontMetrics.setAscent(ascent);
118     m_fontMetrics.setDescent(descent);
119 
120     float xHeight;
121     if (metrics.fXHeight) {
122         xHeight = metrics.fXHeight;
123         m_fontMetrics.setXHeight(xHeight);
124     } else {
125         xHeight = ascent * 0.56; // Best guess from Windows font metrics.
126         m_fontMetrics.setXHeight(xHeight);
127         m_fontMetrics.setHasXHeight(false);
128     }
129 
130     float lineGap = SkScalarToFloat(metrics.fLeading);
131     m_fontMetrics.setLineGap(lineGap);
132     m_fontMetrics.setLineSpacing(lroundf(ascent) + lroundf(descent) + lroundf(lineGap));
133 
134     SkScalar underlineThickness, underlinePosition;
135     if (metrics.hasUnderlineThickness(&underlineThickness)
136         && metrics.hasUnderlinePosition(&underlinePosition)) {
137         m_fontMetrics.setUnderlineThickness(SkScalarToFloat(underlineThickness));
138         m_fontMetrics.setUnderlinePosition(SkScalarToFloat(-underlinePosition));
139     }
140 
141     if (platformData().orientation() == Vertical && !isTextOrientationFallback()) {
142         static const uint32_t vheaTag = SkSetFourByteTag('v', 'h', 'e', 'a');
143         static const uint32_t vorgTag = SkSetFourByteTag('V', 'O', 'R', 'G');
144         size_t vheaSize = face->getTableSize(vheaTag);
145         size_t vorgSize = face->getTableSize(vorgTag);
146         if ((vheaSize > 0) || (vorgSize > 0))
147             m_hasVerticalGlyphs = true;
148     }
149 
150     // In WebKit/WebCore/platform/graphics/SimpleFontData.cpp, m_spaceWidth is
151     // calculated for us, but we need to calculate m_maxCharWidth and
152     // m_avgCharWidth in order for text entry widgets to be sized correctly.
153 #if OS(WIN)
154     m_maxCharWidth = SkScalarRoundToInt(metrics.fMaxCharWidth);
155 #else
156     // FIXME: This seems incorrect and should probably use fMaxCharWidth as
157     // the code path above.
158     SkScalar xRange = metrics.fXMax - metrics.fXMin;
159     m_maxCharWidth = SkScalarRoundToInt(xRange * SkScalarRoundToInt(m_platformData.size()));
160 #endif
161 
162     if (metrics.fAvgCharWidth)
163         m_avgCharWidth = SkScalarRoundToInt(metrics.fAvgCharWidth);
164     else {
165         m_avgCharWidth = xHeight;
166 
167         GlyphPage* glyphPageZero = GlyphPageTreeNode::getRootChild(this, 0)->page();
168 
169         if (glyphPageZero) {
170             static const UChar32 xChar = 'x';
171             const Glyph xGlyph = glyphPageZero->glyphForCharacter(xChar);
172 
173             if (xGlyph) {
174                 // In widthForGlyph(), xGlyph will be compared with
175                 // m_zeroWidthSpaceGlyph, which isn't initialized yet here.
176                 // Initialize it with zero to make sure widthForGlyph() returns
177                 // the right width.
178                 m_zeroWidthSpaceGlyph = 0;
179                 m_avgCharWidth = widthForGlyph(xGlyph);
180             }
181         }
182     }
183 
184     if (int unitsPerEm = face->getUnitsPerEm())
185         m_fontMetrics.setUnitsPerEm(unitsPerEm);
186 }
187 
platformCharWidthInit()188 void SimpleFontData::platformCharWidthInit()
189 {
190     // charwidths are set in platformInit.
191 }
192 
platformDestroy()193 void SimpleFontData::platformDestroy()
194 {
195 }
196 
platformCreateScaledFontData(const FontDescription & fontDescription,float scaleFactor) const197 PassRefPtr<SimpleFontData> SimpleFontData::platformCreateScaledFontData(const FontDescription& fontDescription, float scaleFactor) const
198 {
199     const float scaledSize = lroundf(fontDescription.computedSize() * scaleFactor);
200     return SimpleFontData::create(FontPlatformData(m_platformData, scaledSize), isCustomFont() ? CustomFontData::create() : nullptr);
201 }
202 
determinePitch()203 void SimpleFontData::determinePitch()
204 {
205     m_treatAsFixedPitch = platformData().isFixedPitch();
206 }
207 
getSkiaBoundsForGlyph(SkPaint & paint,Glyph glyph,SkRect & bounds)208 static inline void getSkiaBoundsForGlyph(SkPaint& paint, Glyph glyph, SkRect& bounds)
209 {
210     paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
211 
212     SkPath path;
213     paint.getTextPath(&glyph, sizeof(glyph), 0, 0, &path);
214     bounds = path.getBounds();
215 
216     if (!paint.isSubpixelText()) {
217         SkIRect ir;
218         bounds.round(&ir);
219         bounds.set(ir);
220     }
221 }
222 
platformBoundsForGlyph(Glyph glyph) const223 FloatRect SimpleFontData::platformBoundsForGlyph(Glyph glyph) const
224 {
225     if (!m_platformData.size())
226         return FloatRect();
227 
228     SkASSERT(sizeof(glyph) == 2); // compile-time assert
229 
230     SkPaint paint;
231     m_platformData.setupPaint(&paint);
232 
233     SkRect bounds;
234     getSkiaBoundsForGlyph(paint, glyph, bounds);
235     return FloatRect(bounds);
236 }
237 
platformWidthForGlyph(Glyph glyph) const238 float SimpleFontData::platformWidthForGlyph(Glyph glyph) const
239 {
240     if (!m_platformData.size())
241         return 0;
242 
243     SkASSERT(sizeof(glyph) == 2); // compile-time assert
244 
245     SkPaint paint;
246 
247     m_platformData.setupPaint(&paint);
248 
249     paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
250     SkScalar width = paint.measureText(&glyph, 2);
251     if (!paint.isSubpixelText())
252         width = SkScalarRoundToInt(width);
253     return SkScalarToFloat(width);
254 }
255 
256 #if USE(HARFBUZZ)
canRenderCombiningCharacterSequence(const UChar * characters,size_t length) const257 bool SimpleFontData::canRenderCombiningCharacterSequence(const UChar* characters, size_t length) const
258 {
259     if (!m_combiningCharacterSequenceSupport)
260         m_combiningCharacterSequenceSupport = adoptPtr(new HashMap<String, bool>);
261 
262     WTF::HashMap<String, bool>::AddResult addResult = m_combiningCharacterSequenceSupport->add(String(characters, length), false);
263     if (!addResult.isNewEntry)
264         return addResult.storedValue->value;
265 
266     UErrorCode error = U_ZERO_ERROR;
267     Vector<UChar, 4> normalizedCharacters(length);
268     int32_t normalizedLength = unorm_normalize(characters, length, UNORM_NFC, UNORM_UNICODE_3_2, &normalizedCharacters[0], length, &error);
269     // Can't render if we have an error or no composition occurred.
270     if (U_FAILURE(error) || (static_cast<size_t>(normalizedLength) == length))
271         return false;
272 
273     SkPaint paint;
274     m_platformData.setupPaint(&paint);
275     paint.setTextEncoding(SkPaint::kUTF16_TextEncoding);
276     if (paint.textToGlyphs(&normalizedCharacters[0], normalizedLength * 2, 0)) {
277         addResult.storedValue->value = true;
278         return true;
279     }
280     return false;
281 }
282 #endif
283 
fillGlyphPage(GlyphPage * pageToFill,unsigned offset,unsigned length,UChar * buffer,unsigned bufferLength) const284 bool SimpleFontData::fillGlyphPage(GlyphPage* pageToFill, unsigned offset, unsigned length, UChar* buffer, unsigned bufferLength) const
285 {
286     if (SkUTF16_IsHighSurrogate(buffer[bufferLength-1])) {
287         SkDebugf("%s last char is high-surrogate", __FUNCTION__);
288         return false;
289     }
290 
291     SkAutoSTMalloc<GlyphPage::size, uint16_t> glyphStorage(length);
292 
293     uint16_t* glyphs = glyphStorage.get();
294     SkTypeface* typeface = platformData().typeface();
295     typeface->charsToGlyphs(buffer, SkTypeface::kUTF16_Encoding, glyphs, length);
296 
297     bool haveGlyphs = false;
298     for (unsigned i = 0; i < length; i++) {
299         if (glyphs[i]) {
300             pageToFill->setGlyphDataForIndex(offset + i, glyphs[i], this);
301             haveGlyphs = true;
302         }
303     }
304 
305     return haveGlyphs;
306 }
307 
308 } // namespace WebCore
309