blob: 6d4b0b5c54a9a60227ec6ad07ee7fc137ed89a73 [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
Vishnu Naircfb2d252023-01-19 04:44:02 +0000317void clearChanges(LayerSnapshot& snapshot) {
318 snapshot.changes.clear();
Vishnu Naira02943f2023-06-03 13:44:46 -0700319 snapshot.clientChanges = 0;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000320 snapshot.contentDirty = false;
321 snapshot.hasReadyFrame = false;
322 snapshot.sidebandStreamHasFrame = false;
323 snapshot.surfaceDamage.clear();
324}
325
Vishnu Naira02943f2023-06-03 13:44:46 -0700326// TODO (b/259407931): Remove.
327uint32_t getPrimaryDisplayRotationFlags(
328 const ui::DisplayMap<ui::LayerStack, frontend::DisplayInfo>& displays) {
329 for (auto& [_, display] : displays) {
330 if (display.isPrimary) {
331 return display.rotationFlags;
332 }
333 }
334 return 0;
335}
336
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000337} // namespace
338
339LayerSnapshot LayerSnapshotBuilder::getRootSnapshot() {
340 LayerSnapshot snapshot;
Vishnu Nair92990e22023-02-24 20:01:05 +0000341 snapshot.path = LayerHierarchy::TraversalPath::ROOT;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000342 snapshot.changes = ftl::Flags<RequestedLayerState::Changes>();
Vishnu Naira02943f2023-06-03 13:44:46 -0700343 snapshot.clientChanges = 0;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000344 snapshot.isHiddenByPolicyFromParent = false;
345 snapshot.isHiddenByPolicyFromRelativeParent = false;
346 snapshot.parentTransform.reset();
347 snapshot.geomLayerTransform.reset();
348 snapshot.geomInverseLayerTransform.reset();
349 snapshot.geomLayerBounds = getMaxDisplayBounds({});
350 snapshot.roundedCorner = RoundedCornerState();
351 snapshot.stretchEffect = {};
352 snapshot.outputFilter.layerStack = ui::DEFAULT_LAYER_STACK;
353 snapshot.outputFilter.toInternalDisplay = false;
354 snapshot.isSecure = false;
355 snapshot.color.a = 1.0_hf;
356 snapshot.colorTransformIsIdentity = true;
Vishnu Naird9e4f462023-10-06 04:05:45 +0000357 snapshot.shadowSettings.length = 0.f;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000358 snapshot.layerMetadata.mMap.clear();
359 snapshot.relativeLayerMetadata.mMap.clear();
360 snapshot.inputInfo.touchOcclusionMode = gui::TouchOcclusionMode::BLOCK_UNTRUSTED;
361 snapshot.dropInputMode = gui::DropInputMode::NONE;
Vishnu Nair9e0017e2024-05-22 19:02:44 +0000362 snapshot.trustedOverlay = gui::TrustedOverlay::UNSET;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000363 snapshot.gameMode = gui::GameMode::Unsupported;
364 snapshot.frameRate = {};
365 snapshot.fixedTransformHint = ui::Transform::ROT_INVALID;
Vishnu Nair422b81c2024-05-16 05:44:28 +0000366 snapshot.ignoreLocalTransform = false;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000367 return snapshot;
368}
369
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000370LayerSnapshotBuilder::LayerSnapshotBuilder() {}
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000371
372LayerSnapshotBuilder::LayerSnapshotBuilder(Args args) : LayerSnapshotBuilder() {
Vishnu Naird47bcee2023-02-24 18:08:51 +0000373 args.forceUpdate = ForceUpdateFlags::ALL;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000374 updateSnapshots(args);
375}
376
377bool LayerSnapshotBuilder::tryFastUpdate(const Args& args) {
Vishnu Naira02943f2023-06-03 13:44:46 -0700378 const bool forceUpdate = args.forceUpdate != ForceUpdateFlags::NONE;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000379
Vishnu Naira02943f2023-06-03 13:44:46 -0700380 if (args.layerLifecycleManager.getGlobalChanges().get() == 0 && !forceUpdate &&
381 !args.displayChanges) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000382 return true;
383 }
384
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000385 // There are only content changes which do not require any child layer snapshots to be updated.
386 ALOGV("%s", __func__);
387 ATRACE_NAME("FastPath");
388
Vishnu Naira02943f2023-06-03 13:44:46 -0700389 uint32_t primaryDisplayRotationFlags = getPrimaryDisplayRotationFlags(args.displays);
390 if (forceUpdate || args.displayChanges) {
391 for (auto& snapshot : mSnapshots) {
392 const RequestedLayerState* requested =
393 args.layerLifecycleManager.getLayerFromId(snapshot->path.id);
394 if (!requested) continue;
395 snapshot->merge(*requested, forceUpdate, args.displayChanges, args.forceFullDamage,
396 primaryDisplayRotationFlags);
397 }
398 return false;
399 }
400
401 // Walk through all the updated requested layer states and update the corresponding snapshots.
402 for (const RequestedLayerState* requested : args.layerLifecycleManager.getChangedLayers()) {
403 auto range = mIdToSnapshots.equal_range(requested->id);
404 for (auto it = range.first; it != range.second; it++) {
405 it->second->merge(*requested, forceUpdate, args.displayChanges, args.forceFullDamage,
406 primaryDisplayRotationFlags);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000407 }
408 }
409
Vishnu Naira02943f2023-06-03 13:44:46 -0700410 if ((args.layerLifecycleManager.getGlobalChanges().get() &
411 ~(RequestedLayerState::Changes::Content | RequestedLayerState::Changes::Buffer).get()) !=
412 0) {
413 // We have changes that require us to walk the hierarchy and update child layers.
414 // No fast path for you.
415 return false;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000416 }
417 return true;
418}
419
420void LayerSnapshotBuilder::updateSnapshots(const Args& args) {
421 ATRACE_NAME("UpdateSnapshots");
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000422 LayerSnapshot rootSnapshot = args.rootSnapshot;
Vishnu Nair3af0ec02023-02-10 04:13:48 +0000423 if (args.parentCrop) {
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000424 rootSnapshot.geomLayerBounds = *args.parentCrop;
Vishnu Naird47bcee2023-02-24 18:08:51 +0000425 } else if (args.forceUpdate == ForceUpdateFlags::ALL || args.displayChanges) {
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000426 rootSnapshot.geomLayerBounds = getMaxDisplayBounds(args.displays);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000427 }
428 if (args.displayChanges) {
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000429 rootSnapshot.changes = RequestedLayerState::Changes::AffectsChildren |
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000430 RequestedLayerState::Changes::Geometry;
431 }
Vishnu Naird47bcee2023-02-24 18:08:51 +0000432 if (args.forceUpdate == ForceUpdateFlags::HIERARCHY) {
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000433 rootSnapshot.changes |=
Vishnu Naird47bcee2023-02-24 18:08:51 +0000434 RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Visibility;
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000435 rootSnapshot.clientChanges |= layer_state_t::eReparent;
Vishnu Naird47bcee2023-02-24 18:08:51 +0000436 }
Vishnu Naira02943f2023-06-03 13:44:46 -0700437
438 for (auto& snapshot : mSnapshots) {
439 if (snapshot->reachablilty == LayerSnapshot::Reachablilty::Reachable) {
440 snapshot->reachablilty = LayerSnapshot::Reachablilty::Unreachable;
441 }
442 }
443
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000444 LayerHierarchy::TraversalPath root = LayerHierarchy::TraversalPath::ROOT;
Vishnu Naird47bcee2023-02-24 18:08:51 +0000445 if (args.root.getLayer()) {
446 // The hierarchy can have a root layer when used for screenshots otherwise, it will have
447 // multiple children.
448 LayerHierarchy::ScopedAddToTraversalPath addChildToPath(root, args.root.getLayer()->id,
449 LayerHierarchy::Variant::Attached);
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000450 updateSnapshotsInHierarchy(args, args.root, root, rootSnapshot, /*depth=*/0);
Vishnu Naird47bcee2023-02-24 18:08:51 +0000451 } else {
452 for (auto& [childHierarchy, variant] : args.root.mChildren) {
453 LayerHierarchy::ScopedAddToTraversalPath addChildToPath(root,
454 childHierarchy->getLayer()->id,
455 variant);
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000456 updateSnapshotsInHierarchy(args, *childHierarchy, root, rootSnapshot, /*depth=*/0);
Vishnu Naird47bcee2023-02-24 18:08:51 +0000457 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000458 }
459
Vishnu Nair29354ec2023-03-28 18:51:28 -0700460 // Update touchable region crops outside the main update pass. This is because a layer could be
461 // cropped by any other layer and it requires both snapshots to be updated.
462 updateTouchableRegionCrop(args);
463
Vishnu Nairfccd6362023-02-24 23:39:53 +0000464 const bool hasUnreachableSnapshots = sortSnapshotsByZ(args);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000465
Vishnu Nair29354ec2023-03-28 18:51:28 -0700466 // Destroy unreachable snapshots for clone layers. And destroy snapshots for non-clone
467 // layers if the layer have been destroyed.
468 // TODO(b/238781169) consider making clone layer ids stable as well
469 if (!hasUnreachableSnapshots && args.layerLifecycleManager.getDestroyedLayers().empty()) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000470 return;
471 }
472
Vishnu Nair29354ec2023-03-28 18:51:28 -0700473 std::unordered_set<uint32_t> destroyedLayerIds;
474 for (auto& destroyedLayer : args.layerLifecycleManager.getDestroyedLayers()) {
475 destroyedLayerIds.insert(destroyedLayer->id);
476 }
477
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000478 auto it = mSnapshots.begin();
479 while (it < mSnapshots.end()) {
480 auto& traversalPath = it->get()->path;
Vishnu Naira02943f2023-06-03 13:44:46 -0700481 const bool unreachable =
482 it->get()->reachablilty == LayerSnapshot::Reachablilty::Unreachable;
483 const bool isClone = traversalPath.isClone();
484 const bool layerIsDestroyed =
485 destroyedLayerIds.find(traversalPath.id) != destroyedLayerIds.end();
486 const bool destroySnapshot = (unreachable && isClone) || layerIsDestroyed;
487
488 if (!destroySnapshot) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000489 it++;
490 continue;
491 }
492
Vishnu Naira02943f2023-06-03 13:44:46 -0700493 mPathToSnapshot.erase(traversalPath);
494
495 auto range = mIdToSnapshots.equal_range(traversalPath.id);
496 auto matchingSnapshot =
497 std::find_if(range.first, range.second, [&traversalPath](auto& snapshotWithId) {
498 return snapshotWithId.second->path == traversalPath;
499 });
500 mIdToSnapshots.erase(matchingSnapshot);
Vishnu Nair29354ec2023-03-28 18:51:28 -0700501 mNeedsTouchableRegionCrop.erase(traversalPath);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000502 mSnapshots.back()->globalZ = it->get()->globalZ;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000503 std::iter_swap(it, mSnapshots.end() - 1);
504 mSnapshots.erase(mSnapshots.end() - 1);
505 }
506}
507
508void LayerSnapshotBuilder::update(const Args& args) {
Vishnu Nair92990e22023-02-24 20:01:05 +0000509 for (auto& snapshot : mSnapshots) {
510 clearChanges(*snapshot);
511 }
512
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000513 if (tryFastUpdate(args)) {
514 return;
515 }
516 updateSnapshots(args);
517}
518
Vishnu Naircfb2d252023-01-19 04:44:02 +0000519const LayerSnapshot& LayerSnapshotBuilder::updateSnapshotsInHierarchy(
520 const Args& args, const LayerHierarchy& hierarchy,
Vishnu Naird1f74982023-06-15 20:16:51 -0700521 LayerHierarchy::TraversalPath& traversalPath, const LayerSnapshot& parentSnapshot,
522 int depth) {
Vishnu Nair606d9d02023-08-19 14:20:18 -0700523 LLOG_ALWAYS_FATAL_WITH_TRACE_IF(depth > 50,
524 "Cycle detected in LayerSnapshotBuilder. See "
525 "builder_stack_overflow_transactions.winscope");
Vishnu Naird1f74982023-06-15 20:16:51 -0700526
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000527 const RequestedLayerState* layer = hierarchy.getLayer();
Vishnu Naircfb2d252023-01-19 04:44:02 +0000528 LayerSnapshot* snapshot = getSnapshot(traversalPath);
529 const bool newSnapshot = snapshot == nullptr;
Vishnu Naira02943f2023-06-03 13:44:46 -0700530 uint32_t primaryDisplayRotationFlags = getPrimaryDisplayRotationFlags(args.displays);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000531 if (newSnapshot) {
Vishnu Nair92990e22023-02-24 20:01:05 +0000532 snapshot = createSnapshot(traversalPath, *layer, parentSnapshot);
Vishnu Naira02943f2023-06-03 13:44:46 -0700533 snapshot->merge(*layer, /*forceUpdate=*/true, /*displayChanges=*/true, args.forceFullDamage,
534 primaryDisplayRotationFlags);
535 snapshot->changes |= RequestedLayerState::Changes::Created;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000536 }
Vishnu Nair52d56fd2023-07-20 17:02:43 +0000537
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000538 if (traversalPath.isRelative()) {
539 bool parentIsRelative = traversalPath.variant == LayerHierarchy::Variant::Relative;
540 updateRelativeState(*snapshot, parentSnapshot, parentIsRelative, args);
541 } else {
542 if (traversalPath.isAttached()) {
543 resetRelativeState(*snapshot);
544 }
Vishnu Nair92990e22023-02-24 20:01:05 +0000545 updateSnapshot(*snapshot, args, *layer, parentSnapshot, traversalPath);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000546 }
547
548 for (auto& [childHierarchy, variant] : hierarchy.mChildren) {
549 LayerHierarchy::ScopedAddToTraversalPath addChildToPath(traversalPath,
550 childHierarchy->getLayer()->id,
551 variant);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000552 const LayerSnapshot& childSnapshot =
Vishnu Naird1f74982023-06-15 20:16:51 -0700553 updateSnapshotsInHierarchy(args, *childHierarchy, traversalPath, *snapshot,
554 depth + 1);
Vishnu Nair42b918e2023-07-18 20:05:29 +0000555 updateFrameRateFromChildSnapshot(*snapshot, childSnapshot, args);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000556 }
Vishnu Naird47bcee2023-02-24 18:08:51 +0000557
Vishnu Naircfb2d252023-01-19 04:44:02 +0000558 return *snapshot;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000559}
560
561LayerSnapshot* LayerSnapshotBuilder::getSnapshot(uint32_t layerId) const {
562 if (layerId == UNASSIGNED_LAYER_ID) {
563 return nullptr;
564 }
565 LayerHierarchy::TraversalPath path{.id = layerId};
566 return getSnapshot(path);
567}
568
569LayerSnapshot* LayerSnapshotBuilder::getSnapshot(const LayerHierarchy::TraversalPath& id) const {
Vishnu Naira02943f2023-06-03 13:44:46 -0700570 auto it = mPathToSnapshot.find(id);
571 return it == mPathToSnapshot.end() ? nullptr : it->second;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000572}
573
Vishnu Nair92990e22023-02-24 20:01:05 +0000574LayerSnapshot* LayerSnapshotBuilder::createSnapshot(const LayerHierarchy::TraversalPath& path,
575 const RequestedLayerState& layer,
576 const LayerSnapshot& parentSnapshot) {
577 mSnapshots.emplace_back(std::make_unique<LayerSnapshot>(layer, path));
Vishnu Naircfb2d252023-01-19 04:44:02 +0000578 LayerSnapshot* snapshot = mSnapshots.back().get();
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000579 snapshot->globalZ = static_cast<size_t>(mSnapshots.size()) - 1;
Vishnu Nair491827d2024-04-29 23:43:26 +0000580 if (path.isClone() && !LayerHierarchy::isMirror(path.variant)) {
Vishnu Nair92990e22023-02-24 20:01:05 +0000581 snapshot->mirrorRootPath = parentSnapshot.mirrorRootPath;
582 }
Vishnu Nair491827d2024-04-29 23:43:26 +0000583 snapshot->ignoreLocalTransform =
584 path.isClone() && path.variant == LayerHierarchy::Variant::Detached_Mirror;
Vishnu Naira02943f2023-06-03 13:44:46 -0700585 mPathToSnapshot[path] = snapshot;
586
587 mIdToSnapshots.emplace(path.id, snapshot);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000588 return snapshot;
589}
590
Vishnu Nairfccd6362023-02-24 23:39:53 +0000591bool LayerSnapshotBuilder::sortSnapshotsByZ(const Args& args) {
Vishnu Naird47bcee2023-02-24 18:08:51 +0000592 if (!mResortSnapshots && args.forceUpdate == ForceUpdateFlags::NONE &&
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000593 !args.layerLifecycleManager.getGlobalChanges().any(
Chavi Weingarten92c7d8c2024-01-19 23:25:45 +0000594 RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Visibility |
595 RequestedLayerState::Changes::Input)) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000596 // We are not force updating and there are no hierarchy or visibility changes. Avoid sorting
597 // the snapshots.
Vishnu Nairfccd6362023-02-24 23:39:53 +0000598 return false;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000599 }
Vishnu Naircfb2d252023-01-19 04:44:02 +0000600 mResortSnapshots = false;
601
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000602 size_t globalZ = 0;
603 args.root.traverseInZOrder(
604 [this, &globalZ](const LayerHierarchy&,
605 const LayerHierarchy::TraversalPath& traversalPath) -> bool {
606 LayerSnapshot* snapshot = getSnapshot(traversalPath);
607 if (!snapshot) {
Vishnu Naira02943f2023-06-03 13:44:46 -0700608 return true;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000609 }
610
Vishnu Naircfb2d252023-01-19 04:44:02 +0000611 if (snapshot->getIsVisible() || snapshot->hasInputInfo()) {
Vishnu Nair80a5a702023-02-11 01:21:51 +0000612 updateVisibility(*snapshot, snapshot->getIsVisible());
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000613 size_t oldZ = snapshot->globalZ;
614 size_t newZ = globalZ++;
615 snapshot->globalZ = newZ;
616 if (oldZ == newZ) {
617 return true;
618 }
619 mSnapshots[newZ]->globalZ = oldZ;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000620 LLOGV(snapshot->sequence, "Made visible z=%zu -> %zu %s", oldZ, newZ,
621 snapshot->getDebugString().c_str());
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000622 std::iter_swap(mSnapshots.begin() + static_cast<ssize_t>(oldZ),
623 mSnapshots.begin() + static_cast<ssize_t>(newZ));
624 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000625 return true;
626 });
Vishnu Naircfb2d252023-01-19 04:44:02 +0000627 mNumInterestingSnapshots = (int)globalZ;
Vishnu Nairfccd6362023-02-24 23:39:53 +0000628 bool hasUnreachableSnapshots = false;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000629 while (globalZ < mSnapshots.size()) {
630 mSnapshots[globalZ]->globalZ = globalZ;
Vishnu Nair80a5a702023-02-11 01:21:51 +0000631 /* mark unreachable snapshots as explicitly invisible */
632 updateVisibility(*mSnapshots[globalZ], false);
Vishnu Naira02943f2023-06-03 13:44:46 -0700633 if (mSnapshots[globalZ]->reachablilty == LayerSnapshot::Reachablilty::Unreachable) {
Vishnu Nairfccd6362023-02-24 23:39:53 +0000634 hasUnreachableSnapshots = true;
635 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000636 globalZ++;
637 }
Vishnu Nairfccd6362023-02-24 23:39:53 +0000638 return hasUnreachableSnapshots;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000639}
640
641void LayerSnapshotBuilder::updateRelativeState(LayerSnapshot& snapshot,
642 const LayerSnapshot& parentSnapshot,
643 bool parentIsRelative, const Args& args) {
644 if (parentIsRelative) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000645 snapshot.isHiddenByPolicyFromRelativeParent =
646 parentSnapshot.isHiddenByPolicyFromParent || parentSnapshot.invalidTransform;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000647 if (args.includeMetadata) {
648 snapshot.relativeLayerMetadata = parentSnapshot.layerMetadata;
649 }
650 } else {
651 snapshot.isHiddenByPolicyFromRelativeParent =
652 parentSnapshot.isHiddenByPolicyFromRelativeParent;
653 if (args.includeMetadata) {
654 snapshot.relativeLayerMetadata = parentSnapshot.relativeLayerMetadata;
655 }
656 }
Vishnu Naira02943f2023-06-03 13:44:46 -0700657 if (snapshot.reachablilty == LayerSnapshot::Reachablilty::Unreachable) {
658 snapshot.reachablilty = LayerSnapshot::Reachablilty::ReachableByRelativeParent;
659 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000660}
661
Vishnu Nair42b918e2023-07-18 20:05:29 +0000662void LayerSnapshotBuilder::updateFrameRateFromChildSnapshot(LayerSnapshot& snapshot,
663 const LayerSnapshot& childSnapshot,
664 const Args& args) {
665 if (args.forceUpdate == ForceUpdateFlags::NONE &&
Vishnu Nair52d56fd2023-07-20 17:02:43 +0000666 !args.layerLifecycleManager.getGlobalChanges().any(
667 RequestedLayerState::Changes::Hierarchy) &&
668 !childSnapshot.changes.any(RequestedLayerState::Changes::FrameRate) &&
669 !snapshot.changes.any(RequestedLayerState::Changes::FrameRate)) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000670 return;
671 }
Vishnu Naircfb2d252023-01-19 04:44:02 +0000672
Vishnu Nair3fbe3262023-09-29 17:07:00 -0700673 using FrameRateCompatibility = scheduler::FrameRateCompatibility;
Rachel Leece6e0042023-06-27 11:22:54 -0700674 if (snapshot.frameRate.isValid()) {
Vishnu Nair42b918e2023-07-18 20:05:29 +0000675 // we already have a valid framerate.
676 return;
677 }
Vishnu Naircfb2d252023-01-19 04:44:02 +0000678
Vishnu Nair42b918e2023-07-18 20:05:29 +0000679 // We return whether this layer or its children has a vote. We ignore ExactOrMultiple votes
680 // for the same reason we are allowing touch boost for those layers. See
681 // RefreshRateSelector::rankFrameRates for details.
Rachel Leece6e0042023-06-27 11:22:54 -0700682 const auto layerVotedWithDefaultCompatibility = childSnapshot.frameRate.vote.rate.isValid() &&
683 childSnapshot.frameRate.vote.type == FrameRateCompatibility::Default;
Vishnu Nair42b918e2023-07-18 20:05:29 +0000684 const auto layerVotedWithNoVote =
Rachel Leece6e0042023-06-27 11:22:54 -0700685 childSnapshot.frameRate.vote.type == FrameRateCompatibility::NoVote;
686 const auto layerVotedWithCategory =
687 childSnapshot.frameRate.category != FrameRateCategory::Default;
688 const auto layerVotedWithExactCompatibility = childSnapshot.frameRate.vote.rate.isValid() &&
689 childSnapshot.frameRate.vote.type == FrameRateCompatibility::Exact;
Vishnu Nair42b918e2023-07-18 20:05:29 +0000690
691 bool childHasValidFrameRate = layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
Rachel Leece6e0042023-06-27 11:22:54 -0700692 layerVotedWithCategory || layerVotedWithExactCompatibility;
Vishnu Nair42b918e2023-07-18 20:05:29 +0000693
694 // If we don't have a valid frame rate, but the children do, we set this
695 // layer as NoVote to allow the children to control the refresh rate
696 if (childHasValidFrameRate) {
697 snapshot.frameRate = scheduler::LayerInfo::FrameRate(Fps(), FrameRateCompatibility::NoVote);
698 snapshot.changes |= RequestedLayerState::Changes::FrameRate;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000699 }
700}
701
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000702void LayerSnapshotBuilder::resetRelativeState(LayerSnapshot& snapshot) {
703 snapshot.isHiddenByPolicyFromRelativeParent = false;
704 snapshot.relativeLayerMetadata.mMap.clear();
705}
706
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000707void LayerSnapshotBuilder::updateSnapshot(LayerSnapshot& snapshot, const Args& args,
708 const RequestedLayerState& requested,
709 const LayerSnapshot& parentSnapshot,
Vishnu Nair92990e22023-02-24 20:01:05 +0000710 const LayerHierarchy::TraversalPath& path) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000711 // Always update flags and visibility
712 ftl::Flags<RequestedLayerState::Changes> parentChanges = parentSnapshot.changes &
713 (RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Geometry |
714 RequestedLayerState::Changes::Visibility | RequestedLayerState::Changes::Metadata |
Vishnu Nairf13c8982023-12-02 11:26:09 -0800715 RequestedLayerState::Changes::AffectsChildren | RequestedLayerState::Changes::Input |
Vishnu Naira02943f2023-06-03 13:44:46 -0700716 RequestedLayerState::Changes::FrameRate | RequestedLayerState::Changes::GameMode);
717 snapshot.changes |= parentChanges;
718 if (args.displayChanges) snapshot.changes |= RequestedLayerState::Changes::Geometry;
719 snapshot.reachablilty = LayerSnapshot::Reachablilty::Reachable;
720 snapshot.clientChanges |= (parentSnapshot.clientChanges & layer_state_t::AFFECTS_CHILDREN);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000721 snapshot.isHiddenByPolicyFromParent = parentSnapshot.isHiddenByPolicyFromParent ||
Vishnu Nair3af0ec02023-02-10 04:13:48 +0000722 parentSnapshot.invalidTransform || requested.isHiddenByPolicy() ||
723 (args.excludeLayerIds.find(path.id) != args.excludeLayerIds.end());
Vishnu Nair80a5a702023-02-11 01:21:51 +0000724
Vishnu Nair92990e22023-02-24 20:01:05 +0000725 const bool forceUpdate = args.forceUpdate == ForceUpdateFlags::ALL ||
Vishnu Naira02943f2023-06-03 13:44:46 -0700726 snapshot.clientChanges & layer_state_t::eReparent ||
Vishnu Nair92990e22023-02-24 20:01:05 +0000727 snapshot.changes.any(RequestedLayerState::Changes::Visibility |
728 RequestedLayerState::Changes::Created);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000729
Vishnu Naira02943f2023-06-03 13:44:46 -0700730 if (forceUpdate || snapshot.clientChanges & layer_state_t::eLayerStackChanged) {
731 // If root layer, use the layer stack otherwise get the parent's layer stack.
732 snapshot.outputFilter.layerStack =
733 parentSnapshot.path == LayerHierarchy::TraversalPath::ROOT
734 ? requested.layerStack
735 : parentSnapshot.outputFilter.layerStack;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000736 }
737
Chavi Weingartenb74093a2023-10-11 20:29:59 +0000738 if (forceUpdate || snapshot.clientChanges & layer_state_t::eTrustedOverlayChanged) {
Vishnu Nair9e0017e2024-05-22 19:02:44 +0000739 switch (requested.trustedOverlay) {
740 case gui::TrustedOverlay::UNSET:
741 snapshot.trustedOverlay = parentSnapshot.trustedOverlay;
742 break;
743 case gui::TrustedOverlay::DISABLED:
744 snapshot.trustedOverlay = FlagManager::getInstance().override_trusted_overlay()
745 ? requested.trustedOverlay
746 : parentSnapshot.trustedOverlay;
747 break;
748 case gui::TrustedOverlay::ENABLED:
749 snapshot.trustedOverlay = requested.trustedOverlay;
750 break;
751 }
Chavi Weingartenb74093a2023-10-11 20:29:59 +0000752 }
753
Vishnu Nair92990e22023-02-24 20:01:05 +0000754 if (snapshot.isHiddenByPolicyFromParent &&
755 !snapshot.changes.test(RequestedLayerState::Changes::Created)) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000756 if (forceUpdate ||
Vishnu Naira02943f2023-06-03 13:44:46 -0700757 snapshot.changes.any(RequestedLayerState::Changes::Geometry |
Vishnu Nair494a2e42023-11-10 17:21:19 -0800758 RequestedLayerState::Changes::BufferSize |
Vishnu Naircfb2d252023-01-19 04:44:02 +0000759 RequestedLayerState::Changes::Input)) {
760 updateInput(snapshot, requested, parentSnapshot, path, args);
761 }
762 return;
763 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000764
Vishnu Naira02943f2023-06-03 13:44:46 -0700765 if (forceUpdate || snapshot.changes.any(RequestedLayerState::Changes::Mirror)) {
766 // Display mirrors are always placed in a VirtualDisplay so we never want to capture layers
767 // marked as skip capture
768 snapshot.handleSkipScreenshotFlag = parentSnapshot.handleSkipScreenshotFlag ||
769 (requested.layerStackToMirror != ui::INVALID_LAYER_STACK);
770 }
771
772 if (forceUpdate || snapshot.clientChanges & layer_state_t::eAlphaChanged) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000773 snapshot.color.a = parentSnapshot.color.a * requested.color.a;
774 snapshot.alpha = snapshot.color.a;
Vishnu Nair29354ec2023-03-28 18:51:28 -0700775 snapshot.inputInfo.alpha = snapshot.color.a;
Vishnu Naira02943f2023-06-03 13:44:46 -0700776 }
Vishnu Nair29354ec2023-03-28 18:51:28 -0700777
Vishnu Naira02943f2023-06-03 13:44:46 -0700778 if (forceUpdate || snapshot.clientChanges & layer_state_t::eFlagsChanged) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000779 snapshot.isSecure =
780 parentSnapshot.isSecure || (requested.flags & layer_state_t::eLayerSecure);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000781 snapshot.outputFilter.toInternalDisplay = parentSnapshot.outputFilter.toInternalDisplay ||
782 (requested.flags & layer_state_t::eLayerSkipScreenshot);
Vishnu Naira02943f2023-06-03 13:44:46 -0700783 }
784
Vishnu Naira02943f2023-06-03 13:44:46 -0700785 if (forceUpdate || snapshot.clientChanges & layer_state_t::eStretchChanged) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000786 snapshot.stretchEffect = (requested.stretchEffect.hasEffect())
787 ? requested.stretchEffect
788 : parentSnapshot.stretchEffect;
Vishnu Naira02943f2023-06-03 13:44:46 -0700789 }
790
791 if (forceUpdate || snapshot.clientChanges & layer_state_t::eColorTransformChanged) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000792 if (!parentSnapshot.colorTransformIsIdentity) {
793 snapshot.colorTransform = parentSnapshot.colorTransform * requested.colorTransform;
794 snapshot.colorTransformIsIdentity = false;
795 } else {
796 snapshot.colorTransform = requested.colorTransform;
797 snapshot.colorTransformIsIdentity = !requested.hasColorTransform;
798 }
Vishnu Naira02943f2023-06-03 13:44:46 -0700799 }
800
Nergi Rahardi10fbacd2024-05-21 09:37:59 +0000801 if (forceUpdate || snapshot.changes.test(RequestedLayerState::Changes::GameMode)) {
802 snapshot.gameMode = requested.metadata.has(gui::METADATA_GAME_MODE)
803 ? requested.gameMode
804 : parentSnapshot.gameMode;
Garfield Tanad34a682024-05-21 15:25:35 +0000805 updateMetadata(snapshot, requested, args);
806 if (args.includeMetadata) {
807 snapshot.layerMetadata = parentSnapshot.layerMetadata;
808 snapshot.layerMetadata.merge(requested.metadata);
809 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000810 }
811
Vishnu Naira02943f2023-06-03 13:44:46 -0700812 if (forceUpdate || snapshot.clientChanges & layer_state_t::eFixedTransformHintChanged ||
Vishnu Nairb76d99a2023-03-19 18:22:31 -0700813 args.displayChanges) {
814 snapshot.fixedTransformHint = requested.fixedTransformHint != ui::Transform::ROT_INVALID
815 ? requested.fixedTransformHint
816 : parentSnapshot.fixedTransformHint;
817
818 if (snapshot.fixedTransformHint != ui::Transform::ROT_INVALID) {
819 snapshot.transformHint = snapshot.fixedTransformHint;
820 } else {
821 const auto display = args.displays.get(snapshot.outputFilter.layerStack);
822 snapshot.transformHint = display.has_value()
823 ? std::make_optional<>(display->get().transformHint)
824 : std::nullopt;
825 }
826 }
827
Vishnu Nair42b918e2023-07-18 20:05:29 +0000828 if (forceUpdate ||
Vishnu Nair52d56fd2023-07-20 17:02:43 +0000829 args.layerLifecycleManager.getGlobalChanges().any(
830 RequestedLayerState::Changes::Hierarchy) ||
Vishnu Nair42b918e2023-07-18 20:05:29 +0000831 snapshot.changes.any(RequestedLayerState::Changes::FrameRate |
832 RequestedLayerState::Changes::Hierarchy)) {
Rachel Leea021bb02023-11-20 21:51:09 -0800833 const bool shouldOverrideChildren = parentSnapshot.frameRateSelectionStrategy ==
Rachel Lee58cc90d2023-09-05 18:50:20 -0700834 scheduler::LayerInfo::FrameRateSelectionStrategy::OverrideChildren;
Rachel Leea021bb02023-11-20 21:51:09 -0800835 const bool propagationAllowed = parentSnapshot.frameRateSelectionStrategy !=
Rachel Lee70f7b692023-11-22 11:24:02 -0800836 scheduler::LayerInfo::FrameRateSelectionStrategy::Self;
Rachel Leea021bb02023-11-20 21:51:09 -0800837 if ((!requested.requestedFrameRate.isValid() && propagationAllowed) ||
838 shouldOverrideChildren) {
Vishnu Nair30515cb2023-10-19 21:54:08 -0700839 snapshot.inheritedFrameRate = parentSnapshot.inheritedFrameRate;
840 } else {
841 snapshot.inheritedFrameRate = requested.requestedFrameRate;
842 }
843 // Set the framerate as the inherited frame rate and allow children to override it if
844 // needed.
845 snapshot.frameRate = snapshot.inheritedFrameRate;
Vishnu Nair52d56fd2023-07-20 17:02:43 +0000846 snapshot.changes |= RequestedLayerState::Changes::FrameRate;
Vishnu Naird47bcee2023-02-24 18:08:51 +0000847 }
848
Rachel Lee58cc90d2023-09-05 18:50:20 -0700849 if (forceUpdate || snapshot.clientChanges & layer_state_t::eFrameRateSelectionStrategyChanged) {
Rachel Leea021bb02023-11-20 21:51:09 -0800850 if (parentSnapshot.frameRateSelectionStrategy ==
851 scheduler::LayerInfo::FrameRateSelectionStrategy::OverrideChildren) {
852 snapshot.frameRateSelectionStrategy =
853 scheduler::LayerInfo::FrameRateSelectionStrategy::OverrideChildren;
854 } else {
855 const auto strategy = scheduler::LayerInfo::convertFrameRateSelectionStrategy(
856 requested.frameRateSelectionStrategy);
857 snapshot.frameRateSelectionStrategy = strategy;
858 }
Rachel Lee58cc90d2023-09-05 18:50:20 -0700859 }
860
Vishnu Nair3d8565a2023-06-30 07:23:24 +0000861 if (forceUpdate || snapshot.clientChanges & layer_state_t::eFrameRateSelectionPriority) {
862 snapshot.frameRateSelectionPriority =
863 (requested.frameRateSelectionPriority == Layer::PRIORITY_UNSET)
864 ? parentSnapshot.frameRateSelectionPriority
865 : requested.frameRateSelectionPriority;
866 }
867
Vishnu Naira02943f2023-06-03 13:44:46 -0700868 if (forceUpdate ||
869 snapshot.clientChanges &
870 (layer_state_t::eBackgroundBlurRadiusChanged | layer_state_t::eBlurRegionsChanged |
871 layer_state_t::eAlphaChanged)) {
Vishnu Nair80a5a702023-02-11 01:21:51 +0000872 snapshot.backgroundBlurRadius = args.supportsBlur
873 ? static_cast<int>(parentSnapshot.color.a * (float)requested.backgroundBlurRadius)
874 : 0;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000875 snapshot.blurRegions = requested.blurRegions;
Vishnu Nair80a5a702023-02-11 01:21:51 +0000876 for (auto& region : snapshot.blurRegions) {
877 region.alpha = region.alpha * snapshot.color.a;
878 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000879 }
880
Vishnu Naira02943f2023-06-03 13:44:46 -0700881 if (forceUpdate || snapshot.changes.any(RequestedLayerState::Changes::Geometry)) {
882 uint32_t primaryDisplayRotationFlags = getPrimaryDisplayRotationFlags(args.displays);
Vishnu Nairb76d99a2023-03-19 18:22:31 -0700883 updateLayerBounds(snapshot, requested, parentSnapshot, primaryDisplayRotationFlags);
Vishnu Naira02943f2023-06-03 13:44:46 -0700884 }
885
886 if (forceUpdate || snapshot.clientChanges & layer_state_t::eCornerRadiusChanged ||
Vishnu Nair0808ae62023-08-07 21:42:42 -0700887 snapshot.changes.any(RequestedLayerState::Changes::Geometry |
888 RequestedLayerState::Changes::BufferUsageFlags)) {
889 updateRoundedCorner(snapshot, requested, parentSnapshot, args);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000890 }
891
Vishnu Naira02943f2023-06-03 13:44:46 -0700892 if (forceUpdate || snapshot.clientChanges & layer_state_t::eShadowRadiusChanged ||
893 snapshot.changes.any(RequestedLayerState::Changes::Geometry)) {
894 updateShadows(snapshot, requested, args.globalShadowSettings);
895 }
896
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000897 if (forceUpdate ||
Vishnu Naira02943f2023-06-03 13:44:46 -0700898 snapshot.changes.any(RequestedLayerState::Changes::Geometry |
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000899 RequestedLayerState::Changes::Input)) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000900 updateInput(snapshot, requested, parentSnapshot, path, args);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000901 }
902
903 // computed snapshot properties
Alec Mouri994761f2023-08-04 21:50:55 +0000904 snapshot.forceClientComposition =
905 snapshot.shadowSettings.length > 0 || snapshot.stretchEffect.hasEffect();
Vishnu Nairc765c6c2023-02-23 00:08:01 +0000906 snapshot.contentOpaque = snapshot.isContentOpaque();
907 snapshot.isOpaque = snapshot.contentOpaque && !snapshot.roundedCorner.hasRoundedCorners() &&
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000908 snapshot.color.a == 1.f;
909 snapshot.blendMode = getBlendMode(snapshot, requested);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000910 LLOGV(snapshot.sequence,
Vishnu Nair92990e22023-02-24 20:01:05 +0000911 "%supdated %s changes:%s parent:%s requested:%s requested:%s from parent %s",
912 args.forceUpdate == ForceUpdateFlags::ALL ? "Force " : "",
913 snapshot.getDebugString().c_str(), snapshot.changes.string().c_str(),
914 parentSnapshot.changes.string().c_str(), requested.changes.string().c_str(),
915 std::to_string(requested.what).c_str(), parentSnapshot.getDebugString().c_str());
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000916}
917
918void LayerSnapshotBuilder::updateRoundedCorner(LayerSnapshot& snapshot,
919 const RequestedLayerState& requested,
Vishnu Nair0808ae62023-08-07 21:42:42 -0700920 const LayerSnapshot& parentSnapshot,
921 const Args& args) {
922 if (args.skipRoundCornersWhenProtected && requested.isProtected()) {
923 snapshot.roundedCorner = RoundedCornerState();
924 return;
925 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000926 snapshot.roundedCorner = RoundedCornerState();
927 RoundedCornerState parentRoundedCorner;
928 if (parentSnapshot.roundedCorner.hasRoundedCorners()) {
929 parentRoundedCorner = parentSnapshot.roundedCorner;
930 ui::Transform t = snapshot.localTransform.inverse();
931 parentRoundedCorner.cropRect = t.transform(parentRoundedCorner.cropRect);
932 parentRoundedCorner.radius.x *= t.getScaleX();
933 parentRoundedCorner.radius.y *= t.getScaleY();
934 }
935
936 FloatRect layerCropRect = snapshot.croppedBufferSize.toFloatRect();
937 const vec2 radius(requested.cornerRadius, requested.cornerRadius);
938 RoundedCornerState layerSettings(layerCropRect, radius);
939 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && !layerCropRect.isEmpty();
940 const bool parentRoundedCornerValid = parentRoundedCorner.hasRoundedCorners();
941 if (layerSettingsValid && parentRoundedCornerValid) {
942 // If the parent and the layer have rounded corner settings, use the parent settings if
943 // the parent crop is entirely inside the layer crop. This has limitations and cause
944 // rendering artifacts. See b/200300845 for correct fix.
945 if (parentRoundedCorner.cropRect.left > layerCropRect.left &&
946 parentRoundedCorner.cropRect.top > layerCropRect.top &&
947 parentRoundedCorner.cropRect.right < layerCropRect.right &&
948 parentRoundedCorner.cropRect.bottom < layerCropRect.bottom) {
949 snapshot.roundedCorner = parentRoundedCorner;
950 } else {
951 snapshot.roundedCorner = layerSettings;
952 }
953 } else if (layerSettingsValid) {
954 snapshot.roundedCorner = layerSettings;
955 } else if (parentRoundedCornerValid) {
956 snapshot.roundedCorner = parentRoundedCorner;
957 }
958}
959
960void LayerSnapshotBuilder::updateLayerBounds(LayerSnapshot& snapshot,
961 const RequestedLayerState& requested,
962 const LayerSnapshot& parentSnapshot,
Vishnu Nairb76d99a2023-03-19 18:22:31 -0700963 uint32_t primaryDisplayRotationFlags) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000964 snapshot.geomLayerTransform = parentSnapshot.geomLayerTransform * snapshot.localTransform;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000965 const bool transformWasInvalid = snapshot.invalidTransform;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000966 snapshot.invalidTransform = !LayerSnapshot::isTransformValid(snapshot.geomLayerTransform);
967 if (snapshot.invalidTransform) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000968 auto& t = snapshot.geomLayerTransform;
969 auto& requestedT = requested.requestedTransform;
970 std::string transformDebug =
971 base::StringPrintf(" transform={%f,%f,%f,%f} requestedTransform={%f,%f,%f,%f}",
972 t.dsdx(), t.dsdy(), t.dtdx(), t.dtdy(), requestedT.dsdx(),
973 requestedT.dsdy(), requestedT.dtdx(), requestedT.dtdy());
974 std::string bufferDebug;
975 if (requested.externalTexture) {
Vishnu Nairb76d99a2023-03-19 18:22:31 -0700976 auto unRotBuffer = requested.getUnrotatedBufferSize(primaryDisplayRotationFlags);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000977 auto& destFrame = requested.destinationFrame;
978 bufferDebug = base::StringPrintf(" buffer={%d,%d} displayRot=%d"
979 " destFrame={%d,%d,%d,%d} unRotBuffer={%d,%d}",
980 requested.externalTexture->getWidth(),
981 requested.externalTexture->getHeight(),
Vishnu Nairb76d99a2023-03-19 18:22:31 -0700982 primaryDisplayRotationFlags, destFrame.left,
983 destFrame.top, destFrame.right, destFrame.bottom,
Vishnu Naircfb2d252023-01-19 04:44:02 +0000984 unRotBuffer.getHeight(), unRotBuffer.getWidth());
985 }
986 ALOGW("Resetting transform for %s because it is invalid.%s%s",
987 snapshot.getDebugString().c_str(), transformDebug.c_str(), bufferDebug.c_str());
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000988 snapshot.geomLayerTransform.reset();
989 }
Vishnu Naircfb2d252023-01-19 04:44:02 +0000990 if (transformWasInvalid != snapshot.invalidTransform) {
991 // If transform is invalid, the layer will be hidden.
992 mResortSnapshots = true;
993 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000994 snapshot.geomInverseLayerTransform = snapshot.geomLayerTransform.inverse();
995
996 FloatRect parentBounds = parentSnapshot.geomLayerBounds;
997 parentBounds = snapshot.localTransform.inverse().transform(parentBounds);
998 snapshot.geomLayerBounds =
999 (requested.externalTexture) ? snapshot.bufferSize.toFloatRect() : parentBounds;
1000 if (!requested.crop.isEmpty()) {
1001 snapshot.geomLayerBounds = snapshot.geomLayerBounds.intersect(requested.crop.toFloatRect());
1002 }
1003 snapshot.geomLayerBounds = snapshot.geomLayerBounds.intersect(parentBounds);
1004 snapshot.transformedBounds = snapshot.geomLayerTransform.transform(snapshot.geomLayerBounds);
Vishnu Naircfb2d252023-01-19 04:44:02 +00001005 const Rect geomLayerBoundsWithoutTransparentRegion =
1006 RequestedLayerState::reduce(Rect(snapshot.geomLayerBounds),
1007 requested.transparentRegion);
1008 snapshot.transformedBoundsWithoutTransparentRegion =
1009 snapshot.geomLayerTransform.transform(geomLayerBoundsWithoutTransparentRegion);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001010 snapshot.parentTransform = parentSnapshot.geomLayerTransform;
1011
1012 // Subtract the transparent region and snap to the bounds
Vishnu Naircfb2d252023-01-19 04:44:02 +00001013 const Rect bounds =
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001014 RequestedLayerState::reduce(snapshot.croppedBufferSize, requested.transparentRegion);
Vishnu Naircfb2d252023-01-19 04:44:02 +00001015 if (requested.potentialCursor) {
1016 snapshot.cursorFrame = snapshot.geomLayerTransform.transform(bounds);
1017 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001018}
1019
Vishnu Naira02943f2023-06-03 13:44:46 -07001020void LayerSnapshotBuilder::updateShadows(LayerSnapshot& snapshot, const RequestedLayerState&,
Vishnu Naird9e4f462023-10-06 04:05:45 +00001021 const ShadowSettings& globalShadowSettings) {
1022 if (snapshot.shadowSettings.length > 0.f) {
1023 snapshot.shadowSettings.ambientColor = globalShadowSettings.ambientColor;
1024 snapshot.shadowSettings.spotColor = globalShadowSettings.spotColor;
1025 snapshot.shadowSettings.lightPos = globalShadowSettings.lightPos;
1026 snapshot.shadowSettings.lightRadius = globalShadowSettings.lightRadius;
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001027
1028 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
1029 // it if transparent regions are present. This may not be necessary since shadows are
1030 // typically cast by layers without transparent regions.
1031 snapshot.shadowSettings.boundaries = snapshot.geomLayerBounds;
1032
1033 // If the casting layer is translucent, we need to fill in the shadow underneath the
1034 // layer. Otherwise the generated shadow will only be shown around the casting layer.
1035 snapshot.shadowSettings.casterIsTranslucent =
1036 !snapshot.isContentOpaque() || (snapshot.alpha < 1.0f);
1037 snapshot.shadowSettings.ambientColor *= snapshot.alpha;
1038 snapshot.shadowSettings.spotColor *= snapshot.alpha;
1039 }
1040}
1041
1042void LayerSnapshotBuilder::updateInput(LayerSnapshot& snapshot,
1043 const RequestedLayerState& requested,
1044 const LayerSnapshot& parentSnapshot,
Vishnu Naircfb2d252023-01-19 04:44:02 +00001045 const LayerHierarchy::TraversalPath& path,
1046 const Args& args) {
Prabir Pradhancf359192024-03-20 00:42:57 +00001047 using InputConfig = gui::WindowInfo::InputConfig;
1048
Vishnu Naircfb2d252023-01-19 04:44:02 +00001049 if (requested.windowInfoHandle) {
1050 snapshot.inputInfo = *requested.windowInfoHandle->getInfo();
1051 } else {
1052 snapshot.inputInfo = {};
Vishnu Nair40d02282023-02-28 21:11:40 +00001053 // b/271132344 revisit this and see if we can always use the layers uid/pid
1054 snapshot.inputInfo.name = requested.name;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00001055 snapshot.inputInfo.ownerUid = gui::Uid{requested.ownerUid};
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00001056 snapshot.inputInfo.ownerPid = gui::Pid{requested.ownerPid};
Vishnu Naircfb2d252023-01-19 04:44:02 +00001057 }
Vishnu Nair29354ec2023-03-28 18:51:28 -07001058 snapshot.touchCropId = requested.touchCropId;
Vishnu Naircfb2d252023-01-19 04:44:02 +00001059
Vishnu Nair93b8b792023-02-27 19:40:24 +00001060 snapshot.inputInfo.id = static_cast<int32_t>(snapshot.uniqueSequence);
Linnan Li13bf76a2024-05-05 19:18:02 +08001061 snapshot.inputInfo.displayId =
1062 ui::LogicalDisplayId{static_cast<int32_t>(snapshot.outputFilter.layerStack.id)};
Vishnu Nairf13c8982023-12-02 11:26:09 -08001063 snapshot.inputInfo.touchOcclusionMode = requested.hasInputInfo()
1064 ? requested.windowInfoHandle->getInfo()->touchOcclusionMode
1065 : parentSnapshot.inputInfo.touchOcclusionMode;
Vishnu Nair59a6be32024-01-29 10:26:21 -08001066 snapshot.inputInfo.canOccludePresentation = parentSnapshot.inputInfo.canOccludePresentation ||
1067 (requested.flags & layer_state_t::eCanOccludePresentation);
Vishnu Nairf13c8982023-12-02 11:26:09 -08001068 if (requested.dropInputMode == gui::DropInputMode::ALL ||
1069 parentSnapshot.dropInputMode == gui::DropInputMode::ALL) {
1070 snapshot.dropInputMode = gui::DropInputMode::ALL;
1071 } else if (requested.dropInputMode == gui::DropInputMode::OBSCURED ||
1072 parentSnapshot.dropInputMode == gui::DropInputMode::OBSCURED) {
1073 snapshot.dropInputMode = gui::DropInputMode::OBSCURED;
1074 } else {
1075 snapshot.dropInputMode = gui::DropInputMode::NONE;
1076 }
1077
Prabir Pradhancf359192024-03-20 00:42:57 +00001078 if (snapshot.isSecure ||
Arpit Singh490ccc92024-04-30 14:26:21 +00001079 parentSnapshot.inputInfo.inputConfig.test(InputConfig::SENSITIVE_FOR_PRIVACY)) {
1080 snapshot.inputInfo.inputConfig |= InputConfig::SENSITIVE_FOR_PRIVACY;
Prabir Pradhancf359192024-03-20 00:42:57 +00001081 }
1082
Vishnu Nair29354ec2023-03-28 18:51:28 -07001083 updateVisibility(snapshot, snapshot.isVisible);
Vishnu Naircfb2d252023-01-19 04:44:02 +00001084 if (!needsInputInfo(snapshot, requested)) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001085 return;
1086 }
1087
Vishnu Naircfb2d252023-01-19 04:44:02 +00001088 static frontend::DisplayInfo sDefaultInfo = {.isSecure = false};
1089 const std::optional<frontend::DisplayInfo> displayInfoOpt =
1090 args.displays.get(snapshot.outputFilter.layerStack);
1091 bool noValidDisplay = !displayInfoOpt.has_value();
1092 auto displayInfo = displayInfoOpt.value_or(sDefaultInfo);
1093
1094 if (!requested.windowInfoHandle) {
Prabir Pradhancf359192024-03-20 00:42:57 +00001095 snapshot.inputInfo.inputConfig = InputConfig::NO_INPUT_CHANNEL;
Vishnu Naircfb2d252023-01-19 04:44:02 +00001096 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001097 fillInputFrameInfo(snapshot.inputInfo, displayInfo.transform, snapshot);
1098
1099 if (noValidDisplay) {
1100 // Do not let the window receive touches if it is not associated with a valid display
1101 // transform. We still allow the window to receive keys and prevent ANRs.
Prabir Pradhancf359192024-03-20 00:42:57 +00001102 snapshot.inputInfo.inputConfig |= InputConfig::NOT_TOUCHABLE;
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001103 }
1104
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001105 snapshot.inputInfo.alpha = snapshot.color.a;
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001106
1107 handleDropInputMode(snapshot, parentSnapshot);
1108
1109 // If the window will be blacked out on a display because the display does not have the secure
1110 // flag and the layer has the secure flag set, then drop input.
1111 if (!displayInfo.isSecure && snapshot.isSecure) {
Prabir Pradhancf359192024-03-20 00:42:57 +00001112 snapshot.inputInfo.inputConfig |= InputConfig::DROP_INPUT;
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001113 }
1114
Vishnu Naira02943f2023-06-03 13:44:46 -07001115 if (requested.touchCropId != UNASSIGNED_LAYER_ID || path.isClone()) {
Vishnu Nair29354ec2023-03-28 18:51:28 -07001116 mNeedsTouchableRegionCrop.insert(path);
Vishnu Naira02943f2023-06-03 13:44:46 -07001117 }
1118 auto cropLayerSnapshot = getSnapshot(requested.touchCropId);
1119 if (!cropLayerSnapshot && snapshot.inputInfo.replaceTouchableRegionWithCrop) {
Vishnu Nair29354ec2023-03-28 18:51:28 -07001120 FloatRect inputBounds = getInputBounds(snapshot, /*fillParentBounds=*/true).first;
Vishnu Nairfed7c122023-03-18 01:54:43 +00001121 Rect inputBoundsInDisplaySpace =
Vishnu Nair29354ec2023-03-28 18:51:28 -07001122 getInputBoundsInDisplaySpace(snapshot, inputBounds, displayInfo.transform);
1123 snapshot.inputInfo.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001124 }
1125
1126 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
1127 // if it was set by WM for a known system overlay
Vishnu Nair9e0017e2024-05-22 19:02:44 +00001128 if (snapshot.trustedOverlay == gui::TrustedOverlay::ENABLED) {
Prabir Pradhancf359192024-03-20 00:42:57 +00001129 snapshot.inputInfo.inputConfig |= InputConfig::TRUSTED_OVERLAY;
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001130 }
1131
Vishnu Nair494a2e42023-11-10 17:21:19 -08001132 snapshot.inputInfo.contentSize = snapshot.croppedBufferSize.getSize();
1133
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001134 // If the layer is a clone, we need to crop the input region to cloned root to prevent
1135 // touches from going outside the cloned area.
1136 if (path.isClone()) {
Prabir Pradhancf359192024-03-20 00:42:57 +00001137 snapshot.inputInfo.inputConfig |= InputConfig::CLONE;
Vishnu Nair444f3952023-04-11 13:01:02 -07001138 // Cloned layers shouldn't handle watch outside since their z order is not determined by
1139 // WM or the client.
Prabir Pradhancf359192024-03-20 00:42:57 +00001140 snapshot.inputInfo.inputConfig.clear(InputConfig::WATCH_OUTSIDE_TOUCH);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001141 }
1142}
1143
1144std::vector<std::unique_ptr<LayerSnapshot>>& LayerSnapshotBuilder::getSnapshots() {
1145 return mSnapshots;
1146}
1147
Vishnu Naircfb2d252023-01-19 04:44:02 +00001148void LayerSnapshotBuilder::forEachVisibleSnapshot(const ConstVisitor& visitor) const {
1149 for (int i = 0; i < mNumInterestingSnapshots; i++) {
1150 LayerSnapshot& snapshot = *mSnapshots[(size_t)i];
1151 if (!snapshot.isVisible) continue;
1152 visitor(snapshot);
1153 }
1154}
1155
Vishnu Nair3af0ec02023-02-10 04:13:48 +00001156// Visit each visible snapshot in z-order
1157void LayerSnapshotBuilder::forEachVisibleSnapshot(const ConstVisitor& visitor,
1158 const LayerHierarchy& root) const {
1159 root.traverseInZOrder(
1160 [this, visitor](const LayerHierarchy&,
1161 const LayerHierarchy::TraversalPath& traversalPath) -> bool {
1162 LayerSnapshot* snapshot = getSnapshot(traversalPath);
1163 if (snapshot && snapshot->isVisible) {
1164 visitor(*snapshot);
1165 }
1166 return true;
1167 });
1168}
1169
Vishnu Naircfb2d252023-01-19 04:44:02 +00001170void LayerSnapshotBuilder::forEachVisibleSnapshot(const Visitor& visitor) {
1171 for (int i = 0; i < mNumInterestingSnapshots; i++) {
1172 std::unique_ptr<LayerSnapshot>& snapshot = mSnapshots.at((size_t)i);
1173 if (!snapshot->isVisible) continue;
1174 visitor(snapshot);
1175 }
1176}
1177
1178void LayerSnapshotBuilder::forEachInputSnapshot(const ConstVisitor& visitor) const {
1179 for (int i = mNumInterestingSnapshots - 1; i >= 0; i--) {
1180 LayerSnapshot& snapshot = *mSnapshots[(size_t)i];
1181 if (!snapshot.hasInputInfo()) continue;
1182 visitor(snapshot);
1183 }
1184}
1185
Vishnu Nair29354ec2023-03-28 18:51:28 -07001186void LayerSnapshotBuilder::updateTouchableRegionCrop(const Args& args) {
1187 if (mNeedsTouchableRegionCrop.empty()) {
1188 return;
1189 }
1190
1191 static constexpr ftl::Flags<RequestedLayerState::Changes> AFFECTS_INPUT =
1192 RequestedLayerState::Changes::Visibility | RequestedLayerState::Changes::Created |
1193 RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Geometry |
1194 RequestedLayerState::Changes::Input;
1195
1196 if (args.forceUpdate != ForceUpdateFlags::ALL &&
Vishnu Naira02943f2023-06-03 13:44:46 -07001197 !args.layerLifecycleManager.getGlobalChanges().any(AFFECTS_INPUT) && !args.displayChanges) {
Vishnu Nair29354ec2023-03-28 18:51:28 -07001198 return;
1199 }
1200
1201 for (auto& path : mNeedsTouchableRegionCrop) {
1202 frontend::LayerSnapshot* snapshot = getSnapshot(path);
1203 if (!snapshot) {
1204 continue;
1205 }
Vishnu Naira02943f2023-06-03 13:44:46 -07001206 LLOGV(snapshot->sequence, "updateTouchableRegionCrop=%s",
1207 snapshot->getDebugString().c_str());
Vishnu Nair29354ec2023-03-28 18:51:28 -07001208 const std::optional<frontend::DisplayInfo> displayInfoOpt =
1209 args.displays.get(snapshot->outputFilter.layerStack);
1210 static frontend::DisplayInfo sDefaultInfo = {.isSecure = false};
1211 auto displayInfo = displayInfoOpt.value_or(sDefaultInfo);
1212
1213 bool needsUpdate =
1214 args.forceUpdate == ForceUpdateFlags::ALL || snapshot->changes.any(AFFECTS_INPUT);
1215 auto cropLayerSnapshot = getSnapshot(snapshot->touchCropId);
1216 needsUpdate =
1217 needsUpdate || (cropLayerSnapshot && cropLayerSnapshot->changes.any(AFFECTS_INPUT));
1218 auto clonedRootSnapshot = path.isClone() ? getSnapshot(snapshot->mirrorRootPath) : nullptr;
1219 needsUpdate = needsUpdate ||
1220 (clonedRootSnapshot && clonedRootSnapshot->changes.any(AFFECTS_INPUT));
1221
1222 if (!needsUpdate) {
1223 continue;
1224 }
1225
1226 if (snapshot->inputInfo.replaceTouchableRegionWithCrop) {
1227 Rect inputBoundsInDisplaySpace;
1228 if (!cropLayerSnapshot) {
1229 FloatRect inputBounds = getInputBounds(*snapshot, /*fillParentBounds=*/true).first;
1230 inputBoundsInDisplaySpace =
1231 getInputBoundsInDisplaySpace(*snapshot, inputBounds, displayInfo.transform);
1232 } else {
1233 FloatRect inputBounds =
1234 getInputBounds(*cropLayerSnapshot, /*fillParentBounds=*/true).first;
1235 inputBoundsInDisplaySpace =
1236 getInputBoundsInDisplaySpace(*cropLayerSnapshot, inputBounds,
1237 displayInfo.transform);
1238 }
1239 snapshot->inputInfo.touchableRegion = Region(inputBoundsInDisplaySpace);
1240 } else if (cropLayerSnapshot) {
1241 FloatRect inputBounds =
1242 getInputBounds(*cropLayerSnapshot, /*fillParentBounds=*/true).first;
1243 Rect inputBoundsInDisplaySpace =
1244 getInputBoundsInDisplaySpace(*cropLayerSnapshot, inputBounds,
1245 displayInfo.transform);
Chavi Weingarten1ba381e2024-01-09 21:54:11 +00001246 snapshot->inputInfo.touchableRegion =
1247 snapshot->inputInfo.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair29354ec2023-03-28 18:51:28 -07001248 }
1249
1250 // If the layer is a clone, we need to crop the input region to cloned root to prevent
1251 // touches from going outside the cloned area.
1252 if (clonedRootSnapshot) {
1253 const Rect rect =
1254 displayInfo.transform.transform(Rect{clonedRootSnapshot->transformedBounds});
1255 snapshot->inputInfo.touchableRegion =
1256 snapshot->inputInfo.touchableRegion.intersect(rect);
1257 }
1258 }
1259}
1260
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001261} // namespace android::surfaceflinger::frontend