RecordingCanvas.h revision 268a9c0f29c16a64d5819c7dbe8b0633baedab83
1/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef ANDROID_HWUI_RECORDING_CANVAS_H
18#define ANDROID_HWUI_RECORDING_CANVAS_H
19
20#include "Canvas.h"
21#include "CanvasState.h"
22#include "DisplayList.h"
23#include "ResourceCache.h"
24#include "SkiaCanvasProxy.h"
25#include "Snapshot.h"
26#include "utils/LinearAllocator.h"
27#include "utils/Macros.h"
28#include "utils/NinePatch.h"
29
30#include <SkDrawFilter.h>
31#include <SkPaint.h>
32#include <SkTLazy.h>
33
34#include <vector>
35
36namespace android {
37namespace uirenderer {
38
39class OpReceiver;
40struct RecordedOp;
41
42class RecordingCanvas: public Canvas, public CanvasStateClient {
43    enum class DeferredBarrierType {
44        None,
45        InOrder,
46        OutOfOrder,
47    };
48public:
49    RecordingCanvas(size_t width, size_t height);
50    virtual ~RecordingCanvas();
51
52    void reset(int width, int height);
53    WARN_UNUSED_RESULT DisplayList* finishRecording();
54
55// ----------------------------------------------------------------------------
56// MISC HWUI OPERATIONS - TODO: CATEGORIZE
57// ----------------------------------------------------------------------------
58    void insertReorderBarrier(bool enableReorder) {
59        mDeferredBarrierType = enableReorder
60                ? DeferredBarrierType::OutOfOrder : DeferredBarrierType::InOrder;
61    }
62    void drawRenderNode(RenderNode* renderNode);
63
64// ----------------------------------------------------------------------------
65// CanvasStateClient interface
66// ----------------------------------------------------------------------------
67    virtual void onViewportInitialized() override;
68    virtual void onSnapshotRestored(const Snapshot& removed, const Snapshot& restored) override;
69    virtual GLuint getTargetFbo() const override { return -1; }
70
71// ----------------------------------------------------------------------------
72// HWUI Canvas draw operations
73// ----------------------------------------------------------------------------
74
75    void drawRoundRect(CanvasPropertyPrimitive* left, CanvasPropertyPrimitive* top,
76            CanvasPropertyPrimitive* right, CanvasPropertyPrimitive* bottom,
77            CanvasPropertyPrimitive* rx, CanvasPropertyPrimitive* ry,
78            CanvasPropertyPaint* paint);
79    void drawCircle(CanvasPropertyPrimitive* x, CanvasPropertyPrimitive* y,
80            CanvasPropertyPrimitive* radius, CanvasPropertyPaint* paint);
81
82// ----------------------------------------------------------------------------
83// android/graphics/Canvas interface
84// ----------------------------------------------------------------------------
85    virtual SkCanvas* asSkCanvas() override;
86
87    virtual void setBitmap(const SkBitmap& bitmap) override {
88        LOG_ALWAYS_FATAL("RecordingCanvas is not backed by a bitmap.");
89    }
90
91    virtual bool isOpaque() override { return false; }
92    virtual int width() override { return mState.getWidth(); }
93    virtual int height() override { return mState.getHeight(); }
94
95    virtual void setHighContrastText(bool highContrastText) override {
96        mHighContrastText = highContrastText;
97    }
98    virtual bool isHighContrastText() override { return mHighContrastText; }
99
100// ----------------------------------------------------------------------------
101// android/graphics/Canvas state operations
102// ----------------------------------------------------------------------------
103    // Save (layer)
104    virtual int getSaveCount() const override { return mState.getSaveCount(); }
105    virtual int save(SkCanvas::SaveFlags flags) override;
106    virtual void restore() override;
107    virtual void restoreToCount(int saveCount) override;
108
109    virtual int saveLayer(float left, float top, float right, float bottom, const SkPaint* paint,
110        SkCanvas::SaveFlags flags) override;
111    virtual int saveLayerAlpha(float left, float top, float right, float bottom,
112            int alpha, SkCanvas::SaveFlags flags) override {
113        SkPaint paint;
114        paint.setAlpha(alpha);
115        return saveLayer(left, top, right, bottom, &paint, flags);
116    }
117
118    // Matrix
119    virtual void getMatrix(SkMatrix* outMatrix) const override { mState.getMatrix(outMatrix); }
120    virtual void setMatrix(const SkMatrix& matrix) override { mState.setMatrix(matrix); }
121
122    virtual void concat(const SkMatrix& matrix) override { mState.concatMatrix(matrix); }
123    virtual void rotate(float degrees) override;
124    virtual void scale(float sx, float sy) override;
125    virtual void skew(float sx, float sy) override;
126    virtual void translate(float dx, float dy) override;
127
128    // Clip
129    virtual bool getClipBounds(SkRect* outRect) const override;
130    virtual bool quickRejectRect(float left, float top, float right, float bottom) const override;
131    virtual bool quickRejectPath(const SkPath& path) const override;
132
133    virtual bool clipRect(float left, float top, float right, float bottom, SkRegion::Op op) override;
134    virtual bool clipPath(const SkPath* path, SkRegion::Op op) override;
135    virtual bool clipRegion(const SkRegion* region, SkRegion::Op op) override;
136
137    // Misc
138    virtual SkDrawFilter* getDrawFilter() override { return mDrawFilter.get(); }
139    virtual void setDrawFilter(SkDrawFilter* filter) override {
140        mDrawFilter.reset(SkSafeRef(filter));
141    }
142
143// ----------------------------------------------------------------------------
144// android/graphics/Canvas draw operations
145// ----------------------------------------------------------------------------
146    virtual void drawColor(int color, SkXfermode::Mode mode) override;
147    virtual void drawPaint(const SkPaint& paint) override;
148
149    // Geometry
150    virtual void drawPoint(float x, float y, const SkPaint& paint) override {
151        float points[2] = { x, y };
152        drawPoints(points, 2, paint);
153    }
154    virtual void drawPoints(const float* points, int floatCount, const SkPaint& paint) override;
155    virtual void drawLine(float startX, float startY, float stopX, float stopY,
156            const SkPaint& paint) override {
157        float points[4] = { startX, startY, stopX, stopY };
158        drawLines(points, 4, paint);
159    }
160    virtual void drawLines(const float* points, int floatCount, const SkPaint& paint) override;
161    virtual void drawRect(float left, float top, float right, float bottom, const SkPaint& paint) override;
162    virtual void drawRegion(const SkRegion& region, const SkPaint& paint) override;
163    virtual void drawRoundRect(float left, float top, float right, float bottom,
164            float rx, float ry, const SkPaint& paint) override;
165    virtual void drawCircle(float x, float y, float radius, const SkPaint& paint) override;
166    virtual void drawOval(float left, float top, float right, float bottom, const SkPaint& paint) override;
167    virtual void drawArc(float left, float top, float right, float bottom,
168            float startAngle, float sweepAngle, bool useCenter, const SkPaint& paint) override;
169    virtual void drawPath(const SkPath& path, const SkPaint& paint) override;
170    virtual void drawVertices(SkCanvas::VertexMode vertexMode, int vertexCount,
171            const float* verts, const float* tex, const int* colors,
172            const uint16_t* indices, int indexCount, const SkPaint& paint) override
173        { /* RecordingCanvas does not support drawVertices(); ignore */ }
174
175    // Bitmap-based
176    virtual void drawBitmap(const SkBitmap& bitmap, float left, float top, const SkPaint* paint) override;
177    virtual void drawBitmap(const SkBitmap& bitmap, const SkMatrix& matrix,
178                            const SkPaint* paint) override;
179    virtual void drawBitmap(const SkBitmap& bitmap, float srcLeft, float srcTop,
180            float srcRight, float srcBottom, float dstLeft, float dstTop,
181            float dstRight, float dstBottom, const SkPaint* paint) override;
182    virtual void drawBitmapMesh(const SkBitmap& bitmap, int meshWidth, int meshHeight,
183            const float* vertices, const int* colors, const SkPaint* paint) override;
184    virtual void drawNinePatch(const SkBitmap& bitmap, const android::Res_png_9patch& chunk,
185            float dstLeft, float dstTop, float dstRight, float dstBottom,
186            const SkPaint* paint) override;
187
188    // Text
189    virtual void drawText(const uint16_t* glyphs, const float* positions, int count,
190            const SkPaint& paint, float x, float y, float boundsLeft, float boundsTop,
191            float boundsRight, float boundsBottom, float totalAdvance) override;
192    virtual void drawTextOnPath(const uint16_t* glyphs, int count, const SkPath& path,
193            float hOffset, float vOffset, const SkPaint& paint) override;
194    virtual bool drawTextAbsolutePos() const override { return false; }
195
196private:
197
198    void drawBitmap(const SkBitmap* bitmap, const SkPaint* paint);
199    void drawSimpleRects(const float* rects, int vertexCount, const SkPaint* paint);
200
201
202    size_t addOp(RecordedOp* op);
203// ----------------------------------------------------------------------------
204// lazy object copy
205// ----------------------------------------------------------------------------
206    LinearAllocator& alloc() { return mDisplayList->allocator; }
207
208    void refBitmapsInShader(const SkShader* shader);
209
210    template<class T>
211    inline const T* refBuffer(const T* srcBuffer, int32_t count) {
212        if (!srcBuffer) return nullptr;
213
214        T* dstBuffer = (T*) mDisplayList->allocator.alloc(count * sizeof(T));
215        memcpy(dstBuffer, srcBuffer, count * sizeof(T));
216        return dstBuffer;
217    }
218
219    inline const SkPath* refPath(const SkPath* path) {
220        if (!path) return nullptr;
221
222        // The points/verbs within the path are refcounted so this copy operation
223        // is inexpensive and maintains the generationID of the original path.
224        const SkPath* cachedPath = new SkPath(*path);
225        mDisplayList->pathResources.push_back(cachedPath);
226        return cachedPath;
227    }
228
229    /**
230     * Returns a RenderThread-safe, const copy of the SkPaint parameter passed in
231     * (with deduping based on paint hash / equality check)
232     */
233    inline const SkPaint* refPaint(const SkPaint* paint) {
234        if (!paint) return nullptr;
235
236        // If there is a draw filter apply it here and store the modified paint
237        // so that we don't need to modify the paint every time we access it.
238        SkTLazy<SkPaint> filteredPaint;
239        if (mDrawFilter.get()) {
240            filteredPaint.set(*paint);
241            mDrawFilter->filter(filteredPaint.get(), SkDrawFilter::kPaint_Type);
242            paint = filteredPaint.get();
243        }
244
245        // compute the hash key for the paint and check the cache.
246        const uint32_t key = paint->getHash();
247        const SkPaint* cachedPaint = mPaintMap.valueFor(key);
248        // In the unlikely event that 2 unique paints have the same hash we do a
249        // object equality check to ensure we don't erroneously dedup them.
250        if (cachedPaint == nullptr || *cachedPaint != *paint) {
251            cachedPaint = new SkPaint(*paint);
252            mDisplayList->paints.emplace_back(cachedPaint);
253            // replaceValueFor() performs an add if the entry doesn't exist
254            mPaintMap.replaceValueFor(key, cachedPaint);
255            refBitmapsInShader(cachedPaint->getShader());
256        }
257
258        return cachedPaint;
259    }
260
261    inline const SkRegion* refRegion(const SkRegion* region) {
262        if (!region) {
263            return region;
264        }
265
266        const SkRegion* cachedRegion = mRegionMap.valueFor(region);
267        // TODO: Add generation ID to SkRegion
268        if (cachedRegion == nullptr) {
269            std::unique_ptr<const SkRegion> copy(new SkRegion(*region));
270            cachedRegion = copy.get();
271            mDisplayList->regions.push_back(std::move(copy));
272
273            // replaceValueFor() performs an add if the entry doesn't exist
274            mRegionMap.replaceValueFor(region, cachedRegion);
275        }
276
277        return cachedRegion;
278    }
279
280    inline const SkBitmap* refBitmap(const SkBitmap& bitmap) {
281        // Note that this assumes the bitmap is immutable. There are cases this won't handle
282        // correctly, such as creating the bitmap from scratch, drawing with it, changing its
283        // contents, and drawing again. The only fix would be to always copy it the first time,
284        // which doesn't seem worth the extra cycles for this unlikely case.
285        SkBitmap* localBitmap = new (alloc()) SkBitmap(bitmap);
286        alloc().autoDestroy(localBitmap);
287        mDisplayList->bitmapResources.push_back(localBitmap);
288        return localBitmap;
289    }
290
291    inline const Res_png_9patch* refPatch(const Res_png_9patch* patch) {
292        mDisplayList->patchResources.push_back(patch);
293        mResourceCache.incrementRefcount(patch);
294        return patch;
295    }
296
297    DefaultKeyedVector<uint32_t, const SkPaint*> mPaintMap;
298    DefaultKeyedVector<const SkPath*, const SkPath*> mPathMap;
299    DefaultKeyedVector<const SkRegion*, const SkRegion*> mRegionMap;
300
301    CanvasState mState;
302    std::unique_ptr<SkiaCanvasProxy> mSkiaCanvasProxy;
303    ResourceCache& mResourceCache;
304    DeferredBarrierType mDeferredBarrierType = DeferredBarrierType::None;
305    DisplayList* mDisplayList = nullptr;
306    bool mHighContrastText = false;
307    SkAutoTUnref<SkDrawFilter> mDrawFilter;
308    int mRestoreSaveCount = -1;
309}; // class RecordingCanvas
310
311}; // namespace uirenderer
312}; // namespace android
313
314#endif // ANDROID_HWUI_RECORDING_CANVAS_H
315