REGRESSION (r169407): Calls to RenderStyle::getRoundedBorderFor() in computeRoundedRe...
[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, int 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, int& 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         // SVG font ligatures are handled during glyph selection, only kerning remaining.
127         if (iterator.run().renderingContext() && (typesettingFeatures & Kerning)) {
128             // FIXME: We could pass the necessary context down to this level so we can lazily create rendering contexts at this point.
129             // However, a larger refactoring of SVG fonts might necessary to sidestep this problem completely.
130             iterator.run().renderingContext()->applySVGKerning(fontData, iterator, glyphBuffer, lastGlyphCount);
131         }
132     } else
133 #endif
134         fontData->applyTransforms(glyphBuffer->glyphs(lastGlyphCount), advances + lastGlyphCount, glyphBufferSize - lastGlyphCount, typesettingFeatures);
135
136     if (!ltr)
137         glyphBuffer->reverse(lastGlyphCount, glyphBufferSize - lastGlyphCount);
138
139     for (size_t i = 0; i < charactersTreatedAsSpace.size(); ++i) {
140         int spaceOffset = charactersTreatedAsSpace[i].first;
141         const OriginalAdvancesForCharacterTreatedAsSpace& originalAdvances = charactersTreatedAsSpace[i].second;
142         if (spaceOffset && !originalAdvances.characterIsSpace)
143             glyphBuffer->advances(spaceOffset - 1)->setWidth(originalAdvances.advanceBeforeCharacter);
144         glyphBuffer->advances(spaceOffset)->setWidth(originalAdvances.advanceAtCharacter);
145     }
146     charactersTreatedAsSpace.clear();
147
148     for (int i = lastGlyphCount; i < glyphBufferSize; ++i)
149         widthDifference += advances[i].width();
150
151     lastGlyphCount = glyphBufferSize;
152     return widthDifference;
153 }
154
155 template <typename TextIterator>
156 inline unsigned WidthIterator::advanceInternal(TextIterator& textIterator, GlyphBuffer* glyphBuffer)
157 {
158     bool rtl = m_run.rtl();
159     bool hasExtraSpacing = (m_font->letterSpacing() || m_font->wordSpacing() || m_expansion) && !m_run.spacingDisabled();
160
161     float widthSinceLastRounding = m_runWidthSoFar;
162     m_runWidthSoFar = floorf(m_runWidthSoFar);
163     widthSinceLastRounding -= m_runWidthSoFar;
164
165     float lastRoundingWidth = m_finalRoundingWidth;
166     FloatRect bounds;
167
168     const SimpleFontData* primaryFont = m_font->primaryFont();
169     const SimpleFontData* lastFontData = primaryFont;
170     int lastGlyphCount = glyphBuffer ? glyphBuffer->size() : 0;
171
172     UChar32 character = 0;
173     unsigned clusterLength = 0;
174     CharactersTreatedAsSpace charactersTreatedAsSpace;
175     while (textIterator.consume(character, clusterLength)) {
176         unsigned advanceLength = clusterLength;
177         int currentCharacter = textIterator.currentCharacter();
178         const GlyphData& glyphData = glyphDataForCharacter(character, rtl, currentCharacter, advanceLength);
179         Glyph glyph = glyphData.glyph;
180         const SimpleFontData* fontData = glyphData.fontData;
181
182         ASSERT(fontData);
183
184         // Now that we have a glyph and font data, get its width.
185         float width;
186         if (character == '\t' && m_run.allowTabs())
187             width = m_font->tabWidth(*fontData, m_run.tabSize(), m_run.xPos() + m_runWidthSoFar + widthSinceLastRounding);
188         else {
189             width = fontData->widthForGlyph(glyph);
190
191             // SVG uses horizontalGlyphStretch(), when textLength is used to stretch/squeeze text.
192             width *= m_run.horizontalGlyphStretch();
193
194             // We special case spaces in two ways when applying word rounding.
195             // First, we round spaces to an adjusted width in all fonts.
196             // Second, in fixed-pitch fonts we ensure that all characters that
197             // match the width of the space character have the same width as the space character.
198             if (m_run.applyWordRounding() && width == fontData->spaceWidth() && (fontData->pitch() == FixedPitch || glyph == fontData->spaceGlyph()))
199                 width = fontData->adjustedSpaceWidth();
200         }
201
202         if (fontData != lastFontData && width) {
203             if (shouldApplyFontTransforms()) {
204                 m_runWidthSoFar += applyFontTransforms(glyphBuffer, m_run.ltr(), lastGlyphCount, lastFontData, *this, m_typesettingFeatures, charactersTreatedAsSpace);
205                 lastGlyphCount = glyphBuffer->size(); // applyFontTransforms doesn't update when there had been only one glyph.
206             }
207
208             lastFontData = fontData;
209             if (m_fallbackFonts && fontData != primaryFont) {
210                 // FIXME: This does a little extra work that could be avoided if
211                 // glyphDataForCharacter() returned whether it chose to use a small caps font.
212                 if (!m_font->isSmallCaps() || character == u_toupper(character))
213                     m_fallbackFonts->add(fontData);
214                 else {
215                     const GlyphData& uppercaseGlyphData = m_font->glyphDataForCharacter(u_toupper(character), rtl);
216                     if (uppercaseGlyphData.fontData != primaryFont)
217                         m_fallbackFonts->add(uppercaseGlyphData.fontData);
218                 }
219             }
220         }
221
222         if (hasExtraSpacing) {
223             // Account for letter-spacing.
224             if (width && m_font->letterSpacing())
225                 width += m_font->letterSpacing();
226
227             static bool expandAroundIdeographs = Font::canExpandAroundIdeographsInComplexText();
228             bool treatAsSpace = Font::treatAsSpace(character);
229             if (treatAsSpace || (expandAroundIdeographs && Font::isCJKIdeographOrSymbol(character))) {
230                 // Distribute the run's total expansion evenly over all expansion opportunities in the run.
231                 if (m_expansion) {
232                     float previousExpansion = m_expansion;
233                     if (!treatAsSpace && !m_isAfterExpansion) {
234                         // Take the expansion opportunity before this ideograph.
235                         m_expansion -= m_expansionPerOpportunity;
236                         float expansionAtThisOpportunity = !m_run.applyWordRounding() ? m_expansionPerOpportunity : roundf(previousExpansion) - roundf(m_expansion);
237                         m_runWidthSoFar += expansionAtThisOpportunity;
238                         if (glyphBuffer) {
239                             if (glyphBuffer->isEmpty()) {
240                                 if (m_forTextEmphasis)
241                                     glyphBuffer->add(fontData->zeroWidthSpaceGlyph(), fontData, m_expansionPerOpportunity, currentCharacter);
242                                 else
243                                     glyphBuffer->add(fontData->spaceGlyph(), fontData, expansionAtThisOpportunity, currentCharacter);
244                             } else
245                                 glyphBuffer->expandLastAdvance(expansionAtThisOpportunity);
246                         }
247                         previousExpansion = m_expansion;
248                     }
249                     if (m_run.allowsTrailingExpansion() || (m_run.ltr() && currentCharacter + advanceLength < static_cast<size_t>(m_run.length()))
250                         || (m_run.rtl() && currentCharacter)) {
251                         m_expansion -= m_expansionPerOpportunity;
252                         width += !m_run.applyWordRounding() ? m_expansionPerOpportunity : roundf(previousExpansion) - roundf(m_expansion);
253                         m_isAfterExpansion = true;
254                     }
255                 } else
256                     m_isAfterExpansion = false;
257
258                 // Account for word spacing.
259                 // We apply additional space between "words" by adding width to the space character.
260                 if (treatAsSpace && (character != '\t' || !m_run.allowTabs()) && (currentCharacter || character == noBreakSpace) && m_font->wordSpacing())
261                     width += m_font->wordSpacing();
262             } else
263                 m_isAfterExpansion = false;
264         }
265
266         if (shouldApplyFontTransforms() && glyphBuffer && Font::treatAsSpace(character))
267             charactersTreatedAsSpace.append(std::make_pair(glyphBuffer->size(),
268                 OriginalAdvancesForCharacterTreatedAsSpace(character == ' ', glyphBuffer->size() ? glyphBuffer->advanceAt(glyphBuffer->size() - 1).width() : 0, width)));
269
270         if (m_accountForGlyphBounds) {
271             bounds = fontData->boundsForGlyph(glyph);
272             if (!currentCharacter)
273                 m_firstGlyphOverflow = std::max<float>(0, -bounds.x());
274         }
275
276         if (m_forTextEmphasis && !Font::canReceiveTextEmphasis(character))
277             glyph = 0;
278
279         // Advance past the character we just dealt with.
280         textIterator.advance(advanceLength);
281
282         float oldWidth = width;
283
284         // Force characters that are used to determine word boundaries for the rounding hack
285         // to be integer width, so following words will start on an integer boundary.
286         if (m_run.applyWordRounding() && Font::isRoundingHackCharacter(character)) {
287             width = ceilf(width);
288
289             // Since widthSinceLastRounding can lose precision if we include measurements for
290             // preceding whitespace, we bypass it here.
291             m_runWidthSoFar += width;
292
293             // Since this is a rounding hack character, we should have reset this sum on the previous
294             // iteration.
295             ASSERT(!widthSinceLastRounding);
296         } else {
297             // Check to see if the next character is a "rounding hack character", if so, adjust
298             // width so that the total run width will be on an integer boundary.
299             if ((m_run.applyWordRounding() && textIterator.currentCharacter() < m_run.length() && Font::isRoundingHackCharacter(*(textIterator.characters())))
300                 || (m_run.applyRunRounding() && textIterator.currentCharacter() >= m_run.length())) {
301                 float totalWidth = widthSinceLastRounding + width;
302                 widthSinceLastRounding = ceilf(totalWidth);
303                 width += widthSinceLastRounding - totalWidth;
304                 m_runWidthSoFar += widthSinceLastRounding;
305                 widthSinceLastRounding = 0;
306             } else
307                 widthSinceLastRounding += width;
308         }
309
310         if (glyphBuffer)
311             glyphBuffer->add(glyph, fontData, (rtl ? oldWidth + lastRoundingWidth : width), currentCharacter);
312
313         lastRoundingWidth = width - oldWidth;
314
315         if (m_accountForGlyphBounds) {
316             m_maxGlyphBoundingBoxY = std::max(m_maxGlyphBoundingBoxY, bounds.maxY());
317             m_minGlyphBoundingBoxY = std::min(m_minGlyphBoundingBoxY, bounds.y());
318             m_lastGlyphOverflow = std::max<float>(0, bounds.maxX() - width);
319         }
320     }
321
322     if (shouldApplyFontTransforms())
323         m_runWidthSoFar += applyFontTransforms(glyphBuffer, m_run.ltr(), lastGlyphCount, lastFontData, *this, m_typesettingFeatures, charactersTreatedAsSpace);
324
325     unsigned consumedCharacters = textIterator.currentCharacter() - m_currentCharacter;
326     m_currentCharacter = textIterator.currentCharacter();
327     m_runWidthSoFar += widthSinceLastRounding;
328     m_finalRoundingWidth = lastRoundingWidth;
329     return consumedCharacters;
330 }
331
332 unsigned WidthIterator::advance(int offset, GlyphBuffer* glyphBuffer)
333 {
334     int length = m_run.length();
335
336     if (offset > length)
337         offset = length;
338
339     if (m_currentCharacter >= static_cast<unsigned>(offset))
340         return 0;
341
342     if (m_run.is8Bit()) {
343         Latin1TextIterator textIterator(m_run.data8(m_currentCharacter), m_currentCharacter, offset, length);
344         return advanceInternal(textIterator, glyphBuffer);
345     }
346
347     SurrogatePairAwareTextIterator textIterator(m_run.data16(m_currentCharacter), m_currentCharacter, offset, length);
348     return advanceInternal(textIterator, glyphBuffer);
349 }
350
351 bool WidthIterator::advanceOneCharacter(float& width, GlyphBuffer& glyphBuffer)
352 {
353     int oldSize = glyphBuffer.size();
354     advance(m_currentCharacter + 1, &glyphBuffer);
355     float w = 0;
356     for (int i = oldSize; i < glyphBuffer.size(); ++i)
357         w += glyphBuffer.advanceAt(i).width();
358     width = w;
359     return glyphBuffer.size() > oldSize;
360 }
361
362 }