Upstream version 5.34.92.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / platform / fonts / skia / SimpleFontDataSkia.cpp
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 "platform/fonts/FontDescription.h"
40 #include "platform/fonts/VDMXParser.h"
41 #include "platform/geometry/FloatRect.h"
42 #include "wtf/unicode/Unicode.h"
43
44 #if OS(WIN)
45 #include "platform/win/HWndDC.h"
46 #endif
47
48 namespace WebCore {
49
50 // This is the largest VDMX table which we'll try to load and parse.
51 static const size_t maxVDMXTableSize = 1024 * 1024; // 1 MB
52
53 void SimpleFontData::platformInit()
54 {
55     if (!m_platformData.size()) {
56         m_fontMetrics.reset();
57         m_avgCharWidth = 0;
58         m_maxCharWidth = 0;
59         return;
60     }
61
62     SkPaint paint;
63     SkPaint::FontMetrics metrics;
64
65     m_platformData.setupPaint(&paint);
66     paint.getFontMetrics(&metrics);
67     SkTypeface* face = paint.getTypeface();
68     ASSERT(face);
69
70     int vdmxAscent = 0, vdmxDescent = 0;
71     bool isVDMXValid = false;
72
73 #if OS(LINUX) || OS(ANDROID)
74     // Manually digging up VDMX metrics is only applicable when bytecode hinting using FreeType.
75     // With GDI, the metrics will already have taken this into account (as needed).
76     // With DirectWrite or CoreText, no bytecode hinting is ever done.
77     // This code should be pushed into FreeType (hinted font metrics).
78     static const uint32_t vdmxTag = SkSetFourByteTag('V', 'D', 'M', 'X');
79     int pixelSize = m_platformData.size() + 0.5;
80     if (!paint.isAutohinted()
81         &&    (paint.getHinting() == SkPaint::kFull_Hinting
82             || paint.getHinting() == SkPaint::kNormal_Hinting))
83     {
84         size_t vdmxSize = face->getTableSize(vdmxTag);
85         if (vdmxSize && vdmxSize < maxVDMXTableSize) {
86             uint8_t* vdmxTable = (uint8_t*) fastMalloc(vdmxSize);
87             if (vdmxTable
88                 && face->getTableData(vdmxTag, 0, vdmxSize, vdmxTable) == vdmxSize
89                 && parseVDMX(&vdmxAscent, &vdmxDescent, vdmxTable, vdmxSize, pixelSize))
90                 isVDMXValid = true;
91             fastFree(vdmxTable);
92         }
93     }
94 #endif
95
96     float ascent;
97     float descent;
98
99     // Beware those who step here: This code is designed to match Win32 font
100     // metrics *exactly* (except the adjustment of ascent/descent on Linux/Android).
101     if (isVDMXValid) {
102         ascent = vdmxAscent;
103         descent = -vdmxDescent;
104     } else {
105         ascent = SkScalarRoundToInt(-metrics.fAscent);
106         descent = SkScalarRoundToInt(metrics.fDescent);
107 #if OS(LINUX) || OS(ANDROID)
108         // When subpixel positioning is enabled, if the descent is rounded down, the descent part
109         // of the glyph may be truncated when displayed in a 'overflow: hidden' container.
110         // To avoid that, borrow 1 unit from the ascent when possible.
111         // FIXME: This can be removed if sub-pixel ascent/descent is supported.
112         if (platformData().fontRenderStyle().useSubpixelPositioning && descent < SkScalarToFloat(metrics.fDescent) && ascent >= 1) {
113             ++descent;
114             --ascent;
115         }
116 #endif
117     }
118
119     m_fontMetrics.setAscent(ascent);
120     m_fontMetrics.setDescent(descent);
121
122     float xHeight;
123     if (metrics.fXHeight) {
124         xHeight = metrics.fXHeight;
125         m_fontMetrics.setXHeight(xHeight);
126     } else {
127         xHeight = ascent * 0.56; // Best guess from Windows font metrics.
128         m_fontMetrics.setXHeight(xHeight);
129         m_fontMetrics.setHasXHeight(false);
130     }
131
132     float lineGap = SkScalarToFloat(metrics.fLeading);
133     m_fontMetrics.setLineGap(lineGap);
134     m_fontMetrics.setLineSpacing(lroundf(ascent) + lroundf(descent) + lroundf(lineGap));
135
136     if (platformData().orientation() == Vertical && !isTextOrientationFallback()) {
137         static const uint32_t vheaTag = SkSetFourByteTag('v', 'h', 'e', 'a');
138         static const uint32_t vorgTag = SkSetFourByteTag('V', 'O', 'R', 'G');
139         size_t vheaSize = face->getTableSize(vheaTag);
140         size_t vorgSize = face->getTableSize(vorgTag);
141         if ((vheaSize > 0) || (vorgSize > 0))
142             m_hasVerticalGlyphs = true;
143     }
144
145     // In WebKit/WebCore/platform/graphics/SimpleFontData.cpp, m_spaceWidth is
146     // calculated for us, but we need to calculate m_maxCharWidth and
147     // m_avgCharWidth in order for text entry widgets to be sized correctly.
148 #if OS(WIN)
149     m_maxCharWidth = SkScalarRoundToInt(metrics.fMaxCharWidth);
150 #else
151     // FIXME: This seems incorrect and should probably use fMaxCharWidth as
152     // the code path above.
153     SkScalar xRange = metrics.fXMax - metrics.fXMin;
154     m_maxCharWidth = SkScalarRoundToInt(xRange * SkScalarRoundToInt(m_platformData.size()));
155 #endif
156
157     if (metrics.fAvgCharWidth)
158         m_avgCharWidth = SkScalarRoundToInt(metrics.fAvgCharWidth);
159     else {
160         m_avgCharWidth = xHeight;
161
162         GlyphPage* glyphPageZero = GlyphPageTreeNode::getRootChild(this, 0)->page();
163
164         if (glyphPageZero) {
165             static const UChar32 xChar = 'x';
166             const Glyph xGlyph = glyphPageZero->glyphForCharacter(xChar);
167
168             if (xGlyph) {
169                 // In widthForGlyph(), xGlyph will be compared with
170                 // m_zeroWidthSpaceGlyph, which isn't initialized yet here.
171                 // Initialize it with zero to make sure widthForGlyph() returns
172                 // the right width.
173                 m_zeroWidthSpaceGlyph = 0;
174                 m_avgCharWidth = widthForGlyph(xGlyph);
175             }
176         }
177     }
178
179     if (int unitsPerEm = face->getUnitsPerEm())
180         m_fontMetrics.setUnitsPerEm(unitsPerEm);
181 }
182
183 void SimpleFontData::platformCharWidthInit()
184 {
185     // charwidths are set in platformInit.
186 }
187
188 void SimpleFontData::platformDestroy()
189 {
190 }
191
192 PassRefPtr<SimpleFontData> SimpleFontData::platformCreateScaledFontData(const FontDescription& fontDescription, float scaleFactor) const
193 {
194     const float scaledSize = lroundf(fontDescription.computedSize() * scaleFactor);
195     return SimpleFontData::create(FontPlatformData(m_platformData, scaledSize), isCustomFont() ? CustomFontData::create(false) : 0);
196 }
197
198 bool SimpleFontData::containsCharacters(const UChar* characters, int length) const
199 {
200     SkPaint paint;
201     static const unsigned maxBufferCount = 64;
202     uint16_t glyphs[maxBufferCount];
203
204     m_platformData.setupPaint(&paint);
205     paint.setTextEncoding(SkPaint::kUTF16_TextEncoding);
206
207     while (length > 0) {
208         int n = SkMin32(length, SK_ARRAY_COUNT(glyphs));
209
210         // textToGlyphs takes a byte count so we double the character count.
211         int count = paint.textToGlyphs(characters, n * 2, glyphs);
212         for (int i = 0; i < count; i++) {
213             if (!glyphs[i])
214                 return false; // missing glyph
215         }
216
217         characters += n;
218         length -= n;
219     }
220
221     return true;
222 }
223
224 void SimpleFontData::determinePitch()
225 {
226     m_treatAsFixedPitch = platformData().isFixedPitch();
227 }
228
229 static inline void getSkiaBoundsForGlyph(SkPaint& paint, Glyph glyph, SkRect& bounds)
230 {
231     paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
232
233     SkPath path;
234     paint.getTextPath(&glyph, sizeof(glyph), 0, 0, &path);
235     bounds = path.getBounds();
236
237     if (!paint.isSubpixelText()) {
238         SkIRect ir;
239         bounds.round(&ir);
240         bounds.set(ir);
241     }
242 }
243
244 FloatRect SimpleFontData::platformBoundsForGlyph(Glyph glyph) const
245 {
246     if (!m_platformData.size())
247         return FloatRect();
248
249     SkASSERT(sizeof(glyph) == 2); // compile-time assert
250
251     SkPaint paint;
252     m_platformData.setupPaint(&paint);
253
254     SkRect bounds;
255     getSkiaBoundsForGlyph(paint, glyph, bounds);
256     return FloatRect(bounds);
257 }
258
259 float SimpleFontData::platformWidthForGlyph(Glyph glyph) const
260 {
261     if (!m_platformData.size())
262         return 0;
263
264     SkASSERT(sizeof(glyph) == 2); // compile-time assert
265
266     SkPaint paint;
267
268     m_platformData.setupPaint(&paint);
269
270     paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
271     SkScalar width = paint.measureText(&glyph, 2);
272     if (!paint.isSubpixelText())
273         width = SkScalarRoundToInt(width);
274     return SkScalarToFloat(width);
275 }
276
277 #if USE(HARFBUZZ)
278 bool SimpleFontData::canRenderCombiningCharacterSequence(const UChar* characters, size_t length) const
279 {
280     if (!m_combiningCharacterSequenceSupport)
281         m_combiningCharacterSequenceSupport = adoptPtr(new HashMap<String, bool>);
282
283     WTF::HashMap<String, bool>::AddResult addResult = m_combiningCharacterSequenceSupport->add(String(characters, length), false);
284     if (!addResult.isNewEntry)
285         return addResult.iterator->value;
286
287     UErrorCode error = U_ZERO_ERROR;
288     Vector<UChar, 4> normalizedCharacters(length);
289     int32_t normalizedLength = unorm_normalize(characters, length, UNORM_NFC, UNORM_UNICODE_3_2, &normalizedCharacters[0], length, &error);
290     // Can't render if we have an error or no composition occurred.
291     if (U_FAILURE(error) || (static_cast<size_t>(normalizedLength) == length))
292         return false;
293
294     SkPaint paint;
295     m_platformData.setupPaint(&paint);
296     paint.setTextEncoding(SkPaint::kUTF16_TextEncoding);
297     if (paint.textToGlyphs(&normalizedCharacters[0], normalizedLength * 2, 0)) {
298         addResult.iterator->value = true;
299         return true;
300     }
301     return false;
302 }
303 #endif
304
305 } // namespace WebCore