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