summaryrefslogtreecommitdiff
path: root/services/surfaceflinger/FrontEnd/LayerSnapshotBuilder.cpp
blob: e3526d9de0d6649713c4841fd9476fe9dfa1bc5c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
/*
 * Copyright 2022 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// #define LOG_NDEBUG 0
#define ATRACE_TAG ATRACE_TAG_GRAPHICS
#include "FrontEnd/LayerSnapshot.h"
#include "ui/Transform.h"
#undef LOG_TAG
#define LOG_TAG "SurfaceFlinger"

#include <numeric>
#include <optional>

#include <common/FlagManager.h>
#include <common/trace.h>
#include <ftl/small_map.h>
#include <math/vec2.h>
#include <ui/DisplayMap.h>
#include <ui/FloatRect.h>

#include "DisplayHardware/HWC2.h"
#include "DisplayHardware/Hal.h"
#include "Layer.h" // eFrameRateSelectionPriority constants
#include "LayerLog.h"
#include "LayerSnapshotBuilder.h"
#include "TimeStats/TimeStats.h"
#include "Tracing/TransactionTracing.h"

namespace android::surfaceflinger::frontend {

using namespace ftl::flag_operators;

namespace {

FloatRect getMaxDisplayBounds(const DisplayInfos& displays) {
    const ui::Size maxSize = [&displays] {
        if (displays.empty()) return ui::Size{5000, 5000};

        return std::accumulate(displays.begin(), displays.end(), ui::kEmptySize,
                               [](ui::Size size, const auto& pair) -> ui::Size {
                                   const auto& display = pair.second;
                                   return {std::max(size.getWidth(), display.info.logicalWidth),
                                           std::max(size.getHeight(), display.info.logicalHeight)};
                               });
    }();

    // Ignore display bounds for now since they will be computed later. Use a large Rect bound
    // to ensure it's bigger than an actual display will be.
    const float xMax = static_cast<float>(maxSize.getWidth()) * 10.f;
    const float yMax = static_cast<float>(maxSize.getHeight()) * 10.f;

    return {-xMax, -yMax, xMax, yMax};
}

// Applies the given transform to the region, while protecting against overflows caused by any
// offsets. If applying the offset in the transform to any of the Rects in the region would result
// in an overflow, they are not added to the output Region.
Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
                                      const std::string& debugWindowName) {
    // Round the translation using the same rounding strategy used by ui::Transform.
    const auto tx = static_cast<int32_t>(t.tx() + 0.5);
    const auto ty = static_cast<int32_t>(t.ty() + 0.5);

    ui::Transform transformWithoutOffset = t;
    transformWithoutOffset.set(0.f, 0.f);

    const Region transformed = transformWithoutOffset.transform(r);

    // Apply the translation to each of the Rects in the region while discarding any that overflow.
    Region ret;
    for (const auto& rect : transformed) {
        Rect newRect;
        if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
            __builtin_add_overflow(rect.top, ty, &newRect.top) ||
            __builtin_add_overflow(rect.right, tx, &newRect.right) ||
            __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
            ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
                  debugWindowName.c_str());
            continue;
        }
        ret.orSelf(newRect);
    }
    return ret;
}

/*
 * We don't want to send the layer's transform to input, but rather the
 * parent's transform. This is because Layer's transform is
 * information about how the buffer is placed on screen. The parent's
 * transform makes more sense to send since it's information about how the
 * layer is placed on screen. This transform is used by input to determine
 * how to go from screen space back to window space.
 */
ui::Transform getInputTransform(const LayerSnapshot& snapshot) {
    if (!snapshot.hasBufferOrSidebandStream()) {
        return snapshot.geomLayerTransform;
    }
    return snapshot.parentTransform;
}

/**
 * Returns the bounds used to fill the input frame and the touchable region.
 *
 * Similar to getInputTransform, we need to update the bounds to include the transform.
 * This is because bounds don't include the buffer transform, where the input assumes
 * that's already included.
 */
std::pair<FloatRect, bool> getInputBounds(const LayerSnapshot& snapshot, bool fillParentBounds) {
    FloatRect inputBounds = snapshot.croppedBufferSize;
    if (snapshot.hasBufferOrSidebandStream() && snapshot.croppedBufferSize.isValid() &&
        snapshot.localTransform.getType() != ui::Transform::IDENTITY) {
        inputBounds = snapshot.localTransform.transform(inputBounds);
    }

    bool inputBoundsValid = snapshot.croppedBufferSize.isValid();
    if (!inputBoundsValid) {
        /**
         * Input bounds are based on the layer crop or buffer size. But if we are using
         * the layer bounds as the input bounds (replaceTouchableRegionWithCrop flag) then
         * we can use the parent bounds as the input bounds if the layer does not have buffer
         * or a crop. We want to unify this logic but because of compat reasons we cannot always
         * use the parent bounds. A layer without a buffer can get input. So when a window is
         * initially added, its touchable region can fill its parent layer bounds and that can
         * have negative consequences.
         */
        inputBounds = fillParentBounds ? snapshot.geomLayerBounds : FloatRect{};
    }

    // Clamp surface inset to the input bounds.
    const float inset = static_cast<float>(snapshot.inputInfo.surfaceInset);
    const float xSurfaceInset = std::clamp(inset, 0.f, inputBounds.getWidth() / 2.f);
    const float ySurfaceInset = std::clamp(inset, 0.f, inputBounds.getHeight() / 2.f);

    // Apply the insets to the input bounds.
    inputBounds.left += xSurfaceInset;
    inputBounds.top += ySurfaceInset;
    inputBounds.right -= xSurfaceInset;
    inputBounds.bottom -= ySurfaceInset;
    return {inputBounds, inputBoundsValid};
}

Rect getInputBoundsInDisplaySpace(const LayerSnapshot& snapshot, const FloatRect& insetBounds,
                                  const ui::Transform& screenToDisplay) {
    // InputDispatcher works in the display device's coordinate space. Here, we calculate the
    // frame and transform used for the layer, which determines the bounds and the coordinate space
    // within which the layer will receive input.

    // Coordinate space definitions:
    //   - display: The display device's coordinate space. Correlates to pixels on the display.
    //   - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
    //   - layer: The coordinate space of this layer.
    //   - input: The coordinate space in which this layer will receive input events. This could be
    //            different than layer space if a surfaceInset is used, which changes the origin
    //            of the input space.

    // Crop the input bounds to ensure it is within the parent's bounds.
    const FloatRect croppedInsetBoundsInLayer = snapshot.geomLayerBounds.intersect(insetBounds);

    const ui::Transform layerToScreen = getInputTransform(snapshot);
    const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;

    return Rect{layerToDisplay.transform(croppedInsetBoundsInLayer)};
}

void fillInputFrameInfo(gui::WindowInfo& info, const ui::Transform& screenToDisplay,
                        const LayerSnapshot& snapshot) {
    auto [inputBounds, inputBoundsValid] = getInputBounds(snapshot, /*fillParentBounds=*/false);
    if (!inputBoundsValid) {
        info.touchableRegion.clear();
    }

    info.frame = getInputBoundsInDisplaySpace(snapshot, inputBounds, screenToDisplay);

    ui::Transform inputToLayer;
    inputToLayer.set(inputBounds.left, inputBounds.top);
    const ui::Transform layerToScreen = getInputTransform(snapshot);
    const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer;

    // InputDispatcher expects a display-to-input transform.
    info.transform = inputToDisplay.inverse();

    // The touchable region is specified in the input coordinate space. Change it to display space.
    info.touchableRegion =
            transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, snapshot.name);
}

