Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / ui / gfx / render_text.cc
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "ui/gfx/render_text.h"
6
7 #include <algorithm>
8 #include <climits>
9
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/string_util.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "third_party/icu/source/common/unicode/rbbi.h"
17 #include "third_party/icu/source/common/unicode/utf16.h"
18 #include "third_party/skia/include/core/SkTypeface.h"
19 #include "third_party/skia/include/effects/SkGradientShader.h"
20 #include "ui/gfx/canvas.h"
21 #include "ui/gfx/geometry/safe_integer_conversions.h"
22 #include "ui/gfx/insets.h"
23 #include "ui/gfx/render_text_harfbuzz.h"
24 #include "ui/gfx/scoped_canvas.h"
25 #include "ui/gfx/skia_util.h"
26 #include "ui/gfx/switches.h"
27 #include "ui/gfx/text_elider.h"
28 #include "ui/gfx/text_utils.h"
29 #include "ui/gfx/utf16_indexing.h"
30
31 namespace gfx {
32
33 namespace {
34
35 // All chars are replaced by this char when the password style is set.
36 // TODO(benrg): GTK uses the first of U+25CF, U+2022, U+2731, U+273A, '*'
37 // that's available in the font (find_invisible_char() in gtkentry.c).
38 const base::char16 kPasswordReplacementChar = '*';
39
40 // Default color used for the text and cursor.
41 const SkColor kDefaultColor = SK_ColorBLACK;
42
43 // Default color used for drawing selection background.
44 const SkColor kDefaultSelectionBackgroundColor = SK_ColorGRAY;
45
46 // Fraction of the text size to lower a strike through below the baseline.
47 const SkScalar kStrikeThroughOffset = (-SK_Scalar1 * 6 / 21);
48 // Fraction of the text size to lower an underline below the baseline.
49 const SkScalar kUnderlineOffset = (SK_Scalar1 / 9);
50 // Fraction of the text size to use for a strike through or under-line.
51 const SkScalar kLineThickness = (SK_Scalar1 / 18);
52 // Fraction of the text size to use for a top margin of a diagonal strike.
53 const SkScalar kDiagonalStrikeMarginOffset = (SK_Scalar1 / 4);
54
55 // Invalid value of baseline.  Assigning this value to |baseline_| causes
56 // re-calculation of baseline.
57 const int kInvalidBaseline = INT_MAX;
58
59 // Returns the baseline, with which the text best appears vertically centered.
60 int DetermineBaselineCenteringText(const Rect& display_rect,
61                                    const FontList& font_list) {
62   const int display_height = display_rect.height();
63   const int font_height = font_list.GetHeight();
64   // Lower and upper bound of baseline shift as we try to show as much area of
65   // text as possible.  In particular case of |display_height| == |font_height|,
66   // we do not want to shift the baseline.
67   const int min_shift = std::min(0, display_height - font_height);
68   const int max_shift = std::abs(display_height - font_height);
69   const int baseline = font_list.GetBaseline();
70   const int cap_height = font_list.GetCapHeight();
71   const int internal_leading = baseline - cap_height;
72   // Some platforms don't support getting the cap height, and simply return
73   // the entire font ascent from GetCapHeight().  Centering the ascent makes
74   // the font look too low, so if GetCapHeight() returns the ascent, center
75   // the entire font height instead.
76   const int space =
77       display_height - ((internal_leading != 0) ? cap_height : font_height);
78   const int baseline_shift = space / 2 - internal_leading;
79   return baseline + std::max(min_shift, std::min(max_shift, baseline_shift));
80 }
81
82 // Converts |Font::FontStyle| flags to |SkTypeface::Style| flags.
83 SkTypeface::Style ConvertFontStyleToSkiaTypefaceStyle(int font_style) {
84   int skia_style = SkTypeface::kNormal;
85   skia_style |= (font_style & Font::BOLD) ? SkTypeface::kBold : 0;
86   skia_style |= (font_style & Font::ITALIC) ? SkTypeface::kItalic : 0;
87   return static_cast<SkTypeface::Style>(skia_style);
88 }
89
90 // Given |font| and |display_width|, returns the width of the fade gradient.
91 int CalculateFadeGradientWidth(const FontList& font_list, int display_width) {
92   // Fade in/out about 2.5 characters of the beginning/end of the string.
93   // The .5 here is helpful if one of the characters is a space.
94   // Use a quarter of the display width if the display width is very short.
95   const int average_character_width = font_list.GetExpectedTextWidth(1);
96   const double gradient_width = std::min(average_character_width * 2.5,
97                                          display_width / 4.0);
98   DCHECK_GE(gradient_width, 0.0);
99   return static_cast<int>(floor(gradient_width + 0.5));
100 }
101
102 // Appends to |positions| and |colors| values corresponding to the fade over
103 // |fade_rect| from color |c0| to color |c1|.
104 void AddFadeEffect(const Rect& text_rect,
105                    const Rect& fade_rect,
106                    SkColor c0,
107                    SkColor c1,
108                    std::vector<SkScalar>* positions,
109                    std::vector<SkColor>* colors) {
110   const SkScalar left = static_cast<SkScalar>(fade_rect.x() - text_rect.x());
111   const SkScalar width = static_cast<SkScalar>(fade_rect.width());
112   const SkScalar p0 = left / text_rect.width();
113   const SkScalar p1 = (left + width) / text_rect.width();
114   // Prepend 0.0 to |positions|, as required by Skia.
115   if (positions->empty() && p0 != 0.0) {
116     positions->push_back(0.0);
117     colors->push_back(c0);
118   }
119   positions->push_back(p0);
120   colors->push_back(c0);
121   positions->push_back(p1);
122   colors->push_back(c1);
123 }
124
125 // Creates a SkShader to fade the text, with |left_part| specifying the left
126 // fade effect, if any, and |right_part| specifying the right fade effect.
127 skia::RefPtr<SkShader> CreateFadeShader(const Rect& text_rect,
128                                         const Rect& left_part,
129                                         const Rect& right_part,
130                                         SkColor color) {
131   // Fade alpha of 51/255 corresponds to a fade of 0.2 of the original color.
132   const SkColor fade_color = SkColorSetA(color, 51);
133   std::vector<SkScalar> positions;
134   std::vector<SkColor> colors;
135
136   if (!left_part.IsEmpty())
137     AddFadeEffect(text_rect, left_part, fade_color, color,
138                   &positions, &colors);
139   if (!right_part.IsEmpty())
140     AddFadeEffect(text_rect, right_part, color, fade_color,
141                   &positions, &colors);
142   DCHECK(!positions.empty());
143
144   // Terminate |positions| with 1.0, as required by Skia.
145   if (positions.back() != 1.0) {
146     positions.push_back(1.0);
147     colors.push_back(colors.back());
148   }
149
150   SkPoint points[2];
151   points[0].iset(text_rect.x(), text_rect.y());
152   points[1].iset(text_rect.right(), text_rect.y());
153
154   return skia::AdoptRef(
155       SkGradientShader::CreateLinear(&points[0], &colors[0], &positions[0],
156                                      colors.size(), SkShader::kClamp_TileMode));
157 }
158
159 // Converts a FontRenderParams::Hinting value to the corresponding
160 // SkPaint::Hinting value.
161 SkPaint::Hinting FontRenderParamsHintingToSkPaintHinting(
162     FontRenderParams::Hinting params_hinting) {
163   switch (params_hinting) {
164     case FontRenderParams::HINTING_NONE:   return SkPaint::kNo_Hinting;
165     case FontRenderParams::HINTING_SLIGHT: return SkPaint::kSlight_Hinting;
166     case FontRenderParams::HINTING_MEDIUM: return SkPaint::kNormal_Hinting;
167     case FontRenderParams::HINTING_FULL:   return SkPaint::kFull_Hinting;
168   }
169   return SkPaint::kNo_Hinting;
170 }
171
172 }  // namespace
173
174 namespace internal {
175
176 // Value of |underline_thickness_| that indicates that underline metrics have
177 // not been set explicitly.
178 const SkScalar kUnderlineMetricsNotSet = -1.0f;
179
180 SkiaTextRenderer::SkiaTextRenderer(Canvas* canvas)
181     : canvas_(canvas),
182       canvas_skia_(canvas->sk_canvas()),
183       underline_thickness_(kUnderlineMetricsNotSet),
184       underline_position_(0.0f) {
185   DCHECK(canvas_skia_);
186   paint_.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
187   paint_.setStyle(SkPaint::kFill_Style);
188   paint_.setAntiAlias(true);
189   paint_.setSubpixelText(true);
190   paint_.setLCDRenderText(true);
191   paint_.setHinting(SkPaint::kNormal_Hinting);
192 }
193
194 SkiaTextRenderer::~SkiaTextRenderer() {
195 }
196
197 void SkiaTextRenderer::SetDrawLooper(SkDrawLooper* draw_looper) {
198   paint_.setLooper(draw_looper);
199 }
200
201 void SkiaTextRenderer::SetFontRenderParams(const FontRenderParams& params,
202                                            bool background_is_transparent) {
203   ApplyRenderParams(params, background_is_transparent, &paint_);
204 }
205
206 void SkiaTextRenderer::SetTypeface(SkTypeface* typeface) {
207   paint_.setTypeface(typeface);
208 }
209
210 void SkiaTextRenderer::SetTextSize(SkScalar size) {
211   paint_.setTextSize(size);
212 }
213
214 void SkiaTextRenderer::SetFontFamilyWithStyle(const std::string& family,
215                                               int style) {
216   DCHECK(!family.empty());
217
218   skia::RefPtr<SkTypeface> typeface = CreateSkiaTypeface(family.c_str(), style);
219   if (typeface) {
220     // |paint_| adds its own ref. So don't |release()| it from the ref ptr here.
221     SetTypeface(typeface.get());
222
223     // Enable fake bold text if bold style is needed but new typeface does not
224     // have it.
225     paint_.setFakeBoldText((style & Font::BOLD) && !typeface->isBold());
226   }
227 }
228
229 void SkiaTextRenderer::SetForegroundColor(SkColor foreground) {
230   paint_.setColor(foreground);
231 }
232
233 void SkiaTextRenderer::SetShader(SkShader* shader) {
234   paint_.setShader(shader);
235 }
236
237 void SkiaTextRenderer::SetUnderlineMetrics(SkScalar thickness,
238                                            SkScalar position) {
239   underline_thickness_ = thickness;
240   underline_position_ = position;
241 }
242
243 void SkiaTextRenderer::DrawPosText(const SkPoint* pos,
244                                    const uint16* glyphs,
245                                    size_t glyph_count) {
246   const size_t byte_length = glyph_count * sizeof(glyphs[0]);
247   canvas_skia_->drawPosText(&glyphs[0], byte_length, &pos[0], paint_);
248 }
249
250 void SkiaTextRenderer::DrawDecorations(int x, int y, int width, bool underline,
251                                        bool strike, bool diagonal_strike) {
252   if (underline)
253     DrawUnderline(x, y, width);
254   if (strike)
255     DrawStrike(x, y, width);
256   if (diagonal_strike) {
257     if (!diagonal_)
258       diagonal_.reset(new DiagonalStrike(canvas_, Point(x, y), paint_));
259     diagonal_->AddPiece(width, paint_.getColor());
260   } else if (diagonal_) {
261     EndDiagonalStrike();
262   }
263 }
264
265 void SkiaTextRenderer::EndDiagonalStrike() {
266   if (diagonal_) {
267     diagonal_->Draw();
268     diagonal_.reset();
269   }
270 }
271
272 void SkiaTextRenderer::DrawUnderline(int x, int y, int width) {
273   SkScalar x_scalar = SkIntToScalar(x);
274   SkRect r = SkRect::MakeLTRB(
275       x_scalar, y + underline_position_, x_scalar + width,
276       y + underline_position_ + underline_thickness_);
277   if (underline_thickness_ == kUnderlineMetricsNotSet) {
278     const SkScalar text_size = paint_.getTextSize();
279     r.fTop = SkScalarMulAdd(text_size, kUnderlineOffset, y);
280     r.fBottom = r.fTop + SkScalarMul(text_size, kLineThickness);
281   }
282   canvas_skia_->drawRect(r, paint_);
283 }
284
285 void SkiaTextRenderer::DrawStrike(int x, int y, int width) const {
286   const SkScalar text_size = paint_.getTextSize();
287   const SkScalar height = SkScalarMul(text_size, kLineThickness);
288   const SkScalar offset = SkScalarMulAdd(text_size, kStrikeThroughOffset, y);
289   SkScalar x_scalar = SkIntToScalar(x);
290   const SkRect r =
291       SkRect::MakeLTRB(x_scalar, offset, x_scalar + width, offset + height);
292   canvas_skia_->drawRect(r, paint_);
293 }
294
295 SkiaTextRenderer::DiagonalStrike::DiagonalStrike(Canvas* canvas,
296                                                  Point start,
297                                                  const SkPaint& paint)
298     : canvas_(canvas),
299       start_(start),
300       paint_(paint),
301       total_length_(0) {
302 }
303
304 SkiaTextRenderer::DiagonalStrike::~DiagonalStrike() {
305 }
306
307 void SkiaTextRenderer::DiagonalStrike::AddPiece(int length, SkColor color) {
308   pieces_.push_back(Piece(length, color));
309   total_length_ += length;
310 }
311
312 void SkiaTextRenderer::DiagonalStrike::Draw() {
313   const SkScalar text_size = paint_.getTextSize();
314   const SkScalar offset = SkScalarMul(text_size, kDiagonalStrikeMarginOffset);
315   const int thickness =
316       SkScalarCeilToInt(SkScalarMul(text_size, kLineThickness) * 2);
317   const int height = SkScalarCeilToInt(text_size - offset);
318   const Point end = start_ + Vector2d(total_length_, -height);
319   const int clip_height = height + 2 * thickness;
320
321   paint_.setAntiAlias(true);
322   paint_.setStrokeWidth(SkIntToScalar(thickness));
323
324   const bool clipped = pieces_.size() > 1;
325   SkCanvas* sk_canvas = canvas_->sk_canvas();
326   int x = start_.x();
327
328   for (size_t i = 0; i < pieces_.size(); ++i) {
329     paint_.setColor(pieces_[i].second);
330
331     if (clipped) {
332       canvas_->Save();
333       sk_canvas->clipRect(RectToSkRect(
334           Rect(x, end.y() - thickness, pieces_[i].first, clip_height)));
335     }
336
337     canvas_->DrawLine(start_, end, paint_);
338
339     if (clipped)
340       canvas_->Restore();
341
342     x += pieces_[i].first;
343   }
344 }
345
346 StyleIterator::StyleIterator(const BreakList<SkColor>& colors,
347                              const std::vector<BreakList<bool> >& styles)
348     : colors_(colors),
349       styles_(styles) {
350   color_ = colors_.breaks().begin();
351   for (size_t i = 0; i < styles_.size(); ++i)
352     style_.push_back(styles_[i].breaks().begin());
353 }
354
355 StyleIterator::~StyleIterator() {}
356
357 Range StyleIterator::GetRange() const {
358   Range range(colors_.GetRange(color_));
359   for (size_t i = 0; i < NUM_TEXT_STYLES; ++i)
360     range = range.Intersect(styles_[i].GetRange(style_[i]));
361   return range;
362 }
363
364 void StyleIterator::UpdatePosition(size_t position) {
365   color_ = colors_.GetBreak(position);
366   for (size_t i = 0; i < NUM_TEXT_STYLES; ++i)
367     style_[i] = styles_[i].GetBreak(position);
368 }
369
370 LineSegment::LineSegment() : run(0) {}
371
372 LineSegment::~LineSegment() {}
373
374 Line::Line() : preceding_heights(0), baseline(0) {}
375
376 Line::~Line() {}
377
378 skia::RefPtr<SkTypeface> CreateSkiaTypeface(const std::string& family,
379                                             int style) {
380   SkTypeface::Style skia_style = ConvertFontStyleToSkiaTypefaceStyle(style);
381   return skia::AdoptRef(SkTypeface::CreateFromName(family.c_str(), skia_style));
382 }
383
384 void ApplyRenderParams(const FontRenderParams& params,
385                        bool background_is_transparent,
386                        SkPaint* paint) {
387   paint->setAntiAlias(params.antialiasing);
388   paint->setLCDRenderText(!background_is_transparent &&
389       params.subpixel_rendering != FontRenderParams::SUBPIXEL_RENDERING_NONE);
390   paint->setSubpixelText(params.subpixel_positioning);
391   paint->setAutohinted(params.autohinter);
392   paint->setHinting(FontRenderParamsHintingToSkPaintHinting(params.hinting));
393 }
394
395 }  // namespace internal
396
397 RenderText::~RenderText() {
398 }
399
400 RenderText* RenderText::CreateInstance() {
401 #if defined(OS_MACOSX) && !defined(TOOLKIT_VIEWS)
402   static const bool use_harfbuzz = CommandLine::ForCurrentProcess()->
403       HasSwitch(switches::kEnableHarfBuzzRenderText);
404 #else
405   static const bool use_harfbuzz = !CommandLine::ForCurrentProcess()->
406       HasSwitch(switches::kDisableHarfBuzzRenderText);
407 #endif
408   return use_harfbuzz ? new RenderTextHarfBuzz : CreateNativeInstance();
409 }
410
411 void RenderText::SetText(const base::string16& text) {
412   DCHECK(!composition_range_.IsValid());
413   if (text_ == text)
414     return;
415   text_ = text;
416
417   // Adjust ranged styles and colors to accommodate a new text length.
418   // Clear style ranges as they might break new text graphemes and apply
419   // the first style to the whole text instead.
420   const size_t text_length = text_.length();
421   colors_.SetMax(text_length);
422   for (size_t style = 0; style < NUM_TEXT_STYLES; ++style) {
423     BreakList<bool>& break_list = styles_[style];
424     break_list.SetValue(break_list.breaks().begin()->second);
425     break_list.SetMax(text_length);
426   }
427   cached_bounds_and_offset_valid_ = false;
428
429   // Reset selection model. SetText should always followed by SetSelectionModel
430   // or SetCursorPosition in upper layer.
431   SetSelectionModel(SelectionModel());
432
433   // Invalidate the cached text direction if it depends on the text contents.
434   if (directionality_mode_ == DIRECTIONALITY_FROM_TEXT)
435     text_direction_ = base::i18n::UNKNOWN_DIRECTION;
436
437   obscured_reveal_index_ = -1;
438   UpdateLayoutText();
439 }
440
441 void RenderText::SetHorizontalAlignment(HorizontalAlignment alignment) {
442   if (horizontal_alignment_ != alignment) {
443     horizontal_alignment_ = alignment;
444     display_offset_ = Vector2d();
445     cached_bounds_and_offset_valid_ = false;
446   }
447 }
448
449 void RenderText::SetFontList(const FontList& font_list) {
450   font_list_ = font_list;
451   const int font_style = font_list.GetFontStyle();
452   SetStyle(BOLD, (font_style & gfx::Font::BOLD) != 0);
453   SetStyle(ITALIC, (font_style & gfx::Font::ITALIC) != 0);
454   SetStyle(UNDERLINE, (font_style & gfx::Font::UNDERLINE) != 0);
455   baseline_ = kInvalidBaseline;
456   cached_bounds_and_offset_valid_ = false;
457   ResetLayout();
458 }
459
460 void RenderText::SetCursorEnabled(bool cursor_enabled) {
461   cursor_enabled_ = cursor_enabled;
462   cached_bounds_and_offset_valid_ = false;
463 }
464
465 void RenderText::ToggleInsertMode() {
466   insert_mode_ = !insert_mode_;
467   cached_bounds_and_offset_valid_ = false;
468 }
469
470 void RenderText::SetObscured(bool obscured) {
471   if (obscured != obscured_) {
472     obscured_ = obscured;
473     obscured_reveal_index_ = -1;
474     cached_bounds_and_offset_valid_ = false;
475     UpdateLayoutText();
476   }
477 }
478
479 void RenderText::SetObscuredRevealIndex(int index) {
480   if (obscured_reveal_index_ == index)
481     return;
482
483   obscured_reveal_index_ = index;
484   cached_bounds_and_offset_valid_ = false;
485   UpdateLayoutText();
486 }
487
488 void RenderText::SetReplaceNewlineCharsWithSymbols(bool replace) {
489   replace_newline_chars_with_symbols_ = replace;
490   cached_bounds_and_offset_valid_ = false;
491   UpdateLayoutText();
492 }
493
494 void RenderText::SetMultiline(bool multiline) {
495   if (multiline != multiline_) {
496     multiline_ = multiline;
497     cached_bounds_and_offset_valid_ = false;
498     lines_.clear();
499   }
500 }
501
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();
507   }
508 }
509
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_ != NO_ELIDE)
517       UpdateLayoutText();
518   }
519 }
520
521 void RenderText::SetCursorPosition(size_t position) {
522   MoveCursorTo(position, false);
523 }
524
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);
546   }
547   if (select)
548     cursor.set_selection_start(selection().start());
549   MoveCursorTo(cursor);
550 }
551
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;
564 }
565
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;
576 }
577
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());
584 }
585
586 void RenderText::ClearSelection() {
587   SetSelectionModel(SelectionModel(cursor_position(),
588                                    selection_model_.caret_affinity()));
589 }
590
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);
596 }
597
598 void RenderText::SelectWord() {
599   if (obscured_) {
600     SelectAll(false);
601     return;
602   }
603
604   size_t selection_max = selection().GetMax();
605
606   base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD);
607   bool success = iter.Init();
608   DCHECK(success);
609   if (!success)
610     return;
611
612   size_t selection_min = selection().GetMin();
613   if (selection_min == text().length() && selection_min != 0)
614     --selection_min;
615
616   for (; selection_min != 0; --selection_min) {
617     if (iter.IsStartOfWord(selection_min) ||
618         iter.IsEndOfWord(selection_min))
619       break;
620   }
621
622   if (selection_min == selection_max && selection_max != text().length())
623     ++selection_max;
624
625   for (; selection_max < text().length(); ++selection_max)
626     if (iter.IsEndOfWord(selection_max) || iter.IsStartOfWord(selection_max))
627       break;
628
629   const bool reversed = selection().is_reversed();
630   MoveCursorTo(reversed ? selection_max : selection_min, false);
631   MoveCursorTo(reversed ? selection_min : selection_max, true);
632 }
633
634 const Range& RenderText::GetCompositionRange() const {
635   return composition_range_;
636 }
637
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();
644 }
645
646 void RenderText::SetColor(SkColor value) {
647   colors_.SetValue(value);
648 }
649
650 void RenderText::ApplyColor(SkColor value, const Range& range) {
651   colors_.ApplyValue(value, range);
652 }
653
654 void RenderText::SetStyle(TextStyle style, bool value) {
655   styles_[style].SetValue(value);
656
657   cached_bounds_and_offset_valid_ = false;
658   ResetLayout();
659 }
660
661 void RenderText::ApplyStyle(TextStyle style, bool value, const Range& range) {
662   // Do not change styles mid-grapheme to avoid breaking ligatures.
663   const size_t start = IsValidCursorIndex(range.start()) ? range.start() :
664       IndexOfAdjacentGrapheme(range.start(), CURSOR_BACKWARD);
665   const size_t end = IsValidCursorIndex(range.end()) ? range.end() :
666       IndexOfAdjacentGrapheme(range.end(), CURSOR_FORWARD);
667   styles_[style].ApplyValue(value, Range(start, end));
668
669   cached_bounds_and_offset_valid_ = false;
670   ResetLayout();
671 }
672
673 bool RenderText::GetStyle(TextStyle style) const {
674   return (styles_[style].breaks().size() == 1) &&
675       styles_[style].breaks().front().second;
676 }
677
678 void RenderText::SetDirectionalityMode(DirectionalityMode mode) {
679   if (mode == directionality_mode_)
680     return;
681
682   directionality_mode_ = mode;
683   text_direction_ = base::i18n::UNKNOWN_DIRECTION;
684   cached_bounds_and_offset_valid_ = false;
685   ResetLayout();
686 }
687
688 base::i18n::TextDirection RenderText::GetTextDirection() {
689   if (text_direction_ == base::i18n::UNKNOWN_DIRECTION) {
690     switch (directionality_mode_) {
691       case DIRECTIONALITY_FROM_TEXT:
692         // Derive the direction from the display text, which differs from text()
693         // in the case of obscured (password) textfields.
694         text_direction_ =
695             base::i18n::GetFirstStrongCharacterDirection(GetLayoutText());
696         break;
697       case DIRECTIONALITY_FROM_UI:
698         text_direction_ = base::i18n::IsRTL() ? base::i18n::RIGHT_TO_LEFT :
699                                                 base::i18n::LEFT_TO_RIGHT;
700         break;
701       case DIRECTIONALITY_FORCE_LTR:
702         text_direction_ = base::i18n::LEFT_TO_RIGHT;
703         break;
704       case DIRECTIONALITY_FORCE_RTL:
705         text_direction_ = base::i18n::RIGHT_TO_LEFT;
706         break;
707       default:
708         NOTREACHED();
709     }
710   }
711
712   return text_direction_;
713 }
714
715 VisualCursorDirection RenderText::GetVisualDirectionOfLogicalEnd() {
716   return GetTextDirection() == base::i18n::LEFT_TO_RIGHT ?
717       CURSOR_RIGHT : CURSOR_LEFT;
718 }
719
720 SizeF RenderText::GetStringSizeF() {
721   return GetStringSize();
722 }
723
724 float RenderText::GetContentWidth() {
725   return GetStringSizeF().width() + (cursor_enabled_ ? 1 : 0);
726 }
727
728 int RenderText::GetBaseline() {
729   if (baseline_ == kInvalidBaseline)
730     baseline_ = DetermineBaselineCenteringText(display_rect(), font_list());
731   DCHECK_NE(kInvalidBaseline, baseline_);
732   return baseline_;
733 }
734
735 void RenderText::Draw(Canvas* canvas) {
736   EnsureLayout();
737
738   if (clip_to_display_rect()) {
739     Rect clip_rect(display_rect());
740     clip_rect.Inset(ShadowValue::GetMargin(shadows_));
741
742     canvas->Save();
743     canvas->ClipRect(clip_rect);
744   }
745
746   if (!text().empty() && focused())
747     DrawSelection(canvas);
748
749   if (cursor_enabled() && cursor_visible() && focused())
750     DrawCursor(canvas, selection_model_);
751
752   if (!text().empty())
753     DrawVisualText(canvas);
754
755   if (clip_to_display_rect())
756     canvas->Restore();
757 }
758
759 void RenderText::DrawCursor(Canvas* canvas, const SelectionModel& position) {
760   // Paint cursor. Replace cursor is drawn as rectangle for now.
761   // TODO(msw): Draw a better cursor with a better indication of association.
762   canvas->FillRect(GetCursorBounds(position, true), cursor_color_);
763 }
764
765 bool RenderText::IsValidLogicalIndex(size_t index) {
766   // Check that the index is at a valid code point (not mid-surrgate-pair) and
767   // that it's not truncated from the layout text (its glyph may be shown).
768   //
769   // Indices within truncated text are disallowed so users can easily interact
770   // with the underlying truncated text using the ellipsis as a proxy. This lets
771   // users select all text, select the truncated text, and transition from the
772   // last rendered glyph to the end of the text without getting invisible cursor
773   // positions nor needing unbounded arrow key presses to traverse the ellipsis.
774   return index == 0 || index == text().length() ||
775       (index < text().length() &&
776        (truncate_length_ == 0 || index < truncate_length_) &&
777        IsValidCodePointIndex(text(), index));
778 }
779
780 Rect RenderText::GetCursorBounds(const SelectionModel& caret,
781                                  bool insert_mode) {
782   // TODO(ckocagil): Support multiline. This function should return the height
783   //                 of the line the cursor is on. |GetStringSize()| now returns
784   //                 the multiline size, eliminate its use here.
785
786   EnsureLayout();
787   size_t caret_pos = caret.caret_pos();
788   DCHECK(IsValidLogicalIndex(caret_pos));
789   // In overtype mode, ignore the affinity and always indicate that we will
790   // overtype the next character.
791   LogicalCursorDirection caret_affinity =
792       insert_mode ? caret.caret_affinity() : CURSOR_FORWARD;
793   int x = 0, width = 1;
794   Size size = GetStringSize();
795   if (caret_pos == (caret_affinity == CURSOR_BACKWARD ? 0 : text().length())) {
796     // The caret is attached to the boundary. Always return a 1-dip width caret,
797     // since there is nothing to overtype.
798     if ((GetTextDirection() == base::i18n::RIGHT_TO_LEFT) == (caret_pos == 0))
799       x = size.width();
800   } else {
801     size_t grapheme_start = (caret_affinity == CURSOR_FORWARD) ?
802         caret_pos : IndexOfAdjacentGrapheme(caret_pos, CURSOR_BACKWARD);
803     Range xspan(GetGlyphBounds(grapheme_start));
804     if (insert_mode) {
805       x = (caret_affinity == CURSOR_BACKWARD) ? xspan.end() : xspan.start();
806     } else {  // overtype mode
807       x = xspan.GetMin();
808       width = xspan.length();
809     }
810   }
811   return Rect(ToViewPoint(Point(x, 0)), Size(width, size.height()));
812 }
813
814 const Rect& RenderText::GetUpdatedCursorBounds() {
815   UpdateCachedBoundsAndOffset();
816   return cursor_bounds_;
817 }
818
819 size_t RenderText::IndexOfAdjacentGrapheme(size_t index,
820                                            LogicalCursorDirection direction) {
821   if (index > text().length())
822     return text().length();
823
824   EnsureLayout();
825
826   if (direction == CURSOR_FORWARD) {
827     while (index < text().length()) {
828       index++;
829       if (IsValidCursorIndex(index))
830         return index;
831     }
832     return text().length();
833   }
834
835   while (index > 0) {
836     index--;
837     if (IsValidCursorIndex(index))
838       return index;
839   }
840   return 0;
841 }
842
843 SelectionModel RenderText::GetSelectionModelForSelectionStart() {
844   const Range& sel = selection();
845   if (sel.is_empty())
846     return selection_model_;
847   return SelectionModel(sel.start(),
848                         sel.is_reversed() ? CURSOR_BACKWARD : CURSOR_FORWARD);
849 }
850
851 const Vector2d& RenderText::GetUpdatedDisplayOffset() {
852   UpdateCachedBoundsAndOffset();
853   return display_offset_;
854 }
855
856 void RenderText::SetDisplayOffset(int horizontal_offset) {
857   const int extra_content =
858       ToFlooredInt(GetContentWidth()) - display_rect_.width();
859   const int cursor_width = cursor_enabled_ ? 1 : 0;
860
861   int min_offset = 0;
862   int max_offset = 0;
863   if (extra_content > 0) {
864     switch (GetCurrentHorizontalAlignment()) {
865       case ALIGN_LEFT:
866         min_offset = -extra_content;
867         break;
868       case ALIGN_RIGHT:
869         max_offset = extra_content;
870         break;
871       case ALIGN_CENTER:
872         // The extra space reserved for cursor at the end of the text is ignored
873         // when centering text. So, to calculate the valid range for offset, we
874         // exclude that extra space, calculate the range, and add it back to the
875         // range (if cursor is enabled).
876         min_offset = -(extra_content - cursor_width + 1) / 2 - cursor_width;
877         max_offset = (extra_content - cursor_width) / 2;
878         break;
879       default:
880         break;
881     }
882   }
883   if (horizontal_offset < min_offset)
884     horizontal_offset = min_offset;
885   else if (horizontal_offset > max_offset)
886     horizontal_offset = max_offset;
887
888   cached_bounds_and_offset_valid_ = true;
889   display_offset_.set_x(horizontal_offset);
890   cursor_bounds_ = GetCursorBounds(selection_model_, insert_mode_);
891 }
892
893 RenderText::RenderText()
894     : horizontal_alignment_(base::i18n::IsRTL() ? ALIGN_RIGHT : ALIGN_LEFT),
895       directionality_mode_(DIRECTIONALITY_FROM_TEXT),
896       text_direction_(base::i18n::UNKNOWN_DIRECTION),
897       cursor_enabled_(true),
898       cursor_visible_(false),
899       insert_mode_(true),
900       cursor_color_(kDefaultColor),
901       selection_color_(kDefaultColor),
902       selection_background_focused_color_(kDefaultSelectionBackgroundColor),
903       focused_(false),
904       composition_range_(Range::InvalidRange()),
905       colors_(kDefaultColor),
906       styles_(NUM_TEXT_STYLES),
907       composition_and_selection_styles_applied_(false),
908       obscured_(false),
909       obscured_reveal_index_(-1),
910       truncate_length_(0),
911       elide_behavior_(NO_ELIDE),
912       replace_newline_chars_with_symbols_(true),
913       multiline_(false),
914       background_is_transparent_(false),
915       clip_to_display_rect_(true),
916       baseline_(kInvalidBaseline),
917       cached_bounds_and_offset_valid_(false) {
918 }
919
920 SelectionModel RenderText::GetAdjacentSelectionModel(
921     const SelectionModel& current,
922     BreakType break_type,
923     VisualCursorDirection direction) {
924   EnsureLayout();
925
926   if (break_type == LINE_BREAK || text().empty())
927     return EdgeSelectionModel(direction);
928   if (break_type == CHARACTER_BREAK)
929     return AdjacentCharSelectionModel(current, direction);
930   DCHECK(break_type == WORD_BREAK);
931   return AdjacentWordSelectionModel(current, direction);
932 }
933
934 SelectionModel RenderText::EdgeSelectionModel(
935     VisualCursorDirection direction) {
936   if (direction == GetVisualDirectionOfLogicalEnd())
937     return SelectionModel(text().length(), CURSOR_FORWARD);
938   return SelectionModel(0, CURSOR_BACKWARD);
939 }
940
941 void RenderText::SetSelectionModel(const SelectionModel& model) {
942   DCHECK_LE(model.selection().GetMax(), text().length());
943   selection_model_ = model;
944   cached_bounds_and_offset_valid_ = false;
945 }
946
947 const base::string16& RenderText::GetLayoutText() const {
948   return layout_text_;
949 }
950
951 const BreakList<size_t>& RenderText::GetLineBreaks() {
952   if (line_breaks_.max() != 0)
953     return line_breaks_;
954
955   const base::string16& layout_text = GetLayoutText();
956   const size_t text_length = layout_text.length();
957   line_breaks_.SetValue(0);
958   line_breaks_.SetMax(text_length);
959   base::i18n::BreakIterator iter(layout_text,
960                                  base::i18n::BreakIterator::BREAK_LINE);
961   const bool success = iter.Init();
962   DCHECK(success);
963   if (success) {
964     do {
965       line_breaks_.ApplyValue(iter.pos(), Range(iter.pos(), text_length));
966     } while (iter.Advance());
967   }
968   return line_breaks_;
969 }
970
971 void RenderText::ApplyCompositionAndSelectionStyles() {
972   // Save the underline and color breaks to undo the temporary styles later.
973   DCHECK(!composition_and_selection_styles_applied_);
974   saved_colors_ = colors_;
975   saved_underlines_ = styles_[UNDERLINE];
976
977   // Apply an underline to the composition range in |underlines|.
978   if (composition_range_.IsValid() && !composition_range_.is_empty())
979     styles_[UNDERLINE].ApplyValue(true, composition_range_);
980
981   // Apply the selected text color to the [un-reversed] selection range.
982   if (!selection().is_empty() && focused()) {
983     const Range range(selection().GetMin(), selection().GetMax());
984     colors_.ApplyValue(selection_color_, range);
985   }
986   composition_and_selection_styles_applied_ = true;
987 }
988
989 void RenderText::UndoCompositionAndSelectionStyles() {
990   // Restore the underline and color breaks to undo the temporary styles.
991   DCHECK(composition_and_selection_styles_applied_);
992   colors_ = saved_colors_;
993   styles_[UNDERLINE] = saved_underlines_;
994   composition_and_selection_styles_applied_ = false;
995 }
996
997 Vector2d RenderText::GetLineOffset(size_t line_number) {
998   Vector2d offset = display_rect().OffsetFromOrigin();
999   // TODO(ckocagil): Apply the display offset for multiline scrolling.
1000   if (!multiline())
1001     offset.Add(GetUpdatedDisplayOffset());
1002   else
1003     offset.Add(Vector2d(0, lines_[line_number].preceding_heights));
1004   offset.Add(GetAlignmentOffset(line_number));
1005   return offset;
1006 }
1007
1008 Point RenderText::ToTextPoint(const Point& point) {
1009   return point - GetLineOffset(0);
1010   // TODO(ckocagil): Convert multiline view space points to text space.
1011 }
1012
1013 Point RenderText::ToViewPoint(const Point& point) {
1014   if (!multiline())
1015     return point + GetLineOffset(0);
1016
1017   // TODO(ckocagil): Traverse individual line segments for RTL support.
1018   DCHECK(!lines_.empty());
1019   int x = point.x();
1020   size_t line = 0;
1021   for (; line < lines_.size() && x > lines_[line].size.width(); ++line)
1022     x -= lines_[line].size.width();
1023   return Point(x, point.y()) + GetLineOffset(line);
1024 }
1025
1026 std::vector<Rect> RenderText::TextBoundsToViewBounds(const Range& x) {
1027   std::vector<Rect> rects;
1028
1029   if (!multiline()) {
1030     rects.push_back(Rect(ToViewPoint(Point(x.GetMin(), 0)),
1031                          Size(x.length(), GetStringSize().height())));
1032     return rects;
1033   }
1034
1035   EnsureLayout();
1036
1037   // Each line segment keeps its position in text coordinates. Traverse all line
1038   // segments and if the segment intersects with the given range, add the view
1039   // rect corresponding to the intersection to |rects|.
1040   for (size_t line = 0; line < lines_.size(); ++line) {
1041     int line_x = 0;
1042     const Vector2d offset = GetLineOffset(line);
1043     for (size_t i = 0; i < lines_[line].segments.size(); ++i) {
1044       const internal::LineSegment* segment = &lines_[line].segments[i];
1045       const Range intersection = segment->x_range.Intersect(x);
1046       if (!intersection.is_empty()) {
1047         Rect rect(line_x + intersection.start() - segment->x_range.start(),
1048                   0, intersection.length(), lines_[line].size.height());
1049         rects.push_back(rect + offset);
1050       }
1051       line_x += segment->x_range.length();
1052     }
1053   }
1054
1055   return rects;
1056 }
1057
1058 HorizontalAlignment RenderText::GetCurrentHorizontalAlignment() {
1059   if (horizontal_alignment_ != ALIGN_TO_HEAD)
1060     return horizontal_alignment_;
1061   return GetTextDirection() == base::i18n::RIGHT_TO_LEFT ? ALIGN_RIGHT
1062                                                          : ALIGN_LEFT;
1063 }
1064
1065 Vector2d RenderText::GetAlignmentOffset(size_t line_number) {
1066   // TODO(ckocagil): Enable |lines_| usage in other platforms.
1067 #if defined(OS_WIN)
1068   DCHECK_LT(line_number, lines_.size());
1069 #endif
1070   Vector2d offset;
1071   HorizontalAlignment horizontal_alignment = GetCurrentHorizontalAlignment();
1072   if (horizontal_alignment != ALIGN_LEFT) {
1073 #if defined(OS_WIN)
1074     const int width = lines_[line_number].size.width() +
1075         (cursor_enabled_ ? 1 : 0);
1076 #else
1077     const int width = GetContentWidth();
1078 #endif
1079     offset.set_x(display_rect().width() - width);
1080     // Put any extra margin pixel on the left to match legacy behavior.
1081     if (horizontal_alignment == ALIGN_CENTER)
1082       offset.set_x((offset.x() + 1) / 2);
1083   }
1084
1085   // Vertically center the text.
1086   if (multiline_) {
1087     const int text_height = lines_.back().preceding_heights +
1088         lines_.back().size.height();
1089     offset.set_y((display_rect_.height() - text_height) / 2);
1090   } else {
1091     offset.set_y(GetBaseline() - GetLayoutTextBaseline());
1092   }
1093
1094   return offset;
1095 }
1096
1097 void RenderText::ApplyFadeEffects(internal::SkiaTextRenderer* renderer) {
1098   const int width = display_rect().width();
1099   if (multiline() || elide_behavior_ != FADE_TAIL ||
1100       static_cast<int>(GetContentWidth()) <= width)
1101     return;
1102
1103   const int gradient_width = CalculateFadeGradientWidth(font_list(), width);
1104   if (gradient_width == 0)
1105     return;
1106
1107   HorizontalAlignment horizontal_alignment = GetCurrentHorizontalAlignment();
1108   Rect solid_part = display_rect();
1109   Rect left_part;
1110   Rect right_part;
1111   if (horizontal_alignment != ALIGN_LEFT) {
1112     left_part = solid_part;
1113     left_part.Inset(0, 0, solid_part.width() - gradient_width, 0);
1114     solid_part.Inset(gradient_width, 0, 0, 0);
1115   }
1116   if (horizontal_alignment != ALIGN_RIGHT) {
1117     right_part = solid_part;
1118     right_part.Inset(solid_part.width() - gradient_width, 0, 0, 0);
1119     solid_part.Inset(0, 0, gradient_width, 0);
1120   }
1121
1122   Rect text_rect = display_rect();
1123   text_rect.Inset(GetAlignmentOffset(0).x(), 0, 0, 0);
1124
1125   // TODO(msw): Use the actual text colors corresponding to each faded part.
1126   skia::RefPtr<SkShader> shader = CreateFadeShader(
1127       text_rect, left_part, right_part, colors_.breaks().front().second);
1128   if (shader)
1129     renderer->SetShader(shader.get());
1130 }
1131
1132 void RenderText::ApplyTextShadows(internal::SkiaTextRenderer* renderer) {
1133   skia::RefPtr<SkDrawLooper> looper = CreateShadowDrawLooper(shadows_);
1134   renderer->SetDrawLooper(looper.get());
1135 }
1136
1137 // static
1138 bool RenderText::RangeContainsCaret(const Range& range,
1139                                     size_t caret_pos,
1140                                     LogicalCursorDirection caret_affinity) {
1141   // NB: exploits unsigned wraparound (WG14/N1124 section 6.2.5 paragraph 9).
1142   size_t adjacent = (caret_affinity == CURSOR_BACKWARD) ?
1143       caret_pos - 1 : caret_pos + 1;
1144   return range.Contains(Range(caret_pos, adjacent));
1145 }
1146
1147 void RenderText::MoveCursorTo(size_t position, bool select) {
1148   size_t cursor = std::min(position, text().length());
1149   if (IsValidCursorIndex(cursor))
1150     SetSelectionModel(SelectionModel(
1151         Range(select ? selection().start() : cursor, cursor),
1152         (cursor == 0) ? CURSOR_FORWARD : CURSOR_BACKWARD));
1153 }
1154
1155 void RenderText::UpdateLayoutText() {
1156   layout_text_.clear();
1157   line_breaks_.SetMax(0);
1158
1159   if (obscured_) {
1160     size_t obscured_text_length =
1161         static_cast<size_t>(UTF16IndexToOffset(text_, 0, text_.length()));
1162     layout_text_.assign(obscured_text_length, kPasswordReplacementChar);
1163
1164     if (obscured_reveal_index_ >= 0 &&
1165         obscured_reveal_index_ < static_cast<int>(text_.length())) {
1166       // Gets the index range in |text_| to be revealed.
1167       size_t start = obscured_reveal_index_;
1168       U16_SET_CP_START(text_.data(), 0, start);
1169       size_t end = start;
1170       UChar32 unused_char;
1171       U16_NEXT(text_.data(), end, text_.length(), unused_char);
1172
1173       // Gets the index in |layout_text_| to be replaced.
1174       const size_t cp_start =
1175           static_cast<size_t>(UTF16IndexToOffset(text_, 0, start));
1176       if (layout_text_.length() > cp_start)
1177         layout_text_.replace(cp_start, 1, text_.substr(start, end - start));
1178     }
1179   } else {
1180     layout_text_ = text_;
1181   }
1182
1183   const base::string16& text = layout_text_;
1184   if (truncate_length_ > 0 && truncate_length_ < text.length()) {
1185     // Truncate the text at a valid character break and append an ellipsis.
1186     icu::StringCharacterIterator iter(text.c_str());
1187     // Respect ELIDE_HEAD and ELIDE_MIDDLE preferences during truncation.
1188     if (elide_behavior_ == ELIDE_HEAD) {
1189       iter.setIndex32(text.length() - truncate_length_ + 1);
1190       layout_text_.assign(kEllipsisUTF16 + text.substr(iter.getIndex()));
1191     } else if (elide_behavior_ == ELIDE_MIDDLE) {
1192       iter.setIndex32(truncate_length_ / 2);
1193       const size_t ellipsis_start = iter.getIndex();
1194       iter.setIndex32(text.length() - (truncate_length_ / 2));
1195       const size_t ellipsis_end = iter.getIndex();
1196       DCHECK_LE(ellipsis_start, ellipsis_end);
1197       layout_text_.assign(text.substr(0, ellipsis_start) + kEllipsisUTF16 +
1198                           text.substr(ellipsis_end));
1199     } else {
1200       iter.setIndex32(truncate_length_ - 1);
1201       layout_text_.assign(text.substr(0, iter.getIndex()) + kEllipsisUTF16);
1202     }
1203   }
1204
1205   if (elide_behavior_ != NO_ELIDE &&
1206       elide_behavior_ != FADE_TAIL &&
1207       !layout_text_.empty() &&
1208       static_cast<int>(GetContentWidth()) > display_rect_.width()) {
1209     // This doesn't trim styles so ellipsis may get rendered as a different
1210     // style than the preceding text. See crbug.com/327850.
1211     layout_text_.assign(Elide(layout_text_,
1212                               static_cast<float>(display_rect_.width()),
1213                               elide_behavior_));
1214   }
1215
1216   // Replace the newline character with a newline symbol in single line mode.
1217   static const base::char16 kNewline[] = { '\n', 0 };
1218   static const base::char16 kNewlineSymbol[] = { 0x2424, 0 };
1219   if (!multiline_ && replace_newline_chars_with_symbols_)
1220     base::ReplaceChars(layout_text_, kNewline, kNewlineSymbol, &layout_text_);
1221
1222   ResetLayout();
1223 }
1224
1225 base::string16 RenderText::Elide(const base::string16& text,
1226                                  float available_width,
1227                                  ElideBehavior behavior) {
1228   if (available_width <= 0 || text.empty())
1229     return base::string16();
1230   if (behavior == ELIDE_EMAIL)
1231     return ElideEmail(text, available_width);
1232
1233   // Create a RenderText copy with attributes that affect the rendering width.
1234   scoped_ptr<RenderText> render_text(CreateInstance());
1235   render_text->SetFontList(font_list_);
1236   render_text->SetDirectionalityMode(directionality_mode_);
1237   render_text->SetCursorEnabled(cursor_enabled_);
1238   render_text->set_truncate_length(truncate_length_);
1239   render_text->styles_ = styles_;
1240   render_text->colors_ = colors_;
1241   render_text->SetText(text);
1242   if (render_text->GetContentWidth() <= available_width)
1243     return text;
1244
1245   const base::string16 ellipsis = base::string16(kEllipsisUTF16);
1246   const bool insert_ellipsis = (behavior != TRUNCATE);
1247   const bool elide_in_middle = (behavior == ELIDE_MIDDLE);
1248   const bool elide_at_beginning = (behavior == ELIDE_HEAD);
1249   StringSlicer slicer(text, ellipsis, elide_in_middle, elide_at_beginning);
1250
1251   render_text->SetText(ellipsis);
1252   const float ellipsis_width = render_text->GetContentWidth();
1253
1254   if (insert_ellipsis && (ellipsis_width > available_width))
1255     return base::string16();
1256
1257   // Use binary search to compute the elided text.
1258   size_t lo = 0;
1259   size_t hi = text.length() - 1;
1260   const base::i18n::TextDirection text_direction = GetTextDirection();
1261   for (size_t guess = (lo + hi) / 2; lo <= hi; guess = (lo + hi) / 2) {
1262     // Restore colors. They will be truncated to size by SetText.
1263     render_text->colors_ = colors_;
1264     base::string16 new_text =
1265         slicer.CutString(guess, insert_ellipsis && behavior != ELIDE_TAIL);
1266     render_text->SetText(new_text);
1267
1268     // This has to be an additional step so that the ellipsis is rendered with
1269     // same style as trailing part of the text.
1270     if (insert_ellipsis && behavior == ELIDE_TAIL) {
1271       // When ellipsis follows text whose directionality is not the same as that
1272       // of the whole text, it will be rendered with the directionality of the
1273       // whole text. Since we want ellipsis to indicate continuation of the
1274       // preceding text, we force the directionality of ellipsis to be same as
1275       // the preceding text using LTR or RTL markers.
1276       base::i18n::TextDirection trailing_text_direction =
1277           base::i18n::GetLastStrongCharacterDirection(new_text);
1278       new_text.append(ellipsis);
1279       if (trailing_text_direction != text_direction) {
1280         if (trailing_text_direction == base::i18n::LEFT_TO_RIGHT)
1281           new_text += base::i18n::kLeftToRightMark;
1282         else
1283           new_text += base::i18n::kRightToLeftMark;
1284       }
1285       render_text->SetText(new_text);
1286     }
1287
1288     // Restore styles. Make sure style ranges don't break new text graphemes.
1289     render_text->styles_ = styles_;
1290     for (size_t style = 0; style < NUM_TEXT_STYLES; ++style) {
1291       BreakList<bool>& break_list = render_text->styles_[style];
1292       break_list.SetMax(render_text->text_.length());
1293       Range range;
1294       while (range.end() < break_list.max()) {
1295         BreakList<bool>::const_iterator current_break =
1296             break_list.GetBreak(range.end());
1297         range = break_list.GetRange(current_break);
1298         if (range.end() < break_list.max() &&
1299             !render_text->IsValidCursorIndex(range.end())) {
1300           range.set_end(render_text->IndexOfAdjacentGrapheme(range.end(),
1301                                                              CURSOR_FORWARD));
1302           break_list.ApplyValue(current_break->second, range);
1303         }
1304       }
1305     }
1306
1307     // We check the width of the whole desired string at once to ensure we
1308     // handle kerning/ligatures/etc. correctly.
1309     const float guess_width = render_text->GetContentWidth();
1310     if (guess_width == available_width)
1311       break;
1312     if (guess_width > available_width) {
1313       hi = guess - 1;
1314       // Move back on the loop terminating condition when the guess is too wide.
1315       if (hi < lo)
1316         lo = hi;
1317     } else {
1318       lo = guess + 1;
1319     }
1320   }
1321
1322   return render_text->text();
1323 }
1324
1325 base::string16 RenderText::ElideEmail(const base::string16& email,
1326                                       float available_width) {
1327   // The returned string will have at least one character besides the ellipsis
1328   // on either side of '@'; if that's impossible, a single ellipsis is returned.
1329   // If possible, only the username is elided. Otherwise, the domain is elided
1330   // in the middle, splitting available width equally with the elided username.
1331   // If the username is short enough that it doesn't need half the available
1332   // width, the elided domain will occupy that extra width.
1333
1334   // Split the email into its local-part (username) and domain-part. The email
1335   // spec allows for @ symbols in the username under some special requirements,
1336   // but not in the domain part, so splitting at the last @ symbol is safe.
1337   const size_t split_index = email.find_last_of('@');
1338   DCHECK_NE(split_index, base::string16::npos);
1339   base::string16 username = email.substr(0, split_index);
1340   base::string16 domain = email.substr(split_index + 1);
1341   DCHECK(!username.empty());
1342   DCHECK(!domain.empty());
1343
1344   // Subtract the @ symbol from the available width as it is mandatory.
1345   const base::string16 kAtSignUTF16 = base::ASCIIToUTF16("@");
1346   available_width -= GetStringWidthF(kAtSignUTF16, font_list());
1347
1348   // Check whether eliding the domain is necessary: if eliding the username
1349   // is sufficient, the domain will not be elided.
1350   const float full_username_width = GetStringWidthF(username, font_list());
1351   const float available_domain_width = available_width -
1352       std::min(full_username_width,
1353           GetStringWidthF(username.substr(0, 1) + kEllipsisUTF16, font_list()));
1354   if (GetStringWidthF(domain, font_list()) > available_domain_width) {
1355     // Elide the domain so that it only takes half of the available width.
1356     // Should the username not need all the width available in its half, the
1357     // domain will occupy the leftover width.
1358     // If |desired_domain_width| is greater than |available_domain_width|: the
1359     // minimal username elision allowed by the specifications will not fit; thus
1360     // |desired_domain_width| must be <= |available_domain_width| at all cost.
1361     const float desired_domain_width =
1362         std::min<float>(available_domain_width,
1363             std::max<float>(available_width - full_username_width,
1364                             available_width / 2));
1365     domain = Elide(domain, desired_domain_width, ELIDE_MIDDLE);
1366     // Failing to elide the domain such that at least one character remains
1367     // (other than the ellipsis itself) remains: return a single ellipsis.
1368     if (domain.length() <= 1U)
1369       return base::string16(kEllipsisUTF16);
1370   }
1371
1372   // Fit the username in the remaining width (at this point the elided username
1373   // is guaranteed to fit with at least one character remaining given all the
1374   // precautions taken earlier).
1375   available_width -= GetStringWidthF(domain, font_list());
1376   username = Elide(username, available_width, ELIDE_TAIL);
1377   return username + kAtSignUTF16 + domain;
1378 }
1379
1380 void RenderText::UpdateCachedBoundsAndOffset() {
1381   if (cached_bounds_and_offset_valid_)
1382     return;
1383
1384   // TODO(ckocagil): Add support for scrolling multiline text.
1385
1386   int delta_x = 0;
1387
1388   if (cursor_enabled()) {
1389     // When cursor is enabled, ensure it is visible. For this, set the valid
1390     // flag true and calculate the current cursor bounds using the stale
1391     // |display_offset_|. Then calculate the change in offset needed to move the
1392     // cursor into the visible area.
1393     cached_bounds_and_offset_valid_ = true;
1394     cursor_bounds_ = GetCursorBounds(selection_model_, insert_mode_);
1395
1396     // TODO(bidi): Show RTL glyphs at the cursor position for ALIGN_LEFT, etc.
1397     if (cursor_bounds_.right() > display_rect_.right())
1398       delta_x = display_rect_.right() - cursor_bounds_.right();
1399     else if (cursor_bounds_.x() < display_rect_.x())
1400       delta_x = display_rect_.x() - cursor_bounds_.x();
1401   }
1402
1403   SetDisplayOffset(display_offset_.x() + delta_x);
1404 }
1405
1406 void RenderText::DrawSelection(Canvas* canvas) {
1407   const std::vector<Rect> sel = GetSubstringBounds(selection());
1408   for (std::vector<Rect>::const_iterator i = sel.begin(); i < sel.end(); ++i)
1409     canvas->FillRect(*i, selection_background_focused_color_);
1410 }
1411
1412 }  // namespace gfx