1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "ui/gfx/render_text_harfbuzz.h"
10 #include "base/i18n/bidi_line_iterator.h"
11 #include "base/i18n/break_iterator.h"
12 #include "base/i18n/char_iterator.h"
13 #include "base/profiler/scoped_tracker.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/trace_event/trace_event.h"
17 #include "third_party/harfbuzz-ng/src/hb.h"
18 #include "third_party/icu/source/common/unicode/ubidi.h"
19 #include "third_party/icu/source/common/unicode/utf16.h"
20 #include "third_party/skia/include/core/SkColor.h"
21 #include "third_party/skia/include/core/SkTypeface.h"
22 #include "ui/gfx/canvas.h"
23 #include "ui/gfx/font_fallback.h"
24 #include "ui/gfx/font_render_params.h"
25 #include "ui/gfx/geometry/safe_integer_conversions.h"
26 #include "ui/gfx/harfbuzz_font_skia.h"
27 #include "ui/gfx/range/range_f.h"
28 #include "ui/gfx/text_utils.h"
29 #include "ui/gfx/utf16_indexing.h"
32 #include "ui/gfx/font_fallback_win.h"
39 // Text length limit. Longer strings are slow and not fully tested.
40 const size_t kMaxTextLength
= 10000;
42 // The maximum number of scripts a Unicode character can belong to. This value
43 // is arbitrarily chosen to be a good limit because it is unlikely for a single
44 // character to belong to more scripts.
45 const size_t kMaxScripts
= 5;
47 // Returns true if characters of |block_code| may trigger font fallback.
48 // Dingbats and emoticons can be rendered through the color emoji font file,
49 // therefore it needs to be trigerred as fallbacks. See crbug.com/448909
50 bool IsUnusualBlockCode(UBlockCode block_code
) {
51 return block_code
== UBLOCK_GEOMETRIC_SHAPES
||
52 block_code
== UBLOCK_MISCELLANEOUS_SYMBOLS
;
55 bool IsBracket(UChar32 character
) {
56 static const char kBrackets
[] = { '(', ')', '{', '}', '<', '>', };
57 static const char* kBracketsEnd
= kBrackets
+ arraysize(kBrackets
);
58 return std::find(kBrackets
, kBracketsEnd
, character
) != kBracketsEnd
;
61 // Returns the boundary between a special and a regular character. Special
62 // characters are brackets or characters that satisfy |IsUnusualBlockCode|.
63 size_t FindRunBreakingCharacter(const base::string16
& text
,
66 const int32 run_length
= static_cast<int32
>(run_break
- run_start
);
67 base::i18n::UTF16CharIterator
iter(text
.c_str() + run_start
, run_length
);
68 const UChar32 first_char
= iter
.get();
69 // The newline character should form a single run so that the line breaker
70 // can handle them easily.
71 if (first_char
== '\n')
74 const UBlockCode first_block
= ublock_getCode(first_char
);
75 const bool first_block_unusual
= IsUnusualBlockCode(first_block
);
76 const bool first_bracket
= IsBracket(first_char
);
78 while (iter
.Advance() && iter
.array_pos() < run_length
) {
79 const UChar32 current_char
= iter
.get();
80 const UBlockCode current_block
= ublock_getCode(current_char
);
81 const bool block_break
= current_block
!= first_block
&&
82 (first_block_unusual
|| IsUnusualBlockCode(current_block
));
83 if (block_break
|| current_char
== '\n' ||
84 first_bracket
!= IsBracket(current_char
)) {
85 return run_start
+ iter
.array_pos();
91 // If the given scripts match, returns the one that isn't USCRIPT_INHERITED,
92 // i.e. the more specific one. Otherwise returns USCRIPT_INVALID_CODE.
93 UScriptCode
ScriptIntersect(UScriptCode first
, UScriptCode second
) {
94 if (first
== second
|| second
== USCRIPT_INHERITED
)
96 if (first
== USCRIPT_INHERITED
)
98 return USCRIPT_INVALID_CODE
;
101 // Writes the script and the script extensions of the character with the
102 // Unicode |codepoint|. Returns the number of written scripts.
103 int GetScriptExtensions(UChar32 codepoint
, UScriptCode
* scripts
) {
104 UErrorCode icu_error
= U_ZERO_ERROR
;
105 // ICU documentation incorrectly states that the result of
106 // |uscript_getScriptExtensions| will contain the regular script property.
107 // Write the character's script property to the first element.
108 scripts
[0] = uscript_getScript(codepoint
, &icu_error
);
109 if (U_FAILURE(icu_error
))
111 // Fill the rest of |scripts| with the extensions.
112 int count
= uscript_getScriptExtensions(codepoint
, scripts
+ 1,
113 kMaxScripts
- 1, &icu_error
);
114 if (U_FAILURE(icu_error
))
119 // Intersects the script extensions set of |codepoint| with |result| and writes
120 // to |result|, reading and updating |result_size|.
121 void ScriptSetIntersect(UChar32 codepoint
,
123 size_t* result_size
) {
124 UScriptCode scripts
[kMaxScripts
] = { USCRIPT_INVALID_CODE
};
125 int count
= GetScriptExtensions(codepoint
, scripts
);
129 for (size_t i
= 0; i
< *result_size
; ++i
) {
130 for (int j
= 0; j
< count
; ++j
) {
131 UScriptCode intersection
= ScriptIntersect(result
[i
], scripts
[j
]);
132 if (intersection
!= USCRIPT_INVALID_CODE
) {
133 result
[out_size
++] = intersection
;
139 *result_size
= out_size
;
142 // Find the longest sequence of characters from 0 and up to |length| that
143 // have at least one common UScriptCode value. Writes the common script value to
144 // |script| and returns the length of the sequence. Takes the characters' script
145 // extensions into account. http://www.unicode.org/reports/tr24/#ScriptX
147 // Consider 3 characters with the script values {Kana}, {Hira, Kana}, {Kana}.
148 // Without script extensions only the first script in each set would be taken
149 // into account, resulting in 3 runs where 1 would be enough.
150 // TODO(ckocagil): Write a unit test for the case above.
151 int ScriptInterval(const base::string16
& text
,
154 UScriptCode
* script
) {
155 DCHECK_GT(length
, 0U);
157 UScriptCode scripts
[kMaxScripts
] = { USCRIPT_INVALID_CODE
};
159 base::i18n::UTF16CharIterator
char_iterator(text
.c_str() + start
, length
);
160 size_t scripts_size
= GetScriptExtensions(char_iterator
.get(), scripts
);
161 *script
= scripts
[0];
163 while (char_iterator
.Advance()) {
164 // Special handling to merge white space into the previous run.
165 if (u_isUWhiteSpace(char_iterator
.get()))
167 ScriptSetIntersect(char_iterator
.get(), scripts
, &scripts_size
);
168 if (scripts_size
== 0U)
169 return char_iterator
.array_pos();
170 *script
= scripts
[0];
176 // A port of hb_icu_script_to_script because harfbuzz on CrOS is built without
177 // hb-icu. See http://crbug.com/356929
178 inline hb_script_t
ICUScriptToHBScript(UScriptCode script
) {
179 if (script
== USCRIPT_INVALID_CODE
)
180 return HB_SCRIPT_INVALID
;
181 return hb_script_from_string(uscript_getShortName(script
), -1);
184 // Helper template function for |TextRunHarfBuzz::GetClusterAt()|. |Iterator|
185 // can be a forward or reverse iterator type depending on the text direction.
186 template <class Iterator
>
187 void GetClusterAtImpl(size_t pos
,
189 Iterator elements_begin
,
190 Iterator elements_end
,
194 Iterator element
= std::upper_bound(elements_begin
, elements_end
, pos
);
195 chars
->set_end(element
== elements_end
? range
.end() : *element
);
196 glyphs
->set_end(reversed
? elements_end
- element
: element
- elements_begin
);
198 DCHECK(element
!= elements_begin
);
199 while (--element
!= elements_begin
&& *element
== *(element
- 1));
200 chars
->set_start(*element
);
202 reversed
? elements_end
- element
: element
- elements_begin
);
204 *glyphs
= Range(glyphs
->end(), glyphs
->start());
206 DCHECK(!chars
->is_reversed());
207 DCHECK(!chars
->is_empty());
208 DCHECK(!glyphs
->is_reversed());
209 DCHECK(!glyphs
->is_empty());
212 // Internal class to generate Line structures. If |multiline| is true, the text
213 // is broken into lines at |words| boundaries such that each line is no longer
214 // than |max_width|. If |multiline| is false, only outputs a single Line from
215 // the given runs. |min_baseline| and |min_height| are the minimum baseline and
216 // height for each line.
217 // TODO(ckocagil): Expose the interface of this class in the header and test
218 // this class directly.
219 class HarfBuzzLineBreaker
{
221 HarfBuzzLineBreaker(size_t max_width
,
224 WordWrapBehavior word_wrap_behavior
,
225 const base::string16
& text
,
226 const BreakList
<size_t>* words
,
227 const internal::TextRunList
& run_list
)
228 : max_width_((max_width
== 0) ? SK_ScalarMax
: SkIntToScalar(max_width
)),
229 min_baseline_(min_baseline
),
230 min_height_(min_height
),
231 word_wrap_behavior_(word_wrap_behavior
),
238 available_width_(max_width_
) {
242 // Constructs a single line for |text_| using |run_list_|.
243 void ConstructSingleLine() {
244 for (size_t i
= 0; i
< run_list_
.size(); i
++) {
245 const internal::TextRunHarfBuzz
& run
= *(run_list_
.runs()[i
]);
246 internal::LineSegment segment
;
248 segment
.char_range
= run
.range
;
249 segment
.x_range
= RangeF(SkScalarToFloat(text_x_
),
250 SkScalarToFloat(text_x_
) + run
.width
);
251 AddLineSegment(segment
);
255 // Constructs multiple lines for |text_| based on words iteration approach.
256 void ConstructMultiLines() {
258 for (auto iter
= words_
->breaks().begin(); iter
!= words_
->breaks().end();
260 const Range word_range
= words_
->GetRange(iter
);
261 std::vector
<internal::LineSegment
> word_segments
;
262 SkScalar word_width
= GetWordWidth(word_range
, &word_segments
);
264 // If the last word is '\n', we should advance a new line after adding
265 // the word to the current line.
266 bool new_line
= false;
267 if (!word_segments
.empty() &&
268 text_
[word_segments
.back().char_range
.start()] == '\n') {
270 word_width
-= word_segments
.back().width();
271 word_segments
.pop_back();
274 // If the word is not the first word in the line and it can't fit into
275 // the current line, advance a new line.
276 if (word_width
> available_width_
&& available_width_
!= max_width_
)
278 if (!word_segments
.empty())
279 AddWordToLine(word_segments
);
285 // Finishes line breaking and outputs the results. Can be called at most once.
286 void FinalizeLines(std::vector
<internal::Line
>* lines
, SizeF
* size
) {
287 DCHECK(!lines_
.empty());
288 // Add an empty line to finish the line size calculation and remove it.
296 // A (line index, segment index) pair that specifies a segment in |lines_|.
297 typedef std::pair
<size_t, size_t> SegmentHandle
;
299 internal::LineSegment
* SegmentFromHandle(const SegmentHandle
& handle
) {
300 return &lines_
[handle
.first
].segments
[handle
.second
];
303 // Finishes the size calculations of the last Line in |lines_|. Adds a new
304 // Line to the back of |lines_|.
306 if (!lines_
.empty()) {
307 internal::Line
* line
= &lines_
.back();
308 std::sort(line
->segments
.begin(), line
->segments
.end(),
309 [this](const internal::LineSegment
& s1
,
310 const internal::LineSegment
& s2
) -> bool {
311 return run_list_
.logical_to_visual(s1
.run
) <
312 run_list_
.logical_to_visual(s2
.run
);
314 line
->size
.set_height(std::max(min_height_
, max_descent_
+ max_ascent_
));
315 line
->baseline
= std::max(min_baseline_
, SkScalarRoundToInt(max_ascent_
));
316 line
->preceding_heights
= std::ceil(total_size_
.height());
317 total_size_
.set_height(total_size_
.height() + line
->size
.height());
318 total_size_
.set_width(std::max(total_size_
.width(), line
->size
.width()));
322 available_width_
= max_width_
;
323 lines_
.push_back(internal::Line());
326 // Adds word to the current line. A word may contain multiple segments. If the
327 // word is the first word in line and its width exceeds |available_width_|,
328 // ignore/truncate/wrap it according to |word_wrap_behavior_|.
329 void AddWordToLine(const std::vector
<internal::LineSegment
>& word_segments
) {
330 DCHECK(!lines_
.empty());
331 DCHECK(!word_segments
.empty());
333 bool has_truncated
= false;
334 for (const internal::LineSegment
& segment
: word_segments
) {
337 if (segment
.width() <= available_width_
||
338 word_wrap_behavior_
== IGNORE_LONG_WORDS
) {
339 AddLineSegment(segment
);
341 DCHECK(word_wrap_behavior_
== TRUNCATE_LONG_WORDS
||
342 word_wrap_behavior_
== WRAP_LONG_WORDS
);
343 has_truncated
= (word_wrap_behavior_
== TRUNCATE_LONG_WORDS
);
345 const internal::TextRunHarfBuzz
& run
= *(run_list_
.runs()[segment
.run
]);
346 internal::LineSegment remaining_segment
= segment
;
347 while (!remaining_segment
.char_range
.is_empty()) {
348 size_t cutoff_pos
= GetCutoffPos(remaining_segment
);
349 SkScalar width
= run
.GetGlyphWidthForCharRange(
350 Range(remaining_segment
.char_range
.start(), cutoff_pos
));
352 internal::LineSegment cut_segment
;
353 cut_segment
.run
= remaining_segment
.run
;
354 cut_segment
.char_range
=
355 Range(remaining_segment
.char_range
.start(), cutoff_pos
);
356 cut_segment
.x_range
= RangeF(SkScalarToFloat(text_x_
),
357 SkScalarToFloat(text_x_
+ width
));
358 AddLineSegment(cut_segment
);
359 // Updates old segment range.
360 remaining_segment
.char_range
.set_start(cutoff_pos
);
361 remaining_segment
.x_range
.set_start(SkScalarToFloat(text_x_
));
365 if (!remaining_segment
.char_range
.is_empty())
372 // Add a line segment to the current line. Note that, in order to keep the
373 // visual order correct for ltr and rtl language, we need to merge segments
374 // that belong to the same run.
375 void AddLineSegment(const internal::LineSegment
& segment
) {
376 DCHECK(!lines_
.empty());
377 internal::Line
* line
= &lines_
.back();
378 const internal::TextRunHarfBuzz
& run
= *(run_list_
.runs()[segment
.run
]);
379 if (!line
->segments
.empty()) {
380 internal::LineSegment
& last_segment
= line
->segments
.back();
381 // Merge segments that belong to the same run.
382 if (last_segment
.run
== segment
.run
) {
383 DCHECK_EQ(last_segment
.char_range
.end(), segment
.char_range
.start());
385 std::abs(last_segment
.x_range
.end() - segment
.x_range
.start()),
386 std::numeric_limits
<float>::epsilon());
387 last_segment
.char_range
.set_end(segment
.char_range
.end());
388 last_segment
.x_range
.set_end(SkScalarToFloat(text_x_
) +
390 if (run
.is_rtl
&& last_segment
.char_range
.end() == run
.range
.end())
391 UpdateRTLSegmentRanges();
392 line
->size
.set_width(line
->size
.width() + segment
.width());
393 text_x_
+= segment
.width();
394 available_width_
-= segment
.width();
398 line
->segments
.push_back(segment
);
401 paint
.setTypeface(run
.skia_face
.get());
402 paint
.setTextSize(SkIntToScalar(run
.font_size
));
403 paint
.setAntiAlias(run
.render_params
.antialiasing
);
404 SkPaint::FontMetrics metrics
;
405 paint
.getFontMetrics(&metrics
);
407 line
->size
.set_width(line
->size
.width() + segment
.width());
408 // TODO(dschuyler): Account for stylized baselines in string sizing.
409 max_descent_
= std::max(max_descent_
, metrics
.fDescent
);
410 // fAscent is always negative.
411 max_ascent_
= std::max(max_ascent_
, -metrics
.fAscent
);
414 rtl_segments_
.push_back(
415 SegmentHandle(lines_
.size() - 1, line
->segments
.size() - 1));
416 // If this is the last segment of an RTL run, reprocess the text-space x
417 // ranges of all segments from the run.
418 if (segment
.char_range
.end() == run
.range
.end())
419 UpdateRTLSegmentRanges();
421 text_x_
+= segment
.width();
422 available_width_
-= segment
.width();
425 // Finds the end position |end_pos| in |segment| where the preceding width is
426 // no larger than |available_width_|.
427 size_t GetCutoffPos(const internal::LineSegment
& segment
) const {
428 DCHECK(!segment
.char_range
.is_empty());
429 const internal::TextRunHarfBuzz
& run
= *(run_list_
.runs()[segment
.run
]);
430 size_t end_pos
= segment
.char_range
.start();
432 while (end_pos
< segment
.char_range
.end()) {
433 const SkScalar char_width
=
434 run
.GetGlyphWidthForCharRange(Range(end_pos
, end_pos
+ 1));
435 if (width
+ char_width
> available_width_
)
441 const size_t valid_end_pos
= FindValidBoundaryBefore(text_
, end_pos
);
442 if (end_pos
!= valid_end_pos
) {
443 end_pos
= valid_end_pos
;
444 width
= run
.GetGlyphWidthForCharRange(
445 Range(segment
.char_range
.start(), end_pos
));
448 // |max_width_| might be smaller than a single character. In this case we
449 // need to put at least one character in the line. Note that, we should
450 // not separate surrogate pair or combining characters.
451 // See RenderTextTest.Multiline_MinWidth for an example.
452 if (width
== 0 && available_width_
== max_width_
)
453 end_pos
= FindValidBoundaryAfter(text_
, end_pos
+ 1);
458 // Gets the glyph width for |word_range|, and splits the |word| into different
459 // segments based on its runs.
460 SkScalar
GetWordWidth(const Range
& word_range
,
461 std::vector
<internal::LineSegment
>* segments
) const {
463 if (word_range
.is_empty() || segments
== nullptr)
465 size_t run_start_index
= run_list_
.GetRunIndexAt(word_range
.start());
466 size_t run_end_index
= run_list_
.GetRunIndexAt(word_range
.end() - 1);
468 for (size_t i
= run_start_index
; i
<= run_end_index
; i
++) {
469 const internal::TextRunHarfBuzz
& run
= *(run_list_
.runs()[i
]);
470 const Range char_range
= run
.range
.Intersect(word_range
);
471 DCHECK(!char_range
.is_empty());
472 const SkScalar char_width
= run
.GetGlyphWidthForCharRange(char_range
);
475 internal::LineSegment segment
;
477 segment
.char_range
= char_range
;
478 segment
.x_range
= RangeF(SkScalarToFloat(text_x_
+ width
- char_width
),
479 SkScalarToFloat(text_x_
+ width
));
480 segments
->push_back(segment
);
485 // RTL runs are broken in logical order but displayed in visual order. To find
486 // the text-space coordinate (where it would fall in a single-line text)
487 // |x_range| of RTL segments, segment widths are applied in reverse order.
488 // e.g. {[5, 10], [10, 40]} will become {[35, 40], [5, 35]}.
489 void UpdateRTLSegmentRanges() {
490 if (rtl_segments_
.empty())
492 float x
= SegmentFromHandle(rtl_segments_
[0])->x_range
.start();
493 for (size_t i
= rtl_segments_
.size(); i
> 0; --i
) {
494 internal::LineSegment
* segment
= SegmentFromHandle(rtl_segments_
[i
- 1]);
495 const float segment_width
= segment
->width();
496 segment
->x_range
= RangeF(x
, x
+ segment_width
);
499 rtl_segments_
.clear();
502 const SkScalar max_width_
;
503 const int min_baseline_
;
504 const float min_height_
;
505 const WordWrapBehavior word_wrap_behavior_
;
506 const base::string16
& text_
;
507 const BreakList
<size_t>* const words_
;
508 const internal::TextRunList
& run_list_
;
510 // Stores the resulting lines.
511 std::vector
<internal::Line
> lines_
;
516 // Text space x coordinates of the next segment to be added.
518 // Stores available width in the current line.
519 SkScalar available_width_
;
521 // Size of the multiline text, not including the currently processed line.
524 // The current RTL run segments, to be applied by |UpdateRTLSegmentRanges()|.
525 std::vector
<SegmentHandle
> rtl_segments_
;
527 DISALLOW_COPY_AND_ASSIGN(HarfBuzzLineBreaker
);
530 // Function object for case insensitive string comparison.
531 struct CaseInsensitiveCompare
{
532 bool operator() (const std::string
& a
, const std::string
& b
) const {
533 return base::CompareCaseInsensitiveASCII(a
, b
) < 0;
541 TextRunHarfBuzz::TextRunHarfBuzz()
543 preceding_run_widths(0.0f
),
546 script(USCRIPT_INVALID_CODE
),
547 glyph_count(static_cast<size_t>(-1)),
553 diagonal_strike(false),
557 TextRunHarfBuzz::~TextRunHarfBuzz() {}
559 Range
TextRunHarfBuzz::CharRangeToGlyphRange(const Range
& char_range
) const {
560 DCHECK(range
.Contains(char_range
));
561 DCHECK(!char_range
.is_reversed());
562 DCHECK(!char_range
.is_empty());
567 GetClusterAt(char_range
.start(), &temp_range
, &start_glyphs
);
568 GetClusterAt(char_range
.end() - 1, &temp_range
, &end_glyphs
);
570 return is_rtl
? Range(end_glyphs
.start(), start_glyphs
.end()) :
571 Range(start_glyphs
.start(), end_glyphs
.end());
574 size_t TextRunHarfBuzz::CountMissingGlyphs() const {
575 static const int kMissingGlyphId
= 0;
577 for (size_t i
= 0; i
< glyph_count
; ++i
)
578 missing
+= (glyphs
[i
] == kMissingGlyphId
) ? 1 : 0;
582 void TextRunHarfBuzz::GetClusterAt(size_t pos
,
584 Range
* glyphs
) const {
585 DCHECK(range
.Contains(Range(pos
, pos
+ 1)));
589 if (glyph_count
== 0) {
596 GetClusterAtImpl(pos
, range
, glyph_to_char
.rbegin(), glyph_to_char
.rend(),
597 true, chars
, glyphs
);
601 GetClusterAtImpl(pos
, range
, glyph_to_char
.begin(), glyph_to_char
.end(),
602 false, chars
, glyphs
);
605 RangeF
TextRunHarfBuzz::GetGraphemeBounds(
606 base::i18n::BreakIterator
* grapheme_iterator
,
608 DCHECK_LT(text_index
, range
.end());
609 if (glyph_count
== 0)
610 return RangeF(preceding_run_widths
, preceding_run_widths
+ width
);
614 GetClusterAt(text_index
, &chars
, &glyphs
);
615 const float cluster_begin_x
= positions
[glyphs
.start()].x();
616 const float cluster_end_x
= glyphs
.end() < glyph_count
?
617 positions
[glyphs
.end()].x() : SkFloatToScalar(width
);
619 // A cluster consists of a number of code points and corresponds to a number
620 // of glyphs that should be drawn together. A cluster can contain multiple
621 // graphemes. In order to place the cursor at a grapheme boundary inside the
622 // cluster, we simply divide the cluster width by the number of graphemes.
623 if (chars
.length() > 1 && grapheme_iterator
) {
626 for (size_t i
= chars
.start(); i
< chars
.end(); ++i
) {
627 if (grapheme_iterator
->IsGraphemeBoundary(i
)) {
636 before
= total
- before
- 1;
637 DCHECK_GE(before
, 0);
638 DCHECK_LT(before
, total
);
639 const int cluster_width
= cluster_end_x
- cluster_begin_x
;
640 const int grapheme_begin_x
= cluster_begin_x
+ static_cast<int>(0.5f
+
641 cluster_width
* before
/ static_cast<float>(total
));
642 const int grapheme_end_x
= cluster_begin_x
+ static_cast<int>(0.5f
+
643 cluster_width
* (before
+ 1) / static_cast<float>(total
));
644 return RangeF(preceding_run_widths
+ grapheme_begin_x
,
645 preceding_run_widths
+ grapheme_end_x
);
649 return RangeF(preceding_run_widths
+ cluster_begin_x
,
650 preceding_run_widths
+ cluster_end_x
);
653 SkScalar
TextRunHarfBuzz::GetGlyphWidthForCharRange(
654 const Range
& char_range
) const {
655 if (char_range
.is_empty())
658 DCHECK(range
.Contains(char_range
));
659 Range glyph_range
= CharRangeToGlyphRange(char_range
);
660 return ((glyph_range
.end() == glyph_count
)
661 ? SkFloatToScalar(width
)
662 : positions
[glyph_range
.end()].x()) -
663 positions
[glyph_range
.start()].x();
666 TextRunList::TextRunList() : width_(0.0f
) {}
668 TextRunList::~TextRunList() {}
670 void TextRunList::Reset() {
675 void TextRunList::InitIndexMap() {
676 if (runs_
.size() == 1) {
677 visual_to_logical_
= logical_to_visual_
= std::vector
<int32_t>(1, 0);
680 const size_t num_runs
= runs_
.size();
681 std::vector
<UBiDiLevel
> levels(num_runs
);
682 for (size_t i
= 0; i
< num_runs
; ++i
)
683 levels
[i
] = runs_
[i
]->level
;
684 visual_to_logical_
.resize(num_runs
);
685 ubidi_reorderVisual(&levels
[0], num_runs
, &visual_to_logical_
[0]);
686 logical_to_visual_
.resize(num_runs
);
687 ubidi_reorderLogical(&levels
[0], num_runs
, &logical_to_visual_
[0]);
690 void TextRunList::ComputePrecedingRunWidths() {
691 // Precalculate run width information.
693 for (size_t i
= 0; i
< runs_
.size(); ++i
) {
694 TextRunHarfBuzz
* run
= runs_
[visual_to_logical_
[i
]];
695 run
->preceding_run_widths
= width_
;
696 width_
+= run
->width
;
700 size_t TextRunList::GetRunIndexAt(size_t position
) const {
701 for (size_t i
= 0; i
< runs_
.size(); ++i
) {
702 if (runs_
[i
]->range
.start() <= position
&& runs_
[i
]->range
.end() > position
)
708 } // namespace internal
710 RenderTextHarfBuzz::RenderTextHarfBuzz()
712 update_layout_run_list_(false),
713 update_display_run_list_(false),
714 update_grapheme_iterator_(false),
715 update_display_text_(false),
716 glyph_width_for_test_(0u) {
717 set_truncate_length(kMaxTextLength
);
720 RenderTextHarfBuzz::~RenderTextHarfBuzz() {}
722 scoped_ptr
<RenderText
> RenderTextHarfBuzz::CreateInstanceOfSameType() const {
723 return make_scoped_ptr(new RenderTextHarfBuzz
);
726 bool RenderTextHarfBuzz::MultilineSupported() const {
730 const base::string16
& RenderTextHarfBuzz::GetDisplayText() {
731 // TODO(oshima): Consider supporting eliding multi-line text.
732 // This requires max_line support first.
734 elide_behavior() == NO_ELIDE
||
735 elide_behavior() == FADE_TAIL
) {
736 // Call UpdateDisplayText to clear |display_text_| and |text_elided_|
737 // on the RenderText class.
738 UpdateDisplayText(0);
739 update_display_text_
= false;
740 display_run_list_
.reset();
741 return layout_text();
744 EnsureLayoutRunList();
745 DCHECK(!update_display_text_
);
746 return text_elided() ? display_text() : layout_text();
749 Size
RenderTextHarfBuzz::GetStringSize() {
750 const SizeF size_f
= GetStringSizeF();
751 return Size(std::ceil(size_f
.width()), size_f
.height());
754 SizeF
RenderTextHarfBuzz::GetStringSizeF() {
759 SelectionModel
RenderTextHarfBuzz::FindCursorPosition(const Point
& point
) {
762 int x
= ToTextPoint(point
).x();
764 size_t run_index
= GetRunContainingXCoord(x
, &offset
);
766 internal::TextRunList
* run_list
= GetRunList();
767 if (run_index
>= run_list
->size())
768 return EdgeSelectionModel((x
< 0) ? CURSOR_LEFT
: CURSOR_RIGHT
);
769 const internal::TextRunHarfBuzz
& run
= *run_list
->runs()[run_index
];
770 for (size_t i
= 0; i
< run
.glyph_count
; ++i
) {
772 i
+ 1 == run
.glyph_count
? run
.width
: run
.positions
[i
+ 1].x();
773 const SkScalar middle
= (end
+ run
.positions
[i
].x()) / 2;
775 if (offset
< middle
) {
776 return SelectionModel(DisplayIndexToTextIndex(
777 run
.glyph_to_char
[i
] + (run
.is_rtl
? 1 : 0)),
778 (run
.is_rtl
? CURSOR_BACKWARD
: CURSOR_FORWARD
));
781 return SelectionModel(DisplayIndexToTextIndex(
782 run
.glyph_to_char
[i
] + (run
.is_rtl
? 0 : 1)),
783 (run
.is_rtl
? CURSOR_FORWARD
: CURSOR_BACKWARD
));
786 return EdgeSelectionModel(CURSOR_RIGHT
);
789 std::vector
<RenderText::FontSpan
> RenderTextHarfBuzz::GetFontSpansForTesting() {
792 internal::TextRunList
* run_list
= GetRunList();
793 std::vector
<RenderText::FontSpan
> spans
;
794 for (auto* run
: run_list
->runs()) {
795 SkString family_name
;
796 run
->skia_face
->getFamilyName(&family_name
);
797 Font
font(family_name
.c_str(), run
->font_size
);
798 spans
.push_back(RenderText::FontSpan(
800 Range(DisplayIndexToTextIndex(run
->range
.start()),
801 DisplayIndexToTextIndex(run
->range
.end()))));
807 Range
RenderTextHarfBuzz::GetGlyphBounds(size_t index
) {
809 const size_t run_index
=
810 GetRunContainingCaret(SelectionModel(index
, CURSOR_FORWARD
));
811 internal::TextRunList
* run_list
= GetRunList();
812 // Return edge bounds if the index is invalid or beyond the layout text size.
813 if (run_index
>= run_list
->size())
814 return Range(GetStringSize().width());
815 const size_t layout_index
= TextIndexToDisplayIndex(index
);
816 internal::TextRunHarfBuzz
* run
= run_list
->runs()[run_index
];
818 run
->GetGraphemeBounds(GetGraphemeIterator(), layout_index
);
819 // If cursor is enabled, extend the last glyph up to the rightmost cursor
820 // position since clients expect them to be contiguous.
821 if (cursor_enabled() && run_index
== run_list
->size() - 1 &&
822 index
== (run
->is_rtl
? run
->range
.start() : run
->range
.end() - 1))
823 bounds
.set_end(std::ceil(bounds
.end()));
824 return run
->is_rtl
? RangeF(bounds
.end(), bounds
.start()).Round()
828 int RenderTextHarfBuzz::GetDisplayTextBaseline() {
830 return lines()[0].baseline
;
833 SelectionModel
RenderTextHarfBuzz::AdjacentCharSelectionModel(
834 const SelectionModel
& selection
,
835 VisualCursorDirection direction
) {
836 DCHECK(!update_display_run_list_
);
838 internal::TextRunList
* run_list
= GetRunList();
839 internal::TextRunHarfBuzz
* run
;
841 size_t run_index
= GetRunContainingCaret(selection
);
842 if (run_index
>= run_list
->size()) {
843 // The cursor is not in any run: we're at the visual and logical edge.
844 SelectionModel edge
= EdgeSelectionModel(direction
);
845 if (edge
.caret_pos() == selection
.caret_pos())
847 int visual_index
= (direction
== CURSOR_RIGHT
) ? 0 : run_list
->size() - 1;
848 run
= run_list
->runs()[run_list
->visual_to_logical(visual_index
)];
850 // If the cursor is moving within the current run, just move it by one
851 // grapheme in the appropriate direction.
852 run
= run_list
->runs()[run_index
];
853 size_t caret
= selection
.caret_pos();
854 bool forward_motion
= run
->is_rtl
== (direction
== CURSOR_LEFT
);
855 if (forward_motion
) {
856 if (caret
< DisplayIndexToTextIndex(run
->range
.end())) {
857 caret
= IndexOfAdjacentGrapheme(caret
, CURSOR_FORWARD
);
858 return SelectionModel(caret
, CURSOR_BACKWARD
);
861 if (caret
> DisplayIndexToTextIndex(run
->range
.start())) {
862 caret
= IndexOfAdjacentGrapheme(caret
, CURSOR_BACKWARD
);
863 return SelectionModel(caret
, CURSOR_FORWARD
);
866 // The cursor is at the edge of a run; move to the visually adjacent run.
867 int visual_index
= run_list
->logical_to_visual(run_index
);
868 visual_index
+= (direction
== CURSOR_LEFT
) ? -1 : 1;
869 if (visual_index
< 0 || visual_index
>= static_cast<int>(run_list
->size()))
870 return EdgeSelectionModel(direction
);
871 run
= run_list
->runs()[run_list
->visual_to_logical(visual_index
)];
873 bool forward_motion
= run
->is_rtl
== (direction
== CURSOR_LEFT
);
874 return forward_motion
? FirstSelectionModelInsideRun(run
) :
875 LastSelectionModelInsideRun(run
);
878 SelectionModel
RenderTextHarfBuzz::AdjacentWordSelectionModel(
879 const SelectionModel
& selection
,
880 VisualCursorDirection direction
) {
882 return EdgeSelectionModel(direction
);
884 base::i18n::BreakIterator
iter(text(), base::i18n::BreakIterator::BREAK_WORD
);
885 bool success
= iter
.Init();
890 // Match OS specific word break behavior.
893 if (direction
== CURSOR_RIGHT
) {
894 pos
= std::min(selection
.caret_pos() + 1, text().length());
895 while (iter
.Advance()) {
897 if (iter
.IsWord() && pos
> selection
.caret_pos())
900 } else { // direction == CURSOR_LEFT
901 // Notes: We always iterate words from the beginning.
902 // This is probably fast enough for our usage, but we may
903 // want to modify WordIterator so that it can start from the
904 // middle of string and advance backwards.
905 pos
= std::max
<int>(selection
.caret_pos() - 1, 0);
906 while (iter
.Advance()) {
908 size_t begin
= iter
.pos() - iter
.GetString().length();
909 if (begin
== selection
.caret_pos()) {
910 // The cursor is at the beginning of a word.
911 // Move to previous word.
913 } else if (iter
.pos() >= selection
.caret_pos()) {
914 // The cursor is in the middle or at the end of a word.
915 // Move to the top of current word.
919 pos
= iter
.pos() - iter
.GetString().length();
923 return SelectionModel(pos
, CURSOR_FORWARD
);
925 internal::TextRunList
* run_list
= GetRunList();
926 SelectionModel
cur(selection
);
928 cur
= AdjacentCharSelectionModel(cur
, direction
);
929 size_t run
= GetRunContainingCaret(cur
);
930 if (run
== run_list
->size())
932 const bool is_forward
=
933 run_list
->runs()[run
]->is_rtl
== (direction
== CURSOR_LEFT
);
934 size_t cursor
= cur
.caret_pos();
935 if (is_forward
? iter
.IsEndOfWord(cursor
) : iter
.IsStartOfWord(cursor
))
942 std::vector
<Rect
> RenderTextHarfBuzz::GetSubstringBounds(const Range
& range
) {
943 DCHECK(!update_display_run_list_
);
944 DCHECK(Range(0, text().length()).Contains(range
));
945 Range
layout_range(TextIndexToDisplayIndex(range
.start()),
946 TextIndexToDisplayIndex(range
.end()));
947 DCHECK(Range(0, GetDisplayText().length()).Contains(layout_range
));
949 std::vector
<Rect
> rects
;
950 if (layout_range
.is_empty())
952 std::vector
<Range
> bounds
;
954 internal::TextRunList
* run_list
= GetRunList();
956 // Add a Range for each run/selection intersection.
957 for (size_t i
= 0; i
< run_list
->size(); ++i
) {
958 internal::TextRunHarfBuzz
* run
=
959 run_list
->runs()[run_list
->visual_to_logical(i
)];
960 Range intersection
= run
->range
.Intersect(layout_range
);
961 if (!intersection
.IsValid())
963 DCHECK(!intersection
.is_reversed());
964 const size_t left_index
=
965 run
->is_rtl
? intersection
.end() - 1 : intersection
.start();
966 const Range leftmost_character_x
=
967 run
->GetGraphemeBounds(GetGraphemeIterator(), left_index
).Round();
968 const size_t right_index
=
969 run
->is_rtl
? intersection
.start() : intersection
.end() - 1;
970 const Range rightmost_character_x
=
971 run
->GetGraphemeBounds(GetGraphemeIterator(), right_index
).Round();
972 Range
range_x(leftmost_character_x
.start(), rightmost_character_x
.end());
973 DCHECK(!range_x
.is_reversed());
974 if (range_x
.is_empty())
977 // Union this with the last range if they're adjacent.
978 DCHECK(bounds
.empty() || bounds
.back().GetMax() <= range_x
.GetMin());
979 if (!bounds
.empty() && bounds
.back().GetMax() == range_x
.GetMin()) {
980 range_x
= Range(bounds
.back().GetMin(), range_x
.GetMax());
983 bounds
.push_back(range_x
);
985 for (Range
& bound
: bounds
) {
986 std::vector
<Rect
> current_rects
= TextBoundsToViewBounds(bound
);
987 rects
.insert(rects
.end(), current_rects
.begin(), current_rects
.end());
992 size_t RenderTextHarfBuzz::TextIndexToDisplayIndex(size_t index
) {
993 return TextIndexToGivenTextIndex(GetDisplayText(), index
);
996 size_t RenderTextHarfBuzz::DisplayIndexToTextIndex(size_t index
) {
999 const size_t text_index
= UTF16OffsetToIndex(text(), 0, index
);
1000 DCHECK_LE(text_index
, text().length());
1004 bool RenderTextHarfBuzz::IsValidCursorIndex(size_t index
) {
1005 if (index
== 0 || index
== text().length())
1007 if (!IsValidLogicalIndex(index
))
1009 base::i18n::BreakIterator
* grapheme_iterator
= GetGraphemeIterator();
1010 return !grapheme_iterator
|| grapheme_iterator
->IsGraphemeBoundary(index
);
1013 void RenderTextHarfBuzz::OnLayoutTextAttributeChanged(bool text_changed
) {
1014 update_layout_run_list_
= true;
1015 OnDisplayTextAttributeChanged();
1018 void RenderTextHarfBuzz::OnDisplayTextAttributeChanged() {
1019 update_display_text_
= true;
1020 update_grapheme_iterator_
= true;
1023 void RenderTextHarfBuzz::EnsureLayout() {
1024 EnsureLayoutRunList();
1026 if (update_display_run_list_
) {
1027 DCHECK(text_elided());
1028 const base::string16
& display_text
= GetDisplayText();
1029 display_run_list_
.reset(new internal::TextRunList
);
1031 if (!display_text
.empty()) {
1032 TRACE_EVENT0("ui", "RenderTextHarfBuzz:EnsureLayout1");
1034 ItemizeTextToRuns(display_text
, display_run_list_
.get());
1036 // TODO(ckocagil): Remove ScopedTracker below once crbug.com/441028 is
1038 tracked_objects::ScopedTracker
tracking_profile(
1039 FROM_HERE_WITH_EXPLICIT_FUNCTION("441028 ShapeRunList() 1"));
1040 ShapeRunList(display_text
, display_run_list_
.get());
1042 update_display_run_list_
= false;
1044 std::vector
<internal::Line
> empty_lines
;
1045 set_lines(&empty_lines
);
1048 if (lines().empty()) {
1049 // TODO(ckocagil): Remove ScopedTracker below once crbug.com/441028 is
1051 scoped_ptr
<tracked_objects::ScopedTracker
> tracking_profile(
1052 new tracked_objects::ScopedTracker(
1053 FROM_HERE_WITH_EXPLICIT_FUNCTION("441028 HarfBuzzLineBreaker")));
1055 internal::TextRunList
* run_list
= GetRunList();
1056 HarfBuzzLineBreaker
line_breaker(
1057 display_rect().width(), font_list().GetBaseline(),
1058 std::max(font_list().GetHeight(), min_line_height()),
1059 word_wrap_behavior(), GetDisplayText(),
1060 multiline() ? &GetLineBreaks() : nullptr, *run_list
);
1062 tracking_profile
.reset();
1065 line_breaker
.ConstructMultiLines();
1067 line_breaker
.ConstructSingleLine();
1068 std::vector
<internal::Line
> lines
;
1069 line_breaker
.FinalizeLines(&lines
, &total_size_
);
1074 void RenderTextHarfBuzz::DrawVisualText(Canvas
* canvas
) {
1075 internal::SkiaTextRenderer
renderer(canvas
);
1076 DrawVisualTextInternal(&renderer
);
1079 void RenderTextHarfBuzz::DrawVisualTextInternal(
1080 internal::SkiaTextRenderer
* renderer
) {
1081 DCHECK(!update_layout_run_list_
);
1082 DCHECK(!update_display_run_list_
);
1083 DCHECK(!update_display_text_
);
1084 if (lines().empty())
1087 ApplyFadeEffects(renderer
);
1088 ApplyTextShadows(renderer
);
1089 ApplyCompositionAndSelectionStyles();
1091 internal::TextRunList
* run_list
= GetRunList();
1092 for (size_t i
= 0; i
< lines().size(); ++i
) {
1093 const internal::Line
& line
= lines()[i
];
1094 const Vector2d origin
= GetLineOffset(i
) + Vector2d(0, line
.baseline
);
1095 SkScalar preceding_segment_widths
= 0;
1096 for (const internal::LineSegment
& segment
: line
.segments
) {
1097 const internal::TextRunHarfBuzz
& run
= *run_list
->runs()[segment
.run
];
1098 renderer
->SetTypeface(run
.skia_face
.get());
1099 renderer
->SetTextSize(SkIntToScalar(run
.font_size
));
1100 renderer
->SetFontRenderParams(run
.render_params
,
1101 subpixel_rendering_suppressed());
1102 Range glyphs_range
= run
.CharRangeToGlyphRange(segment
.char_range
);
1103 scoped_ptr
<SkPoint
[]> positions(new SkPoint
[glyphs_range
.length()]);
1104 SkScalar offset_x
= preceding_segment_widths
-
1105 ((glyphs_range
.GetMin() != 0)
1106 ? run
.positions
[glyphs_range
.GetMin()].x()
1108 for (size_t j
= 0; j
< glyphs_range
.length(); ++j
) {
1109 positions
[j
] = run
.positions
[(glyphs_range
.is_reversed()) ?
1110 (glyphs_range
.start() - j
) :
1111 (glyphs_range
.start() + j
)];
1112 positions
[j
].offset(SkIntToScalar(origin
.x()) + offset_x
,
1113 SkIntToScalar(origin
.y() + run
.baseline_offset
));
1115 for (BreakList
<SkColor
>::const_iterator it
=
1116 colors().GetBreak(segment
.char_range
.start());
1117 it
!= colors().breaks().end() &&
1118 it
->first
< segment
.char_range
.end();
1120 const Range intersection
=
1121 colors().GetRange(it
).Intersect(segment
.char_range
);
1122 const Range colored_glyphs
= run
.CharRangeToGlyphRange(intersection
);
1123 // The range may be empty if a portion of a multi-character grapheme is
1124 // selected, yielding two colors for a single glyph. For now, this just
1125 // paints the glyph with a single style, but it should paint it twice,
1126 // clipped according to selection bounds. See http://crbug.com/366786
1127 if (colored_glyphs
.is_empty())
1130 renderer
->SetForegroundColor(it
->second
);
1131 renderer
->DrawPosText(
1132 &positions
[colored_glyphs
.start() - glyphs_range
.start()],
1133 &run
.glyphs
[colored_glyphs
.start()], colored_glyphs
.length());
1134 int start_x
= SkScalarRoundToInt(
1135 positions
[colored_glyphs
.start() - glyphs_range
.start()].x());
1136 int end_x
= SkScalarRoundToInt(
1137 (colored_glyphs
.end() == glyphs_range
.end())
1138 ? (SkFloatToScalar(segment
.width()) + preceding_segment_widths
+
1139 SkIntToScalar(origin
.x()))
1140 : positions
[colored_glyphs
.end() - glyphs_range
.start()].x());
1141 renderer
->DrawDecorations(start_x
, origin
.y(), end_x
- start_x
,
1142 run
.underline
, run
.strike
,
1143 run
.diagonal_strike
);
1145 preceding_segment_widths
+= SkFloatToScalar(segment
.width());
1149 renderer
->EndDiagonalStrike();
1151 UndoCompositionAndSelectionStyles();
1154 size_t RenderTextHarfBuzz::GetRunContainingCaret(
1155 const SelectionModel
& caret
) {
1156 DCHECK(!update_display_run_list_
);
1157 size_t layout_position
= TextIndexToDisplayIndex(caret
.caret_pos());
1158 LogicalCursorDirection affinity
= caret
.caret_affinity();
1159 internal::TextRunList
* run_list
= GetRunList();
1160 for (size_t i
= 0; i
< run_list
->size(); ++i
) {
1161 internal::TextRunHarfBuzz
* run
= run_list
->runs()[i
];
1162 if (RangeContainsCaret(run
->range
, layout_position
, affinity
))
1165 return run_list
->size();
1168 size_t RenderTextHarfBuzz::GetRunContainingXCoord(float x
,
1169 float* offset
) const {
1170 DCHECK(!update_display_run_list_
);
1171 const internal::TextRunList
* run_list
= GetRunList();
1173 return run_list
->size();
1174 // Find the text run containing the argument point (assumed already offset).
1175 float current_x
= 0;
1176 for (size_t i
= 0; i
< run_list
->size(); ++i
) {
1177 size_t run
= run_list
->visual_to_logical(i
);
1178 current_x
+= run_list
->runs()[run
]->width
;
1179 if (x
< current_x
) {
1180 *offset
= x
- (current_x
- run_list
->runs()[run
]->width
);
1184 return run_list
->size();
1187 SelectionModel
RenderTextHarfBuzz::FirstSelectionModelInsideRun(
1188 const internal::TextRunHarfBuzz
* run
) {
1189 size_t position
= DisplayIndexToTextIndex(run
->range
.start());
1190 position
= IndexOfAdjacentGrapheme(position
, CURSOR_FORWARD
);
1191 return SelectionModel(position
, CURSOR_BACKWARD
);
1194 SelectionModel
RenderTextHarfBuzz::LastSelectionModelInsideRun(
1195 const internal::TextRunHarfBuzz
* run
) {
1196 size_t position
= DisplayIndexToTextIndex(run
->range
.end());
1197 position
= IndexOfAdjacentGrapheme(position
, CURSOR_BACKWARD
);
1198 return SelectionModel(position
, CURSOR_FORWARD
);
1201 void RenderTextHarfBuzz::ItemizeTextToRuns(
1202 const base::string16
& text
,
1203 internal::TextRunList
* run_list_out
) {
1204 DCHECK_NE(0U, text
.length());
1206 // If ICU fails to itemize the text, we create a run that spans the entire
1207 // text. This is needed because leaving the runs set empty causes some clients
1208 // to misbehave since they expect non-zero text metrics from a non-empty text.
1209 base::i18n::BiDiLineIterator bidi_iterator
;
1210 if (!bidi_iterator
.Open(text
, GetTextDirection(text
))) {
1211 internal::TextRunHarfBuzz
* run
= new internal::TextRunHarfBuzz
;
1212 run
->range
= Range(0, text
.length());
1213 run_list_out
->add(run
);
1214 run_list_out
->InitIndexMap();
1218 // Temporarily apply composition underlines and selection colors.
1219 ApplyCompositionAndSelectionStyles();
1221 // Build the run list from the script items and ranged styles and baselines.
1222 // Use an empty color BreakList to avoid breaking runs at color boundaries.
1223 BreakList
<SkColor
> empty_colors
;
1224 empty_colors
.SetMax(text
.length());
1225 DCHECK_LE(text
.size(), baselines().max());
1226 for (const BreakList
<bool>& style
: styles())
1227 DCHECK_LE(text
.size(), style
.max());
1228 internal::StyleIterator
style(empty_colors
, baselines(), styles());
1230 for (size_t run_break
= 0; run_break
< text
.length();) {
1231 internal::TextRunHarfBuzz
* run
= new internal::TextRunHarfBuzz
;
1232 run
->range
.set_start(run_break
);
1233 run
->font_style
= (style
.style(BOLD
) ? Font::BOLD
: 0) |
1234 (style
.style(ITALIC
) ? Font::ITALIC
: 0);
1235 run
->baseline_type
= style
.baseline();
1236 run
->strike
= style
.style(STRIKE
);
1237 run
->diagonal_strike
= style
.style(DIAGONAL_STRIKE
);
1238 run
->underline
= style
.style(UNDERLINE
);
1239 int32 script_item_break
= 0;
1240 bidi_iterator
.GetLogicalRun(run_break
, &script_item_break
, &run
->level
);
1241 // Odd BiDi embedding levels correspond to RTL runs.
1242 run
->is_rtl
= (run
->level
% 2) == 1;
1243 // Find the length and script of this script run.
1244 script_item_break
= ScriptInterval(text
, run_break
,
1245 script_item_break
- run_break
, &run
->script
) + run_break
;
1247 // Find the next break and advance the iterators as needed.
1248 run_break
= std::min(
1249 static_cast<size_t>(script_item_break
),
1250 TextIndexToGivenTextIndex(text
, style
.GetRange().end()));
1252 // Break runs at certain characters that need to be rendered separately to
1253 // prevent either an unusual character from forcing a fallback font on the
1254 // entire run, or brackets from being affected by a fallback font.
1255 // http://crbug.com/278913, http://crbug.com/396776
1256 if (run_break
> run
->range
.start())
1257 run_break
= FindRunBreakingCharacter(text
, run
->range
.start(), run_break
);
1259 DCHECK(IsValidCodePointIndex(text
, run_break
));
1260 style
.UpdatePosition(DisplayIndexToTextIndex(run_break
));
1261 run
->range
.set_end(run_break
);
1263 run_list_out
->add(run
);
1266 // Undo the temporarily applied composition underlines and selection colors.
1267 UndoCompositionAndSelectionStyles();
1269 run_list_out
->InitIndexMap();
1272 bool RenderTextHarfBuzz::CompareFamily(
1273 const base::string16
& text
,
1274 const std::string
& family
,
1275 const gfx::FontRenderParams
& render_params
,
1276 internal::TextRunHarfBuzz
* run
,
1277 std::string
* best_family
,
1278 gfx::FontRenderParams
* best_render_params
,
1279 size_t* best_missing_glyphs
) {
1280 if (!ShapeRunWithFont(text
, family
, render_params
, run
))
1283 const size_t missing_glyphs
= run
->CountMissingGlyphs();
1284 if (missing_glyphs
< *best_missing_glyphs
) {
1285 *best_family
= family
;
1286 *best_render_params
= render_params
;
1287 *best_missing_glyphs
= missing_glyphs
;
1289 return missing_glyphs
== 0;
1292 void RenderTextHarfBuzz::ShapeRunList(const base::string16
& text
,
1293 internal::TextRunList
* run_list
) {
1294 for (auto* run
: run_list
->runs())
1295 ShapeRun(text
, run
);
1296 run_list
->ComputePrecedingRunWidths();
1299 void RenderTextHarfBuzz::ShapeRun(const base::string16
& text
,
1300 internal::TextRunHarfBuzz
* run
) {
1301 const Font
& primary_font
= font_list().GetPrimaryFont();
1302 const std::string primary_family
= primary_font
.GetFontName();
1303 run
->font_size
= primary_font
.GetFontSize();
1304 run
->baseline_offset
= 0;
1305 if (run
->baseline_type
!= NORMAL_BASELINE
) {
1306 // Calculate a slightly smaller font. The ratio here is somewhat arbitrary.
1307 // Proportions from 5/9 to 5/7 all look pretty good.
1308 const float ratio
= 5.0f
/ 9.0f
;
1309 run
->font_size
= gfx::ToRoundedInt(primary_font
.GetFontSize() * ratio
);
1310 switch (run
->baseline_type
) {
1312 run
->baseline_offset
=
1313 primary_font
.GetCapHeight() - primary_font
.GetHeight();
1316 run
->baseline_offset
=
1317 gfx::ToRoundedInt(primary_font
.GetCapHeight() * ratio
) -
1318 primary_font
.GetCapHeight();
1321 run
->baseline_offset
=
1322 primary_font
.GetHeight() - primary_font
.GetBaseline();
1324 case INFERIOR
: // Fall through.
1330 std::string best_family
;
1331 FontRenderParams best_render_params
;
1332 size_t best_missing_glyphs
= std::numeric_limits
<size_t>::max();
1334 for (const Font
& font
: font_list().GetFonts()) {
1335 if (CompareFamily(text
, font
.GetFontName(), font
.GetFontRenderParams(),
1336 run
, &best_family
, &best_render_params
,
1337 &best_missing_glyphs
))
1342 Font uniscribe_font
;
1343 std::string uniscribe_family
;
1344 const base::char16
* run_text
= &(text
[run
->range
.start()]);
1345 if (GetUniscribeFallbackFont(primary_font
, run_text
, run
->range
.length(),
1347 uniscribe_family
= uniscribe_font
.GetFontName();
1348 if (CompareFamily(text
, uniscribe_family
,
1349 uniscribe_font
.GetFontRenderParams(), run
,
1350 &best_family
, &best_render_params
, &best_missing_glyphs
))
1355 std::vector
<std::string
> fallback_families
=
1356 GetFallbackFontFamilies(primary_family
);
1359 // Append fonts in the fallback list of the Uniscribe font.
1360 if (!uniscribe_family
.empty()) {
1361 std::vector
<std::string
> uniscribe_fallbacks
=
1362 GetFallbackFontFamilies(uniscribe_family
);
1363 fallback_families
.insert(fallback_families
.end(),
1364 uniscribe_fallbacks
.begin(), uniscribe_fallbacks
.end());
1367 // Add Segoe UI and its associated linked fonts to the fallback font list to
1368 // ensure that the fallback list covers the basic cases.
1369 // http://crbug.com/467459. On some Windows configurations the default font
1370 // could be a raster font like System, which would not give us a reasonable
1371 // fallback font list.
1372 if (!base::LowerCaseEqualsASCII(primary_family
, "segoe ui") &&
1373 !base::LowerCaseEqualsASCII(uniscribe_family
, "segoe ui")) {
1374 std::vector
<std::string
> default_fallback_families
=
1375 GetFallbackFontFamilies("Segoe UI");
1376 fallback_families
.insert(fallback_families
.end(),
1377 default_fallback_families
.begin(), default_fallback_families
.end());
1381 // Use a set to track the fallback fonts and avoid duplicate entries.
1382 std::set
<std::string
, CaseInsensitiveCompare
> fallback_fonts
;
1384 // Try shaping with the fallback fonts.
1385 for (const auto& family
: fallback_families
) {
1386 if (family
== primary_family
)
1389 if (family
== uniscribe_family
)
1392 if (fallback_fonts
.find(family
) != fallback_fonts
.end())
1395 fallback_fonts
.insert(family
);
1397 FontRenderParamsQuery query
;
1398 query
.families
.push_back(family
);
1399 query
.pixel_size
= run
->font_size
;
1400 query
.style
= run
->font_style
;
1401 FontRenderParams fallback_render_params
= GetFontRenderParams(query
, NULL
);
1402 if (CompareFamily(text
, family
, fallback_render_params
, run
, &best_family
,
1403 &best_render_params
, &best_missing_glyphs
))
1407 if (!best_family
.empty() &&
1408 (best_family
== run
->family
||
1409 ShapeRunWithFont(text
, best_family
, best_render_params
, run
)))
1412 run
->glyph_count
= 0;
1416 bool RenderTextHarfBuzz::ShapeRunWithFont(const base::string16
& text
,
1417 const std::string
& font_family
,
1418 const FontRenderParams
& params
,
1419 internal::TextRunHarfBuzz
* run
) {
1420 skia::RefPtr
<SkTypeface
> skia_face
=
1421 internal::CreateSkiaTypeface(font_family
, run
->font_style
);
1422 if (skia_face
== NULL
)
1424 run
->skia_face
= skia_face
;
1425 run
->family
= font_family
;
1426 run
->render_params
= params
;
1428 hb_font_t
* harfbuzz_font
= CreateHarfBuzzFont(
1429 run
->skia_face
.get(), SkIntToScalar(run
->font_size
), run
->render_params
,
1430 subpixel_rendering_suppressed());
1432 // Create a HarfBuzz buffer and add the string to be shaped. The HarfBuzz
1433 // buffer holds our text, run information to be used by the shaping engine,
1434 // and the resulting glyph data.
1435 hb_buffer_t
* buffer
= hb_buffer_create();
1436 hb_buffer_add_utf16(buffer
, reinterpret_cast<const uint16
*>(text
.c_str()),
1437 text
.length(), run
->range
.start(), run
->range
.length());
1438 hb_buffer_set_script(buffer
, ICUScriptToHBScript(run
->script
));
1439 hb_buffer_set_direction(buffer
,
1440 run
->is_rtl
? HB_DIRECTION_RTL
: HB_DIRECTION_LTR
);
1441 // TODO(ckocagil): Should we determine the actual language?
1442 hb_buffer_set_language(buffer
, hb_language_get_default());
1445 // TODO(ckocagil): Remove ScopedTracker below once crbug.com/441028 is
1447 tracked_objects::ScopedTracker
tracking_profile(
1448 FROM_HERE_WITH_EXPLICIT_FUNCTION("441028 hb_shape()"));
1451 hb_shape(harfbuzz_font
, buffer
, NULL
, 0);
1454 // Populate the run fields with the resulting glyph data in the buffer.
1455 unsigned int glyph_count
= 0;
1456 hb_glyph_info_t
* infos
= hb_buffer_get_glyph_infos(buffer
, &glyph_count
);
1457 run
->glyph_count
= glyph_count
;
1458 hb_glyph_position_t
* hb_positions
=
1459 hb_buffer_get_glyph_positions(buffer
, NULL
);
1460 run
->glyphs
.reset(new uint16
[run
->glyph_count
]);
1461 run
->glyph_to_char
.resize(run
->glyph_count
);
1462 run
->positions
.reset(new SkPoint
[run
->glyph_count
]);
1465 for (size_t i
= 0; i
< run
->glyph_count
; ++i
) {
1466 DCHECK_LE(infos
[i
].codepoint
, std::numeric_limits
<uint16
>::max());
1467 run
->glyphs
[i
] = static_cast<uint16
>(infos
[i
].codepoint
);
1468 run
->glyph_to_char
[i
] = infos
[i
].cluster
;
1469 const SkScalar x_offset
= SkFixedToScalar(hb_positions
[i
].x_offset
);
1470 const SkScalar y_offset
= SkFixedToScalar(hb_positions
[i
].y_offset
);
1471 run
->positions
[i
].set(run
->width
+ x_offset
, -y_offset
);
1472 run
->width
+= (glyph_width_for_test_
> 0)
1473 ? glyph_width_for_test_
1474 : SkFixedToFloat(hb_positions
[i
].x_advance
);
1475 // Round run widths if subpixel positioning is off to match native behavior.
1476 if (!run
->render_params
.subpixel_positioning
)
1477 run
->width
= std::floor(run
->width
+ 0.5f
);
1480 hb_buffer_destroy(buffer
);
1481 hb_font_destroy(harfbuzz_font
);
1485 void RenderTextHarfBuzz::EnsureLayoutRunList() {
1486 if (update_layout_run_list_
) {
1487 layout_run_list_
.Reset();
1489 const base::string16
& text
= layout_text();
1490 if (!text
.empty()) {
1491 TRACE_EVENT0("ui", "RenderTextHarfBuzz:EnsureLayoutRunList");
1492 ItemizeTextToRuns(text
, &layout_run_list_
);
1494 // TODO(ckocagil): Remove ScopedTracker below once crbug.com/441028 is
1496 tracked_objects::ScopedTracker
tracking_profile(
1497 FROM_HERE_WITH_EXPLICIT_FUNCTION("441028 ShapeRunList() 2"));
1498 ShapeRunList(text
, &layout_run_list_
);
1501 std::vector
<internal::Line
> empty_lines
;
1502 set_lines(&empty_lines
);
1503 display_run_list_
.reset();
1504 update_display_text_
= true;
1505 update_layout_run_list_
= false;
1507 if (update_display_text_
) {
1508 UpdateDisplayText(multiline() ? 0 : layout_run_list_
.width());
1509 update_display_text_
= false;
1510 update_display_run_list_
= text_elided();
1514 base::i18n::BreakIterator
* RenderTextHarfBuzz::GetGraphemeIterator() {
1515 if (update_grapheme_iterator_
) {
1516 update_grapheme_iterator_
= false;
1517 grapheme_iterator_
.reset(new base::i18n::BreakIterator(
1519 base::i18n::BreakIterator::BREAK_CHARACTER
));
1520 if (!grapheme_iterator_
->Init())
1521 grapheme_iterator_
.reset();
1523 return grapheme_iterator_
.get();
1526 internal::TextRunList
* RenderTextHarfBuzz::GetRunList() {
1527 DCHECK(!update_layout_run_list_
);
1528 DCHECK(!update_display_run_list_
);
1529 return text_elided() ? display_run_list_
.get() : &layout_run_list_
;
1532 const internal::TextRunList
* RenderTextHarfBuzz::GetRunList() const {
1533 return const_cast<RenderTextHarfBuzz
*>(this)->GetRunList();