void handleDropInputMode(LayerSnapshot& snapshot, const LayerSnapshot& parentSnapshot) {
    if (snapshot.inputInfo.inputConfig.test(gui::WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
        return;
    }

    // Check if we need to drop input unconditionally
    const gui::DropInputMode dropInputMode = snapshot.dropInputMode;
    if (dropInputMode == gui::DropInputMode::ALL) {
        snapshot.inputInfo.inputConfig |= gui::WindowInfo::InputConfig::DROP_INPUT;
        ALOGV("Dropping input for %s as requested by policy.", snapshot.name.c_str());
        return;
    }

    // Check if we need to check if the window is obscured by parent
    if (dropInputMode != gui::DropInputMode::OBSCURED) {
        return;
    }

    // Check if the parent has set an alpha on the layer
    if (parentSnapshot.color.a != 1.0_hf) {
        snapshot.inputInfo.inputConfig |= gui::WindowInfo::InputConfig::DROP_INPUT;
        ALOGV("Dropping input for %s as requested by policy because alpha=%f",
              snapshot.name.c_str(), static_cast<float>(parentSnapshot.color.a));
    }

    // Check if the parent has cropped the buffer
    FloatRect bufferSize = snapshot.croppedBufferSize;
    if (!bufferSize.isValid()) {
        snapshot.inputInfo.inputConfig |= gui::WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
        return;
    }

    // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
    // To check if the layer has been cropped, we take the buffer bounds, apply the local
    // layer crop and apply the same set of transforms to move to screenspace. If the bounds
    // match then the layer has not been cropped by its parents.
    Rect bufferInScreenSpace(snapshot.geomLayerTransform.transform(bufferSize));
    bool croppedByParent = bufferInScreenSpace != Rect{snapshot.transformedBounds};

    if (croppedByParent) {
        snapshot.inputInfo.inputConfig |= gui::WindowInfo::InputConfig::DROP_INPUT;
        ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
              snapshot.name.c_str());
    } else {
        // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
        // input if the window is obscured. This check should be done in surfaceflinger but the
        // logic currently resides in inputflinger. So pass the if_obscured check to input to only
        // drop input events if the window is obscured.
        snapshot.inputInfo.inputConfig |= gui::WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
    }
}

auto getBlendMode(const LayerSnapshot& snapshot, const RequestedLayerState& requested) {
    auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
    if (snapshot.alpha != 1.0f || !snapshot.isContentOpaque()) {
        blendMode = requested.premultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
                                                 : Hwc2::IComposerClient::BlendMode::COVERAGE;
    }
    return blendMode;
}

void updateVisibility(LayerSnapshot& snapshot, bool visible) {
    if (snapshot.isVisible != visible) {
        snapshot.changes |= RequestedLayerState::Changes::Visibility;
    }
    snapshot.isVisible = visible;

    // TODO(b/238781169) we are ignoring this compat for now, since we will have
    // to remove any optimization based on visibility.

    // For compatibility reasons we let layers which can receive input
    // receive input before they have actually submitted a buffer. Because
    // of this we use canReceiveInput instead of isVisible to check the
    // policy-visibility, ignoring the buffer state. However for layers with
    // hasInputInfo()==false we can use the real visibility state.
    // We are just using these layers for occlusion detection in
    // InputDispatcher, and obviously if they aren't visible they can't occlude
    // anything.
    const bool visibleForInput =
            snapshot.hasInputInfo() ? snapshot.canReceiveInput() : snapshot.isVisible;
    snapshot.inputInfo.setInputConfig(gui::WindowInfo::InputConfig::NOT_VISIBLE, !visibleForInput);

    LLOGV(snapshot.sequence, "updating visibility %s %s", visible ? "true" : "false",
          snapshot.getDebugString().c_str());
}

void updateMetadata(LayerSnapshot& snapshot, const RequestedLayerState& requested,
                    const LayerSnapshotBuilder::Args& args) {
    snapshot.metadata.clear();
    for (const auto& [key, mandatory] : args.supportedLayerGenericMetadata) {
        auto compatIter = args.genericLayerMetadataKeyMap.find(key);
        if (compatIter == std::end(args.genericLayerMetadataKeyMap)) {
            continue;
        }
        const uint32_t id = compatIter->second;
        auto it = requested.metadata.mMap.find(id);
        if (it == std::end(requested.metadata.mMap)) {
            continue;
        }

        snapshot.metadata.emplace(key,
                                  compositionengine::GenericLayerMetadataEntry{mandatory,
                                                                               it->second});
    }
}

void updateMetadataAndGameMode(LayerSnapshot& snapshot, const RequestedLayerState& requested,
                               const LayerSnapshotBuilder::Args& args,
                               const LayerSnapshot& parentSnapshot) {
    snapshot.gameMode = requested.metadata.has(gui::METADATA_GAME_MODE) ? requested.gameMode
                                                                        : parentSnapshot.gameMode;
    updateMetadata(snapshot, requested, args);
    if (args.includeMetadata) {
        snapshot.layerMetadata = parentSnapshot.layerMetadata;
        snapshot.layerMetadata.merge(requested.metadata);
    }
}

void clearChanges(LayerSnapshot& snapshot) {
    snapshot.changes.clear();
    snapshot.clientChanges = 0;
    snapshot.contentDirty = snapshot.autoRefresh;
    snapshot.hasReadyFrame = snapshot.autoRefresh;
    snapshot.sidebandStreamHasFrame = false;
    snapshot.surfaceDamage.clear();
}

// TODO (b/259407931): Remove.
uint32_t getPrimaryDisplayRotationFlags(
        const ui::DisplayMap<ui::LayerStack, frontend::DisplayInfo>& displays) {
    for (auto& [_, display] : displays) {
        if (display.isPrimary) {
            return display.rotationFlags;
        }
    }
    return 0;
}

} // namespace

LayerSnapshot LayerSnapshotBuilder::getRootSnapshot() {
    LayerSnapshot snapshot;
    snapshot.path = LayerHierarchy::TraversalPath::ROOT;
    snapshot.changes = ftl::Flags<RequestedLayerState::Changes>();
    snapshot.clientChanges = 0;
    snapshot.isHiddenByPolicyFromParent = false;
    snapshot.isHiddenByPolicyFromRelativeParent = false;
    snapshot.parentTransform.reset();
    snapshot.geomLayerTransform.reset();
    snapshot.geomInverseLayerTransform.reset();
    snapshot.geomLayerBounds = getMaxDisplayBounds({});
    snapshot.roundedCorner = RoundedCornerState();
    snapshot.stretchEffect = {};
    snapshot.edgeExtensionEffect = {};
    snapshot.outputFilter.layerStack = ui::DEFAULT_LAYER_STACK;
    snapshot.outputFilter.toInternalDisplay = false;
    snapshot.isSecure = false;
    snapshot.color.a = 1.0_hf;
    snapshot.colorTransformIsIdentity = true;
    snapshot.shadowSettings.length = 0.f;
    snapshot.layerMetadata.mMap.clear();
    snapshot.relativeLayerMetadata.mMap.clear();
    snapshot.inputInfo.touchOcclusionMode = gui::TouchOcclusionMode::BLOCK_UNTRUSTED;
    snapshot.dropInputMode = gui::DropInputMode::NONE;
    snapshot.trustedOverlay = gui::TrustedOverlay::UNSET;
    snapshot.gameMode = gui::GameMode::Unsupported;
    snapshot.frameRate = {};
    snapshot.fixedTransformHint = ui::Transform::ROT_INVALID;
    snapshot.ignoreLocalTransform = false;
    return snapshot;
}

LayerSnapshotBuilder::LayerSnapshotBuilder() {}

LayerSnapshotBuilder::LayerSnapshotBuilder(Args args) : LayerSnapshotBuilder() {
    args.forceUpdate = ForceUpdateFlags::ALL;
    updateSnapshots(args);
}

bool LayerSnapshotBuilder::tryFastUpdate(const Args& args) {
    const bool forceUpdate = args.forceUpdate != ForceUpdateFlags::NONE;

    if (args.layerLifecycleManager.getGlobalChanges().get() == 0 && !forceUpdate &&
        !args.displayChanges) {
        return true;
    }

    // There are only content changes which do not require any child layer snapshots to be updated.
    ALOGV("%s", __func__);
    SFTRACE_NAME("FastPath");

    uint32_t primaryDisplayRotationFlags = getPrimaryDisplayRotationFlags(args.displays);
    if (forceUpdate || args.displayChanges) {
        for (auto& snapshot : mSnapshots) {
            const RequestedLayerState* requested =
                    args.layerLifecycleManager.getLayerFromId(snapshot->path.id);
            if (!requested) continue;
            snapshot->merge(*requested, forceUpdate, args.displayChanges, args.forceFullDamage,
                            primaryDisplayRotationFlags);
        }
        return false;
    }

    // Walk through all the updated requested layer states and update the corresponding snapshots.
    for (const RequestedLayerState* requested : args.layerLifecycleManager.getChangedLayers()) {
        auto range = mIdToSnapshots.equal_range(requested->id);
        for (auto it = range.first; it != range.second; it++) {
            it->second->merge(*requested, forceUpdate, args.displayChanges, args.forceFullDamage,
                              primaryDisplayRotationFlags);
        }
    }

    if ((args.layerLifecycleManager.getGlobalChanges().get() &
         ~(RequestedLayerState::Changes::Content | RequestedLayerState::Changes::Buffer).get()) !=
        0) {
        // We have changes that require us to walk the hierarchy and update child layers.
        // No fast path for you.
        return false;
    }
    return true;
}

