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(base::UTF16ToUTF8(log_font.lfFaceName),
91 found_fallback = true;
94 DeleteEnhMetaFile(meta_file);
96 return found_fallback;
99 // Changes |font| to have the specified |font_size| (or |font_height| on Windows
100 // XP) and |font_style| if it is not the case already. Only considers bold and
101 // italic styles, since the underlined style has no effect on glyph shaping.
102 void DeriveFontIfNecessary(int font_size,
106 const int kStyleMask = (Font::BOLD | Font::ITALIC);
107 const int target_style = (font_style & kStyleMask);
109 // On Windows XP, the font must be resized using |font_height| instead of
110 // |font_size| to match GDI behavior.
111 if (base::win::GetVersion() < base::win::VERSION_VISTA) {
112 PlatformFontWin* platform_font =
113 static_cast<PlatformFontWin*>(font->platform_font());
114 *font = platform_font->DeriveFontWithHeight(font_height, target_style);
118 const int current_style = (font->GetStyle() & kStyleMask);
119 const int current_size = font->GetFontSize();
120 if (current_style != target_style || current_size != font_size)
121 *font = font->Derive(font_size - current_size, target_style);
124 // Returns true if |c| is a Unicode BiDi control character.
125 bool IsUnicodeBidiControlCharacter(base::char16 c) {
126 return c == base::i18n::kRightToLeftMark ||
127 c == base::i18n::kLeftToRightMark ||
128 c == base::i18n::kLeftToRightEmbeddingMark ||
129 c == base::i18n::kRightToLeftEmbeddingMark ||
130 c == base::i18n::kPopDirectionalFormatting ||
131 c == base::i18n::kLeftToRightOverride ||
132 c == base::i18n::kRightToLeftOverride;
135 // Returns the corresponding glyph range of the given character range.
136 // |range| is in text-space (0 corresponds to |GetLayoutText()[0]|).
137 // Returned value is in run-space (0 corresponds to the first glyph in the run).
138 Range CharRangeToGlyphRange(const internal::TextRun& run,
139 const Range& range) {
140 DCHECK(run.range.Contains(range));
141 DCHECK(!range.is_reversed());
142 DCHECK(!range.is_empty());
143 const Range run_range(range.start() - run.range.start(),
144 range.end() - run.range.start());
146 if (run.script_analysis.fRTL) {
147 result = Range(run.logical_clusters[run_range.end() - 1],
148 run_range.start() > 0 ? run.logical_clusters[run_range.start() - 1]
151 result = Range(run.logical_clusters[run_range.start()],
152 run_range.end() < run.range.length() ?
153 run.logical_clusters[run_range.end()] : run.glyph_count);
155 DCHECK(!result.is_reversed());
156 DCHECK(Range(0, run.glyph_count).Contains(result));
160 // Starting from |start_char|, finds a suitable line break position at or before
161 // |available_width| using word break info from |breaks|. If |empty_line| is
162 // true, this function will not roll back to |start_char| and |*next_char| will
163 // be greater than |start_char| (to avoid constructing empty lines). Returns
164 // whether to skip the line before |*next_char|.
165 // TODO(ckocagil): Do not break ligatures and diacritics.
166 // TextRun::logical_clusters might help.
167 // TODO(ckocagil): We might have to reshape after breaking at ligatures.
168 // See whether resolving the TODO above resolves this too.
169 // TODO(ckocagil): Do not reserve width for whitespace at the end of lines.
170 bool BreakRunAtWidth(const wchar_t* text,
171 const internal::TextRun& run,
172 const BreakList<size_t>& breaks,
178 DCHECK(run.range.Contains(Range(start_char, start_char + 1)));
179 BreakList<size_t>::const_iterator word = breaks.GetBreak(start_char);
180 BreakList<size_t>::const_iterator next_word = word + 1;
181 // Width from |std::max(word->first, start_char)| to the current character.
185 for (size_t i = start_char; i < run.range.end(); ++i) {
186 if (U16_IS_SINGLE(text[i]) && text[i] == L'\n') {
191 // |word| holds the word boundary at or before |i|, and |next_word| holds
192 // the word boundary right after |i|. Advance both |word| and |next_word|
193 // when |i| reaches |next_word|.
194 if (next_word != breaks.breaks().end() && i >= next_word->first) {
199 Range glyph_range = CharRangeToGlyphRange(run, Range(i, i + 1));
201 for (size_t j = glyph_range.start(); j < glyph_range.end(); ++j)
202 char_width += run.advance_widths[j];
204 *width += char_width;
205 word_width += char_width;
207 if (*width > available_width) {
208 if (!empty_line || word_width < *width) {
209 // Roll back one word.
210 *width -= word_width;
211 *next_char = std::max(word->first, start_char);
212 } else if (char_width < *width) {
213 // Roll back one character.
214 *width -= char_width;
217 // Continue from the next character.
225 *next_char = run.range.end();
229 // For segments in the same run, checks the continuity and order of |x_range|
230 // and |char_range| fields.
231 void CheckLineIntegrity(const std::vector<internal::Line>& lines,
232 const ScopedVector<internal::TextRun>& runs) {
233 size_t previous_segment_line = 0;
234 const internal::LineSegment* previous_segment = NULL;
236 for (size_t i = 0; i < lines.size(); ++i) {
237 for (size_t j = 0; j < lines[i].segments.size(); ++j) {
238 const internal::LineSegment* segment = &lines[i].segments[j];
239 internal::TextRun* run = runs[segment->run];
241 if (!previous_segment) {
242 previous_segment = segment;
243 } else if (runs[previous_segment->run] != run) {
244 previous_segment = NULL;
246 DCHECK_EQ(previous_segment->char_range.end(),
247 segment->char_range.start());
248 if (!run->script_analysis.fRTL) {
249 DCHECK_EQ(previous_segment->x_range.end(), segment->x_range.start());
251 DCHECK_EQ(segment->x_range.end(), previous_segment->x_range.start());
254 previous_segment = segment;
255 previous_segment_line = i;
261 // Returns true if characters of |block_code| may trigger font fallback.
262 bool IsUnusualBlockCode(const UBlockCode block_code) {
263 return block_code == UBLOCK_GEOMETRIC_SHAPES ||
264 block_code == UBLOCK_MISCELLANEOUS_SYMBOLS;
274 diagonal_strike(false),
277 preceding_run_widths(0),
280 memset(&script_analysis, 0, sizeof(script_analysis));
281 memset(&abc_widths, 0, sizeof(abc_widths));
284 TextRun::~TextRun() {
285 ScriptFreeCache(&script_cache);
288 // Returns the X coordinate of the leading or |trailing| edge of the glyph
289 // starting at |index|, relative to the left of the text (not the view).
290 int GetGlyphXBoundary(const internal::TextRun* run,
293 DCHECK_GE(index, run->range.start());
294 DCHECK_LT(index, run->range.end() + (trailing ? 0 : 1));
296 HRESULT hr = ScriptCPtoX(
297 index - run->range.start(),
301 run->logical_clusters.get(),
302 run->visible_attributes.get(),
303 run->advance_widths.get(),
304 &run->script_analysis,
306 DCHECK(SUCCEEDED(hr));
307 return run->preceding_run_widths + x;
310 // Internal class to generate Line structures. If |multiline| is true, the text
311 // is broken into lines at |words| boundaries such that each line is no longer
312 // than |max_width|. If |multiline| is false, only outputs a single Line from
313 // the given runs. |min_baseline| and |min_height| are the minimum baseline and
314 // height for each line.
315 // TODO(ckocagil): Expose the interface of this class in the header and test
316 // this class directly.
319 LineBreaker(int max_width,
324 const BreakList<size_t>* words,
325 const ScopedVector<TextRun>& runs)
326 : max_width_(max_width),
327 min_baseline_(min_baseline),
328 min_height_(min_height),
329 multiline_(multiline),
340 // Breaks the run at given |run_index| into Line structs.
341 void AddRun(int run_index) {
342 const TextRun* run = runs_[run_index];
343 bool run_fits = !multiline_;
344 if (multiline_ && line_x_ + run->width <= max_width_) {
345 DCHECK(!run->range.is_empty());
346 const wchar_t first_char = text_[run->range.start()];
347 // Uniscribe always puts newline characters in their own runs.
348 if (!U16_IS_SINGLE(first_char) || first_char != L'\n')
355 AddSegment(run_index, run->range, run->width);
358 // Finishes line breaking and outputs the results. Can be called at most once.
359 void Finalize(std::vector<Line>* lines, Size* size) {
360 DCHECK(!lines_.empty());
361 // Add an empty line to finish the line size calculation and remove it.
369 // A (line index, segment index) pair that specifies a segment in |lines_|.
370 typedef std::pair<size_t, size_t> SegmentHandle;
372 LineSegment* SegmentFromHandle(const SegmentHandle& handle) {
373 return &lines_[handle.first].segments[handle.second];
376 // Breaks a run into segments that fit in the last line in |lines_| and adds
377 // them. Adds a new Line to the back of |lines_| whenever a new segment can't
378 // be added without the Line's width exceeding |max_width_|.
379 void BreakRun(int run_index) {
381 const TextRun* const run = runs_[run_index];
383 size_t next_char = run->range.start();
385 // Break the run until it fits the current line.
386 while (next_char < run->range.end()) {
387 const size_t current_char = next_char;
388 const bool skip_line = BreakRunAtWidth(text_, *run, *words_, current_char,
389 max_width_ - line_x_, line_x_ == 0, &width, &next_char);
390 AddSegment(run_index, Range(current_char, next_char), width);
396 // RTL runs are broken in logical order but displayed in visual order. To find
397 // the text-space coordinate (where it would fall in a single-line text)
398 // |x_range| of RTL segments, segment widths are applied in reverse order.
399 // e.g. {[5, 10], [10, 40]} will become {[35, 40], [5, 35]}.
400 void UpdateRTLSegmentRanges() {
401 if (rtl_segments_.empty())
403 int x = SegmentFromHandle(rtl_segments_[0])->x_range.start();
404 for (size_t i = rtl_segments_.size(); i > 0; --i) {
405 LineSegment* segment = SegmentFromHandle(rtl_segments_[i - 1]);
406 const size_t segment_width = segment->x_range.length();
407 segment->x_range = Range(x, x + segment_width);
410 rtl_segments_.clear();
413 // Finishes the size calculations of the last Line in |lines_|. Adds a new
414 // Line to the back of |lines_|.
416 if (!lines_.empty()) {
417 Line* line = &lines_.back();
418 // TODO(ckocagil): Determine optimal multiline height behavior.
419 if (line_ascent_ + line_descent_ == 0) {
420 line_ascent_ = min_baseline_;
421 line_descent_ = min_height_ - min_baseline_;
423 // Set the single-line mode Line's metrics to be at least
424 // |RenderText::font_list()| to not break the current single-line code.
425 line_ascent_ = std::max(line_ascent_, min_baseline_);
426 line_descent_ = std::max(line_descent_, min_height_ - min_baseline_);
428 line->baseline = line_ascent_;
429 line->size.set_height(line_ascent_ + line_descent_);
430 line->preceding_heights = total_size_.height();
431 total_size_.set_height(total_size_.height() + line->size.height());
432 total_size_.set_width(std::max(total_size_.width(), line->size.width()));
437 lines_.push_back(Line());
440 // Adds a new segment with the given properties to |lines_.back()|.
441 void AddSegment(int run_index, Range char_range, int width) {
442 if (char_range.is_empty()) {
446 const TextRun* run = runs_[run_index];
447 line_ascent_ = std::max(line_ascent_, run->font.GetBaseline());
448 line_descent_ = std::max(line_descent_,
449 run->font.GetHeight() - run->font.GetBaseline());
452 segment.run = run_index;
453 segment.char_range = char_range;
454 segment.x_range = Range(text_x_, text_x_ + width);
456 Line* line = &lines_.back();
457 line->segments.push_back(segment);
458 line->size.set_width(line->size.width() + segment.x_range.length());
459 if (run->script_analysis.fRTL) {
460 rtl_segments_.push_back(SegmentHandle(lines_.size() - 1,
461 line->segments.size() - 1));
462 // If this is the last segment of an RTL run, reprocess the text-space x
463 // ranges of all segments from the run.
464 if (char_range.end() == run->range.end())
465 UpdateRTLSegmentRanges();
471 const int max_width_;
472 const int min_baseline_;
473 const int min_height_;
474 const bool multiline_;
475 const wchar_t* text_;
476 const BreakList<size_t>* const words_;
477 const ScopedVector<TextRun>& runs_;
479 // Stores the resulting lines.
480 std::vector<Line> lines_;
482 // Text space and line space x coordinates of the next segment to be added.
486 // Size of the multiline text, not including the currently processed line.
489 // Ascent and descent values of the current line, |lines_.back()|.
493 // The current RTL run segments, to be applied by |UpdateRTLSegmentRanges()|.
494 std::vector<SegmentHandle> rtl_segments_;
496 DISALLOW_COPY_AND_ASSIGN(LineBreaker);
499 } // namespace internal
502 HDC RenderTextWin::cached_hdc_ = NULL;
505 std::map<std::string, Font> RenderTextWin::successful_substitute_fonts_;
507 RenderTextWin::RenderTextWin()
509 needs_layout_(false) {
510 set_truncate_length(kMaxUniscribeTextLength);
512 memset(&script_control_, 0, sizeof(script_control_));
513 memset(&script_state_, 0, sizeof(script_state_));
515 MoveCursorTo(EdgeSelectionModel(CURSOR_LEFT));
518 RenderTextWin::~RenderTextWin() {
521 Size RenderTextWin::GetStringSize() {
523 return multiline_string_size_;
526 SelectionModel RenderTextWin::FindCursorPosition(const Point& point) {
528 return SelectionModel();
531 // Find the run that contains the point and adjust the argument location.
532 int x = ToTextPoint(point).x();
533 size_t run_index = GetRunContainingXCoord(x);
534 if (run_index >= runs_.size())
535 return EdgeSelectionModel((x < 0) ? CURSOR_LEFT : CURSOR_RIGHT);
536 internal::TextRun* run = runs_[run_index];
538 int position = 0, trailing = 0;
539 HRESULT hr = ScriptXtoCP(x - run->preceding_run_widths,
542 run->logical_clusters.get(),
543 run->visible_attributes.get(),
544 run->advance_widths.get(),
545 &(run->script_analysis),
548 DCHECK(SUCCEEDED(hr));
549 DCHECK_GE(trailing, 0);
550 position += run->range.start();
551 const size_t cursor = LayoutIndexToTextIndex(position + trailing);
552 DCHECK_LE(cursor, text().length());
553 return SelectionModel(cursor, trailing ? CURSOR_BACKWARD : CURSOR_FORWARD);
556 std::vector<RenderText::FontSpan> RenderTextWin::GetFontSpansForTesting() {
559 std::vector<RenderText::FontSpan> spans;
560 for (size_t i = 0; i < runs_.size(); ++i) {
561 spans.push_back(RenderText::FontSpan(runs_[i]->font,
562 Range(LayoutIndexToTextIndex(runs_[i]->range.start()),
563 LayoutIndexToTextIndex(runs_[i]->range.end()))));
569 int RenderTextWin::GetLayoutTextBaseline() {
571 return lines()[0].baseline;
574 SelectionModel RenderTextWin::AdjacentCharSelectionModel(
575 const SelectionModel& selection,
576 VisualCursorDirection direction) {
577 DCHECK(!needs_layout_);
578 internal::TextRun* run;
579 size_t run_index = GetRunContainingCaret(selection);
580 if (run_index >= runs_.size()) {
581 // The cursor is not in any run: we're at the visual and logical edge.
582 SelectionModel edge = EdgeSelectionModel(direction);
583 if (edge.caret_pos() == selection.caret_pos())
585 int visual_index = (direction == CURSOR_RIGHT) ? 0 : runs_.size() - 1;
586 run = runs_[visual_to_logical_[visual_index]];
588 // If the cursor is moving within the current run, just move it by one
589 // grapheme in the appropriate direction.
590 run = runs_[run_index];
591 size_t caret = selection.caret_pos();
592 bool forward_motion =
593 run->script_analysis.fRTL == (direction == CURSOR_LEFT);
594 if (forward_motion) {
595 if (caret < LayoutIndexToTextIndex(run->range.end())) {
596 caret = IndexOfAdjacentGrapheme(caret, CURSOR_FORWARD);
597 return SelectionModel(caret, CURSOR_BACKWARD);
600 if (caret > LayoutIndexToTextIndex(run->range.start())) {
601 caret = IndexOfAdjacentGrapheme(caret, CURSOR_BACKWARD);
602 return SelectionModel(caret, CURSOR_FORWARD);
605 // The cursor is at the edge of a run; move to the visually adjacent run.
606 int visual_index = logical_to_visual_[run_index];
607 visual_index += (direction == CURSOR_LEFT) ? -1 : 1;
608 if (visual_index < 0 || visual_index >= static_cast<int>(runs_.size()))
609 return EdgeSelectionModel(direction);
610 run = runs_[visual_to_logical_[visual_index]];
612 bool forward_motion = run->script_analysis.fRTL == (direction == CURSOR_LEFT);
613 return forward_motion ? FirstSelectionModelInsideRun(run) :
614 LastSelectionModelInsideRun(run);
617 // TODO(msw): Implement word breaking for Windows.
618 SelectionModel RenderTextWin::AdjacentWordSelectionModel(
619 const SelectionModel& selection,
620 VisualCursorDirection direction) {
622 return EdgeSelectionModel(direction);
624 base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD);
625 bool success = iter.Init();
631 if (direction == CURSOR_RIGHT) {
632 pos = std::min(selection.caret_pos() + 1, text().length());
633 while (iter.Advance()) {
635 if (iter.IsWord() && pos > selection.caret_pos())
638 } else { // direction == CURSOR_LEFT
639 // Notes: We always iterate words from the beginning.
640 // This is probably fast enough for our usage, but we may
641 // want to modify WordIterator so that it can start from the
642 // middle of string and advance backwards.
643 pos = std::max<int>(selection.caret_pos() - 1, 0);
644 while (iter.Advance()) {
646 size_t begin = iter.pos() - iter.GetString().length();
647 if (begin == selection.caret_pos()) {
648 // The cursor is at the beginning of a word.
649 // Move to previous word.
651 } else if (iter.pos() >= selection.caret_pos()) {
652 // The cursor is in the middle or at the end of a word.
653 // Move to the top of current word.
657 pos = iter.pos() - iter.GetString().length();
662 return SelectionModel(pos, CURSOR_FORWARD);
665 Range RenderTextWin::GetGlyphBounds(size_t index) {
666 const size_t run_index =
667 GetRunContainingCaret(SelectionModel(index, CURSOR_FORWARD));
668 // Return edge bounds if the index is invalid or beyond the layout text size.
669 if (run_index >= runs_.size())
670 return Range(string_width_);
671 internal::TextRun* run = runs_[run_index];
672 const size_t layout_index = TextIndexToLayoutIndex(index);
673 return Range(GetGlyphXBoundary(run, layout_index, false),
674 GetGlyphXBoundary(run, layout_index, true));
677 std::vector<Rect> RenderTextWin::GetSubstringBounds(const Range& range) {
678 DCHECK(!needs_layout_);
679 DCHECK(Range(0, text().length()).Contains(range));
680 Range layout_range(TextIndexToLayoutIndex(range.start()),
681 TextIndexToLayoutIndex(range.end()));
682 DCHECK(Range(0, GetLayoutText().length()).Contains(layout_range));
684 std::vector<Rect> rects;
685 if (layout_range.is_empty())
687 std::vector<Range> bounds;
689 // Add a Range for each run/selection intersection.
690 // TODO(msw): The bounds should probably not always be leading the range ends.
691 for (size_t i = 0; i < runs_.size(); ++i) {
692 const internal::TextRun* run = runs_[visual_to_logical_[i]];
693 Range intersection = run->range.Intersect(layout_range);
694 if (intersection.IsValid()) {
695 DCHECK(!intersection.is_reversed());
696 Range range_x(GetGlyphXBoundary(run, intersection.start(), false),
697 GetGlyphXBoundary(run, intersection.end(), false));
698 if (range_x.is_empty())
700 range_x = Range(range_x.GetMin(), range_x.GetMax());
701 // Union this with the last range if they're adjacent.
702 DCHECK(bounds.empty() || bounds.back().GetMax() <= range_x.GetMin());
703 if (!bounds.empty() && bounds.back().GetMax() == range_x.GetMin()) {
704 range_x = Range(bounds.back().GetMin(), range_x.GetMax());
707 bounds.push_back(range_x);
710 for (size_t i = 0; i < bounds.size(); ++i) {
711 std::vector<Rect> current_rects = TextBoundsToViewBounds(bounds[i]);
712 rects.insert(rects.end(), current_rects.begin(), current_rects.end());
717 size_t RenderTextWin::TextIndexToLayoutIndex(size_t index) const {
718 DCHECK_LE(index, text().length());
719 ptrdiff_t i = obscured() ? gfx::UTF16IndexToOffset(text(), 0, index) : index;
721 // Clamp layout indices to the length of the text actually used for layout.
722 return std::min<size_t>(GetLayoutText().length(), i);
725 size_t RenderTextWin::LayoutIndexToTextIndex(size_t index) const {
729 DCHECK_LE(index, GetLayoutText().length());
730 const size_t text_index = gfx::UTF16OffsetToIndex(text(), 0, index);
731 DCHECK_LE(text_index, text().length());
735 bool RenderTextWin::IsCursorablePosition(size_t position) {
736 if (position == 0 || position == text().length())
740 // Check that the index is at a valid code point (not mid-surrgate-pair),
741 // that it is not truncated from layout text (its glyph is shown on screen),
742 // and that its glyph has distinct bounds (not mid-multi-character-grapheme).
743 // An example of a multi-character-grapheme that is not a surrogate-pair is:
744 // \x0915\x093f - (ki) - one of many Devanagari biconsonantal conjuncts.
745 return gfx::IsValidCodePointIndex(text(), position) &&
746 position < LayoutIndexToTextIndex(GetLayoutText().length()) &&
747 GetGlyphBounds(position) != GetGlyphBounds(position - 1);
750 void RenderTextWin::ResetLayout() {
751 // Layout is performed lazily as needed for drawing/metrics.
752 needs_layout_ = true;
755 void RenderTextWin::EnsureLayout() {
757 // TODO(msw): Skip complex processing if ScriptIsComplex returns false.
758 ItemizeLogicalText();
761 needs_layout_ = false;
762 std::vector<internal::Line> lines;
766 // Compute lines if they're not valid. This is separate from the layout steps
767 // above to avoid text layout and shaping when we resize |display_rect_|.
768 if (lines().empty()) {
769 DCHECK(!needs_layout_);
770 std::vector<internal::Line> lines;
771 internal::LineBreaker line_breaker(display_rect().width() - 1,
772 font_list().GetBaseline(),
773 font_list().GetHeight(), multiline(),
774 GetLayoutText().c_str(),
775 multiline() ? &GetLineBreaks() : NULL,
777 for (size_t i = 0; i < runs_.size(); ++i)
778 line_breaker.AddRun(visual_to_logical_[i]);
779 line_breaker.Finalize(&lines, &multiline_string_size_);
780 DCHECK(!lines.empty());
782 CheckLineIntegrity(lines, runs_);
788 void RenderTextWin::DrawVisualText(Canvas* canvas) {
789 DCHECK(!needs_layout_);
790 DCHECK(!lines().empty());
792 std::vector<SkPoint> pos;
794 internal::SkiaTextRenderer renderer(canvas);
795 ApplyFadeEffects(&renderer);
796 ApplyTextShadows(&renderer);
798 bool smoothing_enabled;
799 bool cleartype_enabled;
800 GetCachedFontSmoothingSettings(&smoothing_enabled, &cleartype_enabled);
801 // Note that |cleartype_enabled| corresponds to Skia's |enable_lcd_text|.
802 renderer.SetFontSmoothingSettings(
803 smoothing_enabled, cleartype_enabled && !background_is_transparent(),
804 smoothing_enabled /* subpixel_positioning */);
806 ApplyCompositionAndSelectionStyles();
808 for (size_t i = 0; i < lines().size(); ++i) {
809 const internal::Line& line = lines()[i];
810 const Vector2d line_offset = GetLineOffset(i);
812 // Skip painting empty lines or lines outside the display rect area.
813 if (!display_rect().Intersects(Rect(PointAtOffsetFromOrigin(line_offset),
817 const Vector2d text_offset = line_offset + Vector2d(0, line.baseline);
818 int preceding_segment_widths = 0;
820 for (size_t j = 0; j < line.segments.size(); ++j) {
821 const internal::LineSegment* segment = &line.segments[j];
822 const int segment_width = segment->x_range.length();
823 const internal::TextRun* run = runs_[segment->run];
824 DCHECK(!segment->char_range.is_empty());
825 DCHECK(run->range.Contains(segment->char_range));
826 Range glyph_range = CharRangeToGlyphRange(*run, segment->char_range);
827 DCHECK(!glyph_range.is_empty());
828 // Skip painting segments outside the display rect area.
830 const Rect segment_bounds(PointAtOffsetFromOrigin(line_offset) +
831 Vector2d(preceding_segment_widths, 0),
832 Size(segment_width, line.size.height()));
833 if (!display_rect().Intersects(segment_bounds)) {
834 preceding_segment_widths += segment_width;
839 // |pos| contains the positions of glyphs. An extra terminal |pos| entry
840 // is added to simplify width calculations.
841 int segment_x = preceding_segment_widths;
842 pos.resize(glyph_range.length() + 1);
843 for (size_t k = glyph_range.start(); k < glyph_range.end(); ++k) {
844 pos[k - glyph_range.start()].set(
845 SkIntToScalar(text_offset.x() + run->offsets[k].du + segment_x),
846 SkIntToScalar(text_offset.y() + run->offsets[k].dv));
847 segment_x += run->advance_widths[k];
849 pos.back().set(SkIntToScalar(text_offset.x() + segment_x),
850 SkIntToScalar(text_offset.y()));
852 renderer.SetTextSize(run->font.GetFontSize());
853 renderer.SetFontFamilyWithStyle(run->font.GetFontName(), run->font_style);
855 for (BreakList<SkColor>::const_iterator it =
856 colors().GetBreak(segment->char_range.start());
857 it != colors().breaks().end() &&
858 it->first < segment->char_range.end();
860 const Range intersection =
861 colors().GetRange(it).Intersect(segment->char_range);
862 const Range colored_glyphs = CharRangeToGlyphRange(*run, intersection);
863 DCHECK(glyph_range.Contains(colored_glyphs));
864 DCHECK(!colored_glyphs.is_empty());
865 const SkPoint& start_pos =
866 pos[colored_glyphs.start() - glyph_range.start()];
867 const SkPoint& end_pos =
868 pos[colored_glyphs.end() - glyph_range.start()];
870 renderer.SetForegroundColor(it->second);
871 renderer.DrawPosText(&start_pos, &run->glyphs[colored_glyphs.start()],
872 colored_glyphs.length());
873 renderer.DrawDecorations(start_pos.x(), text_offset.y(),
874 SkScalarCeilToInt(end_pos.x() - start_pos.x()),
875 run->underline, run->strike,
876 run->diagonal_strike);
879 preceding_segment_widths += segment_width;
883 UndoCompositionAndSelectionStyles();
886 void RenderTextWin::ItemizeLogicalText() {
889 multiline_string_size_ = Size();
891 // Set Uniscribe's base text direction.
892 script_state_.uBidiLevel =
893 (GetTextDirection() == base::i18n::RIGHT_TO_LEFT) ? 1 : 0;
895 const base::string16& layout_text = GetLayoutText();
896 if (layout_text.empty())
899 HRESULT hr = E_OUTOFMEMORY;
900 int script_items_count = 0;
901 std::vector<SCRIPT_ITEM> script_items;
902 const size_t layout_text_length = layout_text.length();
903 // Ensure that |kMaxRuns| is attempted and the loop terminates afterward.
904 for (size_t runs = kGuessRuns; hr == E_OUTOFMEMORY && runs <= kMaxRuns;
905 runs = std::max(runs + 1, std::min(runs * 2, kMaxRuns))) {
906 // Derive the array of Uniscribe script items from the logical text.
907 // ScriptItemize always adds a terminal array item so that the length of
908 // the last item can be derived from the terminal SCRIPT_ITEM::iCharPos.
909 script_items.resize(runs);
910 hr = ScriptItemize(layout_text.c_str(), layout_text_length, runs - 1,
911 &script_control_, &script_state_, &script_items[0],
912 &script_items_count);
914 DCHECK(SUCCEEDED(hr));
915 if (!SUCCEEDED(hr) || script_items_count <= 0)
918 // Temporarily apply composition underlines and selection colors.
919 ApplyCompositionAndSelectionStyles();
921 // Build the list of runs from the script items and ranged styles. Use an
922 // empty color BreakList to avoid breaking runs at color boundaries.
923 BreakList<SkColor> empty_colors;
924 empty_colors.SetMax(layout_text_length);
925 internal::StyleIterator style(empty_colors, styles());
926 SCRIPT_ITEM* script_item = &script_items[0];
927 const size_t max_run_length = kMaxGlyphs / 2;
928 for (size_t run_break = 0; run_break < layout_text_length;) {
929 internal::TextRun* run = new internal::TextRun();
930 run->range.set_start(run_break);
931 run->font = font_list().GetPrimaryFont();
932 run->font_style = (style.style(BOLD) ? Font::BOLD : 0) |
933 (style.style(ITALIC) ? Font::ITALIC : 0);
934 DeriveFontIfNecessary(run->font.GetFontSize(), run->font.GetHeight(),
935 run->font_style, &run->font);
936 run->strike = style.style(STRIKE);
937 run->diagonal_strike = style.style(DIAGONAL_STRIKE);
938 run->underline = style.style(UNDERLINE);
939 run->script_analysis = script_item->a;
941 // Find the next break and advance the iterators as needed.
942 const size_t script_item_break = (script_item + 1)->iCharPos;
943 run_break = std::min(script_item_break,
944 TextIndexToLayoutIndex(style.GetRange().end()));
946 // Clamp run lengths to avoid exceeding the maximum supported glyph count.
947 if ((run_break - run->range.start()) > max_run_length) {
948 run_break = run->range.start() + max_run_length;
949 if (!IsValidCodePointIndex(layout_text, run_break))
953 // Break runs adjacent to character substrings in certain code blocks.
954 // This avoids using their fallback fonts for more characters than needed,
955 // in cases like "\x25B6 Media Title", etc. http://crbug.com/278913
956 if (run_break > run->range.start()) {
957 const size_t run_start = run->range.start();
958 const int32 run_length = static_cast<int32>(run_break - run_start);
959 base::i18n::UTF16CharIterator iter(layout_text.c_str() + run_start,
961 const UBlockCode first_block_code = ublock_getCode(iter.get());
962 const bool first_block_unusual = IsUnusualBlockCode(first_block_code);
963 while (iter.Advance() && iter.array_pos() < run_length) {
964 const UBlockCode current_block_code = ublock_getCode(iter.get());
965 if (current_block_code != first_block_code &&
966 (first_block_unusual || IsUnusualBlockCode(current_block_code))) {
967 run_break = run_start + iter.array_pos();
973 DCHECK(IsValidCodePointIndex(layout_text, run_break));
975 style.UpdatePosition(LayoutIndexToTextIndex(run_break));
976 if (script_item_break == run_break)
978 run->range.set_end(run_break);
979 runs_.push_back(run);
982 // Undo the temporarily applied composition underlines and selection colors.
983 UndoCompositionAndSelectionStyles();
986 void RenderTextWin::LayoutVisualText() {
987 DCHECK(!runs_.empty());
990 cached_hdc_ = CreateCompatibleDC(NULL);
993 // Ensure ascent and descent are not smaller than ones of the font list.
994 // Keep them tall enough to draw often-used characters.
995 // For example, if a text field contains a Japanese character, which is
996 // smaller than Latin ones, and then later a Latin one is inserted, this
997 // ensures that the text baseline does not shift.
998 int ascent = font_list().GetBaseline();
999 int descent = font_list().GetHeight() - font_list().GetBaseline();
1000 for (size_t i = 0; i < runs_.size(); ++i) {
1001 internal::TextRun* run = runs_[i];
1004 ascent = std::max(ascent, run->font.GetBaseline());
1005 descent = std::max(descent,
1006 run->font.GetHeight() - run->font.GetBaseline());
1008 if (run->glyph_count > 0) {
1009 run->advance_widths.reset(new int[run->glyph_count]);
1010 run->offsets.reset(new GOFFSET[run->glyph_count]);
1011 hr = ScriptPlace(cached_hdc_,
1015 run->visible_attributes.get(),
1016 &(run->script_analysis),
1017 run->advance_widths.get(),
1019 &(run->abc_widths));
1020 DCHECK(SUCCEEDED(hr));
1024 // Build the array of bidirectional embedding levels.
1025 scoped_ptr<BYTE[]> levels(new BYTE[runs_.size()]);
1026 for (size_t i = 0; i < runs_.size(); ++i)
1027 levels[i] = runs_[i]->script_analysis.s.uBidiLevel;
1029 // Get the maps between visual and logical run indices.
1030 visual_to_logical_.reset(new int[runs_.size()]);
1031 logical_to_visual_.reset(new int[runs_.size()]);
1032 hr = ScriptLayout(runs_.size(),
1034 visual_to_logical_.get(),
1035 logical_to_visual_.get());
1036 DCHECK(SUCCEEDED(hr));
1038 // Precalculate run width information.
1039 size_t preceding_run_widths = 0;
1040 for (size_t i = 0; i < runs_.size(); ++i) {
1041 internal::TextRun* run = runs_[visual_to_logical_[i]];
1042 run->preceding_run_widths = preceding_run_widths;
1043 const ABC& abc = run->abc_widths;
1044 run->width = abc.abcA + abc.abcB + abc.abcC;
1045 preceding_run_widths += run->width;
1047 string_width_ = preceding_run_widths;
1050 void RenderTextWin::LayoutTextRun(internal::TextRun* run) {
1051 const size_t run_length = run->range.length();
1052 const wchar_t* run_text = &(GetLayoutText()[run->range.start()]);
1053 Font original_font = run->font;
1054 LinkedFontsIterator fonts(original_font);
1055 bool tried_cached_font = false;
1056 bool tried_fallback = false;
1057 // Keep track of the font that is able to display the greatest number of
1058 // characters for which ScriptShape() returned S_OK. This font will be used
1059 // in the case where no font is able to display the entire run.
1060 int best_partial_font_missing_char_count = INT_MAX;
1061 Font best_partial_font = original_font;
1064 run->logical_clusters.reset(new WORD[run_length]);
1065 while (fonts.NextFont(¤t_font)) {
1066 HRESULT hr = ShapeTextRunWithFont(run, current_font);
1068 bool glyphs_missing = false;
1069 if (hr == USP_E_SCRIPT_NOT_IN_FONT) {
1070 glyphs_missing = true;
1071 } else if (hr == S_OK) {
1072 // If |hr| is S_OK, there could still be missing glyphs in the output.
1073 // http://msdn.microsoft.com/en-us/library/windows/desktop/dd368564.aspx
1074 const int missing_count = CountCharsWithMissingGlyphs(run);
1075 // Track the font that produced the least missing glyphs.
1076 if (missing_count < best_partial_font_missing_char_count) {
1077 best_partial_font_missing_char_count = missing_count;
1078 best_partial_font = run->font;
1080 glyphs_missing = (missing_count != 0);
1085 // Use the font if it had glyphs for all characters.
1086 if (!glyphs_missing) {
1087 // Save the successful fallback font that was chosen.
1089 successful_substitute_fonts_[original_font.GetFontName()] = run->font;
1093 // First, try the cached font from previous runs, if any.
1094 if (!tried_cached_font) {
1095 tried_cached_font = true;
1097 std::map<std::string, Font>::const_iterator it =
1098 successful_substitute_fonts_.find(original_font.GetFontName());
1099 if (it != successful_substitute_fonts_.end()) {
1100 fonts.SetNextFont(it->second);
1105 // If there are missing glyphs, first try finding a fallback font using a
1106 // meta file, if it hasn't yet been attempted for this run.
1107 // TODO(msw|asvitkine): Support RenderText's font_list()?
1108 if (!tried_fallback) {
1109 tried_fallback = true;
1112 if (ChooseFallbackFont(cached_hdc_, run->font, run_text, run_length,
1114 fonts.SetNextFont(fallback_font);
1120 // If a font was able to partially display the run, use that now.
1121 if (best_partial_font_missing_char_count < static_cast<int>(run_length)) {
1122 // Re-shape the run only if |best_partial_font| differs from the last font.
1123 if (best_partial_font.GetNativeFont() != run->font.GetNativeFont())
1124 ShapeTextRunWithFont(run, best_partial_font);
1128 // If no font was able to partially display the run, replace all glyphs
1129 // with |wgDefault| from the original font to ensure to they don't hold
1131 // First, clear the cache and select the original font on the HDC.
1132 ScriptFreeCache(&run->script_cache);
1133 run->font = original_font;
1134 SelectObject(cached_hdc_, run->font.GetNativeFont());
1136 // Now, get the font's properties.
1137 SCRIPT_FONTPROPERTIES properties;
1138 memset(&properties, 0, sizeof(properties));
1139 properties.cBytes = sizeof(properties);
1140 HRESULT hr = ScriptGetFontProperties(cached_hdc_, &run->script_cache,
1143 // The initial values for the "missing" glyph and the space glyph are taken
1144 // from the recommendations section of the OpenType spec:
1145 // https://www.microsoft.com/typography/otspec/recom.htm
1146 WORD missing_glyph = 0;
1147 WORD space_glyph = 3;
1149 missing_glyph = properties.wgDefault;
1150 space_glyph = properties.wgBlank;
1153 // Finally, initialize |glyph_count|, |glyphs|, |visible_attributes| and
1154 // |logical_clusters| on the run (since they may not have been set yet).
1155 run->glyph_count = run_length;
1156 memset(run->visible_attributes.get(), 0,
1157 run->glyph_count * sizeof(SCRIPT_VISATTR));
1158 for (int i = 0; i < run->glyph_count; ++i)
1159 run->glyphs[i] = IsWhitespace(run_text[i]) ? space_glyph : missing_glyph;
1160 for (size_t i = 0; i < run_length; ++i) {
1161 run->logical_clusters[i] = run->script_analysis.fRTL ?
1162 run_length - 1 - i : i;
1165 // TODO(msw): Don't use SCRIPT_UNDEFINED. Apparently Uniscribe can
1166 // crash on certain surrogate pairs with SCRIPT_UNDEFINED.
1167 // See https://bugzilla.mozilla.org/show_bug.cgi?id=341500
1168 // And http://maxradi.us/documents/uniscribe/
1169 run->script_analysis.eScript = SCRIPT_UNDEFINED;
1172 HRESULT RenderTextWin::ShapeTextRunWithFont(internal::TextRun* run,
1174 // Update the run's font only if necessary. If the two fonts wrap the same
1175 // PlatformFontWin object, their native fonts will have the same value.
1176 if (run->font.GetNativeFont() != font.GetNativeFont()) {
1177 const int font_size = run->font.GetFontSize();
1178 const int font_height = run->font.GetHeight();
1180 DeriveFontIfNecessary(font_size, font_height, run->font_style, &run->font);
1181 ScriptFreeCache(&run->script_cache);
1184 // Select the font desired for glyph generation.
1185 SelectObject(cached_hdc_, run->font.GetNativeFont());
1187 HRESULT hr = E_OUTOFMEMORY;
1188 const size_t run_length = run->range.length();
1189 const wchar_t* run_text = &(GetLayoutText()[run->range.start()]);
1190 // Guess the expected number of glyphs from the length of the run.
1191 // MSDN suggests this at http://msdn.microsoft.com/en-us/library/dd368564.aspx
1192 size_t max_glyphs = static_cast<size_t>(1.5 * run_length + 16);
1193 while (hr == E_OUTOFMEMORY && max_glyphs <= kMaxGlyphs) {
1194 run->glyph_count = 0;
1195 run->glyphs.reset(new WORD[max_glyphs]);
1196 run->visible_attributes.reset(new SCRIPT_VISATTR[max_glyphs]);
1197 hr = ScriptShape(cached_hdc_, &run->script_cache, run_text, run_length,
1198 max_glyphs, &run->script_analysis, run->glyphs.get(),
1199 run->logical_clusters.get(), run->visible_attributes.get(),
1201 // Ensure that |kMaxGlyphs| is attempted and the loop terminates afterward.
1202 max_glyphs = std::max(max_glyphs + 1, std::min(max_glyphs * 2, kMaxGlyphs));
1207 int RenderTextWin::CountCharsWithMissingGlyphs(internal::TextRun* run) const {
1208 int chars_not_missing_glyphs = 0;
1209 SCRIPT_FONTPROPERTIES properties;
1210 memset(&properties, 0, sizeof(properties));
1211 properties.cBytes = sizeof(properties);
1212 ScriptGetFontProperties(cached_hdc_, &run->script_cache, &properties);
1214 const wchar_t* run_text = &(GetLayoutText()[run->range.start()]);
1215 for (size_t char_index = 0; char_index < run->range.length(); ++char_index) {
1216 const int glyph_index = run->logical_clusters[char_index];
1217 DCHECK_GE(glyph_index, 0);
1218 DCHECK_LT(glyph_index, run->glyph_count);
1220 if (run->glyphs[glyph_index] == properties.wgDefault)
1223 // Windows Vista sometimes returns glyphs equal to wgBlank (instead of
1224 // wgDefault), with fZeroWidth set. Treat such cases as having missing
1225 // glyphs if the corresponding character is not whitespace.
1226 // See: http://crbug.com/125629
1227 if (run->glyphs[glyph_index] == properties.wgBlank &&
1228 run->visible_attributes[glyph_index].fZeroWidth &&
1229 !IsWhitespace(run_text[char_index]) &&
1230 !IsUnicodeBidiControlCharacter(run_text[char_index])) {
1234 ++chars_not_missing_glyphs;
1237 DCHECK_LE(chars_not_missing_glyphs, static_cast<int>(run->range.length()));
1238 return run->range.length() - chars_not_missing_glyphs;
1241 size_t RenderTextWin::GetRunContainingCaret(const SelectionModel& caret) const {
1242 DCHECK(!needs_layout_);
1243 size_t layout_position = TextIndexToLayoutIndex(caret.caret_pos());
1244 LogicalCursorDirection affinity = caret.caret_affinity();
1245 for (size_t run = 0; run < runs_.size(); ++run)
1246 if (RangeContainsCaret(runs_[run]->range, layout_position, affinity))
1248 return runs_.size();
1251 size_t RenderTextWin::GetRunContainingXCoord(int x) const {
1252 DCHECK(!needs_layout_);
1253 // Find the text run containing the argument point (assumed already offset).
1254 for (size_t run = 0; run < runs_.size(); ++run) {
1255 if ((runs_[run]->preceding_run_widths <= x) &&
1256 ((runs_[run]->preceding_run_widths + runs_[run]->width) > x))
1259 return runs_.size();
1262 SelectionModel RenderTextWin::FirstSelectionModelInsideRun(
1263 const internal::TextRun* run) {
1264 size_t position = LayoutIndexToTextIndex(run->range.start());
1265 position = IndexOfAdjacentGrapheme(position, CURSOR_FORWARD);
1266 return SelectionModel(position, CURSOR_BACKWARD);
1269 SelectionModel RenderTextWin::LastSelectionModelInsideRun(
1270 const internal::TextRun* run) {
1271 size_t position = LayoutIndexToTextIndex(run->range.end());
1272 position = IndexOfAdjacentGrapheme(position, CURSOR_BACKWARD);
1273 return SelectionModel(position, CURSOR_FORWARD);
1276 RenderText* RenderText::CreateInstance() {
1277 return new RenderTextWin;