1 /*
2  * Copyright (C) 2016 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 #include "RenderNodeDrawable.h"
18 #include <SkPaintFilterCanvas.h>
19 #include "RenderNode.h"
20 #include "SkiaDisplayList.h"
21 #include "SkiaPipeline.h"
22 #include "utils/TraceUtils.h"
23 
24 #include <optional>
25 
26 namespace android {
27 namespace uirenderer {
28 namespace skiapipeline {
29 
RenderNodeDrawable(RenderNode * node,SkCanvas * canvas,bool composeLayer,bool inReorderingSection)30 RenderNodeDrawable::RenderNodeDrawable(RenderNode* node, SkCanvas* canvas, bool composeLayer,
31                                        bool inReorderingSection)
32         : mRenderNode(node)
33         , mRecordedTransform(canvas->getTotalMatrix())
34         , mComposeLayer(composeLayer)
35         , mInReorderingSection(inReorderingSection) {}
36 
~RenderNodeDrawable()37 RenderNodeDrawable::~RenderNodeDrawable() {
38     // Just here to move the destructor into the cpp file where we can access RenderNode.
39 
40     // TODO: Detangle the header nightmare.
41 }
42 
drawBackwardsProjectedNodes(SkCanvas * canvas,const SkiaDisplayList & displayList,int nestLevel)43 void RenderNodeDrawable::drawBackwardsProjectedNodes(SkCanvas* canvas,
44                                                      const SkiaDisplayList& displayList,
45                                                      int nestLevel) {
46     LOG_ALWAYS_FATAL_IF(0 == nestLevel && !displayList.mProjectionReceiver);
47     for (auto& child : displayList.mChildNodes) {
48         const RenderProperties& childProperties = child.getNodeProperties();
49 
50         // immediate children cannot be projected on their parent
51         if (childProperties.getProjectBackwards() && nestLevel > 0) {
52             SkAutoCanvasRestore acr2(canvas, true);
53             // Apply recorded matrix, which is a total matrix saved at recording time to avoid
54             // replaying all DL commands.
55             canvas->concat(child.getRecordedMatrix());
56             child.drawContent(canvas);
57         }
58 
59         // skip walking sub-nodes if current display list contains a receiver with exception of
60         // level 0, which is a known receiver
61         if (0 == nestLevel || !displayList.containsProjectionReceiver()) {
62             SkAutoCanvasRestore acr(canvas, true);
63             SkMatrix nodeMatrix;
64             mat4 hwuiMatrix(child.getRecordedMatrix());
65             auto childNode = child.getRenderNode();
66             childNode->applyViewPropertyTransforms(hwuiMatrix);
67             hwuiMatrix.copyTo(nodeMatrix);
68             canvas->concat(nodeMatrix);
69             SkiaDisplayList* childDisplayList = static_cast<SkiaDisplayList*>(
70                     (const_cast<DisplayList*>(childNode->getDisplayList())));
71             if (childDisplayList) {
72                 drawBackwardsProjectedNodes(canvas, *childDisplayList, nestLevel + 1);
73             }
74         }
75     }
76 }
77 
clipOutline(const Outline & outline,SkCanvas * canvas,const SkRect * pendingClip)78 static void clipOutline(const Outline& outline, SkCanvas* canvas, const SkRect* pendingClip) {
79     Rect possibleRect;
80     float radius;
81 
82     /* To match the existing HWUI behavior we only supports rectangles or
83      * rounded rectangles; passing in a more complicated outline fails silently.
84      */
85     if (!outline.getAsRoundRect(&possibleRect, &radius)) {
86         if (pendingClip) {
87             canvas->clipRect(*pendingClip);
88         }
89         return;
90     }
91 
92     SkRect rect = possibleRect.toSkRect();
93     if (radius != 0.0f) {
94         if (pendingClip && !pendingClip->contains(rect)) {
95             canvas->clipRect(*pendingClip);
96         }
97         canvas->clipRRect(SkRRect::MakeRectXY(rect, radius, radius), SkClipOp::kIntersect, true);
98     } else {
99         if (pendingClip) {
100             (void)rect.intersect(*pendingClip);
101         }
102         canvas->clipRect(rect);
103     }
104 }
105 
getNodeProperties() const106 const RenderProperties& RenderNodeDrawable::getNodeProperties() const {
107     return mRenderNode->properties();
108 }
109 
onDraw(SkCanvas * canvas)110 void RenderNodeDrawable::onDraw(SkCanvas* canvas) {
111     // negative and positive Z order are drawn out of order, if this render node drawable is in
112     // a reordering section
113     if ((!mInReorderingSection) || MathUtils::isZero(mRenderNode->properties().getZ())) {
114         this->forceDraw(canvas);
115     }
116 }
117 
118 class MarkDraw {
119 public:
MarkDraw(SkCanvas & canvas,RenderNode & node)120     explicit MarkDraw(SkCanvas& canvas, RenderNode& node) : mCanvas(canvas), mNode(node) {
121         if (CC_UNLIKELY(Properties::skpCaptureEnabled)) {
122             mNode.markDrawStart(mCanvas);
123         }
124     }
~MarkDraw()125     ~MarkDraw() {
126         if (CC_UNLIKELY(Properties::skpCaptureEnabled)) {
127             mNode.markDrawEnd(mCanvas);
128         }
129     }
130 
131 private:
132     SkCanvas& mCanvas;
133     RenderNode& mNode;
134 };
135 
forceDraw(SkCanvas * canvas)136 void RenderNodeDrawable::forceDraw(SkCanvas* canvas) {
137     RenderNode* renderNode = mRenderNode.get();
138     MarkDraw _marker{*canvas, *renderNode};
139 
140     // We only respect the nothingToDraw check when we are composing a layer. This
141     // ensures that we paint the layer even if it is not currently visible in the
142     // event that the properties change and it becomes visible.
143     if ((mProjectedDisplayList == nullptr && !renderNode->isRenderable()) ||
144         (renderNode->nothingToDraw() && mComposeLayer)) {
145         return;
146     }
147 
148     SkiaDisplayList* displayList = (SkiaDisplayList*)renderNode->getDisplayList();
149 
150     SkAutoCanvasRestore acr(canvas, true);
151     const RenderProperties& properties = this->getNodeProperties();
152     // pass this outline to the children that may clip backward projected nodes
153     displayList->mProjectedOutline =
154             displayList->containsProjectionReceiver() ? &properties.getOutline() : nullptr;
155     if (!properties.getProjectBackwards()) {
156         drawContent(canvas);
157         if (mProjectedDisplayList) {
158             acr.restore();  // draw projected children using parent matrix
159             LOG_ALWAYS_FATAL_IF(!mProjectedDisplayList->mProjectedOutline);
160             const bool shouldClip = mProjectedDisplayList->mProjectedOutline->getPath();
161             SkAutoCanvasRestore acr2(canvas, shouldClip);
162             canvas->setMatrix(mProjectedDisplayList->mParentMatrix);
163             if (shouldClip) {
164                 canvas->clipPath(*mProjectedDisplayList->mProjectedOutline->getPath());
165             }
166             drawBackwardsProjectedNodes(canvas, *mProjectedDisplayList);
167         }
168     }
169     displayList->mProjectedOutline = nullptr;
170 }
171 
layerNeedsPaint(const LayerProperties & properties,float alphaMultiplier,SkPaint * paint)172 static bool layerNeedsPaint(const LayerProperties& properties, float alphaMultiplier,
173                             SkPaint* paint) {
174     paint->setFilterQuality(kLow_SkFilterQuality);
175     if (alphaMultiplier < 1.0f || properties.alpha() < 255 ||
176         properties.xferMode() != SkBlendMode::kSrcOver || properties.getColorFilter() != nullptr) {
177         paint->setAlpha(properties.alpha() * alphaMultiplier);
178         paint->setBlendMode(properties.xferMode());
179         paint->setColorFilter(sk_ref_sp(properties.getColorFilter()));
180         return true;
181     }
182     return false;
183 }
184 
185 class AlphaFilterCanvas : public SkPaintFilterCanvas {
186 public:
AlphaFilterCanvas(SkCanvas * canvas,float alpha)187     AlphaFilterCanvas(SkCanvas* canvas, float alpha) : SkPaintFilterCanvas(canvas), mAlpha(alpha) {}
188 
189 protected:
onFilter(SkTCopyOnFirstWrite<SkPaint> * paint,Type t) const190     bool onFilter(SkTCopyOnFirstWrite<SkPaint>* paint, Type t) const override {
191         std::optional<SkPaint> defaultPaint;
192         if (!*paint) {
193             paint->init(defaultPaint.emplace());
194         }
195         paint->writable()->setAlpha((uint8_t)(*paint)->getAlpha() * mAlpha);
196         return true;
197     }
onDrawDrawable(SkDrawable * drawable,const SkMatrix * matrix)198     void onDrawDrawable(SkDrawable* drawable, const SkMatrix* matrix) override {
199         // We unroll the drawable using "this" canvas, so that draw calls contained inside will
200         // get their alpha applied. THe default SkPaintFilterCanvas::onDrawDrawable does not unroll.
201         drawable->draw(this, matrix);
202     }
203 
204 private:
205     float mAlpha;
206 };
207 
drawContent(SkCanvas * canvas) const208 void RenderNodeDrawable::drawContent(SkCanvas* canvas) const {
209     RenderNode* renderNode = mRenderNode.get();
210     float alphaMultiplier = 1.0f;
211     const RenderProperties& properties = renderNode->properties();
212 
213     // If we are drawing the contents of layer, we don't want to apply any of
214     // the RenderNode's properties during this pass. Those will all be applied
215     // when the layer is composited.
216     if (mComposeLayer) {
217         setViewProperties(properties, canvas, &alphaMultiplier);
218     }
219     SkiaDisplayList* displayList = (SkiaDisplayList*)mRenderNode->getDisplayList();
220     displayList->mParentMatrix = canvas->getTotalMatrix();
221 
222     // TODO should we let the bound of the drawable do this for us?
223     const SkRect bounds = SkRect::MakeWH(properties.getWidth(), properties.getHeight());
224     bool quickRejected = properties.getClipToBounds() && canvas->quickReject(bounds);
225     if (!quickRejected) {
226         SkiaDisplayList* displayList = (SkiaDisplayList*)renderNode->getDisplayList();
227         const LayerProperties& layerProperties = properties.layerProperties();
228         // composing a hardware layer
229         if (renderNode->getLayerSurface() && mComposeLayer) {
230             SkASSERT(properties.effectiveLayerType() == LayerType::RenderLayer);
231             SkPaint paint;
232             layerNeedsPaint(layerProperties, alphaMultiplier, &paint);
233 
234             // surfaces for layers are created on LAYER_SIZE boundaries (which are >= layer size) so
235             // we need to restrict the portion of the surface drawn to the size of the renderNode.
236             SkASSERT(renderNode->getLayerSurface()->width() >= bounds.width());
237             SkASSERT(renderNode->getLayerSurface()->height() >= bounds.height());
238             canvas->drawImageRect(renderNode->getLayerSurface()->makeImageSnapshot().get(), bounds,
239                                   bounds, &paint);
240 
241             if (!renderNode->getSkiaLayer()->hasRenderedSinceRepaint) {
242                 renderNode->getSkiaLayer()->hasRenderedSinceRepaint = true;
243                 if (CC_UNLIKELY(Properties::debugLayersUpdates)) {
244                     SkPaint layerPaint;
245                     layerPaint.setColor(0x7f00ff00);
246                     canvas->drawRect(bounds, layerPaint);
247                 } else if (CC_UNLIKELY(Properties::debugOverdraw)) {
248                     // Render transparent rect to increment overdraw for repaint area.
249                     // This can be "else if" because flashing green on layer updates
250                     // will also increment the overdraw if it happens to be turned on.
251                     SkPaint transparentPaint;
252                     transparentPaint.setColor(SK_ColorTRANSPARENT);
253                     canvas->drawRect(bounds, transparentPaint);
254                 }
255             }
256         } else {
257             if (alphaMultiplier < 1.0f) {
258                 // Non-layer draw for a view with getHasOverlappingRendering=false, will apply
259                 // the alpha to the paint of each nested draw.
260                 AlphaFilterCanvas alphaCanvas(canvas, alphaMultiplier);
261                 displayList->draw(&alphaCanvas);
262             } else {
263                 displayList->draw(canvas);
264             }
265         }
266     }
267 }
268 
setViewProperties(const RenderProperties & properties,SkCanvas * canvas,float * alphaMultiplier)269 void RenderNodeDrawable::setViewProperties(const RenderProperties& properties, SkCanvas* canvas,
270                                            float* alphaMultiplier) {
271     if (properties.getLeft() != 0 || properties.getTop() != 0) {
272         canvas->translate(properties.getLeft(), properties.getTop());
273     }
274     if (properties.getStaticMatrix()) {
275         canvas->concat(*properties.getStaticMatrix());
276     } else if (properties.getAnimationMatrix()) {
277         canvas->concat(*properties.getAnimationMatrix());
278     }
279     if (properties.hasTransformMatrix()) {
280         if (properties.isTransformTranslateOnly()) {
281             canvas->translate(properties.getTranslationX(), properties.getTranslationY());
282         } else {
283             canvas->concat(*properties.getTransformMatrix());
284         }
285     }
286     const bool isLayer = properties.effectiveLayerType() != LayerType::None;
287     int clipFlags = properties.getClippingFlags();
288     if (properties.getAlpha() < 1) {
289         if (isLayer) {
290             clipFlags &= ~CLIP_TO_BOUNDS;  // bounds clipping done by layer
291         }
292         if (CC_LIKELY(isLayer || !properties.getHasOverlappingRendering())) {
293             *alphaMultiplier = properties.getAlpha();
294         } else {
295             // savelayer needed to create an offscreen buffer
296             Rect layerBounds(0, 0, properties.getWidth(), properties.getHeight());
297             if (clipFlags) {
298                 properties.getClippingRectForFlags(clipFlags, &layerBounds);
299                 clipFlags = 0;  // all clipping done by savelayer
300             }
301             SkRect bounds = SkRect::MakeLTRB(layerBounds.left, layerBounds.top, layerBounds.right,
302                                              layerBounds.bottom);
303             canvas->saveLayerAlpha(&bounds, (int)(properties.getAlpha() * 255));
304         }
305 
306         if (CC_UNLIKELY(ATRACE_ENABLED() && properties.promotedToLayer())) {
307             // pretend alpha always causes savelayer to warn about
308             // performance problem affecting old versions
309             ATRACE_FORMAT("alpha caused saveLayer %dx%d", properties.getWidth(),
310                           properties.getHeight());
311         }
312     }
313 
314     const SkRect* pendingClip = nullptr;
315     SkRect clipRect;
316 
317     if (clipFlags) {
318         Rect tmpRect;
319         properties.getClippingRectForFlags(clipFlags, &tmpRect);
320         clipRect = tmpRect.toSkRect();
321         pendingClip = &clipRect;
322     }
323 
324     if (properties.getRevealClip().willClip()) {
325         canvas->clipPath(*properties.getRevealClip().getPath(), SkClipOp::kIntersect, true);
326     } else if (properties.getOutline().willClip()) {
327         clipOutline(properties.getOutline(), canvas, pendingClip);
328         pendingClip = nullptr;
329     }
330 
331     if (pendingClip) {
332         canvas->clipRect(*pendingClip);
333     }
334 }
335 
336 }  // namespace skiapipeline
337 }  // namespace uirenderer
338 }  // namespace android
339