void LayerSnapshotBuilder::updateSnapshots(const Args& args) {
    SFTRACE_NAME("UpdateSnapshots");
    LayerSnapshot rootSnapshot = args.rootSnapshot;
    if (args.parentCrop) {
        rootSnapshot.geomLayerBounds = *args.parentCrop;
    } else if (args.forceUpdate == ForceUpdateFlags::ALL || args.displayChanges) {
        rootSnapshot.geomLayerBounds = getMaxDisplayBounds(args.displays);
    }
    if (args.displayChanges) {
        rootSnapshot.changes = RequestedLayerState::Changes::AffectsChildren |
                RequestedLayerState::Changes::Geometry;
    }
    if (args.forceUpdate == ForceUpdateFlags::HIERARCHY) {
        rootSnapshot.changes |=
                RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Visibility;
        rootSnapshot.clientChanges |= layer_state_t::eReparent;
    }

    for (auto& snapshot : mSnapshots) {
        if (snapshot->reachablilty == LayerSnapshot::Reachablilty::Reachable) {
            snapshot->reachablilty = LayerSnapshot::Reachablilty::Unreachable;
        }
    }

    LayerHierarchy::TraversalPath root = LayerHierarchy::TraversalPath::ROOT;
    if (args.root.getLayer()) {
        // The hierarchy can have a root layer when used for screenshots otherwise, it will have
        // multiple children.
        LayerHierarchy::TraversalPath childPath =
                root.makeChild(args.root.getLayer()->id, LayerHierarchy::Variant::Attached);
        updateSnapshotsInHierarchy(args, args.root, childPath, rootSnapshot, /*depth=*/0);
    } else {
        for (auto& [childHierarchy, variant] : args.root.mChildren) {
            LayerHierarchy::TraversalPath childPath =
                    root.makeChild(childHierarchy->getLayer()->id, variant);
            updateSnapshotsInHierarchy(args, *childHierarchy, childPath, rootSnapshot, /*depth=*/0);
        }
    }

    // Update touchable region crops outside the main update pass. This is because a layer could be
    // cropped by any other layer and it requires both snapshots to be updated.
    updateTouchableRegionCrop(args);

    const bool hasUnreachableSnapshots = sortSnapshotsByZ(args);

    // Destroy unreachable snapshots for clone layers. And destroy snapshots for non-clone
    // layers if the layer have been destroyed.
    // TODO(b/238781169) consider making clone layer ids stable as well
    if (!hasUnreachableSnapshots && args.layerLifecycleManager.getDestroyedLayers().empty()) {
        return;
    }

    std::unordered_set<uint32_t> destroyedLayerIds;
    for (auto& destroyedLayer : args.layerLifecycleManager.getDestroyedLayers()) {
        destroyedLayerIds.insert(destroyedLayer->id);
    }

    auto it = mSnapshots.begin();
    while (it < mSnapshots.end()) {
        auto& traversalPath = it->get()->path;
        const bool unreachable =
                it->get()->reachablilty == LayerSnapshot::Reachablilty::Unreachable;
        const bool isClone = traversalPath.isClone();
        const bool layerIsDestroyed =
                destroyedLayerIds.find(traversalPath.id) != destroyedLayerIds.end();
        const bool destroySnapshot = (unreachable && isClone) || layerIsDestroyed;

        if (!destroySnapshot) {
            it++;
            continue;
        }

        mPathToSnapshot.erase(traversalPath);

        auto range = mIdToSnapshots.equal_range(traversalPath.id);
        auto matchingSnapshot =
                std::find_if(range.first, range.second, [&traversalPath](auto& snapshotWithId) {
                    return snapshotWithId.second->path == traversalPath;
                });
        mIdToSnapshots.erase(matchingSnapshot);
        mNeedsTouchableRegionCrop.erase(traversalPath);
        mSnapshots.back()->globalZ = it->get()->globalZ;
        std::iter_swap(it, mSnapshots.end() - 1);
        mSnapshots.erase(mSnapshots.end() - 1);
    }
}

void LayerSnapshotBuilder::update(const Args& args) {
    for (auto& snapshot : mSnapshots) {
        clearChanges(*snapshot);
    }

    if (tryFastUpdate(args)) {
        return;
    }
    updateSnapshots(args);
}

const LayerSnapshot& LayerSnapshotBuilder::updateSnapshotsInHierarchy(
        const Args& args, const LayerHierarchy& hierarchy,
        const LayerHierarchy::TraversalPath& traversalPath, const LayerSnapshot& parentSnapshot,
        int depth) {
    LLOG_ALWAYS_FATAL_WITH_TRACE_IF(depth > 50,
                                    "Cycle detected in LayerSnapshotBuilder. See "
                                    "builder_stack_overflow_transactions.winscope");

    const RequestedLayerState* layer = hierarchy.getLayer();
    LayerSnapshot* snapshot = getSnapshot(traversalPath);
    const bool newSnapshot = snapshot == nullptr;
    uint32_t primaryDisplayRotationFlags = getPrimaryDisplayRotationFlags(args.displays);
    if (newSnapshot) {
        snapshot = createSnapshot(traversalPath, *layer, parentSnapshot);
        snapshot->merge(*layer, /*forceUpdate=*/true, /*displayChanges=*/true, args.forceFullDamage,
                        primaryDisplayRotationFlags);
        snapshot->changes |= RequestedLayerState::Changes::Created;
    }

    if (traversalPath.isRelative()) {
        bool parentIsRelative = traversalPath.variant == LayerHierarchy::Variant::Relative;
        updateRelativeState(*snapshot, parentSnapshot, parentIsRelative, args);
    } else {
        if (traversalPath.isAttached()) {
            resetRelativeState(*snapshot);
        }
        updateSnapshot(*snapshot, args, *layer, parentSnapshot, traversalPath);
    }

    bool childHasValidFrameRate = false;
    for (auto& [childHierarchy, variant] : hierarchy.mChildren) {
        LayerHierarchy::TraversalPath childPath =
                traversalPath.makeChild(childHierarchy->getLayer()->id, variant);
        const LayerSnapshot& childSnapshot =
                updateSnapshotsInHierarchy(args, *childHierarchy, childPath, *snapshot, depth + 1);
        updateFrameRateFromChildSnapshot(*snapshot, childSnapshot, *childHierarchy->getLayer(),
                                         args, &childHasValidFrameRate);
    }

    return *snapshot;
}

LayerSnapshot* LayerSnapshotBuilder::getSnapshot(uint32_t layerId) const {
    if (layerId == UNASSIGNED_LAYER_ID) {
        return nullptr;
    }
    LayerHierarchy::TraversalPath path{.id = layerId};
    return getSnapshot(path);
}

LayerSnapshot* LayerSnapshotBuilder::getSnapshot(const LayerHierarchy::TraversalPath& id) const {
    auto it = mPathToSnapshot.find(id);
    return it == mPathToSnapshot.end() ? nullptr : it->second;
}

