1 // Copyright (c) 2012 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_win.h"
9 #include "base/i18n/break_iterator.h"
10 #include "base/i18n/char_iterator.h"
11 #include "base/i18n/rtl.h"
12 #include "base/logging.h"
13 #include "base/strings/string_util.h"
14 #include "base/strings/utf_string_conversions.h"
15 #include "base/win/windows_version.h"
16 #include "third_party/icu/source/common/unicode/uchar.h"
17 #include "ui/gfx/canvas.h"
18 #include "ui/gfx/font_fallback_win.h"
19 #include "ui/gfx/font_smoothing_win.h"
20 #include "ui/gfx/platform_font_win.h"
21 #include "ui/gfx/utf16_indexing.h"
27 // The maximum length of text supported for Uniscribe layout and display.
28 // This empirically chosen value should prevent major performance degradations.
29 // TODO(msw): Support longer text, partial layout/painting, etc.
30 const size_t kMaxUniscribeTextLength = 10000;
32 // The initial guess and maximum supported number of runs; arbitrary values.
33 // TODO(msw): Support more runs, determine a better initial guess, etc.
34 const int kGuessRuns = 100;
35 const size_t kMaxRuns = 10000;
37 // The maximum number of glyphs per run; ScriptShape fails on larger values.
38 const size_t kMaxGlyphs = 65535;
40 // Callback to |EnumEnhMetaFile()| to intercept font creation.
41 int CALLBACK MetaFileEnumProc(HDC hdc,
43 CONST ENHMETARECORD* record,
46 if (record->iType == EMR_EXTCREATEFONTINDIRECTW) {
47 const EMREXTCREATEFONTINDIRECTW* create_font_record =
48 reinterpret_cast<const EMREXTCREATEFONTINDIRECTW*>(record);
49 *reinterpret_cast<LOGFONT*>(log_font) = create_font_record->elfw.elfLogFont;
54 // Finds a fallback font to use to render the specified |text| with respect to
55 // an initial |font|. Returns the resulting font via out param |result|. Returns
56 // |true| if a fallback font was found.
57 // Adapted from WebKit's |FontCache::GetFontDataForCharacters()|.
58 // TODO(asvitkine): This should be moved to font_fallback_win.cc.
59 bool ChooseFallbackFont(HDC hdc,
64 // Use a meta file to intercept the fallback font chosen by Uniscribe.
65 HDC meta_file_dc = CreateEnhMetaFile(hdc, NULL, NULL, NULL);
69 SelectObject(meta_file_dc, font.GetNativeFont());
71 SCRIPT_STRING_ANALYSIS script_analysis;
73 ScriptStringAnalyse(meta_file_dc, text, text_length, 0, -1,
74 SSA_METAFILE | SSA_FALLBACK | SSA_GLYPHS | SSA_LINK,
75 0, NULL, NULL, NULL, NULL, NULL, &script_analysis);
77 if (SUCCEEDED(hresult)) {
78 hresult = ScriptStringOut(script_analysis, 0, 0, 0, NULL, 0, 0, FALSE);
79 ScriptStringFree(&script_analysis);
82 bool found_fallback = false;
83 HENHMETAFILE meta_file = CloseEnhMetaFile(meta_file_dc);
84 if (SUCCEEDED(hresult)) {
86 log_font.lfFaceName[0] = 0;
87 EnumEnhMetaFile(0, meta_file, MetaFileEnumProc, &log_font, NULL);
88 if (log_font.lfFaceName[0]) {
89 *result = Font(UTF16ToUTF8(log_font.lfFaceName), font.GetFontSize());
90 found_fallback = true;
93 DeleteEnhMetaFile(meta_file);
95 return found_fallback;
98 // Changes |font| to have the specified |font_size| (or |font_height| on Windows
99 // XP) and |font_style| if it is not the case already. Only considers bold and
100 // italic styles, since the underlined style has no effect on glyph shaping.
101 void DeriveFontIfNecessary(int font_size,
105 const int kStyleMask = (Font::BOLD | Font::ITALIC);
106 const int target_style = (font_style & kStyleMask);
108 // On Windows XP, the font must be resized using |font_height| instead of
109 // |font_size| to match GDI behavior.
110 if (base::win::GetVersion() < base::win::VERSION_VISTA) {
111 PlatformFontWin* platform_font =
112 static_cast<PlatformFontWin*>(font->platform_font());
113 *font = platform_font->DeriveFontWithHeight(font_height, target_style);
117 const int current_style = (font->GetStyle() & kStyleMask);
118 const int current_size = font->GetFontSize();
119 if (current_style != target_style || current_size != font_size)
120 *font = font->DeriveFont(font_size - current_size, target_style);
123 // Returns true if |c| is a Unicode BiDi control character.
124 bool IsUnicodeBidiControlCharacter(char16 c) {
125 return c == base::i18n::kRightToLeftMark ||
126 c == base::i18n::kLeftToRightMark ||
127 c == base::i18n::kLeftToRightEmbeddingMark ||
128 c == base::i18n::kRightToLeftEmbeddingMark ||
129 c == base::i18n::kPopDirectionalFormatting ||
130 c == base::i18n::kLeftToRightOverride ||
131 c == base::i18n::kRightToLeftOverride;
134 // Returns the corresponding glyph range of the given character range.
135 // |range| is in text-space (0 corresponds to |GetLayoutText()[0]|).
136 // Returned value is in run-space (0 corresponds to the first glyph in the run).
137 Range CharRangeToGlyphRange(const internal::TextRun& run,
138 const Range& range) {
139 DCHECK(run.range.Contains(range));
140 DCHECK(!range.is_reversed());
141 DCHECK(!range.is_empty());
142 const Range run_range(range.start() - run.range.start(),
143 range.end() - run.range.start());
145 if (run.script_analysis.fRTL) {
146 result = Range(run.logical_clusters[run_range.end() - 1],
147 run_range.start() > 0 ? run.logical_clusters[run_range.start() - 1]
150 result = Range(run.logical_clusters[run_range.start()],
151 run_range.end() < run.range.length() ?
152 run.logical_clusters[run_range.end()] : run.glyph_count);
154 DCHECK(!result.is_reversed());
155 DCHECK(Range(0, run.glyph_count).Contains(result));
159 // Starting from |start_char|, finds a suitable line break position at or before
160 // |available_width| using word break info from |breaks|. If |empty_line| is
161 // true, this function will not roll back to |start_char| and |*next_char| will
162 // be greater than |start_char| (to avoid constructing empty lines).
163 // TODO(ckocagil): Do not break ligatures and diacritics.
164 // TextRun::logical_clusters might help.
165 // TODO(ckocagil): We might have to reshape after breaking at ligatures.
166 // See whether resolving the TODO above resolves this too.
167 // TODO(ckocagil): Do not reserve width for whitespace at the end of lines.
168 void BreakRunAtWidth(const internal::TextRun& run,
169 const BreakList<size_t>& breaks,
175 DCHECK(run.range.Contains(Range(start_char, start_char + 1)));
176 BreakList<size_t>::const_iterator word = breaks.GetBreak(start_char);
177 BreakList<size_t>::const_iterator next_word = word + 1;
178 // Width from |std::max(word->first, start_char)| to the current character.
182 for (size_t i = start_char; i < run.range.end(); ++i) {
183 // |word| holds the word boundary at or before |i|, and |next_word| holds
184 // the word boundary right after |i|. Advance both |word| and |next_word|
185 // when |i| reaches |next_word|.
186 if (next_word != breaks.breaks().end() && i >= next_word->first) {
191 Range glyph_range = CharRangeToGlyphRange(run, Range(i, i + 1));
193 for (size_t j = glyph_range.start(); j < glyph_range.end(); ++j)
194 char_width += run.advance_widths[j];
196 *width += char_width;
197 word_width += char_width;
199 if (*width > available_width) {
200 if (!empty_line || word_width < *width) {
201 *width -= word_width;
202 *next_char = std::max(word->first, start_char);
203 } else if (char_width < *width) {
204 *width -= char_width;
214 *next_char = run.range.end();
217 // For segments in the same run, checks the continuity and order of |x_range|
218 // and |char_range| fields.
219 void CheckLineIntegrity(const std::vector<internal::Line>& lines,
220 const ScopedVector<internal::TextRun>& runs) {
221 size_t previous_segment_line = 0;
222 const internal::LineSegment* previous_segment = NULL;
224 for (size_t i = 0; i < lines.size(); ++i) {
225 for (size_t j = 0; j < lines[i].segments.size(); ++j) {
226 const internal::LineSegment* segment = &lines[i].segments[j];
227 internal::TextRun* run = runs[segment->run];
229 if (!previous_segment) {
230 previous_segment = segment;
231 } else if (runs[previous_segment->run] != run) {
232 previous_segment = NULL;
234 DCHECK_EQ(previous_segment->char_range.end(),
235 segment->char_range.start());
236 if (!run->script_analysis.fRTL) {
237 DCHECK_EQ(previous_segment->x_range.end(), segment->x_range.start());
239 DCHECK_EQ(segment->x_range.end(), previous_segment->x_range.start());
242 previous_segment = segment;
243 previous_segment_line = i;
249 // Returns true if characters of |block_code| may trigger font fallback.
250 bool IsUnusualBlockCode(const UBlockCode block_code) {
251 return block_code == UBLOCK_GEOMETRIC_SHAPES ||
252 block_code == UBLOCK_MISCELLANEOUS_SYMBOLS;
262 diagonal_strike(false),
265 preceding_run_widths(0),
268 memset(&script_analysis, 0, sizeof(script_analysis));
269 memset(&abc_widths, 0, sizeof(abc_widths));
272 TextRun::~TextRun() {
273 ScriptFreeCache(&script_cache);
276 // Returns the X coordinate of the leading or |trailing| edge of the glyph
277 // starting at |index|, relative to the left of the text (not the view).
278 int GetGlyphXBoundary(const internal::TextRun* run,
281 DCHECK_GE(index, run->range.start());
282 DCHECK_LT(index, run->range.end() + (trailing ? 0 : 1));
284 HRESULT hr = ScriptCPtoX(
285 index - run->range.start(),
289 run->logical_clusters.get(),
290 run->visible_attributes.get(),
291 run->advance_widths.get(),
292 &run->script_analysis,
294 DCHECK(SUCCEEDED(hr));
295 return run->preceding_run_widths + x;
298 // Internal class to generate Line structures. If |multiline| is true, the text
299 // is broken into lines at |words| boundaries such that each line is no longer
300 // than |max_width|. If |multiline| is false, only outputs a single Line from
301 // the given runs. |min_baseline| and |min_height| are the minimum baseline and
302 // height for each line.
303 // TODO(ckocagil): Expose the interface of this class in the header and test
304 // this class directly.
307 LineBreaker(int max_width,
311 const BreakList<size_t>* words,
312 const ScopedVector<TextRun>& runs)
313 : max_width_(max_width),
314 min_baseline_(min_baseline),
315 min_height_(min_height),
316 multiline_(multiline),
326 // Breaks the run at given |run_index| into Line structs.
327 void AddRun(int run_index) {
328 const TextRun* run = runs_[run_index];
329 if (multiline_ && line_x_ + run->width > max_width_)
332 AddSegment(run_index, run->range, run->width);
335 // Finishes line breaking and outputs the results. Can be called at most once.
336 void Finalize(std::vector<Line>* lines, Size* size) {
337 DCHECK(!lines_.empty());
338 // Add an empty line to finish the line size calculation and remove it.
346 // A (line index, segment index) pair that specifies a segment in |lines_|.
347 typedef std::pair<size_t, size_t> SegmentHandle;
349 LineSegment* SegmentFromHandle(const SegmentHandle& handle) {
350 return &lines_[handle.first].segments[handle.second];
353 // Breaks a run into segments that fit in the last line in |lines_| and adds
354 // them. Adds a new Line to the back of |lines_| whenever a new segment can't
355 // be added without the Line's width exceeding |max_width_|.
356 void BreakRun(int run_index) {
358 const TextRun* const run = runs_[run_index];
360 size_t next_char = run->range.start();
362 // Break the run until it fits the current line.
363 while (next_char < run->range.end()) {
364 const size_t current_char = next_char;
365 BreakRunAtWidth(*run, *words_, current_char, max_width_ - line_x_,
366 line_x_ == 0, &width, &next_char);
367 AddSegment(run_index, Range(current_char, next_char), width);
368 if (next_char < run->range.end())
373 // RTL runs are broken in logical order but displayed in visual order. To find
374 // the text-space coordinate (where it would fall in a single-line text)
375 // |x_range| of RTL segments, segment widths are applied in reverse order.
376 // e.g. {[5, 10], [10, 40]} will become {[35, 40], [5, 35]}.
377 void UpdateRTLSegmentRanges() {
378 if (rtl_segments_.empty())
380 int x = SegmentFromHandle(rtl_segments_[0])->x_range.start();
381 for (size_t i = rtl_segments_.size(); i > 0; --i) {
382 LineSegment* segment = SegmentFromHandle(rtl_segments_[i - 1]);
383 const size_t segment_width = segment->x_range.length();
384 segment->x_range = Range(x, x + segment_width);
387 rtl_segments_.clear();
390 // Finishes the size calculations of the last Line in |lines_|. Adds a new
391 // Line to the back of |lines_|.
393 if (!lines_.empty()) {
394 Line* line = &lines_.back();
395 // TODO(ckocagil): Determine optimal multiline height behavior.
396 if (line_ascent_ + line_descent_ == 0) {
397 line_ascent_ = min_baseline_;
398 line_descent_ = min_height_ - min_baseline_;
400 // Set the single-line mode Line's metrics to be at least
401 // |RenderText::font_list()| to not break the current single-line code.
402 line_ascent_ = std::max(line_ascent_, min_baseline_);
403 line_descent_ = std::max(line_descent_, min_height_ - min_baseline_);
405 line->baseline = line_ascent_;
406 line->size.set_height(line_ascent_ + line_descent_);
407 line->preceding_heights = total_size_.height();
408 total_size_.set_height(total_size_.height() + line->size.height());
409 total_size_.set_width(std::max(total_size_.width(), line->size.width()));
414 lines_.push_back(Line());
417 // Adds a new segment with the given properties to |lines_.back()|.
418 void AddSegment(int run_index, Range char_range, int width) {
419 if (char_range.is_empty()) {
423 const TextRun* run = runs_[run_index];
424 line_ascent_ = std::max(line_ascent_, run->font.GetBaseline());
425 line_descent_ = std::max(line_descent_,
426 run->font.GetHeight() - run->font.GetBaseline());
429 segment.run = run_index;
430 segment.char_range = char_range;
431 segment.x_range = Range(text_x_, text_x_ + width);
433 Line* line = &lines_.back();
434 line->segments.push_back(segment);
435 line->size.set_width(line->size.width() + segment.x_range.length());
436 if (run->script_analysis.fRTL) {
437 rtl_segments_.push_back(SegmentHandle(lines_.size() - 1,
438 line->segments.size() - 1));
439 // If this is the last segment of an RTL run, reprocess the text-space x
440 // ranges of all segments from the run.
441 if (char_range.end() == run->range.end())
442 UpdateRTLSegmentRanges();
448 const int max_width_;
449 const int min_baseline_;
450 const int min_height_;
451 const bool multiline_;
452 const BreakList<size_t>* const words_;
453 const ScopedVector<TextRun>& runs_;
455 // Stores the resulting lines.
456 std::vector<Line> lines_;
458 // Text space and line space x coordinates of the next segment to be added.
462 // Size of the multiline text, not including the currently processed line.
465 // Ascent and descent values of the current line, |lines_.back()|.
469 // The current RTL run segments, to be applied by |UpdateRTLSegmentRanges()|.
470 std::vector<SegmentHandle> rtl_segments_;
472 DISALLOW_COPY_AND_ASSIGN(LineBreaker);
475 } // namespace internal
478 HDC RenderTextWin::cached_hdc_ = NULL;
481 std::map<std::string, Font> RenderTextWin::successful_substitute_fonts_;
483 RenderTextWin::RenderTextWin()
485 needs_layout_(false) {
486 set_truncate_length(kMaxUniscribeTextLength);
488 memset(&script_control_, 0, sizeof(script_control_));
489 memset(&script_state_, 0, sizeof(script_state_));
491 MoveCursorTo(EdgeSelectionModel(CURSOR_LEFT));
494 RenderTextWin::~RenderTextWin() {
497 Size RenderTextWin::GetStringSize() {
499 return multiline_string_size_;
502 SelectionModel RenderTextWin::FindCursorPosition(const Point& point) {
504 return SelectionModel();
507 // Find the run that contains the point and adjust the argument location.
508 int x = ToTextPoint(point).x();
509 size_t run_index = GetRunContainingXCoord(x);
510 if (run_index >= runs_.size())
511 return EdgeSelectionModel((x < 0) ? CURSOR_LEFT : CURSOR_RIGHT);
512 internal::TextRun* run = runs_[run_index];
514 int position = 0, trailing = 0;
515 HRESULT hr = ScriptXtoCP(x - run->preceding_run_widths,
518 run->logical_clusters.get(),
519 run->visible_attributes.get(),
520 run->advance_widths.get(),
521 &(run->script_analysis),
524 DCHECK(SUCCEEDED(hr));
525 DCHECK_GE(trailing, 0);
526 position += run->range.start();
527 const size_t cursor = LayoutIndexToTextIndex(position + trailing);
528 DCHECK_LE(cursor, text().length());
529 return SelectionModel(cursor, trailing ? CURSOR_BACKWARD : CURSOR_FORWARD);
532 std::vector<RenderText::FontSpan> RenderTextWin::GetFontSpansForTesting() {
535 std::vector<RenderText::FontSpan> spans;
536 for (size_t i = 0; i < runs_.size(); ++i) {
537 spans.push_back(RenderText::FontSpan(runs_[i]->font,
538 Range(LayoutIndexToTextIndex(runs_[i]->range.start()),
539 LayoutIndexToTextIndex(runs_[i]->range.end()))));
545 int RenderTextWin::GetLayoutTextBaseline() {
547 return lines()[0].baseline;
550 SelectionModel RenderTextWin::AdjacentCharSelectionModel(
551 const SelectionModel& selection,
552 VisualCursorDirection direction) {
553 DCHECK(!needs_layout_);
554 internal::TextRun* run;
555 size_t run_index = GetRunContainingCaret(selection);
556 if (run_index >= runs_.size()) {
557 // The cursor is not in any run: we're at the visual and logical edge.
558 SelectionModel edge = EdgeSelectionModel(direction);
559 if (edge.caret_pos() == selection.caret_pos())
561 int visual_index = (direction == CURSOR_RIGHT) ? 0 : runs_.size() - 1;
562 run = runs_[visual_to_logical_[visual_index]];
564 // If the cursor is moving within the current run, just move it by one
565 // grapheme in the appropriate direction.
566 run = runs_[run_index];
567 size_t caret = selection.caret_pos();
568 bool forward_motion =
569 run->script_analysis.fRTL == (direction == CURSOR_LEFT);
570 if (forward_motion) {
571 if (caret < LayoutIndexToTextIndex(run->range.end())) {
572 caret = IndexOfAdjacentGrapheme(caret, CURSOR_FORWARD);
573 return SelectionModel(caret, CURSOR_BACKWARD);
576 if (caret > LayoutIndexToTextIndex(run->range.start())) {
577 caret = IndexOfAdjacentGrapheme(caret, CURSOR_BACKWARD);
578 return SelectionModel(caret, CURSOR_FORWARD);
581 // The cursor is at the edge of a run; move to the visually adjacent run.
582 int visual_index = logical_to_visual_[run_index];
583 visual_index += (direction == CURSOR_LEFT) ? -1 : 1;
584 if (visual_index < 0 || visual_index >= static_cast<int>(runs_.size()))
585 return EdgeSelectionModel(direction);
586 run = runs_[visual_to_logical_[visual_index]];
588 bool forward_motion = run->script_analysis.fRTL == (direction == CURSOR_LEFT);
589 return forward_motion ? FirstSelectionModelInsideRun(run) :
590 LastSelectionModelInsideRun(run);
593 // TODO(msw): Implement word breaking for Windows.
594 SelectionModel RenderTextWin::AdjacentWordSelectionModel(
595 const SelectionModel& selection,
596 VisualCursorDirection direction) {
598 return EdgeSelectionModel(direction);
600 base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD);
601 bool success = iter.Init();
607 if (direction == CURSOR_RIGHT) {
608 pos = std::min(selection.caret_pos() + 1, text().length());
609 while (iter.Advance()) {
611 if (iter.IsWord() && pos > selection.caret_pos())
614 } else { // direction == CURSOR_LEFT
615 // Notes: We always iterate words from the beginning.
616 // This is probably fast enough for our usage, but we may
617 // want to modify WordIterator so that it can start from the
618 // middle of string and advance backwards.
619 pos = std::max<int>(selection.caret_pos() - 1, 0);
620 while (iter.Advance()) {
622 size_t begin = iter.pos() - iter.GetString().length();
623 if (begin == selection.caret_pos()) {
624 // The cursor is at the beginning of a word.
625 // Move to previous word.
627 } else if (iter.pos() >= selection.caret_pos()) {
628 // The cursor is in the middle or at the end of a word.
629 // Move to the top of current word.
633 pos = iter.pos() - iter.GetString().length();
638 return SelectionModel(pos, CURSOR_FORWARD);
641 Range RenderTextWin::GetGlyphBounds(size_t index) {
642 const size_t run_index =
643 GetRunContainingCaret(SelectionModel(index, CURSOR_FORWARD));
644 // Return edge bounds if the index is invalid or beyond the layout text size.
645 if (run_index >= runs_.size())
646 return Range(string_width_);
647 internal::TextRun* run = runs_[run_index];
648 const size_t layout_index = TextIndexToLayoutIndex(index);
649 return Range(GetGlyphXBoundary(run, layout_index, false),
650 GetGlyphXBoundary(run, layout_index, true));
653 std::vector<Rect> RenderTextWin::GetSubstringBounds(const Range& range) {
654 DCHECK(!needs_layout_);
655 DCHECK(Range(0, text().length()).Contains(range));
656 Range layout_range(TextIndexToLayoutIndex(range.start()),
657 TextIndexToLayoutIndex(range.end()));
658 DCHECK(Range(0, GetLayoutText().length()).Contains(layout_range));
660 std::vector<Rect> rects;
661 if (layout_range.is_empty())
663 std::vector<Range> bounds;
665 // Add a Range for each run/selection intersection.
666 // TODO(msw): The bounds should probably not always be leading the range ends.
667 for (size_t i = 0; i < runs_.size(); ++i) {
668 const internal::TextRun* run = runs_[visual_to_logical_[i]];
669 Range intersection = run->range.Intersect(layout_range);
670 if (intersection.IsValid()) {
671 DCHECK(!intersection.is_reversed());
672 Range range_x(GetGlyphXBoundary(run, intersection.start(), false),
673 GetGlyphXBoundary(run, intersection.end(), false));
674 if (range_x.is_empty())
676 range_x = Range(range_x.GetMin(), range_x.GetMax());
677 // Union this with the last range if they're adjacent.
678 DCHECK(bounds.empty() || bounds.back().GetMax() <= range_x.GetMin());
679 if (!bounds.empty() && bounds.back().GetMax() == range_x.GetMin()) {
680 range_x = Range(bounds.back().GetMin(), range_x.GetMax());
683 bounds.push_back(range_x);
686 for (size_t i = 0; i < bounds.size(); ++i) {
687 std::vector<Rect> current_rects = TextBoundsToViewBounds(bounds[i]);
688 rects.insert(rects.end(), current_rects.begin(), current_rects.end());
693 size_t RenderTextWin::TextIndexToLayoutIndex(size_t index) const {
694 DCHECK_LE(index, text().length());
695 ptrdiff_t i = obscured() ? gfx::UTF16IndexToOffset(text(), 0, index) : index;
697 // Clamp layout indices to the length of the text actually used for layout.
698 return std::min<size_t>(GetLayoutText().length(), i);
701 size_t RenderTextWin::LayoutIndexToTextIndex(size_t index) const {
705 DCHECK_LE(index, GetLayoutText().length());
706 const size_t text_index = gfx::UTF16OffsetToIndex(text(), 0, index);
707 DCHECK_LE(text_index, text().length());
711 bool RenderTextWin::IsCursorablePosition(size_t position) {
712 if (position == 0 || position == text().length())
716 // Check that the index is at a valid code point (not mid-surrgate-pair),
717 // that it is not truncated from layout text (its glyph is shown on screen),
718 // and that its glyph has distinct bounds (not mid-multi-character-grapheme).
719 // An example of a multi-character-grapheme that is not a surrogate-pair is:
720 // \x0915\x093f - (ki) - one of many Devanagari biconsonantal conjuncts.
721 return gfx::IsValidCodePointIndex(text(), position) &&
722 position < LayoutIndexToTextIndex(GetLayoutText().length()) &&
723 GetGlyphBounds(position) != GetGlyphBounds(position - 1);
726 void RenderTextWin::ResetLayout() {
727 // Layout is performed lazily as needed for drawing/metrics.
728 needs_layout_ = true;
731 void RenderTextWin::EnsureLayout() {
733 // TODO(msw): Skip complex processing if ScriptIsComplex returns false.
734 ItemizeLogicalText();
737 needs_layout_ = false;
738 std::vector<internal::Line> lines;
742 // Compute lines if they're not valid. This is separate from the layout steps
743 // above to avoid text layout and shaping when we resize |display_rect_|.
744 if (lines().empty()) {
745 DCHECK(!needs_layout_);
746 std::vector<internal::Line> lines;
747 internal::LineBreaker line_breaker(display_rect().width() - 1,
748 font_list().GetBaseline(),
749 font_list().GetHeight(), multiline(),
750 multiline() ? &GetLineBreaks() : NULL,
752 for (size_t i = 0; i < runs_.size(); ++i)
753 line_breaker.AddRun(visual_to_logical_[i]);
754 line_breaker.Finalize(&lines, &multiline_string_size_);
755 DCHECK(!lines.empty());
757 CheckLineIntegrity(lines, runs_);
763 void RenderTextWin::DrawVisualText(Canvas* canvas) {
764 DCHECK(!needs_layout_);
765 DCHECK(!lines().empty());
767 std::vector<SkPoint> pos;
769 internal::SkiaTextRenderer renderer(canvas);
770 ApplyFadeEffects(&renderer);
771 ApplyTextShadows(&renderer);
773 bool smoothing_enabled;
774 bool cleartype_enabled;
775 GetCachedFontSmoothingSettings(&smoothing_enabled, &cleartype_enabled);
776 // Note that |cleartype_enabled| corresponds to Skia's |enable_lcd_text|.
777 renderer.SetFontSmoothingSettings(
778 smoothing_enabled, cleartype_enabled && !background_is_transparent());
780 ApplyCompositionAndSelectionStyles();
782 for (size_t i = 0; i < lines().size(); ++i) {
783 const internal::Line& line = lines()[i];
784 const Vector2d line_offset = GetLineOffset(i);
786 // Skip painting empty lines or lines outside the display rect area.
787 if (!display_rect().Intersects(Rect(PointAtOffsetFromOrigin(line_offset),
791 const Vector2d text_offset = line_offset + Vector2d(0, line.baseline);
792 int preceding_segment_widths = 0;
794 for (size_t j = 0; j < line.segments.size(); ++j) {
795 const internal::LineSegment* segment = &line.segments[j];
796 const int segment_width = segment->x_range.length();
797 const internal::TextRun* run = runs_[segment->run];
798 DCHECK(!segment->char_range.is_empty());
799 DCHECK(run->range.Contains(segment->char_range));
800 Range glyph_range = CharRangeToGlyphRange(*run, segment->char_range);
801 DCHECK(!glyph_range.is_empty());
802 // Skip painting segments outside the display rect area.
804 const Rect segment_bounds(PointAtOffsetFromOrigin(line_offset) +
805 Vector2d(preceding_segment_widths, 0),
806 Size(segment_width, line.size.height()));
807 if (!display_rect().Intersects(segment_bounds)) {
808 preceding_segment_widths += segment_width;
813 // |pos| contains the positions of glyphs. An extra terminal |pos| entry
814 // is added to simplify width calculations.
815 int segment_x = preceding_segment_widths;
816 pos.resize(glyph_range.length() + 1);
817 for (size_t k = glyph_range.start(); k < glyph_range.end(); ++k) {
818 pos[k - glyph_range.start()].set(
819 SkIntToScalar(text_offset.x() + run->offsets[k].du + segment_x),
820 SkIntToScalar(text_offset.y() + run->offsets[k].dv));
821 segment_x += run->advance_widths[k];
823 pos.back().set(SkIntToScalar(text_offset.x() + segment_x),
824 SkIntToScalar(text_offset.y()));
826 renderer.SetTextSize(run->font.GetFontSize());
827 renderer.SetFontFamilyWithStyle(run->font.GetFontName(), run->font_style);
829 for (BreakList<SkColor>::const_iterator it =
830 colors().GetBreak(segment->char_range.start());
831 it != colors().breaks().end() &&
832 it->first < segment->char_range.end();
834 const Range intersection =
835 colors().GetRange(it).Intersect(segment->char_range);
836 const Range colored_glyphs = CharRangeToGlyphRange(*run, intersection);
837 DCHECK(glyph_range.Contains(colored_glyphs));
838 DCHECK(!colored_glyphs.is_empty());
839 const SkPoint& start_pos =
840 pos[colored_glyphs.start() - glyph_range.start()];
841 const SkPoint& end_pos =
842 pos[colored_glyphs.end() - glyph_range.start()];
844 renderer.SetForegroundColor(it->second);
845 renderer.DrawPosText(&start_pos, &run->glyphs[colored_glyphs.start()],
846 colored_glyphs.length());
847 renderer.DrawDecorations(start_pos.x(), text_offset.y(),
848 SkScalarCeilToInt(end_pos.x() - start_pos.x()),
849 run->underline, run->strike,
850 run->diagonal_strike);
853 preceding_segment_widths += segment_width;
857 UndoCompositionAndSelectionStyles();
860 void RenderTextWin::ItemizeLogicalText() {
863 multiline_string_size_ = Size();
865 // Set Uniscribe's base text direction.
866 script_state_.uBidiLevel =
867 (GetTextDirection() == base::i18n::RIGHT_TO_LEFT) ? 1 : 0;
869 const base::string16& layout_text = GetLayoutText();
870 if (layout_text.empty())
873 HRESULT hr = E_OUTOFMEMORY;
874 int script_items_count = 0;
875 std::vector<SCRIPT_ITEM> script_items;
876 const size_t layout_text_length = layout_text.length();
877 // Ensure that |kMaxRuns| is attempted and the loop terminates afterward.
878 for (size_t runs = kGuessRuns; hr == E_OUTOFMEMORY && runs <= kMaxRuns;
879 runs = std::max(runs + 1, std::min(runs * 2, kMaxRuns))) {
880 // Derive the array of Uniscribe script items from the logical text.
881 // ScriptItemize always adds a terminal array item so that the length of
882 // the last item can be derived from the terminal SCRIPT_ITEM::iCharPos.
883 script_items.resize(runs);
884 hr = ScriptItemize(layout_text.c_str(), layout_text_length, runs - 1,
885 &script_control_, &script_state_, &script_items[0],
886 &script_items_count);
888 DCHECK(SUCCEEDED(hr));
889 if (!SUCCEEDED(hr) || script_items_count <= 0)
892 // Temporarily apply composition underlines and selection colors.
893 ApplyCompositionAndSelectionStyles();
895 // Build the list of runs from the script items and ranged styles. Use an
896 // empty color BreakList to avoid breaking runs at color boundaries.
897 BreakList<SkColor> empty_colors;
898 empty_colors.SetMax(layout_text_length);
899 internal::StyleIterator style(empty_colors, styles());
900 SCRIPT_ITEM* script_item = &script_items[0];
901 const size_t max_run_length = kMaxGlyphs / 2;
902 for (size_t run_break = 0; run_break < layout_text_length;) {
903 internal::TextRun* run = new internal::TextRun();
904 run->range.set_start(run_break);
905 run->font = GetPrimaryFont();
906 run->font_style = (style.style(BOLD) ? Font::BOLD : 0) |
907 (style.style(ITALIC) ? Font::ITALIC : 0);
908 DeriveFontIfNecessary(run->font.GetFontSize(), run->font.GetHeight(),
909 run->font_style, &run->font);
910 run->strike = style.style(STRIKE);
911 run->diagonal_strike = style.style(DIAGONAL_STRIKE);
912 run->underline = style.style(UNDERLINE);
913 run->script_analysis = script_item->a;
915 // Find the next break and advance the iterators as needed.
916 const size_t script_item_break = (script_item + 1)->iCharPos;
917 run_break = std::min(script_item_break,
918 TextIndexToLayoutIndex(style.GetRange().end()));
920 // Clamp run lengths to avoid exceeding the maximum supported glyph count.
921 if ((run_break - run->range.start()) > max_run_length) {
922 run_break = run->range.start() + max_run_length;
923 if (!IsValidCodePointIndex(layout_text, run_break))
927 // Break runs adjacent to character substrings in certain code blocks.
928 // This avoids using their fallback fonts for more characters than needed,
929 // in cases like "\x25B6 Media Title", etc. http://crbug.com/278913
930 if (run_break > run->range.start()) {
931 const size_t run_start = run->range.start();
932 const int32 run_length = static_cast<int32>(run_break - run_start);
933 base::i18n::UTF16CharIterator iter(layout_text.c_str() + run_start,
935 const UBlockCode first_block_code = ublock_getCode(iter.get());
936 const bool first_block_unusual = IsUnusualBlockCode(first_block_code);
937 while (iter.Advance() && iter.array_pos() < run_length) {
938 const UBlockCode current_block_code = ublock_getCode(iter.get());
939 if (current_block_code != first_block_code &&
940 (first_block_unusual || IsUnusualBlockCode(current_block_code))) {
941 run_break = run_start + iter.array_pos();
947 DCHECK(IsValidCodePointIndex(layout_text, run_break));
949 style.UpdatePosition(LayoutIndexToTextIndex(run_break));
950 if (script_item_break == run_break)
952 run->range.set_end(run_break);
953 runs_.push_back(run);
956 // Undo the temporarily applied composition underlines and selection colors.
957 UndoCompositionAndSelectionStyles();
960 void RenderTextWin::LayoutVisualText() {
961 DCHECK(!runs_.empty());
964 cached_hdc_ = CreateCompatibleDC(NULL);
967 // Ensure ascent and descent are not smaller than ones of the font list.
968 // Keep them tall enough to draw often-used characters.
969 // For example, if a text field contains a Japanese character, which is
970 // smaller than Latin ones, and then later a Latin one is inserted, this
971 // ensures that the text baseline does not shift.
972 int ascent = font_list().GetBaseline();
973 int descent = font_list().GetHeight() - font_list().GetBaseline();
974 for (size_t i = 0; i < runs_.size(); ++i) {
975 internal::TextRun* run = runs_[i];
978 ascent = std::max(ascent, run->font.GetBaseline());
979 descent = std::max(descent,
980 run->font.GetHeight() - run->font.GetBaseline());
982 if (run->glyph_count > 0) {
983 run->advance_widths.reset(new int[run->glyph_count]);
984 run->offsets.reset(new GOFFSET[run->glyph_count]);
985 hr = ScriptPlace(cached_hdc_,
989 run->visible_attributes.get(),
990 &(run->script_analysis),
991 run->advance_widths.get(),
994 DCHECK(SUCCEEDED(hr));
998 // Build the array of bidirectional embedding levels.
999 scoped_ptr<BYTE[]> levels(new BYTE[runs_.size()]);
1000 for (size_t i = 0; i < runs_.size(); ++i)
1001 levels[i] = runs_[i]->script_analysis.s.uBidiLevel;
1003 // Get the maps between visual and logical run indices.
1004 visual_to_logical_.reset(new int[runs_.size()]);
1005 logical_to_visual_.reset(new int[runs_.size()]);
1006 hr = ScriptLayout(runs_.size(),
1008 visual_to_logical_.get(),
1009 logical_to_visual_.get());
1010 DCHECK(SUCCEEDED(hr));
1012 // Precalculate run width information.
1013 size_t preceding_run_widths = 0;
1014 for (size_t i = 0; i < runs_.size(); ++i) {
1015 internal::TextRun* run = runs_[visual_to_logical_[i]];
1016 run->preceding_run_widths = preceding_run_widths;
1017 const ABC& abc = run->abc_widths;
1018 run->width = abc.abcA + abc.abcB + abc.abcC;
1019 preceding_run_widths += run->width;
1021 string_width_ = preceding_run_widths;
1024 void RenderTextWin::LayoutTextRun(internal::TextRun* run) {
1025 const size_t run_length = run->range.length();
1026 const wchar_t* run_text = &(GetLayoutText()[run->range.start()]);
1027 Font original_font = run->font;
1028 LinkedFontsIterator fonts(original_font);
1029 bool tried_cached_font = false;
1030 bool tried_fallback = false;
1031 // Keep track of the font that is able to display the greatest number of
1032 // characters for which ScriptShape() returned S_OK. This font will be used
1033 // in the case where no font is able to display the entire run.
1034 int best_partial_font_missing_char_count = INT_MAX;
1035 Font best_partial_font = original_font;
1038 run->logical_clusters.reset(new WORD[run_length]);
1039 while (fonts.NextFont(¤t_font)) {
1040 HRESULT hr = ShapeTextRunWithFont(run, current_font);
1042 bool glyphs_missing = false;
1043 if (hr == USP_E_SCRIPT_NOT_IN_FONT) {
1044 glyphs_missing = true;
1045 } else if (hr == S_OK) {
1046 // If |hr| is S_OK, there could still be missing glyphs in the output.
1047 // http://msdn.microsoft.com/en-us/library/windows/desktop/dd368564.aspx
1048 const int missing_count = CountCharsWithMissingGlyphs(run);
1049 // Track the font that produced the least missing glyphs.
1050 if (missing_count < best_partial_font_missing_char_count) {
1051 best_partial_font_missing_char_count = missing_count;
1052 best_partial_font = run->font;
1054 glyphs_missing = (missing_count != 0);
1059 // Use the font if it had glyphs for all characters.
1060 if (!glyphs_missing) {
1061 // Save the successful fallback font that was chosen.
1063 successful_substitute_fonts_[original_font.GetFontName()] = run->font;
1067 // First, try the cached font from previous runs, if any.
1068 if (!tried_cached_font) {
1069 tried_cached_font = true;
1071 std::map<std::string, Font>::const_iterator it =
1072 successful_substitute_fonts_.find(original_font.GetFontName());
1073 if (it != successful_substitute_fonts_.end()) {
1074 fonts.SetNextFont(it->second);
1079 // If there are missing glyphs, first try finding a fallback font using a
1080 // meta file, if it hasn't yet been attempted for this run.
1081 // TODO(msw|asvitkine): Support RenderText's font_list()?
1082 if (!tried_fallback) {
1083 tried_fallback = true;
1086 if (ChooseFallbackFont(cached_hdc_, run->font, run_text, run_length,
1088 fonts.SetNextFont(fallback_font);
1094 // If a font was able to partially display the run, use that now.
1095 if (best_partial_font_missing_char_count < static_cast<int>(run_length)) {
1096 // Re-shape the run only if |best_partial_font| differs from the last font.
1097 if (best_partial_font.GetNativeFont() != run->font.GetNativeFont())
1098 ShapeTextRunWithFont(run, best_partial_font);
1102 // If no font was able to partially display the run, replace all glyphs
1103 // with |wgDefault| from the original font to ensure to they don't hold
1105 // First, clear the cache and select the original font on the HDC.
1106 ScriptFreeCache(&run->script_cache);
1107 run->font = original_font;
1108 SelectObject(cached_hdc_, run->font.GetNativeFont());
1110 // Now, get the font's properties.
1111 SCRIPT_FONTPROPERTIES properties;
1112 memset(&properties, 0, sizeof(properties));
1113 properties.cBytes = sizeof(properties);
1114 HRESULT hr = ScriptGetFontProperties(cached_hdc_, &run->script_cache,
1117 // The initial values for the "missing" glyph and the space glyph are taken
1118 // from the recommendations section of the OpenType spec:
1119 // https://www.microsoft.com/typography/otspec/recom.htm
1120 WORD missing_glyph = 0;
1121 WORD space_glyph = 3;
1123 missing_glyph = properties.wgDefault;
1124 space_glyph = properties.wgBlank;
1127 // Finally, initialize |glyph_count|, |glyphs|, |visible_attributes| and
1128 // |logical_clusters| on the run (since they may not have been set yet).
1129 run->glyph_count = run_length;
1130 memset(run->visible_attributes.get(), 0,
1131 run->glyph_count * sizeof(SCRIPT_VISATTR));
1132 for (int i = 0; i < run->glyph_count; ++i)
1133 run->glyphs[i] = IsWhitespace(run_text[i]) ? space_glyph : missing_glyph;
1134 for (size_t i = 0; i < run_length; ++i) {
1135 run->logical_clusters[i] = run->script_analysis.fRTL ?
1136 run_length - 1 - i : i;
1139 // TODO(msw): Don't use SCRIPT_UNDEFINED. Apparently Uniscribe can
1140 // crash on certain surrogate pairs with SCRIPT_UNDEFINED.
1141 // See https://bugzilla.mozilla.org/show_bug.cgi?id=341500
1142 // And http://maxradi.us/documents/uniscribe/
1143 run->script_analysis.eScript = SCRIPT_UNDEFINED;
1146 HRESULT RenderTextWin::ShapeTextRunWithFont(internal::TextRun* run,
1148 // Update the run's font only if necessary. If the two fonts wrap the same
1149 // PlatformFontWin object, their native fonts will have the same value.
1150 if (run->font.GetNativeFont() != font.GetNativeFont()) {
1151 const int font_size = run->font.GetFontSize();
1152 const int font_height = run->font.GetHeight();
1154 DeriveFontIfNecessary(font_size, font_height, run->font_style, &run->font);
1155 ScriptFreeCache(&run->script_cache);
1158 // Select the font desired for glyph generation.
1159 SelectObject(cached_hdc_, run->font.GetNativeFont());
1161 HRESULT hr = E_OUTOFMEMORY;
1162 const size_t run_length = run->range.length();
1163 const wchar_t* run_text = &(GetLayoutText()[run->range.start()]);
1164 // Guess the expected number of glyphs from the length of the run.
1165 // MSDN suggests this at http://msdn.microsoft.com/en-us/library/dd368564.aspx
1166 size_t max_glyphs = static_cast<size_t>(1.5 * run_length + 16);
1167 while (hr == E_OUTOFMEMORY && max_glyphs <= kMaxGlyphs) {
1168 run->glyph_count = 0;
1169 run->glyphs.reset(new WORD[max_glyphs]);
1170 run->visible_attributes.reset(new SCRIPT_VISATTR[max_glyphs]);
1171 hr = ScriptShape(cached_hdc_, &run->script_cache, run_text, run_length,
1172 max_glyphs, &run->script_analysis, run->glyphs.get(),
1173 run->logical_clusters.get(), run->visible_attributes.get(),
1175 // Ensure that |kMaxGlyphs| is attempted and the loop terminates afterward.
1176 max_glyphs = std::max(max_glyphs + 1, std::min(max_glyphs * 2, kMaxGlyphs));
1181 int RenderTextWin::CountCharsWithMissingGlyphs(internal::TextRun* run) const {
1182 int chars_not_missing_glyphs = 0;
1183 SCRIPT_FONTPROPERTIES properties;
1184 memset(&properties, 0, sizeof(properties));
1185 properties.cBytes = sizeof(properties);
1186 ScriptGetFontProperties(cached_hdc_, &run->script_cache, &properties);
1188 const wchar_t* run_text = &(GetLayoutText()[run->range.start()]);
1189 for (size_t char_index = 0; char_index < run->range.length(); ++char_index) {
1190 const int glyph_index = run->logical_clusters[char_index];
1191 DCHECK_GE(glyph_index, 0);
1192 DCHECK_LT(glyph_index, run->glyph_count);
1194 if (run->glyphs[glyph_index] == properties.wgDefault)
1197 // Windows Vista sometimes returns glyphs equal to wgBlank (instead of
1198 // wgDefault), with fZeroWidth set. Treat such cases as having missing
1199 // glyphs if the corresponding character is not whitespace.
1200 // See: http://crbug.com/125629
1201 if (run->glyphs[glyph_index] == properties.wgBlank &&
1202 run->visible_attributes[glyph_index].fZeroWidth &&
1203 !IsWhitespace(run_text[char_index]) &&
1204 !IsUnicodeBidiControlCharacter(run_text[char_index])) {
1208 ++chars_not_missing_glyphs;
1211 DCHECK_LE(chars_not_missing_glyphs, static_cast<int>(run->range.length()));
1212 return run->range.length() - chars_not_missing_glyphs;
1215 size_t RenderTextWin::GetRunContainingCaret(const SelectionModel& caret) const {
1216 DCHECK(!needs_layout_);
1217 size_t layout_position = TextIndexToLayoutIndex(caret.caret_pos());
1218 LogicalCursorDirection affinity = caret.caret_affinity();
1219 for (size_t run = 0; run < runs_.size(); ++run)
1220 if (RangeContainsCaret(runs_[run]->range, layout_position, affinity))
1222 return runs_.size();
1225 size_t RenderTextWin::GetRunContainingXCoord(int x) const {
1226 DCHECK(!needs_layout_);
1227 // Find the text run containing the argument point (assumed already offset).
1228 for (size_t run = 0; run < runs_.size(); ++run) {
1229 if ((runs_[run]->preceding_run_widths <= x) &&
1230 ((runs_[run]->preceding_run_widths + runs_[run]->width) > x))
1233 return runs_.size();
1236 SelectionModel RenderTextWin::FirstSelectionModelInsideRun(
1237 const internal::TextRun* run) {
1238 size_t position = LayoutIndexToTextIndex(run->range.start());
1239 position = IndexOfAdjacentGrapheme(position, CURSOR_FORWARD);
1240 return SelectionModel(position, CURSOR_BACKWARD);
1243 SelectionModel RenderTextWin::LastSelectionModelInsideRun(
1244 const internal::TextRun* run) {
1245 size_t position = LayoutIndexToTextIndex(run->range.end());
1246 position = IndexOfAdjacentGrapheme(position, CURSOR_BACKWARD);
1247 return SelectionModel(position, CURSOR_FORWARD);
1250 RenderText* RenderText::CreateInstance() {
1251 return new RenderTextWin;