blob: 87706d84911b03c9fb330925a9562986e9914817 [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) {
259 snapshot.isVisible = visible;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000260
261 // TODO(b/238781169) we are ignoring this compat for now, since we will have
262 // to remove any optimization based on visibility.
263
264 // For compatibility reasons we let layers which can receive input
265 // receive input before they have actually submitted a buffer. Because
266 // of this we use canReceiveInput instead of isVisible to check the
267 // policy-visibility, ignoring the buffer state. However for layers with
268 // hasInputInfo()==false we can use the real visibility state.
269 // We are just using these layers for occlusion detection in
270 // InputDispatcher, and obviously if they aren't visible they can't occlude
271 // anything.
Vishnu Nair80a5a702023-02-11 01:21:51 +0000272 const bool visibleForInput =
Vishnu Nair40d02282023-02-28 21:11:40 +0000273 snapshot.hasInputInfo() ? snapshot.canReceiveInput() : snapshot.isVisible;
Vishnu Nair80a5a702023-02-11 01:21:51 +0000274 snapshot.inputInfo.setInputConfig(gui::WindowInfo::InputConfig::NOT_VISIBLE, !visibleForInput);
Vishnu Naira02943f2023-06-03 13:44:46 -0700275 LLOGV(snapshot.sequence, "updating visibility %s %s", visible ? "true" : "false",
276 snapshot.getDebugString().c_str());
Vishnu Naircfb2d252023-01-19 04:44:02 +0000277}
278
279bool needsInputInfo(const LayerSnapshot& snapshot, const RequestedLayerState& requested) {
280 if (requested.potentialCursor) {
281 return false;
282 }
283
284 if (snapshot.inputInfo.token != nullptr) {
285 return true;
286 }
287
288 if (snapshot.hasBufferOrSidebandStream()) {
289 return true;
290 }
291
292 return requested.windowInfoHandle &&
293 requested.windowInfoHandle->getInfo()->inputConfig.test(
294 gui::WindowInfo::InputConfig::NO_INPUT_CHANNEL);
295}
296
Vishnu Nairc765c6c2023-02-23 00:08:01 +0000297void updateMetadata(LayerSnapshot& snapshot, const RequestedLayerState& requested,
298 const LayerSnapshotBuilder::Args& args) {
299 snapshot.metadata.clear();
300 for (const auto& [key, mandatory] : args.supportedLayerGenericMetadata) {
301 auto compatIter = args.genericLayerMetadataKeyMap.find(key);
302 if (compatIter == std::end(args.genericLayerMetadataKeyMap)) {
303 continue;
304 }
305 const uint32_t id = compatIter->second;
306 auto it = requested.metadata.mMap.find(id);
307 if (it == std::end(requested.metadata.mMap)) {
308 continue;
309 }
310
311 snapshot.metadata.emplace(key,
312 compositionengine::GenericLayerMetadataEntry{mandatory,
313 it->second});
314 }
315}
316
Garfield Tan8eb8f352024-05-17 09:12:01 -0700317void updateMetadataAndGameMode(LayerSnapshot& snapshot, const RequestedLayerState& requested,
318 const LayerSnapshotBuilder::Args& args,
319 const LayerSnapshot& parentSnapshot) {
320 if (snapshot.changes.test(RequestedLayerState::Changes::GameMode)) {
321 snapshot.gameMode = requested.metadata.has(gui::METADATA_GAME_MODE)
322 ? requested.gameMode
323 : parentSnapshot.gameMode;
324 }
325 updateMetadata(snapshot, requested, args);
326 if (args.includeMetadata) {
327 snapshot.layerMetadata = parentSnapshot.layerMetadata;
328 snapshot.layerMetadata.merge(requested.metadata);
329 }
330}
331
Vishnu Naircfb2d252023-01-19 04:44:02 +0000332void clearChanges(LayerSnapshot& snapshot) {
333 snapshot.changes.clear();
Vishnu Naira02943f2023-06-03 13:44:46 -0700334 snapshot.clientChanges = 0;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000335 snapshot.contentDirty = false;
336 snapshot.hasReadyFrame = false;
337 snapshot.sidebandStreamHasFrame = false;
338 snapshot.surfaceDamage.clear();
339}
340
Vishnu Naira02943f2023-06-03 13:44:46 -0700341// TODO (b/259407931): Remove.
342uint32_t getPrimaryDisplayRotationFlags(
343 const ui::DisplayMap<ui::LayerStack, frontend::DisplayInfo>& displays) {
344 for (auto& [_, display] : displays) {
345 if (display.isPrimary) {
346 return display.rotationFlags;
347 }
348 }
349 return 0;
350}
351
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000352} // namespace
353
354LayerSnapshot LayerSnapshotBuilder::getRootSnapshot() {
355 LayerSnapshot snapshot;
Vishnu Nair92990e22023-02-24 20:01:05 +0000356 snapshot.path = LayerHierarchy::TraversalPath::ROOT;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000357 snapshot.changes = ftl::Flags<RequestedLayerState::Changes>();
Vishnu Naira02943f2023-06-03 13:44:46 -0700358 snapshot.clientChanges = 0;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000359 snapshot.isHiddenByPolicyFromParent = false;
360 snapshot.isHiddenByPolicyFromRelativeParent = false;
361 snapshot.parentTransform.reset();
362 snapshot.geomLayerTransform.reset();
363 snapshot.geomInverseLayerTransform.reset();
364 snapshot.geomLayerBounds = getMaxDisplayBounds({});
365 snapshot.roundedCorner = RoundedCornerState();
366 snapshot.stretchEffect = {};
367 snapshot.outputFilter.layerStack = ui::DEFAULT_LAYER_STACK;
368 snapshot.outputFilter.toInternalDisplay = false;
369 snapshot.isSecure = false;
370 snapshot.color.a = 1.0_hf;
371 snapshot.colorTransformIsIdentity = true;
Vishnu Naird9e4f462023-10-06 04:05:45 +0000372 snapshot.shadowSettings.length = 0.f;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000373 snapshot.layerMetadata.mMap.clear();
374 snapshot.relativeLayerMetadata.mMap.clear();
375 snapshot.inputInfo.touchOcclusionMode = gui::TouchOcclusionMode::BLOCK_UNTRUSTED;
376 snapshot.dropInputMode = gui::DropInputMode::NONE;
Vishnu Nair9e0017e2024-05-22 19:02:44 +0000377 snapshot.trustedOverlay = gui::TrustedOverlay::UNSET;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000378 snapshot.gameMode = gui::GameMode::Unsupported;
379 snapshot.frameRate = {};
380 snapshot.fixedTransformHint = ui::Transform::ROT_INVALID;
Vishnu Nair422b81c2024-05-16 05:44:28 +0000381 snapshot.ignoreLocalTransform = false;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000382 return snapshot;
383}
384
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000385LayerSnapshotBuilder::LayerSnapshotBuilder() {}
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000386
387LayerSnapshotBuilder::LayerSnapshotBuilder(Args args) : LayerSnapshotBuilder() {
Vishnu Naird47bcee2023-02-24 18:08:51 +0000388 args.forceUpdate = ForceUpdateFlags::ALL;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000389 updateSnapshots(args);
390}
391
392bool LayerSnapshotBuilder::tryFastUpdate(const Args& args) {
Vishnu Naira02943f2023-06-03 13:44:46 -0700393 const bool forceUpdate = args.forceUpdate != ForceUpdateFlags::NONE;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000394
Vishnu Naira02943f2023-06-03 13:44:46 -0700395 if (args.layerLifecycleManager.getGlobalChanges().get() == 0 && !forceUpdate &&
396 !args.displayChanges) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000397 return true;
398 }
399
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000400 // There are only content changes which do not require any child layer snapshots to be updated.
401 ALOGV("%s", __func__);
402 ATRACE_NAME("FastPath");
403
Vishnu Naira02943f2023-06-03 13:44:46 -0700404 uint32_t primaryDisplayRotationFlags = getPrimaryDisplayRotationFlags(args.displays);
405 if (forceUpdate || args.displayChanges) {
406 for (auto& snapshot : mSnapshots) {
407 const RequestedLayerState* requested =
408 args.layerLifecycleManager.getLayerFromId(snapshot->path.id);
409 if (!requested) continue;
410 snapshot->merge(*requested, forceUpdate, args.displayChanges, args.forceFullDamage,
411 primaryDisplayRotationFlags);
412 }
413 return false;
414 }
415
416 // Walk through all the updated requested layer states and update the corresponding snapshots.
417 for (const RequestedLayerState* requested : args.layerLifecycleManager.getChangedLayers()) {
418 auto range = mIdToSnapshots.equal_range(requested->id);
419 for (auto it = range.first; it != range.second; it++) {
420 it->second->merge(*requested, forceUpdate, args.displayChanges, args.forceFullDamage,
421 primaryDisplayRotationFlags);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000422 }
423 }
424
Vishnu Naira02943f2023-06-03 13:44:46 -0700425 if ((args.layerLifecycleManager.getGlobalChanges().get() &
426 ~(RequestedLayerState::Changes::Content | RequestedLayerState::Changes::Buffer).get()) !=
427 0) {
428 // We have changes that require us to walk the hierarchy and update child layers.
429 // No fast path for you.
430 return false;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000431 }
432 return true;
433}
434
435void LayerSnapshotBuilder::updateSnapshots(const Args& args) {
436 ATRACE_NAME("UpdateSnapshots");
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000437 LayerSnapshot rootSnapshot = args.rootSnapshot;
Vishnu Nair3af0ec02023-02-10 04:13:48 +0000438 if (args.parentCrop) {
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000439 rootSnapshot.geomLayerBounds = *args.parentCrop;
Vishnu Naird47bcee2023-02-24 18:08:51 +0000440 } else if (args.forceUpdate == ForceUpdateFlags::ALL || args.displayChanges) {
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000441 rootSnapshot.geomLayerBounds = getMaxDisplayBounds(args.displays);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000442 }
443 if (args.displayChanges) {
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000444 rootSnapshot.changes = RequestedLayerState::Changes::AffectsChildren |
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000445 RequestedLayerState::Changes::Geometry;
446 }
Vishnu Naird47bcee2023-02-24 18:08:51 +0000447 if (args.forceUpdate == ForceUpdateFlags::HIERARCHY) {
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000448 rootSnapshot.changes |=
Vishnu Naird47bcee2023-02-24 18:08:51 +0000449 RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Visibility;
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000450 rootSnapshot.clientChanges |= layer_state_t::eReparent;
Vishnu Naird47bcee2023-02-24 18:08:51 +0000451 }
Vishnu Naira02943f2023-06-03 13:44:46 -0700452
453 for (auto& snapshot : mSnapshots) {
454 if (snapshot->reachablilty == LayerSnapshot::Reachablilty::Reachable) {
455 snapshot->reachablilty = LayerSnapshot::Reachablilty::Unreachable;
456 }
457 }
458
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000459 LayerHierarchy::TraversalPath root = LayerHierarchy::TraversalPath::ROOT;
Vishnu Naird47bcee2023-02-24 18:08:51 +0000460 if (args.root.getLayer()) {
461 // The hierarchy can have a root layer when used for screenshots otherwise, it will have
462 // multiple children.
463 LayerHierarchy::ScopedAddToTraversalPath addChildToPath(root, args.root.getLayer()->id,
464 LayerHierarchy::Variant::Attached);
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000465 updateSnapshotsInHierarchy(args, args.root, root, rootSnapshot, /*depth=*/0);
Vishnu Naird47bcee2023-02-24 18:08:51 +0000466 } else {
467 for (auto& [childHierarchy, variant] : args.root.mChildren) {
468 LayerHierarchy::ScopedAddToTraversalPath addChildToPath(root,
469 childHierarchy->getLayer()->id,
470 variant);
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000471 updateSnapshotsInHierarchy(args, *childHierarchy, root, rootSnapshot, /*depth=*/0);
Vishnu Naird47bcee2023-02-24 18:08:51 +0000472 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000473 }
474
Vishnu Nair29354ec2023-03-28 18:51:28 -0700475 // Update touchable region crops outside the main update pass. This is because a layer could be
476 // cropped by any other layer and it requires both snapshots to be updated.
477 updateTouchableRegionCrop(args);
478
Vishnu Nairfccd6362023-02-24 23:39:53 +0000479 const bool hasUnreachableSnapshots = sortSnapshotsByZ(args);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000480
Vishnu Nair29354ec2023-03-28 18:51:28 -0700481 // Destroy unreachable snapshots for clone layers. And destroy snapshots for non-clone
482 // layers if the layer have been destroyed.
483 // TODO(b/238781169) consider making clone layer ids stable as well
484 if (!hasUnreachableSnapshots && args.layerLifecycleManager.getDestroyedLayers().empty()) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000485 return;
486 }
487
Vishnu Nair29354ec2023-03-28 18:51:28 -0700488 std::unordered_set<uint32_t> destroyedLayerIds;
489 for (auto& destroyedLayer : args.layerLifecycleManager.getDestroyedLayers()) {
490 destroyedLayerIds.insert(destroyedLayer->id);
491 }
492
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000493 auto it = mSnapshots.begin();
494 while (it < mSnapshots.end()) {
495 auto& traversalPath = it->get()->path;
Vishnu Naira02943f2023-06-03 13:44:46 -0700496 const bool unreachable =
497 it->get()->reachablilty == LayerSnapshot::Reachablilty::Unreachable;
498 const bool isClone = traversalPath.isClone();
499 const bool layerIsDestroyed =
500 destroyedLayerIds.find(traversalPath.id) != destroyedLayerIds.end();
501 const bool destroySnapshot = (unreachable && isClone) || layerIsDestroyed;
502
503 if (!destroySnapshot) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000504 it++;
505 continue;
506 }
507
Vishnu Naira02943f2023-06-03 13:44:46 -0700508 mPathToSnapshot.erase(traversalPath);
509
510 auto range = mIdToSnapshots.equal_range(traversalPath.id);
511 auto matchingSnapshot =
512 std::find_if(range.first, range.second, [&traversalPath](auto& snapshotWithId) {
513 return snapshotWithId.second->path == traversalPath;
514 });
515 mIdToSnapshots.erase(matchingSnapshot);
Vishnu Nair29354ec2023-03-28 18:51:28 -0700516 mNeedsTouchableRegionCrop.erase(traversalPath);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000517 mSnapshots.back()->globalZ = it->get()->globalZ;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000518 std::iter_swap(it, mSnapshots.end() - 1);
519 mSnapshots.erase(mSnapshots.end() - 1);
520 }
521}
522
523void LayerSnapshotBuilder::update(const Args& args) {
Vishnu Nair92990e22023-02-24 20:01:05 +0000524 for (auto& snapshot : mSnapshots) {
525 clearChanges(*snapshot);
526 }
527
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000528 if (tryFastUpdate(args)) {
529 return;
530 }
531 updateSnapshots(args);
532}
533
Vishnu Naircfb2d252023-01-19 04:44:02 +0000534const LayerSnapshot& LayerSnapshotBuilder::updateSnapshotsInHierarchy(
535 const Args& args, const LayerHierarchy& hierarchy,
Vishnu Naird1f74982023-06-15 20:16:51 -0700536 LayerHierarchy::TraversalPath& traversalPath, const LayerSnapshot& parentSnapshot,
537 int depth) {
Vishnu Nair606d9d02023-08-19 14:20:18 -0700538 LLOG_ALWAYS_FATAL_WITH_TRACE_IF(depth > 50,
539 "Cycle detected in LayerSnapshotBuilder. See "
540 "builder_stack_overflow_transactions.winscope");
Vishnu Naird1f74982023-06-15 20:16:51 -0700541
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000542 const RequestedLayerState* layer = hierarchy.getLayer();
Vishnu Naircfb2d252023-01-19 04:44:02 +0000543 LayerSnapshot* snapshot = getSnapshot(traversalPath);
544 const bool newSnapshot = snapshot == nullptr;
Vishnu Naira02943f2023-06-03 13:44:46 -0700545 uint32_t primaryDisplayRotationFlags = getPrimaryDisplayRotationFlags(args.displays);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000546 if (newSnapshot) {
Vishnu Nair92990e22023-02-24 20:01:05 +0000547 snapshot = createSnapshot(traversalPath, *layer, parentSnapshot);
Vishnu Naira02943f2023-06-03 13:44:46 -0700548 snapshot->merge(*layer, /*forceUpdate=*/true, /*displayChanges=*/true, args.forceFullDamage,
549 primaryDisplayRotationFlags);
550 snapshot->changes |= RequestedLayerState::Changes::Created;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000551 }
Vishnu Nair52d56fd2023-07-20 17:02:43 +0000552
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000553 if (traversalPath.isRelative()) {
554 bool parentIsRelative = traversalPath.variant == LayerHierarchy::Variant::Relative;
555 updateRelativeState(*snapshot, parentSnapshot, parentIsRelative, args);
556 } else {
557 if (traversalPath.isAttached()) {
558 resetRelativeState(*snapshot);
559 }
Vishnu Nair92990e22023-02-24 20:01:05 +0000560 updateSnapshot(*snapshot, args, *layer, parentSnapshot, traversalPath);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000561 }
562
563 for (auto& [childHierarchy, variant] : hierarchy.mChildren) {
564 LayerHierarchy::ScopedAddToTraversalPath addChildToPath(traversalPath,
565 childHierarchy->getLayer()->id,
566 variant);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000567 const LayerSnapshot& childSnapshot =
Vishnu Naird1f74982023-06-15 20:16:51 -0700568 updateSnapshotsInHierarchy(args, *childHierarchy, traversalPath, *snapshot,
569 depth + 1);
Vishnu Nair42b918e2023-07-18 20:05:29 +0000570 updateFrameRateFromChildSnapshot(*snapshot, childSnapshot, args);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000571 }
Vishnu Naird47bcee2023-02-24 18:08:51 +0000572
Vishnu Naircfb2d252023-01-19 04:44:02 +0000573 return *snapshot;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000574}
575
576LayerSnapshot* LayerSnapshotBuilder::getSnapshot(uint32_t layerId) const {
577 if (layerId == UNASSIGNED_LAYER_ID) {
578 return nullptr;
579 }
580 LayerHierarchy::TraversalPath path{.id = layerId};
581 return getSnapshot(path);
582}
583
584LayerSnapshot* LayerSnapshotBuilder::getSnapshot(const LayerHierarchy::TraversalPath& id) const {
Vishnu Naira02943f2023-06-03 13:44:46 -0700585 auto it = mPathToSnapshot.find(id);
586 return it == mPathToSnapshot.end() ? nullptr : it->second;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000587}
588
Vishnu Nair92990e22023-02-24 20:01:05 +0000589LayerSnapshot* LayerSnapshotBuilder::createSnapshot(const LayerHierarchy::TraversalPath& path,
590 const RequestedLayerState& layer,
591 const LayerSnapshot& parentSnapshot) {
592 mSnapshots.emplace_back(std::make_unique<LayerSnapshot>(layer, path));
Vishnu Naircfb2d252023-01-19 04:44:02 +0000593 LayerSnapshot* snapshot = mSnapshots.back().get();
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000594 snapshot->globalZ = static_cast<size_t>(mSnapshots.size()) - 1;
Vishnu Nair491827d2024-04-29 23:43:26 +0000595 if (path.isClone() && !LayerHierarchy::isMirror(path.variant)) {
Vishnu Nair92990e22023-02-24 20:01:05 +0000596 snapshot->mirrorRootPath = parentSnapshot.mirrorRootPath;
597 }
Vishnu Nair491827d2024-04-29 23:43:26 +0000598 snapshot->ignoreLocalTransform =
599 path.isClone() && path.variant == LayerHierarchy::Variant::Detached_Mirror;
Vishnu Naira02943f2023-06-03 13:44:46 -0700600 mPathToSnapshot[path] = snapshot;
601
602 mIdToSnapshots.emplace(path.id, snapshot);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000603 return snapshot;
604}
605
Vishnu Nairfccd6362023-02-24 23:39:53 +0000606bool LayerSnapshotBuilder::sortSnapshotsByZ(const Args& args) {
Vishnu Naird47bcee2023-02-24 18:08:51 +0000607 if (!mResortSnapshots && args.forceUpdate == ForceUpdateFlags::NONE &&
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000608 !args.layerLifecycleManager.getGlobalChanges().any(
Chavi Weingarten92c7d8c2024-01-19 23:25:45 +0000609 RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Visibility |
610 RequestedLayerState::Changes::Input)) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000611 // We are not force updating and there are no hierarchy or visibility changes. Avoid sorting
612 // the snapshots.
Vishnu Nairfccd6362023-02-24 23:39:53 +0000613 return false;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000614 }
Vishnu Naircfb2d252023-01-19 04:44:02 +0000615 mResortSnapshots = false;
616
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000617 size_t globalZ = 0;
618 args.root.traverseInZOrder(
619 [this, &globalZ](const LayerHierarchy&,
620 const LayerHierarchy::TraversalPath& traversalPath) -> bool {
621 LayerSnapshot* snapshot = getSnapshot(traversalPath);
622 if (!snapshot) {
Vishnu Naira02943f2023-06-03 13:44:46 -0700623 return true;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000624 }
625
Vishnu Naircfb2d252023-01-19 04:44:02 +0000626 if (snapshot->getIsVisible() || snapshot->hasInputInfo()) {
Vishnu Nair80a5a702023-02-11 01:21:51 +0000627 updateVisibility(*snapshot, snapshot->getIsVisible());
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000628 size_t oldZ = snapshot->globalZ;
629 size_t newZ = globalZ++;
630 snapshot->globalZ = newZ;
631 if (oldZ == newZ) {
632 return true;
633 }
634 mSnapshots[newZ]->globalZ = oldZ;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000635 LLOGV(snapshot->sequence, "Made visible z=%zu -> %zu %s", oldZ, newZ,
636 snapshot->getDebugString().c_str());
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000637 std::iter_swap(mSnapshots.begin() + static_cast<ssize_t>(oldZ),
638 mSnapshots.begin() + static_cast<ssize_t>(newZ));
639 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000640 return true;
641 });
Vishnu Naircfb2d252023-01-19 04:44:02 +0000642 mNumInterestingSnapshots = (int)globalZ;
Vishnu Nairfccd6362023-02-24 23:39:53 +0000643 bool hasUnreachableSnapshots = false;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000644 while (globalZ < mSnapshots.size()) {
645 mSnapshots[globalZ]->globalZ = globalZ;
Vishnu Nair80a5a702023-02-11 01:21:51 +0000646 /* mark unreachable snapshots as explicitly invisible */
647 updateVisibility(*mSnapshots[globalZ], false);
Vishnu Naira02943f2023-06-03 13:44:46 -0700648 if (mSnapshots[globalZ]->reachablilty == LayerSnapshot::Reachablilty::Unreachable) {
Vishnu Nairfccd6362023-02-24 23:39:53 +0000649 hasUnreachableSnapshots = true;
650 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000651 globalZ++;
652 }
Vishnu Nairfccd6362023-02-24 23:39:53 +0000653 return hasUnreachableSnapshots;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000654}
655
656void LayerSnapshotBuilder::updateRelativeState(LayerSnapshot& snapshot,
657 const LayerSnapshot& parentSnapshot,
658 bool parentIsRelative, const Args& args) {
659 if (parentIsRelative) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000660 snapshot.isHiddenByPolicyFromRelativeParent =
661 parentSnapshot.isHiddenByPolicyFromParent || parentSnapshot.invalidTransform;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000662 if (args.includeMetadata) {
663 snapshot.relativeLayerMetadata = parentSnapshot.layerMetadata;
664 }
665 } else {
666 snapshot.isHiddenByPolicyFromRelativeParent =
667 parentSnapshot.isHiddenByPolicyFromRelativeParent;
668 if (args.includeMetadata) {
669 snapshot.relativeLayerMetadata = parentSnapshot.relativeLayerMetadata;
670 }
671 }
Vishnu Naira02943f2023-06-03 13:44:46 -0700672 if (snapshot.reachablilty == LayerSnapshot::Reachablilty::Unreachable) {
673 snapshot.reachablilty = LayerSnapshot::Reachablilty::ReachableByRelativeParent;
674 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000675}
676
Vishnu Nair42b918e2023-07-18 20:05:29 +0000677void LayerSnapshotBuilder::updateFrameRateFromChildSnapshot(LayerSnapshot& snapshot,
678 const LayerSnapshot& childSnapshot,
679 const Args& args) {
680 if (args.forceUpdate == ForceUpdateFlags::NONE &&
Vishnu Nair52d56fd2023-07-20 17:02:43 +0000681 !args.layerLifecycleManager.getGlobalChanges().any(
682 RequestedLayerState::Changes::Hierarchy) &&
683 !childSnapshot.changes.any(RequestedLayerState::Changes::FrameRate) &&
684 !snapshot.changes.any(RequestedLayerState::Changes::FrameRate)) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000685 return;
686 }
Vishnu Naircfb2d252023-01-19 04:44:02 +0000687
Vishnu Nair3fbe3262023-09-29 17:07:00 -0700688 using FrameRateCompatibility = scheduler::FrameRateCompatibility;
Rachel Leece6e0042023-06-27 11:22:54 -0700689 if (snapshot.frameRate.isValid()) {
Vishnu Nair42b918e2023-07-18 20:05:29 +0000690 // we already have a valid framerate.
691 return;
692 }
Vishnu Naircfb2d252023-01-19 04:44:02 +0000693
Vishnu Nair42b918e2023-07-18 20:05:29 +0000694 // We return whether this layer or its children has a vote. We ignore ExactOrMultiple votes
695 // for the same reason we are allowing touch boost for those layers. See
696 // RefreshRateSelector::rankFrameRates for details.
Rachel Leece6e0042023-06-27 11:22:54 -0700697 const auto layerVotedWithDefaultCompatibility = childSnapshot.frameRate.vote.rate.isValid() &&
698 childSnapshot.frameRate.vote.type == FrameRateCompatibility::Default;
Vishnu Nair42b918e2023-07-18 20:05:29 +0000699 const auto layerVotedWithNoVote =
Rachel Leece6e0042023-06-27 11:22:54 -0700700 childSnapshot.frameRate.vote.type == FrameRateCompatibility::NoVote;
701 const auto layerVotedWithCategory =
702 childSnapshot.frameRate.category != FrameRateCategory::Default;
703 const auto layerVotedWithExactCompatibility = childSnapshot.frameRate.vote.rate.isValid() &&
704 childSnapshot.frameRate.vote.type == FrameRateCompatibility::Exact;
Vishnu Nair42b918e2023-07-18 20:05:29 +0000705
706 bool childHasValidFrameRate = layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
Rachel Leece6e0042023-06-27 11:22:54 -0700707 layerVotedWithCategory || layerVotedWithExactCompatibility;
Vishnu Nair42b918e2023-07-18 20:05:29 +0000708
709 // If we don't have a valid frame rate, but the children do, we set this
710 // layer as NoVote to allow the children to control the refresh rate
711 if (childHasValidFrameRate) {
712 snapshot.frameRate = scheduler::LayerInfo::FrameRate(Fps(), FrameRateCompatibility::NoVote);
713 snapshot.changes |= RequestedLayerState::Changes::FrameRate;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000714 }
715}
716
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000717void LayerSnapshotBuilder::resetRelativeState(LayerSnapshot& snapshot) {
718 snapshot.isHiddenByPolicyFromRelativeParent = false;
719 snapshot.relativeLayerMetadata.mMap.clear();
720}
721
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000722void LayerSnapshotBuilder::updateSnapshot(LayerSnapshot& snapshot, const Args& args,
723 const RequestedLayerState& requested,
724 const LayerSnapshot& parentSnapshot,
Vishnu Nair92990e22023-02-24 20:01:05 +0000725 const LayerHierarchy::TraversalPath& path) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000726 // Always update flags and visibility
727 ftl::Flags<RequestedLayerState::Changes> parentChanges = parentSnapshot.changes &
728 (RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Geometry |
729 RequestedLayerState::Changes::Visibility | RequestedLayerState::Changes::Metadata |
Vishnu Nairf13c8982023-12-02 11:26:09 -0800730 RequestedLayerState::Changes::AffectsChildren | RequestedLayerState::Changes::Input |
Vishnu Naira02943f2023-06-03 13:44:46 -0700731 RequestedLayerState::Changes::FrameRate | RequestedLayerState::Changes::GameMode);
732 snapshot.changes |= parentChanges;
733 if (args.displayChanges) snapshot.changes |= RequestedLayerState::Changes::Geometry;
734 snapshot.reachablilty = LayerSnapshot::Reachablilty::Reachable;
735 snapshot.clientChanges |= (parentSnapshot.clientChanges & layer_state_t::AFFECTS_CHILDREN);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000736 snapshot.isHiddenByPolicyFromParent = parentSnapshot.isHiddenByPolicyFromParent ||
Vishnu Nair3af0ec02023-02-10 04:13:48 +0000737 parentSnapshot.invalidTransform || requested.isHiddenByPolicy() ||
738 (args.excludeLayerIds.find(path.id) != args.excludeLayerIds.end());
Vishnu Nair80a5a702023-02-11 01:21:51 +0000739
Vishnu Nair92990e22023-02-24 20:01:05 +0000740 const bool forceUpdate = args.forceUpdate == ForceUpdateFlags::ALL ||
Vishnu Naira02943f2023-06-03 13:44:46 -0700741 snapshot.clientChanges & layer_state_t::eReparent ||
Vishnu Nair92990e22023-02-24 20:01:05 +0000742 snapshot.changes.any(RequestedLayerState::Changes::Visibility |
743 RequestedLayerState::Changes::Created);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000744
Vishnu Naira02943f2023-06-03 13:44:46 -0700745 if (forceUpdate || snapshot.clientChanges & layer_state_t::eLayerStackChanged) {
746 // If root layer, use the layer stack otherwise get the parent's layer stack.
747 snapshot.outputFilter.layerStack =
748 parentSnapshot.path == LayerHierarchy::TraversalPath::ROOT
749 ? requested.layerStack
750 : parentSnapshot.outputFilter.layerStack;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000751 }
752
Chavi Weingartenb74093a2023-10-11 20:29:59 +0000753 if (forceUpdate || snapshot.clientChanges & layer_state_t::eTrustedOverlayChanged) {
Vishnu Nair9e0017e2024-05-22 19:02:44 +0000754 switch (requested.trustedOverlay) {
755 case gui::TrustedOverlay::UNSET:
756 snapshot.trustedOverlay = parentSnapshot.trustedOverlay;
757 break;
758 case gui::TrustedOverlay::DISABLED:
759 snapshot.trustedOverlay = FlagManager::getInstance().override_trusted_overlay()
760 ? requested.trustedOverlay
761 : parentSnapshot.trustedOverlay;
762 break;
763 case gui::TrustedOverlay::ENABLED:
764 snapshot.trustedOverlay = requested.trustedOverlay;
765 break;
766 }
Chavi Weingartenb74093a2023-10-11 20:29:59 +0000767 }
768
Vishnu Nair92990e22023-02-24 20:01:05 +0000769 if (snapshot.isHiddenByPolicyFromParent &&
770 !snapshot.changes.test(RequestedLayerState::Changes::Created)) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000771 if (forceUpdate ||
Vishnu Naira02943f2023-06-03 13:44:46 -0700772 snapshot.changes.any(RequestedLayerState::Changes::Geometry |
Vishnu Nair494a2e42023-11-10 17:21:19 -0800773 RequestedLayerState::Changes::BufferSize |
Vishnu Naircfb2d252023-01-19 04:44:02 +0000774 RequestedLayerState::Changes::Input)) {
775 updateInput(snapshot, requested, parentSnapshot, path, args);
776 }
Garfield Tan8eb8f352024-05-17 09:12:01 -0700777 if (forceUpdate ||
778 (args.includeMetadata &&
779 snapshot.changes.test(RequestedLayerState::Changes::Metadata))) {
780 updateMetadataAndGameMode(snapshot, requested, args, parentSnapshot);
781 }
Vishnu Naircfb2d252023-01-19 04:44:02 +0000782 return;
783 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000784
Vishnu Naira02943f2023-06-03 13:44:46 -0700785 if (forceUpdate || snapshot.changes.any(RequestedLayerState::Changes::Mirror)) {
786 // Display mirrors are always placed in a VirtualDisplay so we never want to capture layers
787 // marked as skip capture
788 snapshot.handleSkipScreenshotFlag = parentSnapshot.handleSkipScreenshotFlag ||
789 (requested.layerStackToMirror != ui::INVALID_LAYER_STACK);
790 }
791
792 if (forceUpdate || snapshot.clientChanges & layer_state_t::eAlphaChanged) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000793 snapshot.color.a = parentSnapshot.color.a * requested.color.a;
794 snapshot.alpha = snapshot.color.a;
Vishnu Nair29354ec2023-03-28 18:51:28 -0700795 snapshot.inputInfo.alpha = snapshot.color.a;
Vishnu Naira02943f2023-06-03 13:44:46 -0700796 }
Vishnu Nair29354ec2023-03-28 18:51:28 -0700797
Vishnu Naira02943f2023-06-03 13:44:46 -0700798 if (forceUpdate || snapshot.clientChanges & layer_state_t::eFlagsChanged) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000799 snapshot.isSecure =
800 parentSnapshot.isSecure || (requested.flags & layer_state_t::eLayerSecure);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000801 snapshot.outputFilter.toInternalDisplay = parentSnapshot.outputFilter.toInternalDisplay ||
802 (requested.flags & layer_state_t::eLayerSkipScreenshot);
Vishnu Naira02943f2023-06-03 13:44:46 -0700803 }
804
Vishnu Naira02943f2023-06-03 13:44:46 -0700805 if (forceUpdate || snapshot.clientChanges & layer_state_t::eStretchChanged) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000806 snapshot.stretchEffect = (requested.stretchEffect.hasEffect())
807 ? requested.stretchEffect
808 : parentSnapshot.stretchEffect;
Vishnu Naira02943f2023-06-03 13:44:46 -0700809 }
810
811 if (forceUpdate || snapshot.clientChanges & layer_state_t::eColorTransformChanged) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000812 if (!parentSnapshot.colorTransformIsIdentity) {
813 snapshot.colorTransform = parentSnapshot.colorTransform * requested.colorTransform;
814 snapshot.colorTransformIsIdentity = false;
815 } else {
816 snapshot.colorTransform = requested.colorTransform;
817 snapshot.colorTransformIsIdentity = !requested.hasColorTransform;
818 }
Vishnu Naira02943f2023-06-03 13:44:46 -0700819 }
820
Nergi Rahardi6431d4a2024-05-15 18:42:48 +0900821 if (forceUpdate || snapshot.changes.test(RequestedLayerState::Changes::Metadata)) {
Garfield Tan8eb8f352024-05-17 09:12:01 -0700822 updateMetadataAndGameMode(snapshot, requested, args, parentSnapshot);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000823 }
824
Vishnu Naira02943f2023-06-03 13:44:46 -0700825 if (forceUpdate || snapshot.clientChanges & layer_state_t::eFixedTransformHintChanged ||
Vishnu Nairb76d99a2023-03-19 18:22:31 -0700826 args.displayChanges) {
827 snapshot.fixedTransformHint = requested.fixedTransformHint != ui::Transform::ROT_INVALID
828 ? requested.fixedTransformHint
829 : parentSnapshot.fixedTransformHint;
830
831 if (snapshot.fixedTransformHint != ui::Transform::ROT_INVALID) {
832 snapshot.transformHint = snapshot.fixedTransformHint;
833 } else {
834 const auto display = args.displays.get(snapshot.outputFilter.layerStack);
835 snapshot.transformHint = display.has_value()
836 ? std::make_optional<>(display->get().transformHint)
837 : std::nullopt;
838 }
839 }
840
Vishnu Nair42b918e2023-07-18 20:05:29 +0000841 if (forceUpdate ||
Vishnu Nair52d56fd2023-07-20 17:02:43 +0000842 args.layerLifecycleManager.getGlobalChanges().any(
843 RequestedLayerState::Changes::Hierarchy) ||
Vishnu Nair42b918e2023-07-18 20:05:29 +0000844 snapshot.changes.any(RequestedLayerState::Changes::FrameRate |
845 RequestedLayerState::Changes::Hierarchy)) {
Rachel Leea021bb02023-11-20 21:51:09 -0800846 const bool shouldOverrideChildren = parentSnapshot.frameRateSelectionStrategy ==
Rachel Lee58cc90d2023-09-05 18:50:20 -0700847 scheduler::LayerInfo::FrameRateSelectionStrategy::OverrideChildren;
Rachel Leea021bb02023-11-20 21:51:09 -0800848 const bool propagationAllowed = parentSnapshot.frameRateSelectionStrategy !=
Rachel Lee70f7b692023-11-22 11:24:02 -0800849 scheduler::LayerInfo::FrameRateSelectionStrategy::Self;
Rachel Leea021bb02023-11-20 21:51:09 -0800850 if ((!requested.requestedFrameRate.isValid() && propagationAllowed) ||
851 shouldOverrideChildren) {
Vishnu Nair30515cb2023-10-19 21:54:08 -0700852 snapshot.inheritedFrameRate = parentSnapshot.inheritedFrameRate;
853 } else {
854 snapshot.inheritedFrameRate = requested.requestedFrameRate;
855 }
856 // Set the framerate as the inherited frame rate and allow children to override it if
857 // needed.
858 snapshot.frameRate = snapshot.inheritedFrameRate;
Vishnu Nair52d56fd2023-07-20 17:02:43 +0000859 snapshot.changes |= RequestedLayerState::Changes::FrameRate;
Vishnu Naird47bcee2023-02-24 18:08:51 +0000860 }
861
Rachel Lee58cc90d2023-09-05 18:50:20 -0700862 if (forceUpdate || snapshot.clientChanges & layer_state_t::eFrameRateSelectionStrategyChanged) {
Rachel Leea021bb02023-11-20 21:51:09 -0800863 if (parentSnapshot.frameRateSelectionStrategy ==
864 scheduler::LayerInfo::FrameRateSelectionStrategy::OverrideChildren) {
865 snapshot.frameRateSelectionStrategy =
866 scheduler::LayerInfo::FrameRateSelectionStrategy::OverrideChildren;
867 } else {
868 const auto strategy = scheduler::LayerInfo::convertFrameRateSelectionStrategy(
869 requested.frameRateSelectionStrategy);
870 snapshot.frameRateSelectionStrategy = strategy;
871 }
Rachel Lee58cc90d2023-09-05 18:50:20 -0700872 }
873
Vishnu Nair3d8565a2023-06-30 07:23:24 +0000874 if (forceUpdate || snapshot.clientChanges & layer_state_t::eFrameRateSelectionPriority) {
875 snapshot.frameRateSelectionPriority =
876 (requested.frameRateSelectionPriority == Layer::PRIORITY_UNSET)
877 ? parentSnapshot.frameRateSelectionPriority
878 : requested.frameRateSelectionPriority;
879 }
880
Vishnu Naira02943f2023-06-03 13:44:46 -0700881 if (forceUpdate ||
882 snapshot.clientChanges &
883 (layer_state_t::eBackgroundBlurRadiusChanged | layer_state_t::eBlurRegionsChanged |
884 layer_state_t::eAlphaChanged)) {
Vishnu Nair80a5a702023-02-11 01:21:51 +0000885 snapshot.backgroundBlurRadius = args.supportsBlur
886 ? static_cast<int>(parentSnapshot.color.a * (float)requested.backgroundBlurRadius)
887 : 0;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000888 snapshot.blurRegions = requested.blurRegions;
Vishnu Nair80a5a702023-02-11 01:21:51 +0000889 for (auto& region : snapshot.blurRegions) {
890 region.alpha = region.alpha * snapshot.color.a;
891 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000892 }
893
Vishnu Naira02943f2023-06-03 13:44:46 -0700894 if (forceUpdate || snapshot.changes.any(RequestedLayerState::Changes::Geometry)) {
895 uint32_t primaryDisplayRotationFlags = getPrimaryDisplayRotationFlags(args.displays);
Vishnu Nairb76d99a2023-03-19 18:22:31 -0700896 updateLayerBounds(snapshot, requested, parentSnapshot, primaryDisplayRotationFlags);
Vishnu Naira02943f2023-06-03 13:44:46 -0700897 }
898
899 if (forceUpdate || snapshot.clientChanges & layer_state_t::eCornerRadiusChanged ||
Vishnu Nair0808ae62023-08-07 21:42:42 -0700900 snapshot.changes.any(RequestedLayerState::Changes::Geometry |
901 RequestedLayerState::Changes::BufferUsageFlags)) {
902 updateRoundedCorner(snapshot, requested, parentSnapshot, args);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000903 }
904
Vishnu Naira02943f2023-06-03 13:44:46 -0700905 if (forceUpdate || snapshot.clientChanges & layer_state_t::eShadowRadiusChanged ||
906 snapshot.changes.any(RequestedLayerState::Changes::Geometry)) {
907 updateShadows(snapshot, requested, args.globalShadowSettings);
908 }
909
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000910 if (forceUpdate ||
Vishnu Naira02943f2023-06-03 13:44:46 -0700911 snapshot.changes.any(RequestedLayerState::Changes::Geometry |
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000912 RequestedLayerState::Changes::Input)) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000913 updateInput(snapshot, requested, parentSnapshot, path, args);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000914 }
915
916 // computed snapshot properties
Alec Mouri994761f2023-08-04 21:50:55 +0000917 snapshot.forceClientComposition =
918 snapshot.shadowSettings.length > 0 || snapshot.stretchEffect.hasEffect();
Vishnu Nairc765c6c2023-02-23 00:08:01 +0000919 snapshot.contentOpaque = snapshot.isContentOpaque();
920 snapshot.isOpaque = snapshot.contentOpaque && !snapshot.roundedCorner.hasRoundedCorners() &&
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000921 snapshot.color.a == 1.f;
922 snapshot.blendMode = getBlendMode(snapshot, requested);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000923 LLOGV(snapshot.sequence,
Vishnu Nair92990e22023-02-24 20:01:05 +0000924 "%supdated %s changes:%s parent:%s requested:%s requested:%s from parent %s",
925 args.forceUpdate == ForceUpdateFlags::ALL ? "Force " : "",
926 snapshot.getDebugString().c_str(), snapshot.changes.string().c_str(),
927 parentSnapshot.changes.string().c_str(), requested.changes.string().c_str(),
928 std::to_string(requested.what).c_str(), parentSnapshot.getDebugString().c_str());
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000929}
930
931void LayerSnapshotBuilder::updateRoundedCorner(LayerSnapshot& snapshot,
932 const RequestedLayerState& requested,
Vishnu Nair0808ae62023-08-07 21:42:42 -0700933 const LayerSnapshot& parentSnapshot,
934 const Args& args) {
935 if (args.skipRoundCornersWhenProtected && requested.isProtected()) {
936 snapshot.roundedCorner = RoundedCornerState();
937 return;
938 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000939 snapshot.roundedCorner = RoundedCornerState();
940 RoundedCornerState parentRoundedCorner;
941 if (parentSnapshot.roundedCorner.hasRoundedCorners()) {
942 parentRoundedCorner = parentSnapshot.roundedCorner;
943 ui::Transform t = snapshot.localTransform.inverse();
944 parentRoundedCorner.cropRect = t.transform(parentRoundedCorner.cropRect);
945 parentRoundedCorner.radius.x *= t.getScaleX();
946 parentRoundedCorner.radius.y *= t.getScaleY();
947 }
948
949 FloatRect layerCropRect = snapshot.croppedBufferSize.toFloatRect();
950 const vec2 radius(requested.cornerRadius, requested.cornerRadius);
951 RoundedCornerState layerSettings(layerCropRect, radius);
952 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && !layerCropRect.isEmpty();
953 const bool parentRoundedCornerValid = parentRoundedCorner.hasRoundedCorners();
954 if (layerSettingsValid && parentRoundedCornerValid) {
955 // If the parent and the layer have rounded corner settings, use the parent settings if
956 // the parent crop is entirely inside the layer crop. This has limitations and cause
957 // rendering artifacts. See b/200300845 for correct fix.
958 if (parentRoundedCorner.cropRect.left > layerCropRect.left &&
959 parentRoundedCorner.cropRect.top > layerCropRect.top &&
960 parentRoundedCorner.cropRect.right < layerCropRect.right &&
961 parentRoundedCorner.cropRect.bottom < layerCropRect.bottom) {
962 snapshot.roundedCorner = parentRoundedCorner;
963 } else {
964 snapshot.roundedCorner = layerSettings;
965 }
966 } else if (layerSettingsValid) {
967 snapshot.roundedCorner = layerSettings;
968 } else if (parentRoundedCornerValid) {
969 snapshot.roundedCorner = parentRoundedCorner;
970 }
971}
972
973void LayerSnapshotBuilder::updateLayerBounds(LayerSnapshot& snapshot,
974 const RequestedLayerState& requested,
975 const LayerSnapshot& parentSnapshot,
Vishnu Nairb76d99a2023-03-19 18:22:31 -0700976 uint32_t primaryDisplayRotationFlags) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000977 snapshot.geomLayerTransform = parentSnapshot.geomLayerTransform * snapshot.localTransform;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000978 const bool transformWasInvalid = snapshot.invalidTransform;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000979 snapshot.invalidTransform = !LayerSnapshot::isTransformValid(snapshot.geomLayerTransform);
980 if (snapshot.invalidTransform) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000981 auto& t = snapshot.geomLayerTransform;
982 auto& requestedT = requested.requestedTransform;
983 std::string transformDebug =
984 base::StringPrintf(" transform={%f,%f,%f,%f} requestedTransform={%f,%f,%f,%f}",
985 t.dsdx(), t.dsdy(), t.dtdx(), t.dtdy(), requestedT.dsdx(),
986 requestedT.dsdy(), requestedT.dtdx(), requestedT.dtdy());
987 std::string bufferDebug;
988 if (requested.externalTexture) {
Vishnu Nairb76d99a2023-03-19 18:22:31 -0700989 auto unRotBuffer = requested.getUnrotatedBufferSize(primaryDisplayRotationFlags);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000990 auto& destFrame = requested.destinationFrame;
991 bufferDebug = base::StringPrintf(" buffer={%d,%d} displayRot=%d"
992 " destFrame={%d,%d,%d,%d} unRotBuffer={%d,%d}",
993 requested.externalTexture->getWidth(),
994 requested.externalTexture->getHeight(),
Vishnu Nairb76d99a2023-03-19 18:22:31 -0700995 primaryDisplayRotationFlags, destFrame.left,
996 destFrame.top, destFrame.right, destFrame.bottom,
Vishnu Naircfb2d252023-01-19 04:44:02 +0000997 unRotBuffer.getHeight(), unRotBuffer.getWidth());
998 }
999 ALOGW("Resetting transform for %s because it is invalid.%s%s",
1000 snapshot.getDebugString().c_str(), transformDebug.c_str(), bufferDebug.c_str());
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001001 snapshot.geomLayerTransform.reset();
1002 }
Vishnu Naircfb2d252023-01-19 04:44:02 +00001003 if (transformWasInvalid != snapshot.invalidTransform) {
1004 // If transform is invalid, the layer will be hidden.
1005 mResortSnapshots = true;
1006 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001007 snapshot.geomInverseLayerTransform = snapshot.geomLayerTransform.inverse();
1008
1009 FloatRect parentBounds = parentSnapshot.geomLayerBounds;
1010 parentBounds = snapshot.localTransform.inverse().transform(parentBounds);
1011 snapshot.geomLayerBounds =
1012 (requested.externalTexture) ? snapshot.bufferSize.toFloatRect() : parentBounds;
1013 if (!requested.crop.isEmpty()) {
1014 snapshot.geomLayerBounds = snapshot.geomLayerBounds.intersect(requested.crop.toFloatRect());
1015 }
1016 snapshot.geomLayerBounds = snapshot.geomLayerBounds.intersect(parentBounds);
1017 snapshot.transformedBounds = snapshot.geomLayerTransform.transform(snapshot.geomLayerBounds);
Vishnu Naircfb2d252023-01-19 04:44:02 +00001018 const Rect geomLayerBoundsWithoutTransparentRegion =
1019 RequestedLayerState::reduce(Rect(snapshot.geomLayerBounds),
1020 requested.transparentRegion);
1021 snapshot.transformedBoundsWithoutTransparentRegion =
1022 snapshot.geomLayerTransform.transform(geomLayerBoundsWithoutTransparentRegion);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001023 snapshot.parentTransform = parentSnapshot.geomLayerTransform;
1024
1025 // Subtract the transparent region and snap to the bounds
Vishnu Naircfb2d252023-01-19 04:44:02 +00001026 const Rect bounds =
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001027 RequestedLayerState::reduce(snapshot.croppedBufferSize, requested.transparentRegion);
Vishnu Naircfb2d252023-01-19 04:44:02 +00001028 if (requested.potentialCursor) {
1029 snapshot.cursorFrame = snapshot.geomLayerTransform.transform(bounds);
1030 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001031}
1032
Vishnu Naira02943f2023-06-03 13:44:46 -07001033void LayerSnapshotBuilder::updateShadows(LayerSnapshot& snapshot, const RequestedLayerState&,
Vishnu Naird9e4f462023-10-06 04:05:45 +00001034 const ShadowSettings& globalShadowSettings) {
1035 if (snapshot.shadowSettings.length > 0.f) {
1036 snapshot.shadowSettings.ambientColor = globalShadowSettings.ambientColor;
1037 snapshot.shadowSettings.spotColor = globalShadowSettings.spotColor;
1038 snapshot.shadowSettings.lightPos = globalShadowSettings.lightPos;
1039 snapshot.shadowSettings.lightRadius = globalShadowSettings.lightRadius;
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001040
1041 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
1042 // it if transparent regions are present. This may not be necessary since shadows are
1043 // typically cast by layers without transparent regions.
1044 snapshot.shadowSettings.boundaries = snapshot.geomLayerBounds;
1045
1046 // If the casting layer is translucent, we need to fill in the shadow underneath the
1047 // layer. Otherwise the generated shadow will only be shown around the casting layer.
1048 snapshot.shadowSettings.casterIsTranslucent =
1049 !snapshot.isContentOpaque() || (snapshot.alpha < 1.0f);
1050 snapshot.shadowSettings.ambientColor *= snapshot.alpha;
1051 snapshot.shadowSettings.spotColor *= snapshot.alpha;
1052 }
1053}
1054
1055void LayerSnapshotBuilder::updateInput(LayerSnapshot& snapshot,
1056 const RequestedLayerState& requested,
1057 const LayerSnapshot& parentSnapshot,
Vishnu Naircfb2d252023-01-19 04:44:02 +00001058 const LayerHierarchy::TraversalPath& path,
1059 const Args& args) {
Prabir Pradhancf359192024-03-20 00:42:57 +00001060 using InputConfig = gui::WindowInfo::InputConfig;
1061
Vishnu Naircfb2d252023-01-19 04:44:02 +00001062 if (requested.windowInfoHandle) {
1063 snapshot.inputInfo = *requested.windowInfoHandle->getInfo();
1064 } else {
1065 snapshot.inputInfo = {};
Vishnu Nair40d02282023-02-28 21:11:40 +00001066 // b/271132344 revisit this and see if we can always use the layers uid/pid
1067 snapshot.inputInfo.name = requested.name;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00001068 snapshot.inputInfo.ownerUid = gui::Uid{requested.ownerUid};
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00001069 snapshot.inputInfo.ownerPid = gui::Pid{requested.ownerPid};
Vishnu Naircfb2d252023-01-19 04:44:02 +00001070 }
Vishnu Nair29354ec2023-03-28 18:51:28 -07001071 snapshot.touchCropId = requested.touchCropId;
Vishnu Naircfb2d252023-01-19 04:44:02 +00001072
Vishnu Nair93b8b792023-02-27 19:40:24 +00001073 snapshot.inputInfo.id = static_cast<int32_t>(snapshot.uniqueSequence);
Linnan Li13bf76a2024-05-05 19:18:02 +08001074 snapshot.inputInfo.displayId =
1075 ui::LogicalDisplayId{static_cast<int32_t>(snapshot.outputFilter.layerStack.id)};
Vishnu Nairf13c8982023-12-02 11:26:09 -08001076 snapshot.inputInfo.touchOcclusionMode = requested.hasInputInfo()
1077 ? requested.windowInfoHandle->getInfo()->touchOcclusionMode
1078 : parentSnapshot.inputInfo.touchOcclusionMode;
Vishnu Nair59a6be32024-01-29 10:26:21 -08001079 snapshot.inputInfo.canOccludePresentation = parentSnapshot.inputInfo.canOccludePresentation ||
1080 (requested.flags & layer_state_t::eCanOccludePresentation);
Vishnu Nairf13c8982023-12-02 11:26:09 -08001081 if (requested.dropInputMode == gui::DropInputMode::ALL ||
1082 parentSnapshot.dropInputMode == gui::DropInputMode::ALL) {
1083 snapshot.dropInputMode = gui::DropInputMode::ALL;
1084 } else if (requested.dropInputMode == gui::DropInputMode::OBSCURED ||
1085 parentSnapshot.dropInputMode == gui::DropInputMode::OBSCURED) {
1086 snapshot.dropInputMode = gui::DropInputMode::OBSCURED;
1087 } else {
1088 snapshot.dropInputMode = gui::DropInputMode::NONE;
1089 }
1090
Prabir Pradhancf359192024-03-20 00:42:57 +00001091 if (snapshot.isSecure ||
Arpit Singh490ccc92024-04-30 14:26:21 +00001092 parentSnapshot.inputInfo.inputConfig.test(InputConfig::SENSITIVE_FOR_PRIVACY)) {
1093 snapshot.inputInfo.inputConfig |= InputConfig::SENSITIVE_FOR_PRIVACY;
Prabir Pradhancf359192024-03-20 00:42:57 +00001094 }
1095
Vishnu Nair29354ec2023-03-28 18:51:28 -07001096 updateVisibility(snapshot, snapshot.isVisible);
Vishnu Naircfb2d252023-01-19 04:44:02 +00001097 if (!needsInputInfo(snapshot, requested)) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001098 return;
1099 }
1100
Vishnu Naircfb2d252023-01-19 04:44:02 +00001101 static frontend::DisplayInfo sDefaultInfo = {.isSecure = false};
1102 const std::optional<frontend::DisplayInfo> displayInfoOpt =
1103 args.displays.get(snapshot.outputFilter.layerStack);
1104 bool noValidDisplay = !displayInfoOpt.has_value();
1105 auto displayInfo = displayInfoOpt.value_or(sDefaultInfo);
1106
1107 if (!requested.windowInfoHandle) {
Prabir Pradhancf359192024-03-20 00:42:57 +00001108 snapshot.inputInfo.inputConfig = InputConfig::NO_INPUT_CHANNEL;
Vishnu Naircfb2d252023-01-19 04:44:02 +00001109 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001110 fillInputFrameInfo(snapshot.inputInfo, displayInfo.transform, snapshot);
1111
1112 if (noValidDisplay) {
1113 // Do not let the window receive touches if it is not associated with a valid display
1114 // transform. We still allow the window to receive keys and prevent ANRs.
Prabir Pradhancf359192024-03-20 00:42:57 +00001115 snapshot.inputInfo.inputConfig |= InputConfig::NOT_TOUCHABLE;
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001116 }
1117
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001118 snapshot.inputInfo.alpha = snapshot.color.a;
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001119
1120 handleDropInputMode(snapshot, parentSnapshot);
1121
1122 // If the window will be blacked out on a display because the display does not have the secure
1123 // flag and the layer has the secure flag set, then drop input.
1124 if (!displayInfo.isSecure && snapshot.isSecure) {
Prabir Pradhancf359192024-03-20 00:42:57 +00001125 snapshot.inputInfo.inputConfig |= InputConfig::DROP_INPUT;
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001126 }
1127
Vishnu Naira02943f2023-06-03 13:44:46 -07001128 if (requested.touchCropId != UNASSIGNED_LAYER_ID || path.isClone()) {
Vishnu Nair29354ec2023-03-28 18:51:28 -07001129 mNeedsTouchableRegionCrop.insert(path);
Vishnu Naira02943f2023-06-03 13:44:46 -07001130 }
1131 auto cropLayerSnapshot = getSnapshot(requested.touchCropId);
1132 if (!cropLayerSnapshot && snapshot.inputInfo.replaceTouchableRegionWithCrop) {
Vishnu Nair29354ec2023-03-28 18:51:28 -07001133 FloatRect inputBounds = getInputBounds(snapshot, /*fillParentBounds=*/true).first;
Vishnu Nairfed7c122023-03-18 01:54:43 +00001134 Rect inputBoundsInDisplaySpace =
Vishnu Nair29354ec2023-03-28 18:51:28 -07001135 getInputBoundsInDisplaySpace(snapshot, inputBounds, displayInfo.transform);
1136 snapshot.inputInfo.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001137 }
1138
1139 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
1140 // if it was set by WM for a known system overlay
Vishnu Nair9e0017e2024-05-22 19:02:44 +00001141 if (snapshot.trustedOverlay == gui::TrustedOverlay::ENABLED) {
Prabir Pradhancf359192024-03-20 00:42:57 +00001142 snapshot.inputInfo.inputConfig |= InputConfig::TRUSTED_OVERLAY;
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001143 }
1144
Vishnu Nair494a2e42023-11-10 17:21:19 -08001145 snapshot.inputInfo.contentSize = snapshot.croppedBufferSize.getSize();
1146
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001147 // If the layer is a clone, we need to crop the input region to cloned root to prevent
1148 // touches from going outside the cloned area.
1149 if (path.isClone()) {
Prabir Pradhancf359192024-03-20 00:42:57 +00001150 snapshot.inputInfo.inputConfig |= InputConfig::CLONE;
Vishnu Nair444f3952023-04-11 13:01:02 -07001151 // Cloned layers shouldn't handle watch outside since their z order is not determined by
1152 // WM or the client.
Prabir Pradhancf359192024-03-20 00:42:57 +00001153 snapshot.inputInfo.inputConfig.clear(InputConfig::WATCH_OUTSIDE_TOUCH);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001154 }
1155}
1156
1157std::vector<std::unique_ptr<LayerSnapshot>>& LayerSnapshotBuilder::getSnapshots() {
1158 return mSnapshots;
1159}
1160
Vishnu Naircfb2d252023-01-19 04:44:02 +00001161void LayerSnapshotBuilder::forEachVisibleSnapshot(const ConstVisitor& visitor) const {
1162 for (int i = 0; i < mNumInterestingSnapshots; i++) {
1163 LayerSnapshot& snapshot = *mSnapshots[(size_t)i];
1164 if (!snapshot.isVisible) continue;
1165 visitor(snapshot);
1166 }
1167}
1168
Vishnu Nair3af0ec02023-02-10 04:13:48 +00001169// Visit each visible snapshot in z-order
1170void LayerSnapshotBuilder::forEachVisibleSnapshot(const ConstVisitor& visitor,
1171 const LayerHierarchy& root) const {
1172 root.traverseInZOrder(
1173 [this, visitor](const LayerHierarchy&,
1174 const LayerHierarchy::TraversalPath& traversalPath) -> bool {
1175 LayerSnapshot* snapshot = getSnapshot(traversalPath);
1176 if (snapshot && snapshot->isVisible) {
1177 visitor(*snapshot);
1178 }
1179 return true;
1180 });
1181}
1182
Vishnu Naircfb2d252023-01-19 04:44:02 +00001183void LayerSnapshotBuilder::forEachVisibleSnapshot(const Visitor& visitor) {
1184 for (int i = 0; i < mNumInterestingSnapshots; i++) {
1185 std::unique_ptr<LayerSnapshot>& snapshot = mSnapshots.at((size_t)i);
1186 if (!snapshot->isVisible) continue;
1187 visitor(snapshot);
1188 }
1189}
1190
Garfield Tan8eb8f352024-05-17 09:12:01 -07001191void LayerSnapshotBuilder::forEachSnapshot(const Visitor& visitor,
1192 const ConstPredicate& predicate) {
1193 for (int i = 0; i < mNumInterestingSnapshots; i++) {
1194 std::unique_ptr<LayerSnapshot>& snapshot = mSnapshots.at((size_t)i);
1195 if (!predicate(*snapshot)) continue;
1196 visitor(snapshot);
1197 }
1198}
1199
Vishnu Naircfb2d252023-01-19 04:44:02 +00001200void LayerSnapshotBuilder::forEachInputSnapshot(const ConstVisitor& visitor) const {
1201 for (int i = mNumInterestingSnapshots - 1; i >= 0; i--) {
1202 LayerSnapshot& snapshot = *mSnapshots[(size_t)i];
1203 if (!snapshot.hasInputInfo()) continue;
1204 visitor(snapshot);
1205 }
1206}
1207
Vishnu Nair29354ec2023-03-28 18:51:28 -07001208void LayerSnapshotBuilder::updateTouchableRegionCrop(const Args& args) {
1209 if (mNeedsTouchableRegionCrop.empty()) {
1210 return;
1211 }
1212
1213 static constexpr ftl::Flags<RequestedLayerState::Changes> AFFECTS_INPUT =
1214 RequestedLayerState::Changes::Visibility | RequestedLayerState::Changes::Created |
1215 RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Geometry |
1216 RequestedLayerState::Changes::Input;
1217
1218 if (args.forceUpdate != ForceUpdateFlags::ALL &&
Vishnu Naira02943f2023-06-03 13:44:46 -07001219 !args.layerLifecycleManager.getGlobalChanges().any(AFFECTS_INPUT) && !args.displayChanges) {
Vishnu Nair29354ec2023-03-28 18:51:28 -07001220 return;
1221 }
1222
1223 for (auto& path : mNeedsTouchableRegionCrop) {
1224 frontend::LayerSnapshot* snapshot = getSnapshot(path);
1225 if (!snapshot) {
1226 continue;
1227 }
Vishnu Naira02943f2023-06-03 13:44:46 -07001228 LLOGV(snapshot->sequence, "updateTouchableRegionCrop=%s",
1229 snapshot->getDebugString().c_str());
Vishnu Nair29354ec2023-03-28 18:51:28 -07001230 const std::optional<frontend::DisplayInfo> displayInfoOpt =
1231 args.displays.get(snapshot->outputFilter.layerStack);
1232 static frontend::DisplayInfo sDefaultInfo = {.isSecure = false};
1233 auto displayInfo = displayInfoOpt.value_or(sDefaultInfo);
1234
1235 bool needsUpdate =
1236 args.forceUpdate == ForceUpdateFlags::ALL || snapshot->changes.any(AFFECTS_INPUT);
1237 auto cropLayerSnapshot = getSnapshot(snapshot->touchCropId);
1238 needsUpdate =
1239 needsUpdate || (cropLayerSnapshot && cropLayerSnapshot->changes.any(AFFECTS_INPUT));
1240 auto clonedRootSnapshot = path.isClone() ? getSnapshot(snapshot->mirrorRootPath) : nullptr;
1241 needsUpdate = needsUpdate ||
1242 (clonedRootSnapshot && clonedRootSnapshot->changes.any(AFFECTS_INPUT));
1243
1244 if (!needsUpdate) {
1245 continue;
1246 }
1247
1248 if (snapshot->inputInfo.replaceTouchableRegionWithCrop) {
1249 Rect inputBoundsInDisplaySpace;
1250 if (!cropLayerSnapshot) {
1251 FloatRect inputBounds = getInputBounds(*snapshot, /*fillParentBounds=*/true).first;
1252 inputBoundsInDisplaySpace =
1253 getInputBoundsInDisplaySpace(*snapshot, inputBounds, displayInfo.transform);
1254 } else {
1255 FloatRect inputBounds =
1256 getInputBounds(*cropLayerSnapshot, /*fillParentBounds=*/true).first;
1257 inputBoundsInDisplaySpace =
1258 getInputBoundsInDisplaySpace(*cropLayerSnapshot, inputBounds,
1259 displayInfo.transform);
1260 }
1261 snapshot->inputInfo.touchableRegion = Region(inputBoundsInDisplaySpace);
1262 } else if (cropLayerSnapshot) {
1263 FloatRect inputBounds =
1264 getInputBounds(*cropLayerSnapshot, /*fillParentBounds=*/true).first;
1265 Rect inputBoundsInDisplaySpace =
1266 getInputBoundsInDisplaySpace(*cropLayerSnapshot, inputBounds,
1267 displayInfo.transform);
Chavi Weingarten1ba381e2024-01-09 21:54:11 +00001268 snapshot->inputInfo.touchableRegion =
1269 snapshot->inputInfo.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair29354ec2023-03-28 18:51:28 -07001270 }
1271
1272 // If the layer is a clone, we need to crop the input region to cloned root to prevent
1273 // touches from going outside the cloned area.
1274 if (clonedRootSnapshot) {
1275 const Rect rect =
1276 displayInfo.transform.transform(Rect{clonedRootSnapshot->transformedBounds});
1277 snapshot->inputInfo.touchableRegion =
1278 snapshot->inputInfo.touchableRegion.intersect(rect);
1279 }
1280 }
1281}
1282
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001283} // namespace android::surfaceflinger::frontend