LayerSnapshot* LayerSnapshotBuilder::createSnapshot(const LayerHierarchy::TraversalPath& path,
                                                    const RequestedLayerState& layer,
                                                    const LayerSnapshot& parentSnapshot) {
    mSnapshots.emplace_back(std::make_unique<LayerSnapshot>(layer, path));
    LayerSnapshot* snapshot = mSnapshots.back().get();
    snapshot->globalZ = static_cast<size_t>(mSnapshots.size()) - 1;
    if (path.isClone() && !LayerHierarchy::isMirror(path.variant)) {
        snapshot->mirrorRootPath = parentSnapshot.mirrorRootPath;
    }
    snapshot->ignoreLocalTransform =
            path.isClone() && path.variant == LayerHierarchy::Variant::Detached_Mirror;
    mPathToSnapshot[path] = snapshot;

    mIdToSnapshots.emplace(path.id, snapshot);
    return snapshot;
}

bool LayerSnapshotBuilder::sortSnapshotsByZ(const Args& args) {
    if (!mResortSnapshots && args.forceUpdate == ForceUpdateFlags::NONE &&
        !args.layerLifecycleManager.getGlobalChanges().any(
                RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Visibility |
                RequestedLayerState::Changes::Input)) {
        // We are not force updating and there are no hierarchy or visibility changes. Avoid sorting
        // the snapshots.
        return false;
    }
    mResortSnapshots = false;

    size_t globalZ = 0;
    args.root.traverseInZOrder(
            [this, &globalZ](const LayerHierarchy&,
                             const LayerHierarchy::TraversalPath& traversalPath) -> bool {
                LayerSnapshot* snapshot = getSnapshot(traversalPath);
                if (!snapshot) {
                    return true;
                }

                if (snapshot->getIsVisible() || snapshot->hasInputInfo()) {
                    updateVisibility(*snapshot, snapshot->getIsVisible());
                    size_t oldZ = snapshot->globalZ;
                    size_t newZ = globalZ++;
                    snapshot->globalZ = newZ;
                    if (oldZ == newZ) {
                        return true;
                    }
                    mSnapshots[newZ]->globalZ = oldZ;
                    LLOGV(snapshot->sequence, "Made visible z=%zu -> %zu %s", oldZ, newZ,
                          snapshot->getDebugString().c_str());
                    std::iter_swap(mSnapshots.begin() + static_cast<ssize_t>(oldZ),
                                   mSnapshots.begin() + static_cast<ssize_t>(newZ));
                }
                return true;
            });
    mNumInterestingSnapshots = (int)globalZ;
    bool hasUnreachableSnapshots = false;
    while (globalZ < mSnapshots.size()) {
        mSnapshots[globalZ]->globalZ = globalZ;
        /* mark unreachable snapshots as explicitly invisible */
        updateVisibility(*mSnapshots[globalZ], false);
        if (mSnapshots[globalZ]->reachablilty == LayerSnapshot::Reachablilty::Unreachable) {
            hasUnreachableSnapshots = true;
        }
        globalZ++;
    }
    return hasUnreachableSnapshots;
}

void LayerSnapshotBuilder::updateRelativeState(LayerSnapshot& snapshot,
                                               const LayerSnapshot& parentSnapshot,
                                               bool parentIsRelative, const Args& args) {
    if (parentIsRelative) {
        snapshot.isHiddenByPolicyFromRelativeParent =
                parentSnapshot.isHiddenByPolicyFromParent || parentSnapshot.invalidTransform;
        if (args.includeMetadata) {
            snapshot.relativeLayerMetadata = parentSnapshot.layerMetadata;
        }
    } else {
        snapshot.isHiddenByPolicyFromRelativeParent =
                parentSnapshot.isHiddenByPolicyFromRelativeParent;
        if (args.includeMetadata) {
            snapshot.relativeLayerMetadata = parentSnapshot.relativeLayerMetadata;
        }
    }
    if (snapshot.reachablilty == LayerSnapshot::Reachablilty::Unreachable) {
        snapshot.reachablilty = LayerSnapshot::Reachablilty::ReachableByRelativeParent;
    }
}

void LayerSnapshotBuilder::updateFrameRateFromChildSnapshot(
        LayerSnapshot& snapshot, const LayerSnapshot& childSnapshot,
        const RequestedLayerState& /* requestedChildState */, const Args& args,
        bool* outChildHasValidFrameRate) {
    if (args.forceUpdate == ForceUpdateFlags::NONE &&
        !args.layerLifecycleManager.getGlobalChanges().any(
                RequestedLayerState::Changes::Hierarchy) &&
        !childSnapshot.changes.any(RequestedLayerState::Changes::FrameRate) &&
        !snapshot.changes.any(RequestedLayerState::Changes::FrameRate)) {
        return;
    }

    using FrameRateCompatibility = scheduler::FrameRateCompatibility;
    if (snapshot.inheritedFrameRate.isValid() || *outChildHasValidFrameRate) {
        // we already have a valid framerate.
        return;
    }

    // We return whether this layer or its children has a vote. We ignore ExactOrMultiple votes
    // for the same reason we are allowing touch boost for those layers. See
    // RefreshRateSelector::rankFrameRates for details.
    const auto layerVotedWithDefaultCompatibility = childSnapshot.frameRate.vote.rate.isValid() &&
            childSnapshot.frameRate.vote.type == FrameRateCompatibility::Default;
    const auto layerVotedWithNoVote =
            childSnapshot.frameRate.vote.type == FrameRateCompatibility::NoVote;
    const auto layerVotedWithCategory =
            childSnapshot.frameRate.category != FrameRateCategory::Default;
    const auto layerVotedWithExactCompatibility = childSnapshot.frameRate.vote.rate.isValid() &&
            childSnapshot.frameRate.vote.type == FrameRateCompatibility::Exact;

    *outChildHasValidFrameRate |= layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
            layerVotedWithCategory || layerVotedWithExactCompatibility;

    // If we don't have a valid frame rate, but the children do, we set this
    // layer as NoVote to allow the children to control the refresh rate
    static const auto noVote =
            scheduler::LayerInfo::FrameRate(Fps(), FrameRateCompatibility::NoVote);
    if (*outChildHasValidFrameRate) {
        snapshot.frameRate = noVote;
        snapshot.changes |= RequestedLayerState::Changes::FrameRate;
    } else if (snapshot.frameRate != snapshot.inheritedFrameRate) {
        snapshot.frameRate = snapshot.inheritedFrameRate;
        snapshot.changes |= RequestedLayerState::Changes::FrameRate;
    }
}

void LayerSnapshotBuilder::resetRelativeState(LayerSnapshot& snapshot) {
    snapshot.isHiddenByPolicyFromRelativeParent = false;
    snapshot.relativeLayerMetadata.mMap.clear();
}

