Add ICU message format support
[chromium-blink-merge.git] / ui / views / controls / label.cc
blob766452012697dfbbc3b33dd05e44a9f772c15488
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "ui/views/controls/label.h"
7 #include <algorithm>
8 #include <cmath>
9 #include <limits>
10 #include <vector>
12 #include "base/i18n/rtl.h"
13 #include "base/logging.h"
14 #include "base/profiler/scoped_tracker.h"
15 #include "base/strings/string_split.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "ui/accessibility/ax_view_state.h"
18 #include "ui/gfx/canvas.h"
19 #include "ui/gfx/color_utils.h"
20 #include "ui/gfx/geometry/insets.h"
21 #include "ui/gfx/text_elider.h"
22 #include "ui/native_theme/native_theme.h"
24 namespace views {
26 // static
27 const char Label::kViewClassName[] = "Label";
28 const int Label::kFocusBorderPadding = 1;
30 Label::Label() {
31 Init(base::string16(), gfx::FontList());
34 Label::Label(const base::string16& text) {
35 Init(text, gfx::FontList());
38 Label::Label(const base::string16& text, const gfx::FontList& font_list) {
39 Init(text, font_list);
42 Label::~Label() {
45 void Label::SetFontList(const gfx::FontList& font_list) {
46 is_first_paint_text_ = true;
47 render_text_->SetFontList(font_list);
48 ResetLayout();
51 void Label::SetText(const base::string16& new_text) {
52 if (new_text == text())
53 return;
54 is_first_paint_text_ = true;
55 render_text_->SetText(new_text);
56 ResetLayout();
59 void Label::SetAutoColorReadabilityEnabled(bool enabled) {
60 if (auto_color_readability_ == enabled)
61 return;
62 is_first_paint_text_ = true;
63 auto_color_readability_ = enabled;
64 RecalculateColors();
67 void Label::SetEnabledColor(SkColor color) {
68 if (enabled_color_set_ && requested_enabled_color_ == color)
69 return;
70 is_first_paint_text_ = true;
71 requested_enabled_color_ = color;
72 enabled_color_set_ = true;
73 RecalculateColors();
76 void Label::SetDisabledColor(SkColor color) {
77 if (disabled_color_set_ && requested_disabled_color_ == color)
78 return;
79 is_first_paint_text_ = true;
80 requested_disabled_color_ = color;
81 disabled_color_set_ = true;
82 RecalculateColors();
85 void Label::SetBackgroundColor(SkColor color) {
86 if (background_color_set_ && background_color_ == color)
87 return;
88 is_first_paint_text_ = true;
89 background_color_ = color;
90 background_color_set_ = true;
91 RecalculateColors();
94 void Label::SetShadows(const gfx::ShadowValues& shadows) {
95 // TODO(mukai): early exit if the specified shadows are same.
96 is_first_paint_text_ = true;
97 render_text_->set_shadows(shadows);
98 ResetLayout();
101 void Label::SetSubpixelRenderingEnabled(bool subpixel_rendering_enabled) {
102 if (subpixel_rendering_enabled_ == subpixel_rendering_enabled)
103 return;
104 is_first_paint_text_ = true;
105 subpixel_rendering_enabled_ = subpixel_rendering_enabled;
106 RecalculateColors();
109 void Label::SetHorizontalAlignment(gfx::HorizontalAlignment alignment) {
110 // If the UI layout is right-to-left, flip the alignment direction.
111 if (base::i18n::IsRTL() &&
112 (alignment == gfx::ALIGN_LEFT || alignment == gfx::ALIGN_RIGHT)) {
113 alignment = (alignment == gfx::ALIGN_LEFT) ?
114 gfx::ALIGN_RIGHT : gfx::ALIGN_LEFT;
116 if (horizontal_alignment() == alignment)
117 return;
118 is_first_paint_text_ = true;
119 render_text_->SetHorizontalAlignment(alignment);
120 ResetLayout();
123 void Label::SetLineHeight(int height) {
124 if (line_height() == height)
125 return;
126 is_first_paint_text_ = true;
127 render_text_->SetMinLineHeight(height);
128 ResetLayout();
131 void Label::SetMultiLine(bool multi_line) {
132 DCHECK(!multi_line || (elide_behavior_ == gfx::ELIDE_TAIL ||
133 elide_behavior_ == gfx::NO_ELIDE));
134 if (this->multi_line() == multi_line)
135 return;
136 is_first_paint_text_ = true;
137 multi_line_ = multi_line;
138 if (render_text_->MultilineSupported())
139 render_text_->SetMultiline(multi_line);
140 render_text_->SetReplaceNewlineCharsWithSymbols(!multi_line);
141 ResetLayout();
144 void Label::SetObscured(bool obscured) {
145 if (this->obscured() == obscured)
146 return;
147 is_first_paint_text_ = true;
148 render_text_->SetObscured(obscured);
149 ResetLayout();
152 void Label::SetAllowCharacterBreak(bool allow_character_break) {
153 const gfx::WordWrapBehavior behavior =
154 allow_character_break ? gfx::WRAP_LONG_WORDS : gfx::TRUNCATE_LONG_WORDS;
155 if (render_text_->word_wrap_behavior() == behavior)
156 return;
157 render_text_->SetWordWrapBehavior(behavior);
158 if (multi_line()) {
159 is_first_paint_text_ = true;
160 ResetLayout();
164 void Label::SetElideBehavior(gfx::ElideBehavior elide_behavior) {
165 DCHECK(!multi_line() || (elide_behavior_ == gfx::ELIDE_TAIL ||
166 elide_behavior_ == gfx::NO_ELIDE));
167 if (elide_behavior_ == elide_behavior)
168 return;
169 is_first_paint_text_ = true;
170 elide_behavior_ = elide_behavior;
171 ResetLayout();
174 void Label::SetTooltipText(const base::string16& tooltip_text) {
175 DCHECK(handles_tooltips_);
176 tooltip_text_ = tooltip_text;
179 void Label::SetHandlesTooltips(bool enabled) {
180 handles_tooltips_ = enabled;
183 void Label::SizeToFit(int max_width) {
184 DCHECK(multi_line());
185 max_width_ = max_width;
186 SizeToPreferredSize();
189 base::string16 Label::GetDisplayTextForTesting() {
190 lines_.clear();
191 MaybeBuildRenderTextLines();
192 base::string16 result;
193 if (lines_.empty())
194 return result;
195 result.append(lines_[0]->GetDisplayText());
196 for (size_t i = 1; i < lines_.size(); ++i) {
197 result.append(1, '\n');
198 result.append(lines_[i]->GetDisplayText());
200 return result;
203 gfx::Insets Label::GetInsets() const {
204 gfx::Insets insets = View::GetInsets();
205 if (focusable()) {
206 insets += gfx::Insets(kFocusBorderPadding, kFocusBorderPadding,
207 kFocusBorderPadding, kFocusBorderPadding);
209 return insets;
212 int Label::GetBaseline() const {
213 return GetInsets().top() + font_list().GetBaseline();
216 gfx::Size Label::GetPreferredSize() const {
217 // Return a size of (0, 0) if the label is not visible and if the
218 // |collapse_when_hidden_| flag is set.
219 // TODO(munjal): This logic probably belongs to the View class. But for now,
220 // put it here since putting it in View class means all inheriting classes
221 // need to respect the |collapse_when_hidden_| flag.
222 if (!visible() && collapse_when_hidden_)
223 return gfx::Size();
225 if (multi_line() && max_width_ != 0 && !text().empty())
226 return gfx::Size(max_width_, GetHeightForWidth(max_width_));
228 gfx::Size size(GetTextSize());
229 const gfx::Insets insets = GetInsets();
230 size.Enlarge(insets.width(), insets.height());
231 return size;
234 gfx::Size Label::GetMinimumSize() const {
235 if (!visible() && collapse_when_hidden_)
236 return gfx::Size();
238 gfx::Size size(0, font_list().GetHeight());
239 if (elide_behavior_ == gfx::ELIDE_HEAD ||
240 elide_behavior_ == gfx::ELIDE_MIDDLE ||
241 elide_behavior_ == gfx::ELIDE_TAIL ||
242 elide_behavior_ == gfx::ELIDE_EMAIL) {
243 size.set_width(gfx::Canvas::GetStringWidth(
244 base::string16(gfx::kEllipsisUTF16), font_list()));
246 if (!multi_line())
247 size.SetToMin(GetTextSize());
248 size.Enlarge(GetInsets().width(), GetInsets().height());
249 return size;
252 int Label::GetHeightForWidth(int w) const {
253 if (!visible() && collapse_when_hidden_)
254 return 0;
256 w -= GetInsets().width();
257 int height = 0;
258 if (!multi_line() || text().empty() || w <= 0) {
259 height = std::max(line_height(), font_list().GetHeight());
260 } else if (render_text_->MultilineSupported()) {
261 // SetDisplayRect() has a side effect for later calls of GetStringSize().
262 // Be careful to invoke |render_text_->SetDisplayRect(gfx::Rect())| to
263 // cancel this effect before the next time GetStringSize() is called.
264 // It would be beneficial not to cancel here, considering that some layout
265 // managers invoke GetHeightForWidth() for the same width multiple times
266 // and |render_text_| can cache the height.
267 render_text_->SetDisplayRect(gfx::Rect(0, 0, w, 0));
268 height = render_text_->GetStringSize().height();
269 } else {
270 std::vector<base::string16> lines = GetLinesForWidth(w);
271 height = lines.size() * std::max(line_height(), font_list().GetHeight());
273 height -= gfx::ShadowValue::GetMargin(render_text_->shadows()).height();
274 return height + GetInsets().height();
277 void Label::Layout() {
278 lines_.clear();
281 const char* Label::GetClassName() const {
282 return kViewClassName;
285 View* Label::GetTooltipHandlerForPoint(const gfx::Point& point) {
286 if (!handles_tooltips_ ||
287 (tooltip_text_.empty() && !ShouldShowDefaultTooltip()))
288 return NULL;
290 return HitTestPoint(point) ? this : NULL;
293 bool Label::CanProcessEventsWithinSubtree() const {
294 // Send events to the parent view for handling.
295 return false;
298 void Label::GetAccessibleState(ui::AXViewState* state) {
299 state->role = ui::AX_ROLE_STATIC_TEXT;
300 state->AddStateFlag(ui::AX_STATE_READ_ONLY);
301 // Note that |render_text_| is never elided (see the comment in Init() too).
302 state->name = render_text_->GetDisplayText();
305 bool Label::GetTooltipText(const gfx::Point& p, base::string16* tooltip) const {
306 if (!handles_tooltips_)
307 return false;
309 if (!tooltip_text_.empty()) {
310 tooltip->assign(tooltip_text_);
311 return true;
314 if (ShouldShowDefaultTooltip()) {
315 // Note that |render_text_| is never elided (see the comment in Init() too).
316 tooltip->assign(render_text_->GetDisplayText());
317 return true;
320 return false;
323 void Label::OnEnabledChanged() {
324 RecalculateColors();
327 scoped_ptr<gfx::RenderText> Label::CreateRenderText(
328 const base::string16& text,
329 gfx::HorizontalAlignment alignment,
330 gfx::DirectionalityMode directionality,
331 gfx::ElideBehavior elide_behavior) {
332 scoped_ptr<gfx::RenderText> render_text(
333 render_text_->CreateInstanceOfSameType());
334 render_text->SetHorizontalAlignment(alignment);
335 render_text->SetDirectionalityMode(directionality);
336 render_text->SetElideBehavior(elide_behavior);
337 render_text->SetObscured(obscured());
338 render_text->SetMinLineHeight(line_height());
339 render_text->SetFontList(font_list());
340 render_text->set_shadows(shadows());
341 render_text->SetCursorEnabled(false);
342 render_text->SetText(text);
343 return render_text.Pass();
346 void Label::PaintText(gfx::Canvas* canvas) {
347 MaybeBuildRenderTextLines();
348 for (size_t i = 0; i < lines_.size(); ++i)
349 lines_[i]->Draw(canvas);
352 void Label::OnBoundsChanged(const gfx::Rect& previous_bounds) {
353 if (previous_bounds.size() != size())
354 InvalidateLayout();
357 void Label::OnPaint(gfx::Canvas* canvas) {
358 View::OnPaint(canvas);
359 if (is_first_paint_text_) {
360 // TODO(ckocagil): Remove ScopedTracker below once crbug.com/441028 is
361 // fixed.
362 tracked_objects::ScopedTracker tracking_profile(
363 FROM_HERE_WITH_EXPLICIT_FUNCTION("441028 First PaintText()"));
365 is_first_paint_text_ = false;
366 PaintText(canvas);
367 } else {
368 PaintText(canvas);
370 if (HasFocus())
371 canvas->DrawFocusRect(GetFocusBounds());
374 void Label::OnNativeThemeChanged(const ui::NativeTheme* theme) {
375 UpdateColorsFromTheme(theme);
378 void Label::OnDeviceScaleFactorChanged(float device_scale_factor) {
379 View::OnDeviceScaleFactorChanged(device_scale_factor);
380 // When the device scale factor is changed, some font rendering parameters is
381 // changed (especially, hinting). The bounding box of the text has to be
382 // re-computed based on the new parameters. See crbug.com/441439
383 ResetLayout();
386 void Label::VisibilityChanged(View* starting_from, bool is_visible) {
387 if (!is_visible)
388 lines_.clear();
391 void Label::Init(const base::string16& text, const gfx::FontList& font_list) {
392 render_text_.reset(gfx::RenderText::CreateInstance());
393 render_text_->SetHorizontalAlignment(gfx::ALIGN_CENTER);
394 render_text_->SetDirectionalityMode(gfx::DIRECTIONALITY_FROM_TEXT);
395 // NOTE: |render_text_| should not be elided at all. This is used to keep some
396 // properties and to compute the size of the string.
397 render_text_->SetElideBehavior(gfx::NO_ELIDE);
398 render_text_->SetFontList(font_list);
399 render_text_->SetCursorEnabled(false);
400 render_text_->SetWordWrapBehavior(gfx::TRUNCATE_LONG_WORDS);
402 elide_behavior_ = gfx::ELIDE_TAIL;
403 enabled_color_set_ = disabled_color_set_ = background_color_set_ = false;
404 subpixel_rendering_enabled_ = true;
405 auto_color_readability_ = true;
406 multi_line_ = false;
407 UpdateColorsFromTheme(ui::NativeTheme::instance());
408 handles_tooltips_ = true;
409 collapse_when_hidden_ = false;
410 max_width_ = 0;
411 is_first_paint_text_ = true;
412 SetText(text);
415 void Label::ResetLayout() {
416 InvalidateLayout();
417 PreferredSizeChanged();
418 SchedulePaint();
419 lines_.clear();
422 void Label::MaybeBuildRenderTextLines() {
423 if (!lines_.empty())
424 return;
426 gfx::Rect rect = GetContentsBounds();
427 if (focusable())
428 rect.Inset(kFocusBorderPadding, kFocusBorderPadding);
429 if (rect.IsEmpty())
430 return;
432 gfx::HorizontalAlignment alignment = horizontal_alignment();
433 gfx::DirectionalityMode directionality = render_text_->directionality_mode();
434 if (multi_line()) {
435 // Force the directionality and alignment of the first line on other lines.
436 bool rtl =
437 render_text_->GetDisplayTextDirection() == base::i18n::RIGHT_TO_LEFT;
438 if (alignment == gfx::ALIGN_TO_HEAD)
439 alignment = rtl ? gfx::ALIGN_RIGHT : gfx::ALIGN_LEFT;
440 directionality =
441 rtl ? gfx::DIRECTIONALITY_FORCE_RTL : gfx::DIRECTIONALITY_FORCE_LTR;
444 // Text eliding is not supported for multi-lined Labels.
445 // TODO(mukai): Add multi-lined elided text support.
446 gfx::ElideBehavior elide_behavior =
447 multi_line() ? gfx::NO_ELIDE : elide_behavior_;
448 if (!multi_line() || render_text_->MultilineSupported()) {
449 scoped_ptr<gfx::RenderText> render_text =
450 CreateRenderText(text(), alignment, directionality, elide_behavior);
451 render_text->SetDisplayRect(rect);
452 render_text->SetMultiline(multi_line());
453 render_text->SetWordWrapBehavior(render_text_->word_wrap_behavior());
454 lines_.push_back(render_text.Pass());
455 } else {
456 std::vector<base::string16> lines = GetLinesForWidth(rect.width());
457 if (lines.size() > 1)
458 rect.set_height(std::max(line_height(), font_list().GetHeight()));
460 const int bottom = GetContentsBounds().bottom();
461 for (size_t i = 0; i < lines.size() && rect.y() <= bottom; ++i) {
462 scoped_ptr<gfx::RenderText> line =
463 CreateRenderText(lines[i], alignment, directionality, elide_behavior);
464 line->SetDisplayRect(rect);
465 lines_.push_back(line.Pass());
466 rect.set_y(rect.y() + rect.height());
468 // Append the remaining text to the last visible line.
469 for (size_t i = lines_.size(); i < lines.size(); ++i)
470 lines_.back()->SetText(lines_.back()->text() + lines[i]);
472 RecalculateColors();
475 gfx::Rect Label::GetFocusBounds() {
476 MaybeBuildRenderTextLines();
478 gfx::Rect focus_bounds;
479 if (lines_.empty()) {
480 focus_bounds = gfx::Rect(GetTextSize());
481 } else {
482 for (size_t i = 0; i < lines_.size(); ++i) {
483 gfx::Point origin;
484 origin += lines_[i]->GetLineOffset(0);
485 focus_bounds.Union(gfx::Rect(origin, lines_[i]->GetStringSize()));
489 focus_bounds.Inset(-kFocusBorderPadding, -kFocusBorderPadding);
490 focus_bounds.Intersect(GetLocalBounds());
491 return focus_bounds;
494 std::vector<base::string16> Label::GetLinesForWidth(int width) const {
495 std::vector<base::string16> lines;
496 // |width| can be 0 when getting the default text size, in that case
497 // the ideal lines (i.e. broken at newline characters) are wanted.
498 if (width <= 0) {
499 base::SplitString(render_text_->GetDisplayText(), '\n', &lines);
500 } else {
501 gfx::ElideRectangleText(render_text_->GetDisplayText(), font_list(), width,
502 std::numeric_limits<int>::max(),
503 render_text_->word_wrap_behavior(), &lines);
505 return lines;
508 gfx::Size Label::GetTextSize() const {
509 gfx::Size size;
510 if (text().empty()) {
511 size = gfx::Size(0, std::max(line_height(), font_list().GetHeight()));
512 } else if (!multi_line() || render_text_->MultilineSupported()) {
513 // Cancel the display rect of |render_text_|. The display rect may be
514 // specified in GetHeightForWidth(), and specifying empty Rect cancels
515 // its effect. See also the comment in GetHeightForWidth().
516 // TODO(mukai): use gfx::Rect() to compute the ideal size rather than
517 // the current width(). See crbug.com/468494, crbug.com/467526, and
518 // the comment for MultilinePreferredSizeTest in label_unittest.cc.
519 render_text_->SetDisplayRect(gfx::Rect(0, 0, width(), 0));
520 size = render_text_->GetStringSize();
521 } else {
522 // Get the natural text size, unelided and only wrapped on newlines.
523 std::vector<base::string16> lines = GetLinesForWidth(width());
524 scoped_ptr<gfx::RenderText> render_text(gfx::RenderText::CreateInstance());
525 render_text->SetFontList(font_list());
526 for (size_t i = 0; i < lines.size(); ++i) {
527 render_text->SetText(lines[i]);
528 const gfx::Size line = render_text->GetStringSize();
529 size.set_width(std::max(size.width(), line.width()));
530 size.set_height(std::max(line_height(), size.height() + line.height()));
533 const gfx::Insets shadow_margin = -gfx::ShadowValue::GetMargin(shadows());
534 size.Enlarge(shadow_margin.width(), shadow_margin.height());
535 return size;
538 void Label::RecalculateColors() {
539 actual_enabled_color_ = auto_color_readability_ ?
540 color_utils::GetReadableColor(requested_enabled_color_,
541 background_color_) :
542 requested_enabled_color_;
543 actual_disabled_color_ = auto_color_readability_ ?
544 color_utils::GetReadableColor(requested_disabled_color_,
545 background_color_) :
546 requested_disabled_color_;
548 SkColor color = enabled() ? actual_enabled_color_ : actual_disabled_color_;
549 bool subpixel_rendering_suppressed =
550 SkColorGetA(background_color_) != 0xFF || !subpixel_rendering_enabled_;
551 for (size_t i = 0; i < lines_.size(); ++i) {
552 lines_[i]->SetColor(color);
553 lines_[i]->set_subpixel_rendering_suppressed(subpixel_rendering_suppressed);
555 SchedulePaint();
558 void Label::UpdateColorsFromTheme(const ui::NativeTheme* theme) {
559 if (!enabled_color_set_) {
560 requested_enabled_color_ = theme->GetSystemColor(
561 ui::NativeTheme::kColorId_LabelEnabledColor);
563 if (!disabled_color_set_) {
564 requested_disabled_color_ = theme->GetSystemColor(
565 ui::NativeTheme::kColorId_LabelDisabledColor);
567 if (!background_color_set_) {
568 background_color_ = theme->GetSystemColor(
569 ui::NativeTheme::kColorId_LabelBackgroundColor);
571 RecalculateColors();
574 bool Label::ShouldShowDefaultTooltip() const {
575 const gfx::Size text_size = GetTextSize();
576 const gfx::Size size = GetContentsBounds().size();
577 return !obscured() && (text_size.width() > size.width() ||
578 (multi_line() && text_size.height() > size.height()));
581 } // namespace views