2 * Copyright 2013 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #include "SkCanvasStateUtils.h"
10 #include "SkBitmapDevice.h"
12 #include "SkCanvasStack.h"
13 #include "SkErrorInternals.h"
14 #include "SkWriter32.h"
17 * WARNING: The structs below are part of a stable ABI and as such we explicitly
18 * use unambigious primitives (e.g. int32_t instead of an enum).
20 * ANY CHANGES TO THE STRUCTS BELOW THAT IMPACT THE ABI SHOULD RESULT IN A NEW
21 * NEW SUBCLASS OF SkCanvasState. SUCH CHANGES SHOULD ONLY BE MADE IF ABSOLUTELY
25 kUnknown_RasterConfig = 0,
26 kRGB_565_RasterConfig = 1,
27 kARGB_8888_RasterConfig = 2
29 typedef int32_t RasterConfig;
32 kUnknown_CanvasBackend = 0,
33 kRaster_CanvasBackend = 1,
34 kGPU_CanvasBackend = 2,
35 kPDF_CanvasBackend = 3
37 typedef int32_t CanvasBackend;
40 int32_t left, top, right, bottom;
45 // NOTE: this only works for non-antialiased clips
46 int32_t clipRectCount;
50 // NOTE: If you add more members, create a new subclass of SkCanvasState with a
51 // new CanvasState::version.
52 struct SkCanvasLayerState {
62 RasterConfig config; // pixel format: a value from RasterConfigs.
63 uint64_t rowBytes; // Number of bytes from start of one line to next.
64 void* pixels; // The pixels, all (height * rowBytes) of them.
74 SkCanvasState(int32_t version, SkCanvas* canvas) {
76 this->version = version;
77 width = canvas->getBaseLayerSize().width();
78 height = canvas->getBaseLayerSize().height();
83 * The version this struct was built with. This field must always appear
84 * first in the struct so that when the versions don't match (and the
85 * remaining contents and size are potentially different) we can still
86 * compare the version numbers.
91 int32_t alignmentPadding;
94 class SkCanvasState_v1 : public SkCanvasState {
96 static const int32_t kVersion = 1;
98 SkCanvasState_v1(SkCanvas* canvas)
99 : INHERITED(kVersion, canvas)
103 mcState.clipRectCount = 0;
104 mcState.clipRects = NULL;
105 originalCanvas = SkRef(canvas);
108 ~SkCanvasState_v1() {
109 // loop through the layers and free the data allocated to the clipRects
110 for (int i = 0; i < layerCount; ++i) {
111 sk_free(layers[i].mcState.clipRects);
114 sk_free(mcState.clipRects);
117 // it is now safe to free the canvas since there should be no remaining
118 // references to the content that is referenced by this canvas (e.g. pixels)
119 originalCanvas->unref();
125 SkCanvasLayerState* layers;
127 SkCanvas* originalCanvas;
128 typedef SkCanvasState INHERITED;
131 ////////////////////////////////////////////////////////////////////////////////
133 class ClipValidator : public SkCanvas::ClipVisitor {
135 ClipValidator() : fFailed(false) {}
136 bool failed() { return fFailed; }
139 virtual void clipRect(const SkRect& rect, SkRegion::Op op, bool antialias) SK_OVERRIDE {
140 fFailed |= antialias;
143 virtual void clipRRect(const SkRRect& rrect, SkRegion::Op op, bool antialias) SK_OVERRIDE {
144 fFailed |= antialias;
147 virtual void clipPath(const SkPath&, SkRegion::Op, bool antialias) SK_OVERRIDE {
148 fFailed |= antialias;
155 static void setup_MC_state(SkMCState* state, const SkMatrix& matrix, const SkRegion& clip) {
156 // initialize the struct
157 state->clipRectCount = 0;
159 // capture the matrix
160 for (int i = 0; i < 9; i++) {
161 state->matrix[i] = matrix.get(i);
167 * storage is allocated on the stack for the first 4 rects. This value was
168 * chosen somewhat arbitrarily, but does allow us to represent simple clips
169 * and some more common complex clips (e.g. a clipRect with a sub-rect
170 * clipped out of its interior) without needing to malloc any additional memory.
172 SkSWriter32<4*sizeof(ClipRect)> clipWriter;
174 if (!clip.isEmpty()) {
175 // only returns the b/w clip so aa clips fail
176 SkRegion::Iterator clip_iterator(clip);
177 for (; !clip_iterator.done(); clip_iterator.next()) {
178 // this assumes the SkIRect is stored in l,t,r,b ordering which
179 // matches the ordering of our ClipRect struct
180 clipWriter.writeIRect(clip_iterator.rect());
181 state->clipRectCount++;
185 // allocate memory for the clip then and copy them to the struct
186 state->clipRects = (ClipRect*) sk_malloc_throw(clipWriter.bytesWritten());
187 clipWriter.flatten(state->clipRects);
192 SkCanvasState* SkCanvasStateUtils::CaptureCanvasState(SkCanvas* canvas) {
195 // Check the clip can be decomposed into rectangles (i.e. no soft clips).
196 ClipValidator validator;
197 canvas->replayClips(&validator);
198 if (validator.failed()) {
199 SkErrorInternals::SetError(kInvalidOperation_SkError,
200 "CaptureCanvasState does not support canvases with antialiased clips.\n");
204 SkAutoTDelete<SkCanvasState_v1> canvasState(SkNEW_ARGS(SkCanvasState_v1, (canvas)));
206 // decompose the total matrix and clip
207 setup_MC_state(&canvasState->mcState, canvas->getTotalMatrix(),
208 canvas->internal_private_getTotalClip());
211 * decompose the layers
213 * storage is allocated on the stack for the first 3 layers. It is common in
214 * some view systems (e.g. Android) that a few non-clipped layers are present
215 * and we will not need to malloc any additional memory in those cases.
217 SkSWriter32<3*sizeof(SkCanvasLayerState)> layerWriter;
219 for (SkCanvas::LayerIter layer(canvas, true/*skipEmptyClips*/); !layer.done(); layer.next()) {
221 // we currently only work for bitmap backed devices
222 const SkBitmap& bitmap = layer.device()->accessBitmap(true/*changePixels*/);
223 if (bitmap.empty() || bitmap.isNull() || !bitmap.lockPixelsAreWritable()) {
227 SkCanvasLayerState* layerState =
228 (SkCanvasLayerState*) layerWriter.reserve(sizeof(SkCanvasLayerState));
229 layerState->type = kRaster_CanvasBackend;
230 layerState->x = layer.x();
231 layerState->y = layer.y();
232 layerState->width = bitmap.width();
233 layerState->height = bitmap.height();
235 switch (bitmap.colorType()) {
236 case kN32_SkColorType:
237 layerState->raster.config = kARGB_8888_RasterConfig;
239 case kRGB_565_SkColorType:
240 layerState->raster.config = kRGB_565_RasterConfig;
245 layerState->raster.rowBytes = bitmap.rowBytes();
246 layerState->raster.pixels = bitmap.getPixels();
248 setup_MC_state(&layerState->mcState, layer.matrix(), layer.clip());
252 // allocate memory for the layers and then and copy them to the struct
253 SkASSERT(layerWriter.bytesWritten() == layerCount * sizeof(SkCanvasLayerState));
254 canvasState->layerCount = layerCount;
255 canvasState->layers = (SkCanvasLayerState*) sk_malloc_throw(layerWriter.bytesWritten());
256 layerWriter.flatten(canvasState->layers);
258 // for now, just ignore any client supplied DrawFilter.
259 if (canvas->getDrawFilter()) {
260 // SkDEBUGF(("CaptureCanvasState will ignore the canvas's draw filter.\n"));
263 return canvasState.detach();
266 ////////////////////////////////////////////////////////////////////////////////
268 static void setup_canvas_from_MC_state(const SkMCState& state, SkCanvas* canvas) {
269 // reconstruct the matrix
271 for (int i = 0; i < 9; i++) {
272 matrix.set(i, state.matrix[i]);
275 // reconstruct the clip
277 for (int i = 0; i < state.clipRectCount; ++i) {
278 clip.op(SkIRect::MakeLTRB(state.clipRects[i].left,
279 state.clipRects[i].top,
280 state.clipRects[i].right,
281 state.clipRects[i].bottom),
282 SkRegion::kUnion_Op);
285 canvas->setMatrix(matrix);
286 canvas->setClipRegion(clip);
289 static SkCanvas* create_canvas_from_canvas_layer(const SkCanvasLayerState& layerState) {
290 SkASSERT(kRaster_CanvasBackend == layerState.type);
293 SkColorType colorType =
294 layerState.raster.config == kARGB_8888_RasterConfig ? kN32_SkColorType :
295 layerState.raster.config == kRGB_565_RasterConfig ? kRGB_565_SkColorType :
296 kUnknown_SkColorType;
298 if (colorType == kUnknown_SkColorType) {
302 bitmap.installPixels(SkImageInfo::Make(layerState.width, layerState.height,
303 colorType, kPremul_SkAlphaType),
304 layerState.raster.pixels, (size_t) layerState.raster.rowBytes);
306 SkASSERT(!bitmap.empty());
307 SkASSERT(!bitmap.isNull());
309 SkAutoTUnref<SkCanvas> canvas(SkNEW_ARGS(SkCanvas, (bitmap)));
311 // setup the matrix and clip
312 setup_canvas_from_MC_state(layerState.mcState, canvas.get());
314 return canvas.detach();
317 SkCanvas* SkCanvasStateUtils::CreateFromCanvasState(const SkCanvasState* state) {
319 // Currently there is only one possible version.
320 SkASSERT(SkCanvasState_v1::kVersion == state->version);
322 const SkCanvasState_v1* state_v1 = static_cast<const SkCanvasState_v1*>(state);
324 if (state_v1->layerCount < 1) {
328 SkAutoTUnref<SkCanvasStack> canvas(SkNEW_ARGS(SkCanvasStack, (state->width, state->height)));
330 // setup the matrix and clip on the n-way canvas
331 setup_canvas_from_MC_state(state_v1->mcState, canvas);
333 // Iterate over the layers and add them to the n-way canvas
334 for (int i = state_v1->layerCount - 1; i >= 0; --i) {
335 SkAutoTUnref<SkCanvas> canvasLayer(create_canvas_from_canvas_layer(state_v1->layers[i]));
336 if (!canvasLayer.get()) {
339 canvas->pushCanvas(canvasLayer.get(), SkIPoint::Make(state_v1->layers[i].x,
340 state_v1->layers[i].y));
343 return canvas.detach();
346 ////////////////////////////////////////////////////////////////////////////////
348 void SkCanvasStateUtils::ReleaseCanvasState(SkCanvasState* state) {
349 SkASSERT(!state || SkCanvasState_v1::kVersion == state->version);
350 // Upcast to the correct version of SkCanvasState. This avoids having a virtual destructor on
351 // SkCanvasState. That would be strange since SkCanvasState has no other virtual functions, and
352 // instead uses the field "version" to determine how to behave.
353 SkDELETE(static_cast<SkCanvasState_v1*>(state));