blob: cc265916f16d24deb123c8068ace426d9639fba4 [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
20#define LOG_TAG "LayerSnapshotBuilder"
21
22#include "LayerSnapshotBuilder.h"
23#include <gui/TraceUtils.h>
24#include <numeric>
25#include "DisplayHardware/HWC2.h"
26#include "DisplayHardware/Hal.h"
Vishnu Naircfb2d252023-01-19 04:44:02 +000027#include "LayerLog.h"
28#include "TimeStats/TimeStats.h"
Vishnu Nair8fc721b2022-12-22 20:06:32 +000029#include "ftl/small_map.h"
30
31namespace android::surfaceflinger::frontend {
32
33using namespace ftl::flag_operators;
34
35namespace {
36FloatRect getMaxDisplayBounds(
37 const display::DisplayMap<ui::LayerStack, frontend::DisplayInfo>& displays) {
38 const ui::Size maxSize = [&displays] {
39 if (displays.empty()) return ui::Size{5000, 5000};
40
41 return std::accumulate(displays.begin(), displays.end(), ui::kEmptySize,
42 [](ui::Size size, const auto& pair) -> ui::Size {
43 const auto& display = pair.second;
44 return {std::max(size.getWidth(), display.info.logicalWidth),
45 std::max(size.getHeight(), display.info.logicalHeight)};
46 });
47 }();
48
49 // Ignore display bounds for now since they will be computed later. Use a large Rect bound
50 // to ensure it's bigger than an actual display will be.
51 const float xMax = static_cast<float>(maxSize.getWidth()) * 10.f;
52 const float yMax = static_cast<float>(maxSize.getHeight()) * 10.f;
53
54 return {-xMax, -yMax, xMax, yMax};
55}
56
57// Applies the given transform to the region, while protecting against overflows caused by any
58// offsets. If applying the offset in the transform to any of the Rects in the region would result
59// in an overflow, they are not added to the output Region.
60Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
61 const std::string& debugWindowName) {
62 // Round the translation using the same rounding strategy used by ui::Transform.
63 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
64 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
65
66 ui::Transform transformWithoutOffset = t;
67 transformWithoutOffset.set(0.f, 0.f);
68
69 const Region transformed = transformWithoutOffset.transform(r);
70
71 // Apply the translation to each of the Rects in the region while discarding any that overflow.
72 Region ret;
73 for (const auto& rect : transformed) {
74 Rect newRect;
75 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
76 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
77 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
78 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
79 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
80 debugWindowName.c_str());
81 continue;
82 }
83 ret.orSelf(newRect);
84 }
85 return ret;
86}
87
88/*
89 * We don't want to send the layer's transform to input, but rather the
90 * parent's transform. This is because Layer's transform is
91 * information about how the buffer is placed on screen. The parent's
92 * transform makes more sense to send since it's information about how the
93 * layer is placed on screen. This transform is used by input to determine
94 * how to go from screen space back to window space.
95 */
96ui::Transform getInputTransform(const LayerSnapshot& snapshot) {
97 if (!snapshot.hasBufferOrSidebandStream()) {
98 return snapshot.geomLayerTransform;
99 }
100 return snapshot.parentTransform;
101}
102
103/**
104 * Similar to getInputTransform, we need to update the bounds to include the transform.
105 * This is because bounds don't include the buffer transform, where the input assumes
106 * that's already included.
107 */
108Rect getInputBounds(const LayerSnapshot& snapshot) {
109 if (!snapshot.hasBufferOrSidebandStream()) {
110 return snapshot.croppedBufferSize;
111 }
112
113 if (snapshot.localTransform.getType() == ui::Transform::IDENTITY ||
114 !snapshot.croppedBufferSize.isValid()) {
115 return snapshot.croppedBufferSize;
116 }
117 return snapshot.localTransform.transform(snapshot.croppedBufferSize);
118}
119
120void fillInputFrameInfo(gui::WindowInfo& info, const ui::Transform& screenToDisplay,
121 const LayerSnapshot& snapshot) {
122 Rect tmpBounds = getInputBounds(snapshot);
123 if (!tmpBounds.isValid()) {
124 info.touchableRegion.clear();
125 // A layer could have invalid input bounds and still expect to receive touch input if it has
126 // replaceTouchableRegionWithCrop. For that case, the input transform needs to be calculated
127 // correctly to determine the coordinate space for input events. Use an empty rect so that
128 // the layer will receive input in its own layer space.
129 tmpBounds = Rect::EMPTY_RECT;
130 }
131
132 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
133 // frame and transform used for the layer, which determines the bounds and the coordinate space
134 // within which the layer will receive input.
135 //
136 // The coordinate space within which each of the bounds are specified is explicitly documented
137 // in the variable name. For example "inputBoundsInLayer" is specified in layer space. A
138 // Transform converts one coordinate space to another, which is apparent in its naming. For
139 // example, "layerToDisplay" transforms layer space to display space.
140 //
141 // Coordinate space definitions:
142 // - display: The display device's coordinate space. Correlates to pixels on the display.
143 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
144 // - layer: The coordinate space of this layer.
145 // - input: The coordinate space in which this layer will receive input events. This could be
146 // different than layer space if a surfaceInset is used, which changes the origin
147 // of the input space.
148 const FloatRect inputBoundsInLayer = tmpBounds.toFloatRect();
149
150 // Clamp surface inset to the input bounds.
151 const auto surfaceInset = static_cast<float>(info.surfaceInset);
152 const float xSurfaceInset =
153 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getWidth() / 2.f));
154 const float ySurfaceInset =
155 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getHeight() / 2.f));
156
157 // Apply the insets to the input bounds.
158 const FloatRect insetBoundsInLayer(inputBoundsInLayer.left + xSurfaceInset,
159 inputBoundsInLayer.top + ySurfaceInset,
160 inputBoundsInLayer.right - xSurfaceInset,
161 inputBoundsInLayer.bottom - ySurfaceInset);
162
163 // Crop the input bounds to ensure it is within the parent's bounds.
164 const FloatRect croppedInsetBoundsInLayer =
165 snapshot.geomLayerBounds.intersect(insetBoundsInLayer);
166
167 const ui::Transform layerToScreen = getInputTransform(snapshot);
168 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
169
170 const Rect roundedFrameInDisplay{layerToDisplay.transform(croppedInsetBoundsInLayer)};
171 info.frameLeft = roundedFrameInDisplay.left;
172 info.frameTop = roundedFrameInDisplay.top;
173 info.frameRight = roundedFrameInDisplay.right;
174 info.frameBottom = roundedFrameInDisplay.bottom;
175
176 ui::Transform inputToLayer;
177 inputToLayer.set(insetBoundsInLayer.left, insetBoundsInLayer.top);
178 const ui::Transform inputToDisplay = layerToDisplay * inputToLayer;
179
180 // InputDispatcher expects a display-to-input transform.
181 info.transform = inputToDisplay.inverse();
182
183 // The touchable region is specified in the input coordinate space. Change it to display space.
184 info.touchableRegion =
185 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, snapshot.name);
186}
187
188void handleDropInputMode(LayerSnapshot& snapshot, const LayerSnapshot& parentSnapshot) {
189 if (snapshot.inputInfo.inputConfig.test(gui::WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
190 return;
191 }
192
193 // Check if we need to drop input unconditionally
194 const gui::DropInputMode dropInputMode = snapshot.dropInputMode;
195 if (dropInputMode == gui::DropInputMode::ALL) {
196 snapshot.inputInfo.inputConfig |= gui::WindowInfo::InputConfig::DROP_INPUT;
197 ALOGV("Dropping input for %s as requested by policy.", snapshot.name.c_str());
198 return;
199 }
200
201 // Check if we need to check if the window is obscured by parent
202 if (dropInputMode != gui::DropInputMode::OBSCURED) {
203 return;
204 }
205
206 // Check if the parent has set an alpha on the layer
207 if (parentSnapshot.color.a != 1.0_hf) {
208 snapshot.inputInfo.inputConfig |= gui::WindowInfo::InputConfig::DROP_INPUT;
209 ALOGV("Dropping input for %s as requested by policy because alpha=%f",
210 snapshot.name.c_str(), static_cast<float>(parentSnapshot.color.a));
211 }
212
213 // Check if the parent has cropped the buffer
214 Rect bufferSize = snapshot.croppedBufferSize;
215 if (!bufferSize.isValid()) {
216 snapshot.inputInfo.inputConfig |= gui::WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
217 return;
218 }
219
220 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
221 // To check if the layer has been cropped, we take the buffer bounds, apply the local
222 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
223 // match then the layer has not been cropped by its parents.
224 Rect bufferInScreenSpace(snapshot.geomLayerTransform.transform(bufferSize));
225 bool croppedByParent = bufferInScreenSpace != Rect{snapshot.transformedBounds};
226
227 if (croppedByParent) {
228 snapshot.inputInfo.inputConfig |= gui::WindowInfo::InputConfig::DROP_INPUT;
229 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
230 snapshot.name.c_str());
231 } else {
232 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
233 // input if the window is obscured. This check should be done in surfaceflinger but the
234 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
235 // drop input events if the window is obscured.
236 snapshot.inputInfo.inputConfig |= gui::WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
237 }
238}
239
240bool getBufferNeedsFiltering(const LayerSnapshot& snapshot, const ui::Size& unrotatedBufferSize) {
241 const int32_t layerWidth = static_cast<int32_t>(snapshot.geomLayerBounds.getWidth());
242 const int32_t layerHeight = static_cast<int32_t>(snapshot.geomLayerBounds.getHeight());
243 return layerWidth != unrotatedBufferSize.width || layerHeight != unrotatedBufferSize.height;
244}
245
246auto getBlendMode(const LayerSnapshot& snapshot, const RequestedLayerState& requested) {
247 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
248 if (snapshot.alpha != 1.0f || !snapshot.isContentOpaque()) {
249 blendMode = requested.premultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
250 : Hwc2::IComposerClient::BlendMode::COVERAGE;
251 }
252 return blendMode;
253}
254
Vishnu Naircfb2d252023-01-19 04:44:02 +0000255void updateSurfaceDamage(const RequestedLayerState& requested, bool hasReadyFrame,
256 bool forceFullDamage, Region& outSurfaceDamageRegion) {
257 if (!hasReadyFrame) {
258 outSurfaceDamageRegion.clear();
259 return;
260 }
261 if (forceFullDamage) {
262 outSurfaceDamageRegion = Region::INVALID_REGION;
263 } else {
264 outSurfaceDamageRegion = requested.surfaceDamageRegion;
265 }
266}
267
268void updateVisibility(LayerSnapshot& snapshot) {
269 snapshot.isVisible = snapshot.getIsVisible();
270
271 // TODO(b/238781169) we are ignoring this compat for now, since we will have
272 // to remove any optimization based on visibility.
273
274 // For compatibility reasons we let layers which can receive input
275 // receive input before they have actually submitted a buffer. Because
276 // of this we use canReceiveInput instead of isVisible to check the
277 // policy-visibility, ignoring the buffer state. However for layers with
278 // hasInputInfo()==false we can use the real visibility state.
279 // We are just using these layers for occlusion detection in
280 // InputDispatcher, and obviously if they aren't visible they can't occlude
281 // anything.
282 const bool visible =
283 (snapshot.inputInfo.token != nullptr) ? snapshot.canReceiveInput() : snapshot.isVisible;
284 snapshot.inputInfo.setInputConfig(gui::WindowInfo::InputConfig::NOT_VISIBLE, !visible);
285}
286
287bool needsInputInfo(const LayerSnapshot& snapshot, const RequestedLayerState& requested) {
288 if (requested.potentialCursor) {
289 return false;
290 }
291
292 if (snapshot.inputInfo.token != nullptr) {
293 return true;
294 }
295
296 if (snapshot.hasBufferOrSidebandStream()) {
297 return true;
298 }
299
300 return requested.windowInfoHandle &&
301 requested.windowInfoHandle->getInfo()->inputConfig.test(
302 gui::WindowInfo::InputConfig::NO_INPUT_CHANNEL);
303}
304
305void clearChanges(LayerSnapshot& snapshot) {
306 snapshot.changes.clear();
307 snapshot.contentDirty = false;
308 snapshot.hasReadyFrame = false;
309 snapshot.sidebandStreamHasFrame = false;
310 snapshot.surfaceDamage.clear();
311}
312
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000313} // namespace
314
315LayerSnapshot LayerSnapshotBuilder::getRootSnapshot() {
316 LayerSnapshot snapshot;
317 snapshot.changes = ftl::Flags<RequestedLayerState::Changes>();
318 snapshot.isHiddenByPolicyFromParent = false;
319 snapshot.isHiddenByPolicyFromRelativeParent = false;
320 snapshot.parentTransform.reset();
321 snapshot.geomLayerTransform.reset();
322 snapshot.geomInverseLayerTransform.reset();
323 snapshot.geomLayerBounds = getMaxDisplayBounds({});
324 snapshot.roundedCorner = RoundedCornerState();
325 snapshot.stretchEffect = {};
326 snapshot.outputFilter.layerStack = ui::DEFAULT_LAYER_STACK;
327 snapshot.outputFilter.toInternalDisplay = false;
328 snapshot.isSecure = false;
329 snapshot.color.a = 1.0_hf;
330 snapshot.colorTransformIsIdentity = true;
331 snapshot.shadowRadius = 0.f;
332 snapshot.layerMetadata.mMap.clear();
333 snapshot.relativeLayerMetadata.mMap.clear();
334 snapshot.inputInfo.touchOcclusionMode = gui::TouchOcclusionMode::BLOCK_UNTRUSTED;
335 snapshot.dropInputMode = gui::DropInputMode::NONE;
336 snapshot.isTrustedOverlay = false;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000337 snapshot.gameMode = gui::GameMode::Unsupported;
338 snapshot.frameRate = {};
339 snapshot.fixedTransformHint = ui::Transform::ROT_INVALID;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000340 return snapshot;
341}
342
343LayerSnapshotBuilder::LayerSnapshotBuilder() : mRootSnapshot(getRootSnapshot()) {}
344
345LayerSnapshotBuilder::LayerSnapshotBuilder(Args args) : LayerSnapshotBuilder() {
346 args.forceUpdate = true;
347 updateSnapshots(args);
348}
349
350bool LayerSnapshotBuilder::tryFastUpdate(const Args& args) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000351 if (args.forceUpdate || args.displayChanges) {
352 // force update requested, or we have display changes, so skip the fast path
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000353 return false;
354 }
355
356 if (args.layerLifecycleManager.getGlobalChanges().get() == 0) {
357 // there are no changes, so just clear the change flags from before.
358 for (auto& snapshot : mSnapshots) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000359 clearChanges(*snapshot);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000360 }
361 return true;
362 }
363
364 if (args.layerLifecycleManager.getGlobalChanges() != RequestedLayerState::Changes::Content) {
365 // We have changes that require us to walk the hierarchy and update child layers.
366 // No fast path for you.
367 return false;
368 }
369
370 // There are only content changes which do not require any child layer snapshots to be updated.
371 ALOGV("%s", __func__);
372 ATRACE_NAME("FastPath");
373
374 // Collect layers with changes
375 ftl::SmallMap<uint32_t, RequestedLayerState*, 10> layersWithChanges;
376 for (auto& layer : args.layerLifecycleManager.getLayers()) {
377 if (layer->changes.test(RequestedLayerState::Changes::Content)) {
378 layersWithChanges.emplace_or_replace(layer->id, layer.get());
379 }
380 }
381
382 // Walk through the snapshots, clearing previous change flags and updating the snapshots
383 // if needed.
384 for (auto& snapshot : mSnapshots) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000385 clearChanges(*snapshot);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000386 auto it = layersWithChanges.find(snapshot->path.id);
387 if (it != layersWithChanges.end()) {
388 ALOGV("%s fast path snapshot changes = %s", __func__,
389 mRootSnapshot.changes.string().c_str());
390 LayerHierarchy::TraversalPath root = LayerHierarchy::TraversalPath::ROOT;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000391 updateSnapshot(*snapshot, args, *it->second, mRootSnapshot, root,
392 /*newSnapshot=*/false);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000393 }
394 }
395 return true;
396}
397
398void LayerSnapshotBuilder::updateSnapshots(const Args& args) {
399 ATRACE_NAME("UpdateSnapshots");
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000400 if (args.forceUpdate || args.displayChanges) {
401 mRootSnapshot.geomLayerBounds = getMaxDisplayBounds(args.displays);
402 }
403 if (args.displayChanges) {
404 mRootSnapshot.changes = RequestedLayerState::Changes::AffectsChildren |
405 RequestedLayerState::Changes::Geometry;
406 }
407 LayerHierarchy::TraversalPath root = LayerHierarchy::TraversalPath::ROOT;
408 for (auto& [childHierarchy, variant] : args.root.mChildren) {
409 LayerHierarchy::ScopedAddToTraversalPath addChildToPath(root,
410 childHierarchy->getLayer()->id,
411 variant);
412 updateSnapshotsInHierarchy(args, *childHierarchy, root, mRootSnapshot);
413 }
414
415 sortSnapshotsByZ(args);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000416 clearChanges(mRootSnapshot);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000417
418 // Destroy unreachable snapshots
419 if (args.layerLifecycleManager.getDestroyedLayers().empty()) {
420 return;
421 }
422
423 std::unordered_set<uint32_t> destroyedLayerIds;
424 for (auto& destroyedLayer : args.layerLifecycleManager.getDestroyedLayers()) {
425 destroyedLayerIds.emplace(destroyedLayer->id);
426 }
427 auto it = mSnapshots.begin();
428 while (it < mSnapshots.end()) {
429 auto& traversalPath = it->get()->path;
430 if (destroyedLayerIds.find(traversalPath.id) == destroyedLayerIds.end()) {
431 it++;
432 continue;
433 }
434
435 mIdToSnapshot.erase(traversalPath);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000436 mSnapshots.back()->globalZ = it->get()->globalZ;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000437 std::iter_swap(it, mSnapshots.end() - 1);
438 mSnapshots.erase(mSnapshots.end() - 1);
439 }
440}
441
442void LayerSnapshotBuilder::update(const Args& args) {
443 if (tryFastUpdate(args)) {
444 return;
445 }
446 updateSnapshots(args);
447}
448
Vishnu Naircfb2d252023-01-19 04:44:02 +0000449const LayerSnapshot& LayerSnapshotBuilder::updateSnapshotsInHierarchy(
450 const Args& args, const LayerHierarchy& hierarchy,
451 LayerHierarchy::TraversalPath& traversalPath, const LayerSnapshot& parentSnapshot) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000452 const RequestedLayerState* layer = hierarchy.getLayer();
Vishnu Naircfb2d252023-01-19 04:44:02 +0000453 LayerSnapshot* snapshot = getSnapshot(traversalPath);
454 const bool newSnapshot = snapshot == nullptr;
455 if (newSnapshot) {
456 snapshot = createSnapshot(traversalPath, *layer);
457 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000458 if (traversalPath.isRelative()) {
459 bool parentIsRelative = traversalPath.variant == LayerHierarchy::Variant::Relative;
460 updateRelativeState(*snapshot, parentSnapshot, parentIsRelative, args);
461 } else {
462 if (traversalPath.isAttached()) {
463 resetRelativeState(*snapshot);
464 }
Vishnu Naircfb2d252023-01-19 04:44:02 +0000465 updateSnapshot(*snapshot, args, *layer, parentSnapshot, traversalPath, newSnapshot);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000466 }
467
468 for (auto& [childHierarchy, variant] : hierarchy.mChildren) {
469 LayerHierarchy::ScopedAddToTraversalPath addChildToPath(traversalPath,
470 childHierarchy->getLayer()->id,
471 variant);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000472 const LayerSnapshot& childSnapshot =
473 updateSnapshotsInHierarchy(args, *childHierarchy, traversalPath, *snapshot);
474 updateChildState(*snapshot, childSnapshot, args);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000475 }
Vishnu Naircfb2d252023-01-19 04:44:02 +0000476 return *snapshot;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000477}
478
479LayerSnapshot* LayerSnapshotBuilder::getSnapshot(uint32_t layerId) const {
480 if (layerId == UNASSIGNED_LAYER_ID) {
481 return nullptr;
482 }
483 LayerHierarchy::TraversalPath path{.id = layerId};
484 return getSnapshot(path);
485}
486
487LayerSnapshot* LayerSnapshotBuilder::getSnapshot(const LayerHierarchy::TraversalPath& id) const {
488 auto it = mIdToSnapshot.find(id);
489 return it == mIdToSnapshot.end() ? nullptr : it->second;
490}
491
Vishnu Naircfb2d252023-01-19 04:44:02 +0000492LayerSnapshot* LayerSnapshotBuilder::createSnapshot(const LayerHierarchy::TraversalPath& id,
493 const RequestedLayerState& layer) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000494 mSnapshots.emplace_back(std::make_unique<LayerSnapshot>(layer, id));
Vishnu Naircfb2d252023-01-19 04:44:02 +0000495 LayerSnapshot* snapshot = mSnapshots.back().get();
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000496 snapshot->globalZ = static_cast<size_t>(mSnapshots.size()) - 1;
497 mIdToSnapshot[id] = snapshot;
498 return snapshot;
499}
500
501void LayerSnapshotBuilder::sortSnapshotsByZ(const Args& args) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000502 if (!mResortSnapshots && !args.forceUpdate &&
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000503 !args.layerLifecycleManager.getGlobalChanges().any(
504 RequestedLayerState::Changes::Hierarchy |
505 RequestedLayerState::Changes::Visibility)) {
506 // We are not force updating and there are no hierarchy or visibility changes. Avoid sorting
507 // the snapshots.
508 return;
509 }
510
Vishnu Naircfb2d252023-01-19 04:44:02 +0000511 mResortSnapshots = false;
512
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000513 size_t globalZ = 0;
514 args.root.traverseInZOrder(
515 [this, &globalZ](const LayerHierarchy&,
516 const LayerHierarchy::TraversalPath& traversalPath) -> bool {
517 LayerSnapshot* snapshot = getSnapshot(traversalPath);
518 if (!snapshot) {
519 return false;
520 }
521
522 if (snapshot->isHiddenByPolicy() &&
523 !snapshot->changes.test(RequestedLayerState::Changes::Visibility)) {
524 return false;
525 }
526
Vishnu Naircfb2d252023-01-19 04:44:02 +0000527 if (snapshot->getIsVisible() || snapshot->hasInputInfo()) {
528 updateVisibility(*snapshot);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000529 size_t oldZ = snapshot->globalZ;
530 size_t newZ = globalZ++;
531 snapshot->globalZ = newZ;
532 if (oldZ == newZ) {
533 return true;
534 }
535 mSnapshots[newZ]->globalZ = oldZ;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000536 LLOGV(snapshot->sequence, "Made visible z=%zu -> %zu %s", oldZ, newZ,
537 snapshot->getDebugString().c_str());
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000538 std::iter_swap(mSnapshots.begin() + static_cast<ssize_t>(oldZ),
539 mSnapshots.begin() + static_cast<ssize_t>(newZ));
540 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000541 return true;
542 });
Vishnu Naircfb2d252023-01-19 04:44:02 +0000543 mNumInterestingSnapshots = (int)globalZ;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000544 while (globalZ < mSnapshots.size()) {
545 mSnapshots[globalZ]->globalZ = globalZ;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000546 updateVisibility(*mSnapshots[globalZ]);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000547 globalZ++;
548 }
549}
550
551void LayerSnapshotBuilder::updateRelativeState(LayerSnapshot& snapshot,
552 const LayerSnapshot& parentSnapshot,
553 bool parentIsRelative, const Args& args) {
554 if (parentIsRelative) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000555 snapshot.isHiddenByPolicyFromRelativeParent =
556 parentSnapshot.isHiddenByPolicyFromParent || parentSnapshot.invalidTransform;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000557 if (args.includeMetadata) {
558 snapshot.relativeLayerMetadata = parentSnapshot.layerMetadata;
559 }
560 } else {
561 snapshot.isHiddenByPolicyFromRelativeParent =
562 parentSnapshot.isHiddenByPolicyFromRelativeParent;
563 if (args.includeMetadata) {
564 snapshot.relativeLayerMetadata = parentSnapshot.relativeLayerMetadata;
565 }
566 }
567 snapshot.isVisible = snapshot.getIsVisible();
568}
569
Vishnu Naircfb2d252023-01-19 04:44:02 +0000570void LayerSnapshotBuilder::updateChildState(LayerSnapshot& snapshot,
571 const LayerSnapshot& childSnapshot, const Args& args) {
572 if (snapshot.childState.hasValidFrameRate) {
573 return;
574 }
575 if (args.forceUpdate || childSnapshot.changes.test(RequestedLayerState::Changes::FrameRate)) {
576 // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes
577 // for the same reason we are allowing touch boost for those layers. See
578 // RefreshRateSelector::rankFrameRates for details.
579 using FrameRateCompatibility = scheduler::LayerInfo::FrameRateCompatibility;
580 const auto layerVotedWithDefaultCompatibility = childSnapshot.frameRate.rate.isValid() &&
581 childSnapshot.frameRate.type == FrameRateCompatibility::Default;
582 const auto layerVotedWithNoVote =
583 childSnapshot.frameRate.type == FrameRateCompatibility::NoVote;
584 const auto layerVotedWithExactCompatibility = childSnapshot.frameRate.rate.isValid() &&
585 childSnapshot.frameRate.type == FrameRateCompatibility::Exact;
586
587 snapshot.childState.hasValidFrameRate |= layerVotedWithDefaultCompatibility ||
588 layerVotedWithNoVote || layerVotedWithExactCompatibility;
589
590 // If we don't have a valid frame rate, but the children do, we set this
591 // layer as NoVote to allow the children to control the refresh rate
592 if (!snapshot.frameRate.rate.isValid() &&
593 snapshot.frameRate.type != FrameRateCompatibility::NoVote &&
594 snapshot.childState.hasValidFrameRate) {
595 snapshot.frameRate =
596 scheduler::LayerInfo::FrameRate(Fps(), FrameRateCompatibility::NoVote);
597 snapshot.changes |= childSnapshot.changes & RequestedLayerState::Changes::FrameRate;
598 }
599 }
600}
601
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000602void LayerSnapshotBuilder::resetRelativeState(LayerSnapshot& snapshot) {
603 snapshot.isHiddenByPolicyFromRelativeParent = false;
604 snapshot.relativeLayerMetadata.mMap.clear();
605}
606
607uint32_t getDisplayRotationFlags(
608 const display::DisplayMap<ui::LayerStack, frontend::DisplayInfo>& displays,
609 const ui::LayerStack& layerStack) {
610 static frontend::DisplayInfo sDefaultDisplayInfo = {.isPrimary = false};
611 auto display = displays.get(layerStack).value_or(sDefaultDisplayInfo).get();
612 return display.isPrimary ? display.rotationFlags : 0;
613}
614
615void LayerSnapshotBuilder::updateSnapshot(LayerSnapshot& snapshot, const Args& args,
616 const RequestedLayerState& requested,
617 const LayerSnapshot& parentSnapshot,
Vishnu Naircfb2d252023-01-19 04:44:02 +0000618 const LayerHierarchy::TraversalPath& path,
619 bool newSnapshot) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000620 // Always update flags and visibility
621 ftl::Flags<RequestedLayerState::Changes> parentChanges = parentSnapshot.changes &
622 (RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Geometry |
623 RequestedLayerState::Changes::Visibility | RequestedLayerState::Changes::Metadata |
624 RequestedLayerState::Changes::AffectsChildren);
625 snapshot.changes = parentChanges | requested.changes;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000626 snapshot.isHiddenByPolicyFromParent = parentSnapshot.isHiddenByPolicyFromParent ||
627 parentSnapshot.invalidTransform || requested.isHiddenByPolicy();
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000628 snapshot.contentDirty = requested.what & layer_state_t::CONTENT_DIRTY;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000629 // TODO(b/238781169) scope down the changes to only buffer updates.
630 snapshot.hasReadyFrame =
631 (snapshot.contentDirty || requested.autoRefresh) && (requested.externalTexture);
632 // TODO(b/238781169) how is this used? ag/15523870
633 snapshot.sidebandStreamHasFrame = false;
634 updateSurfaceDamage(requested, snapshot.hasReadyFrame, args.forceFullDamage,
635 snapshot.surfaceDamage);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000636
Vishnu Naircfb2d252023-01-19 04:44:02 +0000637 const bool forceUpdate = newSnapshot || args.forceUpdate ||
638 snapshot.changes.any(RequestedLayerState::Changes::Visibility |
639 RequestedLayerState::Changes::Created);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000640 uint32_t displayRotationFlags =
641 getDisplayRotationFlags(args.displays, snapshot.outputFilter.layerStack);
642
Vishnu Naircfb2d252023-01-19 04:44:02 +0000643 // always update the buffer regardless of visibility
644 if (forceUpdate || requested.what & layer_state_t::BUFFER_CHANGES) {
645 snapshot.acquireFence =
646 (requested.externalTexture &&
647 requested.bufferData->flags.test(BufferData::BufferDataChange::fenceChanged))
648 ? requested.bufferData->acquireFence
649 : Fence::NO_FENCE;
650 snapshot.buffer =
651 requested.externalTexture ? requested.externalTexture->getBuffer() : nullptr;
652 snapshot.bufferSize = requested.getBufferSize(displayRotationFlags);
653 snapshot.geomBufferSize = snapshot.bufferSize;
654 snapshot.croppedBufferSize = requested.getCroppedBufferSize(snapshot.bufferSize);
655 snapshot.dataspace = requested.dataspace;
656 snapshot.externalTexture = requested.externalTexture;
657 snapshot.frameNumber = (requested.bufferData) ? requested.bufferData->frameNumber : 0;
658 snapshot.geomBufferTransform = requested.bufferTransform;
659 snapshot.geomBufferUsesDisplayInverseTransform = requested.transformToDisplayInverse;
660 snapshot.geomContentCrop = requested.getBufferCrop();
661 snapshot.geomUsesSourceCrop = snapshot.hasBufferOrSidebandStream();
662 snapshot.hasProtectedContent = requested.externalTexture &&
663 requested.externalTexture->getUsage() & GRALLOC_USAGE_PROTECTED;
664 snapshot.isHdrY410 = requested.dataspace == ui::Dataspace::BT2020_ITU_PQ &&
665 requested.api == NATIVE_WINDOW_API_MEDIA &&
666 requested.bufferData->getPixelFormat() == HAL_PIXEL_FORMAT_RGBA_1010102;
667 snapshot.sidebandStream = requested.sidebandStream;
668 snapshot.transparentRegionHint = requested.transparentRegion;
669 snapshot.color.rgb = requested.getColor().rgb;
John Reck68796592023-01-25 13:47:12 -0500670 snapshot.currentSdrHdrRatio = requested.currentSdrHdrRatio;
671 snapshot.desiredSdrHdrRatio = requested.desiredSdrHdrRatio;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000672 }
673
674 if (snapshot.isHiddenByPolicyFromParent && !newSnapshot) {
675 if (forceUpdate ||
676 snapshot.changes.any(RequestedLayerState::Changes::Hierarchy |
677 RequestedLayerState::Changes::Geometry |
678 RequestedLayerState::Changes::Input)) {
679 updateInput(snapshot, requested, parentSnapshot, path, args);
680 }
681 return;
682 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000683
684 if (forceUpdate || snapshot.changes.any(RequestedLayerState::Changes::AffectsChildren)) {
685 // If root layer, use the layer stack otherwise get the parent's layer stack.
686 snapshot.color.a = parentSnapshot.color.a * requested.color.a;
687 snapshot.alpha = snapshot.color.a;
688 snapshot.isSecure =
689 parentSnapshot.isSecure || (requested.flags & layer_state_t::eLayerSecure);
690 snapshot.isTrustedOverlay = parentSnapshot.isTrustedOverlay || requested.isTrustedOverlay;
691 snapshot.outputFilter.layerStack = requested.parentId != UNASSIGNED_LAYER_ID
692 ? parentSnapshot.outputFilter.layerStack
693 : requested.layerStack;
694 snapshot.outputFilter.toInternalDisplay = parentSnapshot.outputFilter.toInternalDisplay ||
695 (requested.flags & layer_state_t::eLayerSkipScreenshot);
696 snapshot.stretchEffect = (requested.stretchEffect.hasEffect())
697 ? requested.stretchEffect
698 : parentSnapshot.stretchEffect;
699 if (!parentSnapshot.colorTransformIsIdentity) {
700 snapshot.colorTransform = parentSnapshot.colorTransform * requested.colorTransform;
701 snapshot.colorTransformIsIdentity = false;
702 } else {
703 snapshot.colorTransform = requested.colorTransform;
704 snapshot.colorTransformIsIdentity = !requested.hasColorTransform;
705 }
Vishnu Naircfb2d252023-01-19 04:44:02 +0000706 snapshot.gameMode = requested.metadata.has(gui::METADATA_GAME_MODE)
707 ? requested.gameMode
708 : parentSnapshot.gameMode;
709 snapshot.frameRate = (requested.requestedFrameRate.rate.isValid() ||
710 (requested.requestedFrameRate.type ==
711 scheduler::LayerInfo::FrameRateCompatibility::NoVote))
712 ? requested.requestedFrameRate
713 : parentSnapshot.frameRate;
714 snapshot.fixedTransformHint = requested.fixedTransformHint != ui::Transform::ROT_INVALID
715 ? requested.fixedTransformHint
716 : parentSnapshot.fixedTransformHint;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000717 }
718
719 if (forceUpdate || requested.changes.get() != 0) {
720 snapshot.compositionType = requested.getCompositionType();
721 snapshot.dimmingEnabled = requested.dimmingEnabled;
722 snapshot.layerOpaqueFlagSet =
723 (requested.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
724 }
725
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000726 if (forceUpdate || snapshot.changes.any(RequestedLayerState::Changes::Content)) {
727 snapshot.color.rgb = requested.getColor().rgb;
728 snapshot.isColorspaceAgnostic = requested.colorSpaceAgnostic;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000729 snapshot.backgroundBlurRadius =
730 args.supportsBlur ? static_cast<int>(requested.backgroundBlurRadius) : 0;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000731 snapshot.blurRegions = requested.blurRegions;
732 snapshot.hdrMetadata = requested.hdrMetadata;
733 }
734
735 if (forceUpdate ||
736 snapshot.changes.any(RequestedLayerState::Changes::Hierarchy |
737 RequestedLayerState::Changes::Geometry)) {
738 updateLayerBounds(snapshot, requested, parentSnapshot, displayRotationFlags);
739 updateRoundedCorner(snapshot, requested, parentSnapshot);
740 }
741
742 if (forceUpdate ||
743 snapshot.changes.any(RequestedLayerState::Changes::Hierarchy |
744 RequestedLayerState::Changes::Geometry |
745 RequestedLayerState::Changes::Input)) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000746 updateInput(snapshot, requested, parentSnapshot, path, args);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000747 }
748
749 // computed snapshot properties
750 updateShadows(snapshot, requested, args.globalShadowSettings);
751 if (args.includeMetadata) {
752 snapshot.layerMetadata = parentSnapshot.layerMetadata;
753 snapshot.layerMetadata.merge(requested.metadata);
754 }
755 snapshot.forceClientComposition = snapshot.isHdrY410 || snapshot.shadowSettings.length > 0 ||
756 requested.blurRegions.size() > 0 || snapshot.stretchEffect.hasEffect();
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000757 snapshot.isOpaque = snapshot.isContentOpaque() && !snapshot.roundedCorner.hasRoundedCorners() &&
758 snapshot.color.a == 1.f;
759 snapshot.blendMode = getBlendMode(snapshot, requested);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000760 // TODO(b/238781169) pass this from flinger
761 // snapshot.fps;
762 // snapshot.metadata;
763 LLOGV(snapshot.sequence,
764 "%supdated [%d]%s changes parent:%s global:%s local:%s requested:%s %s from parent %s",
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000765 args.forceUpdate ? "Force " : "", requested.id, requested.name.c_str(),
766 parentSnapshot.changes.string().c_str(), snapshot.changes.string().c_str(),
767 requested.changes.string().c_str(), std::to_string(requested.what).c_str(),
768 snapshot.getDebugString().c_str(), parentSnapshot.getDebugString().c_str());
769}
770
771void LayerSnapshotBuilder::updateRoundedCorner(LayerSnapshot& snapshot,
772 const RequestedLayerState& requested,
773 const LayerSnapshot& parentSnapshot) {
774 snapshot.roundedCorner = RoundedCornerState();
775 RoundedCornerState parentRoundedCorner;
776 if (parentSnapshot.roundedCorner.hasRoundedCorners()) {
777 parentRoundedCorner = parentSnapshot.roundedCorner;
778 ui::Transform t = snapshot.localTransform.inverse();
779 parentRoundedCorner.cropRect = t.transform(parentRoundedCorner.cropRect);
780 parentRoundedCorner.radius.x *= t.getScaleX();
781 parentRoundedCorner.radius.y *= t.getScaleY();
782 }
783
784 FloatRect layerCropRect = snapshot.croppedBufferSize.toFloatRect();
785 const vec2 radius(requested.cornerRadius, requested.cornerRadius);
786 RoundedCornerState layerSettings(layerCropRect, radius);
787 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && !layerCropRect.isEmpty();
788 const bool parentRoundedCornerValid = parentRoundedCorner.hasRoundedCorners();
789 if (layerSettingsValid && parentRoundedCornerValid) {
790 // If the parent and the layer have rounded corner settings, use the parent settings if
791 // the parent crop is entirely inside the layer crop. This has limitations and cause
792 // rendering artifacts. See b/200300845 for correct fix.
793 if (parentRoundedCorner.cropRect.left > layerCropRect.left &&
794 parentRoundedCorner.cropRect.top > layerCropRect.top &&
795 parentRoundedCorner.cropRect.right < layerCropRect.right &&
796 parentRoundedCorner.cropRect.bottom < layerCropRect.bottom) {
797 snapshot.roundedCorner = parentRoundedCorner;
798 } else {
799 snapshot.roundedCorner = layerSettings;
800 }
801 } else if (layerSettingsValid) {
802 snapshot.roundedCorner = layerSettings;
803 } else if (parentRoundedCornerValid) {
804 snapshot.roundedCorner = parentRoundedCorner;
805 }
806}
807
808void LayerSnapshotBuilder::updateLayerBounds(LayerSnapshot& snapshot,
809 const RequestedLayerState& requested,
810 const LayerSnapshot& parentSnapshot,
811 uint32_t displayRotationFlags) {
812 snapshot.croppedBufferSize = requested.getCroppedBufferSize(snapshot.bufferSize);
813 snapshot.geomCrop = requested.crop;
814 snapshot.localTransform = requested.getTransform(displayRotationFlags);
815 snapshot.localTransformInverse = snapshot.localTransform.inverse();
816 snapshot.geomLayerTransform = parentSnapshot.geomLayerTransform * snapshot.localTransform;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000817 const bool transformWasInvalid = snapshot.invalidTransform;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000818 snapshot.invalidTransform = !LayerSnapshot::isTransformValid(snapshot.geomLayerTransform);
819 if (snapshot.invalidTransform) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000820 auto& t = snapshot.geomLayerTransform;
821 auto& requestedT = requested.requestedTransform;
822 std::string transformDebug =
823 base::StringPrintf(" transform={%f,%f,%f,%f} requestedTransform={%f,%f,%f,%f}",
824 t.dsdx(), t.dsdy(), t.dtdx(), t.dtdy(), requestedT.dsdx(),
825 requestedT.dsdy(), requestedT.dtdx(), requestedT.dtdy());
826 std::string bufferDebug;
827 if (requested.externalTexture) {
828 auto unRotBuffer = requested.getUnrotatedBufferSize(displayRotationFlags);
829 auto& destFrame = requested.destinationFrame;
830 bufferDebug = base::StringPrintf(" buffer={%d,%d} displayRot=%d"
831 " destFrame={%d,%d,%d,%d} unRotBuffer={%d,%d}",
832 requested.externalTexture->getWidth(),
833 requested.externalTexture->getHeight(),
834 displayRotationFlags, destFrame.left, destFrame.top,
835 destFrame.right, destFrame.bottom,
836 unRotBuffer.getHeight(), unRotBuffer.getWidth());
837 }
838 ALOGW("Resetting transform for %s because it is invalid.%s%s",
839 snapshot.getDebugString().c_str(), transformDebug.c_str(), bufferDebug.c_str());
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000840 snapshot.geomLayerTransform.reset();
841 }
Vishnu Naircfb2d252023-01-19 04:44:02 +0000842 if (transformWasInvalid != snapshot.invalidTransform) {
843 // If transform is invalid, the layer will be hidden.
844 mResortSnapshots = true;
845 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000846 snapshot.geomInverseLayerTransform = snapshot.geomLayerTransform.inverse();
847
848 FloatRect parentBounds = parentSnapshot.geomLayerBounds;
849 parentBounds = snapshot.localTransform.inverse().transform(parentBounds);
850 snapshot.geomLayerBounds =
851 (requested.externalTexture) ? snapshot.bufferSize.toFloatRect() : parentBounds;
852 if (!requested.crop.isEmpty()) {
853 snapshot.geomLayerBounds = snapshot.geomLayerBounds.intersect(requested.crop.toFloatRect());
854 }
855 snapshot.geomLayerBounds = snapshot.geomLayerBounds.intersect(parentBounds);
856 snapshot.transformedBounds = snapshot.geomLayerTransform.transform(snapshot.geomLayerBounds);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000857 const Rect geomLayerBoundsWithoutTransparentRegion =
858 RequestedLayerState::reduce(Rect(snapshot.geomLayerBounds),
859 requested.transparentRegion);
860 snapshot.transformedBoundsWithoutTransparentRegion =
861 snapshot.geomLayerTransform.transform(geomLayerBoundsWithoutTransparentRegion);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000862 snapshot.parentTransform = parentSnapshot.geomLayerTransform;
863
864 // Subtract the transparent region and snap to the bounds
Vishnu Naircfb2d252023-01-19 04:44:02 +0000865 const Rect bounds =
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000866 RequestedLayerState::reduce(snapshot.croppedBufferSize, requested.transparentRegion);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000867 if (requested.potentialCursor) {
868 snapshot.cursorFrame = snapshot.geomLayerTransform.transform(bounds);
869 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000870
871 // TODO(b/238781169) use dest vs src
872 snapshot.bufferNeedsFiltering = snapshot.externalTexture &&
873 getBufferNeedsFiltering(snapshot,
874 requested.getUnrotatedBufferSize(displayRotationFlags));
875}
876
877void LayerSnapshotBuilder::updateShadows(LayerSnapshot& snapshot,
878 const RequestedLayerState& requested,
879 const renderengine::ShadowSettings& globalShadowSettings) {
880 snapshot.shadowRadius = requested.shadowRadius;
881 snapshot.shadowSettings.length = requested.shadowRadius;
882 if (snapshot.shadowRadius > 0.f) {
883 snapshot.shadowSettings = globalShadowSettings;
884
885 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
886 // it if transparent regions are present. This may not be necessary since shadows are
887 // typically cast by layers without transparent regions.
888 snapshot.shadowSettings.boundaries = snapshot.geomLayerBounds;
889
890 // If the casting layer is translucent, we need to fill in the shadow underneath the
891 // layer. Otherwise the generated shadow will only be shown around the casting layer.
892 snapshot.shadowSettings.casterIsTranslucent =
893 !snapshot.isContentOpaque() || (snapshot.alpha < 1.0f);
894 snapshot.shadowSettings.ambientColor *= snapshot.alpha;
895 snapshot.shadowSettings.spotColor *= snapshot.alpha;
896 }
897}
898
899void LayerSnapshotBuilder::updateInput(LayerSnapshot& snapshot,
900 const RequestedLayerState& requested,
901 const LayerSnapshot& parentSnapshot,
Vishnu Naircfb2d252023-01-19 04:44:02 +0000902 const LayerHierarchy::TraversalPath& path,
903 const Args& args) {
904 if (requested.windowInfoHandle) {
905 snapshot.inputInfo = *requested.windowInfoHandle->getInfo();
906 } else {
907 snapshot.inputInfo = {};
908 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000909 snapshot.inputInfo.displayId = static_cast<int32_t>(snapshot.outputFilter.layerStack.id);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000910
911 if (!needsInputInfo(snapshot, requested)) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000912 return;
913 }
914
Vishnu Naircfb2d252023-01-19 04:44:02 +0000915 static frontend::DisplayInfo sDefaultInfo = {.isSecure = false};
916 const std::optional<frontend::DisplayInfo> displayInfoOpt =
917 args.displays.get(snapshot.outputFilter.layerStack);
918 bool noValidDisplay = !displayInfoOpt.has_value();
919 auto displayInfo = displayInfoOpt.value_or(sDefaultInfo);
920
921 if (!requested.windowInfoHandle) {
922 snapshot.inputInfo.inputConfig = gui::WindowInfo::InputConfig::NO_INPUT_CHANNEL;
923 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000924 fillInputFrameInfo(snapshot.inputInfo, displayInfo.transform, snapshot);
925
926 if (noValidDisplay) {
927 // Do not let the window receive touches if it is not associated with a valid display
928 // transform. We still allow the window to receive keys and prevent ANRs.
929 snapshot.inputInfo.inputConfig |= gui::WindowInfo::InputConfig::NOT_TOUCHABLE;
930 }
931
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000932 snapshot.inputInfo.alpha = snapshot.color.a;
933 snapshot.inputInfo.touchOcclusionMode = parentSnapshot.inputInfo.touchOcclusionMode;
934 if (requested.dropInputMode == gui::DropInputMode::ALL ||
935 parentSnapshot.dropInputMode == gui::DropInputMode::ALL) {
936 snapshot.dropInputMode = gui::DropInputMode::ALL;
937 } else if (requested.dropInputMode == gui::DropInputMode::OBSCURED ||
938 parentSnapshot.dropInputMode == gui::DropInputMode::OBSCURED) {
939 snapshot.dropInputMode = gui::DropInputMode::OBSCURED;
940 } else {
941 snapshot.dropInputMode = gui::DropInputMode::NONE;
942 }
943
944 handleDropInputMode(snapshot, parentSnapshot);
945
946 // If the window will be blacked out on a display because the display does not have the secure
947 // flag and the layer has the secure flag set, then drop input.
948 if (!displayInfo.isSecure && snapshot.isSecure) {
949 snapshot.inputInfo.inputConfig |= gui::WindowInfo::InputConfig::DROP_INPUT;
950 }
951
952 auto cropLayerSnapshot = getSnapshot(requested.touchCropId);
953 if (snapshot.inputInfo.replaceTouchableRegionWithCrop) {
954 const Rect bounds(cropLayerSnapshot ? cropLayerSnapshot->transformedBounds
955 : snapshot.transformedBounds);
956 snapshot.inputInfo.touchableRegion = Region(displayInfo.transform.transform(bounds));
957 } else if (cropLayerSnapshot) {
958 snapshot.inputInfo.touchableRegion = snapshot.inputInfo.touchableRegion.intersect(
959 displayInfo.transform.transform(Rect{cropLayerSnapshot->transformedBounds}));
960 }
961
962 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
963 // if it was set by WM for a known system overlay
964 if (snapshot.isTrustedOverlay) {
965 snapshot.inputInfo.inputConfig |= gui::WindowInfo::InputConfig::TRUSTED_OVERLAY;
966 }
967
968 // If the layer is a clone, we need to crop the input region to cloned root to prevent
969 // touches from going outside the cloned area.
970 if (path.isClone()) {
971 snapshot.inputInfo.inputConfig |= gui::WindowInfo::InputConfig::CLONE;
972 auto clonedRootSnapshot = getSnapshot(path.mirrorRootIds.back());
973 if (clonedRootSnapshot) {
974 const Rect rect =
975 displayInfo.transform.transform(Rect{clonedRootSnapshot->transformedBounds});
976 snapshot.inputInfo.touchableRegion = snapshot.inputInfo.touchableRegion.intersect(rect);
977 }
978 }
979}
980
981std::vector<std::unique_ptr<LayerSnapshot>>& LayerSnapshotBuilder::getSnapshots() {
982 return mSnapshots;
983}
984
Vishnu Naircfb2d252023-01-19 04:44:02 +0000985void LayerSnapshotBuilder::forEachVisibleSnapshot(const ConstVisitor& visitor) const {
986 for (int i = 0; i < mNumInterestingSnapshots; i++) {
987 LayerSnapshot& snapshot = *mSnapshots[(size_t)i];
988 if (!snapshot.isVisible) continue;
989 visitor(snapshot);
990 }
991}
992
993void LayerSnapshotBuilder::forEachVisibleSnapshot(const Visitor& visitor) {
994 for (int i = 0; i < mNumInterestingSnapshots; i++) {
995 std::unique_ptr<LayerSnapshot>& snapshot = mSnapshots.at((size_t)i);
996 if (!snapshot->isVisible) continue;
997 visitor(snapshot);
998 }
999}
1000
1001void LayerSnapshotBuilder::forEachInputSnapshot(const ConstVisitor& visitor) const {
1002 for (int i = mNumInterestingSnapshots - 1; i >= 0; i--) {
1003 LayerSnapshot& snapshot = *mSnapshots[(size_t)i];
1004 if (!snapshot.hasInputInfo()) continue;
1005 visitor(snapshot);
1006 }
1007}
1008
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001009} // namespace android::surfaceflinger::frontend