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
45using namespace WTF;
46using namespace Unicode;
47
48namespace blink {
49
50CodePath Font::s_codePath = AutoPath;
51
52// ============================================================================================
53// Font Implementation (Cross-Platform Portion)
54// ============================================================================================
55
56Font::Font()
57{
58}
59
60Font::Font(const FontDescription& fd)
61    : m_fontDescription(fd)
62{
63}
64
65Font::Font(const Font& other)
66    : m_fontDescription(other.m_fontDescription)
67    , m_fontFallbackList(other.m_fontFallbackList)
68{
69}
70
71Font& Font::operator=(const Font& other)
72{
73    m_fontDescription = other.m_fontDescription;
74    m_fontFallbackList = other.m_fontFallbackList;
75    return *this;
76}
77
78bool 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
94void 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
106float 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
125void 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
141static 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
152float 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
194float 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
206PassTextBlobPtr 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
226PassTextBlobPtr 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
242FloatRect 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
257int 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
266void Font::setCodePath(CodePath p)
267{
268    s_codePath = p;
269}
270
271CodePath Font::codePath()
272{
273    return s_codePath;
274}
275
276CodePath 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    // FIXME: This really shouldn't be needed but for some reason the
299    // TextRendering setting doesn't propagate to typesettingFeatures in time
300    // for the prefs width calculation.
301    if (fontDescription().textRendering() == OptimizeLegibility || fontDescription().textRendering() == GeometricPrecision)
302        return ComplexPath;
303
304    if (!run.characterScanForCodePath())
305        return SimplePath;
306
307    if (run.is8Bit())
308        return SimplePath;
309
310    // Start from 0 since drawing and highlighting also measure the characters before run->from.
311    return Character::characterRangeCodePath(run.characters16(), run.length());
312}
313
314void Font::willUseFontData(UChar32 character) const
315{
316    const FontFamily& family = fontDescription().family();
317    if (m_fontFallbackList && m_fontFallbackList->fontSelector() && !family.familyIsEmpty())
318        m_fontFallbackList->fontSelector()->willUseFontData(fontDescription(), family.family(), character);
319}
320
321static inline bool isInRange(UChar32 character, UChar32 lowerBound, UChar32 upperBound)
322{
323    return character >= lowerBound && character <= upperBound;
324}
325
326static bool shouldIgnoreRotation(UChar32 character)
327{
328    if (character == 0x000A7 || character == 0x000A9 || character == 0x000AE)
329        return true;
330
331    if (character == 0x000B6 || character == 0x000BC || character == 0x000BD || character == 0x000BE)
332        return true;
333
334    if (isInRange(character, 0x002E5, 0x002EB))
335        return true;
336
337    if (isInRange(character, 0x01100, 0x011FF) || isInRange(character, 0x01401, 0x0167F) || isInRange(character, 0x01800, 0x018FF))
338        return true;
339
340    if (character == 0x02016 || character == 0x02018 || character == 0x02019 || character == 0x02020 || character == 0x02021
341        || character == 0x2030 || character == 0x02031)
342        return true;
343
344    if (isInRange(character, 0x0203B, 0x0203D) || character == 0x02042 || character == 0x02044 || character == 0x02047
345        || character == 0x02048 || character == 0x02049 || character == 0x2051)
346        return true;
347
348    if (isInRange(character, 0x02065, 0x02069) || isInRange(character, 0x020DD, 0x020E0)
349        || isInRange(character, 0x020E2, 0x020E4) || isInRange(character, 0x02100, 0x02117)
350        || isInRange(character, 0x02119, 0x02131) || isInRange(character, 0x02133, 0x0213F))
351        return true;
352
353    if (isInRange(character, 0x02145, 0x0214A) || character == 0x0214C || character == 0x0214D
354        || isInRange(character, 0x0214F, 0x0218F))
355        return true;
356
357    if (isInRange(character, 0x02300, 0x02307) || isInRange(character, 0x0230C, 0x0231F)
358        || isInRange(character, 0x02322, 0x0232B) || isInRange(character, 0x0237D, 0x0239A)
359        || isInRange(character, 0x023B4, 0x023B6) || isInRange(character, 0x023BA, 0x023CF)
360        || isInRange(character, 0x023D1, 0x023DB) || isInRange(character, 0x023E2, 0x024FF))
361        return true;
362
363    if (isInRange(character, 0x025A0, 0x02619) || isInRange(character, 0x02620, 0x02767)
364        || isInRange(character, 0x02776, 0x02793) || isInRange(character, 0x02B12, 0x02B2F)
365        || isInRange(character, 0x02B4D, 0x02BFF) || isInRange(character, 0x02E80, 0x03007))
366        return true;
367
368    if (character == 0x03012 || character == 0x03013 || isInRange(character, 0x03020, 0x0302F)
369        || isInRange(character, 0x03031, 0x0309F) || isInRange(character, 0x030A1, 0x030FB)
370        || isInRange(character, 0x030FD, 0x0A4CF))
371        return true;
372
373    if (isInRange(character, 0x0A840, 0x0A87F) || isInRange(character, 0x0A960, 0x0A97F)
374        || isInRange(character, 0x0AC00, 0x0D7FF) || isInRange(character, 0x0E000, 0x0FAFF))
375        return true;
376
377    if (isInRange(character, 0x0FE10, 0x0FE1F) || isInRange(character, 0x0FE30, 0x0FE48)
378        || isInRange(character, 0x0FE50, 0x0FE57) || isInRange(character, 0x0FE5F, 0x0FE62)
379        || isInRange(character, 0x0FE67, 0x0FE6F))
380        return true;
381
382    if (isInRange(character, 0x0FF01, 0x0FF07) || isInRange(character, 0x0FF0A, 0x0FF0C)
383        || isInRange(character, 0x0FF0E, 0x0FF19) || isInRange(character, 0x0FF1F, 0x0FF3A))
384        return true;
385
386    if (character == 0x0FF3C || character == 0x0FF3E)
387        return true;
388
389    if (isInRange(character, 0x0FF40, 0x0FF5A) || isInRange(character, 0x0FFE0, 0x0FFE2)
390        || isInRange(character, 0x0FFE4, 0x0FFE7) || isInRange(character, 0x0FFF0, 0x0FFF8)
391        || character == 0x0FFFD)
392        return true;
393
394    if (isInRange(character, 0x13000, 0x1342F) || isInRange(character, 0x1B000, 0x1B0FF)
395        || isInRange(character, 0x1D000, 0x1D1FF) || isInRange(character, 0x1D300, 0x1D37F)
396        || isInRange(character, 0x1F000, 0x1F64F) || isInRange(character, 0x1F680, 0x1F77F))
397        return true;
398
399    if (isInRange(character, 0x20000, 0x2FFFD) || isInRange(character, 0x30000, 0x3FFFD))
400        return true;
401
402    return false;
403}
404
405static inline std::pair<GlyphData, GlyphPage*> glyphDataAndPageForNonCJKCharacterWithGlyphOrientation(UChar32 character, NonCJKGlyphOrientation orientation, GlyphData& data, GlyphPage* page, unsigned pageNumber)
406{
407    if (orientation == NonCJKGlyphOrientationUpright || shouldIgnoreRotation(character)) {
408        RefPtr<SimpleFontData> uprightFontData = data.fontData->uprightOrientationFontData();
409        GlyphPageTreeNode* uprightNode = GlyphPageTreeNode::getRootChild(uprightFontData.get(), pageNumber);
410        GlyphPage* uprightPage = uprightNode->page();
411        if (uprightPage) {
412            GlyphData uprightData = uprightPage->glyphDataForCharacter(character);
413            // If the glyphs are the same, then we know we can just use the horizontal glyph rotated vertically to be upright.
414            if (data.glyph == uprightData.glyph)
415                return std::make_pair(data, page);
416            // The glyphs are distinct, meaning that the font has a vertical-right glyph baked into it. We can't use that
417            // glyph, so we fall back to the upright data and use the horizontal glyph.
418            if (uprightData.fontData)
419                return std::make_pair(uprightData, uprightPage);
420        }
421    } else if (orientation == NonCJKGlyphOrientationVerticalRight) {
422        RefPtr<SimpleFontData> verticalRightFontData = data.fontData->verticalRightOrientationFontData();
423        GlyphPageTreeNode* verticalRightNode = GlyphPageTreeNode::getRootChild(verticalRightFontData.get(), pageNumber);
424        GlyphPage* verticalRightPage = verticalRightNode->page();
425        if (verticalRightPage) {
426            GlyphData verticalRightData = verticalRightPage->glyphDataForCharacter(character);
427            // If the glyphs are distinct, we will make the assumption that the font has a vertical-right glyph baked
428            // into it.
429            if (data.glyph != verticalRightData.glyph)
430                return std::make_pair(data, page);
431            // The glyphs are identical, meaning that we should just use the horizontal glyph.
432            if (verticalRightData.fontData)
433                return std::make_pair(verticalRightData, verticalRightPage);
434        }
435    }
436    return std::make_pair(data, page);
437}
438
439std::pair<GlyphData, GlyphPage*> Font::glyphDataAndPageForCharacter(UChar32& c, bool mirror, bool normalizeSpace, FontDataVariant variant) const
440{
441    ASSERT(isMainThread());
442
443    if (variant == AutoVariant) {
444        if (m_fontDescription.variant() == FontVariantSmallCaps && !primaryFont()->isSVGFont()) {
445            UChar32 upperC = toUpper(c);
446            if (upperC != c) {
447                c = upperC;
448                variant = SmallCapsVariant;
449            } else {
450                variant = NormalVariant;
451            }
452        } else {
453            variant = NormalVariant;
454        }
455    }
456
457    if (normalizeSpace && Character::isNormalizedCanvasSpaceCharacter(c))
458        c = space;
459
460    if (mirror)
461        c = mirroredChar(c);
462
463    unsigned pageNumber = (c / GlyphPage::size);
464
465    GlyphPageTreeNode* node = m_fontFallbackList->getPageNode(pageNumber);
466    if (!node) {
467        node = GlyphPageTreeNode::getRootChild(fontDataAt(0), pageNumber);
468        m_fontFallbackList->setPageNode(pageNumber, node);
469    }
470
471    GlyphPage* page = 0;
472    if (variant == NormalVariant) {
473        // Fastest loop, for the common case (normal variant).
474        while (true) {
475            page = node->page();
476            if (page) {
477                GlyphData data = page->glyphDataForCharacter(c);
478                if (data.fontData && (data.fontData->platformData().orientation() == Horizontal || data.fontData->isTextOrientationFallback()))
479                    return std::make_pair(data, page);
480
481                if (data.fontData) {
482                    if (Character::isCJKIdeographOrSymbol(c)) {
483                        if (!data.fontData->hasVerticalGlyphs()) {
484                            // Use the broken ideograph font data. The broken ideograph font will use the horizontal width of glyphs
485                            // to make sure you get a square (even for broken glyphs like symbols used for punctuation).
486                            variant = BrokenIdeographVariant;
487                            break;
488                        }
489                    } else {
490                        return glyphDataAndPageForNonCJKCharacterWithGlyphOrientation(c, m_fontDescription.nonCJKGlyphOrientation(), data, page, pageNumber);
491                    }
492
493                    return std::make_pair(data, page);
494                }
495
496                if (node->isSystemFallback())
497                    break;
498            }
499
500            // Proceed with the fallback list.
501            node = node->getChild(fontDataAt(node->level()), pageNumber);
502            m_fontFallbackList->setPageNode(pageNumber, node);
503        }
504    }
505    if (variant != NormalVariant) {
506        while (true) {
507            page = node->page();
508            if (page) {
509                GlyphData data = page->glyphDataForCharacter(c);
510                if (data.fontData) {
511                    // The variantFontData function should not normally return 0.
512                    // But if it does, we will just render the capital letter big.
513                    RefPtr<SimpleFontData> variantFontData = data.fontData->variantFontData(m_fontDescription, variant);
514                    if (!variantFontData)
515                        return std::make_pair(data, page);
516
517                    GlyphPageTreeNode* variantNode = GlyphPageTreeNode::getRootChild(variantFontData.get(), pageNumber);
518                    GlyphPage* variantPage = variantNode->page();
519                    if (variantPage) {
520                        GlyphData data = variantPage->glyphDataForCharacter(c);
521                        if (data.fontData)
522                            return std::make_pair(data, variantPage);
523                    }
524
525                    // Do not attempt system fallback off the variantFontData. This is the very unlikely case that
526                    // a font has the lowercase character but the small caps font does not have its uppercase version.
527                    return std::make_pair(variantFontData->missingGlyphData(), page);
528                }
529
530                if (node->isSystemFallback())
531                    break;
532            }
533
534            // Proceed with the fallback list.
535            node = node->getChild(fontDataAt(node->level()), pageNumber);
536            m_fontFallbackList->setPageNode(pageNumber, node);
537        }
538    }
539
540    ASSERT(page);
541    ASSERT(node->isSystemFallback());
542
543    // System fallback is character-dependent. When we get here, we
544    // know that the character in question isn't in the system fallback
545    // font's glyph page. Try to lazily create it here.
546
547    // FIXME: Unclear if this should normalizeSpaces above 0xFFFF.
548    // Doing so changes fast/text/international/plane2-diffs.html
549    UChar32 characterToRender = c;
550    if (characterToRender <=  0xFFFF)
551        characterToRender = Character::normalizeSpaces(characterToRender);
552    const SimpleFontData* fontDataToSubstitute = fontDataAt(0)->fontDataForCharacter(characterToRender);
553    RefPtr<SimpleFontData> characterFontData = FontCache::fontCache()->fallbackFontForCharacter(m_fontDescription, characterToRender, fontDataToSubstitute);
554    if (characterFontData) {
555        if (characterFontData->platformData().orientation() == Vertical && !characterFontData->hasVerticalGlyphs() && Character::isCJKIdeographOrSymbol(c))
556            variant = BrokenIdeographVariant;
557        if (variant != NormalVariant)
558            characterFontData = characterFontData->variantFontData(m_fontDescription, variant);
559    }
560    if (characterFontData) {
561        // Got the fallback glyph and font.
562        GlyphPage* fallbackPage = GlyphPageTreeNode::getRootChild(characterFontData.get(), pageNumber)->page();
563        GlyphData data = fallbackPage && fallbackPage->glyphForCharacter(c) ? fallbackPage->glyphDataForCharacter(c) : characterFontData->missingGlyphData();
564        // Cache it so we don't have to do system fallback again next time.
565        if (variant == NormalVariant) {
566            page->setGlyphDataForCharacter(c, data.glyph, data.fontData);
567            data.fontData->setMaxGlyphPageTreeLevel(std::max(data.fontData->maxGlyphPageTreeLevel(), node->level()));
568            if (!Character::isCJKIdeographOrSymbol(c) && data.fontData->platformData().orientation() != Horizontal && !data.fontData->isTextOrientationFallback())
569                return glyphDataAndPageForNonCJKCharacterWithGlyphOrientation(c, m_fontDescription.nonCJKGlyphOrientation(), data, page, pageNumber);
570        }
571        return std::make_pair(data, page);
572    }
573
574    // Even system fallback can fail; use the missing glyph in that case.
575    // FIXME: It would be nicer to use the missing glyph from the last resort font instead.
576    GlyphData data = primaryFont()->missingGlyphData();
577    if (variant == NormalVariant) {
578        page->setGlyphDataForCharacter(c, data.glyph, data.fontData);
579        data.fontData->setMaxGlyphPageTreeLevel(std::max(data.fontData->maxGlyphPageTreeLevel(), node->level()));
580    }
581    return std::make_pair(data, page);
582}
583
584bool Font::primaryFontHasGlyphForCharacter(UChar32 character) const
585{
586    unsigned pageNumber = (character / GlyphPage::size);
587
588    GlyphPageTreeNode* node = GlyphPageTreeNode::getRootChild(primaryFont(), pageNumber);
589    GlyphPage* page = node->page();
590
591    return page && page->glyphForCharacter(character);
592}
593
594// FIXME: This function may not work if the emphasis mark uses a complex script, but none of the
595// standard emphasis marks do so.
596bool Font::getEmphasisMarkGlyphData(const AtomicString& mark, GlyphData& glyphData) const
597{
598    if (mark.isEmpty())
599        return false;
600
601    UChar32 character = mark[0];
602
603    if (U16_IS_SURROGATE(character)) {
604        if (!U16_IS_SURROGATE_LEAD(character))
605            return false;
606
607        if (mark.length() < 2)
608            return false;
609
610        UChar low = mark[1];
611        if (!U16_IS_TRAIL(low))
612            return false;
613
614        character = U16_GET_SUPPLEMENTARY(character, low);
615    }
616
617    bool normalizeSpace = false;
618    glyphData = glyphDataForCharacter(character, false, normalizeSpace, EmphasisMarkVariant);
619    return true;
620}
621
622int Font::emphasisMarkAscent(const AtomicString& mark) const
623{
624    FontCachePurgePreventer purgePreventer;
625
626    GlyphData markGlyphData;
627    if (!getEmphasisMarkGlyphData(mark, markGlyphData))
628        return 0;
629
630    const SimpleFontData* markFontData = markGlyphData.fontData;
631    ASSERT(markFontData);
632    if (!markFontData)
633        return 0;
634
635    return markFontData->fontMetrics().ascent();
636}
637
638int Font::emphasisMarkDescent(const AtomicString& mark) const
639{
640    FontCachePurgePreventer purgePreventer;
641
642    GlyphData markGlyphData;
643    if (!getEmphasisMarkGlyphData(mark, markGlyphData))
644        return 0;
645
646    const SimpleFontData* markFontData = markGlyphData.fontData;
647    ASSERT(markFontData);
648    if (!markFontData)
649        return 0;
650
651    return markFontData->fontMetrics().descent();
652}
653
654int Font::emphasisMarkHeight(const AtomicString& mark) const
655{
656    FontCachePurgePreventer purgePreventer;
657
658    GlyphData markGlyphData;
659    if (!getEmphasisMarkGlyphData(mark, markGlyphData))
660        return 0;
661
662    const SimpleFontData* markFontData = markGlyphData.fontData;
663    ASSERT(markFontData);
664    if (!markFontData)
665        return 0;
666
667    return markFontData->fontMetrics().height();
668}
669
670float Font::getGlyphsAndAdvancesForSimpleText(const TextRunPaintInfo& runInfo, GlyphBuffer& glyphBuffer, ForTextEmphasisOrNot forTextEmphasis) const
671{
672    float initialAdvance;
673
674    WidthIterator it(this, runInfo.run, 0, false, forTextEmphasis);
675    it.advance(runInfo.from);
676    float beforeWidth = it.m_runWidthSoFar;
677    it.advance(runInfo.to, &glyphBuffer);
678
679    if (glyphBuffer.isEmpty())
680        return 0;
681
682    float afterWidth = it.m_runWidthSoFar;
683
684    if (runInfo.run.rtl()) {
685        it.advance(runInfo.run.length());
686        initialAdvance = it.m_runWidthSoFar - afterWidth;
687        glyphBuffer.reverse();
688    } else {
689        initialAdvance = beforeWidth;
690    }
691
692    return initialAdvance;
693}
694
695float Font::drawSimpleText(GraphicsContext* context, const TextRunPaintInfo& runInfo, const FloatPoint& point) const
696{
697    // This glyph buffer holds our glyphs+advances+font data for each glyph.
698    GlyphBuffer glyphBuffer;
699    float initialAdvance = getGlyphsAndAdvancesForSimpleText(runInfo, glyphBuffer);
700    ASSERT(!glyphBuffer.hasVerticalAdvances());
701
702    if (glyphBuffer.isEmpty())
703        return 0;
704
705    TextBlobPtr textBlob;
706    float advance = 0;
707    if (RuntimeEnabledFeatures::textBlobEnabled()) {
708        // Using text blob causes a small difference in how gradients and
709        // patterns are rendered.
710        // FIXME: Fix this, most likely in Skia.
711        if (!context->strokeGradient() && !context->strokePattern() && !context->fillGradient() && !context->fillPattern()) {
712            FloatRect blobBounds = runInfo.bounds;
713            blobBounds.moveBy(-point);
714            textBlob = buildTextBlob(glyphBuffer, initialAdvance, blobBounds, advance, context->couldUseLCDRenderedText());
715        }
716    }
717
718    if (textBlob) {
719        drawTextBlob(context, textBlob.get(), point.data());
720        return advance;
721    }
722
723    FloatPoint startPoint(point.x() + initialAdvance, point.y());
724    return drawGlyphBuffer(context, runInfo, glyphBuffer, startPoint);
725}
726
727void Font::drawEmphasisMarksForSimpleText(GraphicsContext* context, const TextRunPaintInfo& runInfo, const AtomicString& mark, const FloatPoint& point) const
728{
729    GlyphBuffer glyphBuffer;
730    float initialAdvance = getGlyphsAndAdvancesForSimpleText(runInfo, glyphBuffer, ForTextEmphasis);
731
732    if (glyphBuffer.isEmpty())
733        return;
734
735    drawEmphasisMarks(context, runInfo, glyphBuffer, mark, FloatPoint(point.x() + initialAdvance, point.y()));
736}
737
738float Font::drawGlyphBuffer(GraphicsContext* context, const TextRunPaintInfo& runInfo, const GlyphBuffer& glyphBuffer, const FloatPoint& point) const
739{
740    // Draw each contiguous run of glyphs that use the same font data.
741    const SimpleFontData* fontData = glyphBuffer.fontDataAt(0);
742    FloatPoint startPoint(point);
743    FloatPoint nextPoint = startPoint + glyphBuffer.advanceAt(0);
744    unsigned lastFrom = 0;
745    unsigned nextGlyph = 1;
746#if ENABLE(SVG_FONTS)
747    TextRun::RenderingContext* renderingContext = runInfo.run.renderingContext();
748#endif
749
750    float widthSoFar = 0;
751    widthSoFar += glyphBuffer.advanceAt(0).width();
752    while (nextGlyph < glyphBuffer.size()) {
753        const SimpleFontData* nextFontData = glyphBuffer.fontDataAt(nextGlyph);
754
755        if (nextFontData != fontData) {
756#if ENABLE(SVG_FONTS)
757            if (renderingContext && fontData->isSVGFont())
758                renderingContext->drawSVGGlyphs(context, runInfo.run, fontData, glyphBuffer, lastFrom, nextGlyph - lastFrom, startPoint);
759            else
760#endif
761                drawGlyphs(context, fontData, glyphBuffer, lastFrom, nextGlyph - lastFrom, startPoint, runInfo.bounds);
762
763            lastFrom = nextGlyph;
764            fontData = nextFontData;
765            startPoint = nextPoint;
766        }
767        nextPoint += glyphBuffer.advanceAt(nextGlyph);
768        widthSoFar += glyphBuffer.advanceAt(nextGlyph).width();
769        nextGlyph++;
770    }
771
772#if ENABLE(SVG_FONTS)
773    if (renderingContext && fontData->isSVGFont())
774        renderingContext->drawSVGGlyphs(context, runInfo.run, fontData, glyphBuffer, lastFrom, nextGlyph - lastFrom, startPoint);
775    else
776#endif
777        drawGlyphs(context, fontData, glyphBuffer, lastFrom, nextGlyph - lastFrom, startPoint, runInfo.bounds);
778        return widthSoFar;
779}
780
781inline static float offsetToMiddleOfGlyph(const SimpleFontData* fontData, Glyph glyph)
782{
783    if (fontData->platformData().orientation() == Horizontal) {
784        FloatRect bounds = fontData->boundsForGlyph(glyph);
785        return bounds.x() + bounds.width() / 2;
786    }
787    // FIXME: Use glyph bounds once they make sense for vertical fonts.
788    return fontData->widthForGlyph(glyph) / 2;
789}
790
791inline static float offsetToMiddleOfAdvanceAtIndex(const GlyphBuffer& glyphBuffer, size_t i)
792{
793    return glyphBuffer.advanceAt(i).width() / 2;
794}
795
796void Font::drawEmphasisMarks(GraphicsContext* context, const TextRunPaintInfo& runInfo, const GlyphBuffer& glyphBuffer, const AtomicString& mark, const FloatPoint& point) const
797{
798    FontCachePurgePreventer purgePreventer;
799
800    GlyphData markGlyphData;
801    if (!getEmphasisMarkGlyphData(mark, markGlyphData))
802        return;
803
804    const SimpleFontData* markFontData = markGlyphData.fontData;
805    ASSERT(markFontData);
806    if (!markFontData)
807        return;
808
809    Glyph markGlyph = markGlyphData.glyph;
810    Glyph spaceGlyph = markFontData->spaceGlyph();
811
812    float middleOfLastGlyph = offsetToMiddleOfAdvanceAtIndex(glyphBuffer, 0);
813    FloatPoint startPoint(point.x() + middleOfLastGlyph - offsetToMiddleOfGlyph(markFontData, markGlyph), point.y());
814
815    GlyphBuffer markBuffer;
816    for (unsigned i = 0; i + 1 < glyphBuffer.size(); ++i) {
817        float middleOfNextGlyph = offsetToMiddleOfAdvanceAtIndex(glyphBuffer, i + 1);
818        float advance = glyphBuffer.advanceAt(i).width() - middleOfLastGlyph + middleOfNextGlyph;
819        markBuffer.add(glyphBuffer.glyphAt(i) ? markGlyph : spaceGlyph, markFontData, advance);
820        middleOfLastGlyph = middleOfNextGlyph;
821    }
822    markBuffer.add(glyphBuffer.glyphAt(glyphBuffer.size() - 1) ? markGlyph : spaceGlyph, markFontData, 0);
823
824    drawGlyphBuffer(context, runInfo, markBuffer, startPoint);
825}
826
827float Font::floatWidthForSimpleText(const TextRun& run, HashSet<const SimpleFontData*>* fallbackFonts, IntRectExtent* glyphBounds) const
828{
829    WidthIterator it(this, run, fallbackFonts, glyphBounds);
830    it.advance(run.length());
831
832    if (glyphBounds) {
833        glyphBounds->setTop(floorf(-it.minGlyphBoundingBoxY()));
834        glyphBounds->setBottom(ceilf(it.maxGlyphBoundingBoxY()));
835        glyphBounds->setLeft(floorf(it.firstGlyphOverflow()));
836        glyphBounds->setRight(ceilf(it.lastGlyphOverflow()));
837    }
838
839    return it.m_runWidthSoFar;
840}
841
842FloatRect Font::pixelSnappedSelectionRect(float fromX, float toX, float y, float height)
843{
844    // Using roundf() rather than ceilf() for the right edge as a compromise to
845    // ensure correct caret positioning.
846    float roundedX = roundf(fromX);
847    return FloatRect(roundedX, y, roundf(toX - roundedX), height);
848}
849
850FloatRect Font::selectionRectForSimpleText(const TextRun& run, const FloatPoint& point, int h, int from, int to, bool accountForGlyphBounds) const
851{
852    WidthIterator it(this, run, 0, accountForGlyphBounds);
853    it.advance(from);
854    float fromX = it.m_runWidthSoFar;
855    it.advance(to);
856    float toX = it.m_runWidthSoFar;
857
858    if (run.rtl()) {
859        it.advance(run.length());
860        float totalWidth = it.m_runWidthSoFar;
861        float beforeWidth = fromX;
862        float afterWidth = toX;
863        fromX = totalWidth - afterWidth;
864        toX = totalWidth - beforeWidth;
865    }
866
867    return pixelSnappedSelectionRect(point.x() + fromX, point.x() + toX,
868        accountForGlyphBounds ? it.minGlyphBoundingBoxY() : point.y(),
869        accountForGlyphBounds ? it.maxGlyphBoundingBoxY() - it.minGlyphBoundingBoxY() : h);
870}
871
872int Font::offsetForPositionForSimpleText(const TextRun& run, float x, bool includePartialGlyphs) const
873{
874    float delta = x;
875
876    WidthIterator it(this, run);
877    unsigned offset;
878    if (run.rtl()) {
879        delta -= floatWidthForSimpleText(run);
880        while (1) {
881            offset = it.m_currentCharacter;
882            float w;
883            if (!it.advanceOneCharacter(w))
884                break;
885            delta += w;
886            if (includePartialGlyphs) {
887                if (delta - w / 2 >= 0)
888                    break;
889            } else {
890                if (delta >= 0)
891                    break;
892            }
893        }
894    } else {
895        while (1) {
896            offset = it.m_currentCharacter;
897            float w;
898            if (!it.advanceOneCharacter(w))
899                break;
900            delta -= w;
901            if (includePartialGlyphs) {
902                if (delta + w / 2 <= 0)
903                    break;
904            } else {
905                if (delta <= 0)
906                    break;
907            }
908        }
909    }
910
911    return offset;
912}
913
914} // namespace blink
915