Roll WebRTC 8987:8989, Libjingle 8985:8990
[chromium-blink-merge.git] / skia / ext / bitmap_platform_device_mac.cc
blob066e93ff198b09e3a84302674e8bfd33ca86312a
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 "skia/ext/bitmap_platform_device_mac.h"
7 #import <ApplicationServices/ApplicationServices.h>
8 #include <time.h>
10 #include "base/mac/mac_util.h"
11 #include "base/memory/ref_counted.h"
12 #include "skia/ext/bitmap_platform_device.h"
13 #include "skia/ext/platform_canvas.h"
14 #include "skia/ext/skia_utils_mac.h"
15 #include "third_party/skia/include/core/SkMatrix.h"
16 #include "third_party/skia/include/core/SkRegion.h"
17 #include "third_party/skia/include/core/SkTypes.h"
18 #include "third_party/skia/include/core/SkUtils.h"
20 namespace skia {
22 namespace {
24 static CGContextRef CGContextForData(void* data, int width, int height) {
25 #define HAS_ARGB_SHIFTS(a, r, g, b) \
26 (SK_A32_SHIFT == (a) && SK_R32_SHIFT == (r) \
27 && SK_G32_SHIFT == (g) && SK_B32_SHIFT == (b))
28 #if defined(SK_CPU_LENDIAN) && HAS_ARGB_SHIFTS(24, 16, 8, 0)
29 // Allocate a bitmap context with 4 components per pixel (BGRA). Apple
30 // recommends these flags for improved CG performance.
32 // CGBitmapContextCreate returns NULL if width/height are 0. However, our
33 // callers expect to get a canvas back (which they later resize/reallocate)
34 // so we pin the dimensions here.
35 width = SkMax32(1, width);
36 height = SkMax32(1, height);
37 CGContextRef context =
38 CGBitmapContextCreate(data, width, height, 8, width * 4,
39 base::mac::GetSystemColorSpace(),
40 kCGImageAlphaPremultipliedFirst |
41 kCGBitmapByteOrder32Host);
42 #else
43 #error We require that Skia's and CoreGraphics's recommended \
44 image memory layout match.
45 #endif
46 #undef HAS_ARGB_SHIFTS
48 if (!context)
49 return NULL;
51 // Change the coordinate system to match WebCore's
52 CGContextTranslateCTM(context, 0, height);
53 CGContextScaleCTM(context, 1.0, -1.0);
55 return context;
58 } // namespace
60 void BitmapPlatformDevice::ReleaseBitmapContext() {
61 SkASSERT(bitmap_context_);
62 CGContextRelease(bitmap_context_);
63 bitmap_context_ = NULL;
66 void BitmapPlatformDevice::SetMatrixClip(
67 const SkMatrix& transform,
68 const SkRegion& region) {
69 transform_ = transform;
70 clip_region_ = region;
71 config_dirty_ = true;
74 // Loads the specified Skia transform into the device context
75 static void LoadTransformToCGContext(CGContextRef context,
76 const SkMatrix& matrix) {
77 // CoreGraphics can concatenate transforms, but not reset the current one.
78 // So in order to get the required behavior here, we need to first make
79 // the current transformation matrix identity and only then load the new one.
81 // Reset matrix to identity.
82 CGAffineTransform orig_cg_matrix = CGContextGetCTM(context);
83 CGAffineTransform orig_cg_matrix_inv =
84 CGAffineTransformInvert(orig_cg_matrix);
85 CGContextConcatCTM(context, orig_cg_matrix_inv);
87 // assert that we have indeed returned to the identity Matrix.
88 SkASSERT(CGAffineTransformIsIdentity(CGContextGetCTM(context)));
90 // Convert xform to CG-land.
91 // Our coordinate system is flipped to match WebKit's so we need to modify
92 // the xform to match that.
93 SkMatrix transformed_matrix = matrix;
94 SkScalar sy = -matrix.getScaleY();
95 transformed_matrix.setScaleY(sy);
96 size_t height = CGBitmapContextGetHeight(context);
97 SkScalar ty = -matrix.getTranslateY(); // y axis is flipped.
98 transformed_matrix.setTranslateY(ty + (SkScalar)height);
100 CGAffineTransform cg_matrix =
101 gfx::SkMatrixToCGAffineTransform(transformed_matrix);
103 // Load final transform into context.
104 CGContextConcatCTM(context, cg_matrix);
107 // Loads a SkRegion into the CG context.
108 static void LoadClippingRegionToCGContext(CGContextRef context,
109 const SkRegion& region,
110 const SkMatrix& transformation) {
111 if (region.isEmpty()) {
112 // region can be empty, in which case everything will be clipped.
113 SkRect rect;
114 rect.setEmpty();
115 CGContextClipToRect(context, gfx::SkRectToCGRect(rect));
116 } else if (region.isRect()) {
117 // CoreGraphics applies the current transform to clip rects, which is
118 // unwanted. Inverse-transform the rect before sending it to CG. This only
119 // works for translations and scaling, but not for rotations (but the
120 // viewport is never rotated anyway).
121 SkMatrix t;
122 bool did_invert = transformation.invert(&t);
123 if (!did_invert)
124 t.reset();
125 // Do the transformation.
126 SkRect rect;
127 rect.set(region.getBounds());
128 t.mapRect(&rect);
129 SkIRect irect;
130 rect.round(&irect);
131 CGContextClipToRect(context, gfx::SkIRectToCGRect(irect));
132 } else {
133 // It is complex.
134 SkPath path;
135 region.getBoundaryPath(&path);
136 // Clip. Note that windows clipping regions are not affected by the
137 // transform so apply it manually.
138 path.transform(transformation);
139 // TODO(playmobil): Implement.
140 SkASSERT(false);
141 // LoadPathToDC(context, path);
142 // hrgn = PathToRegion(context);
146 void BitmapPlatformDevice::LoadConfig() {
147 if (!config_dirty_ || !bitmap_context_)
148 return; // Nothing to do.
149 config_dirty_ = false;
151 // We must restore and then save the state of the graphics context since the
152 // calls to Load the clipping region to the context are strictly cummulative,
153 // i.e., you can't replace a clip rect, other than with a save/restore.
154 // But this implies that no other changes to the state are done elsewhere.
155 // If we ever get to need to change this, then we must replace the clip rect
156 // calls in LoadClippingRegionToCGContext() with an image mask instead.
157 CGContextRestoreGState(bitmap_context_);
158 CGContextSaveGState(bitmap_context_);
159 LoadTransformToCGContext(bitmap_context_, transform_);
160 LoadClippingRegionToCGContext(bitmap_context_, clip_region_, transform_);
164 // We use this static factory function instead of the regular constructor so
165 // that we can create the pixel data before calling the constructor. This is
166 // required so that we can call the base class' constructor with the pixel
167 // data.
168 BitmapPlatformDevice* BitmapPlatformDevice::Create(CGContextRef context,
169 int width,
170 int height,
171 bool is_opaque,
172 bool do_clear) {
173 if (RasterDeviceTooBigToAllocate(width, height))
174 return NULL;
176 SkBitmap bitmap;
177 // TODO: verify that the CG Context's pixels will have tight rowbytes or pass in the correct
178 // rowbytes for the case when context != NULL.
179 bitmap.setInfo(SkImageInfo::MakeN32(width, height, is_opaque ? kOpaque_SkAlphaType : kPremul_SkAlphaType));
181 void* data;
182 if (context) {
183 data = CGBitmapContextGetData(context);
184 bitmap.setPixels(data);
185 } else {
186 if (!bitmap.tryAllocPixels())
187 return NULL;
188 data = bitmap.getPixels();
190 if (do_clear)
191 memset(data, 0, bitmap.getSafeSize());
193 // If we were given data, then don't clobber it!
194 #ifndef NDEBUG
195 if (!context && is_opaque) {
196 // To aid in finding bugs, we set the background color to something
197 // obviously wrong so it will be noticable when it is not cleared
198 bitmap.eraseARGB(255, 0, 255, 128); // bright bluish green
200 #endif
202 if (!context) {
203 context = CGContextForData(data, width, height);
204 if (!context)
205 return NULL;
206 } else
207 CGContextRetain(context);
209 BitmapPlatformDevice* rv = new BitmapPlatformDevice(context, bitmap);
211 // The device object took ownership of the graphics context with its own
212 // CGContextRetain call.
213 CGContextRelease(context);
215 return rv;
218 BitmapPlatformDevice* BitmapPlatformDevice::CreateWithData(uint8_t* data,
219 int width,
220 int height,
221 bool is_opaque) {
222 CGContextRef context = NULL;
223 if (data)
224 context = CGContextForData(data, width, height);
226 BitmapPlatformDevice* rv = Create(context, width, height, is_opaque, false);
228 // The device object took ownership of the graphics context with its own
229 // CGContextRetain call.
230 if (context)
231 CGContextRelease(context);
233 return rv;
236 // The device will own the bitmap, which corresponds to also owning the pixel
237 // data. Therefore, we do not transfer ownership to the SkBitmapDevice's bitmap.
238 BitmapPlatformDevice::BitmapPlatformDevice(
239 CGContextRef context, const SkBitmap& bitmap)
240 : SkBitmapDevice(bitmap),
241 bitmap_context_(context),
242 config_dirty_(true), // Want to load the config next time.
243 transform_(SkMatrix::I()) {
244 SetPlatformDevice(this, this);
245 SkASSERT(bitmap_context_);
246 // Initialize the clip region to the entire bitmap.
248 SkIRect rect;
249 rect.set(0, 0,
250 CGBitmapContextGetWidth(bitmap_context_),
251 CGBitmapContextGetHeight(bitmap_context_));
252 clip_region_ = SkRegion(rect);
253 CGContextRetain(bitmap_context_);
254 // We must save the state once so that we can use the restore/save trick
255 // in LoadConfig().
256 CGContextSaveGState(bitmap_context_);
259 BitmapPlatformDevice::~BitmapPlatformDevice() {
260 if (bitmap_context_)
261 CGContextRelease(bitmap_context_);
264 CGContextRef BitmapPlatformDevice::GetBitmapContext() {
265 LoadConfig();
266 return bitmap_context_;
269 void BitmapPlatformDevice::setMatrixClip(const SkMatrix& transform,
270 const SkRegion& region,
271 const SkClipStack&) {
272 SetMatrixClip(transform, region);
275 SkBaseDevice* BitmapPlatformDevice::onCreateDevice(const CreateInfo& cinfo,
276 const SkPaint*) {
277 const SkImageInfo& info = cinfo.fInfo;
278 const bool do_clear = !info.isOpaque();
279 SkASSERT(info.colorType() == kN32_SkColorType);
280 return Create(NULL, info.width(), info.height(), info.isOpaque(), do_clear);
283 // PlatformCanvas impl
285 SkCanvas* CreatePlatformCanvas(CGContextRef ctx, int width, int height,
286 bool is_opaque, OnFailureType failureType) {
287 const bool do_clear = false;
288 skia::RefPtr<SkBaseDevice> dev = skia::AdoptRef(
289 BitmapPlatformDevice::Create(ctx, width, height, is_opaque, do_clear));
290 return CreateCanvas(dev, failureType);
293 SkCanvas* CreatePlatformCanvas(int width, int height, bool is_opaque,
294 uint8_t* data, OnFailureType failureType) {
295 skia::RefPtr<SkBaseDevice> dev = skia::AdoptRef(
296 BitmapPlatformDevice::CreateWithData(data, width, height, is_opaque));
297 return CreateCanvas(dev, failureType);
300 // Port of PlatformBitmap to mac
302 PlatformBitmap::~PlatformBitmap() {
303 if (surface_)
304 CGContextRelease(surface_);
307 bool PlatformBitmap::Allocate(int width, int height, bool is_opaque) {
308 if (RasterDeviceTooBigToAllocate(width, height))
309 return false;
311 if (!bitmap_.tryAllocN32Pixels(width, height, is_opaque))
312 return false;
314 if (!is_opaque)
315 bitmap_.eraseColor(0);
317 surface_ = CGContextForData(bitmap_.getPixels(), bitmap_.width(),
318 bitmap_.height());
319 return true;
322 } // namespace skia