Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / platform / fonts / Font.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2000 Dirk Mueller (mueller@kde.org)
5  * Copyright (C) 2003, 2006, 2010, 2011 Apple Inc. All rights reserved.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public License
18  * along with this library; see the file COPYING.LIB.  If not, write to
19  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20  * Boston, MA 02110-1301, USA.
21  *
22  */
23
24 #include "config.h"
25 #include "platform/fonts/Font.h"
26
27 #include "platform/LayoutUnit.h"
28 #include "platform/RuntimeEnabledFeatures.h"
29 #include "platform/fonts/Character.h"
30 #include "platform/fonts/FontCache.h"
31 #include "platform/fonts/FontFallbackList.h"
32 #include "platform/fonts/FontPlatformFeatures.h"
33 #include "platform/fonts/GlyphBuffer.h"
34 #include "platform/fonts/GlyphPageTreeNode.h"
35 #include "platform/fonts/SimpleFontData.h"
36 #include "platform/fonts/WidthIterator.h"
37 #include "platform/geometry/FloatRect.h"
38 #include "platform/graphics/GraphicsContext.h"
39 #include "platform/text/TextRun.h"
40 #include "wtf/MainThread.h"
41 #include "wtf/StdLibExtras.h"
42 #include "wtf/unicode/CharacterNames.h"
43 #include "wtf/unicode/Unicode.h"
44
45 using namespace WTF;
46 using namespace Unicode;
47
48 namespace blink {
49
50 CodePath Font::s_codePath = AutoPath;
51
52 // ============================================================================================
53 // Font Implementation (Cross-Platform Portion)
54 // ============================================================================================
55
56 Font::Font()
57 {
58 }
59
60 Font::Font(const FontDescription& fd)
61     : m_fontDescription(fd)
62 {
63 }
64
65 Font::Font(const Font& other)
66     : m_fontDescription(other.m_fontDescription)
67     , m_fontFallbackList(other.m_fontFallbackList)
68 {
69 }
70
71 Font& Font::operator=(const Font& other)
72 {
73     m_fontDescription = other.m_fontDescription;
74     m_fontFallbackList = other.m_fontFallbackList;
75     return *this;
76 }
77
78 bool Font::operator==(const Font& other) const
79 {
80     // Our FontData don't have to be checked, since checking the font description will be fine.
81     // FIXME: This does not work if the font was made with the FontPlatformData constructor.
82     if (loadingCustomFonts() || other.loadingCustomFonts())
83         return false;
84
85     FontSelector* first = m_fontFallbackList ? m_fontFallbackList->fontSelector() : 0;
86     FontSelector* second = other.m_fontFallbackList ? other.m_fontFallbackList->fontSelector() : 0;
87
88     return first == second
89         && m_fontDescription == other.m_fontDescription
90         && (m_fontFallbackList ? m_fontFallbackList->fontSelectorVersion() : 0) == (other.m_fontFallbackList ? other.m_fontFallbackList->fontSelectorVersion() : 0)
91         && (m_fontFallbackList ? m_fontFallbackList->generation() : 0) == (other.m_fontFallbackList ? other.m_fontFallbackList->generation() : 0);
92 }
93
94 void Font::update(PassRefPtrWillBeRawPtr<FontSelector> fontSelector) const
95 {
96     // FIXME: It is pretty crazy that we are willing to just poke into a RefPtr, but it ends up
97     // being reasonably safe (because inherited fonts in the render tree pick up the new
98     // style anyway. Other copies are transient, e.g., the state in the GraphicsContext, and
99     // won't stick around long enough to get you in trouble). Still, this is pretty disgusting,
100     // and could eventually be rectified by using RefPtrs for Fonts themselves.
101     if (!m_fontFallbackList)
102         m_fontFallbackList = FontFallbackList::create();
103     m_fontFallbackList->invalidate(fontSelector);
104 }
105
106 float Font::drawText(GraphicsContext* context, const TextRunPaintInfo& runInfo, const FloatPoint& point, CustomFontNotReadyAction customFontNotReadyAction) const
107 {
108     // Don't draw anything while we are using custom fonts that are in the process of loading,
109     // except if the 'force' argument is set to true (in which case it will use a fallback
110     // font).
111     if (shouldSkipDrawing() && customFontNotReadyAction == DoNotPaintIfFontNotReady)
112         return 0;
113
114     CodePath codePathToUse = codePath(runInfo.run);
115     // FIXME: Use the fast code path once it handles partial runs with kerning and ligatures. See http://webkit.org/b/100050
116     if (codePathToUse != ComplexPath && fontDescription().typesettingFeatures() && (runInfo.from || runInfo.to != runInfo.run.length()))
117         codePathToUse = ComplexPath;
118
119     if (codePathToUse != ComplexPath)
120         return drawSimpleText(context, runInfo, point);
121
122     return drawComplexText(context, runInfo, point);
123 }
124
125 void Font::drawEmphasisMarks(GraphicsContext* context, const TextRunPaintInfo& runInfo, const AtomicString& mark, const FloatPoint& point) const
126 {
127     if (shouldSkipDrawing())
128         return;
129
130     CodePath codePathToUse = codePath(runInfo.run);
131     // FIXME: Use the fast code path once it handles partial runs with kerning and ligatures. See http://webkit.org/b/100050
132     if (codePathToUse != ComplexPath && fontDescription().typesettingFeatures() && (runInfo.from || runInfo.to != runInfo.run.length()))
133         codePathToUse = ComplexPath;
134
135     if (codePathToUse != ComplexPath)
136         drawEmphasisMarksForSimpleText(context, runInfo, mark, point);
137     else
138         drawEmphasisMarksForComplexText(context, runInfo, mark, point);
139 }
140
141 static inline void updateGlyphOverflowFromBounds(const IntRectExtent& glyphBounds,
142     const FontMetrics& fontMetrics, GlyphOverflow* glyphOverflow)
143 {
144     glyphOverflow->top = std::max<int>(glyphOverflow->top,
145         glyphBounds.top() - (glyphOverflow->computeBounds ? 0 : fontMetrics.ascent()));
146     glyphOverflow->bottom = std::max<int>(glyphOverflow->bottom,
147         glyphBounds.bottom() - (glyphOverflow->computeBounds ? 0 : fontMetrics.descent()));
148     glyphOverflow->left = glyphBounds.left();
149     glyphOverflow->right = glyphBounds.right();
150 }
151
152 float Font::width(const TextRun& run, HashSet<const SimpleFontData*>* fallbackFonts, GlyphOverflow* glyphOverflow) const
153 {
154     CodePath codePathToUse = codePath(run);
155     if (codePathToUse != ComplexPath) {
156         // The simple path can optimize the case where glyph overflow is not observable.
157         if (codePathToUse != SimpleWithGlyphOverflowPath && (glyphOverflow && !glyphOverflow->computeBounds))
158             glyphOverflow = 0;
159     }
160
161     bool hasWordSpacingOrLetterSpacing = fontDescription().wordSpacing() || fontDescription().letterSpacing();
162     bool isCacheable = codePathToUse == ComplexPath
163         && !hasWordSpacingOrLetterSpacing // Word spacing and letter spacing can change the width of a word.
164         && !run.allowTabs(); // If we allow tabs and a tab occurs inside a word, the width of the word varies based on its position on the line.
165
166     WidthCacheEntry* cacheEntry = isCacheable
167         ? m_fontFallbackList->widthCache().add(run, WidthCacheEntry())
168         : 0;
169     if (cacheEntry && cacheEntry->isValid()) {
170         if (glyphOverflow)
171             updateGlyphOverflowFromBounds(cacheEntry->glyphBounds, fontMetrics(), glyphOverflow);
172         return cacheEntry->width;
173     }
174
175     float result;
176     IntRectExtent glyphBounds;
177     if (codePathToUse == ComplexPath) {
178         result = floatWidthForComplexText(run, fallbackFonts, &glyphBounds);
179     } else {
180         ASSERT(!isCacheable);
181         result = floatWidthForSimpleText(run, fallbackFonts, glyphOverflow ? &glyphBounds : 0);
182     }
183
184     if (cacheEntry && (!fallbackFonts || fallbackFonts->isEmpty())) {
185         cacheEntry->glyphBounds = glyphBounds;
186         cacheEntry->width = result;
187     }
188
189     if (glyphOverflow)
190         updateGlyphOverflowFromBounds(glyphBounds, fontMetrics(), glyphOverflow);
191     return result;
192 }
193
194 float Font::width(const TextRun& run, int& charsConsumed, Glyph& glyphId) const
195 {
196 #if ENABLE(SVG_FONTS)
197     if (TextRun::RenderingContext* renderingContext = run.renderingContext())
198         return renderingContext->floatWidthUsingSVGFont(*this, run, charsConsumed, glyphId);
199 #endif
200
201     charsConsumed = run.length();
202     glyphId = 0;
203     return width(run);
204 }
205
206 PassTextBlobPtr Font::buildTextBlob(const TextRunPaintInfo& runInfo, const FloatPoint& textOrigin, bool couldUseLCDRenderedText, CustomFontNotReadyAction customFontNotReadyAction) const
207 {
208     ASSERT(RuntimeEnabledFeatures::textBlobEnabled());
209
210     // FIXME: Some logic in common with Font::drawText. Would be nice to
211     // deduplicate.
212     if (shouldSkipDrawing() && customFontNotReadyAction == DoNotPaintIfFontNotReady)
213         return nullptr;
214
215     CodePath codePathToUse = codePath(runInfo.run);
216     // FIXME: Use the fast code path once it handles partial runs with kerning and ligatures. See http://webkit.org/b/100050
217     if (codePathToUse != ComplexPath && fontDescription().typesettingFeatures() && (runInfo.from || runInfo.to != runInfo.run.length()))
218         codePathToUse = ComplexPath;
219
220     if (codePathToUse != ComplexPath)
221         return buildTextBlobForSimpleText(runInfo, textOrigin, couldUseLCDRenderedText);
222
223     return nullptr;
224 }
225
226 PassTextBlobPtr Font::buildTextBlobForSimpleText(const TextRunPaintInfo& runInfo, const FloatPoint& textOrigin, bool couldUseLCDRenderedText) const
227 {
228     GlyphBuffer glyphBuffer;
229     float initialAdvance = getGlyphsAndAdvancesForSimpleText(runInfo, glyphBuffer);
230     ASSERT(!glyphBuffer.hasVerticalAdvances());
231
232     if (glyphBuffer.isEmpty())
233         return nullptr;
234
235     FloatRect blobBounds = runInfo.bounds;
236     blobBounds.moveBy(-textOrigin);
237
238     float ignoredWidth;
239     return buildTextBlob(glyphBuffer, initialAdvance, blobBounds, ignoredWidth, couldUseLCDRenderedText);
240 }
241
242 FloatRect Font::selectionRectForText(const TextRun& run, const FloatPoint& point, int h, int from, int to, bool accountForGlyphBounds) const
243 {
244     to = (to == -1 ? run.length() : to);
245
246     CodePath codePathToUse = codePath(run);
247     // FIXME: Use the fast code path once it handles partial runs with kerning and ligatures. See http://webkit.org/b/100050
248     if (codePathToUse != ComplexPath && fontDescription().typesettingFeatures() && (from || to != run.length()))
249         codePathToUse = ComplexPath;
250
251     if (codePathToUse != ComplexPath)
252         return selectionRectForSimpleText(run, point, h, from, to, accountForGlyphBounds);
253
254     return selectionRectForComplexText(run, point, h, from, to);
255 }
256
257 int Font::offsetForPosition(const TextRun& run, float x, bool includePartialGlyphs) const
258 {
259     // FIXME: Use the fast code path once it handles partial runs with kerning and ligatures. See http://webkit.org/b/100050
260     if (codePath(run) != ComplexPath && !fontDescription().typesettingFeatures())
261         return offsetForPositionForSimpleText(run, x, includePartialGlyphs);
262
263     return offsetForPositionForComplexText(run, x, includePartialGlyphs);
264 }
265
266 void Font::setCodePath(CodePath p)
267 {
268     s_codePath = p;
269 }
270
271 CodePath Font::codePath()
272 {
273     return s_codePath;
274 }
275
276 CodePath Font::codePath(const TextRun& run) const
277 {
278     if (s_codePath != AutoPath)
279         return s_codePath;
280
281 #if ENABLE(SVG_FONTS)
282     if (run.renderingContext())
283         return SimplePath;
284 #endif
285
286     if (m_fontDescription.featureSettings() && m_fontDescription.featureSettings()->size() > 0 && m_fontDescription.letterSpacing() == 0)
287         return ComplexPath;
288
289     if (m_fontDescription.widthVariant() != RegularWidth)
290         return ComplexPath;
291
292     if (run.length() > 1 && fontDescription().typesettingFeatures())
293         return ComplexPath;
294
295     if (run.useComplexCodePath())
296         return ComplexPath;
297
298     if (!run.characterScanForCodePath())
299         return SimplePath;
300
301     if (run.is8Bit())
302         return SimplePath;
303
304     // Start from 0 since drawing and highlighting also measure the characters before run->from.
305     return Character::characterRangeCodePath(run.characters16(), run.length());
306 }
307
308 void Font::willUseFontData(UChar32 character) const
309 {
310     const FontFamily& family = fontDescription().family();
311     if (m_fontFallbackList && m_fontFallbackList->fontSelector() && !family.familyIsEmpty())
312         m_fontFallbackList->fontSelector()->willUseFontData(fontDescription(), family.family(), character);
313 }
314
315 static inline bool isInRange(UChar32 character, UChar32 lowerBound, UChar32 upperBound)
316 {
317     return character >= lowerBound && character <= upperBound;
318 }
319
320 static bool shouldIgnoreRotation(UChar32 character)
321 {
322     if (character == 0x000A7 || character == 0x000A9 || character == 0x000AE)
323         return true;
324
325     if (character == 0x000B6 || character == 0x000BC || character == 0x000BD || character == 0x000BE)
326         return true;
327
328     if (isInRange(character, 0x002E5, 0x002EB))
329         return true;
330
331     if (isInRange(character, 0x01100, 0x011FF) || isInRange(character, 0x01401, 0x0167F) || isInRange(character, 0x01800, 0x018FF))
332         return true;
333
334     if (character == 0x02016 || character == 0x02018 || character == 0x02019 || character == 0x02020 || character == 0x02021
335         || character == 0x2030 || character == 0x02031)
336         return true;
337
338     if (isInRange(character, 0x0203B, 0x0203D) || character == 0x02042 || character == 0x02044 || character == 0x02047
339         || character == 0x02048 || character == 0x02049 || character == 0x2051)
340         return true;
341
342     if (isInRange(character, 0x02065, 0x02069) || isInRange(character, 0x020DD, 0x020E0)
343         || isInRange(character, 0x020E2, 0x020E4) || isInRange(character, 0x02100, 0x02117)
344         || isInRange(character, 0x02119, 0x02131) || isInRange(character, 0x02133, 0x0213F))
345         return true;
346
347     if (isInRange(character, 0x02145, 0x0214A) || character == 0x0214C || character == 0x0214D
348         || isInRange(character, 0x0214F, 0x0218F))
349         return true;
350
351     if (isInRange(character, 0x02300, 0x02307) || isInRange(character, 0x0230C, 0x0231F)
352         || isInRange(character, 0x02322, 0x0232B) || isInRange(character, 0x0237D, 0x0239A)
353         || isInRange(character, 0x023B4, 0x023B6) || isInRange(character, 0x023BA, 0x023CF)
354         || isInRange(character, 0x023D1, 0x023DB) || isInRange(character, 0x023E2, 0x024FF))
355         return true;
356
357     if (isInRange(character, 0x025A0, 0x02619) || isInRange(character, 0x02620, 0x02767)
358         || isInRange(character, 0x02776, 0x02793) || isInRange(character, 0x02B12, 0x02B2F)
359         || isInRange(character, 0x02B4D, 0x02BFF) || isInRange(character, 0x02E80, 0x03007))
360         return true;
361
362     if (character == 0x03012 || character == 0x03013 || isInRange(character, 0x03020, 0x0302F)
363         || isInRange(character, 0x03031, 0x0309F) || isInRange(character, 0x030A1, 0x030FB)
364         || isInRange(character, 0x030FD, 0x0A4CF))
365         return true;
366
367     if (isInRange(character, 0x0A840, 0x0A87F) || isInRange(character, 0x0A960, 0x0A97F)
368         || isInRange(character, 0x0AC00, 0x0D7FF) || isInRange(character, 0x0E000, 0x0FAFF))
369         return true;
370
371     if (isInRange(character, 0x0FE10, 0x0FE1F) || isInRange(character, 0x0FE30, 0x0FE48)
372         || isInRange(character, 0x0FE50, 0x0FE57) || isInRange(character, 0x0FE5F, 0x0FE62)
373         || isInRange(character, 0x0FE67, 0x0FE6F))
374         return true;
375
376     if (isInRange(character, 0x0FF01, 0x0FF07) || isInRange(character, 0x0FF0A, 0x0FF0C)
377         || isInRange(character, 0x0FF0E, 0x0FF19) || isInRange(character, 0x0FF1F, 0x0FF3A))
378         return true;
379
380     if (character == 0x0FF3C || character == 0x0FF3E)
381         return true;
382
383     if (isInRange(character, 0x0FF40, 0x0FF5A) || isInRange(character, 0x0FFE0, 0x0FFE2)
384         || isInRange(character, 0x0FFE4, 0x0FFE7) || isInRange(character, 0x0FFF0, 0x0FFF8)
385         || character == 0x0FFFD)
386         return true;
387
388     if (isInRange(character, 0x13000, 0x1342F) || isInRange(character, 0x1B000, 0x1B0FF)
389         || isInRange(character, 0x1D000, 0x1D1FF) || isInRange(character, 0x1D300, 0x1D37F)
390         || isInRange(character, 0x1F000, 0x1F64F) || isInRange(character, 0x1F680, 0x1F77F))
391         return true;
392
393     if (isInRange(character, 0x20000, 0x2FFFD) || isInRange(character, 0x30000, 0x3FFFD))
394         return true;
395
396     return false;
397 }
398
399 static inline std::pair<GlyphData, GlyphPage*> glyphDataAndPageForNonCJKCharacterWithGlyphOrientation(UChar32 character, NonCJKGlyphOrientation orientation, GlyphData& data, GlyphPage* page, unsigned pageNumber)
400 {
401     if (orientation == NonCJKGlyphOrientationUpright || shouldIgnoreRotation(character)) {
402         RefPtr<SimpleFontData> uprightFontData = data.fontData->uprightOrientationFontData();
403         GlyphPageTreeNode* uprightNode = GlyphPageTreeNode::getRootChild(uprightFontData.get(), pageNumber);
404         GlyphPage* uprightPage = uprightNode->page();
405         if (uprightPage) {
406             GlyphData uprightData = uprightPage->glyphDataForCharacter(character);
407             // If the glyphs are the same, then we know we can just use the horizontal glyph rotated vertically to be upright.
408             if (data.glyph == uprightData.glyph)
409                 return std::make_pair(data, page);
410             // The glyphs are distinct, meaning that the font has a vertical-right glyph baked into it. We can't use that
411             // glyph, so we fall back to the upright data and use the horizontal glyph.
412             if (uprightData.fontData)
413                 return std::make_pair(uprightData, uprightPage);
414         }
415     } else if (orientation == NonCJKGlyphOrientationVerticalRight) {
416         RefPtr<SimpleFontData> verticalRightFontData = data.fontData->verticalRightOrientationFontData();
417         GlyphPageTreeNode* verticalRightNode = GlyphPageTreeNode::getRootChild(verticalRightFontData.get(), pageNumber);
418         GlyphPage* verticalRightPage = verticalRightNode->page();
419         if (verticalRightPage) {
420             GlyphData verticalRightData = verticalRightPage->glyphDataForCharacter(character);
421             // If the glyphs are distinct, we will make the assumption that the font has a vertical-right glyph baked
422             // into it.
423             if (data.glyph != verticalRightData.glyph)
424                 return std::make_pair(data, page);
425             // The glyphs are identical, meaning that we should just use the horizontal glyph.
426             if (verticalRightData.fontData)
427                 return std::make_pair(verticalRightData, verticalRightPage);
428         }
429     }
430     return std::make_pair(data, page);
431 }
432
433 std::pair<GlyphData, GlyphPage*> Font::glyphDataAndPageForCharacter(UChar32& c, bool mirror, bool normalizeSpace, FontDataVariant variant) const
434 {
435     ASSERT(isMainThread());
436
437     if (variant == AutoVariant) {
438         if (m_fontDescription.variant() == FontVariantSmallCaps && !primaryFont()->isSVGFont()) {
439             UChar32 upperC = toUpper(c);
440             if (upperC != c) {
441                 c = upperC;
442                 variant = SmallCapsVariant;
443             } else {
444                 variant = NormalVariant;
445             }
446         } else {
447             variant = NormalVariant;
448         }
449     }
450
451     if (normalizeSpace && Character::isNormalizedCanvasSpaceCharacter(c))
452         c = space;
453
454     if (mirror)
455         c = mirroredChar(c);
456
457     unsigned pageNumber = (c / GlyphPage::size);
458
459     GlyphPageTreeNode* node = m_fontFallbackList->getPageNode(pageNumber);
460     if (!node) {
461         node = GlyphPageTreeNode::getRootChild(fontDataAt(0), pageNumber);
462         m_fontFallbackList->setPageNode(pageNumber, node);
463     }
464
465     GlyphPage* page = 0;
466     if (variant == NormalVariant) {
467         // Fastest loop, for the common case (normal variant).
468         while (true) {
469             page = node->page();
470             if (page) {
471                 GlyphData data = page->glyphDataForCharacter(c);
472                 if (data.fontData && (data.fontData->platformData().orientation() == Horizontal || data.fontData->isTextOrientationFallback()))
473                     return std::make_pair(data, page);
474
475                 if (data.fontData) {
476                     if (Character::isCJKIdeographOrSymbol(c)) {
477                         if (!data.fontData->hasVerticalGlyphs()) {
478                             // Use the broken ideograph font data. The broken ideograph font will use the horizontal width of glyphs
479                             // to make sure you get a square (even for broken glyphs like symbols used for punctuation).
480                             variant = BrokenIdeographVariant;
481                             break;
482                         }
483                     } else {
484                         return glyphDataAndPageForNonCJKCharacterWithGlyphOrientation(c, m_fontDescription.nonCJKGlyphOrientation(), data, page, pageNumber);
485                     }
486
487                     return std::make_pair(data, page);
488                 }
489
490                 if (node->isSystemFallback())
491                     break;
492             }
493
494             // Proceed with the fallback list.
495             node = node->getChild(fontDataAt(node->level()), pageNumber);
496             m_fontFallbackList->setPageNode(pageNumber, node);
497         }
498     }
499     if (variant != NormalVariant) {
500         while (true) {
501             page = node->page();
502             if (page) {
503                 GlyphData data = page->glyphDataForCharacter(c);
504                 if (data.fontData) {
505                     // The variantFontData function should not normally return 0.
506                     // But if it does, we will just render the capital letter big.
507                     RefPtr<SimpleFontData> variantFontData = data.fontData->variantFontData(m_fontDescription, variant);
508                     if (!variantFontData)
509                         return std::make_pair(data, page);
510
511                     GlyphPageTreeNode* variantNode = GlyphPageTreeNode::getRootChild(variantFontData.get(), pageNumber);
512                     GlyphPage* variantPage = variantNode->page();
513                     if (variantPage) {
514                         GlyphData data = variantPage->glyphDataForCharacter(c);
515                         if (data.fontData)
516                             return std::make_pair(data, variantPage);
517                     }
518
519                     // Do not attempt system fallback off the variantFontData. This is the very unlikely case that
520                     // a font has the lowercase character but the small caps font does not have its uppercase version.
521                     return std::make_pair(variantFontData->missingGlyphData(), page);
522                 }
523
524                 if (node->isSystemFallback())
525                     break;
526             }
527
528             // Proceed with the fallback list.
529             node = node->getChild(fontDataAt(node->level()), pageNumber);
530             m_fontFallbackList->setPageNode(pageNumber, node);
531         }
532     }
533
534     ASSERT(page);
535     ASSERT(node->isSystemFallback());
536
537     // System fallback is character-dependent. When we get here, we
538     // know that the character in question isn't in the system fallback
539     // font's glyph page. Try to lazily create it here.
540
541     // FIXME: Unclear if this should normalizeSpaces above 0xFFFF.
542     // Doing so changes fast/text/international/plane2-diffs.html
543     UChar32 characterToRender = c;
544     if (characterToRender <=  0xFFFF)
545         characterToRender = Character::normalizeSpaces(characterToRender);
546     const SimpleFontData* fontDataToSubstitute = fontDataAt(0)->fontDataForCharacter(characterToRender);
547     RefPtr<SimpleFontData> characterFontData = FontCache::fontCache()->fallbackFontForCharacter(m_fontDescription, characterToRender, fontDataToSubstitute);
548     if (characterFontData) {
549         if (characterFontData->platformData().orientation() == Vertical && !characterFontData->hasVerticalGlyphs() && Character::isCJKIdeographOrSymbol(c))
550             variant = BrokenIdeographVariant;
551         if (variant != NormalVariant)
552             characterFontData = characterFontData->variantFontData(m_fontDescription, variant);
553     }
554     if (characterFontData) {
555         // Got the fallback glyph and font.
556         GlyphPage* fallbackPage = GlyphPageTreeNode::getRootChild(characterFontData.get(), pageNumber)->page();
557         GlyphData data = fallbackPage && fallbackPage->glyphForCharacter(c) ? fallbackPage->glyphDataForCharacter(c) : characterFontData->missingGlyphData();
558         // Cache it so we don't have to do system fallback again next time.
559         if (variant == NormalVariant) {
560             page->setGlyphDataForCharacter(c, data.glyph, data.fontData);
561             data.fontData->setMaxGlyphPageTreeLevel(std::max(data.fontData->maxGlyphPageTreeLevel(), node->level()));
562             if (!Character::isCJKIdeographOrSymbol(c) && data.fontData->platformData().orientation() != Horizontal && !data.fontData->isTextOrientationFallback())
563                 return glyphDataAndPageForNonCJKCharacterWithGlyphOrientation(c, m_fontDescription.nonCJKGlyphOrientation(), data, page, pageNumber);
564         }
565         return std::make_pair(data, page);
566     }
567
568     // Even system fallback can fail; use the missing glyph in that case.
569     // FIXME: It would be nicer to use the missing glyph from the last resort font instead.
570     GlyphData data = primaryFont()->missingGlyphData();
571     if (variant == NormalVariant) {
572         page->setGlyphDataForCharacter(c, data.glyph, data.fontData);
573         data.fontData->setMaxGlyphPageTreeLevel(std::max(data.fontData->maxGlyphPageTreeLevel(), node->level()));
574     }
575     return std::make_pair(data, page);
576 }
577
578 bool Font::primaryFontHasGlyphForCharacter(UChar32 character) const
579 {
580     unsigned pageNumber = (character / GlyphPage::size);
581
582     GlyphPageTreeNode* node = GlyphPageTreeNode::getRootChild(primaryFont(), pageNumber);
583     GlyphPage* page = node->page();
584
585     return page && page->glyphForCharacter(character);
586 }
587
588 // FIXME: This function may not work if the emphasis mark uses a complex script, but none of the
589 // standard emphasis marks do so.
590 bool Font::getEmphasisMarkGlyphData(const AtomicString& mark, GlyphData& glyphData) const
591 {
592     if (mark.isEmpty())
593         return false;
594
595     UChar32 character = mark[0];
596
597     if (U16_IS_SURROGATE(character)) {
598         if (!U16_IS_SURROGATE_LEAD(character))
599             return false;
600
601         if (mark.length() < 2)
602             return false;
603
604         UChar low = mark[1];
605         if (!U16_IS_TRAIL(low))
606             return false;
607
608         character = U16_GET_SUPPLEMENTARY(character, low);
609     }
610
611     bool normalizeSpace = false;
612     glyphData = glyphDataForCharacter(character, false, normalizeSpace, EmphasisMarkVariant);
613     return true;
614 }
615
616 int Font::emphasisMarkAscent(const AtomicString& mark) const
617 {
618     FontCachePurgePreventer purgePreventer;
619
620     GlyphData markGlyphData;
621     if (!getEmphasisMarkGlyphData(mark, markGlyphData))
622         return 0;
623
624     const SimpleFontData* markFontData = markGlyphData.fontData;
625     ASSERT(markFontData);
626     if (!markFontData)
627         return 0;
628
629     return markFontData->fontMetrics().ascent();
630 }
631
632 int Font::emphasisMarkDescent(const AtomicString& mark) const
633 {
634     FontCachePurgePreventer purgePreventer;
635
636     GlyphData markGlyphData;
637     if (!getEmphasisMarkGlyphData(mark, markGlyphData))
638         return 0;
639
640     const SimpleFontData* markFontData = markGlyphData.fontData;
641     ASSERT(markFontData);
642     if (!markFontData)
643         return 0;
644
645     return markFontData->fontMetrics().descent();
646 }
647
648 int Font::emphasisMarkHeight(const AtomicString& mark) const
649 {
650     FontCachePurgePreventer purgePreventer;
651
652     GlyphData markGlyphData;
653     if (!getEmphasisMarkGlyphData(mark, markGlyphData))
654         return 0;
655
656     const SimpleFontData* markFontData = markGlyphData.fontData;
657     ASSERT(markFontData);
658     if (!markFontData)
659         return 0;
660
661     return markFontData->fontMetrics().height();
662 }
663
664 float Font::getGlyphsAndAdvancesForSimpleText(const TextRunPaintInfo& runInfo, GlyphBuffer& glyphBuffer, ForTextEmphasisOrNot forTextEmphasis) const
665 {
666     float initialAdvance;
667
668     WidthIterator it(this, runInfo.run, 0, false, forTextEmphasis);
669     it.advance(runInfo.from);
670     float beforeWidth = it.m_runWidthSoFar;
671     it.advance(runInfo.to, &glyphBuffer);
672
673     if (glyphBuffer.isEmpty())
674         return 0;
675
676     float afterWidth = it.m_runWidthSoFar;
677
678     if (runInfo.run.rtl()) {
679         it.advance(runInfo.run.length());
680         initialAdvance = it.m_runWidthSoFar - afterWidth;
681         glyphBuffer.reverse();
682     } else {
683         initialAdvance = beforeWidth;
684     }
685
686     return initialAdvance;
687 }
688
689 float Font::drawSimpleText(GraphicsContext* context, const TextRunPaintInfo& runInfo, const FloatPoint& point) const
690 {
691     // This glyph buffer holds our glyphs+advances+font data for each glyph.
692     GlyphBuffer glyphBuffer;
693     float initialAdvance = getGlyphsAndAdvancesForSimpleText(runInfo, glyphBuffer);
694     ASSERT(!glyphBuffer.hasVerticalAdvances());
695
696     if (glyphBuffer.isEmpty())
697         return 0;
698
699     TextBlobPtr textBlob;
700     float advance = 0;
701     if (RuntimeEnabledFeatures::textBlobEnabled()) {
702         // Using text blob causes a small difference in how gradients and
703         // patterns are rendered.
704         // FIXME: Fix this, most likely in Skia.
705         if (!context->strokeGradient() && !context->strokePattern() && !context->fillGradient() && !context->fillPattern()) {
706             FloatRect blobBounds = runInfo.bounds;
707             blobBounds.moveBy(-point);
708             textBlob = buildTextBlob(glyphBuffer, initialAdvance, blobBounds, advance, context->couldUseLCDRenderedText());
709         }
710     }
711
712     if (textBlob) {
713         drawTextBlob(context, textBlob.get(), point.data());
714         return advance;
715     }
716
717     FloatPoint startPoint(point.x() + initialAdvance, point.y());
718     return drawGlyphBuffer(context, runInfo, glyphBuffer, startPoint);
719 }
720
721 void Font::drawEmphasisMarksForSimpleText(GraphicsContext* context, const TextRunPaintInfo& runInfo, const AtomicString& mark, const FloatPoint& point) const
722 {
723     GlyphBuffer glyphBuffer;
724     float initialAdvance = getGlyphsAndAdvancesForSimpleText(runInfo, glyphBuffer, ForTextEmphasis);
725
726     if (glyphBuffer.isEmpty())
727         return;
728
729     drawEmphasisMarks(context, runInfo, glyphBuffer, mark, FloatPoint(point.x() + initialAdvance, point.y()));
730 }
731
732 float Font::drawGlyphBuffer(GraphicsContext* context, const TextRunPaintInfo& runInfo, const GlyphBuffer& glyphBuffer, const FloatPoint& point) const
733 {
734     // Draw each contiguous run of glyphs that use the same font data.
735     const SimpleFontData* fontData = glyphBuffer.fontDataAt(0);
736     FloatPoint startPoint(point);
737     FloatPoint nextPoint = startPoint + glyphBuffer.advanceAt(0);
738     unsigned lastFrom = 0;
739     unsigned nextGlyph = 1;
740 #if ENABLE(SVG_FONTS)
741     TextRun::RenderingContext* renderingContext = runInfo.run.renderingContext();
742 #endif
743
744     float widthSoFar = 0;
745     widthSoFar += glyphBuffer.advanceAt(0).width();
746     while (nextGlyph < glyphBuffer.size()) {
747         const SimpleFontData* nextFontData = glyphBuffer.fontDataAt(nextGlyph);
748
749         if (nextFontData != fontData) {
750 #if ENABLE(SVG_FONTS)
751             if (renderingContext && fontData->isSVGFont())
752                 renderingContext->drawSVGGlyphs(context, runInfo.run, fontData, glyphBuffer, lastFrom, nextGlyph - lastFrom, startPoint);
753             else
754 #endif
755                 drawGlyphs(context, fontData, glyphBuffer, lastFrom, nextGlyph - lastFrom, startPoint, runInfo.bounds);
756
757             lastFrom = nextGlyph;
758             fontData = nextFontData;
759             startPoint = nextPoint;
760         }
761         nextPoint += glyphBuffer.advanceAt(nextGlyph);
762         widthSoFar += glyphBuffer.advanceAt(nextGlyph).width();
763         nextGlyph++;
764     }
765
766 #if ENABLE(SVG_FONTS)
767     if (renderingContext && fontData->isSVGFont())
768         renderingContext->drawSVGGlyphs(context, runInfo.run, fontData, glyphBuffer, lastFrom, nextGlyph - lastFrom, startPoint);
769     else
770 #endif
771         drawGlyphs(context, fontData, glyphBuffer, lastFrom, nextGlyph - lastFrom, startPoint, runInfo.bounds);
772         return widthSoFar;
773 }
774
775 inline static float offsetToMiddleOfGlyph(const SimpleFontData* fontData, Glyph glyph)
776 {
777     if (fontData->platformData().orientation() == Horizontal) {
778         FloatRect bounds = fontData->boundsForGlyph(glyph);
779         return bounds.x() + bounds.width() / 2;
780     }
781     // FIXME: Use glyph bounds once they make sense for vertical fonts.
782     return fontData->widthForGlyph(glyph) / 2;
783 }
784
785 inline static float offsetToMiddleOfAdvanceAtIndex(const GlyphBuffer& glyphBuffer, size_t i)
786 {
787     return glyphBuffer.advanceAt(i).width() / 2;
788 }
789
790 void Font::drawEmphasisMarks(GraphicsContext* context, const TextRunPaintInfo& runInfo, const GlyphBuffer& glyphBuffer, const AtomicString& mark, const FloatPoint& point) const
791 {
792     FontCachePurgePreventer purgePreventer;
793
794     GlyphData markGlyphData;
795     if (!getEmphasisMarkGlyphData(mark, markGlyphData))
796         return;
797
798     const SimpleFontData* markFontData = markGlyphData.fontData;
799     ASSERT(markFontData);
800     if (!markFontData)
801         return;
802
803     Glyph markGlyph = markGlyphData.glyph;
804     Glyph spaceGlyph = markFontData->spaceGlyph();
805
806     float middleOfLastGlyph = offsetToMiddleOfAdvanceAtIndex(glyphBuffer, 0);
807     FloatPoint startPoint(point.x() + middleOfLastGlyph - offsetToMiddleOfGlyph(markFontData, markGlyph), point.y());
808
809     GlyphBuffer markBuffer;
810     for (unsigned i = 0; i + 1 < glyphBuffer.size(); ++i) {
811         float middleOfNextGlyph = offsetToMiddleOfAdvanceAtIndex(glyphBuffer, i + 1);
812         float advance = glyphBuffer.advanceAt(i).width() - middleOfLastGlyph + middleOfNextGlyph;
813         markBuffer.add(glyphBuffer.glyphAt(i) ? markGlyph : spaceGlyph, markFontData, advance);
814         middleOfLastGlyph = middleOfNextGlyph;
815     }
816     markBuffer.add(glyphBuffer.glyphAt(glyphBuffer.size() - 1) ? markGlyph : spaceGlyph, markFontData, 0);
817
818     drawGlyphBuffer(context, runInfo, markBuffer, startPoint);
819 }
820
821 float Font::floatWidthForSimpleText(const TextRun& run, HashSet<const SimpleFontData*>* fallbackFonts, IntRectExtent* glyphBounds) const
822 {
823     WidthIterator it(this, run, fallbackFonts, glyphBounds);
824     it.advance(run.length());
825
826     if (glyphBounds) {
827         glyphBounds->setTop(floorf(-it.minGlyphBoundingBoxY()));
828         glyphBounds->setBottom(ceilf(it.maxGlyphBoundingBoxY()));
829         glyphBounds->setLeft(floorf(it.firstGlyphOverflow()));
830         glyphBounds->setRight(ceilf(it.lastGlyphOverflow()));
831     }
832
833     return it.m_runWidthSoFar;
834 }
835
836 FloatRect Font::pixelSnappedSelectionRect(float fromX, float toX, float y, float height)
837 {
838     // Using roundf() rather than ceilf() for the right edge as a compromise to
839     // ensure correct caret positioning.
840     float roundedX = roundf(fromX);
841     return FloatRect(roundedX, y, roundf(toX - roundedX), height);
842 }
843
844 FloatRect Font::selectionRectForSimpleText(const TextRun& run, const FloatPoint& point, int h, int from, int to, bool accountForGlyphBounds) const
845 {
846     WidthIterator it(this, run, 0, accountForGlyphBounds);
847     it.advance(from);
848     float fromX = it.m_runWidthSoFar;
849     it.advance(to);
850     float toX = it.m_runWidthSoFar;
851
852     if (run.rtl()) {
853         it.advance(run.length());
854         float totalWidth = it.m_runWidthSoFar;
855         float beforeWidth = fromX;
856         float afterWidth = toX;
857         fromX = totalWidth - afterWidth;
858         toX = totalWidth - beforeWidth;
859     }
860
861     return pixelSnappedSelectionRect(point.x() + fromX, point.x() + toX,
862         accountForGlyphBounds ? it.minGlyphBoundingBoxY() : point.y(),
863         accountForGlyphBounds ? it.maxGlyphBoundingBoxY() - it.minGlyphBoundingBoxY() : h);
864 }
865
866 int Font::offsetForPositionForSimpleText(const TextRun& run, float x, bool includePartialGlyphs) const
867 {
868     float delta = x;
869
870     WidthIterator it(this, run);
871     unsigned offset;
872     if (run.rtl()) {
873         delta -= floatWidthForSimpleText(run);
874         while (1) {
875             offset = it.m_currentCharacter;
876             float w;
877             if (!it.advanceOneCharacter(w))
878                 break;
879             delta += w;
880             if (includePartialGlyphs) {
881                 if (delta - w / 2 >= 0)
882                     break;
883             } else {
884                 if (delta >= 0)
885                     break;
886             }
887         }
888     } else {
889         while (1) {
890             offset = it.m_currentCharacter;
891             float w;
892             if (!it.advanceOneCharacter(w))
893                 break;
894             delta -= w;
895             if (includePartialGlyphs) {
896                 if (delta + w / 2 <= 0)
897                     break;
898             } else {
899                 if (delta <= 0)
900                     break;
901             }
902         }
903     }
904
905     return offset;
906 }
907
908 } // namespace blink