blob: 7569c1b8de721679b90c5d3e40c3b05624eb18e7 [file] [log] [blame]
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001/*
2 * Copyright 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17// #define LOG_NDEBUG 0
18#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19#undef LOG_TAG
Vishnu Naira02943f2023-06-03 13:44:46 -070020#define LOG_TAG "SurfaceFlinger"
Vishnu Nair8fc721b2022-12-22 20:06:32 +000021
Vishnu Nair8fc721b2022-12-22 20:06:32 +000022#include <numeric>
Vishnu Nairb76d99a2023-03-19 18:22:31 -070023#include <optional>
24
Vishnu Nair9e0017e2024-05-22 19:02:44 +000025#include <common/FlagManager.h>
Vishnu Nairbe0ad902024-06-27 23:38:43 +000026#include <common/trace.h>
Dominik Laskowski6b049ff2023-01-29 15:46:45 -050027#include <ftl/small_map.h>
Vishnu Naira02943f2023-06-03 13:44:46 -070028#include <ui/DisplayMap.h>
Dominik Laskowski6b049ff2023-01-29 15:46:45 -050029#include <ui/FloatRect.h>
30
Vishnu Nair8fc721b2022-12-22 20:06:32 +000031#include "DisplayHardware/HWC2.h"
32#include "DisplayHardware/Hal.h"
Vishnu Nair3d8565a2023-06-30 07:23:24 +000033#include "Layer.h" // eFrameRateSelectionPriority constants
Vishnu Naircfb2d252023-01-19 04:44:02 +000034#include "LayerLog.h"
Vishnu Nairb76d99a2023-03-19 18:22:31 -070035#include "LayerSnapshotBuilder.h"
Vishnu Naircfb2d252023-01-19 04:44:02 +000036#include "TimeStats/TimeStats.h"
Vishnu Naird1f74982023-06-15 20:16:51 -070037#include "Tracing/TransactionTracing.h"
Vishnu Nair8fc721b2022-12-22 20:06:32 +000038
39namespace android::surfaceflinger::frontend {
40
41using namespace ftl::flag_operators;
42
43namespace {
Dominik Laskowski6b049ff2023-01-29 15:46:45 -050044
45FloatRect getMaxDisplayBounds(const DisplayInfos& displays) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +000046 const ui::Size maxSize = [&displays] {
47 if (displays.empty()) return ui::Size{5000, 5000};
48
49 return std::accumulate(displays.begin(), displays.end(), ui::kEmptySize,
50 [](ui::Size size, const auto& pair) -> ui::Size {
51 const auto& display = pair.second;
52 return {std::max(size.getWidth(), display.info.logicalWidth),
53 std::max(size.getHeight(), display.info.logicalHeight)};
54 });
55 }();
56
57 // Ignore display bounds for now since they will be computed later. Use a large Rect bound
58 // to ensure it's bigger than an actual display will be.
59 const float xMax = static_cast<float>(maxSize.getWidth()) * 10.f;
60 const float yMax = static_cast<float>(maxSize.getHeight()) * 10.f;
61
62 return {-xMax, -yMax, xMax, yMax};
63}
64
65// Applies the given transform to the region, while protecting against overflows caused by any
66// offsets. If applying the offset in the transform to any of the Rects in the region would result
67// in an overflow, they are not added to the output Region.
68Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
69 const std::string& debugWindowName) {
70 // Round the translation using the same rounding strategy used by ui::Transform.
71 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
72 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
73
74 ui::Transform transformWithoutOffset = t;
75 transformWithoutOffset.set(0.f, 0.f);
76
77 const Region transformed = transformWithoutOffset.transform(r);
78
79 // Apply the translation to each of the Rects in the region while discarding any that overflow.
80 Region ret;
81 for (const auto& rect : transformed) {
82 Rect newRect;
83 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
84 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
85 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
86 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
87 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
88 debugWindowName.c_str());
89 continue;
90 }
91 ret.orSelf(newRect);
92 }
93 return ret;
94}
95
96/*
97 * We don't want to send the layer's transform to input, but rather the
98 * parent's transform. This is because Layer's transform is
99 * information about how the buffer is placed on screen. The parent's
100 * transform makes more sense to send since it's information about how the
101 * layer is placed on screen. This transform is used by input to determine
102 * how to go from screen space back to window space.
103 */
104ui::Transform getInputTransform(const LayerSnapshot& snapshot) {
105 if (!snapshot.hasBufferOrSidebandStream()) {
106 return snapshot.geomLayerTransform;
107 }
108 return snapshot.parentTransform;
109}
110
111/**
Vishnu Nairfed7c122023-03-18 01:54:43 +0000112 * Returns the bounds used to fill the input frame and the touchable region.
113 *
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000114 * Similar to getInputTransform, we need to update the bounds to include the transform.
115 * This is because bounds don't include the buffer transform, where the input assumes
116 * that's already included.
117 */
Vishnu Nairfed7c122023-03-18 01:54:43 +0000118std::pair<FloatRect, bool> getInputBounds(const LayerSnapshot& snapshot, bool fillParentBounds) {
Vishnu Naira9123c82024-10-03 03:56:44 +0000119 FloatRect inputBounds = snapshot.croppedBufferSize;
Vishnu Nairfed7c122023-03-18 01:54:43 +0000120 if (snapshot.hasBufferOrSidebandStream() && snapshot.croppedBufferSize.isValid() &&
121 snapshot.localTransform.getType() != ui::Transform::IDENTITY) {
122 inputBounds = snapshot.localTransform.transform(inputBounds);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000123 }
124
Vishnu Nairfed7c122023-03-18 01:54:43 +0000125 bool inputBoundsValid = snapshot.croppedBufferSize.isValid();
126 if (!inputBoundsValid) {
127 /**
128 * Input bounds are based on the layer crop or buffer size. But if we are using
129 * the layer bounds as the input bounds (replaceTouchableRegionWithCrop flag) then
130 * we can use the parent bounds as the input bounds if the layer does not have buffer
131 * or a crop. We want to unify this logic but because of compat reasons we cannot always
132 * use the parent bounds. A layer without a buffer can get input. So when a window is
133 * initially added, its touchable region can fill its parent layer bounds and that can
134 * have negative consequences.
135 */
136 inputBounds = fillParentBounds ? snapshot.geomLayerBounds : FloatRect{};
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000137 }
Vishnu Nairfed7c122023-03-18 01:54:43 +0000138
139 // Clamp surface inset to the input bounds.
140 const float inset = static_cast<float>(snapshot.inputInfo.surfaceInset);
141 const float xSurfaceInset = std::clamp(inset, 0.f, inputBounds.getWidth() / 2.f);
142 const float ySurfaceInset = std::clamp(inset, 0.f, inputBounds.getHeight() / 2.f);
143
144 // Apply the insets to the input bounds.
145 inputBounds.left += xSurfaceInset;
146 inputBounds.top += ySurfaceInset;
147 inputBounds.right -= xSurfaceInset;
148 inputBounds.bottom -= ySurfaceInset;
149 return {inputBounds, inputBoundsValid};
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000150}
151
Vishnu Nairfed7c122023-03-18 01:54:43 +0000152Rect getInputBoundsInDisplaySpace(const LayerSnapshot& snapshot, const FloatRect& insetBounds,
153 const ui::Transform& screenToDisplay) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000154 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
155 // frame and transform used for the layer, which determines the bounds and the coordinate space
156 // within which the layer will receive input.
Vishnu Nairfed7c122023-03-18 01:54:43 +0000157
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000158 // Coordinate space definitions:
159 // - display: The display device's coordinate space. Correlates to pixels on the display.
160 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
161 // - layer: The coordinate space of this layer.
162 // - input: The coordinate space in which this layer will receive input events. This could be
163 // different than layer space if a surfaceInset is used, which changes the origin
164 // of the input space.
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000165
166 // Crop the input bounds to ensure it is within the parent's bounds.
Vishnu Nairfed7c122023-03-18 01:54:43 +0000167 const FloatRect croppedInsetBoundsInLayer = snapshot.geomLayerBounds.intersect(insetBounds);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000168
169 const ui::Transform layerToScreen = getInputTransform(snapshot);
170 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
171
Vishnu Nairfed7c122023-03-18 01:54:43 +0000172 return Rect{layerToDisplay.transform(croppedInsetBoundsInLayer)};
173}
174
175void fillInputFrameInfo(gui::WindowInfo& info, const ui::Transform& screenToDisplay,
176 const LayerSnapshot& snapshot) {
177 auto [inputBounds, inputBoundsValid] = getInputBounds(snapshot, /*fillParentBounds=*/false);
178 if (!inputBoundsValid) {
179 info.touchableRegion.clear();
180 }
181
Chavi Weingarten7f019192023-08-08 20:39:01 +0000182 info.frame = getInputBoundsInDisplaySpace(snapshot, inputBounds, screenToDisplay);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000183
184 ui::Transform inputToLayer;
Vishnu Nairfed7c122023-03-18 01:54:43 +0000185 inputToLayer.set(inputBounds.left, inputBounds.top);
186 const ui::Transform layerToScreen = getInputTransform(snapshot);
187 const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000188
189 // InputDispatcher expects a display-to-input transform.
190 info.transform = inputToDisplay.inverse();
191
192 // The touchable region is specified in the input coordinate space. Change it to display space.
193 info.touchableRegion =
194 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, snapshot.name);
195}
196
197void handleDropInputMode(LayerSnapshot& snapshot, const LayerSnapshot& parentSnapshot) {
198 if (snapshot.inputInfo.inputConfig.test(gui::WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
199 return;
200 }
201
202 // Check if we need to drop input unconditionally
203 const gui::DropInputMode dropInputMode = snapshot.dropInputMode;
204 if (dropInputMode == gui::DropInputMode::ALL) {
205 snapshot.inputInfo.inputConfig |= gui::WindowInfo::InputConfig::DROP_INPUT;
206 ALOGV("Dropping input for %s as requested by policy.", snapshot.name.c_str());
207 return;
208 }
209
210 // Check if we need to check if the window is obscured by parent
211 if (dropInputMode != gui::DropInputMode::OBSCURED) {
212 return;
213 }
214
215 // Check if the parent has set an alpha on the layer
216 if (parentSnapshot.color.a != 1.0_hf) {
217 snapshot.inputInfo.inputConfig |= gui::WindowInfo::InputConfig::DROP_INPUT;
218 ALOGV("Dropping input for %s as requested by policy because alpha=%f",
219 snapshot.name.c_str(), static_cast<float>(parentSnapshot.color.a));
220 }
221
222 // Check if the parent has cropped the buffer
Vishnu Naira9123c82024-10-03 03:56:44 +0000223 FloatRect bufferSize = snapshot.croppedBufferSize;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000224 if (!bufferSize.isValid()) {
225 snapshot.inputInfo.inputConfig |= gui::WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
226 return;
227 }
228
229 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
230 // To check if the layer has been cropped, we take the buffer bounds, apply the local
231 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
232 // match then the layer has not been cropped by its parents.
233 Rect bufferInScreenSpace(snapshot.geomLayerTransform.transform(bufferSize));
234 bool croppedByParent = bufferInScreenSpace != Rect{snapshot.transformedBounds};
235
236 if (croppedByParent) {
237 snapshot.inputInfo.inputConfig |= gui::WindowInfo::InputConfig::DROP_INPUT;
238 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
239 snapshot.name.c_str());
240 } else {
241 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
242 // input if the window is obscured. This check should be done in surfaceflinger but the
243 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
244 // drop input events if the window is obscured.
245 snapshot.inputInfo.inputConfig |= gui::WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
246 }
247}
248
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000249auto getBlendMode(const LayerSnapshot& snapshot, const RequestedLayerState& requested) {
250 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
251 if (snapshot.alpha != 1.0f || !snapshot.isContentOpaque()) {
252 blendMode = requested.premultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
253 : Hwc2::IComposerClient::BlendMode::COVERAGE;
254 }
255 return blendMode;
256}
257
Vishnu Nair80a5a702023-02-11 01:21:51 +0000258void updateVisibility(LayerSnapshot& snapshot, bool visible) {
Vishnu Nairb4a6a772024-06-12 14:41:08 -0700259 if (snapshot.isVisible != visible) {
260 snapshot.changes |= RequestedLayerState::Changes::Visibility;
261 }
Vishnu Nair80a5a702023-02-11 01:21:51 +0000262 snapshot.isVisible = visible;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000263
264 // TODO(b/238781169) we are ignoring this compat for now, since we will have
265 // to remove any optimization based on visibility.
266
267 // For compatibility reasons we let layers which can receive input
268 // receive input before they have actually submitted a buffer. Because
269 // of this we use canReceiveInput instead of isVisible to check the
270 // policy-visibility, ignoring the buffer state. However for layers with
271 // hasInputInfo()==false we can use the real visibility state.
272 // We are just using these layers for occlusion detection in
273 // InputDispatcher, and obviously if they aren't visible they can't occlude
274 // anything.
Vishnu Nair80a5a702023-02-11 01:21:51 +0000275 const bool visibleForInput =
Vishnu Nair40d02282023-02-28 21:11:40 +0000276 snapshot.hasInputInfo() ? snapshot.canReceiveInput() : snapshot.isVisible;
Vishnu Nair80a5a702023-02-11 01:21:51 +0000277 snapshot.inputInfo.setInputConfig(gui::WindowInfo::InputConfig::NOT_VISIBLE, !visibleForInput);
Vishnu Naira02943f2023-06-03 13:44:46 -0700278 LLOGV(snapshot.sequence, "updating visibility %s %s", visible ? "true" : "false",
279 snapshot.getDebugString().c_str());
Vishnu Naircfb2d252023-01-19 04:44:02 +0000280}
281
Vishnu Nairc765c6c2023-02-23 00:08:01 +0000282void updateMetadata(LayerSnapshot& snapshot, const RequestedLayerState& requested,
283 const LayerSnapshotBuilder::Args& args) {
284 snapshot.metadata.clear();
285 for (const auto& [key, mandatory] : args.supportedLayerGenericMetadata) {
286 auto compatIter = args.genericLayerMetadataKeyMap.find(key);
287 if (compatIter == std::end(args.genericLayerMetadataKeyMap)) {
288 continue;
289 }
290 const uint32_t id = compatIter->second;
291 auto it = requested.metadata.mMap.find(id);
292 if (it == std::end(requested.metadata.mMap)) {
293 continue;
294 }
295
296 snapshot.metadata.emplace(key,
297 compositionengine::GenericLayerMetadataEntry{mandatory,
298 it->second});
299 }
300}
301
Nergi Rahardi0dfc0962024-05-23 06:57:36 +0000302void updateMetadataAndGameMode(LayerSnapshot& snapshot, const RequestedLayerState& requested,
303 const LayerSnapshotBuilder::Args& args,
304 const LayerSnapshot& parentSnapshot) {
Vishnu Nair39a74a92024-07-29 19:01:50 +0000305 snapshot.gameMode = requested.metadata.has(gui::METADATA_GAME_MODE) ? requested.gameMode
306 : parentSnapshot.gameMode;
Nergi Rahardi0dfc0962024-05-23 06:57:36 +0000307 updateMetadata(snapshot, requested, args);
308 if (args.includeMetadata) {
309 snapshot.layerMetadata = parentSnapshot.layerMetadata;
310 snapshot.layerMetadata.merge(requested.metadata);
311 }
312}
313
Vishnu Naircfb2d252023-01-19 04:44:02 +0000314void clearChanges(LayerSnapshot& snapshot) {
315 snapshot.changes.clear();
Vishnu Naira02943f2023-06-03 13:44:46 -0700316 snapshot.clientChanges = 0;
Vishnu Naira4b3a102024-11-05 05:26:38 +0000317 snapshot.contentDirty = snapshot.autoRefresh;
318 snapshot.hasReadyFrame = snapshot.autoRefresh;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000319 snapshot.sidebandStreamHasFrame = false;
320 snapshot.surfaceDamage.clear();
321}
322
Vishnu Naira02943f2023-06-03 13:44:46 -0700323// TODO (b/259407931): Remove.
324uint32_t getPrimaryDisplayRotationFlags(
325 const ui::DisplayMap<ui::LayerStack, frontend::DisplayInfo>& displays) {
326 for (auto& [_, display] : displays) {
327 if (display.isPrimary) {
328 return display.rotationFlags;
329 }
330 }
331 return 0;
332}
333
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000334} // namespace
335
336LayerSnapshot LayerSnapshotBuilder::getRootSnapshot() {
337 LayerSnapshot snapshot;
Vishnu Nair92990e22023-02-24 20:01:05 +0000338 snapshot.path = LayerHierarchy::TraversalPath::ROOT;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000339 snapshot.changes = ftl::Flags<RequestedLayerState::Changes>();
Vishnu Naira02943f2023-06-03 13:44:46 -0700340 snapshot.clientChanges = 0;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000341 snapshot.isHiddenByPolicyFromParent = false;
342 snapshot.isHiddenByPolicyFromRelativeParent = false;
343 snapshot.parentTransform.reset();
344 snapshot.geomLayerTransform.reset();
345 snapshot.geomInverseLayerTransform.reset();
346 snapshot.geomLayerBounds = getMaxDisplayBounds({});
347 snapshot.roundedCorner = RoundedCornerState();
348 snapshot.stretchEffect = {};
Marzia Favarodcc9d9b2024-01-10 10:17:00 +0000349 snapshot.edgeExtensionEffect = {};
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000350 snapshot.outputFilter.layerStack = ui::DEFAULT_LAYER_STACK;
351 snapshot.outputFilter.toInternalDisplay = false;
352 snapshot.isSecure = false;
353 snapshot.color.a = 1.0_hf;
354 snapshot.colorTransformIsIdentity = true;
Vishnu Naird9e4f462023-10-06 04:05:45 +0000355 snapshot.shadowSettings.length = 0.f;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000356 snapshot.layerMetadata.mMap.clear();
357 snapshot.relativeLayerMetadata.mMap.clear();
358 snapshot.inputInfo.touchOcclusionMode = gui::TouchOcclusionMode::BLOCK_UNTRUSTED;
359 snapshot.dropInputMode = gui::DropInputMode::NONE;
Vishnu Nair9e0017e2024-05-22 19:02:44 +0000360 snapshot.trustedOverlay = gui::TrustedOverlay::UNSET;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000361 snapshot.gameMode = gui::GameMode::Unsupported;
362 snapshot.frameRate = {};
363 snapshot.fixedTransformHint = ui::Transform::ROT_INVALID;
Vishnu Nair422b81c2024-05-16 05:44:28 +0000364 snapshot.ignoreLocalTransform = false;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000365 return snapshot;
366}
367
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000368LayerSnapshotBuilder::LayerSnapshotBuilder() {}
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000369
370LayerSnapshotBuilder::LayerSnapshotBuilder(Args args) : LayerSnapshotBuilder() {
Vishnu Naird47bcee2023-02-24 18:08:51 +0000371 args.forceUpdate = ForceUpdateFlags::ALL;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000372 updateSnapshots(args);
373}
374
375bool LayerSnapshotBuilder::tryFastUpdate(const Args& args) {
Vishnu Naira02943f2023-06-03 13:44:46 -0700376 const bool forceUpdate = args.forceUpdate != ForceUpdateFlags::NONE;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000377
Vishnu Naira02943f2023-06-03 13:44:46 -0700378 if (args.layerLifecycleManager.getGlobalChanges().get() == 0 && !forceUpdate &&
379 !args.displayChanges) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000380 return true;
381 }
382
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000383 // There are only content changes which do not require any child layer snapshots to be updated.
384 ALOGV("%s", __func__);
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000385 SFTRACE_NAME("FastPath");
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000386
Vishnu Naira02943f2023-06-03 13:44:46 -0700387 uint32_t primaryDisplayRotationFlags = getPrimaryDisplayRotationFlags(args.displays);
388 if (forceUpdate || args.displayChanges) {
389 for (auto& snapshot : mSnapshots) {
390 const RequestedLayerState* requested =
391 args.layerLifecycleManager.getLayerFromId(snapshot->path.id);
392 if (!requested) continue;
393 snapshot->merge(*requested, forceUpdate, args.displayChanges, args.forceFullDamage,
394 primaryDisplayRotationFlags);
395 }
396 return false;
397 }
398
399 // Walk through all the updated requested layer states and update the corresponding snapshots.
400 for (const RequestedLayerState* requested : args.layerLifecycleManager.getChangedLayers()) {
401 auto range = mIdToSnapshots.equal_range(requested->id);
402 for (auto it = range.first; it != range.second; it++) {
403 it->second->merge(*requested, forceUpdate, args.displayChanges, args.forceFullDamage,
404 primaryDisplayRotationFlags);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000405 }
406 }
407
Vishnu Naira02943f2023-06-03 13:44:46 -0700408 if ((args.layerLifecycleManager.getGlobalChanges().get() &
409 ~(RequestedLayerState::Changes::Content | RequestedLayerState::Changes::Buffer).get()) !=
410 0) {
411 // We have changes that require us to walk the hierarchy and update child layers.
412 // No fast path for you.
413 return false;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000414 }
415 return true;
416}
417
418void LayerSnapshotBuilder::updateSnapshots(const Args& args) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000419 SFTRACE_NAME("UpdateSnapshots");
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000420 LayerSnapshot rootSnapshot = args.rootSnapshot;
Vishnu Nair3af0ec02023-02-10 04:13:48 +0000421 if (args.parentCrop) {
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000422 rootSnapshot.geomLayerBounds = *args.parentCrop;
Vishnu Naird47bcee2023-02-24 18:08:51 +0000423 } else if (args.forceUpdate == ForceUpdateFlags::ALL || args.displayChanges) {
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000424 rootSnapshot.geomLayerBounds = getMaxDisplayBounds(args.displays);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000425 }
426 if (args.displayChanges) {
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000427 rootSnapshot.changes = RequestedLayerState::Changes::AffectsChildren |
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000428 RequestedLayerState::Changes::Geometry;
429 }
Vishnu Naird47bcee2023-02-24 18:08:51 +0000430 if (args.forceUpdate == ForceUpdateFlags::HIERARCHY) {
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000431 rootSnapshot.changes |=
Vishnu Naird47bcee2023-02-24 18:08:51 +0000432 RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Visibility;
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000433 rootSnapshot.clientChanges |= layer_state_t::eReparent;
Vishnu Naird47bcee2023-02-24 18:08:51 +0000434 }
Vishnu Naira02943f2023-06-03 13:44:46 -0700435
436 for (auto& snapshot : mSnapshots) {
437 if (snapshot->reachablilty == LayerSnapshot::Reachablilty::Reachable) {
438 snapshot->reachablilty = LayerSnapshot::Reachablilty::Unreachable;
439 }
440 }
441
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000442 LayerHierarchy::TraversalPath root = LayerHierarchy::TraversalPath::ROOT;
Vishnu Naird47bcee2023-02-24 18:08:51 +0000443 if (args.root.getLayer()) {
444 // The hierarchy can have a root layer when used for screenshots otherwise, it will have
445 // multiple children.
446 LayerHierarchy::ScopedAddToTraversalPath addChildToPath(root, args.root.getLayer()->id,
447 LayerHierarchy::Variant::Attached);
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000448 updateSnapshotsInHierarchy(args, args.root, root, rootSnapshot, /*depth=*/0);
Vishnu Naird47bcee2023-02-24 18:08:51 +0000449 } else {
450 for (auto& [childHierarchy, variant] : args.root.mChildren) {
451 LayerHierarchy::ScopedAddToTraversalPath addChildToPath(root,
452 childHierarchy->getLayer()->id,
453 variant);
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000454 updateSnapshotsInHierarchy(args, *childHierarchy, root, rootSnapshot, /*depth=*/0);
Vishnu Naird47bcee2023-02-24 18:08:51 +0000455 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000456 }
457
Vishnu Nair29354ec2023-03-28 18:51:28 -0700458 // Update touchable region crops outside the main update pass. This is because a layer could be
459 // cropped by any other layer and it requires both snapshots to be updated.
460 updateTouchableRegionCrop(args);
461
Vishnu Nairfccd6362023-02-24 23:39:53 +0000462 const bool hasUnreachableSnapshots = sortSnapshotsByZ(args);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000463
Vishnu Nair29354ec2023-03-28 18:51:28 -0700464 // Destroy unreachable snapshots for clone layers. And destroy snapshots for non-clone
465 // layers if the layer have been destroyed.
466 // TODO(b/238781169) consider making clone layer ids stable as well
467 if (!hasUnreachableSnapshots && args.layerLifecycleManager.getDestroyedLayers().empty()) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000468 return;
469 }
470
Vishnu Nair29354ec2023-03-28 18:51:28 -0700471 std::unordered_set<uint32_t> destroyedLayerIds;
472 for (auto& destroyedLayer : args.layerLifecycleManager.getDestroyedLayers()) {
473 destroyedLayerIds.insert(destroyedLayer->id);
474 }
475
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000476 auto it = mSnapshots.begin();
477 while (it < mSnapshots.end()) {
478 auto& traversalPath = it->get()->path;
Vishnu Naira02943f2023-06-03 13:44:46 -0700479 const bool unreachable =
480 it->get()->reachablilty == LayerSnapshot::Reachablilty::Unreachable;
481 const bool isClone = traversalPath.isClone();
482 const bool layerIsDestroyed =
483 destroyedLayerIds.find(traversalPath.id) != destroyedLayerIds.end();
484 const bool destroySnapshot = (unreachable && isClone) || layerIsDestroyed;
485
486 if (!destroySnapshot) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000487 it++;
488 continue;
489 }
490
Vishnu Naira02943f2023-06-03 13:44:46 -0700491 mPathToSnapshot.erase(traversalPath);
492
493 auto range = mIdToSnapshots.equal_range(traversalPath.id);
494 auto matchingSnapshot =
495 std::find_if(range.first, range.second, [&traversalPath](auto& snapshotWithId) {
496 return snapshotWithId.second->path == traversalPath;
497 });
498 mIdToSnapshots.erase(matchingSnapshot);
Vishnu Nair29354ec2023-03-28 18:51:28 -0700499 mNeedsTouchableRegionCrop.erase(traversalPath);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000500 mSnapshots.back()->globalZ = it->get()->globalZ;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000501 std::iter_swap(it, mSnapshots.end() - 1);
502 mSnapshots.erase(mSnapshots.end() - 1);
503 }
504}
505
506void LayerSnapshotBuilder::update(const Args& args) {
Vishnu Nair92990e22023-02-24 20:01:05 +0000507 for (auto& snapshot : mSnapshots) {
508 clearChanges(*snapshot);
509 }
510
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000511 if (tryFastUpdate(args)) {
512 return;
513 }
514 updateSnapshots(args);
515}
516
Vishnu Naircfb2d252023-01-19 04:44:02 +0000517const LayerSnapshot& LayerSnapshotBuilder::updateSnapshotsInHierarchy(
518 const Args& args, const LayerHierarchy& hierarchy,
Vishnu Naird1f74982023-06-15 20:16:51 -0700519 LayerHierarchy::TraversalPath& traversalPath, const LayerSnapshot& parentSnapshot,
520 int depth) {
Vishnu Nair606d9d02023-08-19 14:20:18 -0700521 LLOG_ALWAYS_FATAL_WITH_TRACE_IF(depth > 50,
522 "Cycle detected in LayerSnapshotBuilder. See "
523 "builder_stack_overflow_transactions.winscope");
Vishnu Naird1f74982023-06-15 20:16:51 -0700524
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000525 const RequestedLayerState* layer = hierarchy.getLayer();
Vishnu Naircfb2d252023-01-19 04:44:02 +0000526 LayerSnapshot* snapshot = getSnapshot(traversalPath);
527 const bool newSnapshot = snapshot == nullptr;
Vishnu Naira02943f2023-06-03 13:44:46 -0700528 uint32_t primaryDisplayRotationFlags = getPrimaryDisplayRotationFlags(args.displays);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000529 if (newSnapshot) {
Vishnu Nair92990e22023-02-24 20:01:05 +0000530 snapshot = createSnapshot(traversalPath, *layer, parentSnapshot);
Vishnu Naira02943f2023-06-03 13:44:46 -0700531 snapshot->merge(*layer, /*forceUpdate=*/true, /*displayChanges=*/true, args.forceFullDamage,
532 primaryDisplayRotationFlags);
533 snapshot->changes |= RequestedLayerState::Changes::Created;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000534 }
Vishnu Nair52d56fd2023-07-20 17:02:43 +0000535
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000536 if (traversalPath.isRelative()) {
537 bool parentIsRelative = traversalPath.variant == LayerHierarchy::Variant::Relative;
538 updateRelativeState(*snapshot, parentSnapshot, parentIsRelative, args);
539 } else {
540 if (traversalPath.isAttached()) {
541 resetRelativeState(*snapshot);
542 }
Vishnu Nair92990e22023-02-24 20:01:05 +0000543 updateSnapshot(*snapshot, args, *layer, parentSnapshot, traversalPath);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000544 }
545
Vishnu Nair0fd773f2024-08-05 21:16:15 +0000546 bool childHasValidFrameRate = false;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000547 for (auto& [childHierarchy, variant] : hierarchy.mChildren) {
548 LayerHierarchy::ScopedAddToTraversalPath addChildToPath(traversalPath,
549 childHierarchy->getLayer()->id,
550 variant);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000551 const LayerSnapshot& childSnapshot =
Vishnu Naird1f74982023-06-15 20:16:51 -0700552 updateSnapshotsInHierarchy(args, *childHierarchy, traversalPath, *snapshot,
553 depth + 1);
Vishnu Nair0fd773f2024-08-05 21:16:15 +0000554 updateFrameRateFromChildSnapshot(*snapshot, childSnapshot, *childHierarchy->getLayer(),
555 args, &childHasValidFrameRate);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000556 }
Vishnu Naird47bcee2023-02-24 18:08:51 +0000557
Vishnu Naircfb2d252023-01-19 04:44:02 +0000558 return *snapshot;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000559}
560
561LayerSnapshot* LayerSnapshotBuilder::getSnapshot(uint32_t layerId) const {
562 if (layerId == UNASSIGNED_LAYER_ID) {
563 return nullptr;
564 }
565 LayerHierarchy::TraversalPath path{.id = layerId};
566 return getSnapshot(path);
567}
568
569LayerSnapshot* LayerSnapshotBuilder::getSnapshot(const LayerHierarchy::TraversalPath& id) const {
Vishnu Naira02943f2023-06-03 13:44:46 -0700570 auto it = mPathToSnapshot.find(id);
571 return it == mPathToSnapshot.end() ? nullptr : it->second;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000572}
573
Vishnu Nair92990e22023-02-24 20:01:05 +0000574LayerSnapshot* LayerSnapshotBuilder::createSnapshot(const LayerHierarchy::TraversalPath& path,
575 const RequestedLayerState& layer,
576 const LayerSnapshot& parentSnapshot) {
577 mSnapshots.emplace_back(std::make_unique<LayerSnapshot>(layer, path));
Vishnu Naircfb2d252023-01-19 04:44:02 +0000578 LayerSnapshot* snapshot = mSnapshots.back().get();
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000579 snapshot->globalZ = static_cast<size_t>(mSnapshots.size()) - 1;
Vishnu Nair491827d2024-04-29 23:43:26 +0000580 if (path.isClone() && !LayerHierarchy::isMirror(path.variant)) {
Vishnu Nair92990e22023-02-24 20:01:05 +0000581 snapshot->mirrorRootPath = parentSnapshot.mirrorRootPath;
582 }
Vishnu Nair491827d2024-04-29 23:43:26 +0000583 snapshot->ignoreLocalTransform =
584 path.isClone() && path.variant == LayerHierarchy::Variant::Detached_Mirror;
Vishnu Naira02943f2023-06-03 13:44:46 -0700585 mPathToSnapshot[path] = snapshot;
586
587 mIdToSnapshots.emplace(path.id, snapshot);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000588 return snapshot;
589}
590
Vishnu Nairfccd6362023-02-24 23:39:53 +0000591bool LayerSnapshotBuilder::sortSnapshotsByZ(const Args& args) {
Vishnu Naird47bcee2023-02-24 18:08:51 +0000592 if (!mResortSnapshots && args.forceUpdate == ForceUpdateFlags::NONE &&
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000593 !args.layerLifecycleManager.getGlobalChanges().any(
Chavi Weingarten92c7d8c2024-01-19 23:25:45 +0000594 RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Visibility |
595 RequestedLayerState::Changes::Input)) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000596 // We are not force updating and there are no hierarchy or visibility changes. Avoid sorting
597 // the snapshots.
Vishnu Nairfccd6362023-02-24 23:39:53 +0000598 return false;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000599 }
Vishnu Naircfb2d252023-01-19 04:44:02 +0000600 mResortSnapshots = false;
601
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000602 size_t globalZ = 0;
603 args.root.traverseInZOrder(
604 [this, &globalZ](const LayerHierarchy&,
605 const LayerHierarchy::TraversalPath& traversalPath) -> bool {
606 LayerSnapshot* snapshot = getSnapshot(traversalPath);
607 if (!snapshot) {
Vishnu Naira02943f2023-06-03 13:44:46 -0700608 return true;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000609 }
610
Vishnu Naircfb2d252023-01-19 04:44:02 +0000611 if (snapshot->getIsVisible() || snapshot->hasInputInfo()) {
Vishnu Nair80a5a702023-02-11 01:21:51 +0000612 updateVisibility(*snapshot, snapshot->getIsVisible());
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000613 size_t oldZ = snapshot->globalZ;
614 size_t newZ = globalZ++;
615 snapshot->globalZ = newZ;
616 if (oldZ == newZ) {
617 return true;
618 }
619 mSnapshots[newZ]->globalZ = oldZ;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000620 LLOGV(snapshot->sequence, "Made visible z=%zu -> %zu %s", oldZ, newZ,
621 snapshot->getDebugString().c_str());
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000622 std::iter_swap(mSnapshots.begin() + static_cast<ssize_t>(oldZ),
623 mSnapshots.begin() + static_cast<ssize_t>(newZ));
624 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000625 return true;
626 });
Vishnu Naircfb2d252023-01-19 04:44:02 +0000627 mNumInterestingSnapshots = (int)globalZ;
Vishnu Nairfccd6362023-02-24 23:39:53 +0000628 bool hasUnreachableSnapshots = false;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000629 while (globalZ < mSnapshots.size()) {
630 mSnapshots[globalZ]->globalZ = globalZ;
Vishnu Nair80a5a702023-02-11 01:21:51 +0000631 /* mark unreachable snapshots as explicitly invisible */
632 updateVisibility(*mSnapshots[globalZ], false);
Vishnu Naira02943f2023-06-03 13:44:46 -0700633 if (mSnapshots[globalZ]->reachablilty == LayerSnapshot::Reachablilty::Unreachable) {
Vishnu Nairfccd6362023-02-24 23:39:53 +0000634 hasUnreachableSnapshots = true;
635 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000636 globalZ++;
637 }
Vishnu Nairfccd6362023-02-24 23:39:53 +0000638 return hasUnreachableSnapshots;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000639}
640
641void LayerSnapshotBuilder::updateRelativeState(LayerSnapshot& snapshot,
642 const LayerSnapshot& parentSnapshot,
643 bool parentIsRelative, const Args& args) {
644 if (parentIsRelative) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000645 snapshot.isHiddenByPolicyFromRelativeParent =
646 parentSnapshot.isHiddenByPolicyFromParent || parentSnapshot.invalidTransform;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000647 if (args.includeMetadata) {
648 snapshot.relativeLayerMetadata = parentSnapshot.layerMetadata;
649 }
650 } else {
651 snapshot.isHiddenByPolicyFromRelativeParent =
652 parentSnapshot.isHiddenByPolicyFromRelativeParent;
653 if (args.includeMetadata) {
654 snapshot.relativeLayerMetadata = parentSnapshot.relativeLayerMetadata;
655 }
656 }
Vishnu Naira02943f2023-06-03 13:44:46 -0700657 if (snapshot.reachablilty == LayerSnapshot::Reachablilty::Unreachable) {
658 snapshot.reachablilty = LayerSnapshot::Reachablilty::ReachableByRelativeParent;
659 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000660}
661
Vishnu Nair0fd773f2024-08-05 21:16:15 +0000662void LayerSnapshotBuilder::updateFrameRateFromChildSnapshot(
663 LayerSnapshot& snapshot, const LayerSnapshot& childSnapshot,
664 const RequestedLayerState& /* requestedChildState */, const Args& args,
665 bool* outChildHasValidFrameRate) {
Vishnu Nair42b918e2023-07-18 20:05:29 +0000666 if (args.forceUpdate == ForceUpdateFlags::NONE &&
Vishnu Nair52d56fd2023-07-20 17:02:43 +0000667 !args.layerLifecycleManager.getGlobalChanges().any(
668 RequestedLayerState::Changes::Hierarchy) &&
669 !childSnapshot.changes.any(RequestedLayerState::Changes::FrameRate) &&
670 !snapshot.changes.any(RequestedLayerState::Changes::FrameRate)) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000671 return;
672 }
Vishnu Naircfb2d252023-01-19 04:44:02 +0000673
Vishnu Nair3fbe3262023-09-29 17:07:00 -0700674 using FrameRateCompatibility = scheduler::FrameRateCompatibility;
Vishnu Nair0fd773f2024-08-05 21:16:15 +0000675 if (snapshot.inheritedFrameRate.isValid() || *outChildHasValidFrameRate) {
Vishnu Nair42b918e2023-07-18 20:05:29 +0000676 // we already have a valid framerate.
677 return;
678 }
Vishnu Naircfb2d252023-01-19 04:44:02 +0000679
Vishnu Nair42b918e2023-07-18 20:05:29 +0000680 // We return whether this layer or its children has a vote. We ignore ExactOrMultiple votes
681 // for the same reason we are allowing touch boost for those layers. See
682 // RefreshRateSelector::rankFrameRates for details.
Rachel Leece6e0042023-06-27 11:22:54 -0700683 const auto layerVotedWithDefaultCompatibility = childSnapshot.frameRate.vote.rate.isValid() &&
684 childSnapshot.frameRate.vote.type == FrameRateCompatibility::Default;
Vishnu Nair42b918e2023-07-18 20:05:29 +0000685 const auto layerVotedWithNoVote =
Rachel Leece6e0042023-06-27 11:22:54 -0700686 childSnapshot.frameRate.vote.type == FrameRateCompatibility::NoVote;
687 const auto layerVotedWithCategory =
688 childSnapshot.frameRate.category != FrameRateCategory::Default;
689 const auto layerVotedWithExactCompatibility = childSnapshot.frameRate.vote.rate.isValid() &&
690 childSnapshot.frameRate.vote.type == FrameRateCompatibility::Exact;
Vishnu Nair42b918e2023-07-18 20:05:29 +0000691
Vishnu Nair0fd773f2024-08-05 21:16:15 +0000692 *outChildHasValidFrameRate |= layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
Rachel Leece6e0042023-06-27 11:22:54 -0700693 layerVotedWithCategory || layerVotedWithExactCompatibility;
Vishnu Nair42b918e2023-07-18 20:05:29 +0000694
695 // If we don't have a valid frame rate, but the children do, we set this
696 // layer as NoVote to allow the children to control the refresh rate
Vishnu Nair0fd773f2024-08-05 21:16:15 +0000697 static const auto noVote =
698 scheduler::LayerInfo::FrameRate(Fps(), FrameRateCompatibility::NoVote);
699 if (*outChildHasValidFrameRate) {
700 snapshot.frameRate = noVote;
701 snapshot.changes |= RequestedLayerState::Changes::FrameRate;
702 } else if (snapshot.frameRate != snapshot.inheritedFrameRate) {
703 snapshot.frameRate = snapshot.inheritedFrameRate;
Vishnu Nair42b918e2023-07-18 20:05:29 +0000704 snapshot.changes |= RequestedLayerState::Changes::FrameRate;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000705 }
706}
707
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000708void LayerSnapshotBuilder::resetRelativeState(LayerSnapshot& snapshot) {
709 snapshot.isHiddenByPolicyFromRelativeParent = false;
710 snapshot.relativeLayerMetadata.mMap.clear();
711}
712
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000713void LayerSnapshotBuilder::updateSnapshot(LayerSnapshot& snapshot, const Args& args,
714 const RequestedLayerState& requested,
715 const LayerSnapshot& parentSnapshot,
Vishnu Nair92990e22023-02-24 20:01:05 +0000716 const LayerHierarchy::TraversalPath& path) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000717 // Always update flags and visibility
718 ftl::Flags<RequestedLayerState::Changes> parentChanges = parentSnapshot.changes &
719 (RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Geometry |
720 RequestedLayerState::Changes::Visibility | RequestedLayerState::Changes::Metadata |
Vishnu Nairf13c8982023-12-02 11:26:09 -0800721 RequestedLayerState::Changes::AffectsChildren | RequestedLayerState::Changes::Input |
Vishnu Naira02943f2023-06-03 13:44:46 -0700722 RequestedLayerState::Changes::FrameRate | RequestedLayerState::Changes::GameMode);
723 snapshot.changes |= parentChanges;
724 if (args.displayChanges) snapshot.changes |= RequestedLayerState::Changes::Geometry;
725 snapshot.reachablilty = LayerSnapshot::Reachablilty::Reachable;
726 snapshot.clientChanges |= (parentSnapshot.clientChanges & layer_state_t::AFFECTS_CHILDREN);
Vishnu Naira4b3a102024-11-05 05:26:38 +0000727 // mark the content as dirty if the parent state changes can dirty the child's content (for
728 // example alpha)
729 snapshot.contentDirty |= (snapshot.clientChanges & layer_state_t::CONTENT_DIRTY) != 0;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000730 snapshot.isHiddenByPolicyFromParent = parentSnapshot.isHiddenByPolicyFromParent ||
Vishnu Nair3af0ec02023-02-10 04:13:48 +0000731 parentSnapshot.invalidTransform || requested.isHiddenByPolicy() ||
732 (args.excludeLayerIds.find(path.id) != args.excludeLayerIds.end());
Vishnu Nair92990e22023-02-24 20:01:05 +0000733 const bool forceUpdate = args.forceUpdate == ForceUpdateFlags::ALL ||
Vishnu Naira02943f2023-06-03 13:44:46 -0700734 snapshot.clientChanges & layer_state_t::eReparent ||
Vishnu Nair92990e22023-02-24 20:01:05 +0000735 snapshot.changes.any(RequestedLayerState::Changes::Visibility |
736 RequestedLayerState::Changes::Created);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000737
Vishnu Naira02943f2023-06-03 13:44:46 -0700738 if (forceUpdate || snapshot.clientChanges & layer_state_t::eLayerStackChanged) {
739 // If root layer, use the layer stack otherwise get the parent's layer stack.
740 snapshot.outputFilter.layerStack =
741 parentSnapshot.path == LayerHierarchy::TraversalPath::ROOT
742 ? requested.layerStack
743 : parentSnapshot.outputFilter.layerStack;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000744 }
745
Chavi Weingartenb74093a2023-10-11 20:29:59 +0000746 if (forceUpdate || snapshot.clientChanges & layer_state_t::eTrustedOverlayChanged) {
Vishnu Nair9e0017e2024-05-22 19:02:44 +0000747 switch (requested.trustedOverlay) {
748 case gui::TrustedOverlay::UNSET:
749 snapshot.trustedOverlay = parentSnapshot.trustedOverlay;
750 break;
751 case gui::TrustedOverlay::DISABLED:
752 snapshot.trustedOverlay = FlagManager::getInstance().override_trusted_overlay()
753 ? requested.trustedOverlay
754 : parentSnapshot.trustedOverlay;
755 break;
756 case gui::TrustedOverlay::ENABLED:
757 snapshot.trustedOverlay = requested.trustedOverlay;
758 break;
759 }
Chavi Weingartenb74093a2023-10-11 20:29:59 +0000760 }
761
Vishnu Nair92990e22023-02-24 20:01:05 +0000762 if (snapshot.isHiddenByPolicyFromParent &&
763 !snapshot.changes.test(RequestedLayerState::Changes::Created)) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000764 if (forceUpdate ||
Vishnu Naira02943f2023-06-03 13:44:46 -0700765 snapshot.changes.any(RequestedLayerState::Changes::Geometry |
Vishnu Nair494a2e42023-11-10 17:21:19 -0800766 RequestedLayerState::Changes::BufferSize |
Vishnu Naircfb2d252023-01-19 04:44:02 +0000767 RequestedLayerState::Changes::Input)) {
768 updateInput(snapshot, requested, parentSnapshot, path, args);
769 }
Nergi Rahardi0dfc0962024-05-23 06:57:36 +0000770 if (forceUpdate ||
771 (args.includeMetadata &&
Vishnu Nair39a74a92024-07-29 19:01:50 +0000772 snapshot.changes.any(RequestedLayerState::Changes::Metadata |
773 RequestedLayerState::Changes::Geometry))) {
Nergi Rahardi0dfc0962024-05-23 06:57:36 +0000774 updateMetadataAndGameMode(snapshot, requested, args, parentSnapshot);
775 }
Vishnu Naircfb2d252023-01-19 04:44:02 +0000776 return;
777 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000778
Vishnu Naira02943f2023-06-03 13:44:46 -0700779 if (forceUpdate || snapshot.changes.any(RequestedLayerState::Changes::Mirror)) {
780 // Display mirrors are always placed in a VirtualDisplay so we never want to capture layers
781 // marked as skip capture
782 snapshot.handleSkipScreenshotFlag = parentSnapshot.handleSkipScreenshotFlag ||
783 (requested.layerStackToMirror != ui::INVALID_LAYER_STACK);
784 }
785
786 if (forceUpdate || snapshot.clientChanges & layer_state_t::eAlphaChanged) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000787 snapshot.color.a = parentSnapshot.color.a * requested.color.a;
788 snapshot.alpha = snapshot.color.a;
Vishnu Nair29354ec2023-03-28 18:51:28 -0700789 snapshot.inputInfo.alpha = snapshot.color.a;
Vishnu Naira02943f2023-06-03 13:44:46 -0700790 }
Vishnu Nair29354ec2023-03-28 18:51:28 -0700791
Vishnu Naira02943f2023-06-03 13:44:46 -0700792 if (forceUpdate || snapshot.clientChanges & layer_state_t::eFlagsChanged) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000793 snapshot.isSecure =
794 parentSnapshot.isSecure || (requested.flags & layer_state_t::eLayerSecure);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000795 snapshot.outputFilter.toInternalDisplay = parentSnapshot.outputFilter.toInternalDisplay ||
796 (requested.flags & layer_state_t::eLayerSkipScreenshot);
Vishnu Naira02943f2023-06-03 13:44:46 -0700797 }
798
Vishnu Naira02943f2023-06-03 13:44:46 -0700799 if (forceUpdate || snapshot.clientChanges & layer_state_t::eStretchChanged) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000800 snapshot.stretchEffect = (requested.stretchEffect.hasEffect())
801 ? requested.stretchEffect
802 : parentSnapshot.stretchEffect;
Vishnu Naira02943f2023-06-03 13:44:46 -0700803 }
804
Marzia Favarodcc9d9b2024-01-10 10:17:00 +0000805 if (forceUpdate ||
806 (snapshot.clientChanges | parentSnapshot.clientChanges) &
807 layer_state_t::eEdgeExtensionChanged) {
808 if (requested.edgeExtensionParameters.extendLeft ||
809 requested.edgeExtensionParameters.extendRight ||
810 requested.edgeExtensionParameters.extendTop ||
811 requested.edgeExtensionParameters.extendBottom) {
812 // This is the root layer to which the extension is applied
813 snapshot.edgeExtensionEffect =
814 EdgeExtensionEffect(requested.edgeExtensionParameters.extendLeft,
815 requested.edgeExtensionParameters.extendRight,
816 requested.edgeExtensionParameters.extendTop,
817 requested.edgeExtensionParameters.extendBottom);
818 } else if (parentSnapshot.clientChanges & layer_state_t::eEdgeExtensionChanged) {
819 // Extension is inherited
820 snapshot.edgeExtensionEffect = parentSnapshot.edgeExtensionEffect;
821 } else {
822 // There is no edge extension
823 snapshot.edgeExtensionEffect.reset();
824 }
825 if (snapshot.edgeExtensionEffect.hasEffect()) {
826 snapshot.clientChanges |= layer_state_t::eEdgeExtensionChanged;
827 snapshot.changes |= RequestedLayerState::Changes::Geometry;
828 }
829 }
830
Vishnu Naira02943f2023-06-03 13:44:46 -0700831 if (forceUpdate || snapshot.clientChanges & layer_state_t::eColorTransformChanged) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000832 if (!parentSnapshot.colorTransformIsIdentity) {
833 snapshot.colorTransform = parentSnapshot.colorTransform * requested.colorTransform;
834 snapshot.colorTransformIsIdentity = false;
835 } else {
836 snapshot.colorTransform = requested.colorTransform;
837 snapshot.colorTransformIsIdentity = !requested.hasColorTransform;
838 }
Vishnu Naira02943f2023-06-03 13:44:46 -0700839 }
840
Vishnu Nair39a74a92024-07-29 19:01:50 +0000841 if (forceUpdate ||
842 snapshot.changes.any(RequestedLayerState::Changes::Metadata |
843 RequestedLayerState::Changes::Hierarchy)) {
Nergi Rahardi0dfc0962024-05-23 06:57:36 +0000844 updateMetadataAndGameMode(snapshot, requested, args, parentSnapshot);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000845 }
846
Vishnu Naira02943f2023-06-03 13:44:46 -0700847 if (forceUpdate || snapshot.clientChanges & layer_state_t::eFixedTransformHintChanged ||
Vishnu Nairb76d99a2023-03-19 18:22:31 -0700848 args.displayChanges) {
849 snapshot.fixedTransformHint = requested.fixedTransformHint != ui::Transform::ROT_INVALID
850 ? requested.fixedTransformHint
851 : parentSnapshot.fixedTransformHint;
852
853 if (snapshot.fixedTransformHint != ui::Transform::ROT_INVALID) {
854 snapshot.transformHint = snapshot.fixedTransformHint;
855 } else {
856 const auto display = args.displays.get(snapshot.outputFilter.layerStack);
857 snapshot.transformHint = display.has_value()
858 ? std::make_optional<>(display->get().transformHint)
859 : std::nullopt;
860 }
861 }
862
Vishnu Nair42b918e2023-07-18 20:05:29 +0000863 if (forceUpdate ||
Vishnu Nair52d56fd2023-07-20 17:02:43 +0000864 args.layerLifecycleManager.getGlobalChanges().any(
865 RequestedLayerState::Changes::Hierarchy) ||
Vishnu Nair42b918e2023-07-18 20:05:29 +0000866 snapshot.changes.any(RequestedLayerState::Changes::FrameRate |
867 RequestedLayerState::Changes::Hierarchy)) {
Rachel Leea021bb02023-11-20 21:51:09 -0800868 const bool shouldOverrideChildren = parentSnapshot.frameRateSelectionStrategy ==
Rachel Lee58cc90d2023-09-05 18:50:20 -0700869 scheduler::LayerInfo::FrameRateSelectionStrategy::OverrideChildren;
Rachel Leea021bb02023-11-20 21:51:09 -0800870 const bool propagationAllowed = parentSnapshot.frameRateSelectionStrategy !=
Rachel Lee70f7b692023-11-22 11:24:02 -0800871 scheduler::LayerInfo::FrameRateSelectionStrategy::Self;
Rachel Leea021bb02023-11-20 21:51:09 -0800872 if ((!requested.requestedFrameRate.isValid() && propagationAllowed) ||
873 shouldOverrideChildren) {
Vishnu Nair30515cb2023-10-19 21:54:08 -0700874 snapshot.inheritedFrameRate = parentSnapshot.inheritedFrameRate;
875 } else {
876 snapshot.inheritedFrameRate = requested.requestedFrameRate;
877 }
878 // Set the framerate as the inherited frame rate and allow children to override it if
879 // needed.
880 snapshot.frameRate = snapshot.inheritedFrameRate;
Vishnu Nair52d56fd2023-07-20 17:02:43 +0000881 snapshot.changes |= RequestedLayerState::Changes::FrameRate;
Vishnu Naird47bcee2023-02-24 18:08:51 +0000882 }
883
Rachel Lee58cc90d2023-09-05 18:50:20 -0700884 if (forceUpdate || snapshot.clientChanges & layer_state_t::eFrameRateSelectionStrategyChanged) {
Rachel Leea021bb02023-11-20 21:51:09 -0800885 if (parentSnapshot.frameRateSelectionStrategy ==
886 scheduler::LayerInfo::FrameRateSelectionStrategy::OverrideChildren) {
887 snapshot.frameRateSelectionStrategy =
888 scheduler::LayerInfo::FrameRateSelectionStrategy::OverrideChildren;
889 } else {
890 const auto strategy = scheduler::LayerInfo::convertFrameRateSelectionStrategy(
891 requested.frameRateSelectionStrategy);
892 snapshot.frameRateSelectionStrategy = strategy;
893 }
Rachel Lee58cc90d2023-09-05 18:50:20 -0700894 }
895
Vishnu Nair3d8565a2023-06-30 07:23:24 +0000896 if (forceUpdate || snapshot.clientChanges & layer_state_t::eFrameRateSelectionPriority) {
897 snapshot.frameRateSelectionPriority =
898 (requested.frameRateSelectionPriority == Layer::PRIORITY_UNSET)
899 ? parentSnapshot.frameRateSelectionPriority
900 : requested.frameRateSelectionPriority;
901 }
902
Vishnu Naira02943f2023-06-03 13:44:46 -0700903 if (forceUpdate ||
904 snapshot.clientChanges &
905 (layer_state_t::eBackgroundBlurRadiusChanged | layer_state_t::eBlurRegionsChanged |
906 layer_state_t::eAlphaChanged)) {
Vishnu Nair80a5a702023-02-11 01:21:51 +0000907 snapshot.backgroundBlurRadius = args.supportsBlur
908 ? static_cast<int>(parentSnapshot.color.a * (float)requested.backgroundBlurRadius)
909 : 0;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000910 snapshot.blurRegions = requested.blurRegions;
Vishnu Nair80a5a702023-02-11 01:21:51 +0000911 for (auto& region : snapshot.blurRegions) {
912 region.alpha = region.alpha * snapshot.color.a;
913 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000914 }
915
Vishnu Naira02943f2023-06-03 13:44:46 -0700916 if (forceUpdate || snapshot.changes.any(RequestedLayerState::Changes::Geometry)) {
917 uint32_t primaryDisplayRotationFlags = getPrimaryDisplayRotationFlags(args.displays);
Vishnu Nairb76d99a2023-03-19 18:22:31 -0700918 updateLayerBounds(snapshot, requested, parentSnapshot, primaryDisplayRotationFlags);
Vishnu Naira02943f2023-06-03 13:44:46 -0700919 }
920
Marzia Favarodcc9d9b2024-01-10 10:17:00 +0000921 if (snapshot.edgeExtensionEffect.hasEffect()) {
922 updateBoundsForEdgeExtension(snapshot);
923 }
924
Vishnu Naira02943f2023-06-03 13:44:46 -0700925 if (forceUpdate || snapshot.clientChanges & layer_state_t::eCornerRadiusChanged ||
Vishnu Nair0808ae62023-08-07 21:42:42 -0700926 snapshot.changes.any(RequestedLayerState::Changes::Geometry |
927 RequestedLayerState::Changes::BufferUsageFlags)) {
928 updateRoundedCorner(snapshot, requested, parentSnapshot, args);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000929 }
930
Vishnu Naira02943f2023-06-03 13:44:46 -0700931 if (forceUpdate || snapshot.clientChanges & layer_state_t::eShadowRadiusChanged ||
932 snapshot.changes.any(RequestedLayerState::Changes::Geometry)) {
933 updateShadows(snapshot, requested, args.globalShadowSettings);
934 }
935
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000936 if (forceUpdate ||
Vishnu Naira02943f2023-06-03 13:44:46 -0700937 snapshot.changes.any(RequestedLayerState::Changes::Geometry |
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000938 RequestedLayerState::Changes::Input)) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000939 updateInput(snapshot, requested, parentSnapshot, path, args);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000940 }
941
942 // computed snapshot properties
Marzia Favarodcc9d9b2024-01-10 10:17:00 +0000943 snapshot.forceClientComposition = snapshot.shadowSettings.length > 0 ||
944 snapshot.stretchEffect.hasEffect() || snapshot.edgeExtensionEffect.hasEffect();
Vishnu Nairc765c6c2023-02-23 00:08:01 +0000945 snapshot.contentOpaque = snapshot.isContentOpaque();
946 snapshot.isOpaque = snapshot.contentOpaque && !snapshot.roundedCorner.hasRoundedCorners() &&
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000947 snapshot.color.a == 1.f;
948 snapshot.blendMode = getBlendMode(snapshot, requested);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000949 LLOGV(snapshot.sequence,
Vishnu Nair92990e22023-02-24 20:01:05 +0000950 "%supdated %s changes:%s parent:%s requested:%s requested:%s from parent %s",
951 args.forceUpdate == ForceUpdateFlags::ALL ? "Force " : "",
952 snapshot.getDebugString().c_str(), snapshot.changes.string().c_str(),
953 parentSnapshot.changes.string().c_str(), requested.changes.string().c_str(),
954 std::to_string(requested.what).c_str(), parentSnapshot.getDebugString().c_str());
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000955}
956
957void LayerSnapshotBuilder::updateRoundedCorner(LayerSnapshot& snapshot,
958 const RequestedLayerState& requested,
Vishnu Nair0808ae62023-08-07 21:42:42 -0700959 const LayerSnapshot& parentSnapshot,
960 const Args& args) {
961 if (args.skipRoundCornersWhenProtected && requested.isProtected()) {
962 snapshot.roundedCorner = RoundedCornerState();
963 return;
964 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000965 snapshot.roundedCorner = RoundedCornerState();
966 RoundedCornerState parentRoundedCorner;
967 if (parentSnapshot.roundedCorner.hasRoundedCorners()) {
968 parentRoundedCorner = parentSnapshot.roundedCorner;
969 ui::Transform t = snapshot.localTransform.inverse();
970 parentRoundedCorner.cropRect = t.transform(parentRoundedCorner.cropRect);
971 parentRoundedCorner.radius.x *= t.getScaleX();
972 parentRoundedCorner.radius.y *= t.getScaleY();
973 }
974
Vishnu Naira9123c82024-10-03 03:56:44 +0000975 FloatRect layerCropRect = snapshot.croppedBufferSize;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000976 const vec2 radius(requested.cornerRadius, requested.cornerRadius);
977 RoundedCornerState layerSettings(layerCropRect, radius);
978 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && !layerCropRect.isEmpty();
979 const bool parentRoundedCornerValid = parentRoundedCorner.hasRoundedCorners();
980 if (layerSettingsValid && parentRoundedCornerValid) {
981 // If the parent and the layer have rounded corner settings, use the parent settings if
982 // the parent crop is entirely inside the layer crop. This has limitations and cause
983 // rendering artifacts. See b/200300845 for correct fix.
984 if (parentRoundedCorner.cropRect.left > layerCropRect.left &&
985 parentRoundedCorner.cropRect.top > layerCropRect.top &&
986 parentRoundedCorner.cropRect.right < layerCropRect.right &&
987 parentRoundedCorner.cropRect.bottom < layerCropRect.bottom) {
988 snapshot.roundedCorner = parentRoundedCorner;
989 } else {
990 snapshot.roundedCorner = layerSettings;
991 }
992 } else if (layerSettingsValid) {
993 snapshot.roundedCorner = layerSettings;
994 } else if (parentRoundedCornerValid) {
995 snapshot.roundedCorner = parentRoundedCorner;
996 }
997}
998
Marzia Favarodcc9d9b2024-01-10 10:17:00 +0000999/**
1000 * According to the edges that we are requested to extend, we increase the bounds to the maximum
1001 * extension allowed by the crop (parent crop + requested crop). The animation that called
1002 * Transition#setEdgeExtensionEffect is in charge of setting the requested crop.
1003 * @param snapshot
1004 */
1005void LayerSnapshotBuilder::updateBoundsForEdgeExtension(LayerSnapshot& snapshot) {
1006 EdgeExtensionEffect& effect = snapshot.edgeExtensionEffect;
1007
1008 if (effect.extendsEdge(LEFT)) {
1009 snapshot.geomLayerBounds.left = snapshot.geomLayerCrop.left;
1010 }
1011 if (effect.extendsEdge(RIGHT)) {
1012 snapshot.geomLayerBounds.right = snapshot.geomLayerCrop.right;
1013 }
1014 if (effect.extendsEdge(TOP)) {
1015 snapshot.geomLayerBounds.top = snapshot.geomLayerCrop.top;
1016 }
1017 if (effect.extendsEdge(BOTTOM)) {
1018 snapshot.geomLayerBounds.bottom = snapshot.geomLayerCrop.bottom;
1019 }
1020
1021 snapshot.transformedBounds = snapshot.geomLayerTransform.transform(snapshot.geomLayerBounds);
1022}
1023
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001024void LayerSnapshotBuilder::updateLayerBounds(LayerSnapshot& snapshot,
1025 const RequestedLayerState& requested,
1026 const LayerSnapshot& parentSnapshot,
Vishnu Nairb76d99a2023-03-19 18:22:31 -07001027 uint32_t primaryDisplayRotationFlags) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001028 snapshot.geomLayerTransform = parentSnapshot.geomLayerTransform * snapshot.localTransform;
Vishnu Naircfb2d252023-01-19 04:44:02 +00001029 const bool transformWasInvalid = snapshot.invalidTransform;
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001030 snapshot.invalidTransform = !LayerSnapshot::isTransformValid(snapshot.geomLayerTransform);
1031 if (snapshot.invalidTransform) {
Vishnu Naircfb2d252023-01-19 04:44:02 +00001032 auto& t = snapshot.geomLayerTransform;
1033 auto& requestedT = requested.requestedTransform;
1034 std::string transformDebug =
1035 base::StringPrintf(" transform={%f,%f,%f,%f} requestedTransform={%f,%f,%f,%f}",
1036 t.dsdx(), t.dsdy(), t.dtdx(), t.dtdy(), requestedT.dsdx(),
1037 requestedT.dsdy(), requestedT.dtdx(), requestedT.dtdy());
1038 std::string bufferDebug;
1039 if (requested.externalTexture) {
Vishnu Nairb76d99a2023-03-19 18:22:31 -07001040 auto unRotBuffer = requested.getUnrotatedBufferSize(primaryDisplayRotationFlags);
Vishnu Naircfb2d252023-01-19 04:44:02 +00001041 auto& destFrame = requested.destinationFrame;
1042 bufferDebug = base::StringPrintf(" buffer={%d,%d} displayRot=%d"
1043 " destFrame={%d,%d,%d,%d} unRotBuffer={%d,%d}",
1044 requested.externalTexture->getWidth(),
1045 requested.externalTexture->getHeight(),
Vishnu Nairb76d99a2023-03-19 18:22:31 -07001046 primaryDisplayRotationFlags, destFrame.left,
1047 destFrame.top, destFrame.right, destFrame.bottom,
Vishnu Naircfb2d252023-01-19 04:44:02 +00001048 unRotBuffer.getHeight(), unRotBuffer.getWidth());
1049 }
1050 ALOGW("Resetting transform for %s because it is invalid.%s%s",
1051 snapshot.getDebugString().c_str(), transformDebug.c_str(), bufferDebug.c_str());
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001052 snapshot.geomLayerTransform.reset();
1053 }
Vishnu Naircfb2d252023-01-19 04:44:02 +00001054 if (transformWasInvalid != snapshot.invalidTransform) {
1055 // If transform is invalid, the layer will be hidden.
1056 mResortSnapshots = true;
1057 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001058 snapshot.geomInverseLayerTransform = snapshot.geomLayerTransform.inverse();
1059
1060 FloatRect parentBounds = parentSnapshot.geomLayerBounds;
1061 parentBounds = snapshot.localTransform.inverse().transform(parentBounds);
1062 snapshot.geomLayerBounds =
Marzia Favarodcc9d9b2024-01-10 10:17:00 +00001063 requested.externalTexture ? snapshot.bufferSize.toFloatRect() : parentBounds;
1064 snapshot.geomLayerCrop = parentBounds;
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001065 if (!requested.crop.isEmpty()) {
Vishnu Naira9123c82024-10-03 03:56:44 +00001066 snapshot.geomLayerCrop = snapshot.geomLayerCrop.intersect(requested.crop);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001067 }
Marzia Favarodcc9d9b2024-01-10 10:17:00 +00001068 snapshot.geomLayerBounds = snapshot.geomLayerBounds.intersect(snapshot.geomLayerCrop);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001069 snapshot.transformedBounds = snapshot.geomLayerTransform.transform(snapshot.geomLayerBounds);
Vishnu Naircfb2d252023-01-19 04:44:02 +00001070 const Rect geomLayerBoundsWithoutTransparentRegion =
1071 RequestedLayerState::reduce(Rect(snapshot.geomLayerBounds),
1072 requested.transparentRegion);
1073 snapshot.transformedBoundsWithoutTransparentRegion =
1074 snapshot.geomLayerTransform.transform(geomLayerBoundsWithoutTransparentRegion);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001075 snapshot.parentTransform = parentSnapshot.geomLayerTransform;
1076
Vishnu Naircfb2d252023-01-19 04:44:02 +00001077 if (requested.potentialCursor) {
Vishnu Naira9123c82024-10-03 03:56:44 +00001078 // Subtract the transparent region and snap to the bounds
1079 const Rect bounds = RequestedLayerState::reduce(Rect(snapshot.croppedBufferSize),
1080 requested.transparentRegion);
Vishnu Naircfb2d252023-01-19 04:44:02 +00001081 snapshot.cursorFrame = snapshot.geomLayerTransform.transform(bounds);
1082 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001083}
1084
Vishnu Naira02943f2023-06-03 13:44:46 -07001085void LayerSnapshotBuilder::updateShadows(LayerSnapshot& snapshot, const RequestedLayerState&,
Vishnu Naird9e4f462023-10-06 04:05:45 +00001086 const ShadowSettings& globalShadowSettings) {
1087 if (snapshot.shadowSettings.length > 0.f) {
1088 snapshot.shadowSettings.ambientColor = globalShadowSettings.ambientColor;
1089 snapshot.shadowSettings.spotColor = globalShadowSettings.spotColor;
1090 snapshot.shadowSettings.lightPos = globalShadowSettings.lightPos;
1091 snapshot.shadowSettings.lightRadius = globalShadowSettings.lightRadius;
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001092
1093 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
1094 // it if transparent regions are present. This may not be necessary since shadows are
1095 // typically cast by layers without transparent regions.
1096 snapshot.shadowSettings.boundaries = snapshot.geomLayerBounds;
1097
1098 // If the casting layer is translucent, we need to fill in the shadow underneath the
1099 // layer. Otherwise the generated shadow will only be shown around the casting layer.
1100 snapshot.shadowSettings.casterIsTranslucent =
1101 !snapshot.isContentOpaque() || (snapshot.alpha < 1.0f);
1102 snapshot.shadowSettings.ambientColor *= snapshot.alpha;
1103 snapshot.shadowSettings.spotColor *= snapshot.alpha;
1104 }
1105}
1106
1107void LayerSnapshotBuilder::updateInput(LayerSnapshot& snapshot,
1108 const RequestedLayerState& requested,
1109 const LayerSnapshot& parentSnapshot,
Vishnu Naircfb2d252023-01-19 04:44:02 +00001110 const LayerHierarchy::TraversalPath& path,
1111 const Args& args) {
Prabir Pradhancf359192024-03-20 00:42:57 +00001112 using InputConfig = gui::WindowInfo::InputConfig;
1113
Vishnu Naircfb2d252023-01-19 04:44:02 +00001114 if (requested.windowInfoHandle) {
1115 snapshot.inputInfo = *requested.windowInfoHandle->getInfo();
1116 } else {
1117 snapshot.inputInfo = {};
Vishnu Nair40d02282023-02-28 21:11:40 +00001118 // b/271132344 revisit this and see if we can always use the layers uid/pid
1119 snapshot.inputInfo.name = requested.name;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00001120 snapshot.inputInfo.ownerUid = gui::Uid{requested.ownerUid};
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00001121 snapshot.inputInfo.ownerPid = gui::Pid{requested.ownerPid};
Vishnu Naircfb2d252023-01-19 04:44:02 +00001122 }
Vishnu Nair29354ec2023-03-28 18:51:28 -07001123 snapshot.touchCropId = requested.touchCropId;
Vishnu Naircfb2d252023-01-19 04:44:02 +00001124
Vishnu Nair93b8b792023-02-27 19:40:24 +00001125 snapshot.inputInfo.id = static_cast<int32_t>(snapshot.uniqueSequence);
Linnan Li13bf76a2024-05-05 19:18:02 +08001126 snapshot.inputInfo.displayId =
1127 ui::LogicalDisplayId{static_cast<int32_t>(snapshot.outputFilter.layerStack.id)};
Vishnu Nairf13c8982023-12-02 11:26:09 -08001128 snapshot.inputInfo.touchOcclusionMode = requested.hasInputInfo()
1129 ? requested.windowInfoHandle->getInfo()->touchOcclusionMode
1130 : parentSnapshot.inputInfo.touchOcclusionMode;
Vishnu Nair59a6be32024-01-29 10:26:21 -08001131 snapshot.inputInfo.canOccludePresentation = parentSnapshot.inputInfo.canOccludePresentation ||
1132 (requested.flags & layer_state_t::eCanOccludePresentation);
Vishnu Nairf13c8982023-12-02 11:26:09 -08001133 if (requested.dropInputMode == gui::DropInputMode::ALL ||
1134 parentSnapshot.dropInputMode == gui::DropInputMode::ALL) {
1135 snapshot.dropInputMode = gui::DropInputMode::ALL;
1136 } else if (requested.dropInputMode == gui::DropInputMode::OBSCURED ||
1137 parentSnapshot.dropInputMode == gui::DropInputMode::OBSCURED) {
1138 snapshot.dropInputMode = gui::DropInputMode::OBSCURED;
1139 } else {
1140 snapshot.dropInputMode = gui::DropInputMode::NONE;
1141 }
1142
Prabir Pradhancf359192024-03-20 00:42:57 +00001143 if (snapshot.isSecure ||
Arpit Singh490ccc92024-04-30 14:26:21 +00001144 parentSnapshot.inputInfo.inputConfig.test(InputConfig::SENSITIVE_FOR_PRIVACY)) {
1145 snapshot.inputInfo.inputConfig |= InputConfig::SENSITIVE_FOR_PRIVACY;
Prabir Pradhancf359192024-03-20 00:42:57 +00001146 }
1147
Vishnu Nair29354ec2023-03-28 18:51:28 -07001148 updateVisibility(snapshot, snapshot.isVisible);
Wenhui Yangab89d812024-09-11 23:21:38 +00001149 if (!requested.needsInputInfo()) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001150 return;
1151 }
1152
Vishnu Naircfb2d252023-01-19 04:44:02 +00001153 static frontend::DisplayInfo sDefaultInfo = {.isSecure = false};
1154 const std::optional<frontend::DisplayInfo> displayInfoOpt =
1155 args.displays.get(snapshot.outputFilter.layerStack);
1156 bool noValidDisplay = !displayInfoOpt.has_value();
1157 auto displayInfo = displayInfoOpt.value_or(sDefaultInfo);
1158
Wenhui Yangab89d812024-09-11 23:21:38 +00001159 if (!requested.hasInputInfo()) {
Prabir Pradhancf359192024-03-20 00:42:57 +00001160 snapshot.inputInfo.inputConfig = InputConfig::NO_INPUT_CHANNEL;
Vishnu Naircfb2d252023-01-19 04:44:02 +00001161 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001162 fillInputFrameInfo(snapshot.inputInfo, displayInfo.transform, snapshot);
1163
1164 if (noValidDisplay) {
1165 // Do not let the window receive touches if it is not associated with a valid display
1166 // transform. We still allow the window to receive keys and prevent ANRs.
Prabir Pradhancf359192024-03-20 00:42:57 +00001167 snapshot.inputInfo.inputConfig |= InputConfig::NOT_TOUCHABLE;
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001168 }
1169
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001170 snapshot.inputInfo.alpha = snapshot.color.a;
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001171
1172 handleDropInputMode(snapshot, parentSnapshot);
1173
1174 // If the window will be blacked out on a display because the display does not have the secure
1175 // flag and the layer has the secure flag set, then drop input.
1176 if (!displayInfo.isSecure && snapshot.isSecure) {
Prabir Pradhancf359192024-03-20 00:42:57 +00001177 snapshot.inputInfo.inputConfig |= InputConfig::DROP_INPUT;
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001178 }
1179
Vishnu Naira02943f2023-06-03 13:44:46 -07001180 if (requested.touchCropId != UNASSIGNED_LAYER_ID || path.isClone()) {
Vishnu Nair29354ec2023-03-28 18:51:28 -07001181 mNeedsTouchableRegionCrop.insert(path);
Vishnu Naira02943f2023-06-03 13:44:46 -07001182 }
1183 auto cropLayerSnapshot = getSnapshot(requested.touchCropId);
1184 if (!cropLayerSnapshot && snapshot.inputInfo.replaceTouchableRegionWithCrop) {
Vishnu Nair29354ec2023-03-28 18:51:28 -07001185 FloatRect inputBounds = getInputBounds(snapshot, /*fillParentBounds=*/true).first;
Vishnu Nairfed7c122023-03-18 01:54:43 +00001186 Rect inputBoundsInDisplaySpace =
Vishnu Nair29354ec2023-03-28 18:51:28 -07001187 getInputBoundsInDisplaySpace(snapshot, inputBounds, displayInfo.transform);
1188 snapshot.inputInfo.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001189 }
1190
1191 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
1192 // if it was set by WM for a known system overlay
Vishnu Nair9e0017e2024-05-22 19:02:44 +00001193 if (snapshot.trustedOverlay == gui::TrustedOverlay::ENABLED) {
Prabir Pradhancf359192024-03-20 00:42:57 +00001194 snapshot.inputInfo.inputConfig |= InputConfig::TRUSTED_OVERLAY;
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001195 }
1196
Vishnu Naira9123c82024-10-03 03:56:44 +00001197 snapshot.inputInfo.contentSize = {snapshot.croppedBufferSize.getHeight(),
1198 snapshot.croppedBufferSize.getWidth()};
Vishnu Nair494a2e42023-11-10 17:21:19 -08001199
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001200 // If the layer is a clone, we need to crop the input region to cloned root to prevent
1201 // touches from going outside the cloned area.
1202 if (path.isClone()) {
Prabir Pradhancf359192024-03-20 00:42:57 +00001203 snapshot.inputInfo.inputConfig |= InputConfig::CLONE;
Vishnu Nair444f3952023-04-11 13:01:02 -07001204 // Cloned layers shouldn't handle watch outside since their z order is not determined by
1205 // WM or the client.
Prabir Pradhancf359192024-03-20 00:42:57 +00001206 snapshot.inputInfo.inputConfig.clear(InputConfig::WATCH_OUTSIDE_TOUCH);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001207 }
1208}
1209
1210std::vector<std::unique_ptr<LayerSnapshot>>& LayerSnapshotBuilder::getSnapshots() {
1211 return mSnapshots;
1212}
1213
Vishnu Naircfb2d252023-01-19 04:44:02 +00001214void LayerSnapshotBuilder::forEachVisibleSnapshot(const ConstVisitor& visitor) const {
1215 for (int i = 0; i < mNumInterestingSnapshots; i++) {
1216 LayerSnapshot& snapshot = *mSnapshots[(size_t)i];
1217 if (!snapshot.isVisible) continue;
1218 visitor(snapshot);
1219 }
1220}
1221
Vishnu Nair3af0ec02023-02-10 04:13:48 +00001222// Visit each visible snapshot in z-order
1223void LayerSnapshotBuilder::forEachVisibleSnapshot(const ConstVisitor& visitor,
1224 const LayerHierarchy& root) const {
1225 root.traverseInZOrder(
1226 [this, visitor](const LayerHierarchy&,
1227 const LayerHierarchy::TraversalPath& traversalPath) -> bool {
1228 LayerSnapshot* snapshot = getSnapshot(traversalPath);
1229 if (snapshot && snapshot->isVisible) {
1230 visitor(*snapshot);
1231 }
1232 return true;
1233 });
1234}
1235
Vishnu Naircfb2d252023-01-19 04:44:02 +00001236void LayerSnapshotBuilder::forEachVisibleSnapshot(const Visitor& visitor) {
1237 for (int i = 0; i < mNumInterestingSnapshots; i++) {
1238 std::unique_ptr<LayerSnapshot>& snapshot = mSnapshots.at((size_t)i);
1239 if (!snapshot->isVisible) continue;
1240 visitor(snapshot);
1241 }
1242}
1243
Nergi Rahardi0dfc0962024-05-23 06:57:36 +00001244void LayerSnapshotBuilder::forEachSnapshot(const Visitor& visitor,
1245 const ConstPredicate& predicate) {
1246 for (int i = 0; i < mNumInterestingSnapshots; i++) {
1247 std::unique_ptr<LayerSnapshot>& snapshot = mSnapshots.at((size_t)i);
1248 if (!predicate(*snapshot)) continue;
1249 visitor(snapshot);
1250 }
1251}
1252
Vishnu Nair438a0ac2024-08-15 08:09:32 +00001253void LayerSnapshotBuilder::forEachSnapshot(const ConstVisitor& visitor) const {
1254 for (auto& snapshot : mSnapshots) {
1255 visitor(*snapshot);
1256 }
1257}
1258
Vishnu Naircfb2d252023-01-19 04:44:02 +00001259void LayerSnapshotBuilder::forEachInputSnapshot(const ConstVisitor& visitor) const {
1260 for (int i = mNumInterestingSnapshots - 1; i >= 0; i--) {
1261 LayerSnapshot& snapshot = *mSnapshots[(size_t)i];
1262 if (!snapshot.hasInputInfo()) continue;
1263 visitor(snapshot);
1264 }
1265}
1266
Vishnu Nair29354ec2023-03-28 18:51:28 -07001267void LayerSnapshotBuilder::updateTouchableRegionCrop(const Args& args) {
1268 if (mNeedsTouchableRegionCrop.empty()) {
1269 return;
1270 }
1271
1272 static constexpr ftl::Flags<RequestedLayerState::Changes> AFFECTS_INPUT =
1273 RequestedLayerState::Changes::Visibility | RequestedLayerState::Changes::Created |
1274 RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Geometry |
1275 RequestedLayerState::Changes::Input;
1276
1277 if (args.forceUpdate != ForceUpdateFlags::ALL &&
Vishnu Naira02943f2023-06-03 13:44:46 -07001278 !args.layerLifecycleManager.getGlobalChanges().any(AFFECTS_INPUT) && !args.displayChanges) {
Vishnu Nair29354ec2023-03-28 18:51:28 -07001279 return;
1280 }
1281
1282 for (auto& path : mNeedsTouchableRegionCrop) {
1283 frontend::LayerSnapshot* snapshot = getSnapshot(path);
1284 if (!snapshot) {
1285 continue;
1286 }
Vishnu Naira02943f2023-06-03 13:44:46 -07001287 LLOGV(snapshot->sequence, "updateTouchableRegionCrop=%s",
1288 snapshot->getDebugString().c_str());
Vishnu Nair29354ec2023-03-28 18:51:28 -07001289 const std::optional<frontend::DisplayInfo> displayInfoOpt =
1290 args.displays.get(snapshot->outputFilter.layerStack);
1291 static frontend::DisplayInfo sDefaultInfo = {.isSecure = false};
1292 auto displayInfo = displayInfoOpt.value_or(sDefaultInfo);
1293
1294 bool needsUpdate =
1295 args.forceUpdate == ForceUpdateFlags::ALL || snapshot->changes.any(AFFECTS_INPUT);
1296 auto cropLayerSnapshot = getSnapshot(snapshot->touchCropId);
1297 needsUpdate =
1298 needsUpdate || (cropLayerSnapshot && cropLayerSnapshot->changes.any(AFFECTS_INPUT));
1299 auto clonedRootSnapshot = path.isClone() ? getSnapshot(snapshot->mirrorRootPath) : nullptr;
1300 needsUpdate = needsUpdate ||
1301 (clonedRootSnapshot && clonedRootSnapshot->changes.any(AFFECTS_INPUT));
1302
1303 if (!needsUpdate) {
1304 continue;
1305 }
1306
1307 if (snapshot->inputInfo.replaceTouchableRegionWithCrop) {
1308 Rect inputBoundsInDisplaySpace;
1309 if (!cropLayerSnapshot) {
1310 FloatRect inputBounds = getInputBounds(*snapshot, /*fillParentBounds=*/true).first;
1311 inputBoundsInDisplaySpace =
1312 getInputBoundsInDisplaySpace(*snapshot, inputBounds, displayInfo.transform);
1313 } else {
1314 FloatRect inputBounds =
1315 getInputBounds(*cropLayerSnapshot, /*fillParentBounds=*/true).first;
1316 inputBoundsInDisplaySpace =
1317 getInputBoundsInDisplaySpace(*cropLayerSnapshot, inputBounds,
1318 displayInfo.transform);
1319 }
1320 snapshot->inputInfo.touchableRegion = Region(inputBoundsInDisplaySpace);
1321 } else if (cropLayerSnapshot) {
1322 FloatRect inputBounds =
1323 getInputBounds(*cropLayerSnapshot, /*fillParentBounds=*/true).first;
1324 Rect inputBoundsInDisplaySpace =
1325 getInputBoundsInDisplaySpace(*cropLayerSnapshot, inputBounds,
1326 displayInfo.transform);
Chavi Weingarten1ba381e2024-01-09 21:54:11 +00001327 snapshot->inputInfo.touchableRegion =
1328 snapshot->inputInfo.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair29354ec2023-03-28 18:51:28 -07001329 }
1330
1331 // If the layer is a clone, we need to crop the input region to cloned root to prevent
1332 // touches from going outside the cloned area.
1333 if (clonedRootSnapshot) {
1334 const Rect rect =
1335 displayInfo.transform.transform(Rect{clonedRootSnapshot->transformedBounds});
1336 snapshot->inputInfo.touchableRegion =
1337 snapshot->inputInfo.touchableRegion.intersect(rect);
1338 }
1339 }
1340}
1341
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001342} // namespace android::surfaceflinger::frontend