1 /*
2  * Copyright 2013 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #include "SkCanvasStateUtils.h"
9 
10 #include "SkBitmapDevice.h"
11 #include "SkCanvas.h"
12 #include "SkCanvasStack.h"
13 #include "SkErrorInternals.h"
14 #include "SkWriter32.h"
15 
16 /*
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).
19  *
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
22  * NECESSARY!
23  *
24  * In order to test changes, run the CanvasState tests. gyp/canvas_state_lib.gyp
25  * describes how to create a library to pass to the CanvasState tests. The tests
26  * should succeed when building the library with your changes and passing that to
27  * the tests running in the unchanged Skia.
28  */
29 enum RasterConfigs {
30   kUnknown_RasterConfig   = 0,
31   kRGB_565_RasterConfig   = 1,
32   kARGB_8888_RasterConfig = 2
33 };
34 typedef int32_t RasterConfig;
35 
36 enum CanvasBackends {
37     kUnknown_CanvasBackend = 0,
38     kRaster_CanvasBackend  = 1,
39     kGPU_CanvasBackend     = 2,
40     kPDF_CanvasBackend     = 3
41 };
42 typedef int32_t CanvasBackend;
43 
44 struct ClipRect {
45     int32_t left, top, right, bottom;
46 };
47 
48 struct SkMCState {
49     float matrix[9];
50     // NOTE: this only works for non-antialiased clips
51     int32_t clipRectCount;
52     ClipRect* clipRects;
53 };
54 
55 // NOTE: If you add more members, create a new subclass of SkCanvasState with a
56 // new CanvasState::version.
57 struct SkCanvasLayerState {
58     CanvasBackend type;
59     int32_t x, y;
60     int32_t width;
61     int32_t height;
62 
63     SkMCState mcState;
64 
65     union {
66         struct {
67             RasterConfig config; // pixel format: a value from RasterConfigs.
68             uint64_t rowBytes;   // Number of bytes from start of one line to next.
69             void* pixels;        // The pixels, all (height * rowBytes) of them.
70         } raster;
71         struct {
72             int32_t textureID;
73         } gpu;
74     };
75 };
76 
77 class SkCanvasState {
78 public:
SkCanvasState(int32_t version,SkCanvas * canvas)79     SkCanvasState(int32_t version, SkCanvas* canvas) {
80         SkASSERT(canvas);
81         this->version = version;
82         width = canvas->getBaseLayerSize().width();
83         height = canvas->getBaseLayerSize().height();
84 
85     }
86 
87     /**
88      * The version this struct was built with.  This field must always appear
89      * first in the struct so that when the versions don't match (and the
90      * remaining contents and size are potentially different) we can still
91      * compare the version numbers.
92      */
93     int32_t version;
94     int32_t width;
95     int32_t height;
96     int32_t alignmentPadding;
97 };
98 
99 class SkCanvasState_v1 : public SkCanvasState {
100 public:
101     static const int32_t kVersion = 1;
102 
SkCanvasState_v1(SkCanvas * canvas)103     SkCanvasState_v1(SkCanvas* canvas)
104     : INHERITED(kVersion, canvas)
105     {
106         layerCount = 0;
107         layers = NULL;
108         mcState.clipRectCount = 0;
109         mcState.clipRects = NULL;
110         originalCanvas = SkRef(canvas);
111     }
112 
~SkCanvasState_v1()113     ~SkCanvasState_v1() {
114         // loop through the layers and free the data allocated to the clipRects
115         for (int i = 0; i < layerCount; ++i) {
116             sk_free(layers[i].mcState.clipRects);
117         }
118 
119         sk_free(mcState.clipRects);
120         sk_free(layers);
121 
122         // it is now safe to free the canvas since there should be no remaining
123         // references to the content that is referenced by this canvas (e.g. pixels)
124         originalCanvas->unref();
125     }
126 
127     SkMCState mcState;
128 
129     int32_t layerCount;
130     SkCanvasLayerState* layers;
131 private:
132     SkCanvas* originalCanvas;
133     typedef SkCanvasState INHERITED;
134 };
135 
136 ////////////////////////////////////////////////////////////////////////////////
137 
138 class ClipValidator : public SkCanvas::ClipVisitor {
139 public:
ClipValidator()140     ClipValidator() : fFailed(false) {}
failed()141     bool failed() { return fFailed; }
142 
143     // ClipVisitor
clipRect(const SkRect & rect,SkRegion::Op op,bool antialias)144     void clipRect(const SkRect& rect, SkRegion::Op op, bool antialias) override {
145         fFailed |= antialias;
146     }
147 
clipRRect(const SkRRect & rrect,SkRegion::Op op,bool antialias)148     void clipRRect(const SkRRect& rrect, SkRegion::Op op, bool antialias) override {
149         fFailed |= antialias;
150     }
151 
clipPath(const SkPath &,SkRegion::Op,bool antialias)152     void clipPath(const SkPath&, SkRegion::Op, bool antialias) override {
153         fFailed |= antialias;
154     }
155 
156 private:
157     bool fFailed;
158 };
159 
setup_MC_state(SkMCState * state,const SkMatrix & matrix,const SkRegion & clip)160 static void setup_MC_state(SkMCState* state, const SkMatrix& matrix, const SkRegion& clip) {
161     // initialize the struct
162     state->clipRectCount = 0;
163 
164     // capture the matrix
165     for (int i = 0; i < 9; i++) {
166         state->matrix[i] = matrix.get(i);
167     }
168 
169     /*
170      * capture the clip
171      *
172      * storage is allocated on the stack for the first 4 rects. This value was
173      * chosen somewhat arbitrarily, but does allow us to represent simple clips
174      * and some more common complex clips (e.g. a clipRect with a sub-rect
175      * clipped out of its interior) without needing to malloc any additional memory.
176      */
177     SkSWriter32<4*sizeof(ClipRect)> clipWriter;
178 
179     if (!clip.isEmpty()) {
180         // only returns the b/w clip so aa clips fail
181         SkRegion::Iterator clip_iterator(clip);
182         for (; !clip_iterator.done(); clip_iterator.next()) {
183             // this assumes the SkIRect is stored in l,t,r,b ordering which
184             // matches the ordering of our ClipRect struct
185             clipWriter.writeIRect(clip_iterator.rect());
186             state->clipRectCount++;
187         }
188     }
189 
190     // allocate memory for the clip then and copy them to the struct
191     state->clipRects = (ClipRect*) sk_malloc_throw(clipWriter.bytesWritten());
192     clipWriter.flatten(state->clipRects);
193 }
194 
195 
196 
CaptureCanvasState(SkCanvas * canvas)197 SkCanvasState* SkCanvasStateUtils::CaptureCanvasState(SkCanvas* canvas) {
198     SkASSERT(canvas);
199 
200     // Check the clip can be decomposed into rectangles (i.e. no soft clips).
201     ClipValidator validator;
202     canvas->replayClips(&validator);
203     if (validator.failed()) {
204         SkErrorInternals::SetError(kInvalidOperation_SkError,
205                 "CaptureCanvasState does not support canvases with antialiased clips.\n");
206         return NULL;
207     }
208 
209     SkAutoTDelete<SkCanvasState_v1> canvasState(SkNEW_ARGS(SkCanvasState_v1, (canvas)));
210 
211     // decompose the total matrix and clip
212     setup_MC_state(&canvasState->mcState, canvas->getTotalMatrix(),
213                    canvas->internal_private_getTotalClip());
214 
215     /*
216      * decompose the layers
217      *
218      * storage is allocated on the stack for the first 3 layers. It is common in
219      * some view systems (e.g. Android) that a few non-clipped layers are present
220      * and we will not need to malloc any additional memory in those cases.
221      */
222     SkSWriter32<3*sizeof(SkCanvasLayerState)> layerWriter;
223     int layerCount = 0;
224     for (SkCanvas::LayerIter layer(canvas, true/*skipEmptyClips*/); !layer.done(); layer.next()) {
225 
226         // we currently only work for bitmap backed devices
227         const SkBitmap& bitmap = layer.device()->accessBitmap(true/*changePixels*/);
228         if (bitmap.empty() || bitmap.isNull() || !bitmap.lockPixelsAreWritable()) {
229             return NULL;
230         }
231 
232         SkCanvasLayerState* layerState =
233                 (SkCanvasLayerState*) layerWriter.reserve(sizeof(SkCanvasLayerState));
234         layerState->type = kRaster_CanvasBackend;
235         layerState->x = layer.x();
236         layerState->y = layer.y();
237         layerState->width = bitmap.width();
238         layerState->height = bitmap.height();
239 
240         switch (bitmap.colorType()) {
241             case kN32_SkColorType:
242                 layerState->raster.config = kARGB_8888_RasterConfig;
243                 break;
244             case kRGB_565_SkColorType:
245                 layerState->raster.config = kRGB_565_RasterConfig;
246                 break;
247             default:
248                 return NULL;
249         }
250         layerState->raster.rowBytes = bitmap.rowBytes();
251         layerState->raster.pixels = bitmap.getPixels();
252 
253         setup_MC_state(&layerState->mcState, layer.matrix(), layer.clip());
254         layerCount++;
255     }
256 
257     // allocate memory for the layers and then and copy them to the struct
258     SkASSERT(layerWriter.bytesWritten() == layerCount * sizeof(SkCanvasLayerState));
259     canvasState->layerCount = layerCount;
260     canvasState->layers = (SkCanvasLayerState*) sk_malloc_throw(layerWriter.bytesWritten());
261     layerWriter.flatten(canvasState->layers);
262 
263     // for now, just ignore any client supplied DrawFilter.
264     if (canvas->getDrawFilter()) {
265 //        SkDEBUGF(("CaptureCanvasState will ignore the canvas's draw filter.\n"));
266     }
267 
268     return canvasState.detach();
269 }
270 
271 ////////////////////////////////////////////////////////////////////////////////
272 
setup_canvas_from_MC_state(const SkMCState & state,SkCanvas * canvas)273 static void setup_canvas_from_MC_state(const SkMCState& state, SkCanvas* canvas) {
274     // reconstruct the matrix
275     SkMatrix matrix;
276     for (int i = 0; i < 9; i++) {
277         matrix.set(i, state.matrix[i]);
278     }
279 
280     // reconstruct the clip
281     SkRegion clip;
282     for (int i = 0; i < state.clipRectCount; ++i) {
283         clip.op(SkIRect::MakeLTRB(state.clipRects[i].left,
284                                   state.clipRects[i].top,
285                                   state.clipRects[i].right,
286                                   state.clipRects[i].bottom),
287                 SkRegion::kUnion_Op);
288     }
289 
290     canvas->setMatrix(matrix);
291     canvas->setClipRegion(clip);
292 }
293 
create_canvas_from_canvas_layer(const SkCanvasLayerState & layerState)294 static SkCanvas* create_canvas_from_canvas_layer(const SkCanvasLayerState& layerState) {
295     SkASSERT(kRaster_CanvasBackend == layerState.type);
296 
297     SkBitmap bitmap;
298     SkColorType colorType =
299         layerState.raster.config == kARGB_8888_RasterConfig ? kN32_SkColorType :
300         layerState.raster.config == kRGB_565_RasterConfig ? kRGB_565_SkColorType :
301         kUnknown_SkColorType;
302 
303     if (colorType == kUnknown_SkColorType) {
304         return NULL;
305     }
306 
307     bitmap.installPixels(SkImageInfo::Make(layerState.width, layerState.height,
308                                            colorType, kPremul_SkAlphaType),
309                          layerState.raster.pixels, (size_t) layerState.raster.rowBytes);
310 
311     SkASSERT(!bitmap.empty());
312     SkASSERT(!bitmap.isNull());
313 
314     SkAutoTUnref<SkCanvas> canvas(SkNEW_ARGS(SkCanvas, (bitmap)));
315 
316     // setup the matrix and clip
317     setup_canvas_from_MC_state(layerState.mcState, canvas.get());
318 
319     return canvas.detach();
320 }
321 
CreateFromCanvasState(const SkCanvasState * state)322 SkCanvas* SkCanvasStateUtils::CreateFromCanvasState(const SkCanvasState* state) {
323     SkASSERT(state);
324     // Currently there is only one possible version.
325     SkASSERT(SkCanvasState_v1::kVersion == state->version);
326 
327     const SkCanvasState_v1* state_v1 = static_cast<const SkCanvasState_v1*>(state);
328 
329     if (state_v1->layerCount < 1) {
330         return NULL;
331     }
332 
333     SkAutoTUnref<SkCanvasStack> canvas(SkNEW_ARGS(SkCanvasStack, (state->width, state->height)));
334 
335     // setup the matrix and clip on the n-way canvas
336     setup_canvas_from_MC_state(state_v1->mcState, canvas);
337 
338     // Iterate over the layers and add them to the n-way canvas
339     for (int i = state_v1->layerCount - 1; i >= 0; --i) {
340         SkAutoTUnref<SkCanvas> canvasLayer(create_canvas_from_canvas_layer(state_v1->layers[i]));
341         if (!canvasLayer.get()) {
342             return NULL;
343         }
344         canvas->pushCanvas(canvasLayer.get(), SkIPoint::Make(state_v1->layers[i].x,
345                                                              state_v1->layers[i].y));
346     }
347 
348     return canvas.detach();
349 }
350 
351 ////////////////////////////////////////////////////////////////////////////////
352 
ReleaseCanvasState(SkCanvasState * state)353 void SkCanvasStateUtils::ReleaseCanvasState(SkCanvasState* state) {
354     SkASSERT(!state || SkCanvasState_v1::kVersion == state->version);
355     // Upcast to the correct version of SkCanvasState. This avoids having a virtual destructor on
356     // SkCanvasState. That would be strange since SkCanvasState has no other virtual functions, and
357     // instead uses the field "version" to determine how to behave.
358     SkDELETE(static_cast<SkCanvasState_v1*>(state));
359 }
360