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