void LayerSnapshotBuilder::updateSnapshot(LayerSnapshot& snapshot, const Args& args,
                                          const RequestedLayerState& requested,
                                          const LayerSnapshot& parentSnapshot,
                                          const LayerHierarchy::TraversalPath& path) {
    // Always update flags and visibility
    ftl::Flags<RequestedLayerState::Changes> parentChanges = parentSnapshot.changes &
            (RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Geometry |
             RequestedLayerState::Changes::Visibility | RequestedLayerState::Changes::Metadata |
             RequestedLayerState::Changes::AffectsChildren | RequestedLayerState::Changes::Input |
             RequestedLayerState::Changes::FrameRate | RequestedLayerState::Changes::GameMode);
    snapshot.changes |= parentChanges;
    if (args.displayChanges) snapshot.changes |= RequestedLayerState::Changes::Geometry;
    snapshot.reachablilty = LayerSnapshot::Reachablilty::Reachable;
    snapshot.clientChanges |= (parentSnapshot.clientChanges & layer_state_t::AFFECTS_CHILDREN);
    // mark the content as dirty if the parent state changes can dirty the child's content (for
    // example alpha)
    snapshot.contentDirty |= (snapshot.clientChanges & layer_state_t::CONTENT_DIRTY) != 0;
    snapshot.isHiddenByPolicyFromParent = parentSnapshot.isHiddenByPolicyFromParent ||
            parentSnapshot.invalidTransform || requested.isHiddenByPolicy() ||
            (args.excludeLayerIds.find(path.id) != args.excludeLayerIds.end());
    const bool forceUpdate = args.forceUpdate == ForceUpdateFlags::ALL ||
            snapshot.clientChanges & layer_state_t::eReparent ||
            snapshot.changes.any(RequestedLayerState::Changes::Visibility |
                                 RequestedLayerState::Changes::Created);

    if (forceUpdate || snapshot.clientChanges & layer_state_t::eLayerStackChanged) {
        // If root layer, use the layer stack otherwise get the parent's layer stack.
        snapshot.outputFilter.layerStack =
                parentSnapshot.path == LayerHierarchy::TraversalPath::ROOT
                ? requested.layerStack
                : parentSnapshot.outputFilter.layerStack;
    }

    if (forceUpdate || snapshot.clientChanges & layer_state_t::eTrustedOverlayChanged) {
        switch (requested.trustedOverlay) {
            case gui::TrustedOverlay::UNSET:
                snapshot.trustedOverlay = parentSnapshot.trustedOverlay;
                break;
            case gui::TrustedOverlay::DISABLED:
                snapshot.trustedOverlay = FlagManager::getInstance().override_trusted_overlay()
                        ? requested.trustedOverlay
                        : parentSnapshot.trustedOverlay;
                break;
            case gui::TrustedOverlay::ENABLED:
                snapshot.trustedOverlay = requested.trustedOverlay;
                break;
        }
    }

    if (snapshot.isHiddenByPolicyFromParent &&
        !snapshot.changes.test(RequestedLayerState::Changes::Created)) {
        if (forceUpdate ||
            snapshot.changes.any(RequestedLayerState::Changes::Geometry |
                                 RequestedLayerState::Changes::BufferSize |
                                 RequestedLayerState::Changes::Input)) {
            updateInput(snapshot, requested, parentSnapshot, path, args);
        }
        if (forceUpdate ||
            (args.includeMetadata &&
             snapshot.changes.any(RequestedLayerState::Changes::Metadata |
                                  RequestedLayerState::Changes::Geometry))) {
            updateMetadataAndGameMode(snapshot, requested, args, parentSnapshot);
        }
        return;
    }

    if (forceUpdate || snapshot.changes.any(RequestedLayerState::Changes::Mirror)) {
        // Display mirrors are always placed in a VirtualDisplay so we never want to capture layers
        // marked as skip capture
        snapshot.handleSkipScreenshotFlag = parentSnapshot.handleSkipScreenshotFlag ||
                (requested.layerStackToMirror != ui::INVALID_LAYER_STACK);
    }

    if (forceUpdate || snapshot.clientChanges & layer_state_t::eAlphaChanged) {
        snapshot.color.a = parentSnapshot.color.a * requested.color.a;
        snapshot.alpha = snapshot.color.a;
        snapshot.inputInfo.alpha = snapshot.color.a;
    }

    if (forceUpdate || snapshot.clientChanges & layer_state_t::eFlagsChanged) {
        snapshot.isSecure =
                parentSnapshot.isSecure || (requested.flags & layer_state_t::eLayerSecure);
        snapshot.outputFilter.toInternalDisplay = parentSnapshot.outputFilter.toInternalDisplay ||
                (requested.flags & layer_state_t::eLayerSkipScreenshot);
    }

    if (forceUpdate || snapshot.clientChanges & layer_state_t::eStretchChanged) {
        snapshot.stretchEffect = (requested.stretchEffect.hasEffect())
                ? requested.stretchEffect
                : parentSnapshot.stretchEffect;
    }

    if (forceUpdate ||
        (snapshot.clientChanges | parentSnapshot.clientChanges) &
                layer_state_t::eEdgeExtensionChanged) {
        if (requested.edgeExtensionParameters.extendLeft ||
            requested.edgeExtensionParameters.extendRight ||
            requested.edgeExtensionParameters.extendTop ||
            requested.edgeExtensionParameters.extendBottom) {
            // This is the root layer to which the extension is applied
            snapshot.edgeExtensionEffect =
                    EdgeExtensionEffect(requested.edgeExtensionParameters.extendLeft,
                                        requested.edgeExtensionParameters.extendRight,
                                        requested.edgeExtensionParameters.extendTop,
                                        requested.edgeExtensionParameters.extendBottom);
        } else if (parentSnapshot.clientChanges & layer_state_t::eEdgeExtensionChanged) {
            // Extension is inherited
            snapshot.edgeExtensionEffect = parentSnapshot.edgeExtensionEffect;
        } else {
            // There is no edge extension
            snapshot.edgeExtensionEffect.reset();
        }
        if (snapshot.edgeExtensionEffect.hasEffect()) {
            snapshot.clientChanges |= layer_state_t::eEdgeExtensionChanged;
            snapshot.changes |= RequestedLayerState::Changes::Geometry;
        }
    }

    if (forceUpdate || snapshot.clientChanges & layer_state_t::eColorTransformChanged) {
        if (!parentSnapshot.colorTransformIsIdentity) {
            snapshot.colorTransform = parentSnapshot.colorTransform * requested.colorTransform;
            snapshot.colorTransformIsIdentity = false;
        } else {
            snapshot.colorTransform = requested.colorTransform;
            snapshot.colorTransformIsIdentity = !requested.hasColorTransform;
        }
    }

    if (forceUpdate ||
        snapshot.changes.any(RequestedLayerState::Changes::Metadata |
                             RequestedLayerState::Changes::Hierarchy)) {
        updateMetadataAndGameMode(snapshot, requested, args, parentSnapshot);
    }

    if (forceUpdate || snapshot.clientChanges & layer_state_t::eFixedTransformHintChanged ||
        args.displayChanges) {
        snapshot.fixedTransformHint = requested.fixedTransformHint != ui::Transform::ROT_INVALID
                ? requested.fixedTransformHint
                : parentSnapshot.fixedTransformHint;

        if (snapshot.fixedTransformHint != ui::Transform::ROT_INVALID) {
            snapshot.transformHint = snapshot.fixedTransformHint;
        } else {
            const auto display = args.displays.get(snapshot.outputFilter.layerStack);
            snapshot.transformHint = display.has_value()
                    ? std::make_optional<>(display->get().transformHint)
                    : std::nullopt;
        }
    }

    if (forceUpdate ||
        args.layerLifecycleManager.getGlobalChanges().any(
                RequestedLayerState::Changes::Hierarchy) ||
        snapshot.changes.any(RequestedLayerState::Changes::FrameRate |
                             RequestedLayerState::Changes::Hierarchy)) {
        const bool shouldOverrideChildren = parentSnapshot.frameRateSelectionStrategy ==
                scheduler::LayerInfo::FrameRateSelectionStrategy::OverrideChildren;
        const bool propagationAllowed = parentSnapshot.frameRateSelectionStrategy !=
                scheduler::LayerInfo::FrameRateSelectionStrategy::Self;
        if ((!requested.requestedFrameRate.isValid() && propagationAllowed) ||
            shouldOverrideChildren) {
            snapshot.inheritedFrameRate = parentSnapshot.inheritedFrameRate;
        } else {
            snapshot.inheritedFrameRate = requested.requestedFrameRate;
        }
        // Set the framerate as the inherited frame rate and allow children to override it if
        // needed.
        snapshot.frameRate = snapshot.inheritedFrameRate;
        snapshot.changes |= RequestedLayerState::Changes::FrameRate;
    }

    if (forceUpdate || snapshot.clientChanges & layer_state_t::eFrameRateSelectionStrategyChanged) {
        if (parentSnapshot.frameRateSelectionStrategy ==
            scheduler::LayerInfo::FrameRateSelectionStrategy::OverrideChildren) {
            snapshot.frameRateSelectionStrategy =
                    scheduler::LayerInfo::FrameRateSelectionStrategy::OverrideChildren;
        } else {
            const auto strategy = scheduler::LayerInfo::convertFrameRateSelectionStrategy(
                    requested.frameRateSelectionStrategy);
            snapshot.frameRateSelectionStrategy = strategy;
        }
    }

    if (forceUpdate || snapshot.clientChanges & layer_state_t::eFrameRateSelectionPriority) {
        snapshot.frameRateSelectionPriority =
                (requested.frameRateSelectionPriority == Layer::PRIORITY_UNSET)
                ? parentSnapshot.frameRateSelectionPriority
                : requested.frameRateSelectionPriority;
    }

    if (forceUpdate ||
        snapshot.clientChanges &
                (layer_state_t::eBackgroundBlurRadiusChanged | layer_state_t::eBlurRegionsChanged |
                 layer_state_t::eAlphaChanged)) {
        snapshot.backgroundBlurRadius = args.supportsBlur
                ? static_cast<int>(parentSnapshot.color.a * (float)requested.backgroundBlurRadius)
                : 0;
        snapshot.blurRegions = requested.blurRegions;
        for (auto& region : snapshot.blurRegions) {
            region.alpha = region.alpha * snapshot.color.a;
        }
    }

    if (forceUpdate || snapshot.changes.any(RequestedLayerState::Changes::Geometry)) {
        uint32_t primaryDisplayRotationFlags = getPrimaryDisplayRotationFlags(args.displays);
        updateLayerBounds(snapshot, requested, parentSnapshot, primaryDisplayRotationFlags);
    }

    if (snapshot.edgeExtensionEffect.hasEffect()) {
        updateBoundsForEdgeExtension(snapshot);
    }

    if (forceUpdate || snapshot.clientChanges & layer_state_t::eCornerRadiusChanged ||
        snapshot.changes.any(RequestedLayerState::Changes::Geometry |
                             RequestedLayerState::Changes::BufferUsageFlags) ||
        snapshot.clientChanges & layer_state_t::eClientDrawnCornerRadiusChanged) {
        updateRoundedCorner(snapshot, requested, parentSnapshot, args);
    }

    if (forceUpdate || snapshot.clientChanges & layer_state_t::eShadowRadiusChanged ||
        snapshot.changes.any(RequestedLayerState::Changes::Geometry)) {
        updateShadows(snapshot, requested, args.globalShadowSettings);
    }

    if (forceUpdate ||
        snapshot.clientChanges &
                (layer_state_t::eBorderSettingsChanged | layer_state_t::eAlphaChanged)) {
        snapshot.borderSettings = requested.borderSettings;

        // Multiply outline alpha by snapshot alpha.
        uint32_t c = static_cast<uint32_t>(snapshot.borderSettings.color);
        float alpha = snapshot.alpha * (c >> 24) / 255.0f;
        uint32_t a = static_cast<uint32_t>(alpha * 255 + 0.5f);
        snapshot.borderSettings.color = static_cast<int32_t>((c & ~0xff000000) | (a << 24));
    }

    if (forceUpdate ||
        snapshot.changes.any(RequestedLayerState::Changes::Geometry |
                             RequestedLayerState::Changes::Input)) {
        updateInput(snapshot, requested, parentSnapshot, path, args);
    }

    // computed snapshot properties
    snapshot.forceClientComposition = snapshot.shadowSettings.length > 0 ||
            snapshot.stretchEffect.hasEffect() || snapshot.edgeExtensionEffect.hasEffect() ||
            snapshot.borderSettings.strokeWidth > 0;

    snapshot.contentOpaque = snapshot.isContentOpaque();
    snapshot.isOpaque = snapshot.contentOpaque && !snapshot.roundedCorner.hasRoundedCorners() &&
            snapshot.color.a == 1.f;
    snapshot.blendMode = getBlendMode(snapshot, requested);
    LLOGV(snapshot.sequence,
          "%supdated %s changes:%s parent:%s requested:%s requested:%s from parent %s",
          args.forceUpdate == ForceUpdateFlags::ALL ? "Force " : "",
          snapshot.getDebugString().c_str(), snapshot.changes.string().c_str(),
          parentSnapshot.changes.string().c_str(), requested.changes.string().c_str(),
          std::to_string(requested.what).c_str(), parentSnapshot.getDebugString().c_str());
}

