1 /*
2  * Copyright (C) 2007 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 // TODO(b/129481165): remove the #pragma below and fix conversion issues
18 #pragma clang diagnostic push
19 #pragma clang diagnostic ignored "-Wconversion"
20 
21 //#define LOG_NDEBUG 0
22 #undef LOG_TAG
23 #define LOG_TAG "Layer"
24 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
25 
26 #include "Layer.h"
27 
28 #include <android-base/stringprintf.h>
29 #include <android/native_window.h>
30 #include <binder/IPCThreadState.h>
31 #include <compositionengine/Display.h>
32 #include <compositionengine/LayerFECompositionState.h>
33 #include <compositionengine/OutputLayer.h>
34 #include <compositionengine/impl/OutputLayerCompositionState.h>
35 #include <cutils/compiler.h>
36 #include <cutils/native_handle.h>
37 #include <cutils/properties.h>
38 #include <gui/BufferItem.h>
39 #include <gui/LayerDebugInfo.h>
40 #include <gui/Surface.h>
41 #include <math.h>
42 #include <renderengine/RenderEngine.h>
43 #include <stdint.h>
44 #include <stdlib.h>
45 #include <sys/types.h>
46 #include <ui/DebugUtils.h>
47 #include <ui/GraphicBuffer.h>
48 #include <ui/PixelFormat.h>
49 #include <utils/Errors.h>
50 #include <utils/Log.h>
51 #include <utils/NativeHandle.h>
52 #include <utils/StopWatch.h>
53 #include <utils/Trace.h>
54 
55 #include <algorithm>
56 #include <mutex>
57 #include <sstream>
58 
59 #include "BufferLayer.h"
60 #include "Colorizer.h"
61 #include "DisplayDevice.h"
62 #include "DisplayHardware/HWComposer.h"
63 #include "EffectLayer.h"
64 #include "FrameTracer/FrameTracer.h"
65 #include "LayerProtoHelper.h"
66 #include "LayerRejecter.h"
67 #include "MonitoredProducer.h"
68 #include "SurfaceFlinger.h"
69 #include "TimeStats/TimeStats.h"
70 
71 #define DEBUG_RESIZE 0
72 
73 namespace android {
74 
75 using base::StringAppendF;
76 
77 std::atomic<int32_t> Layer::sSequence{1};
78 
Layer(const LayerCreationArgs & args)79 Layer::Layer(const LayerCreationArgs& args)
80       : mFlinger(args.flinger),
81         mName(args.name),
82         mClientRef(args.client),
83         mWindowType(args.metadata.getInt32(METADATA_WINDOW_TYPE, 0)) {
84     uint32_t layerFlags = 0;
85     if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
86     if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
87     if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
88 
89     mCurrentState.active_legacy.w = args.w;
90     mCurrentState.active_legacy.h = args.h;
91     mCurrentState.flags = layerFlags;
92     mCurrentState.active_legacy.transform.set(0, 0);
93     mCurrentState.crop_legacy.makeInvalid();
94     mCurrentState.requestedCrop_legacy = mCurrentState.crop_legacy;
95     mCurrentState.z = 0;
96     mCurrentState.color.a = 1.0f;
97     mCurrentState.layerStack = 0;
98     mCurrentState.sequence = 0;
99     mCurrentState.requested_legacy = mCurrentState.active_legacy;
100     mCurrentState.active.w = UINT32_MAX;
101     mCurrentState.active.h = UINT32_MAX;
102     mCurrentState.active.transform.set(0, 0);
103     mCurrentState.frameNumber = 0;
104     mCurrentState.transform = 0;
105     mCurrentState.transformToDisplayInverse = false;
106     mCurrentState.crop.makeInvalid();
107     mCurrentState.acquireFence = new Fence(-1);
108     mCurrentState.dataspace = ui::Dataspace::UNKNOWN;
109     mCurrentState.hdrMetadata.validTypes = 0;
110     mCurrentState.surfaceDamageRegion = Region::INVALID_REGION;
111     mCurrentState.cornerRadius = 0.0f;
112     mCurrentState.backgroundBlurRadius = 0;
113     mCurrentState.api = -1;
114     mCurrentState.hasColorTransform = false;
115     mCurrentState.colorSpaceAgnostic = false;
116     mCurrentState.frameRateSelectionPriority = PRIORITY_UNSET;
117     mCurrentState.metadata = args.metadata;
118     mCurrentState.shadowRadius = 0.f;
119     mCurrentState.treeHasFrameRateVote = false;
120     mCurrentState.fixedTransformHint = ui::Transform::ROT_INVALID;
121 
122     if (args.flags & ISurfaceComposerClient::eNoColorFill) {
123         // Set an invalid color so there is no color fill.
124         mCurrentState.color.r = -1.0_hf;
125         mCurrentState.color.g = -1.0_hf;
126         mCurrentState.color.b = -1.0_hf;
127     }
128 
129     // drawing state & current state are identical
130     mDrawingState = mCurrentState;
131 
132     CompositorTiming compositorTiming;
133     args.flinger->getCompositorTiming(&compositorTiming);
134     mFrameEventHistory.initializeCompositorTiming(compositorTiming);
135     mFrameTracker.setDisplayRefreshPeriod(compositorTiming.interval);
136 
137     mCallingPid = args.callingPid;
138     mCallingUid = args.callingUid;
139 }
140 
onFirstRef()141 void Layer::onFirstRef() {
142     mFlinger->onLayerFirstRef(this);
143 }
144 
~Layer()145 Layer::~Layer() {
146     sp<Client> c(mClientRef.promote());
147     if (c != 0) {
148         c->detachLayer(this);
149     }
150 
151     mFrameTracker.logAndResetStats(mName);
152     mFlinger->onLayerDestroyed(this);
153 }
154 
LayerCreationArgs(SurfaceFlinger * flinger,sp<Client> client,std::string name,uint32_t w,uint32_t h,uint32_t flags,LayerMetadata metadata)155 LayerCreationArgs::LayerCreationArgs(SurfaceFlinger* flinger, sp<Client> client, std::string name,
156                                      uint32_t w, uint32_t h, uint32_t flags, LayerMetadata metadata)
157       : flinger(flinger),
158         client(std::move(client)),
159         name(std::move(name)),
160         w(w),
161         h(h),
162         flags(flags),
163         metadata(std::move(metadata)) {
164     IPCThreadState* ipc = IPCThreadState::self();
165     callingPid = ipc->getCallingPid();
166     callingUid = ipc->getCallingUid();
167 }
168 
169 // ---------------------------------------------------------------------------
170 // callbacks
171 // ---------------------------------------------------------------------------
172 
173 /*
174  * onLayerDisplayed is only meaningful for BufferLayer, but, is called through
175  * Layer.  So, the implementation is done in BufferLayer.  When called on a
176  * EffectLayer object, it's essentially a NOP.
177  */
onLayerDisplayed(const sp<Fence> &)178 void Layer::onLayerDisplayed(const sp<Fence>& /*releaseFence*/) {}
179 
removeRemoteSyncPoints()180 void Layer::removeRemoteSyncPoints() {
181     for (auto& point : mRemoteSyncPoints) {
182         point->setTransactionApplied();
183     }
184     mRemoteSyncPoints.clear();
185 
186     {
187         for (State pendingState : mPendingStates) {
188             pendingState.barrierLayer_legacy = nullptr;
189         }
190     }
191 }
192 
removeRelativeZ(const std::vector<Layer * > & layersInTree)193 void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
194     if (mCurrentState.zOrderRelativeOf == nullptr) {
195         return;
196     }
197 
198     sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
199     if (strongRelative == nullptr) {
200         setZOrderRelativeOf(nullptr);
201         return;
202     }
203 
204     if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
205         strongRelative->removeZOrderRelative(this);
206         mFlinger->setTransactionFlags(eTraversalNeeded);
207         setZOrderRelativeOf(nullptr);
208     }
209 }
210 
removeFromCurrentState()211 void Layer::removeFromCurrentState() {
212     mRemovedFromCurrentState = true;
213 
214     // Since we are no longer reachable from CurrentState SurfaceFlinger
215     // will no longer invoke doTransaction for us, and so we will
216     // never finish applying transactions. We signal the sync point
217     // now so that another layer will not become indefinitely
218     // blocked.
219     removeRemoteSyncPoints();
220 
221     {
222     Mutex::Autolock syncLock(mLocalSyncPointMutex);
223     for (auto& point : mLocalSyncPoints) {
224         point->setFrameAvailable();
225     }
226     mLocalSyncPoints.clear();
227     }
228 
229     mFlinger->markLayerPendingRemovalLocked(this);
230 }
231 
getRootLayer()232 sp<Layer> Layer::getRootLayer() {
233     sp<Layer> parent = getParent();
234     if (parent == nullptr) {
235         return this;
236     }
237     return parent->getRootLayer();
238 }
239 
onRemovedFromCurrentState()240 void Layer::onRemovedFromCurrentState() {
241     // Use the root layer since we want to maintain the hierarchy for the entire subtree.
242     auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
243     std::sort(layersInTree.begin(), layersInTree.end());
244 
245     traverse(LayerVector::StateSet::Current, [&](Layer* layer) {
246         layer->removeFromCurrentState();
247         layer->removeRelativeZ(layersInTree);
248     });
249 }
250 
addToCurrentState()251 void Layer::addToCurrentState() {
252     mRemovedFromCurrentState = false;
253 
254     for (const auto& child : mCurrentChildren) {
255         child->addToCurrentState();
256     }
257 }
258 
259 // ---------------------------------------------------------------------------
260 // set-up
261 // ---------------------------------------------------------------------------
262 
getPremultipledAlpha() const263 bool Layer::getPremultipledAlpha() const {
264     return mPremultipliedAlpha;
265 }
266 
getHandle()267 sp<IBinder> Layer::getHandle() {
268     Mutex::Autolock _l(mLock);
269     if (mGetHandleCalled) {
270         ALOGE("Get handle called twice" );
271         return nullptr;
272     }
273     mGetHandleCalled = true;
274     return new Handle(mFlinger, this);
275 }
276 
277 // ---------------------------------------------------------------------------
278 // h/w composer set-up
279 // ---------------------------------------------------------------------------
280 
reduce(const Rect & win,const Region & exclude)281 static Rect reduce(const Rect& win, const Region& exclude) {
282     if (CC_LIKELY(exclude.isEmpty())) {
283         return win;
284     }
285     if (exclude.isRect()) {
286         return win.reduce(exclude.getBounds());
287     }
288     return Region(win).subtract(exclude).getBounds();
289 }
290 
reduce(const FloatRect & win,const Region & exclude)291 static FloatRect reduce(const FloatRect& win, const Region& exclude) {
292     if (CC_LIKELY(exclude.isEmpty())) {
293         return win;
294     }
295     // Convert through Rect (by rounding) for lack of FloatRegion
296     return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
297 }
298 
getScreenBounds(bool reduceTransparentRegion) const299 Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
300     if (!reduceTransparentRegion) {
301         return Rect{mScreenBounds};
302     }
303 
304     FloatRect bounds = getBounds();
305     ui::Transform t = getTransform();
306     // Transform to screen space.
307     bounds = t.transform(bounds);
308     return Rect{bounds};
309 }
310 
getBounds() const311 FloatRect Layer::getBounds() const {
312     const State& s(getDrawingState());
313     return getBounds(getActiveTransparentRegion(s));
314 }
315 
getBounds(const Region & activeTransparentRegion) const316 FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
317     // Subtract the transparent region and snap to the bounds.
318     return reduce(mBounds, activeTransparentRegion);
319 }
320 
getBufferScaleTransform() const321 ui::Transform Layer::getBufferScaleTransform() const {
322     // If the layer is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g.
323     // it isFixedSize) then there may be additional scaling not accounted
324     // for in the layer transform.
325     if (!isFixedSize() || getBuffer() == nullptr) {
326         return {};
327     }
328 
329     // If the layer is a buffer state layer, the active width and height
330     // could be infinite. In that case, return the effective transform.
331     const uint32_t activeWidth = getActiveWidth(getDrawingState());
332     const uint32_t activeHeight = getActiveHeight(getDrawingState());
333     if (activeWidth >= UINT32_MAX && activeHeight >= UINT32_MAX) {
334         return {};
335     }
336 
337     int bufferWidth = getBuffer()->getWidth();
338     int bufferHeight = getBuffer()->getHeight();
339 
340     if (getBufferTransform() & NATIVE_WINDOW_TRANSFORM_ROT_90) {
341         std::swap(bufferWidth, bufferHeight);
342     }
343 
344     float sx = activeWidth / static_cast<float>(bufferWidth);
345     float sy = activeHeight / static_cast<float>(bufferHeight);
346 
347     ui::Transform extraParentScaling;
348     extraParentScaling.set(sx, 0, 0, sy);
349     return extraParentScaling;
350 }
351 
getTransformWithScale(const ui::Transform & bufferScaleTransform) const352 ui::Transform Layer::getTransformWithScale(const ui::Transform& bufferScaleTransform) const {
353     // We need to mirror this scaling to child surfaces or we will break the contract where WM can
354     // treat child surfaces as pixels in the parent surface.
355     if (!isFixedSize() || getBuffer() == nullptr) {
356         return mEffectiveTransform;
357     }
358     return mEffectiveTransform * bufferScaleTransform;
359 }
360 
getBoundsPreScaling(const ui::Transform & bufferScaleTransform) const361 FloatRect Layer::getBoundsPreScaling(const ui::Transform& bufferScaleTransform) const {
362     // We need the pre scaled layer bounds when computing child bounds to make sure the child is
363     // cropped to its parent layer after any buffer transform scaling is applied.
364     if (!isFixedSize() || getBuffer() == nullptr) {
365         return mBounds;
366     }
367     return bufferScaleTransform.inverse().transform(mBounds);
368 }
369 
computeBounds(FloatRect parentBounds,ui::Transform parentTransform,float parentShadowRadius)370 void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
371                           float parentShadowRadius) {
372     const State& s(getDrawingState());
373 
374     // Calculate effective layer transform
375     mEffectiveTransform = parentTransform * getActiveTransform(s);
376 
377     // Transform parent bounds to layer space
378     parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
379 
380     // Calculate source bounds
381     mSourceBounds = computeSourceBounds(parentBounds);
382 
383     // Calculate bounds by croping diplay frame with layer crop and parent bounds
384     FloatRect bounds = mSourceBounds;
385     const Rect layerCrop = getCrop(s);
386     if (!layerCrop.isEmpty()) {
387         bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
388     }
389     bounds = bounds.intersect(parentBounds);
390 
391     mBounds = bounds;
392     mScreenBounds = mEffectiveTransform.transform(mBounds);
393 
394     // Use the layer's own shadow radius if set. Otherwise get the radius from
395     // parent.
396     if (s.shadowRadius > 0.f) {
397         mEffectiveShadowRadius = s.shadowRadius;
398     } else {
399         mEffectiveShadowRadius = parentShadowRadius;
400     }
401 
402     // Shadow radius is passed down to only one layer so if the layer can draw shadows,
403     // don't pass it to its children.
404     const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
405 
406     // Add any buffer scaling to the layer's children.
407     ui::Transform bufferScaleTransform = getBufferScaleTransform();
408     for (const sp<Layer>& child : mDrawingChildren) {
409         child->computeBounds(getBoundsPreScaling(bufferScaleTransform),
410                              getTransformWithScale(bufferScaleTransform), childShadowRadius);
411     }
412 }
413 
getCroppedBufferSize(const State & s) const414 Rect Layer::getCroppedBufferSize(const State& s) const {
415     Rect size = getBufferSize(s);
416     Rect crop = getCrop(s);
417     if (!crop.isEmpty() && size.isValid()) {
418         size.intersect(crop, &size);
419     } else if (!crop.isEmpty()) {
420         size = crop;
421     }
422     return size;
423 }
424 
setupRoundedCornersCropCoordinates(Rect win,const FloatRect & roundedCornersCrop) const425 void Layer::setupRoundedCornersCropCoordinates(Rect win,
426                                                const FloatRect& roundedCornersCrop) const {
427     // Translate win by the rounded corners rect coordinates, to have all values in
428     // layer coordinate space.
429     win.left -= roundedCornersCrop.left;
430     win.right -= roundedCornersCrop.left;
431     win.top -= roundedCornersCrop.top;
432     win.bottom -= roundedCornersCrop.top;
433 }
434 
prepareBasicGeometryCompositionState()435 void Layer::prepareBasicGeometryCompositionState() {
436     const auto& drawingState{getDrawingState()};
437     const uint32_t layerStack = getLayerStack();
438     const auto alpha = static_cast<float>(getAlpha());
439     const bool opaque = isOpaque(drawingState);
440     const bool usesRoundedCorners = getRoundedCornerState().radius != 0.f;
441 
442     auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
443     if (!opaque || alpha != 1.0f) {
444         blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
445                                         : Hwc2::IComposerClient::BlendMode::COVERAGE;
446     }
447 
448     auto* compositionState = editCompositionState();
449     compositionState->layerStackId =
450             (layerStack != ~0u) ? std::make_optional(layerStack) : std::nullopt;
451     compositionState->internalOnly = getPrimaryDisplayOnly();
452     compositionState->isVisible = isVisible();
453     compositionState->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
454     compositionState->shadowRadius = mEffectiveShadowRadius;
455 
456     compositionState->contentDirty = contentDirty;
457     contentDirty = false;
458 
459     compositionState->geomLayerBounds = mBounds;
460     compositionState->geomLayerTransform = getTransform();
461     compositionState->geomInverseLayerTransform = compositionState->geomLayerTransform.inverse();
462     compositionState->transparentRegionHint = getActiveTransparentRegion(drawingState);
463 
464     compositionState->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
465     compositionState->alpha = alpha;
466     compositionState->backgroundBlurRadius = drawingState.backgroundBlurRadius;
467 }
468 
prepareGeometryCompositionState()469 void Layer::prepareGeometryCompositionState() {
470     const auto& drawingState{getDrawingState()};
471 
472     int type = drawingState.metadata.getInt32(METADATA_WINDOW_TYPE, 0);
473     int appId = drawingState.metadata.getInt32(METADATA_OWNER_UID, 0);
474     sp<Layer> parent = mDrawingParent.promote();
475     if (parent.get()) {
476         auto& parentState = parent->getDrawingState();
477         const int parentType = parentState.metadata.getInt32(METADATA_WINDOW_TYPE, 0);
478         const int parentAppId = parentState.metadata.getInt32(METADATA_OWNER_UID, 0);
479         if (parentType > 0 && parentAppId > 0) {
480             type = parentType;
481             appId = parentAppId;
482         }
483     }
484 
485     auto* compositionState = editCompositionState();
486 
487     compositionState->geomBufferSize = getBufferSize(drawingState);
488     compositionState->geomContentCrop = getBufferCrop();
489     compositionState->geomCrop = getCrop(drawingState);
490     compositionState->geomBufferTransform = getBufferTransform();
491     compositionState->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
492     compositionState->geomUsesSourceCrop = usesSourceCrop();
493     compositionState->isSecure = isSecure();
494 
495     compositionState->type = type;
496     compositionState->appId = appId;
497 
498     compositionState->metadata.clear();
499     const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
500     for (const auto& [key, mandatory] : supportedMetadata) {
501         const auto& genericLayerMetadataCompatibilityMap =
502                 mFlinger->getGenericLayerMetadataKeyMap();
503         auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
504         if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
505             continue;
506         }
507         const uint32_t id = compatIter->second;
508 
509         auto it = drawingState.metadata.mMap.find(id);
510         if (it == std::end(drawingState.metadata.mMap)) {
511             continue;
512         }
513 
514         compositionState->metadata
515                 .emplace(key, compositionengine::GenericLayerMetadataEntry{mandatory, it->second});
516     }
517 }
518 
preparePerFrameCompositionState()519 void Layer::preparePerFrameCompositionState() {
520     const auto& drawingState{getDrawingState()};
521     auto* compositionState = editCompositionState();
522 
523     compositionState->forceClientComposition = false;
524 
525     compositionState->isColorspaceAgnostic = isColorSpaceAgnostic();
526     compositionState->dataspace = getDataSpace();
527     compositionState->colorTransform = getColorTransform();
528     compositionState->colorTransformIsIdentity = !hasColorTransform();
529     compositionState->surfaceDamage = surfaceDamageRegion;
530     compositionState->hasProtectedContent = isProtected();
531 
532     const bool usesRoundedCorners = getRoundedCornerState().radius != 0.f;
533 
534     compositionState->isOpaque =
535             isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
536 
537     // Force client composition for special cases known only to the front-end.
538     if (isHdrY410() || usesRoundedCorners || drawShadows()) {
539         compositionState->forceClientComposition = true;
540     }
541 }
542 
prepareCursorCompositionState()543 void Layer::prepareCursorCompositionState() {
544     const State& drawingState{getDrawingState()};
545     auto* compositionState = editCompositionState();
546 
547     // Apply the layer's transform, followed by the display's global transform
548     // Here we're guaranteed that the layer's transform preserves rects
549     Rect win = getCroppedBufferSize(drawingState);
550     // Subtract the transparent region and snap to the bounds
551     Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
552     Rect frame(getTransform().transform(bounds));
553 
554     compositionState->cursorFrame = frame;
555 }
556 
asLayerFE() const557 sp<compositionengine::LayerFE> Layer::asLayerFE() const {
558     return const_cast<compositionengine::LayerFE*>(
559             static_cast<const compositionengine::LayerFE*>(this));
560 }
561 
getCompositionEngineLayerFE() const562 sp<compositionengine::LayerFE> Layer::getCompositionEngineLayerFE() const {
563     return nullptr;
564 }
565 
editCompositionState()566 compositionengine::LayerFECompositionState* Layer::editCompositionState() {
567     return nullptr;
568 }
569 
getCompositionState() const570 const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
571     return nullptr;
572 }
573 
onPreComposition(nsecs_t)574 bool Layer::onPreComposition(nsecs_t) {
575     return false;
576 }
577 
prepareCompositionState(compositionengine::LayerFE::StateSubset subset)578 void Layer::prepareCompositionState(compositionengine::LayerFE::StateSubset subset) {
579     using StateSubset = compositionengine::LayerFE::StateSubset;
580 
581     switch (subset) {
582         case StateSubset::BasicGeometry:
583             prepareBasicGeometryCompositionState();
584             break;
585 
586         case StateSubset::GeometryAndContent:
587             prepareBasicGeometryCompositionState();
588             prepareGeometryCompositionState();
589             preparePerFrameCompositionState();
590             break;
591 
592         case StateSubset::Content:
593             preparePerFrameCompositionState();
594             break;
595 
596         case StateSubset::Cursor:
597             prepareCursorCompositionState();
598             break;
599     }
600 }
601 
getDebugName() const602 const char* Layer::getDebugName() const {
603     return mName.c_str();
604 }
605 
606 // ---------------------------------------------------------------------------
607 // drawing...
608 // ---------------------------------------------------------------------------
609 
prepareClientComposition(compositionengine::LayerFE::ClientCompositionTargetSettings & targetSettings)610 std::optional<compositionengine::LayerFE::LayerSettings> Layer::prepareClientComposition(
611         compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) {
612     if (!getCompositionState()) {
613         return {};
614     }
615 
616     FloatRect bounds = getBounds();
617     half alpha = getAlpha();
618 
619     compositionengine::LayerFE::LayerSettings layerSettings;
620     layerSettings.geometry.boundaries = bounds;
621     if (targetSettings.useIdentityTransform) {
622         layerSettings.geometry.positionTransform = mat4();
623     } else {
624         layerSettings.geometry.positionTransform = getTransform().asMatrix4();
625     }
626 
627     if (hasColorTransform()) {
628         layerSettings.colorTransform = getColorTransform();
629     }
630 
631     const auto roundedCornerState = getRoundedCornerState();
632     layerSettings.geometry.roundedCornersRadius = roundedCornerState.radius;
633     layerSettings.geometry.roundedCornersCrop = roundedCornerState.cropRect;
634 
635     layerSettings.alpha = alpha;
636     layerSettings.sourceDataspace = getDataSpace();
637     layerSettings.backgroundBlurRadius = getBackgroundBlurRadius();
638     return layerSettings;
639 }
640 
prepareShadowClientComposition(const LayerFE::LayerSettings & casterLayerSettings,const Rect & displayViewport,ui::Dataspace outputDataspace)641 std::optional<compositionengine::LayerFE::LayerSettings> Layer::prepareShadowClientComposition(
642         const LayerFE::LayerSettings& casterLayerSettings, const Rect& displayViewport,
643         ui::Dataspace outputDataspace) {
644     renderengine::ShadowSettings shadow = getShadowSettings(displayViewport);
645     if (shadow.length <= 0.f) {
646         return {};
647     }
648 
649     const float casterAlpha = casterLayerSettings.alpha;
650     const bool casterIsOpaque = ((casterLayerSettings.source.buffer.buffer != nullptr) &&
651                                  casterLayerSettings.source.buffer.isOpaque);
652 
653     compositionengine::LayerFE::LayerSettings shadowLayer = casterLayerSettings;
654 
655     shadowLayer.shadow = shadow;
656     shadowLayer.geometry.boundaries = mBounds; // ignore transparent region
657 
658     // If the casting layer is translucent, we need to fill in the shadow underneath the layer.
659     // Otherwise the generated shadow will only be shown around the casting layer.
660     shadowLayer.shadow.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
661     shadowLayer.shadow.ambientColor *= casterAlpha;
662     shadowLayer.shadow.spotColor *= casterAlpha;
663     shadowLayer.sourceDataspace = outputDataspace;
664     shadowLayer.source.buffer.buffer = nullptr;
665     shadowLayer.source.buffer.fence = nullptr;
666     shadowLayer.frameNumber = 0;
667     shadowLayer.bufferId = 0;
668 
669     if (shadowLayer.shadow.ambientColor.a <= 0.f && shadowLayer.shadow.spotColor.a <= 0.f) {
670         return {};
671     }
672 
673     float casterCornerRadius = shadowLayer.geometry.roundedCornersRadius;
674     const FloatRect& cornerRadiusCropRect = shadowLayer.geometry.roundedCornersCrop;
675     const FloatRect& casterRect = shadowLayer.geometry.boundaries;
676 
677     // crop used to set the corner radius may be larger than the content rect. Adjust the corner
678     // radius accordingly.
679     if (casterCornerRadius > 0.f) {
680         float cropRectOffset = std::max(std::abs(cornerRadiusCropRect.top - casterRect.top),
681                                         std::abs(cornerRadiusCropRect.left - casterRect.left));
682         if (cropRectOffset > casterCornerRadius) {
683             casterCornerRadius = 0;
684         } else {
685             casterCornerRadius -= cropRectOffset;
686         }
687         shadowLayer.geometry.roundedCornersRadius = casterCornerRadius;
688     }
689 
690     return shadowLayer;
691 }
692 
prepareClearClientComposition(LayerFE::LayerSettings & layerSettings,bool blackout) const693 void Layer::prepareClearClientComposition(LayerFE::LayerSettings& layerSettings,
694                                           bool blackout) const {
695     layerSettings.source.buffer.buffer = nullptr;
696     layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
697     layerSettings.disableBlending = true;
698     layerSettings.bufferId = 0;
699     layerSettings.frameNumber = 0;
700 
701     // If layer is blacked out, force alpha to 1 so that we draw a black color layer.
702     layerSettings.alpha = blackout ? 1.0f : 0.0f;
703 }
704 
prepareClientCompositionList(compositionengine::LayerFE::ClientCompositionTargetSettings & targetSettings)705 std::vector<compositionengine::LayerFE::LayerSettings> Layer::prepareClientCompositionList(
706         compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) {
707     std::optional<compositionengine::LayerFE::LayerSettings> layerSettings =
708             prepareClientComposition(targetSettings);
709     // Nothing to render.
710     if (!layerSettings) {
711         return {};
712     }
713 
714     // HWC requests to clear this layer.
715     if (targetSettings.clearContent) {
716         prepareClearClientComposition(*layerSettings, false /* blackout */);
717         return {*layerSettings};
718     }
719 
720     std::optional<compositionengine::LayerFE::LayerSettings> shadowSettings =
721             prepareShadowClientComposition(*layerSettings, targetSettings.viewport,
722                                            targetSettings.dataspace);
723     // There are no shadows to render.
724     if (!shadowSettings) {
725         return {*layerSettings};
726     }
727 
728     // If the layer casts a shadow but the content casting the shadow is occluded, skip
729     // composing the non-shadow content and only draw the shadows.
730     if (targetSettings.realContentIsVisible) {
731         return {*shadowSettings, *layerSettings};
732     }
733 
734     return {*shadowSettings};
735 }
736 
getCompositionType(const DisplayDevice & display) const737 Hwc2::IComposerClient::Composition Layer::getCompositionType(const DisplayDevice& display) const {
738     const auto outputLayer = findOutputLayerForDisplay(&display);
739     if (outputLayer == nullptr) {
740         return Hwc2::IComposerClient::Composition::INVALID;
741     }
742     if (outputLayer->getState().hwc) {
743         return (*outputLayer->getState().hwc).hwcCompositionType;
744     } else {
745         return Hwc2::IComposerClient::Composition::CLIENT;
746     }
747 }
748 
addSyncPoint(const std::shared_ptr<SyncPoint> & point)749 bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
750     if (point->getFrameNumber() <= mCurrentFrameNumber) {
751         // Don't bother with a SyncPoint, since we've already latched the
752         // relevant frame
753         return false;
754     }
755     if (isRemovedFromCurrentState()) {
756         return false;
757     }
758 
759     Mutex::Autolock lock(mLocalSyncPointMutex);
760     mLocalSyncPoints.push_back(point);
761     return true;
762 }
763 
764 // ----------------------------------------------------------------------------
765 // local state
766 // ----------------------------------------------------------------------------
767 
isSecure() const768 bool Layer::isSecure() const {
769     const State& s(mDrawingState);
770     return (s.flags & layer_state_t::eLayerSecure);
771 }
772 
773 // ----------------------------------------------------------------------------
774 // transaction
775 // ----------------------------------------------------------------------------
776 
pushPendingState()777 void Layer::pushPendingState() {
778     if (!mCurrentState.modified) {
779         return;
780     }
781     ATRACE_CALL();
782 
783     // If this transaction is waiting on the receipt of a frame, generate a sync
784     // point and send it to the remote layer.
785     // We don't allow installing sync points after we are removed from the current state
786     // as we won't be able to signal our end.
787     if (mCurrentState.barrierLayer_legacy != nullptr && !isRemovedFromCurrentState()) {
788         sp<Layer> barrierLayer = mCurrentState.barrierLayer_legacy.promote();
789         if (barrierLayer == nullptr) {
790             ALOGE("[%s] Unable to promote barrier Layer.", getDebugName());
791             // If we can't promote the layer we are intended to wait on,
792             // then it is expired or otherwise invalid. Allow this transaction
793             // to be applied as per normal (no synchronization).
794             mCurrentState.barrierLayer_legacy = nullptr;
795         } else {
796             auto syncPoint = std::make_shared<SyncPoint>(mCurrentState.frameNumber_legacy, this);
797             if (barrierLayer->addSyncPoint(syncPoint)) {
798                 std::stringstream ss;
799                 ss << "Adding sync point " << mCurrentState.frameNumber_legacy;
800                 ATRACE_NAME(ss.str().c_str());
801                 mRemoteSyncPoints.push_back(std::move(syncPoint));
802             } else {
803                 // We already missed the frame we're supposed to synchronize
804                 // on, so go ahead and apply the state update
805                 mCurrentState.barrierLayer_legacy = nullptr;
806             }
807         }
808 
809         // Wake us up to check if the frame has been received
810         setTransactionFlags(eTransactionNeeded);
811         mFlinger->setTransactionFlags(eTraversalNeeded);
812     }
813     mPendingStates.push_back(mCurrentState);
814     ATRACE_INT(mTransactionName.c_str(), mPendingStates.size());
815 }
816 
popPendingState(State * stateToCommit)817 void Layer::popPendingState(State* stateToCommit) {
818     ATRACE_CALL();
819     *stateToCommit = mPendingStates[0];
820 
821     mPendingStates.removeAt(0);
822     ATRACE_INT(mTransactionName.c_str(), mPendingStates.size());
823 }
824 
applyPendingStates(State * stateToCommit)825 bool Layer::applyPendingStates(State* stateToCommit) {
826     bool stateUpdateAvailable = false;
827     while (!mPendingStates.empty()) {
828         if (mPendingStates[0].barrierLayer_legacy != nullptr) {
829             if (mRemoteSyncPoints.empty()) {
830                 // If we don't have a sync point for this, apply it anyway. It
831                 // will be visually wrong, but it should keep us from getting
832                 // into too much trouble.
833                 ALOGE("[%s] No local sync point found", getDebugName());
834                 popPendingState(stateToCommit);
835                 stateUpdateAvailable = true;
836                 continue;
837             }
838 
839             if (mRemoteSyncPoints.front()->getFrameNumber() !=
840                 mPendingStates[0].frameNumber_legacy) {
841                 ALOGE("[%s] Unexpected sync point frame number found", getDebugName());
842 
843                 // Signal our end of the sync point and then dispose of it
844                 mRemoteSyncPoints.front()->setTransactionApplied();
845                 mRemoteSyncPoints.pop_front();
846                 continue;
847             }
848 
849             if (mRemoteSyncPoints.front()->frameIsAvailable()) {
850                 ATRACE_NAME("frameIsAvailable");
851                 // Apply the state update
852                 popPendingState(stateToCommit);
853                 stateUpdateAvailable = true;
854 
855                 // Signal our end of the sync point and then dispose of it
856                 mRemoteSyncPoints.front()->setTransactionApplied();
857                 mRemoteSyncPoints.pop_front();
858             } else {
859                 ATRACE_NAME("!frameIsAvailable");
860                 break;
861             }
862         } else {
863             popPendingState(stateToCommit);
864             stateUpdateAvailable = true;
865         }
866     }
867 
868     // If we still have pending updates, we need to ensure SurfaceFlinger
869     // will keep calling doTransaction, and so we force a traversal.
870     // However, our pending states won't clear until a frame is available,
871     // and so there is no need to specifically trigger a wakeup.
872     if (!mPendingStates.empty()) {
873         setTransactionFlags(eTransactionNeeded);
874         mFlinger->setTraversalNeeded();
875     }
876 
877     mCurrentState.modified = false;
878     return stateUpdateAvailable;
879 }
880 
doTransactionResize(uint32_t flags,State * stateToCommit)881 uint32_t Layer::doTransactionResize(uint32_t flags, State* stateToCommit) {
882     const State& s(getDrawingState());
883 
884     const bool sizeChanged = (stateToCommit->requested_legacy.w != s.requested_legacy.w) ||
885             (stateToCommit->requested_legacy.h != s.requested_legacy.h);
886 
887     if (sizeChanged) {
888         // the size changed, we need to ask our client to request a new buffer
889         ALOGD_IF(DEBUG_RESIZE,
890                  "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
891                  "  current={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
892                  "            requested={ wh={%4u,%4u} }}\n"
893                  "  drawing={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
894                  "            requested={ wh={%4u,%4u} }}\n",
895                  this, getName().c_str(), getBufferTransform(), getEffectiveScalingMode(),
896                  stateToCommit->active_legacy.w, stateToCommit->active_legacy.h,
897                  stateToCommit->crop_legacy.left, stateToCommit->crop_legacy.top,
898                  stateToCommit->crop_legacy.right, stateToCommit->crop_legacy.bottom,
899                  stateToCommit->crop_legacy.getWidth(), stateToCommit->crop_legacy.getHeight(),
900                  stateToCommit->requested_legacy.w, stateToCommit->requested_legacy.h,
901                  s.active_legacy.w, s.active_legacy.h, s.crop_legacy.left, s.crop_legacy.top,
902                  s.crop_legacy.right, s.crop_legacy.bottom, s.crop_legacy.getWidth(),
903                  s.crop_legacy.getHeight(), s.requested_legacy.w, s.requested_legacy.h);
904     }
905 
906     // Don't let Layer::doTransaction update the drawing state
907     // if we have a pending resize, unless we are in fixed-size mode.
908     // the drawing state will be updated only once we receive a buffer
909     // with the correct size.
910     //
911     // In particular, we want to make sure the clip (which is part
912     // of the geometry state) is latched together with the size but is
913     // latched immediately when no resizing is involved.
914     //
915     // If a sideband stream is attached, however, we want to skip this
916     // optimization so that transactions aren't missed when a buffer
917     // never arrives
918     //
919     // In the case that we don't have a buffer we ignore other factors
920     // and avoid entering the resizePending state. At a high level the
921     // resizePending state is to avoid applying the state of the new buffer
922     // to the old buffer. However in the state where we don't have an old buffer
923     // there is no such concern but we may still be being used as a parent layer.
924     const bool resizePending =
925             ((stateToCommit->requested_legacy.w != stateToCommit->active_legacy.w) ||
926              (stateToCommit->requested_legacy.h != stateToCommit->active_legacy.h)) &&
927             (getBuffer() != nullptr);
928     if (!isFixedSize()) {
929         if (resizePending && mSidebandStream == nullptr) {
930             flags |= eDontUpdateGeometryState;
931         }
932     }
933 
934     // Here we apply various requested geometry states, depending on our
935     // latching configuration. See Layer.h for a detailed discussion of
936     // how geometry latching is controlled.
937     if (!(flags & eDontUpdateGeometryState)) {
938         State& editCurrentState(getCurrentState());
939 
940         // There is an awkward asymmetry in the handling of the crop states in the position
941         // states, as can be seen below. Largely this arises from position and transform
942         // being stored in the same data structure while having different latching rules.
943         // b/38182305
944         //
945         // Careful that "stateToCommit" and editCurrentState may not begin as equivalent due to
946         // applyPendingStates in the presence of deferred transactions.
947         editCurrentState.active_legacy = editCurrentState.requested_legacy;
948         stateToCommit->active_legacy = stateToCommit->requested_legacy;
949     }
950 
951     return flags;
952 }
953 
doTransaction(uint32_t flags)954 uint32_t Layer::doTransaction(uint32_t flags) {
955     ATRACE_CALL();
956 
957     if (mLayerDetached) {
958         // Ensure BLAST buffer callbacks are processed.
959         // detachChildren and mLayerDetached were implemented to avoid geometry updates
960         // to layers in the cases of animation. For BufferQueue layers buffers are still
961         // consumed as normal. This is useful as otherwise the client could get hung
962         // inevitably waiting on a buffer to return. We recreate this semantic for BufferQueue
963         // even though it is a little consistent. detachChildren is shortly slated for removal
964         // by the hierarchy mirroring work so we don't need to worry about it too much.
965         forceSendCallbacks();
966         mCurrentState.callbackHandles = {};
967         return flags;
968     }
969 
970     if (mChildrenChanged) {
971         flags |= eVisibleRegion;
972         mChildrenChanged = false;
973     }
974 
975     pushPendingState();
976     State c = getCurrentState();
977     if (!applyPendingStates(&c)) {
978         return flags;
979     }
980 
981     flags = doTransactionResize(flags, &c);
982 
983     const State& s(getDrawingState());
984 
985     if (getActiveGeometry(c) != getActiveGeometry(s)) {
986         // invalidate and recompute the visible regions if needed
987         flags |= Layer::eVisibleRegion;
988     }
989 
990     if (c.sequence != s.sequence) {
991         // invalidate and recompute the visible regions if needed
992         flags |= eVisibleRegion;
993         this->contentDirty = true;
994 
995         // we may use linear filtering, if the matrix scales us
996         const uint8_t type = getActiveTransform(c).getType();
997         mNeedsFiltering = (!getActiveTransform(c).preserveRects() || type >= ui::Transform::SCALE);
998     }
999 
1000     if (mCurrentState.inputInfoChanged) {
1001         flags |= eInputInfoChanged;
1002         mCurrentState.inputInfoChanged = false;
1003     }
1004 
1005     // Commit the transaction
1006     commitTransaction(c);
1007     mPendingStatesSnapshot = mPendingStates;
1008     mCurrentState.callbackHandles = {};
1009 
1010     return flags;
1011 }
1012 
commitTransaction(const State & stateToCommit)1013 void Layer::commitTransaction(const State& stateToCommit) {
1014     mDrawingState = stateToCommit;
1015 }
1016 
getTransactionFlags(uint32_t flags)1017 uint32_t Layer::getTransactionFlags(uint32_t flags) {
1018     return mTransactionFlags.fetch_and(~flags) & flags;
1019 }
1020 
setTransactionFlags(uint32_t flags)1021 uint32_t Layer::setTransactionFlags(uint32_t flags) {
1022     return mTransactionFlags.fetch_or(flags);
1023 }
1024 
setPosition(float x,float y)1025 bool Layer::setPosition(float x, float y) {
1026     if (mCurrentState.requested_legacy.transform.tx() == x &&
1027         mCurrentState.requested_legacy.transform.ty() == y)
1028         return false;
1029     mCurrentState.sequence++;
1030 
1031     // We update the requested and active position simultaneously because
1032     // we want to apply the position portion of the transform matrix immediately,
1033     // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
1034     mCurrentState.requested_legacy.transform.set(x, y);
1035     // Here we directly update the active state
1036     // unlike other setters, because we store it within
1037     // the transform, but use different latching rules.
1038     // b/38182305
1039     mCurrentState.active_legacy.transform.set(x, y);
1040 
1041     mCurrentState.modified = true;
1042     setTransactionFlags(eTransactionNeeded);
1043     return true;
1044 }
1045 
setChildLayer(const sp<Layer> & childLayer,int32_t z)1046 bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1047     ssize_t idx = mCurrentChildren.indexOf(childLayer);
1048     if (idx < 0) {
1049         return false;
1050     }
1051     if (childLayer->setLayer(z)) {
1052         mCurrentChildren.removeAt(idx);
1053         mCurrentChildren.add(childLayer);
1054         return true;
1055     }
1056     return false;
1057 }
1058 
setChildRelativeLayer(const sp<Layer> & childLayer,const sp<IBinder> & relativeToHandle,int32_t relativeZ)1059 bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
1060         const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
1061     ssize_t idx = mCurrentChildren.indexOf(childLayer);
1062     if (idx < 0) {
1063         return false;
1064     }
1065     if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
1066         mCurrentChildren.removeAt(idx);
1067         mCurrentChildren.add(childLayer);
1068         return true;
1069     }
1070     return false;
1071 }
1072 
setLayer(int32_t z)1073 bool Layer::setLayer(int32_t z) {
1074     if (mCurrentState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
1075     mCurrentState.sequence++;
1076     mCurrentState.z = z;
1077     mCurrentState.modified = true;
1078 
1079     // Discard all relative layering.
1080     if (mCurrentState.zOrderRelativeOf != nullptr) {
1081         sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
1082         if (strongRelative != nullptr) {
1083             strongRelative->removeZOrderRelative(this);
1084         }
1085         setZOrderRelativeOf(nullptr);
1086     }
1087     setTransactionFlags(eTransactionNeeded);
1088     return true;
1089 }
1090 
removeZOrderRelative(const wp<Layer> & relative)1091 void Layer::removeZOrderRelative(const wp<Layer>& relative) {
1092     mCurrentState.zOrderRelatives.remove(relative);
1093     mCurrentState.sequence++;
1094     mCurrentState.modified = true;
1095     setTransactionFlags(eTransactionNeeded);
1096 }
1097 
addZOrderRelative(const wp<Layer> & relative)1098 void Layer::addZOrderRelative(const wp<Layer>& relative) {
1099     mCurrentState.zOrderRelatives.add(relative);
1100     mCurrentState.modified = true;
1101     mCurrentState.sequence++;
1102     setTransactionFlags(eTransactionNeeded);
1103 }
1104 
setZOrderRelativeOf(const wp<Layer> & relativeOf)1105 void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
1106     mCurrentState.zOrderRelativeOf = relativeOf;
1107     mCurrentState.sequence++;
1108     mCurrentState.modified = true;
1109     mCurrentState.isRelativeOf = relativeOf != nullptr;
1110 
1111     setTransactionFlags(eTransactionNeeded);
1112 }
1113 
setRelativeLayer(const sp<IBinder> & relativeToHandle,int32_t relativeZ)1114 bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
1115     sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get());
1116     if (handle == nullptr) {
1117         return false;
1118     }
1119     sp<Layer> relative = handle->owner.promote();
1120     if (relative == nullptr) {
1121         return false;
1122     }
1123 
1124     if (mCurrentState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
1125         mCurrentState.zOrderRelativeOf == relative) {
1126         return false;
1127     }
1128 
1129     mCurrentState.sequence++;
1130     mCurrentState.modified = true;
1131     mCurrentState.z = relativeZ;
1132 
1133     auto oldZOrderRelativeOf = mCurrentState.zOrderRelativeOf.promote();
1134     if (oldZOrderRelativeOf != nullptr) {
1135         oldZOrderRelativeOf->removeZOrderRelative(this);
1136     }
1137     setZOrderRelativeOf(relative);
1138     relative->addZOrderRelative(this);
1139 
1140     setTransactionFlags(eTransactionNeeded);
1141 
1142     return true;
1143 }
1144 
setSize(uint32_t w,uint32_t h)1145 bool Layer::setSize(uint32_t w, uint32_t h) {
1146     if (mCurrentState.requested_legacy.w == w && mCurrentState.requested_legacy.h == h)
1147         return false;
1148     mCurrentState.requested_legacy.w = w;
1149     mCurrentState.requested_legacy.h = h;
1150     mCurrentState.modified = true;
1151     setTransactionFlags(eTransactionNeeded);
1152 
1153     // record the new size, from this point on, when the client request
1154     // a buffer, it'll get the new size.
1155     setDefaultBufferSize(mCurrentState.requested_legacy.w, mCurrentState.requested_legacy.h);
1156     return true;
1157 }
setAlpha(float alpha)1158 bool Layer::setAlpha(float alpha) {
1159     if (mCurrentState.color.a == alpha) return false;
1160     mCurrentState.sequence++;
1161     mCurrentState.color.a = alpha;
1162     mCurrentState.modified = true;
1163     setTransactionFlags(eTransactionNeeded);
1164     return true;
1165 }
1166 
setBackgroundColor(const half3 & color,float alpha,ui::Dataspace dataspace)1167 bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
1168     if (!mCurrentState.bgColorLayer && alpha == 0) {
1169         return false;
1170     }
1171     mCurrentState.sequence++;
1172     mCurrentState.modified = true;
1173     setTransactionFlags(eTransactionNeeded);
1174 
1175     if (!mCurrentState.bgColorLayer && alpha != 0) {
1176         // create background color layer if one does not yet exist
1177         uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
1178         std::string name = mName + "BackgroundColorLayer";
1179         mCurrentState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
1180                 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), 0, 0, flags,
1181                                   LayerMetadata()));
1182 
1183         // add to child list
1184         addChild(mCurrentState.bgColorLayer);
1185         mFlinger->mLayersAdded = true;
1186         // set up SF to handle added color layer
1187         if (isRemovedFromCurrentState()) {
1188             mCurrentState.bgColorLayer->onRemovedFromCurrentState();
1189         }
1190         mFlinger->setTransactionFlags(eTransactionNeeded);
1191     } else if (mCurrentState.bgColorLayer && alpha == 0) {
1192         mCurrentState.bgColorLayer->reparent(nullptr);
1193         mCurrentState.bgColorLayer = nullptr;
1194         return true;
1195     }
1196 
1197     mCurrentState.bgColorLayer->setColor(color);
1198     mCurrentState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1199     mCurrentState.bgColorLayer->setAlpha(alpha);
1200     mCurrentState.bgColorLayer->setDataspace(dataspace);
1201 
1202     return true;
1203 }
1204 
setCornerRadius(float cornerRadius)1205 bool Layer::setCornerRadius(float cornerRadius) {
1206     if (mCurrentState.cornerRadius == cornerRadius) return false;
1207 
1208     mCurrentState.sequence++;
1209     mCurrentState.cornerRadius = cornerRadius;
1210     mCurrentState.modified = true;
1211     setTransactionFlags(eTransactionNeeded);
1212     return true;
1213 }
1214 
setBackgroundBlurRadius(int backgroundBlurRadius)1215 bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
1216     if (mCurrentState.backgroundBlurRadius == backgroundBlurRadius) return false;
1217 
1218     mCurrentState.sequence++;
1219     mCurrentState.backgroundBlurRadius = backgroundBlurRadius;
1220     mCurrentState.modified = true;
1221     setTransactionFlags(eTransactionNeeded);
1222     return true;
1223 }
1224 
setMatrix(const layer_state_t::matrix22_t & matrix,bool allowNonRectPreservingTransforms)1225 bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix,
1226         bool allowNonRectPreservingTransforms) {
1227     ui::Transform t;
1228     t.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
1229 
1230     if (!allowNonRectPreservingTransforms && !t.preserveRects()) {
1231         ALOGW("Attempt to set rotation matrix without permission ACCESS_SURFACE_FLINGER ignored");
1232         return false;
1233     }
1234     mCurrentState.sequence++;
1235     mCurrentState.requested_legacy.transform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx,
1236                                                  matrix.dsdy);
1237     mCurrentState.modified = true;
1238     setTransactionFlags(eTransactionNeeded);
1239     return true;
1240 }
1241 
setTransparentRegionHint(const Region & transparent)1242 bool Layer::setTransparentRegionHint(const Region& transparent) {
1243     mCurrentState.requestedTransparentRegion_legacy = transparent;
1244     mCurrentState.modified = true;
1245     setTransactionFlags(eTransactionNeeded);
1246     return true;
1247 }
1248 
setFlags(uint8_t flags,uint8_t mask)1249 bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1250     const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1251     if (mCurrentState.flags == newFlags) return false;
1252     mCurrentState.sequence++;
1253     mCurrentState.flags = newFlags;
1254     mCurrentState.modified = true;
1255     setTransactionFlags(eTransactionNeeded);
1256     return true;
1257 }
1258 
setCrop_legacy(const Rect & crop)1259 bool Layer::setCrop_legacy(const Rect& crop) {
1260     if (mCurrentState.requestedCrop_legacy == crop) return false;
1261     mCurrentState.sequence++;
1262     mCurrentState.requestedCrop_legacy = crop;
1263     mCurrentState.crop_legacy = crop;
1264 
1265     mCurrentState.modified = true;
1266     setTransactionFlags(eTransactionNeeded);
1267     return true;
1268 }
1269 
setOverrideScalingMode(int32_t scalingMode)1270 bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1271     if (scalingMode == mOverrideScalingMode) return false;
1272     mOverrideScalingMode = scalingMode;
1273     setTransactionFlags(eTransactionNeeded);
1274     return true;
1275 }
1276 
setMetadata(const LayerMetadata & data)1277 bool Layer::setMetadata(const LayerMetadata& data) {
1278     if (!mCurrentState.metadata.merge(data, true /* eraseEmpty */)) return false;
1279     mCurrentState.sequence++;
1280     mCurrentState.modified = true;
1281     setTransactionFlags(eTransactionNeeded);
1282     return true;
1283 }
1284 
setLayerStack(uint32_t layerStack)1285 bool Layer::setLayerStack(uint32_t layerStack) {
1286     if (mCurrentState.layerStack == layerStack) return false;
1287     mCurrentState.sequence++;
1288     mCurrentState.layerStack = layerStack;
1289     mCurrentState.modified = true;
1290     setTransactionFlags(eTransactionNeeded);
1291     return true;
1292 }
1293 
setColorSpaceAgnostic(const bool agnostic)1294 bool Layer::setColorSpaceAgnostic(const bool agnostic) {
1295     if (mCurrentState.colorSpaceAgnostic == agnostic) {
1296         return false;
1297     }
1298     mCurrentState.sequence++;
1299     mCurrentState.colorSpaceAgnostic = agnostic;
1300     mCurrentState.modified = true;
1301     setTransactionFlags(eTransactionNeeded);
1302     return true;
1303 }
1304 
setFrameRateSelectionPriority(int32_t priority)1305 bool Layer::setFrameRateSelectionPriority(int32_t priority) {
1306     if (mCurrentState.frameRateSelectionPriority == priority) return false;
1307     mCurrentState.frameRateSelectionPriority = priority;
1308     mCurrentState.sequence++;
1309     mCurrentState.modified = true;
1310     setTransactionFlags(eTransactionNeeded);
1311     return true;
1312 }
1313 
getFrameRateSelectionPriority() const1314 int32_t Layer::getFrameRateSelectionPriority() const {
1315     // Check if layer has priority set.
1316     if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1317         return mDrawingState.frameRateSelectionPriority;
1318     }
1319     // If not, search whether its parents have it set.
1320     sp<Layer> parent = getParent();
1321     if (parent != nullptr) {
1322         return parent->getFrameRateSelectionPriority();
1323     }
1324 
1325     return Layer::PRIORITY_UNSET;
1326 }
1327 
isLayerFocusedBasedOnPriority(int32_t priority)1328 bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1329     return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1330 };
1331 
getLayerStack() const1332 uint32_t Layer::getLayerStack() const {
1333     auto p = mDrawingParent.promote();
1334     if (p == nullptr) {
1335         return getDrawingState().layerStack;
1336     }
1337     return p->getLayerStack();
1338 }
1339 
setShadowRadius(float shadowRadius)1340 bool Layer::setShadowRadius(float shadowRadius) {
1341     if (mCurrentState.shadowRadius == shadowRadius) {
1342         return false;
1343     }
1344 
1345     mCurrentState.sequence++;
1346     mCurrentState.shadowRadius = shadowRadius;
1347     mCurrentState.modified = true;
1348     setTransactionFlags(eTransactionNeeded);
1349     return true;
1350 }
1351 
setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint)1352 bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
1353     if (mCurrentState.fixedTransformHint == fixedTransformHint) {
1354         return false;
1355     }
1356 
1357     mCurrentState.sequence++;
1358     mCurrentState.fixedTransformHint = fixedTransformHint;
1359     mCurrentState.modified = true;
1360     setTransactionFlags(eTransactionNeeded);
1361     return true;
1362 }
1363 
updateTreeHasFrameRateVote()1364 void Layer::updateTreeHasFrameRateVote() {
1365     const auto traverseTree = [&](const LayerVector::Visitor& visitor) {
1366         auto parent = getParent();
1367         while (parent) {
1368             visitor(parent.get());
1369             parent = parent->getParent();
1370         }
1371 
1372         traverse(LayerVector::StateSet::Current, visitor);
1373     };
1374 
1375     // update parents and children about the vote
1376     // First traverse the tree and count how many layers has votes
1377     int layersWithVote = 0;
1378     traverseTree([&layersWithVote](Layer* layer) {
1379         const auto layerVotedWithDefaultCompatibility = layer->mCurrentState.frameRate.rate > 0 &&
1380                 layer->mCurrentState.frameRate.type == FrameRateCompatibility::Default;
1381         const auto layerVotedWithNoVote =
1382                 layer->mCurrentState.frameRate.type == FrameRateCompatibility::NoVote;
1383 
1384         // We do not count layers that are ExactOrMultiple for the same reason
1385         // we are allowing touch boost for those layers. See
1386         // RefreshRateConfigs::getBestRefreshRate for more details.
1387         if (layerVotedWithDefaultCompatibility || layerVotedWithNoVote) {
1388             layersWithVote++;
1389         }
1390     });
1391 
1392     // Now update the other layers
1393     bool transactionNeeded = false;
1394     traverseTree([layersWithVote, &transactionNeeded](Layer* layer) {
1395         if (layer->mCurrentState.treeHasFrameRateVote != layersWithVote > 0) {
1396             layer->mCurrentState.sequence++;
1397             layer->mCurrentState.treeHasFrameRateVote = layersWithVote > 0;
1398             layer->mCurrentState.modified = true;
1399             layer->setTransactionFlags(eTransactionNeeded);
1400             transactionNeeded = true;
1401         }
1402     });
1403 
1404     if (transactionNeeded) {
1405         mFlinger->setTransactionFlags(eTraversalNeeded);
1406     }
1407 }
1408 
setFrameRate(FrameRate frameRate)1409 bool Layer::setFrameRate(FrameRate frameRate) {
1410     if (!mFlinger->useFrameRateApi) {
1411         return false;
1412     }
1413     if (mCurrentState.frameRate == frameRate) {
1414         return false;
1415     }
1416 
1417     // Activate the layer in Scheduler's LayerHistory
1418     mFlinger->mScheduler->recordLayerHistory(this, systemTime(),
1419                                              LayerHistory::LayerUpdateType::SetFrameRate);
1420 
1421     mCurrentState.sequence++;
1422     mCurrentState.frameRate = frameRate;
1423     mCurrentState.modified = true;
1424 
1425     updateTreeHasFrameRateVote();
1426 
1427     setTransactionFlags(eTransactionNeeded);
1428     return true;
1429 }
1430 
getFrameRateForLayerTree() const1431 Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1432     const auto frameRate = getDrawingState().frameRate;
1433     if (frameRate.rate > 0 || frameRate.type == FrameRateCompatibility::NoVote) {
1434         return frameRate;
1435     }
1436 
1437     // This layer doesn't have a frame rate. If one of its ancestors or successors
1438     // have a vote, return a NoVote for ancestors/successors to set the vote
1439     if (getDrawingState().treeHasFrameRateVote) {
1440         return {0, FrameRateCompatibility::NoVote};
1441     }
1442 
1443     return frameRate;
1444 }
1445 
deferTransactionUntil_legacy(const sp<Layer> & barrierLayer,uint64_t frameNumber)1446 void Layer::deferTransactionUntil_legacy(const sp<Layer>& barrierLayer, uint64_t frameNumber) {
1447     ATRACE_CALL();
1448     mCurrentState.barrierLayer_legacy = barrierLayer;
1449     mCurrentState.frameNumber_legacy = frameNumber;
1450     // We don't set eTransactionNeeded, because just receiving a deferral
1451     // request without any other state updates shouldn't actually induce a delay
1452     mCurrentState.modified = true;
1453     pushPendingState();
1454     mCurrentState.barrierLayer_legacy = nullptr;
1455     mCurrentState.frameNumber_legacy = 0;
1456     mCurrentState.modified = false;
1457 }
1458 
deferTransactionUntil_legacy(const sp<IBinder> & barrierHandle,uint64_t frameNumber)1459 void Layer::deferTransactionUntil_legacy(const sp<IBinder>& barrierHandle, uint64_t frameNumber) {
1460     sp<Handle> handle = static_cast<Handle*>(barrierHandle.get());
1461     deferTransactionUntil_legacy(handle->owner.promote(), frameNumber);
1462 }
1463 
1464 // ----------------------------------------------------------------------------
1465 // pageflip handling...
1466 // ----------------------------------------------------------------------------
1467 
isHiddenByPolicy() const1468 bool Layer::isHiddenByPolicy() const {
1469     const State& s(mDrawingState);
1470     const auto& parent = mDrawingParent.promote();
1471     if (parent != nullptr && parent->isHiddenByPolicy()) {
1472         return true;
1473     }
1474     if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1475         auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1476         if (zOrderRelativeOf != nullptr) {
1477             if (zOrderRelativeOf->isHiddenByPolicy()) {
1478                 return true;
1479             }
1480         }
1481     }
1482     return s.flags & layer_state_t::eLayerHidden;
1483 }
1484 
getEffectiveUsage(uint32_t usage) const1485 uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
1486     // TODO: should we do something special if mSecure is set?
1487     if (mProtectedByApp) {
1488         // need a hardware-protected path to external video sink
1489         usage |= GraphicBuffer::USAGE_PROTECTED;
1490     }
1491     if (mPotentialCursor) {
1492         usage |= GraphicBuffer::USAGE_CURSOR;
1493     }
1494     usage |= GraphicBuffer::USAGE_HW_COMPOSER;
1495     return usage;
1496 }
1497 
updateTransformHint(ui::Transform::RotationFlags transformHint)1498 void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1499     if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1500         transformHint = ui::Transform::ROT_0;
1501     }
1502 
1503     setTransformHint(transformHint);
1504 }
1505 
1506 // ----------------------------------------------------------------------------
1507 // debugging
1508 // ----------------------------------------------------------------------------
1509 
1510 // TODO(marissaw): add new layer state info to layer debugging
getLayerDebugInfo(const DisplayDevice * display) const1511 LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
1512     using namespace std::string_literals;
1513 
1514     LayerDebugInfo info;
1515     const State& ds = getDrawingState();
1516     info.mName = getName();
1517     sp<Layer> parent = mDrawingParent.promote();
1518     info.mParentName = parent ? parent->getName() : "none"s;
1519     info.mType = getType();
1520     info.mTransparentRegion = ds.activeTransparentRegion_legacy;
1521 
1522     info.mVisibleRegion = getVisibleRegion(display);
1523     info.mSurfaceDamageRegion = surfaceDamageRegion;
1524     info.mLayerStack = getLayerStack();
1525     info.mX = ds.active_legacy.transform.tx();
1526     info.mY = ds.active_legacy.transform.ty();
1527     info.mZ = ds.z;
1528     info.mWidth = ds.active_legacy.w;
1529     info.mHeight = ds.active_legacy.h;
1530     info.mCrop = ds.crop_legacy;
1531     info.mColor = ds.color;
1532     info.mFlags = ds.flags;
1533     info.mPixelFormat = getPixelFormat();
1534     info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
1535     info.mMatrix[0][0] = ds.active_legacy.transform[0][0];
1536     info.mMatrix[0][1] = ds.active_legacy.transform[0][1];
1537     info.mMatrix[1][0] = ds.active_legacy.transform[1][0];
1538     info.mMatrix[1][1] = ds.active_legacy.transform[1][1];
1539     {
1540         sp<const GraphicBuffer> buffer = getBuffer();
1541         if (buffer != 0) {
1542             info.mActiveBufferWidth = buffer->getWidth();
1543             info.mActiveBufferHeight = buffer->getHeight();
1544             info.mActiveBufferStride = buffer->getStride();
1545             info.mActiveBufferFormat = buffer->format;
1546         } else {
1547             info.mActiveBufferWidth = 0;
1548             info.mActiveBufferHeight = 0;
1549             info.mActiveBufferStride = 0;
1550             info.mActiveBufferFormat = 0;
1551         }
1552     }
1553     info.mNumQueuedFrames = getQueuedFrameCount();
1554     info.mRefreshPending = isBufferLatched();
1555     info.mIsOpaque = isOpaque(ds);
1556     info.mContentDirty = contentDirty;
1557     return info;
1558 }
1559 
miniDumpHeader(std::string & result)1560 void Layer::miniDumpHeader(std::string& result) {
1561     result.append("-------------------------------");
1562     result.append("-------------------------------");
1563     result.append("-------------------------------");
1564     result.append("-------------------------------");
1565     result.append("-------------------\n");
1566     result.append(" Layer name\n");
1567     result.append("           Z | ");
1568     result.append(" Window Type | ");
1569     result.append(" Comp Type | ");
1570     result.append(" Transform | ");
1571     result.append("  Disp Frame (LTRB) | ");
1572     result.append("         Source Crop (LTRB) | ");
1573     result.append("    Frame Rate (Explicit) [Focused]\n");
1574     result.append("-------------------------------");
1575     result.append("-------------------------------");
1576     result.append("-------------------------------");
1577     result.append("-------------------------------");
1578     result.append("-------------------\n");
1579 }
1580 
frameRateCompatibilityString(Layer::FrameRateCompatibility compatibility)1581 std::string Layer::frameRateCompatibilityString(Layer::FrameRateCompatibility compatibility) {
1582     switch (compatibility) {
1583         case FrameRateCompatibility::Default:
1584             return "Default";
1585         case FrameRateCompatibility::ExactOrMultiple:
1586             return "ExactOrMultiple";
1587         case FrameRateCompatibility::NoVote:
1588             return "NoVote";
1589     }
1590 }
1591 
miniDump(std::string & result,const DisplayDevice & display) const1592 void Layer::miniDump(std::string& result, const DisplayDevice& display) const {
1593     const auto outputLayer = findOutputLayerForDisplay(&display);
1594     if (!outputLayer) {
1595         return;
1596     }
1597 
1598     std::string name;
1599     if (mName.length() > 77) {
1600         std::string shortened;
1601         shortened.append(mName, 0, 36);
1602         shortened.append("[...]");
1603         shortened.append(mName, mName.length() - 36);
1604         name = std::move(shortened);
1605     } else {
1606         name = mName;
1607     }
1608 
1609     StringAppendF(&result, " %s\n", name.c_str());
1610 
1611     const State& layerState(getDrawingState());
1612     const auto& outputLayerState = outputLayer->getState();
1613 
1614     if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
1615         StringAppendF(&result, "  rel %6d | ", layerState.z);
1616     } else {
1617         StringAppendF(&result, "  %10d | ", layerState.z);
1618     }
1619     StringAppendF(&result, "  %10d | ", mWindowType);
1620     StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
1621     StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1622     const Rect& frame = outputLayerState.displayFrame;
1623     StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
1624     const FloatRect& crop = outputLayerState.sourceCrop;
1625     StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
1626                   crop.bottom);
1627     if (layerState.frameRate.rate != 0 ||
1628         layerState.frameRate.type != FrameRateCompatibility::Default) {
1629         StringAppendF(&result, "% 6.2ffps %15s", layerState.frameRate.rate,
1630                       frameRateCompatibilityString(layerState.frameRate.type).c_str());
1631     } else {
1632         StringAppendF(&result, "                         ");
1633     }
1634 
1635     const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1636     StringAppendF(&result, "    [%s]\n", focused ? "*" : " ");
1637 
1638     result.append("- - - - - - - - - - - - - - - - ");
1639     result.append("- - - - - - - - - - - - - - - - ");
1640     result.append("- - - - - - - - - - - - - - - - ");
1641     result.append("- - - - - - - - - - - - - - - - ");
1642     result.append("- - - - - - - -\n");
1643 }
1644 
dumpFrameStats(std::string & result) const1645 void Layer::dumpFrameStats(std::string& result) const {
1646     mFrameTracker.dumpStats(result);
1647 }
1648 
clearFrameStats()1649 void Layer::clearFrameStats() {
1650     mFrameTracker.clearStats();
1651 }
1652 
logFrameStats()1653 void Layer::logFrameStats() {
1654     mFrameTracker.logAndResetStats(mName);
1655 }
1656 
getFrameStats(FrameStats * outStats) const1657 void Layer::getFrameStats(FrameStats* outStats) const {
1658     mFrameTracker.getStats(outStats);
1659 }
1660 
dumpFrameEvents(std::string & result)1661 void Layer::dumpFrameEvents(std::string& result) {
1662     StringAppendF(&result, "- Layer %s (%s, %p)\n", getName().c_str(), getType(), this);
1663     Mutex::Autolock lock(mFrameEventHistoryMutex);
1664     mFrameEventHistory.checkFencesForCompletion();
1665     mFrameEventHistory.dump(result);
1666 }
1667 
dumpCallingUidPid(std::string & result) const1668 void Layer::dumpCallingUidPid(std::string& result) const {
1669     StringAppendF(&result, "Layer %s (%s) pid:%d uid:%d\n", getName().c_str(), getType(),
1670                   mCallingPid, mCallingUid);
1671 }
1672 
onDisconnect()1673 void Layer::onDisconnect() {
1674     Mutex::Autolock lock(mFrameEventHistoryMutex);
1675     mFrameEventHistory.onDisconnect();
1676     const int32_t layerId = getSequence();
1677     mFlinger->mTimeStats->onDestroy(layerId);
1678     mFlinger->mFrameTracer->onDestroy(layerId);
1679 }
1680 
addAndGetFrameTimestamps(const NewFrameEventsEntry * newTimestamps,FrameEventHistoryDelta * outDelta)1681 void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
1682                                      FrameEventHistoryDelta* outDelta) {
1683     if (newTimestamps) {
1684         mFlinger->mTimeStats->setPostTime(getSequence(), newTimestamps->frameNumber,
1685                                           getName().c_str(), newTimestamps->postedTime);
1686         mFlinger->mTimeStats->setAcquireFence(getSequence(), newTimestamps->frameNumber,
1687                                               newTimestamps->acquireFence);
1688     }
1689 
1690     Mutex::Autolock lock(mFrameEventHistoryMutex);
1691     if (newTimestamps) {
1692         // If there are any unsignaled fences in the aquire timeline at this
1693         // point, the previously queued frame hasn't been latched yet. Go ahead
1694         // and try to get the signal time here so the syscall is taken out of
1695         // the main thread's critical path.
1696         mAcquireTimeline.updateSignalTimes();
1697         // Push the new fence after updating since it's likely still pending.
1698         mAcquireTimeline.push(newTimestamps->acquireFence);
1699         mFrameEventHistory.addQueue(*newTimestamps);
1700     }
1701 
1702     if (outDelta) {
1703         mFrameEventHistory.getAndResetDelta(outDelta);
1704     }
1705 }
1706 
getChildrenCount() const1707 size_t Layer::getChildrenCount() const {
1708     size_t count = 0;
1709     for (const sp<Layer>& child : mCurrentChildren) {
1710         count += 1 + child->getChildrenCount();
1711     }
1712     return count;
1713 }
1714 
addChild(const sp<Layer> & layer)1715 void Layer::addChild(const sp<Layer>& layer) {
1716     mChildrenChanged = true;
1717     setTransactionFlags(eTransactionNeeded);
1718 
1719     mCurrentChildren.add(layer);
1720     layer->setParent(this);
1721     updateTreeHasFrameRateVote();
1722 }
1723 
removeChild(const sp<Layer> & layer)1724 ssize_t Layer::removeChild(const sp<Layer>& layer) {
1725     mChildrenChanged = true;
1726     setTransactionFlags(eTransactionNeeded);
1727 
1728     layer->setParent(nullptr);
1729     const auto removeResult = mCurrentChildren.remove(layer);
1730 
1731     updateTreeHasFrameRateVote();
1732     layer->updateTreeHasFrameRateVote();
1733 
1734     return removeResult;
1735 }
1736 
reparentChildren(const sp<Layer> & newParent)1737 void Layer::reparentChildren(const sp<Layer>& newParent) {
1738     if (attachChildren()) {
1739         setTransactionFlags(eTransactionNeeded);
1740     }
1741 
1742     for (const sp<Layer>& child : mCurrentChildren) {
1743         newParent->addChild(child);
1744     }
1745     mCurrentChildren.clear();
1746     updateTreeHasFrameRateVote();
1747 }
1748 
reparentChildren(const sp<IBinder> & newParentHandle)1749 bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
1750     sp<Handle> handle = nullptr;
1751     sp<Layer> newParent = nullptr;
1752     if (newParentHandle == nullptr) {
1753         return false;
1754     }
1755     handle = static_cast<Handle*>(newParentHandle.get());
1756     newParent = handle->owner.promote();
1757     if (newParent == nullptr) {
1758         ALOGE("Unable to promote Layer handle");
1759         return false;
1760     }
1761 
1762     reparentChildren(newParent);
1763 
1764     return true;
1765 }
1766 
setChildrenDrawingParent(const sp<Layer> & newParent)1767 void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
1768     for (const sp<Layer>& child : mDrawingChildren) {
1769         child->mDrawingParent = newParent;
1770         child->computeBounds(newParent->mBounds,
1771                              newParent->getTransformWithScale(newParent->getBufferScaleTransform()),
1772                              newParent->mEffectiveShadowRadius);
1773     }
1774 }
1775 
reparent(const sp<IBinder> & newParentHandle)1776 bool Layer::reparent(const sp<IBinder>& newParentHandle) {
1777     bool callSetTransactionFlags = false;
1778 
1779     // While layers are detached, we allow most operations
1780     // and simply halt performing the actual transaction. However
1781     // for reparent != null we would enter the mRemovedFromCurrentState
1782     // state, regardless of whether doTransaction was called, and
1783     // so we need to prevent the update here.
1784     if (mLayerDetached && newParentHandle == nullptr) {
1785         return false;
1786     }
1787 
1788     sp<Layer> newParent;
1789     if (newParentHandle != nullptr) {
1790         auto handle = static_cast<Handle*>(newParentHandle.get());
1791         newParent = handle->owner.promote();
1792         if (newParent == nullptr) {
1793             ALOGE("Unable to promote Layer handle");
1794             return false;
1795         }
1796         if (newParent == this) {
1797             ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1798             return false;
1799         }
1800     }
1801 
1802     sp<Layer> parent = getParent();
1803     if (parent != nullptr) {
1804         parent->removeChild(this);
1805     }
1806 
1807     if (newParentHandle != nullptr) {
1808         newParent->addChild(this);
1809         if (!newParent->isRemovedFromCurrentState()) {
1810             addToCurrentState();
1811         } else {
1812             onRemovedFromCurrentState();
1813         }
1814 
1815         if (mLayerDetached) {
1816             mLayerDetached = false;
1817             callSetTransactionFlags = true;
1818         }
1819     } else {
1820         onRemovedFromCurrentState();
1821     }
1822 
1823     if (callSetTransactionFlags || attachChildren()) {
1824         setTransactionFlags(eTransactionNeeded);
1825     }
1826     return true;
1827 }
1828 
detachChildren()1829 bool Layer::detachChildren() {
1830     for (const sp<Layer>& child : mCurrentChildren) {
1831         sp<Client> parentClient = mClientRef.promote();
1832         sp<Client> client(child->mClientRef.promote());
1833         if (client != nullptr && parentClient != client) {
1834             child->mLayerDetached = true;
1835             child->detachChildren();
1836             child->removeRemoteSyncPoints();
1837         }
1838     }
1839 
1840     return true;
1841 }
1842 
attachChildren()1843 bool Layer::attachChildren() {
1844     bool changed = false;
1845     for (const sp<Layer>& child : mCurrentChildren) {
1846         sp<Client> parentClient = mClientRef.promote();
1847         sp<Client> client(child->mClientRef.promote());
1848         if (client != nullptr && parentClient != client) {
1849             if (child->mLayerDetached) {
1850                 child->mLayerDetached = false;
1851                 changed = true;
1852             }
1853             changed |= child->attachChildren();
1854         }
1855     }
1856 
1857     return changed;
1858 }
1859 
setColorTransform(const mat4 & matrix)1860 bool Layer::setColorTransform(const mat4& matrix) {
1861     static const mat4 identityMatrix = mat4();
1862 
1863     if (mCurrentState.colorTransform == matrix) {
1864         return false;
1865     }
1866     ++mCurrentState.sequence;
1867     mCurrentState.colorTransform = matrix;
1868     mCurrentState.hasColorTransform = matrix != identityMatrix;
1869     mCurrentState.modified = true;
1870     setTransactionFlags(eTransactionNeeded);
1871     return true;
1872 }
1873 
getColorTransform() const1874 mat4 Layer::getColorTransform() const {
1875     mat4 colorTransform = mat4(getDrawingState().colorTransform);
1876     if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
1877         colorTransform = parent->getColorTransform() * colorTransform;
1878     }
1879     return colorTransform;
1880 }
1881 
hasColorTransform() const1882 bool Layer::hasColorTransform() const {
1883     bool hasColorTransform = getDrawingState().hasColorTransform;
1884     if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
1885         hasColorTransform = hasColorTransform || parent->hasColorTransform();
1886     }
1887     return hasColorTransform;
1888 }
1889 
isLegacyDataSpace() const1890 bool Layer::isLegacyDataSpace() const {
1891     // return true when no higher bits are set
1892     return !(getDataSpace() &
1893              (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1894               ui::Dataspace::RANGE_MASK));
1895 }
1896 
setParent(const sp<Layer> & layer)1897 void Layer::setParent(const sp<Layer>& layer) {
1898     mCurrentParent = layer;
1899 }
1900 
getZ(LayerVector::StateSet stateSet) const1901 int32_t Layer::getZ(LayerVector::StateSet stateSet) const {
1902     const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1903     const State& state = useDrawing ? mDrawingState : mCurrentState;
1904     return state.z;
1905 }
1906 
usingRelativeZ(LayerVector::StateSet stateSet) const1907 bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
1908     const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1909     const State& state = useDrawing ? mDrawingState : mCurrentState;
1910     return state.isRelativeOf;
1911 }
1912 
makeTraversalList(LayerVector::StateSet stateSet,bool * outSkipRelativeZUsers)1913 __attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
1914         LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
1915     LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1916                         "makeTraversalList received invalid stateSet");
1917     const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1918     const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1919     const State& state = useDrawing ? mDrawingState : mCurrentState;
1920 
1921     if (state.zOrderRelatives.size() == 0) {
1922         *outSkipRelativeZUsers = true;
1923         return children;
1924     }
1925 
1926     LayerVector traverse(stateSet);
1927     for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1928         sp<Layer> strongRelative = weakRelative.promote();
1929         if (strongRelative != nullptr) {
1930             traverse.add(strongRelative);
1931         }
1932     }
1933 
1934     for (const sp<Layer>& child : children) {
1935         if (child->usingRelativeZ(stateSet)) {
1936             continue;
1937         }
1938         traverse.add(child);
1939     }
1940 
1941     return traverse;
1942 }
1943 
1944 /**
1945  * Negatively signed relatives are before 'this' in Z-order.
1946  */
traverseInZOrder(LayerVector::StateSet stateSet,const LayerVector::Visitor & visitor)1947 void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
1948     // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1949     // produce a new list for traversing, including our relatives, and not including our children
1950     // who are relatives of another surface. In the case that there are no relative Z,
1951     // makeTraversalList returns our children directly to avoid significant overhead.
1952     // However in this case we need to take the responsibility for filtering children which
1953     // are relatives of another surface here.
1954     bool skipRelativeZUsers = false;
1955     const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
1956 
1957     size_t i = 0;
1958     for (; i < list.size(); i++) {
1959         const auto& relative = list[i];
1960         if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1961             continue;
1962         }
1963 
1964         if (relative->getZ(stateSet) >= 0) {
1965             break;
1966         }
1967         relative->traverseInZOrder(stateSet, visitor);
1968     }
1969 
1970     visitor(this);
1971     for (; i < list.size(); i++) {
1972         const auto& relative = list[i];
1973 
1974         if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1975             continue;
1976         }
1977         relative->traverseInZOrder(stateSet, visitor);
1978     }
1979 }
1980 
1981 /**
1982  * Positively signed relatives are before 'this' in reverse Z-order.
1983  */
traverseInReverseZOrder(LayerVector::StateSet stateSet,const LayerVector::Visitor & visitor)1984 void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1985                                     const LayerVector::Visitor& visitor) {
1986     // See traverseInZOrder for documentation.
1987     bool skipRelativeZUsers = false;
1988     LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
1989 
1990     int32_t i = 0;
1991     for (i = int32_t(list.size()) - 1; i >= 0; i--) {
1992         const auto& relative = list[i];
1993 
1994         if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1995             continue;
1996         }
1997 
1998         if (relative->getZ(stateSet) < 0) {
1999             break;
2000         }
2001         relative->traverseInReverseZOrder(stateSet, visitor);
2002     }
2003     visitor(this);
2004     for (; i >= 0; i--) {
2005         const auto& relative = list[i];
2006 
2007         if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
2008             continue;
2009         }
2010 
2011         relative->traverseInReverseZOrder(stateSet, visitor);
2012     }
2013 }
2014 
traverse(LayerVector::StateSet state,const LayerVector::Visitor & visitor)2015 void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
2016     visitor(this);
2017     const LayerVector& children =
2018             state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
2019     for (const sp<Layer>& child : children) {
2020         child->traverse(state, visitor);
2021     }
2022 }
2023 
makeChildrenTraversalList(LayerVector::StateSet stateSet,const std::vector<Layer * > & layersInTree)2024 LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
2025                                              const std::vector<Layer*>& layersInTree) {
2026     LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2027                         "makeTraversalList received invalid stateSet");
2028     const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2029     const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2030     const State& state = useDrawing ? mDrawingState : mCurrentState;
2031 
2032     LayerVector traverse(stateSet);
2033     for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2034         sp<Layer> strongRelative = weakRelative.promote();
2035         // Only add relative layers that are also descendents of the top most parent of the tree.
2036         // If a relative layer is not a descendent, then it should be ignored.
2037         if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
2038             traverse.add(strongRelative);
2039         }
2040     }
2041 
2042     for (const sp<Layer>& child : children) {
2043         const State& childState = useDrawing ? child->mDrawingState : child->mCurrentState;
2044         // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
2045         // descendent of the top most parent of the tree. If it's not a descendent, then just add
2046         // the child here since it won't be added later as a relative.
2047         if (std::binary_search(layersInTree.begin(), layersInTree.end(),
2048                                childState.zOrderRelativeOf.promote().get())) {
2049             continue;
2050         }
2051         traverse.add(child);
2052     }
2053 
2054     return traverse;
2055 }
2056 
traverseChildrenInZOrderInner(const std::vector<Layer * > & layersInTree,LayerVector::StateSet stateSet,const LayerVector::Visitor & visitor)2057 void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
2058                                           LayerVector::StateSet stateSet,
2059                                           const LayerVector::Visitor& visitor) {
2060     const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
2061 
2062     size_t i = 0;
2063     for (; i < list.size(); i++) {
2064         const auto& relative = list[i];
2065         if (relative->getZ(stateSet) >= 0) {
2066             break;
2067         }
2068         relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
2069     }
2070 
2071     visitor(this);
2072     for (; i < list.size(); i++) {
2073         const auto& relative = list[i];
2074         relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
2075     }
2076 }
2077 
getLayersInTree(LayerVector::StateSet stateSet)2078 std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
2079     const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2080     const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2081 
2082     std::vector<Layer*> layersInTree = {this};
2083     for (size_t i = 0; i < children.size(); i++) {
2084         const auto& child = children[i];
2085         std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
2086         layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
2087     }
2088 
2089     return layersInTree;
2090 }
2091 
traverseChildrenInZOrder(LayerVector::StateSet stateSet,const LayerVector::Visitor & visitor)2092 void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
2093                                      const LayerVector::Visitor& visitor) {
2094     std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
2095     std::sort(layersInTree.begin(), layersInTree.end());
2096     traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
2097 }
2098 
getTransform() const2099 ui::Transform Layer::getTransform() const {
2100     return mEffectiveTransform;
2101 }
2102 
getAlpha() const2103 half Layer::getAlpha() const {
2104     const auto& p = mDrawingParent.promote();
2105 
2106     half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2107     return parentAlpha * getDrawingState().color.a;
2108 }
2109 
getFixedTransformHint() const2110 ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
2111     ui::Transform::RotationFlags fixedTransformHint = mCurrentState.fixedTransformHint;
2112     if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2113         return fixedTransformHint;
2114     }
2115     const auto& p = mCurrentParent.promote();
2116     if (!p) return fixedTransformHint;
2117     return p->getFixedTransformHint();
2118 }
2119 
getColor() const2120 half4 Layer::getColor() const {
2121     const half4 color(getDrawingState().color);
2122     return half4(color.r, color.g, color.b, getAlpha());
2123 }
2124 
getBackgroundBlurRadius() const2125 int32_t Layer::getBackgroundBlurRadius() const {
2126     return getDrawingState().backgroundBlurRadius;
2127 }
2128 
getRoundedCornerState() const2129 Layer::RoundedCornerState Layer::getRoundedCornerState() const {
2130     const auto& p = mDrawingParent.promote();
2131     if (p != nullptr) {
2132         RoundedCornerState parentState = p->getRoundedCornerState();
2133         if (parentState.radius > 0) {
2134             ui::Transform t = getActiveTransform(getDrawingState());
2135             t = t.inverse();
2136             parentState.cropRect = t.transform(parentState.cropRect);
2137             // The rounded corners shader only accepts 1 corner radius for performance reasons,
2138             // but a transform matrix can define horizontal and vertical scales.
2139             // Let's take the average between both of them and pass into the shader, practically we
2140             // never do this type of transformation on windows anyway.
2141             auto scaleX = sqrtf(t[0][0] * t[0][0] + t[0][1] * t[0][1]);
2142             auto scaleY = sqrtf(t[1][0] * t[1][0] + t[1][1] * t[1][1]);
2143             parentState.radius *= (scaleX + scaleY) / 2.0f;
2144             return parentState;
2145         }
2146     }
2147     const float radius = getDrawingState().cornerRadius;
2148     return radius > 0 && getCrop(getDrawingState()).isValid()
2149             ? RoundedCornerState(getCrop(getDrawingState()).toFloatRect(), radius)
2150             : RoundedCornerState();
2151 }
2152 
getShadowSettings(const Rect & viewport) const2153 renderengine::ShadowSettings Layer::getShadowSettings(const Rect& viewport) const {
2154     renderengine::ShadowSettings state = mFlinger->mDrawingState.globalShadowSettings;
2155 
2156     // Shift the spot light x-position to the middle of the display and then
2157     // offset it by casting layer's screen pos.
2158     state.lightPos.x = (viewport.width() / 2.f) - mScreenBounds.left;
2159     state.lightPos.y -= mScreenBounds.top;
2160 
2161     state.length = mEffectiveShadowRadius;
2162     return state;
2163 }
2164 
commitChildList()2165 void Layer::commitChildList() {
2166     for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2167         const auto& child = mCurrentChildren[i];
2168         child->commitChildList();
2169     }
2170     mDrawingChildren = mCurrentChildren;
2171     mDrawingParent = mCurrentParent;
2172 }
2173 
extractLayerFromBinder(const wp<IBinder> & weakBinderHandle)2174 static wp<Layer> extractLayerFromBinder(const wp<IBinder>& weakBinderHandle) {
2175     if (weakBinderHandle == nullptr) {
2176         return nullptr;
2177     }
2178     sp<IBinder> binderHandle = weakBinderHandle.promote();
2179     if (binderHandle == nullptr) {
2180         return nullptr;
2181     }
2182     sp<Layer::Handle> handle = static_cast<Layer::Handle*>(binderHandle.get());
2183     if (handle == nullptr) {
2184         return nullptr;
2185     }
2186     return handle->owner;
2187 }
2188 
setInputInfo(const InputWindowInfo & info)2189 void Layer::setInputInfo(const InputWindowInfo& info) {
2190     mCurrentState.inputInfo = info;
2191     mCurrentState.touchableRegionCrop = extractLayerFromBinder(info.touchableRegionCropHandle);
2192     mCurrentState.modified = true;
2193     mCurrentState.inputInfoChanged = true;
2194     setTransactionFlags(eTransactionNeeded);
2195 }
2196 
writeToProto(LayersProto & layersProto,uint32_t traceFlags,const DisplayDevice * display) const2197 LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags,
2198                                 const DisplayDevice* display) const {
2199     LayerProto* layerProto = layersProto.add_layers();
2200     writeToProtoDrawingState(layerProto, traceFlags, display);
2201     writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2202 
2203     if (traceFlags & SurfaceTracing::TRACE_COMPOSITION) {
2204         // Only populate for the primary display.
2205         if (display) {
2206             const Hwc2::IComposerClient::Composition compositionType = getCompositionType(*display);
2207             layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
2208         }
2209     }
2210 
2211     for (const sp<Layer>& layer : mDrawingChildren) {
2212         layer->writeToProto(layersProto, traceFlags, display);
2213     }
2214 
2215     return layerProto;
2216 }
2217 
writeToProtoDrawingState(LayerProto * layerInfo,uint32_t traceFlags,const DisplayDevice * display) const2218 void Layer::writeToProtoDrawingState(LayerProto* layerInfo, uint32_t traceFlags,
2219                                      const DisplayDevice* display) const {
2220     ui::Transform transform = getTransform();
2221 
2222     if (traceFlags & SurfaceTracing::TRACE_CRITICAL) {
2223         for (const auto& pendingState : mPendingStatesSnapshot) {
2224             auto barrierLayer = pendingState.barrierLayer_legacy.promote();
2225             if (barrierLayer != nullptr) {
2226                 BarrierLayerProto* barrierLayerProto = layerInfo->add_barrier_layer();
2227                 barrierLayerProto->set_id(barrierLayer->sequence);
2228                 barrierLayerProto->set_frame_number(pendingState.frameNumber_legacy);
2229             }
2230         }
2231 
2232         auto buffer = getBuffer();
2233         if (buffer != nullptr) {
2234             LayerProtoHelper::writeToProto(buffer,
2235                                            [&]() { return layerInfo->mutable_active_buffer(); });
2236             LayerProtoHelper::writeToProto(ui::Transform(getBufferTransform()),
2237                                            layerInfo->mutable_buffer_transform());
2238         }
2239         layerInfo->set_invalidate(contentDirty);
2240         layerInfo->set_is_protected(isProtected());
2241         layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2242         layerInfo->set_queued_frames(getQueuedFrameCount());
2243         layerInfo->set_refresh_pending(isBufferLatched());
2244         layerInfo->set_curr_frame(mCurrentFrameNumber);
2245         layerInfo->set_effective_scaling_mode(getEffectiveScalingMode());
2246 
2247         layerInfo->set_corner_radius(getRoundedCornerState().radius);
2248         LayerProtoHelper::writeToProto(transform, layerInfo->mutable_transform());
2249         LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2250                                                [&]() { return layerInfo->mutable_position(); });
2251         LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
2252         if (traceFlags & SurfaceTracing::TRACE_COMPOSITION) {
2253             LayerProtoHelper::writeToProto(getVisibleRegion(display),
2254                                            [&]() { return layerInfo->mutable_visible_region(); });
2255         }
2256         LayerProtoHelper::writeToProto(surfaceDamageRegion,
2257                                        [&]() { return layerInfo->mutable_damage_region(); });
2258 
2259         if (hasColorTransform()) {
2260             LayerProtoHelper::writeToProto(getColorTransform(),
2261                                            layerInfo->mutable_color_transform());
2262         }
2263     }
2264 
2265     LayerProtoHelper::writeToProto(mSourceBounds,
2266                                    [&]() { return layerInfo->mutable_source_bounds(); });
2267     LayerProtoHelper::writeToProto(mScreenBounds,
2268                                    [&]() { return layerInfo->mutable_screen_bounds(); });
2269     LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2270                                    [&]() { return layerInfo->mutable_corner_radius_crop(); });
2271     layerInfo->set_shadow_radius(mEffectiveShadowRadius);
2272 }
2273 
writeToProtoCommonState(LayerProto * layerInfo,LayerVector::StateSet stateSet,uint32_t traceFlags) const2274 void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
2275                                     uint32_t traceFlags) const {
2276     const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2277     const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2278     const State& state = useDrawing ? mDrawingState : mCurrentState;
2279 
2280     ui::Transform requestedTransform = state.active_legacy.transform;
2281 
2282     if (traceFlags & SurfaceTracing::TRACE_CRITICAL) {
2283         layerInfo->set_id(sequence);
2284         layerInfo->set_name(getName().c_str());
2285         layerInfo->set_type(getType());
2286 
2287         for (const auto& child : children) {
2288             layerInfo->add_children(child->sequence);
2289         }
2290 
2291         for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2292             sp<Layer> strongRelative = weakRelative.promote();
2293             if (strongRelative != nullptr) {
2294                 layerInfo->add_relatives(strongRelative->sequence);
2295             }
2296         }
2297 
2298         LayerProtoHelper::writeToProto(state.activeTransparentRegion_legacy,
2299                                        [&]() { return layerInfo->mutable_transparent_region(); });
2300 
2301         layerInfo->set_layer_stack(getLayerStack());
2302         layerInfo->set_z(state.z);
2303 
2304         LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(),
2305                                                [&]() {
2306                                                    return layerInfo->mutable_requested_position();
2307                                                });
2308 
2309         LayerProtoHelper::writeSizeToProto(state.active_legacy.w, state.active_legacy.h,
2310                                            [&]() { return layerInfo->mutable_size(); });
2311 
2312         LayerProtoHelper::writeToProto(state.crop_legacy,
2313                                        [&]() { return layerInfo->mutable_crop(); });
2314 
2315         layerInfo->set_is_opaque(isOpaque(state));
2316 
2317 
2318         layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2319         LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2320         LayerProtoHelper::writeToProto(state.color,
2321                                        [&]() { return layerInfo->mutable_requested_color(); });
2322         layerInfo->set_flags(state.flags);
2323 
2324         LayerProtoHelper::writeToProto(requestedTransform,
2325                                        layerInfo->mutable_requested_transform());
2326 
2327         auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2328         if (parent != nullptr) {
2329             layerInfo->set_parent(parent->sequence);
2330         } else {
2331             layerInfo->set_parent(-1);
2332         }
2333 
2334         auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2335         if (zOrderRelativeOf != nullptr) {
2336             layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2337         } else {
2338             layerInfo->set_z_order_relative_of(-1);
2339         }
2340 
2341         layerInfo->set_is_relative_of(state.isRelativeOf);
2342     }
2343 
2344     if (traceFlags & SurfaceTracing::TRACE_INPUT) {
2345         LayerProtoHelper::writeToProto(state.inputInfo, state.touchableRegionCrop,
2346                                        [&]() { return layerInfo->mutable_input_window_info(); });
2347     }
2348 
2349     if (traceFlags & SurfaceTracing::TRACE_EXTRA) {
2350         auto protoMap = layerInfo->mutable_metadata();
2351         for (const auto& entry : state.metadata.mMap) {
2352             (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2353         }
2354     }
2355 }
2356 
isRemovedFromCurrentState() const2357 bool Layer::isRemovedFromCurrentState() const  {
2358     return mRemovedFromCurrentState;
2359 }
2360 
fillInputInfo()2361 InputWindowInfo Layer::fillInputInfo() {
2362     if (!hasInputInfo()) {
2363         mDrawingState.inputInfo.name = getName();
2364         mDrawingState.inputInfo.ownerUid = mCallingUid;
2365         mDrawingState.inputInfo.ownerPid = mCallingPid;
2366         mDrawingState.inputInfo.inputFeatures =
2367             InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
2368         mDrawingState.inputInfo.layoutParamsFlags = InputWindowInfo::FLAG_NOT_TOUCH_MODAL;
2369         mDrawingState.inputInfo.displayId = getLayerStack();
2370     }
2371 
2372     InputWindowInfo info = mDrawingState.inputInfo;
2373     info.id = sequence;
2374 
2375     if (info.displayId == ADISPLAY_ID_NONE) {
2376         info.displayId = getLayerStack();
2377     }
2378 
2379     ui::Transform t = getTransform();
2380     const float xScale = t.sx();
2381     const float yScale = t.sy();
2382     int32_t xSurfaceInset = info.surfaceInset;
2383     int32_t ySurfaceInset = info.surfaceInset;
2384     if (xScale != 1.0f || yScale != 1.0f) {
2385         info.windowXScale *= (xScale != 0.0f) ? 1.0f / xScale : 0.0f;
2386         info.windowYScale *= (yScale != 0.0f) ? 1.0f / yScale : 0.0f;
2387         info.touchableRegion.scaleSelf(xScale, yScale);
2388         xSurfaceInset = std::round(xSurfaceInset * xScale);
2389         ySurfaceInset = std::round(ySurfaceInset * yScale);
2390     }
2391 
2392     // Transform layer size to screen space and inset it by surface insets.
2393     // If this is a portal window, set the touchableRegion to the layerBounds.
2394     Rect layerBounds = info.portalToDisplayId == ADISPLAY_ID_NONE
2395             ? getBufferSize(getDrawingState())
2396             : info.touchableRegion.getBounds();
2397     if (!layerBounds.isValid()) {
2398         layerBounds = getCroppedBufferSize(getDrawingState());
2399     }
2400     layerBounds = t.transform(layerBounds);
2401 
2402     // clamp inset to layer bounds
2403     xSurfaceInset = (xSurfaceInset >= 0) ? std::min(xSurfaceInset, layerBounds.getWidth() / 2) : 0;
2404     ySurfaceInset = (ySurfaceInset >= 0) ? std::min(ySurfaceInset, layerBounds.getHeight() / 2) : 0;
2405 
2406     layerBounds.inset(xSurfaceInset, ySurfaceInset, xSurfaceInset, ySurfaceInset);
2407 
2408     // Input coordinate should match the layer bounds.
2409     info.frameLeft = layerBounds.left;
2410     info.frameTop = layerBounds.top;
2411     info.frameRight = layerBounds.right;
2412     info.frameBottom = layerBounds.bottom;
2413 
2414     // Position the touchable region relative to frame screen location and restrict it to frame
2415     // bounds.
2416     info.touchableRegion = info.touchableRegion.translate(info.frameLeft, info.frameTop);
2417     // For compatibility reasons we let layers which can receive input
2418     // receive input before they have actually submitted a buffer. Because
2419     // of this we use canReceiveInput instead of isVisible to check the
2420     // policy-visibility, ignoring the buffer state. However for layers with
2421     // hasInputInfo()==false we can use the real visibility state.
2422     // We are just using these layers for occlusion detection in
2423     // InputDispatcher, and obviously if they aren't visible they can't occlude
2424     // anything.
2425     info.visible = hasInputInfo() ? canReceiveInput() : isVisible();
2426 
2427     auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2428     if (info.replaceTouchableRegionWithCrop) {
2429         if (cropLayer == nullptr) {
2430             info.touchableRegion = Region(Rect{mScreenBounds});
2431         } else {
2432             info.touchableRegion = Region(Rect{cropLayer->mScreenBounds});
2433         }
2434     } else if (cropLayer != nullptr) {
2435         info.touchableRegion = info.touchableRegion.intersect(Rect{cropLayer->mScreenBounds});
2436     }
2437 
2438     // If the layer is a clone, we need to crop the input region to cloned root to prevent
2439     // touches from going outside the cloned area.
2440     if (isClone()) {
2441         sp<Layer> clonedRoot = getClonedRoot();
2442         if (clonedRoot != nullptr) {
2443             Rect rect(clonedRoot->mScreenBounds);
2444             info.touchableRegion = info.touchableRegion.intersect(rect);
2445         }
2446     }
2447 
2448     return info;
2449 }
2450 
getClonedRoot()2451 sp<Layer> Layer::getClonedRoot() {
2452     if (mClonedChild != nullptr) {
2453         return this;
2454     }
2455     if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
2456         return nullptr;
2457     }
2458     return mDrawingParent.promote()->getClonedRoot();
2459 }
2460 
hasInputInfo() const2461 bool Layer::hasInputInfo() const {
2462     return mDrawingState.inputInfo.token != nullptr;
2463 }
2464 
canReceiveInput() const2465 bool Layer::canReceiveInput() const {
2466     return !isHiddenByPolicy();
2467 }
2468 
findOutputLayerForDisplay(const DisplayDevice * display) const2469 compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
2470         const DisplayDevice* display) const {
2471     if (!display) return nullptr;
2472     return display->getCompositionDisplay()->getOutputLayerForLayer(getCompositionEngineLayerFE());
2473 }
2474 
getVisibleRegion(const DisplayDevice * display) const2475 Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2476     const auto outputLayer = findOutputLayerForDisplay(display);
2477     return outputLayer ? outputLayer->getState().visibleRegion : Region();
2478 }
2479 
setInitialValuesForClone(const sp<Layer> & clonedFrom)2480 void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
2481     // copy drawing state from cloned layer
2482     mDrawingState = clonedFrom->mDrawingState;
2483     mClonedFrom = clonedFrom;
2484 }
2485 
updateMirrorInfo()2486 void Layer::updateMirrorInfo() {
2487     if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2488         // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2489         // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2490         // that case, we want to delete the reference to the clone since we want it to get
2491         // destroyed. The root, this layer, will still be around since the client can continue
2492         // to hold a reference, but no cloned layers will be displayed.
2493         mClonedChild = nullptr;
2494         return;
2495     }
2496 
2497     std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2498     // If the real layer exists and is in current state, add the clone as a child of the root.
2499     // There's no need to remove from drawingState when the layer is offscreen since currentState is
2500     // copied to drawingState for the root layer. So the clonedChild is always removed from
2501     // drawingState and then needs to be added back each traversal.
2502     if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2503         addChildToDrawing(mClonedChild);
2504     }
2505 
2506     mClonedChild->updateClonedDrawingState(clonedLayersMap);
2507     mClonedChild->updateClonedChildren(this, clonedLayersMap);
2508     mClonedChild->updateClonedRelatives(clonedLayersMap);
2509 }
2510 
updateClonedDrawingState(std::map<sp<Layer>,sp<Layer>> & clonedLayersMap)2511 void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2512     // If the layer the clone was cloned from is alive, copy the content of the drawingState
2513     // to the clone. If the real layer is no longer alive, continue traversing the children
2514     // since we may be able to pull out other children that are still alive.
2515     if (isClonedFromAlive()) {
2516         sp<Layer> clonedFrom = getClonedFrom();
2517         mDrawingState = clonedFrom->mDrawingState;
2518         clonedLayersMap.emplace(clonedFrom, this);
2519     }
2520 
2521     // The clone layer may have children in drawingState since they may have been created and
2522     // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2523     // that already exist, since we can just re-use them.
2524     // The drawingChildren will not get overwritten by the currentChildren since the clones are
2525     // not updated in the regular traversal. They are skipped since the root will lose the
2526     // reference to them when it copies its currentChildren to drawing.
2527     for (sp<Layer>& child : mDrawingChildren) {
2528         child->updateClonedDrawingState(clonedLayersMap);
2529     }
2530 }
2531 
updateClonedChildren(const sp<Layer> & mirrorRoot,std::map<sp<Layer>,sp<Layer>> & clonedLayersMap)2532 void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2533                                  std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2534     mDrawingChildren.clear();
2535 
2536     if (!isClonedFromAlive()) {
2537         return;
2538     }
2539 
2540     sp<Layer> clonedFrom = getClonedFrom();
2541     for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2542         if (child == mirrorRoot) {
2543             // This is to avoid cyclical mirroring.
2544             continue;
2545         }
2546         sp<Layer> clonedChild = clonedLayersMap[child];
2547         if (clonedChild == nullptr) {
2548             clonedChild = child->createClone();
2549             clonedLayersMap[child] = clonedChild;
2550         }
2551         addChildToDrawing(clonedChild);
2552         clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2553     }
2554 }
2555 
updateClonedInputInfo(const std::map<sp<Layer>,sp<Layer>> & clonedLayersMap)2556 void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2557     auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2558     if (cropLayer != nullptr) {
2559         if (clonedLayersMap.count(cropLayer) == 0) {
2560             // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2561             // self as crop layer to avoid going outside bounds.
2562             mDrawingState.touchableRegionCrop = this;
2563         } else {
2564             const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2565             mDrawingState.touchableRegionCrop = clonedCropLayer;
2566         }
2567     }
2568     // Cloned layers shouldn't handle watch outside since their z order is not determined by
2569     // WM or the client.
2570     mDrawingState.inputInfo.layoutParamsFlags &= ~InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH;
2571 }
2572 
updateClonedRelatives(const std::map<sp<Layer>,sp<Layer>> & clonedLayersMap)2573 void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2574     mDrawingState.zOrderRelativeOf = nullptr;
2575     mDrawingState.zOrderRelatives.clear();
2576 
2577     if (!isClonedFromAlive()) {
2578         return;
2579     }
2580 
2581     const sp<Layer>& clonedFrom = getClonedFrom();
2582     for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
2583         const sp<Layer>& relative = relativeWeak.promote();
2584         if (clonedLayersMap.count(relative) > 0) {
2585             auto& clonedRelative = clonedLayersMap.at(relative);
2586             mDrawingState.zOrderRelatives.add(clonedRelative);
2587         }
2588     }
2589 
2590     // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2591     // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2592     // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2593     // still traverse the children, but the layer with the missing relativeOf will not be shown
2594     // on screen.
2595     const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2596     if (clonedLayersMap.count(relativeOf) > 0) {
2597         const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
2598         mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2599     }
2600 
2601     updateClonedInputInfo(clonedLayersMap);
2602 
2603     for (sp<Layer>& child : mDrawingChildren) {
2604         child->updateClonedRelatives(clonedLayersMap);
2605     }
2606 }
2607 
addChildToDrawing(const sp<Layer> & layer)2608 void Layer::addChildToDrawing(const sp<Layer>& layer) {
2609     mDrawingChildren.add(layer);
2610     layer->mDrawingParent = this;
2611 }
2612 
convertCompatibility(int8_t compatibility)2613 Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2614     switch (compatibility) {
2615         case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2616             return FrameRateCompatibility::Default;
2617         case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2618             return FrameRateCompatibility::ExactOrMultiple;
2619         default:
2620             LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2621             return FrameRateCompatibility::Default;
2622     }
2623 }
2624 
2625 // ---------------------------------------------------------------------------
2626 
2627 }; // namespace android
2628 
2629 #if defined(__gl_h_)
2630 #error "don't include gl/gl.h in this file"
2631 #endif
2632 
2633 #if defined(__gl2_h_)
2634 #error "don't include gl2/gl2.h in this file"
2635 #endif
2636 
2637 // TODO(b/129481165): remove the #pragma below and fix conversion issues
2638 #pragma clang diagnostic pop // ignored "-Wconversion"
2639