2 * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
3 * (C) 2000 Antti Koivisto (koivisto@kde.org)
4 * (C) 2000 Dirk Mueller (mueller@kde.org)
5 * Copyright (C) 2003, 2006, 2007, 2010, 2011 Apple Inc. All rights reserved.
6 * Copyright (C) 2008 Holger Hans Peter Freyther
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Library General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Library General Public License for more details.
18 * You should have received a copy of the GNU Library General Public License
19 * along with this library; see the file COPYING.LIB. If not, write to
20 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 * Boston, MA 02110-1301, USA.
28 #include "DashArray.h"
29 #include "FontDescription.h"
30 #include "FontGlyphs.h"
32 #include "SimpleFontData.h"
33 #include "TextDirection.h"
34 #include "TypesettingFeatures.h"
35 #include <wtf/HashMap.h>
36 #include <wtf/HashSet.h>
37 #include <wtf/unicode/CharacterNames.h>
39 // "X11/X.h" defines Complex to 0 and conflicts
40 // with Complex value in CodePath enum.
51 class FontPlatformData;
54 class GraphicsContext;
62 struct GlyphOverflow {
68 , computeBounds(false)
74 return !left && !right && !top && !bottom;
77 inline void extendTo(const GlyphOverflow& other)
79 left = std::max(left, other.left);
80 right = std::max(right, other.right);
81 top = std::max(top, other.top);
82 bottom = std::max(bottom, other.bottom);
85 bool operator!=(const GlyphOverflow& other)
87 return left != other.left || right != other.right || top != other.top || bottom != other.bottom;
97 class GlyphToPathTranslator {
99 enum class GlyphUnderlineType {SkipDescenders, SkipGlyph, DrawOverGlyph};
100 virtual bool containsMorePaths() = 0;
101 virtual Path path() = 0;
102 virtual std::pair<float, float> extents() = 0;
103 virtual GlyphUnderlineType underlineType() = 0;
104 virtual void advance() = 0;
105 virtual ~GlyphToPathTranslator() { }
107 GlyphToPathTranslator::GlyphUnderlineType computeUnderlineType(const TextRun&, const GlyphBuffer&, int index);
111 WEBCORE_EXPORT Font();
112 WEBCORE_EXPORT Font(const FontDescription&, float letterSpacing, float wordSpacing);
113 // This constructor is only used if the platform wants to start with a native font.
114 WEBCORE_EXPORT Font(const FontPlatformData&, bool isPrinting, FontSmoothingMode = AutoSmoothing);
116 // FIXME: We should make this constructor platform-independent.
118 Font(const FontPlatformData&, PassRefPtr<FontSelector>);
123 WEBCORE_EXPORT Font& operator=(const Font&);
125 WEBCORE_EXPORT bool operator==(const Font& other) const;
126 bool operator!=(const Font& other) const { return !(*this == other); }
128 const FontDescription& fontDescription() const { return m_fontDescription; }
130 int pixelSize() const { return fontDescription().computedPixelSize(); }
131 float size() const { return fontDescription().computedSize(); }
133 void update(PassRefPtr<FontSelector>) const;
135 enum CustomFontNotReadyAction { DoNotPaintIfFontNotReady, UseFallbackIfFontNotReady };
136 WEBCORE_EXPORT float drawText(GraphicsContext*, const TextRun&, const FloatPoint&, int from = 0, int to = -1, CustomFontNotReadyAction = DoNotPaintIfFontNotReady) const;
137 void drawGlyphs(GraphicsContext*, const SimpleFontData*, const GlyphBuffer&, int from, int numGlyphs, const FloatPoint&) const;
138 void drawEmphasisMarks(GraphicsContext*, const TextRun&, const AtomicString& mark, const FloatPoint&, int from = 0, int to = -1) const;
140 DashArray dashesForIntersectionsWithRect(const TextRun&, const FloatPoint& textOrigin, const FloatRect& lineExtents) const;
142 WEBCORE_EXPORT float width(const TextRun&, HashSet<const SimpleFontData*>* fallbackFonts = 0, GlyphOverflow* = 0) const;
143 float width(const TextRun&, int& charsConsumed, String& glyphName) const;
145 PassOwnPtr<TextLayout> createLayout(RenderText*, float xPos, bool collapseWhiteSpace) const;
146 static void deleteLayout(TextLayout*);
147 static float width(TextLayout&, unsigned from, unsigned len, HashSet<const SimpleFontData*>* fallbackFonts = 0);
149 int offsetForPosition(const TextRun&, float position, bool includePartialGlyphs) const;
150 void adjustSelectionRectForText(const TextRun&, LayoutRect& selectionRect, int from = 0, int to = -1) const;
152 bool isSmallCaps() const { return m_fontDescription.smallCaps(); }
154 float wordSpacing() const { return m_wordSpacing; }
155 float letterSpacing() const { return m_letterSpacing; }
156 void setWordSpacing(float s) { m_wordSpacing = s; }
157 void setLetterSpacing(float s) { m_letterSpacing = s; }
158 bool isFixedPitch() const;
159 bool isPrinterFont() const { return m_fontDescription.usePrinterFont(); }
161 FontRenderingMode renderingMode() const { return m_fontDescription.renderingMode(); }
163 TypesettingFeatures typesettingFeatures() const { return static_cast<TypesettingFeatures>(m_typesettingFeatures); }
165 const AtomicString& firstFamily() const { return m_fontDescription.firstFamily(); }
166 unsigned familyCount() const { return m_fontDescription.familyCount(); }
167 const AtomicString& familyAt(unsigned i) const { return m_fontDescription.familyAt(i); }
169 FontItalic italic() const { return m_fontDescription.italic(); }
170 FontWeight weight() const { return m_fontDescription.weight(); }
171 FontWidthVariant widthVariant() const { return m_fontDescription.widthVariant(); }
173 bool isPlatformFont() const { return m_glyphs->isForPlatformFont(); }
175 const FontMetrics& fontMetrics() const { return primaryFontData().fontMetrics(); }
176 float spaceWidth() const { return primaryFontData().spaceWidth() + m_letterSpacing; }
177 float tabWidth(const SimpleFontData&, unsigned tabSize, float position) const;
178 float tabWidth(unsigned tabSize, float position) const { return tabWidth(primaryFontData(), tabSize, position); }
179 bool hasValidAverageCharWidth() const;
180 bool fastAverageCharWidthIfAvailable(float &width) const; // returns true on success
182 int emphasisMarkAscent(const AtomicString&) const;
183 int emphasisMarkDescent(const AtomicString&) const;
184 int emphasisMarkHeight(const AtomicString&) const;
186 const SimpleFontData& primaryFontData() const;
187 const FontData* fontDataAt(unsigned) const;
188 GlyphData glyphDataForCharacter(UChar32, bool mirror, FontDataVariant = AutoVariant) const;
191 const SimpleFontData* fontDataForCombiningCharacterSequence(const UChar*, size_t length, FontDataVariant) const;
194 static bool isCJKIdeograph(UChar32);
195 static bool isCJKIdeographOrSymbol(UChar32);
197 // BEWARE: If isAfterExpansion is true after this function call, then the returned value includes a trailing opportunity
198 // which may or may not actually be present. RenderBlockFlow::computeInlineDirectionPositionsForSegment() compensates
199 // for this by decrementing the returned value if isAfterExpansion is true at the end of a line.
200 static unsigned expansionOpportunityCount(const StringView&, TextDirection, bool& isAfterExpansion);
202 WEBCORE_EXPORT static void setShouldUseSmoothing(bool);
203 WEBCORE_EXPORT static bool shouldUseSmoothing();
205 enum CodePath { Auto, Simple, Complex, SimpleWithGlyphOverflow };
206 CodePath codePath(const TextRun&) const;
207 static CodePath characterRangeCodePath(const LChar*, unsigned) { return Simple; }
208 static CodePath characterRangeCodePath(const UChar*, unsigned len);
210 bool primaryFontDataIsSystemFont() const;
213 enum ForTextEmphasisOrNot { NotForTextEmphasis, ForTextEmphasis };
215 // Returns the initial in-stream advance.
216 float getGlyphsAndAdvancesForSimpleText(const TextRun&, int from, int to, GlyphBuffer&, ForTextEmphasisOrNot = NotForTextEmphasis) const;
217 float drawSimpleText(GraphicsContext*, const TextRun&, const FloatPoint&, int from, int to) const;
218 void drawEmphasisMarksForSimpleText(GraphicsContext*, const TextRun&, const AtomicString& mark, const FloatPoint&, int from, int to) const;
219 void drawGlyphBuffer(GraphicsContext*, const TextRun&, const GlyphBuffer&, FloatPoint&) const;
220 void drawEmphasisMarks(GraphicsContext*, const TextRun&, const GlyphBuffer&, const AtomicString&, const FloatPoint&) const;
221 float floatWidthForSimpleText(const TextRun&, HashSet<const SimpleFontData*>* fallbackFonts = 0, GlyphOverflow* = 0) const;
222 int offsetForPositionForSimpleText(const TextRun&, float position, bool includePartialGlyphs) const;
223 void adjustSelectionRectForSimpleText(const TextRun&, LayoutRect& selectionRect, int from, int to) const;
225 bool getEmphasisMarkGlyphData(const AtomicString&, GlyphData&) const;
227 static bool canReturnFallbackFontsForComplexText();
228 static bool canExpandAroundIdeographsInComplexText();
230 // Returns the initial in-stream advance.
231 float getGlyphsAndAdvancesForComplexText(const TextRun&, int from, int to, GlyphBuffer&, ForTextEmphasisOrNot = NotForTextEmphasis) const;
232 float drawComplexText(GraphicsContext*, const TextRun&, const FloatPoint&, int from, int to) const;
233 void drawEmphasisMarksForComplexText(GraphicsContext*, const TextRun&, const AtomicString& mark, const FloatPoint&, int from, int to) const;
234 float floatWidthForComplexText(const TextRun&, HashSet<const SimpleFontData*>* fallbackFonts = 0, GlyphOverflow* = 0) const;
235 int offsetForPositionForComplexText(const TextRun&, float position, bool includePartialGlyphs) const;
236 void adjustSelectionRectForComplexText(const TextRun&, LayoutRect& selectionRect, int from, int to) const;
238 static unsigned expansionOpportunityCountInternal(const LChar*, size_t length, TextDirection, bool& isAfterExpansion);
239 static unsigned expansionOpportunityCountInternal(const UChar*, size_t length, TextDirection, bool& isAfterExpansion);
241 friend struct WidthIterator;
242 friend class SVGTextRunRenderingContext;
245 #if ENABLE(IOS_TEXT_AUTOSIZING)
246 bool equalForTextAutoSizing(const Font& other) const
248 return m_fontDescription.equalForTextAutoSizing(other.m_fontDescription)
249 && m_letterSpacing == other.m_letterSpacing
250 && m_wordSpacing == other.m_wordSpacing;
254 // Useful for debugging the different font rendering code paths.
255 WEBCORE_EXPORT static void setCodePath(CodePath);
256 static CodePath codePath();
257 static CodePath s_codePath;
259 WEBCORE_EXPORT static void setDefaultTypesettingFeatures(TypesettingFeatures);
260 static TypesettingFeatures defaultTypesettingFeatures();
262 static const uint8_t s_roundingHackCharacterTable[256];
263 static bool isRoundingHackCharacter(UChar32 c)
265 return !(c & ~0xFF) && s_roundingHackCharacterTable[c];
268 FontSelector* fontSelector() const;
269 static bool treatAsSpace(UChar c) { return c == ' ' || c == '\t' || c == '\n' || c == noBreakSpace; }
270 static bool treatAsZeroWidthSpace(UChar c) { return treatAsZeroWidthSpaceInComplexScript(c) || c == 0x200c || c == 0x200d; }
271 static bool treatAsZeroWidthSpaceInComplexScript(UChar c) { return c < 0x20 || (c >= 0x7F && c < 0xA0) || c == softHyphen || c == zeroWidthSpace || (c >= 0x200e && c <= 0x200f) || (c >= 0x202a && c <= 0x202e) || c == zeroWidthNoBreakSpace || c == objectReplacementCharacter; }
272 static bool canReceiveTextEmphasis(UChar32 c);
274 static inline UChar normalizeSpaces(UChar character)
276 if (treatAsSpace(character))
279 if (treatAsZeroWidthSpace(character))
280 return zeroWidthSpace;
285 static String normalizeSpaces(const LChar*, unsigned length);
286 static String normalizeSpaces(const UChar*, unsigned length);
288 bool useBackslashAsYenSymbol() const { return m_useBackslashAsYenSymbol; }
289 FontGlyphs* glyphs() const { return m_glyphs.get(); }
292 bool isLoadingCustomFonts() const;
294 TypesettingFeatures computeTypesettingFeatures() const
296 TextRenderingMode textRenderingMode = m_fontDescription.textRenderingMode();
297 TypesettingFeatures features = s_defaultTypesettingFeatures;
299 switch (textRenderingMode) {
300 case AutoTextRendering:
303 features &= ~(Kerning | Ligatures);
305 case GeometricPrecision:
306 case OptimizeLegibility:
307 features |= Kerning | Ligatures;
311 switch (m_fontDescription.kerning()) {
312 case FontDescription::NoneKerning:
313 features &= ~Kerning;
315 case FontDescription::NormalKerning:
318 case FontDescription::AutoKerning:
322 switch (m_fontDescription.commonLigaturesState()) {
323 case FontDescription::DisabledLigaturesState:
324 features &= ~Ligatures;
326 case FontDescription::EnabledLigaturesState:
327 features |= Ligatures;
329 case FontDescription::NormalLigaturesState:
336 static TypesettingFeatures s_defaultTypesettingFeatures;
338 FontDescription m_fontDescription;
339 mutable RefPtr<FontGlyphs> m_glyphs;
340 float m_letterSpacing;
342 mutable bool m_useBackslashAsYenSymbol;
343 mutable unsigned m_typesettingFeatures : 2; // (TypesettingFeatures) Caches values computed from m_fontDescription.
346 void invalidateFontGlyphsCache();
347 void pruneUnreferencedEntriesFromFontGlyphsCache();
348 void clearWidthCaches();
354 inline const SimpleFontData& Font::primaryFontData() const
357 return m_glyphs->primarySimpleFontData(m_fontDescription);
360 inline const FontData* Font::fontDataAt(unsigned index) const
363 return m_glyphs->realizeFontDataAt(m_fontDescription, index);
366 inline bool Font::isFixedPitch() const
369 return m_glyphs->isFixedPitch(m_fontDescription);
372 inline FontSelector* Font::fontSelector() const
374 return m_glyphs ? m_glyphs->fontSelector() : 0;
377 inline float Font::tabWidth(const SimpleFontData& fontData, unsigned tabSize, float position) const
380 return letterSpacing();
381 float tabWidth = tabSize * fontData.spaceWidth() + letterSpacing();
382 float tabDeltaWidth = tabWidth - fmodf(position, tabWidth);
383 return (tabDeltaWidth < fontData.spaceWidth() / 2) ? tabWidth : tabDeltaWidth;
390 template <> void deleteOwnedPtr<WebCore::TextLayout>(WebCore::TextLayout*);