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