Implement MoveFileLocal (with creating a snapshot).
[chromium-blink-merge.git] / ui / gfx / render_text_harfbuzz.cc
bloba2610f3787288305adb7f9d3c7b07044d8391511
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"
7 #include <limits>
9 #include "base/i18n/bidi_line_iterator.h"
10 #include "base/i18n/break_iterator.h"
11 #include "base/i18n/char_iterator.h"
12 #include "base/profiler/scoped_tracker.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "base/trace_event/trace_event.h"
15 #include "third_party/harfbuzz-ng/src/hb.h"
16 #include "third_party/icu/source/common/unicode/ubidi.h"
17 #include "third_party/skia/include/core/SkColor.h"
18 #include "third_party/skia/include/core/SkTypeface.h"
19 #include "ui/gfx/canvas.h"
20 #include "ui/gfx/font_fallback.h"
21 #include "ui/gfx/font_render_params.h"
22 #include "ui/gfx/geometry/safe_integer_conversions.h"
23 #include "ui/gfx/harfbuzz_font_skia.h"
24 #include "ui/gfx/range/range_f.h"
25 #include "ui/gfx/utf16_indexing.h"
27 #if defined(OS_WIN)
28 #include "ui/gfx/font_fallback_win.h"
29 #endif
31 using gfx::internal::RoundRangeF;
33 namespace gfx {
35 namespace {
37 // Text length limit. Longer strings are slow and not fully tested.
38 const size_t kMaxTextLength = 10000;
40 // The maximum number of scripts a Unicode character can belong to. This value
41 // is arbitrarily chosen to be a good limit because it is unlikely for a single
42 // character to belong to more scripts.
43 const size_t kMaxScripts = 5;
45 // Returns true if characters of |block_code| may trigger font fallback.
46 // Dingbats and emoticons can be rendered through the color emoji font file,
47 // therefore it needs to be trigerred as fallbacks. See crbug.com/448909
48 bool IsUnusualBlockCode(UBlockCode block_code) {
49 return block_code == UBLOCK_GEOMETRIC_SHAPES ||
50 block_code == UBLOCK_MISCELLANEOUS_SYMBOLS ||
51 block_code == UBLOCK_DINGBATS ||
52 block_code == UBLOCK_EMOTICONS;
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,
64 size_t run_start,
65 size_t run_break) {
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')
72 return run_start + 1;
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();
88 return run_break;
91 // If the given scripts match, returns the one that isn't USCRIPT_COMMON or
92 // USCRIPT_INHERITED, i.e. the more specific one. Otherwise returns
93 // USCRIPT_INVALID_CODE.
94 UScriptCode ScriptIntersect(UScriptCode first, UScriptCode second) {
95 if (first == second ||
96 (second > USCRIPT_INVALID_CODE && second <= USCRIPT_INHERITED)) {
97 return first;
99 if (first > USCRIPT_INVALID_CODE && first <= USCRIPT_INHERITED)
100 return second;
101 return USCRIPT_INVALID_CODE;
104 // Writes the script and the script extensions of the character with the
105 // Unicode |codepoint|. Returns the number of written scripts.
106 int GetScriptExtensions(UChar32 codepoint, UScriptCode* scripts) {
107 UErrorCode icu_error = U_ZERO_ERROR;
108 // ICU documentation incorrectly states that the result of
109 // |uscript_getScriptExtensions| will contain the regular script property.
110 // Write the character's script property to the first element.
111 scripts[0] = uscript_getScript(codepoint, &icu_error);
112 if (U_FAILURE(icu_error))
113 return 0;
114 // Fill the rest of |scripts| with the extensions.
115 int count = uscript_getScriptExtensions(codepoint, scripts + 1,
116 kMaxScripts - 1, &icu_error);
117 if (U_FAILURE(icu_error))
118 count = 0;
119 return count + 1;
122 // Intersects the script extensions set of |codepoint| with |result| and writes
123 // to |result|, reading and updating |result_size|.
124 void ScriptSetIntersect(UChar32 codepoint,
125 UScriptCode* result,
126 size_t* result_size) {
127 UScriptCode scripts[kMaxScripts] = { USCRIPT_INVALID_CODE };
128 int count = GetScriptExtensions(codepoint, scripts);
130 size_t out_size = 0;
132 for (size_t i = 0; i < *result_size; ++i) {
133 for (int j = 0; j < count; ++j) {
134 UScriptCode intersection = ScriptIntersect(result[i], scripts[j]);
135 if (intersection != USCRIPT_INVALID_CODE) {
136 result[out_size++] = intersection;
137 break;
142 *result_size = out_size;
145 // Find the longest sequence of characters from 0 and up to |length| that
146 // have at least one common UScriptCode value. Writes the common script value to
147 // |script| and returns the length of the sequence. Takes the characters' script
148 // extensions into account. http://www.unicode.org/reports/tr24/#ScriptX
150 // Consider 3 characters with the script values {Kana}, {Hira, Kana}, {Kana}.
151 // Without script extensions only the first script in each set would be taken
152 // into account, resulting in 3 runs where 1 would be enough.
153 // TODO(ckocagil): Write a unit test for the case above.
154 int ScriptInterval(const base::string16& text,
155 size_t start,
156 size_t length,
157 UScriptCode* script) {
158 DCHECK_GT(length, 0U);
160 UScriptCode scripts[kMaxScripts] = { USCRIPT_INVALID_CODE };
162 base::i18n::UTF16CharIterator char_iterator(text.c_str() + start, length);
163 size_t scripts_size = GetScriptExtensions(char_iterator.get(), scripts);
164 *script = scripts[0];
166 while (char_iterator.Advance()) {
167 ScriptSetIntersect(char_iterator.get(), scripts, &scripts_size);
168 if (scripts_size == 0U)
169 return char_iterator.array_pos();
170 *script = scripts[0];
173 return length;
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,
188 Range range,
189 Iterator elements_begin,
190 Iterator elements_end,
191 bool reversed,
192 Range* chars,
193 Range* glyphs) {
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);
201 glyphs->set_start(
202 reversed ? elements_end - element : element - elements_begin);
203 if (reversed)
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 {
220 public:
221 HarfBuzzLineBreaker(size_t max_width,
222 int min_baseline,
223 float min_height,
224 bool multiline,
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 multiline_(multiline),
232 text_(text),
233 words_(words),
234 run_list_(run_list),
235 text_x_(0),
236 line_x_(0),
237 max_descent_(0),
238 max_ascent_(0) {
239 DCHECK_EQ(multiline_, (words_ != nullptr));
240 AdvanceLine();
243 // Breaks the run at given |run_index| into Line structs.
244 void AddRun(int run_index) {
245 const internal::TextRunHarfBuzz* run = run_list_.runs()[run_index];
246 base::char16 first_char = text_[run->range.start()];
247 if (multiline_ && first_char == '\n') {
248 AdvanceLine();
249 } else if (multiline_ && (line_x_ + SkFloatToScalar(run->width)) >
250 max_width_) {
251 BreakRun(run_index);
252 } else {
253 AddSegment(run_index, run->range, run->width);
257 // Finishes line breaking and outputs the results. Can be called at most once.
258 void Finalize(std::vector<internal::Line>* lines, SizeF* size) {
259 DCHECK(!lines_.empty());
260 // Add an empty line to finish the line size calculation and remove it.
261 AdvanceLine();
262 lines_.pop_back();
263 *size = total_size_;
264 lines->swap(lines_);
267 private:
268 // A (line index, segment index) pair that specifies a segment in |lines_|.
269 typedef std::pair<size_t, size_t> SegmentHandle;
271 internal::LineSegment* SegmentFromHandle(const SegmentHandle& handle) {
272 return &lines_[handle.first].segments[handle.second];
275 // Breaks a run into segments that fit in the last line in |lines_| and adds
276 // them. Adds a new Line to the back of |lines_| whenever a new segment can't
277 // be added without the Line's width exceeding |max_width_|.
278 void BreakRun(int run_index) {
279 const internal::TextRunHarfBuzz& run = *(run_list_.runs()[run_index]);
280 SkScalar width = 0;
281 size_t next_char = run.range.start();
283 // Break the run until it fits the current line.
284 while (next_char < run.range.end()) {
285 const size_t current_char = next_char;
286 const bool skip_line =
287 BreakRunAtWidth(run, current_char, &width, &next_char);
288 AddSegment(run_index, Range(current_char, next_char),
289 SkScalarToFloat(width));
290 if (skip_line)
291 AdvanceLine();
295 // Starting from |start_char|, finds a suitable line break position at or
296 // before available width using word break. If the current position is at the
297 // beginning of a line, this function will not roll back to |start_char| and
298 // |*next_char| will be greater than |start_char| (to avoid constructing empty
299 // lines).
300 // Returns whether to skip the line before |*next_char|.
301 // TODO(ckocagil): Check clusters to avoid breaking ligatures and diacritics.
302 // TODO(ckocagil): We might have to reshape after breaking at ligatures.
303 // See whether resolving the TODO above resolves this too.
304 // TODO(ckocagil): Do not reserve width for whitespace at the end of lines.
305 bool BreakRunAtWidth(const internal::TextRunHarfBuzz& run,
306 size_t start_char,
307 SkScalar* width,
308 size_t* next_char) {
309 DCHECK(words_);
310 DCHECK(run.range.Contains(Range(start_char, start_char + 1)));
311 SkScalar available_width = max_width_ - line_x_;
312 BreakList<size_t>::const_iterator word = words_->GetBreak(start_char);
313 BreakList<size_t>::const_iterator next_word = word + 1;
314 // Width from |std::max(word->first, start_char)| to the current character.
315 SkScalar word_width = 0;
316 *width = 0;
318 for (size_t i = start_char; i < run.range.end(); ++i) {
319 // |word| holds the word boundary at or before |i|, and |next_word| holds
320 // the word boundary right after |i|. Advance both |word| and |next_word|
321 // when |i| reaches |next_word|.
322 if (next_word != words_->breaks().end() && i >= next_word->first) {
323 word = next_word++;
324 word_width = 0;
327 Range glyph_range = run.CharRangeToGlyphRange(Range(i, i + 1));
328 SkScalar char_width = ((glyph_range.end() >= run.glyph_count)
329 ? SkFloatToScalar(run.width)
330 : run.positions[glyph_range.end()].x()) -
331 run.positions[glyph_range.start()].x();
333 *width += char_width;
334 word_width += char_width;
336 if (*width > available_width) {
337 if (line_x_ != 0 || word_width < *width) {
338 // Roll back one word.
339 *width -= word_width;
340 *next_char = std::max(word->first, start_char);
341 } else if (char_width < *width) {
342 // Roll back one character.
343 *width -= char_width;
344 *next_char = i;
345 } else {
346 // Continue from the next character.
347 *next_char = i + 1;
349 return true;
353 *next_char = run.range.end();
354 return false;
357 // RTL runs are broken in logical order but displayed in visual order. To find
358 // the text-space coordinate (where it would fall in a single-line text)
359 // |x_range| of RTL segments, segment widths are applied in reverse order.
360 // e.g. {[5, 10], [10, 40]} will become {[35, 40], [5, 35]}.
361 void UpdateRTLSegmentRanges() {
362 if (rtl_segments_.empty())
363 return;
364 float x = SegmentFromHandle(rtl_segments_[0])->x_range.start();
365 for (size_t i = rtl_segments_.size(); i > 0; --i) {
366 internal::LineSegment* segment = SegmentFromHandle(rtl_segments_[i - 1]);
367 const float segment_width = segment->width;
368 segment->x_range = Range(x, x + segment_width);
369 x += segment_width;
371 rtl_segments_.clear();
374 // Finishes the size calculations of the last Line in |lines_|. Adds a new
375 // Line to the back of |lines_|.
376 void AdvanceLine() {
377 if (!lines_.empty()) {
378 internal::Line* line = &lines_.back();
379 std::sort(line->segments.begin(), line->segments.end(),
380 [this](const internal::LineSegment& s1,
381 const internal::LineSegment& s2) -> bool {
382 return run_list_.logical_to_visual(s1.run) <
383 run_list_.logical_to_visual(s2.run);
385 line->size.set_height(std::max(min_height_, max_descent_ + max_ascent_));
386 line->baseline =
387 std::max(min_baseline_, SkScalarRoundToInt(max_ascent_));
388 line->preceding_heights = std::ceil(total_size_.height());
389 total_size_.set_height(total_size_.height() + line->size.height());
390 total_size_.set_width(std::max(total_size_.width(), line->size.width()));
392 max_descent_ = 0;
393 max_ascent_ = 0;
394 line_x_ = 0;
395 lines_.push_back(internal::Line());
398 // Adds a new segment with the given properties to |lines_.back()|.
399 void AddSegment(int run_index, Range char_range, float width) {
400 if (char_range.is_empty()) {
401 DCHECK_EQ(0, width);
402 return;
404 const internal::TextRunHarfBuzz& run = *(run_list_.runs()[run_index]);
406 internal::LineSegment segment;
407 segment.run = run_index;
408 segment.char_range = char_range;
409 segment.x_range = Range(
410 SkScalarCeilToInt(text_x_),
411 SkScalarCeilToInt(text_x_ + SkFloatToScalar(width)));
412 segment.width = width;
414 internal::Line* line = &lines_.back();
415 line->segments.push_back(segment);
417 SkPaint paint;
418 paint.setTypeface(run.skia_face.get());
419 paint.setTextSize(SkIntToScalar(run.font_size));
420 paint.setAntiAlias(run.render_params.antialiasing);
421 SkPaint::FontMetrics metrics;
422 paint.getFontMetrics(&metrics);
424 line->size.set_width(line->size.width() + width);
425 // TODO(dschuyler): Account for stylized baselines in string sizing.
426 max_descent_ = std::max(max_descent_, metrics.fDescent);
427 // fAscent is always negative.
428 max_ascent_ = std::max(max_ascent_, -metrics.fAscent);
430 if (run.is_rtl) {
431 rtl_segments_.push_back(
432 SegmentHandle(lines_.size() - 1, line->segments.size() - 1));
433 // If this is the last segment of an RTL run, reprocess the text-space x
434 // ranges of all segments from the run.
435 if (char_range.end() == run.range.end())
436 UpdateRTLSegmentRanges();
438 text_x_ += SkFloatToScalar(width);
439 line_x_ += SkFloatToScalar(width);
442 const SkScalar max_width_;
443 const int min_baseline_;
444 const float min_height_;
445 const bool multiline_;
446 const base::string16& text_;
447 const BreakList<size_t>* const words_;
448 const internal::TextRunList& run_list_;
450 // Stores the resulting lines.
451 std::vector<internal::Line> lines_;
453 // Text space and line space x coordinates of the next segment to be added.
454 SkScalar text_x_;
455 SkScalar line_x_;
457 float max_descent_;
458 float max_ascent_;
460 // Size of the multiline text, not including the currently processed line.
461 SizeF total_size_;
463 // The current RTL run segments, to be applied by |UpdateRTLSegmentRanges()|.
464 std::vector<SegmentHandle> rtl_segments_;
466 DISALLOW_COPY_AND_ASSIGN(HarfBuzzLineBreaker);
469 } // namespace
471 namespace internal {
473 Range RoundRangeF(const RangeF& range_f) {
474 return Range(std::floor(range_f.start() + 0.5f),
475 std::floor(range_f.end() + 0.5f));
478 TextRunHarfBuzz::TextRunHarfBuzz()
479 : width(0.0f),
480 preceding_run_widths(0.0f),
481 is_rtl(false),
482 level(0),
483 script(USCRIPT_INVALID_CODE),
484 glyph_count(static_cast<size_t>(-1)),
485 font_size(0),
486 baseline_offset(0),
487 baseline_type(0),
488 font_style(0),
489 strike(false),
490 diagonal_strike(false),
491 underline(false) {
494 TextRunHarfBuzz::~TextRunHarfBuzz() {}
496 void TextRunHarfBuzz::GetClusterAt(size_t pos,
497 Range* chars,
498 Range* glyphs) const {
499 DCHECK(range.Contains(Range(pos, pos + 1)));
500 DCHECK(chars);
501 DCHECK(glyphs);
503 if (glyph_count == 0) {
504 *chars = range;
505 *glyphs = Range();
506 return;
509 if (is_rtl) {
510 GetClusterAtImpl(pos, range, glyph_to_char.rbegin(), glyph_to_char.rend(),
511 true, chars, glyphs);
512 return;
515 GetClusterAtImpl(pos, range, glyph_to_char.begin(), glyph_to_char.end(),
516 false, chars, glyphs);
519 Range TextRunHarfBuzz::CharRangeToGlyphRange(const Range& char_range) const {
520 DCHECK(range.Contains(char_range));
521 DCHECK(!char_range.is_reversed());
522 DCHECK(!char_range.is_empty());
524 Range start_glyphs;
525 Range end_glyphs;
526 Range temp_range;
527 GetClusterAt(char_range.start(), &temp_range, &start_glyphs);
528 GetClusterAt(char_range.end() - 1, &temp_range, &end_glyphs);
530 return is_rtl ? Range(end_glyphs.start(), start_glyphs.end()) :
531 Range(start_glyphs.start(), end_glyphs.end());
534 size_t TextRunHarfBuzz::CountMissingGlyphs() const {
535 static const int kMissingGlyphId = 0;
536 size_t missing = 0;
537 for (size_t i = 0; i < glyph_count; ++i)
538 missing += (glyphs[i] == kMissingGlyphId) ? 1 : 0;
539 return missing;
542 RangeF TextRunHarfBuzz::GetGraphemeBounds(
543 base::i18n::BreakIterator* grapheme_iterator,
544 size_t text_index) {
545 DCHECK_LT(text_index, range.end());
546 if (glyph_count == 0)
547 return RangeF(preceding_run_widths, preceding_run_widths + width);
549 Range chars;
550 Range glyphs;
551 GetClusterAt(text_index, &chars, &glyphs);
552 const float cluster_begin_x = positions[glyphs.start()].x();
553 const float cluster_end_x = glyphs.end() < glyph_count ?
554 positions[glyphs.end()].x() : SkFloatToScalar(width);
556 // A cluster consists of a number of code points and corresponds to a number
557 // of glyphs that should be drawn together. A cluster can contain multiple
558 // graphemes. In order to place the cursor at a grapheme boundary inside the
559 // cluster, we simply divide the cluster width by the number of graphemes.
560 if (chars.length() > 1 && grapheme_iterator) {
561 int before = 0;
562 int total = 0;
563 for (size_t i = chars.start(); i < chars.end(); ++i) {
564 if (grapheme_iterator->IsGraphemeBoundary(i)) {
565 if (i < text_index)
566 ++before;
567 ++total;
570 DCHECK_GT(total, 0);
571 if (total > 1) {
572 if (is_rtl)
573 before = total - before - 1;
574 DCHECK_GE(before, 0);
575 DCHECK_LT(before, total);
576 const int cluster_width = cluster_end_x - cluster_begin_x;
577 const int grapheme_begin_x = cluster_begin_x + static_cast<int>(0.5f +
578 cluster_width * before / static_cast<float>(total));
579 const int grapheme_end_x = cluster_begin_x + static_cast<int>(0.5f +
580 cluster_width * (before + 1) / static_cast<float>(total));
581 return RangeF(preceding_run_widths + grapheme_begin_x,
582 preceding_run_widths + grapheme_end_x);
586 return RangeF(preceding_run_widths + cluster_begin_x,
587 preceding_run_widths + cluster_end_x);
590 TextRunList::TextRunList() : width_(0.0f) {}
592 TextRunList::~TextRunList() {}
594 void TextRunList::Reset() {
595 runs_.clear();
596 width_ = 0.0f;
599 void TextRunList::InitIndexMap() {
600 if (runs_.size() == 1) {
601 visual_to_logical_ = logical_to_visual_ = std::vector<int32_t>(1, 0);
602 return;
604 const size_t num_runs = runs_.size();
605 std::vector<UBiDiLevel> levels(num_runs);
606 for (size_t i = 0; i < num_runs; ++i)
607 levels[i] = runs_[i]->level;
608 visual_to_logical_.resize(num_runs);
609 ubidi_reorderVisual(&levels[0], num_runs, &visual_to_logical_[0]);
610 logical_to_visual_.resize(num_runs);
611 ubidi_reorderLogical(&levels[0], num_runs, &logical_to_visual_[0]);
614 void TextRunList::ComputePrecedingRunWidths() {
615 // Precalculate run width information.
616 width_ = 0.0f;
617 for (size_t i = 0; i < runs_.size(); ++i) {
618 TextRunHarfBuzz* run = runs_[visual_to_logical_[i]];
619 run->preceding_run_widths = width_;
620 width_ += run->width;
624 } // namespace internal
626 RenderTextHarfBuzz::RenderTextHarfBuzz()
627 : RenderText(),
628 update_layout_run_list_(false),
629 update_display_run_list_(false),
630 update_grapheme_iterator_(false),
631 update_display_text_(false),
632 glyph_width_for_test_(0u) {
633 set_truncate_length(kMaxTextLength);
636 RenderTextHarfBuzz::~RenderTextHarfBuzz() {}
638 scoped_ptr<RenderText> RenderTextHarfBuzz::CreateInstanceOfSameType() const {
639 return make_scoped_ptr(new RenderTextHarfBuzz);
642 bool RenderTextHarfBuzz::MultilineSupported() const {
643 return true;
646 const base::string16& RenderTextHarfBuzz::GetDisplayText() {
647 // TODO(oshima): Consider supporting eliding multi-line text.
648 // This requires max_line support first.
649 if (multiline() ||
650 elide_behavior() == NO_ELIDE ||
651 elide_behavior() == FADE_TAIL) {
652 // Call UpdateDisplayText to clear |display_text_| and |text_elided_|
653 // on the RenderText class.
654 UpdateDisplayText(0);
655 update_display_text_ = false;
656 display_run_list_.reset();
657 return layout_text();
660 EnsureLayoutRunList();
661 DCHECK(!update_display_text_);
662 return text_elided() ? display_text() : layout_text();
665 Size RenderTextHarfBuzz::GetStringSize() {
666 const SizeF size_f = GetStringSizeF();
667 return Size(std::ceil(size_f.width()), size_f.height());
670 SizeF RenderTextHarfBuzz::GetStringSizeF() {
671 EnsureLayout();
672 return total_size_;
675 SelectionModel RenderTextHarfBuzz::FindCursorPosition(const Point& point) {
676 EnsureLayout();
678 int x = ToTextPoint(point).x();
679 float offset = 0;
680 size_t run_index = GetRunContainingXCoord(x, &offset);
682 internal::TextRunList* run_list = GetRunList();
683 if (run_index >= run_list->size())
684 return EdgeSelectionModel((x < 0) ? CURSOR_LEFT : CURSOR_RIGHT);
685 const internal::TextRunHarfBuzz& run = *run_list->runs()[run_index];
686 for (size_t i = 0; i < run.glyph_count; ++i) {
687 const SkScalar end =
688 i + 1 == run.glyph_count ? run.width : run.positions[i + 1].x();
689 const SkScalar middle = (end + run.positions[i].x()) / 2;
691 if (offset < middle) {
692 return SelectionModel(DisplayIndexToTextIndex(
693 run.glyph_to_char[i] + (run.is_rtl ? 1 : 0)),
694 (run.is_rtl ? CURSOR_BACKWARD : CURSOR_FORWARD));
696 if (offset < end) {
697 return SelectionModel(DisplayIndexToTextIndex(
698 run.glyph_to_char[i] + (run.is_rtl ? 0 : 1)),
699 (run.is_rtl ? CURSOR_FORWARD : CURSOR_BACKWARD));
702 return EdgeSelectionModel(CURSOR_RIGHT);
705 std::vector<RenderText::FontSpan> RenderTextHarfBuzz::GetFontSpansForTesting() {
706 EnsureLayout();
708 internal::TextRunList* run_list = GetRunList();
709 std::vector<RenderText::FontSpan> spans;
710 for (auto* run : run_list->runs()) {
711 SkString family_name;
712 run->skia_face->getFamilyName(&family_name);
713 Font font(family_name.c_str(), run->font_size);
714 spans.push_back(RenderText::FontSpan(
715 font,
716 Range(DisplayIndexToTextIndex(run->range.start()),
717 DisplayIndexToTextIndex(run->range.end()))));
720 return spans;
723 Range RenderTextHarfBuzz::GetGlyphBounds(size_t index) {
724 EnsureLayout();
725 const size_t run_index =
726 GetRunContainingCaret(SelectionModel(index, CURSOR_FORWARD));
727 internal::TextRunList* run_list = GetRunList();
728 // Return edge bounds if the index is invalid or beyond the layout text size.
729 if (run_index >= run_list->size())
730 return Range(GetStringSize().width());
731 const size_t layout_index = TextIndexToDisplayIndex(index);
732 internal::TextRunHarfBuzz* run = run_list->runs()[run_index];
733 RangeF bounds =
734 run->GetGraphemeBounds(GetGraphemeIterator(), layout_index);
735 // If cursor is enabled, extend the last glyph up to the rightmost cursor
736 // position since clients expect them to be contiguous.
737 if (cursor_enabled() && run_index == run_list->size() - 1 &&
738 index == (run->is_rtl ? run->range.start() : run->range.end() - 1))
739 bounds.set_end(std::ceil(bounds.end()));
740 return RoundRangeF(run->is_rtl ?
741 RangeF(bounds.end(), bounds.start()) : bounds);
744 int RenderTextHarfBuzz::GetDisplayTextBaseline() {
745 EnsureLayout();
746 return lines()[0].baseline;
749 SelectionModel RenderTextHarfBuzz::AdjacentCharSelectionModel(
750 const SelectionModel& selection,
751 VisualCursorDirection direction) {
752 DCHECK(!update_display_run_list_);
754 internal::TextRunList* run_list = GetRunList();
755 internal::TextRunHarfBuzz* run;
757 size_t run_index = GetRunContainingCaret(selection);
758 if (run_index >= run_list->size()) {
759 // The cursor is not in any run: we're at the visual and logical edge.
760 SelectionModel edge = EdgeSelectionModel(direction);
761 if (edge.caret_pos() == selection.caret_pos())
762 return edge;
763 int visual_index = (direction == CURSOR_RIGHT) ? 0 : run_list->size() - 1;
764 run = run_list->runs()[run_list->visual_to_logical(visual_index)];
765 } else {
766 // If the cursor is moving within the current run, just move it by one
767 // grapheme in the appropriate direction.
768 run = run_list->runs()[run_index];
769 size_t caret = selection.caret_pos();
770 bool forward_motion = run->is_rtl == (direction == CURSOR_LEFT);
771 if (forward_motion) {
772 if (caret < DisplayIndexToTextIndex(run->range.end())) {
773 caret = IndexOfAdjacentGrapheme(caret, CURSOR_FORWARD);
774 return SelectionModel(caret, CURSOR_BACKWARD);
776 } else {
777 if (caret > DisplayIndexToTextIndex(run->range.start())) {
778 caret = IndexOfAdjacentGrapheme(caret, CURSOR_BACKWARD);
779 return SelectionModel(caret, CURSOR_FORWARD);
782 // The cursor is at the edge of a run; move to the visually adjacent run.
783 int visual_index = run_list->logical_to_visual(run_index);
784 visual_index += (direction == CURSOR_LEFT) ? -1 : 1;
785 if (visual_index < 0 || visual_index >= static_cast<int>(run_list->size()))
786 return EdgeSelectionModel(direction);
787 run = run_list->runs()[run_list->visual_to_logical(visual_index)];
789 bool forward_motion = run->is_rtl == (direction == CURSOR_LEFT);
790 return forward_motion ? FirstSelectionModelInsideRun(run) :
791 LastSelectionModelInsideRun(run);
794 SelectionModel RenderTextHarfBuzz::AdjacentWordSelectionModel(
795 const SelectionModel& selection,
796 VisualCursorDirection direction) {
797 if (obscured())
798 return EdgeSelectionModel(direction);
800 base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD);
801 bool success = iter.Init();
802 DCHECK(success);
803 if (!success)
804 return selection;
806 // Match OS specific word break behavior.
807 #if defined(OS_WIN)
808 size_t pos;
809 if (direction == CURSOR_RIGHT) {
810 pos = std::min(selection.caret_pos() + 1, text().length());
811 while (iter.Advance()) {
812 pos = iter.pos();
813 if (iter.IsWord() && pos > selection.caret_pos())
814 break;
816 } else { // direction == CURSOR_LEFT
817 // Notes: We always iterate words from the beginning.
818 // This is probably fast enough for our usage, but we may
819 // want to modify WordIterator so that it can start from the
820 // middle of string and advance backwards.
821 pos = std::max<int>(selection.caret_pos() - 1, 0);
822 while (iter.Advance()) {
823 if (iter.IsWord()) {
824 size_t begin = iter.pos() - iter.GetString().length();
825 if (begin == selection.caret_pos()) {
826 // The cursor is at the beginning of a word.
827 // Move to previous word.
828 break;
829 } else if (iter.pos() >= selection.caret_pos()) {
830 // The cursor is in the middle or at the end of a word.
831 // Move to the top of current word.
832 pos = begin;
833 break;
835 pos = iter.pos() - iter.GetString().length();
839 return SelectionModel(pos, CURSOR_FORWARD);
840 #else
841 internal::TextRunList* run_list = GetRunList();
842 SelectionModel cur(selection);
843 for (;;) {
844 cur = AdjacentCharSelectionModel(cur, direction);
845 size_t run = GetRunContainingCaret(cur);
846 if (run == run_list->size())
847 break;
848 const bool is_forward =
849 run_list->runs()[run]->is_rtl == (direction == CURSOR_LEFT);
850 size_t cursor = cur.caret_pos();
851 if (is_forward ? iter.IsEndOfWord(cursor) : iter.IsStartOfWord(cursor))
852 break;
854 return cur;
855 #endif
858 std::vector<Rect> RenderTextHarfBuzz::GetSubstringBounds(const Range& range) {
859 DCHECK(!update_display_run_list_);
860 DCHECK(Range(0, text().length()).Contains(range));
861 Range layout_range(TextIndexToDisplayIndex(range.start()),
862 TextIndexToDisplayIndex(range.end()));
863 DCHECK(Range(0, GetDisplayText().length()).Contains(layout_range));
865 std::vector<Rect> rects;
866 if (layout_range.is_empty())
867 return rects;
868 std::vector<Range> bounds;
870 internal::TextRunList* run_list = GetRunList();
872 // Add a Range for each run/selection intersection.
873 for (size_t i = 0; i < run_list->size(); ++i) {
874 internal::TextRunHarfBuzz* run =
875 run_list->runs()[run_list->visual_to_logical(i)];
876 Range intersection = run->range.Intersect(layout_range);
877 if (!intersection.IsValid())
878 continue;
879 DCHECK(!intersection.is_reversed());
880 const Range leftmost_character_x = RoundRangeF(run->GetGraphemeBounds(
881 GetGraphemeIterator(),
882 run->is_rtl ? intersection.end() - 1 : intersection.start()));
883 const Range rightmost_character_x = RoundRangeF(run->GetGraphemeBounds(
884 GetGraphemeIterator(),
885 run->is_rtl ? intersection.start() : intersection.end() - 1));
886 Range range_x(leftmost_character_x.start(), rightmost_character_x.end());
887 DCHECK(!range_x.is_reversed());
888 if (range_x.is_empty())
889 continue;
891 // Union this with the last range if they're adjacent.
892 DCHECK(bounds.empty() || bounds.back().GetMax() <= range_x.GetMin());
893 if (!bounds.empty() && bounds.back().GetMax() == range_x.GetMin()) {
894 range_x = Range(bounds.back().GetMin(), range_x.GetMax());
895 bounds.pop_back();
897 bounds.push_back(range_x);
899 for (Range& bound : bounds) {
900 std::vector<Rect> current_rects = TextBoundsToViewBounds(bound);
901 rects.insert(rects.end(), current_rects.begin(), current_rects.end());
903 return rects;
906 size_t RenderTextHarfBuzz::TextIndexToDisplayIndex(size_t index) {
907 return TextIndexToGivenTextIndex(GetDisplayText(), index);
910 size_t RenderTextHarfBuzz::DisplayIndexToTextIndex(size_t index) {
911 if (!obscured())
912 return index;
913 const size_t text_index = UTF16OffsetToIndex(text(), 0, index);
914 DCHECK_LE(text_index, text().length());
915 return text_index;
918 bool RenderTextHarfBuzz::IsValidCursorIndex(size_t index) {
919 if (index == 0 || index == text().length())
920 return true;
921 if (!IsValidLogicalIndex(index))
922 return false;
923 base::i18n::BreakIterator* grapheme_iterator = GetGraphemeIterator();
924 return !grapheme_iterator || grapheme_iterator->IsGraphemeBoundary(index);
927 void RenderTextHarfBuzz::OnLayoutTextAttributeChanged(bool text_changed) {
928 update_layout_run_list_ = true;
929 OnDisplayTextAttributeChanged();
932 void RenderTextHarfBuzz::OnDisplayTextAttributeChanged() {
933 update_display_text_ = true;
934 update_grapheme_iterator_ = true;
937 void RenderTextHarfBuzz::EnsureLayout() {
938 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
939 tracked_objects::ScopedTracker tracking_profile(
940 FROM_HERE_WITH_EXPLICIT_FUNCTION(
941 "431326 RenderTextHarfBuzz::EnsureLayout"));
943 EnsureLayoutRunList();
945 if (update_display_run_list_) {
946 DCHECK(text_elided());
947 const base::string16& display_text = GetDisplayText();
948 display_run_list_.reset(new internal::TextRunList);
950 if (!display_text.empty()) {
951 TRACE_EVENT0("ui", "RenderTextHarfBuzz:EnsureLayout1");
953 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is
954 // fixed.
955 tracked_objects::ScopedTracker tracking_profile1(
956 FROM_HERE_WITH_EXPLICIT_FUNCTION(
957 "431326 RenderTextHarfBuzz::EnsureLayout1"));
958 ItemizeTextToRuns(display_text, display_run_list_.get());
960 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is
961 // fixed.
962 tracked_objects::ScopedTracker tracking_profile2(
963 FROM_HERE_WITH_EXPLICIT_FUNCTION(
964 "431326 RenderTextHarfBuzz::EnsureLayout12"));
965 ShapeRunList(display_text, display_run_list_.get());
967 update_display_run_list_ = false;
969 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is
970 // fixed.
971 tracked_objects::ScopedTracker tracking_profile14(
972 FROM_HERE_WITH_EXPLICIT_FUNCTION(
973 "431326 RenderTextHarfBuzz::EnsureLayout14"));
974 std::vector<internal::Line> empty_lines;
975 set_lines(&empty_lines);
978 if (lines().empty()) {
979 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
980 tracked_objects::ScopedTracker tracking_profile2(
981 FROM_HERE_WITH_EXPLICIT_FUNCTION(
982 "431326 RenderTextHarfBuzz::EnsureLayout2"));
984 internal::TextRunList* run_list = GetRunList();
985 HarfBuzzLineBreaker line_breaker(
986 display_rect().width(), font_list().GetBaseline(),
987 std::max(font_list().GetHeight(), min_line_height()), multiline(),
988 GetDisplayText(), multiline() ? &GetLineBreaks() : nullptr, *run_list);
990 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
991 tracked_objects::ScopedTracker tracking_profile3(
992 FROM_HERE_WITH_EXPLICIT_FUNCTION(
993 "431326 RenderTextHarfBuzz::EnsureLayout3"));
995 for (size_t i = 0; i < run_list->size(); ++i)
996 line_breaker.AddRun(i);
997 std::vector<internal::Line> lines;
998 line_breaker.Finalize(&lines, &total_size_);
999 set_lines(&lines);
1003 void RenderTextHarfBuzz::DrawVisualText(Canvas* canvas) {
1004 internal::SkiaTextRenderer renderer(canvas);
1005 DrawVisualTextInternal(&renderer);
1008 void RenderTextHarfBuzz::DrawVisualTextInternal(
1009 internal::SkiaTextRenderer* renderer) {
1010 DCHECK(!update_layout_run_list_);
1011 DCHECK(!update_display_run_list_);
1012 DCHECK(!update_display_text_);
1013 if (lines().empty())
1014 return;
1016 ApplyFadeEffects(renderer);
1017 ApplyTextShadows(renderer);
1018 ApplyCompositionAndSelectionStyles();
1020 internal::TextRunList* run_list = GetRunList();
1021 for (size_t i = 0; i < lines().size(); ++i) {
1022 const internal::Line& line = lines()[i];
1023 const Vector2d origin = GetLineOffset(i) + Vector2d(0, line.baseline);
1024 SkScalar preceding_segment_widths = 0;
1025 for (const internal::LineSegment& segment : line.segments) {
1026 const internal::TextRunHarfBuzz& run = *run_list->runs()[segment.run];
1027 renderer->SetTypeface(run.skia_face.get());
1028 renderer->SetTextSize(SkIntToScalar(run.font_size));
1029 renderer->SetFontRenderParams(run.render_params,
1030 subpixel_rendering_suppressed());
1031 Range glyphs_range = run.CharRangeToGlyphRange(segment.char_range);
1032 scoped_ptr<SkPoint[]> positions(new SkPoint[glyphs_range.length()]);
1033 SkScalar offset_x = preceding_segment_widths -
1034 ((glyphs_range.GetMin() != 0)
1035 ? run.positions[glyphs_range.GetMin()].x()
1036 : 0);
1037 for (size_t j = 0; j < glyphs_range.length(); ++j) {
1038 positions[j] = run.positions[(glyphs_range.is_reversed()) ?
1039 (glyphs_range.start() - j) :
1040 (glyphs_range.start() + j)];
1041 positions[j].offset(SkIntToScalar(origin.x()) + offset_x,
1042 SkIntToScalar(origin.y() + run.baseline_offset));
1044 for (BreakList<SkColor>::const_iterator it =
1045 colors().GetBreak(segment.char_range.start());
1046 it != colors().breaks().end() &&
1047 it->first < segment.char_range.end();
1048 ++it) {
1049 const Range intersection =
1050 colors().GetRange(it).Intersect(segment.char_range);
1051 const Range colored_glyphs = run.CharRangeToGlyphRange(intersection);
1052 // The range may be empty if a portion of a multi-character grapheme is
1053 // selected, yielding two colors for a single glyph. For now, this just
1054 // paints the glyph with a single style, but it should paint it twice,
1055 // clipped according to selection bounds. See http://crbug.com/366786
1056 if (colored_glyphs.is_empty())
1057 continue;
1059 renderer->SetForegroundColor(it->second);
1060 renderer->DrawPosText(
1061 &positions[colored_glyphs.start() - glyphs_range.start()],
1062 &run.glyphs[colored_glyphs.start()], colored_glyphs.length());
1063 int start_x = SkScalarRoundToInt(
1064 positions[colored_glyphs.start() - glyphs_range.start()].x());
1065 int end_x = SkScalarRoundToInt(
1066 (colored_glyphs.end() == glyphs_range.end())
1067 ? (SkFloatToScalar(segment.width) + preceding_segment_widths +
1068 SkIntToScalar(origin.x()))
1069 : positions[colored_glyphs.end() - glyphs_range.start()].x());
1070 renderer->DrawDecorations(start_x, origin.y(), end_x - start_x,
1071 run.underline, run.strike,
1072 run.diagonal_strike);
1074 preceding_segment_widths += SkFloatToScalar(segment.width);
1078 renderer->EndDiagonalStrike();
1080 UndoCompositionAndSelectionStyles();
1083 size_t RenderTextHarfBuzz::GetRunContainingCaret(
1084 const SelectionModel& caret) {
1085 DCHECK(!update_display_run_list_);
1086 size_t layout_position = TextIndexToDisplayIndex(caret.caret_pos());
1087 LogicalCursorDirection affinity = caret.caret_affinity();
1088 internal::TextRunList* run_list = GetRunList();
1089 for (size_t i = 0; i < run_list->size(); ++i) {
1090 internal::TextRunHarfBuzz* run = run_list->runs()[i];
1091 if (RangeContainsCaret(run->range, layout_position, affinity))
1092 return i;
1094 return run_list->size();
1097 size_t RenderTextHarfBuzz::GetRunContainingXCoord(float x,
1098 float* offset) const {
1099 DCHECK(!update_display_run_list_);
1100 const internal::TextRunList* run_list = GetRunList();
1101 if (x < 0)
1102 return run_list->size();
1103 // Find the text run containing the argument point (assumed already offset).
1104 float current_x = 0;
1105 for (size_t i = 0; i < run_list->size(); ++i) {
1106 size_t run = run_list->visual_to_logical(i);
1107 current_x += run_list->runs()[run]->width;
1108 if (x < current_x) {
1109 *offset = x - (current_x - run_list->runs()[run]->width);
1110 return run;
1113 return run_list->size();
1116 SelectionModel RenderTextHarfBuzz::FirstSelectionModelInsideRun(
1117 const internal::TextRunHarfBuzz* run) {
1118 size_t position = DisplayIndexToTextIndex(run->range.start());
1119 position = IndexOfAdjacentGrapheme(position, CURSOR_FORWARD);
1120 return SelectionModel(position, CURSOR_BACKWARD);
1123 SelectionModel RenderTextHarfBuzz::LastSelectionModelInsideRun(
1124 const internal::TextRunHarfBuzz* run) {
1125 size_t position = DisplayIndexToTextIndex(run->range.end());
1126 position = IndexOfAdjacentGrapheme(position, CURSOR_BACKWARD);
1127 return SelectionModel(position, CURSOR_FORWARD);
1130 void RenderTextHarfBuzz::ItemizeTextToRuns(
1131 const base::string16& text,
1132 internal::TextRunList* run_list_out) {
1133 const bool is_text_rtl = GetTextDirection(text) == base::i18n::RIGHT_TO_LEFT;
1134 DCHECK_NE(0U, text.length());
1136 // If ICU fails to itemize the text, we create a run that spans the entire
1137 // text. This is needed because leaving the runs set empty causes some clients
1138 // to misbehave since they expect non-zero text metrics from a non-empty text.
1139 base::i18n::BiDiLineIterator bidi_iterator;
1140 if (!bidi_iterator.Open(text, is_text_rtl, false)) {
1141 internal::TextRunHarfBuzz* run = new internal::TextRunHarfBuzz;
1142 run->range = Range(0, text.length());
1143 run_list_out->add(run);
1144 run_list_out->InitIndexMap();
1145 return;
1148 // Temporarily apply composition underlines and selection colors.
1149 ApplyCompositionAndSelectionStyles();
1151 // Build the run list from the script items and ranged styles and baselines.
1152 // Use an empty color BreakList to avoid breaking runs at color boundaries.
1153 BreakList<SkColor> empty_colors;
1154 empty_colors.SetMax(text.length());
1155 internal::StyleIterator style(empty_colors, baselines(), styles());
1157 for (size_t run_break = 0; run_break < text.length();) {
1158 internal::TextRunHarfBuzz* run = new internal::TextRunHarfBuzz;
1159 run->range.set_start(run_break);
1160 run->font_style = (style.style(BOLD) ? Font::BOLD : 0) |
1161 (style.style(ITALIC) ? Font::ITALIC : 0);
1162 run->baseline_type = style.baseline();
1163 run->strike = style.style(STRIKE);
1164 run->diagonal_strike = style.style(DIAGONAL_STRIKE);
1165 run->underline = style.style(UNDERLINE);
1166 int32 script_item_break = 0;
1167 bidi_iterator.GetLogicalRun(run_break, &script_item_break, &run->level);
1168 // Odd BiDi embedding levels correspond to RTL runs.
1169 run->is_rtl = (run->level % 2) == 1;
1170 // Find the length and script of this script run.
1171 script_item_break = ScriptInterval(text, run_break,
1172 script_item_break - run_break, &run->script) + run_break;
1174 // Find the next break and advance the iterators as needed.
1175 run_break = std::min(
1176 static_cast<size_t>(script_item_break),
1177 TextIndexToGivenTextIndex(text, style.GetRange().end()));
1179 // Break runs at certain characters that need to be rendered separately to
1180 // prevent either an unusual character from forcing a fallback font on the
1181 // entire run, or brackets from being affected by a fallback font.
1182 // http://crbug.com/278913, http://crbug.com/396776
1183 if (run_break > run->range.start())
1184 run_break = FindRunBreakingCharacter(text, run->range.start(), run_break);
1186 DCHECK(IsValidCodePointIndex(text, run_break));
1187 style.UpdatePosition(DisplayIndexToTextIndex(run_break));
1188 run->range.set_end(run_break);
1190 run_list_out->add(run);
1193 // Undo the temporarily applied composition underlines and selection colors.
1194 UndoCompositionAndSelectionStyles();
1196 run_list_out->InitIndexMap();
1199 bool RenderTextHarfBuzz::CompareFamily(
1200 const base::string16& text,
1201 const std::string& family,
1202 const gfx::FontRenderParams& render_params,
1203 internal::TextRunHarfBuzz* run,
1204 std::string* best_family,
1205 gfx::FontRenderParams* best_render_params,
1206 size_t* best_missing_glyphs) {
1207 if (!ShapeRunWithFont(text, family, render_params, run))
1208 return false;
1210 const size_t missing_glyphs = run->CountMissingGlyphs();
1211 if (missing_glyphs < *best_missing_glyphs) {
1212 *best_family = family;
1213 *best_render_params = render_params;
1214 *best_missing_glyphs = missing_glyphs;
1216 return missing_glyphs == 0;
1219 void RenderTextHarfBuzz::ShapeRunList(const base::string16& text,
1220 internal::TextRunList* run_list) {
1221 for (auto* run : run_list->runs())
1222 ShapeRun(text, run);
1223 run_list->ComputePrecedingRunWidths();
1226 void RenderTextHarfBuzz::ShapeRun(const base::string16& text,
1227 internal::TextRunHarfBuzz* run) {
1228 const Font& primary_font = font_list().GetPrimaryFont();
1229 const std::string primary_family = primary_font.GetFontName();
1230 run->font_size = primary_font.GetFontSize();
1231 run->baseline_offset = 0;
1232 if (run->baseline_type != NORMAL_BASELINE) {
1233 // Calculate a slightly smaller font. The ratio here is somewhat arbitrary.
1234 // Proportions from 5/9 to 5/7 all look pretty good.
1235 const float ratio = 5.0f / 9.0f;
1236 run->font_size = gfx::ToRoundedInt(primary_font.GetFontSize() * ratio);
1237 switch (run->baseline_type) {
1238 case SUPERSCRIPT:
1239 run->baseline_offset =
1240 primary_font.GetCapHeight() - primary_font.GetHeight();
1241 break;
1242 case SUPERIOR:
1243 run->baseline_offset =
1244 gfx::ToRoundedInt(primary_font.GetCapHeight() * ratio) -
1245 primary_font.GetCapHeight();
1246 break;
1247 case SUBSCRIPT:
1248 run->baseline_offset =
1249 primary_font.GetHeight() - primary_font.GetBaseline();
1250 break;
1251 case INFERIOR: // Fall through.
1252 default:
1253 break;
1257 std::string best_family;
1258 FontRenderParams best_render_params;
1259 size_t best_missing_glyphs = std::numeric_limits<size_t>::max();
1261 for (const Font& font : font_list().GetFonts()) {
1262 if (CompareFamily(text, font.GetFontName(), font.GetFontRenderParams(),
1263 run, &best_family, &best_render_params,
1264 &best_missing_glyphs))
1265 return;
1268 #if defined(OS_WIN)
1269 Font uniscribe_font;
1270 std::string uniscribe_family;
1271 const base::char16* run_text = &(text[run->range.start()]);
1272 if (GetUniscribeFallbackFont(primary_font, run_text, run->range.length(),
1273 &uniscribe_font)) {
1274 uniscribe_family = uniscribe_font.GetFontName();
1275 if (CompareFamily(text, uniscribe_family,
1276 uniscribe_font.GetFontRenderParams(), run,
1277 &best_family, &best_render_params, &best_missing_glyphs))
1278 return;
1280 #endif
1282 std::vector<std::string> fallback_families =
1283 GetFallbackFontFamilies(primary_family);
1285 #if defined(OS_WIN)
1286 // Append fonts in the fallback list of the Uniscribe font.
1287 if (!uniscribe_family.empty()) {
1288 std::vector<std::string> uniscribe_fallbacks =
1289 GetFallbackFontFamilies(uniscribe_family);
1290 fallback_families.insert(fallback_families.end(),
1291 uniscribe_fallbacks.begin(), uniscribe_fallbacks.end());
1293 #endif
1295 // Try shaping with the fallback fonts.
1296 for (const auto& family : fallback_families) {
1297 if (family == primary_family)
1298 continue;
1299 #if defined(OS_WIN)
1300 if (family == uniscribe_family)
1301 continue;
1302 #endif
1303 FontRenderParamsQuery query(false);
1304 query.families.push_back(family);
1305 query.pixel_size = run->font_size;
1306 query.style = run->font_style;
1307 FontRenderParams fallback_render_params = GetFontRenderParams(query, NULL);
1308 if (CompareFamily(text, family, fallback_render_params, run, &best_family,
1309 &best_render_params, &best_missing_glyphs))
1310 return;
1313 if (!best_family.empty() &&
1314 (best_family == run->family ||
1315 ShapeRunWithFont(text, best_family, best_render_params, run)))
1316 return;
1318 run->glyph_count = 0;
1319 run->width = 0.0f;
1322 bool RenderTextHarfBuzz::ShapeRunWithFont(const base::string16& text,
1323 const std::string& font_family,
1324 const FontRenderParams& params,
1325 internal::TextRunHarfBuzz* run) {
1326 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
1327 tracked_objects::ScopedTracker tracking_profile0(
1328 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1329 "431326 RenderTextHarfBuzz::ShapeRunWithFont0"));
1331 skia::RefPtr<SkTypeface> skia_face =
1332 internal::CreateSkiaTypeface(font_family, run->font_style);
1333 if (skia_face == NULL)
1334 return false;
1335 run->skia_face = skia_face;
1336 run->family = font_family;
1337 run->render_params = params;
1339 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
1340 tracked_objects::ScopedTracker tracking_profile01(
1341 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1342 "431326 RenderTextHarfBuzz::ShapeRunWithFont01"));
1344 hb_font_t* harfbuzz_font = CreateHarfBuzzFont(
1345 run->skia_face.get(), SkIntToScalar(run->font_size), run->render_params,
1346 subpixel_rendering_suppressed());
1348 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
1349 tracked_objects::ScopedTracker tracking_profile1(
1350 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1351 "431326 RenderTextHarfBuzz::ShapeRunWithFont1"));
1353 // Create a HarfBuzz buffer and add the string to be shaped. The HarfBuzz
1354 // buffer holds our text, run information to be used by the shaping engine,
1355 // and the resulting glyph data.
1356 hb_buffer_t* buffer = hb_buffer_create();
1358 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
1359 tracked_objects::ScopedTracker tracking_profile1q(
1360 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1361 "431326 RenderTextHarfBuzz::ShapeRunWithFont11"));
1363 hb_buffer_add_utf16(buffer, reinterpret_cast<const uint16*>(text.c_str()),
1364 text.length(), run->range.start(), run->range.length());
1366 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
1367 tracked_objects::ScopedTracker tracking_profile12(
1368 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1369 "431326 RenderTextHarfBuzz::ShapeRunWithFont12"));
1371 hb_buffer_set_script(buffer, ICUScriptToHBScript(run->script));
1373 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
1374 tracked_objects::ScopedTracker tracking_profile13(
1375 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1376 "431326 RenderTextHarfBuzz::ShapeRunWithFont13"));
1378 hb_buffer_set_direction(buffer,
1379 run->is_rtl ? HB_DIRECTION_RTL : HB_DIRECTION_LTR);
1381 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
1382 tracked_objects::ScopedTracker tracking_profile14(
1383 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1384 "431326 RenderTextHarfBuzz::ShapeRunWithFont14"));
1386 // TODO(ckocagil): Should we determine the actual language?
1387 hb_buffer_set_language(buffer, hb_language_get_default());
1389 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
1390 tracked_objects::ScopedTracker tracking_profile15(
1391 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1392 "431326 RenderTextHarfBuzz::ShapeRunWithFont15"));
1394 // Shape the text.
1395 hb_shape(harfbuzz_font, buffer, NULL, 0);
1397 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
1398 tracked_objects::ScopedTracker tracking_profile2(
1399 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1400 "431326 RenderTextHarfBuzz::ShapeRunWithFont2"));
1402 // Populate the run fields with the resulting glyph data in the buffer.
1403 unsigned int glyph_count = 0;
1404 hb_glyph_info_t* infos = hb_buffer_get_glyph_infos(buffer, &glyph_count);
1405 run->glyph_count = glyph_count;
1406 hb_glyph_position_t* hb_positions =
1407 hb_buffer_get_glyph_positions(buffer, NULL);
1408 run->glyphs.reset(new uint16[run->glyph_count]);
1409 run->glyph_to_char.resize(run->glyph_count);
1410 run->positions.reset(new SkPoint[run->glyph_count]);
1411 run->width = 0.0f;
1413 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
1414 tracked_objects::ScopedTracker tracking_profile3(
1415 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1416 "431326 RenderTextHarfBuzz::ShapeRunWithFont3"));
1418 for (size_t i = 0; i < run->glyph_count; ++i) {
1419 DCHECK_LE(infos[i].codepoint, std::numeric_limits<uint16>::max());
1420 run->glyphs[i] = static_cast<uint16>(infos[i].codepoint);
1421 run->glyph_to_char[i] = infos[i].cluster;
1422 const SkScalar x_offset = SkFixedToScalar(hb_positions[i].x_offset);
1423 const SkScalar y_offset = SkFixedToScalar(hb_positions[i].y_offset);
1424 run->positions[i].set(run->width + x_offset, -y_offset);
1425 run->width += (glyph_width_for_test_ > 0)
1426 ? glyph_width_for_test_
1427 : SkFixedToFloat(hb_positions[i].x_advance);
1428 // Round run widths if subpixel positioning is off to match native behavior.
1429 if (!run->render_params.subpixel_positioning)
1430 run->width = std::floor(run->width + 0.5f);
1433 hb_buffer_destroy(buffer);
1434 hb_font_destroy(harfbuzz_font);
1435 return true;
1438 void RenderTextHarfBuzz::EnsureLayoutRunList() {
1439 if (update_layout_run_list_) {
1440 layout_run_list_.Reset();
1442 const base::string16& text = layout_text();
1443 if (!text.empty()) {
1444 TRACE_EVENT0("ui", "RenderTextHarfBuzz:EnsureLayoutRunList");
1445 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is
1446 // fixed.
1447 tracked_objects::ScopedTracker tracking_profile1(
1448 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1449 "431326 RenderTextHarfBuzz::EnsureLayout1"));
1450 ItemizeTextToRuns(text, &layout_run_list_);
1452 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is
1453 // fixed.
1454 tracked_objects::ScopedTracker tracking_profile2(
1455 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1456 "431326 RenderTextHarfBuzz::EnsureLayout12"));
1457 ShapeRunList(text, &layout_run_list_);
1460 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is
1461 // fixed.
1462 tracked_objects::ScopedTracker tracking_profile14(
1463 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1464 "431326 RenderTextHarfBuzz::EnsureLayout14"));
1466 std::vector<internal::Line> empty_lines;
1467 set_lines(&empty_lines);
1468 display_run_list_.reset();
1469 update_display_text_ = true;
1470 update_layout_run_list_ = false;
1472 if (update_display_text_) {
1473 UpdateDisplayText(multiline() ? 0 : layout_run_list_.width());
1474 update_display_text_ = false;
1475 update_display_run_list_ = text_elided();
1479 base::i18n::BreakIterator* RenderTextHarfBuzz::GetGraphemeIterator() {
1480 if (update_grapheme_iterator_) {
1481 update_grapheme_iterator_ = false;
1482 grapheme_iterator_.reset(new base::i18n::BreakIterator(
1483 GetDisplayText(),
1484 base::i18n::BreakIterator::BREAK_CHARACTER));
1485 if (!grapheme_iterator_->Init())
1486 grapheme_iterator_.reset();
1488 return grapheme_iterator_.get();
1491 internal::TextRunList* RenderTextHarfBuzz::GetRunList() {
1492 DCHECK(!update_layout_run_list_);
1493 DCHECK(!update_display_run_list_);
1494 return text_elided() ? display_run_list_.get() : &layout_run_list_;
1497 const internal::TextRunList* RenderTextHarfBuzz::GetRunList() const {
1498 return const_cast<RenderTextHarfBuzz*>(this)->GetRunList();
1501 } // namespace gfx