Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / ui / gfx / canvas.cc
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.
4
5 #include "ui/gfx/canvas.h"
6
7 #include <cmath>
8 #include <limits>
9
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/rect.h"
16 #include "ui/gfx/size_conversions.h"
17 #include "ui/gfx/skia_util.h"
18 #include "ui/gfx/transform.h"
19
20 #if defined(OS_WIN)
21 #include "ui/gfx/canvas_skia_paint.h"
22 #endif
23
24 namespace gfx {
25
26 Canvas::Canvas(const Size& size, float image_scale, bool is_opaque)
27     : image_scale_(image_scale),
28       canvas_(NULL) {
29   Size pixel_size = ToCeiledSize(ScaleSize(size, image_scale));
30   owned_canvas_ = skia::AdoptRef(skia::CreatePlatformCanvas(pixel_size.width(),
31                                                             pixel_size.height(),
32                                                             is_opaque));
33   canvas_ = owned_canvas_.get();
34 #if defined(OS_WIN) || defined(OS_MACOSX)
35   // skia::PlatformCanvas instances are initialized to 0 by Cairo on Linux, but
36   // uninitialized on Win and Mac.
37   if (!is_opaque)
38     owned_canvas_->clear(SkColorSetARGB(0, 0, 0, 0));
39 #endif
40
41   SkScalar scale_scalar = SkFloatToScalar(image_scale);
42   canvas_->scale(scale_scalar, scale_scalar);
43 }
44
45 Canvas::Canvas(const ImageSkiaRep& image_rep, bool is_opaque)
46     : image_scale_(image_rep.scale()),
47       owned_canvas_(skia::AdoptRef(
48           skia::CreatePlatformCanvas(image_rep.pixel_width(),
49                                      image_rep.pixel_height(),
50                                      is_opaque))),
51       canvas_(owned_canvas_.get()) {
52   SkScalar scale_scalar = SkFloatToScalar(image_scale_);
53   canvas_->scale(scale_scalar, scale_scalar);
54   DrawImageInt(ImageSkia(image_rep), 0, 0);
55 }
56
57 Canvas::Canvas()
58     : image_scale_(1.0),
59       owned_canvas_(skia::AdoptRef(skia::CreatePlatformCanvas(0, 0, false))),
60       canvas_(owned_canvas_.get()) {
61 }
62
63 Canvas::~Canvas() {
64 }
65
66 // static
67 Canvas* Canvas::CreateCanvasWithoutScaling(SkCanvas* canvas,
68                                            float image_scale) {
69   return new Canvas(canvas, image_scale);
70 }
71
72 void Canvas::RecreateBackingCanvas(const Size& size,
73                                    float image_scale,
74                                    bool is_opaque) {
75   image_scale_ = image_scale;
76   Size pixel_size = ToFlooredSize(ScaleSize(size, image_scale));
77   owned_canvas_ = skia::AdoptRef(skia::CreatePlatformCanvas(pixel_size.width(),
78                                                             pixel_size.height(),
79                                                             is_opaque));
80   canvas_ = owned_canvas_.get();
81   SkScalar scale_scalar = SkFloatToScalar(image_scale);
82   canvas_->scale(scale_scalar, scale_scalar);
83 }
84
85 // static
86 void Canvas::SizeStringInt(const base::string16& text,
87                            const FontList& font_list,
88                            int* width,
89                            int* height,
90                            int line_height,
91                            int flags) {
92   float fractional_width = *width;
93   float factional_height = *height;
94   SizeStringFloat(text, font_list, &fractional_width,
95                   &factional_height, line_height, flags);
96   *width = std::ceil(fractional_width);
97   *height = std::ceil(factional_height);
98 }
99
100 // static
101 int Canvas::GetStringWidth(const base::string16& text,
102                            const FontList& font_list) {
103   int width = 0, height = 0;
104   SizeStringInt(text, font_list, &width, &height, 0, NO_ELLIPSIS);
105   return width;
106 }
107
108 // static
109 float Canvas::GetStringWidthF(const base::string16& text,
110                               const FontList& font_list) {
111   float width = 0, height = 0;
112   SizeStringFloat(text, font_list, &width, &height, 0, NO_ELLIPSIS);
113   return width;
114 }
115
116 // static
117 int Canvas::GetStringWidth(const base::string16& text, const Font& font) {
118   int width = 0, height = 0;
119   SizeStringInt(text, FontList(font), &width, &height, 0, NO_ELLIPSIS);
120   return width;
121 }
122
123 // static
124 int Canvas::DefaultCanvasTextAlignment() {
125   return base::i18n::IsRTL() ? TEXT_ALIGN_RIGHT : TEXT_ALIGN_LEFT;
126 }
127
128 ImageSkiaRep Canvas::ExtractImageRep() const {
129   const SkBitmap& device_bitmap = canvas_->getDevice()->accessBitmap(false);
130
131   // Make a bitmap to return, and a canvas to draw into it. We don't just want
132   // to call extractSubset or the copy constructor, since we want an actual copy
133   // of the bitmap.
134   SkBitmap result;
135   device_bitmap.copyTo(&result, SkBitmap::kARGB_8888_Config);
136
137   return ImageSkiaRep(result, image_scale_);
138 }
139
140 void Canvas::DrawDashedRect(const Rect& rect, SkColor color) {
141   // Create a 2D bitmap containing alternating on/off pixels - we do this
142   // so that you never get two pixels of the same color around the edges
143   // of the focus rect (this may mean that opposing edges of the rect may
144   // have a dot pattern out of phase to each other).
145   static SkColor last_color;
146   static SkBitmap* dots = NULL;
147   if (!dots || last_color != color) {
148     int col_pixels = 32;
149     int row_pixels = 32;
150
151     delete dots;
152     last_color = color;
153     dots = new SkBitmap;
154     dots->setConfig(SkBitmap::kARGB_8888_Config, col_pixels, row_pixels);
155     dots->allocPixels();
156     dots->eraseARGB(0, 0, 0, 0);
157
158     uint32_t* dot = dots->getAddr32(0, 0);
159     for (int i = 0; i < row_pixels; i++) {
160       for (int u = 0; u < col_pixels; u++) {
161         if ((u % 2 + i % 2) % 2 != 0) {
162           dot[i * row_pixels + u] = color;
163         }
164       }
165     }
166   }
167
168   // Make a shader for the bitmap with an origin of the box we'll draw. This
169   // shader is refcounted and will have an initial refcount of 1.
170   skia::RefPtr<SkShader> shader = skia::AdoptRef(
171       SkShader::CreateBitmapShader(
172           *dots, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode));
173   // Assign the shader to the paint & release our reference. The paint will
174   // now own the shader and the shader will be destroyed when the paint goes
175   // out of scope.
176   SkPaint paint;
177   paint.setShader(shader.get());
178
179   DrawRect(Rect(rect.x(), rect.y(), rect.width(), 1), paint);
180   DrawRect(Rect(rect.x(), rect.y() + rect.height() - 1, rect.width(), 1),
181            paint);
182   DrawRect(Rect(rect.x(), rect.y(), 1, rect.height()), paint);
183   DrawRect(Rect(rect.x() + rect.width() - 1, rect.y(), 1, rect.height()),
184            paint);
185 }
186
187 void Canvas::Save() {
188   canvas_->save();
189 }
190
191 void Canvas::SaveLayerAlpha(uint8 alpha) {
192   canvas_->saveLayerAlpha(NULL, alpha);
193 }
194
195
196 void Canvas::SaveLayerAlpha(uint8 alpha, const Rect& layer_bounds) {
197   SkRect bounds(RectToSkRect(layer_bounds));
198   canvas_->saveLayerAlpha(&bounds, alpha);
199 }
200
201 void Canvas::Restore() {
202   canvas_->restore();
203 }
204
205 bool Canvas::ClipRect(const Rect& rect) {
206   return canvas_->clipRect(RectToSkRect(rect));
207 }
208
209 bool Canvas::ClipPath(const SkPath& path) {
210   return canvas_->clipPath(path);
211 }
212
213 bool Canvas::GetClipBounds(Rect* bounds) {
214   SkRect out;
215   bool has_non_empty_clip = canvas_->getClipBounds(&out);
216   bounds->SetRect(out.left(), out.top(), out.width(), out.height());
217   return has_non_empty_clip;
218 }
219
220 void Canvas::Translate(const Vector2d& offset) {
221   canvas_->translate(SkIntToScalar(offset.x()), SkIntToScalar(offset.y()));
222 }
223
224 void Canvas::Scale(int x_scale, int y_scale) {
225   canvas_->scale(SkIntToScalar(x_scale), SkIntToScalar(y_scale));
226 }
227
228 void Canvas::DrawColor(SkColor color) {
229   DrawColor(color, SkXfermode::kSrcOver_Mode);
230 }
231
232 void Canvas::DrawColor(SkColor color, SkXfermode::Mode mode) {
233   canvas_->drawColor(color, mode);
234 }
235
236 void Canvas::FillRect(const Rect& rect, SkColor color) {
237   FillRect(rect, color, SkXfermode::kSrcOver_Mode);
238 }
239
240 void Canvas::FillRect(const Rect& rect,
241                       SkColor color,
242                       SkXfermode::Mode mode) {
243   SkPaint paint;
244   paint.setColor(color);
245   paint.setStyle(SkPaint::kFill_Style);
246   paint.setXfermodeMode(mode);
247   DrawRect(rect, paint);
248 }
249
250 void Canvas::DrawRect(const Rect& rect, SkColor color) {
251   DrawRect(rect, color, SkXfermode::kSrcOver_Mode);
252 }
253
254 void Canvas::DrawRect(const Rect& rect,
255                       SkColor color,
256                       SkXfermode::Mode mode) {
257   SkPaint paint;
258   paint.setColor(color);
259   paint.setStyle(SkPaint::kStroke_Style);
260   // Set a stroke width of 0, which will put us down the stroke rect path.  If
261   // we set a stroke width of 1, for example, this will internally create a
262   // path and fill it, which causes problems near the edge of the canvas.
263   paint.setStrokeWidth(SkIntToScalar(0));
264   paint.setXfermodeMode(mode);
265
266   DrawRect(rect, paint);
267 }
268
269 void Canvas::DrawRect(const Rect& rect, const SkPaint& paint) {
270   canvas_->drawIRect(RectToSkIRect(rect), paint);
271 }
272
273 void Canvas::DrawPoint(const Point& p1, const SkPaint& paint) {
274   canvas_->drawPoint(SkIntToScalar(p1.x()), SkIntToScalar(p1.y()), paint);
275 }
276
277 void Canvas::DrawLine(const Point& p1, const Point& p2, SkColor color) {
278   SkPaint paint;
279   paint.setColor(color);
280   paint.setStrokeWidth(SkIntToScalar(1));
281   DrawLine(p1, p2, paint);
282 }
283
284 void Canvas::DrawLine(const Point& p1, const Point& p2, const SkPaint& paint) {
285   canvas_->drawLine(SkIntToScalar(p1.x()), SkIntToScalar(p1.y()),
286                     SkIntToScalar(p2.x()), SkIntToScalar(p2.y()), paint);
287 }
288
289 void Canvas::DrawCircle(const Point& center_point,
290                         int radius,
291                         const SkPaint& paint) {
292   canvas_->drawCircle(SkIntToScalar(center_point.x()),
293       SkIntToScalar(center_point.y()), SkIntToScalar(radius), paint);
294 }
295
296 void Canvas::DrawRoundRect(const Rect& rect,
297                            int radius,
298                            const SkPaint& paint) {
299   canvas_->drawRoundRect(RectToSkRect(rect), SkIntToScalar(radius),
300                          SkIntToScalar(radius), paint);
301 }
302
303 void Canvas::DrawPath(const SkPath& path, const SkPaint& paint) {
304   canvas_->drawPath(path, paint);
305 }
306
307 void Canvas::DrawFocusRect(const Rect& rect) {
308   DrawDashedRect(rect, SK_ColorGRAY);
309 }
310
311 void Canvas::DrawSolidFocusRect(const Rect& rect, SkColor color) {
312   SkPaint paint;
313   paint.setColor(color);
314   paint.setStrokeWidth(SkIntToScalar(1));
315   // Note: We cannot use DrawRect since it would create a path and fill it which
316   // would cause problems near the edge of the canvas.
317   int x1 = std::min(rect.x(), rect.right());
318   int x2 = std::max(rect.x(), rect.right());
319   int y1 = std::min(rect.y(), rect.bottom());
320   int y2 = std::max(rect.y(), rect.bottom());
321   DrawLine(Point(x1, y1), Point(x2, y1), paint);
322   DrawLine(Point(x1, y2), Point(x2, y2), paint);
323   DrawLine(Point(x1, y1), Point(x1, y2), paint);
324   DrawLine(Point(x2, y1), Point(x2, y2 + 1), paint);
325 }
326
327 void Canvas::DrawImageInt(const ImageSkia& image, int x, int y) {
328   SkPaint paint;
329   DrawImageInt(image, x, y, paint);
330 }
331
332 void Canvas::DrawImageInt(const ImageSkia& image, int x, int y, uint8 a) {
333   SkPaint paint;
334   paint.setAlpha(a);
335   DrawImageInt(image, x, y, paint);
336 }
337
338 void Canvas::DrawImageInt(const ImageSkia& image,
339                           int x,
340                           int y,
341                           const SkPaint& paint) {
342   const ImageSkiaRep& image_rep = GetImageRepToPaint(image);
343   if (image_rep.is_null())
344     return;
345   const SkBitmap& bitmap = image_rep.sk_bitmap();
346   float bitmap_scale = image_rep.scale();
347
348   canvas_->save();
349   canvas_->scale(SkFloatToScalar(1.0f / bitmap_scale),
350                  SkFloatToScalar(1.0f / bitmap_scale));
351   canvas_->drawBitmap(bitmap,
352                       SkFloatToScalar(x * bitmap_scale),
353                       SkFloatToScalar(y * bitmap_scale),
354                       &paint);
355   canvas_->restore();
356 }
357
358 void Canvas::DrawImageInt(const ImageSkia& image,
359                           int src_x,
360                           int src_y,
361                           int src_w,
362                           int src_h,
363                           int dest_x,
364                           int dest_y,
365                           int dest_w,
366                           int dest_h,
367                           bool filter) {
368   SkPaint p;
369   DrawImageInt(image, src_x, src_y, src_w, src_h, dest_x, dest_y,
370                dest_w, dest_h, filter, p);
371 }
372
373 void Canvas::DrawImageInt(const ImageSkia& image,
374                           int src_x,
375                           int src_y,
376                           int src_w,
377                           int src_h,
378                           int dest_x,
379                           int dest_y,
380                           int dest_w,
381                           int dest_h,
382                           bool filter,
383                           const SkPaint& paint) {
384   DLOG_ASSERT(src_x + src_w < std::numeric_limits<int16_t>::max() &&
385               src_y + src_h < std::numeric_limits<int16_t>::max());
386   if (src_w <= 0 || src_h <= 0) {
387     NOTREACHED() << "Attempting to draw bitmap from an empty rect!";
388     return;
389   }
390
391   if (!IntersectsClipRectInt(dest_x, dest_y, dest_w, dest_h))
392     return;
393
394   float user_scale_x = static_cast<float>(dest_w) / src_w;
395   float user_scale_y = static_cast<float>(dest_h) / src_h;
396
397   const ImageSkiaRep& image_rep = GetImageRepToPaint(image,
398       user_scale_x, user_scale_y);
399   if (image_rep.is_null())
400     return;
401
402   SkRect dest_rect = { SkIntToScalar(dest_x),
403                        SkIntToScalar(dest_y),
404                        SkIntToScalar(dest_x + dest_w),
405                        SkIntToScalar(dest_y + dest_h) };
406
407   if (src_w == dest_w && src_h == dest_h &&
408       user_scale_x == 1.0f && user_scale_y == 1.0f &&
409       image_rep.scale() == 1.0f) {
410     // Workaround for apparent bug in Skia that causes image to occasionally
411     // shift.
412     SkIRect src_rect = { src_x, src_y, src_x + src_w, src_y + src_h };
413     const SkBitmap& bitmap = image_rep.sk_bitmap();
414     canvas_->drawBitmapRect(bitmap, &src_rect, dest_rect, &paint);
415     return;
416   }
417
418   // Make a bitmap shader that contains the bitmap we want to draw. This is
419   // basically what SkCanvas.drawBitmap does internally, but it gives us
420   // more control over quality and will use the mipmap in the source image if
421   // it has one, whereas drawBitmap won't.
422   SkMatrix shader_scale;
423   shader_scale.setScale(SkFloatToScalar(user_scale_x),
424                         SkFloatToScalar(user_scale_y));
425   shader_scale.preTranslate(SkIntToScalar(-src_x), SkIntToScalar(-src_y));
426   shader_scale.postTranslate(SkIntToScalar(dest_x), SkIntToScalar(dest_y));
427
428   skia::RefPtr<SkShader> shader = CreateImageRepShader(
429       image_rep,
430       SkShader::kRepeat_TileMode,
431       shader_scale);
432
433   // Set up our paint to use the shader & release our reference (now just owned
434   // by the paint).
435   SkPaint p(paint);
436   p.setFilterBitmap(filter);
437   p.setShader(shader.get());
438
439   // The rect will be filled by the bitmap.
440   canvas_->drawRect(dest_rect, p);
441 }
442
443 void Canvas::DrawImageInPath(const ImageSkia& image,
444                              int x,
445                              int y,
446                              const SkPath& path,
447                              const SkPaint& paint) {
448   const ImageSkiaRep& image_rep = GetImageRepToPaint(image);
449   if (image_rep.is_null())
450     return;
451
452   SkMatrix matrix;
453   matrix.setTranslate(SkIntToScalar(x), SkIntToScalar(y));
454   skia::RefPtr<SkShader> shader = CreateImageRepShader(
455       image_rep,
456       SkShader::kRepeat_TileMode,
457       matrix);
458
459   SkPaint p(paint);
460   p.setShader(shader.get());
461   canvas_->drawPath(path, p);
462 }
463
464 void Canvas::DrawStringRect(const base::string16& text,
465                             const FontList& font_list,
466                             SkColor color,
467                             const Rect& display_rect) {
468   DrawStringRectWithFlags(text, font_list, color, display_rect,
469                           DefaultCanvasTextAlignment());
470 }
471
472 void Canvas::DrawStringRectWithFlags(const base::string16& text,
473                                      const FontList& font_list,
474                                      SkColor color,
475                                      const Rect& display_rect,
476                                      int flags) {
477   DrawStringRectWithShadows(text, font_list, color, display_rect, 0, flags,
478                             ShadowValues());
479 }
480
481 void Canvas::TileImageInt(const ImageSkia& image,
482                           int x,
483                           int y,
484                           int w,
485                           int h) {
486   TileImageInt(image, 0, 0, x, y, w, h);
487 }
488
489 void Canvas::TileImageInt(const ImageSkia& image,
490                           int src_x,
491                           int src_y,
492                           int dest_x,
493                           int dest_y,
494                           int w,
495                           int h) {
496   TileImageInt(image, src_x, src_y, 1.0f, 1.0f, dest_x, dest_y, w, h);
497 }
498
499 void Canvas::TileImageInt(const ImageSkia& image,
500                           int src_x,
501                           int src_y,
502                           float tile_scale_x,
503                           float tile_scale_y,
504                           int dest_x,
505                           int dest_y,
506                           int w,
507                           int h) {
508   if (!IntersectsClipRectInt(dest_x, dest_y, w, h))
509     return;
510
511   const ImageSkiaRep& image_rep = GetImageRepToPaint(
512       image, tile_scale_x, tile_scale_y);
513   if (image_rep.is_null())
514     return;
515
516   SkMatrix shader_scale;
517   shader_scale.setScale(SkFloatToScalar(tile_scale_x),
518                         SkFloatToScalar(tile_scale_y));
519   shader_scale.preTranslate(SkIntToScalar(-src_x), SkIntToScalar(-src_y));
520   shader_scale.postTranslate(SkIntToScalar(dest_x), SkIntToScalar(dest_y));
521
522   skia::RefPtr<SkShader> shader = CreateImageRepShader(
523       image_rep,
524       SkShader::kRepeat_TileMode,
525       shader_scale);
526
527   SkPaint paint;
528   paint.setShader(shader.get());
529   paint.setXfermodeMode(SkXfermode::kSrcOver_Mode);
530
531   SkRect dest_rect = { SkIntToScalar(dest_x),
532                        SkIntToScalar(dest_y),
533                        SkIntToScalar(dest_x + w),
534                        SkIntToScalar(dest_y + h) };
535   canvas_->drawRect(dest_rect, paint);
536 }
537
538 NativeDrawingContext Canvas::BeginPlatformPaint() {
539   return skia::BeginPlatformPaint(canvas_);
540 }
541
542 void Canvas::EndPlatformPaint() {
543   skia::EndPlatformPaint(canvas_);
544 }
545
546 void Canvas::Transform(const gfx::Transform& transform) {
547   canvas_->concat(transform.matrix());
548 }
549
550 Canvas::Canvas(SkCanvas* canvas, float image_scale)
551     : image_scale_(image_scale),
552       owned_canvas_(),
553       canvas_(canvas) {
554   DCHECK(canvas);
555 }
556
557 bool Canvas::IntersectsClipRectInt(int x, int y, int w, int h) {
558   SkRect clip;
559   return canvas_->getClipBounds(&clip) &&
560       clip.intersect(SkIntToScalar(x), SkIntToScalar(y), SkIntToScalar(x + w),
561                      SkIntToScalar(y + h));
562 }
563
564 bool Canvas::IntersectsClipRect(const Rect& rect) {
565   return IntersectsClipRectInt(rect.x(), rect.y(),
566                                rect.width(), rect.height());
567 }
568
569 const ImageSkiaRep& Canvas::GetImageRepToPaint(const ImageSkia& image) const {
570   return GetImageRepToPaint(image, 1.0f, 1.0f);
571 }
572
573 const ImageSkiaRep& Canvas::GetImageRepToPaint(
574     const ImageSkia& image,
575     float user_additional_scale_x,
576     float user_additional_scale_y) const {
577   const ImageSkiaRep& image_rep = image.GetRepresentation(image_scale_);
578
579   if (!image_rep.is_null()) {
580     SkMatrix m = canvas_->getTotalMatrix();
581     float scale_x = SkScalarToFloat(SkScalarAbs(m.getScaleX())) *
582         user_additional_scale_x;
583     float scale_y = SkScalarToFloat(SkScalarAbs(m.getScaleY())) *
584         user_additional_scale_y;
585
586     float bitmap_scale = image_rep.scale();
587     if (scale_x < bitmap_scale || scale_y < bitmap_scale)
588       const_cast<SkBitmap&>(image_rep.sk_bitmap()).buildMipMap();
589   }
590
591   return image_rep;
592 }
593
594 }  // namespace gfx