Update V8 to version 3.28.7 (based on bleeding_edge revision r22083).
[chromium-blink-merge.git] / ui / gfx / render_text.cc
blob4e7281c11695d4b7b70beb85b36e04227f425936
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "ui/gfx/render_text.h"
7 #include <algorithm>
8 #include <climits>
10 #include "base/command_line.h"
11 #include "base/i18n/break_iterator.h"
12 #include "base/logging.h"
13 #include "base/stl_util.h"
14 #include "base/strings/utf_string_conversions.h"
15 #include "third_party/icu/source/common/unicode/rbbi.h"
16 #include "third_party/icu/source/common/unicode/utf16.h"
17 #include "third_party/skia/include/core/SkTypeface.h"
18 #include "third_party/skia/include/effects/SkGradientShader.h"
19 #include "ui/gfx/canvas.h"
20 #include "ui/gfx/insets.h"
21 #include "ui/gfx/render_text_harfbuzz.h"
22 #include "ui/gfx/scoped_canvas.h"
23 #include "ui/gfx/skia_util.h"
24 #include "ui/gfx/switches.h"
25 #include "ui/gfx/text_constants.h"
26 #include "ui/gfx/text_elider.h"
27 #include "ui/gfx/text_utils.h"
28 #include "ui/gfx/utf16_indexing.h"
30 namespace gfx {
32 namespace {
34 // All chars are replaced by this char when the password style is set.
35 // TODO(benrg): GTK uses the first of U+25CF, U+2022, U+2731, U+273A, '*'
36 // that's available in the font (find_invisible_char() in gtkentry.c).
37 const base::char16 kPasswordReplacementChar = '*';
39 // Default color used for the text and cursor.
40 const SkColor kDefaultColor = SK_ColorBLACK;
42 // Default color used for drawing selection background.
43 const SkColor kDefaultSelectionBackgroundColor = SK_ColorGRAY;
45 // Fraction of the text size to lower a strike through below the baseline.
46 const SkScalar kStrikeThroughOffset = (-SK_Scalar1 * 6 / 21);
47 // Fraction of the text size to lower an underline below the baseline.
48 const SkScalar kUnderlineOffset = (SK_Scalar1 / 9);
49 // Fraction of the text size to use for a strike through or under-line.
50 const SkScalar kLineThickness = (SK_Scalar1 / 18);
51 // Fraction of the text size to use for a top margin of a diagonal strike.
52 const SkScalar kDiagonalStrikeMarginOffset = (SK_Scalar1 / 4);
54 // Invalid value of baseline. Assigning this value to |baseline_| causes
55 // re-calculation of baseline.
56 const int kInvalidBaseline = INT_MAX;
58 // Returns the baseline, with which the text best appears vertically centered.
59 int DetermineBaselineCenteringText(const Rect& display_rect,
60 const FontList& font_list) {
61 const int display_height = display_rect.height();
62 const int font_height = font_list.GetHeight();
63 // Lower and upper bound of baseline shift as we try to show as much area of
64 // text as possible. In particular case of |display_height| == |font_height|,
65 // we do not want to shift the baseline.
66 const int min_shift = std::min(0, display_height - font_height);
67 const int max_shift = std::abs(display_height - font_height);
68 const int baseline = font_list.GetBaseline();
69 const int cap_height = font_list.GetCapHeight();
70 const int internal_leading = baseline - cap_height;
71 // Some platforms don't support getting the cap height, and simply return
72 // the entire font ascent from GetCapHeight(). Centering the ascent makes
73 // the font look too low, so if GetCapHeight() returns the ascent, center
74 // the entire font height instead.
75 const int space =
76 display_height - ((internal_leading != 0) ? cap_height : font_height);
77 const int baseline_shift = space / 2 - internal_leading;
78 return baseline + std::max(min_shift, std::min(max_shift, baseline_shift));
81 // Converts |Font::FontStyle| flags to |SkTypeface::Style| flags.
82 SkTypeface::Style ConvertFontStyleToSkiaTypefaceStyle(int font_style) {
83 int skia_style = SkTypeface::kNormal;
84 skia_style |= (font_style & Font::BOLD) ? SkTypeface::kBold : 0;
85 skia_style |= (font_style & Font::ITALIC) ? SkTypeface::kItalic : 0;
86 return static_cast<SkTypeface::Style>(skia_style);
89 // Given |font| and |display_width|, returns the width of the fade gradient.
90 int CalculateFadeGradientWidth(const FontList& font_list, int display_width) {
91 // Fade in/out about 2.5 characters of the beginning/end of the string.
92 // The .5 here is helpful if one of the characters is a space.
93 // Use a quarter of the display width if the display width is very short.
94 const int average_character_width = font_list.GetExpectedTextWidth(1);
95 const double gradient_width = std::min(average_character_width * 2.5,
96 display_width / 4.0);
97 DCHECK_GE(gradient_width, 0.0);
98 return static_cast<int>(floor(gradient_width + 0.5));
101 // Appends to |positions| and |colors| values corresponding to the fade over
102 // |fade_rect| from color |c0| to color |c1|.
103 void AddFadeEffect(const Rect& text_rect,
104 const Rect& fade_rect,
105 SkColor c0,
106 SkColor c1,
107 std::vector<SkScalar>* positions,
108 std::vector<SkColor>* colors) {
109 const SkScalar left = static_cast<SkScalar>(fade_rect.x() - text_rect.x());
110 const SkScalar width = static_cast<SkScalar>(fade_rect.width());
111 const SkScalar p0 = left / text_rect.width();
112 const SkScalar p1 = (left + width) / text_rect.width();
113 // Prepend 0.0 to |positions|, as required by Skia.
114 if (positions->empty() && p0 != 0.0) {
115 positions->push_back(0.0);
116 colors->push_back(c0);
118 positions->push_back(p0);
119 colors->push_back(c0);
120 positions->push_back(p1);
121 colors->push_back(c1);
124 // Creates a SkShader to fade the text, with |left_part| specifying the left
125 // fade effect, if any, and |right_part| specifying the right fade effect.
126 skia::RefPtr<SkShader> CreateFadeShader(const Rect& text_rect,
127 const Rect& left_part,
128 const Rect& right_part,
129 SkColor color) {
130 // Fade alpha of 51/255 corresponds to a fade of 0.2 of the original color.
131 const SkColor fade_color = SkColorSetA(color, 51);
132 std::vector<SkScalar> positions;
133 std::vector<SkColor> colors;
135 if (!left_part.IsEmpty())
136 AddFadeEffect(text_rect, left_part, fade_color, color,
137 &positions, &colors);
138 if (!right_part.IsEmpty())
139 AddFadeEffect(text_rect, right_part, color, fade_color,
140 &positions, &colors);
141 DCHECK(!positions.empty());
143 // Terminate |positions| with 1.0, as required by Skia.
144 if (positions.back() != 1.0) {
145 positions.push_back(1.0);
146 colors.push_back(colors.back());
149 SkPoint points[2];
150 points[0].iset(text_rect.x(), text_rect.y());
151 points[1].iset(text_rect.right(), text_rect.y());
153 return skia::AdoptRef(
154 SkGradientShader::CreateLinear(&points[0], &colors[0], &positions[0],
155 colors.size(), SkShader::kClamp_TileMode));
158 } // namespace
160 namespace internal {
162 // Value of |underline_thickness_| that indicates that underline metrics have
163 // not been set explicitly.
164 const SkScalar kUnderlineMetricsNotSet = -1.0f;
166 SkiaTextRenderer::SkiaTextRenderer(Canvas* canvas)
167 : canvas_(canvas),
168 canvas_skia_(canvas->sk_canvas()),
169 started_drawing_(false),
170 underline_thickness_(kUnderlineMetricsNotSet),
171 underline_position_(0.0f) {
172 DCHECK(canvas_skia_);
173 paint_.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
174 paint_.setStyle(SkPaint::kFill_Style);
175 paint_.setAntiAlias(true);
176 paint_.setSubpixelText(true);
177 paint_.setLCDRenderText(true);
178 paint_.setHinting(SkPaint::kNormal_Hinting);
179 bounds_.setEmpty();
182 SkiaTextRenderer::~SkiaTextRenderer() {
183 // Work-around for http://crbug.com/122743, where non-ClearType text is
184 // rendered with incorrect gamma when using the fade shader. Draw the text
185 // to a layer and restore it faded by drawing a rect in kDstIn_Mode mode.
187 // TODO(asvitkine): Remove this work-around once the Skia bug is fixed.
188 // http://code.google.com/p/skia/issues/detail?id=590
189 if (deferred_fade_shader_.get()) {
190 paint_.setShader(deferred_fade_shader_.get());
191 paint_.setXfermodeMode(SkXfermode::kDstIn_Mode);
192 canvas_skia_->drawRect(bounds_, paint_);
193 canvas_skia_->restore();
197 void SkiaTextRenderer::SetDrawLooper(SkDrawLooper* draw_looper) {
198 paint_.setLooper(draw_looper);
201 void SkiaTextRenderer::SetFontSmoothingSettings(bool antialiasing,
202 bool subpixel_rendering,
203 bool subpixel_positioning) {
204 paint_.setAntiAlias(antialiasing);
205 paint_.setLCDRenderText(subpixel_rendering);
206 paint_.setSubpixelText(subpixel_positioning);
209 void SkiaTextRenderer::SetFontHinting(SkPaint::Hinting hinting) {
210 paint_.setHinting(hinting);
213 void SkiaTextRenderer::SetTypeface(SkTypeface* typeface) {
214 paint_.setTypeface(typeface);
217 void SkiaTextRenderer::SetTextSize(SkScalar size) {
218 paint_.setTextSize(size);
221 void SkiaTextRenderer::SetFontFamilyWithStyle(const std::string& family,
222 int style) {
223 DCHECK(!family.empty());
225 skia::RefPtr<SkTypeface> typeface = CreateSkiaTypeface(family.c_str(), style);
226 if (typeface) {
227 // |paint_| adds its own ref. So don't |release()| it from the ref ptr here.
228 SetTypeface(typeface.get());
230 // Enable fake bold text if bold style is needed but new typeface does not
231 // have it.
232 paint_.setFakeBoldText((style & Font::BOLD) && !typeface->isBold());
236 void SkiaTextRenderer::SetForegroundColor(SkColor foreground) {
237 paint_.setColor(foreground);
240 void SkiaTextRenderer::SetShader(SkShader* shader, const Rect& bounds) {
241 bounds_ = RectToSkRect(bounds);
242 paint_.setShader(shader);
245 void SkiaTextRenderer::SetUnderlineMetrics(SkScalar thickness,
246 SkScalar position) {
247 underline_thickness_ = thickness;
248 underline_position_ = position;
251 void SkiaTextRenderer::DrawPosText(const SkPoint* pos,
252 const uint16* glyphs,
253 size_t glyph_count) {
254 if (!started_drawing_) {
255 started_drawing_ = true;
256 // Work-around for http://crbug.com/122743, where non-ClearType text is
257 // rendered with incorrect gamma when using the fade shader. Draw the text
258 // to a layer and restore it faded by drawing a rect in kDstIn_Mode mode.
260 // Skip this when there is a looper which seems not working well with
261 // deferred paint. Currently a looper is only used for text shadows.
263 // TODO(asvitkine): Remove this work-around once the Skia bug is fixed.
264 // http://code.google.com/p/skia/issues/detail?id=590
265 if (!paint_.isLCDRenderText() &&
266 paint_.getShader() &&
267 !paint_.getLooper()) {
268 deferred_fade_shader_ = skia::SharePtr(paint_.getShader());
269 paint_.setShader(NULL);
270 canvas_skia_->saveLayer(&bounds_, NULL);
274 const size_t byte_length = glyph_count * sizeof(glyphs[0]);
275 canvas_skia_->drawPosText(&glyphs[0], byte_length, &pos[0], paint_);
278 void SkiaTextRenderer::DrawDecorations(int x, int y, int width, bool underline,
279 bool strike, bool diagonal_strike) {
280 if (underline)
281 DrawUnderline(x, y, width);
282 if (strike)
283 DrawStrike(x, y, width);
284 if (diagonal_strike) {
285 if (!diagonal_)
286 diagonal_.reset(new DiagonalStrike(canvas_, Point(x, y), paint_));
287 diagonal_->AddPiece(width, paint_.getColor());
288 } else if (diagonal_) {
289 EndDiagonalStrike();
293 void SkiaTextRenderer::EndDiagonalStrike() {
294 if (diagonal_) {
295 diagonal_->Draw();
296 diagonal_.reset();
300 void SkiaTextRenderer::DrawUnderline(int x, int y, int width) {
301 SkRect r = SkRect::MakeLTRB(x, y + underline_position_, x + width,
302 y + underline_position_ + underline_thickness_);
303 if (underline_thickness_ == kUnderlineMetricsNotSet) {
304 const SkScalar text_size = paint_.getTextSize();
305 r.fTop = SkScalarMulAdd(text_size, kUnderlineOffset, y);
306 r.fBottom = r.fTop + SkScalarMul(text_size, kLineThickness);
308 canvas_skia_->drawRect(r, paint_);
311 void SkiaTextRenderer::DrawStrike(int x, int y, int width) const {
312 const SkScalar text_size = paint_.getTextSize();
313 const SkScalar height = SkScalarMul(text_size, kLineThickness);
314 const SkScalar offset = SkScalarMulAdd(text_size, kStrikeThroughOffset, y);
315 const SkRect r = SkRect::MakeLTRB(x, offset, x + width, offset + height);
316 canvas_skia_->drawRect(r, paint_);
319 SkiaTextRenderer::DiagonalStrike::DiagonalStrike(Canvas* canvas,
320 Point start,
321 const SkPaint& paint)
322 : canvas_(canvas),
323 start_(start),
324 paint_(paint),
325 total_length_(0) {
328 SkiaTextRenderer::DiagonalStrike::~DiagonalStrike() {
331 void SkiaTextRenderer::DiagonalStrike::AddPiece(int length, SkColor color) {
332 pieces_.push_back(Piece(length, color));
333 total_length_ += length;
336 void SkiaTextRenderer::DiagonalStrike::Draw() {
337 const SkScalar text_size = paint_.getTextSize();
338 const SkScalar offset = SkScalarMul(text_size, kDiagonalStrikeMarginOffset);
339 const int thickness =
340 SkScalarCeilToInt(SkScalarMul(text_size, kLineThickness) * 2);
341 const int height = SkScalarCeilToInt(text_size - offset);
342 const Point end = start_ + Vector2d(total_length_, -height);
343 const int clip_height = height + 2 * thickness;
345 paint_.setAntiAlias(true);
346 paint_.setStrokeWidth(thickness);
348 const bool clipped = pieces_.size() > 1;
349 SkCanvas* sk_canvas = canvas_->sk_canvas();
350 int x = start_.x();
352 for (size_t i = 0; i < pieces_.size(); ++i) {
353 paint_.setColor(pieces_[i].second);
355 if (clipped) {
356 canvas_->Save();
357 sk_canvas->clipRect(RectToSkRect(
358 Rect(x, end.y() - thickness, pieces_[i].first, clip_height)));
361 canvas_->DrawLine(start_, end, paint_);
363 if (clipped)
364 canvas_->Restore();
366 x += pieces_[i].first;
370 StyleIterator::StyleIterator(const BreakList<SkColor>& colors,
371 const std::vector<BreakList<bool> >& styles)
372 : colors_(colors),
373 styles_(styles) {
374 color_ = colors_.breaks().begin();
375 for (size_t i = 0; i < styles_.size(); ++i)
376 style_.push_back(styles_[i].breaks().begin());
379 StyleIterator::~StyleIterator() {}
381 Range StyleIterator::GetRange() const {
382 Range range(colors_.GetRange(color_));
383 for (size_t i = 0; i < NUM_TEXT_STYLES; ++i)
384 range = range.Intersect(styles_[i].GetRange(style_[i]));
385 return range;
388 void StyleIterator::UpdatePosition(size_t position) {
389 color_ = colors_.GetBreak(position);
390 for (size_t i = 0; i < NUM_TEXT_STYLES; ++i)
391 style_[i] = styles_[i].GetBreak(position);
394 LineSegment::LineSegment() : run(0) {}
396 LineSegment::~LineSegment() {}
398 Line::Line() : preceding_heights(0), baseline(0) {}
400 Line::~Line() {}
402 skia::RefPtr<SkTypeface> CreateSkiaTypeface(const std::string& family,
403 int style) {
404 SkTypeface::Style skia_style = ConvertFontStyleToSkiaTypefaceStyle(style);
405 return skia::AdoptRef(SkTypeface::CreateFromName(family.c_str(), skia_style));
408 } // namespace internal
410 RenderText::~RenderText() {
413 RenderText* RenderText::CreateInstance() {
414 #if defined(OS_MACOSX) && defined(TOOLKIT_VIEWS)
415 // Use the more complete HarfBuzz implementation for Views controls on Mac.
416 return new RenderTextHarfBuzz;
417 #else
418 if (CommandLine::ForCurrentProcess()->HasSwitch(
419 switches::kEnableHarfBuzzRenderText)) {
420 return new RenderTextHarfBuzz;
422 return CreateNativeInstance();
423 #endif
426 void RenderText::SetText(const base::string16& text) {
427 DCHECK(!composition_range_.IsValid());
428 if (text_ == text)
429 return;
430 text_ = text;
432 // Adjust ranged styles and colors to accommodate a new text length.
433 const size_t text_length = text_.length();
434 colors_.SetMax(text_length);
435 for (size_t style = 0; style < NUM_TEXT_STYLES; ++style)
436 styles_[style].SetMax(text_length);
437 cached_bounds_and_offset_valid_ = false;
439 // Reset selection model. SetText should always followed by SetSelectionModel
440 // or SetCursorPosition in upper layer.
441 SetSelectionModel(SelectionModel());
443 // Invalidate the cached text direction if it depends on the text contents.
444 if (directionality_mode_ == DIRECTIONALITY_FROM_TEXT)
445 text_direction_ = base::i18n::UNKNOWN_DIRECTION;
447 obscured_reveal_index_ = -1;
448 UpdateLayoutText();
451 void RenderText::SetHorizontalAlignment(HorizontalAlignment alignment) {
452 if (horizontal_alignment_ != alignment) {
453 horizontal_alignment_ = alignment;
454 display_offset_ = Vector2d();
455 cached_bounds_and_offset_valid_ = false;
459 void RenderText::SetFontList(const FontList& font_list) {
460 font_list_ = font_list;
461 baseline_ = kInvalidBaseline;
462 cached_bounds_and_offset_valid_ = false;
463 ResetLayout();
466 void RenderText::SetCursorEnabled(bool cursor_enabled) {
467 cursor_enabled_ = cursor_enabled;
468 cached_bounds_and_offset_valid_ = false;
471 void RenderText::ToggleInsertMode() {
472 insert_mode_ = !insert_mode_;
473 cached_bounds_and_offset_valid_ = false;
476 void RenderText::SetObscured(bool obscured) {
477 if (obscured != obscured_) {
478 obscured_ = obscured;
479 obscured_reveal_index_ = -1;
480 cached_bounds_and_offset_valid_ = false;
481 UpdateLayoutText();
485 void RenderText::SetObscuredRevealIndex(int index) {
486 if (obscured_reveal_index_ == index)
487 return;
489 obscured_reveal_index_ = index;
490 cached_bounds_and_offset_valid_ = false;
491 UpdateLayoutText();
494 void RenderText::SetMultiline(bool multiline) {
495 if (multiline != multiline_) {
496 multiline_ = multiline;
497 cached_bounds_and_offset_valid_ = false;
498 lines_.clear();
502 void RenderText::SetElideBehavior(ElideBehavior elide_behavior) {
503 // TODO(skanuj) : Add a test for triggering layout change.
504 if (elide_behavior_ != elide_behavior) {
505 elide_behavior_ = elide_behavior;
506 UpdateLayoutText();
510 void RenderText::SetDisplayRect(const Rect& r) {
511 if (r != display_rect_) {
512 display_rect_ = r;
513 baseline_ = kInvalidBaseline;
514 cached_bounds_and_offset_valid_ = false;
515 lines_.clear();
516 if (elide_behavior_ != TRUNCATE)
517 UpdateLayoutText();
521 void RenderText::SetCursorPosition(size_t position) {
522 MoveCursorTo(position, false);
525 void RenderText::MoveCursor(BreakType break_type,
526 VisualCursorDirection direction,
527 bool select) {
528 SelectionModel cursor(cursor_position(), selection_model_.caret_affinity());
529 // Cancelling a selection moves to the edge of the selection.
530 if (break_type != LINE_BREAK && !selection().is_empty() && !select) {
531 SelectionModel selection_start = GetSelectionModelForSelectionStart();
532 int start_x = GetCursorBounds(selection_start, true).x();
533 int cursor_x = GetCursorBounds(cursor, true).x();
534 // Use the selection start if it is left (when |direction| is CURSOR_LEFT)
535 // or right (when |direction| is CURSOR_RIGHT) of the selection end.
536 if (direction == CURSOR_RIGHT ? start_x > cursor_x : start_x < cursor_x)
537 cursor = selection_start;
538 // Use the nearest word boundary in the proper |direction| for word breaks.
539 if (break_type == WORD_BREAK)
540 cursor = GetAdjacentSelectionModel(cursor, break_type, direction);
541 // Use an adjacent selection model if the cursor is not at a valid position.
542 if (!IsValidCursorIndex(cursor.caret_pos()))
543 cursor = GetAdjacentSelectionModel(cursor, CHARACTER_BREAK, direction);
544 } else {
545 cursor = GetAdjacentSelectionModel(cursor, break_type, direction);
547 if (select)
548 cursor.set_selection_start(selection().start());
549 MoveCursorTo(cursor);
552 bool RenderText::MoveCursorTo(const SelectionModel& model) {
553 // Enforce valid selection model components.
554 size_t text_length = text().length();
555 Range range(std::min(model.selection().start(), text_length),
556 std::min(model.caret_pos(), text_length));
557 // The current model only supports caret positions at valid cursor indices.
558 if (!IsValidCursorIndex(range.start()) || !IsValidCursorIndex(range.end()))
559 return false;
560 SelectionModel sel(range, model.caret_affinity());
561 bool changed = sel != selection_model_;
562 SetSelectionModel(sel);
563 return changed;
566 bool RenderText::SelectRange(const Range& range) {
567 Range sel(std::min(range.start(), text().length()),
568 std::min(range.end(), text().length()));
569 // Allow selection bounds at valid indicies amid multi-character graphemes.
570 if (!IsValidLogicalIndex(sel.start()) || !IsValidLogicalIndex(sel.end()))
571 return false;
572 LogicalCursorDirection affinity =
573 (sel.is_reversed() || sel.is_empty()) ? CURSOR_FORWARD : CURSOR_BACKWARD;
574 SetSelectionModel(SelectionModel(sel, affinity));
575 return true;
578 bool RenderText::IsPointInSelection(const Point& point) {
579 if (selection().is_empty())
580 return false;
581 SelectionModel cursor = FindCursorPosition(point);
582 return RangeContainsCaret(
583 selection(), cursor.caret_pos(), cursor.caret_affinity());
586 void RenderText::ClearSelection() {
587 SetSelectionModel(SelectionModel(cursor_position(),
588 selection_model_.caret_affinity()));
591 void RenderText::SelectAll(bool reversed) {
592 const size_t length = text().length();
593 const Range all = reversed ? Range(length, 0) : Range(0, length);
594 const bool success = SelectRange(all);
595 DCHECK(success);
598 void RenderText::SelectWord() {
599 if (obscured_) {
600 SelectAll(false);
601 return;
604 size_t selection_max = selection().GetMax();
606 base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD);
607 bool success = iter.Init();
608 DCHECK(success);
609 if (!success)
610 return;
612 size_t selection_min = selection().GetMin();
613 if (selection_min == text().length() && selection_min != 0)
614 --selection_min;
616 for (; selection_min != 0; --selection_min) {
617 if (iter.IsStartOfWord(selection_min) ||
618 iter.IsEndOfWord(selection_min))
619 break;
622 if (selection_min == selection_max && selection_max != text().length())
623 ++selection_max;
625 for (; selection_max < text().length(); ++selection_max)
626 if (iter.IsEndOfWord(selection_max) || iter.IsStartOfWord(selection_max))
627 break;
629 const bool reversed = selection().is_reversed();
630 MoveCursorTo(reversed ? selection_max : selection_min, false);
631 MoveCursorTo(reversed ? selection_min : selection_max, true);
634 const Range& RenderText::GetCompositionRange() const {
635 return composition_range_;
638 void RenderText::SetCompositionRange(const Range& composition_range) {
639 CHECK(!composition_range.IsValid() ||
640 Range(0, text_.length()).Contains(composition_range));
641 composition_range_.set_end(composition_range.end());
642 composition_range_.set_start(composition_range.start());
643 ResetLayout();
646 void RenderText::SetColor(SkColor value) {
647 colors_.SetValue(value);
649 #if defined(OS_WIN)
650 // TODO(msw): Windows applies colors and decorations in the layout process.
651 cached_bounds_and_offset_valid_ = false;
652 ResetLayout();
653 #endif
656 void RenderText::ApplyColor(SkColor value, const Range& range) {
657 colors_.ApplyValue(value, range);
659 #if defined(OS_WIN)
660 // TODO(msw): Windows applies colors and decorations in the layout process.
661 cached_bounds_and_offset_valid_ = false;
662 ResetLayout();
663 #endif
666 void RenderText::SetStyle(TextStyle style, bool value) {
667 styles_[style].SetValue(value);
669 // Only invalidate the layout on font changes; not for colors or decorations.
670 bool invalidate = (style == BOLD) || (style == ITALIC);
671 #if defined(OS_WIN)
672 // TODO(msw): Windows applies colors and decorations in the layout process.
673 invalidate = true;
674 #endif
675 if (invalidate) {
676 cached_bounds_and_offset_valid_ = false;
677 ResetLayout();
681 void RenderText::ApplyStyle(TextStyle style, bool value, const Range& range) {
682 styles_[style].ApplyValue(value, range);
684 // Only invalidate the layout on font changes; not for colors or decorations.
685 bool invalidate = (style == BOLD) || (style == ITALIC);
686 #if defined(OS_WIN)
687 // TODO(msw): Windows applies colors and decorations in the layout process.
688 invalidate = true;
689 #endif
690 if (invalidate) {
691 cached_bounds_and_offset_valid_ = false;
692 ResetLayout();
696 bool RenderText::GetStyle(TextStyle style) const {
697 return (styles_[style].breaks().size() == 1) &&
698 styles_[style].breaks().front().second;
701 void RenderText::SetDirectionalityMode(DirectionalityMode mode) {
702 if (mode == directionality_mode_)
703 return;
705 directionality_mode_ = mode;
706 text_direction_ = base::i18n::UNKNOWN_DIRECTION;
707 cached_bounds_and_offset_valid_ = false;
708 ResetLayout();
711 base::i18n::TextDirection RenderText::GetTextDirection() {
712 if (text_direction_ == base::i18n::UNKNOWN_DIRECTION) {
713 switch (directionality_mode_) {
714 case DIRECTIONALITY_FROM_TEXT:
715 // Derive the direction from the display text, which differs from text()
716 // in the case of obscured (password) textfields.
717 text_direction_ =
718 base::i18n::GetFirstStrongCharacterDirection(GetLayoutText());
719 break;
720 case DIRECTIONALITY_FROM_UI:
721 text_direction_ = base::i18n::IsRTL() ? base::i18n::RIGHT_TO_LEFT :
722 base::i18n::LEFT_TO_RIGHT;
723 break;
724 case DIRECTIONALITY_FORCE_LTR:
725 text_direction_ = base::i18n::LEFT_TO_RIGHT;
726 break;
727 case DIRECTIONALITY_FORCE_RTL:
728 text_direction_ = base::i18n::RIGHT_TO_LEFT;
729 break;
730 default:
731 NOTREACHED();
735 return text_direction_;
738 VisualCursorDirection RenderText::GetVisualDirectionOfLogicalEnd() {
739 return GetTextDirection() == base::i18n::LEFT_TO_RIGHT ?
740 CURSOR_RIGHT : CURSOR_LEFT;
743 SizeF RenderText::GetStringSizeF() {
744 const Size size = GetStringSize();
745 return SizeF(size.width(), size.height());
748 int RenderText::GetContentWidth() {
749 return GetStringSize().width() + (cursor_enabled_ ? 1 : 0);
752 int RenderText::GetBaseline() {
753 if (baseline_ == kInvalidBaseline)
754 baseline_ = DetermineBaselineCenteringText(display_rect(), font_list());
755 DCHECK_NE(kInvalidBaseline, baseline_);
756 return baseline_;
759 void RenderText::Draw(Canvas* canvas) {
760 EnsureLayout();
762 if (clip_to_display_rect()) {
763 Rect clip_rect(display_rect());
764 clip_rect.Inset(ShadowValue::GetMargin(shadows_));
766 canvas->Save();
767 canvas->ClipRect(clip_rect);
770 if (!text().empty() && focused())
771 DrawSelection(canvas);
773 if (cursor_enabled() && cursor_visible() && focused())
774 DrawCursor(canvas, selection_model_);
776 if (!text().empty())
777 DrawVisualText(canvas);
779 if (clip_to_display_rect())
780 canvas->Restore();
783 void RenderText::DrawCursor(Canvas* canvas, const SelectionModel& position) {
784 // Paint cursor. Replace cursor is drawn as rectangle for now.
785 // TODO(msw): Draw a better cursor with a better indication of association.
786 canvas->FillRect(GetCursorBounds(position, true), cursor_color_);
789 bool RenderText::IsValidLogicalIndex(size_t index) {
790 // Check that the index is at a valid code point (not mid-surrgate-pair) and
791 // that it's not truncated from the layout text (its glyph may be shown).
793 // Indices within truncated text are disallowed so users can easily interact
794 // with the underlying truncated text using the ellipsis as a proxy. This lets
795 // users select all text, select the truncated text, and transition from the
796 // last rendered glyph to the end of the text without getting invisible cursor
797 // positions nor needing unbounded arrow key presses to traverse the ellipsis.
798 return index == 0 || index == text().length() ||
799 (index < text().length() &&
800 (truncate_length_ == 0 || index < truncate_length_) &&
801 IsValidCodePointIndex(text(), index));
804 Rect RenderText::GetCursorBounds(const SelectionModel& caret,
805 bool insert_mode) {
806 // TODO(ckocagil): Support multiline. This function should return the height
807 // of the line the cursor is on. |GetStringSize()| now returns
808 // the multiline size, eliminate its use here.
810 EnsureLayout();
811 size_t caret_pos = caret.caret_pos();
812 DCHECK(IsValidLogicalIndex(caret_pos));
813 // In overtype mode, ignore the affinity and always indicate that we will
814 // overtype the next character.
815 LogicalCursorDirection caret_affinity =
816 insert_mode ? caret.caret_affinity() : CURSOR_FORWARD;
817 int x = 0, width = 1;
818 Size size = GetStringSize();
819 if (caret_pos == (caret_affinity == CURSOR_BACKWARD ? 0 : text().length())) {
820 // The caret is attached to the boundary. Always return a 1-dip width caret,
821 // since there is nothing to overtype.
822 if ((GetTextDirection() == base::i18n::RIGHT_TO_LEFT) == (caret_pos == 0))
823 x = size.width();
824 } else {
825 size_t grapheme_start = (caret_affinity == CURSOR_FORWARD) ?
826 caret_pos : IndexOfAdjacentGrapheme(caret_pos, CURSOR_BACKWARD);
827 Range xspan(GetGlyphBounds(grapheme_start));
828 if (insert_mode) {
829 x = (caret_affinity == CURSOR_BACKWARD) ? xspan.end() : xspan.start();
830 } else { // overtype mode
831 x = xspan.GetMin();
832 width = xspan.length();
835 return Rect(ToViewPoint(Point(x, 0)), Size(width, size.height()));
838 const Rect& RenderText::GetUpdatedCursorBounds() {
839 UpdateCachedBoundsAndOffset();
840 return cursor_bounds_;
843 size_t RenderText::IndexOfAdjacentGrapheme(size_t index,
844 LogicalCursorDirection direction) {
845 if (index > text().length())
846 return text().length();
848 EnsureLayout();
850 if (direction == CURSOR_FORWARD) {
851 while (index < text().length()) {
852 index++;
853 if (IsValidCursorIndex(index))
854 return index;
856 return text().length();
859 while (index > 0) {
860 index--;
861 if (IsValidCursorIndex(index))
862 return index;
864 return 0;
867 SelectionModel RenderText::GetSelectionModelForSelectionStart() {
868 const Range& sel = selection();
869 if (sel.is_empty())
870 return selection_model_;
871 return SelectionModel(sel.start(),
872 sel.is_reversed() ? CURSOR_BACKWARD : CURSOR_FORWARD);
875 RenderText::RenderText()
876 : horizontal_alignment_(base::i18n::IsRTL() ? ALIGN_RIGHT : ALIGN_LEFT),
877 directionality_mode_(DIRECTIONALITY_FROM_TEXT),
878 text_direction_(base::i18n::UNKNOWN_DIRECTION),
879 cursor_enabled_(true),
880 cursor_visible_(false),
881 insert_mode_(true),
882 cursor_color_(kDefaultColor),
883 selection_color_(kDefaultColor),
884 selection_background_focused_color_(kDefaultSelectionBackgroundColor),
885 focused_(false),
886 composition_range_(Range::InvalidRange()),
887 colors_(kDefaultColor),
888 styles_(NUM_TEXT_STYLES),
889 composition_and_selection_styles_applied_(false),
890 obscured_(false),
891 obscured_reveal_index_(-1),
892 truncate_length_(0),
893 elide_behavior_(TRUNCATE),
894 multiline_(false),
895 background_is_transparent_(false),
896 clip_to_display_rect_(true),
897 baseline_(kInvalidBaseline),
898 cached_bounds_and_offset_valid_(false) {
901 const Vector2d& RenderText::GetUpdatedDisplayOffset() {
902 UpdateCachedBoundsAndOffset();
903 return display_offset_;
906 SelectionModel RenderText::GetAdjacentSelectionModel(
907 const SelectionModel& current,
908 BreakType break_type,
909 VisualCursorDirection direction) {
910 EnsureLayout();
912 if (break_type == LINE_BREAK || text().empty())
913 return EdgeSelectionModel(direction);
914 if (break_type == CHARACTER_BREAK)
915 return AdjacentCharSelectionModel(current, direction);
916 DCHECK(break_type == WORD_BREAK);
917 return AdjacentWordSelectionModel(current, direction);
920 SelectionModel RenderText::EdgeSelectionModel(
921 VisualCursorDirection direction) {
922 if (direction == GetVisualDirectionOfLogicalEnd())
923 return SelectionModel(text().length(), CURSOR_FORWARD);
924 return SelectionModel(0, CURSOR_BACKWARD);
927 void RenderText::SetSelectionModel(const SelectionModel& model) {
928 DCHECK_LE(model.selection().GetMax(), text().length());
929 selection_model_ = model;
930 cached_bounds_and_offset_valid_ = false;
933 const base::string16& RenderText::GetLayoutText() const {
934 return layout_text_;
937 const BreakList<size_t>& RenderText::GetLineBreaks() {
938 if (line_breaks_.max() != 0)
939 return line_breaks_;
941 const base::string16& layout_text = GetLayoutText();
942 const size_t text_length = layout_text.length();
943 line_breaks_.SetValue(0);
944 line_breaks_.SetMax(text_length);
945 base::i18n::BreakIterator iter(layout_text,
946 base::i18n::BreakIterator::BREAK_LINE);
947 const bool success = iter.Init();
948 DCHECK(success);
949 if (success) {
950 do {
951 line_breaks_.ApplyValue(iter.pos(), Range(iter.pos(), text_length));
952 } while (iter.Advance());
954 return line_breaks_;
957 void RenderText::ApplyCompositionAndSelectionStyles() {
958 // Save the underline and color breaks to undo the temporary styles later.
959 DCHECK(!composition_and_selection_styles_applied_);
960 saved_colors_ = colors_;
961 saved_underlines_ = styles_[UNDERLINE];
963 // Apply an underline to the composition range in |underlines|.
964 if (composition_range_.IsValid() && !composition_range_.is_empty())
965 styles_[UNDERLINE].ApplyValue(true, composition_range_);
967 // Apply the selected text color to the [un-reversed] selection range.
968 if (!selection().is_empty() && focused()) {
969 const Range range(selection().GetMin(), selection().GetMax());
970 colors_.ApplyValue(selection_color_, range);
972 composition_and_selection_styles_applied_ = true;
975 void RenderText::UndoCompositionAndSelectionStyles() {
976 // Restore the underline and color breaks to undo the temporary styles.
977 DCHECK(composition_and_selection_styles_applied_);
978 colors_ = saved_colors_;
979 styles_[UNDERLINE] = saved_underlines_;
980 composition_and_selection_styles_applied_ = false;
983 Vector2d RenderText::GetLineOffset(size_t line_number) {
984 Vector2d offset = display_rect().OffsetFromOrigin();
985 // TODO(ckocagil): Apply the display offset for multiline scrolling.
986 if (!multiline())
987 offset.Add(GetUpdatedDisplayOffset());
988 else
989 offset.Add(Vector2d(0, lines_[line_number].preceding_heights));
990 offset.Add(GetAlignmentOffset(line_number));
991 return offset;
994 Point RenderText::ToTextPoint(const Point& point) {
995 return point - GetLineOffset(0);
996 // TODO(ckocagil): Convert multiline view space points to text space.
999 Point RenderText::ToViewPoint(const Point& point) {
1000 if (!multiline())
1001 return point + GetLineOffset(0);
1003 // TODO(ckocagil): Traverse individual line segments for RTL support.
1004 DCHECK(!lines_.empty());
1005 int x = point.x();
1006 size_t line = 0;
1007 for (; line < lines_.size() && x > lines_[line].size.width(); ++line)
1008 x -= lines_[line].size.width();
1009 return Point(x, point.y()) + GetLineOffset(line);
1012 std::vector<Rect> RenderText::TextBoundsToViewBounds(const Range& x) {
1013 std::vector<Rect> rects;
1015 if (!multiline()) {
1016 rects.push_back(Rect(ToViewPoint(Point(x.GetMin(), 0)),
1017 Size(x.length(), GetStringSize().height())));
1018 return rects;
1021 EnsureLayout();
1023 // Each line segment keeps its position in text coordinates. Traverse all line
1024 // segments and if the segment intersects with the given range, add the view
1025 // rect corresponding to the intersection to |rects|.
1026 for (size_t line = 0; line < lines_.size(); ++line) {
1027 int line_x = 0;
1028 const Vector2d offset = GetLineOffset(line);
1029 for (size_t i = 0; i < lines_[line].segments.size(); ++i) {
1030 const internal::LineSegment* segment = &lines_[line].segments[i];
1031 const Range intersection = segment->x_range.Intersect(x);
1032 if (!intersection.is_empty()) {
1033 Rect rect(line_x + intersection.start() - segment->x_range.start(),
1034 0, intersection.length(), lines_[line].size.height());
1035 rects.push_back(rect + offset);
1037 line_x += segment->x_range.length();
1041 return rects;
1044 Vector2d RenderText::GetAlignmentOffset(size_t line_number) {
1045 // TODO(ckocagil): Enable |lines_| usage in other platforms.
1046 #if defined(OS_WIN)
1047 DCHECK_LT(line_number, lines_.size());
1048 #endif
1049 Vector2d offset;
1050 if (horizontal_alignment_ != ALIGN_LEFT) {
1051 #if defined(OS_WIN)
1052 const int width = lines_[line_number].size.width() +
1053 (cursor_enabled_ ? 1 : 0);
1054 #else
1055 const int width = GetContentWidth();
1056 #endif
1057 offset.set_x(display_rect().width() - width);
1058 if (horizontal_alignment_ == ALIGN_CENTER)
1059 offset.set_x(offset.x() / 2);
1062 // Vertically center the text.
1063 if (multiline_) {
1064 const int text_height = lines_.back().preceding_heights +
1065 lines_.back().size.height();
1066 offset.set_y((display_rect_.height() - text_height) / 2);
1067 } else {
1068 offset.set_y(GetBaseline() - GetLayoutTextBaseline());
1071 return offset;
1074 void RenderText::ApplyFadeEffects(internal::SkiaTextRenderer* renderer) {
1075 const int width = display_rect().width();
1076 if (multiline() || elide_behavior_ != FADE_TAIL || GetContentWidth() <= width)
1077 return;
1079 const int gradient_width = CalculateFadeGradientWidth(font_list(), width);
1080 if (gradient_width == 0)
1081 return;
1083 Rect solid_part = display_rect();
1084 Rect left_part;
1085 Rect right_part;
1086 if (horizontal_alignment_ != ALIGN_LEFT) {
1087 left_part = solid_part;
1088 left_part.Inset(0, 0, solid_part.width() - gradient_width, 0);
1089 solid_part.Inset(gradient_width, 0, 0, 0);
1091 if (horizontal_alignment_ != ALIGN_RIGHT) {
1092 right_part = solid_part;
1093 right_part.Inset(solid_part.width() - gradient_width, 0, 0, 0);
1094 solid_part.Inset(0, 0, gradient_width, 0);
1097 Rect text_rect = display_rect();
1098 text_rect.Inset(GetAlignmentOffset(0).x(), 0, 0, 0);
1100 // TODO(msw): Use the actual text colors corresponding to each faded part.
1101 skia::RefPtr<SkShader> shader = CreateFadeShader(
1102 text_rect, left_part, right_part, colors_.breaks().front().second);
1103 if (shader)
1104 renderer->SetShader(shader.get(), display_rect());
1107 void RenderText::ApplyTextShadows(internal::SkiaTextRenderer* renderer) {
1108 skia::RefPtr<SkDrawLooper> looper = CreateShadowDrawLooper(shadows_);
1109 renderer->SetDrawLooper(looper.get());
1112 // static
1113 bool RenderText::RangeContainsCaret(const Range& range,
1114 size_t caret_pos,
1115 LogicalCursorDirection caret_affinity) {
1116 // NB: exploits unsigned wraparound (WG14/N1124 section 6.2.5 paragraph 9).
1117 size_t adjacent = (caret_affinity == CURSOR_BACKWARD) ?
1118 caret_pos - 1 : caret_pos + 1;
1119 return range.Contains(Range(caret_pos, adjacent));
1122 void RenderText::MoveCursorTo(size_t position, bool select) {
1123 size_t cursor = std::min(position, text().length());
1124 if (IsValidCursorIndex(cursor))
1125 SetSelectionModel(SelectionModel(
1126 Range(select ? selection().start() : cursor, cursor),
1127 (cursor == 0) ? CURSOR_FORWARD : CURSOR_BACKWARD));
1130 void RenderText::UpdateLayoutText() {
1131 layout_text_.clear();
1132 line_breaks_.SetMax(0);
1134 if (obscured_) {
1135 size_t obscured_text_length =
1136 static_cast<size_t>(UTF16IndexToOffset(text_, 0, text_.length()));
1137 layout_text_.assign(obscured_text_length, kPasswordReplacementChar);
1139 if (obscured_reveal_index_ >= 0 &&
1140 obscured_reveal_index_ < static_cast<int>(text_.length())) {
1141 // Gets the index range in |text_| to be revealed.
1142 size_t start = obscured_reveal_index_;
1143 U16_SET_CP_START(text_.data(), 0, start);
1144 size_t end = start;
1145 UChar32 unused_char;
1146 U16_NEXT(text_.data(), end, text_.length(), unused_char);
1148 // Gets the index in |layout_text_| to be replaced.
1149 const size_t cp_start =
1150 static_cast<size_t>(UTF16IndexToOffset(text_, 0, start));
1151 if (layout_text_.length() > cp_start)
1152 layout_text_.replace(cp_start, 1, text_.substr(start, end - start));
1154 } else {
1155 layout_text_ = text_;
1158 const base::string16& text = layout_text_;
1159 if (truncate_length_ > 0 && truncate_length_ < text.length()) {
1160 // Truncate the text at a valid character break and append an ellipsis.
1161 icu::StringCharacterIterator iter(text.c_str());
1162 iter.setIndex32(truncate_length_ - 1);
1163 layout_text_.assign(text.substr(0, iter.getIndex()) + kEllipsisUTF16);
1166 if (elide_behavior_ != TRUNCATE && elide_behavior_ != FADE_TAIL &&
1167 display_rect_.width() > 0 && !layout_text_.empty() &&
1168 GetContentWidth() > display_rect_.width()) {
1169 // This doesn't trim styles so ellipsis may get rendered as a different
1170 // style than the preceding text. See crbug.com/327850.
1171 layout_text_.assign(ElideText(layout_text_));
1174 ResetLayout();
1177 // TODO(skanuj): Fix code duplication with ElideText in ui/gfx/text_elider.cc
1178 // See crbug.com/327846
1179 base::string16 RenderText::ElideText(const base::string16& text) {
1180 const bool insert_ellipsis = (elide_behavior_ != TRUNCATE);
1181 // Create a RenderText copy with attributes that affect the rendering width.
1182 scoped_ptr<RenderText> render_text(CreateInstance());
1183 render_text->SetFontList(font_list_);
1184 render_text->SetDirectionalityMode(directionality_mode_);
1185 render_text->SetCursorEnabled(cursor_enabled_);
1187 render_text->styles_ = styles_;
1188 render_text->colors_ = colors_;
1189 render_text->SetText(text);
1190 const int current_text_pixel_width = render_text->GetContentWidth();
1192 const base::string16 ellipsis = base::string16(kEllipsisUTF16);
1193 const bool elide_in_middle = false;
1194 const bool elide_at_beginning = false;
1195 StringSlicer slicer(text, ellipsis, elide_in_middle, elide_at_beginning);
1197 // Pango will return 0 width for absurdly long strings. Cut the string in
1198 // half and try again.
1199 // This is caused by an int overflow in Pango (specifically, in
1200 // pango_glyph_string_extents_range). It's actually more subtle than just
1201 // returning 0, since on super absurdly long strings, the int can wrap and
1202 // return positive numbers again. Detecting that is probably not worth it
1203 // (eliding way too much from a ridiculous string is probably still
1204 // ridiculous), but we should check other widths for bogus values as well.
1205 if (current_text_pixel_width <= 0 && !text.empty())
1206 return ElideText(slicer.CutString(text.length() / 2, insert_ellipsis));
1208 if (current_text_pixel_width <= display_rect_.width())
1209 return text;
1211 render_text->SetText(base::string16());
1212 render_text->SetText(ellipsis);
1213 const int ellipsis_width = render_text->GetContentWidth();
1215 if (insert_ellipsis && (ellipsis_width >= display_rect_.width()))
1216 return base::string16();
1218 // Use binary search to compute the elided text.
1219 size_t lo = 0;
1220 size_t hi = text.length() - 1;
1221 const base::i18n::TextDirection text_direction = GetTextDirection();
1222 for (size_t guess = (lo + hi) / 2; lo <= hi; guess = (lo + hi) / 2) {
1223 // Restore styles and colors. They will be truncated to size by SetText.
1224 render_text->styles_ = styles_;
1225 render_text->colors_ = colors_;
1226 base::string16 new_text = slicer.CutString(guess, false);
1227 render_text->SetText(new_text);
1229 // This has to be an additional step so that the ellipsis is rendered with
1230 // same style as trailing part of the text.
1231 if (insert_ellipsis) {
1232 // When ellipsis follows text whose directionality is not the same as that
1233 // of the whole text, it will be rendered with the directionality of the
1234 // whole text. Since we want ellipsis to indicate continuation of the
1235 // preceding text, we force the directionality of ellipsis to be same as
1236 // the preceding text using LTR or RTL markers.
1237 base::i18n::TextDirection trailing_text_direction =
1238 base::i18n::GetLastStrongCharacterDirection(new_text);
1239 new_text.append(ellipsis);
1240 if (trailing_text_direction != text_direction) {
1241 if (trailing_text_direction == base::i18n::LEFT_TO_RIGHT)
1242 new_text += base::i18n::kLeftToRightMark;
1243 else
1244 new_text += base::i18n::kRightToLeftMark;
1246 render_text->SetText(new_text);
1249 // We check the width of the whole desired string at once to ensure we
1250 // handle kerning/ligatures/etc. correctly.
1251 const int guess_width = render_text->GetContentWidth();
1252 if (guess_width == display_rect_.width())
1253 break;
1254 if (guess_width > display_rect_.width()) {
1255 hi = guess - 1;
1256 // Move back if we are on loop terminating condition, and guess is wider
1257 // than available.
1258 if (hi < lo)
1259 lo = hi;
1260 } else {
1261 lo = guess + 1;
1265 return render_text->text();
1268 void RenderText::UpdateCachedBoundsAndOffset() {
1269 if (cached_bounds_and_offset_valid_)
1270 return;
1272 // TODO(ckocagil): Add support for scrolling multiline text.
1274 // First, set the valid flag true to calculate the current cursor bounds using
1275 // the stale |display_offset_|. Applying |delta_offset| at the end of this
1276 // function will set |cursor_bounds_| and |display_offset_| to correct values.
1277 cached_bounds_and_offset_valid_ = true;
1278 if (cursor_enabled())
1279 cursor_bounds_ = GetCursorBounds(selection_model_, insert_mode_);
1281 // Update |display_offset_| to ensure the current cursor is visible.
1282 const int display_width = display_rect_.width();
1283 const int content_width = GetContentWidth();
1285 int delta_x = 0;
1286 if (content_width <= display_width || !cursor_enabled()) {
1287 // Don't pan if the text fits in the display width or when the cursor is
1288 // disabled.
1289 delta_x = -display_offset_.x();
1290 } else if (cursor_bounds_.right() > display_rect_.right()) {
1291 // TODO(xji): when the character overflow is a RTL character, currently, if
1292 // we pan cursor at the rightmost position, the entered RTL character is not
1293 // displayed. Should pan cursor to show the last logical characters.
1295 // Pan to show the cursor when it overflows to the right.
1296 delta_x = display_rect_.right() - cursor_bounds_.right();
1297 } else if (cursor_bounds_.x() < display_rect_.x()) {
1298 // TODO(xji): have similar problem as above when overflow character is a
1299 // LTR character.
1301 // Pan to show the cursor when it overflows to the left.
1302 delta_x = display_rect_.x() - cursor_bounds_.x();
1303 } else if (display_offset_.x() != 0) {
1304 // Reduce the pan offset to show additional overflow text when the display
1305 // width increases.
1306 const int negate_rtl = horizontal_alignment_ == ALIGN_RIGHT ? -1 : 1;
1307 const int offset = negate_rtl * display_offset_.x();
1308 if (display_width > (content_width + offset)) {
1309 delta_x = negate_rtl * (display_width - (content_width + offset));
1313 Vector2d delta_offset(delta_x, 0);
1314 display_offset_ += delta_offset;
1315 cursor_bounds_ += delta_offset;
1318 void RenderText::DrawSelection(Canvas* canvas) {
1319 const std::vector<Rect> sel = GetSubstringBounds(selection());
1320 for (std::vector<Rect>::const_iterator i = sel.begin(); i < sel.end(); ++i)
1321 canvas->FillRect(*i, selection_background_focused_color_);
1324 } // namespace gfx