| /* | |
| * Copyright 2022 The Android Open Source Project | |
| * | |
| * Licensed under the Apache License, Version 2.0 (the "License"); | |
| * you may not use this file except in compliance with the License. | |
| * You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, software | |
| * distributed under the License is distributed on an "AS IS" BASIS, | |
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| * See the License for the specific language governing permissions and | |
| * limitations under the License. | |
| */ | |
| // #define LOG_NDEBUG 0 | |
| #include "FrontEnd/LayerCreationArgs.h" | |
| #define ATRACE_TAG ATRACE_TAG_GRAPHICS | |
| #include "FrontEnd/LayerSnapshot.h" | |
| #include "Tracking/ProtozeroWriters.h" | |
| #include "ui/Transform.h" | |
| #include <numeric> | |
| #include <optional> | |
| #include <android/gui/ISystemContentPriorityConstants.h> | |
| #include <android/gui/Vec2.h> | |
| #include <android/ipcrenderbuffer/OoprServer.h> | |
| #include <common/FlagManager.h> | |
| #include <common/trace.h> | |
| #include <ftl/small_map.h> | |
| #include <include/private/SkHdrMetadata.h> | |
| #include <math/vec2.h> | |
| #include <renderengine/ColorSpaces.h> | |
| #include <ui/DisplayMap.h> | |
| #include <ui/FloatRect.h> | |
| #include "DisplayHardware/HWC2.h" | |
| #include "DisplayHardware/Hal.h" | |
| #include "Layer.h" // eFrameRateSelectionPriority constants | |
| #include "LayerLog.h" | |
| #include "LayerSnapshotBuilder.h" | |
| #include "ShaderRegistry.h" | |
| #include "TimeStats/TimeStats.h" | |
| #include "Tracing/TransactionTracing.h" | |
| #include "Tracking/DirtyScope.h" | |
| namespace android::surfaceflinger::frontend { | |
| using namespace ftl::flag_operators; | |
| namespace { | |
| float getMaxHdrSdrRatio(float left, float right) { | |
| if (left >= 1.f && right >= 1.f) { | |
| return std::min(left, right); | |
| } else if (left >= 1.f) { | |
| return left; | |
| } else if (right >= 1.f) { | |
| return right; | |
| } | |
| return 0.f; | |
| } | |
| FloatRect getMaxDisplayBounds(const DisplayInfos& displays) { | |
| const ui::Size maxSize = [&displays] { | |
| if (displays.empty()) return ui::Size{5000, 5000}; | |
| return std::accumulate(displays.begin(), displays.end(), ui::kEmptySize, | |
| [](ui::Size size, const auto& pair) -> ui::Size { | |
| const auto& display = pair.second; | |
| return {std::max(size.getWidth(), display.info.logicalWidth), | |
| std::max(size.getHeight(), display.info.logicalHeight)}; | |
| }); | |
| }(); | |
| // Ignore display bounds for now since they will be computed later. Use a large Rect bound | |
| // to ensure it's bigger than an actual display will be. | |
| const float xMax = static_cast<float>(maxSize.getWidth()) * 10.f; | |
| const float yMax = static_cast<float>(maxSize.getHeight()) * 10.f; | |
| return {-xMax, -yMax, xMax, yMax}; | |
| } | |
| // Applies the given transform to the region, while protecting against overflows caused by any | |
| // offsets. If applying the offset in the transform to any of the Rects in the region would result | |
| // in an overflow, they are not added to the output Region. | |
| Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r, | |
| const std::string& debugWindowName) { | |
| // Round the translation using the same rounding strategy used by ui::Transform. | |
| const auto tx = static_cast<int32_t>(t.tx() + 0.5); | |
| const auto ty = static_cast<int32_t>(t.ty() + 0.5); | |
| ui::Transform transformWithoutOffset = t; | |
| transformWithoutOffset.set(0.f, 0.f); | |
| const Region transformed = transformWithoutOffset.transform(r); | |
| // Apply the translation to each of the Rects in the region while discarding any that overflow. | |
| Region ret; | |
| for (const auto& rect : transformed) { | |
| Rect newRect; | |
| if (__builtin_add_overflow(rect.left, tx, &newRect.left) || | |
| __builtin_add_overflow(rect.top, ty, &newRect.top) || | |
| __builtin_add_overflow(rect.right, tx, &newRect.right) || | |
| __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) { | |
| ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.", | |
| debugWindowName.c_str()); | |
| continue; | |
| } | |
| ret.orSelf(newRect); | |
| } | |
| return ret; | |
| } | |
| /* | |
| * We don't want to send the layer's transform to input, but rather the | |
| * parent's transform. This is because Layer's transform is | |
| * information about how the buffer is placed on screen. The parent's | |
| * transform makes more sense to send since it's information about how the | |
| * layer is placed on screen. This transform is used by input to determine | |
| * how to go from screen space back to window space. | |
| */ | |
| ui::Transform getInputTransform(const LayerSnapshot& snapshot) { | |
| if (!snapshot.hasBufferOrSidebandStream()) { | |
| return snapshot.geomLayerTransform.get(); | |
| } | |
| return snapshot.parentTransform; | |
| } | |
| /** | |
| * Returns the bounds used to fill the input frame and the touchable region. | |
| * | |
| * Similar to getInputTransform, we need to update the bounds to include the transform. | |
| * This is because bounds don't include the buffer transform, where the input assumes | |
| * that's already included. | |
| */ | |
| std::pair<FloatRect, bool> getInputBounds(const LayerSnapshot& snapshot, bool fillParentBounds) { | |
| FloatRect inputBounds = snapshot.croppedBufferSize.get(); | |
| if (snapshot.hasBufferOrSidebandStream() && snapshot.croppedBufferSize.get().isValid() && | |
| snapshot.localTransform.getType() != ui::Transform::IDENTITY) { | |
| inputBounds = snapshot.localTransform.transform(inputBounds); | |
| } | |
| bool inputBoundsValid = snapshot.croppedBufferSize.get().isValid(); | |
| if (!inputBoundsValid) { | |
| /** | |
| * Input bounds are based on the layer crop or buffer size. But if we are using | |
| * the layer bounds as the input bounds (replaceTouchableRegionWithCrop flag) then | |
| * we can use the parent bounds as the input bounds if the layer does not have buffer | |
| * or a crop. We want to unify this logic but because of compat reasons we cannot always | |
| * use the parent bounds. A layer without a buffer can get input. So when a window is | |
| * initially added, its touchable region can fill its parent layer bounds and that can | |
| * have negative consequences. | |
| */ | |
| inputBounds = fillParentBounds ? snapshot.geomLayerBounds : FloatRect{}; | |
| } | |
| // Clamp surface inset to the input bounds. | |
| const float inset = static_cast<float>(snapshot.inputInfo.get().surfaceInset); | |
| const float xSurfaceInset = std::clamp(inset, 0.f, inputBounds.getWidth() / 2.f); | |
| const float ySurfaceInset = std::clamp(inset, 0.f, inputBounds.getHeight() / 2.f); | |
| // Apply the insets to the input bounds. | |
| inputBounds.left += xSurfaceInset; | |
| inputBounds.top += ySurfaceInset; | |
| inputBounds.right -= xSurfaceInset; | |
| inputBounds.bottom -= ySurfaceInset; | |
| return {inputBounds, inputBoundsValid}; | |
| } | |
| Rect getInputBoundsInDisplaySpace(const LayerSnapshot& snapshot, const FloatRect& insetBounds, | |
| const ui::Transform& screenToDisplay) { | |
| // InputDispatcher works in the display device's coordinate space. Here, we calculate the | |
| // frame and transform used for the layer, which determines the bounds and the coordinate space | |
| // within which the layer will receive input. | |
| // Coordinate space definitions: | |
| // - display: The display device's coordinate space. Correlates to pixels on the display. | |
| // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space. | |
| // - layer: The coordinate space of this layer. | |
| // - input: The coordinate space in which this layer will receive input events. This could be | |
| // different than layer space if a surfaceInset is used, which changes the origin | |
| // of the input space. | |
| // Crop the input bounds to ensure it is within the parent's bounds. | |
| const FloatRect croppedInsetBoundsInLayer = | |
| snapshot.geomLayerBounds.toFloatRect().intersect(insetBounds); | |
| const ui::Transform layerToScreen = getInputTransform(snapshot); | |
| const ui::Transform layerToDisplay = screenToDisplay * layerToScreen; | |
| return Rect{layerToDisplay.transform(croppedInsetBoundsInLayer)}; | |
| } | |
| void fillInputFrameInfo(const ui::Transform& screenToDisplay, const LayerSnapshot& snapshot, | |
| TrackedWindowInfo<TrackedField::kInputWindowInfo>& info) { | |
| auto [inputBounds, inputBoundsValid] = getInputBounds(snapshot, /*fillParentBounds=*/false); | |
| static const Region kEmptyRegion; | |
| const Region& touchableRegion = inputBoundsValid ? info.get().touchableRegion : kEmptyRegion; | |
| info.setFrame(getInputBoundsInDisplaySpace(snapshot, inputBounds, screenToDisplay)); | |
| ui::Transform inputToLayer; | |
| inputToLayer.set(inputBounds.left, inputBounds.top); | |
| const ui::Transform layerToScreen = getInputTransform(snapshot); | |
| const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer; | |
| // InputDispatcher expects a display-to-input transform. | |
| info.setTransform(inputToDisplay.inverse()); | |
| // The touchable region is specified in the input coordinate space. Change it to display space. | |
| info.setTouchableRegion( | |
| transformTouchableRegionSafely(inputToDisplay, touchableRegion, snapshot.name)); | |
| } | |
| void handleDropInputMode(LayerSnapshot& snapshot, const LayerSnapshot& parentSnapshot) { | |
| if (snapshot.inputInfo.get().inputConfig.test(gui::WindowInfo::InputConfig::NO_INPUT_CHANNEL)) { | |
| return; | |
| } | |
| // Check if we need to drop input unconditionally | |
| const gui::DropInputMode dropInputMode = snapshot.dropInputMode; | |
| if (dropInputMode == gui::DropInputMode::ALL) { | |
| snapshot.inputInfo.getInputConfigProxy() |= gui::WindowInfo::InputConfig::DROP_INPUT; | |
| ALOGV("Dropping input for %s as requested by policy.", snapshot.name.c_str()); | |
| return; | |
| } | |
| // Check if we need to check if the window is obscured by parent | |
| if (dropInputMode != gui::DropInputMode::OBSCURED && | |
| dropInputMode != gui::DropInputMode::OBSCURED_ALLOW_PARENT_CROP) { | |
| return; | |
| } | |
| // Check if the parent has set an alpha on the layer | |
| if (parentSnapshot.color.get().a != 1.0_hf) { | |
| snapshot.inputInfo.getInputConfigProxy() |= gui::WindowInfo::InputConfig::DROP_INPUT; | |
| ALOGV("Dropping input for %s as requested by policy because alpha=%f", | |
| snapshot.name.c_str(), static_cast<float>(parentSnapshot.color.get().a)); | |
| } | |
| if (dropInputMode == gui::DropInputMode::OBSCURED_ALLOW_PARENT_CROP) { | |
| snapshot.inputInfo.getInputConfigProxy() |= | |
| gui::WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED; | |
| return; | |
| } | |
| // Check if the parent has cropped the buffer | |
| FloatRect bufferSize = snapshot.croppedBufferSize.get(); | |
| if (!bufferSize.isValid()) { | |
| snapshot.inputInfo.getInputConfigProxy() |= | |
| gui::WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED; | |
| return; | |
| } | |
| // Screenbounds are the layer bounds cropped by parents, transformed to screenspace. | |
| // To check if the layer has been cropped, we take the buffer bounds, apply the local | |
| // layer crop and apply the same set of transforms to move to screenspace. If the bounds | |
| // match then the layer has not been cropped by its parents. | |
| Rect bufferInScreenSpace(snapshot.geomLayerTransform.get().transform(bufferSize)); | |
| bool croppedByParent = bufferInScreenSpace != Rect{snapshot.transformedBounds.get()}; | |
| if (croppedByParent) { | |
| snapshot.inputInfo.getInputConfigProxy() |= gui::WindowInfo::InputConfig::DROP_INPUT; | |
| ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent", | |
| snapshot.name.c_str()); | |
| } else { | |
| // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop | |
| // input if the window is obscured. This check should be done in surfaceflinger but the | |
| // logic currently resides in inputflinger. So pass the if_obscured check to input to only | |
| // drop input events if the window is obscured. | |
| snapshot.inputInfo.getInputConfigProxy() |= | |
| gui::WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED; | |
| } | |
| } | |
| auto getBlendMode(const LayerSnapshot& snapshot, const RequestedLayerState& requested) { | |
| auto blendMode = Hwc2::IComposerClient::BlendMode::NONE; | |
| if (snapshot.alpha != 1.0f || !snapshot.isContentOpaque()) { | |
| blendMode = requested.premultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED | |
| : Hwc2::IComposerClient::BlendMode::COVERAGE; | |
| } | |
| return blendMode; | |
| } | |
| void updateMetadata(LayerSnapshot& snapshot, const RequestedLayerState& requested, | |
| const LayerSnapshotBuilder::Args& args) { | |
| snapshot.metadata.clear(); | |
| for (const auto& [key, mandatory] : args.supportedLayerGenericMetadata) { | |
| auto compatIter = args.genericLayerMetadataKeyMap.find(key); | |
| if (compatIter == std::end(args.genericLayerMetadataKeyMap)) { | |
| continue; | |
| } | |
| const uint32_t id = compatIter->second; | |
| auto it = requested.metadata.mMap.find(id); | |
| if (it == std::end(requested.metadata.mMap)) { | |
| continue; | |
| } | |
| snapshot.metadata.emplace(key, | |
| compositionengine::GenericLayerMetadataEntry{mandatory, | |
| it->second}); | |
| } | |
| } | |
| void updateMetadataAndGameMode(LayerSnapshot& snapshot, const RequestedLayerState& requested, | |
| const LayerSnapshotBuilder::Args& args, | |
| const LayerSnapshot& parentSnapshot) { | |
| snapshot.gameMode = requested.metadata.has(gui::METADATA_GAME_MODE) ? requested.gameMode | |
| : parentSnapshot.gameMode; | |
| updateMetadata(snapshot, requested, args); | |
| if (args.includeMetadata) { | |
| snapshot.layerMetadata = parentSnapshot.layerMetadata; | |
| snapshot.layerMetadata.merge(requested.metadata); | |
| } | |
| } | |
| void clearChanges(LayerSnapshot& snapshot) { | |
| snapshot.changes.clear(); | |
| snapshot.clientChanges.reset(); | |
| snapshot.contentDirty = snapshot.autoRefresh; | |
| snapshot.hasReadyFrame = snapshot.autoRefresh; | |
| snapshot.sidebandStreamHasFrame = false; | |
| snapshot.surfaceDamage.clear(); | |
| } | |
| void updateRelativeState(LayerSnapshot& snapshot, const LayerSnapshot& parentSnapshot, | |
| bool parentIsRelative, const LayerSnapshotBuilder::Args& args) { | |
| if (parentIsRelative) { | |
| snapshot.isHiddenByPolicyFromRelativeParent = | |
| parentSnapshot.isHiddenByPolicyFromParent || parentSnapshot.invalidTransform; | |
| if (args.includeMetadata) { | |
| snapshot.relativeLayerMetadata = parentSnapshot.layerMetadata; | |
| } | |
| } else { | |
| snapshot.isHiddenByPolicyFromRelativeParent = | |
| parentSnapshot.isHiddenByPolicyFromRelativeParent; | |
| if (args.includeMetadata) { | |
| snapshot.relativeLayerMetadata = parentSnapshot.relativeLayerMetadata; | |
| } | |
| } | |
| if (snapshot.reachability == LayerSnapshot::Reachability::Unreachable) { | |
| snapshot.reachability = LayerSnapshot::Reachability::ReachableByRelativeParent; | |
| } | |
| } | |
| void resetRelativeState(LayerSnapshot& snapshot) { | |
| snapshot.isHiddenByPolicyFromRelativeParent = false; | |
| snapshot.relativeLayerMetadata.mMap.clear(); | |
| } | |
| RoundedCornerState calculateParentRoundedCornerSettings(const LayerSnapshot& parentSnapshot, | |
| const LayerSnapshot& snapshot) { | |
| RoundedCornerState parentSettings; | |
| const auto& parentRoundedCorner = parentSnapshot.roundedCorner; | |
| // Always inherit the disableClientDrawnRadii flag. During transitions, WindowManager | |
| // may disable the optimization on a parent (like a Task) that does not have rounded | |
| // corners itself. This flag must propagate down to children (like Activities) that | |
| // actually draw the corners to ensure consistent composition state. | |
| parentSettings.disableClientDrawnRadii = parentRoundedCorner.disableClientDrawnRadii; | |
| if (parentRoundedCorner.hasEffectiveRadii()) { | |
| ui::Transform t = snapshot.localTransform.inverse(); | |
| parentSettings.cropRect = t.transform(parentRoundedCorner.cropRect.get()); | |
| parentSettings.effectiveRadii = parentRoundedCorner.effectiveRadii; | |
| parentSettings.effectiveRadii.transform(t); | |
| } | |
| return parentSettings; | |
| } | |
| RoundedCornerState calculateLayerRoundedCornerSettings(LayerSnapshot& snapshot, | |
| const RequestedLayerState& requested) { | |
| RoundedCornerState layerSettings; | |
| layerSettings.effectiveRadii = requested.cornerRadii; | |
| layerSettings.requestedRadii = requested.cornerRadii; | |
| layerSettings.cropRect = snapshot.croppedBufferSize.get(); | |
| return layerSettings; | |
| } | |
| bool childOverlapsParentCornerRegion(const FloatRect& childCropRect, | |
| const FloatRect& parentCropRect, | |
| const gui::CornerRadii& parentRadii) { | |
| if (childCropRect.isEmpty()) { | |
| // If either child crop is empty then assume there is overlap | |
| // so that child can inherit parent rounded corner state. Otherwise, the | |
| // overlap computation will return false. | |
| return true; | |
| } | |
| // TODO(452272969): refactor to compute corner region in separate function | |
| FloatRect parentCornerRegionTL(parentCropRect.left, parentCropRect.top, | |
| parentCropRect.left + parentRadii.topLeft.x, | |
| parentCropRect.top + parentRadii.topLeft.y); | |
| FloatRect parentCornerRegionTR(parentCropRect.right - parentRadii.topRight.x, | |
| parentCropRect.top, parentCropRect.right, | |
| parentCropRect.top + parentRadii.topRight.y); | |
| FloatRect parentCornerRegionBL(parentCropRect.left, | |
| parentCropRect.bottom - parentRadii.bottomLeft.y, | |
| parentCropRect.left + parentRadii.bottomLeft.x, | |
| parentCropRect.bottom); | |
| FloatRect parentCornerRegionBR(parentCropRect.right - parentRadii.bottomRight.x, | |
| parentCropRect.bottom - parentRadii.bottomRight.y, | |
| parentCropRect.right, parentCropRect.bottom); | |
| return !childCropRect.intersect(parentCornerRegionTL).isEmpty() || | |
| !childCropRect.intersect(parentCornerRegionTR).isEmpty() || | |
| !childCropRect.intersect(parentCornerRegionBL).isEmpty() || | |
| !childCropRect.intersect(parentCornerRegionBR).isEmpty(); | |
| } | |
| gui::CornerRadii getClippedClientRadii(const gui::CornerRadii& requestedRadii, | |
| const FloatRect& layerCropRect, | |
| const FloatRect& layerBounds) { | |
| gui::CornerRadii clippedRadii; | |
| android::gui::Vec2 zeroVec; | |
| zeroVec.x = 0.f; | |
| zeroVec.y = 0.f; | |
| auto calculateClippedCorner = [&](const android::gui::Vec2& cornerRadius, float left, float top, | |
| float right, float bottom) { | |
| FloatRect cornerRegion(left, top, right, bottom); | |
| return layerBounds.intersect(cornerRegion).isEmpty() ? zeroVec : cornerRadius; | |
| }; | |
| // TODO(452272969): refactor to compute corner region in separate function | |
| clippedRadii.topLeft = | |
| calculateClippedCorner(requestedRadii.topLeft, layerCropRect.left, layerCropRect.top, | |
| layerCropRect.left + requestedRadii.topLeft.x, | |
| layerCropRect.top + requestedRadii.topLeft.y); | |
| clippedRadii.topRight = calculateClippedCorner(requestedRadii.topRight, | |
| layerCropRect.right - requestedRadii.topRight.x, | |
| layerCropRect.top, layerCropRect.right, | |
| layerCropRect.top + requestedRadii.topRight.y); | |
| clippedRadii.bottomLeft = | |
| calculateClippedCorner(requestedRadii.bottomLeft, layerCropRect.left, | |
| layerCropRect.bottom - requestedRadii.bottomLeft.y, | |
| layerCropRect.left + requestedRadii.bottomLeft.x, | |
| layerCropRect.bottom); | |
| clippedRadii.bottomRight = | |
| calculateClippedCorner(requestedRadii.bottomRight, | |
| layerCropRect.right - requestedRadii.bottomRight.x, | |
| layerCropRect.bottom - requestedRadii.bottomRight.y, | |
| layerCropRect.right, layerCropRect.bottom); | |
| return clippedRadii; | |
| } | |
| bool shouldDisableCornerRounding(LayerSnapshot& snapshot, const RequestedLayerState& requested) { | |
| bool radiiMatch = | |
| snapshot.roundedCorner.clientDrawnRadii == snapshot.roundedCorner.reportedRadii; | |
| bool boundsMatch = snapshot.geomLayerBounds == requested.clientDrawnCornerRadiusCrop; | |
| return !snapshot.roundedCorner.clientDrawnRadii.get().isEmpty() && radiiMatch && boundsMatch; | |
| } | |
| void updateRoundedCorner(LayerSnapshot& snapshot, const RequestedLayerState& requested, | |
| const LayerSnapshot& parentSnapshot, | |
| const LayerSnapshotBuilder::Args& args) { | |
| if (args.skipRoundCornersWhenProtected && requested.isProtected()) { | |
| snapshot.roundedCorner = RoundedCornerState(); | |
| return; | |
| } | |
| RoundedCornerState finalSettings = RoundedCornerState(); | |
| // Populate parent settings to inherit | |
| RoundedCornerState parentSettings = | |
| calculateParentRoundedCornerSettings(parentSnapshot, snapshot); | |
| const bool parentSettingsValid = !parentSettings.effectiveRadii.get().isEmpty(); | |
| // Populate layer settings | |
| RoundedCornerState layerSettings = calculateLayerRoundedCornerSettings(snapshot, requested); | |
| const bool layerSettingsValid = | |
| layerSettings.hasRequestedRadius() && !layerSettings.cropRect.get().isEmpty(); | |
| if (layerSettingsValid && parentSettingsValid) { | |
| // If the parent and the layer have rounded corner settings, use the parent settings if | |
| // the parent crop is entirely inside the layer crop. This has limitations and cause | |
| // rendering artifacts. See b/200300845 for correct fix. | |
| if (parentSettings.cropRect.get().left > layerSettings.cropRect.get().left && | |
| parentSettings.cropRect.get().top > layerSettings.cropRect.get().top && | |
| parentSettings.cropRect.get().right < layerSettings.cropRect.get().right && | |
| parentSettings.cropRect.get().bottom < layerSettings.cropRect.get().bottom) { | |
| finalSettings = parentSettings; | |
| } else { | |
| finalSettings = layerSettings; | |
| } | |
| } else if (layerSettingsValid) { | |
| finalSettings = layerSettings; | |
| } else if (parentSettingsValid && | |
| childOverlapsParentCornerRegion(snapshot.geomLayerBounds, | |
| parentSettings.cropRect.get(), | |
| parentSettings.effectiveRadii.get())) { | |
| finalSettings = parentSettings; | |
| } | |
| snapshot.roundedCorner = finalSettings; | |
| snapshot.roundedCorner.disableClientDrawnRadii = | |
| requested.flags & layer_state_t::eRoundedCornerOptDisabled || | |
| parentSettings.disableClientDrawnRadii; | |
| if (snapshot.clientChanges & layer_state_t::eClientDrawnCornerRadiusChanged) { | |
| snapshot.roundedCorner.clientDrawnRadii = requested.clientDrawnCornerRadii; | |
| } | |
| if (requested.flags & layer_state_t::eWouldBeOpaqueIfNotForClientRoundedCorners) { | |
| snapshot.roundedCorner.wouldBeOpaque = true; | |
| } | |
| if (snapshot.roundedCorner.disableClientDrawnRadii) { | |
| // We are in a transition. Force Client to 0 and let SF handle it. | |
| snapshot.roundedCorner.reportedRadii = gui::CornerRadii(0.f); | |
| snapshot.roundedCorner.sfDrawnRadii = snapshot.roundedCorner.effectiveRadii.get(); | |
| } else { | |
| snapshot.roundedCorner.reportedRadii = | |
| getClippedClientRadii(snapshot.roundedCorner.effectiveRadii.get(), | |
| snapshot.roundedCorner.cropRect.get(), | |
| snapshot.sourceBounds()); | |
| if (shouldDisableCornerRounding(snapshot, requested)) { | |
| // Optimization ENABLED: Client draws, SF is 0. | |
| snapshot.roundedCorner.sfDrawnRadii = gui::CornerRadii(0.f); | |
| } else { | |
| // Optimization DISABLED: Client is 0, SF draws. | |
| snapshot.roundedCorner.sfDrawnRadii = snapshot.roundedCorner.effectiveRadii.get(); | |
| } | |
| } | |
| } | |
| /** | |
| * According to the edges that we are requested to extend, we increase the bounds to the maximum | |
| * extension allowed by the crop (parent crop + requested crop). The animation that called | |
| * Transition#setEdgeExtensionEffect is in charge of setting the requested crop. | |
| * @param snapshot | |
| */ | |
| void updateBoundsForEdgeExtension(LayerSnapshot& snapshot) { | |
| EdgeExtensionEffect& effect = snapshot.edgeExtensionEffect; | |
| FloatRect bounds = snapshot.geomLayerBounds.toFloatRect(); | |
| FloatRect crop = snapshot.geomLayerCrop.toFloatRect(); | |
| if (effect.extendsEdge(LEFT)) { | |
| bounds.left = crop.left; | |
| } | |
| if (effect.extendsEdge(RIGHT)) { | |
| bounds.right = crop.right; | |
| } | |
| if (effect.extendsEdge(TOP)) { | |
| bounds.top = crop.top; | |
| } | |
| if (effect.extendsEdge(BOTTOM)) { | |
| bounds.bottom = crop.bottom; | |
| } | |
| snapshot.geomLayerBounds = bounds; | |
| snapshot.transformedBounds = | |
| snapshot.geomLayerTransform.get().transform(snapshot.geomLayerBounds); | |
| } | |
| void updateShadows(LayerSnapshot& snapshot, const RequestedLayerState&, | |
| const ShadowSettings& globalShadowSettings) { | |
| if (snapshot.shadowSettings.length > 0.f) { | |
| snapshot.shadowSettings.ambientColor = globalShadowSettings.ambientColor; | |
| snapshot.shadowSettings.spotColor = globalShadowSettings.spotColor; | |
| snapshot.shadowSettings.lightPos = globalShadowSettings.lightPos; | |
| snapshot.shadowSettings.lightRadius = globalShadowSettings.lightRadius; | |
| // Note: this preserves existing behavior of shadowing the entire layer and not cropping | |
| // it if transparent regions are present. This may not be necessary since shadows are | |
| // typically cast by layers without transparent regions. | |
| snapshot.shadowSettings.boundaries = snapshot.geomLayerBounds; | |
| // If the casting layer is translucent, we need to fill in the shadow underneath the | |
| // layer. Otherwise the generated shadow will only be shown around the casting layer. | |
| snapshot.shadowSettings.casterIsTranslucent = | |
| !snapshot.isContentOpaque() || (snapshot.alpha < 1.0f); | |
| snapshot.shadowSettings.ambientColor = | |
| snapshot.shadowSettings.ambientColor * snapshot.alpha; | |
| snapshot.shadowSettings.spotColor = snapshot.shadowSettings.spotColor * snapshot.alpha; | |
| } | |
| } | |
| using PathToSnapshotMap = std::unordered_map<LayerHierarchy::TraversalPath, LayerSnapshot*, | |
| LayerHierarchy::TraversalPathHash>; | |
| uint32_t resolveCloneParent(const LayerHierarchy::TraversalPath& path, uint32_t targetParentId, | |
| const PathToSnapshotMap& pathToSnapshot) { | |
| if (targetParentId == UNASSIGNED_LAYER_ID) { | |
| return UNASSIGNED_LAYER_ID; | |
| } | |
| LayerHierarchy::TraversalPath parentPath = path; | |
| parentPath.id = targetParentId; | |
| auto it = pathToSnapshot.find(parentPath); | |
| return it != pathToSnapshot.end() ? it->second->uniqueSequence : UNASSIGNED_LAYER_ID; | |
| } | |
| int32_t getParentId(const LayerSnapshot& snapshot, const LayerLifecycleManager& manager, | |
| const PathToSnapshotMap& pathToSnapshot) { | |
| if (snapshot.path == LayerHierarchy::TraversalPath::ROOT || | |
| snapshot.uniqueSequence == OFFSCREEN_ROOT_LAYER_ID) { | |
| return static_cast<int32_t>(UNASSIGNED_LAYER_ID); | |
| } | |
| const RequestedLayerState* layer = manager.getLayerFromId(snapshot.path.id); | |
| if (layer == nullptr) { | |
| return static_cast<int32_t>(UNASSIGNED_LAYER_ID); | |
| } | |
| if (snapshot.path.isClone()) { | |
| const uint32_t cloneParentId = | |
| resolveCloneParent(snapshot.path, layer->parentId, pathToSnapshot); | |
| if (cloneParentId == UNASSIGNED_LAYER_ID) { | |
| return layer->canBeRoot ? static_cast<int32_t>(UNASSIGNED_LAYER_ID) | |
| : static_cast<int32_t>(OFFSCREEN_ROOT_LAYER_ID); | |
| } | |
| return static_cast<int32_t>(cloneParentId); | |
| } | |
| if (layer->parentId == UNASSIGNED_LAYER_ID) { | |
| return layer->canBeRoot ? static_cast<int32_t>(UNASSIGNED_LAYER_ID) | |
| : static_cast<int32_t>(OFFSCREEN_ROOT_LAYER_ID); | |
| } | |
| return static_cast<int32_t>(layer->parentId); | |
| } | |
| int32_t getRelativeParentId(const LayerSnapshot& snapshot, const LayerLifecycleManager& manager, | |
| const PathToSnapshotMap& pathToSnapshot) { | |
| if (snapshot.path == LayerHierarchy::TraversalPath::ROOT || | |
| snapshot.uniqueSequence == OFFSCREEN_ROOT_LAYER_ID) { | |
| return static_cast<int32_t>(UNASSIGNED_LAYER_ID); | |
| } | |
| const RequestedLayerState* layer = manager.getLayerFromId(snapshot.path.id); | |
| if (layer == nullptr) { | |
| return static_cast<int32_t>(UNASSIGNED_LAYER_ID); | |
| } | |
| if (snapshot.path.isClone()) { | |
| const uint32_t cloneParentId = | |
| resolveCloneParent(snapshot.path, layer->relativeParentId, pathToSnapshot); | |
| return static_cast<int32_t>(cloneParentId); | |
| } | |
| return layer->relativeParentId == UNASSIGNED_LAYER_ID | |
| ? static_cast<int32_t>(UNASSIGNED_LAYER_ID) | |
| : static_cast<int32_t>(layer->relativeParentId); | |
| } | |
| } // namespace | |
| LayerSnapshot LayerSnapshotBuilder::getRootSnapshot() { | |
| LayerSnapshot snapshot; | |
| snapshot.path = LayerHierarchy::TraversalPath::ROOT; | |
| snapshot.uniqueSequence = UNASSIGNED_LAYER_ID; | |
| snapshot.changes = ftl::Flags<RequestedLayerState::Changes>(); | |
| snapshot.clientChanges.reset(); | |
| snapshot.isHiddenByPolicyFromParent = false; | |
| snapshot.isHiddenByPolicyFromRelativeParent = false; | |
| snapshot.parentTransform.reset(); | |
| snapshot.geomLayerTransform.reset(); | |
| snapshot.geomInverseLayerTransform.reset(); | |
| snapshot.geomLayerBounds.setUnboundedValue(getMaxDisplayBounds({})); | |
| snapshot.roundedCorner = RoundedCornerState(); | |
| snapshot.stretchEffect = {}; | |
| snapshot.edgeExtensionEffect = {}; | |
| snapshot.outputFilter.setLayerStack(ui::DEFAULT_LAYER_STACK); | |
| snapshot.outputFilter.setToInternalDisplay(false); | |
| snapshot.outputFilter.setSkipScreenshot(false); | |
| snapshot.isSecure = false; | |
| snapshot.color.setA(1.0_hf); | |
| snapshot.colorTransformIsIdentity = true; | |
| snapshot.shadowSettings.length = 0.f; | |
| snapshot.layerMetadata.mMap.clear(); | |
| snapshot.relativeLayerMetadata.mMap.clear(); | |
| snapshot.inputInfo.setTouchOcclusionMode(gui::TouchOcclusionMode::BLOCK_UNTRUSTED); | |
| snapshot.dropInputMode = gui::DropInputMode::NONE; | |
| snapshot.trustedOverlay = gui::TrustedOverlay::UNSET; | |
| snapshot.gameMode = gui::GameMode::Unsupported; | |
| snapshot.frameRate = {}; | |
| snapshot.desiredHdrSdrRatio = 0.f; | |
| snapshot.maxDesiredHdrSdrRatio = 0.f; | |
| snapshot.fixedTransformHint = ui::Transform::ROT_INVALID; | |
| snapshot.ignoreLocalTransform = false; | |
| return snapshot; | |
| } | |
| void LayerSnapshotBuilder::updateVisibility(LayerSnapshot& snapshot, bool visible) { | |
| DirtyScope scope(snapshot.dirtyMask, mHasDirtySnapshots); | |
| if (snapshot.isVisible != visible) { | |
| snapshot.changes |= RequestedLayerState::Changes::Visibility; | |
| } | |
| snapshot.isVisible = visible; | |
| // TODO(b/238781169) we are ignoring this compat for now, since we will have | |
| // to remove any optimization based on visibility. | |
| // For compatibility reasons we let layers which can receive input | |
| // receive input before they have actually submitted a buffer. Because | |
| // of this we use canReceiveInput instead of isVisible to check the | |
| // policy-visibility, ignoring the buffer state. However for layers with | |
| // hasInputInfo()==false we can use the real visibility state. | |
| // We are just using these layers for occlusion detection in | |
| // InputDispatcher, and obviously if they aren't visible they can't occlude | |
| // anything. | |
| const bool visibleForInput = | |
| snapshot.hasInputInfo() ? snapshot.canReceiveInput() : snapshot.isVisible; | |
| snapshot.inputInfo.setInputConfig(gui::WindowInfo::InputConfig::NOT_VISIBLE, !visibleForInput); | |
| LLOGV(snapshot.sequence.get(), "updating visibility %s %s", visible ? "true" : "false", | |
| snapshot.getDebugString().c_str()); | |
| } | |
| LayerSnapshotBuilder::LayerSnapshotBuilder() {} | |
| LayerSnapshotBuilder::LayerSnapshotBuilder(Args args) : LayerSnapshotBuilder() { | |
| args.forceUpdate = ForceUpdateFlags::ALL; | |
| updateSnapshots(args); | |
| } | |
| bool LayerSnapshotBuilder::tryFastUpdate(const Args& args) { | |
| const bool forceUpdate = args.forceUpdate != ForceUpdateFlags::NONE; | |
| if (args.layerLifecycleManager.getGlobalChanges().get() == 0 && !forceUpdate && | |
| !args.displayChanges) { | |
| return true; | |
| } | |
| // There are only content changes which do not require any child layer snapshots to be updated. | |
| ALOGV("%s", __func__); | |
| SFTRACE_NAME("FastPath"); | |
| uint32_t primaryDisplayRotationFlags = getPrimaryDisplayRotationFlags(args.displays); | |
| if (forceUpdate || args.displayChanges) { | |
| for (auto& snapshot : mSnapshots) { | |
| const RequestedLayerState* requested = | |
| args.layerLifecycleManager.getLayerFromId(snapshot->path.id); | |
| if (!requested) continue; | |
| DirtyScope scope(snapshot->dirtyMask, mHasDirtySnapshots); | |
| snapshot->merge(*requested, forceUpdate, args.displayChanges, args.forceFullDamage, | |
| primaryDisplayRotationFlags, args.shaderRegistry); | |
| } | |
| return false; | |
| } | |
| // Walk through all the updated requested layer states and update the corresponding snapshots. | |
| for (const RequestedLayerState* requested : args.layerLifecycleManager.getChangedLayers()) { | |
| auto range = mIdToSnapshots.equal_range(requested->id); | |
| for (auto it = range.first; it != range.second; it++) { | |
| DirtyScope scope(it->second->dirtyMask, mHasDirtySnapshots); | |
| it->second->merge(*requested, forceUpdate, args.displayChanges, args.forceFullDamage, | |
| primaryDisplayRotationFlags, args.shaderRegistry); | |
| } | |
| } | |
| if ((args.layerLifecycleManager.getGlobalChanges().get() & | |
| ~(RequestedLayerState::Changes::Content | RequestedLayerState::Changes::Buffer).get()) != | |
| 0) { | |
| // We have changes that require us to walk the hierarchy and update child layers. | |
| // No fast path for you. | |
| return false; | |
| } | |
| return true; | |
| } | |
| void LayerSnapshotBuilder::updateSnapshots(const Args& args) { | |
| SFTRACE_NAME("UpdateSnapshots"); | |
| mHasMirrorRequests = false; | |
| LayerSnapshot rootSnapshot = args.rootSnapshot; | |
| if (args.parentCrop) { | |
| rootSnapshot.geomLayerBounds = *args.parentCrop; | |
| } else if (args.forceUpdate == ForceUpdateFlags::ALL || args.displayChanges) { | |
| rootSnapshot.geomLayerBounds.setUnboundedValue(getMaxDisplayBounds(args.displays)); | |
| } | |
| if (args.displayChanges) { | |
| rootSnapshot.changes = RequestedLayerState::Changes::AffectsChildren | | |
| RequestedLayerState::Changes::Geometry; | |
| } | |
| if (args.forceUpdate == ForceUpdateFlags::HIERARCHY) { | |
| rootSnapshot.changes |= | |
| RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Visibility; | |
| rootSnapshot.clientChanges |= layer_state_t::eReparent; | |
| } | |
| for (auto& snapshot : mSnapshots) { | |
| if (snapshot->reachability == LayerSnapshot::Reachability::Reachable) { | |
| snapshot->reachability = LayerSnapshot::Reachability::Unreachable; | |
| } | |
| } | |
| mMergedSnapshots.clear(); | |
| if (args.mergeableHierarchyManager) { | |
| auto mergedSnapshot = | |
| args.mergeableHierarchyManager->findLayerSnapshotCopy(UNASSIGNED_LAYER_ID); | |
| if (mergedSnapshot) { | |
| updateVisibility(*mergedSnapshot, mergedSnapshot->getIsVisible()); | |
| mMergedSnapshots.emplace_back(std::move(mergedSnapshot)); | |
| } | |
| } | |
| LayerHierarchy::TraversalPath root = LayerHierarchy::TraversalPath::ROOT; | |
| if (args.root.getLayer()) { | |
| // The hierarchy can have a root layer when used for screenshots otherwise, it will have | |
| // multiple children. | |
| LayerHierarchy::TraversalPath childPath = | |
| root.makeChild(args.root.getLayer()->id, LayerHierarchy::Variant::Attached); | |
| updateSnapshotsInHierarchy(args, args.root, childPath, rootSnapshot, /*depth=*/0); | |
| } else { | |
| for (auto& [childHierarchy, variant] : args.root.mChildren) { | |
| LayerHierarchy::TraversalPath childPath = | |
| root.makeChild(childHierarchy->getLayer()->id, variant); | |
| updateSnapshotsInHierarchy(args, *childHierarchy, childPath, rootSnapshot, /*depth=*/0); | |
| } | |
| } | |
| if (args.offscreenRoot) { | |
| LayerSnapshot offscreenRootSnapshot = rootSnapshot; | |
| offscreenRootSnapshot.uniqueSequence = OFFSCREEN_ROOT_LAYER_ID; | |
| for (auto& [childHierarchy, variant] : args.offscreenRoot->mChildren) { | |
| const LayerHierarchy::TraversalPath childPath = | |
| root.makeChild(childHierarchy->getLayer()->id, variant); | |
| updateSnapshotsInHierarchy(args, *childHierarchy, childPath, offscreenRootSnapshot, | |
| /*depth=*/0); | |
| } | |
| } | |
| // The crop for a mirror layer is determined by another layer in the hierarchy. | |
| // updateMirrorLayerCrops needs to be called after updateSnapshotsInHierarchy because it relies | |
| // on the global geometry (transforms) of the crop layer and the mirrored layer, which are | |
| // computed during the hierarchy traversal. | |
| // If the crop for a mirror layer has changed, we need to perform a second traversal to update | |
| // the geometry of the mirror layer and its children. | |
| if (FlagManager::getInstance().mirror_with_crop() && updateMirrorLayerCrops(args)) { | |
| if (args.root.getLayer()) { | |
| LayerHierarchy::TraversalPath childPath = | |
| root.makeChild(args.root.getLayer()->id, LayerHierarchy::Variant::Attached); | |
| updateSnapshotsInHierarchy(args, args.root, childPath, rootSnapshot, /*depth=*/0); | |
| } else { | |
| for (auto& [childHierarchy, variant] : args.root.mChildren) { | |
| LayerHierarchy::TraversalPath childPath = | |
| root.makeChild(childHierarchy->getLayer()->id, variant); | |
| updateSnapshotsInHierarchy(args, *childHierarchy, childPath, rootSnapshot, | |
| /*depth=*/0); | |
| } | |
| } | |
| } | |
| // Update touchable region crops outside the main update pass. This is because a layer could be | |
| // cropped by any other layer and it requires both snapshots to be updated. | |
| updateTouchableRegionCrop(args); | |
| // applyStopLayers modifies the snapshot's visibility (isHiddenByPolicyFromParent) based on | |
| // stop layer configuration. This must run after updateSnapshotsInHierarchy so that all | |
| // snapshots are created and their initial state is established. | |
| if (args.root.getLayer()) { | |
| LayerHierarchy::TraversalPath childPath = | |
| root.makeChild(args.root.getLayer()->id, LayerHierarchy::Variant::Attached); | |
| applyStopLayers(args.root, childPath); | |
| } else { | |
| for (auto& [childHierarchy, variant] : args.root.mChildren) { | |
| LayerHierarchy::TraversalPath childPath = | |
| root.makeChild(childHierarchy->getLayer()->id, variant); | |
| applyStopLayers(*childHierarchy, childPath); | |
| } | |
| } | |
| const bool hasUnreachableSnapshots = sortSnapshotsByZ(args); | |
| if (args.mergeableHierarchyManager && mMergedSnapshots.empty()) { | |
| if (args.root.getLayer()) { | |
| LayerHierarchy::TraversalPath childPath = | |
| root.makeChild(args.root.getLayer()->id, LayerHierarchy::Variant::Attached); | |
| populateMergedSnapshots(args, args.root, childPath, rootSnapshot); | |
| } else { | |
| for (auto& [childHierarchy, variant] : args.root.mChildren) { | |
| LayerHierarchy::TraversalPath childPath = | |
| root.makeChild(childHierarchy->getLayer()->id, variant); | |
| populateMergedSnapshots(args, *childHierarchy, childPath, rootSnapshot); | |
| } | |
| } | |
| } | |
| // Destroy unreachable snapshots for clone layers. And destroy snapshots for non-clone | |
| // layers if the layer have been destroyed. | |
| // TODO(b/238781169) consider making clone layer ids stable as well | |
| if (!hasUnreachableSnapshots && args.layerLifecycleManager.getDestroyedLayers().empty()) { | |
| return; | |
| } | |
| std::unordered_set<uint32_t> destroyedLayerIds; | |
| for (auto& destroyedLayer : args.layerLifecycleManager.getDestroyedLayers()) { | |
| destroyedLayerIds.insert(destroyedLayer->id); | |
| } | |
| auto it = mSnapshots.begin(); | |
| while (it < mSnapshots.end()) { | |
| auto& traversalPath = it->get()->path; | |
| const bool unreachable = | |
| it->get()->reachability == LayerSnapshot::Reachability::Unreachable; | |
| const bool isClone = traversalPath.isClone(); | |
| const bool layerIsDestroyed = | |
| destroyedLayerIds.find(traversalPath.id) != destroyedLayerIds.end(); | |
| const bool destroySnapshot = (unreachable && isClone) || layerIsDestroyed; | |
| if (!destroySnapshot) { | |
| it++; | |
| continue; | |
| } | |
| if (args.isProtoVmTracingActive) { | |
| mDestroyedSnapshotIds.push_back(it->get()->uniqueSequence); | |
| mHasDirtySnapshots = true; | |
| } | |
| mPathToSnapshot.erase(traversalPath); | |
| auto range = mIdToSnapshots.equal_range(traversalPath.id); | |
| auto matchingSnapshot = | |
| std::find_if(range.first, range.second, [&traversalPath](auto& snapshotWithId) { | |
| return snapshotWithId.second->path == traversalPath; | |
| }); | |
| mIdToSnapshots.erase(matchingSnapshot); | |
| mNeedsTouchableRegionCrop.erase(traversalPath); | |
| mSnapshots.back()->globalZ = it->get()->globalZ; | |
| std::iter_swap(it, mSnapshots.end() - 1); | |
| mSnapshots.erase(mSnapshots.end() - 1); | |
| } | |
| if (!args.isProtoVmTracingActive) { | |
| return; | |
| } | |
| for (const RequestedLayerState* requested : args.layerLifecycleManager.getChangedLayers()) { | |
| const bool parentChanged = requested->changes.test(RequestedLayerState::Changes::Parent); | |
| const bool relParentChanged = | |
| requested->changes.test(RequestedLayerState::Changes::RelativeParent); | |
| if (parentChanged || relParentChanged) { | |
| const auto [first, last] = mIdToSnapshots.equal_range(requested->id); | |
| for (auto it = first; it != last; ++it) { | |
| DirtyScope scope(it->second->dirtyMask, mHasDirtySnapshots); | |
| if (parentChanged) { | |
| mark(TrackedField::kParent); | |
| } | |
| if (relParentChanged) { | |
| mark(TrackedField::kZOrderRelativeOf); | |
| mark(TrackedField::kIsRelativeOf); | |
| } | |
| } | |
| } | |
| } | |
| } | |
| void LayerSnapshotBuilder::update(const Args& args) { | |
| mHasDirtySnapshots = false; | |
| for (auto& snapshot : mSnapshots) { | |
| DirtyScope scope(snapshot->dirtyMask, mHasDirtySnapshots); | |
| clearChanges(*snapshot); | |
| } | |
| if (tryFastUpdate(args) && args.mergeableHierarchyManager == nullptr) { | |
| return; | |
| } | |
| updateSnapshots(args); | |
| } | |
| const LayerSnapshot& LayerSnapshotBuilder::updateSnapshotsInHierarchy( | |
| const Args& args, const LayerHierarchy& hierarchy, | |
| const LayerHierarchy::TraversalPath& traversalPath, const LayerSnapshot& parentSnapshot, | |
| int depth) { | |
| LLOG_ALWAYS_FATAL_WITH_TRACE_IF(depth > 50, | |
| "Cycle detected in LayerSnapshotBuilder. See " | |
| "builder_stack_overflow_transactions.winscope"); | |
| const RequestedLayerState* layer = hierarchy.getLayer(); | |
| LayerSnapshot* snapshot = getSnapshot(traversalPath); | |
| const bool newSnapshot = snapshot == nullptr; | |
| if (newSnapshot) { | |
| snapshot = createSnapshot(traversalPath, *layer, parentSnapshot); | |
| } | |
| DirtyScope scope(snapshot->dirtyMask, mHasDirtySnapshots); | |
| uint32_t primaryDisplayRotationFlags = getPrimaryDisplayRotationFlags(args.displays); | |
| if (newSnapshot) { | |
| snapshot->merge(*layer, /*forceUpdate=*/true, /*displayChanges=*/true, args.forceFullDamage, | |
| primaryDisplayRotationFlags, args.shaderRegistry); | |
| snapshot->changes |= RequestedLayerState::Changes::Created; | |
| } | |
| if (traversalPath.isRelative()) { | |
| bool parentIsRelative = traversalPath.variant == LayerHierarchy::Variant::Relative; | |
| updateRelativeState(*snapshot, parentSnapshot, parentIsRelative, args); | |
| } else { | |
| if (traversalPath.isAttached()) { | |
| resetRelativeState(*snapshot); | |
| } | |
| updateSnapshot(*snapshot, args, *layer, parentSnapshot, traversalPath); | |
| } | |
| bool childHasValidFrameRate = false; | |
| for (auto& [childHierarchy, variant] : hierarchy.mChildren) { | |
| LayerHierarchy::TraversalPath childPath = | |
| traversalPath.makeChild(childHierarchy->getLayer()->id, variant); | |
| const LayerSnapshot& childSnapshot = | |
| updateSnapshotsInHierarchy(args, *childHierarchy, childPath, *snapshot, depth + 1); | |
| updateFrameRateFromChildSnapshot(*snapshot, childSnapshot, *childHierarchy->getLayer(), | |
| args, &childHasValidFrameRate); | |
| } | |
| return *snapshot; | |
| } | |
| void LayerSnapshotBuilder::populateMergedSnapshots( | |
| const Args& args, const LayerHierarchy& hierarchy, | |
| const LayerHierarchy::TraversalPath& traversalPath, const LayerSnapshot& parentSnapshot) { | |
| const RequestedLayerState* layer = hierarchy.getLayer(); | |
| bool traverseThisLayer = (layer != nullptr); | |
| if (traverseThisLayer) { | |
| auto mergedSnapshot = args.mergeableHierarchyManager->findLayerSnapshotCopy(layer->id); | |
| if (mergedSnapshot) { | |
| updateSnapshot(*mergedSnapshot, args, *layer, parentSnapshot, traversalPath, true); | |
| updateVisibility(*mergedSnapshot, mergedSnapshot->getIsVisible()); | |
| mMergedSnapshots.emplace_back(std::move(mergedSnapshot)); | |
| return; | |
| } | |
| } | |
| for (auto& [child, childVariant] : hierarchy.mChildren) { | |
| if (traverseThisLayer && child->getLayer()->z >= 0) { | |
| traverseThisLayer = false; | |
| LayerSnapshot* snapshot = getSnapshot(traversalPath); | |
| if (snapshot && snapshot->isVisible) { | |
| mMergedSnapshots.emplace_back(std::make_unique<LayerSnapshot>(*snapshot)); | |
| } | |
| } | |
| if (childVariant == LayerHierarchy::Variant::Detached) { | |
| continue; | |
| } | |
| LayerSnapshot* currentSnapshot = getSnapshot(traversalPath); | |
| if (currentSnapshot) { | |
| populateMergedSnapshots(args, *child, | |
| traversalPath.makeChild(child->getLayer()->id, childVariant), | |
| *currentSnapshot); | |
| } | |
| } | |
| if (traverseThisLayer) { | |
| LayerSnapshot* snapshot = getSnapshot(traversalPath); | |
| if (snapshot && snapshot->isVisible) { | |
| mMergedSnapshots.emplace_back(std::make_unique<LayerSnapshot>(*snapshot)); | |
| } | |
| } | |
| } | |
| LayerSnapshot* LayerSnapshotBuilder::getSnapshot(uint32_t layerId) const { | |
| if (layerId == UNASSIGNED_LAYER_ID) { | |
| return nullptr; | |
| } | |
| LayerHierarchy::TraversalPath path{.id = layerId}; | |
| return getSnapshot(path); | |
| } | |
| LayerSnapshot* LayerSnapshotBuilder::getSnapshotFromClonedHierarchy( | |
| uint32_t layerId, const LayerHierarchy::TraversalPath& callerPath) const { | |
| if (layerId == UNASSIGNED_LAYER_ID || !callerPath.isClone()) { | |
| return nullptr; | |
| } | |
| LayerHierarchy::TraversalPath path = callerPath; | |
| path.id = layerId; | |
| return getSnapshot(path); | |
| } | |
| LayerSnapshot* LayerSnapshotBuilder::getSnapshot(const LayerHierarchy::TraversalPath& id) const { | |
| auto it = mPathToSnapshot.find(id); | |
| return it == mPathToSnapshot.end() ? nullptr : it->second; | |
| } | |
| LayerSnapshot* LayerSnapshotBuilder::createSnapshot(const LayerHierarchy::TraversalPath& path, | |
| const RequestedLayerState& layer, | |
| const LayerSnapshot& parentSnapshot) { | |
| mSnapshots.emplace_back(std::make_unique<LayerSnapshot>(layer, path)); | |
| LayerSnapshot* snapshot = mSnapshots.back().get(); | |
| snapshot->outputFilter.setFilterUid(snapshot->uid.get()); | |
| snapshot->dirtyMask.set(); | |
| mHasDirtySnapshots = true; | |
| snapshot->globalZ = static_cast<size_t>(mSnapshots.size()) - 1; | |
| if (path.isClone() && !LayerHierarchy::isMirror(path.variant)) { | |
| snapshot->clonedRootPath = parentSnapshot.clonedRootPath; | |
| } | |
| snapshot->ignoreLocalTransform = | |
| path.isClone() && path.variant == LayerHierarchy::Variant::Detached_Mirror; | |
| mPathToSnapshot[path] = snapshot; | |
| mIdToSnapshots.emplace(path.id, snapshot); | |
| return snapshot; | |
| } | |
| bool LayerSnapshotBuilder::sortSnapshotsByZ(const Args& args) { | |
| if (!mResortSnapshots && args.forceUpdate == ForceUpdateFlags::NONE && | |
| !args.layerLifecycleManager.getGlobalChanges().any( | |
| RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Visibility | | |
| RequestedLayerState::Changes::Input)) { | |
| // We are not force updating and there are no hierarchy or visibility changes. Avoid sorting | |
| // the snapshots. | |
| return false; | |
| } | |
| mResortSnapshots = false; | |
| size_t globalZ = 0; | |
| args.root.traverseInZOrder( | |
| [this, &globalZ](const LayerHierarchy&, | |
| const LayerHierarchy::TraversalPath& traversalPath) -> bool { | |
| LayerSnapshot* snapshot = getSnapshot(traversalPath); | |
| if (!snapshot) { | |
| return true; | |
| } | |
| DirtyScope scope(snapshot->dirtyMask, mHasDirtySnapshots); | |
| if (snapshot->getIsVisible() || snapshot->hasInputInfo()) { | |
| updateVisibility(*snapshot, snapshot->getIsVisible()); | |
| size_t oldZ = snapshot->globalZ; | |
| size_t newZ = globalZ++; | |
| snapshot->globalZ = newZ; | |
| if (oldZ == newZ) { | |
| return true; | |
| } | |
| mSnapshots[newZ]->globalZ = oldZ; | |
| LLOGV(snapshot->sequence.get(), "Made visible z=%zu -> %zu %s", oldZ, newZ, | |
| snapshot->getDebugString().c_str()); | |
| std::iter_swap(mSnapshots.begin() + static_cast<ssize_t>(oldZ), | |
| mSnapshots.begin() + static_cast<ssize_t>(newZ)); | |
| } | |
| return true; | |
| }); | |
| mNumInterestingSnapshots = (int)globalZ; | |
| bool hasUnreachableSnapshots = false; | |
| while (globalZ < mSnapshots.size()) { | |
| mSnapshots[globalZ]->globalZ = globalZ; | |
| /* mark unreachable snapshots as explicitly invisible */ | |
| updateVisibility(*mSnapshots[globalZ], false); | |
| if (mSnapshots[globalZ]->reachability == LayerSnapshot::Reachability::Unreachable) { | |
| hasUnreachableSnapshots = true; | |
| } | |
| globalZ++; | |
| } | |
| return hasUnreachableSnapshots; | |
| } | |
| void LayerSnapshotBuilder::updateFrameRateFromChildSnapshot( | |
| LayerSnapshot& snapshot, const LayerSnapshot& childSnapshot, | |
| const RequestedLayerState& /* requestedChildState */, const Args& args, | |
| bool* outChildHasValidFrameRate) { | |
| if (args.forceUpdate == ForceUpdateFlags::NONE && | |
| !args.layerLifecycleManager.getGlobalChanges().any( | |
| RequestedLayerState::Changes::Hierarchy) && | |
| !childSnapshot.changes.any(RequestedLayerState::Changes::FrameRate) && | |
| !snapshot.changes.any(RequestedLayerState::Changes::FrameRate)) { | |
| return; | |
| } | |
| using FrameRateCompatibility = scheduler::FrameRateCompatibility; | |
| if (snapshot.inheritedFrameRate.isValid() || *outChildHasValidFrameRate) { | |
| // we already have a valid framerate. | |
| return; | |
| } | |
| // We return whether this layer or its children has a vote. We ignore ExactOrMultiple votes | |
| // for the same reason we are allowing touch boost for those layers. See | |
| // RefreshRateSelector::rankFrameRates for details. | |
| const auto layerVotedWithDefaultCompatibility = childSnapshot.frameRate.vote.rate.isValid() && | |
| childSnapshot.frameRate.vote.type == FrameRateCompatibility::Default; | |
| const auto layerVotedWithNoVote = | |
| childSnapshot.frameRate.vote.type == FrameRateCompatibility::NoVote; | |
| const auto layerVotedWithCategory = | |
| childSnapshot.frameRate.category != FrameRateCategory::Default; | |
| const auto layerVotedWithExactCompatibility = childSnapshot.frameRate.vote.rate.isValid() && | |
| childSnapshot.frameRate.vote.type == FrameRateCompatibility::Exact; | |
| *outChildHasValidFrameRate |= layerVotedWithDefaultCompatibility || layerVotedWithNoVote || | |
| layerVotedWithCategory || layerVotedWithExactCompatibility; | |
| // If we don't have a valid frame rate, but the children do, we set this | |
| // layer as NoVote to allow the children to control the refresh rate | |
| static const auto noVote = | |
| scheduler::LayerInfo::FrameRate(Fps(), FrameRateCompatibility::NoVote); | |
| if (*outChildHasValidFrameRate) { | |
| snapshot.frameRate = noVote; | |
| snapshot.changes |= RequestedLayerState::Changes::FrameRate; | |
| } else if (snapshot.frameRate != snapshot.inheritedFrameRate) { | |
| snapshot.frameRate = snapshot.inheritedFrameRate; | |
| snapshot.changes |= RequestedLayerState::Changes::FrameRate; | |
| } | |
| } | |
| int multiplyAlpha(int color, float alpha) { | |
| uint32_t c = static_cast<uint32_t>(color); | |
| float scaledAlpha = alpha * (c >> 24) / 255.0f; | |
| uint32_t a = static_cast<uint32_t>(scaledAlpha * 255 + 0.5f); | |
| return static_cast<int32_t>((c & ~0xff000000) | (a << 24)); | |
| } | |
| void LayerSnapshotBuilder::updateSnapshot(LayerSnapshot& snapshot, const Args& args, | |
| const RequestedLayerState& requested, | |
| const LayerSnapshot& parentSnapshot, | |
| const LayerHierarchy::TraversalPath& path, | |
| bool forMergedSnapshot) { | |
| // Always update flags and visibility | |
| ftl::Flags<RequestedLayerState::Changes> parentChanges = parentSnapshot.changes & | |
| (RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Geometry | | |
| RequestedLayerState::Changes::Visibility | RequestedLayerState::Changes::Metadata | | |
| RequestedLayerState::Changes::AffectsChildren | RequestedLayerState::Changes::Input | | |
| RequestedLayerState::Changes::FrameRate | RequestedLayerState::Changes::GameMode); | |
| snapshot.changes |= parentChanges; | |
| if (args.displayChanges) snapshot.changes |= RequestedLayerState::Changes::Geometry; | |
| snapshot.reachability = LayerSnapshot::Reachability::Reachable; | |
| snapshot.clientChanges |= (parentSnapshot.clientChanges & layer_state_t::AFFECTS_CHILDREN); | |
| // mark the content as dirty if the parent state changes can dirty the child's content (for | |
| // example alpha) | |
| snapshot.contentDirty |= bool(snapshot.clientChanges & layer_state_t::CONTENT_DIRTY); | |
| snapshot.isHiddenByPolicyFromParent = parentSnapshot.isHiddenByPolicyFromParent || | |
| parentSnapshot.invalidTransform || requested.isHiddenByPolicy() || | |
| (args.excludeLayerIds.find(path.id) != args.excludeLayerIds.end()) || | |
| (args.exclusionMask & requested.compositionFilterFlag); | |
| const bool forceUpdate = args.forceUpdate == ForceUpdateFlags::ALL || | |
| snapshot.clientChanges & layer_state_t::eReparent || | |
| snapshot.changes.any(RequestedLayerState::Changes::Visibility | | |
| RequestedLayerState::Changes::Created); | |
| const bool hierarchyChanged = | |
| forceUpdate || snapshot.changes.any(RequestedLayerState::Changes::Hierarchy); | |
| if (hierarchyChanged && args.isProtoVmTracingActive) { | |
| mark(TrackedField::kParent); | |
| mark(TrackedField::kZOrderRelativeOf); | |
| mark(TrackedField::kIsRelativeOf); | |
| } | |
| if (forceUpdate || snapshot.clientChanges & layer_state_t::eLayerStackChanged) { | |
| // If root layer, use the layer stack otherwise get the parent's layer stack. | |
| snapshot.outputFilter.setLayerStack(parentSnapshot.path == | |
| LayerHierarchy::TraversalPath::ROOT | |
| ? requested.layerStack | |
| : parentSnapshot.outputFilter.get().layerStack); | |
| } | |
| if (forceUpdate || snapshot.clientChanges & layer_state_t::eTrustedOverlayChanged) { | |
| switch (requested.trustedOverlay) { | |
| case gui::TrustedOverlay::UNSET: | |
| snapshot.trustedOverlay = parentSnapshot.trustedOverlay; | |
| break; | |
| case gui::TrustedOverlay::DISABLED: | |
| snapshot.trustedOverlay = requested.trustedOverlay; | |
| break; | |
| case gui::TrustedOverlay::ENABLED: | |
| snapshot.trustedOverlay = requested.trustedOverlay; | |
| break; | |
| } | |
| } | |
| if (snapshot.isHiddenByPolicyFromParent && | |
| !snapshot.changes.test(RequestedLayerState::Changes::Created)) { | |
| if (forceUpdate || | |
| snapshot.changes.any(RequestedLayerState::Changes::Geometry | | |
| RequestedLayerState::Changes::BufferSize | | |
| RequestedLayerState::Changes::Input)) { | |
| updateInput(snapshot, requested, parentSnapshot, path, args, forMergedSnapshot); | |
| } | |
| if (forceUpdate || | |
| (args.includeMetadata && | |
| snapshot.changes.any(RequestedLayerState::Changes::Metadata | | |
| RequestedLayerState::Changes::Geometry))) { | |
| updateMetadataAndGameMode(snapshot, requested, args, parentSnapshot); | |
| } | |
| return; | |
| } | |
| if (forceUpdate || snapshot.changes.any(RequestedLayerState::Changes::Mirror)) { | |
| // We don't want to capture layers with eLayerSkipScreenshot in mirrored hierarchies. This | |
| // field is used to hide mirrored layers with the flag set. | |
| snapshot.handleSkipScreenshotFlag = parentSnapshot.handleSkipScreenshotFlag || | |
| (requested.layerStackToMirror != ui::UNASSIGNED_LAYER_STACK) || | |
| (requested.layerIdToMirror != UNASSIGNED_LAYER_ID); | |
| } | |
| if (forceUpdate || snapshot.clientChanges & layer_state_t::eAlphaChanged) { | |
| snapshot.color.setA(parentSnapshot.color.get().a * requested.color.a); | |
| snapshot.alpha = snapshot.color.get().a; | |
| snapshot.inputInfo.setAlpha(snapshot.color.get().a); | |
| } | |
| if (forceUpdate || snapshot.clientChanges & layer_state_t::eFlagsChanged) { | |
| snapshot.isSecure = | |
| parentSnapshot.isSecure || (requested.flags & layer_state_t::eLayerSecure); | |
| snapshot.outputFilter.setSkipScreenshot( | |
| parentSnapshot.outputFilter.get().skipScreenshot || | |
| (requested.flags & layer_state_t::eLayerSkipScreenshot)); | |
| // This may cause a layer to become invisible, removing it from the hierarchy | |
| mResortSnapshots = true; | |
| } | |
| if (forceUpdate || snapshot.clientChanges & layer_state_t::eCompositionFilterFlagChanged) { | |
| snapshot.outputFilter.setFilterMask(requested.compositionFilterFlag | | |
| parentSnapshot.outputFilter.get().filterMask); | |
| } | |
| if (forceUpdate || snapshot.clientChanges & layer_state_t::eStretchChanged) { | |
| snapshot.stretchEffect = (requested.stretchEffect.hasEffect()) | |
| ? requested.stretchEffect | |
| : parentSnapshot.stretchEffect; | |
| } | |
| if (forceUpdate || snapshot.clientChanges & layer_state_t::ePostProcessChanged) { | |
| snapshot.postProcessShader = requested.postProcessShader; | |
| snapshot.postProcessUniforms = requested.postProcessUniforms; | |
| if (args.shaderRegistry && snapshot.postProcessShader) { | |
| snapshot.postProcessEffect = args.shaderRegistry->getShader(snapshot.postProcessShader); | |
| } else { | |
| snapshot.postProcessEffect = nullptr; | |
| } | |
| } | |
| if (forceUpdate || | |
| (snapshot.clientChanges | parentSnapshot.clientChanges) & | |
| layer_state_t::eEdgeExtensionChanged) { | |
| if (requested.edgeExtensionParameters.extendLeft || | |
| requested.edgeExtensionParameters.extendRight || | |
| requested.edgeExtensionParameters.extendTop || | |
| requested.edgeExtensionParameters.extendBottom) { | |
| // This is the root layer to which the extension is applied | |
| snapshot.edgeExtensionEffect = | |
| EdgeExtensionEffect(requested.edgeExtensionParameters.extendLeft, | |
| requested.edgeExtensionParameters.extendRight, | |
| requested.edgeExtensionParameters.extendTop, | |
| requested.edgeExtensionParameters.extendBottom); | |
| } else if (parentSnapshot.clientChanges & layer_state_t::eEdgeExtensionChanged) { | |
| // Extension is inherited | |
| snapshot.edgeExtensionEffect = parentSnapshot.edgeExtensionEffect; | |
| } else { | |
| // There is no edge extension | |
| snapshot.edgeExtensionEffect.reset(); | |
| } | |
| if (snapshot.edgeExtensionEffect.hasEffect()) { | |
| snapshot.clientChanges |= layer_state_t::eEdgeExtensionChanged; | |
| snapshot.changes |= RequestedLayerState::Changes::Geometry; | |
| } | |
| } | |
| if (forceUpdate || snapshot.clientChanges & layer_state_t::eColorTransformChanged) { | |
| if (!parentSnapshot.colorTransformIsIdentity) { | |
| snapshot.colorTransform = | |
| parentSnapshot.colorTransform.get() * requested.colorTransform; | |
| snapshot.colorTransformIsIdentity = false; | |
| } else { | |
| snapshot.colorTransform = requested.colorTransform; | |
| snapshot.colorTransformIsIdentity = !requested.hasColorTransform; | |
| } | |
| } | |
| if (forceUpdate || | |
| snapshot.changes.any(RequestedLayerState::Changes::Metadata | | |
| RequestedLayerState::Changes::Hierarchy)) { | |
| updateMetadataAndGameMode(snapshot, requested, args, parentSnapshot); | |
| } | |
| if (forceUpdate || snapshot.clientChanges & layer_state_t::eFixedTransformHintChanged || | |
| args.displayChanges) { | |
| snapshot.fixedTransformHint = requested.fixedTransformHint != ui::Transform::ROT_INVALID | |
| ? requested.fixedTransformHint | |
| : parentSnapshot.fixedTransformHint; | |
| if (snapshot.fixedTransformHint != ui::Transform::ROT_INVALID) { | |
| snapshot.transformHint = snapshot.fixedTransformHint; | |
| } else { | |
| const auto display = args.displays.get(snapshot.outputFilter.get().layerStack); | |
| snapshot.transformHint = display.has_value() | |
| ? std::make_optional<>(display->get().transformHint) | |
| : std::nullopt; | |
| } | |
| } | |
| if (forceUpdate || | |
| args.layerLifecycleManager.getGlobalChanges().any( | |
| RequestedLayerState::Changes::Hierarchy) || | |
| snapshot.changes.any(RequestedLayerState::Changes::FrameRate | | |
| RequestedLayerState::Changes::Hierarchy)) { | |
| const bool shouldOverrideChildren = parentSnapshot.frameRateSelectionStrategy == | |
| scheduler::LayerInfo::FrameRateSelectionStrategy::OverrideChildren; | |
| const bool propagationAllowed = parentSnapshot.frameRateSelectionStrategy != | |
| scheduler::LayerInfo::FrameRateSelectionStrategy::Self; | |
| if ((!requested.requestedFrameRate.isValid() && propagationAllowed) || | |
| shouldOverrideChildren) { | |
| snapshot.inheritedFrameRate = parentSnapshot.inheritedFrameRate; | |
| } else { | |
| snapshot.inheritedFrameRate = requested.requestedFrameRate; | |
| } | |
| // Set the framerate as the inherited frame rate and allow children to override it if | |
| // needed. | |
| snapshot.frameRate = snapshot.inheritedFrameRate; | |
| snapshot.changes |= RequestedLayerState::Changes::FrameRate; | |
| } | |
| if (forceUpdate || snapshot.clientChanges & layer_state_t::eFrameRateSelectionStrategyChanged) { | |
| if (parentSnapshot.frameRateSelectionStrategy == | |
| scheduler::LayerInfo::FrameRateSelectionStrategy::OverrideChildren) { | |
| snapshot.frameRateSelectionStrategy = | |
| scheduler::LayerInfo::FrameRateSelectionStrategy::OverrideChildren; | |
| } else { | |
| const auto strategy = scheduler::LayerInfo::convertFrameRateSelectionStrategy( | |
| requested.frameRateSelectionStrategy); | |
| snapshot.frameRateSelectionStrategy = strategy; | |
| } | |
| } | |
| if (forceUpdate || snapshot.clientChanges & layer_state_t::eFrameRateSelectionPriority) { | |
| snapshot.frameRateSelectionPriority = | |
| (requested.frameRateSelectionPriority == Layer::PRIORITY_UNSET) | |
| ? parentSnapshot.frameRateSelectionPriority | |
| : requested.frameRateSelectionPriority; | |
| } | |
| if (forceUpdate || | |
| snapshot.clientChanges & | |
| (layer_state_t::eBackgroundBlurRadiusChanged | | |
| layer_state_t::eBackgroundBlurScaleChanged | | |
| layer_state_t::eBlurRegionsChanged | | |
| layer_state_t::eAlphaChanged)) { | |
| snapshot.backgroundBlurRadius = static_cast<int>(parentSnapshot.color.get().a * | |
| (float)requested.backgroundBlurRadius); | |
| snapshot.backgroundBlurScale = requested.backgroundBlurScale; | |
| snapshot.blurRegions = requested.blurRegions; | |
| for (auto& region : snapshot.blurRegions) { | |
| region.alpha = region.alpha * snapshot.color.get().a; | |
| } | |
| } | |
| if (forceUpdate || snapshot.changes.any(RequestedLayerState::Changes::Geometry)) { | |
| uint32_t primaryDisplayRotationFlags = getPrimaryDisplayRotationFlags(args.displays); | |
| updateLayerBounds(snapshot, requested, parentSnapshot, primaryDisplayRotationFlags); | |
| } | |
| if (snapshot.edgeExtensionEffect.hasEffect()) { | |
| updateBoundsForEdgeExtension(snapshot); | |
| } | |
| if (forceUpdate || snapshot.clientChanges & layer_state_t::eCornerRadiusChanged || | |
| snapshot.changes.any(RequestedLayerState::Changes::Geometry | | |
| RequestedLayerState::Changes::BufferUsageFlags) || | |
| snapshot.clientChanges & layer_state_t::eClientDrawnCornerRadiusChanged) { | |
| updateRoundedCorner(snapshot, requested, parentSnapshot, args); | |
| } | |
| if (forceUpdate || snapshot.clientChanges & layer_state_t::eShadowRadiusChanged || | |
| snapshot.changes.any(RequestedLayerState::Changes::Geometry)) { | |
| updateShadows(snapshot, requested, args.globalShadowSettings); | |
| } | |
| if (forceUpdate || | |
| snapshot.clientChanges & | |
| (layer_state_t::eBoxShadowSettingsChanged | layer_state_t::eAlphaChanged)) { | |
| snapshot.boxShadowSettings = requested.boxShadowSettings; | |
| for (gui::BoxShadowSettings::BoxShadowParams& params : | |
| snapshot.boxShadowSettings.boxShadows) { | |
| params.color = multiplyAlpha(params.color, snapshot.alpha); | |
| } | |
| } | |
| if (forceUpdate || | |
| snapshot.clientChanges & | |
| (layer_state_t::eBorderSettingsChanged | layer_state_t::eAlphaChanged)) { | |
| snapshot.borderSettings = requested.borderSettings; | |
| // Multiply outline alpha by snapshot alpha. | |
| snapshot.borderSettings.color = | |
| multiplyAlpha(snapshot.borderSettings.color, snapshot.alpha); | |
| } | |
| if (forceUpdate || | |
| snapshot.changes.any(RequestedLayerState::Changes::Geometry | | |
| RequestedLayerState::Changes::Input)) { | |
| updateInput(snapshot, requested, parentSnapshot, path, args, forMergedSnapshot); | |
| } | |
| if (forceUpdate || snapshot.clientChanges & layer_state_t::eSystemContentPriorityChanged) { | |
| if (requested.systemContentPriority == gui::ISystemContentPriorityConstants::Unset) { | |
| snapshot.systemContentPriority = parentSnapshot.systemContentPriority; | |
| } else { | |
| snapshot.systemContentPriority = requested.systemContentPriority; | |
| } | |
| } | |
| if (forceUpdate || | |
| (snapshot.clientChanges & | |
| (layer_state_t::eRenderCommandBufferChanged | | |
| layer_state_t::eRenderCommandBufferFrameIdChanged))) { | |
| snapshot.renderCommandBufferConsumer = requested.renderCommandBufferConsumer; | |
| snapshot.renderCommandBufferFrameId = requested.renderCommandBufferFrameId; | |
| } | |
| if (forceUpdate || snapshot.clientChanges & layer_state_t::eRenderResourceTokenChanged) { | |
| snapshot.renderResourceToken = requested.renderResourceToken; | |
| if (snapshot.renderResourceToken && args.ooprServer) { | |
| snapshot.ooprCache = args.ooprServer->getCache(snapshot.renderResourceToken); | |
| } else { | |
| snapshot.ooprCache = nullptr; | |
| } | |
| } | |
| if (forceUpdate || | |
| snapshot.clientChanges & | |
| (layer_state_t::eDesiredHdrHeadroomChanged | | |
| layer_state_t::eDesiredMaxHdrHeadroomChanged)) { | |
| snapshot.maxDesiredHdrSdrRatio = getMaxHdrSdrRatio(requested.maxDesiredHdrSdrRatio, | |
| parentSnapshot.maxDesiredHdrSdrRatio); | |
| snapshot.desiredHdrSdrRatio = | |
| getMaxHdrSdrRatio(snapshot.maxDesiredHdrSdrRatio, requested.desiredHdrSdrRatio); | |
| } | |
| // For now we don't check LUT support so guard by a debug sysprop | |
| if (snapshot.buffer) { | |
| std::optional<std::vector<uint8_t>> smpte2094_50; | |
| status_t err; | |
| { | |
| SFTRACE_NAME("getSmpte2094_50"); | |
| err = snapshot.buffer->getSmpte2094_50(&smpte2094_50); | |
| } | |
| if (err == OK && smpte2094_50) { | |
| SFTRACE_NAME("Found smpte2094-50 on a layer!"); | |
| auto smpte2094_50Data = | |
| SkData::MakeWithoutCopy(smpte2094_50->data(), smpte2094_50->size()); | |
| skhdr::AdaptiveGlobalToneMap agtm; | |
| if (agtm.parse(smpte2094_50Data.get())) { | |
| float agtmRatio = renderengine::getMaxHeadroom(agtm); | |
| snapshot.desiredHdrSdrRatio = | |
| getMaxHdrSdrRatio(snapshot.desiredHdrSdrRatio, agtmRatio); | |
| snapshot.agtm = agtm; | |
| } | |
| } | |
| } | |
| // computed snapshot properties | |
| snapshot.forceClientComposition = snapshot.shadowSettings.length > 0 || | |
| snapshot.stretchEffect.hasEffect() || snapshot.edgeExtensionEffect.hasEffect() || | |
| snapshot.borderSettings.strokeWidth > 0 || | |
| !snapshot.boxShadowSettings.boxShadows.empty() || snapshot.renderCommandBufferFrameId || | |
| (snapshot.agtm.has_value() && FlagManager::getInstance().force_agtm_without_luts()); | |
| snapshot.contentOpaque = snapshot.isContentOpaque(); | |
| snapshot.inputInfo.setOpaque((snapshot.contentOpaque.get() || | |
| (snapshot.roundedCorner.hasClientDrawnRadius() && | |
| snapshot.roundedCorner.wouldBeOpaque)) && | |
| snapshot.color.get().a == 1.f); | |
| snapshot.isOpaque = snapshot.contentOpaque.get() && | |
| !(snapshot.roundedCorner.hasSfDrawnRadius() || | |
| snapshot.roundedCorner.hasClientDrawnRadius()) && | |
| snapshot.color.get().a == 1.f; | |
| snapshot.blendMode = getBlendMode(snapshot, requested); | |
| LLOGV(snapshot.sequence.get(), | |
| "%supdated %s changes:%s parent:%s requested:%s requested:%s from parent %s", | |
| args.forceUpdate == ForceUpdateFlags::ALL ? "Force " : "", | |
| snapshot.getDebugString().c_str(), snapshot.changes.string().c_str(), | |
| parentSnapshot.changes.string().c_str(), requested.changes.string().c_str(), | |
| requested.what.to_string().c_str(), parentSnapshot.getDebugString().c_str()); | |
| } | |
| void LayerSnapshotBuilder::updateLayerBounds(LayerSnapshot& snapshot, | |
| const RequestedLayerState& requested, | |
| const LayerSnapshot& parentSnapshot, | |
| uint32_t primaryDisplayRotationFlags) { | |
| if (FlagManager::getInstance().mirror_with_crop()) { | |
| // Fetch the requested transform to update to. | |
| ui::Transform t = snapshot.ignoreLocalTransform ? ui::Transform() | |
| : requested.getTransform(primaryDisplayRotationFlags); | |
| snapshot.localTransform = t; | |
| snapshot.localTransformInverse = snapshot.localTransform.inverse(); | |
| if (snapshot.mirrorCrop.has_value() && | |
| (snapshot.mirrorCrop->left != 0 || snapshot.mirrorCrop->top != 0)) { | |
| ui::Transform translation; | |
| translation.set(-snapshot.mirrorCrop->left, -snapshot.mirrorCrop->top); | |
| snapshot.localTransform = snapshot.localTransform * translation; | |
| snapshot.localTransformInverse = snapshot.localTransform.inverse(); | |
| } | |
| } | |
| snapshot.geomLayerTransform = parentSnapshot.geomLayerTransform.get() * snapshot.localTransform; | |
| const bool transformWasInvalid = snapshot.invalidTransform; | |
| snapshot.invalidTransform = !LayerSnapshot::isTransformValid(snapshot.geomLayerTransform.get()); | |
| if (snapshot.invalidTransform) { | |
| auto& t = snapshot.geomLayerTransform; | |
| auto& requestedT = requested.requestedTransform; | |
| std::string transformDebug = | |
| base::StringPrintf(" transform={%f,%f,%f,%f} requestedTransform={%f,%f,%f,%f}", | |
| t.get().dsdx(), t.get().dsdy(), t.get().dtdx(), t.get().dtdy(), | |
| requestedT.dsdx(), requestedT.dsdy(), requestedT.dtdx(), | |
| requestedT.dtdy()); | |
| std::string bufferDebug; | |
| if (requested.externalTexture || requested.renderCommandBufferConsumer) { | |
| auto unRotBuffer = requested.getUnrotatedBufferSize(primaryDisplayRotationFlags); | |
| auto& destFrame = requested.destinationFrame; | |
| uint32_t bufferWidth, bufferHeight; | |
| requested.getBufferDimensions(bufferWidth, bufferHeight); | |
| bufferDebug = base::StringPrintf(" buffer={%d,%d} displayRot=%d" | |
| " destFrame={%d,%d,%d,%d} unRotBuffer={%d,%d}", | |
| static_cast<int>(bufferWidth), | |
| static_cast<int>(bufferHeight), | |
| primaryDisplayRotationFlags, destFrame.left, | |
| destFrame.top, destFrame.right, destFrame.bottom, | |
| unRotBuffer.getHeight(), unRotBuffer.getWidth()); | |
| } | |
| ALOGW("Resetting transform for %s because it is invalid.%s%s", | |
| snapshot.getDebugString().c_str(), transformDebug.c_str(), bufferDebug.c_str()); | |
| snapshot.geomLayerTransform.reset(); | |
| } | |
| if (transformWasInvalid != snapshot.invalidTransform) { | |
| // If transform is invalid, the layer will be hidden. | |
| mResortSnapshots = true; | |
| } | |
| snapshot.geomInverseLayerTransform = snapshot.geomLayerTransform.get().inverse(); | |
| if (parentSnapshot.geomLayerBounds.isUnbounded() && !requested.externalTexture && | |
| !requested.renderCommandBufferFrameId) { | |
| FloatRect transformedUnbounded = snapshot.localTransform.inverse().transform( | |
| parentSnapshot.geomLayerBounds.toFloatRect()); | |
| snapshot.geomLayerBounds.setUnboundedValue(transformedUnbounded); | |
| snapshot.geomLayerCrop.setUnboundedValue(transformedUnbounded); | |
| } else { | |
| FloatRect parentBounds = parentSnapshot.geomLayerBounds; | |
| parentBounds = snapshot.localTransform.inverse().transform(parentBounds); | |
| snapshot.geomLayerBounds = | |
| requested.externalTexture || requested.renderCommandBufferFrameId | |
| ? snapshot.bufferSize.toFloatRect() | |
| : parentBounds; | |
| snapshot.geomLayerCrop = parentBounds; | |
| } | |
| if (!requested.crop.isEmpty()) { | |
| snapshot.geomLayerCrop = snapshot.geomLayerCrop.intersect(requested.crop); | |
| } | |
| if (snapshot.mirrorCrop.has_value()) { | |
| snapshot.geomLayerCrop = snapshot.geomLayerCrop.intersect(*snapshot.mirrorCrop); | |
| } | |
| snapshot.geomLayerBounds = snapshot.geomLayerBounds.intersect(snapshot.geomLayerCrop); | |
| snapshot.transformedBounds = | |
| snapshot.geomLayerTransform.get().transform(snapshot.geomLayerBounds); | |
| const Rect geomLayerBoundsWithoutTransparentRegion = | |
| RequestedLayerState::reduce(Rect(snapshot.geomLayerBounds), | |
| requested.getTransparentRegion()); | |
| snapshot.transformedBoundsWithoutTransparentRegion = | |
| snapshot.geomLayerTransform.get().transform(geomLayerBoundsWithoutTransparentRegion); | |
| snapshot.parentTransform = parentSnapshot.geomLayerTransform.get(); | |
| if (requested.potentialCursor) { | |
| // Subtract the transparent region and snap to the bounds | |
| const Rect bounds = RequestedLayerState::reduce(Rect(snapshot.croppedBufferSize.get()), | |
| requested.getTransparentRegion()); | |
| snapshot.cursorFrame = snapshot.geomLayerTransform.get().transform(bounds); | |
| } | |
| snapshot.parentGeomLayerCrop = | |
| snapshot.localTransform.inverse().transform(parentSnapshot.geomLayerCrop); | |
| if (requested.croppedByLayerId != UNASSIGNED_LAYER_ID && | |
| requested.layerIdToMirror != UNASSIGNED_LAYER_ID) { | |
| mHasMirrorRequests = true; | |
| } | |
| } | |
| void LayerSnapshotBuilder::updateInput(LayerSnapshot& snapshot, | |
| const RequestedLayerState& requested, | |
| const LayerSnapshot& parentSnapshot, | |
| const LayerHierarchy::TraversalPath& path, const Args& args, | |
| bool forMergedSnapshot) { | |
| using InputConfig = gui::WindowInfo::InputConfig; | |
| snapshot.inputInfo = requested.getWindowInfo(); | |
| snapshot.layerIdsToVerifyTransparency = requested.layerIdsToVerifyTransparency; | |
| snapshot.touchCropId = requested.touchCropId; | |
| snapshot.inputInfo.setId(static_cast<int32_t>(snapshot.uniqueSequence)); | |
| snapshot.inputInfo.setDisplayId( | |
| ui::LogicalDisplayId{static_cast<int32_t>(snapshot.outputFilter.get().layerStack.id)}); | |
| snapshot.inputInfo.setFocusGroup(requested.focusGroup != gui::UNSET_FOCUS_GROUP | |
| ? requested.focusGroup | |
| : parentSnapshot.inputInfo.get().focusGroup); | |
| snapshot.inputInfo.setTouchOcclusionMode( | |
| requested.hasInputInfo() ? requested.getWindowInfo().touchOcclusionMode | |
| : parentSnapshot.inputInfo.get().touchOcclusionMode); | |
| snapshot.inputInfo.setCanOccludePresentation( | |
| parentSnapshot.inputInfo.get().canOccludePresentation || | |
| (requested.flags & layer_state_t::eCanOccludePresentation)); | |
| if (requested.dropInputMode == gui::DropInputMode::ALL || | |
| parentSnapshot.dropInputMode == gui::DropInputMode::ALL) { | |
| snapshot.dropInputMode = gui::DropInputMode::ALL; | |
| } else if (requested.dropInputMode == gui::DropInputMode::OBSCURED || | |
| parentSnapshot.dropInputMode == gui::DropInputMode::OBSCURED) { | |
| snapshot.dropInputMode = gui::DropInputMode::OBSCURED; | |
| } else if (requested.dropInputMode == gui::DropInputMode::OBSCURED_ALLOW_PARENT_CROP || | |
| parentSnapshot.dropInputMode == gui::DropInputMode::OBSCURED_ALLOW_PARENT_CROP) { | |
| snapshot.dropInputMode = gui::DropInputMode::OBSCURED_ALLOW_PARENT_CROP; | |
| } else { | |
| snapshot.dropInputMode = gui::DropInputMode::NONE; | |
| } | |
| if (snapshot.isSecure || | |
| parentSnapshot.inputInfo.get().inputConfig.test(InputConfig::SENSITIVE_FOR_PRIVACY)) { | |
| snapshot.inputInfo.getInputConfigProxy() |= InputConfig::SENSITIVE_FOR_PRIVACY; | |
| } | |
| updateVisibility(snapshot, snapshot.isVisible); | |
| if (!requested.needsInputInfo()) { | |
| return; | |
| } | |
| static frontend::DisplayInfo sDefaultInfo = {.isSecure = false}; | |
| const std::optional<frontend::DisplayInfo> displayInfoOpt = | |
| args.displays.get(snapshot.outputFilter.get().layerStack); | |
| bool noValidDisplay = !displayInfoOpt.has_value(); | |
| auto displayInfo = displayInfoOpt.value_or(sDefaultInfo); | |
| if (!requested.hasInputInfo()) { | |
| snapshot.inputInfo.getInputConfigProxy() |= InputConfig::NO_INPUT_CHANNEL; | |
| } | |
| fillInputFrameInfo(displayInfo.transform, snapshot, snapshot.inputInfo); | |
| if (noValidDisplay) { | |
| // Do not let the window receive touches if it is not associated with a valid display | |
| // transform. We still allow the window to receive keys and prevent ANRs. | |
| snapshot.inputInfo.getInputConfigProxy() |= InputConfig::NOT_TOUCHABLE; | |
| } | |
| snapshot.inputInfo.setAlpha(snapshot.color.get().a); | |
| snapshot.inputInfo.setOpaque((snapshot.contentOpaque.get() || | |
| (snapshot.roundedCorner.hasClientDrawnRadius() && | |
| snapshot.roundedCorner.wouldBeOpaque)) && | |
| snapshot.color.get().a == 1.0f); | |
| handleDropInputMode(snapshot, parentSnapshot); | |
| // If the window will be blacked out on a display because the display does not have the secure | |
| // flag and the layer has the secure flag set, then drop input. | |
| if (!displayInfo.isSecure && snapshot.isSecure) { | |
| snapshot.inputInfo.getInputConfigProxy() |= InputConfig::DROP_INPUT; | |
| } | |
| if (requested.touchCropId != UNASSIGNED_LAYER_ID || path.isClone()) { | |
| if (!forMergedSnapshot) { | |
| mNeedsTouchableRegionCrop.insert(path); | |
| } | |
| } | |
| auto cropLayerSnapshot = path.isClone() | |
| ? getSnapshotFromClonedHierarchy(requested.touchCropId, path) | |
| : getSnapshot(requested.touchCropId); | |
| if (!cropLayerSnapshot && snapshot.inputInfo.get().replaceTouchableRegionWithCrop) { | |
| FloatRect inputBounds = getInputBounds(snapshot, /*fillParentBounds=*/true).first; | |
| Rect inputBoundsInDisplaySpace = | |
| getInputBoundsInDisplaySpace(snapshot, inputBounds, displayInfo.transform); | |
| snapshot.inputInfo.setTouchableRegion(Region(inputBoundsInDisplaySpace)); | |
| } | |
| // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state | |
| // if it was set by WM for a known system overlay. | |
| if (snapshot.trustedOverlay.get() == gui::TrustedOverlay::ENABLED) { | |
| snapshot.inputInfo.getInputConfigProxy() |= InputConfig::TRUSTED_OVERLAY; | |
| } | |
| snapshot.inputInfo.setContentSize({snapshot.croppedBufferSize.get().getHeight(), | |
| snapshot.croppedBufferSize.get().getWidth()}); | |
| snapshot.inputInfo.setCloneLayerStackTransform(std::nullopt); | |
| if (path.isClone()) { | |
| snapshot.inputInfo.getInputConfigProxy() |= InputConfig::CLONE; | |
| // Cloned layers shouldn't handle watch outside since their z order is not determined by | |
| // WM or the client. | |
| snapshot.inputInfo.getInputConfigProxy().clear(InputConfig::WATCH_OUTSIDE_TOUCH); | |
| // Compute the transform that maps the clone's display to the layer stack space of the | |
| // cloned window. | |
| const LayerSnapshot* clonedSnapshot = getSnapshot(path.getClonedFrom()); | |
| if (clonedSnapshot != nullptr) { | |
| const auto& [clonedInputBounds, s] = | |
| getInputBounds(*clonedSnapshot, /*fillParentBounds=*/false); | |
| ui::Transform inputToLayer; | |
| inputToLayer.set(clonedInputBounds.left, clonedInputBounds.top); | |
| const ui::Transform& layerToLayerStack = getInputTransform(*clonedSnapshot); | |
| const auto& displayToInput = snapshot.inputInfo.get().transform; | |
| snapshot.inputInfo.setCloneLayerStackTransform(layerToLayerStack * inputToLayer * | |
| displayToInput); | |
| } | |
| } | |
| } | |
| std::vector<std::unique_ptr<LayerSnapshot>>& LayerSnapshotBuilder::getSnapshots() { | |
| return mSnapshots; | |
| } | |
| void LayerSnapshotBuilder::forEachVisibleSnapshot(const ConstVisitor& visitor) const { | |
| for (int i = 0; i < mNumInterestingSnapshots; i++) { | |
| LayerSnapshot& snapshot = *mSnapshots[(size_t)i]; | |
| if (!snapshot.isVisible) continue; | |
| visitor(snapshot); | |
| } | |
| } | |
| // Visit each visible snapshot in z-order | |
| void LayerSnapshotBuilder::forEachVisibleSnapshot(const ConstVisitor& visitor, | |
| const LayerHierarchy& root) const { | |
| root.traverseInZOrder( | |
| [this, visitor](const LayerHierarchy&, | |
| const LayerHierarchy::TraversalPath& traversalPath) -> bool { | |
| LayerSnapshot* snapshot = getSnapshot(traversalPath); | |
| if (snapshot && snapshot->isVisible) { | |
| visitor(*snapshot); | |
| } | |
| return true; | |
| }); | |
| } | |
| void LayerSnapshotBuilder::forEachVisibleSnapshot(const Visitor& visitor) { | |
| for (int i = 0; i < mNumInterestingSnapshots; i++) { | |
| std::unique_ptr<LayerSnapshot>& snapshot = mSnapshots.at((size_t)i); | |
| if (!snapshot->isVisible) continue; | |
| visitor(snapshot); | |
| } | |
| } | |
| void LayerSnapshotBuilder::forEachNonNullSnapshot(const Visitor& visitor, | |
| const ConstPredicate& predicate) { | |
| for (int i = 0; i < mNumInterestingSnapshots; i++) { | |
| std::unique_ptr<LayerSnapshot>& snapshot = mSnapshots.at((size_t)i); | |
| if (!snapshot || !predicate(*snapshot)) continue; | |
| visitor(snapshot); | |
| } | |
| } | |
| void LayerSnapshotBuilder::forEachSnapshot(const ConstVisitor& visitor) const { | |
| for (auto& snapshot : mSnapshots) { | |
| visitor(*snapshot); | |
| } | |
| } | |
| void LayerSnapshotBuilder::forEachMergedSnapshot(const ConstVisitor& visitor) const { | |
| for (auto& snapshot : mMergedSnapshots) { | |
| visitor(*snapshot); | |
| } | |
| } | |
| void LayerSnapshotBuilder::forEachInputSnapshot(const ConstVisitor& visitor) const { | |
| for (int i = mNumInterestingSnapshots - 1; i >= 0; i--) { | |
| LayerSnapshot& snapshot = *mSnapshots[(size_t)i]; | |
| if (!snapshot.hasInputInfo()) continue; | |
| if (FlagManager::getInstance().skip_invisible_windows_in_input() && | |
| snapshot.inputInfo.get().inputConfig.test(gui::WindowInfo::InputConfig::NOT_VISIBLE)) { | |
| continue; | |
| } | |
| visitor(snapshot); | |
| } | |
| } | |
| // TODO (b/259407931): Remove. | |
| uint32_t LayerSnapshotBuilder::getPrimaryDisplayRotationFlags( | |
| const ui::DisplayMap<ui::LayerStack, frontend::DisplayInfo>& displays) const { | |
| for (auto& [_, display] : displays) { | |
| if (display.isPrimary) { | |
| return display.rotationFlags; | |
| } | |
| } | |
| return 0; | |
| } | |
| void LayerSnapshotBuilder::updateTouchableRegionCrop(const Args& args) { | |
| if (mNeedsTouchableRegionCrop.empty()) { | |
| return; | |
| } | |
| static constexpr ftl::Flags<RequestedLayerState::Changes> AFFECTS_INPUT = | |
| RequestedLayerState::Changes::Visibility | RequestedLayerState::Changes::Created | | |
| RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Geometry | | |
| RequestedLayerState::Changes::Input; | |
| if (args.forceUpdate != ForceUpdateFlags::ALL && | |
| !args.layerLifecycleManager.getGlobalChanges().any(AFFECTS_INPUT) && !args.displayChanges) { | |
| return; | |
| } | |
| for (auto& path : mNeedsTouchableRegionCrop) { | |
| frontend::LayerSnapshot* snapshot = getSnapshot(path); | |
| if (!snapshot) { | |
| continue; | |
| } | |
| LLOGV(snapshot->sequence.get(), "updateTouchableRegionCrop=%s", | |
| snapshot->getDebugString().c_str()); | |
| const std::optional<frontend::DisplayInfo> displayInfoOpt = | |
| args.displays.get(snapshot->outputFilter.get().layerStack); | |
| static frontend::DisplayInfo sDefaultInfo = {.isSecure = false}; | |
| auto displayInfo = displayInfoOpt.value_or(sDefaultInfo); | |
| bool needsUpdate = | |
| args.forceUpdate == ForceUpdateFlags::ALL || snapshot->changes.any(AFFECTS_INPUT); | |
| auto cropLayerSnapshot = path.isClone() | |
| ? getSnapshotFromClonedHierarchy(snapshot->touchCropId, path) | |
| : getSnapshot(snapshot->touchCropId); | |
| needsUpdate = | |
| needsUpdate || (cropLayerSnapshot && cropLayerSnapshot->changes.any(AFFECTS_INPUT)); | |
| auto clonedRootSnapshot = | |
| path.isClone() ? getSnapshot(snapshot->clonedRootPath) : nullptr; | |
| needsUpdate = needsUpdate || | |
| (clonedRootSnapshot && clonedRootSnapshot->changes.any(AFFECTS_INPUT)); | |
| if (!needsUpdate) { | |
| continue; | |
| } | |
| DirtyScope scope(snapshot->dirtyMask, mHasDirtySnapshots); | |
| if (snapshot->inputInfo.get().replaceTouchableRegionWithCrop) { | |
| Rect inputBoundsInDisplaySpace; | |
| if (!cropLayerSnapshot) { | |
| FloatRect inputBounds = getInputBounds(*snapshot, /*fillParentBounds=*/true).first; | |
| inputBoundsInDisplaySpace = | |
| getInputBoundsInDisplaySpace(*snapshot, inputBounds, displayInfo.transform); | |
| } else { | |
| FloatRect inputBounds = | |
| getInputBounds(*cropLayerSnapshot, /*fillParentBounds=*/true).first; | |
| inputBoundsInDisplaySpace = | |
| getInputBoundsInDisplaySpace(*cropLayerSnapshot, inputBounds, | |
| displayInfo.transform); | |
| } | |
| snapshot->inputInfo.setTouchableRegion(Region(inputBoundsInDisplaySpace)); | |
| } else if (cropLayerSnapshot) { | |
| FloatRect inputBounds = | |
| getInputBounds(*cropLayerSnapshot, /*fillParentBounds=*/true).first; | |
| Rect inputBoundsInDisplaySpace = | |
| getInputBoundsInDisplaySpace(*cropLayerSnapshot, inputBounds, | |
| displayInfo.transform); | |
| snapshot->inputInfo.setTouchableRegion( | |
| snapshot->inputInfo.get().touchableRegion.intersect(inputBoundsInDisplaySpace)); | |
| } | |
| // If the layer is a clone, we need to crop the input region to cloned root to prevent | |
| // touches from going outside the cloned area. | |
| if (clonedRootSnapshot) { | |
| const Rect rect = displayInfo.transform.transform( | |
| Rect{clonedRootSnapshot->transformedBounds.get()}); | |
| snapshot->inputInfo.setTouchableRegion( | |
| snapshot->inputInfo.get().touchableRegion.intersect(rect)); | |
| } | |
| } | |
| } | |
| // Apply stop layers to the hierarchy. | |
| // | |
| // If layer X specifies stop layer Y, then any layer within X's subhierarchy that is z-ordered | |
| // above Y is hidden. The stop layer itself, layer Y, is also hidden. | |
| // | |
| // This works by traversing the hierarchy in z-order. When a layer that specifies a stop layer is | |
| // encountered, the specified stop layer is pushed to the stopLayer stack, the subhierarchy is | |
| // traversed, then the stop layer is popped from the stack. If a layer whose id is stored in the | |
| // stop layer stack is encountered during traversal, it is added to the activeStopLayers set. Any | |
| // layer visited while the activeStopLayer set is non-empty is hidden. When an element is popped | |
| // from the stopLayer stack, any active stop layers that are no longer in the stopLayer stack are | |
| // removed from the activeStopLayers set. | |
| void LayerSnapshotBuilder::applyStopLayers(const LayerHierarchy& hierarchy, | |
| const LayerHierarchy::TraversalPath& traversalPath) { | |
| ftl::SmallVector<uint32_t, 5> stopLayers; | |
| ftl::SmallVector<uint32_t, 5> activeStopLayers; | |
| applyStopLayersInternal(hierarchy, traversalPath, stopLayers, activeStopLayers); | |
| } | |
| void LayerSnapshotBuilder::applyStopLayersInternal( | |
| const LayerHierarchy& hierarchy, const LayerHierarchy::TraversalPath& traversalPath, | |
| ftl::SmallVector<uint32_t, 5>& stopLayers, | |
| ftl::SmallVector<uint32_t, 5>& activeStopLayers) { | |
| const RequestedLayerState* layer = hierarchy.getLayer(); | |
| // Push to the stopLayer stack. | |
| if (layer->stopLayerId != UNASSIGNED_LAYER_ID) { | |
| stopLayers.push_back(layer->stopLayerId); | |
| } | |
| // Hide this layer if the activeStopLayers set is non-empty. | |
| if (!activeStopLayers.empty()) { | |
| LayerSnapshot* snapshot = getSnapshot(traversalPath); | |
| DirtyScope scope(snapshot->dirtyMask, mHasDirtySnapshots); | |
| snapshot->isHiddenByPolicyFromParent = true; | |
| snapshot->inputInfo.setInputConfig(gui::WindowInfo::InputConfig::NOT_VISIBLE, true); | |
| } | |
| // Traverse z-ordered below children before potentially activating this layer as a stop layer. | |
| auto childIt = hierarchy.mChildren.begin(); | |
| while (childIt != hierarchy.mChildren.end()) { | |
| auto& [childHierarchy, childVariant] = *childIt; | |
| if (childHierarchy->getLayer()->z >= 0) { | |
| break; | |
| } | |
| childIt++; | |
| LayerHierarchy::TraversalPath childTraversalPath = | |
| traversalPath.makeChild(childHierarchy->getLayer()->id, childVariant); | |
| if (childTraversalPath.detached) { | |
| continue; | |
| } | |
| applyStopLayersInternal(*childHierarchy, childTraversalPath, stopLayers, activeStopLayers); | |
| } | |
| // Activate this layer as a stop layer if it's in the stopLayers stack. | |
| bool isStopLayer = | |
| std::find(stopLayers.begin(), stopLayers.end(), layer->id) != stopLayers.end(); | |
| if (isStopLayer) { | |
| activeStopLayers.push_back(layer->id); | |
| LayerSnapshot* snapshot = getSnapshot(traversalPath); | |
| DirtyScope scope(snapshot->dirtyMask, mHasDirtySnapshots); | |
| snapshot->isHiddenByPolicyFromParent = true; | |
| snapshot->inputInfo.setInputConfig(gui::WindowInfo::InputConfig::NOT_VISIBLE, true); | |
| } | |
| // Traverse z-ordered above children. | |
| while (childIt != hierarchy.mChildren.end()) { | |
| auto& [childHierarchy, childVariant] = *childIt++; | |
| LayerHierarchy::TraversalPath childTraversalPath = | |
| traversalPath.makeChild(childHierarchy->getLayer()->id, childVariant); | |
| if (childTraversalPath.detached) { | |
| continue; | |
| } | |
| applyStopLayersInternal(*childHierarchy, childTraversalPath, stopLayers, activeStopLayers); | |
| } | |
| // Pop from the stopLayer stack and remove active stop layers from the activeStopLayers set | |
| // if necessary. | |
| if (layer->stopLayerId != UNASSIGNED_LAYER_ID) { | |
| stopLayers.pop_back(); | |
| auto it = activeStopLayers.begin(); | |
| while (it != activeStopLayers.end()) { | |
| bool stopLayerNoLongerActive = | |
| std::find(stopLayers.begin(), stopLayers.end(), *it) == stopLayers.end(); | |
| if (stopLayerNoLongerActive) { | |
| activeStopLayers.unstable_erase(it); | |
| } else { | |
| it++; | |
| } | |
| } | |
| } | |
| } | |
| /* | |
| * Updates the crop for each mirror layer that is cropped by another layer. | |
| * | |
| * The crop is calculated in the mirrored layer's coordinate space by transforming the crop | |
| * layer's bounds. If any crop changes, this function returns true, signaling that a second | |
| * traversal of the hierarchy is needed to update the geometry of the mirror layer and its | |
| * children. | |
| * | |
| * @param args The arguments for updating snapshots, containing layer states and other context. | |
| * @return True if any mirror crop has changed, false otherwise. | |
| */ | |
| bool LayerSnapshotBuilder::updateMirrorLayerCrops(const Args& args) { | |
| static constexpr ftl::Flags<RequestedLayerState::Changes> AFFECTS_CROP = | |
| RequestedLayerState::Changes::Geometry | RequestedLayerState::Changes::Hierarchy | | |
| RequestedLayerState::Changes::Created | RequestedLayerState::Changes::Visibility; | |
| if (args.forceUpdate != ForceUpdateFlags::ALL && | |
| !args.layerLifecycleManager.getGlobalChanges().any(AFFECTS_CROP) && !args.displayChanges) { | |
| return false; | |
| } | |
| if (!mHasMirrorRequests && !mSnapshotsHaveMirrorCrop) { | |
| return false; | |
| } | |
| bool changed = false; | |
| bool newSnapshotsHaveMirrorCrop = false; | |
| for (auto& mirrorTargetSnapshot : mSnapshots) { | |
| const RequestedLayerState* requested = | |
| args.layerLifecycleManager.getLayerFromId(mirrorTargetSnapshot->path.id); | |
| if (!requested) { | |
| continue; | |
| } | |
| // If a layer serves as a mirror target for a mirror with crop operation, it would have its | |
| // layerIdToMirror and croppedByLayerId set. | |
| if (requested->croppedByLayerId == UNASSIGNED_LAYER_ID || | |
| requested->layerIdToMirror == UNASSIGNED_LAYER_ID) { | |
| if (mirrorTargetSnapshot->mirrorCrop.has_value()) { | |
| mirrorTargetSnapshot->mirrorCrop.reset(); | |
| mirrorTargetSnapshot->changes |= RequestedLayerState::Changes::Geometry; | |
| changed = true; | |
| } | |
| continue; | |
| } | |
| LayerSnapshot* cropBySnapshot = getSnapshot(requested->croppedByLayerId); | |
| LayerSnapshot* mirrorFromSnapshot = getSnapshot(requested->layerIdToMirror); | |
| const bool isValidMirror = cropBySnapshot && | |
| cropBySnapshot->reachability != LayerSnapshot::Reachability::Unreachable && | |
| mirrorFromSnapshot && | |
| mirrorFromSnapshot->reachability != LayerSnapshot::Reachability::Unreachable && | |
| !mirrorFromSnapshot->invalidTransform; | |
| const bool isUnbounded = cropBySnapshot && cropBySnapshot->geomLayerBounds.isUnbounded(); | |
| if (isValidMirror && !isUnbounded) { | |
| newSnapshotsHaveMirrorCrop = true; | |
| // To calculate the crop in the mirrored layer's (source) coordinate space, we need to | |
| // transform the crop layer's bounds. This is done by creating a transform that maps | |
| // from the crop layer's space to the mirrored layer's space. | |
| // 1. cropBySnapshot->geomLayerTransform: crop layer space -> screen space | |
| // 2. mirrorFromSnapshot->geomLayerTransform.inverse(): screen space -> | |
| // mirrored layer (source) space | |
| // | |
| // We use mirrorFromSnapshot because the crop defines which part of the source content | |
| // to display. mirrorTargetSnapshot->geomLayerTransform would map to the mirror | |
| // destination layer's local space, which would be incorrect as the crop is not relative | |
| // to the mirror's on-screen position. | |
| ui::Transform transform = mirrorFromSnapshot->geomLayerTransform.get().inverse() * | |
| cropBySnapshot->geomLayerTransform.get(); | |
| // Get the bounds of the crop layer. | |
| FloatRect bounds = cropBySnapshot->geomLayerBounds; | |
| // Transform the crop layer's bounds into the mirrored layer's coordinate space. | |
| FloatRect crop = transform.transform(bounds); | |
| if (!mirrorTargetSnapshot->mirrorCrop.has_value() || | |
| !(*mirrorTargetSnapshot->mirrorCrop == crop)) { | |
| mirrorTargetSnapshot->mirrorCrop = crop; | |
| mirrorTargetSnapshot->changes |= RequestedLayerState::Changes::Geometry; | |
| changed = true; | |
| } | |
| } else { | |
| if (mirrorTargetSnapshot->mirrorCrop.has_value()) { | |
| mirrorTargetSnapshot->mirrorCrop.reset(); | |
| mirrorTargetSnapshot->changes |= RequestedLayerState::Changes::Geometry; | |
| changed = true; | |
| } | |
| } | |
| } | |
| mSnapshotsHaveMirrorCrop = newSnapshotsHaveMirrorCrop; | |
| return changed; | |
| } | |
| void LayerSnapshotBuilder::writeSnapshotsToPatch( | |
| com::android::internal::pbzero::LayersPatchProto* msg, const LayerLifecycleManager& manager, | |
| uint32_t traceFlags) { | |
| LOG_ALWAYS_FATAL_IF(msg == nullptr, "LayersPatchProto message cannot be null"); | |
| for (auto& snapshot : mSnapshots) { | |
| if (snapshot->dirtyMask.any()) { | |
| const RequestedLayerState* requested = manager.getLayerFromId(snapshot->path.id); | |
| if (requested != nullptr) { | |
| const int32_t parentId = getParentId(*snapshot, manager, mPathToSnapshot); | |
| const int32_t relativeParentId = | |
| getRelativeParentId(*snapshot, manager, mPathToSnapshot); | |
| writeSnapshotToPatch(msg, *snapshot, *requested, parentId, relativeParentId, | |
| traceFlags); | |
| } | |
| snapshot->dirtyMask.reset(); | |
| } | |
| } | |
| for (uint32_t destroyedId : mDestroyedSnapshotIds) { | |
| msg->add_deleted_layer_ids(static_cast<int32_t>(destroyedId)); | |
| } | |
| mDestroyedSnapshotIds.clear(); | |
| } | |
| void LayerSnapshotBuilder::clearTracingState() { | |
| mDestroyedSnapshotIds.clear(); | |
| for (auto& snapshot : mSnapshots) { | |
| if (snapshot->reachability != LayerSnapshot::Reachability::Unreachable) { | |
| snapshot->dirtyMask.reset(); | |
| snapshot->contentDirty = snapshot->autoRefresh; | |
| } | |
| } | |
| } | |
| bool LayerSnapshotBuilder::hasDirtySnapshots() const { | |
| return mHasDirtySnapshots; | |
| } | |
| } // namespace android::surfaceflinger::frontend |