xref: /aosp_15_r20/frameworks/base/libs/hwui/RenderNode.cpp (revision d57664e9bc4670b3ecf6748a746a57c557b6bc9e)
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 
isForceInvertDark(TreeInfo & info)407 inline bool RenderNode::isForceInvertDark(TreeInfo& info) {
408     return CC_UNLIKELY(
409              info.forceDarkType == android::uirenderer::ForceDarkType::FORCE_INVERT_COLOR_DARK);
410 }
411 
shouldEnableForceDark(TreeInfo * info)412 inline bool RenderNode::shouldEnableForceDark(TreeInfo* info) {
413     return CC_UNLIKELY(
414             info &&
415             (!info->disableForceDark || isForceInvertDark(*info)));
416 }
417 
418 
419 
handleForceDark(android::uirenderer::TreeInfo * info)420 void RenderNode::handleForceDark(android::uirenderer::TreeInfo *info) {
421     if (!shouldEnableForceDark(info)) {
422         return;
423     }
424     auto usage = usageHint();
425     FatVector<RenderNode*, 6> children;
426     mDisplayList.updateChildren([&children](RenderNode* node) {
427         children.push_back(node);
428     });
429     if (mDisplayList.hasText()) {
430         if (isForceInvertDark(*info) && mDisplayList.hasFill()) {
431             // Handle a special case for custom views that draw both text and background in the
432             // same RenderNode, which would otherwise be altered to white-on-white text.
433             usage = UsageHint::Container;
434         } else {
435             usage = UsageHint::Foreground;
436         }
437     }
438     if (usage == UsageHint::Unknown) {
439         if (children.size() > 1) {
440             usage = UsageHint::Background;
441         } else if (children.size() == 1 &&
442                 children.front()->usageHint() !=
443                         UsageHint::Background) {
444             usage = UsageHint::Background;
445         }
446     }
447     if (children.size() > 1) {
448         // Crude overlap check
449         SkRect drawn = SkRect::MakeEmpty();
450         for (auto iter = children.rbegin(); iter != children.rend(); ++iter) {
451             const auto& child = *iter;
452             // We use stagingProperties here because we haven't yet sync'd the children
453             SkRect bounds = SkRect::MakeXYWH(child->stagingProperties().getX(), child->stagingProperties().getY(),
454                     child->stagingProperties().getWidth(), child->stagingProperties().getHeight());
455             if (bounds.contains(drawn)) {
456                 // This contains everything drawn after it, so make it a background
457                 child->setUsageHint(UsageHint::Background);
458             }
459             drawn.join(bounds);
460         }
461     }
462 
463     if (usage == UsageHint::Container) {
464         mDisplayList.applyColorTransform(ColorTransform::Invert);
465     } else {
466         mDisplayList.applyColorTransform(usage == UsageHint::Background ? ColorTransform::Dark
467                                                                         : ColorTransform::Light);
468     }
469 }
470 
pushStagingDisplayListChanges(TreeObserver & observer,TreeInfo & info)471 void RenderNode::pushStagingDisplayListChanges(TreeObserver& observer, TreeInfo& info) {
472     if (mNeedsDisplayListSync) {
473         mNeedsDisplayListSync = false;
474         // Damage with the old display list first then the new one to catch any
475         // changes in isRenderable or, in the future, bounds
476         damageSelf(info);
477         syncDisplayList(observer, &info);
478         damageSelf(info);
479     }
480 }
481 
deleteDisplayList(TreeObserver & observer,TreeInfo * info)482 void RenderNode::deleteDisplayList(TreeObserver& observer, TreeInfo* info) {
483     if (mDisplayList) {
484         mDisplayList.updateChildren(
485                 [&observer, info](RenderNode* child) { child->decParentRefCount(observer, info); });
486         mDisplayList.clear(this);
487     }
488 }
489 
destroyHardwareResources(TreeInfo * info)490 void RenderNode::destroyHardwareResources(TreeInfo* info) {
491     if (hasLayer()) {
492         this->setLayerSurface(nullptr);
493     }
494     discardStagingDisplayList();
495 
496     ImmediateRemoved observer(info);
497     deleteDisplayList(observer, info);
498 }
499 
destroyLayers()500 void RenderNode::destroyLayers() {
501     if (hasLayer()) {
502         this->setLayerSurface(nullptr);
503     }
504 
505     if (mDisplayList) {
506         mDisplayList.updateChildren([](RenderNode* child) { child->destroyLayers(); });
507     }
508 }
509 
decParentRefCount(TreeObserver & observer,TreeInfo * info)510 void RenderNode::decParentRefCount(TreeObserver& observer, TreeInfo* info) {
511     LOG_ALWAYS_FATAL_IF(!mParentCount, "already 0!");
512     mParentCount--;
513     if (!mParentCount) {
514         observer.onMaybeRemovedFromTree(this);
515         if (CC_UNLIKELY(mPositionListener.get())) {
516             mPositionListener->onPositionLost(*this, info);
517         }
518     }
519 }
520 
onRemovedFromTree(TreeInfo * info)521 void RenderNode::onRemovedFromTree(TreeInfo* info) {
522     if (Properties::enableWebViewOverlays && mDisplayList) {
523         mDisplayList.onRemovedFromTree();
524     }
525     destroyHardwareResources(info);
526 }
527 
clearRoot()528 void RenderNode::clearRoot() {
529     ImmediateRemoved observer(nullptr);
530     decParentRefCount(observer);
531 }
532 
533 /**
534  * Apply property-based transformations to input matrix
535  *
536  * If true3dTransform is set to true, the transform applied to the input matrix will use true 4x4
537  * matrix computation instead of the Skia 3x3 matrix + camera hackery.
538  */
applyViewPropertyTransforms(mat4 & matrix,bool true3dTransform) const539 void RenderNode::applyViewPropertyTransforms(mat4& matrix, bool true3dTransform) const {
540     if (properties().getLeft() != 0 || properties().getTop() != 0) {
541         matrix.translate(properties().getLeft(), properties().getTop());
542     }
543     if (properties().getStaticMatrix()) {
544         mat4 stat(*properties().getStaticMatrix());
545         matrix.multiply(stat);
546     } else if (properties().getAnimationMatrix()) {
547         mat4 anim(*properties().getAnimationMatrix());
548         matrix.multiply(anim);
549     }
550 
551     bool applyTranslationZ = true3dTransform && !MathUtils::isZero(properties().getZ());
552     if (properties().hasTransformMatrix() || applyTranslationZ) {
553         if (properties().isTransformTranslateOnly()) {
554             matrix.translate(properties().getTranslationX(), properties().getTranslationY(),
555                              true3dTransform ? properties().getZ() : 0.0f);
556         } else {
557             if (!true3dTransform) {
558                 matrix.multiply(*properties().getTransformMatrix());
559             } else {
560                 mat4 true3dMat;
561                 true3dMat.loadTranslate(properties().getPivotX() + properties().getTranslationX(),
562                                         properties().getPivotY() + properties().getTranslationY(),
563                                         properties().getZ());
564                 true3dMat.rotate(properties().getRotationX(), 1, 0, 0);
565                 true3dMat.rotate(properties().getRotationY(), 0, 1, 0);
566                 true3dMat.rotate(properties().getRotation(), 0, 0, 1);
567                 true3dMat.scale(properties().getScaleX(), properties().getScaleY(), 1);
568                 true3dMat.translate(-properties().getPivotX(), -properties().getPivotY());
569 
570                 matrix.multiply(true3dMat);
571             }
572         }
573     }
574 
575     if (Properties::getStretchEffectBehavior() == StretchEffectBehavior::UniformScale) {
576         const StretchEffect& stretch = properties().layerProperties().getStretchEffect();
577         if (!stretch.isEmpty()) {
578             matrix.multiply(
579                     stretch.makeLinearStretch(properties().getWidth(), properties().getHeight()));
580         }
581     }
582 }
583 
getClippedOutline(const SkRect & clipRect) const584 const SkPath* RenderNode::getClippedOutline(const SkRect& clipRect) const {
585     const SkPath* outlinePath = properties().getOutline().getPath();
586     const uint32_t outlineID = outlinePath->getGenerationID();
587 
588     if (outlineID != mClippedOutlineCache.outlineID || clipRect != mClippedOutlineCache.clipRect) {
589         // update the cache keys
590         mClippedOutlineCache.outlineID = outlineID;
591         mClippedOutlineCache.clipRect = clipRect;
592 
593         // update the cache value by recomputing a new path
594         SkPath clipPath;
595         clipPath.addRect(clipRect);
596         Op(*outlinePath, clipPath, kIntersect_SkPathOp, &mClippedOutlineCache.clippedOutline);
597     }
598     return &mClippedOutlineCache.clippedOutline;
599 }
600 
601 using StringBuffer = FatVector<char, 128>;
602 
603 template <typename... T>
604 // TODO:__printflike(2, 3)
605 // Doesn't work because the warning doesn't understand string_view and doesn't like that
606 // it's not a C-style variadic function.
format(StringBuffer & buffer,const std::string_view & format,T...args)607 static void format(StringBuffer& buffer, const std::string_view& format, T... args) {
608     buffer.resize(buffer.capacity());
609     while (1) {
610         int needed = snprintf(buffer.data(), buffer.size(),
611                 format.data(), std::forward<T>(args)...);
612         if (needed < 0) {
613             buffer[0] = '\0';
614             buffer.resize(1);
615             return;
616         }
617         if (needed < buffer.size()) {
618             buffer.resize(needed + 1);
619             return;
620         }
621         // If we're doing a heap alloc anyway might as well give it some slop
622         buffer.resize(needed + 100);
623     }
624 }
625 
markDrawStart(SkCanvas & canvas)626 void RenderNode::markDrawStart(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 
markDrawEnd(SkCanvas & canvas)632 void RenderNode::markDrawEnd(SkCanvas& canvas) {
633     StringBuffer buffer;
634     format(buffer, "/RenderNode(id=%" PRId64 ", name='%s')", uniqueId(), getName());
635     canvas.drawAnnotation(SkRect::MakeWH(getWidth(), getHeight()), buffer.data(), nullptr);
636 }
637 
638 } /* namespace uirenderer */
639 } /* namespace android */
640