Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / ui / gfx / render_text_win.cc
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.
4
5 #include "ui/gfx/render_text_win.h"
6
7 #include <algorithm>
8
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"
22
23 namespace gfx {
24
25 namespace {
26
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;
31
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;
36
37 // The maximum number of glyphs per run; ScriptShape fails on larger values.
38 const size_t kMaxGlyphs = 65535;
39
40 // Callback to |EnumEnhMetaFile()| to intercept font creation.
41 int CALLBACK MetaFileEnumProc(HDC hdc,
42                               HANDLETABLE* table,
43                               CONST ENHMETARECORD* record,
44                               int table_entries,
45                               LPARAM log_font) {
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;
50   }
51   return 1;
52 }
53
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,
60                         const Font& font,
61                         const wchar_t* text,
62                         int text_length,
63                         Font* result) {
64   // Use a meta file to intercept the fallback font chosen by Uniscribe.
65   HDC meta_file_dc = CreateEnhMetaFile(hdc, NULL, NULL, NULL);
66   if (!meta_file_dc)
67     return false;
68
69   SelectObject(meta_file_dc, font.GetNativeFont());
70
71   SCRIPT_STRING_ANALYSIS script_analysis;
72   HRESULT hresult =
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);
76
77   if (SUCCEEDED(hresult)) {
78     hresult = ScriptStringOut(script_analysis, 0, 0, 0, NULL, 0, 0, FALSE);
79     ScriptStringFree(&script_analysis);
80   }
81
82   bool found_fallback = false;
83   HENHMETAFILE meta_file = CloseEnhMetaFile(meta_file_dc);
84   if (SUCCEEDED(hresult)) {
85     LOGFONT log_font;
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),
90                      font.GetFontSize());
91       found_fallback = true;
92     }
93   }
94   DeleteEnhMetaFile(meta_file);
95
96   return found_fallback;
97 }
98
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,
103                            int font_height,
104                            int font_style,
105                            Font* font) {
106   const int kStyleMask = (Font::BOLD | Font::ITALIC);
107   const int target_style = (font_style & kStyleMask);
108
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);
115     return;
116   }
117
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);
122 }
123
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;
133 }
134
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());
145   Range result;
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]
149                               : run.glyph_count);
150   } else {
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);
154   }
155   DCHECK(!result.is_reversed());
156   DCHECK(Range(0, run.glyph_count).Contains(result));
157   return result;
158 }
159
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,
173                      size_t start_char,
174                      int available_width,
175                      bool empty_line,
176                      int* width,
177                      size_t* next_char) {
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.
182   int word_width = 0;
183   *width = 0;
184
185   for (size_t i = start_char; i < run.range.end(); ++i) {
186     if (U16_IS_SINGLE(text[i]) && text[i] == L'\n') {
187       *next_char = i + 1;
188       return true;
189     }
190
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) {
195       word = next_word++;
196       word_width = 0;
197     }
198
199     Range glyph_range = CharRangeToGlyphRange(run, Range(i, i + 1));
200     int char_width = 0;
201     for (size_t j = glyph_range.start(); j < glyph_range.end(); ++j)
202       char_width += run.advance_widths[j];
203
204     *width += char_width;
205     word_width += char_width;
206
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;
215         *next_char = i;
216       } else {
217         // Continue from the next character.
218         *next_char = i + 1;
219       }
220
221       return true;
222     }
223   }
224
225   *next_char = run.range.end();
226   return false;
227 }
228
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;
235
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];
240
241       if (!previous_segment) {
242         previous_segment = segment;
243       } else if (runs[previous_segment->run] != run) {
244         previous_segment = NULL;
245       } else {
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());
250         } else {
251           DCHECK_EQ(segment->x_range.end(), previous_segment->x_range.start());
252         }
253
254         previous_segment = segment;
255         previous_segment_line = i;
256       }
257     }
258   }
259 }
260
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;
265 }
266
267 }  // namespace
268
269 namespace internal {
270
271 TextRun::TextRun()
272   : font_style(0),
273     strike(false),
274     diagonal_strike(false),
275     underline(false),
276     width(0),
277     preceding_run_widths(0),
278     glyph_count(0),
279     script_cache(NULL) {
280   memset(&script_analysis, 0, sizeof(script_analysis));
281   memset(&abc_widths, 0, sizeof(abc_widths));
282 }
283
284 TextRun::~TextRun() {
285   ScriptFreeCache(&script_cache);
286 }
287
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,
291                       size_t index,
292                       bool trailing) {
293   DCHECK_GE(index, run->range.start());
294   DCHECK_LT(index, run->range.end() + (trailing ? 0 : 1));
295   int x = 0;
296   HRESULT hr = ScriptCPtoX(
297       index - run->range.start(),
298       trailing,
299       run->range.length(),
300       run->glyph_count,
301       run->logical_clusters.get(),
302       run->visible_attributes.get(),
303       run->advance_widths.get(),
304       &run->script_analysis,
305       &x);
306   DCHECK(SUCCEEDED(hr));
307   return run->preceding_run_widths + x;
308 }
309
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.
317 class LineBreaker {
318  public:
319   LineBreaker(int max_width,
320               int min_baseline,
321               int min_height,
322               bool multiline,
323               const wchar_t* text,
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),
330         text_(text),
331         words_(words),
332         runs_(runs),
333         text_x_(0),
334         line_x_(0),
335         line_ascent_(0),
336         line_descent_(0) {
337     AdvanceLine();
338   }
339
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')
349         run_fits = true;
350     }
351
352     if (!run_fits)
353       BreakRun(run_index);
354     else
355       AddSegment(run_index, run->range, run->width);
356   }
357
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.
362     AdvanceLine();
363     lines_.pop_back();
364     *size = total_size_;
365     lines->swap(lines_);
366   }
367
368  private:
369   // A (line index, segment index) pair that specifies a segment in |lines_|.
370   typedef std::pair<size_t, size_t> SegmentHandle;
371
372   LineSegment* SegmentFromHandle(const SegmentHandle& handle) {
373     return &lines_[handle.first].segments[handle.second];
374   }
375
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) {
380     DCHECK(words_);
381     const TextRun* const run = runs_[run_index];
382     int width = 0;
383     size_t next_char = run->range.start();
384
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);
391       if (skip_line)
392         AdvanceLine();
393     }
394   }
395
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())
402       return;
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);
408       x += segment_width;
409     }
410     rtl_segments_.clear();
411   }
412
413   // Finishes the size calculations of the last Line in |lines_|. Adds a new
414   // Line to the back of |lines_|.
415   void AdvanceLine() {
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_;
422       }
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_);
427
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()));
433     }
434     line_x_ = 0;
435     line_ascent_ = 0;
436     line_descent_ = 0;
437     lines_.push_back(Line());
438   }
439
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()) {
443       DCHECK_EQ(width, 0);
444       return;
445     }
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());
450
451     LineSegment segment;
452     segment.run = run_index;
453     segment.char_range = char_range;
454     segment.x_range = Range(text_x_, text_x_ + width);
455
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();
466     }
467     text_x_ += width;
468     line_x_ += width;
469   }
470
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_;
478
479   // Stores the resulting lines.
480   std::vector<Line> lines_;
481
482   // Text space and line space x coordinates of the next segment to be added.
483   int text_x_;
484   int line_x_;
485
486   // Size of the multiline text, not including the currently processed line.
487   Size total_size_;
488
489   // Ascent and descent values of the current line, |lines_.back()|.
490   int line_ascent_;
491   int line_descent_;
492
493   // The current RTL run segments, to be applied by |UpdateRTLSegmentRanges()|.
494   std::vector<SegmentHandle> rtl_segments_;
495
496   DISALLOW_COPY_AND_ASSIGN(LineBreaker);
497 };
498
499 }  // namespace internal
500
501 // static
502 HDC RenderTextWin::cached_hdc_ = NULL;
503
504 // static
505 std::map<std::string, Font> RenderTextWin::successful_substitute_fonts_;
506
507 RenderTextWin::RenderTextWin() : RenderText(), needs_layout_(false) {
508   set_truncate_length(kMaxUniscribeTextLength);
509   memset(&script_control_, 0, sizeof(script_control_));
510   memset(&script_state_, 0, sizeof(script_state_));
511   MoveCursorTo(EdgeSelectionModel(CURSOR_LEFT));
512 }
513
514 RenderTextWin::~RenderTextWin() {}
515
516 Size RenderTextWin::GetStringSize() {
517   EnsureLayout();
518   return multiline_string_size_;
519 }
520
521 SelectionModel RenderTextWin::FindCursorPosition(const Point& point) {
522   if (text().empty())
523     return SelectionModel();
524
525   EnsureLayout();
526   // Find the run that contains the point and adjust the argument location.
527   int x = ToTextPoint(point).x();
528   size_t run_index = GetRunContainingXCoord(x);
529   if (run_index >= runs_.size())
530     return EdgeSelectionModel((x < 0) ? CURSOR_LEFT : CURSOR_RIGHT);
531   internal::TextRun* run = runs_[run_index];
532
533   int position = 0, trailing = 0;
534   HRESULT hr = ScriptXtoCP(x - run->preceding_run_widths,
535                            run->range.length(),
536                            run->glyph_count,
537                            run->logical_clusters.get(),
538                            run->visible_attributes.get(),
539                            run->advance_widths.get(),
540                            &(run->script_analysis),
541                            &position,
542                            &trailing);
543   DCHECK(SUCCEEDED(hr));
544   DCHECK_GE(trailing, 0);
545   position += run->range.start();
546   const size_t cursor = LayoutIndexToTextIndex(position + trailing);
547   DCHECK_LE(cursor, text().length());
548   return SelectionModel(cursor, trailing ? CURSOR_BACKWARD : CURSOR_FORWARD);
549 }
550
551 std::vector<RenderText::FontSpan> RenderTextWin::GetFontSpansForTesting() {
552   EnsureLayout();
553
554   std::vector<RenderText::FontSpan> spans;
555   for (size_t i = 0; i < runs_.size(); ++i) {
556     spans.push_back(RenderText::FontSpan(runs_[i]->font,
557         Range(LayoutIndexToTextIndex(runs_[i]->range.start()),
558               LayoutIndexToTextIndex(runs_[i]->range.end()))));
559   }
560
561   return spans;
562 }
563
564 int RenderTextWin::GetLayoutTextBaseline() {
565   EnsureLayout();
566   return lines()[0].baseline;
567 }
568
569 SelectionModel RenderTextWin::AdjacentCharSelectionModel(
570     const SelectionModel& selection,
571     VisualCursorDirection direction) {
572   DCHECK(!needs_layout_);
573   internal::TextRun* run;
574   size_t run_index = GetRunContainingCaret(selection);
575   if (run_index >= runs_.size()) {
576     // The cursor is not in any run: we're at the visual and logical edge.
577     SelectionModel edge = EdgeSelectionModel(direction);
578     if (edge.caret_pos() == selection.caret_pos())
579       return edge;
580     int visual_index = (direction == CURSOR_RIGHT) ? 0 : runs_.size() - 1;
581     run = runs_[visual_to_logical_[visual_index]];
582   } else {
583     // If the cursor is moving within the current run, just move it by one
584     // grapheme in the appropriate direction.
585     run = runs_[run_index];
586     size_t caret = selection.caret_pos();
587     bool forward_motion =
588         run->script_analysis.fRTL == (direction == CURSOR_LEFT);
589     if (forward_motion) {
590       if (caret < LayoutIndexToTextIndex(run->range.end())) {
591         caret = IndexOfAdjacentGrapheme(caret, CURSOR_FORWARD);
592         return SelectionModel(caret, CURSOR_BACKWARD);
593       }
594     } else {
595       if (caret > LayoutIndexToTextIndex(run->range.start())) {
596         caret = IndexOfAdjacentGrapheme(caret, CURSOR_BACKWARD);
597         return SelectionModel(caret, CURSOR_FORWARD);
598       }
599     }
600     // The cursor is at the edge of a run; move to the visually adjacent run.
601     int visual_index = logical_to_visual_[run_index];
602     visual_index += (direction == CURSOR_LEFT) ? -1 : 1;
603     if (visual_index < 0 || visual_index >= static_cast<int>(runs_.size()))
604       return EdgeSelectionModel(direction);
605     run = runs_[visual_to_logical_[visual_index]];
606   }
607   bool forward_motion = run->script_analysis.fRTL == (direction == CURSOR_LEFT);
608   return forward_motion ? FirstSelectionModelInsideRun(run) :
609                           LastSelectionModelInsideRun(run);
610 }
611
612 // TODO(msw): Implement word breaking for Windows.
613 SelectionModel RenderTextWin::AdjacentWordSelectionModel(
614     const SelectionModel& selection,
615     VisualCursorDirection direction) {
616   if (obscured())
617     return EdgeSelectionModel(direction);
618
619   base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD);
620   bool success = iter.Init();
621   DCHECK(success);
622   if (!success)
623     return selection;
624
625   size_t pos;
626   if (direction == CURSOR_RIGHT) {
627     pos = std::min(selection.caret_pos() + 1, text().length());
628     while (iter.Advance()) {
629       pos = iter.pos();
630       if (iter.IsWord() && pos > selection.caret_pos())
631         break;
632     }
633   } else {  // direction == CURSOR_LEFT
634     // Notes: We always iterate words from the beginning.
635     // This is probably fast enough for our usage, but we may
636     // want to modify WordIterator so that it can start from the
637     // middle of string and advance backwards.
638     pos = std::max<int>(selection.caret_pos() - 1, 0);
639     while (iter.Advance()) {
640       if (iter.IsWord()) {
641         size_t begin = iter.pos() - iter.GetString().length();
642         if (begin == selection.caret_pos()) {
643           // The cursor is at the beginning of a word.
644           // Move to previous word.
645           break;
646         } else if (iter.pos() >= selection.caret_pos()) {
647           // The cursor is in the middle or at the end of a word.
648           // Move to the top of current word.
649           pos = begin;
650           break;
651         } else {
652           pos = iter.pos() - iter.GetString().length();
653         }
654       }
655     }
656   }
657   return SelectionModel(pos, CURSOR_FORWARD);
658 }
659
660 Range RenderTextWin::GetGlyphBounds(size_t index) {
661   const size_t run_index =
662       GetRunContainingCaret(SelectionModel(index, CURSOR_FORWARD));
663   // Return edge bounds if the index is invalid or beyond the layout text size.
664   if (run_index >= runs_.size())
665     return Range(string_width_);
666   internal::TextRun* run = runs_[run_index];
667   const size_t layout_index = TextIndexToLayoutIndex(index);
668   return Range(GetGlyphXBoundary(run, layout_index, false),
669                GetGlyphXBoundary(run, layout_index, true));
670 }
671
672 std::vector<Rect> RenderTextWin::GetSubstringBounds(const Range& range) {
673   DCHECK(!needs_layout_);
674   DCHECK(Range(0, text().length()).Contains(range));
675   Range layout_range(TextIndexToLayoutIndex(range.start()),
676                      TextIndexToLayoutIndex(range.end()));
677   DCHECK(Range(0, GetLayoutText().length()).Contains(layout_range));
678
679   std::vector<Rect> rects;
680   if (layout_range.is_empty())
681     return rects;
682   std::vector<Range> bounds;
683
684   // Add a Range for each run/selection intersection.
685   // TODO(msw): The bounds should probably not always be leading the range ends.
686   for (size_t i = 0; i < runs_.size(); ++i) {
687     const internal::TextRun* run = runs_[visual_to_logical_[i]];
688     Range intersection = run->range.Intersect(layout_range);
689     if (intersection.IsValid()) {
690       DCHECK(!intersection.is_reversed());
691       Range range_x(GetGlyphXBoundary(run, intersection.start(), false),
692                     GetGlyphXBoundary(run, intersection.end(), false));
693       if (range_x.is_empty())
694         continue;
695       range_x = Range(range_x.GetMin(), range_x.GetMax());
696       // Union this with the last range if they're adjacent.
697       DCHECK(bounds.empty() || bounds.back().GetMax() <= range_x.GetMin());
698       if (!bounds.empty() && bounds.back().GetMax() == range_x.GetMin()) {
699         range_x = Range(bounds.back().GetMin(), range_x.GetMax());
700         bounds.pop_back();
701       }
702       bounds.push_back(range_x);
703     }
704   }
705   for (size_t i = 0; i < bounds.size(); ++i) {
706     std::vector<Rect> current_rects = TextBoundsToViewBounds(bounds[i]);
707     rects.insert(rects.end(), current_rects.begin(), current_rects.end());
708   }
709   return rects;
710 }
711
712 size_t RenderTextWin::TextIndexToLayoutIndex(size_t index) const {
713   DCHECK_LE(index, text().length());
714   ptrdiff_t i = obscured() ? UTF16IndexToOffset(text(), 0, index) : index;
715   CHECK_GE(i, 0);
716   // Clamp layout indices to the length of the text actually used for layout.
717   return std::min<size_t>(GetLayoutText().length(), i);
718 }
719
720 size_t RenderTextWin::LayoutIndexToTextIndex(size_t index) const {
721   if (!obscured())
722     return index;
723
724   DCHECK_LE(index, GetLayoutText().length());
725   const size_t text_index = UTF16OffsetToIndex(text(), 0, index);
726   DCHECK_LE(text_index, text().length());
727   return text_index;
728 }
729
730 bool RenderTextWin::IsValidCursorIndex(size_t index) {
731   if (index == 0 || index == text().length())
732     return true;
733   if (!IsValidLogicalIndex(index))
734     return false;
735   EnsureLayout();
736   // Disallow indices amid multi-character graphemes by checking glyph bounds.
737   // These characters are not surrogate-pairs, but may yield a single glyph:
738   //   \x0915\x093f - (ki) - one of many Devanagari biconsonantal conjuncts.
739   //   \x0e08\x0e33 - (cho chan + sara am) - a Thai consonant and vowel pair.
740   return GetGlyphBounds(index) != GetGlyphBounds(index - 1);
741 }
742
743 void RenderTextWin::ResetLayout() {
744   // Layout is performed lazily as needed for drawing/metrics.
745   needs_layout_ = true;
746 }
747
748 void RenderTextWin::EnsureLayout() {
749   if (needs_layout_) {
750     // TODO(msw): Skip complex processing if ScriptIsComplex returns false.
751     ItemizeLogicalText();
752     if (!runs_.empty())
753       LayoutVisualText();
754     needs_layout_ = false;
755     std::vector<internal::Line> lines;
756     set_lines(&lines);
757   }
758
759   // Compute lines if they're not valid. This is separate from the layout steps
760   // above to avoid text layout and shaping when we resize |display_rect_|.
761   if (lines().empty()) {
762     DCHECK(!needs_layout_);
763     std::vector<internal::Line> lines;
764     internal::LineBreaker line_breaker(display_rect().width() - 1,
765                                        font_list().GetBaseline(),
766                                        font_list().GetHeight(), multiline(),
767                                        GetLayoutText().c_str(),
768                                        multiline() ? &GetLineBreaks() : NULL,
769                                        runs_);
770     for (size_t i = 0; i < runs_.size(); ++i)
771       line_breaker.AddRun(visual_to_logical_[i]);
772     line_breaker.Finalize(&lines, &multiline_string_size_);
773     DCHECK(!lines.empty());
774 #ifndef NDEBUG
775     CheckLineIntegrity(lines, runs_);
776 #endif
777     set_lines(&lines);
778   }
779 }
780
781 void RenderTextWin::DrawVisualText(Canvas* canvas) {
782   DCHECK(!needs_layout_);
783   DCHECK(!lines().empty());
784
785   std::vector<SkPoint> pos;
786
787   internal::SkiaTextRenderer renderer(canvas);
788   ApplyFadeEffects(&renderer);
789   ApplyTextShadows(&renderer);
790
791   bool smoothing_enabled;
792   bool cleartype_enabled;
793   GetCachedFontSmoothingSettings(&smoothing_enabled, &cleartype_enabled);
794   // Note that |cleartype_enabled| corresponds to Skia's |enable_lcd_text|.
795   renderer.SetFontSmoothingSettings(
796       smoothing_enabled, cleartype_enabled && !background_is_transparent(),
797       smoothing_enabled /* subpixel_positioning */);
798
799   ApplyCompositionAndSelectionStyles();
800
801   for (size_t i = 0; i < lines().size(); ++i) {
802     const internal::Line& line = lines()[i];
803     const Vector2d line_offset = GetLineOffset(i);
804
805     // Skip painting empty lines or lines outside the display rect area.
806     if (!display_rect().Intersects(Rect(PointAtOffsetFromOrigin(line_offset),
807                                         line.size)))
808       continue;
809
810     const Vector2d text_offset = line_offset + Vector2d(0, line.baseline);
811     int preceding_segment_widths = 0;
812
813     for (size_t j = 0; j < line.segments.size(); ++j) {
814       const internal::LineSegment* segment = &line.segments[j];
815       const int segment_width = segment->x_range.length();
816       const internal::TextRun* run = runs_[segment->run];
817       DCHECK(!segment->char_range.is_empty());
818       DCHECK(run->range.Contains(segment->char_range));
819       Range glyph_range = CharRangeToGlyphRange(*run, segment->char_range);
820       DCHECK(!glyph_range.is_empty());
821       // Skip painting segments outside the display rect area.
822       if (!multiline()) {
823         const Rect segment_bounds(PointAtOffsetFromOrigin(line_offset) +
824                                       Vector2d(preceding_segment_widths, 0),
825                                   Size(segment_width, line.size.height()));
826         if (!display_rect().Intersects(segment_bounds)) {
827           preceding_segment_widths += segment_width;
828           continue;
829         }
830       }
831
832       // |pos| contains the positions of glyphs. An extra terminal |pos| entry
833       // is added to simplify width calculations.
834       int segment_x = preceding_segment_widths;
835       pos.resize(glyph_range.length() + 1);
836       for (size_t k = glyph_range.start(); k < glyph_range.end(); ++k) {
837         pos[k - glyph_range.start()].set(
838             SkIntToScalar(text_offset.x() + run->offsets[k].du + segment_x),
839             SkIntToScalar(text_offset.y() - run->offsets[k].dv));
840         segment_x += run->advance_widths[k];
841       }
842       pos.back().set(SkIntToScalar(text_offset.x() + segment_x),
843                      SkIntToScalar(text_offset.y()));
844
845       renderer.SetTextSize(run->font.GetFontSize());
846       renderer.SetFontFamilyWithStyle(run->font.GetFontName(), run->font_style);
847
848       for (BreakList<SkColor>::const_iterator it =
849                colors().GetBreak(segment->char_range.start());
850            it != colors().breaks().end() &&
851                it->first < segment->char_range.end();
852            ++it) {
853         const Range intersection =
854             colors().GetRange(it).Intersect(segment->char_range);
855         const Range colored_glyphs = CharRangeToGlyphRange(*run, intersection);
856         // The range may be empty if a portion of a multi-character grapheme is
857         // selected, yielding two colors for a single glyph. For now, this just
858         // paints the glyph with a single style, but it should paint it twice,
859         // clipped according to selection bounds. See http://crbug.com/366786
860         if (colored_glyphs.is_empty())
861           continue;
862         DCHECK(glyph_range.Contains(colored_glyphs));
863         const SkPoint& start_pos =
864             pos[colored_glyphs.start() - glyph_range.start()];
865         const SkPoint& end_pos =
866             pos[colored_glyphs.end() - glyph_range.start()];
867
868         renderer.SetForegroundColor(it->second);
869         renderer.DrawPosText(&start_pos, &run->glyphs[colored_glyphs.start()],
870                              colored_glyphs.length());
871         renderer.DrawDecorations(start_pos.x(), text_offset.y(),
872                                  SkScalarCeilToInt(end_pos.x() - start_pos.x()),
873                                  run->underline, run->strike,
874                                  run->diagonal_strike);
875       }
876
877       preceding_segment_widths += segment_width;
878     }
879
880     renderer.EndDiagonalStrike();
881   }
882
883   UndoCompositionAndSelectionStyles();
884 }
885
886 void RenderTextWin::ItemizeLogicalText() {
887   runs_.clear();
888   string_width_ = 0;
889   multiline_string_size_ = Size();
890
891   // Set Uniscribe's base text direction.
892   script_state_.uBidiLevel =
893       (GetTextDirection() == base::i18n::RIGHT_TO_LEFT) ? 1 : 0;
894
895   const base::string16& layout_text = GetLayoutText();
896   if (layout_text.empty())
897     return;
898
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);
913   }
914   DCHECK(SUCCEEDED(hr));
915   if (!SUCCEEDED(hr) || script_items_count <= 0)
916     return;
917
918   // Temporarily apply composition underlines and selection colors.
919   ApplyCompositionAndSelectionStyles();
920
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;
940
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()));
945
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))
950         --run_break;
951     }
952
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,
960                                          run_length);
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();
968           break;
969         }
970       }
971     }
972
973     DCHECK(IsValidCodePointIndex(layout_text, run_break));
974
975     style.UpdatePosition(LayoutIndexToTextIndex(run_break));
976     if (script_item_break == run_break)
977       script_item++;
978     run->range.set_end(run_break);
979     runs_.push_back(run);
980   }
981
982   // Undo the temporarily applied composition underlines and selection colors.
983   UndoCompositionAndSelectionStyles();
984 }
985
986 void RenderTextWin::LayoutVisualText() {
987   DCHECK(!runs_.empty());
988
989   if (!cached_hdc_)
990     cached_hdc_ = CreateCompatibleDC(NULL);
991
992   HRESULT hr = E_FAIL;
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];
1002     LayoutTextRun(run);
1003
1004     ascent = std::max(ascent, run->font.GetBaseline());
1005     descent = std::max(descent,
1006                        run->font.GetHeight() - run->font.GetBaseline());
1007
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_,
1012                        &run->script_cache,
1013                        run->glyphs.get(),
1014                        run->glyph_count,
1015                        run->visible_attributes.get(),
1016                        &(run->script_analysis),
1017                        run->advance_widths.get(),
1018                        run->offsets.get(),
1019                        &(run->abc_widths));
1020       DCHECK(SUCCEEDED(hr));
1021     }
1022   }
1023
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;
1028
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(),
1033                     levels.get(),
1034                     visual_to_logical_.get(),
1035                     logical_to_visual_.get());
1036   DCHECK(SUCCEEDED(hr));
1037
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;
1046   }
1047   string_width_ = preceding_run_widths;
1048 }
1049
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;
1062   Font current_font;
1063
1064   run->logical_clusters.reset(new WORD[run_length]);
1065   while (fonts.NextFont(&current_font)) {
1066     HRESULT hr = ShapeTextRunWithFont(run, current_font);
1067
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;
1079       }
1080       glyphs_missing = (missing_count != 0);
1081     } else {
1082       NOTREACHED() << hr;
1083     }
1084
1085     // Use the font if it had glyphs for all characters.
1086     if (!glyphs_missing) {
1087       // Save the successful fallback font that was chosen.
1088       if (tried_fallback)
1089         successful_substitute_fonts_[original_font.GetFontName()] = run->font;
1090       return;
1091     }
1092
1093     // First, try the cached font from previous runs, if any.
1094     if (!tried_cached_font) {
1095       tried_cached_font = true;
1096
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);
1101         continue;
1102       }
1103     }
1104
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;
1110
1111       Font fallback_font;
1112       if (ChooseFallbackFont(cached_hdc_, run->font, run_text, run_length,
1113                              &fallback_font)) {
1114         fonts.SetNextFont(fallback_font);
1115         continue;
1116       }
1117     }
1118   }
1119
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);
1125     return;
1126   }
1127
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
1130   // garbage values.
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());
1135
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,
1141                                        &properties);
1142
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;
1148   if (hr == S_OK) {
1149     missing_glyph = properties.wgDefault;
1150     space_glyph = properties.wgBlank;
1151   }
1152
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;
1163   }
1164
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;
1170 }
1171
1172 HRESULT RenderTextWin::ShapeTextRunWithFont(internal::TextRun* run,
1173                                             const Font& font) {
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();
1179     run->font = font;
1180     DeriveFontIfNecessary(font_size, font_height, run->font_style, &run->font);
1181     ScriptFreeCache(&run->script_cache);
1182   }
1183
1184   // Select the font desired for glyph generation.
1185   SelectObject(cached_hdc_, run->font.GetNativeFont());
1186
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(),
1200                      &run->glyph_count);
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));
1203   }
1204   return hr;
1205 }
1206
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);
1213
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);
1219
1220     if (run->glyphs[glyph_index] == properties.wgDefault)
1221       continue;
1222
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])) {
1231       continue;
1232     }
1233
1234     ++chars_not_missing_glyphs;
1235   }
1236
1237   DCHECK_LE(chars_not_missing_glyphs, static_cast<int>(run->range.length()));
1238   return run->range.length() - chars_not_missing_glyphs;
1239 }
1240
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))
1247       return run;
1248   return runs_.size();
1249 }
1250
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))
1257       return run;
1258   }
1259   return runs_.size();
1260 }
1261
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);
1267 }
1268
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);
1274 }
1275
1276 RenderText* RenderText::CreateInstance() {
1277   return new RenderTextWin;
1278 }
1279
1280 }  // namespace gfx