blob: a4ffd51d43795253573852f80d2596c18a3e931c [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>
Dominik Laskowski6b049ff2023-01-29 15:46:45 -050026#include <ftl/small_map.h>
Vishnu Nairb76d99a2023-03-19 18:22:31 -070027#include <gui/TraceUtils.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) {
119 FloatRect inputBounds = snapshot.croppedBufferSize.toFloatRect();
120 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
223 Rect bufferSize = snapshot.croppedBufferSize;
224 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
282bool needsInputInfo(const LayerSnapshot& snapshot, const RequestedLayerState& requested) {
283 if (requested.potentialCursor) {
284 return false;
285 }
286
287 if (snapshot.inputInfo.token != nullptr) {
288 return true;
289 }
290
291 if (snapshot.hasBufferOrSidebandStream()) {
292 return true;
293 }
294
295 return requested.windowInfoHandle &&
296 requested.windowInfoHandle->getInfo()->inputConfig.test(
297 gui::WindowInfo::InputConfig::NO_INPUT_CHANNEL);
298}
299
Vishnu Nairc765c6c2023-02-23 00:08:01 +0000300void updateMetadata(LayerSnapshot& snapshot, const RequestedLayerState& requested,
301 const LayerSnapshotBuilder::Args& args) {
302 snapshot.metadata.clear();
303 for (const auto& [key, mandatory] : args.supportedLayerGenericMetadata) {
304 auto compatIter = args.genericLayerMetadataKeyMap.find(key);
305 if (compatIter == std::end(args.genericLayerMetadataKeyMap)) {
306 continue;
307 }
308 const uint32_t id = compatIter->second;
309 auto it = requested.metadata.mMap.find(id);
310 if (it == std::end(requested.metadata.mMap)) {
311 continue;
312 }
313
314 snapshot.metadata.emplace(key,
315 compositionengine::GenericLayerMetadataEntry{mandatory,
316 it->second});
317 }
318}
319
Nergi Rahardi0dfc0962024-05-23 06:57:36 +0000320void updateMetadataAndGameMode(LayerSnapshot& snapshot, const RequestedLayerState& requested,
321 const LayerSnapshotBuilder::Args& args,
322 const LayerSnapshot& parentSnapshot) {
323 if (snapshot.changes.test(RequestedLayerState::Changes::GameMode)) {
324 snapshot.gameMode = requested.metadata.has(gui::METADATA_GAME_MODE)
325 ? requested.gameMode
326 : parentSnapshot.gameMode;
327 }
328 updateMetadata(snapshot, requested, args);
329 if (args.includeMetadata) {
330 snapshot.layerMetadata = parentSnapshot.layerMetadata;
331 snapshot.layerMetadata.merge(requested.metadata);
332 }
333}
334
Vishnu Naircfb2d252023-01-19 04:44:02 +0000335void clearChanges(LayerSnapshot& snapshot) {
336 snapshot.changes.clear();
Vishnu Naira02943f2023-06-03 13:44:46 -0700337 snapshot.clientChanges = 0;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000338 snapshot.contentDirty = false;
339 snapshot.hasReadyFrame = false;
340 snapshot.sidebandStreamHasFrame = false;
341 snapshot.surfaceDamage.clear();
342}
343
Vishnu Naira02943f2023-06-03 13:44:46 -0700344// TODO (b/259407931): Remove.
345uint32_t getPrimaryDisplayRotationFlags(
346 const ui::DisplayMap<ui::LayerStack, frontend::DisplayInfo>& displays) {
347 for (auto& [_, display] : displays) {
348 if (display.isPrimary) {
349 return display.rotationFlags;
350 }
351 }
352 return 0;
353}
354
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000355} // namespace
356
357LayerSnapshot LayerSnapshotBuilder::getRootSnapshot() {
358 LayerSnapshot snapshot;
Vishnu Nair92990e22023-02-24 20:01:05 +0000359 snapshot.path = LayerHierarchy::TraversalPath::ROOT;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000360 snapshot.changes = ftl::Flags<RequestedLayerState::Changes>();
Vishnu Naira02943f2023-06-03 13:44:46 -0700361 snapshot.clientChanges = 0;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000362 snapshot.isHiddenByPolicyFromParent = false;
363 snapshot.isHiddenByPolicyFromRelativeParent = false;
364 snapshot.parentTransform.reset();
365 snapshot.geomLayerTransform.reset();
366 snapshot.geomInverseLayerTransform.reset();
367 snapshot.geomLayerBounds = getMaxDisplayBounds({});
368 snapshot.roundedCorner = RoundedCornerState();
369 snapshot.stretchEffect = {};
370 snapshot.outputFilter.layerStack = ui::DEFAULT_LAYER_STACK;
371 snapshot.outputFilter.toInternalDisplay = false;
372 snapshot.isSecure = false;
373 snapshot.color.a = 1.0_hf;
374 snapshot.colorTransformIsIdentity = true;
Vishnu Naird9e4f462023-10-06 04:05:45 +0000375 snapshot.shadowSettings.length = 0.f;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000376 snapshot.layerMetadata.mMap.clear();
377 snapshot.relativeLayerMetadata.mMap.clear();
378 snapshot.inputInfo.touchOcclusionMode = gui::TouchOcclusionMode::BLOCK_UNTRUSTED;
379 snapshot.dropInputMode = gui::DropInputMode::NONE;
Vishnu Nair9e0017e2024-05-22 19:02:44 +0000380 snapshot.trustedOverlay = gui::TrustedOverlay::UNSET;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000381 snapshot.gameMode = gui::GameMode::Unsupported;
382 snapshot.frameRate = {};
383 snapshot.fixedTransformHint = ui::Transform::ROT_INVALID;
Vishnu Nair422b81c2024-05-16 05:44:28 +0000384 snapshot.ignoreLocalTransform = false;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000385 return snapshot;
386}
387
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000388LayerSnapshotBuilder::LayerSnapshotBuilder() {}
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000389
390LayerSnapshotBuilder::LayerSnapshotBuilder(Args args) : LayerSnapshotBuilder() {
Vishnu Naird47bcee2023-02-24 18:08:51 +0000391 args.forceUpdate = ForceUpdateFlags::ALL;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000392 updateSnapshots(args);
393}
394
395bool LayerSnapshotBuilder::tryFastUpdate(const Args& args) {
Vishnu Naira02943f2023-06-03 13:44:46 -0700396 const bool forceUpdate = args.forceUpdate != ForceUpdateFlags::NONE;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000397
Vishnu Naira02943f2023-06-03 13:44:46 -0700398 if (args.layerLifecycleManager.getGlobalChanges().get() == 0 && !forceUpdate &&
399 !args.displayChanges) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000400 return true;
401 }
402
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000403 // There are only content changes which do not require any child layer snapshots to be updated.
404 ALOGV("%s", __func__);
405 ATRACE_NAME("FastPath");
406
Vishnu Naira02943f2023-06-03 13:44:46 -0700407 uint32_t primaryDisplayRotationFlags = getPrimaryDisplayRotationFlags(args.displays);
408 if (forceUpdate || args.displayChanges) {
409 for (auto& snapshot : mSnapshots) {
410 const RequestedLayerState* requested =
411 args.layerLifecycleManager.getLayerFromId(snapshot->path.id);
412 if (!requested) continue;
413 snapshot->merge(*requested, forceUpdate, args.displayChanges, args.forceFullDamage,
414 primaryDisplayRotationFlags);
415 }
416 return false;
417 }
418
419 // Walk through all the updated requested layer states and update the corresponding snapshots.
420 for (const RequestedLayerState* requested : args.layerLifecycleManager.getChangedLayers()) {
421 auto range = mIdToSnapshots.equal_range(requested->id);
422 for (auto it = range.first; it != range.second; it++) {
423 it->second->merge(*requested, forceUpdate, args.displayChanges, args.forceFullDamage,
424 primaryDisplayRotationFlags);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000425 }
426 }
427
Vishnu Naira02943f2023-06-03 13:44:46 -0700428 if ((args.layerLifecycleManager.getGlobalChanges().get() &
429 ~(RequestedLayerState::Changes::Content | RequestedLayerState::Changes::Buffer).get()) !=
430 0) {
431 // We have changes that require us to walk the hierarchy and update child layers.
432 // No fast path for you.
433 return false;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000434 }
435 return true;
436}
437
438void LayerSnapshotBuilder::updateSnapshots(const Args& args) {
439 ATRACE_NAME("UpdateSnapshots");
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000440 LayerSnapshot rootSnapshot = args.rootSnapshot;
Vishnu Nair3af0ec02023-02-10 04:13:48 +0000441 if (args.parentCrop) {
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000442 rootSnapshot.geomLayerBounds = *args.parentCrop;
Vishnu Naird47bcee2023-02-24 18:08:51 +0000443 } else if (args.forceUpdate == ForceUpdateFlags::ALL || args.displayChanges) {
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000444 rootSnapshot.geomLayerBounds = getMaxDisplayBounds(args.displays);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000445 }
446 if (args.displayChanges) {
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000447 rootSnapshot.changes = RequestedLayerState::Changes::AffectsChildren |
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000448 RequestedLayerState::Changes::Geometry;
449 }
Vishnu Naird47bcee2023-02-24 18:08:51 +0000450 if (args.forceUpdate == ForceUpdateFlags::HIERARCHY) {
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000451 rootSnapshot.changes |=
Vishnu Naird47bcee2023-02-24 18:08:51 +0000452 RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Visibility;
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000453 rootSnapshot.clientChanges |= layer_state_t::eReparent;
Vishnu Naird47bcee2023-02-24 18:08:51 +0000454 }
Vishnu Naira02943f2023-06-03 13:44:46 -0700455
456 for (auto& snapshot : mSnapshots) {
457 if (snapshot->reachablilty == LayerSnapshot::Reachablilty::Reachable) {
458 snapshot->reachablilty = LayerSnapshot::Reachablilty::Unreachable;
459 }
460 }
461
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000462 LayerHierarchy::TraversalPath root = LayerHierarchy::TraversalPath::ROOT;
Vishnu Naird47bcee2023-02-24 18:08:51 +0000463 if (args.root.getLayer()) {
464 // The hierarchy can have a root layer when used for screenshots otherwise, it will have
465 // multiple children.
466 LayerHierarchy::ScopedAddToTraversalPath addChildToPath(root, args.root.getLayer()->id,
467 LayerHierarchy::Variant::Attached);
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000468 updateSnapshotsInHierarchy(args, args.root, root, rootSnapshot, /*depth=*/0);
Vishnu Naird47bcee2023-02-24 18:08:51 +0000469 } else {
470 for (auto& [childHierarchy, variant] : args.root.mChildren) {
471 LayerHierarchy::ScopedAddToTraversalPath addChildToPath(root,
472 childHierarchy->getLayer()->id,
473 variant);
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000474 updateSnapshotsInHierarchy(args, *childHierarchy, root, rootSnapshot, /*depth=*/0);
Vishnu Naird47bcee2023-02-24 18:08:51 +0000475 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000476 }
477
Vishnu Nair29354ec2023-03-28 18:51:28 -0700478 // Update touchable region crops outside the main update pass. This is because a layer could be
479 // cropped by any other layer and it requires both snapshots to be updated.
480 updateTouchableRegionCrop(args);
481
Vishnu Nairfccd6362023-02-24 23:39:53 +0000482 const bool hasUnreachableSnapshots = sortSnapshotsByZ(args);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000483
Vishnu Nair29354ec2023-03-28 18:51:28 -0700484 // Destroy unreachable snapshots for clone layers. And destroy snapshots for non-clone
485 // layers if the layer have been destroyed.
486 // TODO(b/238781169) consider making clone layer ids stable as well
487 if (!hasUnreachableSnapshots && args.layerLifecycleManager.getDestroyedLayers().empty()) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000488 return;
489 }
490
Vishnu Nair29354ec2023-03-28 18:51:28 -0700491 std::unordered_set<uint32_t> destroyedLayerIds;
492 for (auto& destroyedLayer : args.layerLifecycleManager.getDestroyedLayers()) {
493 destroyedLayerIds.insert(destroyedLayer->id);
494 }
495
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000496 auto it = mSnapshots.begin();
497 while (it < mSnapshots.end()) {
498 auto& traversalPath = it->get()->path;
Vishnu Naira02943f2023-06-03 13:44:46 -0700499 const bool unreachable =
500 it->get()->reachablilty == LayerSnapshot::Reachablilty::Unreachable;
501 const bool isClone = traversalPath.isClone();
502 const bool layerIsDestroyed =
503 destroyedLayerIds.find(traversalPath.id) != destroyedLayerIds.end();
504 const bool destroySnapshot = (unreachable && isClone) || layerIsDestroyed;
505
506 if (!destroySnapshot) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000507 it++;
508 continue;
509 }
510
Vishnu Naira02943f2023-06-03 13:44:46 -0700511 mPathToSnapshot.erase(traversalPath);
512
513 auto range = mIdToSnapshots.equal_range(traversalPath.id);
514 auto matchingSnapshot =
515 std::find_if(range.first, range.second, [&traversalPath](auto& snapshotWithId) {
516 return snapshotWithId.second->path == traversalPath;
517 });
518 mIdToSnapshots.erase(matchingSnapshot);
Vishnu Nair29354ec2023-03-28 18:51:28 -0700519 mNeedsTouchableRegionCrop.erase(traversalPath);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000520 mSnapshots.back()->globalZ = it->get()->globalZ;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000521 std::iter_swap(it, mSnapshots.end() - 1);
522 mSnapshots.erase(mSnapshots.end() - 1);
523 }
524}
525
526void LayerSnapshotBuilder::update(const Args& args) {
Vishnu Nair92990e22023-02-24 20:01:05 +0000527 for (auto& snapshot : mSnapshots) {
528 clearChanges(*snapshot);
529 }
530
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000531 if (tryFastUpdate(args)) {
532 return;
533 }
534 updateSnapshots(args);
535}
536
Vishnu Naircfb2d252023-01-19 04:44:02 +0000537const LayerSnapshot& LayerSnapshotBuilder::updateSnapshotsInHierarchy(
538 const Args& args, const LayerHierarchy& hierarchy,
Vishnu Naird1f74982023-06-15 20:16:51 -0700539 LayerHierarchy::TraversalPath& traversalPath, const LayerSnapshot& parentSnapshot,
540 int depth) {
Vishnu Nair606d9d02023-08-19 14:20:18 -0700541 LLOG_ALWAYS_FATAL_WITH_TRACE_IF(depth > 50,
542 "Cycle detected in LayerSnapshotBuilder. See "
543 "builder_stack_overflow_transactions.winscope");
Vishnu Naird1f74982023-06-15 20:16:51 -0700544
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000545 const RequestedLayerState* layer = hierarchy.getLayer();
Vishnu Naircfb2d252023-01-19 04:44:02 +0000546 LayerSnapshot* snapshot = getSnapshot(traversalPath);
547 const bool newSnapshot = snapshot == nullptr;
Vishnu Naira02943f2023-06-03 13:44:46 -0700548 uint32_t primaryDisplayRotationFlags = getPrimaryDisplayRotationFlags(args.displays);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000549 if (newSnapshot) {
Vishnu Nair92990e22023-02-24 20:01:05 +0000550 snapshot = createSnapshot(traversalPath, *layer, parentSnapshot);
Vishnu Naira02943f2023-06-03 13:44:46 -0700551 snapshot->merge(*layer, /*forceUpdate=*/true, /*displayChanges=*/true, args.forceFullDamage,
552 primaryDisplayRotationFlags);
553 snapshot->changes |= RequestedLayerState::Changes::Created;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000554 }
Vishnu Nair52d56fd2023-07-20 17:02:43 +0000555
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000556 if (traversalPath.isRelative()) {
557 bool parentIsRelative = traversalPath.variant == LayerHierarchy::Variant::Relative;
558 updateRelativeState(*snapshot, parentSnapshot, parentIsRelative, args);
559 } else {
560 if (traversalPath.isAttached()) {
561 resetRelativeState(*snapshot);
562 }
Vishnu Nair92990e22023-02-24 20:01:05 +0000563 updateSnapshot(*snapshot, args, *layer, parentSnapshot, traversalPath);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000564 }
565
566 for (auto& [childHierarchy, variant] : hierarchy.mChildren) {
567 LayerHierarchy::ScopedAddToTraversalPath addChildToPath(traversalPath,
568 childHierarchy->getLayer()->id,
569 variant);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000570 const LayerSnapshot& childSnapshot =
Vishnu Naird1f74982023-06-15 20:16:51 -0700571 updateSnapshotsInHierarchy(args, *childHierarchy, traversalPath, *snapshot,
572 depth + 1);
Vishnu Nair42b918e2023-07-18 20:05:29 +0000573 updateFrameRateFromChildSnapshot(*snapshot, childSnapshot, args);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000574 }
Vishnu Naird47bcee2023-02-24 18:08:51 +0000575
Vishnu Naircfb2d252023-01-19 04:44:02 +0000576 return *snapshot;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000577}
578
579LayerSnapshot* LayerSnapshotBuilder::getSnapshot(uint32_t layerId) const {
580 if (layerId == UNASSIGNED_LAYER_ID) {
581 return nullptr;
582 }
583 LayerHierarchy::TraversalPath path{.id = layerId};
584 return getSnapshot(path);
585}
586
587LayerSnapshot* LayerSnapshotBuilder::getSnapshot(const LayerHierarchy::TraversalPath& id) const {
Vishnu Naira02943f2023-06-03 13:44:46 -0700588 auto it = mPathToSnapshot.find(id);
589 return it == mPathToSnapshot.end() ? nullptr : it->second;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000590}
591
Vishnu Nair92990e22023-02-24 20:01:05 +0000592LayerSnapshot* LayerSnapshotBuilder::createSnapshot(const LayerHierarchy::TraversalPath& path,
593 const RequestedLayerState& layer,
594 const LayerSnapshot& parentSnapshot) {
595 mSnapshots.emplace_back(std::make_unique<LayerSnapshot>(layer, path));
Vishnu Naircfb2d252023-01-19 04:44:02 +0000596 LayerSnapshot* snapshot = mSnapshots.back().get();
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000597 snapshot->globalZ = static_cast<size_t>(mSnapshots.size()) - 1;
Vishnu Nair491827d2024-04-29 23:43:26 +0000598 if (path.isClone() && !LayerHierarchy::isMirror(path.variant)) {
Vishnu Nair92990e22023-02-24 20:01:05 +0000599 snapshot->mirrorRootPath = parentSnapshot.mirrorRootPath;
600 }
Vishnu Nair491827d2024-04-29 23:43:26 +0000601 snapshot->ignoreLocalTransform =
602 path.isClone() && path.variant == LayerHierarchy::Variant::Detached_Mirror;
Vishnu Naira02943f2023-06-03 13:44:46 -0700603 mPathToSnapshot[path] = snapshot;
604
605 mIdToSnapshots.emplace(path.id, snapshot);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000606 return snapshot;
607}
608
Vishnu Nairfccd6362023-02-24 23:39:53 +0000609bool LayerSnapshotBuilder::sortSnapshotsByZ(const Args& args) {
Vishnu Naird47bcee2023-02-24 18:08:51 +0000610 if (!mResortSnapshots && args.forceUpdate == ForceUpdateFlags::NONE &&
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000611 !args.layerLifecycleManager.getGlobalChanges().any(
Chavi Weingarten92c7d8c2024-01-19 23:25:45 +0000612 RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Visibility |
613 RequestedLayerState::Changes::Input)) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000614 // We are not force updating and there are no hierarchy or visibility changes. Avoid sorting
615 // the snapshots.
Vishnu Nairfccd6362023-02-24 23:39:53 +0000616 return false;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000617 }
Vishnu Naircfb2d252023-01-19 04:44:02 +0000618 mResortSnapshots = false;
619
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000620 size_t globalZ = 0;
621 args.root.traverseInZOrder(
622 [this, &globalZ](const LayerHierarchy&,
623 const LayerHierarchy::TraversalPath& traversalPath) -> bool {
624 LayerSnapshot* snapshot = getSnapshot(traversalPath);
625 if (!snapshot) {
Vishnu Naira02943f2023-06-03 13:44:46 -0700626 return true;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000627 }
628
Vishnu Naircfb2d252023-01-19 04:44:02 +0000629 if (snapshot->getIsVisible() || snapshot->hasInputInfo()) {
Vishnu Nair80a5a702023-02-11 01:21:51 +0000630 updateVisibility(*snapshot, snapshot->getIsVisible());
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000631 size_t oldZ = snapshot->globalZ;
632 size_t newZ = globalZ++;
633 snapshot->globalZ = newZ;
634 if (oldZ == newZ) {
635 return true;
636 }
637 mSnapshots[newZ]->globalZ = oldZ;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000638 LLOGV(snapshot->sequence, "Made visible z=%zu -> %zu %s", oldZ, newZ,
639 snapshot->getDebugString().c_str());
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000640 std::iter_swap(mSnapshots.begin() + static_cast<ssize_t>(oldZ),
641 mSnapshots.begin() + static_cast<ssize_t>(newZ));
642 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000643 return true;
644 });
Vishnu Naircfb2d252023-01-19 04:44:02 +0000645 mNumInterestingSnapshots = (int)globalZ;
Vishnu Nairfccd6362023-02-24 23:39:53 +0000646 bool hasUnreachableSnapshots = false;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000647 while (globalZ < mSnapshots.size()) {
648 mSnapshots[globalZ]->globalZ = globalZ;
Vishnu Nair80a5a702023-02-11 01:21:51 +0000649 /* mark unreachable snapshots as explicitly invisible */
650 updateVisibility(*mSnapshots[globalZ], false);
Vishnu Naira02943f2023-06-03 13:44:46 -0700651 if (mSnapshots[globalZ]->reachablilty == LayerSnapshot::Reachablilty::Unreachable) {
Vishnu Nairfccd6362023-02-24 23:39:53 +0000652 hasUnreachableSnapshots = true;
653 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000654 globalZ++;
655 }
Vishnu Nairfccd6362023-02-24 23:39:53 +0000656 return hasUnreachableSnapshots;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000657}
658
659void LayerSnapshotBuilder::updateRelativeState(LayerSnapshot& snapshot,
660 const LayerSnapshot& parentSnapshot,
661 bool parentIsRelative, const Args& args) {
662 if (parentIsRelative) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000663 snapshot.isHiddenByPolicyFromRelativeParent =
664 parentSnapshot.isHiddenByPolicyFromParent || parentSnapshot.invalidTransform;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000665 if (args.includeMetadata) {
666 snapshot.relativeLayerMetadata = parentSnapshot.layerMetadata;
667 }
668 } else {
669 snapshot.isHiddenByPolicyFromRelativeParent =
670 parentSnapshot.isHiddenByPolicyFromRelativeParent;
671 if (args.includeMetadata) {
672 snapshot.relativeLayerMetadata = parentSnapshot.relativeLayerMetadata;
673 }
674 }
Vishnu Naira02943f2023-06-03 13:44:46 -0700675 if (snapshot.reachablilty == LayerSnapshot::Reachablilty::Unreachable) {
676 snapshot.reachablilty = LayerSnapshot::Reachablilty::ReachableByRelativeParent;
677 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000678}
679
Vishnu Nair42b918e2023-07-18 20:05:29 +0000680void LayerSnapshotBuilder::updateFrameRateFromChildSnapshot(LayerSnapshot& snapshot,
681 const LayerSnapshot& childSnapshot,
682 const Args& args) {
683 if (args.forceUpdate == ForceUpdateFlags::NONE &&
Vishnu Nair52d56fd2023-07-20 17:02:43 +0000684 !args.layerLifecycleManager.getGlobalChanges().any(
685 RequestedLayerState::Changes::Hierarchy) &&
686 !childSnapshot.changes.any(RequestedLayerState::Changes::FrameRate) &&
687 !snapshot.changes.any(RequestedLayerState::Changes::FrameRate)) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000688 return;
689 }
Vishnu Naircfb2d252023-01-19 04:44:02 +0000690
Vishnu Nair3fbe3262023-09-29 17:07:00 -0700691 using FrameRateCompatibility = scheduler::FrameRateCompatibility;
Rachel Leece6e0042023-06-27 11:22:54 -0700692 if (snapshot.frameRate.isValid()) {
Vishnu Nair42b918e2023-07-18 20:05:29 +0000693 // we already have a valid framerate.
694 return;
695 }
Vishnu Naircfb2d252023-01-19 04:44:02 +0000696
Vishnu Nair42b918e2023-07-18 20:05:29 +0000697 // We return whether this layer or its children has a vote. We ignore ExactOrMultiple votes
698 // for the same reason we are allowing touch boost for those layers. See
699 // RefreshRateSelector::rankFrameRates for details.
Rachel Leece6e0042023-06-27 11:22:54 -0700700 const auto layerVotedWithDefaultCompatibility = childSnapshot.frameRate.vote.rate.isValid() &&
701 childSnapshot.frameRate.vote.type == FrameRateCompatibility::Default;
Vishnu Nair42b918e2023-07-18 20:05:29 +0000702 const auto layerVotedWithNoVote =
Rachel Leece6e0042023-06-27 11:22:54 -0700703 childSnapshot.frameRate.vote.type == FrameRateCompatibility::NoVote;
704 const auto layerVotedWithCategory =
705 childSnapshot.frameRate.category != FrameRateCategory::Default;
706 const auto layerVotedWithExactCompatibility = childSnapshot.frameRate.vote.rate.isValid() &&
707 childSnapshot.frameRate.vote.type == FrameRateCompatibility::Exact;
Vishnu Nair42b918e2023-07-18 20:05:29 +0000708
709 bool childHasValidFrameRate = layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
Rachel Leece6e0042023-06-27 11:22:54 -0700710 layerVotedWithCategory || layerVotedWithExactCompatibility;
Vishnu Nair42b918e2023-07-18 20:05:29 +0000711
712 // If we don't have a valid frame rate, but the children do, we set this
713 // layer as NoVote to allow the children to control the refresh rate
714 if (childHasValidFrameRate) {
715 snapshot.frameRate = scheduler::LayerInfo::FrameRate(Fps(), FrameRateCompatibility::NoVote);
716 snapshot.changes |= RequestedLayerState::Changes::FrameRate;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000717 }
718}
719
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000720void LayerSnapshotBuilder::resetRelativeState(LayerSnapshot& snapshot) {
721 snapshot.isHiddenByPolicyFromRelativeParent = false;
722 snapshot.relativeLayerMetadata.mMap.clear();
723}
724
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000725void LayerSnapshotBuilder::updateSnapshot(LayerSnapshot& snapshot, const Args& args,
726 const RequestedLayerState& requested,
727 const LayerSnapshot& parentSnapshot,
Vishnu Nair92990e22023-02-24 20:01:05 +0000728 const LayerHierarchy::TraversalPath& path) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000729 // Always update flags and visibility
730 ftl::Flags<RequestedLayerState::Changes> parentChanges = parentSnapshot.changes &
731 (RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Geometry |
732 RequestedLayerState::Changes::Visibility | RequestedLayerState::Changes::Metadata |
Vishnu Nairf13c8982023-12-02 11:26:09 -0800733 RequestedLayerState::Changes::AffectsChildren | RequestedLayerState::Changes::Input |
Vishnu Naira02943f2023-06-03 13:44:46 -0700734 RequestedLayerState::Changes::FrameRate | RequestedLayerState::Changes::GameMode);
735 snapshot.changes |= parentChanges;
736 if (args.displayChanges) snapshot.changes |= RequestedLayerState::Changes::Geometry;
737 snapshot.reachablilty = LayerSnapshot::Reachablilty::Reachable;
738 snapshot.clientChanges |= (parentSnapshot.clientChanges & layer_state_t::AFFECTS_CHILDREN);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000739 snapshot.isHiddenByPolicyFromParent = parentSnapshot.isHiddenByPolicyFromParent ||
Vishnu Nair3af0ec02023-02-10 04:13:48 +0000740 parentSnapshot.invalidTransform || requested.isHiddenByPolicy() ||
741 (args.excludeLayerIds.find(path.id) != args.excludeLayerIds.end());
Vishnu Nair80a5a702023-02-11 01:21:51 +0000742
Vishnu Nair92990e22023-02-24 20:01:05 +0000743 const bool forceUpdate = args.forceUpdate == ForceUpdateFlags::ALL ||
Vishnu Naira02943f2023-06-03 13:44:46 -0700744 snapshot.clientChanges & layer_state_t::eReparent ||
Vishnu Nair92990e22023-02-24 20:01:05 +0000745 snapshot.changes.any(RequestedLayerState::Changes::Visibility |
746 RequestedLayerState::Changes::Created);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000747
Vishnu Naira02943f2023-06-03 13:44:46 -0700748 if (forceUpdate || snapshot.clientChanges & layer_state_t::eLayerStackChanged) {
749 // If root layer, use the layer stack otherwise get the parent's layer stack.
750 snapshot.outputFilter.layerStack =
751 parentSnapshot.path == LayerHierarchy::TraversalPath::ROOT
752 ? requested.layerStack
753 : parentSnapshot.outputFilter.layerStack;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000754 }
755
Chavi Weingartenb74093a2023-10-11 20:29:59 +0000756 if (forceUpdate || snapshot.clientChanges & layer_state_t::eTrustedOverlayChanged) {
Vishnu Nair9e0017e2024-05-22 19:02:44 +0000757 switch (requested.trustedOverlay) {
758 case gui::TrustedOverlay::UNSET:
759 snapshot.trustedOverlay = parentSnapshot.trustedOverlay;
760 break;
761 case gui::TrustedOverlay::DISABLED:
762 snapshot.trustedOverlay = FlagManager::getInstance().override_trusted_overlay()
763 ? requested.trustedOverlay
764 : parentSnapshot.trustedOverlay;
765 break;
766 case gui::TrustedOverlay::ENABLED:
767 snapshot.trustedOverlay = requested.trustedOverlay;
768 break;
769 }
Chavi Weingartenb74093a2023-10-11 20:29:59 +0000770 }
771
Vishnu Nair92990e22023-02-24 20:01:05 +0000772 if (snapshot.isHiddenByPolicyFromParent &&
773 !snapshot.changes.test(RequestedLayerState::Changes::Created)) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000774 if (forceUpdate ||
Vishnu Naira02943f2023-06-03 13:44:46 -0700775 snapshot.changes.any(RequestedLayerState::Changes::Geometry |
Vishnu Nair494a2e42023-11-10 17:21:19 -0800776 RequestedLayerState::Changes::BufferSize |
Vishnu Naircfb2d252023-01-19 04:44:02 +0000777 RequestedLayerState::Changes::Input)) {
778 updateInput(snapshot, requested, parentSnapshot, path, args);
779 }
Nergi Rahardi0dfc0962024-05-23 06:57:36 +0000780 if (forceUpdate ||
781 (args.includeMetadata &&
782 snapshot.changes.test(RequestedLayerState::Changes::Metadata))) {
783 updateMetadataAndGameMode(snapshot, requested, args, parentSnapshot);
784 }
Vishnu Naircfb2d252023-01-19 04:44:02 +0000785 return;
786 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000787
Vishnu Naira02943f2023-06-03 13:44:46 -0700788 if (forceUpdate || snapshot.changes.any(RequestedLayerState::Changes::Mirror)) {
789 // Display mirrors are always placed in a VirtualDisplay so we never want to capture layers
790 // marked as skip capture
791 snapshot.handleSkipScreenshotFlag = parentSnapshot.handleSkipScreenshotFlag ||
792 (requested.layerStackToMirror != ui::INVALID_LAYER_STACK);
793 }
794
795 if (forceUpdate || snapshot.clientChanges & layer_state_t::eAlphaChanged) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000796 snapshot.color.a = parentSnapshot.color.a * requested.color.a;
797 snapshot.alpha = snapshot.color.a;
Vishnu Nair29354ec2023-03-28 18:51:28 -0700798 snapshot.inputInfo.alpha = snapshot.color.a;
Vishnu Naira02943f2023-06-03 13:44:46 -0700799 }
Vishnu Nair29354ec2023-03-28 18:51:28 -0700800
Vishnu Naira02943f2023-06-03 13:44:46 -0700801 if (forceUpdate || snapshot.clientChanges & layer_state_t::eFlagsChanged) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000802 snapshot.isSecure =
803 parentSnapshot.isSecure || (requested.flags & layer_state_t::eLayerSecure);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000804 snapshot.outputFilter.toInternalDisplay = parentSnapshot.outputFilter.toInternalDisplay ||
805 (requested.flags & layer_state_t::eLayerSkipScreenshot);
Vishnu Naira02943f2023-06-03 13:44:46 -0700806 }
807
Vishnu Naira02943f2023-06-03 13:44:46 -0700808 if (forceUpdate || snapshot.clientChanges & layer_state_t::eStretchChanged) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000809 snapshot.stretchEffect = (requested.stretchEffect.hasEffect())
810 ? requested.stretchEffect
811 : parentSnapshot.stretchEffect;
Vishnu Naira02943f2023-06-03 13:44:46 -0700812 }
813
814 if (forceUpdate || snapshot.clientChanges & layer_state_t::eColorTransformChanged) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000815 if (!parentSnapshot.colorTransformIsIdentity) {
816 snapshot.colorTransform = parentSnapshot.colorTransform * requested.colorTransform;
817 snapshot.colorTransformIsIdentity = false;
818 } else {
819 snapshot.colorTransform = requested.colorTransform;
820 snapshot.colorTransformIsIdentity = !requested.hasColorTransform;
821 }
Vishnu Naira02943f2023-06-03 13:44:46 -0700822 }
823
Nergi Rahardi27613c32024-05-23 06:57:02 +0000824 if (forceUpdate || snapshot.changes.test(RequestedLayerState::Changes::Metadata)) {
Nergi Rahardi0dfc0962024-05-23 06:57:36 +0000825 updateMetadataAndGameMode(snapshot, requested, args, parentSnapshot);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000826 }
827
Vishnu Naira02943f2023-06-03 13:44:46 -0700828 if (forceUpdate || snapshot.clientChanges & layer_state_t::eFixedTransformHintChanged ||
Vishnu Nairb76d99a2023-03-19 18:22:31 -0700829 args.displayChanges) {
830 snapshot.fixedTransformHint = requested.fixedTransformHint != ui::Transform::ROT_INVALID
831 ? requested.fixedTransformHint
832 : parentSnapshot.fixedTransformHint;
833
834 if (snapshot.fixedTransformHint != ui::Transform::ROT_INVALID) {
835 snapshot.transformHint = snapshot.fixedTransformHint;
836 } else {
837 const auto display = args.displays.get(snapshot.outputFilter.layerStack);
838 snapshot.transformHint = display.has_value()
839 ? std::make_optional<>(display->get().transformHint)
840 : std::nullopt;
841 }
842 }
843
Vishnu Nair42b918e2023-07-18 20:05:29 +0000844 if (forceUpdate ||
Vishnu Nair52d56fd2023-07-20 17:02:43 +0000845 args.layerLifecycleManager.getGlobalChanges().any(
846 RequestedLayerState::Changes::Hierarchy) ||
Vishnu Nair42b918e2023-07-18 20:05:29 +0000847 snapshot.changes.any(RequestedLayerState::Changes::FrameRate |
848 RequestedLayerState::Changes::Hierarchy)) {
Rachel Leea021bb02023-11-20 21:51:09 -0800849 const bool shouldOverrideChildren = parentSnapshot.frameRateSelectionStrategy ==
Rachel Lee58cc90d2023-09-05 18:50:20 -0700850 scheduler::LayerInfo::FrameRateSelectionStrategy::OverrideChildren;
Rachel Leea021bb02023-11-20 21:51:09 -0800851 const bool propagationAllowed = parentSnapshot.frameRateSelectionStrategy !=
Rachel Lee70f7b692023-11-22 11:24:02 -0800852 scheduler::LayerInfo::FrameRateSelectionStrategy::Self;
Rachel Leea021bb02023-11-20 21:51:09 -0800853 if ((!requested.requestedFrameRate.isValid() && propagationAllowed) ||
854 shouldOverrideChildren) {
Vishnu Nair30515cb2023-10-19 21:54:08 -0700855 snapshot.inheritedFrameRate = parentSnapshot.inheritedFrameRate;
856 } else {
857 snapshot.inheritedFrameRate = requested.requestedFrameRate;
858 }
859 // Set the framerate as the inherited frame rate and allow children to override it if
860 // needed.
861 snapshot.frameRate = snapshot.inheritedFrameRate;
Vishnu Nair52d56fd2023-07-20 17:02:43 +0000862 snapshot.changes |= RequestedLayerState::Changes::FrameRate;
Vishnu Naird47bcee2023-02-24 18:08:51 +0000863 }
864
Rachel Lee58cc90d2023-09-05 18:50:20 -0700865 if (forceUpdate || snapshot.clientChanges & layer_state_t::eFrameRateSelectionStrategyChanged) {
Rachel Leea021bb02023-11-20 21:51:09 -0800866 if (parentSnapshot.frameRateSelectionStrategy ==
867 scheduler::LayerInfo::FrameRateSelectionStrategy::OverrideChildren) {
868 snapshot.frameRateSelectionStrategy =
869 scheduler::LayerInfo::FrameRateSelectionStrategy::OverrideChildren;
870 } else {
871 const auto strategy = scheduler::LayerInfo::convertFrameRateSelectionStrategy(
872 requested.frameRateSelectionStrategy);
873 snapshot.frameRateSelectionStrategy = strategy;
874 }
Rachel Lee58cc90d2023-09-05 18:50:20 -0700875 }
876
Vishnu Nair3d8565a2023-06-30 07:23:24 +0000877 if (forceUpdate || snapshot.clientChanges & layer_state_t::eFrameRateSelectionPriority) {
878 snapshot.frameRateSelectionPriority =
879 (requested.frameRateSelectionPriority == Layer::PRIORITY_UNSET)
880 ? parentSnapshot.frameRateSelectionPriority
881 : requested.frameRateSelectionPriority;
882 }
883
Vishnu Naira02943f2023-06-03 13:44:46 -0700884 if (forceUpdate ||
885 snapshot.clientChanges &
886 (layer_state_t::eBackgroundBlurRadiusChanged | layer_state_t::eBlurRegionsChanged |
887 layer_state_t::eAlphaChanged)) {
Vishnu Nair80a5a702023-02-11 01:21:51 +0000888 snapshot.backgroundBlurRadius = args.supportsBlur
889 ? static_cast<int>(parentSnapshot.color.a * (float)requested.backgroundBlurRadius)
890 : 0;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000891 snapshot.blurRegions = requested.blurRegions;
Vishnu Nair80a5a702023-02-11 01:21:51 +0000892 for (auto& region : snapshot.blurRegions) {
893 region.alpha = region.alpha * snapshot.color.a;
894 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000895 }
896
Vishnu Naira02943f2023-06-03 13:44:46 -0700897 if (forceUpdate || snapshot.changes.any(RequestedLayerState::Changes::Geometry)) {
898 uint32_t primaryDisplayRotationFlags = getPrimaryDisplayRotationFlags(args.displays);
Vishnu Nairb76d99a2023-03-19 18:22:31 -0700899 updateLayerBounds(snapshot, requested, parentSnapshot, primaryDisplayRotationFlags);
Vishnu Naira02943f2023-06-03 13:44:46 -0700900 }
901
902 if (forceUpdate || snapshot.clientChanges & layer_state_t::eCornerRadiusChanged ||
Vishnu Nair0808ae62023-08-07 21:42:42 -0700903 snapshot.changes.any(RequestedLayerState::Changes::Geometry |
904 RequestedLayerState::Changes::BufferUsageFlags)) {
905 updateRoundedCorner(snapshot, requested, parentSnapshot, args);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000906 }
907
Vishnu Naira02943f2023-06-03 13:44:46 -0700908 if (forceUpdate || snapshot.clientChanges & layer_state_t::eShadowRadiusChanged ||
909 snapshot.changes.any(RequestedLayerState::Changes::Geometry)) {
910 updateShadows(snapshot, requested, args.globalShadowSettings);
911 }
912
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000913 if (forceUpdate ||
Vishnu Naira02943f2023-06-03 13:44:46 -0700914 snapshot.changes.any(RequestedLayerState::Changes::Geometry |
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000915 RequestedLayerState::Changes::Input)) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000916 updateInput(snapshot, requested, parentSnapshot, path, args);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000917 }
918
919 // computed snapshot properties
Alec Mouri994761f2023-08-04 21:50:55 +0000920 snapshot.forceClientComposition =
921 snapshot.shadowSettings.length > 0 || snapshot.stretchEffect.hasEffect();
Vishnu Nairc765c6c2023-02-23 00:08:01 +0000922 snapshot.contentOpaque = snapshot.isContentOpaque();
923 snapshot.isOpaque = snapshot.contentOpaque && !snapshot.roundedCorner.hasRoundedCorners() &&
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000924 snapshot.color.a == 1.f;
925 snapshot.blendMode = getBlendMode(snapshot, requested);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000926 LLOGV(snapshot.sequence,
Vishnu Nair92990e22023-02-24 20:01:05 +0000927 "%supdated %s changes:%s parent:%s requested:%s requested:%s from parent %s",
928 args.forceUpdate == ForceUpdateFlags::ALL ? "Force " : "",
929 snapshot.getDebugString().c_str(), snapshot.changes.string().c_str(),
930 parentSnapshot.changes.string().c_str(), requested.changes.string().c_str(),
931 std::to_string(requested.what).c_str(), parentSnapshot.getDebugString().c_str());
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000932}
933
934void LayerSnapshotBuilder::updateRoundedCorner(LayerSnapshot& snapshot,
935 const RequestedLayerState& requested,
Vishnu Nair0808ae62023-08-07 21:42:42 -0700936 const LayerSnapshot& parentSnapshot,
937 const Args& args) {
938 if (args.skipRoundCornersWhenProtected && requested.isProtected()) {
939 snapshot.roundedCorner = RoundedCornerState();
940 return;
941 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000942 snapshot.roundedCorner = RoundedCornerState();
943 RoundedCornerState parentRoundedCorner;
944 if (parentSnapshot.roundedCorner.hasRoundedCorners()) {
945 parentRoundedCorner = parentSnapshot.roundedCorner;
946 ui::Transform t = snapshot.localTransform.inverse();
947 parentRoundedCorner.cropRect = t.transform(parentRoundedCorner.cropRect);
948 parentRoundedCorner.radius.x *= t.getScaleX();
949 parentRoundedCorner.radius.y *= t.getScaleY();
950 }
951
952 FloatRect layerCropRect = snapshot.croppedBufferSize.toFloatRect();
953 const vec2 radius(requested.cornerRadius, requested.cornerRadius);
954 RoundedCornerState layerSettings(layerCropRect, radius);
955 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && !layerCropRect.isEmpty();
956 const bool parentRoundedCornerValid = parentRoundedCorner.hasRoundedCorners();
957 if (layerSettingsValid && parentRoundedCornerValid) {
958 // If the parent and the layer have rounded corner settings, use the parent settings if
959 // the parent crop is entirely inside the layer crop. This has limitations and cause
960 // rendering artifacts. See b/200300845 for correct fix.
961 if (parentRoundedCorner.cropRect.left > layerCropRect.left &&
962 parentRoundedCorner.cropRect.top > layerCropRect.top &&
963 parentRoundedCorner.cropRect.right < layerCropRect.right &&
964 parentRoundedCorner.cropRect.bottom < layerCropRect.bottom) {
965 snapshot.roundedCorner = parentRoundedCorner;
966 } else {
967 snapshot.roundedCorner = layerSettings;
968 }
969 } else if (layerSettingsValid) {
970 snapshot.roundedCorner = layerSettings;
971 } else if (parentRoundedCornerValid) {
972 snapshot.roundedCorner = parentRoundedCorner;
973 }
974}
975
976void LayerSnapshotBuilder::updateLayerBounds(LayerSnapshot& snapshot,
977 const RequestedLayerState& requested,
978 const LayerSnapshot& parentSnapshot,
Vishnu Nairb76d99a2023-03-19 18:22:31 -0700979 uint32_t primaryDisplayRotationFlags) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000980 snapshot.geomLayerTransform = parentSnapshot.geomLayerTransform * snapshot.localTransform;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000981 const bool transformWasInvalid = snapshot.invalidTransform;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000982 snapshot.invalidTransform = !LayerSnapshot::isTransformValid(snapshot.geomLayerTransform);
983 if (snapshot.invalidTransform) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000984 auto& t = snapshot.geomLayerTransform;
985 auto& requestedT = requested.requestedTransform;
986 std::string transformDebug =
987 base::StringPrintf(" transform={%f,%f,%f,%f} requestedTransform={%f,%f,%f,%f}",
988 t.dsdx(), t.dsdy(), t.dtdx(), t.dtdy(), requestedT.dsdx(),
989 requestedT.dsdy(), requestedT.dtdx(), requestedT.dtdy());
990 std::string bufferDebug;
991 if (requested.externalTexture) {
Vishnu Nairb76d99a2023-03-19 18:22:31 -0700992 auto unRotBuffer = requested.getUnrotatedBufferSize(primaryDisplayRotationFlags);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000993 auto& destFrame = requested.destinationFrame;
994 bufferDebug = base::StringPrintf(" buffer={%d,%d} displayRot=%d"
995 " destFrame={%d,%d,%d,%d} unRotBuffer={%d,%d}",
996 requested.externalTexture->getWidth(),
997 requested.externalTexture->getHeight(),
Vishnu Nairb76d99a2023-03-19 18:22:31 -0700998 primaryDisplayRotationFlags, destFrame.left,
999 destFrame.top, destFrame.right, destFrame.bottom,
Vishnu Naircfb2d252023-01-19 04:44:02 +00001000 unRotBuffer.getHeight(), unRotBuffer.getWidth());
1001 }
1002 ALOGW("Resetting transform for %s because it is invalid.%s%s",
1003 snapshot.getDebugString().c_str(), transformDebug.c_str(), bufferDebug.c_str());
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001004 snapshot.geomLayerTransform.reset();
1005 }
Vishnu Naircfb2d252023-01-19 04:44:02 +00001006 if (transformWasInvalid != snapshot.invalidTransform) {
1007 // If transform is invalid, the layer will be hidden.
1008 mResortSnapshots = true;
1009 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001010 snapshot.geomInverseLayerTransform = snapshot.geomLayerTransform.inverse();
1011
1012 FloatRect parentBounds = parentSnapshot.geomLayerBounds;
1013 parentBounds = snapshot.localTransform.inverse().transform(parentBounds);
1014 snapshot.geomLayerBounds =
1015 (requested.externalTexture) ? snapshot.bufferSize.toFloatRect() : parentBounds;
1016 if (!requested.crop.isEmpty()) {
1017 snapshot.geomLayerBounds = snapshot.geomLayerBounds.intersect(requested.crop.toFloatRect());
1018 }
1019 snapshot.geomLayerBounds = snapshot.geomLayerBounds.intersect(parentBounds);
1020 snapshot.transformedBounds = snapshot.geomLayerTransform.transform(snapshot.geomLayerBounds);
Vishnu Naircfb2d252023-01-19 04:44:02 +00001021 const Rect geomLayerBoundsWithoutTransparentRegion =
1022 RequestedLayerState::reduce(Rect(snapshot.geomLayerBounds),
1023 requested.transparentRegion);
1024 snapshot.transformedBoundsWithoutTransparentRegion =
1025 snapshot.geomLayerTransform.transform(geomLayerBoundsWithoutTransparentRegion);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001026 snapshot.parentTransform = parentSnapshot.geomLayerTransform;
1027
1028 // Subtract the transparent region and snap to the bounds
Vishnu Naircfb2d252023-01-19 04:44:02 +00001029 const Rect bounds =
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001030 RequestedLayerState::reduce(snapshot.croppedBufferSize, requested.transparentRegion);
Vishnu Naircfb2d252023-01-19 04:44:02 +00001031 if (requested.potentialCursor) {
1032 snapshot.cursorFrame = snapshot.geomLayerTransform.transform(bounds);
1033 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001034}
1035
Vishnu Naira02943f2023-06-03 13:44:46 -07001036void LayerSnapshotBuilder::updateShadows(LayerSnapshot& snapshot, const RequestedLayerState&,
Vishnu Naird9e4f462023-10-06 04:05:45 +00001037 const ShadowSettings& globalShadowSettings) {
1038 if (snapshot.shadowSettings.length > 0.f) {
1039 snapshot.shadowSettings.ambientColor = globalShadowSettings.ambientColor;
1040 snapshot.shadowSettings.spotColor = globalShadowSettings.spotColor;
1041 snapshot.shadowSettings.lightPos = globalShadowSettings.lightPos;
1042 snapshot.shadowSettings.lightRadius = globalShadowSettings.lightRadius;
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001043
1044 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
1045 // it if transparent regions are present. This may not be necessary since shadows are
1046 // typically cast by layers without transparent regions.
1047 snapshot.shadowSettings.boundaries = snapshot.geomLayerBounds;
1048
1049 // If the casting layer is translucent, we need to fill in the shadow underneath the
1050 // layer. Otherwise the generated shadow will only be shown around the casting layer.
1051 snapshot.shadowSettings.casterIsTranslucent =
1052 !snapshot.isContentOpaque() || (snapshot.alpha < 1.0f);
1053 snapshot.shadowSettings.ambientColor *= snapshot.alpha;
1054 snapshot.shadowSettings.spotColor *= snapshot.alpha;
1055 }
1056}
1057
1058void LayerSnapshotBuilder::updateInput(LayerSnapshot& snapshot,
1059 const RequestedLayerState& requested,
1060 const LayerSnapshot& parentSnapshot,
Vishnu Naircfb2d252023-01-19 04:44:02 +00001061 const LayerHierarchy::TraversalPath& path,
1062 const Args& args) {
Prabir Pradhancf359192024-03-20 00:42:57 +00001063 using InputConfig = gui::WindowInfo::InputConfig;
1064
Vishnu Naircfb2d252023-01-19 04:44:02 +00001065 if (requested.windowInfoHandle) {
1066 snapshot.inputInfo = *requested.windowInfoHandle->getInfo();
1067 } else {
1068 snapshot.inputInfo = {};
Vishnu Nair40d02282023-02-28 21:11:40 +00001069 // b/271132344 revisit this and see if we can always use the layers uid/pid
1070 snapshot.inputInfo.name = requested.name;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00001071 snapshot.inputInfo.ownerUid = gui::Uid{requested.ownerUid};
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00001072 snapshot.inputInfo.ownerPid = gui::Pid{requested.ownerPid};
Vishnu Naircfb2d252023-01-19 04:44:02 +00001073 }
Vishnu Nair29354ec2023-03-28 18:51:28 -07001074 snapshot.touchCropId = requested.touchCropId;
Vishnu Naircfb2d252023-01-19 04:44:02 +00001075
Vishnu Nair93b8b792023-02-27 19:40:24 +00001076 snapshot.inputInfo.id = static_cast<int32_t>(snapshot.uniqueSequence);
Linnan Li13bf76a2024-05-05 19:18:02 +08001077 snapshot.inputInfo.displayId =
1078 ui::LogicalDisplayId{static_cast<int32_t>(snapshot.outputFilter.layerStack.id)};
Vishnu Nairf13c8982023-12-02 11:26:09 -08001079 snapshot.inputInfo.touchOcclusionMode = requested.hasInputInfo()
1080 ? requested.windowInfoHandle->getInfo()->touchOcclusionMode
1081 : parentSnapshot.inputInfo.touchOcclusionMode;
Vishnu Nair59a6be32024-01-29 10:26:21 -08001082 snapshot.inputInfo.canOccludePresentation = parentSnapshot.inputInfo.canOccludePresentation ||
1083 (requested.flags & layer_state_t::eCanOccludePresentation);
Vishnu Nairf13c8982023-12-02 11:26:09 -08001084 if (requested.dropInputMode == gui::DropInputMode::ALL ||
1085 parentSnapshot.dropInputMode == gui::DropInputMode::ALL) {
1086 snapshot.dropInputMode = gui::DropInputMode::ALL;
1087 } else if (requested.dropInputMode == gui::DropInputMode::OBSCURED ||
1088 parentSnapshot.dropInputMode == gui::DropInputMode::OBSCURED) {
1089 snapshot.dropInputMode = gui::DropInputMode::OBSCURED;
1090 } else {
1091 snapshot.dropInputMode = gui::DropInputMode::NONE;
1092 }
1093
Prabir Pradhancf359192024-03-20 00:42:57 +00001094 if (snapshot.isSecure ||
Arpit Singh490ccc92024-04-30 14:26:21 +00001095 parentSnapshot.inputInfo.inputConfig.test(InputConfig::SENSITIVE_FOR_PRIVACY)) {
1096 snapshot.inputInfo.inputConfig |= InputConfig::SENSITIVE_FOR_PRIVACY;
Prabir Pradhancf359192024-03-20 00:42:57 +00001097 }
1098
Vishnu Nair29354ec2023-03-28 18:51:28 -07001099 updateVisibility(snapshot, snapshot.isVisible);
Vishnu Naircfb2d252023-01-19 04:44:02 +00001100 if (!needsInputInfo(snapshot, requested)) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001101 return;
1102 }
1103
Vishnu Naircfb2d252023-01-19 04:44:02 +00001104 static frontend::DisplayInfo sDefaultInfo = {.isSecure = false};
1105 const std::optional<frontend::DisplayInfo> displayInfoOpt =
1106 args.displays.get(snapshot.outputFilter.layerStack);
1107 bool noValidDisplay = !displayInfoOpt.has_value();
1108 auto displayInfo = displayInfoOpt.value_or(sDefaultInfo);
1109
1110 if (!requested.windowInfoHandle) {
Prabir Pradhancf359192024-03-20 00:42:57 +00001111 snapshot.inputInfo.inputConfig = InputConfig::NO_INPUT_CHANNEL;
Vishnu Naircfb2d252023-01-19 04:44:02 +00001112 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001113 fillInputFrameInfo(snapshot.inputInfo, displayInfo.transform, snapshot);
1114
1115 if (noValidDisplay) {
1116 // Do not let the window receive touches if it is not associated with a valid display
1117 // transform. We still allow the window to receive keys and prevent ANRs.
Prabir Pradhancf359192024-03-20 00:42:57 +00001118 snapshot.inputInfo.inputConfig |= InputConfig::NOT_TOUCHABLE;
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001119 }
1120
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001121 snapshot.inputInfo.alpha = snapshot.color.a;
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001122
1123 handleDropInputMode(snapshot, parentSnapshot);
1124
1125 // If the window will be blacked out on a display because the display does not have the secure
1126 // flag and the layer has the secure flag set, then drop input.
1127 if (!displayInfo.isSecure && snapshot.isSecure) {
Prabir Pradhancf359192024-03-20 00:42:57 +00001128 snapshot.inputInfo.inputConfig |= InputConfig::DROP_INPUT;
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001129 }
1130
Vishnu Naira02943f2023-06-03 13:44:46 -07001131 if (requested.touchCropId != UNASSIGNED_LAYER_ID || path.isClone()) {
Vishnu Nair29354ec2023-03-28 18:51:28 -07001132 mNeedsTouchableRegionCrop.insert(path);
Vishnu Naira02943f2023-06-03 13:44:46 -07001133 }
1134 auto cropLayerSnapshot = getSnapshot(requested.touchCropId);
1135 if (!cropLayerSnapshot && snapshot.inputInfo.replaceTouchableRegionWithCrop) {
Vishnu Nair29354ec2023-03-28 18:51:28 -07001136 FloatRect inputBounds = getInputBounds(snapshot, /*fillParentBounds=*/true).first;
Vishnu Nairfed7c122023-03-18 01:54:43 +00001137 Rect inputBoundsInDisplaySpace =
Vishnu Nair29354ec2023-03-28 18:51:28 -07001138 getInputBoundsInDisplaySpace(snapshot, inputBounds, displayInfo.transform);
1139 snapshot.inputInfo.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001140 }
1141
1142 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
1143 // if it was set by WM for a known system overlay
Vishnu Nair9e0017e2024-05-22 19:02:44 +00001144 if (snapshot.trustedOverlay == gui::TrustedOverlay::ENABLED) {
Prabir Pradhancf359192024-03-20 00:42:57 +00001145 snapshot.inputInfo.inputConfig |= InputConfig::TRUSTED_OVERLAY;
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001146 }
1147
Vishnu Nair494a2e42023-11-10 17:21:19 -08001148 snapshot.inputInfo.contentSize = snapshot.croppedBufferSize.getSize();
1149
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001150 // If the layer is a clone, we need to crop the input region to cloned root to prevent
1151 // touches from going outside the cloned area.
1152 if (path.isClone()) {
Prabir Pradhancf359192024-03-20 00:42:57 +00001153 snapshot.inputInfo.inputConfig |= InputConfig::CLONE;
Vishnu Nair444f3952023-04-11 13:01:02 -07001154 // Cloned layers shouldn't handle watch outside since their z order is not determined by
1155 // WM or the client.
Prabir Pradhancf359192024-03-20 00:42:57 +00001156 snapshot.inputInfo.inputConfig.clear(InputConfig::WATCH_OUTSIDE_TOUCH);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001157 }
1158}
1159
1160std::vector<std::unique_ptr<LayerSnapshot>>& LayerSnapshotBuilder::getSnapshots() {
1161 return mSnapshots;
1162}
1163
Vishnu Naircfb2d252023-01-19 04:44:02 +00001164void LayerSnapshotBuilder::forEachVisibleSnapshot(const ConstVisitor& visitor) const {
1165 for (int i = 0; i < mNumInterestingSnapshots; i++) {
1166 LayerSnapshot& snapshot = *mSnapshots[(size_t)i];
1167 if (!snapshot.isVisible) continue;
1168 visitor(snapshot);
1169 }
1170}
1171
Vishnu Nair3af0ec02023-02-10 04:13:48 +00001172// Visit each visible snapshot in z-order
1173void LayerSnapshotBuilder::forEachVisibleSnapshot(const ConstVisitor& visitor,
1174 const LayerHierarchy& root) const {
1175 root.traverseInZOrder(
1176 [this, visitor](const LayerHierarchy&,
1177 const LayerHierarchy::TraversalPath& traversalPath) -> bool {
1178 LayerSnapshot* snapshot = getSnapshot(traversalPath);
1179 if (snapshot && snapshot->isVisible) {
1180 visitor(*snapshot);
1181 }
1182 return true;
1183 });
1184}
1185
Vishnu Naircfb2d252023-01-19 04:44:02 +00001186void LayerSnapshotBuilder::forEachVisibleSnapshot(const Visitor& visitor) {
1187 for (int i = 0; i < mNumInterestingSnapshots; i++) {
1188 std::unique_ptr<LayerSnapshot>& snapshot = mSnapshots.at((size_t)i);
1189 if (!snapshot->isVisible) continue;
1190 visitor(snapshot);
1191 }
1192}
1193
Nergi Rahardi0dfc0962024-05-23 06:57:36 +00001194void LayerSnapshotBuilder::forEachSnapshot(const Visitor& visitor,
1195 const ConstPredicate& predicate) {
1196 for (int i = 0; i < mNumInterestingSnapshots; i++) {
1197 std::unique_ptr<LayerSnapshot>& snapshot = mSnapshots.at((size_t)i);
1198 if (!predicate(*snapshot)) continue;
1199 visitor(snapshot);
1200 }
1201}
1202
Vishnu Naircfb2d252023-01-19 04:44:02 +00001203void LayerSnapshotBuilder::forEachInputSnapshot(const ConstVisitor& visitor) const {
1204 for (int i = mNumInterestingSnapshots - 1; i >= 0; i--) {
1205 LayerSnapshot& snapshot = *mSnapshots[(size_t)i];
1206 if (!snapshot.hasInputInfo()) continue;
1207 visitor(snapshot);
1208 }
1209}
1210
Vishnu Nair29354ec2023-03-28 18:51:28 -07001211void LayerSnapshotBuilder::updateTouchableRegionCrop(const Args& args) {
1212 if (mNeedsTouchableRegionCrop.empty()) {
1213 return;
1214 }
1215
1216 static constexpr ftl::Flags<RequestedLayerState::Changes> AFFECTS_INPUT =
1217 RequestedLayerState::Changes::Visibility | RequestedLayerState::Changes::Created |
1218 RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Geometry |
1219 RequestedLayerState::Changes::Input;
1220
1221 if (args.forceUpdate != ForceUpdateFlags::ALL &&
Vishnu Naira02943f2023-06-03 13:44:46 -07001222 !args.layerLifecycleManager.getGlobalChanges().any(AFFECTS_INPUT) && !args.displayChanges) {
Vishnu Nair29354ec2023-03-28 18:51:28 -07001223 return;
1224 }
1225
1226 for (auto& path : mNeedsTouchableRegionCrop) {
1227 frontend::LayerSnapshot* snapshot = getSnapshot(path);
1228 if (!snapshot) {
1229 continue;
1230 }
Vishnu Naira02943f2023-06-03 13:44:46 -07001231 LLOGV(snapshot->sequence, "updateTouchableRegionCrop=%s",
1232 snapshot->getDebugString().c_str());
Vishnu Nair29354ec2023-03-28 18:51:28 -07001233 const std::optional<frontend::DisplayInfo> displayInfoOpt =
1234 args.displays.get(snapshot->outputFilter.layerStack);
1235 static frontend::DisplayInfo sDefaultInfo = {.isSecure = false};
1236 auto displayInfo = displayInfoOpt.value_or(sDefaultInfo);
1237
1238 bool needsUpdate =
1239 args.forceUpdate == ForceUpdateFlags::ALL || snapshot->changes.any(AFFECTS_INPUT);
1240 auto cropLayerSnapshot = getSnapshot(snapshot->touchCropId);
1241 needsUpdate =
1242 needsUpdate || (cropLayerSnapshot && cropLayerSnapshot->changes.any(AFFECTS_INPUT));
1243 auto clonedRootSnapshot = path.isClone() ? getSnapshot(snapshot->mirrorRootPath) : nullptr;
1244 needsUpdate = needsUpdate ||
1245 (clonedRootSnapshot && clonedRootSnapshot->changes.any(AFFECTS_INPUT));
1246
1247 if (!needsUpdate) {
1248 continue;
1249 }
1250
1251 if (snapshot->inputInfo.replaceTouchableRegionWithCrop) {
1252 Rect inputBoundsInDisplaySpace;
1253 if (!cropLayerSnapshot) {
1254 FloatRect inputBounds = getInputBounds(*snapshot, /*fillParentBounds=*/true).first;
1255 inputBoundsInDisplaySpace =
1256 getInputBoundsInDisplaySpace(*snapshot, inputBounds, displayInfo.transform);
1257 } else {
1258 FloatRect inputBounds =
1259 getInputBounds(*cropLayerSnapshot, /*fillParentBounds=*/true).first;
1260 inputBoundsInDisplaySpace =
1261 getInputBoundsInDisplaySpace(*cropLayerSnapshot, inputBounds,
1262 displayInfo.transform);
1263 }
1264 snapshot->inputInfo.touchableRegion = Region(inputBoundsInDisplaySpace);
1265 } else if (cropLayerSnapshot) {
1266 FloatRect inputBounds =
1267 getInputBounds(*cropLayerSnapshot, /*fillParentBounds=*/true).first;
1268 Rect inputBoundsInDisplaySpace =
1269 getInputBoundsInDisplaySpace(*cropLayerSnapshot, inputBounds,
1270 displayInfo.transform);
Chavi Weingarten1ba381e2024-01-09 21:54:11 +00001271 snapshot->inputInfo.touchableRegion =
1272 snapshot->inputInfo.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair29354ec2023-03-28 18:51:28 -07001273 }
1274
1275 // If the layer is a clone, we need to crop the input region to cloned root to prevent
1276 // touches from going outside the cloned area.
1277 if (clonedRootSnapshot) {
1278 const Rect rect =
1279 displayInfo.transform.transform(Rect{clonedRootSnapshot->transformedBounds});
1280 snapshot->inputInfo.touchableRegion =
1281 snapshot->inputInfo.touchableRegion.intersect(rect);
1282 }
1283 }
1284}
1285
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001286} // namespace android::surfaceflinger::frontend