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());
384 DCHECK_EQ(last_segment
.x_range
.end(), segment
.x_range
.start());
385 last_segment
.char_range
.set_end(segment
.char_range
.end());
386 last_segment
.x_range
.set_end(SkScalarToFloat(text_x_
) +
388 if (run
.is_rtl
&& last_segment
.char_range
.end() == run
.range
.end())
389 UpdateRTLSegmentRanges();
390 line
->size
.set_width(line
->size
.width() + segment
.width());
391 text_x_
+= segment
.width();
392 available_width_
-= segment
.width();
396 line
->segments
.push_back(segment
);
399 paint
.setTypeface(run
.skia_face
.get());
400 paint
.setTextSize(SkIntToScalar(run
.font_size
));
401 paint
.setAntiAlias(run
.render_params
.antialiasing
);
402 SkPaint::FontMetrics metrics
;
403 paint
.getFontMetrics(&metrics
);
405 line
->size
.set_width(line
->size
.width() + segment
.width());
406 // TODO(dschuyler): Account for stylized baselines in string sizing.
407 max_descent_
= std::max(max_descent_
, metrics
.fDescent
);
408 // fAscent is always negative.
409 max_ascent_
= std::max(max_ascent_
, -metrics
.fAscent
);
412 rtl_segments_
.push_back(
413 SegmentHandle(lines_
.size() - 1, line
->segments
.size() - 1));
414 // If this is the last segment of an RTL run, reprocess the text-space x
415 // ranges of all segments from the run.
416 if (segment
.char_range
.end() == run
.range
.end())
417 UpdateRTLSegmentRanges();
419 text_x_
+= segment
.width();
420 available_width_
-= segment
.width();
423 // Finds the end position |end_pos| in |segment| where the preceding width is
424 // no larger than |available_width_|.
425 size_t GetCutoffPos(const internal::LineSegment
& segment
) const {
426 DCHECK(!segment
.char_range
.is_empty());
427 const internal::TextRunHarfBuzz
& run
= *(run_list_
.runs()[segment
.run
]);
428 size_t end_pos
= segment
.char_range
.start();
430 while (end_pos
< segment
.char_range
.end()) {
431 const SkScalar char_width
=
432 run
.GetGlyphWidthForCharRange(Range(end_pos
, end_pos
+ 1));
433 if (width
+ char_width
> available_width_
)
439 const size_t valid_end_pos
= FindValidBoundaryBefore(text_
, end_pos
);
440 if (end_pos
!= valid_end_pos
) {
441 end_pos
= valid_end_pos
;
442 width
= run
.GetGlyphWidthForCharRange(
443 Range(segment
.char_range
.start(), end_pos
));
446 // |max_width_| might be smaller than a single character. In this case we
447 // need to put at least one character in the line. Note that, we should
448 // not separate surrogate pair or combining characters.
449 // See RenderTextTest.Multiline_MinWidth for an example.
450 if (width
== 0 && available_width_
== max_width_
)
451 end_pos
= FindValidBoundaryAfter(text_
, end_pos
+ 1);
456 // Gets the glyph width for |word_range|, and splits the |word| into different
457 // segments based on its runs.
458 SkScalar
GetWordWidth(const Range
& word_range
,
459 std::vector
<internal::LineSegment
>* segments
) const {
461 if (word_range
.is_empty() || segments
== nullptr)
463 size_t run_start_index
= run_list_
.GetRunIndexAt(word_range
.start());
464 size_t run_end_index
= run_list_
.GetRunIndexAt(word_range
.end() - 1);
466 for (size_t i
= run_start_index
; i
<= run_end_index
; i
++) {
467 const internal::TextRunHarfBuzz
& run
= *(run_list_
.runs()[i
]);
468 const Range char_range
= run
.range
.Intersect(word_range
);
469 DCHECK(!char_range
.is_empty());
470 const SkScalar char_width
= run
.GetGlyphWidthForCharRange(char_range
);
473 internal::LineSegment segment
;
475 segment
.char_range
= char_range
;
476 segment
.x_range
= RangeF(SkScalarToFloat(text_x_
+ width
- char_width
),
477 SkScalarToFloat(text_x_
+ width
));
478 segments
->push_back(segment
);
483 // RTL runs are broken in logical order but displayed in visual order. To find
484 // the text-space coordinate (where it would fall in a single-line text)
485 // |x_range| of RTL segments, segment widths are applied in reverse order.
486 // e.g. {[5, 10], [10, 40]} will become {[35, 40], [5, 35]}.
487 void UpdateRTLSegmentRanges() {
488 if (rtl_segments_
.empty())
490 float x
= SegmentFromHandle(rtl_segments_
[0])->x_range
.start();
491 for (size_t i
= rtl_segments_
.size(); i
> 0; --i
) {
492 internal::LineSegment
* segment
= SegmentFromHandle(rtl_segments_
[i
- 1]);
493 const float segment_width
= segment
->width();
494 segment
->x_range
= RangeF(x
, x
+ segment_width
);
497 rtl_segments_
.clear();
500 const SkScalar max_width_
;
501 const int min_baseline_
;
502 const float min_height_
;
503 const WordWrapBehavior word_wrap_behavior_
;
504 const base::string16
& text_
;
505 const BreakList
<size_t>* const words_
;
506 const internal::TextRunList
& run_list_
;
508 // Stores the resulting lines.
509 std::vector
<internal::Line
> lines_
;
514 // Text space x coordinates of the next segment to be added.
516 // Stores available width in the current line.
517 SkScalar available_width_
;
519 // Size of the multiline text, not including the currently processed line.
522 // The current RTL run segments, to be applied by |UpdateRTLSegmentRanges()|.
523 std::vector
<SegmentHandle
> rtl_segments_
;
525 DISALLOW_COPY_AND_ASSIGN(HarfBuzzLineBreaker
);
528 // Function object for case insensitive string comparison.
529 struct CaseInsensitiveCompare
{
530 bool operator() (const std::string
& a
, const std::string
& b
) const {
531 return base::strncasecmp(a
.c_str(), b
.c_str(), b
.length()) < 0;
539 TextRunHarfBuzz::TextRunHarfBuzz()
541 preceding_run_widths(0.0f
),
544 script(USCRIPT_INVALID_CODE
),
545 glyph_count(static_cast<size_t>(-1)),
551 diagonal_strike(false),
555 TextRunHarfBuzz::~TextRunHarfBuzz() {}
557 Range
TextRunHarfBuzz::CharRangeToGlyphRange(const Range
& char_range
) const {
558 DCHECK(range
.Contains(char_range
));
559 DCHECK(!char_range
.is_reversed());
560 DCHECK(!char_range
.is_empty());
565 GetClusterAt(char_range
.start(), &temp_range
, &start_glyphs
);
566 GetClusterAt(char_range
.end() - 1, &temp_range
, &end_glyphs
);
568 return is_rtl
? Range(end_glyphs
.start(), start_glyphs
.end()) :
569 Range(start_glyphs
.start(), end_glyphs
.end());
572 size_t TextRunHarfBuzz::CountMissingGlyphs() const {
573 static const int kMissingGlyphId
= 0;
575 for (size_t i
= 0; i
< glyph_count
; ++i
)
576 missing
+= (glyphs
[i
] == kMissingGlyphId
) ? 1 : 0;
580 void TextRunHarfBuzz::GetClusterAt(size_t pos
,
582 Range
* glyphs
) const {
583 DCHECK(range
.Contains(Range(pos
, pos
+ 1)));
587 if (glyph_count
== 0) {
594 GetClusterAtImpl(pos
, range
, glyph_to_char
.rbegin(), glyph_to_char
.rend(),
595 true, chars
, glyphs
);
599 GetClusterAtImpl(pos
, range
, glyph_to_char
.begin(), glyph_to_char
.end(),
600 false, chars
, glyphs
);
603 RangeF
TextRunHarfBuzz::GetGraphemeBounds(
604 base::i18n::BreakIterator
* grapheme_iterator
,
606 DCHECK_LT(text_index
, range
.end());
607 if (glyph_count
== 0)
608 return RangeF(preceding_run_widths
, preceding_run_widths
+ width
);
612 GetClusterAt(text_index
, &chars
, &glyphs
);
613 const float cluster_begin_x
= positions
[glyphs
.start()].x();
614 const float cluster_end_x
= glyphs
.end() < glyph_count
?
615 positions
[glyphs
.end()].x() : SkFloatToScalar(width
);
617 // A cluster consists of a number of code points and corresponds to a number
618 // of glyphs that should be drawn together. A cluster can contain multiple
619 // graphemes. In order to place the cursor at a grapheme boundary inside the
620 // cluster, we simply divide the cluster width by the number of graphemes.
621 if (chars
.length() > 1 && grapheme_iterator
) {
624 for (size_t i
= chars
.start(); i
< chars
.end(); ++i
) {
625 if (grapheme_iterator
->IsGraphemeBoundary(i
)) {
634 before
= total
- before
- 1;
635 DCHECK_GE(before
, 0);
636 DCHECK_LT(before
, total
);
637 const int cluster_width
= cluster_end_x
- cluster_begin_x
;
638 const int grapheme_begin_x
= cluster_begin_x
+ static_cast<int>(0.5f
+
639 cluster_width
* before
/ static_cast<float>(total
));
640 const int grapheme_end_x
= cluster_begin_x
+ static_cast<int>(0.5f
+
641 cluster_width
* (before
+ 1) / static_cast<float>(total
));
642 return RangeF(preceding_run_widths
+ grapheme_begin_x
,
643 preceding_run_widths
+ grapheme_end_x
);
647 return RangeF(preceding_run_widths
+ cluster_begin_x
,
648 preceding_run_widths
+ cluster_end_x
);
651 SkScalar
TextRunHarfBuzz::GetGlyphWidthForCharRange(
652 const Range
& char_range
) const {
653 if (char_range
.is_empty())
656 DCHECK(range
.Contains(char_range
));
657 Range glyph_range
= CharRangeToGlyphRange(char_range
);
658 return ((glyph_range
.end() == glyph_count
)
659 ? SkFloatToScalar(width
)
660 : positions
[glyph_range
.end()].x()) -
661 positions
[glyph_range
.start()].x();
664 TextRunList::TextRunList() : width_(0.0f
) {}
666 TextRunList::~TextRunList() {}
668 void TextRunList::Reset() {
673 void TextRunList::InitIndexMap() {
674 if (runs_
.size() == 1) {
675 visual_to_logical_
= logical_to_visual_
= std::vector
<int32_t>(1, 0);
678 const size_t num_runs
= runs_
.size();
679 std::vector
<UBiDiLevel
> levels(num_runs
);
680 for (size_t i
= 0; i
< num_runs
; ++i
)
681 levels
[i
] = runs_
[i
]->level
;
682 visual_to_logical_
.resize(num_runs
);
683 ubidi_reorderVisual(&levels
[0], num_runs
, &visual_to_logical_
[0]);
684 logical_to_visual_
.resize(num_runs
);
685 ubidi_reorderLogical(&levels
[0], num_runs
, &logical_to_visual_
[0]);
688 void TextRunList::ComputePrecedingRunWidths() {
689 // Precalculate run width information.
691 for (size_t i
= 0; i
< runs_
.size(); ++i
) {
692 TextRunHarfBuzz
* run
= runs_
[visual_to_logical_
[i
]];
693 run
->preceding_run_widths
= width_
;
694 width_
+= run
->width
;
698 size_t TextRunList::GetRunIndexAt(size_t position
) const {
699 for (size_t i
= 0; i
< runs_
.size(); ++i
) {
700 if (runs_
[i
]->range
.start() <= position
&& runs_
[i
]->range
.end() > position
)
706 } // namespace internal
708 RenderTextHarfBuzz::RenderTextHarfBuzz()
710 update_layout_run_list_(false),
711 update_display_run_list_(false),
712 update_grapheme_iterator_(false),
713 update_display_text_(false),
714 glyph_width_for_test_(0u) {
715 set_truncate_length(kMaxTextLength
);
718 RenderTextHarfBuzz::~RenderTextHarfBuzz() {}
720 scoped_ptr
<RenderText
> RenderTextHarfBuzz::CreateInstanceOfSameType() const {
721 return make_scoped_ptr(new RenderTextHarfBuzz
);
724 bool RenderTextHarfBuzz::MultilineSupported() const {
728 const base::string16
& RenderTextHarfBuzz::GetDisplayText() {
729 // TODO(oshima): Consider supporting eliding multi-line text.
730 // This requires max_line support first.
732 elide_behavior() == NO_ELIDE
||
733 elide_behavior() == FADE_TAIL
) {
734 // Call UpdateDisplayText to clear |display_text_| and |text_elided_|
735 // on the RenderText class.
736 UpdateDisplayText(0);
737 update_display_text_
= false;
738 display_run_list_
.reset();
739 return layout_text();
742 EnsureLayoutRunList();
743 DCHECK(!update_display_text_
);
744 return text_elided() ? display_text() : layout_text();
747 Size
RenderTextHarfBuzz::GetStringSize() {
748 const SizeF size_f
= GetStringSizeF();
749 return Size(std::ceil(size_f
.width()), size_f
.height());
752 SizeF
RenderTextHarfBuzz::GetStringSizeF() {
757 SelectionModel
RenderTextHarfBuzz::FindCursorPosition(const Point
& point
) {
760 int x
= ToTextPoint(point
).x();
762 size_t run_index
= GetRunContainingXCoord(x
, &offset
);
764 internal::TextRunList
* run_list
= GetRunList();
765 if (run_index
>= run_list
->size())
766 return EdgeSelectionModel((x
< 0) ? CURSOR_LEFT
: CURSOR_RIGHT
);
767 const internal::TextRunHarfBuzz
& run
= *run_list
->runs()[run_index
];
768 for (size_t i
= 0; i
< run
.glyph_count
; ++i
) {
770 i
+ 1 == run
.glyph_count
? run
.width
: run
.positions
[i
+ 1].x();
771 const SkScalar middle
= (end
+ run
.positions
[i
].x()) / 2;
773 if (offset
< middle
) {
774 return SelectionModel(DisplayIndexToTextIndex(
775 run
.glyph_to_char
[i
] + (run
.is_rtl
? 1 : 0)),
776 (run
.is_rtl
? CURSOR_BACKWARD
: CURSOR_FORWARD
));
779 return SelectionModel(DisplayIndexToTextIndex(
780 run
.glyph_to_char
[i
] + (run
.is_rtl
? 0 : 1)),
781 (run
.is_rtl
? CURSOR_FORWARD
: CURSOR_BACKWARD
));
784 return EdgeSelectionModel(CURSOR_RIGHT
);
787 std::vector
<RenderText::FontSpan
> RenderTextHarfBuzz::GetFontSpansForTesting() {
790 internal::TextRunList
* run_list
= GetRunList();
791 std::vector
<RenderText::FontSpan
> spans
;
792 for (auto* run
: run_list
->runs()) {
793 SkString family_name
;
794 run
->skia_face
->getFamilyName(&family_name
);
795 Font
font(family_name
.c_str(), run
->font_size
);
796 spans
.push_back(RenderText::FontSpan(
798 Range(DisplayIndexToTextIndex(run
->range
.start()),
799 DisplayIndexToTextIndex(run
->range
.end()))));
805 Range
RenderTextHarfBuzz::GetGlyphBounds(size_t index
) {
807 const size_t run_index
=
808 GetRunContainingCaret(SelectionModel(index
, CURSOR_FORWARD
));
809 internal::TextRunList
* run_list
= GetRunList();
810 // Return edge bounds if the index is invalid or beyond the layout text size.
811 if (run_index
>= run_list
->size())
812 return Range(GetStringSize().width());
813 const size_t layout_index
= TextIndexToDisplayIndex(index
);
814 internal::TextRunHarfBuzz
* run
= run_list
->runs()[run_index
];
816 run
->GetGraphemeBounds(GetGraphemeIterator(), layout_index
);
817 // If cursor is enabled, extend the last glyph up to the rightmost cursor
818 // position since clients expect them to be contiguous.
819 if (cursor_enabled() && run_index
== run_list
->size() - 1 &&
820 index
== (run
->is_rtl
? run
->range
.start() : run
->range
.end() - 1))
821 bounds
.set_end(std::ceil(bounds
.end()));
822 return run
->is_rtl
? RangeF(bounds
.end(), bounds
.start()).Round()
826 int RenderTextHarfBuzz::GetDisplayTextBaseline() {
828 return lines()[0].baseline
;
831 SelectionModel
RenderTextHarfBuzz::AdjacentCharSelectionModel(
832 const SelectionModel
& selection
,
833 VisualCursorDirection direction
) {
834 DCHECK(!update_display_run_list_
);
836 internal::TextRunList
* run_list
= GetRunList();
837 internal::TextRunHarfBuzz
* run
;
839 size_t run_index
= GetRunContainingCaret(selection
);
840 if (run_index
>= run_list
->size()) {
841 // The cursor is not in any run: we're at the visual and logical edge.
842 SelectionModel edge
= EdgeSelectionModel(direction
);
843 if (edge
.caret_pos() == selection
.caret_pos())
845 int visual_index
= (direction
== CURSOR_RIGHT
) ? 0 : run_list
->size() - 1;
846 run
= run_list
->runs()[run_list
->visual_to_logical(visual_index
)];
848 // If the cursor is moving within the current run, just move it by one
849 // grapheme in the appropriate direction.
850 run
= run_list
->runs()[run_index
];
851 size_t caret
= selection
.caret_pos();
852 bool forward_motion
= run
->is_rtl
== (direction
== CURSOR_LEFT
);
853 if (forward_motion
) {
854 if (caret
< DisplayIndexToTextIndex(run
->range
.end())) {
855 caret
= IndexOfAdjacentGrapheme(caret
, CURSOR_FORWARD
);
856 return SelectionModel(caret
, CURSOR_BACKWARD
);
859 if (caret
> DisplayIndexToTextIndex(run
->range
.start())) {
860 caret
= IndexOfAdjacentGrapheme(caret
, CURSOR_BACKWARD
);
861 return SelectionModel(caret
, CURSOR_FORWARD
);
864 // The cursor is at the edge of a run; move to the visually adjacent run.
865 int visual_index
= run_list
->logical_to_visual(run_index
);
866 visual_index
+= (direction
== CURSOR_LEFT
) ? -1 : 1;
867 if (visual_index
< 0 || visual_index
>= static_cast<int>(run_list
->size()))
868 return EdgeSelectionModel(direction
);
869 run
= run_list
->runs()[run_list
->visual_to_logical(visual_index
)];
871 bool forward_motion
= run
->is_rtl
== (direction
== CURSOR_LEFT
);
872 return forward_motion
? FirstSelectionModelInsideRun(run
) :
873 LastSelectionModelInsideRun(run
);
876 SelectionModel
RenderTextHarfBuzz::AdjacentWordSelectionModel(
877 const SelectionModel
& selection
,
878 VisualCursorDirection direction
) {
880 return EdgeSelectionModel(direction
);
882 base::i18n::BreakIterator
iter(text(), base::i18n::BreakIterator::BREAK_WORD
);
883 bool success
= iter
.Init();
888 // Match OS specific word break behavior.
891 if (direction
== CURSOR_RIGHT
) {
892 pos
= std::min(selection
.caret_pos() + 1, text().length());
893 while (iter
.Advance()) {
895 if (iter
.IsWord() && pos
> selection
.caret_pos())
898 } else { // direction == CURSOR_LEFT
899 // Notes: We always iterate words from the beginning.
900 // This is probably fast enough for our usage, but we may
901 // want to modify WordIterator so that it can start from the
902 // middle of string and advance backwards.
903 pos
= std::max
<int>(selection
.caret_pos() - 1, 0);
904 while (iter
.Advance()) {
906 size_t begin
= iter
.pos() - iter
.GetString().length();
907 if (begin
== selection
.caret_pos()) {
908 // The cursor is at the beginning of a word.
909 // Move to previous word.
911 } else if (iter
.pos() >= selection
.caret_pos()) {
912 // The cursor is in the middle or at the end of a word.
913 // Move to the top of current word.
917 pos
= iter
.pos() - iter
.GetString().length();
921 return SelectionModel(pos
, CURSOR_FORWARD
);
923 internal::TextRunList
* run_list
= GetRunList();
924 SelectionModel
cur(selection
);
926 cur
= AdjacentCharSelectionModel(cur
, direction
);
927 size_t run
= GetRunContainingCaret(cur
);
928 if (run
== run_list
->size())
930 const bool is_forward
=
931 run_list
->runs()[run
]->is_rtl
== (direction
== CURSOR_LEFT
);
932 size_t cursor
= cur
.caret_pos();
933 if (is_forward
? iter
.IsEndOfWord(cursor
) : iter
.IsStartOfWord(cursor
))
940 std::vector
<Rect
> RenderTextHarfBuzz::GetSubstringBounds(const Range
& range
) {
941 DCHECK(!update_display_run_list_
);
942 DCHECK(Range(0, text().length()).Contains(range
));
943 Range
layout_range(TextIndexToDisplayIndex(range
.start()),
944 TextIndexToDisplayIndex(range
.end()));
945 DCHECK(Range(0, GetDisplayText().length()).Contains(layout_range
));
947 std::vector
<Rect
> rects
;
948 if (layout_range
.is_empty())
950 std::vector
<Range
> bounds
;
952 internal::TextRunList
* run_list
= GetRunList();
954 // Add a Range for each run/selection intersection.
955 for (size_t i
= 0; i
< run_list
->size(); ++i
) {
956 internal::TextRunHarfBuzz
* run
=
957 run_list
->runs()[run_list
->visual_to_logical(i
)];
958 Range intersection
= run
->range
.Intersect(layout_range
);
959 if (!intersection
.IsValid())
961 DCHECK(!intersection
.is_reversed());
962 const size_t left_index
=
963 run
->is_rtl
? intersection
.end() - 1 : intersection
.start();
964 const Range leftmost_character_x
=
965 run
->GetGraphemeBounds(GetGraphemeIterator(), left_index
).Round();
966 const size_t right_index
=
967 run
->is_rtl
? intersection
.start() : intersection
.end() - 1;
968 const Range rightmost_character_x
=
969 run
->GetGraphemeBounds(GetGraphemeIterator(), right_index
).Round();
970 Range
range_x(leftmost_character_x
.start(), rightmost_character_x
.end());
971 DCHECK(!range_x
.is_reversed());
972 if (range_x
.is_empty())
975 // Union this with the last range if they're adjacent.
976 DCHECK(bounds
.empty() || bounds
.back().GetMax() <= range_x
.GetMin());
977 if (!bounds
.empty() && bounds
.back().GetMax() == range_x
.GetMin()) {
978 range_x
= Range(bounds
.back().GetMin(), range_x
.GetMax());
981 bounds
.push_back(range_x
);
983 for (Range
& bound
: bounds
) {
984 std::vector
<Rect
> current_rects
= TextBoundsToViewBounds(bound
);
985 rects
.insert(rects
.end(), current_rects
.begin(), current_rects
.end());
990 size_t RenderTextHarfBuzz::TextIndexToDisplayIndex(size_t index
) {
991 return TextIndexToGivenTextIndex(GetDisplayText(), index
);
994 size_t RenderTextHarfBuzz::DisplayIndexToTextIndex(size_t index
) {
997 const size_t text_index
= UTF16OffsetToIndex(text(), 0, index
);
998 DCHECK_LE(text_index
, text().length());
1002 bool RenderTextHarfBuzz::IsValidCursorIndex(size_t index
) {
1003 if (index
== 0 || index
== text().length())
1005 if (!IsValidLogicalIndex(index
))
1007 base::i18n::BreakIterator
* grapheme_iterator
= GetGraphemeIterator();
1008 return !grapheme_iterator
|| grapheme_iterator
->IsGraphemeBoundary(index
);
1011 void RenderTextHarfBuzz::OnLayoutTextAttributeChanged(bool text_changed
) {
1012 update_layout_run_list_
= true;
1013 OnDisplayTextAttributeChanged();
1016 void RenderTextHarfBuzz::OnDisplayTextAttributeChanged() {
1017 update_display_text_
= true;
1018 update_grapheme_iterator_
= true;
1021 void RenderTextHarfBuzz::EnsureLayout() {
1022 EnsureLayoutRunList();
1024 if (update_display_run_list_
) {
1025 DCHECK(text_elided());
1026 const base::string16
& display_text
= GetDisplayText();
1027 display_run_list_
.reset(new internal::TextRunList
);
1029 if (!display_text
.empty()) {
1030 TRACE_EVENT0("ui", "RenderTextHarfBuzz:EnsureLayout1");
1032 ItemizeTextToRuns(display_text
, display_run_list_
.get());
1034 // TODO(ckocagil): Remove ScopedTracker below once crbug.com/441028 is
1036 tracked_objects::ScopedTracker
tracking_profile(
1037 FROM_HERE_WITH_EXPLICIT_FUNCTION("441028 ShapeRunList() 1"));
1038 ShapeRunList(display_text
, display_run_list_
.get());
1040 update_display_run_list_
= false;
1042 std::vector
<internal::Line
> empty_lines
;
1043 set_lines(&empty_lines
);
1046 if (lines().empty()) {
1047 // TODO(ckocagil): Remove ScopedTracker below once crbug.com/441028 is
1049 scoped_ptr
<tracked_objects::ScopedTracker
> tracking_profile(
1050 new tracked_objects::ScopedTracker(
1051 FROM_HERE_WITH_EXPLICIT_FUNCTION("441028 HarfBuzzLineBreaker")));
1053 internal::TextRunList
* run_list
= GetRunList();
1054 HarfBuzzLineBreaker
line_breaker(
1055 display_rect().width(), font_list().GetBaseline(),
1056 std::max(font_list().GetHeight(), min_line_height()),
1057 word_wrap_behavior(), GetDisplayText(),
1058 multiline() ? &GetLineBreaks() : nullptr, *run_list
);
1060 tracking_profile
.reset();
1063 line_breaker
.ConstructMultiLines();
1065 line_breaker
.ConstructSingleLine();
1066 std::vector
<internal::Line
> lines
;
1067 line_breaker
.FinalizeLines(&lines
, &total_size_
);
1072 void RenderTextHarfBuzz::DrawVisualText(Canvas
* canvas
) {
1073 internal::SkiaTextRenderer
renderer(canvas
);
1074 DrawVisualTextInternal(&renderer
);
1077 void RenderTextHarfBuzz::DrawVisualTextInternal(
1078 internal::SkiaTextRenderer
* renderer
) {
1079 DCHECK(!update_layout_run_list_
);
1080 DCHECK(!update_display_run_list_
);
1081 DCHECK(!update_display_text_
);
1082 if (lines().empty())
1085 ApplyFadeEffects(renderer
);
1086 ApplyTextShadows(renderer
);
1087 ApplyCompositionAndSelectionStyles();
1089 internal::TextRunList
* run_list
= GetRunList();
1090 for (size_t i
= 0; i
< lines().size(); ++i
) {
1091 const internal::Line
& line
= lines()[i
];
1092 const Vector2d origin
= GetLineOffset(i
) + Vector2d(0, line
.baseline
);
1093 SkScalar preceding_segment_widths
= 0;
1094 for (const internal::LineSegment
& segment
: line
.segments
) {
1095 const internal::TextRunHarfBuzz
& run
= *run_list
->runs()[segment
.run
];
1096 renderer
->SetTypeface(run
.skia_face
.get());
1097 renderer
->SetTextSize(SkIntToScalar(run
.font_size
));
1098 renderer
->SetFontRenderParams(run
.render_params
,
1099 subpixel_rendering_suppressed());
1100 Range glyphs_range
= run
.CharRangeToGlyphRange(segment
.char_range
);
1101 scoped_ptr
<SkPoint
[]> positions(new SkPoint
[glyphs_range
.length()]);
1102 SkScalar offset_x
= preceding_segment_widths
-
1103 ((glyphs_range
.GetMin() != 0)
1104 ? run
.positions
[glyphs_range
.GetMin()].x()
1106 for (size_t j
= 0; j
< glyphs_range
.length(); ++j
) {
1107 positions
[j
] = run
.positions
[(glyphs_range
.is_reversed()) ?
1108 (glyphs_range
.start() - j
) :
1109 (glyphs_range
.start() + j
)];
1110 positions
[j
].offset(SkIntToScalar(origin
.x()) + offset_x
,
1111 SkIntToScalar(origin
.y() + run
.baseline_offset
));
1113 for (BreakList
<SkColor
>::const_iterator it
=
1114 colors().GetBreak(segment
.char_range
.start());
1115 it
!= colors().breaks().end() &&
1116 it
->first
< segment
.char_range
.end();
1118 const Range intersection
=
1119 colors().GetRange(it
).Intersect(segment
.char_range
);
1120 const Range colored_glyphs
= run
.CharRangeToGlyphRange(intersection
);
1121 // The range may be empty if a portion of a multi-character grapheme is
1122 // selected, yielding two colors for a single glyph. For now, this just
1123 // paints the glyph with a single style, but it should paint it twice,
1124 // clipped according to selection bounds. See http://crbug.com/366786
1125 if (colored_glyphs
.is_empty())
1128 renderer
->SetForegroundColor(it
->second
);
1129 renderer
->DrawPosText(
1130 &positions
[colored_glyphs
.start() - glyphs_range
.start()],
1131 &run
.glyphs
[colored_glyphs
.start()], colored_glyphs
.length());
1132 int start_x
= SkScalarRoundToInt(
1133 positions
[colored_glyphs
.start() - glyphs_range
.start()].x());
1134 int end_x
= SkScalarRoundToInt(
1135 (colored_glyphs
.end() == glyphs_range
.end())
1136 ? (SkFloatToScalar(segment
.width()) + preceding_segment_widths
+
1137 SkIntToScalar(origin
.x()))
1138 : positions
[colored_glyphs
.end() - glyphs_range
.start()].x());
1139 renderer
->DrawDecorations(start_x
, origin
.y(), end_x
- start_x
,
1140 run
.underline
, run
.strike
,
1141 run
.diagonal_strike
);
1143 preceding_segment_widths
+= SkFloatToScalar(segment
.width());
1147 renderer
->EndDiagonalStrike();
1149 UndoCompositionAndSelectionStyles();
1152 size_t RenderTextHarfBuzz::GetRunContainingCaret(
1153 const SelectionModel
& caret
) {
1154 DCHECK(!update_display_run_list_
);
1155 size_t layout_position
= TextIndexToDisplayIndex(caret
.caret_pos());
1156 LogicalCursorDirection affinity
= caret
.caret_affinity();
1157 internal::TextRunList
* run_list
= GetRunList();
1158 for (size_t i
= 0; i
< run_list
->size(); ++i
) {
1159 internal::TextRunHarfBuzz
* run
= run_list
->runs()[i
];
1160 if (RangeContainsCaret(run
->range
, layout_position
, affinity
))
1163 return run_list
->size();
1166 size_t RenderTextHarfBuzz::GetRunContainingXCoord(float x
,
1167 float* offset
) const {
1168 DCHECK(!update_display_run_list_
);
1169 const internal::TextRunList
* run_list
= GetRunList();
1171 return run_list
->size();
1172 // Find the text run containing the argument point (assumed already offset).
1173 float current_x
= 0;
1174 for (size_t i
= 0; i
< run_list
->size(); ++i
) {
1175 size_t run
= run_list
->visual_to_logical(i
);
1176 current_x
+= run_list
->runs()[run
]->width
;
1177 if (x
< current_x
) {
1178 *offset
= x
- (current_x
- run_list
->runs()[run
]->width
);
1182 return run_list
->size();
1185 SelectionModel
RenderTextHarfBuzz::FirstSelectionModelInsideRun(
1186 const internal::TextRunHarfBuzz
* run
) {
1187 size_t position
= DisplayIndexToTextIndex(run
->range
.start());
1188 position
= IndexOfAdjacentGrapheme(position
, CURSOR_FORWARD
);
1189 return SelectionModel(position
, CURSOR_BACKWARD
);
1192 SelectionModel
RenderTextHarfBuzz::LastSelectionModelInsideRun(
1193 const internal::TextRunHarfBuzz
* run
) {
1194 size_t position
= DisplayIndexToTextIndex(run
->range
.end());
1195 position
= IndexOfAdjacentGrapheme(position
, CURSOR_BACKWARD
);
1196 return SelectionModel(position
, CURSOR_FORWARD
);
1199 void RenderTextHarfBuzz::ItemizeTextToRuns(
1200 const base::string16
& text
,
1201 internal::TextRunList
* run_list_out
) {
1202 DCHECK_NE(0U, text
.length());
1204 // If ICU fails to itemize the text, we create a run that spans the entire
1205 // text. This is needed because leaving the runs set empty causes some clients
1206 // to misbehave since they expect non-zero text metrics from a non-empty text.
1207 base::i18n::BiDiLineIterator bidi_iterator
;
1208 if (!bidi_iterator
.Open(text
, GetTextDirection(text
))) {
1209 internal::TextRunHarfBuzz
* run
= new internal::TextRunHarfBuzz
;
1210 run
->range
= Range(0, text
.length());
1211 run_list_out
->add(run
);
1212 run_list_out
->InitIndexMap();
1216 // Temporarily apply composition underlines and selection colors.
1217 ApplyCompositionAndSelectionStyles();
1219 // Build the run list from the script items and ranged styles and baselines.
1220 // Use an empty color BreakList to avoid breaking runs at color boundaries.
1221 BreakList
<SkColor
> empty_colors
;
1222 empty_colors
.SetMax(text
.length());
1223 DCHECK_LE(text
.size(), baselines().max());
1224 for (const BreakList
<bool>& style
: styles())
1225 DCHECK_LE(text
.size(), style
.max());
1226 internal::StyleIterator
style(empty_colors
, baselines(), styles());
1228 for (size_t run_break
= 0; run_break
< text
.length();) {
1229 internal::TextRunHarfBuzz
* run
= new internal::TextRunHarfBuzz
;
1230 run
->range
.set_start(run_break
);
1231 run
->font_style
= (style
.style(BOLD
) ? Font::BOLD
: 0) |
1232 (style
.style(ITALIC
) ? Font::ITALIC
: 0);
1233 run
->baseline_type
= style
.baseline();
1234 run
->strike
= style
.style(STRIKE
);
1235 run
->diagonal_strike
= style
.style(DIAGONAL_STRIKE
);
1236 run
->underline
= style
.style(UNDERLINE
);
1237 int32 script_item_break
= 0;
1238 bidi_iterator
.GetLogicalRun(run_break
, &script_item_break
, &run
->level
);
1239 // Odd BiDi embedding levels correspond to RTL runs.
1240 run
->is_rtl
= (run
->level
% 2) == 1;
1241 // Find the length and script of this script run.
1242 script_item_break
= ScriptInterval(text
, run_break
,
1243 script_item_break
- run_break
, &run
->script
) + run_break
;
1245 // Find the next break and advance the iterators as needed.
1246 run_break
= std::min(
1247 static_cast<size_t>(script_item_break
),
1248 TextIndexToGivenTextIndex(text
, style
.GetRange().end()));
1250 // Break runs at certain characters that need to be rendered separately to
1251 // prevent either an unusual character from forcing a fallback font on the
1252 // entire run, or brackets from being affected by a fallback font.
1253 // http://crbug.com/278913, http://crbug.com/396776
1254 if (run_break
> run
->range
.start())
1255 run_break
= FindRunBreakingCharacter(text
, run
->range
.start(), run_break
);
1257 DCHECK(IsValidCodePointIndex(text
, run_break
));
1258 style
.UpdatePosition(DisplayIndexToTextIndex(run_break
));
1259 run
->range
.set_end(run_break
);
1261 run_list_out
->add(run
);
1264 // Undo the temporarily applied composition underlines and selection colors.
1265 UndoCompositionAndSelectionStyles();
1267 run_list_out
->InitIndexMap();
1270 bool RenderTextHarfBuzz::CompareFamily(
1271 const base::string16
& text
,
1272 const std::string
& family
,
1273 const gfx::FontRenderParams
& render_params
,
1274 internal::TextRunHarfBuzz
* run
,
1275 std::string
* best_family
,
1276 gfx::FontRenderParams
* best_render_params
,
1277 size_t* best_missing_glyphs
) {
1278 if (!ShapeRunWithFont(text
, family
, render_params
, run
))
1281 const size_t missing_glyphs
= run
->CountMissingGlyphs();
1282 if (missing_glyphs
< *best_missing_glyphs
) {
1283 *best_family
= family
;
1284 *best_render_params
= render_params
;
1285 *best_missing_glyphs
= missing_glyphs
;
1287 return missing_glyphs
== 0;
1290 void RenderTextHarfBuzz::ShapeRunList(const base::string16
& text
,
1291 internal::TextRunList
* run_list
) {
1292 for (auto* run
: run_list
->runs())
1293 ShapeRun(text
, run
);
1294 run_list
->ComputePrecedingRunWidths();
1297 void RenderTextHarfBuzz::ShapeRun(const base::string16
& text
,
1298 internal::TextRunHarfBuzz
* run
) {
1299 const Font
& primary_font
= font_list().GetPrimaryFont();
1300 const std::string primary_family
= primary_font
.GetFontName();
1301 run
->font_size
= primary_font
.GetFontSize();
1302 run
->baseline_offset
= 0;
1303 if (run
->baseline_type
!= NORMAL_BASELINE
) {
1304 // Calculate a slightly smaller font. The ratio here is somewhat arbitrary.
1305 // Proportions from 5/9 to 5/7 all look pretty good.
1306 const float ratio
= 5.0f
/ 9.0f
;
1307 run
->font_size
= gfx::ToRoundedInt(primary_font
.GetFontSize() * ratio
);
1308 switch (run
->baseline_type
) {
1310 run
->baseline_offset
=
1311 primary_font
.GetCapHeight() - primary_font
.GetHeight();
1314 run
->baseline_offset
=
1315 gfx::ToRoundedInt(primary_font
.GetCapHeight() * ratio
) -
1316 primary_font
.GetCapHeight();
1319 run
->baseline_offset
=
1320 primary_font
.GetHeight() - primary_font
.GetBaseline();
1322 case INFERIOR
: // Fall through.
1328 std::string best_family
;
1329 FontRenderParams best_render_params
;
1330 size_t best_missing_glyphs
= std::numeric_limits
<size_t>::max();
1332 for (const Font
& font
: font_list().GetFonts()) {
1333 if (CompareFamily(text
, font
.GetFontName(), font
.GetFontRenderParams(),
1334 run
, &best_family
, &best_render_params
,
1335 &best_missing_glyphs
))
1340 Font uniscribe_font
;
1341 std::string uniscribe_family
;
1342 const base::char16
* run_text
= &(text
[run
->range
.start()]);
1343 if (GetUniscribeFallbackFont(primary_font
, run_text
, run
->range
.length(),
1345 uniscribe_family
= uniscribe_font
.GetFontName();
1346 if (CompareFamily(text
, uniscribe_family
,
1347 uniscribe_font
.GetFontRenderParams(), run
,
1348 &best_family
, &best_render_params
, &best_missing_glyphs
))
1353 std::vector
<std::string
> fallback_families
=
1354 GetFallbackFontFamilies(primary_family
);
1357 // Append fonts in the fallback list of the Uniscribe font.
1358 if (!uniscribe_family
.empty()) {
1359 std::vector
<std::string
> uniscribe_fallbacks
=
1360 GetFallbackFontFamilies(uniscribe_family
);
1361 fallback_families
.insert(fallback_families
.end(),
1362 uniscribe_fallbacks
.begin(), uniscribe_fallbacks
.end());
1365 // Add Segoe UI and its associated linked fonts to the fallback font list to
1366 // ensure that the fallback list covers the basic cases.
1367 // http://crbug.com/467459. On some Windows configurations the default font
1368 // could be a raster font like System, which would not give us a reasonable
1369 // fallback font list.
1370 if (!base::LowerCaseEqualsASCII(primary_family
, "segoe ui") &&
1371 !base::LowerCaseEqualsASCII(uniscribe_family
, "segoe ui")) {
1372 std::vector
<std::string
> default_fallback_families
=
1373 GetFallbackFontFamilies("Segoe UI");
1374 fallback_families
.insert(fallback_families
.end(),
1375 default_fallback_families
.begin(), default_fallback_families
.end());
1379 // Use a set to track the fallback fonts and avoid duplicate entries.
1380 std::set
<std::string
, CaseInsensitiveCompare
> fallback_fonts
;
1382 // Try shaping with the fallback fonts.
1383 for (const auto& family
: fallback_families
) {
1384 if (family
== primary_family
)
1387 if (family
== uniscribe_family
)
1390 if (fallback_fonts
.find(family
) != fallback_fonts
.end())
1393 fallback_fonts
.insert(family
);
1395 FontRenderParamsQuery query
;
1396 query
.families
.push_back(family
);
1397 query
.pixel_size
= run
->font_size
;
1398 query
.style
= run
->font_style
;
1399 FontRenderParams fallback_render_params
= GetFontRenderParams(query
, NULL
);
1400 if (CompareFamily(text
, family
, fallback_render_params
, run
, &best_family
,
1401 &best_render_params
, &best_missing_glyphs
))
1405 if (!best_family
.empty() &&
1406 (best_family
== run
->family
||
1407 ShapeRunWithFont(text
, best_family
, best_render_params
, run
)))
1410 run
->glyph_count
= 0;
1414 bool RenderTextHarfBuzz::ShapeRunWithFont(const base::string16
& text
,
1415 const std::string
& font_family
,
1416 const FontRenderParams
& params
,
1417 internal::TextRunHarfBuzz
* run
) {
1418 skia::RefPtr
<SkTypeface
> skia_face
=
1419 internal::CreateSkiaTypeface(font_family
, run
->font_style
);
1420 if (skia_face
== NULL
)
1422 run
->skia_face
= skia_face
;
1423 run
->family
= font_family
;
1424 run
->render_params
= params
;
1426 hb_font_t
* harfbuzz_font
= CreateHarfBuzzFont(
1427 run
->skia_face
.get(), SkIntToScalar(run
->font_size
), run
->render_params
,
1428 subpixel_rendering_suppressed());
1430 // Create a HarfBuzz buffer and add the string to be shaped. The HarfBuzz
1431 // buffer holds our text, run information to be used by the shaping engine,
1432 // and the resulting glyph data.
1433 hb_buffer_t
* buffer
= hb_buffer_create();
1434 hb_buffer_add_utf16(buffer
, reinterpret_cast<const uint16
*>(text
.c_str()),
1435 text
.length(), run
->range
.start(), run
->range
.length());
1436 hb_buffer_set_script(buffer
, ICUScriptToHBScript(run
->script
));
1437 hb_buffer_set_direction(buffer
,
1438 run
->is_rtl
? HB_DIRECTION_RTL
: HB_DIRECTION_LTR
);
1439 // TODO(ckocagil): Should we determine the actual language?
1440 hb_buffer_set_language(buffer
, hb_language_get_default());
1443 // TODO(ckocagil): Remove ScopedTracker below once crbug.com/441028 is
1445 tracked_objects::ScopedTracker
tracking_profile(
1446 FROM_HERE_WITH_EXPLICIT_FUNCTION("441028 hb_shape()"));
1449 hb_shape(harfbuzz_font
, buffer
, NULL
, 0);
1452 // Populate the run fields with the resulting glyph data in the buffer.
1453 unsigned int glyph_count
= 0;
1454 hb_glyph_info_t
* infos
= hb_buffer_get_glyph_infos(buffer
, &glyph_count
);
1455 run
->glyph_count
= glyph_count
;
1456 hb_glyph_position_t
* hb_positions
=
1457 hb_buffer_get_glyph_positions(buffer
, NULL
);
1458 run
->glyphs
.reset(new uint16
[run
->glyph_count
]);
1459 run
->glyph_to_char
.resize(run
->glyph_count
);
1460 run
->positions
.reset(new SkPoint
[run
->glyph_count
]);
1463 for (size_t i
= 0; i
< run
->glyph_count
; ++i
) {
1464 DCHECK_LE(infos
[i
].codepoint
, std::numeric_limits
<uint16
>::max());
1465 run
->glyphs
[i
] = static_cast<uint16
>(infos
[i
].codepoint
);
1466 run
->glyph_to_char
[i
] = infos
[i
].cluster
;
1467 const SkScalar x_offset
= SkFixedToScalar(hb_positions
[i
].x_offset
);
1468 const SkScalar y_offset
= SkFixedToScalar(hb_positions
[i
].y_offset
);
1469 run
->positions
[i
].set(run
->width
+ x_offset
, -y_offset
);
1470 run
->width
+= (glyph_width_for_test_
> 0)
1471 ? glyph_width_for_test_
1472 : SkFixedToFloat(hb_positions
[i
].x_advance
);
1473 // Round run widths if subpixel positioning is off to match native behavior.
1474 if (!run
->render_params
.subpixel_positioning
)
1475 run
->width
= std::floor(run
->width
+ 0.5f
);
1478 hb_buffer_destroy(buffer
);
1479 hb_font_destroy(harfbuzz_font
);
1483 void RenderTextHarfBuzz::EnsureLayoutRunList() {
1484 if (update_layout_run_list_
) {
1485 layout_run_list_
.Reset();
1487 const base::string16
& text
= layout_text();
1488 if (!text
.empty()) {
1489 TRACE_EVENT0("ui", "RenderTextHarfBuzz:EnsureLayoutRunList");
1490 ItemizeTextToRuns(text
, &layout_run_list_
);
1492 // TODO(ckocagil): Remove ScopedTracker below once crbug.com/441028 is
1494 tracked_objects::ScopedTracker
tracking_profile(
1495 FROM_HERE_WITH_EXPLICIT_FUNCTION("441028 ShapeRunList() 2"));
1496 ShapeRunList(text
, &layout_run_list_
);
1499 std::vector
<internal::Line
> empty_lines
;
1500 set_lines(&empty_lines
);
1501 display_run_list_
.reset();
1502 update_display_text_
= true;
1503 update_layout_run_list_
= false;
1505 if (update_display_text_
) {
1506 UpdateDisplayText(multiline() ? 0 : layout_run_list_
.width());
1507 update_display_text_
= false;
1508 update_display_run_list_
= text_elided();
1512 base::i18n::BreakIterator
* RenderTextHarfBuzz::GetGraphemeIterator() {
1513 if (update_grapheme_iterator_
) {
1514 update_grapheme_iterator_
= false;
1515 grapheme_iterator_
.reset(new base::i18n::BreakIterator(
1517 base::i18n::BreakIterator::BREAK_CHARACTER
));
1518 if (!grapheme_iterator_
->Init())
1519 grapheme_iterator_
.reset();
1521 return grapheme_iterator_
.get();
1524 internal::TextRunList
* RenderTextHarfBuzz::GetRunList() {
1525 DCHECK(!update_layout_run_list_
);
1526 DCHECK(!update_display_run_list_
);
1527 return text_elided() ? display_run_list_
.get() : &layout_run_list_
;
1530 const internal::TextRunList
* RenderTextHarfBuzz::GetRunList() const {
1531 return const_cast<RenderTextHarfBuzz
*>(this)->GetRunList();