1 /*
2  * Copyright (C) 2014 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 "RenderNode.h"
18 
19 #include <SkPathOps.h>
20 #include <gui/TraceUtils.h>
21 #include <ui/FatVector.h>
22 
23 #include <algorithm>
24 #include <atomic>
25 #include <sstream>
26 #include <string>
27 
28 #include "DamageAccumulator.h"
29 #include "Debug.h"
30 #include "Properties.h"
31 #include "TreeInfo.h"
32 #include "VectorDrawable.h"
33 #include "private/hwui/WebViewFunctor.h"
34 #include "renderthread/CanvasContext.h"
35 
36 #ifdef __ANDROID__
37 #include "include/gpu/ganesh/SkImageGanesh.h"
38 #endif
39 #include "utils/ForceDark.h"
40 #include "utils/MathUtils.h"
41 #include "utils/StringUtils.h"
42 
43 namespace android {
44 namespace uirenderer {
45 
46 // Used for tree mutations that are purely destructive.
47 // Generic tree mutations should use MarkAndSweepObserver instead
48 class ImmediateRemoved : public TreeObserver {
49 public:
ImmediateRemoved(TreeInfo * info)50     explicit ImmediateRemoved(TreeInfo* info) : mTreeInfo(info) {}
51 
onMaybeRemovedFromTree(RenderNode * node)52     void onMaybeRemovedFromTree(RenderNode* node) override { node->onRemovedFromTree(mTreeInfo); }
53 
54 private:
55     TreeInfo* mTreeInfo;
56 };
57 
generateId()58 static int64_t generateId() {
59     static std::atomic<int64_t> sNextId{1};
60     return sNextId++;
61 }
62 
RenderNode()63 RenderNode::RenderNode()
64         : mUniqueId(generateId())
65         , mDirtyPropertyFields(0)
66         , mNeedsDisplayListSync(false)
67         , mDisplayList(nullptr)
68         , mStagingDisplayList(nullptr)
69         , mAnimatorManager(*this)
70         , mParentCount(0) {}
71 
~RenderNode()72 RenderNode::~RenderNode() {
73     ImmediateRemoved observer(nullptr);
74     deleteDisplayList(observer);
75     LOG_ALWAYS_FATAL_IF(hasLayer(), "layer missed detachment!");
76 }
77 
setStagingDisplayList(DisplayList && newData)78 void RenderNode::setStagingDisplayList(DisplayList&& newData) {
79     mValid = newData.isValid();
80     mNeedsDisplayListSync = true;
81     mStagingDisplayList = std::move(newData);
82 }
83 
discardStagingDisplayList()84 void RenderNode::discardStagingDisplayList() {
85     setStagingDisplayList(DisplayList());
86 }
87 
88 /**
89  * This function is a simplified version of replay(), where we simply retrieve and log the
90  * display list. This function should remain in sync with the replay() function.
91  */
output()92 void RenderNode::output() {
93     LogcatStream strout;
94     strout << "Root";
95     output(strout, 0);
96 }
97 
output(std::ostream & output,uint32_t level)98 void RenderNode::output(std::ostream& output, uint32_t level) {
99     output << "  (" << getName() << " " << this
100            << (MathUtils::isZero(properties().getAlpha()) ? ", zero alpha" : "")
101            << (properties().hasShadow() ? ", casting shadow" : "")
102            << (isRenderable() ? "" : ", empty")
103            << (properties().getProjectBackwards() ? ", projected" : "")
104            << (hasLayer() ? ", on HW Layer" : "") << ")" << std::endl;
105 
106     properties().debugOutputProperties(output, level + 1);
107 
108     mDisplayList.output(output, level);
109     output << std::string(level * 2, ' ') << "/RenderNode(" << getName() << " " << this << ")";
110     output << std::endl;
111 }
112 
visit(std::function<void (const RenderNode &)> func) const113 void RenderNode::visit(std::function<void(const RenderNode&)> func) const {
114     func(*this);
115     if (mDisplayList) {
116         mDisplayList.visit(func);
117     }
118 }
119 
getUsageSize()120 int RenderNode::getUsageSize() {
121     int size = sizeof(RenderNode);
122     size += mStagingDisplayList.getUsedSize();
123     size += mDisplayList.getUsedSize();
124     return size;
125 }
126 
getAllocatedSize()127 int RenderNode::getAllocatedSize() {
128     int size = sizeof(RenderNode);
129     size += mStagingDisplayList.getAllocatedSize();
130     size += mDisplayList.getAllocatedSize();
131     return size;
132 }
133 
134 
prepareTree(TreeInfo & info)135 void RenderNode::prepareTree(TreeInfo& info) {
136     ATRACE_CALL();
137     LOG_ALWAYS_FATAL_IF(!info.damageAccumulator, "DamageAccumulator missing");
138     MarkAndSweepRemoved observer(&info);
139 
140     const int before = info.disableForceDark;
141     prepareTreeImpl(observer, info, false);
142     LOG_ALWAYS_FATAL_IF(before != info.disableForceDark, "Mis-matched force dark");
143 }
144 
addAnimator(const sp<BaseRenderNodeAnimator> & animator)145 void RenderNode::addAnimator(const sp<BaseRenderNodeAnimator>& animator) {
146     mAnimatorManager.addAnimator(animator);
147 }
148 
removeAnimator(const sp<BaseRenderNodeAnimator> & animator)149 void RenderNode::removeAnimator(const sp<BaseRenderNodeAnimator>& animator) {
150     mAnimatorManager.removeAnimator(animator);
151 }
152 
damageSelf(TreeInfo & info)153 void RenderNode::damageSelf(TreeInfo& info) {
154     if (isRenderable()) {
155         mDamageGenerationId = info.damageGenerationId;
156         if (properties().getClipDamageToBounds()) {
157             info.damageAccumulator->dirty(0, 0, properties().getWidth(), properties().getHeight());
158         } else {
159             // Hope this is big enough?
160             // TODO: Get this from the display list ops or something
161             info.damageAccumulator->dirty(DIRTY_MIN, DIRTY_MIN, DIRTY_MAX, DIRTY_MAX);
162         }
163         if (!mIsTextureView) {
164             info.out.solelyTextureViewUpdates = false;
165         }
166     }
167 }
168 
prepareLayer(TreeInfo & info,uint32_t dirtyMask)169 void RenderNode::prepareLayer(TreeInfo& info, uint32_t dirtyMask) {
170     LayerType layerType = properties().effectiveLayerType();
171     if (CC_UNLIKELY(layerType == LayerType::RenderLayer)) {
172         // Damage applied so far needs to affect our parent, but does not require
173         // the layer to be updated. So we pop/push here to clear out the current
174         // damage and get a clean state for display list or children updates to
175         // affect, which will require the layer to be updated
176         info.damageAccumulator->popTransform();
177         info.damageAccumulator->pushTransform(this);
178         if (dirtyMask & DISPLAY_LIST) {
179             damageSelf(info);
180         }
181     }
182 }
183 
pushLayerUpdate(TreeInfo & info)184 void RenderNode::pushLayerUpdate(TreeInfo& info) {
185     LayerType layerType = properties().effectiveLayerType();
186     // If we are not a layer OR we cannot be rendered (eg, view was detached)
187     // we need to destroy any Layers we may have had previously
188     if (CC_LIKELY(layerType != LayerType::RenderLayer) || CC_UNLIKELY(!isRenderable()) ||
189         CC_UNLIKELY(properties().getWidth() == 0) || CC_UNLIKELY(properties().getHeight() == 0) ||
190         CC_UNLIKELY(!properties().fitsOnLayer())) {
191         if (CC_UNLIKELY(hasLayer())) {
192             this->setLayerSurface(nullptr);
193         }
194         return;
195     }
196 
197     if (info.canvasContext.createOrUpdateLayer(this, *info.damageAccumulator, info.errorHandler)) {
198         damageSelf(info);
199     }
200 
201     if (!hasLayer()) {
202         return;
203     }
204 
205     SkRect dirty;
206     info.damageAccumulator->peekAtDirty(&dirty);
207     info.layerUpdateQueue->enqueueLayerWithDamage(this, dirty);
208     if (!dirty.isEmpty()) {
209       mStretchMask.markDirty();
210     }
211 
212     // There might be prefetched layers that need to be accounted for.
213     // That might be us, so tell CanvasContext that this layer is in the
214     // tree and should not be destroyed.
215     info.canvasContext.markLayerInUse(this);
216 }
217 
218 /**
219  * Traverse down the the draw tree to prepare for a frame.
220  *
221  * MODE_FULL = UI Thread-driven (thus properties must be synced), otherwise RT driven
222  *
223  * While traversing down the tree, functorsNeedLayer flag is set to true if anything that uses the
224  * stencil buffer may be needed. Views that use a functor to draw will be forced onto a layer.
225  */
prepareTreeImpl(TreeObserver & observer,TreeInfo & info,bool functorsNeedLayer)226 void RenderNode::prepareTreeImpl(TreeObserver& observer, TreeInfo& info, bool functorsNeedLayer) {
227     if (mDamageGenerationId == info.damageGenerationId && mDamageGenerationId != 0) {
228         // We hit the same node a second time in the same tree. We don't know the minimal
229         // damage rect anymore, so just push the biggest we can onto our parent's transform
230         // We push directly onto parent in case we are clipped to bounds but have moved position.
231         info.damageAccumulator->dirty(DIRTY_MIN, DIRTY_MIN, DIRTY_MAX, DIRTY_MAX);
232     }
233     info.damageAccumulator->pushTransform(this);
234 
235     if (info.mode == TreeInfo::MODE_FULL) {
236         pushStagingPropertiesChanges(info);
237     }
238 
239     if (!mProperties.getAllowForceDark()) {
240         info.disableForceDark++;
241     }
242     if (!mProperties.layerProperties().getStretchEffect().isEmpty()) {
243         info.stretchEffectCount++;
244     }
245 
246     uint32_t animatorDirtyMask = 0;
247     if (CC_LIKELY(info.runAnimations)) {
248         animatorDirtyMask = mAnimatorManager.animate(info);
249     }
250 
251     bool willHaveFunctor = false;
252     if (info.mode == TreeInfo::MODE_FULL && mStagingDisplayList) {
253         willHaveFunctor = mStagingDisplayList.hasFunctor();
254     } else if (mDisplayList) {
255         willHaveFunctor = mDisplayList.hasFunctor();
256     }
257     bool childFunctorsNeedLayer =
258             mProperties.prepareForFunctorPresence(willHaveFunctor, functorsNeedLayer);
259 
260     if (CC_UNLIKELY(mPositionListener.get())) {
261         mPositionListener->onPositionUpdated(*this, info);
262     }
263 
264     prepareLayer(info, animatorDirtyMask);
265     if (info.mode == TreeInfo::MODE_FULL) {
266         pushStagingDisplayListChanges(observer, info);
267     }
268 
269     // always damageSelf when filtering backdrop content, or else the BackdropFilterDrawable will
270     // get a wrong snapshot of previous content.
271     if (mProperties.layerProperties().getBackdropImageFilter()) {
272         damageSelf(info);
273     }
274 
275     if (mDisplayList) {
276         info.out.hasFunctors |= mDisplayList.hasFunctor();
277         mHasHolePunches = mDisplayList.hasHolePunches();
278         bool isDirty = mDisplayList.prepareListAndChildren(
279                 observer, info, childFunctorsNeedLayer,
280                 [this](RenderNode* child, TreeObserver& observer, TreeInfo& info,
281                        bool functorsNeedLayer) {
282                     child->prepareTreeImpl(observer, info, functorsNeedLayer);
283                     mHasHolePunches |= child->hasHolePunches();
284                 });
285         if (isDirty) {
286             damageSelf(info);
287         }
288     } else {
289         mHasHolePunches = false;
290     }
291     pushLayerUpdate(info);
292 
293     if (!mProperties.getAllowForceDark()) {
294         info.disableForceDark--;
295     }
296     if (!mProperties.layerProperties().getStretchEffect().isEmpty()) {
297         info.stretchEffectCount--;
298     }
299     info.damageAccumulator->popTransform();
300 }
301 
syncProperties()302 void RenderNode::syncProperties() {
303     mProperties = mStagingProperties;
304 }
305 
pushStagingPropertiesChanges(TreeInfo & info)306 void RenderNode::pushStagingPropertiesChanges(TreeInfo& info) {
307     if (mPositionListenerDirty) {
308         mPositionListener = std::move(mStagingPositionListener);
309         mStagingPositionListener = nullptr;
310         mPositionListenerDirty = false;
311     }
312 
313     // Push the animators first so that setupStartValueIfNecessary() is called
314     // before properties() is trampled by stagingProperties(), as they are
315     // required by some animators.
316     if (CC_LIKELY(info.runAnimations)) {
317         mAnimatorManager.pushStaging();
318     }
319     if (mDirtyPropertyFields) {
320         mDirtyPropertyFields = 0;
321         damageSelf(info);
322         info.damageAccumulator->popTransform();
323         syncProperties();
324 
325         auto& layerProperties = mProperties.layerProperties();
326         const StretchEffect& stagingStretch = layerProperties.getStretchEffect();
327         if (stagingStretch.isEmpty()) {
328             mStretchMask.clear();
329         }
330 
331         if (layerProperties.getImageFilter() == nullptr) {
332             mSnapshotResult.snapshot = nullptr;
333             mTargetImageFilter = nullptr;
334         }
335 
336         // We could try to be clever and only re-damage if the matrix changed.
337         // However, we don't need to worry about that. The cost of over-damaging
338         // here is only going to be a single additional map rect of this node
339         // plus a rect join(). The parent's transform (and up) will only be
340         // performed once.
341         info.damageAccumulator->pushTransform(this);
342         damageSelf(info);
343     }
344 }
345 
updateSnapshotIfRequired(GrRecordingContext * context,const SkImageFilter * imageFilter,const SkIRect & clipBounds)346 std::optional<RenderNode::SnapshotResult> RenderNode::updateSnapshotIfRequired(
347     GrRecordingContext* context,
348     const SkImageFilter* imageFilter,
349     const SkIRect& clipBounds
350 ) {
351     auto* layerSurface = getLayerSurface();
352     if (layerSurface == nullptr) {
353         return std::nullopt;
354     }
355 
356     sk_sp<SkImage> snapshot = layerSurface->makeImageSnapshot();
357     const auto subset = SkIRect::MakeWH(properties().getWidth(),
358                                         properties().getHeight());
359     uint32_t layerSurfaceGenerationId = layerSurface->generationID();
360     // If we don't have an ImageFilter just return the snapshot
361     if (imageFilter == nullptr) {
362         mSnapshotResult.snapshot = snapshot;
363         mSnapshotResult.outSubset = subset;
364         mSnapshotResult.outOffset = SkIPoint::Make(0.0f, 0.0f);
365         mImageFilterClipBounds = clipBounds;
366         mTargetImageFilter = nullptr;
367         mTargetImageFilterLayerSurfaceGenerationId = 0;
368     } else if (mSnapshotResult.snapshot == nullptr || imageFilter != mTargetImageFilter.get() ||
369                mImageFilterClipBounds != clipBounds ||
370                mTargetImageFilterLayerSurfaceGenerationId != layerSurfaceGenerationId) {
371         // Otherwise create a new snapshot with the given filter and snapshot
372 #ifdef __ANDROID__
373         if (context) {
374             mSnapshotResult.snapshot = SkImages::MakeWithFilter(
375                     context, snapshot, imageFilter, subset, clipBounds, &mSnapshotResult.outSubset,
376                     &mSnapshotResult.outOffset);
377         } else
378 #endif
379         {
380             mSnapshotResult.snapshot = SkImages::MakeWithFilter(
381                     snapshot, imageFilter, subset, clipBounds, &mSnapshotResult.outSubset,
382                     &mSnapshotResult.outOffset);
383         }
384         mTargetImageFilter = sk_ref_sp(imageFilter);
385         mImageFilterClipBounds = clipBounds;
386         mTargetImageFilterLayerSurfaceGenerationId = layerSurfaceGenerationId;
387     }
388 
389     return mSnapshotResult;
390 }
391 
syncDisplayList(TreeObserver & observer,TreeInfo * info)392 void RenderNode::syncDisplayList(TreeObserver& observer, TreeInfo* info) {
393     // Make sure we inc first so that we don't fluctuate between 0 and 1,
394     // which would thrash the layer cache
395     if (mStagingDisplayList) {
396         mStagingDisplayList.updateChildren([](RenderNode* child) { child->incParentRefCount(); });
397     }
398     deleteDisplayList(observer, info);
399     mDisplayList = std::move(mStagingDisplayList);
400     if (mDisplayList) {
401         WebViewSyncData syncData{.applyForceDark = shouldEnableForceDark(info)};
402         mDisplayList.syncContents(syncData);
403         handleForceDark(info);
404     }
405 }
406 
shouldEnableForceDark(TreeInfo * info)407 inline bool RenderNode::shouldEnableForceDark(TreeInfo* info) {
408     return CC_UNLIKELY(
409             info &&
410             (!info->disableForceDark ||
411              info->forceDarkType == android::uirenderer::ForceDarkType::FORCE_INVERT_COLOR_DARK));
412 }
413 
handleForceDark(android::uirenderer::TreeInfo * info)414 void RenderNode::handleForceDark(android::uirenderer::TreeInfo *info) {
415     if (!shouldEnableForceDark(info)) {
416         return;
417     }
418     auto usage = usageHint();
419     FatVector<RenderNode*, 6> children;
420     mDisplayList.updateChildren([&children](RenderNode* node) {
421         children.push_back(node);
422     });
423     if (mDisplayList.hasText()) {
424         if (mDisplayList.hasFill()) {
425             // Handle a special case for custom views that draw both text and background in the
426             // same RenderNode, which would otherwise be altered to white-on-white text.
427             usage = UsageHint::Container;
428         } else {
429             usage = UsageHint::Foreground;
430         }
431     }
432     if (usage == UsageHint::Unknown) {
433         if (children.size() > 1) {
434             usage = UsageHint::Background;
435         } else if (children.size() == 1 &&
436                 children.front()->usageHint() !=
437                         UsageHint::Background) {
438             usage = UsageHint::Background;
439         }
440     }
441     if (children.size() > 1) {
442         // Crude overlap check
443         SkRect drawn = SkRect::MakeEmpty();
444         for (auto iter = children.rbegin(); iter != children.rend(); ++iter) {
445             const auto& child = *iter;
446             // We use stagingProperties here because we haven't yet sync'd the children
447             SkRect bounds = SkRect::MakeXYWH(child->stagingProperties().getX(), child->stagingProperties().getY(),
448                     child->stagingProperties().getWidth(), child->stagingProperties().getHeight());
449             if (bounds.contains(drawn)) {
450                 // This contains everything drawn after it, so make it a background
451                 child->setUsageHint(UsageHint::Background);
452             }
453             drawn.join(bounds);
454         }
455     }
456 
457     if (usage == UsageHint::Container) {
458         mDisplayList.applyColorTransform(ColorTransform::Invert);
459     } else {
460         mDisplayList.applyColorTransform(usage == UsageHint::Background ? ColorTransform::Dark
461                                                                         : ColorTransform::Light);
462     }
463 }
464 
pushStagingDisplayListChanges(TreeObserver & observer,TreeInfo & info)465 void RenderNode::pushStagingDisplayListChanges(TreeObserver& observer, TreeInfo& info) {
466     if (mNeedsDisplayListSync) {
467         mNeedsDisplayListSync = false;
468         // Damage with the old display list first then the new one to catch any
469         // changes in isRenderable or, in the future, bounds
470         damageSelf(info);
471         syncDisplayList(observer, &info);
472         damageSelf(info);
473     }
474 }
475 
deleteDisplayList(TreeObserver & observer,TreeInfo * info)476 void RenderNode::deleteDisplayList(TreeObserver& observer, TreeInfo* info) {
477     if (mDisplayList) {
478         mDisplayList.updateChildren(
479                 [&observer, info](RenderNode* child) { child->decParentRefCount(observer, info); });
480         mDisplayList.clear(this);
481     }
482 }
483 
destroyHardwareResources(TreeInfo * info)484 void RenderNode::destroyHardwareResources(TreeInfo* info) {
485     if (hasLayer()) {
486         this->setLayerSurface(nullptr);
487     }
488     discardStagingDisplayList();
489 
490     ImmediateRemoved observer(info);
491     deleteDisplayList(observer, info);
492 }
493 
destroyLayers()494 void RenderNode::destroyLayers() {
495     if (hasLayer()) {
496         this->setLayerSurface(nullptr);
497     }
498 
499     if (mDisplayList) {
500         mDisplayList.updateChildren([](RenderNode* child) { child->destroyLayers(); });
501     }
502 }
503 
decParentRefCount(TreeObserver & observer,TreeInfo * info)504 void RenderNode::decParentRefCount(TreeObserver& observer, TreeInfo* info) {
505     LOG_ALWAYS_FATAL_IF(!mParentCount, "already 0!");
506     mParentCount--;
507     if (!mParentCount) {
508         observer.onMaybeRemovedFromTree(this);
509         if (CC_UNLIKELY(mPositionListener.get())) {
510             mPositionListener->onPositionLost(*this, info);
511         }
512     }
513 }
514 
onRemovedFromTree(TreeInfo * info)515 void RenderNode::onRemovedFromTree(TreeInfo* info) {
516     if (Properties::enableWebViewOverlays && mDisplayList) {
517         mDisplayList.onRemovedFromTree();
518     }
519     destroyHardwareResources(info);
520 }
521 
clearRoot()522 void RenderNode::clearRoot() {
523     ImmediateRemoved observer(nullptr);
524     decParentRefCount(observer);
525 }
526 
527 /**
528  * Apply property-based transformations to input matrix
529  *
530  * If true3dTransform is set to true, the transform applied to the input matrix will use true 4x4
531  * matrix computation instead of the Skia 3x3 matrix + camera hackery.
532  */
applyViewPropertyTransforms(mat4 & matrix,bool true3dTransform) const533 void RenderNode::applyViewPropertyTransforms(mat4& matrix, bool true3dTransform) const {
534     if (properties().getLeft() != 0 || properties().getTop() != 0) {
535         matrix.translate(properties().getLeft(), properties().getTop());
536     }
537     if (properties().getStaticMatrix()) {
538         mat4 stat(*properties().getStaticMatrix());
539         matrix.multiply(stat);
540     } else if (properties().getAnimationMatrix()) {
541         mat4 anim(*properties().getAnimationMatrix());
542         matrix.multiply(anim);
543     }
544 
545     bool applyTranslationZ = true3dTransform && !MathUtils::isZero(properties().getZ());
546     if (properties().hasTransformMatrix() || applyTranslationZ) {
547         if (properties().isTransformTranslateOnly()) {
548             matrix.translate(properties().getTranslationX(), properties().getTranslationY(),
549                              true3dTransform ? properties().getZ() : 0.0f);
550         } else {
551             if (!true3dTransform) {
552                 matrix.multiply(*properties().getTransformMatrix());
553             } else {
554                 mat4 true3dMat;
555                 true3dMat.loadTranslate(properties().getPivotX() + properties().getTranslationX(),
556                                         properties().getPivotY() + properties().getTranslationY(),
557                                         properties().getZ());
558                 true3dMat.rotate(properties().getRotationX(), 1, 0, 0);
559                 true3dMat.rotate(properties().getRotationY(), 0, 1, 0);
560                 true3dMat.rotate(properties().getRotation(), 0, 0, 1);
561                 true3dMat.scale(properties().getScaleX(), properties().getScaleY(), 1);
562                 true3dMat.translate(-properties().getPivotX(), -properties().getPivotY());
563 
564                 matrix.multiply(true3dMat);
565             }
566         }
567     }
568 
569     if (Properties::getStretchEffectBehavior() == StretchEffectBehavior::UniformScale) {
570         const StretchEffect& stretch = properties().layerProperties().getStretchEffect();
571         if (!stretch.isEmpty()) {
572             matrix.multiply(
573                     stretch.makeLinearStretch(properties().getWidth(), properties().getHeight()));
574         }
575     }
576 }
577 
getClippedOutline(const SkRect & clipRect) const578 const SkPath* RenderNode::getClippedOutline(const SkRect& clipRect) const {
579     const SkPath* outlinePath = properties().getOutline().getPath();
580     const uint32_t outlineID = outlinePath->getGenerationID();
581 
582     if (outlineID != mClippedOutlineCache.outlineID || clipRect != mClippedOutlineCache.clipRect) {
583         // update the cache keys
584         mClippedOutlineCache.outlineID = outlineID;
585         mClippedOutlineCache.clipRect = clipRect;
586 
587         // update the cache value by recomputing a new path
588         SkPath clipPath;
589         clipPath.addRect(clipRect);
590         Op(*outlinePath, clipPath, kIntersect_SkPathOp, &mClippedOutlineCache.clippedOutline);
591     }
592     return &mClippedOutlineCache.clippedOutline;
593 }
594 
595 using StringBuffer = FatVector<char, 128>;
596 
597 template <typename... T>
598 // TODO:__printflike(2, 3)
599 // Doesn't work because the warning doesn't understand string_view and doesn't like that
600 // it's not a C-style variadic function.
format(StringBuffer & buffer,const std::string_view & format,T...args)601 static void format(StringBuffer& buffer, const std::string_view& format, T... args) {
602     buffer.resize(buffer.capacity());
603     while (1) {
604         int needed = snprintf(buffer.data(), buffer.size(),
605                 format.data(), std::forward<T>(args)...);
606         if (needed < 0) {
607             buffer[0] = '\0';
608             buffer.resize(1);
609             return;
610         }
611         if (needed < buffer.size()) {
612             buffer.resize(needed + 1);
613             return;
614         }
615         // If we're doing a heap alloc anyway might as well give it some slop
616         buffer.resize(needed + 100);
617     }
618 }
619 
markDrawStart(SkCanvas & canvas)620 void RenderNode::markDrawStart(SkCanvas& canvas) {
621     StringBuffer buffer;
622     format(buffer, "RenderNode(id=%" PRId64 ", name='%s')", uniqueId(), getName());
623     canvas.drawAnnotation(SkRect::MakeWH(getWidth(), getHeight()), buffer.data(), nullptr);
624 }
625 
markDrawEnd(SkCanvas & canvas)626 void RenderNode::markDrawEnd(SkCanvas& canvas) {
627     StringBuffer buffer;
628     format(buffer, "/RenderNode(id=%" PRId64 ", name='%s')", uniqueId(), getName());
629     canvas.drawAnnotation(SkRect::MakeWH(getWidth(), getHeight()), buffer.data(), nullptr);
630 }
631 
632 } /* namespace uirenderer */
633 } /* namespace android */
634