void LayerSnapshotBuilder::updateRoundedCorner(LayerSnapshot& snapshot,
                                               const RequestedLayerState& requested,
                                               const LayerSnapshot& parentSnapshot,
                                               const Args& args) {
    if (args.skipRoundCornersWhenProtected && requested.isProtected()) {
        snapshot.roundedCorner = RoundedCornerState();
        return;
    }
    snapshot.roundedCorner = RoundedCornerState();
    RoundedCornerState parentRoundedCorner;
    if (parentSnapshot.roundedCorner.hasRequestedRadius()) {
        parentRoundedCorner = parentSnapshot.roundedCorner;
        ui::Transform t = snapshot.localTransform.inverse();
        parentRoundedCorner.cropRect = t.transform(parentRoundedCorner.cropRect);
        parentRoundedCorner.radius.x *= t.getScaleX();
        parentRoundedCorner.radius.y *= t.getScaleY();
        parentRoundedCorner.requestedRadius.x *= t.getScaleX();
        parentRoundedCorner.requestedRadius.y *= t.getScaleY();
    }

    FloatRect layerCropRect = snapshot.croppedBufferSize;
    const vec2 requestedRadius(requested.cornerRadius, requested.cornerRadius);
    const vec2 clientDrawnRadius(requested.clientDrawnCornerRadius,
                                 requested.clientDrawnCornerRadius);
    RoundedCornerState layerSettings;
    layerSettings.cropRect = layerCropRect;
    layerSettings.requestedRadius = requestedRadius;
    layerSettings.clientDrawnRadius = clientDrawnRadius;

    const bool layerSettingsValid = layerSettings.hasRequestedRadius() && !layerCropRect.isEmpty();
    const bool parentRoundedCornerValid = parentRoundedCorner.hasRequestedRadius();
    if (layerSettingsValid && parentRoundedCornerValid) {
        // If the parent and the layer have rounded corner settings, use the parent settings if
        // the parent crop is entirely inside the layer crop. This has limitations and cause
        // rendering artifacts. See b/200300845 for correct fix.
        if (parentRoundedCorner.cropRect.left > layerCropRect.left &&
            parentRoundedCorner.cropRect.top > layerCropRect.top &&
            parentRoundedCorner.cropRect.right < layerCropRect.right &&
            parentRoundedCorner.cropRect.bottom < layerCropRect.bottom) {
            snapshot.roundedCorner = parentRoundedCorner;
        } else {
            snapshot.roundedCorner = layerSettings;
        }
    } else if (layerSettingsValid) {
        snapshot.roundedCorner = layerSettings;
    } else if (parentRoundedCornerValid) {
        snapshot.roundedCorner = parentRoundedCorner;
    }

    if (snapshot.roundedCorner.requestedRadius.x == requested.clientDrawnCornerRadius) {
        // If the client drawn radius matches the requested radius, then surfaceflinger
        // does not need to draw rounded corners for this layer
        snapshot.roundedCorner.radius = vec2(0.f, 0.f);
    } else {
        snapshot.roundedCorner.radius = snapshot.roundedCorner.requestedRadius;
    }
}

/**
 * According to the edges that we are requested to extend, we increase the bounds to the maximum
 * extension allowed by the crop (parent crop + requested crop). The animation that called
 * Transition#setEdgeExtensionEffect is in charge of setting the requested crop.
 * @param snapshot
 */
void LayerSnapshotBuilder::updateBoundsForEdgeExtension(LayerSnapshot& snapshot) {
    EdgeExtensionEffect& effect = snapshot.edgeExtensionEffect;

    if (effect.extendsEdge(LEFT)) {
        snapshot.geomLayerBounds.left = snapshot.geomLayerCrop.left;
    }
    if (effect.extendsEdge(RIGHT)) {
        snapshot.geomLayerBounds.right = snapshot.geomLayerCrop.right;
    }
    if (effect.extendsEdge(TOP)) {
        snapshot.geomLayerBounds.top = snapshot.geomLayerCrop.top;
    }
    if (effect.extendsEdge(BOTTOM)) {
        snapshot.geomLayerBounds.bottom = snapshot.geomLayerCrop.bottom;
    }

    snapshot.transformedBounds = snapshot.geomLayerTransform.transform(snapshot.geomLayerBounds);
}

