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