RecordingCanvas.h revision 42a5407f2c6403ea7aa7a64eaf19948dc4050df5
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// android/graphics/Canvas interface
73// ----------------------------------------------------------------------------
74    virtual SkCanvas* asSkCanvas() override;
75
76    virtual void setBitmap(const SkBitmap& bitmap) override {
77        LOG_ALWAYS_FATAL("RecordingCanvas is not backed by a bitmap.");
78    }
79
80    virtual bool isOpaque() override { return false; }
81    virtual int width() override { return mState.getWidth(); }
82    virtual int height() override { return mState.getHeight(); }
83
84    virtual void setHighContrastText(bool highContrastText) override {
85        mHighContrastText = highContrastText;
86    }
87    virtual bool isHighContrastText() override { return mHighContrastText; }
88
89// ----------------------------------------------------------------------------
90// android/graphics/Canvas state operations
91// ----------------------------------------------------------------------------
92    // Save (layer)
93    virtual int getSaveCount() const override { return mState.getSaveCount(); }
94    virtual int save(SkCanvas::SaveFlags flags) override;
95    virtual void restore() override;
96    virtual void restoreToCount(int saveCount) override;
97
98    virtual int saveLayer(float left, float top, float right, float bottom, const SkPaint* paint,
99        SkCanvas::SaveFlags flags) override;
100    virtual int saveLayerAlpha(float left, float top, float right, float bottom,
101            int alpha, SkCanvas::SaveFlags flags) override {
102        SkPaint paint;
103        paint.setAlpha(alpha);
104        return saveLayer(left, top, right, bottom, &paint, flags);
105    }
106
107    // Matrix
108    virtual void getMatrix(SkMatrix* outMatrix) const override { mState.getMatrix(outMatrix); }
109    virtual void setMatrix(const SkMatrix& matrix) override { mState.setMatrix(matrix); }
110
111    virtual void concat(const SkMatrix& matrix) override { mState.concatMatrix(matrix); }
112    virtual void rotate(float degrees) override;
113    virtual void scale(float sx, float sy) override;
114    virtual void skew(float sx, float sy) override;
115    virtual void translate(float dx, float dy) override;
116
117    // Clip
118    virtual bool getClipBounds(SkRect* outRect) const override;
119    virtual bool quickRejectRect(float left, float top, float right, float bottom) const override;
120    virtual bool quickRejectPath(const SkPath& path) const override;
121
122    virtual bool clipRect(float left, float top, float right, float bottom, SkRegion::Op op) override;
123    virtual bool clipPath(const SkPath* path, SkRegion::Op op) override;
124    virtual bool clipRegion(const SkRegion* region, SkRegion::Op op) override;
125
126    // Misc
127    virtual SkDrawFilter* getDrawFilter() override { return mDrawFilter.get(); }
128    virtual void setDrawFilter(SkDrawFilter* filter) override {
129        mDrawFilter.reset(SkSafeRef(filter));
130    }
131
132// ----------------------------------------------------------------------------
133// android/graphics/Canvas draw operations
134// ----------------------------------------------------------------------------
135    virtual void drawColor(int color, SkXfermode::Mode mode) override;
136    virtual void drawPaint(const SkPaint& paint) override;
137
138    // Geometry
139    virtual void drawPoint(float x, float y, const SkPaint& paint) override {
140        float points[2] = { x, y };
141        drawPoints(points, 2, paint);
142    }
143    virtual void drawPoints(const float* points, int count, const SkPaint& paint) override;
144    virtual void drawLine(float startX, float startY, float stopX, float stopY,
145            const SkPaint& paint) override {
146        float points[4] = { startX, startY, stopX, stopY };
147        drawLines(points, 4, paint);
148    }
149    virtual void drawLines(const float* points, int count, const SkPaint& paint) override;
150    virtual void drawRect(float left, float top, float right, float bottom, const SkPaint& paint) override;
151    virtual void drawRegion(const SkRegion& region, const SkPaint& paint) override;
152    virtual void drawRoundRect(float left, float top, float right, float bottom,
153            float rx, float ry, const SkPaint& paint) override;
154    virtual void drawCircle(float x, float y, float radius, const SkPaint& paint) override;
155    virtual void drawOval(float left, float top, float right, float bottom, const SkPaint& paint) override;
156    virtual void drawArc(float left, float top, float right, float bottom,
157            float startAngle, float sweepAngle, bool useCenter, const SkPaint& paint) override;
158    virtual void drawPath(const SkPath& path, const SkPaint& paint) override;
159    virtual void drawVertices(SkCanvas::VertexMode vertexMode, int vertexCount,
160            const float* verts, const float* tex, const int* colors,
161            const uint16_t* indices, int indexCount, const SkPaint& paint) override
162        { /* RecordingCanvas does not support drawVertices(); ignore */ }
163
164    // Bitmap-based
165    virtual void drawBitmap(const SkBitmap& bitmap, float left, float top, const SkPaint* paint) override;
166    virtual void drawBitmap(const SkBitmap& bitmap, const SkMatrix& matrix,
167                            const SkPaint* paint) override;
168    virtual void drawBitmap(const SkBitmap& bitmap, float srcLeft, float srcTop,
169            float srcRight, float srcBottom, float dstLeft, float dstTop,
170            float dstRight, float dstBottom, const SkPaint* paint) override;
171    virtual void drawBitmapMesh(const SkBitmap& bitmap, int meshWidth, int meshHeight,
172            const float* vertices, const int* colors, const SkPaint* paint) override;
173    virtual void drawNinePatch(const SkBitmap& bitmap, const android::Res_png_9patch& chunk,
174            float dstLeft, float dstTop, float dstRight, float dstBottom,
175            const SkPaint* paint) override;
176
177    // Text
178    virtual void drawText(const uint16_t* glyphs, const float* positions, int count,
179            const SkPaint& paint, float x, float y, float boundsLeft, float boundsTop,
180            float boundsRight, float boundsBottom, float totalAdvance) override;
181    virtual void drawTextOnPath(const uint16_t* glyphs, int count, const SkPath& path,
182            float hOffset, float vOffset, const SkPaint& paint) override;
183    virtual bool drawTextAbsolutePos() const override { return false; }
184
185private:
186
187    void drawBitmap(const SkBitmap* bitmap, const SkPaint* paint);
188    void drawSimpleRects(const float* rects, int vertexCount, const SkPaint* paint);
189
190
191    size_t addOp(RecordedOp* op);
192// ----------------------------------------------------------------------------
193// lazy object copy
194// ----------------------------------------------------------------------------
195    LinearAllocator& alloc() { return mDisplayList->allocator; }
196
197    void refBitmapsInShader(const SkShader* shader);
198
199    template<class T>
200    inline const T* refBuffer(const T* srcBuffer, int32_t count) {
201        if (!srcBuffer) return nullptr;
202
203        T* dstBuffer = (T*) mDisplayList->allocator.alloc(count * sizeof(T));
204        memcpy(dstBuffer, srcBuffer, count * sizeof(T));
205        return dstBuffer;
206    }
207
208    inline const SkPath* refPath(const SkPath* path) {
209        if (!path) return nullptr;
210
211        // The points/verbs within the path are refcounted so this copy operation
212        // is inexpensive and maintains the generationID of the original path.
213        const SkPath* cachedPath = new SkPath(*path);
214        mDisplayList->pathResources.push_back(cachedPath);
215        return cachedPath;
216    }
217
218    /**
219     * Returns a RenderThread-safe, const copy of the SkPaint parameter passed in
220     * (with deduping based on paint hash / equality check)
221     */
222    inline const SkPaint* refPaint(const SkPaint* paint) {
223        if (!paint) return nullptr;
224
225        // If there is a draw filter apply it here and store the modified paint
226        // so that we don't need to modify the paint every time we access it.
227        SkTLazy<SkPaint> filteredPaint;
228        if (mDrawFilter.get()) {
229            filteredPaint.set(*paint);
230            mDrawFilter->filter(filteredPaint.get(), SkDrawFilter::kPaint_Type);
231            paint = filteredPaint.get();
232        }
233
234        // compute the hash key for the paint and check the cache.
235        const uint32_t key = paint->getHash();
236        const SkPaint* cachedPaint = mPaintMap.valueFor(key);
237        // In the unlikely event that 2 unique paints have the same hash we do a
238        // object equality check to ensure we don't erroneously dedup them.
239        if (cachedPaint == nullptr || *cachedPaint != *paint) {
240            cachedPaint = new SkPaint(*paint);
241            mDisplayList->paints.emplace_back(cachedPaint);
242            // replaceValueFor() performs an add if the entry doesn't exist
243            mPaintMap.replaceValueFor(key, cachedPaint);
244            refBitmapsInShader(cachedPaint->getShader());
245        }
246
247        return cachedPaint;
248    }
249
250    inline const SkRegion* refRegion(const SkRegion* region) {
251        if (!region) {
252            return region;
253        }
254
255        const SkRegion* cachedRegion = mRegionMap.valueFor(region);
256        // TODO: Add generation ID to SkRegion
257        if (cachedRegion == nullptr) {
258            std::unique_ptr<const SkRegion> copy(new SkRegion(*region));
259            cachedRegion = copy.get();
260            mDisplayList->regions.push_back(std::move(copy));
261
262            // replaceValueFor() performs an add if the entry doesn't exist
263            mRegionMap.replaceValueFor(region, cachedRegion);
264        }
265
266        return cachedRegion;
267    }
268
269    inline const SkBitmap* refBitmap(const SkBitmap& bitmap) {
270        // Note that this assumes the bitmap is immutable. There are cases this won't handle
271        // correctly, such as creating the bitmap from scratch, drawing with it, changing its
272        // contents, and drawing again. The only fix would be to always copy it the first time,
273        // which doesn't seem worth the extra cycles for this unlikely case.
274        SkBitmap* localBitmap = new (alloc()) SkBitmap(bitmap);
275        alloc().autoDestroy(localBitmap);
276        mDisplayList->bitmapResources.push_back(localBitmap);
277        return localBitmap;
278    }
279
280    inline const Res_png_9patch* refPatch(const Res_png_9patch* patch) {
281        mDisplayList->patchResources.push_back(patch);
282        mResourceCache.incrementRefcount(patch);
283        return patch;
284    }
285
286    DefaultKeyedVector<uint32_t, const SkPaint*> mPaintMap;
287    DefaultKeyedVector<const SkPath*, const SkPath*> mPathMap;
288    DefaultKeyedVector<const SkRegion*, const SkRegion*> mRegionMap;
289
290    CanvasState mState;
291    std::unique_ptr<SkiaCanvasProxy> mSkiaCanvasProxy;
292    ResourceCache& mResourceCache;
293    DeferredBarrierType mDeferredBarrierType = DeferredBarrierType::None;
294    DisplayList* mDisplayList = nullptr;
295    bool mHighContrastText = false;
296    SkAutoTUnref<SkDrawFilter> mDrawFilter;
297    int mRestoreSaveCount = -1;
298}; // class RecordingCanvas
299
300}; // namespace uirenderer
301}; // namespace android
302
303#endif // ANDROID_HWUI_RECORDING_CANVAS_H
304