void LayerSnapshotBuilder::updateLayerBounds(LayerSnapshot& snapshot,
                                             const RequestedLayerState& requested,
                                             const LayerSnapshot& parentSnapshot,
                                             uint32_t primaryDisplayRotationFlags) {
    snapshot.geomLayerTransform = parentSnapshot.geomLayerTransform * snapshot.localTransform;
    const bool transformWasInvalid = snapshot.invalidTransform;
    snapshot.invalidTransform = !LayerSnapshot::isTransformValid(snapshot.geomLayerTransform);
    if (snapshot.invalidTransform) {
        auto& t = snapshot.geomLayerTransform;
        auto& requestedT = requested.requestedTransform;
        std::string transformDebug =
                base::StringPrintf(" transform={%f,%f,%f,%f}  requestedTransform={%f,%f,%f,%f}",
                                   t.dsdx(), t.dsdy(), t.dtdx(), t.dtdy(), requestedT.dsdx(),
                                   requestedT.dsdy(), requestedT.dtdx(), requestedT.dtdy());
        std::string bufferDebug;
        if (requested.externalTexture) {
            auto unRotBuffer = requested.getUnrotatedBufferSize(primaryDisplayRotationFlags);
            auto& destFrame = requested.destinationFrame;
            bufferDebug = base::StringPrintf(" buffer={%d,%d}  displayRot=%d"
                                             " destFrame={%d,%d,%d,%d} unRotBuffer={%d,%d}",
                                             requested.externalTexture->getWidth(),
                                             requested.externalTexture->getHeight(),
                                             primaryDisplayRotationFlags, destFrame.left,
                                             destFrame.top, destFrame.right, destFrame.bottom,
                                             unRotBuffer.getHeight(), unRotBuffer.getWidth());
        }
        ALOGW("Resetting transform for %s because it is invalid.%s%s",
              snapshot.getDebugString().c_str(), transformDebug.c_str(), bufferDebug.c_str());
        snapshot.geomLayerTransform.reset();
    }
    if (transformWasInvalid != snapshot.invalidTransform) {
        // If transform is invalid, the layer will be hidden.
        mResortSnapshots = true;
    }
    snapshot.geomInverseLayerTransform = snapshot.geomLayerTransform.inverse();

    FloatRect parentBounds = parentSnapshot.geomLayerBounds;
    parentBounds = snapshot.localTransform.inverse().transform(parentBounds);
    snapshot.geomLayerBounds =
            requested.externalTexture ? snapshot.bufferSize.toFloatRect() : parentBounds;
    snapshot.geomLayerCrop = parentBounds;
    if (!requested.crop.isEmpty()) {
        snapshot.geomLayerCrop = snapshot.geomLayerCrop.intersect(requested.crop);
    }
    snapshot.geomLayerBounds = snapshot.geomLayerBounds.intersect(snapshot.geomLayerCrop);
    snapshot.transformedBounds = snapshot.geomLayerTransform.transform(snapshot.geomLayerBounds);
    const Rect geomLayerBoundsWithoutTransparentRegion =
            RequestedLayerState::reduce(Rect(snapshot.geomLayerBounds),
                                        requested.getTransparentRegion());
    snapshot.transformedBoundsWithoutTransparentRegion =
            snapshot.geomLayerTransform.transform(geomLayerBoundsWithoutTransparentRegion);
    snapshot.parentTransform = parentSnapshot.geomLayerTransform;

    if (requested.potentialCursor) {
        // Subtract the transparent region and snap to the bounds
        const Rect bounds = RequestedLayerState::reduce(Rect(snapshot.croppedBufferSize),
                                                        requested.getTransparentRegion());
        snapshot.cursorFrame = snapshot.geomLayerTransform.transform(bounds);
    }
}

void LayerSnapshotBuilder::updateShadows(LayerSnapshot& snapshot, const RequestedLayerState&,
                                         const ShadowSettings& globalShadowSettings) {
    if (snapshot.shadowSettings.length > 0.f) {
        snapshot.shadowSettings.ambientColor = globalShadowSettings.ambientColor;
        snapshot.shadowSettings.spotColor = globalShadowSettings.spotColor;
        snapshot.shadowSettings.lightPos = globalShadowSettings.lightPos;
        snapshot.shadowSettings.lightRadius = globalShadowSettings.lightRadius;

        // Note: this preserves existing behavior of shadowing the entire layer and not cropping
        // it if transparent regions are present. This may not be necessary since shadows are
        // typically cast by layers without transparent regions.
        snapshot.shadowSettings.boundaries = snapshot.geomLayerBounds;

        // If the casting layer is translucent, we need to fill in the shadow underneath the
        // layer. Otherwise the generated shadow will only be shown around the casting layer.
        snapshot.shadowSettings.casterIsTranslucent =
                !snapshot.isContentOpaque() || (snapshot.alpha < 1.0f);
        snapshot.shadowSettings.ambientColor *= snapshot.alpha;
        snapshot.shadowSettings.spotColor *= snapshot.alpha;
    }
}

void LayerSnapshotBuilder::updateInput(LayerSnapshot& snapshot,
                                       const RequestedLayerState& requested,
                                       const LayerSnapshot& parentSnapshot,
                                       const LayerHierarchy::TraversalPath& path,
                                       const Args& args) {
    using InputConfig = gui::WindowInfo::InputConfig;

    snapshot.inputInfo = requested.getWindowInfo();
    snapshot.touchCropId = requested.touchCropId;

    snapshot.inputInfo.id = static_cast<int32_t>(snapshot.uniqueSequence);
    snapshot.inputInfo.displayId =
            ui::LogicalDisplayId{static_cast<int32_t>(snapshot.outputFilter.layerStack.id)};
    snapshot.inputInfo.touchOcclusionMode = requested.hasInputInfo()
            ? requested.getWindowInfo().touchOcclusionMode
            : parentSnapshot.inputInfo.touchOcclusionMode;
    snapshot.inputInfo.canOccludePresentation = parentSnapshot.inputInfo.canOccludePresentation ||
            (requested.flags & layer_state_t::eCanOccludePresentation);
    if (requested.dropInputMode == gui::DropInputMode::ALL ||
        parentSnapshot.dropInputMode == gui::DropInputMode::ALL) {
        snapshot.dropInputMode = gui::DropInputMode::ALL;
    } else if (requested.dropInputMode == gui::DropInputMode::OBSCURED ||
               parentSnapshot.dropInputMode == gui::DropInputMode::OBSCURED) {
        snapshot.dropInputMode = gui::DropInputMode::OBSCURED;
    } else {
        snapshot.dropInputMode = gui::DropInputMode::NONE;
    }

    if (snapshot.isSecure ||
        parentSnapshot.inputInfo.inputConfig.test(InputConfig::SENSITIVE_FOR_PRIVACY)) {
        snapshot.inputInfo.inputConfig |= InputConfig::SENSITIVE_FOR_PRIVACY;
    }

    updateVisibility(snapshot, snapshot.isVisible);
    if (!requested.needsInputInfo()) {
        return;
    }

    static frontend::DisplayInfo sDefaultInfo = {.isSecure = false};
    const std::optional<frontend::DisplayInfo> displayInfoOpt =
            args.displays.get(snapshot.outputFilter.layerStack);
    bool noValidDisplay = !displayInfoOpt.has_value();
    auto displayInfo = displayInfoOpt.value_or(sDefaultInfo);

    if (!requested.hasInputInfo()) {
        snapshot.inputInfo.inputConfig |= InputConfig::NO_INPUT_CHANNEL;
    }
    fillInputFrameInfo(snapshot.inputInfo, displayInfo.transform, snapshot);

    if (noValidDisplay) {
        // Do not let the window receive touches if it is not associated with a valid display
        // transform. We still allow the window to receive keys and prevent ANRs.
        snapshot.inputInfo.inputConfig |= InputConfig::NOT_TOUCHABLE;
    }

    snapshot.inputInfo.alpha = snapshot.color.a;

    handleDropInputMode(snapshot, parentSnapshot);

    // If the window will be blacked out on a display because the display does not have the secure
    // flag and the layer has the secure flag set, then drop input.
    if (!displayInfo.isSecure && snapshot.isSecure) {
        snapshot.inputInfo.inputConfig |= InputConfig::DROP_INPUT;
    }

    if (requested.touchCropId != UNASSIGNED_LAYER_ID || path.isClone()) {
        mNeedsTouchableRegionCrop.insert(path);
    }
    auto cropLayerSnapshot = getSnapshot(requested.touchCropId);
    if (!cropLayerSnapshot && snapshot.inputInfo.replaceTouchableRegionWithCrop) {
        FloatRect inputBounds = getInputBounds(snapshot, /*fillParentBounds=*/true).first;
        Rect inputBoundsInDisplaySpace =
                getInputBoundsInDisplaySpace(snapshot, inputBounds, displayInfo.transform);
        snapshot.inputInfo.touchableRegion = Region(inputBoundsInDisplaySpace);
    }

    // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
    // if it was set by WM for a known system overlay
    if (snapshot.trustedOverlay == gui::TrustedOverlay::ENABLED) {
        snapshot.inputInfo.inputConfig |= InputConfig::TRUSTED_OVERLAY;
    }

    snapshot.inputInfo.contentSize = {snapshot.croppedBufferSize.getHeight(),
                                      snapshot.croppedBufferSize.getWidth()};

    snapshot.inputInfo.cloneLayerStackTransform.reset();

    if (path.isClone()) {
        snapshot.inputInfo.inputConfig |= InputConfig::CLONE;
        // Cloned layers shouldn't handle watch outside since their z order is not determined by
        // WM or the client.
        snapshot.inputInfo.inputConfig.clear(InputConfig::WATCH_OUTSIDE_TOUCH);

        // Compute the transform that maps the clone's display to the layer stack space of the
        // cloned window.
        const LayerSnapshot* clonedSnapshot = getSnapshot(path.getClonedFrom());
        if (clonedSnapshot != nullptr) {
            const auto& [clonedInputBounds, s] =
                    getInputBounds(*clonedSnapshot, /*fillParentBounds=*/false);
            ui::Transform inputToLayer;
            inputToLayer.set(clonedInputBounds.left, clonedInputBounds.top);
            const ui::Transform& layerToLayerStack = getInputTransform(*clonedSnapshot);
            const auto& displayToInput = snapshot.inputInfo.transform;
            snapshot.inputInfo.cloneLayerStackTransform =
                    layerToLayerStack * inputToLayer * displayToInput;
        }
    }
}

