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.
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.
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.
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.
25 #include "platform/fonts/Font.h"
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"
46 using namespace Unicode;
50 CodePath Font::s_codePath = AutoPath;
52 // ============================================================================================
53 // Font Implementation (Cross-Platform Portion)
54 // ============================================================================================
60 Font::Font(const FontDescription& fd)
61 : m_fontDescription(fd)
65 Font::Font(const Font& other)
66 : m_fontDescription(other.m_fontDescription)
67 , m_fontFallbackList(other.m_fontFallbackList)
71 Font& Font::operator=(const Font& other)
73 m_fontDescription = other.m_fontDescription;
74 m_fontFallbackList = other.m_fontFallbackList;
78 bool Font::operator==(const Font& other) const
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())
85 FontSelector* first = m_fontFallbackList ? m_fontFallbackList->fontSelector() : 0;
86 FontSelector* second = other.m_fontFallbackList ? other.m_fontFallbackList->fontSelector() : 0;
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);
94 void Font::update(PassRefPtrWillBeRawPtr<FontSelector> fontSelector) const
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);
106 float Font::drawText(GraphicsContext* context, const TextRunPaintInfo& runInfo, const FloatPoint& point, CustomFontNotReadyAction customFontNotReadyAction) const
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
111 if (shouldSkipDrawing() && customFontNotReadyAction == DoNotPaintIfFontNotReady)
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;
119 if (codePathToUse != ComplexPath)
120 return drawSimpleText(context, runInfo, point);
122 return drawComplexText(context, runInfo, point);
125 void Font::drawEmphasisMarks(GraphicsContext* context, const TextRunPaintInfo& runInfo, const AtomicString& mark, const FloatPoint& point) const
127 if (shouldSkipDrawing())
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;
135 if (codePathToUse != ComplexPath)
136 drawEmphasisMarksForSimpleText(context, runInfo, mark, point);
138 drawEmphasisMarksForComplexText(context, runInfo, mark, point);
141 static inline void updateGlyphOverflowFromBounds(const IntRectExtent& glyphBounds,
142 const FontMetrics& fontMetrics, GlyphOverflow* glyphOverflow)
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();
152 float Font::width(const TextRun& run, HashSet<const SimpleFontData*>* fallbackFonts, GlyphOverflow* glyphOverflow) const
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))
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.
166 WidthCacheEntry* cacheEntry = isCacheable
167 ? m_fontFallbackList->widthCache().add(run, WidthCacheEntry())
169 if (cacheEntry && cacheEntry->isValid()) {
171 updateGlyphOverflowFromBounds(cacheEntry->glyphBounds, fontMetrics(), glyphOverflow);
172 return cacheEntry->width;
176 IntRectExtent glyphBounds;
177 if (codePathToUse == ComplexPath) {
178 result = floatWidthForComplexText(run, fallbackFonts, &glyphBounds);
180 ASSERT(!isCacheable);
181 result = floatWidthForSimpleText(run, fallbackFonts, glyphOverflow ? &glyphBounds : 0);
184 if (cacheEntry && (!fallbackFonts || fallbackFonts->isEmpty())) {
185 cacheEntry->glyphBounds = glyphBounds;
186 cacheEntry->width = result;
190 updateGlyphOverflowFromBounds(glyphBounds, fontMetrics(), glyphOverflow);
194 float Font::width(const TextRun& run, int& charsConsumed, Glyph& glyphId) const
196 #if ENABLE(SVG_FONTS)
197 if (TextRun::RenderingContext* renderingContext = run.renderingContext())
198 return renderingContext->floatWidthUsingSVGFont(*this, run, charsConsumed, glyphId);
201 charsConsumed = run.length();
206 PassTextBlobPtr Font::buildTextBlob(const TextRunPaintInfo& runInfo, const FloatPoint& textOrigin, bool couldUseLCDRenderedText, CustomFontNotReadyAction customFontNotReadyAction) const
208 ASSERT(RuntimeEnabledFeatures::textBlobEnabled());
210 // FIXME: Some logic in common with Font::drawText. Would be nice to
212 if (shouldSkipDrawing() && customFontNotReadyAction == DoNotPaintIfFontNotReady)
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;
220 if (codePathToUse != ComplexPath)
221 return buildTextBlobForSimpleText(runInfo, textOrigin, couldUseLCDRenderedText);
226 PassTextBlobPtr Font::buildTextBlobForSimpleText(const TextRunPaintInfo& runInfo, const FloatPoint& textOrigin, bool couldUseLCDRenderedText) const
228 GlyphBuffer glyphBuffer;
229 float initialAdvance = getGlyphsAndAdvancesForSimpleText(runInfo, glyphBuffer);
230 ASSERT(!glyphBuffer.hasVerticalAdvances());
232 if (glyphBuffer.isEmpty())
235 FloatRect blobBounds = runInfo.bounds;
236 blobBounds.moveBy(-textOrigin);
239 return buildTextBlob(glyphBuffer, initialAdvance, blobBounds, ignoredWidth, couldUseLCDRenderedText);
242 FloatRect Font::selectionRectForText(const TextRun& run, const FloatPoint& point, int h, int from, int to, bool accountForGlyphBounds) const
244 to = (to == -1 ? run.length() : to);
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;
251 if (codePathToUse != ComplexPath)
252 return selectionRectForSimpleText(run, point, h, from, to, accountForGlyphBounds);
254 return selectionRectForComplexText(run, point, h, from, to);
257 int Font::offsetForPosition(const TextRun& run, float x, bool includePartialGlyphs) const
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);
263 return offsetForPositionForComplexText(run, x, includePartialGlyphs);
266 void Font::setCodePath(CodePath p)
271 CodePath Font::codePath()
276 CodePath Font::codePath(const TextRun& run) const
278 if (s_codePath != AutoPath)
281 #if ENABLE(SVG_FONTS)
282 if (run.renderingContext())
286 if (m_fontDescription.featureSettings() && m_fontDescription.featureSettings()->size() > 0 && m_fontDescription.letterSpacing() == 0)
289 if (m_fontDescription.widthVariant() != RegularWidth)
292 if (run.length() > 1 && fontDescription().typesettingFeatures())
295 if (run.useComplexCodePath())
298 if (!run.characterScanForCodePath())
304 // Start from 0 since drawing and highlighting also measure the characters before run->from.
305 return Character::characterRangeCodePath(run.characters16(), run.length());
308 void Font::willUseFontData(UChar32 character) const
310 const FontFamily& family = fontDescription().family();
311 if (m_fontFallbackList && m_fontFallbackList->fontSelector() && !family.familyIsEmpty())
312 m_fontFallbackList->fontSelector()->willUseFontData(fontDescription(), family.family(), character);
315 static inline bool isInRange(UChar32 character, UChar32 lowerBound, UChar32 upperBound)
317 return character >= lowerBound && character <= upperBound;
320 static bool shouldIgnoreRotation(UChar32 character)
322 if (character == 0x000A7 || character == 0x000A9 || character == 0x000AE)
325 if (character == 0x000B6 || character == 0x000BC || character == 0x000BD || character == 0x000BE)
328 if (isInRange(character, 0x002E5, 0x002EB))
331 if (isInRange(character, 0x01100, 0x011FF) || isInRange(character, 0x01401, 0x0167F) || isInRange(character, 0x01800, 0x018FF))
334 if (character == 0x02016 || character == 0x02018 || character == 0x02019 || character == 0x02020 || character == 0x02021
335 || character == 0x2030 || character == 0x02031)
338 if (isInRange(character, 0x0203B, 0x0203D) || character == 0x02042 || character == 0x02044 || character == 0x02047
339 || character == 0x02048 || character == 0x02049 || character == 0x2051)
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))
347 if (isInRange(character, 0x02145, 0x0214A) || character == 0x0214C || character == 0x0214D
348 || isInRange(character, 0x0214F, 0x0218F))
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))
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))
362 if (character == 0x03012 || character == 0x03013 || isInRange(character, 0x03020, 0x0302F)
363 || isInRange(character, 0x03031, 0x0309F) || isInRange(character, 0x030A1, 0x030FB)
364 || isInRange(character, 0x030FD, 0x0A4CF))
367 if (isInRange(character, 0x0A840, 0x0A87F) || isInRange(character, 0x0A960, 0x0A97F)
368 || isInRange(character, 0x0AC00, 0x0D7FF) || isInRange(character, 0x0E000, 0x0FAFF))
371 if (isInRange(character, 0x0FE10, 0x0FE1F) || isInRange(character, 0x0FE30, 0x0FE48)
372 || isInRange(character, 0x0FE50, 0x0FE57) || isInRange(character, 0x0FE5F, 0x0FE62)
373 || isInRange(character, 0x0FE67, 0x0FE6F))
376 if (isInRange(character, 0x0FF01, 0x0FF07) || isInRange(character, 0x0FF0A, 0x0FF0C)
377 || isInRange(character, 0x0FF0E, 0x0FF19) || isInRange(character, 0x0FF1F, 0x0FF3A))
380 if (character == 0x0FF3C || character == 0x0FF3E)
383 if (isInRange(character, 0x0FF40, 0x0FF5A) || isInRange(character, 0x0FFE0, 0x0FFE2)
384 || isInRange(character, 0x0FFE4, 0x0FFE7) || isInRange(character, 0x0FFF0, 0x0FFF8)
385 || character == 0x0FFFD)
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))
393 if (isInRange(character, 0x20000, 0x2FFFD) || isInRange(character, 0x30000, 0x3FFFD))
399 static inline std::pair<GlyphData, GlyphPage*> glyphDataAndPageForNonCJKCharacterWithGlyphOrientation(UChar32 character, NonCJKGlyphOrientation orientation, GlyphData& data, GlyphPage* page, unsigned pageNumber)
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();
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);
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
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);
430 return std::make_pair(data, page);
433 std::pair<GlyphData, GlyphPage*> Font::glyphDataAndPageForCharacter(UChar32& c, bool mirror, bool normalizeSpace, FontDataVariant variant) const
435 ASSERT(isMainThread());
437 if (variant == AutoVariant) {
438 if (m_fontDescription.variant() == FontVariantSmallCaps && !primaryFont()->isSVGFont()) {
439 UChar32 upperC = toUpper(c);
442 variant = SmallCapsVariant;
444 variant = NormalVariant;
447 variant = NormalVariant;
451 if (normalizeSpace && Character::isNormalizedCanvasSpaceCharacter(c))
457 unsigned pageNumber = (c / GlyphPage::size);
459 GlyphPageTreeNode* node = m_fontFallbackList->getPageNode(pageNumber);
461 node = GlyphPageTreeNode::getRootChild(fontDataAt(0), pageNumber);
462 m_fontFallbackList->setPageNode(pageNumber, node);
466 if (variant == NormalVariant) {
467 // Fastest loop, for the common case (normal variant).
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);
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;
484 return glyphDataAndPageForNonCJKCharacterWithGlyphOrientation(c, m_fontDescription.nonCJKGlyphOrientation(), data, page, pageNumber);
487 return std::make_pair(data, page);
490 if (node->isSystemFallback())
494 // Proceed with the fallback list.
495 node = node->getChild(fontDataAt(node->level()), pageNumber);
496 m_fontFallbackList->setPageNode(pageNumber, node);
499 if (variant != NormalVariant) {
503 GlyphData data = page->glyphDataForCharacter(c);
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);
511 GlyphPageTreeNode* variantNode = GlyphPageTreeNode::getRootChild(variantFontData.get(), pageNumber);
512 GlyphPage* variantPage = variantNode->page();
514 GlyphData data = variantPage->glyphDataForCharacter(c);
516 return std::make_pair(data, variantPage);
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);
524 if (node->isSystemFallback())
528 // Proceed with the fallback list.
529 node = node->getChild(fontDataAt(node->level()), pageNumber);
530 m_fontFallbackList->setPageNode(pageNumber, node);
535 ASSERT(node->isSystemFallback());
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.
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);
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);
565 return std::make_pair(data, page);
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()));
575 return std::make_pair(data, page);
578 bool Font::primaryFontHasGlyphForCharacter(UChar32 character) const
580 unsigned pageNumber = (character / GlyphPage::size);
582 GlyphPageTreeNode* node = GlyphPageTreeNode::getRootChild(primaryFont(), pageNumber);
583 GlyphPage* page = node->page();
585 return page && page->glyphForCharacter(character);
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
595 UChar32 character = mark[0];
597 if (U16_IS_SURROGATE(character)) {
598 if (!U16_IS_SURROGATE_LEAD(character))
601 if (mark.length() < 2)
605 if (!U16_IS_TRAIL(low))
608 character = U16_GET_SUPPLEMENTARY(character, low);
611 bool normalizeSpace = false;
612 glyphData = glyphDataForCharacter(character, false, normalizeSpace, EmphasisMarkVariant);
616 int Font::emphasisMarkAscent(const AtomicString& mark) const
618 FontCachePurgePreventer purgePreventer;
620 GlyphData markGlyphData;
621 if (!getEmphasisMarkGlyphData(mark, markGlyphData))
624 const SimpleFontData* markFontData = markGlyphData.fontData;
625 ASSERT(markFontData);
629 return markFontData->fontMetrics().ascent();
632 int Font::emphasisMarkDescent(const AtomicString& mark) const
634 FontCachePurgePreventer purgePreventer;
636 GlyphData markGlyphData;
637 if (!getEmphasisMarkGlyphData(mark, markGlyphData))
640 const SimpleFontData* markFontData = markGlyphData.fontData;
641 ASSERT(markFontData);
645 return markFontData->fontMetrics().descent();
648 int Font::emphasisMarkHeight(const AtomicString& mark) const
650 FontCachePurgePreventer purgePreventer;
652 GlyphData markGlyphData;
653 if (!getEmphasisMarkGlyphData(mark, markGlyphData))
656 const SimpleFontData* markFontData = markGlyphData.fontData;
657 ASSERT(markFontData);
661 return markFontData->fontMetrics().height();
664 float Font::getGlyphsAndAdvancesForSimpleText(const TextRunPaintInfo& runInfo, GlyphBuffer& glyphBuffer, ForTextEmphasisOrNot forTextEmphasis) const
666 float initialAdvance;
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);
673 if (glyphBuffer.isEmpty())
676 float afterWidth = it.m_runWidthSoFar;
678 if (runInfo.run.rtl()) {
679 it.advance(runInfo.run.length());
680 initialAdvance = it.m_runWidthSoFar - afterWidth;
681 glyphBuffer.reverse();
683 initialAdvance = beforeWidth;
686 return initialAdvance;
689 float Font::drawSimpleText(GraphicsContext* context, const TextRunPaintInfo& runInfo, const FloatPoint& point) const
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());
696 if (glyphBuffer.isEmpty())
699 TextBlobPtr textBlob;
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());
713 drawTextBlob(context, textBlob.get(), point.data());
717 FloatPoint startPoint(point.x() + initialAdvance, point.y());
718 return drawGlyphBuffer(context, runInfo, glyphBuffer, startPoint);
721 void Font::drawEmphasisMarksForSimpleText(GraphicsContext* context, const TextRunPaintInfo& runInfo, const AtomicString& mark, const FloatPoint& point) const
723 GlyphBuffer glyphBuffer;
724 float initialAdvance = getGlyphsAndAdvancesForSimpleText(runInfo, glyphBuffer, ForTextEmphasis);
726 if (glyphBuffer.isEmpty())
729 drawEmphasisMarks(context, runInfo, glyphBuffer, mark, FloatPoint(point.x() + initialAdvance, point.y()));
732 float Font::drawGlyphBuffer(GraphicsContext* context, const TextRunPaintInfo& runInfo, const GlyphBuffer& glyphBuffer, const FloatPoint& point) const
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();
744 float widthSoFar = 0;
745 widthSoFar += glyphBuffer.advanceAt(0).width();
746 while (nextGlyph < glyphBuffer.size()) {
747 const SimpleFontData* nextFontData = glyphBuffer.fontDataAt(nextGlyph);
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);
755 drawGlyphs(context, fontData, glyphBuffer, lastFrom, nextGlyph - lastFrom, startPoint, runInfo.bounds);
757 lastFrom = nextGlyph;
758 fontData = nextFontData;
759 startPoint = nextPoint;
761 nextPoint += glyphBuffer.advanceAt(nextGlyph);
762 widthSoFar += glyphBuffer.advanceAt(nextGlyph).width();
766 #if ENABLE(SVG_FONTS)
767 if (renderingContext && fontData->isSVGFont())
768 renderingContext->drawSVGGlyphs(context, runInfo.run, fontData, glyphBuffer, lastFrom, nextGlyph - lastFrom, startPoint);
771 drawGlyphs(context, fontData, glyphBuffer, lastFrom, nextGlyph - lastFrom, startPoint, runInfo.bounds);
775 inline static float offsetToMiddleOfGlyph(const SimpleFontData* fontData, Glyph glyph)
777 if (fontData->platformData().orientation() == Horizontal) {
778 FloatRect bounds = fontData->boundsForGlyph(glyph);
779 return bounds.x() + bounds.width() / 2;
781 // FIXME: Use glyph bounds once they make sense for vertical fonts.
782 return fontData->widthForGlyph(glyph) / 2;
785 inline static float offsetToMiddleOfAdvanceAtIndex(const GlyphBuffer& glyphBuffer, size_t i)
787 return glyphBuffer.advanceAt(i).width() / 2;
790 void Font::drawEmphasisMarks(GraphicsContext* context, const TextRunPaintInfo& runInfo, const GlyphBuffer& glyphBuffer, const AtomicString& mark, const FloatPoint& point) const
792 FontCachePurgePreventer purgePreventer;
794 GlyphData markGlyphData;
795 if (!getEmphasisMarkGlyphData(mark, markGlyphData))
798 const SimpleFontData* markFontData = markGlyphData.fontData;
799 ASSERT(markFontData);
803 Glyph markGlyph = markGlyphData.glyph;
804 Glyph spaceGlyph = markFontData->spaceGlyph();
806 float middleOfLastGlyph = offsetToMiddleOfAdvanceAtIndex(glyphBuffer, 0);
807 FloatPoint startPoint(point.x() + middleOfLastGlyph - offsetToMiddleOfGlyph(markFontData, markGlyph), point.y());
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;
816 markBuffer.add(glyphBuffer.glyphAt(glyphBuffer.size() - 1) ? markGlyph : spaceGlyph, markFontData, 0);
818 drawGlyphBuffer(context, runInfo, markBuffer, startPoint);
821 float Font::floatWidthForSimpleText(const TextRun& run, HashSet<const SimpleFontData*>* fallbackFonts, IntRectExtent* glyphBounds) const
823 WidthIterator it(this, run, fallbackFonts, glyphBounds);
824 it.advance(run.length());
827 glyphBounds->setTop(floorf(-it.minGlyphBoundingBoxY()));
828 glyphBounds->setBottom(ceilf(it.maxGlyphBoundingBoxY()));
829 glyphBounds->setLeft(floorf(it.firstGlyphOverflow()));
830 glyphBounds->setRight(ceilf(it.lastGlyphOverflow()));
833 return it.m_runWidthSoFar;
836 FloatRect Font::pixelSnappedSelectionRect(float fromX, float toX, float y, float height)
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);
844 FloatRect Font::selectionRectForSimpleText(const TextRun& run, const FloatPoint& point, int h, int from, int to, bool accountForGlyphBounds) const
846 WidthIterator it(this, run, 0, accountForGlyphBounds);
848 float fromX = it.m_runWidthSoFar;
850 float toX = it.m_runWidthSoFar;
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;
861 return pixelSnappedSelectionRect(point.x() + fromX, point.x() + toX,
862 accountForGlyphBounds ? it.minGlyphBoundingBoxY() : point.y(),
863 accountForGlyphBounds ? it.maxGlyphBoundingBoxY() - it.minGlyphBoundingBoxY() : h);
866 int Font::offsetForPositionForSimpleText(const TextRun& run, float x, bool includePartialGlyphs) const
870 WidthIterator it(this, run);
873 delta -= floatWidthForSimpleText(run);
875 offset = it.m_currentCharacter;
877 if (!it.advanceOneCharacter(w))
880 if (includePartialGlyphs) {
881 if (delta - w / 2 >= 0)
890 offset = it.m_currentCharacter;
892 if (!it.advanceOneCharacter(w))
895 if (includePartialGlyphs) {
896 if (delta + w / 2 <= 0)