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