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