Home | History | Annotate | Download | only in surfaceflinger
      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 //#define LOG_NDEBUG 0
     18 #undef LOG_TAG
     19 #define LOG_TAG "Layer"
     20 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
     21 
     22 #include "Layer.h"
     23 
     24 #include <android-base/stringprintf.h>
     25 #include <compositionengine/Display.h>
     26 #include <compositionengine/Layer.h>
     27 #include <compositionengine/LayerFECompositionState.h>
     28 #include <compositionengine/OutputLayer.h>
     29 #include <compositionengine/impl/LayerCompositionState.h>
     30 #include <compositionengine/impl/OutputLayerCompositionState.h>
     31 #include <cutils/compiler.h>
     32 #include <cutils/native_handle.h>
     33 #include <cutils/properties.h>
     34 #include <gui/BufferItem.h>
     35 #include <gui/LayerDebugInfo.h>
     36 #include <gui/Surface.h>
     37 #include <math.h>
     38 #include <renderengine/RenderEngine.h>
     39 #include <stdint.h>
     40 #include <stdlib.h>
     41 #include <sys/types.h>
     42 #include <ui/DebugUtils.h>
     43 #include <ui/GraphicBuffer.h>
     44 #include <ui/PixelFormat.h>
     45 #include <utils/Errors.h>
     46 #include <utils/Log.h>
     47 #include <utils/NativeHandle.h>
     48 #include <utils/StopWatch.h>
     49 #include <utils/Trace.h>
     50 
     51 #include <algorithm>
     52 #include <mutex>
     53 #include <sstream>
     54 
     55 #include "BufferLayer.h"
     56 #include "ColorLayer.h"
     57 #include "Colorizer.h"
     58 #include "DisplayDevice.h"
     59 #include "DisplayHardware/HWComposer.h"
     60 #include "LayerProtoHelper.h"
     61 #include "LayerRejecter.h"
     62 #include "MonitoredProducer.h"
     63 #include "SurfaceFlinger.h"
     64 #include "TimeStats/TimeStats.h"
     65 
     66 #define DEBUG_RESIZE 0
     67 
     68 namespace android {
     69 
     70 using base::StringAppendF;
     71 
     72 std::atomic<int32_t> Layer::sSequence{1};
     73 
     74 Layer::Layer(const LayerCreationArgs& args)
     75       : mFlinger(args.flinger),
     76         mName(args.name),
     77         mClientRef(args.client),
     78         mWindowType(args.metadata.getInt32(METADATA_WINDOW_TYPE, 0)) {
     79     mCurrentCrop.makeInvalid();
     80 
     81     uint32_t layerFlags = 0;
     82     if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
     83     if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
     84     if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
     85 
     86     mTransactionName = String8("TX - ") + mName;
     87 
     88     mCurrentState.active_legacy.w = args.w;
     89     mCurrentState.active_legacy.h = args.h;
     90     mCurrentState.flags = layerFlags;
     91     mCurrentState.active_legacy.transform.set(0, 0);
     92     mCurrentState.crop_legacy.makeInvalid();
     93     mCurrentState.requestedCrop_legacy = mCurrentState.crop_legacy;
     94     mCurrentState.z = 0;
     95     mCurrentState.color.a = 1.0f;
     96     mCurrentState.layerStack = 0;
     97     mCurrentState.sequence = 0;
     98     mCurrentState.requested_legacy = mCurrentState.active_legacy;
     99     mCurrentState.active.w = UINT32_MAX;
    100     mCurrentState.active.h = UINT32_MAX;
    101     mCurrentState.active.transform.set(0, 0);
    102     mCurrentState.transform = 0;
    103     mCurrentState.transformToDisplayInverse = false;
    104     mCurrentState.crop.makeInvalid();
    105     mCurrentState.acquireFence = new Fence(-1);
    106     mCurrentState.dataspace = ui::Dataspace::UNKNOWN;
    107     mCurrentState.hdrMetadata.validTypes = 0;
    108     mCurrentState.surfaceDamageRegion.clear();
    109     mCurrentState.cornerRadius = 0.0f;
    110     mCurrentState.api = -1;
    111     mCurrentState.hasColorTransform = false;
    112     mCurrentState.colorSpaceAgnostic = false;
    113     mCurrentState.metadata = args.metadata;
    114 
    115     // drawing state & current state are identical
    116     mDrawingState = mCurrentState;
    117 
    118     CompositorTiming compositorTiming;
    119     args.flinger->getCompositorTiming(&compositorTiming);
    120     mFrameEventHistory.initializeCompositorTiming(compositorTiming);
    121     mFrameTracker.setDisplayRefreshPeriod(compositorTiming.interval);
    122 
    123     mSchedulerLayerHandle = mFlinger->mScheduler->registerLayer(mName.c_str(), mWindowType);
    124 
    125     mFlinger->onLayerCreated();
    126 }
    127 
    128 Layer::~Layer() {
    129     sp<Client> c(mClientRef.promote());
    130     if (c != 0) {
    131         c->detachLayer(this);
    132     }
    133 
    134     mFrameTracker.logAndResetStats(mName);
    135     mFlinger->onLayerDestroyed(this);
    136 }
    137 
    138 // ---------------------------------------------------------------------------
    139 // callbacks
    140 // ---------------------------------------------------------------------------
    141 
    142 /*
    143  * onLayerDisplayed is only meaningful for BufferLayer, but, is called through
    144  * Layer.  So, the implementation is done in BufferLayer.  When called on a
    145  * ColorLayer object, it's essentially a NOP.
    146  */
    147 void Layer::onLayerDisplayed(const sp<Fence>& /*releaseFence*/) {}
    148 
    149 void Layer::removeRemoteSyncPoints() {
    150     for (auto& point : mRemoteSyncPoints) {
    151         point->setTransactionApplied();
    152     }
    153     mRemoteSyncPoints.clear();
    154 
    155     {
    156         Mutex::Autolock pendingStateLock(mPendingStateMutex);
    157         for (State pendingState : mPendingStates) {
    158             pendingState.barrierLayer_legacy = nullptr;
    159         }
    160     }
    161 }
    162 
    163 void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
    164     if (mCurrentState.zOrderRelativeOf == nullptr) {
    165         return;
    166     }
    167 
    168     sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
    169     if (strongRelative == nullptr) {
    170         setZOrderRelativeOf(nullptr);
    171         return;
    172     }
    173 
    174     if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
    175         strongRelative->removeZOrderRelative(this);
    176         mFlinger->setTransactionFlags(eTraversalNeeded);
    177         setZOrderRelativeOf(nullptr);
    178     }
    179 }
    180 
    181 void Layer::removeFromCurrentState() {
    182     mRemovedFromCurrentState = true;
    183 
    184     // Since we are no longer reachable from CurrentState SurfaceFlinger
    185     // will no longer invoke doTransaction for us, and so we will
    186     // never finish applying transactions. We signal the sync point
    187     // now so that another layer will not become indefinitely
    188     // blocked.
    189     removeRemoteSyncPoints();
    190 
    191     {
    192     Mutex::Autolock syncLock(mLocalSyncPointMutex);
    193     for (auto& point : mLocalSyncPoints) {
    194         point->setFrameAvailable();
    195     }
    196     mLocalSyncPoints.clear();
    197     }
    198 
    199     mFlinger->markLayerPendingRemovalLocked(this);
    200 }
    201 
    202 void Layer::onRemovedFromCurrentState() {
    203     auto layersInTree = getLayersInTree(LayerVector::StateSet::Current);
    204     std::sort(layersInTree.begin(), layersInTree.end());
    205     for (const auto& layer : layersInTree) {
    206         layer->removeFromCurrentState();
    207         layer->removeRelativeZ(layersInTree);
    208     }
    209 }
    210 
    211 void Layer::addToCurrentState() {
    212     mRemovedFromCurrentState = false;
    213 
    214     for (const auto& child : mCurrentChildren) {
    215         child->addToCurrentState();
    216     }
    217 }
    218 
    219 // ---------------------------------------------------------------------------
    220 // set-up
    221 // ---------------------------------------------------------------------------
    222 
    223 const String8& Layer::getName() const {
    224     return mName;
    225 }
    226 
    227 bool Layer::getPremultipledAlpha() const {
    228     return mPremultipliedAlpha;
    229 }
    230 
    231 sp<IBinder> Layer::getHandle() {
    232     Mutex::Autolock _l(mLock);
    233     if (mGetHandleCalled) {
    234         ALOGE("Get handle called twice" );
    235         return nullptr;
    236     }
    237     mGetHandleCalled = true;
    238     return new Handle(mFlinger, this);
    239 }
    240 
    241 // ---------------------------------------------------------------------------
    242 // h/w composer set-up
    243 // ---------------------------------------------------------------------------
    244 
    245 bool Layer::hasHwcLayer(const sp<const DisplayDevice>& displayDevice) {
    246     auto outputLayer = findOutputLayerForDisplay(displayDevice);
    247     LOG_FATAL_IF(!outputLayer);
    248     return outputLayer->getState().hwc && (*outputLayer->getState().hwc).hwcLayer != nullptr;
    249 }
    250 
    251 HWC2::Layer* Layer::getHwcLayer(const sp<const DisplayDevice>& displayDevice) {
    252     auto outputLayer = findOutputLayerForDisplay(displayDevice);
    253     if (!outputLayer || !outputLayer->getState().hwc) {
    254         return nullptr;
    255     }
    256     return (*outputLayer->getState().hwc).hwcLayer.get();
    257 }
    258 
    259 Rect Layer::getContentCrop() const {
    260     // this is the crop rectangle that applies to the buffer
    261     // itself (as opposed to the window)
    262     Rect crop;
    263     if (!mCurrentCrop.isEmpty()) {
    264         // if the buffer crop is defined, we use that
    265         crop = mCurrentCrop;
    266     } else if (mActiveBuffer != nullptr) {
    267         // otherwise we use the whole buffer
    268         crop = mActiveBuffer->getBounds();
    269     } else {
    270         // if we don't have a buffer yet, we use an empty/invalid crop
    271         crop.makeInvalid();
    272     }
    273     return crop;
    274 }
    275 
    276 static Rect reduce(const Rect& win, const Region& exclude) {
    277     if (CC_LIKELY(exclude.isEmpty())) {
    278         return win;
    279     }
    280     if (exclude.isRect()) {
    281         return win.reduce(exclude.getBounds());
    282     }
    283     return Region(win).subtract(exclude).getBounds();
    284 }
    285 
    286 static FloatRect reduce(const FloatRect& win, const Region& exclude) {
    287     if (CC_LIKELY(exclude.isEmpty())) {
    288         return win;
    289     }
    290     // Convert through Rect (by rounding) for lack of FloatRegion
    291     return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
    292 }
    293 
    294 Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
    295     if (!reduceTransparentRegion) {
    296         return Rect{mScreenBounds};
    297     }
    298 
    299     FloatRect bounds = getBounds();
    300     ui::Transform t = getTransform();
    301     // Transform to screen space.
    302     bounds = t.transform(bounds);
    303     return Rect{bounds};
    304 }
    305 
    306 FloatRect Layer::getBounds() const {
    307     const State& s(getDrawingState());
    308     return getBounds(getActiveTransparentRegion(s));
    309 }
    310 
    311 FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
    312     // Subtract the transparent region and snap to the bounds.
    313     return reduce(mBounds, activeTransparentRegion);
    314 }
    315 
    316 ui::Transform Layer::getBufferScaleTransform() const {
    317     // If the layer is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g.
    318     // it isFixedSize) then there may be additional scaling not accounted
    319     // for in the layer transform.
    320     if (!isFixedSize() || !mActiveBuffer) {
    321         return {};
    322     }
    323 
    324     // If the layer is a buffer state layer, the active width and height
    325     // could be infinite. In that case, return the effective transform.
    326     const uint32_t activeWidth = getActiveWidth(getDrawingState());
    327     const uint32_t activeHeight = getActiveHeight(getDrawingState());
    328     if (activeWidth >= UINT32_MAX && activeHeight >= UINT32_MAX) {
    329         return {};
    330     }
    331 
    332     int bufferWidth = mActiveBuffer->getWidth();
    333     int bufferHeight = mActiveBuffer->getHeight();
    334 
    335     if (mCurrentTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
    336         std::swap(bufferWidth, bufferHeight);
    337     }
    338 
    339     float sx = activeWidth / static_cast<float>(bufferWidth);
    340     float sy = activeHeight / static_cast<float>(bufferHeight);
    341 
    342     ui::Transform extraParentScaling;
    343     extraParentScaling.set(sx, 0, 0, sy);
    344     return extraParentScaling;
    345 }
    346 
    347 ui::Transform Layer::getTransformWithScale(const ui::Transform& bufferScaleTransform) const {
    348     // We need to mirror this scaling to child surfaces or we will break the contract where WM can
    349     // treat child surfaces as pixels in the parent surface.
    350     if (!isFixedSize() || !mActiveBuffer) {
    351         return mEffectiveTransform;
    352     }
    353     return mEffectiveTransform * bufferScaleTransform;
    354 }
    355 
    356 FloatRect Layer::getBoundsPreScaling(const ui::Transform& bufferScaleTransform) const {
    357     // We need the pre scaled layer bounds when computing child bounds to make sure the child is
    358     // cropped to its parent layer after any buffer transform scaling is applied.
    359     if (!isFixedSize() || !mActiveBuffer) {
    360         return mBounds;
    361     }
    362     return bufferScaleTransform.inverse().transform(mBounds);
    363 }
    364 
    365 void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform) {
    366     const State& s(getDrawingState());
    367 
    368     // Calculate effective layer transform
    369     mEffectiveTransform = parentTransform * getActiveTransform(s);
    370 
    371     // Transform parent bounds to layer space
    372     parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
    373 
    374     // Calculate source bounds
    375     mSourceBounds = computeSourceBounds(parentBounds);
    376 
    377     // Calculate bounds by croping diplay frame with layer crop and parent bounds
    378     FloatRect bounds = mSourceBounds;
    379     const Rect layerCrop = getCrop(s);
    380     if (!layerCrop.isEmpty()) {
    381         bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
    382     }
    383     bounds = bounds.intersect(parentBounds);
    384 
    385     mBounds = bounds;
    386     mScreenBounds = mEffectiveTransform.transform(mBounds);
    387 
    388     // Add any buffer scaling to the layer's children.
    389     ui::Transform bufferScaleTransform = getBufferScaleTransform();
    390     for (const sp<Layer>& child : mDrawingChildren) {
    391         child->computeBounds(getBoundsPreScaling(bufferScaleTransform),
    392                              getTransformWithScale(bufferScaleTransform));
    393     }
    394 }
    395 
    396 Rect Layer::getCroppedBufferSize(const State& s) const {
    397     Rect size = getBufferSize(s);
    398     Rect crop = getCrop(s);
    399     if (!crop.isEmpty() && size.isValid()) {
    400         size.intersect(crop, &size);
    401     } else if (!crop.isEmpty()) {
    402         size = crop;
    403     }
    404     return size;
    405 }
    406 
    407 void Layer::setupRoundedCornersCropCoordinates(Rect win,
    408                                                const FloatRect& roundedCornersCrop) const {
    409     // Translate win by the rounded corners rect coordinates, to have all values in
    410     // layer coordinate space.
    411     win.left -= roundedCornersCrop.left;
    412     win.right -= roundedCornersCrop.left;
    413     win.top -= roundedCornersCrop.top;
    414     win.bottom -= roundedCornersCrop.top;
    415 }
    416 
    417 void Layer::latchGeometry(compositionengine::LayerFECompositionState& compositionState) const {
    418     const auto& drawingState{getDrawingState()};
    419     auto alpha = static_cast<float>(getAlpha());
    420     auto blendMode = HWC2::BlendMode::None;
    421     if (!isOpaque(drawingState) || alpha != 1.0f) {
    422         blendMode =
    423                 mPremultipliedAlpha ? HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
    424     }
    425 
    426     int type = drawingState.metadata.getInt32(METADATA_WINDOW_TYPE, 0);
    427     int appId = drawingState.metadata.getInt32(METADATA_OWNER_UID, 0);
    428     sp<Layer> parent = mDrawingParent.promote();
    429     if (parent.get()) {
    430         auto& parentState = parent->getDrawingState();
    431         const int parentType = parentState.metadata.getInt32(METADATA_WINDOW_TYPE, 0);
    432         const int parentAppId = parentState.metadata.getInt32(METADATA_OWNER_UID, 0);
    433         if (parentType >= 0 || parentAppId >= 0) {
    434             type = parentType;
    435             appId = parentAppId;
    436         }
    437     }
    438 
    439     compositionState.geomLayerTransform = getTransform();
    440     compositionState.geomInverseLayerTransform = compositionState.geomLayerTransform.inverse();
    441     compositionState.geomBufferSize = getBufferSize(drawingState);
    442     compositionState.geomContentCrop = getContentCrop();
    443     compositionState.geomCrop = getCrop(drawingState);
    444     compositionState.geomBufferTransform = mCurrentTransform;
    445     compositionState.geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
    446     compositionState.geomActiveTransparentRegion = getActiveTransparentRegion(drawingState);
    447     compositionState.geomLayerBounds = mBounds;
    448     compositionState.geomUsesSourceCrop = usesSourceCrop();
    449     compositionState.isSecure = isSecure();
    450 
    451     compositionState.blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
    452     compositionState.alpha = alpha;
    453     compositionState.type = type;
    454     compositionState.appId = appId;
    455 }
    456 
    457 void Layer::latchCompositionState(compositionengine::LayerFECompositionState& compositionState,
    458                                   bool includeGeometry) const {
    459     if (includeGeometry) {
    460         latchGeometry(compositionState);
    461     }
    462 }
    463 
    464 const char* Layer::getDebugName() const {
    465     return mName.string();
    466 }
    467 
    468 void Layer::forceClientComposition(const sp<DisplayDevice>& display) {
    469     const auto outputLayer = findOutputLayerForDisplay(display);
    470     LOG_FATAL_IF(!outputLayer);
    471     outputLayer->editState().forceClientComposition = true;
    472 }
    473 
    474 bool Layer::getForceClientComposition(const sp<DisplayDevice>& display) {
    475     const auto outputLayer = findOutputLayerForDisplay(display);
    476     LOG_FATAL_IF(!outputLayer);
    477     return outputLayer->getState().forceClientComposition;
    478 }
    479 
    480 void Layer::updateCursorPosition(const sp<const DisplayDevice>& display) {
    481     const auto outputLayer = findOutputLayerForDisplay(display);
    482     LOG_FATAL_IF(!outputLayer);
    483 
    484     if (!outputLayer->getState().hwc ||
    485         (*outputLayer->getState().hwc).hwcCompositionType !=
    486                 Hwc2::IComposerClient::Composition::CURSOR) {
    487         return;
    488     }
    489 
    490     // This gives us only the "orientation" component of the transform
    491     const State& s(getDrawingState());
    492 
    493     // Apply the layer's transform, followed by the display's global transform
    494     // Here we're guaranteed that the layer's transform preserves rects
    495     Rect win = getCroppedBufferSize(s);
    496     // Subtract the transparent region and snap to the bounds
    497     Rect bounds = reduce(win, getActiveTransparentRegion(s));
    498     Rect frame(getTransform().transform(bounds));
    499     frame.intersect(display->getViewport(), &frame);
    500     auto& displayTransform = display->getTransform();
    501     auto position = displayTransform.transform(frame);
    502 
    503     auto error =
    504             (*outputLayer->getState().hwc).hwcLayer->setCursorPosition(position.left, position.top);
    505     ALOGE_IF(error != HWC2::Error::None,
    506              "[%s] Failed to set cursor position "
    507              "to (%d, %d): %s (%d)",
    508              mName.string(), position.left, position.top, to_string(error).c_str(),
    509              static_cast<int32_t>(error));
    510 }
    511 
    512 // ---------------------------------------------------------------------------
    513 // drawing...
    514 // ---------------------------------------------------------------------------
    515 
    516 bool Layer::prepareClientLayer(const RenderArea& renderArea, const Region& clip,
    517                                Region& clearRegion, const bool supportProtectedContent,
    518                                renderengine::LayerSettings& layer) {
    519     return prepareClientLayer(renderArea, clip, false, clearRegion, supportProtectedContent, layer);
    520 }
    521 
    522 bool Layer::prepareClientLayer(const RenderArea& renderArea, bool useIdentityTransform,
    523                                Region& clearRegion, const bool supportProtectedContent,
    524                                renderengine::LayerSettings& layer) {
    525     return prepareClientLayer(renderArea, Region(renderArea.getBounds()), useIdentityTransform,
    526                               clearRegion, supportProtectedContent, layer);
    527 }
    528 
    529 bool Layer::prepareClientLayer(const RenderArea& /*renderArea*/, const Region& /*clip*/,
    530                                bool useIdentityTransform, Region& /*clearRegion*/,
    531                                const bool /*supportProtectedContent*/,
    532                                renderengine::LayerSettings& layer) {
    533     FloatRect bounds = getBounds();
    534     half alpha = getAlpha();
    535     layer.geometry.boundaries = bounds;
    536     if (useIdentityTransform) {
    537         layer.geometry.positionTransform = mat4();
    538     } else {
    539         const ui::Transform transform = getTransform();
    540         mat4 m;
    541         m[0][0] = transform[0][0];
    542         m[0][1] = transform[0][1];
    543         m[0][3] = transform[0][2];
    544         m[1][0] = transform[1][0];
    545         m[1][1] = transform[1][1];
    546         m[1][3] = transform[1][2];
    547         m[3][0] = transform[2][0];
    548         m[3][1] = transform[2][1];
    549         m[3][3] = transform[2][2];
    550         layer.geometry.positionTransform = m;
    551     }
    552 
    553     if (hasColorTransform()) {
    554         layer.colorTransform = getColorTransform();
    555     }
    556 
    557     const auto roundedCornerState = getRoundedCornerState();
    558     layer.geometry.roundedCornersRadius = roundedCornerState.radius;
    559     layer.geometry.roundedCornersCrop = roundedCornerState.cropRect;
    560 
    561     layer.alpha = alpha;
    562     layer.sourceDataspace = mCurrentDataSpace;
    563     return true;
    564 }
    565 
    566 void Layer::setCompositionType(const sp<const DisplayDevice>& display,
    567                                Hwc2::IComposerClient::Composition type) {
    568     const auto outputLayer = findOutputLayerForDisplay(display);
    569     LOG_FATAL_IF(!outputLayer);
    570     LOG_FATAL_IF(!outputLayer->getState().hwc);
    571     auto& compositionState = outputLayer->editState();
    572 
    573     ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", ((*compositionState.hwc).hwcLayer)->getId(),
    574           toString(type).c_str(), 1);
    575     if ((*compositionState.hwc).hwcCompositionType != type) {
    576         ALOGV("    actually setting");
    577         (*compositionState.hwc).hwcCompositionType = type;
    578 
    579         auto error = (*compositionState.hwc)
    580                              .hwcLayer->setCompositionType(static_cast<HWC2::Composition>(type));
    581         ALOGE_IF(error != HWC2::Error::None,
    582                  "[%s] Failed to set "
    583                  "composition type %s: %s (%d)",
    584                  mName.string(), toString(type).c_str(), to_string(error).c_str(),
    585                  static_cast<int32_t>(error));
    586     }
    587 }
    588 
    589 Hwc2::IComposerClient::Composition Layer::getCompositionType(
    590         const sp<const DisplayDevice>& display) const {
    591     const auto outputLayer = findOutputLayerForDisplay(display);
    592     LOG_FATAL_IF(!outputLayer);
    593     return outputLayer->getState().hwc ? (*outputLayer->getState().hwc).hwcCompositionType
    594                                        : Hwc2::IComposerClient::Composition::CLIENT;
    595 }
    596 
    597 bool Layer::getClearClientTarget(const sp<const DisplayDevice>& display) const {
    598     const auto outputLayer = findOutputLayerForDisplay(display);
    599     LOG_FATAL_IF(!outputLayer);
    600     return outputLayer->getState().clearClientTarget;
    601 }
    602 
    603 bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
    604     if (point->getFrameNumber() <= mCurrentFrameNumber) {
    605         // Don't bother with a SyncPoint, since we've already latched the
    606         // relevant frame
    607         return false;
    608     }
    609     if (isRemovedFromCurrentState()) {
    610         return false;
    611     }
    612 
    613     Mutex::Autolock lock(mLocalSyncPointMutex);
    614     mLocalSyncPoints.push_back(point);
    615     return true;
    616 }
    617 
    618 // ----------------------------------------------------------------------------
    619 // local state
    620 // ----------------------------------------------------------------------------
    621 
    622 void Layer::computeGeometry(const RenderArea& renderArea,
    623                             renderengine::Mesh& mesh,
    624                             bool useIdentityTransform) const {
    625     const ui::Transform renderAreaTransform(renderArea.getTransform());
    626     FloatRect win = getBounds();
    627 
    628     vec2 lt = vec2(win.left, win.top);
    629     vec2 lb = vec2(win.left, win.bottom);
    630     vec2 rb = vec2(win.right, win.bottom);
    631     vec2 rt = vec2(win.right, win.top);
    632 
    633     ui::Transform layerTransform = getTransform();
    634     if (!useIdentityTransform) {
    635         lt = layerTransform.transform(lt);
    636         lb = layerTransform.transform(lb);
    637         rb = layerTransform.transform(rb);
    638         rt = layerTransform.transform(rt);
    639     }
    640 
    641     renderengine::Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
    642     position[0] = renderAreaTransform.transform(lt);
    643     position[1] = renderAreaTransform.transform(lb);
    644     position[2] = renderAreaTransform.transform(rb);
    645     position[3] = renderAreaTransform.transform(rt);
    646 }
    647 
    648 bool Layer::isSecure() const {
    649     const State& s(mDrawingState);
    650     return (s.flags & layer_state_t::eLayerSecure);
    651 }
    652 
    653 void Layer::setVisibleRegion(const Region& visibleRegion) {
    654     // always called from main thread
    655     this->visibleRegion = visibleRegion;
    656 }
    657 
    658 void Layer::setCoveredRegion(const Region& coveredRegion) {
    659     // always called from main thread
    660     this->coveredRegion = coveredRegion;
    661 }
    662 
    663 void Layer::setVisibleNonTransparentRegion(const Region& setVisibleNonTransparentRegion) {
    664     // always called from main thread
    665     this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
    666 }
    667 
    668 void Layer::clearVisibilityRegions() {
    669     visibleRegion.clear();
    670     visibleNonTransparentRegion.clear();
    671     coveredRegion.clear();
    672 }
    673 
    674 // ----------------------------------------------------------------------------
    675 // transaction
    676 // ----------------------------------------------------------------------------
    677 
    678 void Layer::pushPendingState() {
    679     if (!mCurrentState.modified) {
    680         return;
    681     }
    682     ATRACE_CALL();
    683 
    684     // If this transaction is waiting on the receipt of a frame, generate a sync
    685     // point and send it to the remote layer.
    686     // We don't allow installing sync points after we are removed from the current state
    687     // as we won't be able to signal our end.
    688     if (mCurrentState.barrierLayer_legacy != nullptr && !isRemovedFromCurrentState()) {
    689         sp<Layer> barrierLayer = mCurrentState.barrierLayer_legacy.promote();
    690         if (barrierLayer == nullptr) {
    691             ALOGE("[%s] Unable to promote barrier Layer.", mName.string());
    692             // If we can't promote the layer we are intended to wait on,
    693             // then it is expired or otherwise invalid. Allow this transaction
    694             // to be applied as per normal (no synchronization).
    695             mCurrentState.barrierLayer_legacy = nullptr;
    696         } else {
    697             auto syncPoint = std::make_shared<SyncPoint>(mCurrentState.frameNumber_legacy, this);
    698             if (barrierLayer->addSyncPoint(syncPoint)) {
    699                 std::stringstream ss;
    700                 ss << "Adding sync point " << mCurrentState.frameNumber_legacy;
    701                 ATRACE_NAME(ss.str().c_str());
    702                 mRemoteSyncPoints.push_back(std::move(syncPoint));
    703             } else {
    704                 // We already missed the frame we're supposed to synchronize
    705                 // on, so go ahead and apply the state update
    706                 mCurrentState.barrierLayer_legacy = nullptr;
    707             }
    708         }
    709 
    710         // Wake us up to check if the frame has been received
    711         setTransactionFlags(eTransactionNeeded);
    712         mFlinger->setTransactionFlags(eTraversalNeeded);
    713     }
    714     mPendingStates.push_back(mCurrentState);
    715     ATRACE_INT(mTransactionName.string(), mPendingStates.size());
    716 }
    717 
    718 void Layer::popPendingState(State* stateToCommit) {
    719     ATRACE_CALL();
    720     *stateToCommit = mPendingStates[0];
    721 
    722     mPendingStates.removeAt(0);
    723     ATRACE_INT(mTransactionName.string(), mPendingStates.size());
    724 }
    725 
    726 bool Layer::applyPendingStates(State* stateToCommit) {
    727     bool stateUpdateAvailable = false;
    728     while (!mPendingStates.empty()) {
    729         if (mPendingStates[0].barrierLayer_legacy != nullptr) {
    730             if (mRemoteSyncPoints.empty()) {
    731                 // If we don't have a sync point for this, apply it anyway. It
    732                 // will be visually wrong, but it should keep us from getting
    733                 // into too much trouble.
    734                 ALOGE("[%s] No local sync point found", mName.string());
    735                 popPendingState(stateToCommit);
    736                 stateUpdateAvailable = true;
    737                 continue;
    738             }
    739 
    740             if (mRemoteSyncPoints.front()->getFrameNumber() !=
    741                 mPendingStates[0].frameNumber_legacy) {
    742                 ALOGE("[%s] Unexpected sync point frame number found", mName.string());
    743 
    744                 // Signal our end of the sync point and then dispose of it
    745                 mRemoteSyncPoints.front()->setTransactionApplied();
    746                 mRemoteSyncPoints.pop_front();
    747                 continue;
    748             }
    749 
    750             if (mRemoteSyncPoints.front()->frameIsAvailable()) {
    751                 ATRACE_NAME("frameIsAvailable");
    752                 // Apply the state update
    753                 popPendingState(stateToCommit);
    754                 stateUpdateAvailable = true;
    755 
    756                 // Signal our end of the sync point and then dispose of it
    757                 mRemoteSyncPoints.front()->setTransactionApplied();
    758                 mRemoteSyncPoints.pop_front();
    759             } else {
    760                 ATRACE_NAME("!frameIsAvailable");
    761                 break;
    762             }
    763         } else {
    764             popPendingState(stateToCommit);
    765             stateUpdateAvailable = true;
    766         }
    767     }
    768 
    769     // If we still have pending updates, wake SurfaceFlinger back up and point
    770     // it at this layer so we can process them
    771     if (!mPendingStates.empty()) {
    772         setTransactionFlags(eTransactionNeeded);
    773         mFlinger->setTransactionFlags(eTraversalNeeded);
    774     }
    775 
    776     mCurrentState.modified = false;
    777     return stateUpdateAvailable;
    778 }
    779 
    780 uint32_t Layer::doTransactionResize(uint32_t flags, State* stateToCommit) {
    781     const State& s(getDrawingState());
    782 
    783     const bool sizeChanged = (stateToCommit->requested_legacy.w != s.requested_legacy.w) ||
    784             (stateToCommit->requested_legacy.h != s.requested_legacy.h);
    785 
    786     if (sizeChanged) {
    787         // the size changed, we need to ask our client to request a new buffer
    788         ALOGD_IF(DEBUG_RESIZE,
    789                  "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
    790                  "  current={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
    791                  "            requested={ wh={%4u,%4u} }}\n"
    792                  "  drawing={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
    793                  "            requested={ wh={%4u,%4u} }}\n",
    794                  this, getName().string(), mCurrentTransform, getEffectiveScalingMode(),
    795                  stateToCommit->active_legacy.w, stateToCommit->active_legacy.h,
    796                  stateToCommit->crop_legacy.left, stateToCommit->crop_legacy.top,
    797                  stateToCommit->crop_legacy.right, stateToCommit->crop_legacy.bottom,
    798                  stateToCommit->crop_legacy.getWidth(), stateToCommit->crop_legacy.getHeight(),
    799                  stateToCommit->requested_legacy.w, stateToCommit->requested_legacy.h,
    800                  s.active_legacy.w, s.active_legacy.h, s.crop_legacy.left, s.crop_legacy.top,
    801                  s.crop_legacy.right, s.crop_legacy.bottom, s.crop_legacy.getWidth(),
    802                  s.crop_legacy.getHeight(), s.requested_legacy.w, s.requested_legacy.h);
    803     }
    804 
    805     // Don't let Layer::doTransaction update the drawing state
    806     // if we have a pending resize, unless we are in fixed-size mode.
    807     // the drawing state will be updated only once we receive a buffer
    808     // with the correct size.
    809     //
    810     // In particular, we want to make sure the clip (which is part
    811     // of the geometry state) is latched together with the size but is
    812     // latched immediately when no resizing is involved.
    813     //
    814     // If a sideband stream is attached, however, we want to skip this
    815     // optimization so that transactions aren't missed when a buffer
    816     // never arrives
    817     //
    818     // In the case that we don't have a buffer we ignore other factors
    819     // and avoid entering the resizePending state. At a high level the
    820     // resizePending state is to avoid applying the state of the new buffer
    821     // to the old buffer. However in the state where we don't have an old buffer
    822     // there is no such concern but we may still be being used as a parent layer.
    823     const bool resizePending =
    824             ((stateToCommit->requested_legacy.w != stateToCommit->active_legacy.w) ||
    825              (stateToCommit->requested_legacy.h != stateToCommit->active_legacy.h)) &&
    826             (mActiveBuffer != nullptr);
    827     if (!isFixedSize()) {
    828         if (resizePending && mSidebandStream == nullptr) {
    829             flags |= eDontUpdateGeometryState;
    830         }
    831     }
    832 
    833     // Here we apply various requested geometry states, depending on our
    834     // latching configuration. See Layer.h for a detailed discussion of
    835     // how geometry latching is controlled.
    836     if (!(flags & eDontUpdateGeometryState)) {
    837         State& editCurrentState(getCurrentState());
    838 
    839         // If mFreezeGeometryUpdates is true we are in the setGeometryAppliesWithResize
    840         // mode, which causes attributes which normally latch regardless of scaling mode,
    841         // to be delayed. We copy the requested state to the active state making sure
    842         // to respect these rules (again see Layer.h for a detailed discussion).
    843         //
    844         // There is an awkward asymmetry in the handling of the crop states in the position
    845         // states, as can be seen below. Largely this arises from position and transform
    846         // being stored in the same data structure while having different latching rules.
    847         // b/38182305
    848         //
    849         // Careful that "stateToCommit" and editCurrentState may not begin as equivalent due to
    850         // applyPendingStates in the presence of deferred transactions.
    851         if (mFreezeGeometryUpdates) {
    852             float tx = stateToCommit->active_legacy.transform.tx();
    853             float ty = stateToCommit->active_legacy.transform.ty();
    854             stateToCommit->active_legacy = stateToCommit->requested_legacy;
    855             stateToCommit->active_legacy.transform.set(tx, ty);
    856             editCurrentState.active_legacy = stateToCommit->active_legacy;
    857         } else {
    858             editCurrentState.active_legacy = editCurrentState.requested_legacy;
    859             stateToCommit->active_legacy = stateToCommit->requested_legacy;
    860         }
    861     }
    862 
    863     return flags;
    864 }
    865 
    866 uint32_t Layer::doTransaction(uint32_t flags) {
    867     ATRACE_CALL();
    868 
    869     if (mLayerDetached) {
    870         return flags;
    871     }
    872 
    873     if (mChildrenChanged) {
    874         flags |= eVisibleRegion;
    875         mChildrenChanged = false;
    876     }
    877 
    878     pushPendingState();
    879     State c = getCurrentState();
    880     if (!applyPendingStates(&c)) {
    881         return flags;
    882     }
    883 
    884     flags = doTransactionResize(flags, &c);
    885 
    886     const State& s(getDrawingState());
    887 
    888     if (getActiveGeometry(c) != getActiveGeometry(s)) {
    889         // invalidate and recompute the visible regions if needed
    890         flags |= Layer::eVisibleRegion;
    891     }
    892 
    893     if (c.sequence != s.sequence) {
    894         // invalidate and recompute the visible regions if needed
    895         flags |= eVisibleRegion;
    896         this->contentDirty = true;
    897 
    898         // we may use linear filtering, if the matrix scales us
    899         const uint8_t type = getActiveTransform(c).getType();
    900         mNeedsFiltering = (!getActiveTransform(c).preserveRects() || type >= ui::Transform::SCALE);
    901     }
    902 
    903     if (mCurrentState.inputInfoChanged) {
    904         flags |= eInputInfoChanged;
    905         mCurrentState.inputInfoChanged = false;
    906     }
    907 
    908     // Commit the transaction
    909     commitTransaction(c);
    910     mCurrentState.callbackHandles = {};
    911     return flags;
    912 }
    913 
    914 void Layer::commitTransaction(const State& stateToCommit) {
    915     mDrawingState = stateToCommit;
    916 }
    917 
    918 uint32_t Layer::getTransactionFlags(uint32_t flags) {
    919     return mTransactionFlags.fetch_and(~flags) & flags;
    920 }
    921 
    922 uint32_t Layer::setTransactionFlags(uint32_t flags) {
    923     return mTransactionFlags.fetch_or(flags);
    924 }
    925 
    926 bool Layer::setPosition(float x, float y, bool immediate) {
    927     if (mCurrentState.requested_legacy.transform.tx() == x &&
    928         mCurrentState.requested_legacy.transform.ty() == y)
    929         return false;
    930     mCurrentState.sequence++;
    931 
    932     // We update the requested and active position simultaneously because
    933     // we want to apply the position portion of the transform matrix immediately,
    934     // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
    935     mCurrentState.requested_legacy.transform.set(x, y);
    936     if (immediate && !mFreezeGeometryUpdates) {
    937         // Here we directly update the active state
    938         // unlike other setters, because we store it within
    939         // the transform, but use different latching rules.
    940         // b/38182305
    941         mCurrentState.active_legacy.transform.set(x, y);
    942     }
    943     mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
    944 
    945     mCurrentState.modified = true;
    946     setTransactionFlags(eTransactionNeeded);
    947     return true;
    948 }
    949 
    950 bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
    951     ssize_t idx = mCurrentChildren.indexOf(childLayer);
    952     if (idx < 0) {
    953         return false;
    954     }
    955     if (childLayer->setLayer(z)) {
    956         mCurrentChildren.removeAt(idx);
    957         mCurrentChildren.add(childLayer);
    958         return true;
    959     }
    960     return false;
    961 }
    962 
    963 bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
    964         const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
    965     ssize_t idx = mCurrentChildren.indexOf(childLayer);
    966     if (idx < 0) {
    967         return false;
    968     }
    969     if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
    970         mCurrentChildren.removeAt(idx);
    971         mCurrentChildren.add(childLayer);
    972         return true;
    973     }
    974     return false;
    975 }
    976 
    977 bool Layer::setLayer(int32_t z) {
    978     if (mCurrentState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
    979     mCurrentState.sequence++;
    980     mCurrentState.z = z;
    981     mCurrentState.modified = true;
    982 
    983     // Discard all relative layering.
    984     if (mCurrentState.zOrderRelativeOf != nullptr) {
    985         sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
    986         if (strongRelative != nullptr) {
    987             strongRelative->removeZOrderRelative(this);
    988         }
    989         setZOrderRelativeOf(nullptr);
    990     }
    991     setTransactionFlags(eTransactionNeeded);
    992     return true;
    993 }
    994 
    995 void Layer::removeZOrderRelative(const wp<Layer>& relative) {
    996     mCurrentState.zOrderRelatives.remove(relative);
    997     mCurrentState.sequence++;
    998     mCurrentState.modified = true;
    999     setTransactionFlags(eTransactionNeeded);
   1000 }
   1001 
   1002 void Layer::addZOrderRelative(const wp<Layer>& relative) {
   1003     mCurrentState.zOrderRelatives.add(relative);
   1004     mCurrentState.modified = true;
   1005     mCurrentState.sequence++;
   1006     setTransactionFlags(eTransactionNeeded);
   1007 }
   1008 
   1009 void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
   1010     mCurrentState.zOrderRelativeOf = relativeOf;
   1011     mCurrentState.sequence++;
   1012     mCurrentState.modified = true;
   1013     setTransactionFlags(eTransactionNeeded);
   1014 }
   1015 
   1016 bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
   1017     sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get());
   1018     if (handle == nullptr) {
   1019         return false;
   1020     }
   1021     sp<Layer> relative = handle->owner.promote();
   1022     if (relative == nullptr) {
   1023         return false;
   1024     }
   1025 
   1026     if (mCurrentState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
   1027         mCurrentState.zOrderRelativeOf == relative) {
   1028         return false;
   1029     }
   1030 
   1031     mCurrentState.sequence++;
   1032     mCurrentState.modified = true;
   1033     mCurrentState.z = relativeZ;
   1034 
   1035     auto oldZOrderRelativeOf = mCurrentState.zOrderRelativeOf.promote();
   1036     if (oldZOrderRelativeOf != nullptr) {
   1037         oldZOrderRelativeOf->removeZOrderRelative(this);
   1038     }
   1039     setZOrderRelativeOf(relative);
   1040     relative->addZOrderRelative(this);
   1041 
   1042     setTransactionFlags(eTransactionNeeded);
   1043 
   1044     return true;
   1045 }
   1046 
   1047 bool Layer::setSize(uint32_t w, uint32_t h) {
   1048     if (mCurrentState.requested_legacy.w == w && mCurrentState.requested_legacy.h == h)
   1049         return false;
   1050     mCurrentState.requested_legacy.w = w;
   1051     mCurrentState.requested_legacy.h = h;
   1052     mCurrentState.modified = true;
   1053     setTransactionFlags(eTransactionNeeded);
   1054 
   1055     // record the new size, from this point on, when the client request
   1056     // a buffer, it'll get the new size.
   1057     setDefaultBufferSize(mCurrentState.requested_legacy.w, mCurrentState.requested_legacy.h);
   1058     return true;
   1059 }
   1060 bool Layer::setAlpha(float alpha) {
   1061     if (mCurrentState.color.a == alpha) return false;
   1062     mCurrentState.sequence++;
   1063     mCurrentState.color.a = alpha;
   1064     mCurrentState.modified = true;
   1065     setTransactionFlags(eTransactionNeeded);
   1066     return true;
   1067 }
   1068 
   1069 bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
   1070     if (!mCurrentState.bgColorLayer && alpha == 0) {
   1071         return false;
   1072     }
   1073     mCurrentState.sequence++;
   1074     mCurrentState.modified = true;
   1075     setTransactionFlags(eTransactionNeeded);
   1076 
   1077     if (!mCurrentState.bgColorLayer && alpha != 0) {
   1078         // create background color layer if one does not yet exist
   1079         uint32_t flags = ISurfaceComposerClient::eFXSurfaceColor;
   1080         const String8& name = mName + "BackgroundColorLayer";
   1081         mCurrentState.bgColorLayer = new ColorLayer(
   1082                 LayerCreationArgs(mFlinger.get(), nullptr, name, 0, 0, flags, LayerMetadata()));
   1083 
   1084         // add to child list
   1085         addChild(mCurrentState.bgColorLayer);
   1086         mFlinger->mLayersAdded = true;
   1087         // set up SF to handle added color layer
   1088         if (isRemovedFromCurrentState()) {
   1089             mCurrentState.bgColorLayer->onRemovedFromCurrentState();
   1090         }
   1091         mFlinger->setTransactionFlags(eTransactionNeeded);
   1092     } else if (mCurrentState.bgColorLayer && alpha == 0) {
   1093         mCurrentState.bgColorLayer->reparent(nullptr);
   1094         mCurrentState.bgColorLayer = nullptr;
   1095         return true;
   1096     }
   1097 
   1098     mCurrentState.bgColorLayer->setColor(color);
   1099     mCurrentState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
   1100     mCurrentState.bgColorLayer->setAlpha(alpha);
   1101     mCurrentState.bgColorLayer->setDataspace(dataspace);
   1102 
   1103     return true;
   1104 }
   1105 
   1106 bool Layer::setCornerRadius(float cornerRadius) {
   1107     if (mCurrentState.cornerRadius == cornerRadius) return false;
   1108 
   1109     mCurrentState.sequence++;
   1110     mCurrentState.cornerRadius = cornerRadius;
   1111     mCurrentState.modified = true;
   1112     setTransactionFlags(eTransactionNeeded);
   1113     return true;
   1114 }
   1115 
   1116 bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix,
   1117         bool allowNonRectPreservingTransforms) {
   1118     ui::Transform t;
   1119     t.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
   1120 
   1121     if (!allowNonRectPreservingTransforms && !t.preserveRects()) {
   1122         ALOGW("Attempt to set rotation matrix without permission ACCESS_SURFACE_FLINGER ignored");
   1123         return false;
   1124     }
   1125     mCurrentState.sequence++;
   1126     mCurrentState.requested_legacy.transform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx,
   1127                                                  matrix.dsdy);
   1128     mCurrentState.modified = true;
   1129     setTransactionFlags(eTransactionNeeded);
   1130     return true;
   1131 }
   1132 
   1133 bool Layer::setTransparentRegionHint(const Region& transparent) {
   1134     mCurrentState.requestedTransparentRegion_legacy = transparent;
   1135     mCurrentState.modified = true;
   1136     setTransactionFlags(eTransactionNeeded);
   1137     return true;
   1138 }
   1139 bool Layer::setFlags(uint8_t flags, uint8_t mask) {
   1140     const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
   1141     if (mCurrentState.flags == newFlags) return false;
   1142     mCurrentState.sequence++;
   1143     mCurrentState.flags = newFlags;
   1144     mCurrentState.modified = true;
   1145     setTransactionFlags(eTransactionNeeded);
   1146     return true;
   1147 }
   1148 
   1149 bool Layer::setCrop_legacy(const Rect& crop, bool immediate) {
   1150     if (mCurrentState.requestedCrop_legacy == crop) return false;
   1151     mCurrentState.sequence++;
   1152     mCurrentState.requestedCrop_legacy = crop;
   1153     if (immediate && !mFreezeGeometryUpdates) {
   1154         mCurrentState.crop_legacy = crop;
   1155     }
   1156     mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
   1157 
   1158     mCurrentState.modified = true;
   1159     setTransactionFlags(eTransactionNeeded);
   1160     return true;
   1161 }
   1162 
   1163 bool Layer::setOverrideScalingMode(int32_t scalingMode) {
   1164     if (scalingMode == mOverrideScalingMode) return false;
   1165     mOverrideScalingMode = scalingMode;
   1166     setTransactionFlags(eTransactionNeeded);
   1167     return true;
   1168 }
   1169 
   1170 bool Layer::setMetadata(const LayerMetadata& data) {
   1171     if (!mCurrentState.metadata.merge(data, true /* eraseEmpty */)) return false;
   1172     mCurrentState.sequence++;
   1173     mCurrentState.modified = true;
   1174     setTransactionFlags(eTransactionNeeded);
   1175     return true;
   1176 }
   1177 
   1178 bool Layer::setLayerStack(uint32_t layerStack) {
   1179     if (mCurrentState.layerStack == layerStack) return false;
   1180     mCurrentState.sequence++;
   1181     mCurrentState.layerStack = layerStack;
   1182     mCurrentState.modified = true;
   1183     setTransactionFlags(eTransactionNeeded);
   1184     return true;
   1185 }
   1186 
   1187 bool Layer::setColorSpaceAgnostic(const bool agnostic) {
   1188     if (mCurrentState.colorSpaceAgnostic == agnostic) {
   1189         return false;
   1190     }
   1191     mCurrentState.sequence++;
   1192     mCurrentState.colorSpaceAgnostic = agnostic;
   1193     mCurrentState.modified = true;
   1194     setTransactionFlags(eTransactionNeeded);
   1195     return true;
   1196 }
   1197 
   1198 uint32_t Layer::getLayerStack() const {
   1199     auto p = mDrawingParent.promote();
   1200     if (p == nullptr) {
   1201         return getDrawingState().layerStack;
   1202     }
   1203     return p->getLayerStack();
   1204 }
   1205 
   1206 void Layer::deferTransactionUntil_legacy(const sp<Layer>& barrierLayer, uint64_t frameNumber) {
   1207     ATRACE_CALL();
   1208     mCurrentState.barrierLayer_legacy = barrierLayer;
   1209     mCurrentState.frameNumber_legacy = frameNumber;
   1210     // We don't set eTransactionNeeded, because just receiving a deferral
   1211     // request without any other state updates shouldn't actually induce a delay
   1212     mCurrentState.modified = true;
   1213     pushPendingState();
   1214     mCurrentState.barrierLayer_legacy = nullptr;
   1215     mCurrentState.frameNumber_legacy = 0;
   1216     mCurrentState.modified = false;
   1217 }
   1218 
   1219 void Layer::deferTransactionUntil_legacy(const sp<IBinder>& barrierHandle, uint64_t frameNumber) {
   1220     sp<Handle> handle = static_cast<Handle*>(barrierHandle.get());
   1221     deferTransactionUntil_legacy(handle->owner.promote(), frameNumber);
   1222 }
   1223 
   1224 // ----------------------------------------------------------------------------
   1225 // pageflip handling...
   1226 // ----------------------------------------------------------------------------
   1227 
   1228 bool Layer::isHiddenByPolicy() const {
   1229     const State& s(mDrawingState);
   1230     const auto& parent = mDrawingParent.promote();
   1231     if (parent != nullptr && parent->isHiddenByPolicy()) {
   1232         return true;
   1233     }
   1234     if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
   1235         auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
   1236         if (zOrderRelativeOf != nullptr) {
   1237             if (zOrderRelativeOf->isHiddenByPolicy()) {
   1238                 return true;
   1239             }
   1240         }
   1241     }
   1242     return s.flags & layer_state_t::eLayerHidden;
   1243 }
   1244 
   1245 uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
   1246     // TODO: should we do something special if mSecure is set?
   1247     if (mProtectedByApp) {
   1248         // need a hardware-protected path to external video sink
   1249         usage |= GraphicBuffer::USAGE_PROTECTED;
   1250     }
   1251     if (mPotentialCursor) {
   1252         usage |= GraphicBuffer::USAGE_CURSOR;
   1253     }
   1254     usage |= GraphicBuffer::USAGE_HW_COMPOSER;
   1255     return usage;
   1256 }
   1257 
   1258 void Layer::updateTransformHint(const sp<const DisplayDevice>& display) const {
   1259     uint32_t orientation = 0;
   1260     // Disable setting transform hint if the debug flag is set.
   1261     if (!mFlinger->mDebugDisableTransformHint) {
   1262         // The transform hint is used to improve performance, but we can
   1263         // only have a single transform hint, it cannot
   1264         // apply to all displays.
   1265         const ui::Transform& planeTransform = display->getTransform();
   1266         orientation = planeTransform.getOrientation();
   1267         if (orientation & ui::Transform::ROT_INVALID) {
   1268             orientation = 0;
   1269         }
   1270     }
   1271     setTransformHint(orientation);
   1272 }
   1273 
   1274 // ----------------------------------------------------------------------------
   1275 // debugging
   1276 // ----------------------------------------------------------------------------
   1277 
   1278 // TODO(marissaw): add new layer state info to layer debugging
   1279 LayerDebugInfo Layer::getLayerDebugInfo() const {
   1280     LayerDebugInfo info;
   1281     const State& ds = getDrawingState();
   1282     info.mName = getName();
   1283     sp<Layer> parent = getParent();
   1284     info.mParentName = (parent == nullptr ? std::string("none") : parent->getName().string());
   1285     info.mType = std::string(getTypeId());
   1286     info.mTransparentRegion = ds.activeTransparentRegion_legacy;
   1287     info.mVisibleRegion = visibleRegion;
   1288     info.mSurfaceDamageRegion = surfaceDamageRegion;
   1289     info.mLayerStack = getLayerStack();
   1290     info.mX = ds.active_legacy.transform.tx();
   1291     info.mY = ds.active_legacy.transform.ty();
   1292     info.mZ = ds.z;
   1293     info.mWidth = ds.active_legacy.w;
   1294     info.mHeight = ds.active_legacy.h;
   1295     info.mCrop = ds.crop_legacy;
   1296     info.mColor = ds.color;
   1297     info.mFlags = ds.flags;
   1298     info.mPixelFormat = getPixelFormat();
   1299     info.mDataSpace = static_cast<android_dataspace>(mCurrentDataSpace);
   1300     info.mMatrix[0][0] = ds.active_legacy.transform[0][0];
   1301     info.mMatrix[0][1] = ds.active_legacy.transform[0][1];
   1302     info.mMatrix[1][0] = ds.active_legacy.transform[1][0];
   1303     info.mMatrix[1][1] = ds.active_legacy.transform[1][1];
   1304     {
   1305         sp<const GraphicBuffer> buffer = mActiveBuffer;
   1306         if (buffer != 0) {
   1307             info.mActiveBufferWidth = buffer->getWidth();
   1308             info.mActiveBufferHeight = buffer->getHeight();
   1309             info.mActiveBufferStride = buffer->getStride();
   1310             info.mActiveBufferFormat = buffer->format;
   1311         } else {
   1312             info.mActiveBufferWidth = 0;
   1313             info.mActiveBufferHeight = 0;
   1314             info.mActiveBufferStride = 0;
   1315             info.mActiveBufferFormat = 0;
   1316         }
   1317     }
   1318     info.mNumQueuedFrames = getQueuedFrameCount();
   1319     info.mRefreshPending = isBufferLatched();
   1320     info.mIsOpaque = isOpaque(ds);
   1321     info.mContentDirty = contentDirty;
   1322     return info;
   1323 }
   1324 
   1325 void Layer::miniDumpHeader(std::string& result) {
   1326     result.append("-------------------------------");
   1327     result.append("-------------------------------");
   1328     result.append("-----------------------------\n");
   1329     result.append(" Layer name\n");
   1330     result.append("           Z | ");
   1331     result.append(" Window Type | ");
   1332     result.append(" Comp Type | ");
   1333     result.append(" Transform | ");
   1334     result.append("  Disp Frame (LTRB) | ");
   1335     result.append("         Source Crop (LTRB)\n");
   1336     result.append("-------------------------------");
   1337     result.append("-------------------------------");
   1338     result.append("-----------------------------\n");
   1339 }
   1340 
   1341 void Layer::miniDump(std::string& result, const sp<DisplayDevice>& displayDevice) const {
   1342     auto outputLayer = findOutputLayerForDisplay(displayDevice);
   1343     if (!outputLayer) {
   1344         return;
   1345     }
   1346 
   1347     std::string name;
   1348     if (mName.length() > 77) {
   1349         std::string shortened;
   1350         shortened.append(mName.string(), 36);
   1351         shortened.append("[...]");
   1352         shortened.append(mName.string() + (mName.length() - 36), 36);
   1353         name = shortened;
   1354     } else {
   1355         name = std::string(mName.string(), mName.size());
   1356     }
   1357 
   1358     StringAppendF(&result, " %s\n", name.c_str());
   1359 
   1360     const State& layerState(getDrawingState());
   1361     const auto& compositionState = outputLayer->getState();
   1362 
   1363     if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
   1364         StringAppendF(&result, "  rel %6d | ", layerState.z);
   1365     } else {
   1366         StringAppendF(&result, "  %10d | ", layerState.z);
   1367     }
   1368     StringAppendF(&result, "  %10d | ", mWindowType);
   1369     StringAppendF(&result, "%10s | ", toString(getCompositionType(displayDevice)).c_str());
   1370     StringAppendF(&result, "%10s | ",
   1371                   toString(getCompositionLayer() ? compositionState.bufferTransform
   1372                                                  : static_cast<Hwc2::Transform>(0))
   1373                           .c_str());
   1374     const Rect& frame = compositionState.displayFrame;
   1375     StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
   1376     const FloatRect& crop = compositionState.sourceCrop;
   1377     StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top, crop.right,
   1378                   crop.bottom);
   1379 
   1380     result.append("- - - - - - - - - - - - - - - -");
   1381     result.append("- - - - - - - - - - - - - - - -");
   1382     result.append("- - - - - - - - - - - - - - -\n");
   1383 }
   1384 
   1385 void Layer::dumpFrameStats(std::string& result) const {
   1386     mFrameTracker.dumpStats(result);
   1387 }
   1388 
   1389 void Layer::clearFrameStats() {
   1390     mFrameTracker.clearStats();
   1391 }
   1392 
   1393 void Layer::logFrameStats() {
   1394     mFrameTracker.logAndResetStats(mName);
   1395 }
   1396 
   1397 void Layer::getFrameStats(FrameStats* outStats) const {
   1398     mFrameTracker.getStats(outStats);
   1399 }
   1400 
   1401 void Layer::dumpFrameEvents(std::string& result) {
   1402     StringAppendF(&result, "- Layer %s (%s, %p)\n", getName().string(), getTypeId(), this);
   1403     Mutex::Autolock lock(mFrameEventHistoryMutex);
   1404     mFrameEventHistory.checkFencesForCompletion();
   1405     mFrameEventHistory.dump(result);
   1406 }
   1407 
   1408 void Layer::onDisconnect() {
   1409     Mutex::Autolock lock(mFrameEventHistoryMutex);
   1410     mFrameEventHistory.onDisconnect();
   1411     mFlinger->mTimeStats->onDestroy(getSequence());
   1412 }
   1413 
   1414 void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
   1415                                      FrameEventHistoryDelta* outDelta) {
   1416     if (newTimestamps) {
   1417         mFlinger->mTimeStats->setPostTime(getSequence(), newTimestamps->frameNumber,
   1418                                           getName().c_str(), newTimestamps->postedTime);
   1419     }
   1420 
   1421     Mutex::Autolock lock(mFrameEventHistoryMutex);
   1422     if (newTimestamps) {
   1423         // If there are any unsignaled fences in the aquire timeline at this
   1424         // point, the previously queued frame hasn't been latched yet. Go ahead
   1425         // and try to get the signal time here so the syscall is taken out of
   1426         // the main thread's critical path.
   1427         mAcquireTimeline.updateSignalTimes();
   1428         // Push the new fence after updating since it's likely still pending.
   1429         mAcquireTimeline.push(newTimestamps->acquireFence);
   1430         mFrameEventHistory.addQueue(*newTimestamps);
   1431     }
   1432 
   1433     if (outDelta) {
   1434         mFrameEventHistory.getAndResetDelta(outDelta);
   1435     }
   1436 }
   1437 
   1438 size_t Layer::getChildrenCount() const {
   1439     size_t count = 0;
   1440     for (const sp<Layer>& child : mCurrentChildren) {
   1441         count += 1 + child->getChildrenCount();
   1442     }
   1443     return count;
   1444 }
   1445 
   1446 void Layer::addChild(const sp<Layer>& layer) {
   1447     mChildrenChanged = true;
   1448     setTransactionFlags(eTransactionNeeded);
   1449 
   1450     mCurrentChildren.add(layer);
   1451     layer->setParent(this);
   1452 }
   1453 
   1454 ssize_t Layer::removeChild(const sp<Layer>& layer) {
   1455     mChildrenChanged = true;
   1456     setTransactionFlags(eTransactionNeeded);
   1457 
   1458     layer->setParent(nullptr);
   1459     return mCurrentChildren.remove(layer);
   1460 }
   1461 
   1462 bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
   1463     sp<Handle> handle = nullptr;
   1464     sp<Layer> newParent = nullptr;
   1465     if (newParentHandle == nullptr) {
   1466         return false;
   1467     }
   1468     handle = static_cast<Handle*>(newParentHandle.get());
   1469     newParent = handle->owner.promote();
   1470     if (newParent == nullptr) {
   1471         ALOGE("Unable to promote Layer handle");
   1472         return false;
   1473     }
   1474 
   1475     if (attachChildren()) {
   1476         setTransactionFlags(eTransactionNeeded);
   1477     }
   1478     for (const sp<Layer>& child : mCurrentChildren) {
   1479         newParent->addChild(child);
   1480     }
   1481     mCurrentChildren.clear();
   1482 
   1483     return true;
   1484 }
   1485 
   1486 void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
   1487     for (const sp<Layer>& child : mDrawingChildren) {
   1488         child->mDrawingParent = newParent;
   1489         child->computeBounds(newParent->mBounds,
   1490                              newParent->getTransformWithScale(
   1491                                      newParent->getBufferScaleTransform()));
   1492     }
   1493 }
   1494 
   1495 bool Layer::reparent(const sp<IBinder>& newParentHandle) {
   1496     bool callSetTransactionFlags = false;
   1497 
   1498     // While layers are detached, we allow most operations
   1499     // and simply halt performing the actual transaction. However
   1500     // for reparent != null we would enter the mRemovedFromCurrentState
   1501     // state, regardless of whether doTransaction was called, and
   1502     // so we need to prevent the update here.
   1503     if (mLayerDetached && newParentHandle == nullptr) {
   1504         return false;
   1505     }
   1506 
   1507     sp<Layer> newParent;
   1508     if (newParentHandle != nullptr) {
   1509         auto handle = static_cast<Handle*>(newParentHandle.get());
   1510         newParent = handle->owner.promote();
   1511         if (newParent == nullptr) {
   1512             ALOGE("Unable to promote Layer handle");
   1513             return false;
   1514         }
   1515         if (newParent == this) {
   1516             ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
   1517             return false;
   1518         }
   1519     }
   1520 
   1521     sp<Layer> parent = getParent();
   1522     if (parent != nullptr) {
   1523         parent->removeChild(this);
   1524     }
   1525 
   1526     if (newParentHandle != nullptr) {
   1527         newParent->addChild(this);
   1528         if (!newParent->isRemovedFromCurrentState()) {
   1529             addToCurrentState();
   1530         } else {
   1531             onRemovedFromCurrentState();
   1532         }
   1533 
   1534         if (mLayerDetached) {
   1535             mLayerDetached = false;
   1536             callSetTransactionFlags = true;
   1537         }
   1538     } else {
   1539         onRemovedFromCurrentState();
   1540     }
   1541 
   1542     if (callSetTransactionFlags || attachChildren()) {
   1543         setTransactionFlags(eTransactionNeeded);
   1544     }
   1545     return true;
   1546 }
   1547 
   1548 bool Layer::detachChildren() {
   1549     for (const sp<Layer>& child : mCurrentChildren) {
   1550         sp<Client> parentClient = mClientRef.promote();
   1551         sp<Client> client(child->mClientRef.promote());
   1552         if (client != nullptr && parentClient != client) {
   1553             child->mLayerDetached = true;
   1554             child->detachChildren();
   1555             child->removeRemoteSyncPoints();
   1556         }
   1557     }
   1558 
   1559     return true;
   1560 }
   1561 
   1562 bool Layer::attachChildren() {
   1563     bool changed = false;
   1564     for (const sp<Layer>& child : mCurrentChildren) {
   1565         sp<Client> parentClient = mClientRef.promote();
   1566         sp<Client> client(child->mClientRef.promote());
   1567         if (client != nullptr && parentClient != client) {
   1568             if (child->mLayerDetached) {
   1569                 child->mLayerDetached = false;
   1570                 changed = true;
   1571             }
   1572             changed |= child->attachChildren();
   1573         }
   1574     }
   1575 
   1576     return changed;
   1577 }
   1578 
   1579 bool Layer::setColorTransform(const mat4& matrix) {
   1580     static const mat4 identityMatrix = mat4();
   1581 
   1582     if (mCurrentState.colorTransform == matrix) {
   1583         return false;
   1584     }
   1585     ++mCurrentState.sequence;
   1586     mCurrentState.colorTransform = matrix;
   1587     mCurrentState.hasColorTransform = matrix != identityMatrix;
   1588     mCurrentState.modified = true;
   1589     setTransactionFlags(eTransactionNeeded);
   1590     return true;
   1591 }
   1592 
   1593 mat4 Layer::getColorTransform() const {
   1594     mat4 colorTransform = mat4(getDrawingState().colorTransform);
   1595     if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
   1596         colorTransform = parent->getColorTransform() * colorTransform;
   1597     }
   1598     return colorTransform;
   1599 }
   1600 
   1601 bool Layer::hasColorTransform() const {
   1602     bool hasColorTransform = getDrawingState().hasColorTransform;
   1603     if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
   1604         hasColorTransform = hasColorTransform || parent->hasColorTransform();
   1605     }
   1606     return hasColorTransform;
   1607 }
   1608 
   1609 bool Layer::isLegacyDataSpace() const {
   1610     // return true when no higher bits are set
   1611     return !(mCurrentDataSpace & (ui::Dataspace::STANDARD_MASK |
   1612                 ui::Dataspace::TRANSFER_MASK | ui::Dataspace::RANGE_MASK));
   1613 }
   1614 
   1615 void Layer::setParent(const sp<Layer>& layer) {
   1616     mCurrentParent = layer;
   1617 }
   1618 
   1619 int32_t Layer::getZ() const {
   1620     return mDrawingState.z;
   1621 }
   1622 
   1623 bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
   1624     const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
   1625     const State& state = useDrawing ? mDrawingState : mCurrentState;
   1626     return state.zOrderRelativeOf != nullptr;
   1627 }
   1628 
   1629 __attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
   1630         LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
   1631     LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
   1632                         "makeTraversalList received invalid stateSet");
   1633     const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
   1634     const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
   1635     const State& state = useDrawing ? mDrawingState : mCurrentState;
   1636 
   1637     if (state.zOrderRelatives.size() == 0) {
   1638         *outSkipRelativeZUsers = true;
   1639         return children;
   1640     }
   1641 
   1642     LayerVector traverse(stateSet);
   1643     for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
   1644         sp<Layer> strongRelative = weakRelative.promote();
   1645         if (strongRelative != nullptr) {
   1646             traverse.add(strongRelative);
   1647         }
   1648     }
   1649 
   1650     for (const sp<Layer>& child : children) {
   1651         const State& childState = useDrawing ? child->mDrawingState : child->mCurrentState;
   1652         if (childState.zOrderRelativeOf != nullptr) {
   1653             continue;
   1654         }
   1655         traverse.add(child);
   1656     }
   1657 
   1658     return traverse;
   1659 }
   1660 
   1661 /**
   1662  * Negatively signed relatives are before 'this' in Z-order.
   1663  */
   1664 void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
   1665     // In the case we have other layers who are using a relative Z to us, makeTraversalList will
   1666     // produce a new list for traversing, including our relatives, and not including our children
   1667     // who are relatives of another surface. In the case that there are no relative Z,
   1668     // makeTraversalList returns our children directly to avoid significant overhead.
   1669     // However in this case we need to take the responsibility for filtering children which
   1670     // are relatives of another surface here.
   1671     bool skipRelativeZUsers = false;
   1672     const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
   1673 
   1674     size_t i = 0;
   1675     for (; i < list.size(); i++) {
   1676         const auto& relative = list[i];
   1677         if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
   1678             continue;
   1679         }
   1680 
   1681         if (relative->getZ() >= 0) {
   1682             break;
   1683         }
   1684         relative->traverseInZOrder(stateSet, visitor);
   1685     }
   1686 
   1687     visitor(this);
   1688     for (; i < list.size(); i++) {
   1689         const auto& relative = list[i];
   1690 
   1691         if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
   1692             continue;
   1693         }
   1694         relative->traverseInZOrder(stateSet, visitor);
   1695     }
   1696 }
   1697 
   1698 /**
   1699  * Positively signed relatives are before 'this' in reverse Z-order.
   1700  */
   1701 void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
   1702                                     const LayerVector::Visitor& visitor) {
   1703     // See traverseInZOrder for documentation.
   1704     bool skipRelativeZUsers = false;
   1705     LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
   1706 
   1707     int32_t i = 0;
   1708     for (i = int32_t(list.size()) - 1; i >= 0; i--) {
   1709         const auto& relative = list[i];
   1710 
   1711         if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
   1712             continue;
   1713         }
   1714 
   1715         if (relative->getZ() < 0) {
   1716             break;
   1717         }
   1718         relative->traverseInReverseZOrder(stateSet, visitor);
   1719     }
   1720     visitor(this);
   1721     for (; i >= 0; i--) {
   1722         const auto& relative = list[i];
   1723 
   1724         if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
   1725             continue;
   1726         }
   1727 
   1728         relative->traverseInReverseZOrder(stateSet, visitor);
   1729     }
   1730 }
   1731 
   1732 LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
   1733                                              const std::vector<Layer*>& layersInTree) {
   1734     LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
   1735                         "makeTraversalList received invalid stateSet");
   1736     const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
   1737     const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
   1738     const State& state = useDrawing ? mDrawingState : mCurrentState;
   1739 
   1740     LayerVector traverse(stateSet);
   1741     for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
   1742         sp<Layer> strongRelative = weakRelative.promote();
   1743         // Only add relative layers that are also descendents of the top most parent of the tree.
   1744         // If a relative layer is not a descendent, then it should be ignored.
   1745         if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
   1746             traverse.add(strongRelative);
   1747         }
   1748     }
   1749 
   1750     for (const sp<Layer>& child : children) {
   1751         const State& childState = useDrawing ? child->mDrawingState : child->mCurrentState;
   1752         // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
   1753         // descendent of the top most parent of the tree. If it's not a descendent, then just add
   1754         // the child here since it won't be added later as a relative.
   1755         if (std::binary_search(layersInTree.begin(), layersInTree.end(),
   1756                                childState.zOrderRelativeOf.promote().get())) {
   1757             continue;
   1758         }
   1759         traverse.add(child);
   1760     }
   1761 
   1762     return traverse;
   1763 }
   1764 
   1765 void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
   1766                                           LayerVector::StateSet stateSet,
   1767                                           const LayerVector::Visitor& visitor) {
   1768     const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
   1769 
   1770     size_t i = 0;
   1771     for (; i < list.size(); i++) {
   1772         const auto& relative = list[i];
   1773         if (relative->getZ() >= 0) {
   1774             break;
   1775         }
   1776         relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
   1777     }
   1778 
   1779     visitor(this);
   1780     for (; i < list.size(); i++) {
   1781         const auto& relative = list[i];
   1782         relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
   1783     }
   1784 }
   1785 
   1786 std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
   1787     const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
   1788     const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
   1789 
   1790     std::vector<Layer*> layersInTree = {this};
   1791     for (size_t i = 0; i < children.size(); i++) {
   1792         const auto& child = children[i];
   1793         std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
   1794         layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
   1795     }
   1796 
   1797     return layersInTree;
   1798 }
   1799 
   1800 void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
   1801                                      const LayerVector::Visitor& visitor) {
   1802     std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
   1803     std::sort(layersInTree.begin(), layersInTree.end());
   1804     traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
   1805 }
   1806 
   1807 ui::Transform Layer::getTransform() const {
   1808     return mEffectiveTransform;
   1809 }
   1810 
   1811 half Layer::getAlpha() const {
   1812     const auto& p = mDrawingParent.promote();
   1813 
   1814     half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
   1815     return parentAlpha * getDrawingState().color.a;
   1816 }
   1817 
   1818 half4 Layer::getColor() const {
   1819     const half4 color(getDrawingState().color);
   1820     return half4(color.r, color.g, color.b, getAlpha());
   1821 }
   1822 
   1823 Layer::RoundedCornerState Layer::getRoundedCornerState() const {
   1824     const auto& p = mDrawingParent.promote();
   1825     if (p != nullptr) {
   1826         RoundedCornerState parentState = p->getRoundedCornerState();
   1827         if (parentState.radius > 0) {
   1828             ui::Transform t = getActiveTransform(getDrawingState());
   1829             t = t.inverse();
   1830             parentState.cropRect = t.transform(parentState.cropRect);
   1831             // The rounded corners shader only accepts 1 corner radius for performance reasons,
   1832             // but a transform matrix can define horizontal and vertical scales.
   1833             // Let's take the average between both of them and pass into the shader, practically we
   1834             // never do this type of transformation on windows anyway.
   1835             parentState.radius *= (t[0][0] + t[1][1]) / 2.0f;
   1836             return parentState;
   1837         }
   1838     }
   1839     const float radius = getDrawingState().cornerRadius;
   1840     return radius > 0 && getCrop(getDrawingState()).isValid()
   1841             ? RoundedCornerState(getCrop(getDrawingState()).toFloatRect(), radius)
   1842             : RoundedCornerState();
   1843 }
   1844 
   1845 void Layer::commitChildList() {
   1846     for (size_t i = 0; i < mCurrentChildren.size(); i++) {
   1847         const auto& child = mCurrentChildren[i];
   1848         child->commitChildList();
   1849     }
   1850     mDrawingChildren = mCurrentChildren;
   1851     mDrawingParent = mCurrentParent;
   1852 }
   1853 
   1854 static wp<Layer> extractLayerFromBinder(const wp<IBinder>& weakBinderHandle) {
   1855     if (weakBinderHandle == nullptr) {
   1856         return nullptr;
   1857     }
   1858     sp<IBinder> binderHandle = weakBinderHandle.promote();
   1859     if (binderHandle == nullptr) {
   1860         return nullptr;
   1861     }
   1862     sp<Layer::Handle> handle = static_cast<Layer::Handle*>(binderHandle.get());
   1863     if (handle == nullptr) {
   1864         return nullptr;
   1865     }
   1866     return handle->owner;
   1867 }
   1868 
   1869 void Layer::setInputInfo(const InputWindowInfo& info) {
   1870     mCurrentState.inputInfo = info;
   1871     mCurrentState.touchableRegionCrop = extractLayerFromBinder(info.touchableRegionCropHandle);
   1872     mCurrentState.modified = true;
   1873     mCurrentState.inputInfoChanged = true;
   1874     setTransactionFlags(eTransactionNeeded);
   1875 }
   1876 
   1877 void Layer::writeToProto(LayerProto* layerInfo, LayerVector::StateSet stateSet,
   1878                          uint32_t traceFlags) {
   1879     const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
   1880     const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
   1881     const State& state = useDrawing ? mDrawingState : mCurrentState;
   1882 
   1883     ui::Transform requestedTransform = state.active_legacy.transform;
   1884     ui::Transform transform = getTransform();
   1885 
   1886     if (traceFlags & SurfaceTracing::TRACE_CRITICAL) {
   1887         layerInfo->set_id(sequence);
   1888         layerInfo->set_name(getName().c_str());
   1889         layerInfo->set_type(String8(getTypeId()));
   1890 
   1891         for (const auto& child : children) {
   1892             layerInfo->add_children(child->sequence);
   1893         }
   1894 
   1895         for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
   1896             sp<Layer> strongRelative = weakRelative.promote();
   1897             if (strongRelative != nullptr) {
   1898                 layerInfo->add_relatives(strongRelative->sequence);
   1899             }
   1900         }
   1901 
   1902         LayerProtoHelper::writeToProto(state.activeTransparentRegion_legacy,
   1903                                        [&]() { return layerInfo->mutable_transparent_region(); });
   1904         LayerProtoHelper::writeToProto(visibleRegion,
   1905                                        [&]() { return layerInfo->mutable_visible_region(); });
   1906         LayerProtoHelper::writeToProto(surfaceDamageRegion,
   1907                                        [&]() { return layerInfo->mutable_damage_region(); });
   1908 
   1909         layerInfo->set_layer_stack(getLayerStack());
   1910         layerInfo->set_z(state.z);
   1911 
   1912         LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
   1913                                                [&]() { return layerInfo->mutable_position(); });
   1914 
   1915         LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(),
   1916                                                [&]() {
   1917                                                    return layerInfo->mutable_requested_position();
   1918                                                });
   1919 
   1920         LayerProtoHelper::writeSizeToProto(state.active_legacy.w, state.active_legacy.h,
   1921                                            [&]() { return layerInfo->mutable_size(); });
   1922 
   1923         LayerProtoHelper::writeToProto(state.crop_legacy,
   1924                                        [&]() { return layerInfo->mutable_crop(); });
   1925         layerInfo->set_corner_radius(getRoundedCornerState().radius);
   1926 
   1927         layerInfo->set_is_opaque(isOpaque(state));
   1928         layerInfo->set_invalidate(contentDirty);
   1929         layerInfo->set_is_protected(isProtected());
   1930 
   1931         // XXX (b/79210409) mCurrentDataSpace is not protected
   1932         layerInfo->set_dataspace(
   1933                 dataspaceDetails(static_cast<android_dataspace>(mCurrentDataSpace)));
   1934 
   1935         layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
   1936         LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
   1937         LayerProtoHelper::writeToProto(state.color,
   1938                                        [&]() { return layerInfo->mutable_requested_color(); });
   1939         layerInfo->set_flags(state.flags);
   1940 
   1941         LayerProtoHelper::writeToProto(transform, layerInfo->mutable_transform());
   1942         LayerProtoHelper::writeToProto(requestedTransform,
   1943                                        layerInfo->mutable_requested_transform());
   1944 
   1945         auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
   1946         if (parent != nullptr) {
   1947             layerInfo->set_parent(parent->sequence);
   1948         } else {
   1949             layerInfo->set_parent(-1);
   1950         }
   1951 
   1952         auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
   1953         if (zOrderRelativeOf != nullptr) {
   1954             layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
   1955         } else {
   1956             layerInfo->set_z_order_relative_of(-1);
   1957         }
   1958 
   1959         auto buffer = mActiveBuffer;
   1960         if (buffer != nullptr) {
   1961             LayerProtoHelper::writeToProto(buffer,
   1962                                            [&]() { return layerInfo->mutable_active_buffer(); });
   1963             LayerProtoHelper::writeToProto(ui::Transform(mCurrentTransform),
   1964                                            layerInfo->mutable_buffer_transform());
   1965         }
   1966 
   1967         layerInfo->set_queued_frames(getQueuedFrameCount());
   1968         layerInfo->set_refresh_pending(isBufferLatched());
   1969         layerInfo->set_curr_frame(mCurrentFrameNumber);
   1970         layerInfo->set_effective_scaling_mode(getEffectiveScalingMode());
   1971 
   1972         for (const auto& pendingState : mPendingStates) {
   1973             auto barrierLayer = pendingState.barrierLayer_legacy.promote();
   1974             if (barrierLayer != nullptr) {
   1975                 BarrierLayerProto* barrierLayerProto = layerInfo->add_barrier_layer();
   1976                 barrierLayerProto->set_id(barrierLayer->sequence);
   1977                 barrierLayerProto->set_frame_number(pendingState.frameNumber_legacy);
   1978             }
   1979         }
   1980         LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
   1981     }
   1982 
   1983     if (traceFlags & SurfaceTracing::TRACE_INPUT) {
   1984         LayerProtoHelper::writeToProto(state.inputInfo, state.touchableRegionCrop,
   1985                                        [&]() { return layerInfo->mutable_input_window_info(); });
   1986     }
   1987 
   1988     if (traceFlags & SurfaceTracing::TRACE_EXTRA) {
   1989         auto protoMap = layerInfo->mutable_metadata();
   1990         for (const auto& entry : state.metadata.mMap) {
   1991             (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
   1992         }
   1993         LayerProtoHelper::writeToProto(mEffectiveTransform,
   1994                                        layerInfo->mutable_effective_transform());
   1995         LayerProtoHelper::writeToProto(mSourceBounds,
   1996                                        [&]() { return layerInfo->mutable_source_bounds(); });
   1997         LayerProtoHelper::writeToProto(mScreenBounds,
   1998                                        [&]() { return layerInfo->mutable_screen_bounds(); });
   1999     }
   2000 }
   2001 
   2002 void Layer::writeToProto(LayerProto* layerInfo, const sp<DisplayDevice>& displayDevice,
   2003                          uint32_t traceFlags) {
   2004     auto outputLayer = findOutputLayerForDisplay(displayDevice);
   2005     if (!outputLayer) {
   2006         return;
   2007     }
   2008 
   2009     writeToProto(layerInfo, LayerVector::StateSet::Drawing, traceFlags);
   2010 
   2011     const auto& compositionState = outputLayer->getState();
   2012 
   2013     const Rect& frame = compositionState.displayFrame;
   2014     LayerProtoHelper::writeToProto(frame, [&]() { return layerInfo->mutable_hwc_frame(); });
   2015 
   2016     const FloatRect& crop = compositionState.sourceCrop;
   2017     LayerProtoHelper::writeToProto(crop, [&]() { return layerInfo->mutable_hwc_crop(); });
   2018 
   2019     const int32_t transform =
   2020             getCompositionLayer() ? static_cast<int32_t>(compositionState.bufferTransform) : 0;
   2021     layerInfo->set_hwc_transform(transform);
   2022 
   2023     const int32_t compositionType =
   2024             static_cast<int32_t>(compositionState.hwc ? (*compositionState.hwc).hwcCompositionType
   2025                                                       : Hwc2::IComposerClient::Composition::CLIENT);
   2026     layerInfo->set_hwc_composition_type(compositionType);
   2027 
   2028     if (std::strcmp(getTypeId(), "BufferLayer") == 0 &&
   2029         static_cast<BufferLayer*>(this)->isProtected()) {
   2030         layerInfo->set_is_protected(true);
   2031     } else {
   2032         layerInfo->set_is_protected(false);
   2033     }
   2034 }
   2035 
   2036 bool Layer::isRemovedFromCurrentState() const  {
   2037     return mRemovedFromCurrentState;
   2038 }
   2039 
   2040 InputWindowInfo Layer::fillInputInfo() {
   2041     InputWindowInfo info = mDrawingState.inputInfo;
   2042 
   2043     if (info.displayId == ADISPLAY_ID_NONE) {
   2044         info.displayId = mDrawingState.layerStack;
   2045     }
   2046 
   2047     ui::Transform t = getTransform();
   2048     const float xScale = t.sx();
   2049     const float yScale = t.sy();
   2050     float xSurfaceInset = info.surfaceInset;
   2051     float ySurfaceInset = info.surfaceInset;
   2052     if (xScale != 1.0f || yScale != 1.0f) {
   2053         info.windowXScale *= 1.0f / xScale;
   2054         info.windowYScale *= 1.0f / yScale;
   2055         info.touchableRegion.scaleSelf(xScale, yScale);
   2056         xSurfaceInset *= xScale;
   2057         ySurfaceInset *= yScale;
   2058     }
   2059 
   2060     // Transform layer size to screen space and inset it by surface insets.
   2061     // If this is a portal window, set the touchableRegion to the layerBounds.
   2062     Rect layerBounds = info.portalToDisplayId == ADISPLAY_ID_NONE
   2063             ? getBufferSize(getDrawingState())
   2064             : info.touchableRegion.getBounds();
   2065     if (!layerBounds.isValid()) {
   2066         layerBounds = getCroppedBufferSize(getDrawingState());
   2067     }
   2068     layerBounds = t.transform(layerBounds);
   2069     layerBounds.inset(xSurfaceInset, ySurfaceInset, xSurfaceInset, ySurfaceInset);
   2070 
   2071     // Input coordinate should match the layer bounds.
   2072     info.frameLeft = layerBounds.left;
   2073     info.frameTop = layerBounds.top;
   2074     info.frameRight = layerBounds.right;
   2075     info.frameBottom = layerBounds.bottom;
   2076 
   2077     // Position the touchable region relative to frame screen location and restrict it to frame
   2078     // bounds.
   2079     info.touchableRegion = info.touchableRegion.translate(info.frameLeft, info.frameTop);
   2080     info.visible = canReceiveInput();
   2081 
   2082     auto cropLayer = mDrawingState.touchableRegionCrop.promote();
   2083     if (info.replaceTouchableRegionWithCrop) {
   2084         if (cropLayer == nullptr) {
   2085             info.touchableRegion = Region(Rect{mScreenBounds});
   2086         } else {
   2087             info.touchableRegion = Region(Rect{cropLayer->mScreenBounds});
   2088         }
   2089     } else if (cropLayer != nullptr) {
   2090         info.touchableRegion = info.touchableRegion.intersect(Rect{cropLayer->mScreenBounds});
   2091     }
   2092 
   2093     return info;
   2094 }
   2095 
   2096 bool Layer::hasInput() const {
   2097     return mDrawingState.inputInfo.token != nullptr;
   2098 }
   2099 
   2100 std::shared_ptr<compositionengine::Layer> Layer::getCompositionLayer() const {
   2101     return nullptr;
   2102 }
   2103 
   2104 bool Layer::canReceiveInput() const {
   2105     return isVisible();
   2106 }
   2107 
   2108 compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
   2109         const sp<const DisplayDevice>& display) const {
   2110     return display->getCompositionDisplay()->getOutputLayerForLayer(getCompositionLayer().get());
   2111 }
   2112 
   2113 // ---------------------------------------------------------------------------
   2114 
   2115 }; // namespace android
   2116 
   2117 #if defined(__gl_h_)
   2118 #error "don't include gl/gl.h in this file"
   2119 #endif
   2120 
   2121 #if defined(__gl2_h_)
   2122 #error "don't include gl2/gl2.h in this file"
   2123 #endif
   2124