Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / platform / fonts / harfbuzz / HarfBuzzShaper.cpp
1 /*
2  * Copyright (c) 2012 Google Inc. All rights reserved.
3  * Copyright (C) 2013 BlackBerry Limited. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are
7  * met:
8  *
9  *     * Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  *     * Redistributions in binary form must reproduce the above
12  * copyright notice, this list of conditions and the following disclaimer
13  * in the documentation and/or other materials provided with the
14  * distribution.
15  *     * Neither the name of Google Inc. nor the names of its
16  * contributors may be used to endorse or promote products derived from
17  * this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31
32 #include "config.h"
33 #include "platform/fonts/harfbuzz/HarfBuzzShaper.h"
34
35 #include "hb.h"
36 #include "platform/LayoutUnit.h"
37 #include "platform/RuntimeEnabledFeatures.h"
38 #include "platform/fonts/Character.h"
39 #include "platform/fonts/Font.h"
40 #include "platform/fonts/GlyphBuffer.h"
41 #include "platform/fonts/harfbuzz/HarfBuzzFace.h"
42 #include "platform/text/SurrogatePairAwareTextIterator.h"
43 #include "platform/text/TextBreakIterator.h"
44 #include "wtf/Compiler.h"
45 #include "wtf/MathExtras.h"
46 #include "wtf/unicode/Unicode.h"
47 #include <unicode/normlzr.h>
48 #include <unicode/uchar.h>
49 #include <unicode/uscript.h>
50
51 #include <list>
52 #include <map>
53 #include <string>
54
55 namespace blink {
56
57 template<typename T>
58 class HarfBuzzScopedPtr {
59 public:
60     typedef void (*DestroyFunction)(T*);
61
62     HarfBuzzScopedPtr(T* ptr, DestroyFunction destroy)
63         : m_ptr(ptr)
64         , m_destroy(destroy)
65     {
66         ASSERT(m_destroy);
67     }
68     ~HarfBuzzScopedPtr()
69     {
70         if (m_ptr)
71             (*m_destroy)(m_ptr);
72     }
73
74     T* get() { return m_ptr; }
75     void set(T* ptr) { m_ptr = ptr; }
76 private:
77     T* m_ptr;
78     DestroyFunction m_destroy;
79 };
80
81
82 static const unsigned cHarfBuzzCacheMaxSize = 256;
83
84 struct CachedShapingResultsLRUNode;
85 struct CachedShapingResults;
86 typedef std::map<std::wstring, CachedShapingResults*> CachedShapingResultsMap;
87 typedef std::list<CachedShapingResultsLRUNode*> CachedShapingResultsLRU;
88
89 struct CachedShapingResults {
90     CachedShapingResults(hb_buffer_t* harfBuzzBuffer, const Font* runFont, hb_direction_t runDir, const String& newLocale);
91     ~CachedShapingResults();
92
93     hb_buffer_t* buffer;
94     Font font;
95     hb_direction_t dir;
96     String locale;
97     CachedShapingResultsLRU::iterator lru;
98 };
99
100 struct CachedShapingResultsLRUNode {
101     CachedShapingResultsLRUNode(const CachedShapingResultsMap::iterator& cacheEntry);
102     ~CachedShapingResultsLRUNode();
103
104     CachedShapingResultsMap::iterator entry;
105 };
106
107 CachedShapingResults::CachedShapingResults(hb_buffer_t* harfBuzzBuffer, const Font* fontData, hb_direction_t dirData, const String& newLocale)
108     : buffer(harfBuzzBuffer)
109     , font(*fontData)
110     , dir(dirData)
111     , locale(newLocale)
112 {
113 }
114
115 CachedShapingResults::~CachedShapingResults()
116 {
117     hb_buffer_destroy(buffer);
118 }
119
120 CachedShapingResultsLRUNode::CachedShapingResultsLRUNode(const CachedShapingResultsMap::iterator& cacheEntry)
121     : entry(cacheEntry)
122 {
123 }
124
125 CachedShapingResultsLRUNode::~CachedShapingResultsLRUNode()
126 {
127 }
128
129 class HarfBuzzRunCache {
130 public:
131     HarfBuzzRunCache();
132     ~HarfBuzzRunCache();
133
134     CachedShapingResults* find(const std::wstring& key) const;
135     void remove(CachedShapingResults* node);
136     void moveToBack(CachedShapingResults* node);
137     bool insert(const std::wstring& key, CachedShapingResults* run);
138
139 private:
140     CachedShapingResultsMap m_harfBuzzRunMap;
141     CachedShapingResultsLRU m_harfBuzzRunLRU;
142 };
143
144
145 HarfBuzzRunCache::HarfBuzzRunCache()
146 {
147 }
148
149 HarfBuzzRunCache::~HarfBuzzRunCache()
150 {
151     for (CachedShapingResultsMap::iterator it = m_harfBuzzRunMap.begin(); it != m_harfBuzzRunMap.end(); ++it)
152         delete it->second;
153     for (CachedShapingResultsLRU::iterator it = m_harfBuzzRunLRU.begin(); it != m_harfBuzzRunLRU.end(); ++it)
154         delete *it;
155 }
156
157 bool HarfBuzzRunCache::insert(const std::wstring& key, CachedShapingResults* data)
158 {
159     std::pair<CachedShapingResultsMap::iterator, bool> results =
160         m_harfBuzzRunMap.insert(CachedShapingResultsMap::value_type(key, data));
161
162     if (!results.second)
163         return false;
164
165     CachedShapingResultsLRUNode* node = new CachedShapingResultsLRUNode(results.first);
166
167     m_harfBuzzRunLRU.push_back(node);
168     data->lru = --m_harfBuzzRunLRU.end();
169
170     if (m_harfBuzzRunMap.size() > cHarfBuzzCacheMaxSize) {
171         CachedShapingResultsLRUNode* lru = m_harfBuzzRunLRU.front();
172         CachedShapingResults* foo = lru->entry->second;
173         m_harfBuzzRunMap.erase(lru->entry);
174         m_harfBuzzRunLRU.pop_front();
175         delete foo;
176         delete lru;
177     }
178
179     return true;
180 }
181
182 inline CachedShapingResults* HarfBuzzRunCache::find(const std::wstring& key) const
183 {
184     CachedShapingResultsMap::const_iterator it = m_harfBuzzRunMap.find(key);
185
186     return it != m_harfBuzzRunMap.end() ? it->second : 0;
187 }
188
189 inline void HarfBuzzRunCache::remove(CachedShapingResults* node)
190 {
191     CachedShapingResultsLRUNode* lruNode = *node->lru;
192
193     m_harfBuzzRunLRU.erase(node->lru);
194     m_harfBuzzRunMap.erase(lruNode->entry);
195     delete lruNode;
196     delete node;
197 }
198
199 inline void HarfBuzzRunCache::moveToBack(CachedShapingResults* node)
200 {
201     CachedShapingResultsLRUNode* lruNode = *node->lru;
202     m_harfBuzzRunLRU.erase(node->lru);
203     m_harfBuzzRunLRU.push_back(lruNode);
204     node->lru = --m_harfBuzzRunLRU.end();
205 }
206
207 HarfBuzzRunCache& harfBuzzRunCache()
208 {
209     DEFINE_STATIC_LOCAL(HarfBuzzRunCache, globalHarfBuzzRunCache, ());
210     return globalHarfBuzzRunCache;
211 }
212
213 static inline float harfBuzzPositionToFloat(hb_position_t value)
214 {
215     return static_cast<float>(value) / (1 << 16);
216 }
217
218 static inline unsigned countGraphemesInCluster(const UChar* normalizedBuffer, unsigned normalizedBufferLength, uint16_t startIndex, uint16_t endIndex)
219 {
220     if (startIndex > endIndex) {
221         uint16_t tempIndex = startIndex;
222         startIndex = endIndex;
223         endIndex = tempIndex;
224     }
225     uint16_t length = endIndex - startIndex;
226     ASSERT(static_cast<unsigned>(startIndex + length) <= normalizedBufferLength);
227     TextBreakIterator* cursorPosIterator = cursorMovementIterator(&normalizedBuffer[startIndex], length);
228
229     int cursorPos = cursorPosIterator->current();
230     int numGraphemes = -1;
231     while (0 <= cursorPos) {
232         cursorPos = cursorPosIterator->next();
233         numGraphemes++;
234     }
235     return numGraphemes < 0 ? 0 : numGraphemes;
236 }
237
238 inline HarfBuzzShaper::HarfBuzzRun::HarfBuzzRun(const SimpleFontData* fontData, unsigned startIndex, unsigned numCharacters, TextDirection direction, hb_script_t script)
239     : m_fontData(fontData)
240     , m_startIndex(startIndex)
241     , m_numCharacters(numCharacters)
242     , m_numGlyphs(0)
243     , m_direction(direction)
244     , m_script(script)
245     , m_width(0)
246 {
247 }
248
249 inline HarfBuzzShaper::HarfBuzzRun::HarfBuzzRun(const HarfBuzzRun& rhs)
250     : m_fontData(rhs.m_fontData)
251     , m_startIndex(rhs.m_startIndex)
252     , m_numCharacters(rhs.m_numCharacters)
253     , m_numGlyphs(rhs.m_numGlyphs)
254     , m_direction(rhs.m_direction)
255     , m_script(rhs.m_script)
256     , m_glyphs(rhs.m_glyphs)
257     , m_advances(rhs.m_advances)
258     , m_glyphToCharacterIndexes(rhs.m_glyphToCharacterIndexes)
259     , m_offsets(rhs.m_offsets)
260     , m_width(rhs.m_width)
261 {
262 }
263
264 HarfBuzzShaper::HarfBuzzRun::~HarfBuzzRun()
265 {
266 }
267
268 inline void HarfBuzzShaper::HarfBuzzRun::applyShapeResult(hb_buffer_t* harfBuzzBuffer)
269 {
270     m_numGlyphs = hb_buffer_get_length(harfBuzzBuffer);
271     m_glyphs.resize(m_numGlyphs);
272     m_advances.resize(m_numGlyphs);
273     m_glyphToCharacterIndexes.resize(m_numGlyphs);
274     m_offsets.resize(m_numGlyphs);
275 }
276
277 inline void HarfBuzzShaper::HarfBuzzRun::copyShapeResultAndGlyphPositions(const HarfBuzzRun& run)
278 {
279     m_numGlyphs = run.m_numGlyphs;
280     m_glyphs = run.m_glyphs;
281     m_advances = run.m_advances;
282     m_glyphToCharacterIndexes = run.m_glyphToCharacterIndexes;
283     m_offsets = run.m_offsets;
284     m_width = run.m_width;
285 }
286
287 inline void HarfBuzzShaper::HarfBuzzRun::setGlyphAndPositions(unsigned index, uint16_t glyphId, float advance, float offsetX, float offsetY)
288 {
289     m_glyphs[index] = glyphId;
290     m_advances[index] = advance;
291     m_offsets[index] = FloatPoint(offsetX, offsetY);
292 }
293
294 int HarfBuzzShaper::HarfBuzzRun::characterIndexForXPosition(float targetX)
295 {
296     ASSERT(targetX <= m_width);
297     float currentX = 0;
298     float currentAdvance = m_advances[0];
299     unsigned glyphIndex = 0;
300
301     // Sum up advances that belong to a character.
302     while (glyphIndex < m_numGlyphs - 1 && m_glyphToCharacterIndexes[glyphIndex] == m_glyphToCharacterIndexes[glyphIndex + 1])
303         currentAdvance += m_advances[++glyphIndex];
304     currentAdvance = currentAdvance / 2.0;
305     if (targetX <= currentAdvance)
306         return rtl() ? m_numCharacters : 0;
307
308     currentX = currentAdvance;
309     ++glyphIndex;
310     while (glyphIndex < m_numGlyphs) {
311         unsigned prevCharacterIndex = m_glyphToCharacterIndexes[glyphIndex - 1];
312         float prevAdvance = currentAdvance;
313         currentAdvance = m_advances[glyphIndex];
314         while (glyphIndex < m_numGlyphs - 1 && m_glyphToCharacterIndexes[glyphIndex] == m_glyphToCharacterIndexes[glyphIndex + 1])
315             currentAdvance += m_advances[++glyphIndex];
316         currentAdvance = currentAdvance / 2.0;
317         float nextX = currentX + prevAdvance + currentAdvance;
318         if (currentX <= targetX && targetX <= nextX)
319             return rtl() ? prevCharacterIndex : m_glyphToCharacterIndexes[glyphIndex];
320         currentX = nextX;
321         ++glyphIndex;
322     }
323
324     return rtl() ? 0 : m_numCharacters;
325 }
326
327 float HarfBuzzShaper::HarfBuzzRun::xPositionForOffset(unsigned offset)
328 {
329     ASSERT(offset < m_numCharacters);
330     unsigned glyphIndex = 0;
331     float position = 0;
332     if (rtl()) {
333         while (glyphIndex < m_numGlyphs && m_glyphToCharacterIndexes[glyphIndex] > offset) {
334             position += m_advances[glyphIndex];
335             ++glyphIndex;
336         }
337         // For RTL, we need to return the right side boundary of the character.
338         // Add advance of glyphs which are part of the character.
339         while (glyphIndex < m_numGlyphs - 1 && m_glyphToCharacterIndexes[glyphIndex] == m_glyphToCharacterIndexes[glyphIndex + 1]) {
340             position += m_advances[glyphIndex];
341             ++glyphIndex;
342         }
343         position += m_advances[glyphIndex];
344     } else {
345         while (glyphIndex < m_numGlyphs && m_glyphToCharacterIndexes[glyphIndex] < offset) {
346             position += m_advances[glyphIndex];
347             ++glyphIndex;
348         }
349     }
350     return position;
351 }
352
353 static void normalizeCharacters(const TextRun& run, unsigned length, UChar* destination, unsigned* destinationLength)
354 {
355     unsigned position = 0;
356     bool error = false;
357     const UChar* source;
358     String stringFor8BitRun;
359     if (run.is8Bit()) {
360         stringFor8BitRun = String::make16BitFrom8BitSource(run.characters8(), run.length());
361         source = stringFor8BitRun.characters16();
362     } else
363         source = run.characters16();
364
365     *destinationLength = 0;
366     while (position < length) {
367         UChar32 character;
368         U16_NEXT(source, position, length, character);
369         // Don't normalize tabs as they are not treated as spaces for word-end.
370         if (Character::treatAsSpace(character) && character != '\t')
371             character = ' ';
372         else if (Character::treatAsZeroWidthSpaceInComplexScript(character))
373             character = zeroWidthSpace;
374         U16_APPEND(destination, *destinationLength, length, character, error);
375         ASSERT_UNUSED(error, !error);
376     }
377 }
378
379 HarfBuzzShaper::HarfBuzzShaper(const Font* font, const TextRun& run, ForTextEmphasisOrNot forTextEmphasis)
380     : m_font(font)
381     , m_normalizedBufferLength(0)
382     , m_run(run)
383     , m_wordSpacingAdjustment(font->fontDescription().wordSpacing())
384     , m_padding(0)
385     , m_padPerWordBreak(0)
386     , m_padError(0)
387     , m_letterSpacing(font->fontDescription().letterSpacing())
388     , m_fromIndex(0)
389     , m_toIndex(m_run.length())
390     , m_forTextEmphasis(forTextEmphasis)
391     , m_glyphBoundingBox(std::numeric_limits<float>::max(), std::numeric_limits<float>::min(), std::numeric_limits<float>::min(), std::numeric_limits<float>::max())
392 {
393     m_normalizedBuffer = adoptArrayPtr(new UChar[m_run.length() + 1]);
394     normalizeCharacters(m_run, m_run.length(), m_normalizedBuffer.get(), &m_normalizedBufferLength);
395     setPadding(m_run.expansion());
396     setFontFeatures();
397 }
398
399 bool HarfBuzzShaper::isWordEnd(unsigned index)
400 {
401     // This could refer a high-surrogate, but should work.
402     return index && isCodepointSpace(m_normalizedBuffer[index]);
403 }
404
405 int HarfBuzzShaper::determineWordBreakSpacing()
406 {
407     int wordBreakSpacing = m_wordSpacingAdjustment;
408
409     if (m_padding > 0) {
410         int toPad = roundf(m_padPerWordBreak + m_padError);
411         m_padError += m_padPerWordBreak - toPad;
412
413         if (m_padding < toPad)
414             toPad = m_padding;
415         m_padding -= toPad;
416         wordBreakSpacing += toPad;
417     }
418     return wordBreakSpacing;
419 }
420
421 // setPadding sets a number of pixels to be distributed across the TextRun.
422 // WebKit uses this to justify text.
423 void HarfBuzzShaper::setPadding(int padding)
424 {
425     m_padding = padding;
426     m_padError = 0;
427     if (!m_padding)
428         return;
429
430     // If we have padding to distribute, then we try to give an equal
431     // amount to each space. The last space gets the smaller amount, if
432     // any.
433     unsigned numWordEnds = 0;
434
435     for (unsigned i = 0; i < m_normalizedBufferLength; i++) {
436         if (isWordEnd(i))
437             numWordEnds++;
438     }
439
440     if (numWordEnds)
441         m_padPerWordBreak = m_padding / numWordEnds;
442     else
443         m_padPerWordBreak = 0;
444 }
445
446
447 void HarfBuzzShaper::setDrawRange(int from, int to)
448 {
449     ASSERT_WITH_SECURITY_IMPLICATION(from >= 0);
450     ASSERT_WITH_SECURITY_IMPLICATION(to <= m_run.length());
451     m_fromIndex = from;
452     m_toIndex = to;
453 }
454
455 void HarfBuzzShaper::setFontFeatures()
456 {
457     const FontDescription& description = m_font->fontDescription();
458     if (description.orientation() == Vertical) {
459         static hb_feature_t vert = { HarfBuzzFace::vertTag, 1, 0, static_cast<unsigned>(-1) };
460         static hb_feature_t vrt2 = { HarfBuzzFace::vrt2Tag, 1, 0, static_cast<unsigned>(-1) };
461         m_features.append(vert);
462         m_features.append(vrt2);
463     }
464
465     static hb_feature_t noKern = { HB_TAG('k', 'e', 'r', 'n'), 0, 0, static_cast<unsigned>(-1) };
466     static hb_feature_t noVkrn = { HB_TAG('v', 'k', 'r', 'n'), 0, 0, static_cast<unsigned>(-1) };
467     switch (description.kerning()) {
468     case FontDescription::NormalKerning:
469         // kern/vkrn are enabled by default
470         break;
471     case FontDescription::NoneKerning:
472         m_features.append(description.orientation() == Vertical ? noVkrn : noKern);
473         break;
474     case FontDescription::AutoKerning:
475         break;
476     }
477
478     static hb_feature_t noClig = { HB_TAG('c', 'l', 'i', 'g'), 0, 0, static_cast<unsigned>(-1) };
479     static hb_feature_t noLiga = { HB_TAG('l', 'i', 'g', 'a'), 0, 0, static_cast<unsigned>(-1) };
480     switch (description.commonLigaturesState()) {
481     case FontDescription::DisabledLigaturesState:
482         m_features.append(noLiga);
483         m_features.append(noClig);
484         break;
485     case FontDescription::EnabledLigaturesState:
486         // liga and clig are on by default
487         break;
488     case FontDescription::NormalLigaturesState:
489         break;
490     }
491     static hb_feature_t dlig = { HB_TAG('d', 'l', 'i', 'g'), 1, 0, static_cast<unsigned>(-1) };
492     switch (description.discretionaryLigaturesState()) {
493     case FontDescription::DisabledLigaturesState:
494         // dlig is off by default
495         break;
496     case FontDescription::EnabledLigaturesState:
497         m_features.append(dlig);
498         break;
499     case FontDescription::NormalLigaturesState:
500         break;
501     }
502     static hb_feature_t hlig = { HB_TAG('h', 'l', 'i', 'g'), 1, 0, static_cast<unsigned>(-1) };
503     switch (description.historicalLigaturesState()) {
504     case FontDescription::DisabledLigaturesState:
505         // hlig is off by default
506         break;
507     case FontDescription::EnabledLigaturesState:
508         m_features.append(hlig);
509         break;
510     case FontDescription::NormalLigaturesState:
511         break;
512     }
513     static hb_feature_t noCalt = { HB_TAG('c', 'a', 'l', 't'), 0, 0, static_cast<unsigned>(-1) };
514     switch (description.contextualLigaturesState()) {
515     case FontDescription::DisabledLigaturesState:
516         m_features.append(noCalt);
517         break;
518     case FontDescription::EnabledLigaturesState:
519         // calt is on by default
520         break;
521     case FontDescription::NormalLigaturesState:
522         break;
523     }
524
525     static hb_feature_t hwid = { HB_TAG('h', 'w', 'i', 'd'), 1, 0, static_cast<unsigned>(-1) };
526     static hb_feature_t twid = { HB_TAG('t', 'w', 'i', 'd'), 1, 0, static_cast<unsigned>(-1) };
527     static hb_feature_t qwid = { HB_TAG('d', 'w', 'i', 'd'), 1, 0, static_cast<unsigned>(-1) };
528     switch (description.widthVariant()) {
529     case HalfWidth:
530         m_features.append(hwid);
531         break;
532     case ThirdWidth:
533         m_features.append(twid);
534         break;
535     case QuarterWidth:
536         m_features.append(qwid);
537         break;
538     case RegularWidth:
539         break;
540     }
541
542     FontFeatureSettings* settings = description.featureSettings();
543     if (!settings)
544         return;
545
546     unsigned numFeatures = settings->size();
547     for (unsigned i = 0; i < numFeatures; ++i) {
548         hb_feature_t feature;
549         const AtomicString& tag = settings->at(i).tag();
550         feature.tag = HB_TAG(tag[0], tag[1], tag[2], tag[3]);
551         feature.value = settings->at(i).value();
552         feature.start = 0;
553         feature.end = static_cast<unsigned>(-1);
554         m_features.append(feature);
555     }
556 }
557
558 bool HarfBuzzShaper::shape(GlyphBuffer* glyphBuffer)
559 {
560     if (!createHarfBuzzRuns())
561         return false;
562
563     m_totalWidth = 0;
564     if (!shapeHarfBuzzRuns())
565         return false;
566
567     if (!RuntimeEnabledFeatures::subpixelFontScalingEnabled())
568         m_totalWidth = roundf(m_totalWidth);
569
570     if (m_harfBuzzRuns.last()->hasGlyphToCharacterIndexes()
571         && glyphBuffer && !fillGlyphBuffer(glyphBuffer))
572         return false;
573
574     return true;
575 }
576
577 FloatPoint HarfBuzzShaper::adjustStartPoint(const FloatPoint& point)
578 {
579     return point + m_startOffset;
580 }
581
582 static inline int handleMultipleUChar(
583     UChar32 character,
584     unsigned clusterLength,
585     const SimpleFontData* currentFontData,
586     const UChar* currentCharacterPosition,
587     const UChar* markCharactersEnd,
588     const UChar* normalizedBufferEnd)
589 {
590     if (U_GET_GC_MASK(character) & U_GC_M_MASK) {
591         int markLength = clusterLength;
592         while (markCharactersEnd < normalizedBufferEnd) {
593             UChar32 nextCharacter;
594             int nextCharacterLength = 0;
595             U16_NEXT(markCharactersEnd, nextCharacterLength, normalizedBufferEnd - markCharactersEnd, nextCharacter);
596             if (!(U_GET_GC_MASK(nextCharacter) & U_GC_M_MASK))
597                 break;
598             markLength += nextCharacterLength;
599             markCharactersEnd += nextCharacterLength;
600         }
601
602         if (currentFontData->canRenderCombiningCharacterSequence(currentCharacterPosition, markCharactersEnd - currentCharacterPosition)) {
603             return markLength;
604         }
605     }
606     return 0;
607 }
608
609 struct CandidateRun {
610     UChar32 character;
611     unsigned start;
612     unsigned end;
613     const SimpleFontData* fontData;
614     UScriptCode script;
615 };
616
617 static inline bool collectCandidateRuns(const UChar* normalizedBuffer,
618     size_t bufferLength, const Font* font, Vector<CandidateRun>* runs)
619 {
620     const UChar* normalizedBufferEnd = normalizedBuffer + bufferLength;
621     SurrogatePairAwareTextIterator iterator(normalizedBuffer, 0, bufferLength, bufferLength);
622     UChar32 character;
623     unsigned clusterLength = 0;
624     unsigned startIndexOfCurrentRun = 0;
625     if (!iterator.consume(character, clusterLength))
626         return false;
627
628     const SimpleFontData* nextFontData = font->glyphDataForCharacter(character, false).fontData;
629     UErrorCode errorCode = U_ZERO_ERROR;
630     UScriptCode nextScript = uscript_getScript(character, &errorCode);
631     if (U_FAILURE(errorCode))
632         return false;
633
634     do {
635         const UChar* currentCharacterPosition = iterator.characters();
636         const SimpleFontData* currentFontData = nextFontData;
637         UScriptCode currentScript = nextScript;
638
639         UChar32 lastCharacter = character;
640         for (iterator.advance(clusterLength); iterator.consume(character, clusterLength); iterator.advance(clusterLength)) {
641             if (Character::treatAsZeroWidthSpace(character))
642                 continue;
643
644             int length = handleMultipleUChar(character, clusterLength, currentFontData, currentCharacterPosition, iterator.characters() + clusterLength, normalizedBufferEnd);
645             if (length) {
646                 clusterLength = length;
647                 continue;
648             }
649
650             nextFontData = font->glyphDataForCharacter(character, false).fontData;
651             nextScript = uscript_getScript(character, &errorCode);
652             if (U_FAILURE(errorCode))
653                 return false;
654             if (lastCharacter == zeroWidthJoiner)
655                 currentFontData = nextFontData;
656             if ((nextFontData != currentFontData) || ((currentScript != nextScript) && (nextScript != USCRIPT_INHERITED) && (!uscript_hasScript(character, currentScript))))
657                 break;
658             currentCharacterPosition = iterator.characters();
659             lastCharacter = character;
660         }
661
662         CandidateRun run = { character, startIndexOfCurrentRun, iterator.currentCharacter(), currentFontData, currentScript };
663         runs->append(run);
664
665         startIndexOfCurrentRun = iterator.currentCharacter();
666     } while (iterator.consume(character, clusterLength));
667
668     return true;
669 }
670
671 static inline bool matchesAdjacentRun(UScriptCode* scriptExtensions, int length,
672     CandidateRun& adjacentRun)
673 {
674     for (int i = 0; i < length; i++) {
675         if (scriptExtensions[i] == adjacentRun.script)
676             return true;
677     }
678     return false;
679 }
680
681 static inline void resolveRunBasedOnScriptExtensions(Vector<CandidateRun>& runs,
682     CandidateRun& run, size_t i, size_t length, UScriptCode* scriptExtensions,
683     int extensionsLength, size_t& nextResolvedRun)
684 {
685     // If uscript_getScriptExtensions returns 1 it only contains the script value,
686     // we only care about ScriptExtensions which is indicated by a value >= 2.
687     if (extensionsLength <= 1)
688         return;
689
690     if (i > 0 && matchesAdjacentRun(scriptExtensions, extensionsLength, runs[i - 1])) {
691         run.script = runs[i - 1].script;
692         return;
693     }
694
695     for (size_t j = i + 1; j < length; j++) {
696         if (runs[j].script != USCRIPT_COMMON
697             && runs[j].script != USCRIPT_INHERITED
698             && matchesAdjacentRun(scriptExtensions, extensionsLength, runs[j])) {
699             nextResolvedRun = j;
700             break;
701         }
702     }
703 }
704
705 static inline void resolveRunBasedOnScriptValue(Vector<CandidateRun>& runs,
706     CandidateRun& run, size_t i, size_t length, size_t& nextResolvedRun)
707 {
708     if (run.script != USCRIPT_COMMON)
709         return;
710
711     if (i > 0 && runs[i - 1].script != USCRIPT_COMMON) {
712         run.script = runs[i - 1].script;
713         return;
714     }
715
716     for (size_t j = i + 1; j < length; j++) {
717         if (runs[j].script != USCRIPT_COMMON
718             && runs[j].script != USCRIPT_INHERITED) {
719             nextResolvedRun = j;
720             break;
721         }
722     }
723 }
724
725 static inline bool resolveCandidateRuns(Vector<CandidateRun>& runs)
726 {
727     UScriptCode scriptExtensions[8];
728     UErrorCode errorCode = U_ZERO_ERROR;
729     size_t length = runs.size();
730     size_t nextResolvedRun = 0;
731     for (size_t i = 0; i < length; i++) {
732         CandidateRun& run = runs[i];
733         nextResolvedRun = 0;
734
735         if (run.script == USCRIPT_INHERITED)
736             run.script = i > 0 ? runs[i - 1].script : USCRIPT_COMMON;
737
738         int extensionsLength = uscript_getScriptExtensions(run.character,
739             scriptExtensions, sizeof(scriptExtensions), &errorCode);
740         if (U_FAILURE(errorCode))
741             return false;
742
743         resolveRunBasedOnScriptExtensions(runs, run, i, length,
744             scriptExtensions, extensionsLength, nextResolvedRun);
745         resolveRunBasedOnScriptValue(runs, run, i, length,
746             nextResolvedRun);
747         for (size_t j = i; j < nextResolvedRun; j++)
748             runs[j].script = runs[nextResolvedRun].script;
749
750         i = std::max(i, nextResolvedRun);
751     }
752     return true;
753 }
754
755 bool HarfBuzzShaper::createHarfBuzzRuns()
756 {
757     Vector<CandidateRun> candidateRuns;
758     if (!collectCandidateRuns(m_normalizedBuffer.get(),
759         m_normalizedBufferLength, m_font, &candidateRuns))
760         return false;
761
762     if (!resolveCandidateRuns(candidateRuns))
763         return false;
764
765     size_t length = candidateRuns.size();
766     for (size_t i = 0; i < length; ) {
767         CandidateRun& run = candidateRuns[i];
768         CandidateRun lastMatchingRun = run;
769         for (i++; i < length; i++) {
770             if (candidateRuns[i].script != run.script
771                 || candidateRuns[i].fontData != run.fontData)
772                 break;
773             lastMatchingRun = candidateRuns[i];
774         }
775         addHarfBuzzRun(run.start, lastMatchingRun.end, run.fontData, run.script);
776     }
777     return !m_harfBuzzRuns.isEmpty();
778 }
779
780 // A port of hb_icu_script_to_script because harfbuzz on CrOS is built
781 // without hb-icu. See http://crbug.com/356929
782 static inline hb_script_t ICUScriptToHBScript(UScriptCode script)
783 {
784     if (UNLIKELY(script == USCRIPT_INVALID_CODE))
785         return HB_SCRIPT_INVALID;
786
787     return hb_script_from_string(uscript_getShortName(script), -1);
788 }
789
790
791 void HarfBuzzShaper::addHarfBuzzRun(unsigned startCharacter,
792     unsigned endCharacter, const SimpleFontData* fontData,
793     UScriptCode script)
794 {
795     ASSERT(endCharacter > startCharacter);
796     ASSERT(script != USCRIPT_INVALID_CODE);
797     return m_harfBuzzRuns.append(HarfBuzzRun::create(fontData,
798         startCharacter, endCharacter - startCharacter,
799         m_run.direction(), ICUScriptToHBScript(script)));
800 }
801
802 static const uint16_t* toUint16(const UChar* src)
803 {
804     // FIXME: This relies on undefined behavior however it works on the
805     // current versions of all compilers we care about and avoids making
806     // a copy of the string.
807     COMPILE_ASSERT(sizeof(UChar) == sizeof(uint16_t), UChar_is_the_same_size_as_uint16_t);
808     return reinterpret_cast<const uint16_t*>(src);
809 }
810
811 bool HarfBuzzShaper::shapeHarfBuzzRuns()
812 {
813     HarfBuzzScopedPtr<hb_buffer_t> harfBuzzBuffer(hb_buffer_create(), hb_buffer_destroy);
814
815     HarfBuzzRunCache& runCache = harfBuzzRunCache();
816     const FontDescription& fontDescription = m_font->fontDescription();
817     const String& localeString = fontDescription.locale();
818     CString locale = localeString.latin1();
819
820     for (unsigned i = 0; i < m_harfBuzzRuns.size(); ++i) {
821         unsigned runIndex = m_run.rtl() ? m_harfBuzzRuns.size() - i - 1 : i;
822         HarfBuzzRun* currentRun = m_harfBuzzRuns[runIndex].get();
823         const SimpleFontData* currentFontData = currentRun->fontData();
824         if (currentFontData->isSVGFont())
825             return false;
826
827         FontPlatformData* platformData = const_cast<FontPlatformData*>(&currentFontData->platformData());
828         HarfBuzzFace* face = platformData->harfBuzzFace();
829         if (!face)
830             return false;
831
832         hb_buffer_set_language(harfBuzzBuffer.get(), hb_language_from_string(locale.data(), locale.length()));
833         hb_buffer_set_script(harfBuzzBuffer.get(), currentRun->script());
834         hb_buffer_set_direction(harfBuzzBuffer.get(), currentRun->rtl() ? HB_DIRECTION_RTL : HB_DIRECTION_LTR);
835
836         hb_segment_properties_t props;
837         hb_buffer_get_segment_properties(harfBuzzBuffer.get(), &props);
838
839         const UChar* src = m_normalizedBuffer.get() + currentRun->startIndex();
840         std::wstring key(src, src + currentRun->numCharacters());
841
842         CachedShapingResults* cachedResults = runCache.find(key);
843         if (cachedResults) {
844             if (cachedResults->dir == props.direction && cachedResults->font == *m_font && cachedResults->locale == localeString) {
845                 currentRun->applyShapeResult(cachedResults->buffer);
846                 setGlyphPositionsForHarfBuzzRun(currentRun, cachedResults->buffer);
847
848                 hb_buffer_clear_contents(harfBuzzBuffer.get());
849
850                 runCache.moveToBack(cachedResults);
851
852                 continue;
853             }
854
855             runCache.remove(cachedResults);
856         }
857
858         // Add a space as pre-context to the buffer. This prevents showing dotted-circle
859         // for combining marks at the beginning of runs.
860         static const uint16_t preContext = ' ';
861         hb_buffer_add_utf16(harfBuzzBuffer.get(), &preContext, 1, 1, 0);
862
863         if (fontDescription.variant() == FontVariantSmallCaps && u_islower(m_normalizedBuffer[currentRun->startIndex()])) {
864             String upperText = String(m_normalizedBuffer.get() + currentRun->startIndex(), currentRun->numCharacters()).upper();
865             ASSERT(!upperText.is8Bit()); // m_normalizedBuffer is 16 bit, therefore upperText is 16 bit, even after we call makeUpper().
866             hb_buffer_add_utf16(harfBuzzBuffer.get(), toUint16(upperText.characters16()), currentRun->numCharacters(), 0, currentRun->numCharacters());
867         } else {
868             hb_buffer_add_utf16(harfBuzzBuffer.get(), toUint16(m_normalizedBuffer.get() + currentRun->startIndex()), currentRun->numCharacters(), 0, currentRun->numCharacters());
869         }
870
871         if (fontDescription.orientation() == Vertical)
872             face->setScriptForVerticalGlyphSubstitution(harfBuzzBuffer.get());
873
874         HarfBuzzScopedPtr<hb_font_t> harfBuzzFont(face->createFont(), hb_font_destroy);
875
876         hb_shape(harfBuzzFont.get(), harfBuzzBuffer.get(), m_features.isEmpty() ? 0 : m_features.data(), m_features.size());
877         currentRun->applyShapeResult(harfBuzzBuffer.get());
878         setGlyphPositionsForHarfBuzzRun(currentRun, harfBuzzBuffer.get());
879
880         runCache.insert(key, new CachedShapingResults(harfBuzzBuffer.get(), m_font, props.direction, localeString));
881
882         harfBuzzBuffer.set(hb_buffer_create());
883     }
884
885     return true;
886 }
887
888 void HarfBuzzShaper::setGlyphPositionsForHarfBuzzRun(HarfBuzzRun* currentRun, hb_buffer_t* harfBuzzBuffer)
889 {
890     const SimpleFontData* currentFontData = currentRun->fontData();
891     hb_glyph_info_t* glyphInfos = hb_buffer_get_glyph_infos(harfBuzzBuffer, 0);
892     hb_glyph_position_t* glyphPositions = hb_buffer_get_glyph_positions(harfBuzzBuffer, 0);
893
894     if (!currentRun->hasGlyphToCharacterIndexes()) {
895         // FIXME: https://crbug.com/337886
896         ASSERT_NOT_REACHED();
897         return;
898     }
899
900     unsigned numGlyphs = currentRun->numGlyphs();
901     uint16_t* glyphToCharacterIndexes = currentRun->glyphToCharacterIndexes();
902     float totalAdvance = 0;
903     FloatPoint glyphOrigin;
904
905     // HarfBuzz returns the shaping result in visual order. We need not to flip for RTL.
906     for (size_t i = 0; i < numGlyphs; ++i) {
907         bool runEnd = i + 1 == numGlyphs;
908         uint16_t glyph = glyphInfos[i].codepoint;
909         float offsetX = harfBuzzPositionToFloat(glyphPositions[i].x_offset);
910         float offsetY = -harfBuzzPositionToFloat(glyphPositions[i].y_offset);
911         float advance = harfBuzzPositionToFloat(glyphPositions[i].x_advance);
912
913         unsigned currentCharacterIndex = currentRun->startIndex() + glyphInfos[i].cluster;
914         bool isClusterEnd = runEnd || glyphInfos[i].cluster != glyphInfos[i + 1].cluster;
915         float spacing = 0;
916
917         glyphToCharacterIndexes[i] = glyphInfos[i].cluster;
918
919         if (isClusterEnd && !Character::treatAsZeroWidthSpace(m_normalizedBuffer[currentCharacterIndex]))
920             spacing += m_letterSpacing;
921
922         if (isClusterEnd && isWordEnd(currentCharacterIndex))
923             spacing += determineWordBreakSpacing();
924
925         if (currentFontData->isZeroWidthSpaceGlyph(glyph)) {
926             currentRun->setGlyphAndPositions(i, glyph, 0, 0, 0);
927             continue;
928         }
929
930         advance += spacing;
931         if (m_run.rtl()) {
932             // In RTL, spacing should be added to left side of glyphs.
933             offsetX += spacing;
934             if (!isClusterEnd)
935                 offsetX += m_letterSpacing;
936         }
937
938         currentRun->setGlyphAndPositions(i, glyph, advance, offsetX, offsetY);
939
940         FloatRect glyphBounds = currentFontData->boundsForGlyph(glyph);
941         glyphBounds.move(glyphOrigin.x(), glyphOrigin.y());
942         m_glyphBoundingBox.unite(glyphBounds);
943         glyphOrigin += FloatSize(advance + offsetX, offsetY);
944
945         totalAdvance += advance;
946     }
947     currentRun->setWidth(totalAdvance > 0.0 ? totalAdvance : 0.0);
948     m_totalWidth += currentRun->width();
949 }
950
951 void HarfBuzzShaper::fillGlyphBufferFromHarfBuzzRun(GlyphBuffer* glyphBuffer, HarfBuzzRun* currentRun, FloatPoint& firstOffsetOfNextRun)
952 {
953     FloatPoint* offsets = currentRun->offsets();
954     uint16_t* glyphs = currentRun->glyphs();
955     float* advances = currentRun->advances();
956     unsigned numGlyphs = currentRun->numGlyphs();
957     uint16_t* glyphToCharacterIndexes = currentRun->glyphToCharacterIndexes();
958     for (unsigned i = 0; i < numGlyphs; ++i) {
959         uint16_t currentCharacterIndex = currentRun->startIndex() + glyphToCharacterIndexes[i];
960         FloatPoint& currentOffset = offsets[i];
961         FloatPoint& nextOffset = (i == numGlyphs - 1) ? firstOffsetOfNextRun : offsets[i + 1];
962         float glyphAdvanceX = advances[i] + nextOffset.x() - currentOffset.x();
963         float glyphAdvanceY = nextOffset.y() - currentOffset.y();
964         if (m_run.rtl()) {
965             if (currentCharacterIndex >= m_toIndex)
966                 m_startOffset.move(glyphAdvanceX, glyphAdvanceY);
967             else if (currentCharacterIndex >= m_fromIndex)
968                 glyphBuffer->add(glyphs[i], currentRun->fontData(), FloatSize(glyphAdvanceX, glyphAdvanceY));
969         } else {
970             if (currentCharacterIndex < m_fromIndex)
971                 m_startOffset.move(glyphAdvanceX, glyphAdvanceY);
972             else if (currentCharacterIndex < m_toIndex)
973                 glyphBuffer->add(glyphs[i], currentRun->fontData(), FloatSize(glyphAdvanceX, glyphAdvanceY));
974         }
975     }
976 }
977
978 void HarfBuzzShaper::fillGlyphBufferForTextEmphasis(GlyphBuffer* glyphBuffer, HarfBuzzRun* currentRun)
979 {
980     // FIXME: Instead of generating a synthetic GlyphBuffer here which is then used by the
981     // drawEmphasisMarks method of FontFastPath, we should roll our own emphasis mark drawing function.
982
983     float* advances = currentRun->advances();
984     unsigned numGlyphs = currentRun->numGlyphs();
985     uint16_t* glyphToCharacterIndexes = currentRun->glyphToCharacterIndexes();
986     unsigned graphemesInCluster = 1;
987     float clusterAdvance = 0;
988     uint16_t clusterStart;
989
990     // A "cluster" in this context means a cluster as it is used by HarfBuzz:
991     // The minimal group of characters and corresponding glyphs, that cannot be broken
992     // down further from a text shaping point of view.
993     // A cluster can contain multiple glyphs and grapheme clusters, with mutually
994     // overlapping boundaries. Below we count grapheme clusters per HarfBuzz clusters,
995     // then linearly split the sum of corresponding glyph advances by the number of
996     // grapheme clusters in order to find positions for emphasis mark drawing.
997
998     if (m_run.rtl())
999         clusterStart = currentRun->startIndex() + currentRun->numCharacters();
1000     else
1001         clusterStart = currentRun->startIndex() + glyphToCharacterIndexes[0];
1002
1003     for (unsigned i = 0; i < numGlyphs; ++i) {
1004         uint16_t currentCharacterIndex = currentRun->startIndex() + glyphToCharacterIndexes[i];
1005         bool isRunEnd = (i + 1 == numGlyphs);
1006         bool isClusterEnd =  isRunEnd || (currentRun->startIndex() + glyphToCharacterIndexes[i + 1] != currentCharacterIndex);
1007         clusterAdvance += advances[i];
1008
1009         if (isClusterEnd) {
1010             uint16_t clusterEnd;
1011             if (m_run.rtl())
1012                 clusterEnd = currentCharacterIndex;
1013             else
1014                 clusterEnd = isRunEnd ? currentRun->startIndex() + currentRun->numCharacters() : currentRun->startIndex() + glyphToCharacterIndexes[i + 1];
1015
1016             graphemesInCluster = countGraphemesInCluster(m_normalizedBuffer.get(), m_normalizedBufferLength, clusterStart, clusterEnd);
1017             if (!graphemesInCluster || !clusterAdvance)
1018                 continue;
1019
1020             float glyphAdvanceX = clusterAdvance / graphemesInCluster;
1021             for (unsigned j = 0; j < graphemesInCluster; ++j) {
1022                 // Do not put emphasis marks on space, separator, and control characters.
1023                 Glyph glyphToAdd = Character::canReceiveTextEmphasis(m_run[currentCharacterIndex]) ? 1 : 0;
1024                 glyphBuffer->add(glyphToAdd, currentRun->fontData(), glyphAdvanceX);
1025             }
1026             clusterStart = clusterEnd;
1027             clusterAdvance = 0;
1028         }
1029     }
1030 }
1031
1032 bool HarfBuzzShaper::fillGlyphBuffer(GlyphBuffer* glyphBuffer)
1033 {
1034     unsigned numRuns = m_harfBuzzRuns.size();
1035     if (m_run.rtl()) {
1036         m_startOffset = m_harfBuzzRuns.last()->offsets()[0];
1037         for (int runIndex = numRuns - 1; runIndex >= 0; --runIndex) {
1038             HarfBuzzRun* currentRun = m_harfBuzzRuns[runIndex].get();
1039             if (!currentRun->hasGlyphToCharacterIndexes()) {
1040                 // FIXME: bug 337886, 359664
1041                 continue;
1042             }
1043             FloatPoint firstOffsetOfNextRun = !runIndex ? FloatPoint() : m_harfBuzzRuns[runIndex - 1]->offsets()[0];
1044             if (m_forTextEmphasis == ForTextEmphasis)
1045                 fillGlyphBufferForTextEmphasis(glyphBuffer, currentRun);
1046             else
1047                 fillGlyphBufferFromHarfBuzzRun(glyphBuffer, currentRun, firstOffsetOfNextRun);
1048         }
1049     } else {
1050         m_startOffset = m_harfBuzzRuns.first()->offsets()[0];
1051         for (unsigned runIndex = 0; runIndex < numRuns; ++runIndex) {
1052             HarfBuzzRun* currentRun = m_harfBuzzRuns[runIndex].get();
1053             if (!currentRun->hasGlyphToCharacterIndexes()) {
1054                 // FIXME: bug 337886, 359664
1055                 continue;
1056             }
1057             FloatPoint firstOffsetOfNextRun = runIndex == numRuns - 1 ? FloatPoint() : m_harfBuzzRuns[runIndex + 1]->offsets()[0];
1058             if (m_forTextEmphasis == ForTextEmphasis)
1059                 fillGlyphBufferForTextEmphasis(glyphBuffer, currentRun);
1060             else
1061                 fillGlyphBufferFromHarfBuzzRun(glyphBuffer, currentRun, firstOffsetOfNextRun);
1062         }
1063     }
1064     return glyphBuffer->size();
1065 }
1066
1067 int HarfBuzzShaper::offsetForPosition(float targetX)
1068 {
1069     int charactersSoFar = 0;
1070     float currentX = 0;
1071
1072     if (m_run.rtl()) {
1073         charactersSoFar = m_normalizedBufferLength;
1074         for (int i = m_harfBuzzRuns.size() - 1; i >= 0; --i) {
1075             charactersSoFar -= m_harfBuzzRuns[i]->numCharacters();
1076             float nextX = currentX + m_harfBuzzRuns[i]->width();
1077             float offsetForRun = targetX - currentX;
1078             if (offsetForRun >= 0 && offsetForRun <= m_harfBuzzRuns[i]->width()) {
1079                 // The x value in question is within this script run.
1080                 const unsigned index = m_harfBuzzRuns[i]->characterIndexForXPosition(offsetForRun);
1081                 return charactersSoFar + index;
1082             }
1083             currentX = nextX;
1084         }
1085     } else {
1086         for (unsigned i = 0; i < m_harfBuzzRuns.size(); ++i) {
1087             float nextX = currentX + m_harfBuzzRuns[i]->width();
1088             float offsetForRun = targetX - currentX;
1089             if (offsetForRun >= 0 && offsetForRun <= m_harfBuzzRuns[i]->width()) {
1090                 const unsigned index = m_harfBuzzRuns[i]->characterIndexForXPosition(offsetForRun);
1091                 return charactersSoFar + index;
1092             }
1093             charactersSoFar += m_harfBuzzRuns[i]->numCharacters();
1094             currentX = nextX;
1095         }
1096     }
1097
1098     return charactersSoFar;
1099 }
1100
1101 FloatRect HarfBuzzShaper::selectionRect(const FloatPoint& point, int height, int from, int to)
1102 {
1103     float currentX = 0;
1104     float fromX = 0;
1105     float toX = 0;
1106     bool foundFromX = false;
1107     bool foundToX = false;
1108
1109     if (m_run.rtl())
1110         currentX = m_totalWidth;
1111     for (unsigned i = 0; i < m_harfBuzzRuns.size(); ++i) {
1112         if (m_run.rtl())
1113             currentX -= m_harfBuzzRuns[i]->width();
1114         int numCharacters = m_harfBuzzRuns[i]->numCharacters();
1115         if (!foundFromX && from >= 0 && from < numCharacters) {
1116             fromX = m_harfBuzzRuns[i]->xPositionForOffset(from) + currentX;
1117             foundFromX = true;
1118         } else
1119             from -= numCharacters;
1120
1121         if (!foundToX && to >= 0 && to < numCharacters) {
1122             toX = m_harfBuzzRuns[i]->xPositionForOffset(to) + currentX;
1123             foundToX = true;
1124         } else
1125             to -= numCharacters;
1126
1127         if (foundFromX && foundToX)
1128             break;
1129         if (!m_run.rtl())
1130             currentX += m_harfBuzzRuns[i]->width();
1131     }
1132
1133     // The position in question might be just after the text.
1134     if (!foundFromX)
1135         fromX = 0;
1136     if (!foundToX)
1137         toX = m_run.rtl() ? 0 : m_totalWidth;
1138
1139     if (fromX < toX) {
1140         return Font::pixelSnappedSelectionRect(
1141             point.x() + fromX, point.x() + toX,
1142             point.y(), height);
1143     }
1144
1145     return Font::pixelSnappedSelectionRect(
1146         point.x() + toX, point.x() + fromX,
1147         point.y(), height);
1148 }
1149
1150 } // namespace blink