summaryrefslogtreecommitdiff
path: root/services/surfaceflinger/CompositionEngine/tests/OutputTest.cpp
blob: 615fb94c3437d758cb8e8f508120faf66bff75bb (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
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
/*
 * Copyright 2019 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.
 */

#include <cmath>

#include <android-base/stringprintf.h>
#include <compositionengine/LayerFECompositionState.h>
#include <compositionengine/impl/Output.h>
#include <compositionengine/impl/OutputCompositionState.h>
#include <compositionengine/impl/OutputLayerCompositionState.h>
#include <compositionengine/mock/CompositionEngine.h>
#include <compositionengine/mock/DisplayColorProfile.h>
#include <compositionengine/mock/Layer.h>
#include <compositionengine/mock/LayerFE.h>
#include <compositionengine/mock/OutputLayer.h>
#include <compositionengine/mock/RenderSurface.h>
#include <gtest/gtest.h>
#include <renderengine/mock/RenderEngine.h>
#include <ui/Rect.h>
#include <ui/Region.h>

#include "CallOrderStateMachineHelper.h"
#include "RegionMatcher.h"
#include "TransformMatcher.h"

namespace android::compositionengine {
namespace {

using testing::_;
using testing::ByMove;
using testing::DoAll;
using testing::InSequence;
using testing::Mock;
using testing::Ref;
using testing::Return;
using testing::ReturnRef;
using testing::SetArgPointee;
using testing::StrictMock;

constexpr auto TR_IDENT = 0u;
constexpr auto TR_ROT_90 = HAL_TRANSFORM_ROT_90;

const mat4 kIdentity;
const mat4 kNonIdentityHalf = mat4() * 0.5;
const mat4 kNonIdentityQuarter = mat4() * 0.25;

constexpr OutputColorSetting kVendorSpecifiedOutputColorSetting =
        static_cast<OutputColorSetting>(0x100);

struct OutputPartialMockBase : public impl::Output {
    // compositionengine::Output overrides
    const OutputCompositionState& getState() const override { return mState; }
    OutputCompositionState& editState() override { return mState; }

    // Use mocks for all the remaining virtual functions
    // not implemented by the base implementation class.
    MOCK_CONST_METHOD0(getOutputLayerCount, size_t());
    MOCK_CONST_METHOD1(getOutputLayerOrderedByZByIndex, compositionengine::OutputLayer*(size_t));
    MOCK_METHOD3(ensureOutputLayer,
                 compositionengine::OutputLayer*(std::optional<size_t>,
                                                 const std::shared_ptr<compositionengine::Layer>&,
                                                 const sp<LayerFE>&));
    MOCK_METHOD0(finalizePendingOutputLayers, void());
    MOCK_METHOD0(clearOutputLayers, void());
    MOCK_CONST_METHOD1(dumpState, void(std::string&));
    MOCK_CONST_METHOD0(getCompositionEngine, const CompositionEngine&());
    MOCK_METHOD2(injectOutputLayerForTest,
                 compositionengine::OutputLayer*(const std::shared_ptr<compositionengine::Layer>&,
                                                 const sp<LayerFE>&));
    MOCK_METHOD1(injectOutputLayerForTest, void(std::unique_ptr<OutputLayer>));

    impl::OutputCompositionState mState;
};

struct OutputTest : public testing::Test {
    class Output : public impl::Output {
    public:
        using impl::Output::injectOutputLayerForTest;
        virtual void injectOutputLayerForTest(std::unique_ptr<compositionengine::OutputLayer>) = 0;
    };

    static std::shared_ptr<Output> createOutput(
            const compositionengine::CompositionEngine& compositionEngine) {
        return impl::createOutputTemplated<Output>(compositionEngine);
    }

    OutputTest() {
        mOutput->setDisplayColorProfileForTest(
                std::unique_ptr<DisplayColorProfile>(mDisplayColorProfile));
        mOutput->setRenderSurfaceForTest(std::unique_ptr<RenderSurface>(mRenderSurface));

        mOutput->editState().bounds = kDefaultDisplaySize;
    }

    static const Rect kDefaultDisplaySize;

    StrictMock<mock::CompositionEngine> mCompositionEngine;
    mock::DisplayColorProfile* mDisplayColorProfile = new StrictMock<mock::DisplayColorProfile>();
    mock::RenderSurface* mRenderSurface = new StrictMock<mock::RenderSurface>();
    std::shared_ptr<Output> mOutput = createOutput(mCompositionEngine);
};

const Rect OutputTest::kDefaultDisplaySize{100, 200};

using ColorProfile = compositionengine::Output::ColorProfile;

void dumpColorProfile(ColorProfile profile, std::string& result, const char* name) {
    android::base::StringAppendF(&result, "%s (%s[%d] %s[%d] %s[%d] %s[%d]) ", name,
                                 toString(profile.mode).c_str(), profile.mode,
                                 toString(profile.dataspace).c_str(), profile.dataspace,
                                 toString(profile.renderIntent).c_str(), profile.renderIntent,
                                 toString(profile.colorSpaceAgnosticDataspace).c_str(),
                                 profile.colorSpaceAgnosticDataspace);
}

// Checks for a ColorProfile match
MATCHER_P(ColorProfileEq, expected, "") {
    std::string buf;
    buf.append("ColorProfiles are not equal\n");
    dumpColorProfile(expected, buf, "expected value");
    dumpColorProfile(arg, buf, "actual value");
    *result_listener << buf;

    return (expected.mode == arg.mode) && (expected.dataspace == arg.dataspace) &&
            (expected.renderIntent == arg.renderIntent) &&
            (expected.colorSpaceAgnosticDataspace == arg.colorSpaceAgnosticDataspace);
}

/*
 * Basic construction
 */

TEST_F(OutputTest, canInstantiateOutput) {
    // The validation check checks each required component.
    EXPECT_CALL(*mDisplayColorProfile, isValid()).WillOnce(Return(true));
    EXPECT_CALL(*mRenderSurface, isValid()).WillOnce(Return(true));

    EXPECT_TRUE(mOutput->isValid());

    // If we take away the required components, it is no longer valid.
    mOutput->setRenderSurfaceForTest(std::unique_ptr<RenderSurface>());

    EXPECT_CALL(*mDisplayColorProfile, isValid()).WillOnce(Return(true));

    EXPECT_FALSE(mOutput->isValid());
}

/*
 * Output::setCompositionEnabled()
 */

TEST_F(OutputTest, setCompositionEnabledDoesNothingIfAlreadyEnabled) {
    mOutput->editState().isEnabled = true;

    mOutput->setCompositionEnabled(true);

    EXPECT_TRUE(mOutput->getState().isEnabled);
    EXPECT_THAT(mOutput->getState().dirtyRegion, RegionEq(Region()));
}

TEST_F(OutputTest, setCompositionEnabledSetsEnabledAndDirtiesEntireOutput) {
    mOutput->editState().isEnabled = false;

    mOutput->setCompositionEnabled(true);

    EXPECT_TRUE(mOutput->getState().isEnabled);
    EXPECT_THAT(mOutput->getState().dirtyRegion, RegionEq(Region(kDefaultDisplaySize)));
}

TEST_F(OutputTest, setCompositionEnabledSetsDisabledAndDirtiesEntireOutput) {
    mOutput->editState().isEnabled = true;

    mOutput->setCompositionEnabled(false);

    EXPECT_FALSE(mOutput->getState().isEnabled);
    EXPECT_THAT(mOutput->getState().dirtyRegion, RegionEq(Region(kDefaultDisplaySize)));
}

/*
 * Output::setProjection()
 */

TEST_F(OutputTest, setProjectionTriviallyWorks) {
    const ui::Transform transform{ui::Transform::ROT_180};
    const int32_t orientation = 123;
    const Rect frame{1, 2, 3, 4};
    const Rect viewport{5, 6, 7, 8};
    const Rect scissor{9, 10, 11, 12};
    const bool needsFiltering = true;

    mOutput->setProjection(transform, orientation, frame, viewport, scissor, needsFiltering);

    EXPECT_THAT(mOutput->getState().transform, TransformEq(transform));
    EXPECT_EQ(orientation, mOutput->getState().orientation);
    EXPECT_EQ(frame, mOutput->getState().frame);
    EXPECT_EQ(viewport, mOutput->getState().viewport);
    EXPECT_EQ(scissor, mOutput->getState().scissor);
    EXPECT_EQ(needsFiltering, mOutput->getState().needsFiltering);
}

/*
 * Output::setBounds()
 */

TEST_F(OutputTest, setBoundsSetsSizeAndDirtiesEntireOutput) {
    const ui::Size displaySize{200, 400};

    EXPECT_CALL(*mRenderSurface, setDisplaySize(displaySize)).Times(1);
    EXPECT_CALL(*mRenderSurface, getSize()).WillOnce(ReturnRef(displaySize));

    mOutput->setBounds(displaySize);

    EXPECT_EQ(Rect(displaySize), mOutput->getState().bounds);

    EXPECT_THAT(mOutput->getState().dirtyRegion, RegionEq(Region(Rect(displaySize))));
}

/*
 * Output::setLayerStackFilter()
 */

TEST_F(OutputTest, setLayerStackFilterSetsFilterAndDirtiesEntireOutput) {
    const uint32_t layerStack = 123u;
    mOutput->setLayerStackFilter(layerStack, true);

    EXPECT_TRUE(mOutput->getState().layerStackInternal);
    EXPECT_EQ(layerStack, mOutput->getState().layerStackId);

    EXPECT_THAT(mOutput->getState().dirtyRegion, RegionEq(Region(kDefaultDisplaySize)));
}

/*
 * Output::setColorTransform
 */

TEST_F(OutputTest, setColorTransformWithNoChangeFlaggedSkipsUpdates) {
    mOutput->editState().colorTransformMatrix = kIdentity;

    // If no colorTransformMatrix is set the update should be skipped.
    CompositionRefreshArgs refreshArgs;
    refreshArgs.colorTransformMatrix = std::nullopt;

    mOutput->setColorTransform(refreshArgs);

    // The internal state should be unchanged
    EXPECT_EQ(kIdentity, mOutput->getState().colorTransformMatrix);

    // No dirty region should be set
    EXPECT_THAT(mOutput->getState().dirtyRegion, RegionEq(Region()));
}

TEST_F(OutputTest, setColorTransformWithNoActualChangeSkipsUpdates) {
    mOutput->editState().colorTransformMatrix = kIdentity;

    // Attempting to set the same colorTransformMatrix that is already set should
    // also skip the update.
    CompositionRefreshArgs refreshArgs;
    refreshArgs.colorTransformMatrix = kIdentity;

    mOutput->setColorTransform(refreshArgs);

    // The internal state should be unchanged
    EXPECT_EQ(kIdentity, mOutput->getState().colorTransformMatrix);

    // No dirty region should be set
    EXPECT_THAT(mOutput->getState().dirtyRegion, RegionEq(Region()));
}

TEST_F(OutputTest, setColorTransformPerformsUpdateToIdentity) {
    mOutput->editState().colorTransformMatrix = kNonIdentityHalf;

    // Setting a different colorTransformMatrix should perform the update.
    CompositionRefreshArgs refreshArgs;
    refreshArgs.colorTransformMatrix = kIdentity;

    mOutput->setColorTransform(refreshArgs);

    // The internal state should have been updated
    EXPECT_EQ(kIdentity, mOutput->getState().colorTransformMatrix);

    // The dirtyRegion should be set to the full display size
    EXPECT_THAT(mOutput->getState().dirtyRegion, RegionEq(Region(kDefaultDisplaySize)));
}

TEST_F(OutputTest, setColorTransformPerformsUpdateForIdentityToHalf) {
    mOutput->editState().colorTransformMatrix = kIdentity;

    // Setting a different colorTransformMatrix should perform the update.
    CompositionRefreshArgs refreshArgs;
    refreshArgs.colorTransformMatrix = kNonIdentityHalf;

    mOutput->setColorTransform(refreshArgs);

    // The internal state should have been updated
    EXPECT_EQ(kNonIdentityHalf, mOutput->getState().colorTransformMatrix);

    // The dirtyRegion should be set to the full display size
    EXPECT_THAT(mOutput->getState().dirtyRegion, RegionEq(Region(kDefaultDisplaySize)));
}

TEST_F(OutputTest, setColorTransformPerformsUpdateForHalfToQuarter) {
    mOutput->editState().colorTransformMatrix = kNonIdentityHalf;

    // Setting a different colorTransformMatrix should perform the update.
    CompositionRefreshArgs refreshArgs;
    refreshArgs.colorTransformMatrix = kNonIdentityQuarter;

    mOutput->setColorTransform(refreshArgs);

    // The internal state should have been updated
    EXPECT_EQ(kNonIdentityQuarter, mOutput->getState().colorTransformMatrix);

    // The dirtyRegion should be set to the full display size
    EXPECT_THAT(mOutput->getState().dirtyRegion, RegionEq(Region(kDefaultDisplaySize)));
}

/*
 * Output::setColorProfile
 */

using OutputSetColorProfileTest = OutputTest;

TEST_F(OutputSetColorProfileTest, setsStateAndDirtiesOutputIfChanged) {
    using ColorProfile = Output::ColorProfile;

    EXPECT_CALL(*mDisplayColorProfile,
                getTargetDataspace(ui::ColorMode::DISPLAY_P3, ui::Dataspace::DISPLAY_P3,
                                   ui::Dataspace::UNKNOWN))
            .WillOnce(Return(ui::Dataspace::UNKNOWN));
    EXPECT_CALL(*mRenderSurface, setBufferDataspace(ui::Dataspace::DISPLAY_P3)).Times(1);

    mOutput->setColorProfile(ColorProfile{ui::ColorMode::DISPLAY_P3, ui::Dataspace::DISPLAY_P3,
                                          ui::RenderIntent::TONE_MAP_COLORIMETRIC,
                                          ui::Dataspace::UNKNOWN});

    EXPECT_EQ(ui::ColorMode::DISPLAY_P3, mOutput->getState().colorMode);
    EXPECT_EQ(ui::Dataspace::DISPLAY_P3, mOutput->getState().dataspace);
    EXPECT_EQ(ui::RenderIntent::TONE_MAP_COLORIMETRIC, mOutput->getState().renderIntent);
    EXPECT_EQ(ui::Dataspace::UNKNOWN, mOutput->getState().targetDataspace);

    EXPECT_THAT(mOutput->getState().dirtyRegion, RegionEq(Region(kDefaultDisplaySize)));
}

TEST_F(OutputSetColorProfileTest, doesNothingIfNoChange) {
    using ColorProfile = Output::ColorProfile;

    EXPECT_CALL(*mDisplayColorProfile,
                getTargetDataspace(ui::ColorMode::DISPLAY_P3, ui::Dataspace::DISPLAY_P3,
                                   ui::Dataspace::UNKNOWN))
            .WillOnce(Return(ui::Dataspace::UNKNOWN));

    mOutput->editState().colorMode = ui::ColorMode::DISPLAY_P3;
    mOutput->editState().dataspace = ui::Dataspace::DISPLAY_P3;
    mOutput->editState().renderIntent = ui::RenderIntent::TONE_MAP_COLORIMETRIC;
    mOutput->editState().targetDataspace = ui::Dataspace::UNKNOWN;

    mOutput->setColorProfile(ColorProfile{ui::ColorMode::DISPLAY_P3, ui::Dataspace::DISPLAY_P3,
                                          ui::RenderIntent::TONE_MAP_COLORIMETRIC,
                                          ui::Dataspace::UNKNOWN});

    EXPECT_THAT(mOutput->getState().dirtyRegion, RegionEq(Region()));
}

/*
 * Output::setRenderSurface()
 */

TEST_F(OutputTest, setRenderSurfaceResetsBounds) {
    const ui::Size newDisplaySize{640, 480};

    mock::RenderSurface* renderSurface = new StrictMock<mock::RenderSurface>();
    EXPECT_CALL(*renderSurface, getSize()).WillOnce(ReturnRef(newDisplaySize));

    mOutput->setRenderSurface(std::unique_ptr<RenderSurface>(renderSurface));

    EXPECT_EQ(Rect(newDisplaySize), mOutput->getState().bounds);
}

/*
 * Output::getDirtyRegion()
 */

TEST_F(OutputTest, getDirtyRegionWithRepaintEverythingTrue) {
    const Rect viewport{100, 200};
    mOutput->editState().viewport = viewport;
    mOutput->editState().dirtyRegion.set(50, 300);

    {
        Region result = mOutput->getDirtyRegion(true);

        EXPECT_THAT(result, RegionEq(Region(viewport)));
    }
}

TEST_F(OutputTest, getDirtyRegionWithRepaintEverythingFalse) {
    const Rect viewport{100, 200};
    mOutput->editState().viewport = viewport;
    mOutput->editState().dirtyRegion.set(50, 300);

    {
        Region result = mOutput->getDirtyRegion(false);

        // The dirtyRegion should be clipped to the display bounds.
        EXPECT_THAT(result, RegionEq(Region(Rect(50, 200))));
    }
}

/*
 * Output::belongsInOutput()
 */

TEST_F(OutputTest, belongsInOutputFiltersAsExpected) {
    const uint32_t layerStack1 = 123u;
    const uint32_t layerStack2 = 456u;

    // If the output accepts layerStack1 and internal-only layers....
    mOutput->setLayerStackFilter(layerStack1, true);

    // A layer with no layerStack does not belong to it, internal-only or not.
    EXPECT_FALSE(mOutput->belongsInOutput(std::nullopt, false));
    EXPECT_FALSE(mOutput->belongsInOutput(std::nullopt, true));

    // Any layer with layerStack1 belongs to it, internal-only or not.
    EXPECT_TRUE(mOutput->belongsInOutput(layerStack1, false));
    EXPECT_TRUE(mOutput->belongsInOutput(layerStack1, true));
    EXPECT_FALSE(mOutput->belongsInOutput(layerStack2, true));
    EXPECT_FALSE(mOutput->belongsInOutput(layerStack2, false));

    // If the output accepts layerStack21 but not internal-only layers...
    mOutput->setLayerStackFilter(layerStack1, false);

    // Only non-internal layers with layerStack1 belong to it.
    EXPECT_TRUE(mOutput->belongsInOutput(layerStack1, false));
    EXPECT_FALSE(mOutput->belongsInOutput(layerStack1, true));
    EXPECT_FALSE(mOutput->belongsInOutput(layerStack2, true));
    EXPECT_FALSE(mOutput->belongsInOutput(layerStack2, false));
}

TEST_F(OutputTest, belongsInOutputFiltersLayersAsExpected) {
    StrictMock<mock::Layer> layer;
    LayerFECompositionState layerFEState;

    EXPECT_CALL(layer, getFEState()).WillRepeatedly(ReturnRef(layerFEState));

    const uint32_t layerStack1 = 123u;
    const uint32_t layerStack2 = 456u;

    // If the output accepts layerStack1 and internal-only layers....
    mOutput->setLayerStackFilter(layerStack1, true);

    // A null layer pointer does not belong to the output
    EXPECT_FALSE(mOutput->belongsInOutput(nullptr));

    // A layer with no layerStack does not belong to it, internal-only or not.
    layerFEState.layerStackId = std::nullopt;
    layerFEState.internalOnly = false;
    EXPECT_FALSE(mOutput->belongsInOutput(&layer));

    layerFEState.layerStackId = std::nullopt;
    layerFEState.internalOnly = true;
    EXPECT_FALSE(mOutput->belongsInOutput(&layer));

    // Any layer with layerStack1 belongs to it, internal-only or not.
    layerFEState.layerStackId = layerStack1;
    layerFEState.internalOnly = false;
    EXPECT_TRUE(mOutput->belongsInOutput(&layer));

    layerFEState.layerStackId = layerStack1;
    layerFEState.internalOnly = true;
    EXPECT_TRUE(mOutput->belongsInOutput(&layer));

    layerFEState.layerStackId = layerStack2;
    layerFEState.internalOnly = true;
    EXPECT_FALSE(mOutput->belongsInOutput(&layer));

    layerFEState.layerStackId = layerStack2;
    layerFEState.internalOnly = false;
    EXPECT_FALSE(mOutput->belongsInOutput(&layer));

    // If the output accepts layerStack1 but not internal-only layers...
    mOutput->setLayerStackFilter(layerStack1, false);

    // A null layer pointer does not belong to the output
    EXPECT_FALSE(mOutput->belongsInOutput(nullptr));

    // Only non-internal layers with layerStack1 belong to it.
    layerFEState.layerStackId = layerStack1;
    layerFEState.internalOnly = false;
    EXPECT_TRUE(mOutput->belongsInOutput(&layer));

    layerFEState.layerStackId = layerStack1;
    layerFEState.internalOnly = true;
    EXPECT_FALSE(mOutput->belongsInOutput(&layer));

    layerFEState.layerStackId = layerStack2;
    layerFEState.internalOnly = true;
    EXPECT_FALSE(mOutput->belongsInOutput(&layer));

    layerFEState.layerStackId = layerStack2;
    layerFEState.internalOnly = false;
    EXPECT_FALSE(mOutput->belongsInOutput(&layer));
}

/*
 * Output::getOutputLayerForLayer()
 */

TEST_F(OutputTest, getOutputLayerForLayerWorks) {
    mock::OutputLayer* outputLayer1 = new StrictMock<mock::OutputLayer>();
    mock::OutputLayer* outputLayer2 = new StrictMock<mock::OutputLayer>();

    mOutput->injectOutputLayerForTest(std::unique_ptr<OutputLayer>(outputLayer1));
    mOutput->injectOutputLayerForTest(nullptr);
    mOutput->injectOutputLayerForTest(std::unique_ptr<OutputLayer>(outputLayer2));

    StrictMock<mock::Layer> layer;
    StrictMock<mock::Layer> otherLayer;

    // If the input layer matches the first OutputLayer, it will be returned.
    EXPECT_CALL(*outputLayer1, getLayer()).WillOnce(ReturnRef(layer));
    EXPECT_EQ(outputLayer1, mOutput->getOutputLayerForLayer(&layer));

    // If the input layer matches the second OutputLayer, it will be returned.
    EXPECT_CALL(*outputLayer1, getLayer()).WillOnce(ReturnRef(otherLayer));
    EXPECT_CALL(*outputLayer2, getLayer()).WillOnce(ReturnRef(layer));
    EXPECT_EQ(outputLayer2, mOutput->getOutputLayerForLayer(&layer));

    // If the input layer does not match an output layer, null will be returned.
    EXPECT_CALL(*outputLayer1, getLayer()).WillOnce(ReturnRef(otherLayer));
    EXPECT_CALL(*outputLayer2, getLayer()).WillOnce(ReturnRef(otherLayer));
    EXPECT_EQ(nullptr, mOutput->getOutputLayerForLayer(&layer));
}

/*
 * Output::setReleasedLayers()
 */

using OutputSetReleasedLayersTest = OutputTest;

TEST_F(OutputSetReleasedLayersTest, setReleasedLayersTakesGivenLayers) {
    sp<StrictMock<mock::LayerFE>> layer1FE{new StrictMock<mock::LayerFE>()};
    sp<StrictMock<mock::LayerFE>> layer2FE{new StrictMock<mock::LayerFE>()};
    sp<StrictMock<mock::LayerFE>> layer3FE{new StrictMock<mock::LayerFE>()};

    Output::ReleasedLayers layers;
    layers.push_back(layer1FE);
    layers.push_back(layer2FE);
    layers.push_back(layer3FE);

    mOutput->setReleasedLayers(std::move(layers));

    const auto& setLayers = mOutput->getReleasedLayersForTest();
    ASSERT_EQ(3u, setLayers.size());
    ASSERT_EQ(layer1FE.get(), setLayers[0].promote().get());
    ASSERT_EQ(layer2FE.get(), setLayers[1].promote().get());
    ASSERT_EQ(layer3FE.get(), setLayers[2].promote().get());
}

/*
 * Output::updateAndWriteCompositionState()
 */

TEST_F(OutputTest, updateAndWriteCompositionState_takesEarlyOutIfNotEnabled) {
    mOutput->editState().isEnabled = false;

    CompositionRefreshArgs args;
    mOutput->updateAndWriteCompositionState(args);
}

TEST_F(OutputTest, updateAndWriteCompositionState_updatesLayers) {
    mOutput->editState().isEnabled = true;
    mock::OutputLayer* outputLayer = new StrictMock<mock::OutputLayer>();
    mOutput->injectOutputLayerForTest(std::unique_ptr<OutputLayer>(outputLayer));

    EXPECT_CALL(*outputLayer, updateCompositionState(true, true)).Times(1);
    EXPECT_CALL(*outputLayer, writeStateToHWC(true)).Times(1);

    CompositionRefreshArgs args;
    args.updatingGeometryThisFrame = true;
    args.devOptForceClientComposition = true;
    mOutput->updateAndWriteCompositionState(args);
}

/*
 * Output::prepareFrame()
 */

struct OutputPrepareFrameTest : public testing::Test {
    struct OutputPartialMock : public OutputPartialMockBase {
        // Sets up the helper functions called by prepareFrame to use a mock
        // implementations.
        MOCK_METHOD0(chooseCompositionStrategy, void());
    };

    OutputPrepareFrameTest() {
        mOutput.setDisplayColorProfileForTest(
                std::unique_ptr<DisplayColorProfile>(mDisplayColorProfile));
        mOutput.setRenderSurfaceForTest(std::unique_ptr<RenderSurface>(mRenderSurface));
    }

    StrictMock<mock::CompositionEngine> mCompositionEngine;
    mock::DisplayColorProfile* mDisplayColorProfile = new StrictMock<mock::DisplayColorProfile>();
    mock::RenderSurface* mRenderSurface = new StrictMock<mock::RenderSurface>();
    StrictMock<OutputPartialMock> mOutput;
};

TEST_F(OutputPrepareFrameTest, takesEarlyOutIfNotEnabled) {
    mOutput.editState().isEnabled = false;

    mOutput.prepareFrame();
}

TEST_F(OutputPrepareFrameTest, delegatesToChooseCompositionStrategyAndRenderSurface) {
    mOutput.editState().isEnabled = true;
    mOutput.editState().usesClientComposition = false;
    mOutput.editState().usesDeviceComposition = true;

    EXPECT_CALL(mOutput, chooseCompositionStrategy()).Times(1);
    EXPECT_CALL(*mRenderSurface, prepareFrame(false, true));

    mOutput.prepareFrame();
}

// Note: Use OutputTest and not OutputPrepareFrameTest, so the real
// base chooseCompositionStrategy() is invoked.
TEST_F(OutputTest, prepareFrameSetsClientCompositionOnlyByDefault) {
    mOutput->editState().isEnabled = true;
    mOutput->editState().usesClientComposition = false;
    mOutput->editState().usesDeviceComposition = true;

    EXPECT_CALL(*mRenderSurface, prepareFrame(true, false));

    mOutput->prepareFrame();

    EXPECT_TRUE(mOutput->getState().usesClientComposition);
    EXPECT_FALSE(mOutput->getState().usesDeviceComposition);
}

/*
 * Output::present()
 */

struct OutputPresentTest : public testing::Test {
    struct OutputPartialMock : public OutputPartialMockBase {
        // All child helper functions Output::present() are defined as mocks,
        // and those are tested separately, allowing the present() test to
        // just cover the high level flow.
        MOCK_METHOD1(updateColorProfile, void(const compositionengine::CompositionRefreshArgs&));
        MOCK_METHOD1(updateAndWriteCompositionState,
                     void(const compositionengine::CompositionRefreshArgs&));
        MOCK_METHOD1(setColorTransform, void(const compositionengine::CompositionRefreshArgs&));
        MOCK_METHOD0(beginFrame, void());
        MOCK_METHOD0(prepareFrame, void());
        MOCK_METHOD1(devOptRepaintFlash, void(const compositionengine::CompositionRefreshArgs&));
        MOCK_METHOD1(finishFrame, void(const compositionengine::CompositionRefreshArgs&));
        MOCK_METHOD0(postFramebuffer, void());
    };

    StrictMock<OutputPartialMock> mOutput;
};

TEST_F(OutputPresentTest, justInvokesChildFunctionsInSequence) {
    CompositionRefreshArgs args;

    InSequence seq;
    EXPECT_CALL(mOutput, updateColorProfile(Ref(args)));
    EXPECT_CALL(mOutput, updateAndWriteCompositionState(Ref(args)));
    EXPECT_CALL(mOutput, setColorTransform(Ref(args)));
    EXPECT_CALL(mOutput, beginFrame());
    EXPECT_CALL(mOutput, prepareFrame());
    EXPECT_CALL(mOutput, devOptRepaintFlash(Ref(args)));
    EXPECT_CALL(mOutput, finishFrame(Ref(args)));
    EXPECT_CALL(mOutput, postFramebuffer());

    mOutput.present(args);
}

/*
 * Output::updateColorProfile()
 */

struct OutputUpdateColorProfileTest : public testing::Test {
    using TestType = OutputUpdateColorProfileTest;

    struct OutputPartialMock : public OutputPartialMockBase {
        // All child helper functions Output::present() are defined as mocks,
        // and those are tested separately, allowing the present() test to
        // just cover the high level flow.
        MOCK_METHOD1(setColorProfile, void(const ColorProfile&));
    };

    struct Layer {
        Layer() {
            EXPECT_CALL(mOutputLayer, getLayer()).WillRepeatedly(ReturnRef(mLayer));
            EXPECT_CALL(mOutputLayer, getLayerFE()).WillRepeatedly(ReturnRef(mLayerFE));
            EXPECT_CALL(mLayer, getFEState()).WillRepeatedly(ReturnRef(mLayerFEState));
        }

        StrictMock<mock::OutputLayer> mOutputLayer;
        StrictMock<mock::Layer> mLayer;
        StrictMock<mock::LayerFE> mLayerFE;
        LayerFECompositionState mLayerFEState;
    };

    OutputUpdateColorProfileTest() {
        mOutput.setDisplayColorProfileForTest(
                std::unique_ptr<DisplayColorProfile>(mDisplayColorProfile));
        mOutput.setRenderSurfaceForTest(std::unique_ptr<RenderSurface>(mRenderSurface));

        EXPECT_CALL(mOutput, getOutputLayerOrderedByZByIndex(0))
                .WillRepeatedly(Return(&mLayer1.mOutputLayer));
        EXPECT_CALL(mOutput, getOutputLayerOrderedByZByIndex(1))
                .WillRepeatedly(Return(&mLayer2.mOutputLayer));
        EXPECT_CALL(mOutput, getOutputLayerOrderedByZByIndex(2))
                .WillRepeatedly(Return(&mLayer3.mOutputLayer));
    }

    struct ExecuteState : public CallOrderStateMachineHelper<TestType, ExecuteState> {
        void execute() { getInstance()->mOutput.updateColorProfile(getInstance()->mRefreshArgs); }
    };

    mock::DisplayColorProfile* mDisplayColorProfile = new StrictMock<mock::DisplayColorProfile>();
    mock::RenderSurface* mRenderSurface = new StrictMock<mock::RenderSurface>();
    StrictMock<OutputPartialMock> mOutput;

    Layer mLayer1;
    Layer mLayer2;
    Layer mLayer3;

    CompositionRefreshArgs mRefreshArgs;
};

// TODO(b/144522012): Refactor Output::updateColorProfile and the related code
// to make it easier to write unit tests.

TEST_F(OutputUpdateColorProfileTest, setsAColorProfileWhenUnmanaged) {
    // When the outputColorSetting is set to kUnmanaged, the implementation sets
    // a simple default color profile without looking at anything else.

    EXPECT_CALL(mOutput, getOutputLayerCount()).WillRepeatedly(Return(3));
    EXPECT_CALL(mOutput,
                setColorProfile(ColorProfileEq(
                        ColorProfile{ui::ColorMode::NATIVE, ui::Dataspace::UNKNOWN,
                                     ui::RenderIntent::COLORIMETRIC, ui::Dataspace::UNKNOWN})));

    mRefreshArgs.outputColorSetting = OutputColorSetting::kUnmanaged;
    mRefreshArgs.colorSpaceAgnosticDataspace = ui::Dataspace::UNKNOWN;

    mOutput.updateColorProfile(mRefreshArgs);
}

struct OutputUpdateColorProfileTest_GetBestColorModeResultBecomesSetProfile
      : public OutputUpdateColorProfileTest {
    OutputUpdateColorProfileTest_GetBestColorModeResultBecomesSetProfile() {
        EXPECT_CALL(mOutput, getOutputLayerCount()).WillRepeatedly(Return(0));
        mRefreshArgs.outputColorSetting = OutputColorSetting::kEnhanced;
        mRefreshArgs.colorSpaceAgnosticDataspace = ui::Dataspace::UNKNOWN;
    }

    struct ExpectBestColorModeCallResultUsedToSetColorProfileState
          : public CallOrderStateMachineHelper<
                    TestType, ExpectBestColorModeCallResultUsedToSetColorProfileState> {
        [[nodiscard]] auto expectBestColorModeCallResultUsedToSetColorProfile(
                ui::ColorMode colorMode, ui::Dataspace dataspace, ui::RenderIntent renderIntent) {
            EXPECT_CALL(*getInstance()->mDisplayColorProfile,
                        getBestColorMode(ui::Dataspace::V0_SRGB, ui::RenderIntent::ENHANCE, _, _,
                                         _))
                    .WillOnce(DoAll(SetArgPointee<2>(dataspace), SetArgPointee<3>(colorMode),
                                    SetArgPointee<4>(renderIntent)));
            EXPECT_CALL(getInstance()->mOutput,
                        setColorProfile(
                                ColorProfileEq(ColorProfile{colorMode, dataspace, renderIntent,
                                                            ui::Dataspace::UNKNOWN})));
            return nextState<ExecuteState>();
        }
    };

    // Call this member function to start using the mini-DSL defined above.
    [[nodiscard]] auto verify() {
        return ExpectBestColorModeCallResultUsedToSetColorProfileState::make(this);
    }
};

TEST_F(OutputUpdateColorProfileTest_GetBestColorModeResultBecomesSetProfile,
       Native_Unknown_Colorimetric_Set) {
    verify().expectBestColorModeCallResultUsedToSetColorProfile(ui::ColorMode::NATIVE,
                                                                ui::Dataspace::UNKNOWN,
                                                                ui::RenderIntent::COLORIMETRIC)
            .execute();
}

TEST_F(OutputUpdateColorProfileTest_GetBestColorModeResultBecomesSetProfile,
       DisplayP3_DisplayP3_Enhance_Set) {
    verify().expectBestColorModeCallResultUsedToSetColorProfile(ui::ColorMode::DISPLAY_P3,
                                                                ui::Dataspace::DISPLAY_P3,
                                                                ui::RenderIntent::ENHANCE)
            .execute();
}

struct OutputUpdateColorProfileTest_ColorSpaceAgnosticeDataspaceAffectsSetColorProfile
      : public OutputUpdateColorProfileTest {
    OutputUpdateColorProfileTest_ColorSpaceAgnosticeDataspaceAffectsSetColorProfile() {
        EXPECT_CALL(mOutput, getOutputLayerCount()).WillRepeatedly(Return(0));
        EXPECT_CALL(*mDisplayColorProfile,
                    getBestColorMode(ui::Dataspace::V0_SRGB, ui::RenderIntent::ENHANCE, _, _, _))
                .WillRepeatedly(DoAll(SetArgPointee<2>(ui::Dataspace::UNKNOWN),
                                      SetArgPointee<3>(ui::ColorMode::NATIVE),
                                      SetArgPointee<4>(ui::RenderIntent::COLORIMETRIC)));
        mRefreshArgs.outputColorSetting = OutputColorSetting::kEnhanced;
    }

    struct IfColorSpaceAgnosticDataspaceSetToState
          : public CallOrderStateMachineHelper<TestType, IfColorSpaceAgnosticDataspaceSetToState> {
        [[nodiscard]] auto ifColorSpaceAgnosticDataspaceSetTo(ui::Dataspace dataspace) {
            getInstance()->mRefreshArgs.colorSpaceAgnosticDataspace = dataspace;
            return nextState<ThenExpectSetColorProfileCallUsesColorSpaceAgnosticDataspaceState>();
        }
    };

    struct ThenExpectSetColorProfileCallUsesColorSpaceAgnosticDataspaceState
          : public CallOrderStateMachineHelper<
                    TestType, ThenExpectSetColorProfileCallUsesColorSpaceAgnosticDataspaceState> {
        [[nodiscard]] auto thenExpectSetColorProfileCallUsesColorSpaceAgnosticDataspace(
                ui::Dataspace dataspace) {
            EXPECT_CALL(getInstance()->mOutput,
                        setColorProfile(ColorProfileEq(
                                ColorProfile{ui::ColorMode::NATIVE, ui::Dataspace::UNKNOWN,
                                             ui::RenderIntent::COLORIMETRIC, dataspace})));
            return nextState<ExecuteState>();
        }
    };

    // Call this member function to start using the mini-DSL defined above.
    [[nodiscard]] auto verify() { return IfColorSpaceAgnosticDataspaceSetToState::make(this); }
};

TEST_F(OutputUpdateColorProfileTest_ColorSpaceAgnosticeDataspaceAffectsSetColorProfile, DisplayP3) {
    verify().ifColorSpaceAgnosticDataspaceSetTo(ui::Dataspace::DISPLAY_P3)
            .thenExpectSetColorProfileCallUsesColorSpaceAgnosticDataspace(ui::Dataspace::DISPLAY_P3)
            .execute();
}

TEST_F(OutputUpdateColorProfileTest_ColorSpaceAgnosticeDataspaceAffectsSetColorProfile, V0_SRGB) {
    verify().ifColorSpaceAgnosticDataspaceSetTo(ui::Dataspace::V0_SRGB)
            .thenExpectSetColorProfileCallUsesColorSpaceAgnosticDataspace(ui::Dataspace::V0_SRGB)
            .execute();
}

struct OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference
      : public OutputUpdateColorProfileTest {
    // Internally the implementation looks through the dataspaces of all the
    // visible layers. The topmost one that also has an actual dataspace
    // preference set is used to drive subsequent choices.

    OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference() {
        mRefreshArgs.outputColorSetting = OutputColorSetting::kEnhanced;
        mRefreshArgs.colorSpaceAgnosticDataspace = ui::Dataspace::UNKNOWN;

        EXPECT_CALL(mOutput, getOutputLayerCount()).WillRepeatedly(Return(3));
        EXPECT_CALL(mOutput, setColorProfile(_)).WillRepeatedly(Return());
    }

    struct IfTopLayerDataspaceState
          : public CallOrderStateMachineHelper<TestType, IfTopLayerDataspaceState> {
        [[nodiscard]] auto ifTopLayerIs(ui::Dataspace dataspace) {
            getInstance()->mLayer3.mLayerFEState.dataspace = dataspace;
            return nextState<AndIfMiddleLayerDataspaceState>();
        }
        [[nodiscard]] auto ifTopLayerHasNoPreference() {
            return ifTopLayerIs(ui::Dataspace::UNKNOWN);
        }
    };

    struct AndIfMiddleLayerDataspaceState
          : public CallOrderStateMachineHelper<TestType, AndIfMiddleLayerDataspaceState> {
        [[nodiscard]] auto andIfMiddleLayerIs(ui::Dataspace dataspace) {
            getInstance()->mLayer2.mLayerFEState.dataspace = dataspace;
            return nextState<AndIfBottomLayerDataspaceState>();
        }
        [[nodiscard]] auto andIfMiddleLayerHasNoPreference() {
            return andIfMiddleLayerIs(ui::Dataspace::UNKNOWN);
        }
    };

    struct AndIfBottomLayerDataspaceState
          : public CallOrderStateMachineHelper<TestType, AndIfBottomLayerDataspaceState> {
        [[nodiscard]] auto andIfBottomLayerIs(ui::Dataspace dataspace) {
            getInstance()->mLayer1.mLayerFEState.dataspace = dataspace;
            return nextState<ThenExpectBestColorModeCallUsesState>();
        }
        [[nodiscard]] auto andIfBottomLayerHasNoPreference() {
            return andIfBottomLayerIs(ui::Dataspace::UNKNOWN);
        }
    };

    struct ThenExpectBestColorModeCallUsesState
          : public CallOrderStateMachineHelper<TestType, ThenExpectBestColorModeCallUsesState> {
        [[nodiscard]] auto thenExpectBestColorModeCallUses(ui::Dataspace dataspace) {
            EXPECT_CALL(*getInstance()->mDisplayColorProfile,
                        getBestColorMode(dataspace, _, _, _, _));
            return nextState<ExecuteState>();
        }
    };

    // Call this member function to start using the mini-DSL defined above.
    [[nodiscard]] auto verify() { return IfTopLayerDataspaceState::make(this); }
};

TEST_F(OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference,
       noStrongLayerPrefenceUses_V0_SRGB) {
    // If none of the layers indicate a preference, then V0_SRGB is the
    // preferred choice (subject to additional checks).
    verify().ifTopLayerHasNoPreference()
            .andIfMiddleLayerHasNoPreference()
            .andIfBottomLayerHasNoPreference()
            .thenExpectBestColorModeCallUses(ui::Dataspace::V0_SRGB)
            .execute();
}

TEST_F(OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference,
       ifTopmostUses_DisplayP3_Then_DisplayP3_Chosen) {
    // If only the topmost layer has a preference, then that is what is chosen.
    verify().ifTopLayerIs(ui::Dataspace::DISPLAY_P3)
            .andIfMiddleLayerHasNoPreference()
            .andIfBottomLayerHasNoPreference()
            .thenExpectBestColorModeCallUses(ui::Dataspace::DISPLAY_P3)
            .execute();
}

TEST_F(OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference,
       ifMiddleUses_DisplayP3_Then_DisplayP3_Chosen) {
    // If only the middle layer has a preference, that that is what is chosen.
    verify().ifTopLayerHasNoPreference()
            .andIfMiddleLayerIs(ui::Dataspace::DISPLAY_P3)
            .andIfBottomLayerHasNoPreference()
            .thenExpectBestColorModeCallUses(ui::Dataspace::DISPLAY_P3)
            .execute();
}

TEST_F(OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference,
       ifBottomUses_DisplayP3_Then_DisplayP3_Chosen) {
    // If only the middle layer has a preference, that that is what is chosen.
    verify().ifTopLayerHasNoPreference()
            .andIfMiddleLayerHasNoPreference()
            .andIfBottomLayerIs(ui::Dataspace::DISPLAY_P3)
            .thenExpectBestColorModeCallUses(ui::Dataspace::DISPLAY_P3)
            .execute();
}

TEST_F(OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference,
       ifTopUses_DisplayBT2020_AndBottomUses_DisplayP3_Then_DisplayBT2020_Chosen) {
    // If multiple layers have a preference, the topmost value is what is used.
    verify().ifTopLayerIs(ui::Dataspace::DISPLAY_BT2020)
            .andIfMiddleLayerHasNoPreference()
            .andIfBottomLayerIs(ui::Dataspace::DISPLAY_P3)
            .thenExpectBestColorModeCallUses(ui::Dataspace::DISPLAY_BT2020)
            .execute();
}

TEST_F(OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference,
       ifTopUses_DisplayP3_AndBottomUses_V0_SRGB_Then_DisplayP3_Chosen) {
    // If multiple layers have a preference, the topmost value is what is used.
    verify().ifTopLayerIs(ui::Dataspace::DISPLAY_P3)
            .andIfMiddleLayerHasNoPreference()
            .andIfBottomLayerIs(ui::Dataspace::DISPLAY_BT2020)
            .thenExpectBestColorModeCallUses(ui::Dataspace::DISPLAY_P3)
            .execute();
}

struct OutputUpdateColorProfileTest_ForceOutputColorOverrides
      : public OutputUpdateColorProfileTest {
    // If CompositionRefreshArgs::forceOutputColorMode is set to some specific
    // values, it overrides the layer dataspace choice.

    OutputUpdateColorProfileTest_ForceOutputColorOverrides() {
        mRefreshArgs.outputColorSetting = OutputColorSetting::kEnhanced;
        mRefreshArgs.colorSpaceAgnosticDataspace = ui::Dataspace::UNKNOWN;

        mLayer1.mLayerFEState.dataspace = ui::Dataspace::DISPLAY_BT2020;

        EXPECT_CALL(mOutput, getOutputLayerCount()).WillRepeatedly(Return(1));
        EXPECT_CALL(mOutput, setColorProfile(_)).WillRepeatedly(Return());
    }

    struct IfForceOutputColorModeState
          : public CallOrderStateMachineHelper<TestType, IfForceOutputColorModeState> {
        [[nodiscard]] auto ifForceOutputColorMode(ui::ColorMode colorMode) {
            getInstance()->mRefreshArgs.forceOutputColorMode = colorMode;
            return nextState<ThenExpectBestColorModeCallUsesState>();
        }
        [[nodiscard]] auto ifNoOverride() { return ifForceOutputColorMode(ui::ColorMode::NATIVE); }
    };

    struct ThenExpectBestColorModeCallUsesState
          : public CallOrderStateMachineHelper<TestType, ThenExpectBestColorModeCallUsesState> {
        [[nodiscard]] auto thenExpectBestColorModeCallUses(ui::Dataspace dataspace) {
            EXPECT_CALL(*getInstance()->mDisplayColorProfile,
                        getBestColorMode(dataspace, _, _, _, _));
            return nextState<ExecuteState>();
        }
    };

    // Call this member function to start using the mini-DSL defined above.
    [[nodiscard]] auto verify() { return IfForceOutputColorModeState::make(this); }
};

TEST_F(OutputUpdateColorProfileTest_ForceOutputColorOverrides, NoOverride_DoesNotOverride) {
    // By default the layer state is used to set the preferred dataspace
    verify().ifNoOverride()
            .thenExpectBestColorModeCallUses(ui::Dataspace::DISPLAY_BT2020)
            .execute();
}

TEST_F(OutputUpdateColorProfileTest_ForceOutputColorOverrides, SRGB_Override_USES_V0_SRGB) {
    // Setting ui::ColorMode::SRGB overrides it with ui::Dataspace::V0_SRGB
    verify().ifForceOutputColorMode(ui::ColorMode::SRGB)
            .thenExpectBestColorModeCallUses(ui::Dataspace::V0_SRGB)
            .execute();
}

TEST_F(OutputUpdateColorProfileTest_ForceOutputColorOverrides, DisplayP3_Override_Uses_DisplayP3) {
    // Setting ui::ColorMode::DISPLAY_P3 overrides it with ui::Dataspace::DISPLAY_P3
    verify().ifForceOutputColorMode(ui::ColorMode::DISPLAY_P3)
            .thenExpectBestColorModeCallUses(ui::Dataspace::DISPLAY_P3)
            .execute();
}

// HDR output requires all layers to be compatible with the chosen HDR
// dataspace, along with there being proper support.
struct OutputUpdateColorProfileTest_Hdr : public OutputUpdateColorProfileTest {
    OutputUpdateColorProfileTest_Hdr() {
        mRefreshArgs.outputColorSetting = OutputColorSetting::kEnhanced;
        mRefreshArgs.colorSpaceAgnosticDataspace = ui::Dataspace::UNKNOWN;
        EXPECT_CALL(mOutput, getOutputLayerCount()).WillRepeatedly(Return(2));
        EXPECT_CALL(mOutput, setColorProfile(_)).WillRepeatedly(Return());
    }

    static constexpr ui::Dataspace kNonHdrDataspace = ui::Dataspace::DISPLAY_P3;
    static constexpr ui::Dataspace BT2020_PQ = ui::Dataspace::BT2020_PQ;
    static constexpr ui::Dataspace BT2020_HLG = ui::Dataspace::BT2020_HLG;
    static constexpr ui::Dataspace DISPLAY_P3 = ui::Dataspace::DISPLAY_P3;

    struct IfTopLayerDataspaceState
          : public CallOrderStateMachineHelper<TestType, IfTopLayerDataspaceState> {
        [[nodiscard]] auto ifTopLayerIs(ui::Dataspace dataspace) {
            getInstance()->mLayer2.mLayerFEState.dataspace = dataspace;
            return nextState<AndTopLayerCompositionTypeState>();
        }
        [[nodiscard]] auto ifTopLayerIsNotHdr() { return ifTopLayerIs(kNonHdrDataspace); }
    };

    struct AndTopLayerCompositionTypeState
          : public CallOrderStateMachineHelper<TestType, AndTopLayerCompositionTypeState> {
        [[nodiscard]] auto andTopLayerIsREComposed(bool renderEngineComposed) {
            getInstance()->mLayer2.mLayerFEState.forceClientComposition = renderEngineComposed;
            return nextState<AndIfBottomLayerDataspaceState>();
        }
    };

    struct AndIfBottomLayerDataspaceState
          : public CallOrderStateMachineHelper<TestType, AndIfBottomLayerDataspaceState> {
        [[nodiscard]] auto andIfBottomLayerIs(ui::Dataspace dataspace) {
            getInstance()->mLayer1.mLayerFEState.dataspace = dataspace;
            return nextState<AndBottomLayerCompositionTypeState>();
        }
        [[nodiscard]] auto andIfBottomLayerIsNotHdr() {
            return andIfBottomLayerIs(kNonHdrDataspace);
        }
    };

    struct AndBottomLayerCompositionTypeState
          : public CallOrderStateMachineHelper<TestType, AndBottomLayerCompositionTypeState> {
        [[nodiscard]] auto andBottomLayerIsREComposed(bool renderEngineComposed) {
            getInstance()->mLayer1.mLayerFEState.forceClientComposition = renderEngineComposed;
            return nextState<AndIfHasLegacySupportState>();
        }
    };

    struct AndIfHasLegacySupportState
          : public CallOrderStateMachineHelper<TestType, AndIfHasLegacySupportState> {
        [[nodiscard]] auto andIfLegacySupportFor(ui::Dataspace dataspace, bool legacySupport) {
            EXPECT_CALL(*getInstance()->mDisplayColorProfile, hasLegacyHdrSupport(dataspace))
                    .WillOnce(Return(legacySupport));
            return nextState<ThenExpectBestColorModeCallUsesState>();
        }
    };

    struct ThenExpectBestColorModeCallUsesState
          : public CallOrderStateMachineHelper<TestType, ThenExpectBestColorModeCallUsesState> {
        [[nodiscard]] auto thenExpectBestColorModeCallUses(ui::Dataspace dataspace) {
            EXPECT_CALL(*getInstance()->mDisplayColorProfile,
                        getBestColorMode(dataspace, _, _, _, _));
            return nextState<ExecuteState>();
        }
    };

    // Call this member function to start using the mini-DSL defined above.
    [[nodiscard]] auto verify() { return IfTopLayerDataspaceState::make(this); }
};

TEST_F(OutputUpdateColorProfileTest_Hdr, PQ_HW_On_PQ_HW_Uses_PQ) {
    // If all layers use BT2020_PQ, and there are no other special conditions,
    // BT2020_PQ is used.
    verify().ifTopLayerIs(BT2020_PQ)
            .andTopLayerIsREComposed(false)
            .andIfBottomLayerIs(BT2020_PQ)
            .andBottomLayerIsREComposed(false)
            .andIfLegacySupportFor(BT2020_PQ, false)
            .thenExpectBestColorModeCallUses(BT2020_PQ)
            .execute();
}

TEST_F(OutputUpdateColorProfileTest_Hdr, PQ_HW_On_PQ_HW_IfPQHasLegacySupport_Uses_DisplayP3) {
    // BT2020_PQ is not used if there is only legacy support for it.
    verify().ifTopLayerIs(BT2020_PQ)
            .andTopLayerIsREComposed(false)
            .andIfBottomLayerIs(BT2020_PQ)
            .andBottomLayerIsREComposed(false)
            .andIfLegacySupportFor(BT2020_PQ, true)
            .thenExpectBestColorModeCallUses(DISPLAY_P3)
            .execute();
}

TEST_F(OutputUpdateColorProfileTest_Hdr, PQ_HW_On_PQ_RE_Uses_PQ) {
    // BT2020_PQ is still used if the bottom layer is RenderEngine composed.
    verify().ifTopLayerIs(BT2020_PQ)
            .andTopLayerIsREComposed(false)
            .andIfBottomLayerIs(BT2020_PQ)
            .andBottomLayerIsREComposed(true)
            .andIfLegacySupportFor(BT2020_PQ, false)
            .thenExpectBestColorModeCallUses(BT2020_PQ)
            .execute();
}

TEST_F(OutputUpdateColorProfileTest_Hdr, PQ_RE_On_PQ_HW_Uses_DisplayP3) {
    // BT2020_PQ is not used if the top layer is RenderEngine composed.
    verify().ifTopLayerIs(BT2020_PQ)
            .andTopLayerIsREComposed(true)
            .andIfBottomLayerIs(BT2020_PQ)
            .andBottomLayerIsREComposed(false)
            .andIfLegacySupportFor(BT2020_PQ, false)
            .thenExpectBestColorModeCallUses(DISPLAY_P3)
            .execute();
}

TEST_F(OutputUpdateColorProfileTest_Hdr, PQ_HW_On_HLG_HW_Uses_PQ) {
    // If there is mixed HLG/PQ use, and the topmost layer is PQ, then PQ is used if there
    // are no other special conditions.
    verify().ifTopLayerIs(BT2020_PQ)
            .andTopLayerIsREComposed(false)
            .andIfBottomLayerIs(BT2020_HLG)
            .andBottomLayerIsREComposed(false)
            .andIfLegacySupportFor(BT2020_PQ, false)
            .thenExpectBestColorModeCallUses(BT2020_PQ)
            .execute();
}

TEST_F(OutputUpdateColorProfileTest_Hdr, PQ_HW_On_HLG_HW_IfPQHasLegacySupport_Uses_DisplayP3) {
    // BT2020_PQ is not used if there is only legacy support for it.
    verify().ifTopLayerIs(BT2020_PQ)
            .andTopLayerIsREComposed(false)
            .andIfBottomLayerIs(BT2020_HLG)
            .andBottomLayerIsREComposed(false)
            .andIfLegacySupportFor(BT2020_PQ, true)
            .thenExpectBestColorModeCallUses(DISPLAY_P3)
            .execute();
}

TEST_F(OutputUpdateColorProfileTest_Hdr, PQ_HW_On_HLG_RE_Uses_PQ) {
    // BT2020_PQ is used if the bottom HLG layer is RenderEngine composed.
    verify().ifTopLayerIs(BT2020_PQ)
            .andTopLayerIsREComposed(false)
            .andIfBottomLayerIs(BT2020_HLG)
            .andBottomLayerIsREComposed(true)
            .andIfLegacySupportFor(BT2020_PQ, false)
            .thenExpectBestColorModeCallUses(BT2020_PQ)
            .execute();
}

TEST_F(OutputUpdateColorProfileTest_Hdr, PQ_RE_On_HLG_HW_Uses_DisplayP3) {
    // BT2020_PQ is not used if the top PQ layer is RenderEngine composed.
    verify().ifTopLayerIs(BT2020_PQ)
            .andTopLayerIsREComposed(true)
            .andIfBottomLayerIs(BT2020_HLG)
            .andBottomLayerIsREComposed(false)
            .andIfLegacySupportFor(BT2020_PQ, false)
            .thenExpectBestColorModeCallUses(DISPLAY_P3)
            .execute();
}

TEST_F(OutputUpdateColorProfileTest_Hdr, HLG_HW_On_PQ_HW_Uses_PQ) {
    // If there is mixed HLG/PQ use, and the topmost layer is HLG, then PQ is
    // used if there are no other special conditions.
    verify().ifTopLayerIs(BT2020_HLG)
            .andTopLayerIsREComposed(false)
            .andIfBottomLayerIs(BT2020_PQ)
            .andBottomLayerIsREComposed(false)
            .andIfLegacySupportFor(BT2020_PQ, false)
            .thenExpectBestColorModeCallUses(BT2020_PQ)
            .execute();
}

TEST_F(OutputUpdateColorProfileTest_Hdr, HLG_HW_On_PQ_HW_IfPQHasLegacySupport_Uses_DisplayP3) {
    // BT2020_PQ is not used if there is only legacy support for it.
    verify().ifTopLayerIs(BT2020_HLG)
            .andTopLayerIsREComposed(false)
            .andIfBottomLayerIs(BT2020_PQ)
            .andBottomLayerIsREComposed(false)
            .andIfLegacySupportFor(BT2020_PQ, true)
            .thenExpectBestColorModeCallUses(DISPLAY_P3)
            .execute();
}

TEST_F(OutputUpdateColorProfileTest_Hdr, HLG_HW_On_PQ_RE_Uses_DisplayP3) {
    // BT2020_PQ is not used if the bottom PQ layer is RenderEngine composed.
    verify().ifTopLayerIs(BT2020_HLG)
            .andTopLayerIsREComposed(false)
            .andIfBottomLayerIs(BT2020_PQ)
            .andBottomLayerIsREComposed(true)
            .andIfLegacySupportFor(BT2020_PQ, false)
            .thenExpectBestColorModeCallUses(DISPLAY_P3)
            .execute();
}

TEST_F(OutputUpdateColorProfileTest_Hdr, HLG_RE_On_PQ_HW_Uses_PQ) {
    // BT2020_PQ is still used if the top HLG layer is RenderEngine composed.
    verify().ifTopLayerIs(BT2020_HLG)
            .andTopLayerIsREComposed(true)
            .andIfBottomLayerIs(BT2020_PQ)
            .andBottomLayerIsREComposed(false)
            .andIfLegacySupportFor(BT2020_PQ, false)
            .thenExpectBestColorModeCallUses(BT2020_PQ)
            .execute();
}

TEST_F(OutputUpdateColorProfileTest_Hdr, HLG_HW_On_HLG_HW_Uses_HLG) {
    // If all layers use HLG then HLG is used if there are no other special
    // conditions.
    verify().ifTopLayerIs(BT2020_HLG)
            .andTopLayerIsREComposed(false)
            .andIfBottomLayerIs(BT2020_HLG)
            .andBottomLayerIsREComposed(false)
            .andIfLegacySupportFor(BT2020_HLG, false)
            .thenExpectBestColorModeCallUses(BT2020_HLG)
            .execute();
}

TEST_F(OutputUpdateColorProfileTest_Hdr, HLG_HW_On_HLG_HW_IfPQHasLegacySupport_Uses_DisplayP3) {
    // BT2020_HLG is not used if there is legacy support for it.
    verify().ifTopLayerIs(BT2020_HLG)
            .andTopLayerIsREComposed(false)
            .andIfBottomLayerIs(BT2020_HLG)
            .andBottomLayerIsREComposed(false)
            .andIfLegacySupportFor(BT2020_HLG, true)
            .thenExpectBestColorModeCallUses(DISPLAY_P3)
            .execute();
}

TEST_F(OutputUpdateColorProfileTest_Hdr, HLG_HW_On_HLG_RE_Uses_HLG) {
    // BT2020_HLG is used even if the bottom layer is client composed.
    verify().ifTopLayerIs(BT2020_HLG)
            .andTopLayerIsREComposed(false)
            .andIfBottomLayerIs(BT2020_HLG)
            .andBottomLayerIsREComposed(true)
            .andIfLegacySupportFor(BT2020_HLG, false)
            .thenExpectBestColorModeCallUses(BT2020_HLG)
            .execute();
}

TEST_F(OutputUpdateColorProfileTest_Hdr, HLG_RE_On_HLG_HW_Uses_HLG) {
    // BT2020_HLG is used even if the top layer is client composed.
    verify().ifTopLayerIs(BT2020_HLG)
            .andTopLayerIsREComposed(true)
            .andIfBottomLayerIs(BT2020_HLG)
            .andBottomLayerIsREComposed(false)
            .andIfLegacySupportFor(BT2020_HLG, false)
            .thenExpectBestColorModeCallUses(BT2020_HLG)
            .execute();
}

TEST_F(OutputUpdateColorProfileTest_Hdr, PQ_HW_On_NonHdr_HW_Uses_PQ) {
    // Even if there are non-HDR layers present, BT2020_PQ can still be used.
    verify().ifTopLayerIs(BT2020_PQ)
            .andTopLayerIsREComposed(false)
            .andIfBottomLayerIsNotHdr()
            .andBottomLayerIsREComposed(false)
            .andIfLegacySupportFor(BT2020_PQ, false)
            .thenExpectBestColorModeCallUses(BT2020_PQ)
            .execute();
}

TEST_F(OutputUpdateColorProfileTest_Hdr, HLG_HW_On_NonHdr_RE_Uses_HLG) {
    // If all layers use HLG then HLG is used if there are no other special
    // conditions.
    verify().ifTopLayerIs(BT2020_HLG)
            .andTopLayerIsREComposed(false)
            .andIfBottomLayerIsNotHdr()
            .andBottomLayerIsREComposed(true)
            .andIfLegacySupportFor(BT2020_HLG, false)
            .thenExpectBestColorModeCallUses(BT2020_HLG)
            .execute();
}

struct OutputUpdateColorProfile_AffectsChosenRenderIntentTest
      : public OutputUpdateColorProfileTest {
    // The various values for CompositionRefreshArgs::outputColorSetting affect
    // the chosen renderIntent, along with whether the preferred dataspace is an
    // HDR dataspace or not.

    OutputUpdateColorProfile_AffectsChosenRenderIntentTest() {
        mRefreshArgs.outputColorSetting = OutputColorSetting::kEnhanced;
        mRefreshArgs.colorSpaceAgnosticDataspace = ui::Dataspace::UNKNOWN;
        mLayer1.mLayerFEState.dataspace = ui::Dataspace::BT2020_PQ;
        EXPECT_CALL(mOutput, getOutputLayerCount()).WillRepeatedly(Return(1));
        EXPECT_CALL(mOutput, setColorProfile(_)).WillRepeatedly(Return());
        EXPECT_CALL(*mDisplayColorProfile, hasLegacyHdrSupport(ui::Dataspace::BT2020_PQ))
                .WillRepeatedly(Return(false));
    }

    // The tests here involve enough state and GMock setup that using a mini-DSL
    // makes the tests much more readable, and allows the test to focus more on
    // the intent than on some of the details.

    static constexpr ui::Dataspace kNonHdrDataspace = ui::Dataspace::DISPLAY_P3;
    static constexpr ui::Dataspace kHdrDataspace = ui::Dataspace::BT2020_PQ;

    struct IfDataspaceChosenState
          : public CallOrderStateMachineHelper<TestType, IfDataspaceChosenState> {
        [[nodiscard]] auto ifDataspaceChosenIs(ui::Dataspace dataspace) {
            getInstance()->mLayer1.mLayerFEState.dataspace = dataspace;
            return nextState<AndOutputColorSettingState>();
        }
        [[nodiscard]] auto ifDataspaceChosenIsNonHdr() {
            return ifDataspaceChosenIs(kNonHdrDataspace);
        }
        [[nodiscard]] auto ifDataspaceChosenIsHdr() { return ifDataspaceChosenIs(kHdrDataspace); }
    };

    struct AndOutputColorSettingState
          : public CallOrderStateMachineHelper<TestType, AndOutputColorSettingState> {
        [[nodiscard]] auto andOutputColorSettingIs(OutputColorSetting setting) {
            getInstance()->mRefreshArgs.outputColorSetting = setting;
            return nextState<ThenExpectBestColorModeCallUsesState>();
        }
    };

    struct ThenExpectBestColorModeCallUsesState
          : public CallOrderStateMachineHelper<TestType, ThenExpectBestColorModeCallUsesState> {
        [[nodiscard]] auto thenExpectBestColorModeCallUses(ui::RenderIntent intent) {
            EXPECT_CALL(*getInstance()->mDisplayColorProfile,
                        getBestColorMode(getInstance()->mLayer1.mLayerFEState.dataspace, intent, _,
                                         _, _));
            return nextState<ExecuteState>();
        }
    };

    // Tests call one of these two helper member functions to start using the
    // mini-DSL defined above.
    [[nodiscard]] auto verify() { return IfDataspaceChosenState::make(this); }
};

TEST_F(OutputUpdateColorProfile_AffectsChosenRenderIntentTest,
       Managed_NonHdr_Prefers_Colorimetric) {
    verify().ifDataspaceChosenIsNonHdr()
            .andOutputColorSettingIs(OutputColorSetting::kManaged)
            .thenExpectBestColorModeCallUses(ui::RenderIntent::COLORIMETRIC)
            .execute();
}

TEST_F(OutputUpdateColorProfile_AffectsChosenRenderIntentTest,
       Managed_Hdr_Prefers_ToneMapColorimetric) {
    verify().ifDataspaceChosenIsHdr()
            .andOutputColorSettingIs(OutputColorSetting::kManaged)
            .thenExpectBestColorModeCallUses(ui::RenderIntent::TONE_MAP_COLORIMETRIC)
            .execute();
}

TEST_F(OutputUpdateColorProfile_AffectsChosenRenderIntentTest, Enhanced_NonHdr_Prefers_Enhance) {
    verify().ifDataspaceChosenIsNonHdr()
            .andOutputColorSettingIs(OutputColorSetting::kEnhanced)
            .thenExpectBestColorModeCallUses(ui::RenderIntent::ENHANCE)
            .execute();
}

TEST_F(OutputUpdateColorProfile_AffectsChosenRenderIntentTest,
       Enhanced_Hdr_Prefers_ToneMapEnhance) {
    verify().ifDataspaceChosenIsHdr()
            .andOutputColorSettingIs(OutputColorSetting::kEnhanced)
            .thenExpectBestColorModeCallUses(ui::RenderIntent::TONE_MAP_ENHANCE)
            .execute();
}

TEST_F(OutputUpdateColorProfile_AffectsChosenRenderIntentTest, Vendor_NonHdr_Prefers_Vendor) {
    verify().ifDataspaceChosenIsNonHdr()
            .andOutputColorSettingIs(kVendorSpecifiedOutputColorSetting)
            .thenExpectBestColorModeCallUses(
                    static_cast<ui::RenderIntent>(kVendorSpecifiedOutputColorSetting))
            .execute();
}

TEST_F(OutputUpdateColorProfile_AffectsChosenRenderIntentTest, Vendor_Hdr_Prefers_Vendor) {
    verify().ifDataspaceChosenIsHdr()
            .andOutputColorSettingIs(kVendorSpecifiedOutputColorSetting)
            .thenExpectBestColorModeCallUses(
                    static_cast<ui::RenderIntent>(kVendorSpecifiedOutputColorSetting))
            .execute();
}

/*
 * Output::beginFrame()
 */

/*
 * Output::devOptRepaintFlash()
 */

struct OutputDevOptRepaintFlashTest : public testing::Test {
    struct OutputPartialMock : public OutputPartialMockBase {
        // Sets up the helper functions called by composeSurfaces to use a mock
        // implementations.
        MOCK_CONST_METHOD1(getDirtyRegion, Region(bool));
        MOCK_METHOD1(composeSurfaces, std::optional<base::unique_fd>(const Region&));
        MOCK_METHOD0(postFramebuffer, void());
        MOCK_METHOD0(prepareFrame, void());
    };

    OutputDevOptRepaintFlashTest() {
        mOutput.setDisplayColorProfileForTest(
                std::unique_ptr<DisplayColorProfile>(mDisplayColorProfile));
        mOutput.setRenderSurfaceForTest(std::unique_ptr<RenderSurface>(mRenderSurface));
    }

    static const Region kEmptyRegion;
    static const Region kNotEmptyRegion;

    StrictMock<OutputPartialMock> mOutput;
    mock::DisplayColorProfile* mDisplayColorProfile = new StrictMock<mock::DisplayColorProfile>();
    mock::RenderSurface* mRenderSurface = new StrictMock<mock::RenderSurface>();
    CompositionRefreshArgs mRefreshArgs;
};

const Region OutputDevOptRepaintFlashTest::kEmptyRegion{Rect{0, 0, 0, 0}};
const Region OutputDevOptRepaintFlashTest::kNotEmptyRegion{Rect{0, 0, 1, 1}};

TEST_F(OutputDevOptRepaintFlashTest, doesNothingIfFlashDelayNotSet) {
    mRefreshArgs.devOptFlashDirtyRegionsDelay = {};
    mRefreshArgs.repaintEverything = true;
    mOutput.mState.isEnabled = true;

    mOutput.devOptRepaintFlash(mRefreshArgs);
}

TEST_F(OutputDevOptRepaintFlashTest, postsAndPreparesANewFrameIfNotEnabled) {
    mRefreshArgs.devOptFlashDirtyRegionsDelay = std::chrono::microseconds(1);
    mRefreshArgs.repaintEverything = true;
    mOutput.mState.isEnabled = false;

    InSequence seq;
    EXPECT_CALL(mOutput, postFramebuffer());
    EXPECT_CALL(mOutput, prepareFrame());

    mOutput.devOptRepaintFlash(mRefreshArgs);
}

TEST_F(OutputDevOptRepaintFlashTest, postsAndPreparesANewFrameIfNotDirty) {
    mRefreshArgs.devOptFlashDirtyRegionsDelay = std::chrono::microseconds(1);
    mRefreshArgs.repaintEverything = true;
    mOutput.mState.isEnabled = true;

    InSequence seq;
    EXPECT_CALL(mOutput, getDirtyRegion(true)).WillOnce(Return(kEmptyRegion));
    EXPECT_CALL(mOutput, postFramebuffer());
    EXPECT_CALL(mOutput, prepareFrame());

    mOutput.devOptRepaintFlash(mRefreshArgs);
}

TEST_F(OutputDevOptRepaintFlashTest, alsoComposesSurfacesAndQueuesABufferIfDirty) {
    mRefreshArgs.devOptFlashDirtyRegionsDelay = std::chrono::microseconds(1);
    mRefreshArgs.repaintEverything = false;
    mOutput.mState.isEnabled = true;

    InSequence seq;
    EXPECT_CALL(mOutput, getDirtyRegion(false)).WillOnce(Return(kNotEmptyRegion));
    EXPECT_CALL(mOutput, composeSurfaces(RegionEq(kNotEmptyRegion)));
    EXPECT_CALL(*mRenderSurface, queueBuffer(_));
    EXPECT_CALL(mOutput, postFramebuffer());
    EXPECT_CALL(mOutput, prepareFrame());

    mOutput.devOptRepaintFlash(mRefreshArgs);
}

// TODO(b/144060211) - Add coverage

/*
 * Output::finishFrame()
 */

struct OutputFinishFrameTest : public testing::Test {
    struct OutputPartialMock : public OutputPartialMockBase {
        // Sets up the helper functions called by composeSurfaces to use a mock
        // implementations.
        MOCK_METHOD1(composeSurfaces, std::optional<base::unique_fd>(const Region&));
        MOCK_METHOD0(postFramebuffer, void());
    };

    OutputFinishFrameTest() {
        mOutput.setDisplayColorProfileForTest(
                std::unique_ptr<DisplayColorProfile>(mDisplayColorProfile));
        mOutput.setRenderSurfaceForTest(std::unique_ptr<RenderSurface>(mRenderSurface));
    }

    StrictMock<OutputPartialMock> mOutput;
    mock::DisplayColorProfile* mDisplayColorProfile = new StrictMock<mock::DisplayColorProfile>();
    mock::RenderSurface* mRenderSurface = new StrictMock<mock::RenderSurface>();
    CompositionRefreshArgs mRefreshArgs;
};

TEST_F(OutputFinishFrameTest, ifNotEnabledDoesNothing) {
    mOutput.mState.isEnabled = false;

    mOutput.finishFrame(mRefreshArgs);
}

TEST_F(OutputFinishFrameTest, takesEarlyOutifComposeSurfacesReturnsNoFence) {
    mOutput.mState.isEnabled = true;

    InSequence seq;
    EXPECT_CALL(mOutput, composeSurfaces(RegionEq(Region::INVALID_REGION)));

    mOutput.finishFrame(mRefreshArgs);
}

TEST_F(OutputFinishFrameTest, queuesBufferIfComposeSurfacesReturnsAFence) {
    mOutput.mState.isEnabled = true;

    InSequence seq;
    EXPECT_CALL(mOutput, composeSurfaces(RegionEq(Region::INVALID_REGION)))
            .WillOnce(Return(ByMove(base::unique_fd())));
    EXPECT_CALL(*mRenderSurface, queueBuffer(_));

    mOutput.finishFrame(mRefreshArgs);
}

/*
 * Output::postFramebuffer()
 */

// TODO(b/144060211) - Add coverage

/*
 * Output::composeSurfaces()
 */

struct OutputComposeSurfacesTest : public testing::Test {
    static constexpr uint32_t kDefaultOutputOrientation = TR_IDENT;
    static constexpr ui::Dataspace kDefaultOutputDataspace = ui::Dataspace::DISPLAY_P3;

    static const Rect kDefaultOutputFrame;
    static const Rect kDefaultOutputViewport;
    static const Rect kDefaultOutputScissor;
    static const mat4 kDefaultColorTransformMat;

    struct OutputPartialMock : public OutputPartialMockBase {
        // Sets up the helper functions called by composeSurfaces to use a mock
        // implementations.
        MOCK_CONST_METHOD0(getSkipColorTransform, bool());
        MOCK_METHOD2(generateClientCompositionRequests,
                     std::vector<renderengine::LayerSettings>(bool, Region&));
        MOCK_METHOD2(appendRegionFlashRequests,
                     void(const Region&, std::vector<renderengine::LayerSettings>&));
        MOCK_METHOD1(setExpensiveRenderingExpected, void(bool));
    };

    OutputComposeSurfacesTest() {
        mOutput.setDisplayColorProfileForTest(
                std::unique_ptr<DisplayColorProfile>(mDisplayColorProfile));
        mOutput.setRenderSurfaceForTest(std::unique_ptr<RenderSurface>(mRenderSurface));

        mOutput.editState().frame = kDefaultOutputFrame;
        mOutput.editState().viewport = kDefaultOutputViewport;
        mOutput.editState().scissor = kDefaultOutputScissor;
        mOutput.editState().transform = ui::Transform{kDefaultOutputOrientation};
        mOutput.editState().orientation = kDefaultOutputOrientation;
        mOutput.editState().dataspace = kDefaultOutputDataspace;
        mOutput.editState().colorTransformMatrix = kDefaultColorTransformMat;
        mOutput.editState().isSecure = true;
        mOutput.editState().needsFiltering = false;
        mOutput.editState().usesClientComposition = true;
        mOutput.editState().usesDeviceComposition = false;

        EXPECT_CALL(mOutput, getOutputLayerCount()).WillRepeatedly(Return(2u));
        EXPECT_CALL(mOutput, getOutputLayerOrderedByZByIndex(0u))
                .WillRepeatedly(Return(&mOutputLayer1));
        EXPECT_CALL(mOutput, getOutputLayerOrderedByZByIndex(1u))
                .WillRepeatedly(Return(&mOutputLayer2));
        EXPECT_CALL(mOutput, getCompositionEngine()).WillRepeatedly(ReturnRef(mCompositionEngine));
        EXPECT_CALL(mCompositionEngine, getRenderEngine()).WillRepeatedly(ReturnRef(mRenderEngine));
    }

    StrictMock<mock::CompositionEngine> mCompositionEngine;
    StrictMock<renderengine::mock::RenderEngine> mRenderEngine;
    mock::DisplayColorProfile* mDisplayColorProfile = new StrictMock<mock::DisplayColorProfile>();
    mock::RenderSurface* mRenderSurface = new StrictMock<mock::RenderSurface>();
    StrictMock<mock::OutputLayer> mOutputLayer1;
    StrictMock<mock::OutputLayer> mOutputLayer2;
    StrictMock<OutputPartialMock> mOutput;
    sp<GraphicBuffer> mOutputBuffer = new GraphicBuffer();
};

const Rect OutputComposeSurfacesTest::kDefaultOutputFrame{1001, 1002, 1003, 1004};
const Rect OutputComposeSurfacesTest::kDefaultOutputViewport{1005, 1006, 1007, 1008};
const Rect OutputComposeSurfacesTest::kDefaultOutputScissor{1009, 1010, 1011, 1012};
const mat4 OutputComposeSurfacesTest::kDefaultColorTransformMat{mat4() * 0.5};

// TODO(b/121291683): Expand unit test coverage for composeSurfaces beyond these
// basic tests.

TEST_F(OutputComposeSurfacesTest, doesNothingIfNoClientComposition) {
    mOutput.editState().usesClientComposition = false;

    Region debugRegion;
    std::optional<base::unique_fd> readyFence = mOutput.composeSurfaces(debugRegion);
    EXPECT_TRUE(readyFence);
}

TEST_F(OutputComposeSurfacesTest, worksIfNoClientLayersQueued) {
    const Region kDebugRegion{Rect{100, 101, 102, 103}};

    constexpr float kDefaultMaxLuminance = 1.0f;
    constexpr float kDefaultAvgLuminance = 0.7f;
    constexpr float kDefaultMinLuminance = 0.1f;
    HdrCapabilities HdrCapabilities{{},
                                    kDefaultMaxLuminance,
                                    kDefaultAvgLuminance,
                                    kDefaultMinLuminance};

    EXPECT_CALL(mRenderEngine, supportsProtectedContent()).WillOnce(Return(false));
    EXPECT_CALL(mRenderEngine, drawLayers(_, _, _, true, _, _)).Times(1);

    EXPECT_CALL(*mDisplayColorProfile, hasWideColorGamut()).WillOnce(Return(true));
    EXPECT_CALL(*mDisplayColorProfile, getHdrCapabilities()).WillOnce(ReturnRef(HdrCapabilities));

    EXPECT_CALL(*mRenderSurface, dequeueBuffer(_)).WillOnce(Return(mOutputBuffer));

    EXPECT_CALL(mOutput, getSkipColorTransform()).WillOnce(Return(false));
    EXPECT_CALL(mOutput, generateClientCompositionRequests(false, _)).Times(1);
    EXPECT_CALL(mOutput, appendRegionFlashRequests(RegionEq(kDebugRegion), _)).Times(1);
    EXPECT_CALL(mOutput, setExpensiveRenderingExpected(true)).Times(1);
    EXPECT_CALL(mOutput, setExpensiveRenderingExpected(false)).Times(1);

    std::optional<base::unique_fd> readyFence = mOutput.composeSurfaces(kDebugRegion);
    EXPECT_TRUE(readyFence);
}

/*
 * Output::generateClientCompositionRequests()
 */

struct GenerateClientCompositionRequestsTest : public testing::Test {
    struct OutputPartialMock : public OutputPartialMockBase {
        // compositionengine::Output overrides
        std::vector<renderengine::LayerSettings> generateClientCompositionRequests(
                bool supportsProtectedContent, Region& clearRegion) override {
            return impl::Output::generateClientCompositionRequests(supportsProtectedContent,
                                                                   clearRegion);
        }
    };

    GenerateClientCompositionRequestsTest() {
        mOutput.setDisplayColorProfileForTest(
                std::unique_ptr<DisplayColorProfile>(mDisplayColorProfile));
        mOutput.setRenderSurfaceForTest(std::unique_ptr<RenderSurface>(mRenderSurface));
    }

    mock::DisplayColorProfile* mDisplayColorProfile = new StrictMock<mock::DisplayColorProfile>();
    mock::RenderSurface* mRenderSurface = new StrictMock<mock::RenderSurface>();
    StrictMock<OutputPartialMock> mOutput;
};

// TODO(b/121291683): Add more unit test coverage for generateClientCompositionRequests

TEST_F(GenerateClientCompositionRequestsTest, worksForLandscapeModeSplitScreen) {
    // In split-screen landscape mode, the screen is rotated 90 degrees, with
    // one layer on the left covering the left side of the output, and one layer
    // on the right covering that side of the output.

    StrictMock<mock::OutputLayer> leftOutputLayer;
    StrictMock<mock::OutputLayer> rightOutputLayer;

    StrictMock<mock::Layer> leftLayer;
    StrictMock<mock::LayerFE> leftLayerFE;
    StrictMock<mock::Layer> rightLayer;
    StrictMock<mock::LayerFE> rightLayerFE;

    impl::OutputLayerCompositionState leftOutputLayerState;
    leftOutputLayerState.clearClientTarget = false;
    leftOutputLayerState.visibleRegion = Region{Rect{0, 0, 1000, 1000}};

    LayerFECompositionState leftLayerFEState;
    leftLayerFEState.isOpaque = true;

    const half3 leftLayerColor{1.f, 0.f, 0.f};
    renderengine::LayerSettings leftLayerRESettings;
    leftLayerRESettings.source.solidColor = leftLayerColor;

    impl::OutputLayerCompositionState rightOutputLayerState;
    rightOutputLayerState.clearClientTarget = false;
    rightOutputLayerState.visibleRegion = Region{Rect{1000, 0, 2000, 1000}};

    LayerFECompositionState rightLayerFEState;
    rightLayerFEState.isOpaque = true;

    const half3 rightLayerColor{0.f, 1.f, 0.f};
    renderengine::LayerSettings rightLayerRESettings;
    rightLayerRESettings.source.solidColor = rightLayerColor;

    EXPECT_CALL(leftOutputLayer, getState()).WillRepeatedly(ReturnRef(leftOutputLayerState));
    EXPECT_CALL(leftOutputLayer, getLayer()).WillRepeatedly(ReturnRef(leftLayer));
    EXPECT_CALL(leftOutputLayer, getLayerFE()).WillRepeatedly(ReturnRef(leftLayerFE));
    EXPECT_CALL(leftOutputLayer, requiresClientComposition()).WillRepeatedly(Return(true));
    EXPECT_CALL(leftOutputLayer, needsFiltering()).WillRepeatedly(Return(false));
    EXPECT_CALL(leftLayer, getFEState()).WillRepeatedly(ReturnRef(leftLayerFEState));
    EXPECT_CALL(leftLayerFE, prepareClientComposition(_)).WillOnce(Return(leftLayerRESettings));
    EXPECT_CALL(leftOutputLayer, editState()).WillRepeatedly(ReturnRef(leftOutputLayerState));

    EXPECT_CALL(rightOutputLayer, getState()).WillRepeatedly(ReturnRef(rightOutputLayerState));
    EXPECT_CALL(rightOutputLayer, getLayer()).WillRepeatedly(ReturnRef(rightLayer));
    EXPECT_CALL(rightOutputLayer, getLayerFE()).WillRepeatedly(ReturnRef(rightLayerFE));
    EXPECT_CALL(rightOutputLayer, requiresClientComposition()).WillRepeatedly(Return(true));
    EXPECT_CALL(rightOutputLayer, needsFiltering()).WillRepeatedly(Return(false));
    EXPECT_CALL(rightLayer, getFEState()).WillRepeatedly(ReturnRef(rightLayerFEState));
    EXPECT_CALL(rightLayerFE, prepareClientComposition(_)).WillOnce(Return(rightLayerRESettings));
    EXPECT_CALL(rightOutputLayer, editState()).WillRepeatedly(ReturnRef(rightOutputLayerState));

    EXPECT_CALL(mOutput, getOutputLayerCount()).WillRepeatedly(Return(2u));
    EXPECT_CALL(mOutput, getOutputLayerOrderedByZByIndex(0u))
            .WillRepeatedly(Return(&leftOutputLayer));
    EXPECT_CALL(mOutput, getOutputLayerOrderedByZByIndex(1u))
            .WillRepeatedly(Return(&rightOutputLayer));

    const Rect kPortraitFrame(0, 0, 1000, 2000);
    const Rect kPortraitViewport(0, 0, 2000, 1000);
    const Rect kPortraitScissor(0, 0, 1000, 2000);
    const uint32_t kPortraitOrientation = TR_ROT_90;

    mOutput.editState().frame = kPortraitFrame;
    mOutput.editState().viewport = kPortraitViewport;
    mOutput.editState().scissor = kPortraitScissor;
    mOutput.editState().transform = ui::Transform{kPortraitOrientation};
    mOutput.editState().orientation = kPortraitOrientation;
    mOutput.editState().needsFiltering = true;
    mOutput.editState().isSecure = false;

    constexpr bool supportsProtectedContent = false;
    Region clearRegion;
    auto requests =
            mOutput.generateClientCompositionRequests(supportsProtectedContent, clearRegion);

    ASSERT_EQ(2u, requests.size());
    EXPECT_EQ(leftLayerColor, requests[0].source.solidColor);
    EXPECT_EQ(rightLayerColor, requests[1].source.solidColor);
}

TEST_F(GenerateClientCompositionRequestsTest, ignoresLayersThatDoNotIntersectWithViewport) {
    // Layers whose visible region does not intersect with the viewport will be
    // skipped when generating client composition request state.

    StrictMock<mock::OutputLayer> outputLayer;
    StrictMock<mock::Layer> layer;
    StrictMock<mock::LayerFE> layerFE;

    impl::OutputLayerCompositionState outputLayerState;
    outputLayerState.clearClientTarget = false;
    outputLayerState.visibleRegion = Region{Rect{3000, 0, 4000, 1000}};

    LayerFECompositionState layerFEState;
    layerFEState.isOpaque = true;

    EXPECT_CALL(outputLayer, getState()).WillRepeatedly(ReturnRef(outputLayerState));
    EXPECT_CALL(outputLayer, getLayer()).WillRepeatedly(ReturnRef(layer));
    EXPECT_CALL(outputLayer, getLayerFE()).WillRepeatedly(ReturnRef(layerFE));
    EXPECT_CALL(outputLayer, requiresClientComposition()).WillRepeatedly(Return(true));
    EXPECT_CALL(outputLayer, needsFiltering()).WillRepeatedly(Return(false));
    EXPECT_CALL(layer, getFEState()).WillRepeatedly(ReturnRef(layerFEState));
    EXPECT_CALL(layerFE, prepareClientComposition(_)).Times(0);
    EXPECT_CALL(outputLayer, editState()).WillRepeatedly(ReturnRef(outputLayerState));

    EXPECT_CALL(mOutput, getOutputLayerCount()).WillRepeatedly(Return(1u));
    EXPECT_CALL(mOutput, getOutputLayerOrderedByZByIndex(0u)).WillRepeatedly(Return(&outputLayer));

    const Rect kPortraitFrame(0, 0, 1000, 2000);
    const Rect kPortraitViewport(0, 0, 2000, 1000);
    const Rect kPortraitScissor(0, 0, 1000, 2000);
    const uint32_t kPortraitOrientation = TR_ROT_90;

    mOutput.editState().frame = kPortraitFrame;
    mOutput.editState().viewport = kPortraitViewport;
    mOutput.editState().scissor = kPortraitScissor;
    mOutput.editState().transform = ui::Transform{kPortraitOrientation};
    mOutput.editState().orientation = kPortraitOrientation;
    mOutput.editState().needsFiltering = true;
    mOutput.editState().isSecure = false;

    constexpr bool supportsProtectedContent = false;
    Region clearRegion;
    auto requests =
            mOutput.generateClientCompositionRequests(supportsProtectedContent, clearRegion);

    EXPECT_EQ(0u, requests.size());
}

TEST_F(GenerateClientCompositionRequestsTest, clearsDeviceLayesAfterFirst) {
    // If client composition is performed with some layers set to use device
    // composition, device layers after the first layer (device or client) will
    // clear the frame buffer if they are opaque and if that layer has a flag
    // set to do so. The first layer is skipped as the frame buffer is already
    // expected to be clear.

    StrictMock<mock::OutputLayer> leftOutputLayer;
    StrictMock<mock::OutputLayer> rightOutputLayer;

    StrictMock<mock::Layer> leftLayer;
    StrictMock<mock::LayerFE> leftLayerFE;
    StrictMock<mock::Layer> rightLayer;
    StrictMock<mock::LayerFE> rightLayerFE;

    impl::OutputLayerCompositionState leftOutputLayerState;
    leftOutputLayerState.clearClientTarget = true;
    leftOutputLayerState.visibleRegion = Region{Rect{0, 0, 1000, 1000}};

    LayerFECompositionState leftLayerFEState;
    leftLayerFEState.isOpaque = true;

    impl::OutputLayerCompositionState rightOutputLayerState;
    rightOutputLayerState.clearClientTarget = true;
    rightOutputLayerState.visibleRegion = Region{Rect{1000, 0, 2000, 1000}};

    LayerFECompositionState rightLayerFEState;
    rightLayerFEState.isOpaque = true;

    const half3 rightLayerColor{0.f, 1.f, 0.f};
    renderengine::LayerSettings rightLayerRESettings;
    rightLayerRESettings.geometry.boundaries = FloatRect{456, 0, 0, 0};
    rightLayerRESettings.source.solidColor = rightLayerColor;

    EXPECT_CALL(leftOutputLayer, getState()).WillRepeatedly(ReturnRef(leftOutputLayerState));
    EXPECT_CALL(leftOutputLayer, getLayer()).WillRepeatedly(ReturnRef(leftLayer));
    EXPECT_CALL(leftOutputLayer, getLayerFE()).WillRepeatedly(ReturnRef(leftLayerFE));
    EXPECT_CALL(leftOutputLayer, requiresClientComposition()).WillRepeatedly(Return(false));
    EXPECT_CALL(leftOutputLayer, needsFiltering()).WillRepeatedly(Return(false));
    EXPECT_CALL(leftLayer, getFEState()).WillRepeatedly(ReturnRef(leftLayerFEState));
    EXPECT_CALL(leftOutputLayer, editState()).WillRepeatedly(ReturnRef(leftOutputLayerState));

    EXPECT_CALL(rightOutputLayer, getState()).WillRepeatedly(ReturnRef(rightOutputLayerState));
    EXPECT_CALL(rightOutputLayer, getLayer()).WillRepeatedly(ReturnRef(rightLayer));
    EXPECT_CALL(rightOutputLayer, getLayerFE()).WillRepeatedly(ReturnRef(rightLayerFE));
    EXPECT_CALL(rightOutputLayer, requiresClientComposition()).WillRepeatedly(Return(false));
    EXPECT_CALL(rightOutputLayer, needsFiltering()).WillRepeatedly(Return(false));
    EXPECT_CALL(rightLayer, getFEState()).WillRepeatedly(ReturnRef(rightLayerFEState));
    EXPECT_CALL(rightLayerFE, prepareClientComposition(_)).WillOnce(Return(rightLayerRESettings));
    EXPECT_CALL(rightOutputLayer, editState()).WillRepeatedly(ReturnRef(rightOutputLayerState));

    EXPECT_CALL(mOutput, getOutputLayerCount()).WillRepeatedly(Return(2u));
    EXPECT_CALL(mOutput, getOutputLayerOrderedByZByIndex(0u))
            .WillRepeatedly(Return(&leftOutputLayer));
    EXPECT_CALL(mOutput, getOutputLayerOrderedByZByIndex(1u))
            .WillRepeatedly(Return(&rightOutputLayer));

    const Rect kPortraitFrame(0, 0, 1000, 2000);
    const Rect kPortraitViewport(0, 0, 2000, 1000);
    const Rect kPortraitScissor(0, 0, 1000, 2000);
    const uint32_t kPortraitOrientation = TR_ROT_90;

    mOutput.editState().frame = kPortraitFrame;
    mOutput.editState().viewport = kPortraitViewport;
    mOutput.editState().scissor = kPortraitScissor;
    mOutput.editState().transform = ui::Transform{kPortraitOrientation};
    mOutput.editState().orientation = kPortraitOrientation;
    mOutput.editState().needsFiltering = true;
    mOutput.editState().isSecure = false;

    constexpr bool supportsProtectedContent = false;
    Region clearRegion;
    auto requests =
            mOutput.generateClientCompositionRequests(supportsProtectedContent, clearRegion);

    const half3 clearColor{0.f, 0.f, 0.f};

    ASSERT_EQ(1u, requests.size());
    EXPECT_EQ(456.f, requests[0].geometry.boundaries.left);
    EXPECT_EQ(clearColor, requests[0].source.solidColor);
}

} // namespace
} // namespace android::compositionengine