Replace gfx::ClampToInt with base::saturated_cast.
[chromium-blink-merge.git] / ui / gfx / canvas_skia.cc
blob0d1b70d0d30002ae4f7c2c28d7b9144744ea6ee4
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "ui/gfx/canvas.h"
7 #include "base/i18n/rtl.h"
8 #include "base/logging.h"
9 #include "base/memory/scoped_ptr.h"
10 #include "base/numerics/safe_conversions.h"
11 #include "ui/gfx/font_list.h"
12 #include "ui/gfx/geometry/insets.h"
13 #include "ui/gfx/geometry/rect.h"
14 #include "ui/gfx/range/range.h"
15 #include "ui/gfx/render_text.h"
16 #include "ui/gfx/shadow_value.h"
17 #include "ui/gfx/text_elider.h"
18 #include "ui/gfx/text_utils.h"
20 namespace gfx {
22 namespace {
24 // Checks each pixel immediately adjacent to the given pixel in the bitmap. If
25 // any of them are not the halo color, returns true. This defines the halo of
26 // pixels that will appear around the text. Note that we have to check each
27 // pixel against both the halo color and transparent since
28 // |DrawStringRectWithHalo| will modify the bitmap as it goes, and cleared
29 // pixels shouldn't count as changed.
30 bool PixelShouldGetHalo(const SkBitmap& bitmap,
31 int x, int y,
32 SkColor halo_color) {
33 if (x > 0 &&
34 *bitmap.getAddr32(x - 1, y) != halo_color &&
35 *bitmap.getAddr32(x - 1, y) != 0)
36 return true; // Touched pixel to the left.
37 if (x < bitmap.width() - 1 &&
38 *bitmap.getAddr32(x + 1, y) != halo_color &&
39 *bitmap.getAddr32(x + 1, y) != 0)
40 return true; // Touched pixel to the right.
41 if (y > 0 &&
42 *bitmap.getAddr32(x, y - 1) != halo_color &&
43 *bitmap.getAddr32(x, y - 1) != 0)
44 return true; // Touched pixel above.
45 if (y < bitmap.height() - 1 &&
46 *bitmap.getAddr32(x, y + 1) != halo_color &&
47 *bitmap.getAddr32(x, y + 1) != 0)
48 return true; // Touched pixel below.
49 return false;
52 // Strips accelerator character prefixes in |text| if needed, based on |flags|.
53 // Returns a range in |text| to underline or Range::InvalidRange() if
54 // underlining is not needed.
55 Range StripAcceleratorChars(int flags, base::string16* text) {
56 if (flags & (Canvas::SHOW_PREFIX | Canvas::HIDE_PREFIX)) {
57 int char_pos = -1;
58 int char_span = 0;
59 *text = RemoveAcceleratorChar(*text, '&', &char_pos, &char_span);
60 if ((flags & Canvas::SHOW_PREFIX) && char_pos != -1)
61 return Range(char_pos, char_pos + char_span);
63 return Range::InvalidRange();
66 // Elides |text| and adjusts |range| appropriately. If eliding causes |range|
67 // to no longer point to the same character in |text|, |range| is made invalid.
68 void ElideTextAndAdjustRange(const FontList& font_list,
69 float width,
70 base::string16* text,
71 Range* range) {
72 const base::char16 start_char =
73 (range->IsValid() ? text->at(range->start()) : 0);
74 *text = ElideText(*text, font_list, width, ELIDE_TAIL);
75 if (!range->IsValid())
76 return;
77 if (range->start() >= text->length() ||
78 text->at(range->start()) != start_char) {
79 *range = Range::InvalidRange();
83 // Updates |render_text| from the specified parameters.
84 void UpdateRenderText(const Rect& rect,
85 const base::string16& text,
86 const FontList& font_list,
87 int flags,
88 SkColor color,
89 RenderText* render_text) {
90 render_text->SetFontList(font_list);
91 render_text->SetText(text);
92 render_text->SetCursorEnabled(false);
93 render_text->SetDisplayRect(rect);
95 // Set the text alignment explicitly based on the directionality of the UI,
96 // if not specified.
97 if (!(flags & (Canvas::TEXT_ALIGN_CENTER |
98 Canvas::TEXT_ALIGN_RIGHT |
99 Canvas::TEXT_ALIGN_LEFT |
100 Canvas::TEXT_ALIGN_TO_HEAD))) {
101 flags |= Canvas::DefaultCanvasTextAlignment();
104 if (flags & Canvas::TEXT_ALIGN_TO_HEAD)
105 render_text->SetHorizontalAlignment(ALIGN_TO_HEAD);
106 else if (flags & Canvas::TEXT_ALIGN_RIGHT)
107 render_text->SetHorizontalAlignment(ALIGN_RIGHT);
108 else if (flags & Canvas::TEXT_ALIGN_CENTER)
109 render_text->SetHorizontalAlignment(ALIGN_CENTER);
110 else
111 render_text->SetHorizontalAlignment(ALIGN_LEFT);
113 render_text->set_subpixel_rendering_suppressed(
114 (flags & Canvas::NO_SUBPIXEL_RENDERING) != 0);
116 render_text->SetColor(color);
117 const int font_style = font_list.GetFontStyle();
118 render_text->SetStyle(BOLD, (font_style & Font::BOLD) != 0);
119 render_text->SetStyle(ITALIC, (font_style & Font::ITALIC) != 0);
120 render_text->SetStyle(UNDERLINE, (font_style & Font::UNDERLINE) != 0);
123 } // namespace
125 // static
126 void Canvas::SizeStringFloat(const base::string16& text,
127 const FontList& font_list,
128 float* width, float* height,
129 int line_height,
130 int flags) {
131 DCHECK_GE(*width, 0);
132 DCHECK_GE(*height, 0);
134 if ((flags & MULTI_LINE) && *width != 0) {
135 WordWrapBehavior wrap_behavior = TRUNCATE_LONG_WORDS;
136 if (flags & CHARACTER_BREAK)
137 wrap_behavior = WRAP_LONG_WORDS;
138 else if (!(flags & NO_ELLIPSIS))
139 wrap_behavior = ELIDE_LONG_WORDS;
141 std::vector<base::string16> strings;
142 ElideRectangleText(text, font_list, *width, INT_MAX, wrap_behavior,
143 &strings);
144 Rect rect(base::saturated_cast<int>(*width), INT_MAX);
145 scoped_ptr<RenderText> render_text(RenderText::CreateInstance());
146 UpdateRenderText(rect, base::string16(), font_list, flags, 0,
147 render_text.get());
149 float h = 0;
150 float w = 0;
151 for (size_t i = 0; i < strings.size(); ++i) {
152 StripAcceleratorChars(flags, &strings[i]);
153 render_text->SetText(strings[i]);
154 const SizeF& string_size = render_text->GetStringSizeF();
155 w = std::max(w, string_size.width());
156 h += (i > 0 && line_height > 0) ?
157 std::max(static_cast<float>(line_height), string_size.height())
158 : string_size.height();
160 *width = w;
161 *height = h;
162 } else {
163 scoped_ptr<RenderText> render_text(RenderText::CreateInstance());
164 Rect rect(base::saturated_cast<int>(*width),
165 base::saturated_cast<int>(*height));
166 base::string16 adjusted_text = text;
167 StripAcceleratorChars(flags, &adjusted_text);
168 UpdateRenderText(rect, adjusted_text, font_list, flags, 0,
169 render_text.get());
170 const SizeF& string_size = render_text->GetStringSizeF();
171 *width = string_size.width();
172 *height = string_size.height();
176 void Canvas::DrawStringRectWithShadows(const base::string16& text,
177 const FontList& font_list,
178 SkColor color,
179 const Rect& text_bounds,
180 int line_height,
181 int flags,
182 const ShadowValues& shadows) {
183 if (!IntersectsClipRect(text_bounds))
184 return;
186 Rect clip_rect(text_bounds);
187 clip_rect.Inset(ShadowValue::GetMargin(shadows));
189 canvas_->save();
190 ClipRect(clip_rect);
192 Rect rect(text_bounds);
194 scoped_ptr<RenderText> render_text(RenderText::CreateInstance());
195 render_text->set_shadows(shadows);
197 if (flags & MULTI_LINE) {
198 WordWrapBehavior wrap_behavior = IGNORE_LONG_WORDS;
199 if (flags & CHARACTER_BREAK)
200 wrap_behavior = WRAP_LONG_WORDS;
201 else if (!(flags & NO_ELLIPSIS))
202 wrap_behavior = ELIDE_LONG_WORDS;
204 std::vector<base::string16> strings;
205 ElideRectangleText(text, font_list,
206 static_cast<float>(text_bounds.width()),
207 text_bounds.height(), wrap_behavior, &strings);
209 for (size_t i = 0; i < strings.size(); i++) {
210 Range range = StripAcceleratorChars(flags, &strings[i]);
211 UpdateRenderText(rect, strings[i], font_list, flags, color,
212 render_text.get());
213 int line_padding = 0;
214 if (line_height > 0)
215 line_padding = line_height - render_text->GetStringSize().height();
216 else
217 line_height = render_text->GetStringSize().height();
219 // TODO(msw|asvitkine): Center Windows multi-line text: crbug.com/107357
220 #if !defined(OS_WIN)
221 if (i == 0) {
222 // TODO(msw|asvitkine): Support multi-line text with varied heights.
223 const int text_height = strings.size() * line_height - line_padding;
224 rect += Vector2d(0, (text_bounds.height() - text_height) / 2);
226 #endif
228 rect.set_height(line_height - line_padding);
230 if (range.IsValid())
231 render_text->ApplyStyle(UNDERLINE, true, range);
232 render_text->SetDisplayRect(rect);
233 render_text->Draw(this);
234 rect += Vector2d(0, line_height);
236 } else {
237 base::string16 adjusted_text = text;
238 Range range = StripAcceleratorChars(flags, &adjusted_text);
239 bool elide_text = ((flags & NO_ELLIPSIS) == 0);
241 #if defined(OS_LINUX)
242 // On Linux, eliding really means fading the end of the string. But only
243 // for LTR text. RTL text is still elided (on the left) with "...".
244 if (elide_text) {
245 render_text->SetText(adjusted_text);
246 if (render_text->GetDisplayTextDirection() == base::i18n::LEFT_TO_RIGHT) {
247 render_text->SetElideBehavior(FADE_TAIL);
248 elide_text = false;
251 #endif
253 if (elide_text) {
254 ElideTextAndAdjustRange(font_list,
255 static_cast<float>(text_bounds.width()),
256 &adjusted_text, &range);
259 UpdateRenderText(rect, adjusted_text, font_list, flags, color,
260 render_text.get());
261 if (range.IsValid())
262 render_text->ApplyStyle(UNDERLINE, true, range);
263 render_text->Draw(this);
266 canvas_->restore();
269 void Canvas::DrawStringRectWithHalo(const base::string16& text,
270 const FontList& font_list,
271 SkColor text_color,
272 SkColor halo_color_in,
273 const Rect& display_rect,
274 int flags) {
275 // Some callers will have semitransparent halo colors, which we don't handle
276 // (since the resulting image can have 1-bit transparency only).
277 SkColor halo_color = SkColorSetA(halo_color_in, 0xFF);
279 // Create a temporary buffer filled with the halo color. It must leave room
280 // for the 1-pixel border around the text.
281 Size size(display_rect.width() + 2, display_rect.height() + 2);
282 Canvas text_canvas(size, image_scale(), false);
283 SkPaint bkgnd_paint;
284 bkgnd_paint.setColor(halo_color);
285 text_canvas.DrawRect(Rect(size), bkgnd_paint);
287 // Draw the text into the temporary buffer. This will have correct
288 // ClearType since the background color is the same as the halo color.
289 text_canvas.DrawStringRectWithFlags(
290 text, font_list, text_color,
291 Rect(1, 1, display_rect.width(), display_rect.height()), flags);
293 uint32_t halo_premul = SkPreMultiplyColor(halo_color);
294 SkBitmap& text_bitmap = const_cast<SkBitmap&>(
295 skia::GetTopDevice(*text_canvas.sk_canvas())->accessBitmap(true));
297 for (int cur_y = 0; cur_y < text_bitmap.height(); cur_y++) {
298 uint32_t* text_row = text_bitmap.getAddr32(0, cur_y);
299 for (int cur_x = 0; cur_x < text_bitmap.width(); cur_x++) {
300 if (text_row[cur_x] == halo_premul) {
301 // This pixel was not touched by the text routines. See if it borders
302 // a touched pixel in any of the 4 directions (not diagonally).
303 if (!PixelShouldGetHalo(text_bitmap, cur_x, cur_y, halo_premul))
304 text_row[cur_x] = 0; // Make transparent.
305 } else {
306 text_row[cur_x] |= 0xff << SK_A32_SHIFT; // Make opaque.
311 // Draw the halo bitmap with blur.
312 ImageSkia text_image = ImageSkia(ImageSkiaRep(text_bitmap,
313 text_canvas.image_scale()));
314 DrawImageInt(text_image, display_rect.x() - 1, display_rect.y() - 1);
317 void Canvas::DrawFadedString(const base::string16& text,
318 const FontList& font_list,
319 SkColor color,
320 const Rect& display_rect,
321 int flags) {
322 // If the whole string fits in the destination then just draw it directly.
323 if (GetStringWidth(text, font_list) <= display_rect.width()) {
324 DrawStringRectWithFlags(text, font_list, color, display_rect, flags);
325 return;
327 // Align with content directionality instead of fading both ends.
328 flags &= ~TEXT_ALIGN_CENTER;
329 if (!(flags & (TEXT_ALIGN_LEFT | TEXT_ALIGN_RIGHT)))
330 flags |= TEXT_ALIGN_TO_HEAD;
331 flags |= NO_ELLIPSIS;
333 scoped_ptr<RenderText> render_text(RenderText::CreateInstance());
334 Rect rect = display_rect;
335 UpdateRenderText(rect, text, font_list, flags, color, render_text.get());
336 render_text->SetElideBehavior(FADE_TAIL);
338 canvas_->save();
339 ClipRect(display_rect);
340 render_text->Draw(this);
341 canvas_->restore();
344 } // namespace gfx