blob: d0ffe613cc556d7ff77cdd00d29b73a8a99cc1de [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 Naira9c43762023-01-27 19:10:25 +0000717 // Display mirrors are always placed in a VirtualDisplay so we never want to capture layers
718 // marked as skip capture
719 snapshot.handleSkipScreenshotFlag = parentSnapshot.handleSkipScreenshotFlag ||
720 (requested.layerStackToMirror != ui::INVALID_LAYER_STACK);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000721 }
722
723 if (forceUpdate || requested.changes.get() != 0) {
724 snapshot.compositionType = requested.getCompositionType();
725 snapshot.dimmingEnabled = requested.dimmingEnabled;
726 snapshot.layerOpaqueFlagSet =
727 (requested.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
728 }
729
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000730 if (forceUpdate || snapshot.changes.any(RequestedLayerState::Changes::Content)) {
731 snapshot.color.rgb = requested.getColor().rgb;
732 snapshot.isColorspaceAgnostic = requested.colorSpaceAgnostic;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000733 snapshot.backgroundBlurRadius =
734 args.supportsBlur ? static_cast<int>(requested.backgroundBlurRadius) : 0;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000735 snapshot.blurRegions = requested.blurRegions;
736 snapshot.hdrMetadata = requested.hdrMetadata;
737 }
738
739 if (forceUpdate ||
740 snapshot.changes.any(RequestedLayerState::Changes::Hierarchy |
741 RequestedLayerState::Changes::Geometry)) {
742 updateLayerBounds(snapshot, requested, parentSnapshot, displayRotationFlags);
743 updateRoundedCorner(snapshot, requested, parentSnapshot);
744 }
745
746 if (forceUpdate ||
747 snapshot.changes.any(RequestedLayerState::Changes::Hierarchy |
748 RequestedLayerState::Changes::Geometry |
749 RequestedLayerState::Changes::Input)) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000750 updateInput(snapshot, requested, parentSnapshot, path, args);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000751 }
752
753 // computed snapshot properties
754 updateShadows(snapshot, requested, args.globalShadowSettings);
755 if (args.includeMetadata) {
756 snapshot.layerMetadata = parentSnapshot.layerMetadata;
757 snapshot.layerMetadata.merge(requested.metadata);
758 }
759 snapshot.forceClientComposition = snapshot.isHdrY410 || snapshot.shadowSettings.length > 0 ||
760 requested.blurRegions.size() > 0 || snapshot.stretchEffect.hasEffect();
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000761 snapshot.isOpaque = snapshot.isContentOpaque() && !snapshot.roundedCorner.hasRoundedCorners() &&
762 snapshot.color.a == 1.f;
763 snapshot.blendMode = getBlendMode(snapshot, requested);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000764 // TODO(b/238781169) pass this from flinger
765 // snapshot.fps;
766 // snapshot.metadata;
767 LLOGV(snapshot.sequence,
768 "%supdated [%d]%s changes parent:%s global:%s local:%s requested:%s %s from parent %s",
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000769 args.forceUpdate ? "Force " : "", requested.id, requested.name.c_str(),
770 parentSnapshot.changes.string().c_str(), snapshot.changes.string().c_str(),
771 requested.changes.string().c_str(), std::to_string(requested.what).c_str(),
772 snapshot.getDebugString().c_str(), parentSnapshot.getDebugString().c_str());
773}
774
775void LayerSnapshotBuilder::updateRoundedCorner(LayerSnapshot& snapshot,
776 const RequestedLayerState& requested,
777 const LayerSnapshot& parentSnapshot) {
778 snapshot.roundedCorner = RoundedCornerState();
779 RoundedCornerState parentRoundedCorner;
780 if (parentSnapshot.roundedCorner.hasRoundedCorners()) {
781 parentRoundedCorner = parentSnapshot.roundedCorner;
782 ui::Transform t = snapshot.localTransform.inverse();
783 parentRoundedCorner.cropRect = t.transform(parentRoundedCorner.cropRect);
784 parentRoundedCorner.radius.x *= t.getScaleX();
785 parentRoundedCorner.radius.y *= t.getScaleY();
786 }
787
788 FloatRect layerCropRect = snapshot.croppedBufferSize.toFloatRect();
789 const vec2 radius(requested.cornerRadius, requested.cornerRadius);
790 RoundedCornerState layerSettings(layerCropRect, radius);
791 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && !layerCropRect.isEmpty();
792 const bool parentRoundedCornerValid = parentRoundedCorner.hasRoundedCorners();
793 if (layerSettingsValid && parentRoundedCornerValid) {
794 // If the parent and the layer have rounded corner settings, use the parent settings if
795 // the parent crop is entirely inside the layer crop. This has limitations and cause
796 // rendering artifacts. See b/200300845 for correct fix.
797 if (parentRoundedCorner.cropRect.left > layerCropRect.left &&
798 parentRoundedCorner.cropRect.top > layerCropRect.top &&
799 parentRoundedCorner.cropRect.right < layerCropRect.right &&
800 parentRoundedCorner.cropRect.bottom < layerCropRect.bottom) {
801 snapshot.roundedCorner = parentRoundedCorner;
802 } else {
803 snapshot.roundedCorner = layerSettings;
804 }
805 } else if (layerSettingsValid) {
806 snapshot.roundedCorner = layerSettings;
807 } else if (parentRoundedCornerValid) {
808 snapshot.roundedCorner = parentRoundedCorner;
809 }
810}
811
812void LayerSnapshotBuilder::updateLayerBounds(LayerSnapshot& snapshot,
813 const RequestedLayerState& requested,
814 const LayerSnapshot& parentSnapshot,
815 uint32_t displayRotationFlags) {
816 snapshot.croppedBufferSize = requested.getCroppedBufferSize(snapshot.bufferSize);
817 snapshot.geomCrop = requested.crop;
818 snapshot.localTransform = requested.getTransform(displayRotationFlags);
819 snapshot.localTransformInverse = snapshot.localTransform.inverse();
820 snapshot.geomLayerTransform = parentSnapshot.geomLayerTransform * snapshot.localTransform;
Vishnu Naircfb2d252023-01-19 04:44:02 +0000821 const bool transformWasInvalid = snapshot.invalidTransform;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000822 snapshot.invalidTransform = !LayerSnapshot::isTransformValid(snapshot.geomLayerTransform);
823 if (snapshot.invalidTransform) {
Vishnu Naircfb2d252023-01-19 04:44:02 +0000824 auto& t = snapshot.geomLayerTransform;
825 auto& requestedT = requested.requestedTransform;
826 std::string transformDebug =
827 base::StringPrintf(" transform={%f,%f,%f,%f} requestedTransform={%f,%f,%f,%f}",
828 t.dsdx(), t.dsdy(), t.dtdx(), t.dtdy(), requestedT.dsdx(),
829 requestedT.dsdy(), requestedT.dtdx(), requestedT.dtdy());
830 std::string bufferDebug;
831 if (requested.externalTexture) {
832 auto unRotBuffer = requested.getUnrotatedBufferSize(displayRotationFlags);
833 auto& destFrame = requested.destinationFrame;
834 bufferDebug = base::StringPrintf(" buffer={%d,%d} displayRot=%d"
835 " destFrame={%d,%d,%d,%d} unRotBuffer={%d,%d}",
836 requested.externalTexture->getWidth(),
837 requested.externalTexture->getHeight(),
838 displayRotationFlags, destFrame.left, destFrame.top,
839 destFrame.right, destFrame.bottom,
840 unRotBuffer.getHeight(), unRotBuffer.getWidth());
841 }
842 ALOGW("Resetting transform for %s because it is invalid.%s%s",
843 snapshot.getDebugString().c_str(), transformDebug.c_str(), bufferDebug.c_str());
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000844 snapshot.geomLayerTransform.reset();
845 }
Vishnu Naircfb2d252023-01-19 04:44:02 +0000846 if (transformWasInvalid != snapshot.invalidTransform) {
847 // If transform is invalid, the layer will be hidden.
848 mResortSnapshots = true;
849 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000850 snapshot.geomInverseLayerTransform = snapshot.geomLayerTransform.inverse();
851
852 FloatRect parentBounds = parentSnapshot.geomLayerBounds;
853 parentBounds = snapshot.localTransform.inverse().transform(parentBounds);
854 snapshot.geomLayerBounds =
855 (requested.externalTexture) ? snapshot.bufferSize.toFloatRect() : parentBounds;
856 if (!requested.crop.isEmpty()) {
857 snapshot.geomLayerBounds = snapshot.geomLayerBounds.intersect(requested.crop.toFloatRect());
858 }
859 snapshot.geomLayerBounds = snapshot.geomLayerBounds.intersect(parentBounds);
860 snapshot.transformedBounds = snapshot.geomLayerTransform.transform(snapshot.geomLayerBounds);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000861 const Rect geomLayerBoundsWithoutTransparentRegion =
862 RequestedLayerState::reduce(Rect(snapshot.geomLayerBounds),
863 requested.transparentRegion);
864 snapshot.transformedBoundsWithoutTransparentRegion =
865 snapshot.geomLayerTransform.transform(geomLayerBoundsWithoutTransparentRegion);
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000866 snapshot.parentTransform = parentSnapshot.geomLayerTransform;
867
868 // Subtract the transparent region and snap to the bounds
Vishnu Naircfb2d252023-01-19 04:44:02 +0000869 const Rect bounds =
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000870 RequestedLayerState::reduce(snapshot.croppedBufferSize, requested.transparentRegion);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000871 if (requested.potentialCursor) {
872 snapshot.cursorFrame = snapshot.geomLayerTransform.transform(bounds);
873 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000874
875 // TODO(b/238781169) use dest vs src
876 snapshot.bufferNeedsFiltering = snapshot.externalTexture &&
877 getBufferNeedsFiltering(snapshot,
878 requested.getUnrotatedBufferSize(displayRotationFlags));
879}
880
881void LayerSnapshotBuilder::updateShadows(LayerSnapshot& snapshot,
882 const RequestedLayerState& requested,
883 const renderengine::ShadowSettings& globalShadowSettings) {
884 snapshot.shadowRadius = requested.shadowRadius;
885 snapshot.shadowSettings.length = requested.shadowRadius;
886 if (snapshot.shadowRadius > 0.f) {
887 snapshot.shadowSettings = globalShadowSettings;
888
889 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
890 // it if transparent regions are present. This may not be necessary since shadows are
891 // typically cast by layers without transparent regions.
892 snapshot.shadowSettings.boundaries = snapshot.geomLayerBounds;
893
894 // If the casting layer is translucent, we need to fill in the shadow underneath the
895 // layer. Otherwise the generated shadow will only be shown around the casting layer.
896 snapshot.shadowSettings.casterIsTranslucent =
897 !snapshot.isContentOpaque() || (snapshot.alpha < 1.0f);
898 snapshot.shadowSettings.ambientColor *= snapshot.alpha;
899 snapshot.shadowSettings.spotColor *= snapshot.alpha;
900 }
901}
902
903void LayerSnapshotBuilder::updateInput(LayerSnapshot& snapshot,
904 const RequestedLayerState& requested,
905 const LayerSnapshot& parentSnapshot,
Vishnu Naircfb2d252023-01-19 04:44:02 +0000906 const LayerHierarchy::TraversalPath& path,
907 const Args& args) {
908 if (requested.windowInfoHandle) {
909 snapshot.inputInfo = *requested.windowInfoHandle->getInfo();
910 } else {
911 snapshot.inputInfo = {};
912 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000913 snapshot.inputInfo.displayId = static_cast<int32_t>(snapshot.outputFilter.layerStack.id);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000914
915 if (!needsInputInfo(snapshot, requested)) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000916 return;
917 }
918
Vishnu Naircfb2d252023-01-19 04:44:02 +0000919 static frontend::DisplayInfo sDefaultInfo = {.isSecure = false};
920 const std::optional<frontend::DisplayInfo> displayInfoOpt =
921 args.displays.get(snapshot.outputFilter.layerStack);
922 bool noValidDisplay = !displayInfoOpt.has_value();
923 auto displayInfo = displayInfoOpt.value_or(sDefaultInfo);
924
925 if (!requested.windowInfoHandle) {
926 snapshot.inputInfo.inputConfig = gui::WindowInfo::InputConfig::NO_INPUT_CHANNEL;
927 }
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000928 fillInputFrameInfo(snapshot.inputInfo, displayInfo.transform, snapshot);
929
930 if (noValidDisplay) {
931 // Do not let the window receive touches if it is not associated with a valid display
932 // transform. We still allow the window to receive keys and prevent ANRs.
933 snapshot.inputInfo.inputConfig |= gui::WindowInfo::InputConfig::NOT_TOUCHABLE;
934 }
935
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000936 snapshot.inputInfo.alpha = snapshot.color.a;
937 snapshot.inputInfo.touchOcclusionMode = parentSnapshot.inputInfo.touchOcclusionMode;
938 if (requested.dropInputMode == gui::DropInputMode::ALL ||
939 parentSnapshot.dropInputMode == gui::DropInputMode::ALL) {
940 snapshot.dropInputMode = gui::DropInputMode::ALL;
941 } else if (requested.dropInputMode == gui::DropInputMode::OBSCURED ||
942 parentSnapshot.dropInputMode == gui::DropInputMode::OBSCURED) {
943 snapshot.dropInputMode = gui::DropInputMode::OBSCURED;
944 } else {
945 snapshot.dropInputMode = gui::DropInputMode::NONE;
946 }
947
948 handleDropInputMode(snapshot, parentSnapshot);
949
950 // If the window will be blacked out on a display because the display does not have the secure
951 // flag and the layer has the secure flag set, then drop input.
952 if (!displayInfo.isSecure && snapshot.isSecure) {
953 snapshot.inputInfo.inputConfig |= gui::WindowInfo::InputConfig::DROP_INPUT;
954 }
955
956 auto cropLayerSnapshot = getSnapshot(requested.touchCropId);
957 if (snapshot.inputInfo.replaceTouchableRegionWithCrop) {
958 const Rect bounds(cropLayerSnapshot ? cropLayerSnapshot->transformedBounds
959 : snapshot.transformedBounds);
960 snapshot.inputInfo.touchableRegion = Region(displayInfo.transform.transform(bounds));
961 } else if (cropLayerSnapshot) {
962 snapshot.inputInfo.touchableRegion = snapshot.inputInfo.touchableRegion.intersect(
963 displayInfo.transform.transform(Rect{cropLayerSnapshot->transformedBounds}));
964 }
965
966 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
967 // if it was set by WM for a known system overlay
968 if (snapshot.isTrustedOverlay) {
969 snapshot.inputInfo.inputConfig |= gui::WindowInfo::InputConfig::TRUSTED_OVERLAY;
970 }
971
972 // If the layer is a clone, we need to crop the input region to cloned root to prevent
973 // touches from going outside the cloned area.
974 if (path.isClone()) {
975 snapshot.inputInfo.inputConfig |= gui::WindowInfo::InputConfig::CLONE;
976 auto clonedRootSnapshot = getSnapshot(path.mirrorRootIds.back());
977 if (clonedRootSnapshot) {
978 const Rect rect =
979 displayInfo.transform.transform(Rect{clonedRootSnapshot->transformedBounds});
980 snapshot.inputInfo.touchableRegion = snapshot.inputInfo.touchableRegion.intersect(rect);
981 }
982 }
983}
984
985std::vector<std::unique_ptr<LayerSnapshot>>& LayerSnapshotBuilder::getSnapshots() {
986 return mSnapshots;
987}
988
Vishnu Naircfb2d252023-01-19 04:44:02 +0000989void LayerSnapshotBuilder::forEachVisibleSnapshot(const ConstVisitor& visitor) const {
990 for (int i = 0; i < mNumInterestingSnapshots; i++) {
991 LayerSnapshot& snapshot = *mSnapshots[(size_t)i];
992 if (!snapshot.isVisible) continue;
993 visitor(snapshot);
994 }
995}
996
997void LayerSnapshotBuilder::forEachVisibleSnapshot(const Visitor& visitor) {
998 for (int i = 0; i < mNumInterestingSnapshots; i++) {
999 std::unique_ptr<LayerSnapshot>& snapshot = mSnapshots.at((size_t)i);
1000 if (!snapshot->isVisible) continue;
1001 visitor(snapshot);
1002 }
1003}
1004
1005void LayerSnapshotBuilder::forEachInputSnapshot(const ConstVisitor& visitor) const {
1006 for (int i = mNumInterestingSnapshots - 1; i >= 0; i--) {
1007 LayerSnapshot& snapshot = *mSnapshots[(size_t)i];
1008 if (!snapshot.hasInputInfo()) continue;
1009 visitor(snapshot);
1010 }
1011}
1012
Vishnu Nair8fc721b2022-12-22 20:06:32 +00001013} // namespace android::surfaceflinger::frontend