• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.h"
6 
7 #include <algorithm>
8 #include <climits>
9 
10 #include "base/i18n/break_iterator.h"
11 #include "base/logging.h"
12 #include "base/stl_util.h"
13 #include "third_party/icu/source/common/unicode/rbbi.h"
14 #include "third_party/icu/source/common/unicode/utf16.h"
15 #include "third_party/skia/include/core/SkTypeface.h"
16 #include "third_party/skia/include/effects/SkGradientShader.h"
17 #include "ui/gfx/canvas.h"
18 #include "ui/gfx/insets.h"
19 #include "ui/gfx/skia_util.h"
20 #include "ui/gfx/text_constants.h"
21 #include "ui/gfx/text_elider.h"
22 #include "ui/gfx/utf16_indexing.h"
23 
24 namespace gfx {
25 
26 namespace {
27 
28 // All chars are replaced by this char when the password style is set.
29 // TODO(benrg): GTK uses the first of U+25CF, U+2022, U+2731, U+273A, '*'
30 // that's available in the font (find_invisible_char() in gtkentry.c).
31 const base::char16 kPasswordReplacementChar = '*';
32 
33 // Default color used for the text and cursor.
34 const SkColor kDefaultColor = SK_ColorBLACK;
35 
36 // Default color used for drawing selection background.
37 const SkColor kDefaultSelectionBackgroundColor = SK_ColorGRAY;
38 
39 // Fraction of the text size to lower a strike through below the baseline.
40 const SkScalar kStrikeThroughOffset = (-SK_Scalar1 * 6 / 21);
41 // Fraction of the text size to lower an underline below the baseline.
42 const SkScalar kUnderlineOffset = (SK_Scalar1 / 9);
43 // Fraction of the text size to use for a strike through or under-line.
44 const SkScalar kLineThickness = (SK_Scalar1 / 18);
45 // Fraction of the text size to use for a top margin of a diagonal strike.
46 const SkScalar kDiagonalStrikeMarginOffset = (SK_Scalar1 / 4);
47 
48 // Invalid value of baseline.  Assigning this value to |baseline_| causes
49 // re-calculation of baseline.
50 const int kInvalidBaseline = INT_MAX;
51 
52 // Returns the baseline, with which the text best appears vertically centered.
DetermineBaselineCenteringText(const Rect & display_rect,const FontList & font_list)53 int DetermineBaselineCenteringText(const Rect& display_rect,
54                                    const FontList& font_list) {
55   const int display_height = display_rect.height();
56   const int font_height = font_list.GetHeight();
57   // Lower and upper bound of baseline shift as we try to show as much area of
58   // text as possible.  In particular case of |display_height| == |font_height|,
59   // we do not want to shift the baseline.
60   const int min_shift = std::min(0, display_height - font_height);
61   const int max_shift = std::abs(display_height - font_height);
62   const int baseline = font_list.GetBaseline();
63   const int cap_height = font_list.GetCapHeight();
64   const int internal_leading = baseline - cap_height;
65   // Some platforms don't support getting the cap height, and simply return
66   // the entire font ascent from GetCapHeight().  Centering the ascent makes
67   // the font look too low, so if GetCapHeight() returns the ascent, center
68   // the entire font height instead.
69   const int space =
70       display_height - ((internal_leading != 0) ? cap_height : font_height);
71   const int baseline_shift = space / 2 - internal_leading;
72   return baseline + std::max(min_shift, std::min(max_shift, baseline_shift));
73 }
74 
75 // Converts |gfx::Font::FontStyle| flags to |SkTypeface::Style| flags.
ConvertFontStyleToSkiaTypefaceStyle(int font_style)76 SkTypeface::Style ConvertFontStyleToSkiaTypefaceStyle(int font_style) {
77   int skia_style = SkTypeface::kNormal;
78   skia_style |= (font_style & gfx::Font::BOLD) ? SkTypeface::kBold : 0;
79   skia_style |= (font_style & gfx::Font::ITALIC) ? SkTypeface::kItalic : 0;
80   return static_cast<SkTypeface::Style>(skia_style);
81 }
82 
83 // Given |font| and |display_width|, returns the width of the fade gradient.
CalculateFadeGradientWidth(const Font & font,int display_width)84 int CalculateFadeGradientWidth(const Font& font, int display_width) {
85   // Fade in/out about 2.5 characters of the beginning/end of the string.
86   // The .5 here is helpful if one of the characters is a space.
87   // Use a quarter of the display width if the display width is very short.
88   const int average_character_width = font.GetAverageCharacterWidth();
89   const double gradient_width = std::min(average_character_width * 2.5,
90                                          display_width / 4.0);
91   DCHECK_GE(gradient_width, 0.0);
92   return static_cast<int>(floor(gradient_width + 0.5));
93 }
94 
95 // Appends to |positions| and |colors| values corresponding to the fade over
96 // |fade_rect| from color |c0| to color |c1|.
AddFadeEffect(const Rect & text_rect,const Rect & fade_rect,SkColor c0,SkColor c1,std::vector<SkScalar> * positions,std::vector<SkColor> * colors)97 void AddFadeEffect(const Rect& text_rect,
98                    const Rect& fade_rect,
99                    SkColor c0,
100                    SkColor c1,
101                    std::vector<SkScalar>* positions,
102                    std::vector<SkColor>* colors) {
103   const SkScalar left = static_cast<SkScalar>(fade_rect.x() - text_rect.x());
104   const SkScalar width = static_cast<SkScalar>(fade_rect.width());
105   const SkScalar p0 = left / text_rect.width();
106   const SkScalar p1 = (left + width) / text_rect.width();
107   // Prepend 0.0 to |positions|, as required by Skia.
108   if (positions->empty() && p0 != 0.0) {
109     positions->push_back(0.0);
110     colors->push_back(c0);
111   }
112   positions->push_back(p0);
113   colors->push_back(c0);
114   positions->push_back(p1);
115   colors->push_back(c1);
116 }
117 
118 // Creates a SkShader to fade the text, with |left_part| specifying the left
119 // fade effect, if any, and |right_part| specifying the right fade effect.
CreateFadeShader(const Rect & text_rect,const Rect & left_part,const Rect & right_part,SkColor color)120 skia::RefPtr<SkShader> CreateFadeShader(const Rect& text_rect,
121                                         const Rect& left_part,
122                                         const Rect& right_part,
123                                         SkColor color) {
124   // Fade alpha of 51/255 corresponds to a fade of 0.2 of the original color.
125   const SkColor fade_color = SkColorSetA(color, 51);
126   std::vector<SkScalar> positions;
127   std::vector<SkColor> colors;
128 
129   if (!left_part.IsEmpty())
130     AddFadeEffect(text_rect, left_part, fade_color, color,
131                   &positions, &colors);
132   if (!right_part.IsEmpty())
133     AddFadeEffect(text_rect, right_part, color, fade_color,
134                   &positions, &colors);
135   DCHECK(!positions.empty());
136 
137   // Terminate |positions| with 1.0, as required by Skia.
138   if (positions.back() != 1.0) {
139     positions.push_back(1.0);
140     colors.push_back(colors.back());
141   }
142 
143   SkPoint points[2];
144   points[0].iset(text_rect.x(), text_rect.y());
145   points[1].iset(text_rect.right(), text_rect.y());
146 
147   return skia::AdoptRef(
148       SkGradientShader::CreateLinear(&points[0], &colors[0], &positions[0],
149                                      colors.size(), SkShader::kClamp_TileMode));
150 }
151 
152 }  // namespace
153 
154 namespace internal {
155 
156 // Value of |underline_thickness_| that indicates that underline metrics have
157 // not been set explicitly.
158 const SkScalar kUnderlineMetricsNotSet = -1.0f;
159 
SkiaTextRenderer(Canvas * canvas)160 SkiaTextRenderer::SkiaTextRenderer(Canvas* canvas)
161     : canvas_skia_(canvas->sk_canvas()),
162       started_drawing_(false),
163       underline_thickness_(kUnderlineMetricsNotSet),
164       underline_position_(0.0f) {
165   DCHECK(canvas_skia_);
166   paint_.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
167   paint_.setStyle(SkPaint::kFill_Style);
168   paint_.setAntiAlias(true);
169   paint_.setSubpixelText(true);
170   paint_.setLCDRenderText(true);
171   bounds_.setEmpty();
172 }
173 
~SkiaTextRenderer()174 SkiaTextRenderer::~SkiaTextRenderer() {
175   // Work-around for http://crbug.com/122743, where non-ClearType text is
176   // rendered with incorrect gamma when using the fade shader. Draw the text
177   // to a layer and restore it faded by drawing a rect in kDstIn_Mode mode.
178   //
179   // TODO(asvitkine): Remove this work-around once the Skia bug is fixed.
180   //                  http://code.google.com/p/skia/issues/detail?id=590
181   if (deferred_fade_shader_.get()) {
182     paint_.setShader(deferred_fade_shader_.get());
183     paint_.setXfermodeMode(SkXfermode::kDstIn_Mode);
184     canvas_skia_->drawRect(bounds_, paint_);
185     canvas_skia_->restore();
186   }
187 }
188 
SetDrawLooper(SkDrawLooper * draw_looper)189 void SkiaTextRenderer::SetDrawLooper(SkDrawLooper* draw_looper) {
190   paint_.setLooper(draw_looper);
191 }
192 
SetFontSmoothingSettings(bool enable_smoothing,bool enable_lcd_text)193 void SkiaTextRenderer::SetFontSmoothingSettings(bool enable_smoothing,
194                                                 bool enable_lcd_text) {
195   paint_.setAntiAlias(enable_smoothing);
196   paint_.setSubpixelText(enable_smoothing);
197   paint_.setLCDRenderText(enable_lcd_text);
198 }
199 
SetTypeface(SkTypeface * typeface)200 void SkiaTextRenderer::SetTypeface(SkTypeface* typeface) {
201   paint_.setTypeface(typeface);
202 }
203 
SetTextSize(SkScalar size)204 void SkiaTextRenderer::SetTextSize(SkScalar size) {
205   paint_.setTextSize(size);
206 }
207 
SetFontFamilyWithStyle(const std::string & family,int style)208 void SkiaTextRenderer::SetFontFamilyWithStyle(const std::string& family,
209                                               int style) {
210   DCHECK(!family.empty());
211 
212   SkTypeface::Style skia_style = ConvertFontStyleToSkiaTypefaceStyle(style);
213   skia::RefPtr<SkTypeface> typeface =
214       skia::AdoptRef(SkTypeface::CreateFromName(family.c_str(), skia_style));
215   if (typeface) {
216     // |paint_| adds its own ref. So don't |release()| it from the ref ptr here.
217     SetTypeface(typeface.get());
218 
219     // Enable fake bold text if bold style is needed but new typeface does not
220     // have it.
221     paint_.setFakeBoldText((skia_style & SkTypeface::kBold) &&
222                            !typeface->isBold());
223   }
224 }
225 
SetForegroundColor(SkColor foreground)226 void SkiaTextRenderer::SetForegroundColor(SkColor foreground) {
227   paint_.setColor(foreground);
228 }
229 
SetShader(SkShader * shader,const Rect & bounds)230 void SkiaTextRenderer::SetShader(SkShader* shader, const Rect& bounds) {
231   bounds_ = RectToSkRect(bounds);
232   paint_.setShader(shader);
233 }
234 
SetUnderlineMetrics(SkScalar thickness,SkScalar position)235 void SkiaTextRenderer::SetUnderlineMetrics(SkScalar thickness,
236                                            SkScalar position) {
237   underline_thickness_ = thickness;
238   underline_position_ = position;
239 }
240 
DrawPosText(const SkPoint * pos,const uint16 * glyphs,size_t glyph_count)241 void SkiaTextRenderer::DrawPosText(const SkPoint* pos,
242                                    const uint16* glyphs,
243                                    size_t glyph_count) {
244   if (!started_drawing_) {
245     started_drawing_ = true;
246     // Work-around for http://crbug.com/122743, where non-ClearType text is
247     // rendered with incorrect gamma when using the fade shader. Draw the text
248     // to a layer and restore it faded by drawing a rect in kDstIn_Mode mode.
249     //
250     // Skip this when there is a looper which seems not working well with
251     // deferred paint. Currently a looper is only used for text shadows.
252     //
253     // TODO(asvitkine): Remove this work-around once the Skia bug is fixed.
254     //                  http://code.google.com/p/skia/issues/detail?id=590
255     if (!paint_.isLCDRenderText() &&
256         paint_.getShader() &&
257         !paint_.getLooper()) {
258       deferred_fade_shader_ = skia::SharePtr(paint_.getShader());
259       paint_.setShader(NULL);
260       canvas_skia_->saveLayer(&bounds_, NULL);
261     }
262   }
263 
264   const size_t byte_length = glyph_count * sizeof(glyphs[0]);
265   canvas_skia_->drawPosText(&glyphs[0], byte_length, &pos[0], paint_);
266 }
267 
DrawDecorations(int x,int y,int width,bool underline,bool strike,bool diagonal_strike)268 void SkiaTextRenderer::DrawDecorations(int x, int y, int width, bool underline,
269                                        bool strike, bool diagonal_strike) {
270   if (underline)
271     DrawUnderline(x, y, width);
272   if (strike)
273     DrawStrike(x, y, width);
274   if (diagonal_strike)
275     DrawDiagonalStrike(x, y, width);
276 }
277 
DrawUnderline(int x,int y,int width)278 void SkiaTextRenderer::DrawUnderline(int x, int y, int width) {
279   SkRect r = SkRect::MakeLTRB(x, y + underline_position_, x + width,
280                               y + underline_position_ + underline_thickness_);
281   if (underline_thickness_ == kUnderlineMetricsNotSet) {
282     const SkScalar text_size = paint_.getTextSize();
283     r.fTop = SkScalarMulAdd(text_size, kUnderlineOffset, y);
284     r.fBottom = r.fTop + SkScalarMul(text_size, kLineThickness);
285   }
286   canvas_skia_->drawRect(r, paint_);
287 }
288 
DrawStrike(int x,int y,int width) const289 void SkiaTextRenderer::DrawStrike(int x, int y, int width) const {
290   const SkScalar text_size = paint_.getTextSize();
291   const SkScalar height = SkScalarMul(text_size, kLineThickness);
292   const SkScalar offset = SkScalarMulAdd(text_size, kStrikeThroughOffset, y);
293   const SkRect r = SkRect::MakeLTRB(x, offset, x + width, offset + height);
294   canvas_skia_->drawRect(r, paint_);
295 }
296 
DrawDiagonalStrike(int x,int y,int width) const297 void SkiaTextRenderer::DrawDiagonalStrike(int x, int y, int width) const {
298   const SkScalar text_size = paint_.getTextSize();
299   const SkScalar offset = SkScalarMul(text_size, kDiagonalStrikeMarginOffset);
300 
301   SkPaint paint(paint_);
302   paint.setAntiAlias(true);
303   paint.setStyle(SkPaint::kFill_Style);
304   paint.setStrokeWidth(SkScalarMul(text_size, kLineThickness) * 2);
305   canvas_skia_->drawLine(x, y, x + width, y - text_size + offset, paint);
306 }
307 
StyleIterator(const BreakList<SkColor> & colors,const std::vector<BreakList<bool>> & styles)308 StyleIterator::StyleIterator(const BreakList<SkColor>& colors,
309                              const std::vector<BreakList<bool> >& styles)
310     : colors_(colors),
311       styles_(styles) {
312   color_ = colors_.breaks().begin();
313   for (size_t i = 0; i < styles_.size(); ++i)
314     style_.push_back(styles_[i].breaks().begin());
315 }
316 
~StyleIterator()317 StyleIterator::~StyleIterator() {}
318 
GetRange() const319 Range StyleIterator::GetRange() const {
320   Range range(colors_.GetRange(color_));
321   for (size_t i = 0; i < NUM_TEXT_STYLES; ++i)
322     range = range.Intersect(styles_[i].GetRange(style_[i]));
323   return range;
324 }
325 
UpdatePosition(size_t position)326 void StyleIterator::UpdatePosition(size_t position) {
327   color_ = colors_.GetBreak(position);
328   for (size_t i = 0; i < NUM_TEXT_STYLES; ++i)
329     style_[i] = styles_[i].GetBreak(position);
330 }
331 
LineSegment()332 LineSegment::LineSegment() : run(0) {}
333 
~LineSegment()334 LineSegment::~LineSegment() {}
335 
Line()336 Line::Line() : preceding_heights(0), baseline(0) {}
337 
~Line()338 Line::~Line() {}
339 
340 }  // namespace internal
341 
~RenderText()342 RenderText::~RenderText() {
343 }
344 
SetText(const base::string16 & text)345 void RenderText::SetText(const base::string16& text) {
346   DCHECK(!composition_range_.IsValid());
347   if (text_ == text)
348     return;
349   text_ = text;
350 
351   // Adjust ranged styles and colors to accommodate a new text length.
352   const size_t text_length = text_.length();
353   colors_.SetMax(text_length);
354   for (size_t style = 0; style < NUM_TEXT_STYLES; ++style)
355     styles_[style].SetMax(text_length);
356   cached_bounds_and_offset_valid_ = false;
357 
358   // Reset selection model. SetText should always followed by SetSelectionModel
359   // or SetCursorPosition in upper layer.
360   SetSelectionModel(SelectionModel());
361 
362   // Invalidate the cached text direction if it depends on the text contents.
363   if (directionality_mode_ == DIRECTIONALITY_FROM_TEXT)
364     text_direction_ = base::i18n::UNKNOWN_DIRECTION;
365 
366   obscured_reveal_index_ = -1;
367   UpdateLayoutText();
368   ResetLayout();
369 }
370 
SetHorizontalAlignment(HorizontalAlignment alignment)371 void RenderText::SetHorizontalAlignment(HorizontalAlignment alignment) {
372   if (horizontal_alignment_ != alignment) {
373     horizontal_alignment_ = alignment;
374     display_offset_ = Vector2d();
375     cached_bounds_and_offset_valid_ = false;
376   }
377 }
378 
SetFontList(const FontList & font_list)379 void RenderText::SetFontList(const FontList& font_list) {
380   font_list_ = font_list;
381   baseline_ = kInvalidBaseline;
382   cached_bounds_and_offset_valid_ = false;
383   ResetLayout();
384 }
385 
SetFont(const Font & font)386 void RenderText::SetFont(const Font& font) {
387   SetFontList(FontList(font));
388 }
389 
SetFontSize(int size)390 void RenderText::SetFontSize(int size) {
391   SetFontList(font_list_.DeriveFontListWithSize(size));
392 }
393 
GetPrimaryFont() const394 const Font& RenderText::GetPrimaryFont() const {
395   return font_list_.GetPrimaryFont();
396 }
397 
SetCursorEnabled(bool cursor_enabled)398 void RenderText::SetCursorEnabled(bool cursor_enabled) {
399   cursor_enabled_ = cursor_enabled;
400   cached_bounds_and_offset_valid_ = false;
401 }
402 
ToggleInsertMode()403 void RenderText::ToggleInsertMode() {
404   insert_mode_ = !insert_mode_;
405   cached_bounds_and_offset_valid_ = false;
406 }
407 
SetObscured(bool obscured)408 void RenderText::SetObscured(bool obscured) {
409   if (obscured != obscured_) {
410     obscured_ = obscured;
411     obscured_reveal_index_ = -1;
412     cached_bounds_and_offset_valid_ = false;
413     UpdateLayoutText();
414     ResetLayout();
415   }
416 }
417 
SetObscuredRevealIndex(int index)418 void RenderText::SetObscuredRevealIndex(int index) {
419   if (obscured_reveal_index_ == index)
420     return;
421 
422   obscured_reveal_index_ = index;
423   cached_bounds_and_offset_valid_ = false;
424   UpdateLayoutText();
425   ResetLayout();
426 }
427 
SetMultiline(bool multiline)428 void RenderText::SetMultiline(bool multiline) {
429   if (multiline != multiline_) {
430     multiline_ = multiline;
431     cached_bounds_and_offset_valid_ = false;
432     lines_.clear();
433   }
434 }
435 
SetDisplayRect(const Rect & r)436 void RenderText::SetDisplayRect(const Rect& r) {
437   display_rect_ = r;
438   baseline_ = kInvalidBaseline;
439   cached_bounds_and_offset_valid_ = false;
440   lines_.clear();
441 }
442 
SetCursorPosition(size_t position)443 void RenderText::SetCursorPosition(size_t position) {
444   MoveCursorTo(position, false);
445 }
446 
MoveCursor(BreakType break_type,VisualCursorDirection direction,bool select)447 void RenderText::MoveCursor(BreakType break_type,
448                             VisualCursorDirection direction,
449                             bool select) {
450   SelectionModel position(cursor_position(), selection_model_.caret_affinity());
451   // Cancelling a selection moves to the edge of the selection.
452   if (break_type != LINE_BREAK && !selection().is_empty() && !select) {
453     SelectionModel selection_start = GetSelectionModelForSelectionStart();
454     int start_x = GetCursorBounds(selection_start, true).x();
455     int cursor_x = GetCursorBounds(position, true).x();
456     // Use the selection start if it is left (when |direction| is CURSOR_LEFT)
457     // or right (when |direction| is CURSOR_RIGHT) of the selection end.
458     if (direction == CURSOR_RIGHT ? start_x > cursor_x : start_x < cursor_x)
459       position = selection_start;
460     // For word breaks, use the nearest word boundary in the appropriate
461     // |direction|.
462     if (break_type == WORD_BREAK)
463       position = GetAdjacentSelectionModel(position, break_type, direction);
464   } else {
465     position = GetAdjacentSelectionModel(position, break_type, direction);
466   }
467   if (select)
468     position.set_selection_start(selection().start());
469   MoveCursorTo(position);
470 }
471 
MoveCursorTo(const SelectionModel & model)472 bool RenderText::MoveCursorTo(const SelectionModel& model) {
473   // Enforce valid selection model components.
474   size_t text_length = text().length();
475   Range range(std::min(model.selection().start(), text_length),
476               std::min(model.caret_pos(), text_length));
477   // The current model only supports caret positions at valid character indices.
478   if (!IsCursorablePosition(range.start()) ||
479       !IsCursorablePosition(range.end()))
480     return false;
481   SelectionModel sel(range, model.caret_affinity());
482   bool changed = sel != selection_model_;
483   SetSelectionModel(sel);
484   return changed;
485 }
486 
MoveCursorTo(const Point & point,bool select)487 bool RenderText::MoveCursorTo(const Point& point, bool select) {
488   SelectionModel position = FindCursorPosition(point);
489   if (select)
490     position.set_selection_start(selection().start());
491   return MoveCursorTo(position);
492 }
493 
SelectRange(const Range & range)494 bool RenderText::SelectRange(const Range& range) {
495   Range sel(std::min(range.start(), text().length()),
496             std::min(range.end(), text().length()));
497   if (!IsCursorablePosition(sel.start()) || !IsCursorablePosition(sel.end()))
498     return false;
499   LogicalCursorDirection affinity =
500       (sel.is_reversed() || sel.is_empty()) ? CURSOR_FORWARD : CURSOR_BACKWARD;
501   SetSelectionModel(SelectionModel(sel, affinity));
502   return true;
503 }
504 
IsPointInSelection(const Point & point)505 bool RenderText::IsPointInSelection(const Point& point) {
506   if (selection().is_empty())
507     return false;
508   SelectionModel cursor = FindCursorPosition(point);
509   return RangeContainsCaret(
510       selection(), cursor.caret_pos(), cursor.caret_affinity());
511 }
512 
ClearSelection()513 void RenderText::ClearSelection() {
514   SetSelectionModel(SelectionModel(cursor_position(),
515                                    selection_model_.caret_affinity()));
516 }
517 
SelectAll(bool reversed)518 void RenderText::SelectAll(bool reversed) {
519   const size_t length = text().length();
520   const Range all = reversed ? Range(length, 0) : Range(0, length);
521   const bool success = SelectRange(all);
522   DCHECK(success);
523 }
524 
SelectWord()525 void RenderText::SelectWord() {
526   if (obscured_) {
527     SelectAll(false);
528     return;
529   }
530 
531   size_t selection_max = selection().GetMax();
532 
533   base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD);
534   bool success = iter.Init();
535   DCHECK(success);
536   if (!success)
537     return;
538 
539   size_t selection_min = selection().GetMin();
540   if (selection_min == text().length() && selection_min != 0)
541     --selection_min;
542 
543   for (; selection_min != 0; --selection_min) {
544     if (iter.IsStartOfWord(selection_min) ||
545         iter.IsEndOfWord(selection_min))
546       break;
547   }
548 
549   if (selection_min == selection_max && selection_max != text().length())
550     ++selection_max;
551 
552   for (; selection_max < text().length(); ++selection_max)
553     if (iter.IsEndOfWord(selection_max) || iter.IsStartOfWord(selection_max))
554       break;
555 
556   const bool reversed = selection().is_reversed();
557   MoveCursorTo(reversed ? selection_max : selection_min, false);
558   MoveCursorTo(reversed ? selection_min : selection_max, true);
559 }
560 
GetCompositionRange() const561 const Range& RenderText::GetCompositionRange() const {
562   return composition_range_;
563 }
564 
SetCompositionRange(const Range & composition_range)565 void RenderText::SetCompositionRange(const Range& composition_range) {
566   CHECK(!composition_range.IsValid() ||
567         Range(0, text_.length()).Contains(composition_range));
568   composition_range_.set_end(composition_range.end());
569   composition_range_.set_start(composition_range.start());
570   ResetLayout();
571 }
572 
SetColor(SkColor value)573 void RenderText::SetColor(SkColor value) {
574   colors_.SetValue(value);
575 
576 #if defined(OS_WIN)
577   // TODO(msw): Windows applies colors and decorations in the layout process.
578   cached_bounds_and_offset_valid_ = false;
579   ResetLayout();
580 #endif
581 }
582 
ApplyColor(SkColor value,const Range & range)583 void RenderText::ApplyColor(SkColor value, const Range& range) {
584   colors_.ApplyValue(value, range);
585 
586 #if defined(OS_WIN)
587   // TODO(msw): Windows applies colors and decorations in the layout process.
588   cached_bounds_and_offset_valid_ = false;
589   ResetLayout();
590 #endif
591 }
592 
SetStyle(TextStyle style,bool value)593 void RenderText::SetStyle(TextStyle style, bool value) {
594   styles_[style].SetValue(value);
595 
596   // Only invalidate the layout on font changes; not for colors or decorations.
597   bool invalidate = (style == BOLD) || (style == ITALIC);
598 #if defined(OS_WIN)
599   // TODO(msw): Windows applies colors and decorations in the layout process.
600   invalidate = true;
601 #endif
602   if (invalidate) {
603     cached_bounds_and_offset_valid_ = false;
604     ResetLayout();
605   }
606 }
607 
ApplyStyle(TextStyle style,bool value,const Range & range)608 void RenderText::ApplyStyle(TextStyle style, bool value, const Range& range) {
609   styles_[style].ApplyValue(value, range);
610 
611   // Only invalidate the layout on font changes; not for colors or decorations.
612   bool invalidate = (style == BOLD) || (style == ITALIC);
613 #if defined(OS_WIN)
614   // TODO(msw): Windows applies colors and decorations in the layout process.
615   invalidate = true;
616 #endif
617   if (invalidate) {
618     cached_bounds_and_offset_valid_ = false;
619     ResetLayout();
620   }
621 }
622 
GetStyle(TextStyle style) const623 bool RenderText::GetStyle(TextStyle style) const {
624   return (styles_[style].breaks().size() == 1) &&
625       styles_[style].breaks().front().second;
626 }
627 
SetDirectionalityMode(DirectionalityMode mode)628 void RenderText::SetDirectionalityMode(DirectionalityMode mode) {
629   if (mode == directionality_mode_)
630     return;
631 
632   directionality_mode_ = mode;
633   text_direction_ = base::i18n::UNKNOWN_DIRECTION;
634   cached_bounds_and_offset_valid_ = false;
635   ResetLayout();
636 }
637 
GetTextDirection()638 base::i18n::TextDirection RenderText::GetTextDirection() {
639   if (text_direction_ == base::i18n::UNKNOWN_DIRECTION) {
640     switch (directionality_mode_) {
641       case DIRECTIONALITY_FROM_TEXT:
642         // Derive the direction from the display text, which differs from text()
643         // in the case of obscured (password) textfields.
644         text_direction_ =
645             base::i18n::GetFirstStrongCharacterDirection(GetLayoutText());
646         break;
647       case DIRECTIONALITY_FROM_UI:
648         text_direction_ = base::i18n::IsRTL() ? base::i18n::RIGHT_TO_LEFT :
649                                                 base::i18n::LEFT_TO_RIGHT;
650         break;
651       case DIRECTIONALITY_FORCE_LTR:
652         text_direction_ = base::i18n::LEFT_TO_RIGHT;
653         break;
654       case DIRECTIONALITY_FORCE_RTL:
655         text_direction_ = base::i18n::RIGHT_TO_LEFT;
656         break;
657       default:
658         NOTREACHED();
659     }
660   }
661 
662   return text_direction_;
663 }
664 
GetVisualDirectionOfLogicalEnd()665 VisualCursorDirection RenderText::GetVisualDirectionOfLogicalEnd() {
666   return GetTextDirection() == base::i18n::LEFT_TO_RIGHT ?
667       CURSOR_RIGHT : CURSOR_LEFT;
668 }
669 
GetStringSizeF()670 SizeF RenderText::GetStringSizeF() {
671   const Size size = GetStringSize();
672   return SizeF(size.width(), size.height());
673 }
674 
GetContentWidth()675 int RenderText::GetContentWidth() {
676   return GetStringSize().width() + (cursor_enabled_ ? 1 : 0);
677 }
678 
GetBaseline()679 int RenderText::GetBaseline() {
680   if (baseline_ == kInvalidBaseline)
681     baseline_ = DetermineBaselineCenteringText(display_rect(), font_list());
682   DCHECK_NE(kInvalidBaseline, baseline_);
683   return baseline_;
684 }
685 
Draw(Canvas * canvas)686 void RenderText::Draw(Canvas* canvas) {
687   EnsureLayout();
688 
689   if (clip_to_display_rect()) {
690     Rect clip_rect(display_rect());
691     clip_rect.Inset(ShadowValue::GetMargin(text_shadows_));
692 
693     canvas->Save();
694     canvas->ClipRect(clip_rect);
695   }
696 
697   if (!text().empty() && focused())
698     DrawSelection(canvas);
699 
700   if (cursor_enabled() && cursor_visible() && focused())
701     DrawCursor(canvas, selection_model_);
702 
703   if (!text().empty())
704     DrawVisualText(canvas);
705 
706   if (clip_to_display_rect())
707     canvas->Restore();
708 }
709 
DrawCursor(Canvas * canvas,const SelectionModel & position)710 void RenderText::DrawCursor(Canvas* canvas, const SelectionModel& position) {
711   // Paint cursor. Replace cursor is drawn as rectangle for now.
712   // TODO(msw): Draw a better cursor with a better indication of association.
713   canvas->FillRect(GetCursorBounds(position, true), cursor_color_);
714 }
715 
DrawSelectedTextForDrag(Canvas * canvas)716 void RenderText::DrawSelectedTextForDrag(Canvas* canvas) {
717   EnsureLayout();
718   const std::vector<Rect> sel = GetSubstringBounds(selection());
719 
720   // Override the selection color with black, and force the background to be
721   // transparent so that it's rendered without subpixel antialiasing.
722   const bool saved_background_is_transparent = background_is_transparent();
723   const SkColor saved_selection_color = selection_color();
724   set_background_is_transparent(true);
725   set_selection_color(SK_ColorBLACK);
726 
727   for (size_t i = 0; i < sel.size(); ++i) {
728     canvas->Save();
729     canvas->ClipRect(sel[i]);
730     DrawVisualText(canvas);
731     canvas->Restore();
732   }
733 
734   // Restore saved transparency and selection color.
735   set_selection_color(saved_selection_color);
736   set_background_is_transparent(saved_background_is_transparent);
737 }
738 
GetCursorBounds(const SelectionModel & caret,bool insert_mode)739 Rect RenderText::GetCursorBounds(const SelectionModel& caret,
740                                  bool insert_mode) {
741   // TODO(ckocagil): Support multiline. This function should return the height
742   //                 of the line the cursor is on. |GetStringSize()| now returns
743   //                 the multiline size, eliminate its use here.
744 
745   EnsureLayout();
746 
747   size_t caret_pos = caret.caret_pos();
748   DCHECK(IsCursorablePosition(caret_pos));
749   // In overtype mode, ignore the affinity and always indicate that we will
750   // overtype the next character.
751   LogicalCursorDirection caret_affinity =
752       insert_mode ? caret.caret_affinity() : CURSOR_FORWARD;
753   int x = 0, width = 1;
754   Size size = GetStringSize();
755   if (caret_pos == (caret_affinity == CURSOR_BACKWARD ? 0 : text().length())) {
756     // The caret is attached to the boundary. Always return a 1-dip width caret,
757     // since there is nothing to overtype.
758     if ((GetTextDirection() == base::i18n::RIGHT_TO_LEFT) == (caret_pos == 0))
759       x = size.width();
760   } else {
761     size_t grapheme_start = (caret_affinity == CURSOR_FORWARD) ?
762         caret_pos : IndexOfAdjacentGrapheme(caret_pos, CURSOR_BACKWARD);
763     Range xspan(GetGlyphBounds(grapheme_start));
764     if (insert_mode) {
765       x = (caret_affinity == CURSOR_BACKWARD) ? xspan.end() : xspan.start();
766     } else {  // overtype mode
767       x = xspan.GetMin();
768       width = xspan.length();
769     }
770   }
771   return Rect(ToViewPoint(Point(x, 0)), Size(width, size.height()));
772 }
773 
GetUpdatedCursorBounds()774 const Rect& RenderText::GetUpdatedCursorBounds() {
775   UpdateCachedBoundsAndOffset();
776   return cursor_bounds_;
777 }
778 
IndexOfAdjacentGrapheme(size_t index,LogicalCursorDirection direction)779 size_t RenderText::IndexOfAdjacentGrapheme(size_t index,
780                                            LogicalCursorDirection direction) {
781   if (index > text().length())
782     return text().length();
783 
784   EnsureLayout();
785 
786   if (direction == CURSOR_FORWARD) {
787     while (index < text().length()) {
788       index++;
789       if (IsCursorablePosition(index))
790         return index;
791     }
792     return text().length();
793   }
794 
795   while (index > 0) {
796     index--;
797     if (IsCursorablePosition(index))
798       return index;
799   }
800   return 0;
801 }
802 
GetSelectionModelForSelectionStart()803 SelectionModel RenderText::GetSelectionModelForSelectionStart() {
804   const Range& sel = selection();
805   if (sel.is_empty())
806     return selection_model_;
807   return SelectionModel(sel.start(),
808                         sel.is_reversed() ? CURSOR_BACKWARD : CURSOR_FORWARD);
809 }
810 
SetTextShadows(const ShadowValues & shadows)811 void RenderText::SetTextShadows(const ShadowValues& shadows) {
812   text_shadows_ = shadows;
813 }
814 
RenderText()815 RenderText::RenderText()
816     : horizontal_alignment_(base::i18n::IsRTL() ? ALIGN_RIGHT : ALIGN_LEFT),
817       directionality_mode_(DIRECTIONALITY_FROM_TEXT),
818       text_direction_(base::i18n::UNKNOWN_DIRECTION),
819       cursor_enabled_(true),
820       cursor_visible_(false),
821       insert_mode_(true),
822       cursor_color_(kDefaultColor),
823       selection_color_(kDefaultColor),
824       selection_background_focused_color_(kDefaultSelectionBackgroundColor),
825       focused_(false),
826       composition_range_(Range::InvalidRange()),
827       colors_(kDefaultColor),
828       styles_(NUM_TEXT_STYLES),
829       composition_and_selection_styles_applied_(false),
830       obscured_(false),
831       obscured_reveal_index_(-1),
832       truncate_length_(0),
833       multiline_(false),
834       fade_head_(false),
835       fade_tail_(false),
836       background_is_transparent_(false),
837       clip_to_display_rect_(true),
838       baseline_(kInvalidBaseline),
839       cached_bounds_and_offset_valid_(false) {
840 }
841 
GetUpdatedDisplayOffset()842 const Vector2d& RenderText::GetUpdatedDisplayOffset() {
843   UpdateCachedBoundsAndOffset();
844   return display_offset_;
845 }
846 
GetAdjacentSelectionModel(const SelectionModel & current,BreakType break_type,VisualCursorDirection direction)847 SelectionModel RenderText::GetAdjacentSelectionModel(
848     const SelectionModel& current,
849     BreakType break_type,
850     VisualCursorDirection direction) {
851   EnsureLayout();
852 
853   if (break_type == LINE_BREAK || text().empty())
854     return EdgeSelectionModel(direction);
855   if (break_type == CHARACTER_BREAK)
856     return AdjacentCharSelectionModel(current, direction);
857   DCHECK(break_type == WORD_BREAK);
858   return AdjacentWordSelectionModel(current, direction);
859 }
860 
EdgeSelectionModel(VisualCursorDirection direction)861 SelectionModel RenderText::EdgeSelectionModel(
862     VisualCursorDirection direction) {
863   if (direction == GetVisualDirectionOfLogicalEnd())
864     return SelectionModel(text().length(), CURSOR_FORWARD);
865   return SelectionModel(0, CURSOR_BACKWARD);
866 }
867 
SetSelectionModel(const SelectionModel & model)868 void RenderText::SetSelectionModel(const SelectionModel& model) {
869   DCHECK_LE(model.selection().GetMax(), text().length());
870   selection_model_ = model;
871   cached_bounds_and_offset_valid_ = false;
872 }
873 
GetLayoutText() const874 const base::string16& RenderText::GetLayoutText() const {
875   return layout_text_.empty() ? text_ : layout_text_;
876 }
877 
GetLineBreaks()878 const BreakList<size_t>& RenderText::GetLineBreaks() {
879   if (line_breaks_.max() != 0)
880     return line_breaks_;
881 
882   const base::string16& layout_text = GetLayoutText();
883   const size_t text_length = layout_text.length();
884   line_breaks_.SetValue(0);
885   line_breaks_.SetMax(text_length);
886   base::i18n::BreakIterator iter(layout_text,
887                                  base::i18n::BreakIterator::BREAK_LINE);
888   const bool success = iter.Init();
889   DCHECK(success);
890   if (success) {
891     do {
892       line_breaks_.ApplyValue(iter.pos(), Range(iter.pos(), text_length));
893     } while (iter.Advance());
894   }
895   return line_breaks_;
896 }
897 
ApplyCompositionAndSelectionStyles()898 void RenderText::ApplyCompositionAndSelectionStyles() {
899   // Save the underline and color breaks to undo the temporary styles later.
900   DCHECK(!composition_and_selection_styles_applied_);
901   saved_colors_ = colors_;
902   saved_underlines_ = styles_[UNDERLINE];
903 
904   // Apply an underline to the composition range in |underlines|.
905   if (composition_range_.IsValid() && !composition_range_.is_empty())
906     styles_[UNDERLINE].ApplyValue(true, composition_range_);
907 
908   // Apply the selected text color to the [un-reversed] selection range.
909   if (!selection().is_empty() && focused()) {
910     const Range range(selection().GetMin(), selection().GetMax());
911     colors_.ApplyValue(selection_color_, range);
912   }
913   composition_and_selection_styles_applied_ = true;
914 }
915 
UndoCompositionAndSelectionStyles()916 void RenderText::UndoCompositionAndSelectionStyles() {
917   // Restore the underline and color breaks to undo the temporary styles.
918   DCHECK(composition_and_selection_styles_applied_);
919   colors_ = saved_colors_;
920   styles_[UNDERLINE] = saved_underlines_;
921   composition_and_selection_styles_applied_ = false;
922 }
923 
GetLineOffset(size_t line_number)924 Vector2d RenderText::GetLineOffset(size_t line_number) {
925   Vector2d offset = display_rect().OffsetFromOrigin();
926   // TODO(ckocagil): Apply the display offset for multiline scrolling.
927   if (!multiline())
928     offset.Add(GetUpdatedDisplayOffset());
929   else
930     offset.Add(Vector2d(0, lines_[line_number].preceding_heights));
931   offset.Add(GetAlignmentOffset(line_number));
932   return offset;
933 }
934 
ToTextPoint(const Point & point)935 Point RenderText::ToTextPoint(const Point& point) {
936   return point - GetLineOffset(0);
937   // TODO(ckocagil): Convert multiline view space points to text space.
938 }
939 
ToViewPoint(const Point & point)940 Point RenderText::ToViewPoint(const Point& point) {
941   if (!multiline())
942     return point + GetLineOffset(0);
943 
944   // TODO(ckocagil): Traverse individual line segments for RTL support.
945   DCHECK(!lines_.empty());
946   int x = point.x();
947   size_t line = 0;
948   for (; line < lines_.size() && x > lines_[line].size.width(); ++line)
949     x -= lines_[line].size.width();
950   return Point(x, point.y()) + GetLineOffset(line);
951 }
952 
TextBoundsToViewBounds(const Range & x)953 std::vector<Rect> RenderText::TextBoundsToViewBounds(const Range& x) {
954   std::vector<Rect> rects;
955 
956   if (!multiline()) {
957     rects.push_back(Rect(ToViewPoint(Point(x.GetMin(), 0)),
958                          Size(x.length(), GetStringSize().height())));
959     return rects;
960   }
961 
962   EnsureLayout();
963 
964   // Each line segment keeps its position in text coordinates. Traverse all line
965   // segments and if the segment intersects with the given range, add the view
966   // rect corresponding to the intersection to |rects|.
967   for (size_t line = 0; line < lines_.size(); ++line) {
968     int line_x = 0;
969     const Vector2d offset = GetLineOffset(line);
970     for (size_t i = 0; i < lines_[line].segments.size(); ++i) {
971       const internal::LineSegment* segment = &lines_[line].segments[i];
972       const Range intersection = segment->x_range.Intersect(x);
973       if (!intersection.is_empty()) {
974         Rect rect(line_x + intersection.start() - segment->x_range.start(),
975                   0, intersection.length(), lines_[line].size.height());
976         rects.push_back(rect + offset);
977       }
978       line_x += segment->x_range.length();
979     }
980   }
981 
982   return rects;
983 }
984 
GetAlignmentOffset(size_t line_number)985 Vector2d RenderText::GetAlignmentOffset(size_t line_number) {
986   // TODO(ckocagil): Enable |lines_| usage in other platforms.
987 #if defined(OS_WIN)
988   DCHECK_LT(line_number, lines_.size());
989 #endif
990   Vector2d offset;
991   if (horizontal_alignment_ != ALIGN_LEFT) {
992 #if defined(OS_WIN)
993     const int width = lines_[line_number].size.width() +
994         (cursor_enabled_ ? 1 : 0);
995 #else
996     const int width = GetContentWidth();
997 #endif
998     offset.set_x(display_rect().width() - width);
999     if (horizontal_alignment_ == ALIGN_CENTER)
1000       offset.set_x(offset.x() / 2);
1001   }
1002 
1003   // Vertically center the text.
1004   if (multiline_) {
1005     const int text_height = lines_.back().preceding_heights +
1006         lines_.back().size.height();
1007     offset.set_y((display_rect_.height() - text_height) / 2);
1008   } else {
1009     offset.set_y(GetBaseline() - GetLayoutTextBaseline());
1010   }
1011 
1012   return offset;
1013 }
1014 
ApplyFadeEffects(internal::SkiaTextRenderer * renderer)1015 void RenderText::ApplyFadeEffects(internal::SkiaTextRenderer* renderer) {
1016   if (multiline() || (!fade_head() && !fade_tail()))
1017     return;
1018 
1019   const int display_width = display_rect().width();
1020 
1021   // If the text fits as-is, no need to fade.
1022   if (GetStringSize().width() <= display_width)
1023     return;
1024 
1025   int gradient_width = CalculateFadeGradientWidth(GetPrimaryFont(),
1026                                                   display_width);
1027   if (gradient_width == 0)
1028     return;
1029 
1030   bool fade_left = fade_head();
1031   bool fade_right = fade_tail();
1032   // Under RTL, |fade_right| == |fade_head|.
1033   // TODO(asvitkine): This is currently not based on GetTextDirection() because
1034   //                  RenderTextWin does not return a direction that's based on
1035   //                  the text content.
1036   if (horizontal_alignment_ == ALIGN_RIGHT)
1037     std::swap(fade_left, fade_right);
1038 
1039   Rect solid_part = display_rect();
1040   Rect left_part;
1041   Rect right_part;
1042   if (fade_left) {
1043     left_part = solid_part;
1044     left_part.Inset(0, 0, solid_part.width() - gradient_width, 0);
1045     solid_part.Inset(gradient_width, 0, 0, 0);
1046   }
1047   if (fade_right) {
1048     right_part = solid_part;
1049     right_part.Inset(solid_part.width() - gradient_width, 0, 0, 0);
1050     solid_part.Inset(0, 0, gradient_width, 0);
1051   }
1052 
1053   Rect text_rect = display_rect();
1054   text_rect.Inset(GetAlignmentOffset(0).x(), 0, 0, 0);
1055 
1056   // TODO(msw): Use the actual text colors corresponding to each faded part.
1057   skia::RefPtr<SkShader> shader = CreateFadeShader(
1058       text_rect, left_part, right_part, colors_.breaks().front().second);
1059   if (shader)
1060     renderer->SetShader(shader.get(), display_rect());
1061 }
1062 
ApplyTextShadows(internal::SkiaTextRenderer * renderer)1063 void RenderText::ApplyTextShadows(internal::SkiaTextRenderer* renderer) {
1064   skia::RefPtr<SkDrawLooper> looper = CreateShadowDrawLooper(text_shadows_);
1065   renderer->SetDrawLooper(looper.get());
1066 }
1067 
1068 // static
RangeContainsCaret(const Range & range,size_t caret_pos,LogicalCursorDirection caret_affinity)1069 bool RenderText::RangeContainsCaret(const Range& range,
1070                                     size_t caret_pos,
1071                                     LogicalCursorDirection caret_affinity) {
1072   // NB: exploits unsigned wraparound (WG14/N1124 section 6.2.5 paragraph 9).
1073   size_t adjacent = (caret_affinity == CURSOR_BACKWARD) ?
1074       caret_pos - 1 : caret_pos + 1;
1075   return range.Contains(Range(caret_pos, adjacent));
1076 }
1077 
MoveCursorTo(size_t position,bool select)1078 void RenderText::MoveCursorTo(size_t position, bool select) {
1079   size_t cursor = std::min(position, text().length());
1080   if (IsCursorablePosition(cursor))
1081     SetSelectionModel(SelectionModel(
1082         Range(select ? selection().start() : cursor, cursor),
1083         (cursor == 0) ? CURSOR_FORWARD : CURSOR_BACKWARD));
1084 }
1085 
UpdateLayoutText()1086 void RenderText::UpdateLayoutText() {
1087   layout_text_.clear();
1088   line_breaks_.SetMax(0);
1089 
1090   if (obscured_) {
1091     size_t obscured_text_length =
1092         static_cast<size_t>(gfx::UTF16IndexToOffset(text_, 0, text_.length()));
1093     layout_text_.assign(obscured_text_length, kPasswordReplacementChar);
1094 
1095     if (obscured_reveal_index_ >= 0 &&
1096         obscured_reveal_index_ < static_cast<int>(text_.length())) {
1097       // Gets the index range in |text_| to be revealed.
1098       size_t start = obscured_reveal_index_;
1099       U16_SET_CP_START(text_.data(), 0, start);
1100       size_t end = start;
1101       UChar32 unused_char;
1102       U16_NEXT(text_.data(), end, text_.length(), unused_char);
1103 
1104       // Gets the index in |layout_text_| to be replaced.
1105       const size_t cp_start =
1106           static_cast<size_t>(gfx::UTF16IndexToOffset(text_, 0, start));
1107       if (layout_text_.length() > cp_start)
1108         layout_text_.replace(cp_start, 1, text_.substr(start, end - start));
1109     }
1110   }
1111 
1112   const base::string16& text = obscured_ ? layout_text_ : text_;
1113   if (truncate_length_ > 0 && truncate_length_ < text.length()) {
1114     // Truncate the text at a valid character break and append an ellipsis.
1115     icu::StringCharacterIterator iter(text.c_str());
1116     iter.setIndex32(truncate_length_ - 1);
1117     layout_text_.assign(text.substr(0, iter.getIndex()) + gfx::kEllipsisUTF16);
1118   }
1119 }
1120 
UpdateCachedBoundsAndOffset()1121 void RenderText::UpdateCachedBoundsAndOffset() {
1122   if (cached_bounds_and_offset_valid_)
1123     return;
1124 
1125   // TODO(ckocagil): Add support for scrolling multiline text.
1126 
1127   // First, set the valid flag true to calculate the current cursor bounds using
1128   // the stale |display_offset_|. Applying |delta_offset| at the end of this
1129   // function will set |cursor_bounds_| and |display_offset_| to correct values.
1130   cached_bounds_and_offset_valid_ = true;
1131   cursor_bounds_ = GetCursorBounds(selection_model_, insert_mode_);
1132 
1133   // Update |display_offset_| to ensure the current cursor is visible.
1134   const int display_width = display_rect_.width();
1135   const int content_width = GetContentWidth();
1136 
1137   int delta_x = 0;
1138   if (content_width <= display_width || !cursor_enabled()) {
1139     // Don't pan if the text fits in the display width or when the cursor is
1140     // disabled.
1141     delta_x = -display_offset_.x();
1142   } else if (cursor_bounds_.right() > display_rect_.right()) {
1143     // TODO(xji): when the character overflow is a RTL character, currently, if
1144     // we pan cursor at the rightmost position, the entered RTL character is not
1145     // displayed. Should pan cursor to show the last logical characters.
1146     //
1147     // Pan to show the cursor when it overflows to the right.
1148     delta_x = display_rect_.right() - cursor_bounds_.right();
1149   } else if (cursor_bounds_.x() < display_rect_.x()) {
1150     // TODO(xji): have similar problem as above when overflow character is a
1151     // LTR character.
1152     //
1153     // Pan to show the cursor when it overflows to the left.
1154     delta_x = display_rect_.x() - cursor_bounds_.x();
1155   } else if (display_offset_.x() != 0) {
1156     // Reduce the pan offset to show additional overflow text when the display
1157     // width increases.
1158     const int negate_rtl = horizontal_alignment_ == ALIGN_RIGHT ? -1 : 1;
1159     const int offset = negate_rtl * display_offset_.x();
1160     if (display_width > (content_width + offset)) {
1161       delta_x = negate_rtl * (display_width - (content_width + offset));
1162     }
1163   }
1164 
1165   Vector2d delta_offset(delta_x, 0);
1166   display_offset_ += delta_offset;
1167   cursor_bounds_ += delta_offset;
1168 }
1169 
DrawSelection(Canvas * canvas)1170 void RenderText::DrawSelection(Canvas* canvas) {
1171   const std::vector<Rect> sel = GetSubstringBounds(selection());
1172   for (std::vector<Rect>::const_iterator i = sel.begin(); i < sel.end(); ++i)
1173     canvas->FillRect(*i, selection_background_focused_color_);
1174 }
1175 
1176 }  // namespace gfx
1177