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