ui: Eliminate allocating gfx::Canvas on the heap for every view.
[chromium-blink-merge.git] / ui / gfx / canvas.cc
blob0c4a5a09363e66eed784d894a8bf870a9c91ceb6
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 <cmath>
8 #include <limits>
10 #include "base/i18n/rtl.h"
11 #include "base/logging.h"
12 #include "third_party/skia/include/core/SkBitmap.h"
13 #include "third_party/skia/include/effects/SkGradientShader.h"
14 #include "ui/gfx/font_list.h"
15 #include "ui/gfx/geometry/rect.h"
16 #include "ui/gfx/geometry/rect_conversions.h"
17 #include "ui/gfx/geometry/safe_integer_conversions.h"
18 #include "ui/gfx/geometry/size_conversions.h"
19 #include "ui/gfx/scoped_canvas.h"
20 #include "ui/gfx/skia_util.h"
21 #include "ui/gfx/transform.h"
23 namespace gfx {
25 Canvas::Canvas(const Size& size, float image_scale, bool is_opaque)
26 : image_scale_(image_scale),
27 canvas_(NULL) {
28 Size pixel_size = ToCeiledSize(ScaleSize(size, image_scale));
29 owned_canvas_ = skia::AdoptRef(skia::CreatePlatformCanvas(pixel_size.width(),
30 pixel_size.height(),
31 is_opaque));
32 canvas_ = owned_canvas_.get();
33 #if defined(OS_WIN) || defined(OS_MACOSX)
34 // skia::PlatformCanvas instances are initialized to 0 by Cairo on Linux, but
35 // uninitialized on Win and Mac.
36 if (!is_opaque)
37 owned_canvas_->clear(SkColorSetARGB(0, 0, 0, 0));
38 #endif
40 SkScalar scale_scalar = SkFloatToScalar(image_scale);
41 canvas_->scale(scale_scalar, scale_scalar);
44 Canvas::Canvas(const ImageSkiaRep& image_rep, bool is_opaque)
45 : image_scale_(image_rep.scale()),
46 owned_canvas_(skia::AdoptRef(
47 skia::CreatePlatformCanvas(image_rep.pixel_width(),
48 image_rep.pixel_height(),
49 is_opaque))),
50 canvas_(owned_canvas_.get()) {
51 SkScalar scale_scalar = SkFloatToScalar(image_scale_);
52 canvas_->scale(scale_scalar, scale_scalar);
53 DrawImageInt(ImageSkia(image_rep), 0, 0);
56 Canvas::Canvas()
57 : image_scale_(1.0),
58 owned_canvas_(skia::AdoptRef(skia::CreatePlatformCanvas(0, 0, false))),
59 canvas_(owned_canvas_.get()) {
62 Canvas::Canvas(SkCanvas* canvas, float image_scale)
63 : image_scale_(image_scale), owned_canvas_(), canvas_(canvas) {
64 DCHECK(canvas);
67 Canvas::~Canvas() {
70 void Canvas::RecreateBackingCanvas(const Size& size,
71 float image_scale,
72 bool is_opaque) {
73 image_scale_ = image_scale;
74 Size pixel_size = ToFlooredSize(ScaleSize(size, image_scale));
75 owned_canvas_ = skia::AdoptRef(skia::CreatePlatformCanvas(pixel_size.width(),
76 pixel_size.height(),
77 is_opaque));
78 canvas_ = owned_canvas_.get();
79 SkScalar scale_scalar = SkFloatToScalar(image_scale);
80 canvas_->scale(scale_scalar, scale_scalar);
83 // static
84 void Canvas::SizeStringInt(const base::string16& text,
85 const FontList& font_list,
86 int* width,
87 int* height,
88 int line_height,
89 int flags) {
90 float fractional_width = static_cast<float>(*width);
91 float factional_height = static_cast<float>(*height);
92 SizeStringFloat(text, font_list, &fractional_width,
93 &factional_height, line_height, flags);
94 *width = ToCeiledInt(fractional_width);
95 *height = ToCeiledInt(factional_height);
98 // static
99 int Canvas::GetStringWidth(const base::string16& text,
100 const FontList& font_list) {
101 int width = 0, height = 0;
102 SizeStringInt(text, font_list, &width, &height, 0, NO_ELLIPSIS);
103 return width;
106 // static
107 float Canvas::GetStringWidthF(const base::string16& text,
108 const FontList& font_list) {
109 float width = 0, height = 0;
110 SizeStringFloat(text, font_list, &width, &height, 0, NO_ELLIPSIS);
111 return width;
114 // static
115 int Canvas::DefaultCanvasTextAlignment() {
116 return base::i18n::IsRTL() ? TEXT_ALIGN_RIGHT : TEXT_ALIGN_LEFT;
119 ImageSkiaRep Canvas::ExtractImageRep() const {
120 // Make a bitmap to return, and a canvas to draw into it. We don't just want
121 // to call extractSubset or the copy constructor, since we want an actual copy
122 // of the bitmap.
123 const SkISize size = canvas_->getDeviceSize();
124 SkBitmap result;
125 result.allocN32Pixels(size.width(), size.height());
127 canvas_->readPixels(&result, 0, 0);
128 return ImageSkiaRep(result, image_scale_);
131 void Canvas::DrawDashedRect(const Rect& rect, SkColor color) {
132 if (rect.IsEmpty())
133 return;
134 // Create a 2D bitmap containing alternating on/off pixels - we do this
135 // so that you never get two pixels of the same color around the edges
136 // of the focus rect (this may mean that opposing edges of the rect may
137 // have a dot pattern out of phase to each other).
138 static SkColor last_color;
139 static SkBitmap* dots = NULL;
140 if (!dots || last_color != color) {
141 int col_pixels = 32;
142 int row_pixels = 32;
144 delete dots;
145 last_color = color;
146 dots = new SkBitmap;
147 dots->allocN32Pixels(col_pixels, row_pixels);
148 dots->eraseARGB(0, 0, 0, 0);
150 uint32_t* dot = dots->getAddr32(0, 0);
151 for (int i = 0; i < row_pixels; i++) {
152 for (int u = 0; u < col_pixels; u++) {
153 if ((u % 2 + i % 2) % 2 != 0) {
154 dot[i * row_pixels + u] = color;
160 // Make a shader for the bitmap with an origin of the box we'll draw. This
161 // shader is refcounted and will have an initial refcount of 1.
162 skia::RefPtr<SkShader> shader = skia::AdoptRef(
163 SkShader::CreateBitmapShader(
164 *dots, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode));
165 // Assign the shader to the paint & release our reference. The paint will
166 // now own the shader and the shader will be destroyed when the paint goes
167 // out of scope.
168 SkPaint paint;
169 paint.setShader(shader.get());
171 DrawRect(Rect(rect.x(), rect.y(), rect.width(), 1), paint);
172 DrawRect(Rect(rect.x(), rect.y() + rect.height() - 1, rect.width(), 1),
173 paint);
174 DrawRect(Rect(rect.x(), rect.y(), 1, rect.height()), paint);
175 DrawRect(Rect(rect.x() + rect.width() - 1, rect.y(), 1, rect.height()),
176 paint);
179 void Canvas::Save() {
180 canvas_->save();
183 void Canvas::SaveLayerAlpha(uint8 alpha) {
184 canvas_->saveLayerAlpha(NULL, alpha);
187 void Canvas::SaveLayerAlpha(uint8 alpha, const Rect& layer_bounds) {
188 SkRect bounds(RectToSkRect(layer_bounds));
189 canvas_->saveLayerAlpha(&bounds, alpha);
192 void Canvas::Restore() {
193 canvas_->restore();
196 void Canvas::ClipRect(const Rect& rect) {
197 canvas_->clipRect(RectToSkRect(rect));
200 void Canvas::ClipPath(const SkPath& path, bool do_anti_alias) {
201 canvas_->clipPath(path, SkRegion::kIntersect_Op, do_anti_alias);
204 bool Canvas::IsClipEmpty() const {
205 return canvas_->isClipEmpty();
208 bool Canvas::GetClipBounds(Rect* bounds) {
209 SkRect out;
210 if (canvas_->getClipBounds(&out)) {
211 *bounds = ToEnclosingRect(SkRectToRectF(out));
212 return true;
214 *bounds = gfx::Rect();
215 return false;
218 void Canvas::Translate(const Vector2d& offset) {
219 canvas_->translate(SkIntToScalar(offset.x()), SkIntToScalar(offset.y()));
222 void Canvas::Scale(int x_scale, int y_scale) {
223 canvas_->scale(SkIntToScalar(x_scale), SkIntToScalar(y_scale));
226 void Canvas::DrawColor(SkColor color) {
227 DrawColor(color, SkXfermode::kSrcOver_Mode);
230 void Canvas::DrawColor(SkColor color, SkXfermode::Mode mode) {
231 canvas_->drawColor(color, mode);
234 void Canvas::FillRect(const Rect& rect, SkColor color) {
235 FillRect(rect, color, SkXfermode::kSrcOver_Mode);
238 void Canvas::FillRect(const Rect& rect,
239 SkColor color,
240 SkXfermode::Mode mode) {
241 SkPaint paint;
242 paint.setColor(color);
243 paint.setStyle(SkPaint::kFill_Style);
244 paint.setXfermodeMode(mode);
245 DrawRect(rect, paint);
248 void Canvas::DrawRect(const Rect& rect, SkColor color) {
249 DrawRect(rect, color, SkXfermode::kSrcOver_Mode);
252 void Canvas::DrawRect(const Rect& rect,
253 SkColor color,
254 SkXfermode::Mode mode) {
255 SkPaint paint;
256 paint.setColor(color);
257 paint.setStyle(SkPaint::kStroke_Style);
258 // Set a stroke width of 0, which will put us down the stroke rect path. If
259 // we set a stroke width of 1, for example, this will internally create a
260 // path and fill it, which causes problems near the edge of the canvas.
261 paint.setStrokeWidth(SkIntToScalar(0));
262 paint.setXfermodeMode(mode);
264 DrawRect(rect, paint);
267 void Canvas::DrawRect(const Rect& rect, const SkPaint& paint) {
268 canvas_->drawIRect(RectToSkIRect(rect), paint);
271 void Canvas::DrawPoint(const Point& p1, const SkPaint& paint) {
272 canvas_->drawPoint(SkIntToScalar(p1.x()), SkIntToScalar(p1.y()), paint);
275 void Canvas::DrawLine(const Point& p1, const Point& p2, SkColor color) {
276 SkPaint paint;
277 paint.setColor(color);
278 paint.setStrokeWidth(SkIntToScalar(1));
279 DrawLine(p1, p2, paint);
282 void Canvas::DrawLine(const Point& p1, const Point& p2, const SkPaint& paint) {
283 canvas_->drawLine(SkIntToScalar(p1.x()), SkIntToScalar(p1.y()),
284 SkIntToScalar(p2.x()), SkIntToScalar(p2.y()), paint);
287 void Canvas::DrawCircle(const Point& center_point,
288 int radius,
289 const SkPaint& paint) {
290 canvas_->drawCircle(SkIntToScalar(center_point.x()),
291 SkIntToScalar(center_point.y()), SkIntToScalar(radius), paint);
294 void Canvas::DrawRoundRect(const Rect& rect,
295 int radius,
296 const SkPaint& paint) {
297 canvas_->drawRoundRect(RectToSkRect(rect), SkIntToScalar(radius),
298 SkIntToScalar(radius), paint);
301 void Canvas::DrawPath(const SkPath& path, const SkPaint& paint) {
302 canvas_->drawPath(path, paint);
305 void Canvas::DrawFocusRect(const Rect& rect) {
306 DrawDashedRect(rect, SK_ColorGRAY);
309 void Canvas::DrawSolidFocusRect(const Rect& rect, SkColor color) {
310 SkPaint paint;
311 paint.setColor(color);
312 paint.setStrokeWidth(SkIntToScalar(1));
313 // Note: We cannot use DrawRect since it would create a path and fill it which
314 // would cause problems near the edge of the canvas.
315 int x1 = std::min(rect.x(), rect.right());
316 int x2 = std::max(rect.x(), rect.right());
317 int y1 = std::min(rect.y(), rect.bottom());
318 int y2 = std::max(rect.y(), rect.bottom());
319 DrawLine(Point(x1, y1), Point(x2, y1), paint);
320 DrawLine(Point(x1, y2), Point(x2, y2), paint);
321 DrawLine(Point(x1, y1), Point(x1, y2), paint);
322 DrawLine(Point(x2, y1), Point(x2, y2 + 1), paint);
325 void Canvas::DrawImageInt(const ImageSkia& image, int x, int y) {
326 SkPaint paint;
327 DrawImageInt(image, x, y, paint);
330 void Canvas::DrawImageInt(const ImageSkia& image, int x, int y, uint8 a) {
331 SkPaint paint;
332 paint.setAlpha(a);
333 DrawImageInt(image, x, y, paint);
336 void Canvas::DrawImageInt(const ImageSkia& image,
337 int x,
338 int y,
339 const SkPaint& paint) {
340 const ImageSkiaRep& image_rep = image.GetRepresentation(image_scale_);
341 if (image_rep.is_null())
342 return;
343 const SkBitmap& bitmap = image_rep.sk_bitmap();
344 float bitmap_scale = image_rep.scale();
346 ScopedCanvas scoper(this);
347 canvas_->scale(SkFloatToScalar(1.0f / bitmap_scale),
348 SkFloatToScalar(1.0f / bitmap_scale));
349 canvas_->drawBitmap(bitmap,
350 SkFloatToScalar(x * bitmap_scale),
351 SkFloatToScalar(y * bitmap_scale),
352 &paint);
355 void Canvas::DrawImageInt(const ImageSkia& image,
356 int src_x,
357 int src_y,
358 int src_w,
359 int src_h,
360 int dest_x,
361 int dest_y,
362 int dest_w,
363 int dest_h,
364 bool filter) {
365 SkPaint p;
366 DrawImageInt(image, src_x, src_y, src_w, src_h, dest_x, dest_y,
367 dest_w, dest_h, filter, p);
370 void Canvas::DrawImageInt(const ImageSkia& image,
371 int src_x,
372 int src_y,
373 int src_w,
374 int src_h,
375 int dest_x,
376 int dest_y,
377 int dest_w,
378 int dest_h,
379 bool filter,
380 const SkPaint& paint) {
381 DrawImageIntHelper(image, src_x, src_y, src_w, src_h, dest_x, dest_y, dest_w,
382 dest_h, filter, paint, image_scale_, false);
385 void Canvas::DrawImageIntInPixel(const ImageSkia& image,
386 int src_x,
387 int src_y,
388 int src_w,
389 int src_h,
390 int dest_x,
391 int dest_y,
392 int dest_w,
393 int dest_h,
394 bool filter,
395 const SkPaint& paint) {
396 // All values passed into this function are in pixels, i.e. no scaling needs
397 // be done.
398 // Logic as below:-
399 // 1. Get the matrix transform from the canvas.
400 // 2. Set the scale in the matrix to 1.0 while honoring the direction of the
401 // the scale (x/y). Example RTL layouts.
402 // 3. Round off the X and Y translation components in the matrix. This is to
403 // reduce floating point errors during rect transformation. This is needed
404 // for fractional scale factors like 1.25/1.5, etc.
405 // 4. Save the current state of the canvas and restore the state when going
406 // out of scope with ScopedCanvas.
407 // 5. Set the modified matrix in the canvas. This ensures that no scaling
408 // will be done for draw operations on the canvas.
409 // 6. Draw the image.
410 SkMatrix matrix = canvas_->getTotalMatrix();
412 // Ensure that the direction of the x and y scales is preserved. This is
413 // important for RTL layouts.
414 matrix.setScaleX(matrix.getScaleX() > 0 ? 1.0f : -1.0f);
415 matrix.setScaleY(matrix.getScaleY() > 0 ? 1.0f : -1.0f);
417 // Floor so that we get consistent rounding.
418 matrix.setTranslateX(SkScalarFloorToScalar(matrix.getTranslateX()));
419 matrix.setTranslateY(SkScalarFloorToScalar(matrix.getTranslateY()));
421 ScopedCanvas scoper(this);
423 canvas_->setMatrix(matrix);
425 DrawImageIntHelper(image,
426 src_x,
427 src_y,
428 src_w,
429 src_h,
430 dest_x,
431 dest_y,
432 dest_w,
433 dest_h,
434 filter,
435 paint,
436 image_scale_,
437 true);
440 void Canvas::DrawImageInPath(const ImageSkia& image,
441 int x,
442 int y,
443 const SkPath& path,
444 const SkPaint& paint) {
445 const ImageSkiaRep& image_rep = image.GetRepresentation(image_scale_);
446 if (image_rep.is_null())
447 return;
449 SkMatrix matrix;
450 matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
451 skia::RefPtr<SkShader> shader = CreateImageRepShader(
452 image_rep,
453 SkShader::kRepeat_TileMode,
454 matrix);
456 SkPaint p(paint);
457 p.setShader(shader.get());
458 canvas_->drawPath(path, p);
461 void Canvas::DrawStringRect(const base::string16& text,
462 const FontList& font_list,
463 SkColor color,
464 const Rect& display_rect) {
465 DrawStringRectWithFlags(text, font_list, color, display_rect,
466 DefaultCanvasTextAlignment());
469 void Canvas::DrawStringRectWithFlags(const base::string16& text,
470 const FontList& font_list,
471 SkColor color,
472 const Rect& display_rect,
473 int flags) {
474 DrawStringRectWithShadows(text, font_list, color, display_rect, 0, flags,
475 ShadowValues());
478 void Canvas::TileImageInt(const ImageSkia& image,
479 int x,
480 int y,
481 int w,
482 int h) {
483 TileImageInt(image, 0, 0, x, y, w, h);
486 void Canvas::TileImageInt(const ImageSkia& image,
487 int src_x,
488 int src_y,
489 int dest_x,
490 int dest_y,
491 int w,
492 int h) {
493 TileImageInt(image, src_x, src_y, 1.0f, 1.0f, dest_x, dest_y, w, h);
496 void Canvas::TileImageInt(const ImageSkia& image,
497 int src_x,
498 int src_y,
499 float tile_scale_x,
500 float tile_scale_y,
501 int dest_x,
502 int dest_y,
503 int w,
504 int h) {
505 if (!IntersectsClipRectInt(dest_x, dest_y, w, h))
506 return;
508 const ImageSkiaRep& image_rep = image.GetRepresentation(image_scale_);
509 if (image_rep.is_null())
510 return;
512 SkMatrix shader_scale;
513 shader_scale.setScale(SkFloatToScalar(tile_scale_x),
514 SkFloatToScalar(tile_scale_y));
515 shader_scale.preTranslate(SkIntToScalar(-src_x), SkIntToScalar(-src_y));
516 shader_scale.postTranslate(SkIntToScalar(dest_x), SkIntToScalar(dest_y));
518 skia::RefPtr<SkShader> shader = CreateImageRepShader(
519 image_rep,
520 SkShader::kRepeat_TileMode,
521 shader_scale);
523 SkPaint paint;
524 paint.setShader(shader.get());
525 paint.setXfermodeMode(SkXfermode::kSrcOver_Mode);
527 SkRect dest_rect = { SkIntToScalar(dest_x),
528 SkIntToScalar(dest_y),
529 SkIntToScalar(dest_x + w),
530 SkIntToScalar(dest_y + h) };
531 canvas_->drawRect(dest_rect, paint);
534 NativeDrawingContext Canvas::BeginPlatformPaint() {
535 return skia::BeginPlatformPaint(canvas_);
538 void Canvas::EndPlatformPaint() {
539 skia::EndPlatformPaint(canvas_);
542 void Canvas::Transform(const gfx::Transform& transform) {
543 canvas_->concat(transform.matrix());
546 bool Canvas::IntersectsClipRectInt(int x, int y, int w, int h) {
547 SkRect clip;
548 return canvas_->getClipBounds(&clip) &&
549 clip.intersect(SkIntToScalar(x), SkIntToScalar(y), SkIntToScalar(x + w),
550 SkIntToScalar(y + h));
553 bool Canvas::IntersectsClipRect(const Rect& rect) {
554 return IntersectsClipRectInt(rect.x(), rect.y(),
555 rect.width(), rect.height());
558 void Canvas::DrawImageIntHelper(const ImageSkia& image,
559 int src_x,
560 int src_y,
561 int src_w,
562 int src_h,
563 int dest_x,
564 int dest_y,
565 int dest_w,
566 int dest_h,
567 bool filter,
568 const SkPaint& paint,
569 float image_scale,
570 bool pixel) {
571 DLOG_ASSERT(src_x + src_w < std::numeric_limits<int16_t>::max() &&
572 src_y + src_h < std::numeric_limits<int16_t>::max());
573 if (src_w <= 0 || src_h <= 0) {
574 NOTREACHED() << "Attempting to draw bitmap from an empty rect!";
575 return;
578 if (!IntersectsClipRectInt(dest_x, dest_y, dest_w, dest_h))
579 return;
581 float user_scale_x = static_cast<float>(dest_w) / src_w;
582 float user_scale_y = static_cast<float>(dest_h) / src_h;
584 const ImageSkiaRep& image_rep = image.GetRepresentation(image_scale);
585 if (image_rep.is_null())
586 return;
588 SkRect dest_rect = { SkIntToScalar(dest_x),
589 SkIntToScalar(dest_y),
590 SkIntToScalar(dest_x + dest_w),
591 SkIntToScalar(dest_y + dest_h) };
593 if (src_w == dest_w && src_h == dest_h &&
594 user_scale_x == 1.0f && user_scale_y == 1.0f &&
595 image_rep.scale() == 1.0f && !pixel) {
596 // Workaround for apparent bug in Skia that causes image to occasionally
597 // shift.
598 SkIRect src_rect = { src_x, src_y, src_x + src_w, src_y + src_h };
599 const SkBitmap& bitmap = image_rep.sk_bitmap();
600 canvas_->drawBitmapRect(bitmap, &src_rect, dest_rect, &paint);
601 return;
604 // Make a bitmap shader that contains the bitmap we want to draw. This is
605 // basically what SkCanvas.drawBitmap does internally, but it gives us
606 // more control over quality and will use the mipmap in the source image if
607 // it has one, whereas drawBitmap won't.
608 SkMatrix shader_scale;
609 shader_scale.setScale(SkFloatToScalar(user_scale_x),
610 SkFloatToScalar(user_scale_y));
611 shader_scale.preTranslate(SkIntToScalar(-src_x), SkIntToScalar(-src_y));
612 shader_scale.postTranslate(SkIntToScalar(dest_x), SkIntToScalar(dest_y));
614 skia::RefPtr<SkShader> shader = CreateImageRepShaderForScale(
615 image_rep,
616 SkShader::kRepeat_TileMode,
617 shader_scale,
618 pixel ? 1.0f : image_rep.scale());
620 // Set up our paint to use the shader & release our reference (now just owned
621 // by the paint).
622 SkPaint p(paint);
623 p.setFilterQuality(filter ? kLow_SkFilterQuality : kNone_SkFilterQuality);
624 p.setShader(shader.get());
626 // The rect will be filled by the bitmap.
627 canvas_->drawRect(dest_rect, p);
630 } // namespace gfx