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