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