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(UTF16ToUTF8(log_font.lfFaceName), font.GetFontSize()); 90 found_fallback = true; 91 } 92 } 93 DeleteEnhMetaFile(meta_file); 94 95 return found_fallback; 96 } 97 98 // Changes |font| to have the specified |font_size| (or |font_height| on Windows 99 // XP) and |font_style| if it is not the case already. Only considers bold and 100 // italic styles, since the underlined style has no effect on glyph shaping. 101 void DeriveFontIfNecessary(int font_size, 102 int font_height, 103 int font_style, 104 Font* font) { 105 const int kStyleMask = (Font::BOLD | Font::ITALIC); 106 const int target_style = (font_style & kStyleMask); 107 108 // On Windows XP, the font must be resized using |font_height| instead of 109 // |font_size| to match GDI behavior. 110 if (base::win::GetVersion() < base::win::VERSION_VISTA) { 111 PlatformFontWin* platform_font = 112 static_cast<PlatformFontWin*>(font->platform_font()); 113 *font = platform_font->DeriveFontWithHeight(font_height, target_style); 114 return; 115 } 116 117 const int current_style = (font->GetStyle() & kStyleMask); 118 const int current_size = font->GetFontSize(); 119 if (current_style != target_style || current_size != font_size) 120 *font = font->DeriveFont(font_size - current_size, target_style); 121 } 122 123 // Returns true if |c| is a Unicode BiDi control character. 124 bool IsUnicodeBidiControlCharacter(char16 c) { 125 return c == base::i18n::kRightToLeftMark || 126 c == base::i18n::kLeftToRightMark || 127 c == base::i18n::kLeftToRightEmbeddingMark || 128 c == base::i18n::kRightToLeftEmbeddingMark || 129 c == base::i18n::kPopDirectionalFormatting || 130 c == base::i18n::kLeftToRightOverride || 131 c == base::i18n::kRightToLeftOverride; 132 } 133 134 // Returns the corresponding glyph range of the given character range. 135 // |range| is in text-space (0 corresponds to |GetLayoutText()[0]|). 136 // Returned value is in run-space (0 corresponds to the first glyph in the run). 137 Range CharRangeToGlyphRange(const internal::TextRun& run, 138 const Range& range) { 139 DCHECK(run.range.Contains(range)); 140 DCHECK(!range.is_reversed()); 141 DCHECK(!range.is_empty()); 142 const Range run_range(range.start() - run.range.start(), 143 range.end() - run.range.start()); 144 Range result; 145 if (run.script_analysis.fRTL) { 146 result = Range(run.logical_clusters[run_range.end() - 1], 147 run_range.start() > 0 ? run.logical_clusters[run_range.start() - 1] 148 : run.glyph_count); 149 } else { 150 result = Range(run.logical_clusters[run_range.start()], 151 run_range.end() < run.range.length() ? 152 run.logical_clusters[run_range.end()] : run.glyph_count); 153 } 154 DCHECK(!result.is_reversed()); 155 DCHECK(Range(0, run.glyph_count).Contains(result)); 156 return result; 157 } 158 159 // Starting from |start_char|, finds a suitable line break position at or before 160 // |available_width| using word break info from |breaks|. If |empty_line| is 161 // true, this function will not roll back to |start_char| and |*next_char| will 162 // be greater than |start_char| (to avoid constructing empty lines). Returns 163 // whether to skip the line before |*next_char|. 164 // TODO(ckocagil): Do not break ligatures and diacritics. 165 // TextRun::logical_clusters might help. 166 // TODO(ckocagil): We might have to reshape after breaking at ligatures. 167 // See whether resolving the TODO above resolves this too. 168 // TODO(ckocagil): Do not reserve width for whitespace at the end of lines. 169 bool BreakRunAtWidth(const wchar_t* text, 170 const internal::TextRun& run, 171 const BreakList<size_t>& breaks, 172 size_t start_char, 173 int available_width, 174 bool empty_line, 175 int* width, 176 size_t* next_char) { 177 DCHECK(run.range.Contains(Range(start_char, start_char + 1))); 178 BreakList<size_t>::const_iterator word = breaks.GetBreak(start_char); 179 BreakList<size_t>::const_iterator next_word = word + 1; 180 // Width from |std::max(word->first, start_char)| to the current character. 181 int word_width = 0; 182 *width = 0; 183 184 for (size_t i = start_char; i < run.range.end(); ++i) { 185 if (U16_IS_SINGLE(text[i]) && text[i] == L'\n') { 186 *next_char = i + 1; 187 return true; 188 } 189 190 // |word| holds the word boundary at or before |i|, and |next_word| holds 191 // the word boundary right after |i|. Advance both |word| and |next_word| 192 // when |i| reaches |next_word|. 193 if (next_word != breaks.breaks().end() && i >= next_word->first) { 194 word = next_word++; 195 word_width = 0; 196 } 197 198 Range glyph_range = CharRangeToGlyphRange(run, Range(i, i + 1)); 199 int char_width = 0; 200 for (size_t j = glyph_range.start(); j < glyph_range.end(); ++j) 201 char_width += run.advance_widths[j]; 202 203 *width += char_width; 204 word_width += char_width; 205 206 if (*width > available_width) { 207 if (!empty_line || word_width < *width) { 208 // Roll back one word. 209 *width -= word_width; 210 *next_char = std::max(word->first, start_char); 211 } else if (char_width < *width) { 212 // Roll back one character. 213 *width -= char_width; 214 *next_char = i; 215 } else { 216 // Continue from the next character. 217 *next_char = i + 1; 218 } 219 220 return true; 221 } 222 } 223 224 *next_char = run.range.end(); 225 return false; 226 } 227 228 // For segments in the same run, checks the continuity and order of |x_range| 229 // and |char_range| fields. 230 void CheckLineIntegrity(const std::vector<internal::Line>& lines, 231 const ScopedVector<internal::TextRun>& runs) { 232 size_t previous_segment_line = 0; 233 const internal::LineSegment* previous_segment = NULL; 234 235 for (size_t i = 0; i < lines.size(); ++i) { 236 for (size_t j = 0; j < lines[i].segments.size(); ++j) { 237 const internal::LineSegment* segment = &lines[i].segments[j]; 238 internal::TextRun* run = runs[segment->run]; 239 240 if (!previous_segment) { 241 previous_segment = segment; 242 } else if (runs[previous_segment->run] != run) { 243 previous_segment = NULL; 244 } else { 245 DCHECK_EQ(previous_segment->char_range.end(), 246 segment->char_range.start()); 247 if (!run->script_analysis.fRTL) { 248 DCHECK_EQ(previous_segment->x_range.end(), segment->x_range.start()); 249 } else { 250 DCHECK_EQ(segment->x_range.end(), previous_segment->x_range.start()); 251 } 252 253 previous_segment = segment; 254 previous_segment_line = i; 255 } 256 } 257 } 258 } 259 260 // Returns true if characters of |block_code| may trigger font fallback. 261 bool IsUnusualBlockCode(const UBlockCode block_code) { 262 return block_code == UBLOCK_GEOMETRIC_SHAPES || 263 block_code == UBLOCK_MISCELLANEOUS_SYMBOLS; 264 } 265 266 } // namespace 267 268 namespace internal { 269 270 TextRun::TextRun() 271 : font_style(0), 272 strike(false), 273 diagonal_strike(false), 274 underline(false), 275 width(0), 276 preceding_run_widths(0), 277 glyph_count(0), 278 script_cache(NULL) { 279 memset(&script_analysis, 0, sizeof(script_analysis)); 280 memset(&abc_widths, 0, sizeof(abc_widths)); 281 } 282 283 TextRun::~TextRun() { 284 ScriptFreeCache(&script_cache); 285 } 286 287 // Returns the X coordinate of the leading or |trailing| edge of the glyph 288 // starting at |index|, relative to the left of the text (not the view). 289 int GetGlyphXBoundary(const internal::TextRun* run, 290 size_t index, 291 bool trailing) { 292 DCHECK_GE(index, run->range.start()); 293 DCHECK_LT(index, run->range.end() + (trailing ? 0 : 1)); 294 int x = 0; 295 HRESULT hr = ScriptCPtoX( 296 index - run->range.start(), 297 trailing, 298 run->range.length(), 299 run->glyph_count, 300 run->logical_clusters.get(), 301 run->visible_attributes.get(), 302 run->advance_widths.get(), 303 &run->script_analysis, 304 &x); 305 DCHECK(SUCCEEDED(hr)); 306 return run->preceding_run_widths + x; 307 } 308 309 // Internal class to generate Line structures. If |multiline| is true, the text 310 // is broken into lines at |words| boundaries such that each line is no longer 311 // than |max_width|. If |multiline| is false, only outputs a single Line from 312 // the given runs. |min_baseline| and |min_height| are the minimum baseline and 313 // height for each line. 314 // TODO(ckocagil): Expose the interface of this class in the header and test 315 // this class directly. 316 class LineBreaker { 317 public: 318 LineBreaker(int max_width, 319 int min_baseline, 320 int min_height, 321 bool multiline, 322 const wchar_t* text, 323 const BreakList<size_t>* words, 324 const ScopedVector<TextRun>& runs) 325 : max_width_(max_width), 326 min_baseline_(min_baseline), 327 min_height_(min_height), 328 multiline_(multiline), 329 text_(text), 330 words_(words), 331 runs_(runs), 332 text_x_(0), 333 line_x_(0), 334 line_ascent_(0), 335 line_descent_(0) { 336 AdvanceLine(); 337 } 338 339 // Breaks the run at given |run_index| into Line structs. 340 void AddRun(int run_index) { 341 const TextRun* run = runs_[run_index]; 342 bool run_fits = !multiline_; 343 if (multiline_ && line_x_ + run->width <= max_width_) { 344 DCHECK(!run->range.is_empty()); 345 const wchar_t first_char = text_[run->range.start()]; 346 // Uniscribe always puts newline characters in their own runs. 347 if (!U16_IS_SINGLE(first_char) || first_char != L'\n') 348 run_fits = true; 349 } 350 351 if (!run_fits) 352 BreakRun(run_index); 353 else 354 AddSegment(run_index, run->range, run->width); 355 } 356 357 // Finishes line breaking and outputs the results. Can be called at most once. 358 void Finalize(std::vector<Line>* lines, Size* size) { 359 DCHECK(!lines_.empty()); 360 // Add an empty line to finish the line size calculation and remove it. 361 AdvanceLine(); 362 lines_.pop_back(); 363 *size = total_size_; 364 lines->swap(lines_); 365 } 366 367 private: 368 // A (line index, segment index) pair that specifies a segment in |lines_|. 369 typedef std::pair<size_t, size_t> SegmentHandle; 370 371 LineSegment* SegmentFromHandle(const SegmentHandle& handle) { 372 return &lines_[handle.first].segments[handle.second]; 373 } 374 375 // Breaks a run into segments that fit in the last line in |lines_| and adds 376 // them. Adds a new Line to the back of |lines_| whenever a new segment can't 377 // be added without the Line's width exceeding |max_width_|. 378 void BreakRun(int run_index) { 379 DCHECK(words_); 380 const TextRun* const run = runs_[run_index]; 381 int width = 0; 382 size_t next_char = run->range.start(); 383 384 // Break the run until it fits the current line. 385 while (next_char < run->range.end()) { 386 const size_t current_char = next_char; 387 const bool skip_line = BreakRunAtWidth(text_, *run, *words_, current_char, 388 max_width_ - line_x_, line_x_ == 0, &width, &next_char); 389 AddSegment(run_index, Range(current_char, next_char), width); 390 if (skip_line) 391 AdvanceLine(); 392 } 393 } 394 395 // RTL runs are broken in logical order but displayed in visual order. To find 396 // the text-space coordinate (where it would fall in a single-line text) 397 // |x_range| of RTL segments, segment widths are applied in reverse order. 398 // e.g. {[5, 10], [10, 40]} will become {[35, 40], [5, 35]}. 399 void UpdateRTLSegmentRanges() { 400 if (rtl_segments_.empty()) 401 return; 402 int x = SegmentFromHandle(rtl_segments_[0])->x_range.start(); 403 for (size_t i = rtl_segments_.size(); i > 0; --i) { 404 LineSegment* segment = SegmentFromHandle(rtl_segments_[i - 1]); 405 const size_t segment_width = segment->x_range.length(); 406 segment->x_range = Range(x, x + segment_width); 407 x += segment_width; 408 } 409 rtl_segments_.clear(); 410 } 411 412 // Finishes the size calculations of the last Line in |lines_|. Adds a new 413 // Line to the back of |lines_|. 414 void AdvanceLine() { 415 if (!lines_.empty()) { 416 Line* line = &lines_.back(); 417 // TODO(ckocagil): Determine optimal multiline height behavior. 418 if (line_ascent_ + line_descent_ == 0) { 419 line_ascent_ = min_baseline_; 420 line_descent_ = min_height_ - min_baseline_; 421 } 422 // Set the single-line mode Line's metrics to be at least 423 // |RenderText::font_list()| to not break the current single-line code. 424 line_ascent_ = std::max(line_ascent_, min_baseline_); 425 line_descent_ = std::max(line_descent_, min_height_ - min_baseline_); 426 427 line->baseline = line_ascent_; 428 line->size.set_height(line_ascent_ + line_descent_); 429 line->preceding_heights = total_size_.height(); 430 total_size_.set_height(total_size_.height() + line->size.height()); 431 total_size_.set_width(std::max(total_size_.width(), line->size.width())); 432 } 433 line_x_ = 0; 434 line_ascent_ = 0; 435 line_descent_ = 0; 436 lines_.push_back(Line()); 437 } 438 439 // Adds a new segment with the given properties to |lines_.back()|. 440 void AddSegment(int run_index, Range char_range, int width) { 441 if (char_range.is_empty()) { 442 DCHECK_EQ(width, 0); 443 return; 444 } 445 const TextRun* run = runs_[run_index]; 446 line_ascent_ = std::max(line_ascent_, run->font.GetBaseline()); 447 line_descent_ = std::max(line_descent_, 448 run->font.GetHeight() - run->font.GetBaseline()); 449 450 LineSegment segment; 451 segment.run = run_index; 452 segment.char_range = char_range; 453 segment.x_range = Range(text_x_, text_x_ + width); 454 455 Line* line = &lines_.back(); 456 line->segments.push_back(segment); 457 line->size.set_width(line->size.width() + segment.x_range.length()); 458 if (run->script_analysis.fRTL) { 459 rtl_segments_.push_back(SegmentHandle(lines_.size() - 1, 460 line->segments.size() - 1)); 461 // If this is the last segment of an RTL run, reprocess the text-space x 462 // ranges of all segments from the run. 463 if (char_range.end() == run->range.end()) 464 UpdateRTLSegmentRanges(); 465 } 466 text_x_ += width; 467 line_x_ += width; 468 } 469 470 const int max_width_; 471 const int min_baseline_; 472 const int min_height_; 473 const bool multiline_; 474 const wchar_t* text_; 475 const BreakList<size_t>* const words_; 476 const ScopedVector<TextRun>& runs_; 477 478 // Stores the resulting lines. 479 std::vector<Line> lines_; 480 481 // Text space and line space x coordinates of the next segment to be added. 482 int text_x_; 483 int line_x_; 484 485 // Size of the multiline text, not including the currently processed line. 486 Size total_size_; 487 488 // Ascent and descent values of the current line, |lines_.back()|. 489 int line_ascent_; 490 int line_descent_; 491 492 // The current RTL run segments, to be applied by |UpdateRTLSegmentRanges()|. 493 std::vector<SegmentHandle> rtl_segments_; 494 495 DISALLOW_COPY_AND_ASSIGN(LineBreaker); 496 }; 497 498 } // namespace internal 499 500 // static 501 HDC RenderTextWin::cached_hdc_ = NULL; 502 503 // static 504 std::map<std::string, Font> RenderTextWin::successful_substitute_fonts_; 505 506 RenderTextWin::RenderTextWin() 507 : RenderText(), 508 needs_layout_(false) { 509 set_truncate_length(kMaxUniscribeTextLength); 510 511 memset(&script_control_, 0, sizeof(script_control_)); 512 memset(&script_state_, 0, sizeof(script_state_)); 513 514 MoveCursorTo(EdgeSelectionModel(CURSOR_LEFT)); 515 } 516 517 RenderTextWin::~RenderTextWin() { 518 } 519 520 Size RenderTextWin::GetStringSize() { 521 EnsureLayout(); 522 return multiline_string_size_; 523 } 524 525 SelectionModel RenderTextWin::FindCursorPosition(const Point& point) { 526 if (text().empty()) 527 return SelectionModel(); 528 529 EnsureLayout(); 530 // Find the run that contains the point and adjust the argument location. 531 int x = ToTextPoint(point).x(); 532 size_t run_index = GetRunContainingXCoord(x); 533 if (run_index >= runs_.size()) 534 return EdgeSelectionModel((x < 0) ? CURSOR_LEFT : CURSOR_RIGHT); 535 internal::TextRun* run = runs_[run_index]; 536 537 int position = 0, trailing = 0; 538 HRESULT hr = ScriptXtoCP(x - run->preceding_run_widths, 539 run->range.length(), 540 run->glyph_count, 541 run->logical_clusters.get(), 542 run->visible_attributes.get(), 543 run->advance_widths.get(), 544 &(run->script_analysis), 545 &position, 546 &trailing); 547 DCHECK(SUCCEEDED(hr)); 548 DCHECK_GE(trailing, 0); 549 position += run->range.start(); 550 const size_t cursor = LayoutIndexToTextIndex(position + trailing); 551 DCHECK_LE(cursor, text().length()); 552 return SelectionModel(cursor, trailing ? CURSOR_BACKWARD : CURSOR_FORWARD); 553 } 554 555 std::vector<RenderText::FontSpan> RenderTextWin::GetFontSpansForTesting() { 556 EnsureLayout(); 557 558 std::vector<RenderText::FontSpan> spans; 559 for (size_t i = 0; i < runs_.size(); ++i) { 560 spans.push_back(RenderText::FontSpan(runs_[i]->font, 561 Range(LayoutIndexToTextIndex(runs_[i]->range.start()), 562 LayoutIndexToTextIndex(runs_[i]->range.end())))); 563 } 564 565 return spans; 566 } 567 568 int RenderTextWin::GetLayoutTextBaseline() { 569 EnsureLayout(); 570 return lines()[0].baseline; 571 } 572 573 SelectionModel RenderTextWin::AdjacentCharSelectionModel( 574 const SelectionModel& selection, 575 VisualCursorDirection direction) { 576 DCHECK(!needs_layout_); 577 internal::TextRun* run; 578 size_t run_index = GetRunContainingCaret(selection); 579 if (run_index >= runs_.size()) { 580 // The cursor is not in any run: we're at the visual and logical edge. 581 SelectionModel edge = EdgeSelectionModel(direction); 582 if (edge.caret_pos() == selection.caret_pos()) 583 return edge; 584 int visual_index = (direction == CURSOR_RIGHT) ? 0 : runs_.size() - 1; 585 run = runs_[visual_to_logical_[visual_index]]; 586 } else { 587 // If the cursor is moving within the current run, just move it by one 588 // grapheme in the appropriate direction. 589 run = runs_[run_index]; 590 size_t caret = selection.caret_pos(); 591 bool forward_motion = 592 run->script_analysis.fRTL == (direction == CURSOR_LEFT); 593 if (forward_motion) { 594 if (caret < LayoutIndexToTextIndex(run->range.end())) { 595 caret = IndexOfAdjacentGrapheme(caret, CURSOR_FORWARD); 596 return SelectionModel(caret, CURSOR_BACKWARD); 597 } 598 } else { 599 if (caret > LayoutIndexToTextIndex(run->range.start())) { 600 caret = IndexOfAdjacentGrapheme(caret, CURSOR_BACKWARD); 601 return SelectionModel(caret, CURSOR_FORWARD); 602 } 603 } 604 // The cursor is at the edge of a run; move to the visually adjacent run. 605 int visual_index = logical_to_visual_[run_index]; 606 visual_index += (direction == CURSOR_LEFT) ? -1 : 1; 607 if (visual_index < 0 || visual_index >= static_cast<int>(runs_.size())) 608 return EdgeSelectionModel(direction); 609 run = runs_[visual_to_logical_[visual_index]]; 610 } 611 bool forward_motion = run->script_analysis.fRTL == (direction == CURSOR_LEFT); 612 return forward_motion ? FirstSelectionModelInsideRun(run) : 613 LastSelectionModelInsideRun(run); 614 } 615 616 // TODO(msw): Implement word breaking for Windows. 617 SelectionModel RenderTextWin::AdjacentWordSelectionModel( 618 const SelectionModel& selection, 619 VisualCursorDirection direction) { 620 if (obscured()) 621 return EdgeSelectionModel(direction); 622 623 base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD); 624 bool success = iter.Init(); 625 DCHECK(success); 626 if (!success) 627 return selection; 628 629 size_t pos; 630 if (direction == CURSOR_RIGHT) { 631 pos = std::min(selection.caret_pos() + 1, text().length()); 632 while (iter.Advance()) { 633 pos = iter.pos(); 634 if (iter.IsWord() && pos > selection.caret_pos()) 635 break; 636 } 637 } else { // direction == CURSOR_LEFT 638 // Notes: We always iterate words from the beginning. 639 // This is probably fast enough for our usage, but we may 640 // want to modify WordIterator so that it can start from the 641 // middle of string and advance backwards. 642 pos = std::max<int>(selection.caret_pos() - 1, 0); 643 while (iter.Advance()) { 644 if (iter.IsWord()) { 645 size_t begin = iter.pos() - iter.GetString().length(); 646 if (begin == selection.caret_pos()) { 647 // The cursor is at the beginning of a word. 648 // Move to previous word. 649 break; 650 } else if (iter.pos() >= selection.caret_pos()) { 651 // The cursor is in the middle or at the end of a word. 652 // Move to the top of current word. 653 pos = begin; 654 break; 655 } else { 656 pos = iter.pos() - iter.GetString().length(); 657 } 658 } 659 } 660 } 661 return SelectionModel(pos, CURSOR_FORWARD); 662 } 663 664 Range RenderTextWin::GetGlyphBounds(size_t index) { 665 const size_t run_index = 666 GetRunContainingCaret(SelectionModel(index, CURSOR_FORWARD)); 667 // Return edge bounds if the index is invalid or beyond the layout text size. 668 if (run_index >= runs_.size()) 669 return Range(string_width_); 670 internal::TextRun* run = runs_[run_index]; 671 const size_t layout_index = TextIndexToLayoutIndex(index); 672 return Range(GetGlyphXBoundary(run, layout_index, false), 673 GetGlyphXBoundary(run, layout_index, true)); 674 } 675 676 std::vector<Rect> RenderTextWin::GetSubstringBounds(const Range& range) { 677 DCHECK(!needs_layout_); 678 DCHECK(Range(0, text().length()).Contains(range)); 679 Range layout_range(TextIndexToLayoutIndex(range.start()), 680 TextIndexToLayoutIndex(range.end())); 681 DCHECK(Range(0, GetLayoutText().length()).Contains(layout_range)); 682 683 std::vector<Rect> rects; 684 if (layout_range.is_empty()) 685 return rects; 686 std::vector<Range> bounds; 687 688 // Add a Range for each run/selection intersection. 689 // TODO(msw): The bounds should probably not always be leading the range ends. 690 for (size_t i = 0; i < runs_.size(); ++i) { 691 const internal::TextRun* run = runs_[visual_to_logical_[i]]; 692 Range intersection = run->range.Intersect(layout_range); 693 if (intersection.IsValid()) { 694 DCHECK(!intersection.is_reversed()); 695 Range range_x(GetGlyphXBoundary(run, intersection.start(), false), 696 GetGlyphXBoundary(run, intersection.end(), false)); 697 if (range_x.is_empty()) 698 continue; 699 range_x = Range(range_x.GetMin(), range_x.GetMax()); 700 // Union this with the last range if they're adjacent. 701 DCHECK(bounds.empty() || bounds.back().GetMax() <= range_x.GetMin()); 702 if (!bounds.empty() && bounds.back().GetMax() == range_x.GetMin()) { 703 range_x = Range(bounds.back().GetMin(), range_x.GetMax()); 704 bounds.pop_back(); 705 } 706 bounds.push_back(range_x); 707 } 708 } 709 for (size_t i = 0; i < bounds.size(); ++i) { 710 std::vector<Rect> current_rects = TextBoundsToViewBounds(bounds[i]); 711 rects.insert(rects.end(), current_rects.begin(), current_rects.end()); 712 } 713 return rects; 714 } 715 716 size_t RenderTextWin::TextIndexToLayoutIndex(size_t index) const { 717 DCHECK_LE(index, text().length()); 718 ptrdiff_t i = obscured() ? gfx::UTF16IndexToOffset(text(), 0, index) : index; 719 CHECK_GE(i, 0); 720 // Clamp layout indices to the length of the text actually used for layout. 721 return std::min<size_t>(GetLayoutText().length(), i); 722 } 723 724 size_t RenderTextWin::LayoutIndexToTextIndex(size_t index) const { 725 if (!obscured()) 726 return index; 727 728 DCHECK_LE(index, GetLayoutText().length()); 729 const size_t text_index = gfx::UTF16OffsetToIndex(text(), 0, index); 730 DCHECK_LE(text_index, text().length()); 731 return text_index; 732 } 733 734 bool RenderTextWin::IsCursorablePosition(size_t position) { 735 if (position == 0 || position == text().length()) 736 return true; 737 EnsureLayout(); 738 739 // Check that the index is at a valid code point (not mid-surrgate-pair), 740 // that it is not truncated from layout text (its glyph is shown on screen), 741 // and that its glyph has distinct bounds (not mid-multi-character-grapheme). 742 // An example of a multi-character-grapheme that is not a surrogate-pair is: 743 // \x0915\x093f - (ki) - one of many Devanagari biconsonantal conjuncts. 744 return gfx::IsValidCodePointIndex(text(), position) && 745 position < LayoutIndexToTextIndex(GetLayoutText().length()) && 746 GetGlyphBounds(position) != GetGlyphBounds(position - 1); 747 } 748 749 void RenderTextWin::ResetLayout() { 750 // Layout is performed lazily as needed for drawing/metrics. 751 needs_layout_ = true; 752 } 753 754 void RenderTextWin::EnsureLayout() { 755 if (needs_layout_) { 756 // TODO(msw): Skip complex processing if ScriptIsComplex returns false. 757 ItemizeLogicalText(); 758 if (!runs_.empty()) 759 LayoutVisualText(); 760 needs_layout_ = false; 761 std::vector<internal::Line> lines; 762 set_lines(&lines); 763 } 764 765 // Compute lines if they're not valid. This is separate from the layout steps 766 // above to avoid text layout and shaping when we resize |display_rect_|. 767 if (lines().empty()) { 768 DCHECK(!needs_layout_); 769 std::vector<internal::Line> lines; 770 internal::LineBreaker line_breaker(display_rect().width() - 1, 771 font_list().GetBaseline(), 772 font_list().GetHeight(), multiline(), 773 GetLayoutText().c_str(), 774 multiline() ? &GetLineBreaks() : NULL, 775 runs_); 776 for (size_t i = 0; i < runs_.size(); ++i) 777 line_breaker.AddRun(visual_to_logical_[i]); 778 line_breaker.Finalize(&lines, &multiline_string_size_); 779 DCHECK(!lines.empty()); 780 #ifndef NDEBUG 781 CheckLineIntegrity(lines, runs_); 782 #endif 783 set_lines(&lines); 784 } 785 } 786 787 void RenderTextWin::DrawVisualText(Canvas* canvas) { 788 DCHECK(!needs_layout_); 789 DCHECK(!lines().empty()); 790 791 std::vector<SkPoint> pos; 792 793 internal::SkiaTextRenderer renderer(canvas); 794 ApplyFadeEffects(&renderer); 795 ApplyTextShadows(&renderer); 796 797 bool smoothing_enabled; 798 bool cleartype_enabled; 799 GetCachedFontSmoothingSettings(&smoothing_enabled, &cleartype_enabled); 800 // Note that |cleartype_enabled| corresponds to Skia's |enable_lcd_text|. 801 renderer.SetFontSmoothingSettings( 802 smoothing_enabled, cleartype_enabled && !background_is_transparent()); 803 804 ApplyCompositionAndSelectionStyles(); 805 806 for (size_t i = 0; i < lines().size(); ++i) { 807 const internal::Line& line = lines()[i]; 808 const Vector2d line_offset = GetLineOffset(i); 809 810 // Skip painting empty lines or lines outside the display rect area. 811 if (!display_rect().Intersects(Rect(PointAtOffsetFromOrigin(line_offset), 812 line.size))) 813 continue; 814 815 const Vector2d text_offset = line_offset + Vector2d(0, line.baseline); 816 int preceding_segment_widths = 0; 817 818 for (size_t j = 0; j < line.segments.size(); ++j) { 819 const internal::LineSegment* segment = &line.segments[j]; 820 const int segment_width = segment->x_range.length(); 821 const internal::TextRun* run = runs_[segment->run]; 822 DCHECK(!segment->char_range.is_empty()); 823 DCHECK(run->range.Contains(segment->char_range)); 824 Range glyph_range = CharRangeToGlyphRange(*run, segment->char_range); 825 DCHECK(!glyph_range.is_empty()); 826 // Skip painting segments outside the display rect area. 827 if (!multiline()) { 828 const Rect segment_bounds(PointAtOffsetFromOrigin(line_offset) + 829 Vector2d(preceding_segment_widths, 0), 830 Size(segment_width, line.size.height())); 831 if (!display_rect().Intersects(segment_bounds)) { 832 preceding_segment_widths += segment_width; 833 continue; 834 } 835 } 836 837 // |pos| contains the positions of glyphs. An extra terminal |pos| entry 838 // is added to simplify width calculations. 839 int segment_x = preceding_segment_widths; 840 pos.resize(glyph_range.length() + 1); 841 for (size_t k = glyph_range.start(); k < glyph_range.end(); ++k) { 842 pos[k - glyph_range.start()].set( 843 SkIntToScalar(text_offset.x() + run->offsets[k].du + segment_x), 844 SkIntToScalar(text_offset.y() + run->offsets[k].dv)); 845 segment_x += run->advance_widths[k]; 846 } 847 pos.back().set(SkIntToScalar(text_offset.x() + segment_x), 848 SkIntToScalar(text_offset.y())); 849 850 renderer.SetTextSize(run->font.GetFontSize()); 851 renderer.SetFontFamilyWithStyle(run->font.GetFontName(), run->font_style); 852 853 for (BreakList<SkColor>::const_iterator it = 854 colors().GetBreak(segment->char_range.start()); 855 it != colors().breaks().end() && 856 it->first < segment->char_range.end(); 857 ++it) { 858 const Range intersection = 859 colors().GetRange(it).Intersect(segment->char_range); 860 const Range colored_glyphs = CharRangeToGlyphRange(*run, intersection); 861 DCHECK(glyph_range.Contains(colored_glyphs)); 862 DCHECK(!colored_glyphs.is_empty()); 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 881 UndoCompositionAndSelectionStyles(); 882 } 883 884 void RenderTextWin::ItemizeLogicalText() { 885 runs_.clear(); 886 string_width_ = 0; 887 multiline_string_size_ = Size(); 888 889 // Set Uniscribe's base text direction. 890 script_state_.uBidiLevel = 891 (GetTextDirection() == base::i18n::RIGHT_TO_LEFT) ? 1 : 0; 892 893 const base::string16& layout_text = GetLayoutText(); 894 if (layout_text.empty()) 895 return; 896 897 HRESULT hr = E_OUTOFMEMORY; 898 int script_items_count = 0; 899 std::vector<SCRIPT_ITEM> script_items; 900 const size_t layout_text_length = layout_text.length(); 901 // Ensure that |kMaxRuns| is attempted and the loop terminates afterward. 902 for (size_t runs = kGuessRuns; hr == E_OUTOFMEMORY && runs <= kMaxRuns; 903 runs = std::max(runs + 1, std::min(runs * 2, kMaxRuns))) { 904 // Derive the array of Uniscribe script items from the logical text. 905 // ScriptItemize always adds a terminal array item so that the length of 906 // the last item can be derived from the terminal SCRIPT_ITEM::iCharPos. 907 script_items.resize(runs); 908 hr = ScriptItemize(layout_text.c_str(), layout_text_length, runs - 1, 909 &script_control_, &script_state_, &script_items[0], 910 &script_items_count); 911 } 912 DCHECK(SUCCEEDED(hr)); 913 if (!SUCCEEDED(hr) || script_items_count <= 0) 914 return; 915 916 // Temporarily apply composition underlines and selection colors. 917 ApplyCompositionAndSelectionStyles(); 918 919 // Build the list of runs from the script items and ranged styles. Use an 920 // empty color BreakList to avoid breaking runs at color boundaries. 921 BreakList<SkColor> empty_colors; 922 empty_colors.SetMax(layout_text_length); 923 internal::StyleIterator style(empty_colors, styles()); 924 SCRIPT_ITEM* script_item = &script_items[0]; 925 const size_t max_run_length = kMaxGlyphs / 2; 926 for (size_t run_break = 0; run_break < layout_text_length;) { 927 internal::TextRun* run = new internal::TextRun(); 928 run->range.set_start(run_break); 929 run->font = GetPrimaryFont(); 930 run->font_style = (style.style(BOLD) ? Font::BOLD : 0) | 931 (style.style(ITALIC) ? Font::ITALIC : 0); 932 DeriveFontIfNecessary(run->font.GetFontSize(), run->font.GetHeight(), 933 run->font_style, &run->font); 934 run->strike = style.style(STRIKE); 935 run->diagonal_strike = style.style(DIAGONAL_STRIKE); 936 run->underline = style.style(UNDERLINE); 937 run->script_analysis = script_item->a; 938 939 // Find the next break and advance the iterators as needed. 940 const size_t script_item_break = (script_item + 1)->iCharPos; 941 run_break = std::min(script_item_break, 942 TextIndexToLayoutIndex(style.GetRange().end())); 943 944 // Clamp run lengths to avoid exceeding the maximum supported glyph count. 945 if ((run_break - run->range.start()) > max_run_length) { 946 run_break = run->range.start() + max_run_length; 947 if (!IsValidCodePointIndex(layout_text, run_break)) 948 --run_break; 949 } 950 951 // Break runs adjacent to character substrings in certain code blocks. 952 // This avoids using their fallback fonts for more characters than needed, 953 // in cases like "\x25B6 Media Title", etc. http://crbug.com/278913 954 if (run_break > run->range.start()) { 955 const size_t run_start = run->range.start(); 956 const int32 run_length = static_cast<int32>(run_break - run_start); 957 base::i18n::UTF16CharIterator iter(layout_text.c_str() + run_start, 958 run_length); 959 const UBlockCode first_block_code = ublock_getCode(iter.get()); 960 const bool first_block_unusual = IsUnusualBlockCode(first_block_code); 961 while (iter.Advance() && iter.array_pos() < run_length) { 962 const UBlockCode current_block_code = ublock_getCode(iter.get()); 963 if (current_block_code != first_block_code && 964 (first_block_unusual || IsUnusualBlockCode(current_block_code))) { 965 run_break = run_start + iter.array_pos(); 966 break; 967 } 968 } 969 } 970 971 DCHECK(IsValidCodePointIndex(layout_text, run_break)); 972 973 style.UpdatePosition(LayoutIndexToTextIndex(run_break)); 974 if (script_item_break == run_break) 975 script_item++; 976 run->range.set_end(run_break); 977 runs_.push_back(run); 978 } 979 980 // Undo the temporarily applied composition underlines and selection colors. 981 UndoCompositionAndSelectionStyles(); 982 } 983 984 void RenderTextWin::LayoutVisualText() { 985 DCHECK(!runs_.empty()); 986 987 if (!cached_hdc_) 988 cached_hdc_ = CreateCompatibleDC(NULL); 989 990 HRESULT hr = E_FAIL; 991 // Ensure ascent and descent are not smaller than ones of the font list. 992 // Keep them tall enough to draw often-used characters. 993 // For example, if a text field contains a Japanese character, which is 994 // smaller than Latin ones, and then later a Latin one is inserted, this 995 // ensures that the text baseline does not shift. 996 int ascent = font_list().GetBaseline(); 997 int descent = font_list().GetHeight() - font_list().GetBaseline(); 998 for (size_t i = 0; i < runs_.size(); ++i) { 999 internal::TextRun* run = runs_[i]; 1000 LayoutTextRun(run); 1001 1002 ascent = std::max(ascent, run->font.GetBaseline()); 1003 descent = std::max(descent, 1004 run->font.GetHeight() - run->font.GetBaseline()); 1005 1006 if (run->glyph_count > 0) { 1007 run->advance_widths.reset(new int[run->glyph_count]); 1008 run->offsets.reset(new GOFFSET[run->glyph_count]); 1009 hr = ScriptPlace(cached_hdc_, 1010 &run->script_cache, 1011 run->glyphs.get(), 1012 run->glyph_count, 1013 run->visible_attributes.get(), 1014 &(run->script_analysis), 1015 run->advance_widths.get(), 1016 run->offsets.get(), 1017 &(run->abc_widths)); 1018 DCHECK(SUCCEEDED(hr)); 1019 } 1020 } 1021 1022 // Build the array of bidirectional embedding levels. 1023 scoped_ptr<BYTE[]> levels(new BYTE[runs_.size()]); 1024 for (size_t i = 0; i < runs_.size(); ++i) 1025 levels[i] = runs_[i]->script_analysis.s.uBidiLevel; 1026 1027 // Get the maps between visual and logical run indices. 1028 visual_to_logical_.reset(new int[runs_.size()]); 1029 logical_to_visual_.reset(new int[runs_.size()]); 1030 hr = ScriptLayout(runs_.size(), 1031 levels.get(), 1032 visual_to_logical_.get(), 1033 logical_to_visual_.get()); 1034 DCHECK(SUCCEEDED(hr)); 1035 1036 // Precalculate run width information. 1037 size_t preceding_run_widths = 0; 1038 for (size_t i = 0; i < runs_.size(); ++i) { 1039 internal::TextRun* run = runs_[visual_to_logical_[i]]; 1040 run->preceding_run_widths = preceding_run_widths; 1041 const ABC& abc = run->abc_widths; 1042 run->width = abc.abcA + abc.abcB + abc.abcC; 1043 preceding_run_widths += run->width; 1044 } 1045 string_width_ = preceding_run_widths; 1046 } 1047 1048 void RenderTextWin::LayoutTextRun(internal::TextRun* run) { 1049 const size_t run_length = run->range.length(); 1050 const wchar_t* run_text = &(GetLayoutText()[run->range.start()]); 1051 Font original_font = run->font; 1052 LinkedFontsIterator fonts(original_font); 1053 bool tried_cached_font = false; 1054 bool tried_fallback = false; 1055 // Keep track of the font that is able to display the greatest number of 1056 // characters for which ScriptShape() returned S_OK. This font will be used 1057 // in the case where no font is able to display the entire run. 1058 int best_partial_font_missing_char_count = INT_MAX; 1059 Font best_partial_font = original_font; 1060 Font current_font; 1061 1062 run->logical_clusters.reset(new WORD[run_length]); 1063 while (fonts.NextFont(¤t_font)) { 1064 HRESULT hr = ShapeTextRunWithFont(run, current_font); 1065 1066 bool glyphs_missing = false; 1067 if (hr == USP_E_SCRIPT_NOT_IN_FONT) { 1068 glyphs_missing = true; 1069 } else if (hr == S_OK) { 1070 // If |hr| is S_OK, there could still be missing glyphs in the output. 1071 // http://msdn.microsoft.com/en-us/library/windows/desktop/dd368564.aspx 1072 const int missing_count = CountCharsWithMissingGlyphs(run); 1073 // Track the font that produced the least missing glyphs. 1074 if (missing_count < best_partial_font_missing_char_count) { 1075 best_partial_font_missing_char_count = missing_count; 1076 best_partial_font = run->font; 1077 } 1078 glyphs_missing = (missing_count != 0); 1079 } else { 1080 NOTREACHED() << hr; 1081 } 1082 1083 // Use the font if it had glyphs for all characters. 1084 if (!glyphs_missing) { 1085 // Save the successful fallback font that was chosen. 1086 if (tried_fallback) 1087 successful_substitute_fonts_[original_font.GetFontName()] = run->font; 1088 return; 1089 } 1090 1091 // First, try the cached font from previous runs, if any. 1092 if (!tried_cached_font) { 1093 tried_cached_font = true; 1094 1095 std::map<std::string, Font>::const_iterator it = 1096 successful_substitute_fonts_.find(original_font.GetFontName()); 1097 if (it != successful_substitute_fonts_.end()) { 1098 fonts.SetNextFont(it->second); 1099 continue; 1100 } 1101 } 1102 1103 // If there are missing glyphs, first try finding a fallback font using a 1104 // meta file, if it hasn't yet been attempted for this run. 1105 // TODO(msw|asvitkine): Support RenderText's font_list()? 1106 if (!tried_fallback) { 1107 tried_fallback = true; 1108 1109 Font fallback_font; 1110 if (ChooseFallbackFont(cached_hdc_, run->font, run_text, run_length, 1111 &fallback_font)) { 1112 fonts.SetNextFont(fallback_font); 1113 continue; 1114 } 1115 } 1116 } 1117 1118 // If a font was able to partially display the run, use that now. 1119 if (best_partial_font_missing_char_count < static_cast<int>(run_length)) { 1120 // Re-shape the run only if |best_partial_font| differs from the last font. 1121 if (best_partial_font.GetNativeFont() != run->font.GetNativeFont()) 1122 ShapeTextRunWithFont(run, best_partial_font); 1123 return; 1124 } 1125 1126 // If no font was able to partially display the run, replace all glyphs 1127 // with |wgDefault| from the original font to ensure to they don't hold 1128 // garbage values. 1129 // First, clear the cache and select the original font on the HDC. 1130 ScriptFreeCache(&run->script_cache); 1131 run->font = original_font; 1132 SelectObject(cached_hdc_, run->font.GetNativeFont()); 1133 1134 // Now, get the font's properties. 1135 SCRIPT_FONTPROPERTIES properties; 1136 memset(&properties, 0, sizeof(properties)); 1137 properties.cBytes = sizeof(properties); 1138 HRESULT hr = ScriptGetFontProperties(cached_hdc_, &run->script_cache, 1139 &properties); 1140 1141 // The initial values for the "missing" glyph and the space glyph are taken 1142 // from the recommendations section of the OpenType spec: 1143 // https://www.microsoft.com/typography/otspec/recom.htm 1144 WORD missing_glyph = 0; 1145 WORD space_glyph = 3; 1146 if (hr == S_OK) { 1147 missing_glyph = properties.wgDefault; 1148 space_glyph = properties.wgBlank; 1149 } 1150 1151 // Finally, initialize |glyph_count|, |glyphs|, |visible_attributes| and 1152 // |logical_clusters| on the run (since they may not have been set yet). 1153 run->glyph_count = run_length; 1154 memset(run->visible_attributes.get(), 0, 1155 run->glyph_count * sizeof(SCRIPT_VISATTR)); 1156 for (int i = 0; i < run->glyph_count; ++i) 1157 run->glyphs[i] = IsWhitespace(run_text[i]) ? space_glyph : missing_glyph; 1158 for (size_t i = 0; i < run_length; ++i) { 1159 run->logical_clusters[i] = run->script_analysis.fRTL ? 1160 run_length - 1 - i : i; 1161 } 1162 1163 // TODO(msw): Don't use SCRIPT_UNDEFINED. Apparently Uniscribe can 1164 // crash on certain surrogate pairs with SCRIPT_UNDEFINED. 1165 // See https://bugzilla.mozilla.org/show_bug.cgi?id=341500 1166 // And http://maxradi.us/documents/uniscribe/ 1167 run->script_analysis.eScript = SCRIPT_UNDEFINED; 1168 } 1169 1170 HRESULT RenderTextWin::ShapeTextRunWithFont(internal::TextRun* run, 1171 const Font& font) { 1172 // Update the run's font only if necessary. If the two fonts wrap the same 1173 // PlatformFontWin object, their native fonts will have the same value. 1174 if (run->font.GetNativeFont() != font.GetNativeFont()) { 1175 const int font_size = run->font.GetFontSize(); 1176 const int font_height = run->font.GetHeight(); 1177 run->font = font; 1178 DeriveFontIfNecessary(font_size, font_height, run->font_style, &run->font); 1179 ScriptFreeCache(&run->script_cache); 1180 } 1181 1182 // Select the font desired for glyph generation. 1183 SelectObject(cached_hdc_, run->font.GetNativeFont()); 1184 1185 HRESULT hr = E_OUTOFMEMORY; 1186 const size_t run_length = run->range.length(); 1187 const wchar_t* run_text = &(GetLayoutText()[run->range.start()]); 1188 // Guess the expected number of glyphs from the length of the run. 1189 // MSDN suggests this at http://msdn.microsoft.com/en-us/library/dd368564.aspx 1190 size_t max_glyphs = static_cast<size_t>(1.5 * run_length + 16); 1191 while (hr == E_OUTOFMEMORY && max_glyphs <= kMaxGlyphs) { 1192 run->glyph_count = 0; 1193 run->glyphs.reset(new WORD[max_glyphs]); 1194 run->visible_attributes.reset(new SCRIPT_VISATTR[max_glyphs]); 1195 hr = ScriptShape(cached_hdc_, &run->script_cache, run_text, run_length, 1196 max_glyphs, &run->script_analysis, run->glyphs.get(), 1197 run->logical_clusters.get(), run->visible_attributes.get(), 1198 &run->glyph_count); 1199 // Ensure that |kMaxGlyphs| is attempted and the loop terminates afterward. 1200 max_glyphs = std::max(max_glyphs + 1, std::min(max_glyphs * 2, kMaxGlyphs)); 1201 } 1202 return hr; 1203 } 1204 1205 int RenderTextWin::CountCharsWithMissingGlyphs(internal::TextRun* run) const { 1206 int chars_not_missing_glyphs = 0; 1207 SCRIPT_FONTPROPERTIES properties; 1208 memset(&properties, 0, sizeof(properties)); 1209 properties.cBytes = sizeof(properties); 1210 ScriptGetFontProperties(cached_hdc_, &run->script_cache, &properties); 1211 1212 const wchar_t* run_text = &(GetLayoutText()[run->range.start()]); 1213 for (size_t char_index = 0; char_index < run->range.length(); ++char_index) { 1214 const int glyph_index = run->logical_clusters[char_index]; 1215 DCHECK_GE(glyph_index, 0); 1216 DCHECK_LT(glyph_index, run->glyph_count); 1217 1218 if (run->glyphs[glyph_index] == properties.wgDefault) 1219 continue; 1220 1221 // Windows Vista sometimes returns glyphs equal to wgBlank (instead of 1222 // wgDefault), with fZeroWidth set. Treat such cases as having missing 1223 // glyphs if the corresponding character is not whitespace. 1224 // See: http://crbug.com/125629 1225 if (run->glyphs[glyph_index] == properties.wgBlank && 1226 run->visible_attributes[glyph_index].fZeroWidth && 1227 !IsWhitespace(run_text[char_index]) && 1228 !IsUnicodeBidiControlCharacter(run_text[char_index])) { 1229 continue; 1230 } 1231 1232 ++chars_not_missing_glyphs; 1233 } 1234 1235 DCHECK_LE(chars_not_missing_glyphs, static_cast<int>(run->range.length())); 1236 return run->range.length() - chars_not_missing_glyphs; 1237 } 1238 1239 size_t RenderTextWin::GetRunContainingCaret(const SelectionModel& caret) const { 1240 DCHECK(!needs_layout_); 1241 size_t layout_position = TextIndexToLayoutIndex(caret.caret_pos()); 1242 LogicalCursorDirection affinity = caret.caret_affinity(); 1243 for (size_t run = 0; run < runs_.size(); ++run) 1244 if (RangeContainsCaret(runs_[run]->range, layout_position, affinity)) 1245 return run; 1246 return runs_.size(); 1247 } 1248 1249 size_t RenderTextWin::GetRunContainingXCoord(int x) const { 1250 DCHECK(!needs_layout_); 1251 // Find the text run containing the argument point (assumed already offset). 1252 for (size_t run = 0; run < runs_.size(); ++run) { 1253 if ((runs_[run]->preceding_run_widths <= x) && 1254 ((runs_[run]->preceding_run_widths + runs_[run]->width) > x)) 1255 return run; 1256 } 1257 return runs_.size(); 1258 } 1259 1260 SelectionModel RenderTextWin::FirstSelectionModelInsideRun( 1261 const internal::TextRun* run) { 1262 size_t position = LayoutIndexToTextIndex(run->range.start()); 1263 position = IndexOfAdjacentGrapheme(position, CURSOR_FORWARD); 1264 return SelectionModel(position, CURSOR_BACKWARD); 1265 } 1266 1267 SelectionModel RenderTextWin::LastSelectionModelInsideRun( 1268 const internal::TextRun* run) { 1269 size_t position = LayoutIndexToTextIndex(run->range.end()); 1270 position = IndexOfAdjacentGrapheme(position, CURSOR_BACKWARD); 1271 return SelectionModel(position, CURSOR_FORWARD); 1272 } 1273 1274 RenderText* RenderText::CreateInstance() { 1275 return new RenderTextWin; 1276 } 1277 1278 } // namespace gfx 1279