Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1063)

Side by Side Diff: ui/views/controls/label.cc

Issue 867003002: Cache gfx::RenderText instances in views::Label. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: rebase Created 5 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « ui/views/controls/label.h ('k') | ui/views/controls/label_unittest.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "ui/views/controls/label.h" 5 #include "ui/views/controls/label.h"
6 6
7 #include <algorithm> 7 #include <algorithm>
8 #include <cmath> 8 #include <cmath>
9 #include <limits> 9 #include <limits>
10 #include <vector> 10 #include <vector>
11 11
12 #include "base/i18n/rtl.h" 12 #include "base/i18n/rtl.h"
13 #include "base/logging.h" 13 #include "base/logging.h"
14 #include "base/profiler/scoped_tracker.h" 14 #include "base/profiler/scoped_tracker.h"
15 #include "base/strings/string_split.h" 15 #include "base/strings/string_split.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/utf_string_conversions.h" 16 #include "base/strings/utf_string_conversions.h"
18 #include "ui/accessibility/ax_view_state.h" 17 #include "ui/accessibility/ax_view_state.h"
19 #include "ui/gfx/canvas.h" 18 #include "ui/gfx/canvas.h"
20 #include "ui/gfx/color_utils.h" 19 #include "ui/gfx/color_utils.h"
21 #include "ui/gfx/geometry/insets.h" 20 #include "ui/gfx/geometry/insets.h"
22 #include "ui/gfx/text_elider.h" 21 #include "ui/gfx/text_elider.h"
23 #include "ui/gfx/text_utils.h"
24 #include "ui/gfx/utf16_indexing.h"
25 #include "ui/native_theme/native_theme.h" 22 #include "ui/native_theme/native_theme.h"
26 #include "ui/views/background.h"
27
28 namespace {
29
30 const int kCachedSizeLimit = 10;
31 const base::char16 kPasswordReplacementChar = '*';
32
33 } // namespace
34 23
35 namespace views { 24 namespace views {
36 25
37 // static 26 // static
38 const char Label::kViewClassName[] = "Label"; 27 const char Label::kViewClassName[] = "Label";
39 const int Label::kFocusBorderPadding = 1; 28 const int Label::kFocusBorderPadding = 1;
40 29
41 Label::Label() { 30 Label::Label() {
42 Init(base::string16(), gfx::FontList()); 31 Init(base::string16(), gfx::FontList());
43 } 32 }
44 33
45 Label::Label(const base::string16& text) { 34 Label::Label(const base::string16& text) {
46 Init(text, gfx::FontList()); 35 Init(text, gfx::FontList());
47 } 36 }
48 37
49 Label::Label(const base::string16& text, const gfx::FontList& font_list) { 38 Label::Label(const base::string16& text, const gfx::FontList& font_list) {
50 Init(text, font_list); 39 Init(text, font_list);
51 } 40 }
52 41
53 Label::~Label() { 42 Label::~Label() {
54 } 43 }
55 44
56 void Label::SetFontList(const gfx::FontList& font_list) { 45 void Label::SetFontList(const gfx::FontList& font_list) {
57 is_first_paint_text_ = true; 46 is_first_paint_text_ = true;
58 font_list_ = font_list; 47 render_text_->SetFontList(font_list);
59 ResetLayoutCache(); 48 ResetLayout();
60 PreferredSizeChanged();
61 SchedulePaint();
62 } 49 }
63 50
64 void Label::SetText(const base::string16& text) { 51 void Label::SetText(const base::string16& new_text) {
65 if (text != text_) 52 if (new_text == text())
66 SetTextInternal(text); 53 return;
67 }
68
69 void Label::SetTextInternal(const base::string16& text) {
70 is_first_paint_text_ = true; 54 is_first_paint_text_ = true;
71 text_ = text; 55 render_text_->SetText(new_text);
72 56 ResetLayout();
73 if (obscured_) {
74 size_t obscured_text_length =
75 static_cast<size_t>(gfx::UTF16IndexToOffset(text_, 0, text_.length()));
76 layout_text_.assign(obscured_text_length, kPasswordReplacementChar);
77 } else {
78 layout_text_ = text_;
79 }
80
81 ResetLayoutCache();
82 PreferredSizeChanged();
83 SchedulePaint();
84 } 57 }
85 58
86 void Label::SetAutoColorReadabilityEnabled(bool enabled) { 59 void Label::SetAutoColorReadabilityEnabled(bool enabled) {
60 if (auto_color_readability_ == enabled)
61 return;
87 is_first_paint_text_ = true; 62 is_first_paint_text_ = true;
88 auto_color_readability_ = enabled; 63 auto_color_readability_ = enabled;
89 RecalculateColors(); 64 RecalculateColors();
90 } 65 }
91 66
92 void Label::SetEnabledColor(SkColor color) { 67 void Label::SetEnabledColor(SkColor color) {
68 if (enabled_color_set_ && requested_enabled_color_ == color)
69 return;
93 is_first_paint_text_ = true; 70 is_first_paint_text_ = true;
94 requested_enabled_color_ = color; 71 requested_enabled_color_ = color;
95 enabled_color_set_ = true; 72 enabled_color_set_ = true;
96 RecalculateColors(); 73 RecalculateColors();
97 } 74 }
98 75
99 void Label::SetDisabledColor(SkColor color) { 76 void Label::SetDisabledColor(SkColor color) {
77 if (disabled_color_set_ && requested_disabled_color_ == color)
78 return;
100 is_first_paint_text_ = true; 79 is_first_paint_text_ = true;
101 requested_disabled_color_ = color; 80 requested_disabled_color_ = color;
102 disabled_color_set_ = true; 81 disabled_color_set_ = true;
103 RecalculateColors(); 82 RecalculateColors();
104 } 83 }
105 84
106 void Label::SetBackgroundColor(SkColor color) { 85 void Label::SetBackgroundColor(SkColor color) {
86 if (background_color_set_ && background_color_ == color)
87 return;
107 is_first_paint_text_ = true; 88 is_first_paint_text_ = true;
108 background_color_ = color; 89 background_color_ = color;
109 background_color_set_ = true; 90 background_color_set_ = true;
110 RecalculateColors(); 91 RecalculateColors();
111 cached_draw_params_.text.clear();
112 } 92 }
113 93
114 void Label::SetShadows(const gfx::ShadowValues& shadows) { 94 void Label::SetShadows(const gfx::ShadowValues& shadows) {
95 // TODO(mukai): early exit if the specified shadows are same.
115 is_first_paint_text_ = true; 96 is_first_paint_text_ = true;
116 shadows_ = shadows; 97 render_text_->set_shadows(shadows);
117 ResetLayoutCache(); 98 ResetLayout();
118 } 99 }
119 100
120 void Label::SetSubpixelRenderingEnabled(bool subpixel_rendering_enabled) { 101 void Label::SetSubpixelRenderingEnabled(bool subpixel_rendering_enabled) {
102 if (subpixel_rendering_enabled_ == subpixel_rendering_enabled)
103 return;
121 is_first_paint_text_ = true; 104 is_first_paint_text_ = true;
122 subpixel_rendering_enabled_ = subpixel_rendering_enabled; 105 subpixel_rendering_enabled_ = subpixel_rendering_enabled;
106 RecalculateColors();
123 } 107 }
124 108
125 void Label::SetHorizontalAlignment(gfx::HorizontalAlignment alignment) { 109 void Label::SetHorizontalAlignment(gfx::HorizontalAlignment alignment) {
126 is_first_paint_text_ = true;
127 // If the UI layout is right-to-left, flip the alignment direction. 110 // If the UI layout is right-to-left, flip the alignment direction.
128 if (base::i18n::IsRTL() && 111 if (base::i18n::IsRTL() &&
129 (alignment == gfx::ALIGN_LEFT || alignment == gfx::ALIGN_RIGHT)) { 112 (alignment == gfx::ALIGN_LEFT || alignment == gfx::ALIGN_RIGHT)) {
130 alignment = (alignment == gfx::ALIGN_LEFT) ? 113 alignment = (alignment == gfx::ALIGN_LEFT) ?
131 gfx::ALIGN_RIGHT : gfx::ALIGN_LEFT; 114 gfx::ALIGN_RIGHT : gfx::ALIGN_LEFT;
132 } 115 }
133 if (horizontal_alignment_ != alignment) { 116 if (horizontal_alignment() == alignment)
134 horizontal_alignment_ = alignment; 117 return;
135 SchedulePaint(); 118 is_first_paint_text_ = true;
136 } 119 render_text_->SetHorizontalAlignment(alignment);
137 } 120 ResetLayout();
138
139 gfx::HorizontalAlignment Label::GetHorizontalAlignment() const {
140 if (horizontal_alignment_ != gfx::ALIGN_TO_HEAD)
141 return horizontal_alignment_;
142
143 const base::i18n::TextDirection dir =
144 base::i18n::GetFirstStrongCharacterDirection(layout_text_);
145 return dir == base::i18n::RIGHT_TO_LEFT ? gfx::ALIGN_RIGHT : gfx::ALIGN_LEFT;
146 } 121 }
147 122
148 void Label::SetLineHeight(int height) { 123 void Label::SetLineHeight(int height) {
124 if (line_height() == height)
125 return;
149 is_first_paint_text_ = true; 126 is_first_paint_text_ = true;
150 if (height != line_height_) { 127 render_text_->SetMinLineHeight(height);
151 line_height_ = height; 128 ResetLayout();
152 ResetLayoutCache();
153 PreferredSizeChanged();
154 SchedulePaint();
155 }
156 } 129 }
157 130
158 void Label::SetMultiLine(bool multi_line) { 131 void Label::SetMultiLine(bool multi_line) {
159 is_first_paint_text_ = true;
160 DCHECK(!multi_line || (elide_behavior_ == gfx::ELIDE_TAIL || 132 DCHECK(!multi_line || (elide_behavior_ == gfx::ELIDE_TAIL ||
161 elide_behavior_ == gfx::NO_ELIDE)); 133 elide_behavior_ == gfx::NO_ELIDE));
162 if (multi_line != multi_line_) { 134 if (this->multi_line() == multi_line)
163 multi_line_ = multi_line; 135 return;
164 ResetLayoutCache(); 136 is_first_paint_text_ = true;
165 PreferredSizeChanged(); 137 multi_line_ = multi_line;
166 SchedulePaint(); 138 if (render_text_->MultilineSupported())
167 } 139 render_text_->SetMultiline(multi_line);
140 render_text_->SetReplaceNewlineCharsWithSymbols(!multi_line);
141 ResetLayout();
168 } 142 }
169 143
170 void Label::SetObscured(bool obscured) { 144 void Label::SetObscured(bool obscured) {
145 if (this->obscured() == obscured)
146 return;
171 is_first_paint_text_ = true; 147 is_first_paint_text_ = true;
172 if (obscured != obscured_) { 148 render_text_->SetObscured(obscured);
173 obscured_ = obscured; 149 ResetLayout();
174 SetTextInternal(text_);
175 }
176 } 150 }
177 151
178 void Label::SetAllowCharacterBreak(bool allow_character_break) { 152 void Label::SetAllowCharacterBreak(bool allow_character_break) {
153 if (allow_character_break_ == allow_character_break)
154 return;
179 is_first_paint_text_ = true; 155 is_first_paint_text_ = true;
180 if (allow_character_break != allow_character_break_) { 156 allow_character_break_ = allow_character_break;
181 allow_character_break_ = allow_character_break; 157 ResetLayout();
182 ResetLayoutCache();
183 PreferredSizeChanged();
184 SchedulePaint();
185 }
186 } 158 }
187 159
188 void Label::SetElideBehavior(gfx::ElideBehavior elide_behavior) { 160 void Label::SetElideBehavior(gfx::ElideBehavior elide_behavior) {
161 DCHECK(!multi_line() || (elide_behavior_ == gfx::ELIDE_TAIL ||
162 elide_behavior_ == gfx::NO_ELIDE));
163 if (elide_behavior_ == elide_behavior)
164 return;
189 is_first_paint_text_ = true; 165 is_first_paint_text_ = true;
190 DCHECK(!multi_line_ || (elide_behavior_ == gfx::ELIDE_TAIL || 166 elide_behavior_ = elide_behavior;
191 elide_behavior_ == gfx::NO_ELIDE)); 167 ResetLayout();
192 if (elide_behavior != elide_behavior_) {
193 elide_behavior_ = elide_behavior;
194 ResetLayoutCache();
195 PreferredSizeChanged();
196 SchedulePaint();
197 }
198 } 168 }
199 169
200 void Label::SetTooltipText(const base::string16& tooltip_text) { 170 void Label::SetTooltipText(const base::string16& tooltip_text) {
201 DCHECK(handles_tooltips_); 171 DCHECK(handles_tooltips_);
202 tooltip_text_ = tooltip_text; 172 tooltip_text_ = tooltip_text;
203 } 173 }
204 174
205 void Label::SetHandlesTooltips(bool enabled) { 175 void Label::SetHandlesTooltips(bool enabled) {
206 handles_tooltips_ = enabled; 176 handles_tooltips_ = enabled;
207 } 177 }
208 178
209 void Label::SizeToFit(int max_width) { 179 void Label::SizeToFit(int max_width) {
210 DCHECK(multi_line_); 180 DCHECK(multi_line());
211 181 max_width_ = max_width;
212 std::vector<base::string16> lines;
213 base::SplitString(layout_text_, '\n', &lines);
214
215 int label_width = 0;
216 for (std::vector<base::string16>::const_iterator iter = lines.begin();
217 iter != lines.end(); ++iter) {
218 label_width = std::max(label_width, gfx::GetStringWidth(*iter, font_list_));
219 }
220
221 label_width += GetInsets().width();
222
223 if (max_width > 0)
224 label_width = std::min(label_width, max_width);
225
226 SetBounds(x(), y(), label_width, 0);
227 SizeToPreferredSize(); 182 SizeToPreferredSize();
228 } 183 }
229 184
230 const base::string16& Label::GetLayoutTextForTesting() const { 185 base::string16 Label::GetDisplayTextForTesting() {
231 return layout_text_; 186 lines_.clear();
187 MaybeBuildRenderTextLines();
188 base::string16 result;
189 if (lines_.empty())
190 return result;
191 result.append(lines_[0]->GetDisplayText());
192 for (size_t i = 1; i < lines_.size(); ++i) {
193 result.append(1, '\n');
194 result.append(lines_[i]->GetDisplayText());
195 }
196 return result;
232 } 197 }
233 198
234 gfx::Insets Label::GetInsets() const { 199 gfx::Insets Label::GetInsets() const {
235 gfx::Insets insets = View::GetInsets(); 200 gfx::Insets insets = View::GetInsets();
236 if (focusable()) { 201 if (focusable()) {
237 insets += gfx::Insets(kFocusBorderPadding, kFocusBorderPadding, 202 insets += gfx::Insets(kFocusBorderPadding, kFocusBorderPadding,
238 kFocusBorderPadding, kFocusBorderPadding); 203 kFocusBorderPadding, kFocusBorderPadding);
239 } 204 }
240 return insets; 205 return insets;
241 } 206 }
242 207
243 int Label::GetBaseline() const { 208 int Label::GetBaseline() const {
244 return GetInsets().top() + font_list_.GetBaseline(); 209 return GetInsets().top() + font_list().GetBaseline();
245 } 210 }
246 211
247 gfx::Size Label::GetPreferredSize() const { 212 gfx::Size Label::GetPreferredSize() const {
248 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed. 213 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
249 tracked_objects::ScopedTracker tracking_profile( 214 tracked_objects::ScopedTracker tracking_profile(
250 FROM_HERE_WITH_EXPLICIT_FUNCTION("431326 Label::GetPreferredSize")); 215 FROM_HERE_WITH_EXPLICIT_FUNCTION("431326 Label::GetPreferredSize"));
251 216
252 // Return a size of (0, 0) if the label is not visible and if the 217 // Return a size of (0, 0) if the label is not visible and if the
253 // collapse_when_hidden_ flag is set. 218 // |collapse_when_hidden_| flag is set.
254 // TODO(munjal): This logic probably belongs to the View class. But for now, 219 // TODO(munjal): This logic probably belongs to the View class. But for now,
255 // put it here since putting it in View class means all inheriting classes 220 // put it here since putting it in View class means all inheriting classes
256 // need ot respect the collapse_when_hidden_ flag. 221 // need to respect the |collapse_when_hidden_| flag.
257 if (!visible() && collapse_when_hidden_) 222 if (!visible() && collapse_when_hidden_)
258 return gfx::Size(); 223 return gfx::Size();
259 224
225 if (multi_line() && max_width_ != 0 && !text().empty())
226 return gfx::Size(max_width_, GetHeightForWidth(max_width_));
227
260 gfx::Size size(GetTextSize()); 228 gfx::Size size(GetTextSize());
261 gfx::Insets insets = GetInsets(); 229 const gfx::Insets insets = GetInsets();
262 size.Enlarge(insets.width(), insets.height()); 230 size.Enlarge(insets.width(), insets.height());
263 return size; 231 return size;
264 } 232 }
265 233
266 gfx::Size Label::GetMinimumSize() const { 234 gfx::Size Label::GetMinimumSize() const {
267 gfx::Size text_size(GetTextSize()); 235 if (!visible() && collapse_when_hidden_)
268 if ((!visible() && collapse_when_hidden_) || text_size.IsEmpty())
269 return gfx::Size(); 236 return gfx::Size();
270 237
271 gfx::Size size(gfx::GetStringWidth(base::string16(gfx::kEllipsisUTF16), 238 gfx::Size size(0, font_list().GetHeight());
272 font_list_), 239 if (elide_behavior_ == gfx::ELIDE_HEAD ||
273 font_list_.GetHeight()); 240 elide_behavior_ == gfx::ELIDE_MIDDLE ||
274 size.SetToMin(text_size); // The actual text may be shorter than an ellipsis. 241 elide_behavior_ == gfx::ELIDE_TAIL ||
275 gfx::Insets insets = GetInsets(); 242 elide_behavior_ == gfx::ELIDE_EMAIL) {
276 size.Enlarge(insets.width(), insets.height()); 243 size.set_width(gfx::Canvas::GetStringWidth(
244 base::string16(gfx::kEllipsisUTF16), font_list()));
245 }
246 if (!multi_line())
247 size.SetToMin(GetTextSize());
248 size.Enlarge(GetInsets().width(), GetInsets().height());
277 return size; 249 return size;
278 } 250 }
279 251
280 int Label::GetHeightForWidth(int w) const { 252 int Label::GetHeightForWidth(int w) const {
281 if (!multi_line_) 253 if (!visible() && collapse_when_hidden_)
282 return View::GetHeightForWidth(w); 254 return 0;
283 255
284 w = std::max(0, w - GetInsets().width()); 256 w -= GetInsets().width();
257 if (!multi_line() || text().empty() || w <= 0)
258 return std::max(line_height(), font_list().GetHeight());
285 259
286 for (size_t i = 0; i < cached_heights_.size(); ++i) { 260 int height = 0;
287 const gfx::Size& s = cached_heights_[i]; 261 // RenderText doesn't support character breaks.
288 if (s.width() == w) 262 // TODO(mukai): remove this restriction.
289 return s.height() + GetInsets().height(); 263 if (render_text_->MultilineSupported() && !allow_character_break_) {
264 // SetDisplayRect() has a side effect for later calls of GetStringSize().
265 // Be careful to invoke |render_text_->SetDisplayRect(gfx::Rect())| to
266 // cancel this effect before the next time GetStringSize() is called.
267 // It would be beneficial not to cancel here, considering that some layout
268 // managers invoke GetHeightForWidth() for the same width multiple times
269 // and |render_text_| can cache the height.
270 render_text_->SetDisplayRect(gfx::Rect(0, 0, w, 0));
271 height = render_text_->GetStringSize().height();
272 } else {
273 std::vector<base::string16> lines = GetLinesForWidth(w);
274 height = lines.size() * std::max(line_height(), font_list().GetHeight());
290 } 275 }
276 height -= gfx::ShadowValue::GetMargin(render_text_->shadows()).height();
277 return height + GetInsets().height();
278 }
291 279
292 int cache_width = w; 280 void Label::Layout() {
293 281 lines_.clear();
294 int h = font_list_.GetHeight();
295 // Flags returned in the cached |DrawStringParams| has a different value
296 // from the result of |ComputeDrawStringFlags()|. The latter is needed here.
297 const int flags = ComputeDrawStringFlags();
298 gfx::Canvas::SizeStringInt(
299 layout_text_, font_list_, &w, &h, line_height_, flags);
300 cached_heights_[cached_heights_cursor_] = gfx::Size(cache_width, h);
301 cached_heights_cursor_ = (cached_heights_cursor_ + 1) % kCachedSizeLimit;
302 return h + GetInsets().height();
303 } 282 }
304 283
305 const char* Label::GetClassName() const { 284 const char* Label::GetClassName() const {
306 return kViewClassName; 285 return kViewClassName;
307 } 286 }
308 287
309 View* Label::GetTooltipHandlerForPoint(const gfx::Point& point) { 288 View* Label::GetTooltipHandlerForPoint(const gfx::Point& point) {
310 if (!handles_tooltips_ || 289 if (!handles_tooltips_ ||
311 (tooltip_text_.empty() && !ShouldShowDefaultTooltip())) 290 (tooltip_text_.empty() && !ShouldShowDefaultTooltip()))
312 return NULL; 291 return NULL;
313 292
314 return HitTestPoint(point) ? this : NULL; 293 return HitTestPoint(point) ? this : NULL;
315 } 294 }
316 295
317 bool Label::CanProcessEventsWithinSubtree() const { 296 bool Label::CanProcessEventsWithinSubtree() const {
318 // Send events to the parent view for handling. 297 // Send events to the parent view for handling.
319 return false; 298 return false;
320 } 299 }
321 300
322 void Label::GetAccessibleState(ui::AXViewState* state) { 301 void Label::GetAccessibleState(ui::AXViewState* state) {
323 state->role = ui::AX_ROLE_STATIC_TEXT; 302 state->role = ui::AX_ROLE_STATIC_TEXT;
324 state->AddStateFlag(ui::AX_STATE_READ_ONLY); 303 state->AddStateFlag(ui::AX_STATE_READ_ONLY);
325 state->name = layout_text_; 304 // Note that |render_text_| is never elided (see the comment in Init() too).
305 state->name = render_text_->GetDisplayText();
326 } 306 }
327 307
328 bool Label::GetTooltipText(const gfx::Point& p, base::string16* tooltip) const { 308 bool Label::GetTooltipText(const gfx::Point& p, base::string16* tooltip) const {
329 if (!handles_tooltips_) 309 if (!handles_tooltips_)
330 return false; 310 return false;
331 311
332 if (!tooltip_text_.empty()) { 312 if (!tooltip_text_.empty()) {
333 tooltip->assign(tooltip_text_); 313 tooltip->assign(tooltip_text_);
334 return true; 314 return true;
335 } 315 }
336 316
337 if (ShouldShowDefaultTooltip()) { 317 if (ShouldShowDefaultTooltip()) {
338 *tooltip = layout_text_; 318 // Note that |render_text_| is never elided (see the comment in Init() too).
319 tooltip->assign(render_text_->GetDisplayText());
339 return true; 320 return true;
340 } 321 }
341 322
342 return false; 323 return false;
343 } 324 }
344 325
345 void Label::PaintText(gfx::Canvas* canvas, 326 void Label::OnEnabledChanged() {
346 const base::string16& text, 327 RecalculateColors();
347 const gfx::Rect& text_bounds,
348 int flags) {
349 SkColor color = enabled() ? actual_enabled_color_ : actual_disabled_color_;
350 if (elide_behavior_ == gfx::FADE_TAIL &&
351 text_bounds.width() < GetTextSize().width()) {
352 canvas->DrawFadedString(text, font_list_, color, text_bounds, flags);
353 } else {
354 canvas->DrawStringRectWithShadows(text, font_list_, color, text_bounds,
355 line_height_, flags, shadows_);
356 }
357
358 if (HasFocus()) {
359 gfx::Rect focus_bounds = text_bounds;
360 focus_bounds.Inset(-kFocusBorderPadding, -kFocusBorderPadding);
361 canvas->DrawFocusRect(focus_bounds);
362 }
363 } 328 }
364 329
365 gfx::Size Label::GetTextSize() const { 330 void Label::PaintText(gfx::Canvas* canvas) {
366 if (!text_size_valid_) { 331 MaybeBuildRenderTextLines();
367 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed. 332 for (size_t i = 0; i < lines_.size(); ++i)
368 tracked_objects::ScopedTracker tracking_profile1( 333 lines_[i]->Draw(canvas);
369 FROM_HERE_WITH_EXPLICIT_FUNCTION("431326 Label::GetTextSize1"));
370
371 // For single-line strings, we supply the largest possible width, because
372 // while adding NO_ELLIPSIS to the flags works on Windows for forcing
373 // SizeStringInt() to calculate the desired width, it doesn't seem to work
374 // on Linux.
375 int w = multi_line_ ?
376 GetAvailableRect().width() : std::numeric_limits<int>::max();
377 int h = font_list_.GetHeight();
378 // For single-line strings, ignore the available width and calculate how
379 // wide the text wants to be.
380 // Call |ComputeDrawStringFlags()| instead of |CalculateDrawStringParams()|
381 // here since the latter calls this function and causes infinite recursion.
382 int flags = ComputeDrawStringFlags();
383 if (!multi_line_)
384 flags |= gfx::Canvas::NO_ELLIPSIS;
385 {
386 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is
387 // fixed.
388 tracked_objects::ScopedTracker tracking_profile2(
389 FROM_HERE_WITH_EXPLICIT_FUNCTION("431326 Label::GetTextSize2"));
390
391 gfx::Canvas::SizeStringInt(layout_text_, font_list_, &w, &h, line_height_,
392 flags);
393 }
394 text_size_.SetSize(w, h);
395 const gfx::Insets shadow_margin = -gfx::ShadowValue::GetMargin(shadows_);
396 text_size_.Enlarge(shadow_margin.width(), shadow_margin.height());
397 text_size_valid_ = true;
398 }
399
400 return text_size_;
401 } 334 }
402 335
403 void Label::OnBoundsChanged(const gfx::Rect& previous_bounds) { 336 void Label::OnBoundsChanged(const gfx::Rect& previous_bounds) {
404 text_size_valid_ &= !multi_line_; 337 if (previous_bounds.size() != size())
405 cached_draw_params_.text.clear(); 338 InvalidateLayout();
406 } 339 }
407 340
408 void Label::OnPaint(gfx::Canvas* canvas) { 341 void Label::OnPaint(gfx::Canvas* canvas) {
409 OnPaintBackground(canvas); 342 View::OnPaint(canvas);
410 // We skip painting the focus border because it is being handled seperately by
411 // some subclasses of Label. We do not want View's focus border painting to
412 // interfere with that.
413 OnPaintBorder(canvas);
414 if (layout_text_.empty())
415 return;
416
417 const DrawStringParams* params = CalculateDrawStringParams();
418 if (is_first_paint_text_) { 343 if (is_first_paint_text_) {
419 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed. 344 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
420 tracked_objects::ScopedTracker tracking_profile( 345 tracked_objects::ScopedTracker tracking_profile(
421 FROM_HERE_WITH_EXPLICIT_FUNCTION("431326 Label::PaintText first")); 346 FROM_HERE_WITH_EXPLICIT_FUNCTION("431326 Label::PaintText first"));
422 347
423 is_first_paint_text_ = false; 348 is_first_paint_text_ = false;
424 PaintText(canvas, params->text, params->bounds, params->flags); 349 PaintText(canvas);
425 } else { 350 } else {
426 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed. 351 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
427 tracked_objects::ScopedTracker tracking_profile( 352 tracked_objects::ScopedTracker tracking_profile(
428 FROM_HERE_WITH_EXPLICIT_FUNCTION("431326 Label::PaintText not first")); 353 FROM_HERE_WITH_EXPLICIT_FUNCTION("431326 Label::PaintText not first"));
429 354
430 PaintText(canvas, params->text, params->bounds, params->flags); 355 PaintText(canvas);
356 }
357 if (HasFocus()) {
358 gfx::Rect focus_bounds = GetLocalBounds();
359 focus_bounds.Inset(-kFocusBorderPadding, -kFocusBorderPadding);
360 canvas->DrawFocusRect(focus_bounds);
431 } 361 }
432 } 362 }
433 363
434 void Label::OnNativeThemeChanged(const ui::NativeTheme* theme) { 364 void Label::OnNativeThemeChanged(const ui::NativeTheme* theme) {
435 UpdateColorsFromTheme(theme); 365 UpdateColorsFromTheme(theme);
436 } 366 }
437 367
438 void Label::OnDeviceScaleFactorChanged(float device_scale_factor) { 368 void Label::OnDeviceScaleFactorChanged(float device_scale_factor) {
439 View::OnDeviceScaleFactorChanged(device_scale_factor); 369 View::OnDeviceScaleFactorChanged(device_scale_factor);
440 // When the device scale factor is changed, some font rendering parameters is 370 // When the device scale factor is changed, some font rendering parameters is
441 // changed (especially, hinting). The bounding box of the text has to be 371 // changed (especially, hinting). The bounding box of the text has to be
442 // re-computed based on the new parameters. See crbug.com/441439 372 // re-computed based on the new parameters. See crbug.com/441439
443 ResetLayoutCache(); 373 ResetLayout();
374 }
375
376 void Label::VisibilityChanged(View* starting_from, bool is_visible) {
377 if (!is_visible)
378 lines_.clear();
379 }
380
381 void Label::Init(const base::string16& text, const gfx::FontList& font_list) {
382 render_text_.reset(gfx::RenderText::CreateInstance());
383 render_text_->SetHorizontalAlignment(gfx::ALIGN_CENTER);
384 render_text_->SetDirectionalityMode(gfx::DIRECTIONALITY_FROM_TEXT);
385 // NOTE: |render_text_| should not be elided at all. This is used to keep some
386 // properties and to compute the size of the string.
387 render_text_->SetElideBehavior(gfx::NO_ELIDE);
388 render_text_->SetFontList(font_list);
389 render_text_->SetCursorEnabled(false);
390
391 elide_behavior_ = gfx::ELIDE_TAIL;
392 enabled_color_set_ = disabled_color_set_ = background_color_set_ = false;
393 subpixel_rendering_enabled_ = true;
394 auto_color_readability_ = true;
395 multi_line_ = false;
396 UpdateColorsFromTheme(ui::NativeTheme::instance());
397 handles_tooltips_ = true;
398 collapse_when_hidden_ = false;
399 allow_character_break_ = false;
400 max_width_ = 0;
401 is_first_paint_text_ = true;
402 SetText(text);
403 }
404
405 void Label::ResetLayout() {
406 InvalidateLayout();
444 PreferredSizeChanged(); 407 PreferredSizeChanged();
445 SchedulePaint(); 408 SchedulePaint();
446 } 409 }
447 410
448 void Label::Init(const base::string16& text, const gfx::FontList& font_list) { 411 scoped_ptr<gfx::RenderText> Label::CreateRenderText(
449 font_list_ = font_list; 412 const base::string16& text,
450 enabled_color_set_ = disabled_color_set_ = background_color_set_ = false; 413 gfx::HorizontalAlignment alignment,
451 subpixel_rendering_enabled_ = true; 414 gfx::DirectionalityMode directionality,
452 auto_color_readability_ = true; 415 gfx::ElideBehavior elide_behavior) {
453 UpdateColorsFromTheme(ui::NativeTheme::instance()); 416 scoped_ptr<gfx::RenderText> render_text(
454 horizontal_alignment_ = gfx::ALIGN_CENTER; 417 render_text_->CreateInstanceOfSameType());
455 line_height_ = 0; 418 render_text->SetHorizontalAlignment(alignment);
456 multi_line_ = false; 419 render_text->SetDirectionalityMode(directionality);
457 obscured_ = false; 420 render_text->SetElideBehavior(elide_behavior);
458 allow_character_break_ = false; 421 render_text->SetObscured(obscured());
459 elide_behavior_ = gfx::ELIDE_TAIL; 422 render_text->SetMinLineHeight(line_height());
460 handles_tooltips_ = true; 423 render_text->SetFontList(font_list());
461 collapse_when_hidden_ = false; 424 render_text->set_shadows(shadows());
462 cached_heights_.resize(kCachedSizeLimit); 425 render_text->SetCursorEnabled(false);
463 ResetLayoutCache(); 426 render_text->SetText(text);
464 is_first_paint_text_ = true; 427 return render_text.Pass();
428 }
465 429
466 SetText(text); 430 void Label::MaybeBuildRenderTextLines() {
431 if (!lines_.empty())
432 return;
433
434 gfx::Rect rect = GetContentsBounds();
435 if (rect.IsEmpty())
436 return;
437
438 gfx::HorizontalAlignment alignment = horizontal_alignment();
439 gfx::DirectionalityMode directionality = render_text_->directionality_mode();
440 if (multi_line()) {
441 // Force the directionality and alignment of the first line on other lines.
442 bool rtl =
443 render_text_->GetDisplayTextDirection() == base::i18n::RIGHT_TO_LEFT;
444 if (alignment == gfx::ALIGN_TO_HEAD)
445 alignment = rtl ? gfx::ALIGN_RIGHT : gfx::ALIGN_LEFT;
446 directionality =
447 rtl ? gfx::DIRECTIONALITY_FORCE_RTL : gfx::DIRECTIONALITY_FORCE_LTR;
448 }
449
450 // Text eliding is not supported for multi-lined Labels.
451 // TODO(mukai): Add multi-lined elided text support.
452 gfx::ElideBehavior elide_behavior =
453 multi_line() ? gfx::NO_ELIDE : elide_behavior_;
454 if (!multi_line() ||
455 (render_text_->MultilineSupported() && !allow_character_break_)) {
456 scoped_ptr<gfx::RenderText> render_text =
457 CreateRenderText(text(), alignment, directionality, elide_behavior);
458 render_text->SetDisplayRect(rect);
459 render_text->SetMultiline(multi_line());
460 lines_.push_back(render_text.release());
461 } else {
462 std::vector<base::string16> lines = GetLinesForWidth(rect.width());
463 if (lines.size() > 1)
464 rect.set_height(std::max(line_height(), font_list().GetHeight()));
465
466 const int bottom = GetContentsBounds().bottom();
467 for (size_t i = 0; i < lines.size() && rect.y() <= bottom; ++i) {
468 scoped_ptr<gfx::RenderText> line =
469 CreateRenderText(lines[i], alignment, directionality, elide_behavior);
470 line->SetDisplayRect(rect);
471 lines_.push_back(line.release());
472 rect.set_y(rect.y() + rect.height());
473 }
474 // Append the remaining text to the last visible line.
475 for (size_t i = lines_.size(); i < lines.size(); ++i)
476 lines_.back()->SetText(lines_.back()->text() + lines[i]);
477 }
478 RecalculateColors();
479 }
480
481 std::vector<base::string16> Label::GetLinesForWidth(int width) const {
482 std::vector<base::string16> lines;
483 const gfx::WordWrapBehavior wrap =
484 allow_character_break_ ? gfx::WRAP_LONG_WORDS : gfx::TRUNCATE_LONG_WORDS;
485 gfx::ElideRectangleText(render_text_->GetDisplayText(), font_list(), width,
486 std::numeric_limits<int>::max(), wrap, &lines);
487 return lines;
488 }
489
490 gfx::Size Label::GetTextSize() const {
491 gfx::Size size;
492 if (text().empty()) {
493 size = gfx::Size(0, std::max(line_height(), font_list().GetHeight()));
494 } else if (!multi_line() ||
495 (render_text_->MultilineSupported() && !allow_character_break_)) {
496 // Cancel the display rect of |render_text_|. The display rect may be
497 // specified in GetHeightForWidth(), and specifying empty Rect cancels
498 // its effect. See also the comment in GetHeightForWidth().
499 render_text_->SetDisplayRect(gfx::Rect());
500 size = render_text_->GetStringSize();
501 } else {
502 // Get the natural text size, unelided and only wrapped on newlines.
503 std::vector<base::string16> lines;
504 base::SplitString(render_text_->GetDisplayText(), '\n', &lines);
505 scoped_ptr<gfx::RenderText> render_text(gfx::RenderText::CreateInstance());
506 render_text->SetFontList(font_list());
507 for (size_t i = 0; i < lines.size(); ++i) {
508 render_text->SetText(lines[i]);
509 const gfx::Size line = render_text->GetStringSize();
510 size.set_width(std::max(size.width(), line.width()));
511 size.set_height(std::max(line_height(), size.height() + line.height()));
512 }
513 }
514 const gfx::Insets shadow_margin = -gfx::ShadowValue::GetMargin(shadows());
515 size.Enlarge(shadow_margin.width(), shadow_margin.height());
516 return size;
467 } 517 }
468 518
469 void Label::RecalculateColors() { 519 void Label::RecalculateColors() {
470 actual_enabled_color_ = auto_color_readability_ ? 520 actual_enabled_color_ = auto_color_readability_ ?
471 color_utils::GetReadableColor(requested_enabled_color_, 521 color_utils::GetReadableColor(requested_enabled_color_,
472 background_color_) : 522 background_color_) :
473 requested_enabled_color_; 523 requested_enabled_color_;
474 actual_disabled_color_ = auto_color_readability_ ? 524 actual_disabled_color_ = auto_color_readability_ ?
475 color_utils::GetReadableColor(requested_disabled_color_, 525 color_utils::GetReadableColor(requested_disabled_color_,
476 background_color_) : 526 background_color_) :
477 requested_disabled_color_; 527 requested_disabled_color_;
478 }
479 528
480 gfx::Rect Label::GetTextBounds() const { 529 SkColor color = enabled() ? actual_enabled_color_ : actual_disabled_color_;
481 gfx::Rect available(GetAvailableRect()); 530 bool subpixel_rendering_suppressed =
482 gfx::Size text_size(GetTextSize()); 531 SkColorGetA(background_color_) != 0xFF || !subpixel_rendering_enabled_;
483 text_size.set_width(std::min(available.width(), text_size.width())); 532 for (size_t i = 0; i < lines_.size(); ++i) {
484 gfx::Point origin(GetInsets().left(), GetInsets().top()); 533 lines_[i]->SetColor(color);
485 switch (GetHorizontalAlignment()) { 534 lines_[i]->set_subpixel_rendering_suppressed(subpixel_rendering_suppressed);
486 case gfx::ALIGN_LEFT:
487 break;
488 case gfx::ALIGN_CENTER:
489 // Put any extra margin pixel on the left to match the legacy behavior
490 // from the use of GetTextExtentPoint32() on Windows.
491 origin.Offset((available.width() + 1 - text_size.width()) / 2, 0);
492 break;
493 case gfx::ALIGN_RIGHT:
494 origin.set_x(available.right() - text_size.width());
495 break;
496 default:
497 NOTREACHED();
498 break;
499 } 535 }
500 if (!multi_line_) 536 SchedulePaint();
501 text_size.set_height(available.height());
502 // Support vertical centering of multi-line labels: http://crbug.com/429595
503 origin.Offset(0, std::max(0, (available.height() - text_size.height())) / 2);
504 return gfx::Rect(origin, text_size);
505 }
506
507 int Label::ComputeDrawStringFlags() const {
508 int flags = 0;
509
510 // We can't use subpixel rendering if the background is non-opaque.
511 if (SkColorGetA(background_color_) != 0xFF || !subpixel_rendering_enabled_)
512 flags |= gfx::Canvas::NO_SUBPIXEL_RENDERING;
513
514 switch (GetHorizontalAlignment()) {
515 case gfx::ALIGN_LEFT:
516 flags |= gfx::Canvas::TEXT_ALIGN_LEFT;
517 break;
518 case gfx::ALIGN_CENTER:
519 flags |= gfx::Canvas::TEXT_ALIGN_CENTER;
520 break;
521 case gfx::ALIGN_RIGHT:
522 flags |= gfx::Canvas::TEXT_ALIGN_RIGHT;
523 break;
524 default:
525 NOTREACHED();
526 break;
527 }
528
529 if (!multi_line_)
530 return flags;
531
532 flags |= gfx::Canvas::MULTI_LINE;
533 #if !defined(OS_WIN)
534 // Don't elide multiline labels on Linux.
535 // Todo(davemoore): Do we depend on eliding multiline text?
536 // Pango insists on limiting the number of lines to one if text is
537 // elided. You can get around this if you can pass a maximum height
538 // but we don't currently have that data when we call the pango code.
539 flags |= gfx::Canvas::NO_ELLIPSIS;
540 #endif
541 if (allow_character_break_)
542 flags |= gfx::Canvas::CHARACTER_BREAK;
543
544 return flags;
545 }
546
547 gfx::Rect Label::GetAvailableRect() const {
548 gfx::Rect bounds(size());
549 bounds.Inset(GetInsets());
550 return bounds;
551 }
552
553 const Label::DrawStringParams* Label::CalculateDrawStringParams() const {
554 if (cached_draw_params_.text.empty()) {
555 const bool forbid_ellipsis = elide_behavior_ == gfx::NO_ELIDE ||
556 elide_behavior_ == gfx::FADE_TAIL;
557 if (multi_line_ || forbid_ellipsis) {
558 cached_draw_params_.text = layout_text_;
559 } else {
560 cached_draw_params_.text = gfx::ElideText(layout_text_, font_list_,
561 GetAvailableRect().width(), elide_behavior_);
562 }
563
564 cached_draw_params_.bounds = GetTextBounds();
565 cached_draw_params_.flags = ComputeDrawStringFlags();
566 // TODO(msw): Elide multi-line text with ElideRectangleText instead.
567 if (!multi_line_ || forbid_ellipsis)
568 cached_draw_params_.flags |= gfx::Canvas::NO_ELLIPSIS;
569 }
570
571 return &cached_draw_params_;
572 } 537 }
573 538
574 void Label::UpdateColorsFromTheme(const ui::NativeTheme* theme) { 539 void Label::UpdateColorsFromTheme(const ui::NativeTheme* theme) {
575 if (!enabled_color_set_) { 540 if (!enabled_color_set_) {
576 requested_enabled_color_ = theme->GetSystemColor( 541 requested_enabled_color_ = theme->GetSystemColor(
577 ui::NativeTheme::kColorId_LabelEnabledColor); 542 ui::NativeTheme::kColorId_LabelEnabledColor);
578 } 543 }
579 if (!disabled_color_set_) { 544 if (!disabled_color_set_) {
580 requested_disabled_color_ = theme->GetSystemColor( 545 requested_disabled_color_ = theme->GetSystemColor(
581 ui::NativeTheme::kColorId_LabelDisabledColor); 546 ui::NativeTheme::kColorId_LabelDisabledColor);
582 } 547 }
583 if (!background_color_set_) { 548 if (!background_color_set_) {
584 background_color_ = theme->GetSystemColor( 549 background_color_ = theme->GetSystemColor(
585 ui::NativeTheme::kColorId_LabelBackgroundColor); 550 ui::NativeTheme::kColorId_LabelBackgroundColor);
586 } 551 }
587 RecalculateColors(); 552 RecalculateColors();
588 } 553 }
589 554
590 void Label::ResetLayoutCache() {
591 cached_draw_params_.text.clear();
592 text_size_valid_ = false;
593 cached_heights_cursor_ = 0;
594 for (int i = 0; i < kCachedSizeLimit; ++i)
595 cached_heights_[i] = gfx::Size();
596 }
597
598 bool Label::ShouldShowDefaultTooltip() const { 555 bool Label::ShouldShowDefaultTooltip() const {
599 const gfx::Size text_size = GetTextSize(); 556 const gfx::Size text_size = GetTextSize();
600 const gfx::Size size = GetContentsBounds().size(); 557 const gfx::Size size = GetContentsBounds().size();
601 return !obscured() && (text_size.width() > size.width() || 558 return !obscured() && (text_size.width() > size.width() ||
602 (multi_line_ && text_size.height() > size.height())); 559 (multi_line() && text_size.height() > size.height()));
603 } 560 }
604 561
605 } // namespace views 562 } // namespace views
OLDNEW
« no previous file with comments | « ui/views/controls/label.h ('k') | ui/views/controls/label_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698