blob: f2497d4bc8d90fbc3a86f3e1dbc1a8fa1a38ca94 [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
Dominik Laskowski6b049ff2023-01-29 15:46:45 -050025#include <ftl/small_map.h>
Vishnu Nairb76d99a2023-03-19 18:22:31 -070026#include <gui/TraceUtils.h>
Vishnu Naira02943f2023-06-03 13:44:46 -070027#include <ui/DisplayMap.h>
Dominik Laskowski6b049ff2023-01-29 15:46:45 -050028#include <ui/FloatRect.h>
29
Vishnu Nair8fc721b2022-12-22 20:06:32 +000030#include "DisplayHardware/HWC2.h"
31#include "DisplayHardware/Hal.h"
Vishnu Nair3d8565a2023-06-30 07:23:24 +000032#include "Layer.h" // eFrameRateSelectionPriority constants
Vishnu Naircfb2d252023-01-19 04:44:02 +000033#include "LayerLog.h"
Vishnu Nairb76d99a2023-03-19 18:22:31 -070034#include "LayerSnapshotBuilder.h"
Vishnu Naircfb2d252023-01-19 04:44:02 +000035#include "TimeStats/TimeStats.h"
Vishnu Naird1f74982023-06-15 20:16:51 -070036#include "Tracing/TransactionTracing.h"
Vishnu Nair8fc721b2022-12-22 20:06:32 +000037
38namespace android::surfaceflinger::frontend {
39
40using namespace ftl::flag_operators;
41
42namespace {
Dominik Laskowski6b049ff2023-01-29 15:46:45 -050043
44FloatRect getMaxDisplayBounds(const DisplayInfos& displays) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +000045 const ui::Size maxSize = [&displays] {
46 if (displays.empty()) return ui::Size{5000, 5000};
47
48 return std::accumulate(displays.begin(), displays.end(), ui::kEmptySize,
49 [](ui::Size size, const auto& pair) -> ui::Size {
50 const auto& display = pair.second;
51 return {std::max(size.getWidth(), display.info.logicalWidth),
52 std::max(size.getHeight(), display.info.logicalHeight)};
53 });
54 }();
55
56 // Ignore display bounds for now since they will be computed later. Use a large Rect bound
57 // to ensure it's bigger than an actual display will be.
58 const float xMax = static_cast<float>(maxSize.getWidth()) * 10.f;
59 const float yMax = static_cast<float>(maxSize.getHeight()) * 10.f;
60
61 return {-xMax, -yMax, xMax, yMax};
62}
63
64// Applies the given transform to the region, while protecting against overflows caused by any
65// offsets. If applying the offset in the transform to any of the Rects in the region would result
66// in an overflow, they are not added to the output Region.
67Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
68 const std::string& debugWindowName) {
69 // Round the translation using the same rounding strategy used by ui::Transform.
70 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
71 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
72
73 ui::Transform transformWithoutOffset = t;
74 transformWithoutOffset.set(0.f, 0.f);
75
76 const Region transformed = transformWithoutOffset.transform(r);
77
78 // Apply the translation to each of the Rects in the region while discarding any that overflow.
79 Region ret;
80 for (const auto& rect : transformed) {
81 Rect newRect;
82 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
83 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
84 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
85 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
86 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
87 debugWindowName.c_str());
88 continue;
89 }
90 ret.orSelf(newRect);
91 }
92 return ret;
93}
94
95/*
96 * We don't want to send the layer's transform to input, but rather the
97 * parent's transform. This is because Layer's transform is
98 * information about how the buffer is placed on screen. The parent's
99 * transform makes more sense to send since it's information about how the
100 * layer is placed on screen. This transform is used by input to determine
101 * how to go from screen space back to window space.
102 */
103ui::Transform getInputTransform(const LayerSnapshot& snapshot) {
104 if (!snapshot.hasBufferOrSidebandStream()) {
105 return snapshot.geomLayerTransform;
106 }
107 return snapshot.parentTransform;
108}
109
110/**
Vishnu Nairfed7c122023-03-18 01:54:43 +0000111 * Returns the bounds used to fill the input frame and the touchable region.
112 *
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000113 * Similar to getInputTransform, we need to update the bounds to include the transform.
114 * This is because bounds don't include the buffer transform, where the input assumes
115 * that's already included.
116 */
Vishnu Nairfed7c122023-03-18 01:54:43 +0000117std::pair<FloatRect, bool> getInputBounds(const LayerSnapshot& snapshot, bool fillParentBounds) {
118 FloatRect inputBounds = snapshot.croppedBufferSize.toFloatRect();
119 if (snapshot.hasBufferOrSidebandStream() && snapshot.croppedBufferSize.isValid() &&
120 snapshot.localTransform.getType() != ui::Transform::IDENTITY) {
121 inputBounds = snapshot.localTransform.transform(inputBounds);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000122 }
123
Vishnu Nairfed7c122023-03-18 01:54:43 +0000124 bool inputBoundsValid = snapshot.croppedBufferSize.isValid();
125 if (!inputBoundsValid) {
126 /**
127 * Input bounds are based on the layer crop or buffer size. But if we are using
128 * the layer bounds as the input bounds (replaceTouchableRegionWithCrop flag) then
129 * we can use the parent bounds as the input bounds if the layer does not have buffer
130 * or a crop. We want to unify this logic but because of compat reasons we cannot always
131 * use the parent bounds. A layer without a buffer can get input. So when a window is
132 * initially added, its touchable region can fill its parent layer bounds and that can
133 * have negative consequences.
134 */
135 inputBounds = fillParentBounds ? snapshot.geomLayerBounds : FloatRect{};
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000136 }
Vishnu Nairfed7c122023-03-18 01:54:43 +0000137
138 // Clamp surface inset to the input bounds.
139 const float inset = static_cast<float>(snapshot.inputInfo.surfaceInset);
140 const float xSurfaceInset = std::clamp(inset, 0.f, inputBounds.getWidth() / 2.f);
141 const float ySurfaceInset = std::clamp(inset, 0.f, inputBounds.getHeight() / 2.f);
142
143 // Apply the insets to the input bounds.
144 inputBounds.left += xSurfaceInset;
145 inputBounds.top += ySurfaceInset;
146 inputBounds.right -= xSurfaceInset;
147 inputBounds.bottom -= ySurfaceInset;
148 return {inputBounds, inputBoundsValid};
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000149}
150
Vishnu Nairfed7c122023-03-18 01:54:43 +0000151Rect getInputBoundsInDisplaySpace(const LayerSnapshot& snapshot, const FloatRect& insetBounds,
152 const ui::Transform& screenToDisplay) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000153 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
154 // frame and transform used for the layer, which determines the bounds and the coordinate space
155 // within which the layer will receive input.
Vishnu Nairfed7c122023-03-18 01:54:43 +0000156
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000157 // Coordinate space definitions:
158 // - display: The display device's coordinate space. Correlates to pixels on the display.
159 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
160 // - layer: The coordinate space of this layer.
161 // - input: The coordinate space in which this layer will receive input events. This could be
162 // different than layer space if a surfaceInset is used, which changes the origin
163 // of the input space.
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000164
165 // Crop the input bounds to ensure it is within the parent's bounds.
Vishnu Nairfed7c122023-03-18 01:54:43 +0000166 const FloatRect croppedInsetBoundsInLayer = snapshot.geomLayerBounds.intersect(insetBounds);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000167
168 const ui::Transform layerToScreen = getInputTransform(snapshot);
169 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
170
Vishnu Nairfed7c122023-03-18 01:54:43 +0000171 return Rect{layerToDisplay.transform(croppedInsetBoundsInLayer)};
172}
173
174void fillInputFrameInfo(gui::WindowInfo& info, const ui::Transform& screenToDisplay,
175 const LayerSnapshot& snapshot) {
176 auto [inputBounds, inputBoundsValid] = getInputBounds(snapshot, /*fillParentBounds=*/false);
177 if (!inputBoundsValid) {
178 info.touchableRegion.clear();
179 }
180
Chavi Weingarten7f019192023-08-08 20:39:01 +0000181 info.frame = getInputBoundsInDisplaySpace(snapshot, inputBounds, screenToDisplay);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000182
183 ui::Transform inputToLayer;
Vishnu Nairfed7c122023-03-18 01:54:43 +0000184 inputToLayer.set(inputBounds.left, inputBounds.top);
185 const ui::Transform layerToScreen = getInputTransform(snapshot);
186 const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000187
188 // InputDispatcher expects a display-to-input transform.
189 info.transform = inputToDisplay.inverse();
190
191 // The touchable region is specified in the input coordinate space. Change it to display space.
192 info.touchableRegion =
193 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, snapshot.name);
194}
195
196void handleDropInputMode(LayerSnapshot& snapshot, const LayerSnapshot& parentSnapshot) {
197 if (snapshot.inputInfo.inputConfig.test(gui::WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
198 return;
199 }
200
201 // Check if we need to drop input unconditionally
202 const gui::DropInputMode dropInputMode = snapshot.dropInputMode;
203 if (dropInputMode == gui::DropInputMode::ALL) {
204 snapshot.inputInfo.inputConfig |= gui::WindowInfo::InputConfig::DROP_INPUT;
205 ALOGV("Dropping input for %s as requested by policy.", snapshot.name.c_str());
206 return;
207 }
208
209 // Check if we need to check if the window is obscured by parent
210 if (dropInputMode != gui::DropInputMode::OBSCURED) {
211 return;
212 }
213
214 // Check if the parent has set an alpha on the layer
215 if (parentSnapshot.color.a != 1.0_hf) {
216 snapshot.inputInfo.inputConfig |= gui::WindowInfo::InputConfig::DROP_INPUT;
217 ALOGV("Dropping input for %s as requested by policy because alpha=%f",
218 snapshot.name.c_str(), static_cast<float>(parentSnapshot.color.a));
219 }
220
221 // Check if the parent has cropped the buffer
222 Rect bufferSize = snapshot.croppedBufferSize;
223 if (!bufferSize.isValid()) {
224 snapshot.inputInfo.inputConfig |= gui::WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
225 return;
226 }
227
228 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
229 // To check if the layer has been cropped, we take the buffer bounds, apply the local
230 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
231 // match then the layer has not been cropped by its parents.
232 Rect bufferInScreenSpace(snapshot.geomLayerTransform.transform(bufferSize));
233 bool croppedByParent = bufferInScreenSpace != Rect{snapshot.transformedBounds};
234
235 if (croppedByParent) {
236 snapshot.inputInfo.inputConfig |= gui::WindowInfo::InputConfig::DROP_INPUT;
237 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
238 snapshot.name.c_str());
239 } else {
240 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
241 // input if the window is obscured. This check should be done in surfaceflinger but the
242 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
243 // drop input events if the window is obscured.
244 snapshot.inputInfo.inputConfig |= gui::WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
245 }
246}
247
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000248auto getBlendMode(const LayerSnapshot& snapshot, const RequestedLayerState& requested) {
249 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
250 if (snapshot.alpha != 1.0f || !snapshot.isContentOpaque()) {
251 blendMode = requested.premultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
252 : Hwc2::IComposerClient::BlendMode::COVERAGE;
253 }
254 return blendMode;
255}
256
Vishnu Nair80a5a702023-02-11 01:21:51 +0000257void updateVisibility(LayerSnapshot& snapshot, bool visible) {
258 snapshot.isVisible = visible;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000259
260 // TODO(b/238781169) we are ignoring this compat for now, since we will have
261 // to remove any optimization based on visibility.
262
263 // For compatibility reasons we let layers which can receive input
264 // receive input before they have actually submitted a buffer. Because
265 // of this we use canReceiveInput instead of isVisible to check the
266 // policy-visibility, ignoring the buffer state. However for layers with
267 // hasInputInfo()==false we can use the real visibility state.
268 // We are just using these layers for occlusion detection in
269 // InputDispatcher, and obviously if they aren't visible they can't occlude
270 // anything.
Vishnu Nair80a5a702023-02-11 01:21:51 +0000271 const bool visibleForInput =
Vishnu Nair40d02282023-02-28 21:11:40 +0000272 snapshot.hasInputInfo() ? snapshot.canReceiveInput() : snapshot.isVisible;
Vishnu Nair80a5a702023-02-11 01:21:51 +0000273 snapshot.inputInfo.setInputConfig(gui::WindowInfo::InputConfig::NOT_VISIBLE, !visibleForInput);
Vishnu Naira02943f2023-06-03 13:44:46 -0700274 LLOGV(snapshot.sequence, "updating visibility %s %s", visible ? "true" : "false",
275 snapshot.getDebugString().c_str());
Vishnu Naircfb2d252023-01-19 04:44:02 +0000276}
277
278bool needsInputInfo(const LayerSnapshot& snapshot, const RequestedLayerState& requested) {
279 if (requested.potentialCursor) {
280 return false;
281 }
282
283 if (snapshot.inputInfo.token != nullptr) {
284 return true;
285 }
286
287 if (snapshot.hasBufferOrSidebandStream()) {
288 return true;
289 }
290
291 return requested.windowInfoHandle &&
292 requested.windowInfoHandle->getInfo()->inputConfig.test(
293 gui::WindowInfo::InputConfig::NO_INPUT_CHANNEL);
294}
295
Vishnu Nairc765c6c2023-02-23 00:08:01 +0000296void updateMetadata(LayerSnapshot& snapshot, const RequestedLayerState& requested,
297 const LayerSnapshotBuilder::Args& args) {
298 snapshot.metadata.clear();
299 for (const auto& [key, mandatory] : args.supportedLayerGenericMetadata) {
300 auto compatIter = args.genericLayerMetadataKeyMap.find(key);
301 if (compatIter == std::end(args.genericLayerMetadataKeyMap)) {
302 continue;
303 }
304 const uint32_t id = compatIter->second;
305 auto it = requested.metadata.mMap.find(id);
306 if (it == std::end(requested.metadata.mMap)) {
307 continue;
308 }
309
310 snapshot.metadata.emplace(key,
311 compositionengine::GenericLayerMetadataEntry{mandatory,
312 it->second});
313 }
314}
315
Vishnu Naircfb2d252023-01-19 04:44:02 +0000316void clearChanges(LayerSnapshot& snapshot) {
317 snapshot.changes.clear();
Vishnu Naira02943f2023-06-03 13:44:46 -0700318 snapshot.clientChanges = 0;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000319 snapshot.contentDirty = false;
320 snapshot.hasReadyFrame = false;
321 snapshot.sidebandStreamHasFrame = false;
322 snapshot.surfaceDamage.clear();
323}
324
Vishnu Naira02943f2023-06-03 13:44:46 -0700325// TODO (b/259407931): Remove.
326uint32_t getPrimaryDisplayRotationFlags(
327 const ui::DisplayMap<ui::LayerStack, frontend::DisplayInfo>& displays) {
328 for (auto& [_, display] : displays) {
329 if (display.isPrimary) {
330 return display.rotationFlags;
331 }
332 }
333 return 0;
334}
335
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000336} // namespace
337
338LayerSnapshot LayerSnapshotBuilder::getRootSnapshot() {
339 LayerSnapshot snapshot;
Vishnu Nair92990e22023-02-24 20:01:05 +0000340 snapshot.path = LayerHierarchy::TraversalPath::ROOT;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000341 snapshot.changes = ftl::Flags<RequestedLayerState::Changes>();
Vishnu Naira02943f2023-06-03 13:44:46 -0700342 snapshot.clientChanges = 0;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000343 snapshot.isHiddenByPolicyFromParent = false;
344 snapshot.isHiddenByPolicyFromRelativeParent = false;
345 snapshot.parentTransform.reset();
346 snapshot.geomLayerTransform.reset();
347 snapshot.geomInverseLayerTransform.reset();
348 snapshot.geomLayerBounds = getMaxDisplayBounds({});
349 snapshot.roundedCorner = RoundedCornerState();
350 snapshot.stretchEffect = {};
351 snapshot.outputFilter.layerStack = ui::DEFAULT_LAYER_STACK;
352 snapshot.outputFilter.toInternalDisplay = false;
353 snapshot.isSecure = false;
354 snapshot.color.a = 1.0_hf;
355 snapshot.colorTransformIsIdentity = true;
Vishnu Naird9e4f462023-10-06 04:05:45 +0000356 snapshot.shadowSettings.length = 0.f;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000357 snapshot.layerMetadata.mMap.clear();
358 snapshot.relativeLayerMetadata.mMap.clear();
359 snapshot.inputInfo.touchOcclusionMode = gui::TouchOcclusionMode::BLOCK_UNTRUSTED;
360 snapshot.dropInputMode = gui::DropInputMode::NONE;
361 snapshot.isTrustedOverlay = false;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000362 snapshot.gameMode = gui::GameMode::Unsupported;
363 snapshot.frameRate = {};
364 snapshot.fixedTransformHint = ui::Transform::ROT_INVALID;
Vishnu Nair422b81c2024-05-16 05:44:28 +0000365 snapshot.ignoreLocalTransform = false;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000366 return snapshot;
367}
368
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000369LayerSnapshotBuilder::LayerSnapshotBuilder() {}
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000370
371LayerSnapshotBuilder::LayerSnapshotBuilder(Args args) : LayerSnapshotBuilder() {
Vishnu Naird47bcee2023-02-24 18:08:51 +0000372 args.forceUpdate = ForceUpdateFlags::ALL;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000373 updateSnapshots(args);
374}
375
376bool LayerSnapshotBuilder::tryFastUpdate(const Args& args) {
Vishnu Naira02943f2023-06-03 13:44:46 -0700377 const bool forceUpdate = args.forceUpdate != ForceUpdateFlags::NONE;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000378
Vishnu Naira02943f2023-06-03 13:44:46 -0700379 if (args.layerLifecycleManager.getGlobalChanges().get() == 0 && !forceUpdate &&
380 !args.displayChanges) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000381 return true;
382 }
383
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000384 // There are only content changes which do not require any child layer snapshots to be updated.
385 ALOGV("%s", __func__);
386 ATRACE_NAME("FastPath");
387
Vishnu Naira02943f2023-06-03 13:44:46 -0700388 uint32_t primaryDisplayRotationFlags = getPrimaryDisplayRotationFlags(args.displays);
389 if (forceUpdate || args.displayChanges) {
390 for (auto& snapshot : mSnapshots) {
391 const RequestedLayerState* requested =
392 args.layerLifecycleManager.getLayerFromId(snapshot->path.id);
393 if (!requested) continue;
394 snapshot->merge(*requested, forceUpdate, args.displayChanges, args.forceFullDamage,
395 primaryDisplayRotationFlags);
396 }
397 return false;
398 }
399
400 // Walk through all the updated requested layer states and update the corresponding snapshots.
401 for (const RequestedLayerState* requested : args.layerLifecycleManager.getChangedLayers()) {
402 auto range = mIdToSnapshots.equal_range(requested->id);
403 for (auto it = range.first; it != range.second; it++) {
404 it->second->merge(*requested, forceUpdate, args.displayChanges, args.forceFullDamage,
405 primaryDisplayRotationFlags);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000406 }
407 }
408
Vishnu Naira02943f2023-06-03 13:44:46 -0700409 if ((args.layerLifecycleManager.getGlobalChanges().get() &
410 ~(RequestedLayerState::Changes::Content | RequestedLayerState::Changes::Buffer).get()) !=
411 0) {
412 // We have changes that require us to walk the hierarchy and update child layers.
413 // No fast path for you.
414 return false;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000415 }
416 return true;
417}
418
419void LayerSnapshotBuilder::updateSnapshots(const Args& args) {
420 ATRACE_NAME("UpdateSnapshots");
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000421 LayerSnapshot rootSnapshot = args.rootSnapshot;
Vishnu Nair3af0ec02023-02-10 04:13:48 +0000422 if (args.parentCrop) {
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000423 rootSnapshot.geomLayerBounds = *args.parentCrop;
Vishnu Naird47bcee2023-02-24 18:08:51 +0000424 } else if (args.forceUpdate == ForceUpdateFlags::ALL || args.displayChanges) {
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000425 rootSnapshot.geomLayerBounds = getMaxDisplayBounds(args.displays);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000426 }
427 if (args.displayChanges) {
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000428 rootSnapshot.changes = RequestedLayerState::Changes::AffectsChildren |
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000429 RequestedLayerState::Changes::Geometry;
430 }
Vishnu Naird47bcee2023-02-24 18:08:51 +0000431 if (args.forceUpdate == ForceUpdateFlags::HIERARCHY) {
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000432 rootSnapshot.changes |=
Vishnu Naird47bcee2023-02-24 18:08:51 +0000433 RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Visibility;
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000434 rootSnapshot.clientChanges |= layer_state_t::eReparent;
Vishnu Naird47bcee2023-02-24 18:08:51 +0000435 }
Vishnu Naira02943f2023-06-03 13:44:46 -0700436
437 for (auto& snapshot : mSnapshots) {
438 if (snapshot->reachablilty == LayerSnapshot::Reachablilty::Reachable) {
439 snapshot->reachablilty = LayerSnapshot::Reachablilty::Unreachable;
440 }
441 }
442
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000443 LayerHierarchy::TraversalPath root = LayerHierarchy::TraversalPath::ROOT;
Vishnu Naird47bcee2023-02-24 18:08:51 +0000444 if (args.root.getLayer()) {
445 // The hierarchy can have a root layer when used for screenshots otherwise, it will have
446 // multiple children.
447 LayerHierarchy::ScopedAddToTraversalPath addChildToPath(root, args.root.getLayer()->id,
448 LayerHierarchy::Variant::Attached);
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000449 updateSnapshotsInHierarchy(args, args.root, root, rootSnapshot, /*depth=*/0);
Vishnu Naird47bcee2023-02-24 18:08:51 +0000450 } else {
451 for (auto& [childHierarchy, variant] : args.root.mChildren) {
452 LayerHierarchy::ScopedAddToTraversalPath addChildToPath(root,
453 childHierarchy->getLayer()->id,
454 variant);
Chavi Weingarten4aa22af2023-11-17 19:37:07 +0000455 updateSnapshotsInHierarchy(args, *childHierarchy, root, rootSnapshot, /*depth=*/0);
Vishnu Naird47bcee2023-02-24 18:08:51 +0000456 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000457 }
458
Vishnu Nair29354ec2023-03-28 18:51:28 -0700459 // Update touchable region crops outside the main update pass. This is because a layer could be
460 // cropped by any other layer and it requires both snapshots to be updated.
461 updateTouchableRegionCrop(args);
462
Vishnu Nairfccd6362023-02-24 23:39:53 +0000463 const bool hasUnreachableSnapshots = sortSnapshotsByZ(args);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000464
Vishnu Nair29354ec2023-03-28 18:51:28 -0700465 // Destroy unreachable snapshots for clone layers. And destroy snapshots for non-clone
466 // layers if the layer have been destroyed.
467 // TODO(b/238781169) consider making clone layer ids stable as well
468 if (!hasUnreachableSnapshots && args.layerLifecycleManager.getDestroyedLayers().empty()) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000469 return;
470 }
471
Vishnu Nair29354ec2023-03-28 18:51:28 -0700472 std::unordered_set<uint32_t> destroyedLayerIds;
473 for (auto& destroyedLayer : args.layerLifecycleManager.getDestroyedLayers()) {
474 destroyedLayerIds.insert(destroyedLayer->id);
475 }
476
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000477 auto it = mSnapshots.begin();
478 while (it < mSnapshots.end()) {
479 auto& traversalPath = it->get()->path;
Vishnu Naira02943f2023-06-03 13:44:46 -0700480 const bool unreachable =
481 it->get()->reachablilty == LayerSnapshot::Reachablilty::Unreachable;
482 const bool isClone = traversalPath.isClone();
483 const bool layerIsDestroyed =
484 destroyedLayerIds.find(traversalPath.id) != destroyedLayerIds.end();
485 const bool destroySnapshot = (unreachable && isClone) || layerIsDestroyed;
486
487 if (!destroySnapshot) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000488 it++;
489 continue;
490 }
491
Vishnu Naira02943f2023-06-03 13:44:46 -0700492 mPathToSnapshot.erase(traversalPath);
493
494 auto range = mIdToSnapshots.equal_range(traversalPath.id);
495 auto matchingSnapshot =
496 std::find_if(range.first, range.second, [&traversalPath](auto& snapshotWithId) {
497 return snapshotWithId.second->path == traversalPath;
498 });
499 mIdToSnapshots.erase(matchingSnapshot);
Vishnu Nair29354ec2023-03-28 18:51:28 -0700500 mNeedsTouchableRegionCrop.erase(traversalPath);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000501 mSnapshots.back()->globalZ = it->get()->globalZ;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000502 std::iter_swap(it, mSnapshots.end() - 1);
503 mSnapshots.erase(mSnapshots.end() - 1);
504 }
505}
506
507void LayerSnapshotBuilder::update(const Args& args) {
Vishnu Nair92990e22023-02-24 20:01:05 +0000508 for (auto& snapshot : mSnapshots) {
509 clearChanges(*snapshot);
510 }
511
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000512 if (tryFastUpdate(args)) {
513 return;
514 }
515 updateSnapshots(args);
516}
517
Vishnu Naircfb2d252023-01-19 04:44:02 +0000518const LayerSnapshot& LayerSnapshotBuilder::updateSnapshotsInHierarchy(
519 const Args& args, const LayerHierarchy& hierarchy,
Vishnu Naird1f74982023-06-15 20:16:51 -0700520 LayerHierarchy::TraversalPath& traversalPath, const LayerSnapshot& parentSnapshot,
521 int depth) {
Vishnu Nair606d9d02023-08-19 14:20:18 -0700522 LLOG_ALWAYS_FATAL_WITH_TRACE_IF(depth > 50,
523 "Cycle detected in LayerSnapshotBuilder. See "
524 "builder_stack_overflow_transactions.winscope");
Vishnu Naird1f74982023-06-15 20:16:51 -0700525
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000526 const RequestedLayerState* layer = hierarchy.getLayer();
Vishnu Naircfb2d252023-01-19 04:44:02 +0000527 LayerSnapshot* snapshot = getSnapshot(traversalPath);
528 const bool newSnapshot = snapshot == nullptr;
Vishnu Naira02943f2023-06-03 13:44:46 -0700529 uint32_t primaryDisplayRotationFlags = getPrimaryDisplayRotationFlags(args.displays);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000530 if (newSnapshot) {
Vishnu Nair92990e22023-02-24 20:01:05 +0000531 snapshot = createSnapshot(traversalPath, *layer, parentSnapshot);
Vishnu Naira02943f2023-06-03 13:44:46 -0700532 snapshot->merge(*layer, /*forceUpdate=*/true, /*displayChanges=*/true, args.forceFullDamage,
533 primaryDisplayRotationFlags);
534 snapshot->changes |= RequestedLayerState::Changes::Created;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000535 }
Vishnu Nair52d56fd2023-07-20 17:02:43 +0000536
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000537 if (traversalPath.isRelative()) {
538 bool parentIsRelative = traversalPath.variant == LayerHierarchy::Variant::Relative;
539 updateRelativeState(*snapshot, parentSnapshot, parentIsRelative, args);
540 } else {
541 if (traversalPath.isAttached()) {
542 resetRelativeState(*snapshot);
543 }
Vishnu Nair92990e22023-02-24 20:01:05 +0000544 updateSnapshot(*snapshot, args, *layer, parentSnapshot, traversalPath);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000545 }
546
547 for (auto& [childHierarchy, variant] : hierarchy.mChildren) {
548 LayerHierarchy::ScopedAddToTraversalPath addChildToPath(traversalPath,
549 childHierarchy->getLayer()->id,
550 variant);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000551 const LayerSnapshot& childSnapshot =
Vishnu Naird1f74982023-06-15 20:16:51 -0700552 updateSnapshotsInHierarchy(args, *childHierarchy, traversalPath, *snapshot,
553 depth + 1);
Vishnu Nair42b918e2023-07-18 20:05:29 +0000554 updateFrameRateFromChildSnapshot(*snapshot, childSnapshot, args);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000555 }
Vishnu Naird47bcee2023-02-24 18:08:51 +0000556
Vishnu Naircfb2d252023-01-19 04:44:02 +0000557 return *snapshot;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000558}
559
560LayerSnapshot* LayerSnapshotBuilder::getSnapshot(uint32_t layerId) const {
561 if (layerId == UNASSIGNED_LAYER_ID) {
562 return nullptr;
563 }
564 LayerHierarchy::TraversalPath path{.id = layerId};
565 return getSnapshot(path);
566}
567
568LayerSnapshot* LayerSnapshotBuilder::getSnapshot(const LayerHierarchy::TraversalPath& id) const {
Vishnu Naira02943f2023-06-03 13:44:46 -0700569 auto it = mPathToSnapshot.find(id);
570 return it == mPathToSnapshot.end() ? nullptr : it->second;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000571}
572
Vishnu Nair92990e22023-02-24 20:01:05 +0000573LayerSnapshot* LayerSnapshotBuilder::createSnapshot(const LayerHierarchy::TraversalPath& path,
574 const RequestedLayerState& layer,
575 const LayerSnapshot& parentSnapshot) {
576 mSnapshots.emplace_back(std::make_unique<LayerSnapshot>(layer, path));
Vishnu Naircfb2d252023-01-19 04:44:02 +0000577 LayerSnapshot* snapshot = mSnapshots.back().get();
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000578 snapshot->globalZ = static_cast<size_t>(mSnapshots.size()) - 1;
Vishnu Nair491827d2024-04-29 23:43:26 +0000579 if (path.isClone() && !LayerHierarchy::isMirror(path.variant)) {
Vishnu Nair92990e22023-02-24 20:01:05 +0000580 snapshot->mirrorRootPath = parentSnapshot.mirrorRootPath;
581 }
Vishnu Nair491827d2024-04-29 23:43:26 +0000582 snapshot->ignoreLocalTransform =
583 path.isClone() && path.variant == LayerHierarchy::Variant::Detached_Mirror;
Vishnu Naira02943f2023-06-03 13:44:46 -0700584 mPathToSnapshot[path] = snapshot;
585
586 mIdToSnapshots.emplace(path.id, snapshot);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000587 return snapshot;
588}
589
Vishnu Nairfccd6362023-02-24 23:39:53 +0000590bool LayerSnapshotBuilder::sortSnapshotsByZ(const Args& args) {
Vishnu Naird47bcee2023-02-24 18:08:51 +0000591 if (!mResortSnapshots && args.forceUpdate == ForceUpdateFlags::NONE &&
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000592 !args.layerLifecycleManager.getGlobalChanges().any(
Chavi Weingarten92c7d8c2024-01-19 23:25:45 +0000593 RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Visibility |
594 RequestedLayerState::Changes::Input)) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000595 // We are not force updating and there are no hierarchy or visibility changes. Avoid sorting
596 // the snapshots.
Vishnu Nairfccd6362023-02-24 23:39:53 +0000597 return false;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000598 }
Vishnu Naircfb2d252023-01-19 04:44:02 +0000599 mResortSnapshots = false;
600
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000601 size_t globalZ = 0;
602 args.root.traverseInZOrder(
603 [this, &globalZ](const LayerHierarchy&,
604 const LayerHierarchy::TraversalPath& traversalPath) -> bool {
605 LayerSnapshot* snapshot = getSnapshot(traversalPath);
606 if (!snapshot) {
Vishnu Naira02943f2023-06-03 13:44:46 -0700607 return true;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000608 }
609
Vishnu Naircfb2d252023-01-19 04:44:02 +0000610 if (snapshot->getIsVisible() || snapshot->hasInputInfo()) {
Vishnu Nair80a5a702023-02-11 01:21:51 +0000611 updateVisibility(*snapshot, snapshot->getIsVisible());
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000612 size_t oldZ = snapshot->globalZ;
613 size_t newZ = globalZ++;
614 snapshot->globalZ = newZ;
615 if (oldZ == newZ) {
616 return true;
617 }
618 mSnapshots[newZ]->globalZ = oldZ;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000619 LLOGV(snapshot->sequence, "Made visible z=%zu -> %zu %s", oldZ, newZ,
620 snapshot->getDebugString().c_str());
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000621 std::iter_swap(mSnapshots.begin() + static_cast<ssize_t>(oldZ),
622 mSnapshots.begin() + static_cast<ssize_t>(newZ));
623 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000624 return true;
625 });
Vishnu Naircfb2d252023-01-19 04:44:02 +0000626 mNumInterestingSnapshots = (int)globalZ;
Vishnu Nairfccd6362023-02-24 23:39:53 +0000627 bool hasUnreachableSnapshots = false;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000628 while (globalZ < mSnapshots.size()) {
629 mSnapshots[globalZ]->globalZ = globalZ;
Vishnu Nair80a5a702023-02-11 01:21:51 +0000630 /* mark unreachable snapshots as explicitly invisible */
631 updateVisibility(*mSnapshots[globalZ], false);
Vishnu Naira02943f2023-06-03 13:44:46 -0700632 if (mSnapshots[globalZ]->reachablilty == LayerSnapshot::Reachablilty::Unreachable) {
Vishnu Nairfccd6362023-02-24 23:39:53 +0000633 hasUnreachableSnapshots = true;
634 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000635 globalZ++;
636 }
Vishnu Nairfccd6362023-02-24 23:39:53 +0000637 return hasUnreachableSnapshots;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000638}
639
640void LayerSnapshotBuilder::updateRelativeState(LayerSnapshot& snapshot,
641 const LayerSnapshot& parentSnapshot,
642 bool parentIsRelative, const Args& args) {
643 if (parentIsRelative) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000644 snapshot.isHiddenByPolicyFromRelativeParent =
645 parentSnapshot.isHiddenByPolicyFromParent || parentSnapshot.invalidTransform;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000646 if (args.includeMetadata) {
647 snapshot.relativeLayerMetadata = parentSnapshot.layerMetadata;
648 }
649 } else {
650 snapshot.isHiddenByPolicyFromRelativeParent =
651 parentSnapshot.isHiddenByPolicyFromRelativeParent;
652 if (args.includeMetadata) {
653 snapshot.relativeLayerMetadata = parentSnapshot.relativeLayerMetadata;
654 }
655 }
Vishnu Naira02943f2023-06-03 13:44:46 -0700656 if (snapshot.reachablilty == LayerSnapshot::Reachablilty::Unreachable) {
657 snapshot.reachablilty = LayerSnapshot::Reachablilty::ReachableByRelativeParent;
658 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000659}
660
Vishnu Nair42b918e2023-07-18 20:05:29 +0000661void LayerSnapshotBuilder::updateFrameRateFromChildSnapshot(LayerSnapshot& snapshot,
662 const LayerSnapshot& childSnapshot,
663 const Args& args) {
664 if (args.forceUpdate == ForceUpdateFlags::NONE &&
Vishnu Nair52d56fd2023-07-20 17:02:43 +0000665 !args.layerLifecycleManager.getGlobalChanges().any(
666 RequestedLayerState::Changes::Hierarchy) &&
667 !childSnapshot.changes.any(RequestedLayerState::Changes::FrameRate) &&
668 !snapshot.changes.any(RequestedLayerState::Changes::FrameRate)) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000669 return;
670 }
Vishnu Naircfb2d252023-01-19 04:44:02 +0000671
Vishnu Nair3fbe3262023-09-29 17:07:00 -0700672 using FrameRateCompatibility = scheduler::FrameRateCompatibility;
Rachel Leece6e0042023-06-27 11:22:54 -0700673 if (snapshot.frameRate.isValid()) {
Vishnu Nair42b918e2023-07-18 20:05:29 +0000674 // we already have a valid framerate.
675 return;
676 }
Vishnu Naircfb2d252023-01-19 04:44:02 +0000677
Vishnu Nair42b918e2023-07-18 20:05:29 +0000678 // We return whether this layer or its children has a vote. We ignore ExactOrMultiple votes
679 // for the same reason we are allowing touch boost for those layers. See
680 // RefreshRateSelector::rankFrameRates for details.
Rachel Leece6e0042023-06-27 11:22:54 -0700681 const auto layerVotedWithDefaultCompatibility = childSnapshot.frameRate.vote.rate.isValid() &&
682 childSnapshot.frameRate.vote.type == FrameRateCompatibility::Default;
Vishnu Nair42b918e2023-07-18 20:05:29 +0000683 const auto layerVotedWithNoVote =
Rachel Leece6e0042023-06-27 11:22:54 -0700684 childSnapshot.frameRate.vote.type == FrameRateCompatibility::NoVote;
685 const auto layerVotedWithCategory =
686 childSnapshot.frameRate.category != FrameRateCategory::Default;
687 const auto layerVotedWithExactCompatibility = childSnapshot.frameRate.vote.rate.isValid() &&
688 childSnapshot.frameRate.vote.type == FrameRateCompatibility::Exact;
Vishnu Nair42b918e2023-07-18 20:05:29 +0000689
690 bool childHasValidFrameRate = layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
Rachel Leece6e0042023-06-27 11:22:54 -0700691 layerVotedWithCategory || layerVotedWithExactCompatibility;
Vishnu Nair42b918e2023-07-18 20:05:29 +0000692
693 // If we don't have a valid frame rate, but the children do, we set this
694 // layer as NoVote to allow the children to control the refresh rate
695 if (childHasValidFrameRate) {
696 snapshot.frameRate = scheduler::LayerInfo::FrameRate(Fps(), FrameRateCompatibility::NoVote);
697 snapshot.changes |= RequestedLayerState::Changes::FrameRate;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000698 }
699}
700
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000701void LayerSnapshotBuilder::resetRelativeState(LayerSnapshot& snapshot) {
702 snapshot.isHiddenByPolicyFromRelativeParent = false;
703 snapshot.relativeLayerMetadata.mMap.clear();
704}
705
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000706void LayerSnapshotBuilder::updateSnapshot(LayerSnapshot& snapshot, const Args& args,
707 const RequestedLayerState& requested,
708 const LayerSnapshot& parentSnapshot,
Vishnu Nair92990e22023-02-24 20:01:05 +0000709 const LayerHierarchy::TraversalPath& path) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000710 // Always update flags and visibility
711 ftl::Flags<RequestedLayerState::Changes> parentChanges = parentSnapshot.changes &
712 (RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Geometry |
713 RequestedLayerState::Changes::Visibility | RequestedLayerState::Changes::Metadata |
Vishnu Nairf13c8982023-12-02 11:26:09 -0800714 RequestedLayerState::Changes::AffectsChildren | RequestedLayerState::Changes::Input |
Vishnu Naira02943f2023-06-03 13:44:46 -0700715 RequestedLayerState::Changes::FrameRate | RequestedLayerState::Changes::GameMode);
716 snapshot.changes |= parentChanges;
717 if (args.displayChanges) snapshot.changes |= RequestedLayerState::Changes::Geometry;
718 snapshot.reachablilty = LayerSnapshot::Reachablilty::Reachable;
719 snapshot.clientChanges |= (parentSnapshot.clientChanges & layer_state_t::AFFECTS_CHILDREN);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000720 snapshot.isHiddenByPolicyFromParent = parentSnapshot.isHiddenByPolicyFromParent ||
Vishnu Nair3af0ec02023-02-10 04:13:48 +0000721 parentSnapshot.invalidTransform || requested.isHiddenByPolicy() ||
722 (args.excludeLayerIds.find(path.id) != args.excludeLayerIds.end());
Vishnu Nair80a5a702023-02-11 01:21:51 +0000723
Vishnu Nair92990e22023-02-24 20:01:05 +0000724 const bool forceUpdate = args.forceUpdate == ForceUpdateFlags::ALL ||
Vishnu Naira02943f2023-06-03 13:44:46 -0700725 snapshot.clientChanges & layer_state_t::eReparent ||
Vishnu Nair92990e22023-02-24 20:01:05 +0000726 snapshot.changes.any(RequestedLayerState::Changes::Visibility |
727 RequestedLayerState::Changes::Created);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000728
Vishnu Naira02943f2023-06-03 13:44:46 -0700729 if (forceUpdate || snapshot.clientChanges & layer_state_t::eLayerStackChanged) {
730 // If root layer, use the layer stack otherwise get the parent's layer stack.
731 snapshot.outputFilter.layerStack =
732 parentSnapshot.path == LayerHierarchy::TraversalPath::ROOT
733 ? requested.layerStack
734 : parentSnapshot.outputFilter.layerStack;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000735 }
736
Chavi Weingartenb74093a2023-10-11 20:29:59 +0000737 if (forceUpdate || snapshot.clientChanges & layer_state_t::eTrustedOverlayChanged) {
738 snapshot.isTrustedOverlay = parentSnapshot.isTrustedOverlay || requested.isTrustedOverlay;
739 }
740
Vishnu Nair92990e22023-02-24 20:01:05 +0000741 if (snapshot.isHiddenByPolicyFromParent &&
742 !snapshot.changes.test(RequestedLayerState::Changes::Created)) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000743 if (forceUpdate ||
Vishnu Naira02943f2023-06-03 13:44:46 -0700744 snapshot.changes.any(RequestedLayerState::Changes::Geometry |
Vishnu Nair494a2e42023-11-10 17:21:19 -0800745 RequestedLayerState::Changes::BufferSize |
Vishnu Naircfb2d252023-01-19 04:44:02 +0000746 RequestedLayerState::Changes::Input)) {
747 updateInput(snapshot, requested, parentSnapshot, path, args);
748 }
749 return;
750 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000751
Vishnu Naira02943f2023-06-03 13:44:46 -0700752 if (forceUpdate || snapshot.changes.any(RequestedLayerState::Changes::Mirror)) {
753 // Display mirrors are always placed in a VirtualDisplay so we never want to capture layers
754 // marked as skip capture
755 snapshot.handleSkipScreenshotFlag = parentSnapshot.handleSkipScreenshotFlag ||
756 (requested.layerStackToMirror != ui::INVALID_LAYER_STACK);
757 }
758
759 if (forceUpdate || snapshot.clientChanges & layer_state_t::eAlphaChanged) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000760 snapshot.color.a = parentSnapshot.color.a * requested.color.a;
761 snapshot.alpha = snapshot.color.a;
Vishnu Nair29354ec2023-03-28 18:51:28 -0700762 snapshot.inputInfo.alpha = snapshot.color.a;
Vishnu Naira02943f2023-06-03 13:44:46 -0700763 }
Vishnu Nair29354ec2023-03-28 18:51:28 -0700764
Vishnu Naira02943f2023-06-03 13:44:46 -0700765 if (forceUpdate || snapshot.clientChanges & layer_state_t::eFlagsChanged) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000766 snapshot.isSecure =
767 parentSnapshot.isSecure || (requested.flags & layer_state_t::eLayerSecure);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000768 snapshot.outputFilter.toInternalDisplay = parentSnapshot.outputFilter.toInternalDisplay ||
769 (requested.flags & layer_state_t::eLayerSkipScreenshot);
Vishnu Naira02943f2023-06-03 13:44:46 -0700770 }
771
Vishnu Naira02943f2023-06-03 13:44:46 -0700772 if (forceUpdate || snapshot.clientChanges & layer_state_t::eStretchChanged) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000773 snapshot.stretchEffect = (requested.stretchEffect.hasEffect())
774 ? requested.stretchEffect
775 : parentSnapshot.stretchEffect;
Vishnu Naira02943f2023-06-03 13:44:46 -0700776 }
777
778 if (forceUpdate || snapshot.clientChanges & layer_state_t::eColorTransformChanged) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000779 if (!parentSnapshot.colorTransformIsIdentity) {
780 snapshot.colorTransform = parentSnapshot.colorTransform * requested.colorTransform;
781 snapshot.colorTransformIsIdentity = false;
782 } else {
783 snapshot.colorTransform = requested.colorTransform;
784 snapshot.colorTransformIsIdentity = !requested.hasColorTransform;
785 }
Vishnu Naira02943f2023-06-03 13:44:46 -0700786 }
787
788 if (forceUpdate || snapshot.changes.test(RequestedLayerState::Changes::GameMode)) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000789 snapshot.gameMode = requested.metadata.has(gui::METADATA_GAME_MODE)
790 ? requested.gameMode
791 : parentSnapshot.gameMode;
Vishnu Naira02943f2023-06-03 13:44:46 -0700792 updateMetadata(snapshot, requested, args);
793 if (args.includeMetadata) {
794 snapshot.layerMetadata = parentSnapshot.layerMetadata;
795 snapshot.layerMetadata.merge(requested.metadata);
796 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000797 }
798
Vishnu Naira02943f2023-06-03 13:44:46 -0700799 if (forceUpdate || snapshot.clientChanges & layer_state_t::eFixedTransformHintChanged ||
Vishnu Nairb76d99a2023-03-19 18:22:31 -0700800 args.displayChanges) {
801 snapshot.fixedTransformHint = requested.fixedTransformHint != ui::Transform::ROT_INVALID
802 ? requested.fixedTransformHint
803 : parentSnapshot.fixedTransformHint;
804
805 if (snapshot.fixedTransformHint != ui::Transform::ROT_INVALID) {
806 snapshot.transformHint = snapshot.fixedTransformHint;
807 } else {
808 const auto display = args.displays.get(snapshot.outputFilter.layerStack);
809 snapshot.transformHint = display.has_value()
810 ? std::make_optional<>(display->get().transformHint)
811 : std::nullopt;
812 }
813 }
814
Vishnu Nair42b918e2023-07-18 20:05:29 +0000815 if (forceUpdate ||
Vishnu Nair52d56fd2023-07-20 17:02:43 +0000816 args.layerLifecycleManager.getGlobalChanges().any(
817 RequestedLayerState::Changes::Hierarchy) ||
Vishnu Nair42b918e2023-07-18 20:05:29 +0000818 snapshot.changes.any(RequestedLayerState::Changes::FrameRate |
819 RequestedLayerState::Changes::Hierarchy)) {
Rachel Leea021bb02023-11-20 21:51:09 -0800820 const bool shouldOverrideChildren = parentSnapshot.frameRateSelectionStrategy ==
Rachel Lee58cc90d2023-09-05 18:50:20 -0700821 scheduler::LayerInfo::FrameRateSelectionStrategy::OverrideChildren;
Rachel Leea021bb02023-11-20 21:51:09 -0800822 const bool propagationAllowed = parentSnapshot.frameRateSelectionStrategy !=
Rachel Lee70f7b692023-11-22 11:24:02 -0800823 scheduler::LayerInfo::FrameRateSelectionStrategy::Self;
Rachel Leea021bb02023-11-20 21:51:09 -0800824 if ((!requested.requestedFrameRate.isValid() && propagationAllowed) ||
825 shouldOverrideChildren) {
Vishnu Nair30515cb2023-10-19 21:54:08 -0700826 snapshot.inheritedFrameRate = parentSnapshot.inheritedFrameRate;
827 } else {
828 snapshot.inheritedFrameRate = requested.requestedFrameRate;
829 }
830 // Set the framerate as the inherited frame rate and allow children to override it if
831 // needed.
832 snapshot.frameRate = snapshot.inheritedFrameRate;
Vishnu Nair52d56fd2023-07-20 17:02:43 +0000833 snapshot.changes |= RequestedLayerState::Changes::FrameRate;
Vishnu Naird47bcee2023-02-24 18:08:51 +0000834 }
835
Rachel Lee58cc90d2023-09-05 18:50:20 -0700836 if (forceUpdate || snapshot.clientChanges & layer_state_t::eFrameRateSelectionStrategyChanged) {
Rachel Leea021bb02023-11-20 21:51:09 -0800837 if (parentSnapshot.frameRateSelectionStrategy ==
838 scheduler::LayerInfo::FrameRateSelectionStrategy::OverrideChildren) {
839 snapshot.frameRateSelectionStrategy =
840 scheduler::LayerInfo::FrameRateSelectionStrategy::OverrideChildren;
841 } else {
842 const auto strategy = scheduler::LayerInfo::convertFrameRateSelectionStrategy(
843 requested.frameRateSelectionStrategy);
844 snapshot.frameRateSelectionStrategy = strategy;
845 }
Rachel Lee58cc90d2023-09-05 18:50:20 -0700846 }
847
Vishnu Nair3d8565a2023-06-30 07:23:24 +0000848 if (forceUpdate || snapshot.clientChanges & layer_state_t::eFrameRateSelectionPriority) {
849 snapshot.frameRateSelectionPriority =
850 (requested.frameRateSelectionPriority == Layer::PRIORITY_UNSET)
851 ? parentSnapshot.frameRateSelectionPriority
852 : requested.frameRateSelectionPriority;
853 }
854
Vishnu Naira02943f2023-06-03 13:44:46 -0700855 if (forceUpdate ||
856 snapshot.clientChanges &
857 (layer_state_t::eBackgroundBlurRadiusChanged | layer_state_t::eBlurRegionsChanged |
858 layer_state_t::eAlphaChanged)) {
Vishnu Nair80a5a702023-02-11 01:21:51 +0000859 snapshot.backgroundBlurRadius = args.supportsBlur
860 ? static_cast<int>(parentSnapshot.color.a * (float)requested.backgroundBlurRadius)
861 : 0;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000862 snapshot.blurRegions = requested.blurRegions;
Vishnu Nair80a5a702023-02-11 01:21:51 +0000863 for (auto& region : snapshot.blurRegions) {
864 region.alpha = region.alpha * snapshot.color.a;
865 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000866 }
867
Vishnu Naira02943f2023-06-03 13:44:46 -0700868 if (forceUpdate || snapshot.changes.any(RequestedLayerState::Changes::Geometry)) {
869 uint32_t primaryDisplayRotationFlags = getPrimaryDisplayRotationFlags(args.displays);
Vishnu Nairb76d99a2023-03-19 18:22:31 -0700870 updateLayerBounds(snapshot, requested, parentSnapshot, primaryDisplayRotationFlags);
Vishnu Naira02943f2023-06-03 13:44:46 -0700871 }
872
873 if (forceUpdate || snapshot.clientChanges & layer_state_t::eCornerRadiusChanged ||
Vishnu Nair0808ae62023-08-07 21:42:42 -0700874 snapshot.changes.any(RequestedLayerState::Changes::Geometry |
875 RequestedLayerState::Changes::BufferUsageFlags)) {
876 updateRoundedCorner(snapshot, requested, parentSnapshot, args);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000877 }
878
Vishnu Naira02943f2023-06-03 13:44:46 -0700879 if (forceUpdate || snapshot.clientChanges & layer_state_t::eShadowRadiusChanged ||
880 snapshot.changes.any(RequestedLayerState::Changes::Geometry)) {
881 updateShadows(snapshot, requested, args.globalShadowSettings);
882 }
883
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000884 if (forceUpdate ||
Vishnu Naira02943f2023-06-03 13:44:46 -0700885 snapshot.changes.any(RequestedLayerState::Changes::Geometry |
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000886 RequestedLayerState::Changes::Input)) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000887 updateInput(snapshot, requested, parentSnapshot, path, args);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000888 }
889
890 // computed snapshot properties
Alec Mouri994761f2023-08-04 21:50:55 +0000891 snapshot.forceClientComposition =
892 snapshot.shadowSettings.length > 0 || snapshot.stretchEffect.hasEffect();
Vishnu Nairc765c6c2023-02-23 00:08:01 +0000893 snapshot.contentOpaque = snapshot.isContentOpaque();
894 snapshot.isOpaque = snapshot.contentOpaque && !snapshot.roundedCorner.hasRoundedCorners() &&
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000895 snapshot.color.a == 1.f;
896 snapshot.blendMode = getBlendMode(snapshot, requested);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000897 LLOGV(snapshot.sequence,
Vishnu Nair92990e22023-02-24 20:01:05 +0000898 "%supdated %s changes:%s parent:%s requested:%s requested:%s from parent %s",
899 args.forceUpdate == ForceUpdateFlags::ALL ? "Force " : "",
900 snapshot.getDebugString().c_str(), snapshot.changes.string().c_str(),
901 parentSnapshot.changes.string().c_str(), requested.changes.string().c_str(),
902 std::to_string(requested.what).c_str(), parentSnapshot.getDebugString().c_str());
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000903}
904
905void LayerSnapshotBuilder::updateRoundedCorner(LayerSnapshot& snapshot,
906 const RequestedLayerState& requested,
Vishnu Nair0808ae62023-08-07 21:42:42 -0700907 const LayerSnapshot& parentSnapshot,
908 const Args& args) {
909 if (args.skipRoundCornersWhenProtected && requested.isProtected()) {
910 snapshot.roundedCorner = RoundedCornerState();
911 return;
912 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000913 snapshot.roundedCorner = RoundedCornerState();
914 RoundedCornerState parentRoundedCorner;
915 if (parentSnapshot.roundedCorner.hasRoundedCorners()) {
916 parentRoundedCorner = parentSnapshot.roundedCorner;
917 ui::Transform t = snapshot.localTransform.inverse();
918 parentRoundedCorner.cropRect = t.transform(parentRoundedCorner.cropRect);
919 parentRoundedCorner.radius.x *= t.getScaleX();
920 parentRoundedCorner.radius.y *= t.getScaleY();
921 }
922
923 FloatRect layerCropRect = snapshot.croppedBufferSize.toFloatRect();
924 const vec2 radius(requested.cornerRadius, requested.cornerRadius);
925 RoundedCornerState layerSettings(layerCropRect, radius);
926 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && !layerCropRect.isEmpty();
927 const bool parentRoundedCornerValid = parentRoundedCorner.hasRoundedCorners();
928 if (layerSettingsValid && parentRoundedCornerValid) {
929 // If the parent and the layer have rounded corner settings, use the parent settings if
930 // the parent crop is entirely inside the layer crop. This has limitations and cause
931 // rendering artifacts. See b/200300845 for correct fix.
932 if (parentRoundedCorner.cropRect.left > layerCropRect.left &&
933 parentRoundedCorner.cropRect.top > layerCropRect.top &&
934 parentRoundedCorner.cropRect.right < layerCropRect.right &&
935 parentRoundedCorner.cropRect.bottom < layerCropRect.bottom) {
936 snapshot.roundedCorner = parentRoundedCorner;
937 } else {
938 snapshot.roundedCorner = layerSettings;
939 }
940 } else if (layerSettingsValid) {
941 snapshot.roundedCorner = layerSettings;
942 } else if (parentRoundedCornerValid) {
943 snapshot.roundedCorner = parentRoundedCorner;
944 }
945}
946
947void LayerSnapshotBuilder::updateLayerBounds(LayerSnapshot& snapshot,
948 const RequestedLayerState& requested,
949 const LayerSnapshot& parentSnapshot,
Vishnu Nairb76d99a2023-03-19 18:22:31 -0700950 uint32_t primaryDisplayRotationFlags) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000951 snapshot.geomLayerTransform = parentSnapshot.geomLayerTransform * snapshot.localTransform;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000952 const bool transformWasInvalid = snapshot.invalidTransform;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000953 snapshot.invalidTransform = !LayerSnapshot::isTransformValid(snapshot.geomLayerTransform);
954 if (snapshot.invalidTransform) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000955 auto& t = snapshot.geomLayerTransform;
956 auto& requestedT = requested.requestedTransform;
957 std::string transformDebug =
958 base::StringPrintf(" transform={%f,%f,%f,%f} requestedTransform={%f,%f,%f,%f}",
959 t.dsdx(), t.dsdy(), t.dtdx(), t.dtdy(), requestedT.dsdx(),
960 requestedT.dsdy(), requestedT.dtdx(), requestedT.dtdy());
961 std::string bufferDebug;
962 if (requested.externalTexture) {
Vishnu Nairb76d99a2023-03-19 18:22:31 -0700963 auto unRotBuffer = requested.getUnrotatedBufferSize(primaryDisplayRotationFlags);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000964 auto& destFrame = requested.destinationFrame;
965 bufferDebug = base::StringPrintf(" buffer={%d,%d} displayRot=%d"
966 " destFrame={%d,%d,%d,%d} unRotBuffer={%d,%d}",
967 requested.externalTexture->getWidth(),
968 requested.externalTexture->getHeight(),
Vishnu Nairb76d99a2023-03-19 18:22:31 -0700969 primaryDisplayRotationFlags, destFrame.left,
970 destFrame.top, destFrame.right, destFrame.bottom,
Vishnu Naircfb2d252023-01-19 04:44:02 +0000971 unRotBuffer.getHeight(), unRotBuffer.getWidth());
972 }
973 ALOGW("Resetting transform for %s because it is invalid.%s%s",
974 snapshot.getDebugString().c_str(), transformDebug.c_str(), bufferDebug.c_str());
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000975 snapshot.geomLayerTransform.reset();
976 }
Vishnu Naircfb2d252023-01-19 04:44:02 +0000977 if (transformWasInvalid != snapshot.invalidTransform) {
978 // If transform is invalid, the layer will be hidden.
979 mResortSnapshots = true;
980 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000981 snapshot.geomInverseLayerTransform = snapshot.geomLayerTransform.inverse();
982
983 FloatRect parentBounds = parentSnapshot.geomLayerBounds;
984 parentBounds = snapshot.localTransform.inverse().transform(parentBounds);
985 snapshot.geomLayerBounds =
986 (requested.externalTexture) ? snapshot.bufferSize.toFloatRect() : parentBounds;
987 if (!requested.crop.isEmpty()) {
988 snapshot.geomLayerBounds = snapshot.geomLayerBounds.intersect(requested.crop.toFloatRect());
989 }
990 snapshot.geomLayerBounds = snapshot.geomLayerBounds.intersect(parentBounds);
991 snapshot.transformedBounds = snapshot.geomLayerTransform.transform(snapshot.geomLayerBounds);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000992 const Rect geomLayerBoundsWithoutTransparentRegion =
993 RequestedLayerState::reduce(Rect(snapshot.geomLayerBounds),
994 requested.transparentRegion);
995 snapshot.transformedBoundsWithoutTransparentRegion =
996 snapshot.geomLayerTransform.transform(geomLayerBoundsWithoutTransparentRegion);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000997 snapshot.parentTransform = parentSnapshot.geomLayerTransform;
998
999 // Subtract the transparent region and snap to the bounds
Vishnu Naircfb2d252023-01-19 04:44:02 +00001000 const Rect bounds =
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001001 RequestedLayerState::reduce(snapshot.croppedBufferSize, requested.transparentRegion);
Vishnu Naircfb2d252023-01-19 04:44:02 +00001002 if (requested.potentialCursor) {
1003 snapshot.cursorFrame = snapshot.geomLayerTransform.transform(bounds);
1004 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001005}
1006
Vishnu Naira02943f2023-06-03 13:44:46 -07001007void LayerSnapshotBuilder::updateShadows(LayerSnapshot& snapshot, const RequestedLayerState&,
Vishnu Naird9e4f462023-10-06 04:05:45 +00001008 const ShadowSettings& globalShadowSettings) {
1009 if (snapshot.shadowSettings.length > 0.f) {
1010 snapshot.shadowSettings.ambientColor = globalShadowSettings.ambientColor;
1011 snapshot.shadowSettings.spotColor = globalShadowSettings.spotColor;
1012 snapshot.shadowSettings.lightPos = globalShadowSettings.lightPos;
1013 snapshot.shadowSettings.lightRadius = globalShadowSettings.lightRadius;
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001014
1015 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
1016 // it if transparent regions are present. This may not be necessary since shadows are
1017 // typically cast by layers without transparent regions.
1018 snapshot.shadowSettings.boundaries = snapshot.geomLayerBounds;
1019
1020 // If the casting layer is translucent, we need to fill in the shadow underneath the
1021 // layer. Otherwise the generated shadow will only be shown around the casting layer.
1022 snapshot.shadowSettings.casterIsTranslucent =
1023 !snapshot.isContentOpaque() || (snapshot.alpha < 1.0f);
1024 snapshot.shadowSettings.ambientColor *= snapshot.alpha;
1025 snapshot.shadowSettings.spotColor *= snapshot.alpha;
1026 }
1027}
1028
1029void LayerSnapshotBuilder::updateInput(LayerSnapshot& snapshot,
1030 const RequestedLayerState& requested,
1031 const LayerSnapshot& parentSnapshot,
Vishnu Naircfb2d252023-01-19 04:44:02 +00001032 const LayerHierarchy::TraversalPath& path,
1033 const Args& args) {
Prabir Pradhancf359192024-03-20 00:42:57 +00001034 using InputConfig = gui::WindowInfo::InputConfig;
1035
Vishnu Naircfb2d252023-01-19 04:44:02 +00001036 if (requested.windowInfoHandle) {
1037 snapshot.inputInfo = *requested.windowInfoHandle->getInfo();
1038 } else {
1039 snapshot.inputInfo = {};
Vishnu Nair40d02282023-02-28 21:11:40 +00001040 // b/271132344 revisit this and see if we can always use the layers uid/pid
1041 snapshot.inputInfo.name = requested.name;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00001042 snapshot.inputInfo.ownerUid = gui::Uid{requested.ownerUid};
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00001043 snapshot.inputInfo.ownerPid = gui::Pid{requested.ownerPid};
Vishnu Naircfb2d252023-01-19 04:44:02 +00001044 }
Vishnu Nair29354ec2023-03-28 18:51:28 -07001045 snapshot.touchCropId = requested.touchCropId;
Vishnu Naircfb2d252023-01-19 04:44:02 +00001046
Vishnu Nair93b8b792023-02-27 19:40:24 +00001047 snapshot.inputInfo.id = static_cast<int32_t>(snapshot.uniqueSequence);
Linnan Li13bf76a2024-05-05 19:18:02 +08001048 snapshot.inputInfo.displayId =
1049 ui::LogicalDisplayId{static_cast<int32_t>(snapshot.outputFilter.layerStack.id)};
Vishnu Nairf13c8982023-12-02 11:26:09 -08001050 snapshot.inputInfo.touchOcclusionMode = requested.hasInputInfo()
1051 ? requested.windowInfoHandle->getInfo()->touchOcclusionMode
1052 : parentSnapshot.inputInfo.touchOcclusionMode;
Vishnu Nair59a6be32024-01-29 10:26:21 -08001053 snapshot.inputInfo.canOccludePresentation = parentSnapshot.inputInfo.canOccludePresentation ||
1054 (requested.flags & layer_state_t::eCanOccludePresentation);
Vishnu Nairf13c8982023-12-02 11:26:09 -08001055 if (requested.dropInputMode == gui::DropInputMode::ALL ||
1056 parentSnapshot.dropInputMode == gui::DropInputMode::ALL) {
1057 snapshot.dropInputMode = gui::DropInputMode::ALL;
1058 } else if (requested.dropInputMode == gui::DropInputMode::OBSCURED ||
1059 parentSnapshot.dropInputMode == gui::DropInputMode::OBSCURED) {
1060 snapshot.dropInputMode = gui::DropInputMode::OBSCURED;
1061 } else {
1062 snapshot.dropInputMode = gui::DropInputMode::NONE;
1063 }
1064
Prabir Pradhancf359192024-03-20 00:42:57 +00001065 if (snapshot.isSecure ||
Arpit Singh490ccc92024-04-30 14:26:21 +00001066 parentSnapshot.inputInfo.inputConfig.test(InputConfig::SENSITIVE_FOR_PRIVACY)) {
1067 snapshot.inputInfo.inputConfig |= InputConfig::SENSITIVE_FOR_PRIVACY;
Prabir Pradhancf359192024-03-20 00:42:57 +00001068 }
1069
Vishnu Nair29354ec2023-03-28 18:51:28 -07001070 updateVisibility(snapshot, snapshot.isVisible);
Vishnu Naircfb2d252023-01-19 04:44:02 +00001071 if (!needsInputInfo(snapshot, requested)) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001072 return;
1073 }
1074
Vishnu Naircfb2d252023-01-19 04:44:02 +00001075 static frontend::DisplayInfo sDefaultInfo = {.isSecure = false};
1076 const std::optional<frontend::DisplayInfo> displayInfoOpt =
1077 args.displays.get(snapshot.outputFilter.layerStack);
1078 bool noValidDisplay = !displayInfoOpt.has_value();
1079 auto displayInfo = displayInfoOpt.value_or(sDefaultInfo);
1080
1081 if (!requested.windowInfoHandle) {
Prabir Pradhancf359192024-03-20 00:42:57 +00001082 snapshot.inputInfo.inputConfig = InputConfig::NO_INPUT_CHANNEL;
Vishnu Naircfb2d252023-01-19 04:44:02 +00001083 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001084 fillInputFrameInfo(snapshot.inputInfo, displayInfo.transform, snapshot);
1085
1086 if (noValidDisplay) {
1087 // Do not let the window receive touches if it is not associated with a valid display
1088 // transform. We still allow the window to receive keys and prevent ANRs.
Prabir Pradhancf359192024-03-20 00:42:57 +00001089 snapshot.inputInfo.inputConfig |= InputConfig::NOT_TOUCHABLE;
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001090 }
1091
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001092 snapshot.inputInfo.alpha = snapshot.color.a;
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001093
1094 handleDropInputMode(snapshot, parentSnapshot);
1095
1096 // If the window will be blacked out on a display because the display does not have the secure
1097 // flag and the layer has the secure flag set, then drop input.
1098 if (!displayInfo.isSecure && snapshot.isSecure) {
Prabir Pradhancf359192024-03-20 00:42:57 +00001099 snapshot.inputInfo.inputConfig |= InputConfig::DROP_INPUT;
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001100 }
1101
Vishnu Naira02943f2023-06-03 13:44:46 -07001102 if (requested.touchCropId != UNASSIGNED_LAYER_ID || path.isClone()) {
Vishnu Nair29354ec2023-03-28 18:51:28 -07001103 mNeedsTouchableRegionCrop.insert(path);
Vishnu Naira02943f2023-06-03 13:44:46 -07001104 }
1105 auto cropLayerSnapshot = getSnapshot(requested.touchCropId);
1106 if (!cropLayerSnapshot && snapshot.inputInfo.replaceTouchableRegionWithCrop) {
Vishnu Nair29354ec2023-03-28 18:51:28 -07001107 FloatRect inputBounds = getInputBounds(snapshot, /*fillParentBounds=*/true).first;
Vishnu Nairfed7c122023-03-18 01:54:43 +00001108 Rect inputBoundsInDisplaySpace =
Vishnu Nair29354ec2023-03-28 18:51:28 -07001109 getInputBoundsInDisplaySpace(snapshot, inputBounds, displayInfo.transform);
1110 snapshot.inputInfo.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001111 }
1112
1113 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
1114 // if it was set by WM for a known system overlay
1115 if (snapshot.isTrustedOverlay) {
Prabir Pradhancf359192024-03-20 00:42:57 +00001116 snapshot.inputInfo.inputConfig |= InputConfig::TRUSTED_OVERLAY;
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001117 }
1118
Vishnu Nair494a2e42023-11-10 17:21:19 -08001119 snapshot.inputInfo.contentSize = snapshot.croppedBufferSize.getSize();
1120
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001121 // If the layer is a clone, we need to crop the input region to cloned root to prevent
1122 // touches from going outside the cloned area.
1123 if (path.isClone()) {
Prabir Pradhancf359192024-03-20 00:42:57 +00001124 snapshot.inputInfo.inputConfig |= InputConfig::CLONE;
Vishnu Nair444f3952023-04-11 13:01:02 -07001125 // Cloned layers shouldn't handle watch outside since their z order is not determined by
1126 // WM or the client.
Prabir Pradhancf359192024-03-20 00:42:57 +00001127 snapshot.inputInfo.inputConfig.clear(InputConfig::WATCH_OUTSIDE_TOUCH);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001128 }
1129}
1130
1131std::vector<std::unique_ptr<LayerSnapshot>>& LayerSnapshotBuilder::getSnapshots() {
1132 return mSnapshots;
1133}
1134
Vishnu Naircfb2d252023-01-19 04:44:02 +00001135void LayerSnapshotBuilder::forEachVisibleSnapshot(const ConstVisitor& visitor) const {
1136 for (int i = 0; i < mNumInterestingSnapshots; i++) {
1137 LayerSnapshot& snapshot = *mSnapshots[(size_t)i];
1138 if (!snapshot.isVisible) continue;
1139 visitor(snapshot);
1140 }
1141}
1142
Vishnu Nair3af0ec02023-02-10 04:13:48 +00001143// Visit each visible snapshot in z-order
1144void LayerSnapshotBuilder::forEachVisibleSnapshot(const ConstVisitor& visitor,
1145 const LayerHierarchy& root) const {
1146 root.traverseInZOrder(
1147 [this, visitor](const LayerHierarchy&,
1148 const LayerHierarchy::TraversalPath& traversalPath) -> bool {
1149 LayerSnapshot* snapshot = getSnapshot(traversalPath);
1150 if (snapshot && snapshot->isVisible) {
1151 visitor(*snapshot);
1152 }
1153 return true;
1154 });
1155}
1156
Vishnu Naircfb2d252023-01-19 04:44:02 +00001157void LayerSnapshotBuilder::forEachVisibleSnapshot(const Visitor& visitor) {
1158 for (int i = 0; i < mNumInterestingSnapshots; i++) {
1159 std::unique_ptr<LayerSnapshot>& snapshot = mSnapshots.at((size_t)i);
1160 if (!snapshot->isVisible) continue;
1161 visitor(snapshot);
1162 }
1163}
1164
1165void LayerSnapshotBuilder::forEachInputSnapshot(const ConstVisitor& visitor) const {
1166 for (int i = mNumInterestingSnapshots - 1; i >= 0; i--) {
1167 LayerSnapshot& snapshot = *mSnapshots[(size_t)i];
1168 if (!snapshot.hasInputInfo()) continue;
1169 visitor(snapshot);
1170 }
1171}
1172
Vishnu Nair29354ec2023-03-28 18:51:28 -07001173void LayerSnapshotBuilder::updateTouchableRegionCrop(const Args& args) {
1174 if (mNeedsTouchableRegionCrop.empty()) {
1175 return;
1176 }
1177
1178 static constexpr ftl::Flags<RequestedLayerState::Changes> AFFECTS_INPUT =
1179 RequestedLayerState::Changes::Visibility | RequestedLayerState::Changes::Created |
1180 RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Geometry |
1181 RequestedLayerState::Changes::Input;
1182
1183 if (args.forceUpdate != ForceUpdateFlags::ALL &&
Vishnu Naira02943f2023-06-03 13:44:46 -07001184 !args.layerLifecycleManager.getGlobalChanges().any(AFFECTS_INPUT) && !args.displayChanges) {
Vishnu Nair29354ec2023-03-28 18:51:28 -07001185 return;
1186 }
1187
1188 for (auto& path : mNeedsTouchableRegionCrop) {
1189 frontend::LayerSnapshot* snapshot = getSnapshot(path);
1190 if (!snapshot) {
1191 continue;
1192 }
Vishnu Naira02943f2023-06-03 13:44:46 -07001193 LLOGV(snapshot->sequence, "updateTouchableRegionCrop=%s",
1194 snapshot->getDebugString().c_str());
Vishnu Nair29354ec2023-03-28 18:51:28 -07001195 const std::optional<frontend::DisplayInfo> displayInfoOpt =
1196 args.displays.get(snapshot->outputFilter.layerStack);
1197 static frontend::DisplayInfo sDefaultInfo = {.isSecure = false};
1198 auto displayInfo = displayInfoOpt.value_or(sDefaultInfo);
1199
1200 bool needsUpdate =
1201 args.forceUpdate == ForceUpdateFlags::ALL || snapshot->changes.any(AFFECTS_INPUT);
1202 auto cropLayerSnapshot = getSnapshot(snapshot->touchCropId);
1203 needsUpdate =
1204 needsUpdate || (cropLayerSnapshot && cropLayerSnapshot->changes.any(AFFECTS_INPUT));
1205 auto clonedRootSnapshot = path.isClone() ? getSnapshot(snapshot->mirrorRootPath) : nullptr;
1206 needsUpdate = needsUpdate ||
1207 (clonedRootSnapshot && clonedRootSnapshot->changes.any(AFFECTS_INPUT));
1208
1209 if (!needsUpdate) {
1210 continue;
1211 }
1212
1213 if (snapshot->inputInfo.replaceTouchableRegionWithCrop) {
1214 Rect inputBoundsInDisplaySpace;
1215 if (!cropLayerSnapshot) {
1216 FloatRect inputBounds = getInputBounds(*snapshot, /*fillParentBounds=*/true).first;
1217 inputBoundsInDisplaySpace =
1218 getInputBoundsInDisplaySpace(*snapshot, inputBounds, displayInfo.transform);
1219 } else {
1220 FloatRect inputBounds =
1221 getInputBounds(*cropLayerSnapshot, /*fillParentBounds=*/true).first;
1222 inputBoundsInDisplaySpace =
1223 getInputBoundsInDisplaySpace(*cropLayerSnapshot, inputBounds,
1224 displayInfo.transform);
1225 }
1226 snapshot->inputInfo.touchableRegion = Region(inputBoundsInDisplaySpace);
1227 } else if (cropLayerSnapshot) {
1228 FloatRect inputBounds =
1229 getInputBounds(*cropLayerSnapshot, /*fillParentBounds=*/true).first;
1230 Rect inputBoundsInDisplaySpace =
1231 getInputBoundsInDisplaySpace(*cropLayerSnapshot, inputBounds,
1232 displayInfo.transform);
Chavi Weingarten1ba381e2024-01-09 21:54:11 +00001233 snapshot->inputInfo.touchableRegion =
1234 snapshot->inputInfo.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair29354ec2023-03-28 18:51:28 -07001235 }
1236
1237 // If the layer is a clone, we need to crop the input region to cloned root to prevent
1238 // touches from going outside the cloned area.
1239 if (clonedRootSnapshot) {
1240 const Rect rect =
1241 displayInfo.transform.transform(Rect{clonedRootSnapshot->transformedBounds});
1242 snapshot->inputInfo.touchableRegion =
1243 snapshot->inputInfo.touchableRegion.intersect(rect);
1244 }
1245 }
1246}
1247
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001248} // namespace android::surfaceflinger::frontend