• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/properties.h>
29 #include <android-base/stringprintf.h>
30 #include <android/native_window.h>
31 #include <binder/IPCThreadState.h>
32 #include <compositionengine/Display.h>
33 #include <compositionengine/LayerFECompositionState.h>
34 #include <compositionengine/OutputLayer.h>
35 #include <compositionengine/impl/OutputLayerCompositionState.h>
36 #include <cutils/compiler.h>
37 #include <cutils/native_handle.h>
38 #include <cutils/properties.h>
39 #include <ftl/enum.h>
40 #include <ftl/fake_guard.h>
41 #include <gui/BufferItem.h>
42 #include <gui/LayerDebugInfo.h>
43 #include <gui/Surface.h>
44 #include <math.h>
45 #include <private/android_filesystem_config.h>
46 #include <renderengine/RenderEngine.h>
47 #include <stdint.h>
48 #include <stdlib.h>
49 #include <sys/types.h>
50 #include <system/graphics-base-v1.0.h>
51 #include <ui/DataspaceUtils.h>
52 #include <ui/DebugUtils.h>
53 #include <ui/GraphicBuffer.h>
54 #include <ui/PixelFormat.h>
55 #include <utils/Errors.h>
56 #include <utils/Log.h>
57 #include <utils/NativeHandle.h>
58 #include <utils/StopWatch.h>
59 #include <utils/Trace.h>
60 
61 #include <algorithm>
62 #include <mutex>
63 #include <sstream>
64 
65 #include "BufferLayer.h"
66 #include "Colorizer.h"
67 #include "DisplayDevice.h"
68 #include "DisplayHardware/HWComposer.h"
69 #include "EffectLayer.h"
70 #include "FrameTimeline.h"
71 #include "FrameTracer/FrameTracer.h"
72 #include "LayerProtoHelper.h"
73 #include "LayerRejecter.h"
74 #include "MonitoredProducer.h"
75 #include "SurfaceFlinger.h"
76 #include "TimeStats/TimeStats.h"
77 #include "TunnelModeEnabledReporter.h"
78 
79 #define DEBUG_RESIZE 0
80 
81 namespace android {
82 namespace {
83 constexpr int kDumpTableRowLength = 159;
84 const ui::Transform kIdentityTransform;
85 } // namespace
86 
87 using namespace ftl::flag_operators;
88 
89 using base::StringAppendF;
90 using gui::WindowInfo;
91 
92 using PresentState = frametimeline::SurfaceFrame::PresentState;
93 
94 std::atomic<int32_t> Layer::sSequence{1};
95 
Layer(const LayerCreationArgs & args)96 Layer::Layer(const LayerCreationArgs& args)
97       : sequence(args.sequence.value_or(sSequence++)),
98         mFlinger(args.flinger),
99         mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
100         mClientRef(args.client),
101         mWindowType(static_cast<WindowInfo::Type>(args.metadata.getInt32(METADATA_WINDOW_TYPE, 0))),
102         mLayerCreationFlags(args.flags) {
103     uint32_t layerFlags = 0;
104     if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
105     if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
106     if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
107     if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
108         layerFlags |= layer_state_t::eLayerSkipScreenshot;
109     if (args.sequence) {
110         sSequence = *args.sequence + 1;
111     }
112     mDrawingState.flags = layerFlags;
113     mDrawingState.active_legacy.transform.set(0, 0);
114     mDrawingState.crop.makeInvalid();
115     mDrawingState.requestedCrop = mDrawingState.crop;
116     mDrawingState.z = 0;
117     mDrawingState.color.a = 1.0f;
118     mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
119     mDrawingState.sequence = 0;
120     mDrawingState.requested_legacy = mDrawingState.active_legacy;
121     mDrawingState.width = UINT32_MAX;
122     mDrawingState.height = UINT32_MAX;
123     mDrawingState.transform.set(0, 0);
124     mDrawingState.frameNumber = 0;
125     mDrawingState.bufferTransform = 0;
126     mDrawingState.transformToDisplayInverse = false;
127     mDrawingState.crop.makeInvalid();
128     mDrawingState.acquireFence = sp<Fence>::make(-1);
129     mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
130     mDrawingState.dataspace = ui::Dataspace::UNKNOWN;
131     mDrawingState.hdrMetadata.validTypes = 0;
132     mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
133     mDrawingState.cornerRadius = 0.0f;
134     mDrawingState.backgroundBlurRadius = 0;
135     mDrawingState.api = -1;
136     mDrawingState.hasColorTransform = false;
137     mDrawingState.colorSpaceAgnostic = false;
138     mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
139     mDrawingState.metadata = args.metadata;
140     mDrawingState.shadowRadius = 0.f;
141     mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
142     mDrawingState.frameTimelineInfo = {};
143     mDrawingState.postTime = -1;
144     mDrawingState.destinationFrame.makeInvalid();
145     mDrawingState.isTrustedOverlay = false;
146     mDrawingState.dropInputMode = gui::DropInputMode::NONE;
147     mDrawingState.dimmingEnabled = true;
148 
149     if (args.flags & ISurfaceComposerClient::eNoColorFill) {
150         // Set an invalid color so there is no color fill.
151         mDrawingState.color.r = -1.0_hf;
152         mDrawingState.color.g = -1.0_hf;
153         mDrawingState.color.b = -1.0_hf;
154     }
155     CompositorTiming compositorTiming;
156     args.flinger->getCompositorTiming(&compositorTiming);
157     mFrameTracker.setDisplayRefreshPeriod(compositorTiming.interval);
158 
159     mCallingPid = args.callingPid;
160     mCallingUid = args.callingUid;
161 
162     if (mCallingUid == AID_GRAPHICS || mCallingUid == AID_SYSTEM) {
163         // If the system didn't send an ownerUid, use the callingUid for the ownerUid.
164         mOwnerUid = args.metadata.getInt32(METADATA_OWNER_UID, mCallingUid);
165         mOwnerPid = args.metadata.getInt32(METADATA_OWNER_PID, mCallingPid);
166     } else {
167         // A create layer request from a non system request cannot specify the owner uid
168         mOwnerUid = mCallingUid;
169         mOwnerPid = mCallingPid;
170     }
171 }
172 
onFirstRef()173 void Layer::onFirstRef() {
174     mFlinger->onLayerFirstRef(this);
175 }
176 
~Layer()177 Layer::~Layer() {
178     sp<Client> c(mClientRef.promote());
179     if (c != 0) {
180         c->detachLayer(this);
181     }
182 
183     mFrameTracker.logAndResetStats(mName);
184     mFlinger->onLayerDestroyed(this);
185 
186     if (mDrawingState.sidebandStream != nullptr) {
187         mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
188     }
189     if (mHadClonedChild) {
190         mFlinger->mNumClones--;
191     }
192 }
193 
LayerCreationArgs(SurfaceFlinger * flinger,sp<Client> client,std::string name,uint32_t flags,LayerMetadata metadata)194 LayerCreationArgs::LayerCreationArgs(SurfaceFlinger* flinger, sp<Client> client, std::string name,
195                                      uint32_t flags, LayerMetadata metadata)
196       : flinger(flinger),
197         client(std::move(client)),
198         name(std::move(name)),
199         flags(flags),
200         metadata(std::move(metadata)) {
201     IPCThreadState* ipc = IPCThreadState::self();
202     callingPid = ipc->getCallingPid();
203     callingUid = ipc->getCallingUid();
204 }
205 
206 // ---------------------------------------------------------------------------
207 // callbacks
208 // ---------------------------------------------------------------------------
209 
210 /*
211  * onLayerDisplayed is only meaningful for BufferLayer, but, is called through
212  * Layer.  So, the implementation is done in BufferLayer.  When called on a
213  * EffectLayer object, it's essentially a NOP.
214  */
onLayerDisplayed(ftl::SharedFuture<FenceResult>)215 void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult>) {}
216 
removeRelativeZ(const std::vector<Layer * > & layersInTree)217 void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
218     if (mDrawingState.zOrderRelativeOf == nullptr) {
219         return;
220     }
221 
222     sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
223     if (strongRelative == nullptr) {
224         setZOrderRelativeOf(nullptr);
225         return;
226     }
227 
228     if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
229         strongRelative->removeZOrderRelative(this);
230         mFlinger->setTransactionFlags(eTraversalNeeded);
231         setZOrderRelativeOf(nullptr);
232     }
233 }
234 
removeFromCurrentState()235 void Layer::removeFromCurrentState() {
236     if (!mRemovedFromDrawingState) {
237         mRemovedFromDrawingState = true;
238         mFlinger->mScheduler->deregisterLayer(this);
239     }
240 
241     mFlinger->markLayerPendingRemovalLocked(this);
242 }
243 
getRootLayer()244 sp<Layer> Layer::getRootLayer() {
245     sp<Layer> parent = getParent();
246     if (parent == nullptr) {
247         return this;
248     }
249     return parent->getRootLayer();
250 }
251 
onRemovedFromCurrentState()252 void Layer::onRemovedFromCurrentState() {
253     // Use the root layer since we want to maintain the hierarchy for the entire subtree.
254     auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
255     std::sort(layersInTree.begin(), layersInTree.end());
256 
257     traverse(LayerVector::StateSet::Current, [&](Layer* layer) {
258         layer->removeFromCurrentState();
259         layer->removeRelativeZ(layersInTree);
260     });
261 }
262 
addToCurrentState()263 void Layer::addToCurrentState() {
264     if (mRemovedFromDrawingState) {
265         mRemovedFromDrawingState = false;
266         mFlinger->mScheduler->registerLayer(this);
267         mFlinger->removeFromOffscreenLayers(this);
268     }
269 
270     for (const auto& child : mCurrentChildren) {
271         child->addToCurrentState();
272     }
273 }
274 
275 // ---------------------------------------------------------------------------
276 // set-up
277 // ---------------------------------------------------------------------------
278 
getPremultipledAlpha() const279 bool Layer::getPremultipledAlpha() const {
280     return mPremultipliedAlpha;
281 }
282 
getHandle()283 sp<IBinder> Layer::getHandle() {
284     Mutex::Autolock _l(mLock);
285     if (mGetHandleCalled) {
286         ALOGE("Get handle called twice" );
287         return nullptr;
288     }
289     mGetHandleCalled = true;
290     return new Handle(mFlinger, this);
291 }
292 
293 // ---------------------------------------------------------------------------
294 // h/w composer set-up
295 // ---------------------------------------------------------------------------
296 
reduce(const Rect & win,const Region & exclude)297 static Rect reduce(const Rect& win, const Region& exclude) {
298     if (CC_LIKELY(exclude.isEmpty())) {
299         return win;
300     }
301     if (exclude.isRect()) {
302         return win.reduce(exclude.getBounds());
303     }
304     return Region(win).subtract(exclude).getBounds();
305 }
306 
reduce(const FloatRect & win,const Region & exclude)307 static FloatRect reduce(const FloatRect& win, const Region& exclude) {
308     if (CC_LIKELY(exclude.isEmpty())) {
309         return win;
310     }
311     // Convert through Rect (by rounding) for lack of FloatRegion
312     return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
313 }
314 
getScreenBounds(bool reduceTransparentRegion) const315 Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
316     if (!reduceTransparentRegion) {
317         return Rect{mScreenBounds};
318     }
319 
320     FloatRect bounds = getBounds();
321     ui::Transform t = getTransform();
322     // Transform to screen space.
323     bounds = t.transform(bounds);
324     return Rect{bounds};
325 }
326 
getBounds() const327 FloatRect Layer::getBounds() const {
328     const State& s(getDrawingState());
329     return getBounds(getActiveTransparentRegion(s));
330 }
331 
getBounds(const Region & activeTransparentRegion) const332 FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
333     // Subtract the transparent region and snap to the bounds.
334     return reduce(mBounds, activeTransparentRegion);
335 }
336 
computeBounds(FloatRect parentBounds,ui::Transform parentTransform,float parentShadowRadius)337 void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
338                           float parentShadowRadius) {
339     const State& s(getDrawingState());
340 
341     // Calculate effective layer transform
342     mEffectiveTransform = parentTransform * getActiveTransform(s);
343 
344     if (CC_UNLIKELY(!isTransformValid())) {
345         ALOGW("Stop computing bounds for %s because it has invalid transformation.",
346               getDebugName());
347         return;
348     }
349 
350     // Transform parent bounds to layer space
351     parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
352 
353     // Calculate source bounds
354     mSourceBounds = computeSourceBounds(parentBounds);
355 
356     // Calculate bounds by croping diplay frame with layer crop and parent bounds
357     FloatRect bounds = mSourceBounds;
358     const Rect layerCrop = getCrop(s);
359     if (!layerCrop.isEmpty()) {
360         bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
361     }
362     bounds = bounds.intersect(parentBounds);
363 
364     mBounds = bounds;
365     mScreenBounds = mEffectiveTransform.transform(mBounds);
366 
367     // Use the layer's own shadow radius if set. Otherwise get the radius from
368     // parent.
369     if (s.shadowRadius > 0.f) {
370         mEffectiveShadowRadius = s.shadowRadius;
371     } else {
372         mEffectiveShadowRadius = parentShadowRadius;
373     }
374 
375     // Shadow radius is passed down to only one layer so if the layer can draw shadows,
376     // don't pass it to its children.
377     const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
378 
379     for (const sp<Layer>& child : mDrawingChildren) {
380         child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
381     }
382 }
383 
getCroppedBufferSize(const State & s) const384 Rect Layer::getCroppedBufferSize(const State& s) const {
385     Rect size = getBufferSize(s);
386     Rect crop = getCrop(s);
387     if (!crop.isEmpty() && size.isValid()) {
388         size.intersect(crop, &size);
389     } else if (!crop.isEmpty()) {
390         size = crop;
391     }
392     return size;
393 }
394 
setupRoundedCornersCropCoordinates(Rect win,const FloatRect & roundedCornersCrop) const395 void Layer::setupRoundedCornersCropCoordinates(Rect win,
396                                                const FloatRect& roundedCornersCrop) const {
397     // Translate win by the rounded corners rect coordinates, to have all values in
398     // layer coordinate space.
399     win.left -= roundedCornersCrop.left;
400     win.right -= roundedCornersCrop.left;
401     win.top -= roundedCornersCrop.top;
402     win.bottom -= roundedCornersCrop.top;
403 }
404 
prepareBasicGeometryCompositionState()405 void Layer::prepareBasicGeometryCompositionState() {
406     const auto& drawingState{getDrawingState()};
407     const auto alpha = static_cast<float>(getAlpha());
408     const bool opaque = isOpaque(drawingState);
409     const bool usesRoundedCorners = hasRoundedCorners();
410 
411     auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
412     if (!opaque || alpha != 1.0f) {
413         blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
414                                         : Hwc2::IComposerClient::BlendMode::COVERAGE;
415     }
416 
417     auto* compositionState = editCompositionState();
418     compositionState->outputFilter = getOutputFilter();
419     compositionState->isVisible = isVisible();
420     compositionState->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
421     compositionState->shadowRadius = mEffectiveShadowRadius;
422 
423     compositionState->contentDirty = contentDirty;
424     contentDirty = false;
425 
426     compositionState->geomLayerBounds = mBounds;
427     compositionState->geomLayerTransform = getTransform();
428     compositionState->geomInverseLayerTransform = compositionState->geomLayerTransform.inverse();
429     compositionState->transparentRegionHint = getActiveTransparentRegion(drawingState);
430 
431     compositionState->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
432     compositionState->alpha = alpha;
433     compositionState->backgroundBlurRadius = drawingState.backgroundBlurRadius;
434     compositionState->blurRegions = drawingState.blurRegions;
435     compositionState->stretchEffect = getStretchEffect();
436 }
437 
prepareGeometryCompositionState()438 void Layer::prepareGeometryCompositionState() {
439     const auto& drawingState{getDrawingState()};
440     auto* compositionState = editCompositionState();
441 
442     compositionState->geomBufferSize = getBufferSize(drawingState);
443     compositionState->geomContentCrop = getBufferCrop();
444     compositionState->geomCrop = getCrop(drawingState);
445     compositionState->geomBufferTransform = getBufferTransform();
446     compositionState->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
447     compositionState->geomUsesSourceCrop = usesSourceCrop();
448     compositionState->isSecure = isSecure();
449 
450     compositionState->metadata.clear();
451     const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
452     for (const auto& [key, mandatory] : supportedMetadata) {
453         const auto& genericLayerMetadataCompatibilityMap =
454                 mFlinger->getGenericLayerMetadataKeyMap();
455         auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
456         if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
457             continue;
458         }
459         const uint32_t id = compatIter->second;
460 
461         auto it = drawingState.metadata.mMap.find(id);
462         if (it == std::end(drawingState.metadata.mMap)) {
463             continue;
464         }
465 
466         compositionState->metadata
467                 .emplace(key, compositionengine::GenericLayerMetadataEntry{mandatory, it->second});
468     }
469 }
470 
preparePerFrameCompositionState()471 void Layer::preparePerFrameCompositionState() {
472     const auto& drawingState{getDrawingState()};
473     auto* compositionState = editCompositionState();
474 
475     compositionState->forceClientComposition = false;
476 
477     compositionState->isColorspaceAgnostic = isColorSpaceAgnostic();
478     compositionState->dataspace = getDataSpace();
479     compositionState->colorTransform = getColorTransform();
480     compositionState->colorTransformIsIdentity = !hasColorTransform();
481     compositionState->surfaceDamage = surfaceDamageRegion;
482     compositionState->hasProtectedContent = isProtected();
483     compositionState->dimmingEnabled = isDimmingEnabled();
484 
485     const bool usesRoundedCorners = hasRoundedCorners();
486 
487     compositionState->isOpaque =
488             isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
489 
490     // Force client composition for special cases known only to the front-end.
491     // Rounded corners no longer force client composition, since we may use a
492     // hole punch so that the layer will appear to have rounded corners.
493     if (isHdrY410() || drawShadows() || drawingState.blurRegions.size() > 0 ||
494         compositionState->stretchEffect.hasEffect()) {
495         compositionState->forceClientComposition = true;
496     }
497     // If there are no visible region changes, we still need to update blur parameters.
498     compositionState->blurRegions = drawingState.blurRegions;
499     compositionState->backgroundBlurRadius = drawingState.backgroundBlurRadius;
500 
501     // Layer framerate is used in caching decisions.
502     // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
503     // LayerFECompositionState where it would be visible to Flattener.
504     compositionState->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
505 }
506 
prepareCursorCompositionState()507 void Layer::prepareCursorCompositionState() {
508     const State& drawingState{getDrawingState()};
509     auto* compositionState = editCompositionState();
510 
511     // Apply the layer's transform, followed by the display's global transform
512     // Here we're guaranteed that the layer's transform preserves rects
513     Rect win = getCroppedBufferSize(drawingState);
514     // Subtract the transparent region and snap to the bounds
515     Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
516     Rect frame(getTransform().transform(bounds));
517 
518     compositionState->cursorFrame = frame;
519 }
520 
asLayerFE() const521 sp<compositionengine::LayerFE> Layer::asLayerFE() const {
522     return const_cast<compositionengine::LayerFE*>(
523             static_cast<const compositionengine::LayerFE*>(this));
524 }
525 
getCompositionEngineLayerFE() const526 sp<compositionengine::LayerFE> Layer::getCompositionEngineLayerFE() const {
527     return nullptr;
528 }
529 
editCompositionState()530 compositionengine::LayerFECompositionState* Layer::editCompositionState() {
531     return nullptr;
532 }
533 
getCompositionState() const534 const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
535     return nullptr;
536 }
537 
onPreComposition(nsecs_t)538 bool Layer::onPreComposition(nsecs_t) {
539     return false;
540 }
541 
prepareCompositionState(compositionengine::LayerFE::StateSubset subset)542 void Layer::prepareCompositionState(compositionengine::LayerFE::StateSubset subset) {
543     using StateSubset = compositionengine::LayerFE::StateSubset;
544 
545     switch (subset) {
546         case StateSubset::BasicGeometry:
547             prepareBasicGeometryCompositionState();
548             break;
549 
550         case StateSubset::GeometryAndContent:
551             prepareBasicGeometryCompositionState();
552             prepareGeometryCompositionState();
553             preparePerFrameCompositionState();
554             break;
555 
556         case StateSubset::Content:
557             preparePerFrameCompositionState();
558             break;
559 
560         case StateSubset::Cursor:
561             prepareCursorCompositionState();
562             break;
563     }
564 }
565 
getDebugName() const566 const char* Layer::getDebugName() const {
567     return mName.c_str();
568 }
569 
570 // ---------------------------------------------------------------------------
571 // drawing...
572 // ---------------------------------------------------------------------------
573 
prepareClientComposition(compositionengine::LayerFE::ClientCompositionTargetSettings & targetSettings)574 std::optional<compositionengine::LayerFE::LayerSettings> Layer::prepareClientComposition(
575         compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) {
576     if (!getCompositionState()) {
577         return {};
578     }
579 
580     FloatRect bounds = getBounds();
581     half alpha = getAlpha();
582 
583     compositionengine::LayerFE::LayerSettings layerSettings;
584     layerSettings.geometry.boundaries = bounds;
585     layerSettings.geometry.positionTransform = getTransform().asMatrix4();
586 
587     // skip drawing content if the targetSettings indicate the content will be occluded
588     const bool drawContent = targetSettings.realContentIsVisible || targetSettings.clearContent;
589     layerSettings.skipContentDraw = !drawContent;
590 
591     if (hasColorTransform()) {
592         layerSettings.colorTransform = getColorTransform();
593     }
594 
595     const auto roundedCornerState = getRoundedCornerState();
596     layerSettings.geometry.roundedCornersRadius = roundedCornerState.radius;
597     layerSettings.geometry.roundedCornersCrop = roundedCornerState.cropRect;
598 
599     layerSettings.alpha = alpha;
600     layerSettings.sourceDataspace = getDataSpace();
601 
602     // Override the dataspace transfer from 170M to sRGB if the device configuration requests this.
603     // We do this here instead of in buffer info so that dumpsys can still report layers that are
604     // using the 170M transfer.
605     if (mFlinger->mTreat170mAsSrgb &&
606         (layerSettings.sourceDataspace & HAL_DATASPACE_TRANSFER_MASK) ==
607                 HAL_DATASPACE_TRANSFER_SMPTE_170M) {
608         layerSettings.sourceDataspace = static_cast<ui::Dataspace>(
609                 (layerSettings.sourceDataspace & HAL_DATASPACE_STANDARD_MASK) |
610                 (layerSettings.sourceDataspace & HAL_DATASPACE_RANGE_MASK) |
611                 HAL_DATASPACE_TRANSFER_SRGB);
612     }
613 
614     layerSettings.whitePointNits = targetSettings.whitePointNits;
615     switch (targetSettings.blurSetting) {
616         case LayerFE::ClientCompositionTargetSettings::BlurSetting::Enabled:
617             layerSettings.backgroundBlurRadius = getBackgroundBlurRadius();
618             layerSettings.blurRegions = getBlurRegions();
619             layerSettings.blurRegionTransform =
620                     getActiveTransform(getDrawingState()).inverse().asMatrix4();
621             break;
622         case LayerFE::ClientCompositionTargetSettings::BlurSetting::BackgroundBlurOnly:
623             layerSettings.backgroundBlurRadius = getBackgroundBlurRadius();
624             break;
625         case LayerFE::ClientCompositionTargetSettings::BlurSetting::BlurRegionsOnly:
626             layerSettings.blurRegions = getBlurRegions();
627             layerSettings.blurRegionTransform =
628                     getActiveTransform(getDrawingState()).inverse().asMatrix4();
629             break;
630         case LayerFE::ClientCompositionTargetSettings::BlurSetting::Disabled:
631         default:
632             break;
633     }
634     layerSettings.stretchEffect = getStretchEffect();
635     // Record the name of the layer for debugging further down the stack.
636     layerSettings.name = getName();
637     return layerSettings;
638 }
639 
prepareClearClientComposition(LayerFE::LayerSettings & layerSettings,bool blackout) const640 void Layer::prepareClearClientComposition(LayerFE::LayerSettings& layerSettings,
641                                           bool blackout) const {
642     layerSettings.source.buffer.buffer = nullptr;
643     layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
644     layerSettings.disableBlending = true;
645     layerSettings.bufferId = 0;
646     layerSettings.frameNumber = 0;
647 
648     // If layer is blacked out, force alpha to 1 so that we draw a black color layer.
649     layerSettings.alpha = blackout ? 1.0f : 0.0f;
650     layerSettings.name = getName();
651 }
652 
653 // TODO(b/188891810): This method now only ever returns 0 or 1 layers so we should return
654 // std::optional instead of a vector.  Additionally, we should consider removing
655 // this method entirely in favor of calling prepareClientComposition directly.
prepareClientCompositionList(compositionengine::LayerFE::ClientCompositionTargetSettings & targetSettings)656 std::vector<compositionengine::LayerFE::LayerSettings> Layer::prepareClientCompositionList(
657         compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) {
658     std::optional<compositionengine::LayerFE::LayerSettings> layerSettings =
659             prepareClientComposition(targetSettings);
660     // Nothing to render.
661     if (!layerSettings) {
662         return {};
663     }
664 
665     // HWC requests to clear this layer.
666     if (targetSettings.clearContent) {
667         prepareClearClientComposition(*layerSettings, false /* blackout */);
668         return {*layerSettings};
669     }
670 
671     // set the shadow for the layer if needed
672     prepareShadowClientComposition(*layerSettings, targetSettings.viewport);
673 
674     return {*layerSettings};
675 }
676 
getCompositionType(const DisplayDevice & display) const677 aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
678         const DisplayDevice& display) const {
679     const auto outputLayer = findOutputLayerForDisplay(&display);
680     if (outputLayer == nullptr) {
681         return aidl::android::hardware::graphics::composer3::Composition::INVALID;
682     }
683     if (outputLayer->getState().hwc) {
684         return (*outputLayer->getState().hwc).hwcCompositionType;
685     } else {
686         return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
687     }
688 }
689 
690 // ----------------------------------------------------------------------------
691 // local state
692 // ----------------------------------------------------------------------------
693 
isSecure() const694 bool Layer::isSecure() const {
695     const State& s(mDrawingState);
696     if (s.flags & layer_state_t::eLayerSecure) {
697         return true;
698     }
699 
700     const auto p = mDrawingParent.promote();
701     return (p != nullptr) ? p->isSecure() : false;
702 }
703 
704 // ----------------------------------------------------------------------------
705 // transaction
706 // ----------------------------------------------------------------------------
707 
doTransaction(uint32_t flags)708 uint32_t Layer::doTransaction(uint32_t flags) {
709     ATRACE_CALL();
710 
711     // TODO: This is unfortunate.
712     mDrawingStateModified = mDrawingState.modified;
713     mDrawingState.modified = false;
714 
715     const State& s(getDrawingState());
716 
717     if (updateGeometry()) {
718         // invalidate and recompute the visible regions if needed
719         flags |= Layer::eVisibleRegion;
720     }
721 
722     if (s.sequence != mLastCommittedTxSequence) {
723         // invalidate and recompute the visible regions if needed
724          mLastCommittedTxSequence = s.sequence;
725         flags |= eVisibleRegion;
726         this->contentDirty = true;
727 
728         // we may use linear filtering, if the matrix scales us
729         mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
730     }
731 
732     commitTransaction(mDrawingState);
733 
734     return flags;
735 }
736 
commitTransaction(State &)737 void Layer::commitTransaction(State&) {
738     // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
739     // bufferSurfaceFrameTX will be presented in latchBuffer.
740     for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
741         if (surfaceFrame->getPresentState() != PresentState::Presented) {
742             // With applyPendingStates, we could end up having presented surfaceframes from previous
743             // states
744             surfaceFrame->setPresentState(PresentState::Presented);
745             mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
746         }
747     }
748     mDrawingState.bufferlessSurfaceFramesTX.clear();
749 }
750 
clearTransactionFlags(uint32_t mask)751 uint32_t Layer::clearTransactionFlags(uint32_t mask) {
752     const auto flags = mTransactionFlags & mask;
753     mTransactionFlags &= ~mask;
754     return flags;
755 }
756 
setTransactionFlags(uint32_t mask)757 void Layer::setTransactionFlags(uint32_t mask) {
758     mTransactionFlags |= mask;
759 }
760 
setPosition(float x,float y)761 bool Layer::setPosition(float x, float y) {
762     if (mDrawingState.transform.tx() == x && mDrawingState.transform.ty() == y) return false;
763     mDrawingState.sequence++;
764     mDrawingState.transform.set(x, y);
765 
766     mDrawingState.modified = true;
767     setTransactionFlags(eTransactionNeeded);
768     return true;
769 }
770 
setChildLayer(const sp<Layer> & childLayer,int32_t z)771 bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
772     ssize_t idx = mCurrentChildren.indexOf(childLayer);
773     if (idx < 0) {
774         return false;
775     }
776     if (childLayer->setLayer(z)) {
777         mCurrentChildren.removeAt(idx);
778         mCurrentChildren.add(childLayer);
779         return true;
780     }
781     return false;
782 }
783 
setChildRelativeLayer(const sp<Layer> & childLayer,const sp<IBinder> & relativeToHandle,int32_t relativeZ)784 bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
785         const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
786     ssize_t idx = mCurrentChildren.indexOf(childLayer);
787     if (idx < 0) {
788         return false;
789     }
790     if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
791         mCurrentChildren.removeAt(idx);
792         mCurrentChildren.add(childLayer);
793         return true;
794     }
795     return false;
796 }
797 
setLayer(int32_t z)798 bool Layer::setLayer(int32_t z) {
799     if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
800     mDrawingState.sequence++;
801     mDrawingState.z = z;
802     mDrawingState.modified = true;
803 
804     mFlinger->mSomeChildrenChanged = true;
805 
806     // Discard all relative layering.
807     if (mDrawingState.zOrderRelativeOf != nullptr) {
808         sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
809         if (strongRelative != nullptr) {
810             strongRelative->removeZOrderRelative(this);
811         }
812         setZOrderRelativeOf(nullptr);
813     }
814     setTransactionFlags(eTransactionNeeded);
815     return true;
816 }
817 
removeZOrderRelative(const wp<Layer> & relative)818 void Layer::removeZOrderRelative(const wp<Layer>& relative) {
819     mDrawingState.zOrderRelatives.remove(relative);
820     mDrawingState.sequence++;
821     mDrawingState.modified = true;
822     setTransactionFlags(eTransactionNeeded);
823 }
824 
addZOrderRelative(const wp<Layer> & relative)825 void Layer::addZOrderRelative(const wp<Layer>& relative) {
826     mDrawingState.zOrderRelatives.add(relative);
827     mDrawingState.modified = true;
828     mDrawingState.sequence++;
829     setTransactionFlags(eTransactionNeeded);
830 }
831 
setZOrderRelativeOf(const wp<Layer> & relativeOf)832 void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
833     mDrawingState.zOrderRelativeOf = relativeOf;
834     mDrawingState.sequence++;
835     mDrawingState.modified = true;
836     mDrawingState.isRelativeOf = relativeOf != nullptr;
837 
838     setTransactionFlags(eTransactionNeeded);
839 }
840 
setRelativeLayer(const sp<IBinder> & relativeToHandle,int32_t relativeZ)841 bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
842     sp<Layer> relative = fromHandle(relativeToHandle).promote();
843     if (relative == nullptr) {
844         return false;
845     }
846 
847     if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
848         mDrawingState.zOrderRelativeOf == relative) {
849         return false;
850     }
851 
852     if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
853         (relative->mDrawingState.zOrderRelativeOf == this)) {
854         ALOGE("Detected relative layer loop between %s and %s",
855               mName.c_str(), relative->mName.c_str());
856         ALOGE("Ignoring new call to set relative layer");
857         return false;
858     }
859 
860     mFlinger->mSomeChildrenChanged = true;
861 
862     mDrawingState.sequence++;
863     mDrawingState.modified = true;
864     mDrawingState.z = relativeZ;
865 
866     auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
867     if (oldZOrderRelativeOf != nullptr) {
868         oldZOrderRelativeOf->removeZOrderRelative(this);
869     }
870     setZOrderRelativeOf(relative);
871     relative->addZOrderRelative(this);
872 
873     setTransactionFlags(eTransactionNeeded);
874 
875     return true;
876 }
877 
setTrustedOverlay(bool isTrustedOverlay)878 bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
879     if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
880     mDrawingState.isTrustedOverlay = isTrustedOverlay;
881     mDrawingState.modified = true;
882     mFlinger->mInputInfoChanged = true;
883     setTransactionFlags(eTransactionNeeded);
884     return true;
885 }
886 
isTrustedOverlay() const887 bool Layer::isTrustedOverlay() const {
888     if (getDrawingState().isTrustedOverlay) {
889         return true;
890     }
891     const auto& p = mDrawingParent.promote();
892     return (p != nullptr) && p->isTrustedOverlay();
893 }
894 
setSize(uint32_t w,uint32_t h)895 bool Layer::setSize(uint32_t w, uint32_t h) {
896     if (mDrawingState.requested_legacy.w == w && mDrawingState.requested_legacy.h == h)
897         return false;
898     mDrawingState.requested_legacy.w = w;
899     mDrawingState.requested_legacy.h = h;
900     mDrawingState.modified = true;
901     setTransactionFlags(eTransactionNeeded);
902 
903     // record the new size, from this point on, when the client request
904     // a buffer, it'll get the new size.
905     setDefaultBufferSize(mDrawingState.requested_legacy.w, mDrawingState.requested_legacy.h);
906     return true;
907 }
908 
setAlpha(float alpha)909 bool Layer::setAlpha(float alpha) {
910     if (mDrawingState.color.a == alpha) return false;
911     mDrawingState.sequence++;
912     mDrawingState.color.a = alpha;
913     mDrawingState.modified = true;
914     setTransactionFlags(eTransactionNeeded);
915     return true;
916 }
917 
setBackgroundColor(const half3 & color,float alpha,ui::Dataspace dataspace)918 bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
919     if (!mDrawingState.bgColorLayer && alpha == 0) {
920         return false;
921     }
922     mDrawingState.sequence++;
923     mDrawingState.modified = true;
924     setTransactionFlags(eTransactionNeeded);
925 
926     if (!mDrawingState.bgColorLayer && alpha != 0) {
927         // create background color layer if one does not yet exist
928         uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
929         std::string name = mName + "BackgroundColorLayer";
930         mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
931                 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
932                                   LayerMetadata()));
933 
934         // add to child list
935         addChild(mDrawingState.bgColorLayer);
936         mFlinger->mLayersAdded = true;
937         // set up SF to handle added color layer
938         if (isRemovedFromCurrentState()) {
939             mDrawingState.bgColorLayer->onRemovedFromCurrentState();
940         }
941         mFlinger->setTransactionFlags(eTransactionNeeded);
942     } else if (mDrawingState.bgColorLayer && alpha == 0) {
943         mDrawingState.bgColorLayer->reparent(nullptr);
944         mDrawingState.bgColorLayer = nullptr;
945         return true;
946     }
947 
948     mDrawingState.bgColorLayer->setColor(color);
949     mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
950     mDrawingState.bgColorLayer->setAlpha(alpha);
951     mDrawingState.bgColorLayer->setDataspace(dataspace);
952 
953     return true;
954 }
955 
setCornerRadius(float cornerRadius)956 bool Layer::setCornerRadius(float cornerRadius) {
957     if (mDrawingState.cornerRadius == cornerRadius) return false;
958 
959     mDrawingState.sequence++;
960     mDrawingState.cornerRadius = cornerRadius;
961     mDrawingState.modified = true;
962     setTransactionFlags(eTransactionNeeded);
963     return true;
964 }
965 
setBackgroundBlurRadius(int backgroundBlurRadius)966 bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
967     if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
968     // If we start or stop drawing blur then the layer's visibility state may change so increment
969     // the magic sequence number.
970     if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
971         mDrawingState.sequence++;
972     }
973     mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
974     mDrawingState.modified = true;
975     setTransactionFlags(eTransactionNeeded);
976     return true;
977 }
setMatrix(const layer_state_t::matrix22_t & matrix)978 bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
979     ui::Transform t;
980     t.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
981 
982     mDrawingState.sequence++;
983     mDrawingState.transform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
984     mDrawingState.modified = true;
985 
986     setTransactionFlags(eTransactionNeeded);
987     return true;
988 }
989 
setTransparentRegionHint(const Region & transparent)990 bool Layer::setTransparentRegionHint(const Region& transparent) {
991     mDrawingState.requestedTransparentRegion_legacy = transparent;
992     mDrawingState.modified = true;
993     setTransactionFlags(eTransactionNeeded);
994     return true;
995 }
996 
setBlurRegions(const std::vector<BlurRegion> & blurRegions)997 bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
998     // If we start or stop drawing blur then the layer's visibility state may change so increment
999     // the magic sequence number.
1000     if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1001         mDrawingState.sequence++;
1002     }
1003     mDrawingState.blurRegions = blurRegions;
1004     mDrawingState.modified = true;
1005     setTransactionFlags(eTransactionNeeded);
1006     return true;
1007 }
1008 
setFlags(uint32_t flags,uint32_t mask)1009 bool Layer::setFlags(uint32_t flags, uint32_t mask) {
1010     const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1011     if (mDrawingState.flags == newFlags) return false;
1012     mDrawingState.sequence++;
1013     mDrawingState.flags = newFlags;
1014     mDrawingState.modified = true;
1015     setTransactionFlags(eTransactionNeeded);
1016     return true;
1017 }
1018 
setCrop(const Rect & crop)1019 bool Layer::setCrop(const Rect& crop) {
1020     if (mDrawingState.requestedCrop == crop) return false;
1021     mDrawingState.sequence++;
1022     mDrawingState.requestedCrop = crop;
1023     mDrawingState.crop = crop;
1024 
1025     mDrawingState.modified = true;
1026     setTransactionFlags(eTransactionNeeded);
1027     return true;
1028 }
1029 
setMetadata(const LayerMetadata & data)1030 bool Layer::setMetadata(const LayerMetadata& data) {
1031     if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1032     mDrawingState.modified = true;
1033     setTransactionFlags(eTransactionNeeded);
1034     return true;
1035 }
1036 
setLayerStack(ui::LayerStack layerStack)1037 bool Layer::setLayerStack(ui::LayerStack layerStack) {
1038     if (mDrawingState.layerStack == layerStack) return false;
1039     mDrawingState.sequence++;
1040     mDrawingState.layerStack = layerStack;
1041     mDrawingState.modified = true;
1042     setTransactionFlags(eTransactionNeeded);
1043     return true;
1044 }
1045 
setColorSpaceAgnostic(const bool agnostic)1046 bool Layer::setColorSpaceAgnostic(const bool agnostic) {
1047     if (mDrawingState.colorSpaceAgnostic == agnostic) {
1048         return false;
1049     }
1050     mDrawingState.sequence++;
1051     mDrawingState.colorSpaceAgnostic = agnostic;
1052     mDrawingState.modified = true;
1053     setTransactionFlags(eTransactionNeeded);
1054     return true;
1055 }
1056 
setDimmingEnabled(const bool dimmingEnabled)1057 bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1058     if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1059 
1060     mDrawingState.sequence++;
1061     mDrawingState.dimmingEnabled = dimmingEnabled;
1062     mDrawingState.modified = true;
1063     setTransactionFlags(eTransactionNeeded);
1064     return true;
1065 }
1066 
setFrameRateSelectionPriority(int32_t priority)1067 bool Layer::setFrameRateSelectionPriority(int32_t priority) {
1068     if (mDrawingState.frameRateSelectionPriority == priority) return false;
1069     mDrawingState.frameRateSelectionPriority = priority;
1070     mDrawingState.sequence++;
1071     mDrawingState.modified = true;
1072     setTransactionFlags(eTransactionNeeded);
1073     return true;
1074 }
1075 
getFrameRateSelectionPriority() const1076 int32_t Layer::getFrameRateSelectionPriority() const {
1077     // Check if layer has priority set.
1078     if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1079         return mDrawingState.frameRateSelectionPriority;
1080     }
1081     // If not, search whether its parents have it set.
1082     sp<Layer> parent = getParent();
1083     if (parent != nullptr) {
1084         return parent->getFrameRateSelectionPriority();
1085     }
1086 
1087     return Layer::PRIORITY_UNSET;
1088 }
1089 
isLayerFocusedBasedOnPriority(int32_t priority)1090 bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1091     return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1092 };
1093 
getLayerStack() const1094 ui::LayerStack Layer::getLayerStack() const {
1095     if (const auto parent = mDrawingParent.promote()) {
1096         return parent->getLayerStack();
1097     }
1098     return getDrawingState().layerStack;
1099 }
1100 
setShadowRadius(float shadowRadius)1101 bool Layer::setShadowRadius(float shadowRadius) {
1102     if (mDrawingState.shadowRadius == shadowRadius) {
1103         return false;
1104     }
1105 
1106     mDrawingState.sequence++;
1107     mDrawingState.shadowRadius = shadowRadius;
1108     mDrawingState.modified = true;
1109     setTransactionFlags(eTransactionNeeded);
1110     return true;
1111 }
1112 
setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint)1113 bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
1114     if (mDrawingState.fixedTransformHint == fixedTransformHint) {
1115         return false;
1116     }
1117 
1118     mDrawingState.sequence++;
1119     mDrawingState.fixedTransformHint = fixedTransformHint;
1120     mDrawingState.modified = true;
1121     setTransactionFlags(eTransactionNeeded);
1122     return true;
1123 }
1124 
setStretchEffect(const StretchEffect & effect)1125 bool Layer::setStretchEffect(const StretchEffect& effect) {
1126     StretchEffect temp = effect;
1127     temp.sanitize();
1128     if (mDrawingState.stretchEffect == temp) {
1129         return false;
1130     }
1131     mDrawingState.sequence++;
1132     mDrawingState.stretchEffect = temp;
1133     mDrawingState.modified = true;
1134     setTransactionFlags(eTransactionNeeded);
1135     return true;
1136 }
1137 
getStretchEffect() const1138 StretchEffect Layer::getStretchEffect() const {
1139     if (mDrawingState.stretchEffect.hasEffect()) {
1140         return mDrawingState.stretchEffect;
1141     }
1142 
1143     sp<Layer> parent = getParent();
1144     if (parent != nullptr) {
1145         auto effect = parent->getStretchEffect();
1146         if (effect.hasEffect()) {
1147             // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1148             return effect;
1149         }
1150     }
1151     return StretchEffect{};
1152 }
1153 
propagateFrameRateForLayerTree(FrameRate parentFrameRate,bool * transactionNeeded)1154 bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1155     // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1156     const auto frameRate = [&] {
1157         if (mDrawingState.frameRate.rate.isValid() ||
1158             mDrawingState.frameRate.type == FrameRateCompatibility::NoVote) {
1159             return mDrawingState.frameRate;
1160         }
1161 
1162         return parentFrameRate;
1163     }();
1164 
1165     *transactionNeeded |= setFrameRateForLayerTree(frameRate);
1166 
1167     // The frame rate is propagated to the children
1168     bool childrenHaveFrameRate = false;
1169     for (const sp<Layer>& child : mCurrentChildren) {
1170         childrenHaveFrameRate |=
1171                 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1172     }
1173 
1174     // If we don't have a valid frame rate, but the children do, we set this
1175     // layer as NoVote to allow the children to control the refresh rate
1176     if (!frameRate.rate.isValid() && frameRate.type != FrameRateCompatibility::NoVote &&
1177         childrenHaveFrameRate) {
1178         *transactionNeeded |=
1179                 setFrameRateForLayerTree(FrameRate(Fps(), FrameRateCompatibility::NoVote));
1180     }
1181 
1182     // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes for
1183     // the same reason we are allowing touch boost for those layers. See
1184     // RefreshRateConfigs::getBestRefreshRate for more details.
1185     const auto layerVotedWithDefaultCompatibility =
1186             frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Default;
1187     const auto layerVotedWithNoVote = frameRate.type == FrameRateCompatibility::NoVote;
1188     const auto layerVotedWithExactCompatibility =
1189             frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Exact;
1190     return layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
1191             layerVotedWithExactCompatibility || childrenHaveFrameRate;
1192 }
1193 
updateTreeHasFrameRateVote()1194 void Layer::updateTreeHasFrameRateVote() {
1195     const auto root = [&]() -> sp<Layer> {
1196         sp<Layer> layer = this;
1197         while (auto parent = layer->getParent()) {
1198             layer = parent;
1199         }
1200         return layer;
1201     }();
1202 
1203     bool transactionNeeded = false;
1204     root->propagateFrameRateForLayerTree({}, &transactionNeeded);
1205 
1206     // TODO(b/195668952): we probably don't need eTraversalNeeded here
1207     if (transactionNeeded) {
1208         mFlinger->setTransactionFlags(eTraversalNeeded);
1209     }
1210 }
1211 
setFrameRate(FrameRate frameRate)1212 bool Layer::setFrameRate(FrameRate frameRate) {
1213     if (mDrawingState.frameRate == frameRate) {
1214         return false;
1215     }
1216 
1217     mDrawingState.sequence++;
1218     mDrawingState.frameRate = frameRate;
1219     mDrawingState.modified = true;
1220 
1221     updateTreeHasFrameRateVote();
1222 
1223     setTransactionFlags(eTransactionNeeded);
1224     return true;
1225 }
1226 
setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo & info,nsecs_t postTime)1227 void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1228                                                       nsecs_t postTime) {
1229     mDrawingState.postTime = postTime;
1230 
1231     // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1232     // there are two transactions with the same token, the first one without a buffer and the
1233     // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1234     // in that case.
1235     auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1236     if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
1237         // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1238         mDrawingState.bufferSurfaceFrameTX = it->second;
1239         mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1240         mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1241         mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
1242     } else {
1243         mDrawingState.bufferSurfaceFrameTX =
1244                 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1245     }
1246 }
1247 
setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo & info,nsecs_t postTime)1248 void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1249                                                           nsecs_t postTime) {
1250     mDrawingState.frameTimelineInfo = info;
1251     mDrawingState.postTime = postTime;
1252     mDrawingState.modified = true;
1253     setTransactionFlags(eTransactionNeeded);
1254 
1255     if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
1256         bufferSurfaceFrameTX != nullptr) {
1257         if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1258             // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1259             // being used for BufferSurfaceFrame, don't create a new one.
1260             return;
1261         }
1262     }
1263     // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1264     // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1265     // targeting different vsyncs).
1266     auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1267     if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
1268         auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
1269         mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
1270     } else {
1271         if (it->second->getPresentState() == PresentState::Presented) {
1272             // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1273             // have been from previous vsync.
1274             it->second = createSurfaceFrameForTransaction(info, postTime);
1275         }
1276     }
1277 }
1278 
addSurfaceFrameDroppedForBuffer(std::shared_ptr<frametimeline::SurfaceFrame> & surfaceFrame)1279 void Layer::addSurfaceFrameDroppedForBuffer(
1280         std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
1281     surfaceFrame->setDropTime(systemTime());
1282     surfaceFrame->setPresentState(PresentState::Dropped);
1283     mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1284 }
1285 
addSurfaceFramePresentedForBuffer(std::shared_ptr<frametimeline::SurfaceFrame> & surfaceFrame,nsecs_t acquireFenceTime,nsecs_t currentLatchTime)1286 void Layer::addSurfaceFramePresentedForBuffer(
1287         std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1288         nsecs_t currentLatchTime) {
1289     surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1290     surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1291     mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1292     mLastLatchTime = currentLatchTime;
1293 }
1294 
createSurfaceFrameForTransaction(const FrameTimelineInfo & info,nsecs_t postTime)1295 std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1296         const FrameTimelineInfo& info, nsecs_t postTime) {
1297     auto surfaceFrame =
1298             mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1299                                                                  getSequence(), mName,
1300                                                                  mTransactionName,
1301                                                                  /*isBuffer*/ false, getGameMode());
1302     surfaceFrame->setActualStartTime(info.startTimeNanos);
1303     // For Transactions, the post time is considered to be both queue and acquire fence time.
1304     surfaceFrame->setActualQueueTime(postTime);
1305     surfaceFrame->setAcquireFenceTime(postTime);
1306     const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1307     if (fps) {
1308         surfaceFrame->setRenderRate(*fps);
1309     }
1310     onSurfaceFrameCreated(surfaceFrame);
1311     return surfaceFrame;
1312 }
1313 
createSurfaceFrameForBuffer(const FrameTimelineInfo & info,nsecs_t queueTime,std::string debugName)1314 std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1315         const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1316     auto surfaceFrame =
1317             mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1318                                                                  getSequence(), mName, debugName,
1319                                                                  /*isBuffer*/ true, getGameMode());
1320     surfaceFrame->setActualStartTime(info.startTimeNanos);
1321     // For buffers, acquire fence time will set during latch.
1322     surfaceFrame->setActualQueueTime(queueTime);
1323     const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1324     if (fps) {
1325         surfaceFrame->setRenderRate(*fps);
1326     }
1327     // TODO(b/178542907): Implement onSurfaceFrameCreated for BQLayer as well.
1328     onSurfaceFrameCreated(surfaceFrame);
1329     return surfaceFrame;
1330 }
1331 
setFrameRateForLayerTree(FrameRate frameRate)1332 bool Layer::setFrameRateForLayerTree(FrameRate frameRate) {
1333     if (mDrawingState.frameRateForLayerTree == frameRate) {
1334         return false;
1335     }
1336 
1337     mDrawingState.frameRateForLayerTree = frameRate;
1338 
1339     // TODO(b/195668952): we probably don't need to dirty visible regions here
1340     // or even store frameRateForLayerTree in mDrawingState
1341     mDrawingState.sequence++;
1342     mDrawingState.modified = true;
1343     setTransactionFlags(eTransactionNeeded);
1344 
1345     using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
1346     mFlinger->mScheduler->recordLayerHistory(this, systemTime(), LayerUpdateType::SetFrameRate);
1347 
1348     return true;
1349 }
1350 
getFrameRateForLayerTree() const1351 Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1352     return getDrawingState().frameRateForLayerTree;
1353 }
1354 
isHiddenByPolicy() const1355 bool Layer::isHiddenByPolicy() const {
1356     const State& s(mDrawingState);
1357     const auto& parent = mDrawingParent.promote();
1358     if (parent != nullptr && parent->isHiddenByPolicy()) {
1359         return true;
1360     }
1361     if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1362         auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1363         if (zOrderRelativeOf != nullptr) {
1364             if (zOrderRelativeOf->isHiddenByPolicy()) {
1365                 return true;
1366             }
1367         }
1368     }
1369     if (CC_UNLIKELY(!isTransformValid())) {
1370         ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1371         return true;
1372     }
1373     return s.flags & layer_state_t::eLayerHidden;
1374 }
1375 
getEffectiveUsage(uint32_t usage) const1376 uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
1377     // TODO: should we do something special if mSecure is set?
1378     if (mProtectedByApp) {
1379         // need a hardware-protected path to external video sink
1380         usage |= GraphicBuffer::USAGE_PROTECTED;
1381     }
1382     if (mPotentialCursor) {
1383         usage |= GraphicBuffer::USAGE_CURSOR;
1384     }
1385     usage |= GraphicBuffer::USAGE_HW_COMPOSER;
1386     return usage;
1387 }
1388 
updateTransformHint(ui::Transform::RotationFlags transformHint)1389 void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1390     if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1391         transformHint = ui::Transform::ROT_0;
1392     }
1393 
1394     setTransformHint(transformHint);
1395 }
1396 
1397 // ----------------------------------------------------------------------------
1398 // debugging
1399 // ----------------------------------------------------------------------------
1400 
1401 // TODO(marissaw): add new layer state info to layer debugging
getLayerDebugInfo(const DisplayDevice * display) const1402 LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
1403     using namespace std::string_literals;
1404 
1405     LayerDebugInfo info;
1406     const State& ds = getDrawingState();
1407     info.mName = getName();
1408     sp<Layer> parent = mDrawingParent.promote();
1409     info.mParentName = parent ? parent->getName() : "none"s;
1410     info.mType = getType();
1411     info.mTransparentRegion = ds.activeTransparentRegion_legacy;
1412 
1413     info.mVisibleRegion = getVisibleRegion(display);
1414     info.mSurfaceDamageRegion = surfaceDamageRegion;
1415     info.mLayerStack = getLayerStack().id;
1416     info.mX = ds.transform.tx();
1417     info.mY = ds.transform.ty();
1418     info.mZ = ds.z;
1419     info.mWidth = ds.width;
1420     info.mHeight = ds.height;
1421     info.mCrop = ds.crop;
1422     info.mColor = ds.color;
1423     info.mFlags = ds.flags;
1424     info.mPixelFormat = getPixelFormat();
1425     info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
1426     info.mMatrix[0][0] = ds.transform[0][0];
1427     info.mMatrix[0][1] = ds.transform[0][1];
1428     info.mMatrix[1][0] = ds.transform[1][0];
1429     info.mMatrix[1][1] = ds.transform[1][1];
1430     {
1431         sp<const GraphicBuffer> buffer = getBuffer();
1432         if (buffer != 0) {
1433             info.mActiveBufferWidth = buffer->getWidth();
1434             info.mActiveBufferHeight = buffer->getHeight();
1435             info.mActiveBufferStride = buffer->getStride();
1436             info.mActiveBufferFormat = buffer->format;
1437         } else {
1438             info.mActiveBufferWidth = 0;
1439             info.mActiveBufferHeight = 0;
1440             info.mActiveBufferStride = 0;
1441             info.mActiveBufferFormat = 0;
1442         }
1443     }
1444     info.mNumQueuedFrames = getQueuedFrameCount();
1445     info.mIsOpaque = isOpaque(ds);
1446     info.mContentDirty = contentDirty;
1447     info.mStretchEffect = getStretchEffect();
1448     return info;
1449 }
1450 
miniDumpHeader(std::string & result)1451 void Layer::miniDumpHeader(std::string& result) {
1452     result.append(kDumpTableRowLength, '-');
1453     result.append("\n");
1454     result.append(" Layer name\n");
1455     result.append("           Z | ");
1456     result.append(" Window Type | ");
1457     result.append(" Comp Type | ");
1458     result.append(" Transform | ");
1459     result.append("  Disp Frame (LTRB) | ");
1460     result.append("         Source Crop (LTRB) | ");
1461     result.append("    Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1462     result.append(kDumpTableRowLength, '-');
1463     result.append("\n");
1464 }
1465 
miniDump(std::string & result,const DisplayDevice & display) const1466 void Layer::miniDump(std::string& result, const DisplayDevice& display) const {
1467     const auto outputLayer = findOutputLayerForDisplay(&display);
1468     if (!outputLayer) {
1469         return;
1470     }
1471 
1472     std::string name;
1473     if (mName.length() > 77) {
1474         std::string shortened;
1475         shortened.append(mName, 0, 36);
1476         shortened.append("[...]");
1477         shortened.append(mName, mName.length() - 36);
1478         name = std::move(shortened);
1479     } else {
1480         name = mName;
1481     }
1482 
1483     StringAppendF(&result, " %s\n", name.c_str());
1484 
1485     const State& layerState(getDrawingState());
1486     const auto& outputLayerState = outputLayer->getState();
1487 
1488     if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
1489         StringAppendF(&result, "  rel %6d | ", layerState.z);
1490     } else {
1491         StringAppendF(&result, "  %10d | ", layerState.z);
1492     }
1493     StringAppendF(&result, "  %10d | ", mWindowType);
1494     StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
1495     StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1496     const Rect& frame = outputLayerState.displayFrame;
1497     StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
1498     const FloatRect& crop = outputLayerState.sourceCrop;
1499     StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
1500                   crop.bottom);
1501     const auto frameRate = getFrameRateForLayerTree();
1502     if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1503         StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
1504                       ftl::enum_string(frameRate.type).c_str(),
1505                       ftl::enum_string(frameRate.seamlessness).c_str());
1506     } else {
1507         result.append(41, ' ');
1508     }
1509 
1510     const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1511     StringAppendF(&result, "    [%s]\n", focused ? "*" : " ");
1512 
1513     result.append(kDumpTableRowLength, '-');
1514     result.append("\n");
1515 }
1516 
dumpFrameStats(std::string & result) const1517 void Layer::dumpFrameStats(std::string& result) const {
1518     mFrameTracker.dumpStats(result);
1519 }
1520 
clearFrameStats()1521 void Layer::clearFrameStats() {
1522     mFrameTracker.clearStats();
1523 }
1524 
logFrameStats()1525 void Layer::logFrameStats() {
1526     mFrameTracker.logAndResetStats(mName);
1527 }
1528 
getFrameStats(FrameStats * outStats) const1529 void Layer::getFrameStats(FrameStats* outStats) const {
1530     mFrameTracker.getStats(outStats);
1531 }
1532 
dumpCallingUidPid(std::string & result) const1533 void Layer::dumpCallingUidPid(std::string& result) const {
1534     StringAppendF(&result, "Layer %s (%s) callingPid:%d callingUid:%d ownerUid:%d\n",
1535                   getName().c_str(), getType(), mCallingPid, mCallingUid, mOwnerUid);
1536 }
1537 
onDisconnect()1538 void Layer::onDisconnect() {
1539     const int32_t layerId = getSequence();
1540     mFlinger->mTimeStats->onDestroy(layerId);
1541     mFlinger->mFrameTracer->onDestroy(layerId);
1542 }
1543 
getChildrenCount() const1544 size_t Layer::getChildrenCount() const {
1545     size_t count = 0;
1546     for (const sp<Layer>& child : mCurrentChildren) {
1547         count += 1 + child->getChildrenCount();
1548     }
1549     return count;
1550 }
1551 
setGameModeForTree(GameMode gameMode)1552 void Layer::setGameModeForTree(GameMode gameMode) {
1553     const auto& currentState = getDrawingState();
1554     if (currentState.metadata.has(METADATA_GAME_MODE)) {
1555         gameMode = static_cast<GameMode>(currentState.metadata.getInt32(METADATA_GAME_MODE, 0));
1556     }
1557     setGameMode(gameMode);
1558     for (const sp<Layer>& child : mCurrentChildren) {
1559         child->setGameModeForTree(gameMode);
1560     }
1561 }
1562 
addChild(const sp<Layer> & layer)1563 void Layer::addChild(const sp<Layer>& layer) {
1564     mFlinger->mSomeChildrenChanged = true;
1565     setTransactionFlags(eTransactionNeeded);
1566 
1567     mCurrentChildren.add(layer);
1568     layer->setParent(this);
1569     layer->setGameModeForTree(mGameMode);
1570     updateTreeHasFrameRateVote();
1571 }
1572 
removeChild(const sp<Layer> & layer)1573 ssize_t Layer::removeChild(const sp<Layer>& layer) {
1574     mFlinger->mSomeChildrenChanged = true;
1575     setTransactionFlags(eTransactionNeeded);
1576 
1577     layer->setParent(nullptr);
1578     const auto removeResult = mCurrentChildren.remove(layer);
1579 
1580     updateTreeHasFrameRateVote();
1581     layer->setGameModeForTree(GameMode::Unsupported);
1582     layer->updateTreeHasFrameRateVote();
1583 
1584     return removeResult;
1585 }
1586 
setChildrenDrawingParent(const sp<Layer> & newParent)1587 void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
1588     for (const sp<Layer>& child : mDrawingChildren) {
1589         child->mDrawingParent = newParent;
1590         child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
1591                              newParent->mEffectiveShadowRadius);
1592     }
1593 }
1594 
reparent(const sp<IBinder> & newParentHandle)1595 bool Layer::reparent(const sp<IBinder>& newParentHandle) {
1596     sp<Layer> newParent;
1597     if (newParentHandle != nullptr) {
1598         newParent = fromHandle(newParentHandle).promote();
1599         if (newParent == nullptr) {
1600             ALOGE("Unable to promote Layer handle");
1601             return false;
1602         }
1603         if (newParent == this) {
1604             ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1605             return false;
1606         }
1607     }
1608 
1609     sp<Layer> parent = getParent();
1610     if (parent != nullptr) {
1611         parent->removeChild(this);
1612     }
1613 
1614     if (newParentHandle != nullptr) {
1615         newParent->addChild(this);
1616         if (!newParent->isRemovedFromCurrentState()) {
1617             addToCurrentState();
1618         } else {
1619             onRemovedFromCurrentState();
1620         }
1621     } else {
1622         onRemovedFromCurrentState();
1623     }
1624 
1625     return true;
1626 }
1627 
setColorTransform(const mat4 & matrix)1628 bool Layer::setColorTransform(const mat4& matrix) {
1629     static const mat4 identityMatrix = mat4();
1630 
1631     if (mDrawingState.colorTransform == matrix) {
1632         return false;
1633     }
1634     ++mDrawingState.sequence;
1635     mDrawingState.colorTransform = matrix;
1636     mDrawingState.hasColorTransform = matrix != identityMatrix;
1637     mDrawingState.modified = true;
1638     setTransactionFlags(eTransactionNeeded);
1639     return true;
1640 }
1641 
getColorTransform() const1642 mat4 Layer::getColorTransform() const {
1643     mat4 colorTransform = mat4(getDrawingState().colorTransform);
1644     if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
1645         colorTransform = parent->getColorTransform() * colorTransform;
1646     }
1647     return colorTransform;
1648 }
1649 
hasColorTransform() const1650 bool Layer::hasColorTransform() const {
1651     bool hasColorTransform = getDrawingState().hasColorTransform;
1652     if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
1653         hasColorTransform = hasColorTransform || parent->hasColorTransform();
1654     }
1655     return hasColorTransform;
1656 }
1657 
isLegacyDataSpace() const1658 bool Layer::isLegacyDataSpace() const {
1659     // return true when no higher bits are set
1660     return !(getDataSpace() &
1661              (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1662               ui::Dataspace::RANGE_MASK));
1663 }
1664 
setParent(const sp<Layer> & layer)1665 void Layer::setParent(const sp<Layer>& layer) {
1666     mCurrentParent = layer;
1667 }
1668 
getZ(LayerVector::StateSet) const1669 int32_t Layer::getZ(LayerVector::StateSet) const {
1670     return mDrawingState.z;
1671 }
1672 
usingRelativeZ(LayerVector::StateSet stateSet) const1673 bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
1674     const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1675     const State& state = useDrawing ? mDrawingState : mDrawingState;
1676     return state.isRelativeOf;
1677 }
1678 
makeTraversalList(LayerVector::StateSet stateSet,bool * outSkipRelativeZUsers)1679 __attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
1680         LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
1681     LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1682                         "makeTraversalList received invalid stateSet");
1683     const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1684     const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1685     const State& state = useDrawing ? mDrawingState : mDrawingState;
1686 
1687     if (state.zOrderRelatives.size() == 0) {
1688         *outSkipRelativeZUsers = true;
1689         return children;
1690     }
1691 
1692     LayerVector traverse(stateSet);
1693     for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1694         sp<Layer> strongRelative = weakRelative.promote();
1695         if (strongRelative != nullptr) {
1696             traverse.add(strongRelative);
1697         }
1698     }
1699 
1700     for (const sp<Layer>& child : children) {
1701         if (child->usingRelativeZ(stateSet)) {
1702             continue;
1703         }
1704         traverse.add(child);
1705     }
1706 
1707     return traverse;
1708 }
1709 
1710 /**
1711  * Negatively signed relatives are before 'this' in Z-order.
1712  */
traverseInZOrder(LayerVector::StateSet stateSet,const LayerVector::Visitor & visitor)1713 void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
1714     // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1715     // produce a new list for traversing, including our relatives, and not including our children
1716     // who are relatives of another surface. In the case that there are no relative Z,
1717     // makeTraversalList returns our children directly to avoid significant overhead.
1718     // However in this case we need to take the responsibility for filtering children which
1719     // are relatives of another surface here.
1720     bool skipRelativeZUsers = false;
1721     const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
1722 
1723     size_t i = 0;
1724     for (; i < list.size(); i++) {
1725         const auto& relative = list[i];
1726         if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1727             continue;
1728         }
1729 
1730         if (relative->getZ(stateSet) >= 0) {
1731             break;
1732         }
1733         relative->traverseInZOrder(stateSet, visitor);
1734     }
1735 
1736     visitor(this);
1737     for (; i < list.size(); i++) {
1738         const auto& relative = list[i];
1739 
1740         if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1741             continue;
1742         }
1743         relative->traverseInZOrder(stateSet, visitor);
1744     }
1745 }
1746 
1747 /**
1748  * Positively signed relatives are before 'this' in reverse Z-order.
1749  */
traverseInReverseZOrder(LayerVector::StateSet stateSet,const LayerVector::Visitor & visitor)1750 void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1751                                     const LayerVector::Visitor& visitor) {
1752     // See traverseInZOrder for documentation.
1753     bool skipRelativeZUsers = false;
1754     LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
1755 
1756     int32_t i = 0;
1757     for (i = int32_t(list.size()) - 1; i >= 0; i--) {
1758         const auto& relative = list[i];
1759 
1760         if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1761             continue;
1762         }
1763 
1764         if (relative->getZ(stateSet) < 0) {
1765             break;
1766         }
1767         relative->traverseInReverseZOrder(stateSet, visitor);
1768     }
1769     visitor(this);
1770     for (; i >= 0; i--) {
1771         const auto& relative = list[i];
1772 
1773         if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1774             continue;
1775         }
1776 
1777         relative->traverseInReverseZOrder(stateSet, visitor);
1778     }
1779 }
1780 
traverse(LayerVector::StateSet state,const LayerVector::Visitor & visitor)1781 void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1782     visitor(this);
1783     const LayerVector& children =
1784           state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
1785     for (const sp<Layer>& child : children) {
1786         child->traverse(state, visitor);
1787     }
1788 }
1789 
makeChildrenTraversalList(LayerVector::StateSet stateSet,const std::vector<Layer * > & layersInTree)1790 LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1791                                              const std::vector<Layer*>& layersInTree) {
1792     LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1793                         "makeTraversalList received invalid stateSet");
1794     const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1795     const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1796     const State& state = useDrawing ? mDrawingState : mDrawingState;
1797 
1798     LayerVector traverse(stateSet);
1799     for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1800         sp<Layer> strongRelative = weakRelative.promote();
1801         // Only add relative layers that are also descendents of the top most parent of the tree.
1802         // If a relative layer is not a descendent, then it should be ignored.
1803         if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1804             traverse.add(strongRelative);
1805         }
1806     }
1807 
1808     for (const sp<Layer>& child : children) {
1809         const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
1810         // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1811         // descendent of the top most parent of the tree. If it's not a descendent, then just add
1812         // the child here since it won't be added later as a relative.
1813         if (std::binary_search(layersInTree.begin(), layersInTree.end(),
1814                                childState.zOrderRelativeOf.promote().get())) {
1815             continue;
1816         }
1817         traverse.add(child);
1818     }
1819 
1820     return traverse;
1821 }
1822 
traverseChildrenInZOrderInner(const std::vector<Layer * > & layersInTree,LayerVector::StateSet stateSet,const LayerVector::Visitor & visitor)1823 void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1824                                           LayerVector::StateSet stateSet,
1825                                           const LayerVector::Visitor& visitor) {
1826     const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
1827 
1828     size_t i = 0;
1829     for (; i < list.size(); i++) {
1830         const auto& relative = list[i];
1831         if (relative->getZ(stateSet) >= 0) {
1832             break;
1833         }
1834         relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
1835     }
1836 
1837     visitor(this);
1838     for (; i < list.size(); i++) {
1839         const auto& relative = list[i];
1840         relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
1841     }
1842 }
1843 
getLayersInTree(LayerVector::StateSet stateSet)1844 std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
1845     const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1846     const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1847 
1848     std::vector<Layer*> layersInTree = {this};
1849     for (size_t i = 0; i < children.size(); i++) {
1850         const auto& child = children[i];
1851         std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
1852         layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
1853     }
1854 
1855     return layersInTree;
1856 }
1857 
traverseChildrenInZOrder(LayerVector::StateSet stateSet,const LayerVector::Visitor & visitor)1858 void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
1859                                      const LayerVector::Visitor& visitor) {
1860     std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
1861     std::sort(layersInTree.begin(), layersInTree.end());
1862     traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
1863 }
1864 
getTransform() const1865 ui::Transform Layer::getTransform() const {
1866     return mEffectiveTransform;
1867 }
1868 
isTransformValid() const1869 bool Layer::isTransformValid() const {
1870     float transformDet = getTransform().det();
1871     return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
1872 }
1873 
getAlpha() const1874 half Layer::getAlpha() const {
1875     const auto& p = mDrawingParent.promote();
1876 
1877     half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1878     return parentAlpha * getDrawingState().color.a;
1879 }
1880 
getFixedTransformHint() const1881 ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
1882     ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
1883     if (fixedTransformHint != ui::Transform::ROT_INVALID) {
1884         return fixedTransformHint;
1885     }
1886     const auto& p = mCurrentParent.promote();
1887     if (!p) return fixedTransformHint;
1888     return p->getFixedTransformHint();
1889 }
1890 
getColor() const1891 half4 Layer::getColor() const {
1892     const half4 color(getDrawingState().color);
1893     return half4(color.r, color.g, color.b, getAlpha());
1894 }
1895 
getBackgroundBlurRadius() const1896 int32_t Layer::getBackgroundBlurRadius() const {
1897     const auto& p = mDrawingParent.promote();
1898 
1899     half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1900     return parentAlpha * getDrawingState().backgroundBlurRadius;
1901 }
1902 
getBlurRegions() const1903 const std::vector<BlurRegion> Layer::getBlurRegions() const {
1904     auto regionsCopy(getDrawingState().blurRegions);
1905     float layerAlpha = getAlpha();
1906     for (auto& region : regionsCopy) {
1907         region.alpha = region.alpha * layerAlpha;
1908     }
1909     return regionsCopy;
1910 }
1911 
getRoundedCornerState() const1912 Layer::RoundedCornerState Layer::getRoundedCornerState() const {
1913     // Get parent settings
1914     RoundedCornerState parentSettings;
1915     const auto& parent = mDrawingParent.promote();
1916     if (parent != nullptr) {
1917         parentSettings = parent->getRoundedCornerState();
1918         if (parentSettings.hasRoundedCorners()) {
1919             ui::Transform t = getActiveTransform(getDrawingState());
1920             t = t.inverse();
1921             parentSettings.cropRect = t.transform(parentSettings.cropRect);
1922             parentSettings.radius.x *= t.getScaleX();
1923             parentSettings.radius.y *= t.getScaleY();
1924         }
1925     }
1926 
1927     // Get layer settings
1928     Rect layerCropRect = getCroppedBufferSize(getDrawingState());
1929     const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
1930     RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
1931     const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
1932 
1933     if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
1934         // If the parent and the layer have rounded corner settings, use the parent settings if the
1935         // parent crop is entirely inside the layer crop.
1936         // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
1937         if (parentSettings.cropRect.left > layerCropRect.left &&
1938             parentSettings.cropRect.top > layerCropRect.top &&
1939             parentSettings.cropRect.right < layerCropRect.right &&
1940             parentSettings.cropRect.bottom < layerCropRect.bottom) {
1941             return parentSettings;
1942         } else {
1943             return layerSettings;
1944         }
1945     } else if (layerSettingsValid) {
1946         return layerSettings;
1947     } else if (parentSettings.hasRoundedCorners()) {
1948         return parentSettings;
1949     }
1950     return {};
1951 }
1952 
prepareShadowClientComposition(LayerFE::LayerSettings & caster,const Rect & layerStackRect)1953 void Layer::prepareShadowClientComposition(LayerFE::LayerSettings& caster,
1954                                            const Rect& layerStackRect) {
1955     renderengine::ShadowSettings state = mFlinger->mDrawingState.globalShadowSettings;
1956 
1957     // Note: this preserves existing behavior of shadowing the entire layer and not cropping it if
1958     // transparent regions are present. This may not be necessary since shadows are only cast by
1959     // SurfaceFlinger's EffectLayers, which do not typically use transparent regions.
1960     state.boundaries = mBounds;
1961 
1962     // Shift the spot light x-position to the middle of the display and then
1963     // offset it by casting layer's screen pos.
1964     state.lightPos.x = (layerStackRect.width() / 2.f) - mScreenBounds.left;
1965     state.lightPos.y -= mScreenBounds.top;
1966 
1967     state.length = mEffectiveShadowRadius;
1968 
1969     if (state.length > 0.f) {
1970         const float casterAlpha = caster.alpha;
1971         const bool casterIsOpaque =
1972                 ((caster.source.buffer.buffer != nullptr) && caster.source.buffer.isOpaque);
1973 
1974         // If the casting layer is translucent, we need to fill in the shadow underneath the layer.
1975         // Otherwise the generated shadow will only be shown around the casting layer.
1976         state.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
1977         state.ambientColor *= casterAlpha;
1978         state.spotColor *= casterAlpha;
1979 
1980         if (state.ambientColor.a > 0.f && state.spotColor.a > 0.f) {
1981             caster.shadow = state;
1982         }
1983     }
1984 }
1985 
findInHierarchy(const sp<Layer> & l)1986 bool Layer::findInHierarchy(const sp<Layer>& l) {
1987     if (l == this) {
1988         return true;
1989     }
1990     for (auto& child : mDrawingChildren) {
1991       if (child->findInHierarchy(l)) {
1992           return true;
1993       }
1994     }
1995     return false;
1996 }
1997 
commitChildList()1998 void Layer::commitChildList() {
1999     for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2000         const auto& child = mCurrentChildren[i];
2001         child->commitChildList();
2002     }
2003     mDrawingChildren = mCurrentChildren;
2004     mDrawingParent = mCurrentParent;
2005     if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2006         auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2007         if (zOrderRelativeOf == nullptr) return;
2008         if (findInHierarchy(zOrderRelativeOf)) {
2009             ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2010                   zOrderRelativeOf->mName.c_str());
2011             ALOGE("Severing rel Z loop, potentially dangerous");
2012             mDrawingState.isRelativeOf = false;
2013             zOrderRelativeOf->removeZOrderRelative(this);
2014         }
2015     }
2016 }
2017 
2018 
setInputInfo(const WindowInfo & info)2019 void Layer::setInputInfo(const WindowInfo& info) {
2020     mDrawingState.inputInfo = info;
2021     mDrawingState.touchableRegionCrop = fromHandle(info.touchableRegionCropHandle.promote());
2022     mDrawingState.modified = true;
2023     mFlinger->mInputInfoChanged = true;
2024     setTransactionFlags(eTransactionNeeded);
2025 }
2026 
writeToProto(LayersProto & layersProto,uint32_t traceFlags)2027 LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
2028     LayerProto* layerProto = layersProto.add_layers();
2029     writeToProtoDrawingState(layerProto);
2030     writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2031 
2032     if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
2033         ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
2034 
2035         // Only populate for the primary display.
2036         if (const auto display = mFlinger->getDefaultDisplayDeviceLocked()) {
2037             const auto compositionType = getCompositionType(*display);
2038             layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
2039             LayerProtoHelper::writeToProto(getVisibleRegion(display.get()),
2040                                            [&]() { return layerProto->mutable_visible_region(); });
2041         }
2042     }
2043 
2044     for (const sp<Layer>& layer : mDrawingChildren) {
2045         layer->writeToProto(layersProto, traceFlags);
2046     }
2047 
2048     return layerProto;
2049 }
2050 
writeToProtoDrawingState(LayerProto * layerInfo)2051 void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
2052     const ui::Transform transform = getTransform();
2053     auto buffer = getExternalTexture();
2054     if (buffer != nullptr) {
2055         LayerProtoHelper::writeToProto(*buffer,
2056                                        [&]() { return layerInfo->mutable_active_buffer(); });
2057         LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2058                                                  layerInfo->mutable_buffer_transform());
2059     }
2060     layerInfo->set_invalidate(contentDirty);
2061     layerInfo->set_is_protected(isProtected());
2062     layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2063     layerInfo->set_queued_frames(getQueuedFrameCount());
2064     layerInfo->set_curr_frame(mCurrentFrameNumber);
2065     layerInfo->set_effective_scaling_mode(getEffectiveScalingMode());
2066 
2067     layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
2068     layerInfo->set_corner_radius(
2069             (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
2070     layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2071     layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2072     LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2073     LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2074                                            [&]() { return layerInfo->mutable_position(); });
2075     LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
2076     LayerProtoHelper::writeToProto(surfaceDamageRegion,
2077                                    [&]() { return layerInfo->mutable_damage_region(); });
2078 
2079     if (hasColorTransform()) {
2080         LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
2081     }
2082 
2083     LayerProtoHelper::writeToProto(mSourceBounds,
2084                                    [&]() { return layerInfo->mutable_source_bounds(); });
2085     LayerProtoHelper::writeToProto(mScreenBounds,
2086                                    [&]() { return layerInfo->mutable_screen_bounds(); });
2087     LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2088                                    [&]() { return layerInfo->mutable_corner_radius_crop(); });
2089     layerInfo->set_shadow_radius(mEffectiveShadowRadius);
2090 }
2091 
writeToProtoCommonState(LayerProto * layerInfo,LayerVector::StateSet stateSet,uint32_t traceFlags)2092 void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
2093                                     uint32_t traceFlags) {
2094     const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2095     const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2096     const State& state = useDrawing ? mDrawingState : mDrawingState;
2097 
2098     ui::Transform requestedTransform = state.transform;
2099 
2100     layerInfo->set_id(sequence);
2101     layerInfo->set_name(getName().c_str());
2102     layerInfo->set_type(getType());
2103 
2104     for (const auto& child : children) {
2105         layerInfo->add_children(child->sequence);
2106     }
2107 
2108     for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2109         sp<Layer> strongRelative = weakRelative.promote();
2110         if (strongRelative != nullptr) {
2111             layerInfo->add_relatives(strongRelative->sequence);
2112         }
2113     }
2114 
2115     LayerProtoHelper::writeToProto(state.activeTransparentRegion_legacy,
2116                                    [&]() { return layerInfo->mutable_transparent_region(); });
2117 
2118     layerInfo->set_layer_stack(getLayerStack().id);
2119     layerInfo->set_z(state.z);
2120 
2121     LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2122         return layerInfo->mutable_requested_position();
2123     });
2124 
2125     LayerProtoHelper::writeSizeToProto(state.width, state.height,
2126                                        [&]() { return layerInfo->mutable_size(); });
2127 
2128     LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2129 
2130     layerInfo->set_is_opaque(isOpaque(state));
2131 
2132     layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2133     LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2134     LayerProtoHelper::writeToProto(state.color,
2135                                    [&]() { return layerInfo->mutable_requested_color(); });
2136     layerInfo->set_flags(state.flags);
2137 
2138     LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2139                                              layerInfo->mutable_requested_transform());
2140 
2141     auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2142     if (parent != nullptr) {
2143         layerInfo->set_parent(parent->sequence);
2144     } else {
2145         layerInfo->set_parent(-1);
2146     }
2147 
2148     auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2149     if (zOrderRelativeOf != nullptr) {
2150         layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2151     } else {
2152         layerInfo->set_z_order_relative_of(-1);
2153     }
2154 
2155     layerInfo->set_is_relative_of(state.isRelativeOf);
2156 
2157     layerInfo->set_owner_uid(mOwnerUid);
2158 
2159     if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
2160         WindowInfo info;
2161         if (useDrawing) {
2162             info = fillInputInfo(
2163                     InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
2164         } else {
2165             info = state.inputInfo;
2166         }
2167 
2168         LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
2169                                        [&]() { return layerInfo->mutable_input_window_info(); });
2170     }
2171 
2172     if (traceFlags & LayerTracing::TRACE_EXTRA) {
2173         auto protoMap = layerInfo->mutable_metadata();
2174         for (const auto& entry : state.metadata.mMap) {
2175             (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2176         }
2177     }
2178 
2179     LayerProtoHelper::writeToProto(state.destinationFrame,
2180                                    [&]() { return layerInfo->mutable_destination_frame(); });
2181 }
2182 
isRemovedFromCurrentState() const2183 bool Layer::isRemovedFromCurrentState() const  {
2184     return mRemovedFromDrawingState;
2185 }
2186 
getInputTransform() const2187 ui::Transform Layer::getInputTransform() const {
2188     return getTransform();
2189 }
2190 
getInputBounds() const2191 Rect Layer::getInputBounds() const {
2192     return getCroppedBufferSize(getDrawingState());
2193 }
2194 
2195 // Applies the given transform to the region, while protecting against overflows caused by any
2196 // offsets. If applying the offset in the transform to any of the Rects in the region would result
2197 // in an overflow, they are not added to the output Region.
transformTouchableRegionSafely(const ui::Transform & t,const Region & r,const std::string & debugWindowName)2198 static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2199                                              const std::string& debugWindowName) {
2200     // Round the translation using the same rounding strategy used by ui::Transform.
2201     const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2202     const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2203 
2204     ui::Transform transformWithoutOffset = t;
2205     transformWithoutOffset.set(0.f, 0.f);
2206 
2207     const Region transformed = transformWithoutOffset.transform(r);
2208 
2209     // Apply the translation to each of the Rects in the region while discarding any that overflow.
2210     Region ret;
2211     for (const auto& rect : transformed) {
2212         Rect newRect;
2213         if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2214             __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2215             __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2216             __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2217             ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2218                   debugWindowName.c_str());
2219             continue;
2220         }
2221         ret.orSelf(newRect);
2222     }
2223     return ret;
2224 }
2225 
fillInputFrameInfo(WindowInfo & info,const ui::Transform & screenToDisplay)2226 void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
2227     Rect tmpBounds = getInputBounds();
2228     if (!tmpBounds.isValid()) {
2229         info.touchableRegion.clear();
2230         // A layer could have invalid input bounds and still expect to receive touch input if it has
2231         // replaceTouchableRegionWithCrop. For that case, the input transform needs to be calculated
2232         // correctly to determine the coordinate space for input events. Use an empty rect so that
2233         // the layer will receive input in its own layer space.
2234         tmpBounds = Rect::EMPTY_RECT;
2235     }
2236 
2237     // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2238     // frame and transform used for the layer, which determines the bounds and the coordinate space
2239     // within which the layer will receive input.
2240     //
2241     // The coordinate space within which each of the bounds are specified is explicitly documented
2242     // in the variable name. For example "inputBoundsInLayer" is specified in layer space. A
2243     // Transform converts one coordinate space to another, which is apparent in its naming. For
2244     // example, "layerToDisplay" transforms layer space to display space.
2245     //
2246     // Coordinate space definitions:
2247     //   - display: The display device's coordinate space. Correlates to pixels on the display.
2248     //   - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2249     //   - layer: The coordinate space of this layer.
2250     //   - input: The coordinate space in which this layer will receive input events. This could be
2251     //            different than layer space if a surfaceInset is used, which changes the origin
2252     //            of the input space.
2253     const FloatRect inputBoundsInLayer = tmpBounds.toFloatRect();
2254 
2255     // Clamp surface inset to the input bounds.
2256     const auto surfaceInset = static_cast<float>(info.surfaceInset);
2257     const float xSurfaceInset =
2258             std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getWidth() / 2.f));
2259     const float ySurfaceInset =
2260             std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getHeight() / 2.f));
2261 
2262     // Apply the insets to the input bounds.
2263     const FloatRect insetBoundsInLayer(inputBoundsInLayer.left + xSurfaceInset,
2264                                        inputBoundsInLayer.top + ySurfaceInset,
2265                                        inputBoundsInLayer.right - xSurfaceInset,
2266                                        inputBoundsInLayer.bottom - ySurfaceInset);
2267 
2268     // Crop the input bounds to ensure it is within the parent's bounds.
2269     const FloatRect croppedInsetBoundsInLayer = mBounds.intersect(insetBoundsInLayer);
2270 
2271     const ui::Transform layerToScreen = getInputTransform();
2272     const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
2273 
2274     const Rect roundedFrameInDisplay{layerToDisplay.transform(croppedInsetBoundsInLayer)};
2275     info.frameLeft = roundedFrameInDisplay.left;
2276     info.frameTop = roundedFrameInDisplay.top;
2277     info.frameRight = roundedFrameInDisplay.right;
2278     info.frameBottom = roundedFrameInDisplay.bottom;
2279 
2280     ui::Transform inputToLayer;
2281     inputToLayer.set(insetBoundsInLayer.left, insetBoundsInLayer.top);
2282     const ui::Transform inputToDisplay = layerToDisplay * inputToLayer;
2283 
2284     // InputDispatcher expects a display-to-input transform.
2285     info.transform = inputToDisplay.inverse();
2286 
2287     // The touchable region is specified in the input coordinate space. Change it to display space.
2288     info.touchableRegion =
2289             transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
2290 }
2291 
fillTouchOcclusionMode(WindowInfo & info)2292 void Layer::fillTouchOcclusionMode(WindowInfo& info) {
2293     sp<Layer> p = this;
2294     while (p != nullptr && !p->hasInputInfo()) {
2295         p = p->mDrawingParent.promote();
2296     }
2297     if (p != nullptr) {
2298         info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2299     }
2300 }
2301 
getDropInputMode() const2302 gui::DropInputMode Layer::getDropInputMode() const {
2303     gui::DropInputMode mode = mDrawingState.dropInputMode;
2304     if (mode == gui::DropInputMode::ALL) {
2305         return mode;
2306     }
2307     sp<Layer> parent = mDrawingParent.promote();
2308     if (parent) {
2309         gui::DropInputMode parentMode = parent->getDropInputMode();
2310         if (parentMode != gui::DropInputMode::NONE) {
2311             return parentMode;
2312         }
2313     }
2314     return mode;
2315 }
2316 
handleDropInputMode(gui::WindowInfo & info) const2317 void Layer::handleDropInputMode(gui::WindowInfo& info) const {
2318     if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
2319         return;
2320     }
2321 
2322     // Check if we need to drop input unconditionally
2323     gui::DropInputMode dropInputMode = getDropInputMode();
2324     if (dropInputMode == gui::DropInputMode::ALL) {
2325         info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
2326         ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2327         return;
2328     }
2329 
2330     // Check if we need to check if the window is obscured by parent
2331     if (dropInputMode != gui::DropInputMode::OBSCURED) {
2332         return;
2333     }
2334 
2335     // Check if the parent has set an alpha on the layer
2336     sp<Layer> parent = mDrawingParent.promote();
2337     if (parent && parent->getAlpha() != 1.0_hf) {
2338         info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
2339         ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2340               static_cast<float>(getAlpha()));
2341     }
2342 
2343     // Check if the parent has cropped the buffer
2344     Rect bufferSize = getCroppedBufferSize(getDrawingState());
2345     if (!bufferSize.isValid()) {
2346         info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
2347         return;
2348     }
2349 
2350     // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2351     // To check if the layer has been cropped, we take the buffer bounds, apply the local
2352     // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2353     // match then the layer has not been cropped by its parents.
2354     Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2355     bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2356 
2357     if (croppedByParent) {
2358         info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
2359         ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2360               getDebugName());
2361     } else {
2362         // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2363         // input if the window is obscured. This check should be done in surfaceflinger but the
2364         // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2365         // drop input events if the window is obscured.
2366         info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
2367     }
2368 }
2369 
fillInputInfo(const InputDisplayArgs & displayArgs)2370 WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
2371     if (!hasInputInfo()) {
2372         mDrawingState.inputInfo.name = getName();
2373         mDrawingState.inputInfo.ownerUid = mOwnerUid;
2374         mDrawingState.inputInfo.ownerPid = mOwnerPid;
2375         mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
2376         mDrawingState.inputInfo.displayId = getLayerStack().id;
2377     }
2378 
2379     const ui::Transform& displayTransform =
2380             displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2381 
2382     WindowInfo info = mDrawingState.inputInfo;
2383     info.id = sequence;
2384     info.displayId = getLayerStack().id;
2385 
2386     fillInputFrameInfo(info, displayTransform);
2387 
2388     if (displayArgs.transform == nullptr) {
2389         // Do not let the window receive touches if it is not associated with a valid display
2390         // transform. We still allow the window to receive keys and prevent ANRs.
2391         info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2392     }
2393 
2394     // For compatibility reasons we let layers which can receive input
2395     // receive input before they have actually submitted a buffer. Because
2396     // of this we use canReceiveInput instead of isVisible to check the
2397     // policy-visibility, ignoring the buffer state. However for layers with
2398     // hasInputInfo()==false we can use the real visibility state.
2399     // We are just using these layers for occlusion detection in
2400     // InputDispatcher, and obviously if they aren't visible they can't occlude
2401     // anything.
2402     const bool visible = hasInputInfo() ? canReceiveInput() : isVisible();
2403     info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
2404 
2405     info.alpha = getAlpha();
2406     fillTouchOcclusionMode(info);
2407     handleDropInputMode(info);
2408 
2409     // If the window will be blacked out on a display because the display does not have the secure
2410     // flag and the layer has the secure flag set, then drop input.
2411     if (!displayArgs.isSecure && isSecure()) {
2412         info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
2413     }
2414 
2415     auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2416     if (info.replaceTouchableRegionWithCrop) {
2417         const Rect bounds(cropLayer ? cropLayer->mScreenBounds : mScreenBounds);
2418         info.touchableRegion = Region(displayTransform.transform(bounds));
2419     } else if (cropLayer != nullptr) {
2420         info.touchableRegion = info.touchableRegion.intersect(
2421                 displayTransform.transform(Rect{cropLayer->mScreenBounds}));
2422     }
2423 
2424     // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2425     // if it was set by WM for a known system overlay
2426     if (isTrustedOverlay()) {
2427         info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2428     }
2429 
2430     // If the layer is a clone, we need to crop the input region to cloned root to prevent
2431     // touches from going outside the cloned area.
2432     if (isClone()) {
2433         info.isClone = true;
2434         if (const sp<Layer> clonedRoot = getClonedRoot()) {
2435             const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
2436             info.touchableRegion = info.touchableRegion.intersect(rect);
2437         }
2438     }
2439 
2440     return info;
2441 }
2442 
getClonedRoot()2443 sp<Layer> Layer::getClonedRoot() {
2444     if (mClonedChild != nullptr) {
2445         return this;
2446     }
2447     if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
2448         return nullptr;
2449     }
2450     return mDrawingParent.promote()->getClonedRoot();
2451 }
2452 
hasInputInfo() const2453 bool Layer::hasInputInfo() const {
2454     return mDrawingState.inputInfo.token != nullptr ||
2455             mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
2456 }
2457 
canReceiveInput() const2458 bool Layer::canReceiveInput() const {
2459     return !isHiddenByPolicy();
2460 }
2461 
findOutputLayerForDisplay(const DisplayDevice * display) const2462 compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
2463         const DisplayDevice* display) const {
2464     if (!display) return nullptr;
2465     return display->getCompositionDisplay()->getOutputLayerForLayer(getCompositionEngineLayerFE());
2466 }
2467 
getVisibleRegion(const DisplayDevice * display) const2468 Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2469     const auto outputLayer = findOutputLayerForDisplay(display);
2470     return outputLayer ? outputLayer->getState().visibleRegion : Region();
2471 }
2472 
setInitialValuesForClone(const sp<Layer> & clonedFrom)2473 void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
2474     cloneDrawingState(clonedFrom.get());
2475     mClonedFrom = clonedFrom;
2476 }
2477 
updateMirrorInfo()2478 void Layer::updateMirrorInfo() {
2479     if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2480         // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2481         // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2482         // that case, we want to delete the reference to the clone since we want it to get
2483         // destroyed. The root, this layer, will still be around since the client can continue
2484         // to hold a reference, but no cloned layers will be displayed.
2485         mClonedChild = nullptr;
2486         return;
2487     }
2488 
2489     std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2490     // If the real layer exists and is in current state, add the clone as a child of the root.
2491     // There's no need to remove from drawingState when the layer is offscreen since currentState is
2492     // copied to drawingState for the root layer. So the clonedChild is always removed from
2493     // drawingState and then needs to be added back each traversal.
2494     if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2495         addChildToDrawing(mClonedChild);
2496     }
2497 
2498     mClonedChild->updateClonedDrawingState(clonedLayersMap);
2499     mClonedChild->updateClonedChildren(this, clonedLayersMap);
2500     mClonedChild->updateClonedRelatives(clonedLayersMap);
2501 }
2502 
updateClonedDrawingState(std::map<sp<Layer>,sp<Layer>> & clonedLayersMap)2503 void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2504     // If the layer the clone was cloned from is alive, copy the content of the drawingState
2505     // to the clone. If the real layer is no longer alive, continue traversing the children
2506     // since we may be able to pull out other children that are still alive.
2507     if (isClonedFromAlive()) {
2508         sp<Layer> clonedFrom = getClonedFrom();
2509         cloneDrawingState(clonedFrom.get());
2510         clonedLayersMap.emplace(clonedFrom, this);
2511     }
2512 
2513     // The clone layer may have children in drawingState since they may have been created and
2514     // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2515     // that already exist, since we can just re-use them.
2516     // The drawingChildren will not get overwritten by the currentChildren since the clones are
2517     // not updated in the regular traversal. They are skipped since the root will lose the
2518     // reference to them when it copies its currentChildren to drawing.
2519     for (sp<Layer>& child : mDrawingChildren) {
2520         child->updateClonedDrawingState(clonedLayersMap);
2521     }
2522 }
2523 
updateClonedChildren(const sp<Layer> & mirrorRoot,std::map<sp<Layer>,sp<Layer>> & clonedLayersMap)2524 void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2525                                  std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2526     mDrawingChildren.clear();
2527 
2528     if (!isClonedFromAlive()) {
2529         return;
2530     }
2531 
2532     sp<Layer> clonedFrom = getClonedFrom();
2533     for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2534         if (child == mirrorRoot) {
2535             // This is to avoid cyclical mirroring.
2536             continue;
2537         }
2538         sp<Layer> clonedChild = clonedLayersMap[child];
2539         if (clonedChild == nullptr) {
2540             clonedChild = child->createClone();
2541             clonedLayersMap[child] = clonedChild;
2542         }
2543         addChildToDrawing(clonedChild);
2544         clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2545     }
2546 }
2547 
updateClonedInputInfo(const std::map<sp<Layer>,sp<Layer>> & clonedLayersMap)2548 void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2549     auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2550     if (cropLayer != nullptr) {
2551         if (clonedLayersMap.count(cropLayer) == 0) {
2552             // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2553             // self as crop layer to avoid going outside bounds.
2554             mDrawingState.touchableRegionCrop = this;
2555         } else {
2556             const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2557             mDrawingState.touchableRegionCrop = clonedCropLayer;
2558         }
2559     }
2560     // Cloned layers shouldn't handle watch outside since their z order is not determined by
2561     // WM or the client.
2562     mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
2563 }
2564 
updateClonedRelatives(const std::map<sp<Layer>,sp<Layer>> & clonedLayersMap)2565 void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2566     mDrawingState.zOrderRelativeOf = nullptr;
2567     mDrawingState.zOrderRelatives.clear();
2568 
2569     if (!isClonedFromAlive()) {
2570         return;
2571     }
2572 
2573     const sp<Layer>& clonedFrom = getClonedFrom();
2574     for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
2575         const sp<Layer>& relative = relativeWeak.promote();
2576         if (clonedLayersMap.count(relative) > 0) {
2577             auto& clonedRelative = clonedLayersMap.at(relative);
2578             mDrawingState.zOrderRelatives.add(clonedRelative);
2579         }
2580     }
2581 
2582     // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2583     // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2584     // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2585     // still traverse the children, but the layer with the missing relativeOf will not be shown
2586     // on screen.
2587     const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2588     if (clonedLayersMap.count(relativeOf) > 0) {
2589         const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
2590         mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2591     }
2592 
2593     updateClonedInputInfo(clonedLayersMap);
2594 
2595     for (sp<Layer>& child : mDrawingChildren) {
2596         child->updateClonedRelatives(clonedLayersMap);
2597     }
2598 }
2599 
addChildToDrawing(const sp<Layer> & layer)2600 void Layer::addChildToDrawing(const sp<Layer>& layer) {
2601     mDrawingChildren.add(layer);
2602     layer->mDrawingParent = this;
2603 }
2604 
convertCompatibility(int8_t compatibility)2605 Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2606     switch (compatibility) {
2607         case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2608             return FrameRateCompatibility::Default;
2609         case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2610             return FrameRateCompatibility::ExactOrMultiple;
2611         case ANATIVEWINDOW_FRAME_RATE_EXACT:
2612             return FrameRateCompatibility::Exact;
2613         case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2614             return FrameRateCompatibility::NoVote;
2615         default:
2616             LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2617             return FrameRateCompatibility::Default;
2618     }
2619 }
2620 
convertChangeFrameRateStrategy(int8_t strategy)2621 scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2622     switch (strategy) {
2623         case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2624             return Seamlessness::OnlySeamless;
2625         case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2626             return Seamlessness::SeamedAndSeamless;
2627         default:
2628             LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2629             return Seamlessness::Default;
2630     }
2631 }
2632 
isInternalDisplayOverlay() const2633 bool Layer::isInternalDisplayOverlay() const {
2634     const State& s(mDrawingState);
2635     if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2636         return true;
2637     }
2638 
2639     sp<Layer> parent = mDrawingParent.promote();
2640     return parent && parent->isInternalDisplayOverlay();
2641 }
2642 
setClonedChild(const sp<Layer> & clonedChild)2643 void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2644     mClonedChild = clonedChild;
2645     mHadClonedChild = true;
2646     mFlinger->mNumClones++;
2647 }
2648 
2649 const String16 Layer::Handle::kDescriptor = String16("android.Layer.Handle");
2650 
fromHandle(const sp<IBinder> & handleBinder)2651 wp<Layer> Layer::fromHandle(const sp<IBinder>& handleBinder) {
2652     if (handleBinder == nullptr) {
2653         return nullptr;
2654     }
2655 
2656     BBinder* b = handleBinder->localBinder();
2657     if (b == nullptr || b->getInterfaceDescriptor() != Handle::kDescriptor) {
2658         return nullptr;
2659     }
2660 
2661     // We can safely cast this binder since its local and we verified its interface descriptor.
2662     sp<Handle> handle = static_cast<Handle*>(handleBinder.get());
2663     return handle->owner;
2664 }
2665 
setDropInputMode(gui::DropInputMode mode)2666 bool Layer::setDropInputMode(gui::DropInputMode mode) {
2667     if (mDrawingState.dropInputMode == mode) {
2668         return false;
2669     }
2670     mDrawingState.dropInputMode = mode;
2671     return true;
2672 }
2673 
cloneDrawingState(const Layer * from)2674 void Layer::cloneDrawingState(const Layer* from) {
2675     mDrawingState = from->mDrawingState;
2676     // Skip callback info since they are not applicable for cloned layers.
2677     mDrawingState.releaseBufferListener = nullptr;
2678     mDrawingState.callbackHandles = {};
2679 }
2680 
setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>> & handles)2681 bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles) {
2682     if (handles.empty()) {
2683         return false;
2684     }
2685 
2686     for (const auto& handle : handles) {
2687         mFlinger->getTransactionCallbackInvoker().registerUnpresentedCallbackHandle(handle);
2688     }
2689 
2690     return true;
2691 }
2692 
2693 // ---------------------------------------------------------------------------
2694 
operator <<(std::ostream & stream,const Layer::FrameRate & rate)2695 std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
2696     return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
2697                   << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
2698 }
2699 
2700 } // namespace android
2701 
2702 #if defined(__gl_h_)
2703 #error "don't include gl/gl.h in this file"
2704 #endif
2705 
2706 #if defined(__gl2_h_)
2707 #error "don't include gl2/gl2.h in this file"
2708 #endif
2709 
2710 // TODO(b/129481165): remove the #pragma below and fix conversion issues
2711 #pragma clang diagnostic pop // ignored "-Wconversion"
2712