std::vector<std::unique_ptr<LayerSnapshot>>& LayerSnapshotBuilder::getSnapshots() {
    return mSnapshots;
}

void LayerSnapshotBuilder::forEachVisibleSnapshot(const ConstVisitor& visitor) const {
    for (int i = 0; i < mNumInterestingSnapshots; i++) {
        LayerSnapshot& snapshot = *mSnapshots[(size_t)i];
        if (!snapshot.isVisible) continue;
        visitor(snapshot);
    }
}

// Visit each visible snapshot in z-order
void LayerSnapshotBuilder::forEachVisibleSnapshot(const ConstVisitor& visitor,
                                                  const LayerHierarchy& root) const {
    root.traverseInZOrder(
            [this, visitor](const LayerHierarchy&,
                            const LayerHierarchy::TraversalPath& traversalPath) -> bool {
                LayerSnapshot* snapshot = getSnapshot(traversalPath);
                if (snapshot && snapshot->isVisible) {
                    visitor(*snapshot);
                }
                return true;
            });
}

void LayerSnapshotBuilder::forEachVisibleSnapshot(const Visitor& visitor) {
    for (int i = 0; i < mNumInterestingSnapshots; i++) {
        std::unique_ptr<LayerSnapshot>& snapshot = mSnapshots.at((size_t)i);
        if (!snapshot->isVisible) continue;
        visitor(snapshot);
    }
}

void LayerSnapshotBuilder::forEachSnapshot(const Visitor& visitor,
                                           const ConstPredicate& predicate) {
    for (int i = 0; i < mNumInterestingSnapshots; i++) {
        std::unique_ptr<LayerSnapshot>& snapshot = mSnapshots.at((size_t)i);
        if (!predicate(*snapshot)) continue;
        visitor(snapshot);
    }
}

void LayerSnapshotBuilder::forEachSnapshot(const ConstVisitor& visitor) const {
    for (auto& snapshot : mSnapshots) {
        visitor(*snapshot);
    }
}

void LayerSnapshotBuilder::forEachInputSnapshot(const ConstVisitor& visitor) const {
    for (int i = mNumInterestingSnapshots - 1; i >= 0; i--) {
        LayerSnapshot& snapshot = *mSnapshots[(size_t)i];
        if (!snapshot.hasInputInfo()) continue;
        if (FlagManager::getInstance().skip_invisible_windows_in_input() &&
            snapshot.inputInfo.inputConfig.test(gui::WindowInfo::InputConfig::NOT_VISIBLE)) {
            continue;
        }
        visitor(snapshot);
    }
}

void LayerSnapshotBuilder::updateTouchableRegionCrop(const Args& args) {
    if (mNeedsTouchableRegionCrop.empty()) {
        return;
    }

    static constexpr ftl::Flags<RequestedLayerState::Changes> AFFECTS_INPUT =
            RequestedLayerState::Changes::Visibility | RequestedLayerState::Changes::Created |
            RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Geometry |
            RequestedLayerState::Changes::Input;

    if (args.forceUpdate != ForceUpdateFlags::ALL &&
        !args.layerLifecycleManager.getGlobalChanges().any(AFFECTS_INPUT) && !args.displayChanges) {
        return;
    }

    for (auto& path : mNeedsTouchableRegionCrop) {
        frontend::LayerSnapshot* snapshot = getSnapshot(path);
        if (!snapshot) {
            continue;
        }
        LLOGV(snapshot->sequence, "updateTouchableRegionCrop=%s",
              snapshot->getDebugString().c_str());
        const std::optional<frontend::DisplayInfo> displayInfoOpt =
                args.displays.get(snapshot->outputFilter.layerStack);
        static frontend::DisplayInfo sDefaultInfo = {.isSecure = false};
        auto displayInfo = displayInfoOpt.value_or(sDefaultInfo);

        bool needsUpdate =
                args.forceUpdate == ForceUpdateFlags::ALL || snapshot->changes.any(AFFECTS_INPUT);
        auto cropLayerSnapshot = getSnapshot(snapshot->touchCropId);
        needsUpdate =
                needsUpdate || (cropLayerSnapshot && cropLayerSnapshot->changes.any(AFFECTS_INPUT));
        auto clonedRootSnapshot = path.isClone() ? getSnapshot(snapshot->mirrorRootPath) : nullptr;
        needsUpdate = needsUpdate ||
                (clonedRootSnapshot && clonedRootSnapshot->changes.any(AFFECTS_INPUT));

        if (!needsUpdate) {
            continue;
        }

        if (snapshot->inputInfo.replaceTouchableRegionWithCrop) {
            Rect inputBoundsInDisplaySpace;
            if (!cropLayerSnapshot) {
                FloatRect inputBounds = getInputBounds(*snapshot, /*fillParentBounds=*/true).first;
                inputBoundsInDisplaySpace =
                        getInputBoundsInDisplaySpace(*snapshot, inputBounds, displayInfo.transform);
            } else {
                FloatRect inputBounds =
                        getInputBounds(*cropLayerSnapshot, /*fillParentBounds=*/true).first;
                inputBoundsInDisplaySpace =
                        getInputBoundsInDisplaySpace(*cropLayerSnapshot, inputBounds,
                                                     displayInfo.transform);
            }
            snapshot->inputInfo.touchableRegion = Region(inputBoundsInDisplaySpace);
        } else if (cropLayerSnapshot) {
            FloatRect inputBounds =
                    getInputBounds(*cropLayerSnapshot, /*fillParentBounds=*/true).first;
            Rect inputBoundsInDisplaySpace =
                    getInputBoundsInDisplaySpace(*cropLayerSnapshot, inputBounds,
                                                 displayInfo.transform);
            snapshot->inputInfo.touchableRegion =
                    snapshot->inputInfo.touchableRegion.intersect(inputBoundsInDisplaySpace);
        }

        // If the layer is a clone, we need to crop the input region to cloned root to prevent
        // touches from going outside the cloned area.
        if (clonedRootSnapshot) {
            const Rect rect =
                    displayInfo.transform.transform(Rect{clonedRootSnapshot->transformedBounds});
            snapshot->inputInfo.touchableRegion =
                    snapshot->inputInfo.touchableRegion.intersect(rect);
        }
    }
}

} // namespace android::surfaceflinger::frontend