9889bd0ed639e6dc8461d1274303c12c1a648520
[WebKit-https.git] / Source / WebCore / platform / graphics / WidthIterator.cpp
1 /*
2  * Copyright (C) 2003, 2006, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
3  * Copyright (C) 2008 Holger Hans Peter Freyther
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public License
16  * along with this library; see the file COPYING.LIB.  If not, write to
17  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18  * Boston, MA 02110-1301, USA.
19  *
20  */
21
22 #include "config.h"
23 #include "WidthIterator.h"
24
25 #include "Font.h"
26 #include "GlyphBuffer.h"
27 #include "Latin1TextIterator.h"
28 #include "SimpleFontData.h"
29 #include "SurrogatePairAwareTextIterator.h"
30 #include <wtf/MathExtras.h>
31
32 using namespace WTF;
33 using namespace Unicode;
34
35 namespace WebCore {
36
37 WidthIterator::WidthIterator(const Font* font, const TextRun& run, HashSet<const SimpleFontData*>* fallbackFonts, bool accountForGlyphBounds, bool forTextEmphasis)
38     : m_font(font)
39     , m_run(run)
40     , m_currentCharacter(0)
41     , m_runWidthSoFar(0)
42     , m_isAfterExpansion(!run.allowsLeadingExpansion())
43     , m_finalRoundingWidth(0)
44     , m_typesettingFeatures(font->typesettingFeatures())
45     , m_fallbackFonts(fallbackFonts)
46     , m_accountForGlyphBounds(accountForGlyphBounds)
47     , m_maxGlyphBoundingBoxY(std::numeric_limits<float>::min())
48     , m_minGlyphBoundingBoxY(std::numeric_limits<float>::max())
49     , m_firstGlyphOverflow(0)
50     , m_lastGlyphOverflow(0)
51     , m_forTextEmphasis(forTextEmphasis)
52 {
53     // If the padding is non-zero, count the number of spaces in the run
54     // and divide that by the padding for per space addition.
55     m_expansion = m_run.expansion();
56     if (!m_expansion)
57         m_expansionPerOpportunity = 0;
58     else {
59         bool isAfterExpansion = m_isAfterExpansion;
60         unsigned expansionOpportunityCount = m_run.is8Bit() ? Font::expansionOpportunityCount(m_run.characters8(), m_run.length(), m_run.ltr() ? LTR : RTL, isAfterExpansion) : Font::expansionOpportunityCount(m_run.characters16(), m_run.length(), m_run.ltr() ? LTR : RTL, isAfterExpansion);
61         if (isAfterExpansion && !m_run.allowsTrailingExpansion())
62             expansionOpportunityCount--;
63
64         if (!expansionOpportunityCount)
65             m_expansionPerOpportunity = 0;
66         else
67             m_expansionPerOpportunity = m_expansion / expansionOpportunityCount;
68     }
69 }
70
71 GlyphData WidthIterator::glyphDataForCharacter(UChar32 character, bool mirror, unsigned currentCharacter, unsigned& advanceLength)
72 {
73     ASSERT(m_font);
74
75 #if ENABLE(SVG_FONTS)
76     if (TextRun::RenderingContext* renderingContext = m_run.renderingContext())
77         return renderingContext->glyphDataForCharacter(*m_font, *this, character, mirror, currentCharacter, advanceLength);
78 #else
79     UNUSED_PARAM(currentCharacter);
80     UNUSED_PARAM(advanceLength);
81 #endif
82
83     return m_font->glyphDataForCharacter(character, mirror);
84 }
85
86 struct OriginalAdvancesForCharacterTreatedAsSpace {
87 public:
88     OriginalAdvancesForCharacterTreatedAsSpace(bool isSpace, float advanceBefore, float advanceAt)
89         : characterIsSpace(isSpace)
90         , advanceBeforeCharacter(advanceBefore)
91         , advanceAtCharacter(advanceAt)
92     {
93     }
94
95     bool characterIsSpace;
96     float advanceBeforeCharacter;
97     float advanceAtCharacter;
98 };
99
100 typedef Vector<std::pair<int, OriginalAdvancesForCharacterTreatedAsSpace>, 64> CharactersTreatedAsSpace;
101
102 static inline float applyFontTransforms(GlyphBuffer* glyphBuffer, bool ltr, unsigned& lastGlyphCount, const SimpleFontData* fontData, WidthIterator& iterator, TypesettingFeatures typesettingFeatures, CharactersTreatedAsSpace& charactersTreatedAsSpace)
103 {
104     ASSERT(typesettingFeatures & (Kerning | Ligatures));
105
106     if (!glyphBuffer)
107         return 0;
108
109     int glyphBufferSize = glyphBuffer->size();
110     if (glyphBuffer->size() <= lastGlyphCount + 1)
111         return 0;
112
113     GlyphBufferAdvance* advances = glyphBuffer->advances(0);
114     float widthDifference = 0;
115     for (int i = lastGlyphCount; i < glyphBufferSize; ++i)
116         widthDifference -= advances[i].width();
117
118     if (!ltr)
119         glyphBuffer->reverse(lastGlyphCount, glyphBufferSize - lastGlyphCount);
120
121 #if !ENABLE(SVG_FONTS)
122     UNUSED_PARAM(iterator);
123 #else
124     // We need to handle transforms on SVG fonts internally, since they are rendered internally.
125     if (fontData->isSVGFont()) {
126         ASSERT(iterator.run().renderingContext());
127         // SVG font ligatures are handled during glyph selection, only kerning remaining.
128         if (typesettingFeatures & Kerning)
129             iterator.run().renderingContext()->applySVGKerning(fontData, iterator, glyphBuffer, lastGlyphCount);
130     } else
131 #endif
132         fontData->applyTransforms(glyphBuffer->glyphs(lastGlyphCount), advances + lastGlyphCount, glyphBufferSize - lastGlyphCount, typesettingFeatures);
133
134     if (!ltr)
135         glyphBuffer->reverse(lastGlyphCount, glyphBufferSize - lastGlyphCount);
136
137     for (size_t i = 0; i < charactersTreatedAsSpace.size(); ++i) {
138         int spaceOffset = charactersTreatedAsSpace[i].first;
139         const OriginalAdvancesForCharacterTreatedAsSpace& originalAdvances = charactersTreatedAsSpace[i].second;
140         if (spaceOffset && !originalAdvances.characterIsSpace)
141             glyphBuffer->advances(spaceOffset - 1)->setWidth(originalAdvances.advanceBeforeCharacter);
142         glyphBuffer->advances(spaceOffset)->setWidth(originalAdvances.advanceAtCharacter);
143     }
144     charactersTreatedAsSpace.clear();
145
146     for (int i = lastGlyphCount; i < glyphBufferSize; ++i)
147         widthDifference += advances[i].width();
148
149     lastGlyphCount = glyphBufferSize;
150     return widthDifference;
151 }
152
153 template <typename TextIterator>
154 inline unsigned WidthIterator::advanceInternal(TextIterator& textIterator, GlyphBuffer* glyphBuffer)
155 {
156     bool rtl = m_run.rtl();
157     bool hasExtraSpacing = (m_font->letterSpacing() || m_font->wordSpacing() || m_expansion) && !m_run.spacingDisabled();
158
159     float widthSinceLastRounding = m_runWidthSoFar;
160     m_runWidthSoFar = floorf(m_runWidthSoFar);
161     widthSinceLastRounding -= m_runWidthSoFar;
162
163     float lastRoundingWidth = m_finalRoundingWidth;
164     FloatRect bounds;
165
166     const SimpleFontData* primaryFont = m_font->primaryFont();
167     const SimpleFontData* lastFontData = primaryFont;
168     unsigned lastGlyphCount = glyphBuffer ? glyphBuffer->size() : 0;
169
170     UChar32 character = 0;
171     unsigned clusterLength = 0;
172     CharactersTreatedAsSpace charactersTreatedAsSpace;
173     while (textIterator.consume(character, clusterLength)) {
174         unsigned advanceLength = clusterLength;
175         unsigned currentCharacter = textIterator.currentCharacter();
176         const GlyphData& glyphData = glyphDataForCharacter(character, rtl, currentCharacter, advanceLength);
177         Glyph glyph = glyphData.glyph;
178         const SimpleFontData* fontData = glyphData.fontData;
179
180         ASSERT(fontData);
181
182         // Now that we have a glyph and font data, get its width.
183         float width;
184         if (character == '\t' && m_run.allowTabs())
185             width = m_font->tabWidth(*fontData, m_run.tabSize(), m_run.xPos() + m_runWidthSoFar + widthSinceLastRounding);
186         else {
187             width = fontData->widthForGlyph(glyph);
188
189             // SVG uses horizontalGlyphStretch(), when textLength is used to stretch/squeeze text.
190             width *= m_run.horizontalGlyphStretch();
191
192             // We special case spaces in two ways when applying word rounding.
193             // First, we round spaces to an adjusted width in all fonts.
194             // Second, in fixed-pitch fonts we ensure that all characters that
195             // match the width of the space character have the same width as the space character.
196             if (m_run.applyWordRounding() && width == fontData->spaceWidth() && (fontData->pitch() == FixedPitch || glyph == fontData->spaceGlyph()))
197                 width = fontData->adjustedSpaceWidth();
198         }
199
200         if (fontData != lastFontData && width) {
201             if (shouldApplyFontTransforms()) {
202                 m_runWidthSoFar += applyFontTransforms(glyphBuffer, m_run.ltr(), lastGlyphCount, lastFontData, *this, m_typesettingFeatures, charactersTreatedAsSpace);
203                 lastGlyphCount = glyphBuffer->size(); // applyFontTransforms doesn't update when there had been only one glyph.
204             }
205
206             lastFontData = fontData;
207             if (m_fallbackFonts && fontData != primaryFont) {
208                 // FIXME: This does a little extra work that could be avoided if
209                 // glyphDataForCharacter() returned whether it chose to use a small caps font.
210                 if (!m_font->isSmallCaps() || character == u_toupper(character))
211                     m_fallbackFonts->add(fontData);
212                 else {
213                     const GlyphData& uppercaseGlyphData = m_font->glyphDataForCharacter(u_toupper(character), rtl);
214                     if (uppercaseGlyphData.fontData != primaryFont)
215                         m_fallbackFonts->add(uppercaseGlyphData.fontData);
216                 }
217             }
218         }
219
220         if (hasExtraSpacing) {
221             // Account for letter-spacing.
222             if (width && m_font->letterSpacing())
223                 width += m_font->letterSpacing();
224
225             static bool expandAroundIdeographs = Font::canExpandAroundIdeographsInComplexText();
226             bool treatAsSpace = Font::treatAsSpace(character);
227             if (treatAsSpace || (expandAroundIdeographs && Font::isCJKIdeographOrSymbol(character))) {
228                 // Distribute the run's total expansion evenly over all expansion opportunities in the run.
229                 if (m_expansion) {
230                     float previousExpansion = m_expansion;
231                     if (!treatAsSpace && !m_isAfterExpansion) {
232                         // Take the expansion opportunity before this ideograph.
233                         m_expansion -= m_expansionPerOpportunity;
234                         float expansionAtThisOpportunity = !m_run.applyWordRounding() ? m_expansionPerOpportunity : roundf(previousExpansion) - roundf(m_expansion);
235                         m_runWidthSoFar += expansionAtThisOpportunity;
236                         if (glyphBuffer) {
237                             if (glyphBuffer->isEmpty()) {
238                                 if (m_forTextEmphasis)
239                                     glyphBuffer->add(fontData->zeroWidthSpaceGlyph(), fontData, m_expansionPerOpportunity, currentCharacter);
240                                 else
241                                     glyphBuffer->add(fontData->spaceGlyph(), fontData, expansionAtThisOpportunity, currentCharacter);
242                             } else
243                                 glyphBuffer->expandLastAdvance(expansionAtThisOpportunity);
244                         }
245                         previousExpansion = m_expansion;
246                     }
247                     if (m_run.allowsTrailingExpansion() || (m_run.ltr() && currentCharacter + advanceLength < static_cast<size_t>(m_run.length()))
248                         || (m_run.rtl() && currentCharacter)) {
249                         m_expansion -= m_expansionPerOpportunity;
250                         width += !m_run.applyWordRounding() ? m_expansionPerOpportunity : roundf(previousExpansion) - roundf(m_expansion);
251                         m_isAfterExpansion = true;
252                     }
253                 } else
254                     m_isAfterExpansion = false;
255
256                 // Account for word spacing.
257                 // We apply additional space between "words" by adding width to the space character.
258                 if (treatAsSpace && (character != '\t' || !m_run.allowTabs()) && (currentCharacter || character == noBreakSpace) && m_font->wordSpacing())
259                     width += m_font->wordSpacing();
260             } else
261                 m_isAfterExpansion = false;
262         }
263
264         if (shouldApplyFontTransforms() && glyphBuffer && Font::treatAsSpace(character))
265             charactersTreatedAsSpace.append(std::make_pair(glyphBuffer->size(),
266                 OriginalAdvancesForCharacterTreatedAsSpace(character == ' ', glyphBuffer->size() ? glyphBuffer->advanceAt(glyphBuffer->size() - 1).width() : 0, width)));
267
268         if (m_accountForGlyphBounds) {
269             bounds = fontData->boundsForGlyph(glyph);
270             if (!currentCharacter)
271                 m_firstGlyphOverflow = std::max<float>(0, -bounds.x());
272         }
273
274         if (m_forTextEmphasis && !Font::canReceiveTextEmphasis(character))
275             glyph = 0;
276
277         // Advance past the character we just dealt with.
278         textIterator.advance(advanceLength);
279
280         float oldWidth = width;
281
282         // Force characters that are used to determine word boundaries for the rounding hack
283         // to be integer width, so following words will start on an integer boundary.
284         if (m_run.applyWordRounding() && Font::isRoundingHackCharacter(character)) {
285             width = ceilf(width);
286
287             // Since widthSinceLastRounding can lose precision if we include measurements for
288             // preceding whitespace, we bypass it here.
289             m_runWidthSoFar += width;
290
291             // Since this is a rounding hack character, we should have reset this sum on the previous
292             // iteration.
293             ASSERT(!widthSinceLastRounding);
294         } else {
295             // Check to see if the next character is a "rounding hack character", if so, adjust
296             // width so that the total run width will be on an integer boundary.
297             if ((m_run.applyWordRounding() && textIterator.currentCharacter() < m_run.length() && Font::isRoundingHackCharacter(*(textIterator.characters())))
298                 || (m_run.applyRunRounding() && textIterator.currentCharacter() >= m_run.length())) {
299                 float totalWidth = widthSinceLastRounding + width;
300                 widthSinceLastRounding = ceilf(totalWidth);
301                 width += widthSinceLastRounding - totalWidth;
302                 m_runWidthSoFar += widthSinceLastRounding;
303                 widthSinceLastRounding = 0;
304             } else
305                 widthSinceLastRounding += width;
306         }
307
308         if (glyphBuffer)
309             glyphBuffer->add(glyph, fontData, (rtl ? oldWidth + lastRoundingWidth : width), currentCharacter);
310
311         lastRoundingWidth = width - oldWidth;
312
313         if (m_accountForGlyphBounds) {
314             m_maxGlyphBoundingBoxY = std::max(m_maxGlyphBoundingBoxY, bounds.maxY());
315             m_minGlyphBoundingBoxY = std::min(m_minGlyphBoundingBoxY, bounds.y());
316             m_lastGlyphOverflow = std::max<float>(0, bounds.maxX() - width);
317         }
318     }
319
320     if (shouldApplyFontTransforms())
321         m_runWidthSoFar += applyFontTransforms(glyphBuffer, m_run.ltr(), lastGlyphCount, lastFontData, *this, m_typesettingFeatures, charactersTreatedAsSpace);
322
323     unsigned consumedCharacters = textIterator.currentCharacter() - m_currentCharacter;
324     m_currentCharacter = textIterator.currentCharacter();
325     m_runWidthSoFar += widthSinceLastRounding;
326     m_finalRoundingWidth = lastRoundingWidth;
327     return consumedCharacters;
328 }
329
330 unsigned WidthIterator::advance(unsigned offset, GlyphBuffer* glyphBuffer)
331 {
332     unsigned length = m_run.length();
333
334     if (offset > length)
335         offset = length;
336
337     if (m_currentCharacter >= offset)
338         return 0;
339
340     if (m_run.is8Bit()) {
341         Latin1TextIterator textIterator(m_run.data8(m_currentCharacter), m_currentCharacter, offset, length);
342         return advanceInternal(textIterator, glyphBuffer);
343     }
344
345     SurrogatePairAwareTextIterator textIterator(m_run.data16(m_currentCharacter), m_currentCharacter, offset, length);
346     return advanceInternal(textIterator, glyphBuffer);
347 }
348
349 bool WidthIterator::advanceOneCharacter(float& width, GlyphBuffer& glyphBuffer)
350 {
351     unsigned oldSize = glyphBuffer.size();
352     advance(m_currentCharacter + 1, &glyphBuffer);
353     float w = 0;
354     for (unsigned i = oldSize; i < glyphBuffer.size(); ++i)
355         w += glyphBuffer.advanceAt(i).width();
356     width = w;
357     return glyphBuffer.size() > oldSize;
358 }
359
360 }