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