Disable ExtensionIconSourceTest.IconLoaded* on Mac and Win
[chromium-blink-merge.git] / ui / gfx / canvas_skia.cc
blobbaed1dd571ba7767fe9f4f58d486bfea104fef4d
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 "ui/base/range/range.h"
11 #include "ui/base/text/text_elider.h"
12 #include "ui/gfx/font.h"
13 #include "ui/gfx/font_list.h"
14 #include "ui/gfx/insets.h"
15 #include "ui/gfx/rect.h"
16 #include "ui/gfx/render_text.h"
17 #include "ui/gfx/shadow_value.h"
18 #include "ui/gfx/text_utils.h"
20 namespace gfx {
22 namespace {
24 // If necessary, wraps |text| with RTL/LTR directionality characters based on
25 // |flags| and |text| content.
26 // Returns true if the text will be rendered right-to-left.
27 // TODO(msw): Nix this, now that RenderTextWin supports directionality directly.
28 bool AdjustStringDirection(int flags, string16* text) {
29 // TODO(msw): FORCE_LTR_DIRECTIONALITY does not work for RTL text now.
31 // If the string is empty or LTR was forced, simply return false since the
32 // default RenderText directionality is already LTR.
33 if (text->empty() || (flags & Canvas::FORCE_LTR_DIRECTIONALITY))
34 return false;
36 // If RTL is forced, apply it to the string.
37 if (flags & Canvas::FORCE_RTL_DIRECTIONALITY) {
38 base::i18n::WrapStringWithRTLFormatting(text);
39 return true;
42 // If a direction wasn't forced but the UI language is RTL and there were
43 // strong RTL characters, ensure RTL is applied.
44 if (base::i18n::IsRTL() && base::i18n::StringContainsStrongRTLChars(*text)) {
45 base::i18n::WrapStringWithRTLFormatting(text);
46 return true;
49 // In the default case, the string should be rendered as LTR. RenderText's
50 // default directionality is LTR, so the text doesn't need to be wrapped.
51 // Note that individual runs within the string may still be rendered RTL
52 // (which will be the case for RTL text under non-RTL locales, since under RTL
53 // locales it will be handled by the if statement above).
54 return false;
57 // Checks each pixel immediately adjacent to the given pixel in the bitmap. If
58 // any of them are not the halo color, returns true. This defines the halo of
59 // pixels that will appear around the text. Note that we have to check each
60 // pixel against both the halo color and transparent since |DrawStringWithHalo|
61 // will modify the bitmap as it goes, and cleared pixels shouldn't count as
62 // changed.
63 bool PixelShouldGetHalo(const SkBitmap& bitmap,
64 int x, int y,
65 SkColor halo_color) {
66 if (x > 0 &&
67 *bitmap.getAddr32(x - 1, y) != halo_color &&
68 *bitmap.getAddr32(x - 1, y) != 0)
69 return true; // Touched pixel to the left.
70 if (x < bitmap.width() - 1 &&
71 *bitmap.getAddr32(x + 1, y) != halo_color &&
72 *bitmap.getAddr32(x + 1, y) != 0)
73 return true; // Touched pixel to the right.
74 if (y > 0 &&
75 *bitmap.getAddr32(x, y - 1) != halo_color &&
76 *bitmap.getAddr32(x, y - 1) != 0)
77 return true; // Touched pixel above.
78 if (y < bitmap.height() - 1 &&
79 *bitmap.getAddr32(x, y + 1) != halo_color &&
80 *bitmap.getAddr32(x, y + 1) != 0)
81 return true; // Touched pixel below.
82 return false;
85 // Strips accelerator character prefixes in |text| if needed, based on |flags|.
86 // Returns a range in |text| to underline or ui::Range::InvalidRange() if
87 // underlining is not needed.
88 ui::Range StripAcceleratorChars(int flags, string16* text) {
89 if (flags & (Canvas::SHOW_PREFIX | Canvas::HIDE_PREFIX)) {
90 int char_pos = -1;
91 int char_span = 0;
92 *text = RemoveAcceleratorChar(*text, '&', &char_pos, &char_span);
93 if ((flags & Canvas::SHOW_PREFIX) && char_pos != -1)
94 return ui::Range(char_pos, char_pos + char_span);
96 return ui::Range::InvalidRange();
99 // Elides |text| and adjusts |range| appropriately. If eliding causes |range|
100 // to no longer point to the same character in |text|, |range| is made invalid.
101 void ElideTextAndAdjustRange(const Font& font,
102 int width,
103 string16* text,
104 ui::Range* range) {
105 const char16 start_char = (range->IsValid() ? text->at(range->start()) : 0);
106 *text = ui::ElideText(*text, font, width, ui::ELIDE_AT_END);
107 if (!range->IsValid())
108 return;
109 if (range->start() >= text->length() ||
110 text->at(range->start()) != start_char) {
111 *range = ui::Range::InvalidRange();
115 // Updates |render_text| from the specified parameters.
116 void UpdateRenderText(const Rect& rect,
117 const string16& text,
118 const Font& font,
119 int flags,
120 SkColor color,
121 RenderText* render_text) {
122 render_text->SetFont(font);
123 render_text->SetText(text);
124 render_text->SetCursorEnabled(false);
126 Rect display_rect = rect;
127 display_rect.set_height(font.GetHeight());
128 render_text->SetDisplayRect(display_rect);
130 // Set the text alignment explicitly based on the directionality of the UI,
131 // if not specified.
132 if (!(flags & (Canvas::TEXT_ALIGN_CENTER |
133 Canvas::TEXT_ALIGN_RIGHT |
134 Canvas::TEXT_ALIGN_LEFT))) {
135 flags |= Canvas::DefaultCanvasTextAlignment();
138 if (flags & Canvas::TEXT_ALIGN_RIGHT)
139 render_text->SetHorizontalAlignment(ALIGN_RIGHT);
140 else if (flags & Canvas::TEXT_ALIGN_CENTER)
141 render_text->SetHorizontalAlignment(ALIGN_CENTER);
142 else
143 render_text->SetHorizontalAlignment(ALIGN_LEFT);
145 if (flags & Canvas::NO_SUBPIXEL_RENDERING)
146 render_text->set_background_is_transparent(true);
148 render_text->SetColor(color);
149 render_text->SetStyle(BOLD, (font.GetStyle() & Font::BOLD) != 0);
150 render_text->SetStyle(ITALIC, (font.GetStyle() & Font::ITALIC) != 0);
151 render_text->SetStyle(UNDERLINE, (font.GetStyle() & Font::UNDERLINE) != 0);
154 // Returns updated |flags| to match platform-specific expected behavior.
155 int AdjustPlatformSpecificFlags(const string16& text, int flags) {
156 #if defined(OS_LINUX)
157 // TODO(asvitkine): ash/tooltips/tooltip_controller.cc adds \n's to the string
158 // without passing MULTI_LINE.
159 if (text.find('\n') != string16::npos)
160 flags |= Canvas::MULTI_LINE;
161 #endif
163 return flags;
166 } // namespace
168 // static
169 void Canvas::SizeStringInt(const string16& text,
170 const Font& font,
171 int* width, int* height,
172 int line_height,
173 int flags) {
174 DCHECK_GE(*width, 0);
175 DCHECK_GE(*height, 0);
177 flags = AdjustPlatformSpecificFlags(text, flags);
179 string16 adjusted_text = text;
180 #if defined(OS_WIN)
181 AdjustStringDirection(flags, &adjusted_text);
182 #endif
184 if ((flags & MULTI_LINE) && *width != 0) {
185 ui::WordWrapBehavior wrap_behavior = ui::TRUNCATE_LONG_WORDS;
186 if (flags & CHARACTER_BREAK)
187 wrap_behavior = ui::WRAP_LONG_WORDS;
188 else if (!(flags & NO_ELLIPSIS))
189 wrap_behavior = ui::ELIDE_LONG_WORDS;
191 Rect rect(*width, INT_MAX);
192 std::vector<string16> strings;
193 ui::ElideRectangleText(adjusted_text, font, rect.width(), rect.height(),
194 wrap_behavior, &strings);
195 scoped_ptr<RenderText> render_text(RenderText::CreateInstance());
196 UpdateRenderText(rect, string16(), font, flags, 0, render_text.get());
198 int h = 0;
199 int w = 0;
200 for (size_t i = 0; i < strings.size(); ++i) {
201 StripAcceleratorChars(flags, &strings[i]);
202 render_text->SetText(strings[i]);
203 const Size string_size = render_text->GetStringSize();
204 w = std::max(w, string_size.width());
205 h += (i > 0 && line_height > 0) ? line_height : string_size.height();
207 *width = w;
208 *height = h;
209 } else {
210 // If the string is too long, the call by |RenderTextWin| to |ScriptShape()|
211 // will inexplicably fail with result E_INVALIDARG. Guard against this.
212 const size_t kMaxRenderTextLength = 5000;
213 if (adjusted_text.length() >= kMaxRenderTextLength) {
214 *width = adjusted_text.length() * font.GetAverageCharacterWidth();
215 *height = font.GetHeight();
216 } else {
217 scoped_ptr<RenderText> render_text(RenderText::CreateInstance());
218 Rect rect(*width, *height);
219 StripAcceleratorChars(flags, &adjusted_text);
220 UpdateRenderText(rect, adjusted_text, font, flags, 0, render_text.get());
221 const Size string_size = render_text->GetStringSize();
222 *width = string_size.width();
223 *height = string_size.height();
228 void Canvas::DrawStringWithShadows(const string16& text,
229 const Font& font,
230 SkColor color,
231 const Rect& text_bounds,
232 int line_height,
233 int flags,
234 const ShadowValues& shadows) {
235 if (!IntersectsClipRect(text_bounds))
236 return;
238 flags = AdjustPlatformSpecificFlags(text, flags);
240 Rect clip_rect(text_bounds);
241 clip_rect.Inset(ShadowValue::GetMargin(shadows));
243 canvas_->save(SkCanvas::kClip_SaveFlag);
244 ClipRect(clip_rect);
246 Rect rect(text_bounds);
247 string16 adjusted_text = text;
249 #if defined(OS_WIN)
250 AdjustStringDirection(flags, &adjusted_text);
251 #endif
253 scoped_ptr<RenderText> render_text(RenderText::CreateInstance());
254 render_text->SetTextShadows(shadows);
256 if (flags & MULTI_LINE) {
257 ui::WordWrapBehavior wrap_behavior = ui::IGNORE_LONG_WORDS;
258 if (flags & CHARACTER_BREAK)
259 wrap_behavior = ui::WRAP_LONG_WORDS;
260 else if (!(flags & NO_ELLIPSIS))
261 wrap_behavior = ui::ELIDE_LONG_WORDS;
263 std::vector<string16> strings;
264 ui::ElideRectangleText(adjusted_text,
265 font,
266 text_bounds.width(), text_bounds.height(),
267 wrap_behavior,
268 &strings);
270 for (size_t i = 0; i < strings.size(); i++) {
271 ui::Range range = StripAcceleratorChars(flags, &strings[i]);
272 UpdateRenderText(rect, strings[i], font, flags, color, render_text.get());
273 int line_padding = 0;
274 if (line_height > 0)
275 line_padding = line_height - render_text->GetStringSize().height();
276 else
277 line_height = render_text->GetStringSize().height();
279 // TODO(msw|asvitkine): Center Windows multi-line text: crbug.com/107357
280 #if !defined(OS_WIN)
281 if (i == 0) {
282 // TODO(msw|asvitkine): Support multi-line text with varied heights.
283 const int text_height = strings.size() * line_height - line_padding;
284 rect += Vector2d(0, (text_bounds.height() - text_height) / 2);
286 #endif
288 rect.set_height(line_height - line_padding);
290 if (range.IsValid())
291 render_text->ApplyStyle(UNDERLINE, true, range);
292 render_text->SetDisplayRect(rect);
293 render_text->Draw(this);
294 rect += Vector2d(0, line_height);
296 } else {
297 ui::Range range = StripAcceleratorChars(flags, &adjusted_text);
298 bool elide_text = ((flags & NO_ELLIPSIS) == 0);
300 #if defined(OS_LINUX)
301 // On Linux, eliding really means fading the end of the string. But only
302 // for LTR text. RTL text is still elided (on the left) with "...".
303 if (elide_text) {
304 render_text->SetText(adjusted_text);
305 if (render_text->GetTextDirection() == base::i18n::LEFT_TO_RIGHT) {
306 render_text->set_fade_tail(true);
307 elide_text = false;
310 #endif
312 if (elide_text) {
313 ElideTextAndAdjustRange(font,
314 text_bounds.width(),
315 &adjusted_text,
316 &range);
319 UpdateRenderText(rect, adjusted_text, font, flags, color,
320 render_text.get());
322 const int text_height = render_text->GetStringSize().height();
323 // Center the text vertically.
324 rect += Vector2d(0, (text_bounds.height() - text_height) / 2);
325 rect.set_height(text_height);
326 render_text->SetDisplayRect(rect);
327 if (range.IsValid())
328 render_text->ApplyStyle(UNDERLINE, true, range);
329 render_text->Draw(this);
332 canvas_->restore();
335 void Canvas::DrawStringWithHalo(const string16& text,
336 const Font& font,
337 SkColor text_color,
338 SkColor halo_color_in,
339 int x, int y, int w, int h,
340 int flags) {
341 // Some callers will have semitransparent halo colors, which we don't handle
342 // (since the resulting image can have 1-bit transparency only).
343 SkColor halo_color = SkColorSetA(halo_color_in, 0xFF);
345 // Create a temporary buffer filled with the halo color. It must leave room
346 // for the 1-pixel border around the text.
347 Size size(w + 2, h + 2);
348 Canvas text_canvas(size, scale_factor(), true);
349 SkPaint bkgnd_paint;
350 bkgnd_paint.setColor(halo_color);
351 text_canvas.DrawRect(Rect(size), bkgnd_paint);
353 // Draw the text into the temporary buffer. This will have correct
354 // ClearType since the background color is the same as the halo color.
355 text_canvas.DrawStringInt(text, font, text_color, 1, 1, w, h, flags);
357 uint32_t halo_premul = SkPreMultiplyColor(halo_color);
358 SkBitmap& text_bitmap = const_cast<SkBitmap&>(
359 skia::GetTopDevice(*text_canvas.sk_canvas())->accessBitmap(true));
361 for (int cur_y = 0; cur_y < text_bitmap.height(); cur_y++) {
362 uint32_t* text_row = text_bitmap.getAddr32(0, cur_y);
363 for (int cur_x = 0; cur_x < text_bitmap.width(); cur_x++) {
364 if (text_row[cur_x] == halo_premul) {
365 // This pixel was not touched by the text routines. See if it borders
366 // a touched pixel in any of the 4 directions (not diagonally).
367 if (!PixelShouldGetHalo(text_bitmap, cur_x, cur_y, halo_premul))
368 text_row[cur_x] = 0; // Make transparent.
369 } else {
370 text_row[cur_x] |= 0xff << SK_A32_SHIFT; // Make opaque.
375 // Draw the halo bitmap with blur.
376 ImageSkia text_image = ImageSkia(ImageSkiaRep(text_bitmap,
377 text_canvas.scale_factor()));
378 DrawImageInt(text_image, x - 1, y - 1);
381 void Canvas::DrawFadeTruncatingString(
382 const string16& text,
383 TruncateFadeMode truncate_mode,
384 size_t desired_characters_to_truncate_from_head,
385 const Font& font,
386 SkColor color,
387 const Rect& display_rect) {
388 int flags = NO_ELLIPSIS;
390 // If the whole string fits in the destination then just draw it directly.
391 if (GetStringWidth(text, font) <= display_rect.width()) {
392 DrawStringInt(text, font, color, display_rect.x(), display_rect.y(),
393 display_rect.width(), display_rect.height(), flags);
394 return;
397 scoped_ptr<RenderText> render_text(RenderText::CreateInstance());
398 string16 clipped_text = text;
399 const bool is_rtl = AdjustStringDirection(flags, &clipped_text);
401 switch (truncate_mode) {
402 case TruncateFadeTail:
403 render_text->set_fade_tail(true);
404 if (is_rtl)
405 flags |= TEXT_ALIGN_RIGHT;
406 break;
407 case TruncateFadeHead:
408 render_text->set_fade_head(true);
409 if (!is_rtl)
410 flags |= TEXT_ALIGN_RIGHT;
411 break;
412 case TruncateFadeHeadAndTail:
413 DCHECK_GT(desired_characters_to_truncate_from_head, 0u);
414 // Due to the fade effect the first character is hard to see.
415 // We want to make sure that the first character starting at
416 // |desired_characters_to_truncate_from_head| is readable so we reduce
417 // the offset by a little bit.
418 desired_characters_to_truncate_from_head =
419 std::max<int>(0, desired_characters_to_truncate_from_head - 2);
421 if (desired_characters_to_truncate_from_head) {
422 // Make sure to clip the text at a UTF16 boundary.
423 U16_SET_CP_LIMIT(text.data(), 0,
424 desired_characters_to_truncate_from_head,
425 text.length());
426 clipped_text = text.substr(desired_characters_to_truncate_from_head);
429 render_text->set_fade_tail(true);
430 render_text->set_fade_head(true);
431 break;
434 // Default to left alignment unless right alignment was chosen above.
435 if (!(flags & TEXT_ALIGN_RIGHT))
436 flags |= TEXT_ALIGN_LEFT;
438 Rect rect = display_rect;
439 UpdateRenderText(rect, clipped_text, font, flags, color, render_text.get());
441 const int line_height = render_text->GetStringSize().height();
442 // Center the text vertically.
443 rect += Vector2d(0, (display_rect.height() - line_height) / 2);
444 rect.set_height(line_height);
445 render_text->SetDisplayRect(rect);
447 canvas_->save(SkCanvas::kClip_SaveFlag);
448 ClipRect(display_rect);
449 render_text->Draw(this);
450 canvas_->restore();
453 } // namespace gfx