Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(735)

Side by Side Diff: ui/gfx/render_text_harfbuzz.cc

Issue 1070223004: Stop combining text runs which are connected by 'COMMON' blocks. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Address mukai@'s comments. Created 5 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « ui/gfx/render_text_harfbuzz.h ('k') | ui/gfx/render_text_unittest.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright 2014 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "ui/gfx/render_text_harfbuzz.h" 5 #include "ui/gfx/render_text_harfbuzz.h"
6 6
7 #include <limits> 7 #include <limits>
8 #include <set> 8 #include <set>
9 9
10 #include "base/i18n/bidi_line_iterator.h" 10 #include "base/i18n/bidi_line_iterator.h"
(...skipping 31 matching lines...) Expand 10 before | Expand all | Expand 10 after
42 // The maximum number of scripts a Unicode character can belong to. This value 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 43 // is arbitrarily chosen to be a good limit because it is unlikely for a single
44 // character to belong to more scripts. 44 // character to belong to more scripts.
45 const size_t kMaxScripts = 5; 45 const size_t kMaxScripts = 5;
46 46
47 // Returns true if characters of |block_code| may trigger font fallback. 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, 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 49 // therefore it needs to be trigerred as fallbacks. See crbug.com/448909
50 bool IsUnusualBlockCode(UBlockCode block_code) { 50 bool IsUnusualBlockCode(UBlockCode block_code) {
51 return block_code == UBLOCK_GEOMETRIC_SHAPES || 51 return block_code == UBLOCK_GEOMETRIC_SHAPES ||
52 block_code == UBLOCK_MISCELLANEOUS_SYMBOLS || 52 block_code == UBLOCK_MISCELLANEOUS_SYMBOLS;
53 block_code == UBLOCK_DINGBATS ||
54 block_code == UBLOCK_EMOTICONS;
55 } 53 }
56 54
57 bool IsBracket(UChar32 character) { 55 bool IsBracket(UChar32 character) {
58 static const char kBrackets[] = { '(', ')', '{', '}', '<', '>', }; 56 static const char kBrackets[] = { '(', ')', '{', '}', '<', '>', };
59 static const char* kBracketsEnd = kBrackets + arraysize(kBrackets); 57 static const char* kBracketsEnd = kBrackets + arraysize(kBrackets);
60 return std::find(kBrackets, kBracketsEnd, character) != kBracketsEnd; 58 return std::find(kBrackets, kBracketsEnd, character) != kBracketsEnd;
61 } 59 }
62 60
63 // Returns the boundary between a special and a regular character. Special 61 // Returns the boundary between a special and a regular character. Special
64 // characters are brackets or characters that satisfy |IsUnusualBlockCode|. 62 // characters are brackets or characters that satisfy |IsUnusualBlockCode|.
(...skipping 18 matching lines...) Expand all
83 const bool block_break = current_block != first_block && 81 const bool block_break = current_block != first_block &&
84 (first_block_unusual || IsUnusualBlockCode(current_block)); 82 (first_block_unusual || IsUnusualBlockCode(current_block));
85 if (block_break || current_char == '\n' || 83 if (block_break || current_char == '\n' ||
86 first_bracket != IsBracket(current_char)) { 84 first_bracket != IsBracket(current_char)) {
87 return run_start + iter.array_pos(); 85 return run_start + iter.array_pos();
88 } 86 }
89 } 87 }
90 return run_break; 88 return run_break;
91 } 89 }
92 90
93 // If the given scripts match, returns the one that isn't USCRIPT_COMMON or 91 // If the given scripts match, returns the one that isn't USCRIPT_INHERITED,
94 // USCRIPT_INHERITED, i.e. the more specific one. Otherwise returns 92 // i.e. the more specific one. Otherwise returns
95 // USCRIPT_INVALID_CODE. 93 // USCRIPT_INVALID_CODE.
96 UScriptCode ScriptIntersect(UScriptCode first, UScriptCode second) { 94 UScriptCode ScriptIntersect(UScriptCode first, UScriptCode second) {
97 if (first == second || 95 if (first == second || second == USCRIPT_INHERITED)
98 (second > USCRIPT_INVALID_CODE && second <= USCRIPT_INHERITED)) {
99 return first; 96 return first;
100 } 97 if (first == USCRIPT_INHERITED)
101 if (first > USCRIPT_INVALID_CODE && first <= USCRIPT_INHERITED)
102 return second; 98 return second;
103 return USCRIPT_INVALID_CODE; 99 return USCRIPT_INVALID_CODE;
104 } 100 }
105 101
106 // Writes the script and the script extensions of the character with the 102 // Writes the script and the script extensions of the character with the
107 // Unicode |codepoint|. Returns the number of written scripts. 103 // Unicode |codepoint|. Returns the number of written scripts.
108 int GetScriptExtensions(UChar32 codepoint, UScriptCode* scripts) { 104 int GetScriptExtensions(UChar32 codepoint, UScriptCode* scripts) {
109 UErrorCode icu_error = U_ZERO_ERROR; 105 UErrorCode icu_error = U_ZERO_ERROR;
110 // ICU documentation incorrectly states that the result of 106 // ICU documentation incorrectly states that the result of
111 // |uscript_getScriptExtensions| will contain the regular script property. 107 // |uscript_getScriptExtensions| will contain the regular script property.
(...skipping 47 matching lines...) Expand 10 before | Expand all | Expand 10 after
159 UScriptCode* script) { 155 UScriptCode* script) {
160 DCHECK_GT(length, 0U); 156 DCHECK_GT(length, 0U);
161 157
162 UScriptCode scripts[kMaxScripts] = { USCRIPT_INVALID_CODE }; 158 UScriptCode scripts[kMaxScripts] = { USCRIPT_INVALID_CODE };
163 159
164 base::i18n::UTF16CharIterator char_iterator(text.c_str() + start, length); 160 base::i18n::UTF16CharIterator char_iterator(text.c_str() + start, length);
165 size_t scripts_size = GetScriptExtensions(char_iterator.get(), scripts); 161 size_t scripts_size = GetScriptExtensions(char_iterator.get(), scripts);
166 *script = scripts[0]; 162 *script = scripts[0];
167 163
168 while (char_iterator.Advance()) { 164 while (char_iterator.Advance()) {
165 // Special handling to merge white space into the previous run.
166 if (u_isUWhiteSpace(char_iterator.get()))
167 continue;
169 ScriptSetIntersect(char_iterator.get(), scripts, &scripts_size); 168 ScriptSetIntersect(char_iterator.get(), scripts, &scripts_size);
170 if (scripts_size == 0U) 169 if (scripts_size == 0U)
171 return char_iterator.array_pos(); 170 return char_iterator.array_pos();
172 *script = scripts[0]; 171 *script = scripts[0];
173 } 172 }
174 173
175 return length; 174 return length;
176 } 175 }
177 176
178 // A port of hb_icu_script_to_script because harfbuzz on CrOS is built without 177 // A port of hb_icu_script_to_script because harfbuzz on CrOS is built without
(...skipping 37 matching lines...) Expand 10 before | Expand all | Expand 10 after
216 // than |max_width|. If |multiline| is false, only outputs a single Line from 215 // than |max_width|. If |multiline| is false, only outputs a single Line from
217 // the given runs. |min_baseline| and |min_height| are the minimum baseline and 216 // the given runs. |min_baseline| and |min_height| are the minimum baseline and
218 // height for each line. 217 // height for each line.
219 // TODO(ckocagil): Expose the interface of this class in the header and test 218 // TODO(ckocagil): Expose the interface of this class in the header and test
220 // this class directly. 219 // this class directly.
221 class HarfBuzzLineBreaker { 220 class HarfBuzzLineBreaker {
222 public: 221 public:
223 HarfBuzzLineBreaker(size_t max_width, 222 HarfBuzzLineBreaker(size_t max_width,
224 int min_baseline, 223 int min_baseline,
225 float min_height, 224 float min_height,
226 bool multiline,
227 WordWrapBehavior word_wrap_behavior, 225 WordWrapBehavior word_wrap_behavior,
228 const base::string16& text, 226 const base::string16& text,
229 const BreakList<size_t>* words, 227 const BreakList<size_t>* words,
230 const internal::TextRunList& run_list) 228 const internal::TextRunList& run_list)
231 : max_width_((max_width == 0) ? SK_ScalarMax : SkIntToScalar(max_width)), 229 : max_width_((max_width == 0) ? SK_ScalarMax : SkIntToScalar(max_width)),
232 min_baseline_(min_baseline), 230 min_baseline_(min_baseline),
233 min_height_(min_height), 231 min_height_(min_height),
234 multiline_(multiline),
235 word_wrap_behavior_(word_wrap_behavior), 232 word_wrap_behavior_(word_wrap_behavior),
236 text_(text), 233 text_(text),
237 words_(words), 234 words_(words),
238 run_list_(run_list), 235 run_list_(run_list),
236 max_descent_(0),
237 max_ascent_(0),
239 text_x_(0), 238 text_x_(0),
240 line_x_(0), 239 available_width_(max_width_) {
241 max_descent_(0),
242 max_ascent_(0) {
243 DCHECK_EQ(multiline_, (words_ != nullptr));
244 AdvanceLine(); 240 AdvanceLine();
245 } 241 }
246 242
247 // Breaks the run at given |run_index| into Line structs. 243 // Constructs a single line for |text_| using |run_list_|.
248 void AddRun(int run_index) { 244 void ConstructSingleLine() {
249 const internal::TextRunHarfBuzz* run = run_list_.runs()[run_index]; 245 for (size_t i = 0; i < run_list_.size(); i++) {
250 base::char16 first_char = text_[run->range.start()]; 246 const internal::TextRunHarfBuzz& run = *(run_list_.runs()[i]);
251 if (multiline_ && first_char == '\n') { 247 internal::LineSegment segment;
252 AdvanceLine(); 248 segment.run = i;
253 } else if (multiline_ && (line_x_ + SkFloatToScalar(run->width)) > 249 segment.char_range = run.range;
254 max_width_) { 250 segment.x_range = Range(SkScalarCeilToInt(text_x_),
255 BreakRun(run_index); 251 SkScalarCeilToInt(text_x_ + run.width));
256 } else { 252 segment.width = run.width;
257 AddSegment(run_index, run->range, run->width); 253 AddLineSegment(segment);
254 }
255 }
256
257 // Constructs multiple lines for |text_| based on words iteration approach.
258 void ConstructMultiLines() {
259 DCHECK(words_);
260 for (const auto& word : words_->breaks()) {
Jun Mukai 2015/05/16 00:21:57 Oops, I think previous code could be better if we
xdai1 2015/05/18 17:41:26 Done.
261 std::vector<internal::LineSegment> word_segments;
262 SkScalar word_width = GetWordWidth(&word, &word_segments);
Jun Mukai 2015/05/16 00:21:57 I think it's better to pass the range rather than
xdai1 2015/05/18 17:41:26 Done.
263
264 bool new_line = false;
265 if (!word_segments.empty()) {
266 // If the word is end with '\n', we should advance a new line after
267 // adding the word to current line.
268 const internal::LineSegment& last_segment = word_segments.back();
269 const base::char16 last_char = text_[last_segment.char_range.start()];
270 if (last_char == '\n') {
271 new_line = true;
272 word_width -= last_segment.width;
273 word_segments.pop_back();
274 }
275 }
276
277 // If the word is not the first word in the line and it can't fit into
278 // the current line, advance a new line.
279 if (word_width > available_width_ && available_width_ != max_width_)
280 AdvanceLine();
281 AddWordToLine(word_segments);
282 if (new_line)
283 AdvanceLine();
258 } 284 }
259 } 285 }
260 286
261 // Finishes line breaking and outputs the results. Can be called at most once. 287 // Finishes line breaking and outputs the results. Can be called at most once.
262 void Finalize(std::vector<internal::Line>* lines, SizeF* size) { 288 void FinalizeLines(std::vector<internal::Line>* lines, SizeF* size) {
263 DCHECK(!lines_.empty()); 289 DCHECK(!lines_.empty());
264 // Add an empty line to finish the line size calculation and remove it. 290 // Add an empty line to finish the line size calculation and remove it.
265 AdvanceLine(); 291 AdvanceLine();
266 lines_.pop_back(); 292 lines_.pop_back();
267 *size = total_size_; 293 *size = total_size_;
268 lines->swap(lines_); 294 lines->swap(lines_);
269 } 295 }
270 296
271 private: 297 private:
272 // A (line index, segment index) pair that specifies a segment in |lines_|. 298 // A (line index, segment index) pair that specifies a segment in |lines_|.
273 typedef std::pair<size_t, size_t> SegmentHandle; 299 typedef std::pair<size_t, size_t> SegmentHandle;
274 300
275 internal::LineSegment* SegmentFromHandle(const SegmentHandle& handle) { 301 internal::LineSegment* SegmentFromHandle(const SegmentHandle& handle) {
276 return &lines_[handle.first].segments[handle.second]; 302 return &lines_[handle.first].segments[handle.second];
277 } 303 }
278 304
279 // Breaks a run into segments that fit in the last line in |lines_| and adds
280 // them. Adds a new Line to the back of |lines_| whenever a new segment can't
281 // be added without the Line's width exceeding |max_width_|.
282 void BreakRun(int run_index) {
283 const internal::TextRunHarfBuzz& run = *(run_list_.runs()[run_index]);
284 SkScalar width = 0;
285 size_t next_char = run.range.start();
286
287 // Break the run until it fits the current line.
288 while (next_char < run.range.end()) {
289 const size_t current_char = next_char;
290 size_t end_char = next_char;
291 const bool skip_line =
292 BreakRunAtWidth(run, current_char, &width, &end_char, &next_char);
293 AddSegment(run_index, Range(current_char, end_char),
294 SkScalarToFloat(width));
295 if (skip_line)
296 AdvanceLine();
297 }
298 }
299
300 // Starting from |start_char|, finds a suitable line break position at or
301 // before available width using word break. If the current position is at the
302 // beginning of a line, this function will not roll back to |start_char| and
303 // |*next_char| will be greater than |start_char| (to avoid constructing empty
304 // lines). It stores the end of the segment range to |end_char|, which can be
305 // smaller than |*next_char| for certain word wrapping behavior.
306 // Returns whether to skip the line before |*next_char|.
307 // TODO(ckocagil): We might have to reshape after breaking at ligatures.
308 // See whether resolving the TODO above resolves this too.
309 // TODO(ckocagil): Do not reserve width for whitespace at the end of lines.
310 bool BreakRunAtWidth(const internal::TextRunHarfBuzz& run,
311 size_t start_char,
312 SkScalar* width,
313 size_t* end_char,
314 size_t* next_char) {
315 DCHECK(words_);
316 DCHECK(run.range.Contains(Range(start_char, start_char + 1)));
317 SkScalar available_width = max_width_ - line_x_;
318 BreakList<size_t>::const_iterator word = words_->GetBreak(start_char);
319 BreakList<size_t>::const_iterator next_word = word + 1;
320 // Width from |std::max(word->first, start_char)| to the current character.
321 SkScalar word_width = 0;
322 *width = 0;
323
324 Range char_range;
325 SkScalar truncated_width = 0;
326 for (size_t i = start_char; i < run.range.end(); i += char_range.length()) {
327 // |word| holds the word boundary at or before |i|, and |next_word| holds
328 // the word boundary right after |i|. Advance both |word| and |next_word|
329 // when |i| reaches |next_word|.
330 if (next_word != words_->breaks().end() && i >= next_word->first) {
331 if (*width > available_width) {
332 DCHECK_NE(WRAP_LONG_WORDS, word_wrap_behavior_);
333 *next_char = i;
334 if (word_wrap_behavior_ != TRUNCATE_LONG_WORDS)
335 *end_char = *next_char;
336 else
337 *width = truncated_width;
338 return true;
339 }
340 word = next_word++;
341 word_width = 0;
342 }
343
344 Range glyph_range;
345 run.GetClusterAt(i, &char_range, &glyph_range);
346 DCHECK_LT(0U, char_range.length());
347
348 SkScalar char_width = ((glyph_range.end() >= run.glyph_count)
349 ? SkFloatToScalar(run.width)
350 : run.positions[glyph_range.end()].x()) -
351 run.positions[glyph_range.start()].x();
352
353 *width += char_width;
354 word_width += char_width;
355
356 // TODO(mukai): implement ELIDE_LONG_WORDS.
357 if (*width > available_width) {
358 if (line_x_ != 0 || word_width < *width) {
359 // Roll back one word.
360 *width -= word_width;
361 *next_char = std::max(word->first, start_char);
362 *end_char = *next_char;
363 return true;
364 } else if (word_wrap_behavior_ == WRAP_LONG_WORDS) {
365 if (char_width < *width) {
366 // Roll back one character.
367 *width -= char_width;
368 *next_char = i;
369 } else {
370 // Continue from the next character.
371 *next_char = i + char_range.length();
372 }
373 *end_char = *next_char;
374 return true;
375 }
376 } else {
377 *end_char = char_range.end();
378 truncated_width = *width;
379 }
380 }
381
382 if (word_wrap_behavior_ == TRUNCATE_LONG_WORDS)
383 *width = truncated_width;
384 *end_char = *next_char = run.range.end();
385 return false;
386 }
387
388 // RTL runs are broken in logical order but displayed in visual order. To find
389 // the text-space coordinate (where it would fall in a single-line text)
390 // |x_range| of RTL segments, segment widths are applied in reverse order.
391 // e.g. {[5, 10], [10, 40]} will become {[35, 40], [5, 35]}.
392 void UpdateRTLSegmentRanges() {
393 if (rtl_segments_.empty())
394 return;
395 float x = SegmentFromHandle(rtl_segments_[0])->x_range.start();
396 for (size_t i = rtl_segments_.size(); i > 0; --i) {
397 internal::LineSegment* segment = SegmentFromHandle(rtl_segments_[i - 1]);
398 const float segment_width = segment->width;
399 segment->x_range = Range(x, x + segment_width);
400 x += segment_width;
401 }
402 rtl_segments_.clear();
403 }
404
405 // Finishes the size calculations of the last Line in |lines_|. Adds a new 305 // Finishes the size calculations of the last Line in |lines_|. Adds a new
406 // Line to the back of |lines_|. 306 // Line to the back of |lines_|.
407 void AdvanceLine() { 307 void AdvanceLine() {
408 if (!lines_.empty()) { 308 if (!lines_.empty()) {
409 internal::Line* line = &lines_.back(); 309 internal::Line* line = &lines_.back();
410 std::sort(line->segments.begin(), line->segments.end(), 310 std::sort(line->segments.begin(), line->segments.end(),
411 [this](const internal::LineSegment& s1, 311 [this](const internal::LineSegment& s1,
412 const internal::LineSegment& s2) -> bool { 312 const internal::LineSegment& s2) -> bool {
413 return run_list_.logical_to_visual(s1.run) < 313 return run_list_.logical_to_visual(s1.run) <
414 run_list_.logical_to_visual(s2.run); 314 run_list_.logical_to_visual(s2.run);
415 }); 315 });
416 line->size.set_height(std::max(min_height_, max_descent_ + max_ascent_)); 316 line->size.set_height(std::max(min_height_, max_descent_ + max_ascent_));
417 line->baseline = 317 line->baseline = std::max(min_baseline_, SkScalarRoundToInt(max_ascent_));
418 std::max(min_baseline_, SkScalarRoundToInt(max_ascent_));
419 line->preceding_heights = std::ceil(total_size_.height()); 318 line->preceding_heights = std::ceil(total_size_.height());
420 total_size_.set_height(total_size_.height() + line->size.height()); 319 total_size_.set_height(total_size_.height() + line->size.height());
421 total_size_.set_width(std::max(total_size_.width(), line->size.width())); 320 total_size_.set_width(std::max(total_size_.width(), line->size.width()));
422 } 321 }
423 max_descent_ = 0; 322 max_descent_ = 0;
424 max_ascent_ = 0; 323 max_ascent_ = 0;
425 line_x_ = 0; 324 available_width_ = max_width_;
426 lines_.push_back(internal::Line()); 325 lines_.push_back(internal::Line());
427 } 326 }
428 327
429 // Adds a new segment with the given properties to |lines_.back()|. 328 // Adds word to the current line. A word may contain multiple segments. If the
430 void AddSegment(int run_index, Range char_range, float width) { 329 // word is the first word in line and its width exceeds |available_width_|,
431 if (char_range.is_empty()) { 330 // ignore/truncate/wrap it according to |word_wrap_behavior_|.
432 DCHECK_EQ(0, width); 331 void AddWordToLine(std::vector<internal::LineSegment>& word_segments) {
332 DCHECK(!lines_.empty());
333 if (word_segments.empty())
433 return; 334 return;
335
336 bool has_truncated = false;
337 for (internal::LineSegment& segment : word_segments) {
338 if (has_truncated)
339 break;
340 if (segment.width <= available_width_ ||
341 word_wrap_behavior_ == IGNORE_LONG_WORDS) {
342 AddLineSegment(segment);
343 } else {
344 DCHECK(word_wrap_behavior_ == TRUNCATE_LONG_WORDS ||
345 word_wrap_behavior_ == WRAP_LONG_WORDS);
346 has_truncated = (word_wrap_behavior_ == TRUNCATE_LONG_WORDS);
347
348 while (!segment.char_range.is_empty()) {
349 size_t cutoff_pos = 0;
350 SkScalar width = GetCutoffWidth(segment, &cutoff_pos);
351 if (width == 0 && available_width_ == max_width_) {
352 // |max_width_| might be smaller than a single character. In this
353 // case we need to put at least one character in the line.
354 // See RenderTextTest.Multiline_MinWidth for example.
355 cutoff_pos = segment.char_range.start() + 1;
356 const internal::TextRunHarfBuzz& run =
357 *(run_list_.runs()[segment.run]);
358 width = run.GetGlyphWidthForCharRange(
359 Range(segment.char_range.start(), cutoff_pos));
360 }
361 if (width > 0) {
362 internal::LineSegment cut_segment;
363 cut_segment.run = segment.run;
364 cut_segment.char_range =
365 Range(segment.char_range.start(), cutoff_pos);
366 cut_segment.width = width;
367 cut_segment.x_range = Range(segment.x_range.start(),
368 SkScalarCeilToInt(text_x_ + width));
369 AddLineSegment(cut_segment);
370 // Updates old segment.
371 segment.char_range.set_start(cutoff_pos);
372 segment.x_range.set_start(SkScalarCeilToInt(text_x_));
373 segment.width -= width;
374 }
375 if (has_truncated)
376 break;
377 if (!segment.char_range.is_empty())
378 AdvanceLine();
379 }
380 }
434 } 381 }
435 const internal::TextRunHarfBuzz& run = *(run_list_.runs()[run_index]); 382 }
436 383
437 internal::LineSegment segment; 384 // Add line segment to current line. Note in order to keep the visual order
438 segment.run = run_index; 385 // correct for ltr and rtl language, we need to merge segments that belong to
439 segment.char_range = char_range; 386 // a same run.
440 segment.x_range = Range( 387 void AddLineSegment(internal::LineSegment& segment) {
441 SkScalarCeilToInt(text_x_), 388 DCHECK(!lines_.empty());
442 SkScalarCeilToInt(text_x_ + SkFloatToScalar(width)));
443 segment.width = width;
444
445 internal::Line* line = &lines_.back(); 389 internal::Line* line = &lines_.back();
390 const internal::TextRunHarfBuzz& run = *(run_list_.runs()[segment.run]);
391 if (!line->segments.empty()) {
392 const internal::LineSegment& last_segment = line->segments.back();
393 // Merge segments that belong to the same run.
394 if (last_segment.run == segment.run) {
395 segment.char_range.set_start(last_segment.char_range.start());
396 segment.width += last_segment.width;
397 segment.x_range.set_start(
398 SkScalarCeilToInt(text_x_ - last_segment.width));
399 line->segments.pop_back();
400 if (run.is_rtl)
401 rtl_segments_.pop_back();
402 line->size.set_width(line->size.width() - last_segment.width);
403 text_x_ -= last_segment.width;
404 available_width_ += last_segment.width;
405 }
406 }
446 line->segments.push_back(segment); 407 line->segments.push_back(segment);
447 408
448 SkPaint paint; 409 SkPaint paint;
449 paint.setTypeface(run.skia_face.get()); 410 paint.setTypeface(run.skia_face.get());
450 paint.setTextSize(SkIntToScalar(run.font_size)); 411 paint.setTextSize(SkIntToScalar(run.font_size));
451 paint.setAntiAlias(run.render_params.antialiasing); 412 paint.setAntiAlias(run.render_params.antialiasing);
452 SkPaint::FontMetrics metrics; 413 SkPaint::FontMetrics metrics;
453 paint.getFontMetrics(&metrics); 414 paint.getFontMetrics(&metrics);
454 415
455 line->size.set_width(line->size.width() + width); 416 line->size.set_width(line->size.width() + segment.width);
456 // TODO(dschuyler): Account for stylized baselines in string sizing. 417 // TODO(dschuyler): Account for stylized baselines in string sizing.
457 max_descent_ = std::max(max_descent_, metrics.fDescent); 418 max_descent_ = std::max(max_descent_, metrics.fDescent);
458 // fAscent is always negative. 419 // fAscent is always negative.
459 max_ascent_ = std::max(max_ascent_, -metrics.fAscent); 420 max_ascent_ = std::max(max_ascent_, -metrics.fAscent);
460 421
461 if (run.is_rtl) { 422 if (run.is_rtl) {
462 rtl_segments_.push_back( 423 rtl_segments_.push_back(
463 SegmentHandle(lines_.size() - 1, line->segments.size() - 1)); 424 SegmentHandle(lines_.size() - 1, line->segments.size() - 1));
464 // If this is the last segment of an RTL run, reprocess the text-space x 425 // If this is the last segment of an RTL run, reprocess the text-space x
465 // ranges of all segments from the run. 426 // ranges of all segments from the run.
466 if (char_range.end() == run.range.end()) 427 if (segment.char_range.end() == run.range.end())
467 UpdateRTLSegmentRanges(); 428 UpdateRTLSegmentRanges();
468 } 429 }
469 text_x_ += SkFloatToScalar(width); 430 text_x_ += segment.width;
470 line_x_ += SkFloatToScalar(width); 431 available_width_ -= segment.width;
432 }
433
434 // Finds the end position |end_pos| in |segment| that the preceding width is
435 // no larger than |available_width_|, and returns the preceding width.
436 SkScalar GetCutoffWidth(const internal::LineSegment& segment,
437 size_t* end_pos) const {
438 DCHECK(!segment.char_range.is_empty());
439 const internal::TextRunHarfBuzz& run = *(run_list_.runs()[segment.run]);
440 *end_pos = segment.char_range.start();
441 SkScalar width = 0;
442 while (*end_pos < segment.char_range.end()) {
443 const SkScalar char_width =
444 run.GetGlyphWidthForCharRange(Range(*end_pos, *end_pos + 1));
445 if (width + char_width > available_width_)
446 break;
447 width += char_width;
448 *end_pos += 1;
449 }
450 return width;
451 }
452
453 // Gets the glyph width for |word|, and splits the |word| into different
454 // segments based on its runs.
455 SkScalar GetWordWidth(const gfx::BreakList<size_t>::Break* word,
456 std::vector<internal::LineSegment>* segments) const {
457 DCHECK(word && words_);
458 int word_st = word->first;
459 int word_en = (*word == words_->breaks().back()) ? text_.size() - 1
460 : (word + 1)->first - 1;
461 if (word_en < 0 || word_en < word_st)
462 return 0;
463 size_t run_st_idx = run_list_.GetRunIndexAt(word_st);
464 size_t run_en_idx = run_list_.GetRunIndexAt(word_en);
Jun Mukai 2015/05/16 00:21:57 Let's rename run_start_index and run_end_index. U
xdai1 2015/05/18 17:41:26 Done.
465 SkScalar width = 0;
466 for (size_t idx = run_st_idx; idx <= run_en_idx; idx++) {
467 const internal::TextRunHarfBuzz& run = *(run_list_.runs()[idx]);
468 const Range char_range = run.range.Intersect(Range(word_st, word_en + 1));
Jun Mukai 2015/05/16 00:21:57 if (char_range.IsEmpty()) continue; I am not sure
xdai1 2015/05/18 17:41:26 Done.
469 const SkScalar char_width = run.GetGlyphWidthForCharRange(char_range);
470 width += char_width;
471
472 internal::LineSegment segment;
473 segment.run = idx;
474 segment.char_range = char_range;
475 segment.width = char_width;
476 segment.x_range = Range(SkScalarCeilToInt(text_x_ + width - char_width),
477 SkScalarCeilToInt(text_x_ + width));
478 segments->push_back(segment);
479 }
480 return width;
481 }
482
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())
489 return;
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 = Range(x, x + segment_width);
495 x += segment_width;
496 }
497 rtl_segments_.clear();
471 } 498 }
472 499
473 const SkScalar max_width_; 500 const SkScalar max_width_;
474 const int min_baseline_; 501 const int min_baseline_;
475 const float min_height_; 502 const float min_height_;
476 const bool multiline_;
477 const WordWrapBehavior word_wrap_behavior_; 503 const WordWrapBehavior word_wrap_behavior_;
478 const base::string16& text_; 504 const base::string16& text_;
479 const BreakList<size_t>* const words_; 505 const BreakList<size_t>* const words_;
480 const internal::TextRunList& run_list_; 506 const internal::TextRunList& run_list_;
481 507
482 // Stores the resulting lines. 508 // Stores the resulting lines.
483 std::vector<internal::Line> lines_; 509 std::vector<internal::Line> lines_;
484 510
485 // Text space and line space x coordinates of the next segment to be added.
486 SkScalar text_x_;
487 SkScalar line_x_;
488
489 float max_descent_; 511 float max_descent_;
490 float max_ascent_; 512 float max_ascent_;
491 513
514 // Text space x coordinates of the next segment to be added.
515 SkScalar text_x_;
516 // Stores available width in the current line.
517 SkScalar available_width_;
518
492 // Size of the multiline text, not including the currently processed line. 519 // Size of the multiline text, not including the currently processed line.
493 SizeF total_size_; 520 SizeF total_size_;
494 521
495 // The current RTL run segments, to be applied by |UpdateRTLSegmentRanges()|. 522 // The current RTL run segments, to be applied by |UpdateRTLSegmentRanges()|.
496 std::vector<SegmentHandle> rtl_segments_; 523 std::vector<SegmentHandle> rtl_segments_;
497 524
498 DISALLOW_COPY_AND_ASSIGN(HarfBuzzLineBreaker); 525 DISALLOW_COPY_AND_ASSIGN(HarfBuzzLineBreaker);
499 }; 526 };
500 527
501 // Function object for case insensitive string comparison. 528 // Function object for case insensitive string comparison.
(...skipping 23 matching lines...) Expand all
525 baseline_offset(0), 552 baseline_offset(0),
526 baseline_type(0), 553 baseline_type(0),
527 font_style(0), 554 font_style(0),
528 strike(false), 555 strike(false),
529 diagonal_strike(false), 556 diagonal_strike(false),
530 underline(false) { 557 underline(false) {
531 } 558 }
532 559
533 TextRunHarfBuzz::~TextRunHarfBuzz() {} 560 TextRunHarfBuzz::~TextRunHarfBuzz() {}
534 561
535 void TextRunHarfBuzz::GetClusterAt(size_t pos,
536 Range* chars,
537 Range* glyphs) const {
538 DCHECK(range.Contains(Range(pos, pos + 1)));
539 DCHECK(chars);
540 DCHECK(glyphs);
541
542 if (glyph_count == 0) {
543 *chars = range;
544 *glyphs = Range();
545 return;
546 }
547
548 if (is_rtl) {
549 GetClusterAtImpl(pos, range, glyph_to_char.rbegin(), glyph_to_char.rend(),
550 true, chars, glyphs);
551 return;
552 }
553
554 GetClusterAtImpl(pos, range, glyph_to_char.begin(), glyph_to_char.end(),
555 false, chars, glyphs);
556 }
557
558 Range TextRunHarfBuzz::CharRangeToGlyphRange(const Range& char_range) const { 562 Range TextRunHarfBuzz::CharRangeToGlyphRange(const Range& char_range) const {
559 DCHECK(range.Contains(char_range)); 563 DCHECK(range.Contains(char_range));
560 DCHECK(!char_range.is_reversed()); 564 DCHECK(!char_range.is_reversed());
561 DCHECK(!char_range.is_empty()); 565 DCHECK(!char_range.is_empty());
562 566
563 Range start_glyphs; 567 Range start_glyphs;
564 Range end_glyphs; 568 Range end_glyphs;
565 Range temp_range; 569 Range temp_range;
566 GetClusterAt(char_range.start(), &temp_range, &start_glyphs); 570 GetClusterAt(char_range.start(), &temp_range, &start_glyphs);
567 GetClusterAt(char_range.end() - 1, &temp_range, &end_glyphs); 571 GetClusterAt(char_range.end() - 1, &temp_range, &end_glyphs);
568 572
569 return is_rtl ? Range(end_glyphs.start(), start_glyphs.end()) : 573 return is_rtl ? Range(end_glyphs.start(), start_glyphs.end()) :
570 Range(start_glyphs.start(), end_glyphs.end()); 574 Range(start_glyphs.start(), end_glyphs.end());
571 } 575 }
572 576
573 size_t TextRunHarfBuzz::CountMissingGlyphs() const { 577 size_t TextRunHarfBuzz::CountMissingGlyphs() const {
574 static const int kMissingGlyphId = 0; 578 static const int kMissingGlyphId = 0;
575 size_t missing = 0; 579 size_t missing = 0;
576 for (size_t i = 0; i < glyph_count; ++i) 580 for (size_t i = 0; i < glyph_count; ++i)
577 missing += (glyphs[i] == kMissingGlyphId) ? 1 : 0; 581 missing += (glyphs[i] == kMissingGlyphId) ? 1 : 0;
578 return missing; 582 return missing;
579 } 583 }
580 584
585 void TextRunHarfBuzz::GetClusterAt(size_t pos,
586 Range* chars,
587 Range* glyphs) const {
588 DCHECK(range.Contains(Range(pos, pos + 1)));
589 DCHECK(chars);
590 DCHECK(glyphs);
591
592 if (glyph_count == 0) {
593 *chars = range;
594 *glyphs = Range();
595 return;
596 }
597
598 if (is_rtl) {
599 GetClusterAtImpl(pos, range, glyph_to_char.rbegin(), glyph_to_char.rend(),
600 true, chars, glyphs);
601 return;
602 }
603
604 GetClusterAtImpl(pos, range, glyph_to_char.begin(), glyph_to_char.end(),
605 false, chars, glyphs);
606 }
607
581 RangeF TextRunHarfBuzz::GetGraphemeBounds( 608 RangeF TextRunHarfBuzz::GetGraphemeBounds(
582 base::i18n::BreakIterator* grapheme_iterator, 609 base::i18n::BreakIterator* grapheme_iterator,
583 size_t text_index) { 610 size_t text_index) {
584 DCHECK_LT(text_index, range.end()); 611 DCHECK_LT(text_index, range.end());
585 if (glyph_count == 0) 612 if (glyph_count == 0)
586 return RangeF(preceding_run_widths, preceding_run_widths + width); 613 return RangeF(preceding_run_widths, preceding_run_widths + width);
587 614
588 Range chars; 615 Range chars;
589 Range glyphs; 616 Range glyphs;
590 GetClusterAt(text_index, &chars, &glyphs); 617 GetClusterAt(text_index, &chars, &glyphs);
(...skipping 28 matching lines...) Expand all
619 cluster_width * (before + 1) / static_cast<float>(total)); 646 cluster_width * (before + 1) / static_cast<float>(total));
620 return RangeF(preceding_run_widths + grapheme_begin_x, 647 return RangeF(preceding_run_widths + grapheme_begin_x,
621 preceding_run_widths + grapheme_end_x); 648 preceding_run_widths + grapheme_end_x);
622 } 649 }
623 } 650 }
624 651
625 return RangeF(preceding_run_widths + cluster_begin_x, 652 return RangeF(preceding_run_widths + cluster_begin_x,
626 preceding_run_widths + cluster_end_x); 653 preceding_run_widths + cluster_end_x);
627 } 654 }
628 655
656 SkScalar TextRunHarfBuzz::GetGlyphWidthForCharRange(
657 const Range& char_range) const {
658 DCHECK(range.Contains(char_range));
659 Range glyph_range = CharRangeToGlyphRange(char_range);
660 return ((glyph_range.end() >= glyph_count)
661 ? SkFloatToScalar(width)
662 : positions[glyph_range.end()].x()) -
663 positions[glyph_range.start()].x();
664 }
665
629 TextRunList::TextRunList() : width_(0.0f) {} 666 TextRunList::TextRunList() : width_(0.0f) {}
630 667
631 TextRunList::~TextRunList() {} 668 TextRunList::~TextRunList() {}
632 669
633 void TextRunList::Reset() { 670 void TextRunList::Reset() {
634 runs_.clear(); 671 runs_.clear();
635 width_ = 0.0f; 672 width_ = 0.0f;
636 } 673 }
637 674
638 void TextRunList::InitIndexMap() { 675 void TextRunList::InitIndexMap() {
(...skipping 14 matching lines...) Expand all
653 void TextRunList::ComputePrecedingRunWidths() { 690 void TextRunList::ComputePrecedingRunWidths() {
654 // Precalculate run width information. 691 // Precalculate run width information.
655 width_ = 0.0f; 692 width_ = 0.0f;
656 for (size_t i = 0; i < runs_.size(); ++i) { 693 for (size_t i = 0; i < runs_.size(); ++i) {
657 TextRunHarfBuzz* run = runs_[visual_to_logical_[i]]; 694 TextRunHarfBuzz* run = runs_[visual_to_logical_[i]];
658 run->preceding_run_widths = width_; 695 run->preceding_run_widths = width_;
659 width_ += run->width; 696 width_ += run->width;
660 } 697 }
661 } 698 }
662 699
700 size_t TextRunList::GetRunIndexAt(size_t position) const {
701 for (size_t i = 0; i < runs_.size(); ++i) {
702 if (runs_[i]->range.start() <= position && runs_[i]->range.end() > position)
703 return i;
704 }
705 return runs_.size();
706 }
707
663 } // namespace internal 708 } // namespace internal
664 709
665 RenderTextHarfBuzz::RenderTextHarfBuzz() 710 RenderTextHarfBuzz::RenderTextHarfBuzz()
666 : RenderText(), 711 : RenderText(),
667 update_layout_run_list_(false), 712 update_layout_run_list_(false),
668 update_display_run_list_(false), 713 update_display_run_list_(false),
669 update_grapheme_iterator_(false), 714 update_grapheme_iterator_(false),
670 update_display_text_(false), 715 update_display_text_(false),
671 glyph_width_for_test_(0u) { 716 glyph_width_for_test_(0u) {
672 set_truncate_length(kMaxTextLength); 717 set_truncate_length(kMaxTextLength);
(...skipping 328 matching lines...) Expand 10 before | Expand all | Expand 10 after
1001 if (lines().empty()) { 1046 if (lines().empty()) {
1002 // TODO(ckocagil): Remove ScopedTracker below once crbug.com/441028 is 1047 // TODO(ckocagil): Remove ScopedTracker below once crbug.com/441028 is
1003 // fixed. 1048 // fixed.
1004 scoped_ptr<tracked_objects::ScopedTracker> tracking_profile( 1049 scoped_ptr<tracked_objects::ScopedTracker> tracking_profile(
1005 new tracked_objects::ScopedTracker( 1050 new tracked_objects::ScopedTracker(
1006 FROM_HERE_WITH_EXPLICIT_FUNCTION("441028 HarfBuzzLineBreaker"))); 1051 FROM_HERE_WITH_EXPLICIT_FUNCTION("441028 HarfBuzzLineBreaker")));
1007 1052
1008 internal::TextRunList* run_list = GetRunList(); 1053 internal::TextRunList* run_list = GetRunList();
1009 HarfBuzzLineBreaker line_breaker( 1054 HarfBuzzLineBreaker line_breaker(
1010 display_rect().width(), font_list().GetBaseline(), 1055 display_rect().width(), font_list().GetBaseline(),
1011 std::max(font_list().GetHeight(), min_line_height()), multiline(), 1056 std::max(font_list().GetHeight(), min_line_height()),
1012 word_wrap_behavior(), GetDisplayText(), 1057 word_wrap_behavior(), GetDisplayText(),
1013 multiline() ? &GetLineBreaks() : nullptr, *run_list); 1058 multiline() ? &GetLineBreaks() : nullptr, *run_list);
1014 1059
1015 tracking_profile.reset(); 1060 tracking_profile.reset();
1016 1061
1017 for (size_t i = 0; i < run_list->size(); ++i) 1062 if (multiline())
1018 line_breaker.AddRun(i); 1063 line_breaker.ConstructMultiLines();
1064 else
1065 line_breaker.ConstructSingleLine();
1019 std::vector<internal::Line> lines; 1066 std::vector<internal::Line> lines;
1020 line_breaker.Finalize(&lines, &total_size_); 1067 line_breaker.FinalizeLines(&lines, &total_size_);
1021 set_lines(&lines); 1068 set_lines(&lines);
1022 } 1069 }
1023 } 1070 }
1024 1071
1025 void RenderTextHarfBuzz::DrawVisualText(Canvas* canvas) { 1072 void RenderTextHarfBuzz::DrawVisualText(Canvas* canvas) {
1026 internal::SkiaTextRenderer renderer(canvas); 1073 internal::SkiaTextRenderer renderer(canvas);
1027 DrawVisualTextInternal(&renderer); 1074 DrawVisualTextInternal(&renderer);
1028 } 1075 }
1029 1076
1030 void RenderTextHarfBuzz::DrawVisualTextInternal( 1077 void RenderTextHarfBuzz::DrawVisualTextInternal(
(...skipping 448 matching lines...) Expand 10 before | Expand all | Expand 10 after
1479 DCHECK(!update_layout_run_list_); 1526 DCHECK(!update_layout_run_list_);
1480 DCHECK(!update_display_run_list_); 1527 DCHECK(!update_display_run_list_);
1481 return text_elided() ? display_run_list_.get() : &layout_run_list_; 1528 return text_elided() ? display_run_list_.get() : &layout_run_list_;
1482 } 1529 }
1483 1530
1484 const internal::TextRunList* RenderTextHarfBuzz::GetRunList() const { 1531 const internal::TextRunList* RenderTextHarfBuzz::GetRunList() const {
1485 return const_cast<RenderTextHarfBuzz*>(this)->GetRunList(); 1532 return const_cast<RenderTextHarfBuzz*>(this)->GetRunList();
1486 } 1533 }
1487 1534
1488 } // namespace gfx 1535 } // namespace gfx
OLDNEW
« no previous file with comments | « ui/gfx/render_text_harfbuzz.h ('k') | ui/gfx/render_text_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698