1 /*
2  * Copyright 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <cmath>
18 
19 #include <android-base/stringprintf.h>
20 #include <compositionengine/LayerFECompositionState.h>
21 #include <compositionengine/impl/Output.h>
22 #include <compositionengine/impl/OutputCompositionState.h>
23 #include <compositionengine/impl/OutputLayerCompositionState.h>
24 #include <compositionengine/mock/CompositionEngine.h>
25 #include <compositionengine/mock/DisplayColorProfile.h>
26 #include <compositionengine/mock/LayerFE.h>
27 #include <compositionengine/mock/OutputLayer.h>
28 #include <compositionengine/mock/RenderSurface.h>
29 #include <gtest/gtest.h>
30 #include <renderengine/mock/RenderEngine.h>
31 #include <ui/Rect.h>
32 #include <ui/Region.h>
33 
34 #include "CallOrderStateMachineHelper.h"
35 #include "MockHWC2.h"
36 #include "RegionMatcher.h"
37 
38 namespace android::compositionengine {
39 namespace {
40 
41 using testing::_;
42 using testing::ByMove;
43 using testing::ByRef;
44 using testing::DoAll;
45 using testing::ElementsAre;
46 using testing::ElementsAreArray;
47 using testing::Eq;
48 using testing::InSequence;
49 using testing::Invoke;
50 using testing::IsEmpty;
51 using testing::Mock;
52 using testing::Pointee;
53 using testing::Property;
54 using testing::Ref;
55 using testing::Return;
56 using testing::ReturnRef;
57 using testing::SetArgPointee;
58 using testing::StrictMock;
59 
60 constexpr auto TR_IDENT = 0u;
61 constexpr auto TR_ROT_90 = HAL_TRANSFORM_ROT_90;
62 constexpr auto MAX_CLIENT_COMPOSITION_CACHE_SIZE = 3;
63 
64 const mat4 kIdentity;
65 const mat4 kNonIdentityHalf = mat4() * 0.5f;
66 const mat4 kNonIdentityQuarter = mat4() * 0.25f;
67 
68 constexpr OutputColorSetting kVendorSpecifiedOutputColorSetting =
69         static_cast<OutputColorSetting>(0x100);
70 
71 struct OutputPartialMockBase : public impl::Output {
72     // compositionengine::Output overrides
getStateandroid::compositionengine::__anon0cff14940111::OutputPartialMockBase73     const OutputCompositionState& getState() const override { return mState; }
editStateandroid::compositionengine::__anon0cff14940111::OutputPartialMockBase74     OutputCompositionState& editState() override { return mState; }
75 
76     // Use mocks for all the remaining virtual functions
77     // not implemented by the base implementation class.
78     MOCK_CONST_METHOD0(getOutputLayerCount, size_t());
79     MOCK_CONST_METHOD1(getOutputLayerOrderedByZByIndex, compositionengine::OutputLayer*(size_t));
80     MOCK_METHOD2(ensureOutputLayer,
81                  compositionengine::OutputLayer*(std::optional<size_t>, const sp<LayerFE>&));
82     MOCK_METHOD0(finalizePendingOutputLayers, void());
83     MOCK_METHOD0(clearOutputLayers, void());
84     MOCK_CONST_METHOD1(dumpState, void(std::string&));
85     MOCK_CONST_METHOD0(getCompositionEngine, const CompositionEngine&());
86     MOCK_METHOD1(injectOutputLayerForTest, compositionengine::OutputLayer*(const sp<LayerFE>&));
87     MOCK_METHOD1(injectOutputLayerForTest, void(std::unique_ptr<OutputLayer>));
88 
89     impl::OutputCompositionState mState;
90 };
91 
92 struct InjectedLayer {
InjectedLayerandroid::compositionengine::__anon0cff14940111::InjectedLayer93     InjectedLayer() {
94         EXPECT_CALL(*outputLayer, getLayerFE()).WillRepeatedly(ReturnRef(*layerFE.get()));
95         EXPECT_CALL(*outputLayer, getState()).WillRepeatedly(ReturnRef(outputLayerState));
96         EXPECT_CALL(*outputLayer, editState()).WillRepeatedly(ReturnRef(outputLayerState));
97 
98         EXPECT_CALL(*layerFE, getCompositionState()).WillRepeatedly(Return(&layerFEState));
99     }
100 
101     mock::OutputLayer* outputLayer = {new StrictMock<mock::OutputLayer>};
102     sp<StrictMock<mock::LayerFE>> layerFE = new StrictMock<mock::LayerFE>();
103     LayerFECompositionState layerFEState;
104     impl::OutputLayerCompositionState outputLayerState;
105 };
106 
107 struct NonInjectedLayer {
NonInjectedLayerandroid::compositionengine::__anon0cff14940111::NonInjectedLayer108     NonInjectedLayer() {
109         EXPECT_CALL(outputLayer, getLayerFE()).WillRepeatedly(ReturnRef(*layerFE.get()));
110         EXPECT_CALL(outputLayer, getState()).WillRepeatedly(ReturnRef(outputLayerState));
111         EXPECT_CALL(outputLayer, editState()).WillRepeatedly(ReturnRef(outputLayerState));
112 
113         EXPECT_CALL(*layerFE, getCompositionState()).WillRepeatedly(Return(&layerFEState));
114     }
115 
116     mock::OutputLayer outputLayer;
117     sp<StrictMock<mock::LayerFE>> layerFE = new StrictMock<mock::LayerFE>();
118     LayerFECompositionState layerFEState;
119     impl::OutputLayerCompositionState outputLayerState;
120 };
121 
122 struct OutputTest : public testing::Test {
123     class Output : public impl::Output {
124     public:
125         using impl::Output::injectOutputLayerForTest;
126         virtual void injectOutputLayerForTest(std::unique_ptr<compositionengine::OutputLayer>) = 0;
127     };
128 
createOutputandroid::compositionengine::__anon0cff14940111::OutputTest129     static std::shared_ptr<Output> createOutput(
130             const compositionengine::CompositionEngine& compositionEngine) {
131         return impl::createOutputTemplated<Output>(compositionEngine);
132     }
133 
OutputTestandroid::compositionengine::__anon0cff14940111::OutputTest134     OutputTest() {
135         mOutput->setDisplayColorProfileForTest(
136                 std::unique_ptr<DisplayColorProfile>(mDisplayColorProfile));
137         mOutput->setRenderSurfaceForTest(std::unique_ptr<RenderSurface>(mRenderSurface));
138 
139         mOutput->editState().bounds = kDefaultDisplaySize;
140     }
141 
injectOutputLayerandroid::compositionengine::__anon0cff14940111::OutputTest142     void injectOutputLayer(InjectedLayer& layer) {
143         mOutput->injectOutputLayerForTest(std::unique_ptr<OutputLayer>(layer.outputLayer));
144     }
145 
injectNullOutputLayerandroid::compositionengine::__anon0cff14940111::OutputTest146     void injectNullOutputLayer() {
147         mOutput->injectOutputLayerForTest(std::unique_ptr<OutputLayer>(nullptr));
148     }
149 
150     static const Rect kDefaultDisplaySize;
151 
152     StrictMock<mock::CompositionEngine> mCompositionEngine;
153     mock::DisplayColorProfile* mDisplayColorProfile = new StrictMock<mock::DisplayColorProfile>();
154     mock::RenderSurface* mRenderSurface = new StrictMock<mock::RenderSurface>();
155     std::shared_ptr<Output> mOutput = createOutput(mCompositionEngine);
156 };
157 
158 const Rect OutputTest::kDefaultDisplaySize{100, 200};
159 
160 using ColorProfile = compositionengine::Output::ColorProfile;
161 
dumpColorProfile(ColorProfile profile,std::string & result,const char * name)162 void dumpColorProfile(ColorProfile profile, std::string& result, const char* name) {
163     android::base::StringAppendF(&result, "%s (%s[%d] %s[%d] %s[%d] %s[%d]) ", name,
164                                  toString(profile.mode).c_str(), profile.mode,
165                                  toString(profile.dataspace).c_str(), profile.dataspace,
166                                  toString(profile.renderIntent).c_str(), profile.renderIntent,
167                                  toString(profile.colorSpaceAgnosticDataspace).c_str(),
168                                  profile.colorSpaceAgnosticDataspace);
169 }
170 
171 // Checks for a ColorProfile match
172 MATCHER_P(ColorProfileEq, expected, "") {
173     std::string buf;
174     buf.append("ColorProfiles are not equal\n");
175     dumpColorProfile(expected, buf, "expected value");
176     dumpColorProfile(arg, buf, "actual value");
177     *result_listener << buf;
178 
179     return (expected.mode == arg.mode) && (expected.dataspace == arg.dataspace) &&
180             (expected.renderIntent == arg.renderIntent) &&
181             (expected.colorSpaceAgnosticDataspace == arg.colorSpaceAgnosticDataspace);
182 }
183 
184 /*
185  * Basic construction
186  */
187 
TEST_F(OutputTest,canInstantiateOutput)188 TEST_F(OutputTest, canInstantiateOutput) {
189     // The validation check checks each required component.
190     EXPECT_CALL(*mDisplayColorProfile, isValid()).WillOnce(Return(true));
191     EXPECT_CALL(*mRenderSurface, isValid()).WillOnce(Return(true));
192 
193     EXPECT_TRUE(mOutput->isValid());
194 
195     // If we take away the required components, it is no longer valid.
196     mOutput->setRenderSurfaceForTest(std::unique_ptr<RenderSurface>());
197 
198     EXPECT_CALL(*mDisplayColorProfile, isValid()).WillOnce(Return(true));
199 
200     EXPECT_FALSE(mOutput->isValid());
201 }
202 
203 /*
204  * Output::setCompositionEnabled()
205  */
206 
TEST_F(OutputTest,setCompositionEnabledDoesNothingIfAlreadyEnabled)207 TEST_F(OutputTest, setCompositionEnabledDoesNothingIfAlreadyEnabled) {
208     mOutput->editState().isEnabled = true;
209 
210     mOutput->setCompositionEnabled(true);
211 
212     EXPECT_TRUE(mOutput->getState().isEnabled);
213     EXPECT_THAT(mOutput->getState().dirtyRegion, RegionEq(Region()));
214 }
215 
TEST_F(OutputTest,setCompositionEnabledSetsEnabledAndDirtiesEntireOutput)216 TEST_F(OutputTest, setCompositionEnabledSetsEnabledAndDirtiesEntireOutput) {
217     mOutput->editState().isEnabled = false;
218 
219     mOutput->setCompositionEnabled(true);
220 
221     EXPECT_TRUE(mOutput->getState().isEnabled);
222     EXPECT_THAT(mOutput->getState().dirtyRegion, RegionEq(Region(kDefaultDisplaySize)));
223 }
224 
TEST_F(OutputTest,setCompositionEnabledSetsDisabledAndDirtiesEntireOutput)225 TEST_F(OutputTest, setCompositionEnabledSetsDisabledAndDirtiesEntireOutput) {
226     mOutput->editState().isEnabled = true;
227 
228     mOutput->setCompositionEnabled(false);
229 
230     EXPECT_FALSE(mOutput->getState().isEnabled);
231     EXPECT_THAT(mOutput->getState().dirtyRegion, RegionEq(Region(kDefaultDisplaySize)));
232 }
233 
234 /*
235  * Output::setProjection()
236  */
237 
TEST_F(OutputTest,setProjectionTriviallyWorks)238 TEST_F(OutputTest, setProjectionTriviallyWorks) {
239     const ui::Transform transform{ui::Transform::ROT_180};
240     const int32_t orientation = 123;
241     const Rect frame{1, 2, 3, 4};
242     const Rect viewport{5, 6, 7, 8};
243     const Rect sourceClip{9, 10, 11, 12};
244     const Rect destinationClip{13, 14, 15, 16};
245     const bool needsFiltering = true;
246 
247     mOutput->setProjection(transform, orientation, frame, viewport, sourceClip, destinationClip,
248                            needsFiltering);
249 
250     EXPECT_THAT(mOutput->getState().transform, transform);
251     EXPECT_EQ(orientation, mOutput->getState().orientation);
252     EXPECT_EQ(frame, mOutput->getState().frame);
253     EXPECT_EQ(viewport, mOutput->getState().viewport);
254     EXPECT_EQ(sourceClip, mOutput->getState().sourceClip);
255     EXPECT_EQ(destinationClip, mOutput->getState().destinationClip);
256     EXPECT_EQ(needsFiltering, mOutput->getState().needsFiltering);
257 }
258 
259 /*
260  * Output::setBounds()
261  */
262 
TEST_F(OutputTest,setBoundsSetsSizeAndDirtiesEntireOutput)263 TEST_F(OutputTest, setBoundsSetsSizeAndDirtiesEntireOutput) {
264     const ui::Size displaySize{200, 400};
265 
266     EXPECT_CALL(*mRenderSurface, setDisplaySize(displaySize)).Times(1);
267     EXPECT_CALL(*mRenderSurface, getSize()).WillOnce(ReturnRef(displaySize));
268 
269     mOutput->setBounds(displaySize);
270 
271     EXPECT_EQ(Rect(displaySize), mOutput->getState().bounds);
272 
273     EXPECT_THAT(mOutput->getState().dirtyRegion, RegionEq(Region(Rect(displaySize))));
274 }
275 
276 /*
277  * Output::setLayerStackFilter()
278  */
279 
TEST_F(OutputTest,setLayerStackFilterSetsFilterAndDirtiesEntireOutput)280 TEST_F(OutputTest, setLayerStackFilterSetsFilterAndDirtiesEntireOutput) {
281     const uint32_t layerStack = 123u;
282     mOutput->setLayerStackFilter(layerStack, true);
283 
284     EXPECT_TRUE(mOutput->getState().layerStackInternal);
285     EXPECT_EQ(layerStack, mOutput->getState().layerStackId);
286 
287     EXPECT_THAT(mOutput->getState().dirtyRegion, RegionEq(Region(kDefaultDisplaySize)));
288 }
289 
290 /*
291  * Output::setColorTransform
292  */
293 
TEST_F(OutputTest,setColorTransformWithNoChangeFlaggedSkipsUpdates)294 TEST_F(OutputTest, setColorTransformWithNoChangeFlaggedSkipsUpdates) {
295     mOutput->editState().colorTransformMatrix = kIdentity;
296 
297     // If no colorTransformMatrix is set the update should be skipped.
298     CompositionRefreshArgs refreshArgs;
299     refreshArgs.colorTransformMatrix = std::nullopt;
300 
301     mOutput->setColorTransform(refreshArgs);
302 
303     // The internal state should be unchanged
304     EXPECT_EQ(kIdentity, mOutput->getState().colorTransformMatrix);
305 
306     // No dirty region should be set
307     EXPECT_THAT(mOutput->getState().dirtyRegion, RegionEq(Region()));
308 }
309 
TEST_F(OutputTest,setColorTransformWithNoActualChangeSkipsUpdates)310 TEST_F(OutputTest, setColorTransformWithNoActualChangeSkipsUpdates) {
311     mOutput->editState().colorTransformMatrix = kIdentity;
312 
313     // Attempting to set the same colorTransformMatrix that is already set should
314     // also skip the update.
315     CompositionRefreshArgs refreshArgs;
316     refreshArgs.colorTransformMatrix = kIdentity;
317 
318     mOutput->setColorTransform(refreshArgs);
319 
320     // The internal state should be unchanged
321     EXPECT_EQ(kIdentity, mOutput->getState().colorTransformMatrix);
322 
323     // No dirty region should be set
324     EXPECT_THAT(mOutput->getState().dirtyRegion, RegionEq(Region()));
325 }
326 
TEST_F(OutputTest,setColorTransformPerformsUpdateToIdentity)327 TEST_F(OutputTest, setColorTransformPerformsUpdateToIdentity) {
328     mOutput->editState().colorTransformMatrix = kNonIdentityHalf;
329 
330     // Setting a different colorTransformMatrix should perform the update.
331     CompositionRefreshArgs refreshArgs;
332     refreshArgs.colorTransformMatrix = kIdentity;
333 
334     mOutput->setColorTransform(refreshArgs);
335 
336     // The internal state should have been updated
337     EXPECT_EQ(kIdentity, mOutput->getState().colorTransformMatrix);
338 
339     // The dirtyRegion should be set to the full display size
340     EXPECT_THAT(mOutput->getState().dirtyRegion, RegionEq(Region(kDefaultDisplaySize)));
341 }
342 
TEST_F(OutputTest,setColorTransformPerformsUpdateForIdentityToHalf)343 TEST_F(OutputTest, setColorTransformPerformsUpdateForIdentityToHalf) {
344     mOutput->editState().colorTransformMatrix = kIdentity;
345 
346     // Setting a different colorTransformMatrix should perform the update.
347     CompositionRefreshArgs refreshArgs;
348     refreshArgs.colorTransformMatrix = kNonIdentityHalf;
349 
350     mOutput->setColorTransform(refreshArgs);
351 
352     // The internal state should have been updated
353     EXPECT_EQ(kNonIdentityHalf, mOutput->getState().colorTransformMatrix);
354 
355     // The dirtyRegion should be set to the full display size
356     EXPECT_THAT(mOutput->getState().dirtyRegion, RegionEq(Region(kDefaultDisplaySize)));
357 }
358 
TEST_F(OutputTest,setColorTransformPerformsUpdateForHalfToQuarter)359 TEST_F(OutputTest, setColorTransformPerformsUpdateForHalfToQuarter) {
360     mOutput->editState().colorTransformMatrix = kNonIdentityHalf;
361 
362     // Setting a different colorTransformMatrix should perform the update.
363     CompositionRefreshArgs refreshArgs;
364     refreshArgs.colorTransformMatrix = kNonIdentityQuarter;
365 
366     mOutput->setColorTransform(refreshArgs);
367 
368     // The internal state should have been updated
369     EXPECT_EQ(kNonIdentityQuarter, mOutput->getState().colorTransformMatrix);
370 
371     // The dirtyRegion should be set to the full display size
372     EXPECT_THAT(mOutput->getState().dirtyRegion, RegionEq(Region(kDefaultDisplaySize)));
373 }
374 
375 /*
376  * Output::setColorProfile
377  */
378 
379 using OutputSetColorProfileTest = OutputTest;
380 
TEST_F(OutputSetColorProfileTest,setsStateAndDirtiesOutputIfChanged)381 TEST_F(OutputSetColorProfileTest, setsStateAndDirtiesOutputIfChanged) {
382     using ColorProfile = Output::ColorProfile;
383 
384     EXPECT_CALL(*mDisplayColorProfile,
385                 getTargetDataspace(ui::ColorMode::DISPLAY_P3, ui::Dataspace::DISPLAY_P3,
386                                    ui::Dataspace::UNKNOWN))
387             .WillOnce(Return(ui::Dataspace::UNKNOWN));
388     EXPECT_CALL(*mRenderSurface, setBufferDataspace(ui::Dataspace::DISPLAY_P3)).Times(1);
389 
390     mOutput->setColorProfile(ColorProfile{ui::ColorMode::DISPLAY_P3, ui::Dataspace::DISPLAY_P3,
391                                           ui::RenderIntent::TONE_MAP_COLORIMETRIC,
392                                           ui::Dataspace::UNKNOWN});
393 
394     EXPECT_EQ(ui::ColorMode::DISPLAY_P3, mOutput->getState().colorMode);
395     EXPECT_EQ(ui::Dataspace::DISPLAY_P3, mOutput->getState().dataspace);
396     EXPECT_EQ(ui::RenderIntent::TONE_MAP_COLORIMETRIC, mOutput->getState().renderIntent);
397     EXPECT_EQ(ui::Dataspace::UNKNOWN, mOutput->getState().targetDataspace);
398 
399     EXPECT_THAT(mOutput->getState().dirtyRegion, RegionEq(Region(kDefaultDisplaySize)));
400 }
401 
TEST_F(OutputSetColorProfileTest,doesNothingIfNoChange)402 TEST_F(OutputSetColorProfileTest, doesNothingIfNoChange) {
403     using ColorProfile = Output::ColorProfile;
404 
405     EXPECT_CALL(*mDisplayColorProfile,
406                 getTargetDataspace(ui::ColorMode::DISPLAY_P3, ui::Dataspace::DISPLAY_P3,
407                                    ui::Dataspace::UNKNOWN))
408             .WillOnce(Return(ui::Dataspace::UNKNOWN));
409 
410     mOutput->editState().colorMode = ui::ColorMode::DISPLAY_P3;
411     mOutput->editState().dataspace = ui::Dataspace::DISPLAY_P3;
412     mOutput->editState().renderIntent = ui::RenderIntent::TONE_MAP_COLORIMETRIC;
413     mOutput->editState().targetDataspace = ui::Dataspace::UNKNOWN;
414 
415     mOutput->setColorProfile(ColorProfile{ui::ColorMode::DISPLAY_P3, ui::Dataspace::DISPLAY_P3,
416                                           ui::RenderIntent::TONE_MAP_COLORIMETRIC,
417                                           ui::Dataspace::UNKNOWN});
418 
419     EXPECT_THAT(mOutput->getState().dirtyRegion, RegionEq(Region()));
420 }
421 
422 /*
423  * Output::setRenderSurface()
424  */
425 
TEST_F(OutputTest,setRenderSurfaceResetsBounds)426 TEST_F(OutputTest, setRenderSurfaceResetsBounds) {
427     const ui::Size newDisplaySize{640, 480};
428 
429     mock::RenderSurface* renderSurface = new StrictMock<mock::RenderSurface>();
430     EXPECT_CALL(*renderSurface, getSize()).WillOnce(ReturnRef(newDisplaySize));
431 
432     mOutput->setRenderSurface(std::unique_ptr<RenderSurface>(renderSurface));
433 
434     EXPECT_EQ(Rect(newDisplaySize), mOutput->getState().bounds);
435 }
436 
437 /*
438  * Output::getDirtyRegion()
439  */
440 
TEST_F(OutputTest,getDirtyRegionWithRepaintEverythingTrue)441 TEST_F(OutputTest, getDirtyRegionWithRepaintEverythingTrue) {
442     const Rect viewport{100, 200};
443     mOutput->editState().viewport = viewport;
444     mOutput->editState().dirtyRegion.set(50, 300);
445 
446     {
447         Region result = mOutput->getDirtyRegion(true);
448 
449         EXPECT_THAT(result, RegionEq(Region(viewport)));
450     }
451 }
452 
TEST_F(OutputTest,getDirtyRegionWithRepaintEverythingFalse)453 TEST_F(OutputTest, getDirtyRegionWithRepaintEverythingFalse) {
454     const Rect viewport{100, 200};
455     mOutput->editState().viewport = viewport;
456     mOutput->editState().dirtyRegion.set(50, 300);
457 
458     {
459         Region result = mOutput->getDirtyRegion(false);
460 
461         // The dirtyRegion should be clipped to the display bounds.
462         EXPECT_THAT(result, RegionEq(Region(Rect(50, 200))));
463     }
464 }
465 
466 /*
467  * Output::belongsInOutput()
468  */
469 
TEST_F(OutputTest,belongsInOutputFiltersAsExpected)470 TEST_F(OutputTest, belongsInOutputFiltersAsExpected) {
471     const uint32_t layerStack1 = 123u;
472     const uint32_t layerStack2 = 456u;
473 
474     // If the output accepts layerStack1 and internal-only layers....
475     mOutput->setLayerStackFilter(layerStack1, true);
476 
477     // A layer with no layerStack does not belong to it, internal-only or not.
478     EXPECT_FALSE(mOutput->belongsInOutput(std::nullopt, false));
479     EXPECT_FALSE(mOutput->belongsInOutput(std::nullopt, true));
480 
481     // Any layer with layerStack1 belongs to it, internal-only or not.
482     EXPECT_TRUE(mOutput->belongsInOutput(layerStack1, false));
483     EXPECT_TRUE(mOutput->belongsInOutput(layerStack1, true));
484     EXPECT_FALSE(mOutput->belongsInOutput(layerStack2, true));
485     EXPECT_FALSE(mOutput->belongsInOutput(layerStack2, false));
486 
487     // If the output accepts layerStack21 but not internal-only layers...
488     mOutput->setLayerStackFilter(layerStack1, false);
489 
490     // Only non-internal layers with layerStack1 belong to it.
491     EXPECT_TRUE(mOutput->belongsInOutput(layerStack1, false));
492     EXPECT_FALSE(mOutput->belongsInOutput(layerStack1, true));
493     EXPECT_FALSE(mOutput->belongsInOutput(layerStack2, true));
494     EXPECT_FALSE(mOutput->belongsInOutput(layerStack2, false));
495 }
496 
TEST_F(OutputTest,belongsInOutputHandlesLayerWithNoCompositionState)497 TEST_F(OutputTest, belongsInOutputHandlesLayerWithNoCompositionState) {
498     NonInjectedLayer layer;
499     sp<LayerFE> layerFE(layer.layerFE);
500 
501     // If the layer has no composition state, it does not belong to any output.
502     EXPECT_CALL(*layer.layerFE, getCompositionState).WillOnce(Return(nullptr));
503     EXPECT_FALSE(mOutput->belongsInOutput(layerFE));
504 }
505 
TEST_F(OutputTest,belongsInOutputFiltersLayersAsExpected)506 TEST_F(OutputTest, belongsInOutputFiltersLayersAsExpected) {
507     NonInjectedLayer layer;
508     sp<LayerFE> layerFE(layer.layerFE);
509 
510     const uint32_t layerStack1 = 123u;
511     const uint32_t layerStack2 = 456u;
512 
513     // If the output accepts layerStack1 and internal-only layers....
514     mOutput->setLayerStackFilter(layerStack1, true);
515 
516     // A layer with no layerStack does not belong to it, internal-only or not.
517     layer.layerFEState.layerStackId = std::nullopt;
518     layer.layerFEState.internalOnly = false;
519     EXPECT_FALSE(mOutput->belongsInOutput(layerFE));
520 
521     layer.layerFEState.layerStackId = std::nullopt;
522     layer.layerFEState.internalOnly = true;
523     EXPECT_FALSE(mOutput->belongsInOutput(layerFE));
524 
525     // Any layer with layerStack1 belongs to it, internal-only or not.
526     layer.layerFEState.layerStackId = layerStack1;
527     layer.layerFEState.internalOnly = false;
528     EXPECT_TRUE(mOutput->belongsInOutput(layerFE));
529 
530     layer.layerFEState.layerStackId = layerStack1;
531     layer.layerFEState.internalOnly = true;
532     EXPECT_TRUE(mOutput->belongsInOutput(layerFE));
533 
534     layer.layerFEState.layerStackId = layerStack2;
535     layer.layerFEState.internalOnly = true;
536     EXPECT_FALSE(mOutput->belongsInOutput(layerFE));
537 
538     layer.layerFEState.layerStackId = layerStack2;
539     layer.layerFEState.internalOnly = false;
540     EXPECT_FALSE(mOutput->belongsInOutput(layerFE));
541 
542     // If the output accepts layerStack1 but not internal-only layers...
543     mOutput->setLayerStackFilter(layerStack1, false);
544 
545     // Only non-internal layers with layerStack1 belong to it.
546     layer.layerFEState.layerStackId = layerStack1;
547     layer.layerFEState.internalOnly = false;
548     EXPECT_TRUE(mOutput->belongsInOutput(layerFE));
549 
550     layer.layerFEState.layerStackId = layerStack1;
551     layer.layerFEState.internalOnly = true;
552     EXPECT_FALSE(mOutput->belongsInOutput(layerFE));
553 
554     layer.layerFEState.layerStackId = layerStack2;
555     layer.layerFEState.internalOnly = true;
556     EXPECT_FALSE(mOutput->belongsInOutput(layerFE));
557 
558     layer.layerFEState.layerStackId = layerStack2;
559     layer.layerFEState.internalOnly = false;
560     EXPECT_FALSE(mOutput->belongsInOutput(layerFE));
561 }
562 
563 /*
564  * Output::getOutputLayerForLayer()
565  */
566 
TEST_F(OutputTest,getOutputLayerForLayerWorks)567 TEST_F(OutputTest, getOutputLayerForLayerWorks) {
568     InjectedLayer layer1;
569     InjectedLayer layer2;
570     NonInjectedLayer layer3;
571 
572     injectOutputLayer(layer1);
573     injectNullOutputLayer();
574     injectOutputLayer(layer2);
575 
576     // If the input layer matches the first OutputLayer, it will be returned.
577     EXPECT_CALL(*layer1.outputLayer, getLayerFE()).WillOnce(ReturnRef(*layer1.layerFE.get()));
578     EXPECT_EQ(layer1.outputLayer, mOutput->getOutputLayerForLayer(layer1.layerFE));
579 
580     // If the input layer matches the second OutputLayer, it will be returned.
581     EXPECT_CALL(*layer1.outputLayer, getLayerFE()).WillOnce(ReturnRef(*layer1.layerFE.get()));
582     EXPECT_CALL(*layer2.outputLayer, getLayerFE()).WillOnce(ReturnRef(*layer2.layerFE.get()));
583     EXPECT_EQ(layer2.outputLayer, mOutput->getOutputLayerForLayer(layer2.layerFE));
584 
585     // If the input layer does not match an output layer, null will be returned.
586     EXPECT_CALL(*layer1.outputLayer, getLayerFE()).WillOnce(ReturnRef(*layer1.layerFE.get()));
587     EXPECT_CALL(*layer2.outputLayer, getLayerFE()).WillOnce(ReturnRef(*layer2.layerFE.get()));
588     EXPECT_EQ(nullptr, mOutput->getOutputLayerForLayer(layer3.layerFE));
589 }
590 
591 /*
592  * Output::setReleasedLayers()
593  */
594 
595 using OutputSetReleasedLayersTest = OutputTest;
596 
TEST_F(OutputSetReleasedLayersTest,setReleasedLayersTakesGivenLayers)597 TEST_F(OutputSetReleasedLayersTest, setReleasedLayersTakesGivenLayers) {
598     sp<StrictMock<mock::LayerFE>> layer1FE{new StrictMock<mock::LayerFE>()};
599     sp<StrictMock<mock::LayerFE>> layer2FE{new StrictMock<mock::LayerFE>()};
600     sp<StrictMock<mock::LayerFE>> layer3FE{new StrictMock<mock::LayerFE>()};
601 
602     Output::ReleasedLayers layers;
603     layers.push_back(layer1FE);
604     layers.push_back(layer2FE);
605     layers.push_back(layer3FE);
606 
607     mOutput->setReleasedLayers(std::move(layers));
608 
609     const auto& setLayers = mOutput->getReleasedLayersForTest();
610     ASSERT_EQ(3u, setLayers.size());
611     ASSERT_EQ(layer1FE.get(), setLayers[0].promote().get());
612     ASSERT_EQ(layer2FE.get(), setLayers[1].promote().get());
613     ASSERT_EQ(layer3FE.get(), setLayers[2].promote().get());
614 }
615 
616 /*
617  * Output::updateLayerStateFromFE()
618  */
619 
620 using OutputUpdateLayerStateFromFETest = OutputTest;
621 
TEST_F(OutputUpdateLayerStateFromFETest,handlesNoOutputLayerCase)622 TEST_F(OutputUpdateLayerStateFromFETest, handlesNoOutputLayerCase) {
623     CompositionRefreshArgs refreshArgs;
624 
625     mOutput->updateLayerStateFromFE(refreshArgs);
626 }
627 
TEST_F(OutputUpdateLayerStateFromFETest,preparesContentStateForAllContainedLayers)628 TEST_F(OutputUpdateLayerStateFromFETest, preparesContentStateForAllContainedLayers) {
629     InjectedLayer layer1;
630     InjectedLayer layer2;
631     InjectedLayer layer3;
632 
633     EXPECT_CALL(*layer1.layerFE.get(), prepareCompositionState(LayerFE::StateSubset::Content));
634     EXPECT_CALL(*layer2.layerFE.get(), prepareCompositionState(LayerFE::StateSubset::Content));
635     EXPECT_CALL(*layer3.layerFE.get(), prepareCompositionState(LayerFE::StateSubset::Content));
636 
637     injectOutputLayer(layer1);
638     injectOutputLayer(layer2);
639     injectOutputLayer(layer3);
640 
641     CompositionRefreshArgs refreshArgs;
642     refreshArgs.updatingGeometryThisFrame = false;
643 
644     mOutput->updateLayerStateFromFE(refreshArgs);
645 }
646 
TEST_F(OutputUpdateLayerStateFromFETest,preparesGeometryAndContentStateForAllContainedLayers)647 TEST_F(OutputUpdateLayerStateFromFETest, preparesGeometryAndContentStateForAllContainedLayers) {
648     InjectedLayer layer1;
649     InjectedLayer layer2;
650     InjectedLayer layer3;
651 
652     EXPECT_CALL(*layer1.layerFE, prepareCompositionState(LayerFE::StateSubset::GeometryAndContent));
653     EXPECT_CALL(*layer2.layerFE, prepareCompositionState(LayerFE::StateSubset::GeometryAndContent));
654     EXPECT_CALL(*layer3.layerFE, prepareCompositionState(LayerFE::StateSubset::GeometryAndContent));
655 
656     injectOutputLayer(layer1);
657     injectOutputLayer(layer2);
658     injectOutputLayer(layer3);
659 
660     CompositionRefreshArgs refreshArgs;
661     refreshArgs.updatingGeometryThisFrame = true;
662 
663     mOutput->updateLayerStateFromFE(refreshArgs);
664 }
665 
666 /*
667  * Output::updateAndWriteCompositionState()
668  */
669 
670 using OutputUpdateAndWriteCompositionStateTest = OutputTest;
671 
TEST_F(OutputUpdateAndWriteCompositionStateTest,doesNothingIfLayers)672 TEST_F(OutputUpdateAndWriteCompositionStateTest, doesNothingIfLayers) {
673     mOutput->editState().isEnabled = true;
674 
675     CompositionRefreshArgs args;
676     mOutput->updateAndWriteCompositionState(args);
677 }
678 
TEST_F(OutputUpdateAndWriteCompositionStateTest,doesNothingIfOutputNotEnabled)679 TEST_F(OutputUpdateAndWriteCompositionStateTest, doesNothingIfOutputNotEnabled) {
680     InjectedLayer layer1;
681     InjectedLayer layer2;
682     InjectedLayer layer3;
683 
684     mOutput->editState().isEnabled = false;
685 
686     injectOutputLayer(layer1);
687     injectOutputLayer(layer2);
688     injectOutputLayer(layer3);
689 
690     CompositionRefreshArgs args;
691     mOutput->updateAndWriteCompositionState(args);
692 }
693 
TEST_F(OutputUpdateAndWriteCompositionStateTest,updatesLayerContentForAllLayers)694 TEST_F(OutputUpdateAndWriteCompositionStateTest, updatesLayerContentForAllLayers) {
695     InjectedLayer layer1;
696     InjectedLayer layer2;
697     InjectedLayer layer3;
698 
699     EXPECT_CALL(*layer1.outputLayer, updateCompositionState(false, false, ui::Transform::ROT_180));
700     EXPECT_CALL(*layer1.outputLayer, writeStateToHWC(false));
701     EXPECT_CALL(*layer2.outputLayer, updateCompositionState(false, false, ui::Transform::ROT_180));
702     EXPECT_CALL(*layer2.outputLayer, writeStateToHWC(false));
703     EXPECT_CALL(*layer3.outputLayer, updateCompositionState(false, false, ui::Transform::ROT_180));
704     EXPECT_CALL(*layer3.outputLayer, writeStateToHWC(false));
705 
706     injectOutputLayer(layer1);
707     injectOutputLayer(layer2);
708     injectOutputLayer(layer3);
709 
710     mOutput->editState().isEnabled = true;
711 
712     CompositionRefreshArgs args;
713     args.updatingGeometryThisFrame = false;
714     args.devOptForceClientComposition = false;
715     args.internalDisplayRotationFlags = ui::Transform::ROT_180;
716     mOutput->updateAndWriteCompositionState(args);
717 }
718 
TEST_F(OutputUpdateAndWriteCompositionStateTest,updatesLayerGeometryAndContentForAllLayers)719 TEST_F(OutputUpdateAndWriteCompositionStateTest, updatesLayerGeometryAndContentForAllLayers) {
720     InjectedLayer layer1;
721     InjectedLayer layer2;
722     InjectedLayer layer3;
723 
724     EXPECT_CALL(*layer1.outputLayer, updateCompositionState(true, false, ui::Transform::ROT_0));
725     EXPECT_CALL(*layer1.outputLayer, writeStateToHWC(true));
726     EXPECT_CALL(*layer2.outputLayer, updateCompositionState(true, false, ui::Transform::ROT_0));
727     EXPECT_CALL(*layer2.outputLayer, writeStateToHWC(true));
728     EXPECT_CALL(*layer3.outputLayer, updateCompositionState(true, false, ui::Transform::ROT_0));
729     EXPECT_CALL(*layer3.outputLayer, writeStateToHWC(true));
730 
731     injectOutputLayer(layer1);
732     injectOutputLayer(layer2);
733     injectOutputLayer(layer3);
734 
735     mOutput->editState().isEnabled = true;
736 
737     CompositionRefreshArgs args;
738     args.updatingGeometryThisFrame = true;
739     args.devOptForceClientComposition = false;
740     mOutput->updateAndWriteCompositionState(args);
741 }
742 
TEST_F(OutputUpdateAndWriteCompositionStateTest,forcesClientCompositionForAllLayers)743 TEST_F(OutputUpdateAndWriteCompositionStateTest, forcesClientCompositionForAllLayers) {
744     InjectedLayer layer1;
745     InjectedLayer layer2;
746     InjectedLayer layer3;
747 
748     EXPECT_CALL(*layer1.outputLayer, updateCompositionState(false, true, ui::Transform::ROT_0));
749     EXPECT_CALL(*layer1.outputLayer, writeStateToHWC(false));
750     EXPECT_CALL(*layer2.outputLayer, updateCompositionState(false, true, ui::Transform::ROT_0));
751     EXPECT_CALL(*layer2.outputLayer, writeStateToHWC(false));
752     EXPECT_CALL(*layer3.outputLayer, updateCompositionState(false, true, ui::Transform::ROT_0));
753     EXPECT_CALL(*layer3.outputLayer, writeStateToHWC(false));
754 
755     injectOutputLayer(layer1);
756     injectOutputLayer(layer2);
757     injectOutputLayer(layer3);
758 
759     mOutput->editState().isEnabled = true;
760 
761     CompositionRefreshArgs args;
762     args.updatingGeometryThisFrame = false;
763     args.devOptForceClientComposition = true;
764     mOutput->updateAndWriteCompositionState(args);
765 }
766 
767 /*
768  * Output::prepareFrame()
769  */
770 
771 struct OutputPrepareFrameTest : public testing::Test {
772     struct OutputPartialMock : public OutputPartialMockBase {
773         // Sets up the helper functions called by the function under test to use
774         // mock implementations.
775         MOCK_METHOD0(chooseCompositionStrategy, void());
776     };
777 
OutputPrepareFrameTestandroid::compositionengine::__anon0cff14940111::OutputPrepareFrameTest778     OutputPrepareFrameTest() {
779         mOutput.setDisplayColorProfileForTest(
780                 std::unique_ptr<DisplayColorProfile>(mDisplayColorProfile));
781         mOutput.setRenderSurfaceForTest(std::unique_ptr<RenderSurface>(mRenderSurface));
782     }
783 
784     StrictMock<mock::CompositionEngine> mCompositionEngine;
785     mock::DisplayColorProfile* mDisplayColorProfile = new StrictMock<mock::DisplayColorProfile>();
786     mock::RenderSurface* mRenderSurface = new StrictMock<mock::RenderSurface>();
787     StrictMock<OutputPartialMock> mOutput;
788 };
789 
TEST_F(OutputPrepareFrameTest,takesEarlyOutIfNotEnabled)790 TEST_F(OutputPrepareFrameTest, takesEarlyOutIfNotEnabled) {
791     mOutput.editState().isEnabled = false;
792 
793     mOutput.prepareFrame();
794 }
795 
TEST_F(OutputPrepareFrameTest,delegatesToChooseCompositionStrategyAndRenderSurface)796 TEST_F(OutputPrepareFrameTest, delegatesToChooseCompositionStrategyAndRenderSurface) {
797     mOutput.editState().isEnabled = true;
798     mOutput.editState().usesClientComposition = false;
799     mOutput.editState().usesDeviceComposition = true;
800 
801     EXPECT_CALL(mOutput, chooseCompositionStrategy()).Times(1);
802     EXPECT_CALL(*mRenderSurface, prepareFrame(false, true));
803 
804     mOutput.prepareFrame();
805 }
806 
807 // Note: Use OutputTest and not OutputPrepareFrameTest, so the real
808 // base chooseCompositionStrategy() is invoked.
TEST_F(OutputTest,prepareFrameSetsClientCompositionOnlyByDefault)809 TEST_F(OutputTest, prepareFrameSetsClientCompositionOnlyByDefault) {
810     mOutput->editState().isEnabled = true;
811     mOutput->editState().usesClientComposition = false;
812     mOutput->editState().usesDeviceComposition = true;
813 
814     EXPECT_CALL(*mRenderSurface, prepareFrame(true, false));
815 
816     mOutput->prepareFrame();
817 
818     EXPECT_TRUE(mOutput->getState().usesClientComposition);
819     EXPECT_FALSE(mOutput->getState().usesDeviceComposition);
820 }
821 
822 /*
823  * Output::prepare()
824  */
825 
826 struct OutputPrepareTest : public testing::Test {
827     struct OutputPartialMock : public OutputPartialMockBase {
828         // Sets up the helper functions called by the function under test to use
829         // mock implementations.
830         MOCK_METHOD2(rebuildLayerStacks,
831                      void(const compositionengine::CompositionRefreshArgs&,
832                           compositionengine::LayerFESet&));
833     };
834 
835     StrictMock<OutputPartialMock> mOutput;
836     CompositionRefreshArgs mRefreshArgs;
837     LayerFESet mGeomSnapshots;
838 };
839 
TEST_F(OutputPrepareTest,justInvokesRebuildLayerStacks)840 TEST_F(OutputPrepareTest, justInvokesRebuildLayerStacks) {
841     InSequence seq;
842     EXPECT_CALL(mOutput, rebuildLayerStacks(Ref(mRefreshArgs), Ref(mGeomSnapshots)));
843 
844     mOutput.prepare(mRefreshArgs, mGeomSnapshots);
845 }
846 
847 /*
848  * Output::rebuildLayerStacks()
849  */
850 
851 struct OutputRebuildLayerStacksTest : public testing::Test {
852     struct OutputPartialMock : public OutputPartialMockBase {
853         // Sets up the helper functions called by the function under test to use
854         // mock implementations.
855         MOCK_METHOD2(collectVisibleLayers,
856                      void(const compositionengine::CompositionRefreshArgs&,
857                           compositionengine::Output::CoverageState&));
858     };
859 
OutputRebuildLayerStacksTestandroid::compositionengine::__anon0cff14940111::OutputRebuildLayerStacksTest860     OutputRebuildLayerStacksTest() {
861         mOutput.mState.isEnabled = true;
862         mOutput.mState.transform = kIdentityTransform;
863         mOutput.mState.bounds = kOutputBounds;
864 
865         mRefreshArgs.updatingOutputGeometryThisFrame = true;
866 
867         mCoverageAboveCoveredLayersToSet = Region(Rect(0, 0, 10, 10));
868 
869         EXPECT_CALL(mOutput, collectVisibleLayers(Ref(mRefreshArgs), _))
870                 .WillRepeatedly(Invoke(this, &OutputRebuildLayerStacksTest::setTestCoverageValues));
871     }
872 
setTestCoverageValuesandroid::compositionengine::__anon0cff14940111::OutputRebuildLayerStacksTest873     void setTestCoverageValues(const CompositionRefreshArgs&,
874                                compositionengine::Output::CoverageState& state) {
875         state.aboveCoveredLayers = mCoverageAboveCoveredLayersToSet;
876         state.aboveOpaqueLayers = mCoverageAboveOpaqueLayersToSet;
877         state.dirtyRegion = mCoverageDirtyRegionToSet;
878     }
879 
880     static const ui::Transform kIdentityTransform;
881     static const ui::Transform kRotate90Transform;
882     static const Rect kOutputBounds;
883 
884     StrictMock<OutputPartialMock> mOutput;
885     CompositionRefreshArgs mRefreshArgs;
886     LayerFESet mGeomSnapshots;
887     Region mCoverageAboveCoveredLayersToSet;
888     Region mCoverageAboveOpaqueLayersToSet;
889     Region mCoverageDirtyRegionToSet;
890 };
891 
892 const ui::Transform OutputRebuildLayerStacksTest::kIdentityTransform{TR_IDENT, 1920, 1080};
893 const ui::Transform OutputRebuildLayerStacksTest::kRotate90Transform{TR_ROT_90, 1920, 1080};
894 const Rect OutputRebuildLayerStacksTest::kOutputBounds{0, 0, 1920, 1080};
895 
TEST_F(OutputRebuildLayerStacksTest,doesNothingIfNotEnabled)896 TEST_F(OutputRebuildLayerStacksTest, doesNothingIfNotEnabled) {
897     mOutput.mState.isEnabled = false;
898 
899     mOutput.rebuildLayerStacks(mRefreshArgs, mGeomSnapshots);
900 }
901 
TEST_F(OutputRebuildLayerStacksTest,doesNothingIfNotUpdatingGeometryThisFrame)902 TEST_F(OutputRebuildLayerStacksTest, doesNothingIfNotUpdatingGeometryThisFrame) {
903     mRefreshArgs.updatingOutputGeometryThisFrame = false;
904 
905     mOutput.rebuildLayerStacks(mRefreshArgs, mGeomSnapshots);
906 }
907 
TEST_F(OutputRebuildLayerStacksTest,computesUndefinedRegionWithNoRotationAndFullCoverage)908 TEST_F(OutputRebuildLayerStacksTest, computesUndefinedRegionWithNoRotationAndFullCoverage) {
909     mOutput.mState.transform = kIdentityTransform;
910 
911     mCoverageAboveOpaqueLayersToSet = Region(Rect(0, 0, 1920, 1080));
912 
913     mOutput.rebuildLayerStacks(mRefreshArgs, mGeomSnapshots);
914 
915     EXPECT_THAT(mOutput.mState.undefinedRegion, RegionEq(Region(Rect(0, 0, 0, 0))));
916 }
917 
TEST_F(OutputRebuildLayerStacksTest,computesUndefinedRegionWithNoRotationAndPartialCoverage)918 TEST_F(OutputRebuildLayerStacksTest, computesUndefinedRegionWithNoRotationAndPartialCoverage) {
919     mOutput.mState.transform = kIdentityTransform;
920 
921     mCoverageAboveOpaqueLayersToSet = Region(Rect(0, 0, 960, 1080));
922 
923     mOutput.rebuildLayerStacks(mRefreshArgs, mGeomSnapshots);
924 
925     EXPECT_THAT(mOutput.mState.undefinedRegion, RegionEq(Region(Rect(960, 0, 1920, 1080))));
926 }
927 
TEST_F(OutputRebuildLayerStacksTest,computesUndefinedRegionWith90RotationAndFullCoverage)928 TEST_F(OutputRebuildLayerStacksTest, computesUndefinedRegionWith90RotationAndFullCoverage) {
929     mOutput.mState.transform = kRotate90Transform;
930 
931     mCoverageAboveOpaqueLayersToSet = Region(Rect(0, 0, 1080, 1920));
932 
933     mOutput.rebuildLayerStacks(mRefreshArgs, mGeomSnapshots);
934 
935     EXPECT_THAT(mOutput.mState.undefinedRegion, RegionEq(Region(Rect(0, 0, 0, 0))));
936 }
937 
TEST_F(OutputRebuildLayerStacksTest,computesUndefinedRegionWith90RotationAndPartialCoverage)938 TEST_F(OutputRebuildLayerStacksTest, computesUndefinedRegionWith90RotationAndPartialCoverage) {
939     mOutput.mState.transform = kRotate90Transform;
940 
941     mCoverageAboveOpaqueLayersToSet = Region(Rect(0, 0, 1080, 960));
942 
943     mOutput.rebuildLayerStacks(mRefreshArgs, mGeomSnapshots);
944 
945     EXPECT_THAT(mOutput.mState.undefinedRegion, RegionEq(Region(Rect(0, 0, 960, 1080))));
946 }
947 
TEST_F(OutputRebuildLayerStacksTest,addsToDirtyRegionWithNoRotation)948 TEST_F(OutputRebuildLayerStacksTest, addsToDirtyRegionWithNoRotation) {
949     mOutput.mState.transform = kIdentityTransform;
950     mOutput.mState.dirtyRegion = Region(Rect(960, 0, 1920, 1080));
951 
952     mCoverageDirtyRegionToSet = Region(Rect(0, 0, 960, 1080));
953 
954     mOutput.rebuildLayerStacks(mRefreshArgs, mGeomSnapshots);
955 
956     EXPECT_THAT(mOutput.mState.dirtyRegion, RegionEq(Region(Rect(0, 0, 1920, 1080))));
957 }
958 
TEST_F(OutputRebuildLayerStacksTest,addsToDirtyRegionWith90Rotation)959 TEST_F(OutputRebuildLayerStacksTest, addsToDirtyRegionWith90Rotation) {
960     mOutput.mState.transform = kRotate90Transform;
961     mOutput.mState.dirtyRegion = Region(Rect(0, 960, 1080, 1920));
962 
963     mCoverageDirtyRegionToSet = Region(Rect(0, 0, 1080, 960));
964 
965     mOutput.rebuildLayerStacks(mRefreshArgs, mGeomSnapshots);
966 
967     EXPECT_THAT(mOutput.mState.dirtyRegion, RegionEq(Region(Rect(0, 0, 1080, 1920))));
968 }
969 
970 /*
971  * Output::collectVisibleLayers()
972  */
973 
974 struct OutputCollectVisibleLayersTest : public testing::Test {
975     struct OutputPartialMock : public OutputPartialMockBase {
976         // Sets up the helper functions called by the function under test to use
977         // mock implementations.
978         MOCK_METHOD2(ensureOutputLayerIfVisible,
979                      void(sp<compositionengine::LayerFE>&,
980                           compositionengine::Output::CoverageState&));
981         MOCK_METHOD1(setReleasedLayers, void(const compositionengine::CompositionRefreshArgs&));
982         MOCK_METHOD0(finalizePendingOutputLayers, void());
983     };
984 
985     struct Layer {
Layerandroid::compositionengine::__anon0cff14940111::OutputCollectVisibleLayersTest::Layer986         Layer() {
987             EXPECT_CALL(outputLayer, getState()).WillRepeatedly(ReturnRef(outputLayerState));
988             EXPECT_CALL(outputLayer, editState()).WillRepeatedly(ReturnRef(outputLayerState));
989         }
990 
991         StrictMock<mock::OutputLayer> outputLayer;
992         impl::OutputLayerCompositionState outputLayerState;
993         sp<StrictMock<mock::LayerFE>> layerFE{new StrictMock<mock::LayerFE>()};
994     };
995 
OutputCollectVisibleLayersTestandroid::compositionengine::__anon0cff14940111::OutputCollectVisibleLayersTest996     OutputCollectVisibleLayersTest() {
997         EXPECT_CALL(mOutput, getOutputLayerCount()).WillRepeatedly(Return(3u));
998         EXPECT_CALL(mOutput, getOutputLayerOrderedByZByIndex(0))
999                 .WillRepeatedly(Return(&mLayer1.outputLayer));
1000         EXPECT_CALL(mOutput, getOutputLayerOrderedByZByIndex(1))
1001                 .WillRepeatedly(Return(&mLayer2.outputLayer));
1002         EXPECT_CALL(mOutput, getOutputLayerOrderedByZByIndex(2))
1003                 .WillRepeatedly(Return(&mLayer3.outputLayer));
1004 
1005         mRefreshArgs.layers.push_back(mLayer1.layerFE);
1006         mRefreshArgs.layers.push_back(mLayer2.layerFE);
1007         mRefreshArgs.layers.push_back(mLayer3.layerFE);
1008     }
1009 
1010     StrictMock<OutputPartialMock> mOutput;
1011     CompositionRefreshArgs mRefreshArgs;
1012     LayerFESet mGeomSnapshots;
1013     Output::CoverageState mCoverageState{mGeomSnapshots};
1014     Layer mLayer1;
1015     Layer mLayer2;
1016     Layer mLayer3;
1017 };
1018 
TEST_F(OutputCollectVisibleLayersTest,doesMinimalWorkIfNoLayers)1019 TEST_F(OutputCollectVisibleLayersTest, doesMinimalWorkIfNoLayers) {
1020     mRefreshArgs.layers.clear();
1021     EXPECT_CALL(mOutput, getOutputLayerCount()).WillRepeatedly(Return(0u));
1022 
1023     EXPECT_CALL(mOutput, setReleasedLayers(Ref(mRefreshArgs)));
1024     EXPECT_CALL(mOutput, finalizePendingOutputLayers());
1025 
1026     mOutput.collectVisibleLayers(mRefreshArgs, mCoverageState);
1027 }
1028 
TEST_F(OutputCollectVisibleLayersTest,processesCandidateLayersReversedAndSetsOutputLayerZ)1029 TEST_F(OutputCollectVisibleLayersTest, processesCandidateLayersReversedAndSetsOutputLayerZ) {
1030     // Enforce a call order sequence for this test.
1031     InSequence seq;
1032 
1033     // Layer coverage is evaluated from front to back!
1034     EXPECT_CALL(mOutput, ensureOutputLayerIfVisible(Eq(mLayer3.layerFE), Ref(mCoverageState)));
1035     EXPECT_CALL(mOutput, ensureOutputLayerIfVisible(Eq(mLayer2.layerFE), Ref(mCoverageState)));
1036     EXPECT_CALL(mOutput, ensureOutputLayerIfVisible(Eq(mLayer1.layerFE), Ref(mCoverageState)));
1037 
1038     EXPECT_CALL(mOutput, setReleasedLayers(Ref(mRefreshArgs)));
1039     EXPECT_CALL(mOutput, finalizePendingOutputLayers());
1040 
1041     mOutput.collectVisibleLayers(mRefreshArgs, mCoverageState);
1042 
1043     // Ensure all output layers have been assigned a simple/flattened z-order.
1044     EXPECT_EQ(0u, mLayer1.outputLayerState.z);
1045     EXPECT_EQ(1u, mLayer2.outputLayerState.z);
1046     EXPECT_EQ(2u, mLayer3.outputLayerState.z);
1047 }
1048 
1049 /*
1050  * Output::ensureOutputLayerIfVisible()
1051  */
1052 
1053 struct OutputEnsureOutputLayerIfVisibleTest : public testing::Test {
1054     struct OutputPartialMock : public OutputPartialMockBase {
1055         // Sets up the helper functions called by the function under test to use
1056         // mock implementations.
1057         MOCK_CONST_METHOD1(belongsInOutput, bool(const sp<compositionengine::LayerFE>&));
1058         MOCK_CONST_METHOD1(getOutputLayerOrderedByZByIndex, OutputLayer*(size_t));
1059         MOCK_METHOD2(ensureOutputLayer,
1060                      compositionengine::OutputLayer*(std::optional<size_t>, const sp<LayerFE>&));
1061     };
1062 
OutputEnsureOutputLayerIfVisibleTestandroid::compositionengine::__anon0cff14940111::OutputEnsureOutputLayerIfVisibleTest1063     OutputEnsureOutputLayerIfVisibleTest() {
1064         EXPECT_CALL(mOutput, belongsInOutput(sp<LayerFE>(mLayer.layerFE)))
1065                 .WillRepeatedly(Return(true));
1066         EXPECT_CALL(mOutput, getOutputLayerCount()).WillRepeatedly(Return(1u));
1067         EXPECT_CALL(mOutput, getOutputLayerOrderedByZByIndex(0u))
1068                 .WillRepeatedly(Return(&mLayer.outputLayer));
1069 
1070         mOutput.mState.bounds = Rect(0, 0, 200, 300);
1071         mOutput.mState.viewport = Rect(0, 0, 200, 300);
1072         mOutput.mState.transform = ui::Transform(TR_IDENT, 200, 300);
1073 
1074         mLayer.layerFEState.isVisible = true;
1075         mLayer.layerFEState.isOpaque = true;
1076         mLayer.layerFEState.contentDirty = true;
1077         mLayer.layerFEState.geomLayerBounds = FloatRect{0, 0, 100, 200};
1078         mLayer.layerFEState.geomLayerTransform = ui::Transform(TR_IDENT, 100, 200);
1079         mLayer.layerFEState.transparentRegionHint = Region(Rect(0, 0, 100, 100));
1080 
1081         mLayer.outputLayerState.visibleRegion = Region(Rect(0, 0, 50, 200));
1082         mLayer.outputLayerState.coveredRegion = Region(Rect(50, 0, 100, 200));
1083 
1084         mGeomSnapshots.insert(mLayer.layerFE);
1085     }
1086 
ensureOutputLayerIfVisibleandroid::compositionengine::__anon0cff14940111::OutputEnsureOutputLayerIfVisibleTest1087     void ensureOutputLayerIfVisible() {
1088         sp<LayerFE> layerFE(mLayer.layerFE);
1089         mOutput.ensureOutputLayerIfVisible(layerFE, mCoverageState);
1090     }
1091 
1092     static const Region kEmptyRegion;
1093     static const Region kFullBoundsNoRotation;
1094     static const Region kRightHalfBoundsNoRotation;
1095     static const Region kLowerHalfBoundsNoRotation;
1096     static const Region kFullBounds90Rotation;
1097 
1098     StrictMock<OutputPartialMock> mOutput;
1099     LayerFESet mGeomSnapshots;
1100     Output::CoverageState mCoverageState{mGeomSnapshots};
1101 
1102     NonInjectedLayer mLayer;
1103 };
1104 
1105 const Region OutputEnsureOutputLayerIfVisibleTest::kEmptyRegion = Region(Rect(0, 0, 0, 0));
1106 const Region OutputEnsureOutputLayerIfVisibleTest::kFullBoundsNoRotation =
1107         Region(Rect(0, 0, 100, 200));
1108 const Region OutputEnsureOutputLayerIfVisibleTest::kRightHalfBoundsNoRotation =
1109         Region(Rect(0, 100, 100, 200));
1110 const Region OutputEnsureOutputLayerIfVisibleTest::kLowerHalfBoundsNoRotation =
1111         Region(Rect(50, 0, 100, 200));
1112 const Region OutputEnsureOutputLayerIfVisibleTest::kFullBounds90Rotation =
1113         Region(Rect(0, 0, 200, 100));
1114 
TEST_F(OutputEnsureOutputLayerIfVisibleTest,performsGeomLatchBeforeCheckingIfLayerBelongs)1115 TEST_F(OutputEnsureOutputLayerIfVisibleTest, performsGeomLatchBeforeCheckingIfLayerBelongs) {
1116     EXPECT_CALL(mOutput, belongsInOutput(sp<LayerFE>(mLayer.layerFE))).WillOnce(Return(false));
1117     EXPECT_CALL(*mLayer.layerFE,
1118                 prepareCompositionState(compositionengine::LayerFE::StateSubset::BasicGeometry));
1119 
1120     mGeomSnapshots.clear();
1121 
1122     ensureOutputLayerIfVisible();
1123 }
1124 
TEST_F(OutputEnsureOutputLayerIfVisibleTest,skipsLatchIfAlreadyLatchedBeforeCheckingIfLayerBelongs)1125 TEST_F(OutputEnsureOutputLayerIfVisibleTest,
1126        skipsLatchIfAlreadyLatchedBeforeCheckingIfLayerBelongs) {
1127     EXPECT_CALL(mOutput, belongsInOutput(sp<LayerFE>(mLayer.layerFE))).WillOnce(Return(false));
1128 
1129     ensureOutputLayerIfVisible();
1130 }
1131 
TEST_F(OutputEnsureOutputLayerIfVisibleTest,takesEarlyOutIfLayerHasNoCompositionState)1132 TEST_F(OutputEnsureOutputLayerIfVisibleTest, takesEarlyOutIfLayerHasNoCompositionState) {
1133     EXPECT_CALL(*mLayer.layerFE, getCompositionState()).WillOnce(Return(nullptr));
1134 
1135     ensureOutputLayerIfVisible();
1136 }
1137 
TEST_F(OutputEnsureOutputLayerIfVisibleTest,takesEarlyOutIfLayerNotVisible)1138 TEST_F(OutputEnsureOutputLayerIfVisibleTest, takesEarlyOutIfLayerNotVisible) {
1139     mLayer.layerFEState.isVisible = false;
1140 
1141     ensureOutputLayerIfVisible();
1142 }
1143 
TEST_F(OutputEnsureOutputLayerIfVisibleTest,takesEarlyOutIfLayerHasEmptyVisibleRegion)1144 TEST_F(OutputEnsureOutputLayerIfVisibleTest, takesEarlyOutIfLayerHasEmptyVisibleRegion) {
1145     mLayer.layerFEState.geomLayerBounds = FloatRect{0, 0, 0, 0};
1146 
1147     ensureOutputLayerIfVisible();
1148 }
1149 
TEST_F(OutputEnsureOutputLayerIfVisibleTest,takesNotSoEarlyOutifDrawRegionEmpty)1150 TEST_F(OutputEnsureOutputLayerIfVisibleTest, takesNotSoEarlyOutifDrawRegionEmpty) {
1151     mOutput.mState.bounds = Rect(0, 0, 0, 0);
1152 
1153     ensureOutputLayerIfVisible();
1154 }
1155 
TEST_F(OutputEnsureOutputLayerIfVisibleTest,handlesCreatingOutputLayerForOpaqueDirtyNotRotatedLayer)1156 TEST_F(OutputEnsureOutputLayerIfVisibleTest,
1157        handlesCreatingOutputLayerForOpaqueDirtyNotRotatedLayer) {
1158     mLayer.layerFEState.isOpaque = true;
1159     mLayer.layerFEState.contentDirty = true;
1160     mLayer.layerFEState.geomLayerTransform = ui::Transform(TR_IDENT, 100, 200);
1161 
1162     EXPECT_CALL(mOutput, getOutputLayerCount()).WillOnce(Return(0u));
1163     EXPECT_CALL(mOutput, ensureOutputLayer(Eq(std::nullopt), Eq(mLayer.layerFE)))
1164             .WillOnce(Return(&mLayer.outputLayer));
1165 
1166     ensureOutputLayerIfVisible();
1167 
1168     EXPECT_THAT(mCoverageState.dirtyRegion, RegionEq(kFullBoundsNoRotation));
1169     EXPECT_THAT(mCoverageState.aboveCoveredLayers, RegionEq(kFullBoundsNoRotation));
1170     EXPECT_THAT(mCoverageState.aboveOpaqueLayers, RegionEq(kFullBoundsNoRotation));
1171 
1172     EXPECT_THAT(mLayer.outputLayerState.visibleRegion, RegionEq(kFullBoundsNoRotation));
1173     EXPECT_THAT(mLayer.outputLayerState.visibleNonTransparentRegion,
1174                 RegionEq(kFullBoundsNoRotation));
1175     EXPECT_THAT(mLayer.outputLayerState.coveredRegion, RegionEq(kEmptyRegion));
1176     EXPECT_THAT(mLayer.outputLayerState.outputSpaceVisibleRegion, RegionEq(kFullBoundsNoRotation));
1177 }
1178 
TEST_F(OutputEnsureOutputLayerIfVisibleTest,handlesUpdatingOutputLayerForOpaqueDirtyNotRotatedLayer)1179 TEST_F(OutputEnsureOutputLayerIfVisibleTest,
1180        handlesUpdatingOutputLayerForOpaqueDirtyNotRotatedLayer) {
1181     mLayer.layerFEState.isOpaque = true;
1182     mLayer.layerFEState.contentDirty = true;
1183     mLayer.layerFEState.geomLayerTransform = ui::Transform(TR_IDENT, 100, 200);
1184 
1185     EXPECT_CALL(mOutput, ensureOutputLayer(Eq(0u), Eq(mLayer.layerFE)))
1186             .WillOnce(Return(&mLayer.outputLayer));
1187 
1188     ensureOutputLayerIfVisible();
1189 
1190     EXPECT_THAT(mCoverageState.dirtyRegion, RegionEq(kFullBoundsNoRotation));
1191     EXPECT_THAT(mCoverageState.aboveCoveredLayers, RegionEq(kFullBoundsNoRotation));
1192     EXPECT_THAT(mCoverageState.aboveOpaqueLayers, RegionEq(kFullBoundsNoRotation));
1193 
1194     EXPECT_THAT(mLayer.outputLayerState.visibleRegion, RegionEq(kFullBoundsNoRotation));
1195     EXPECT_THAT(mLayer.outputLayerState.visibleNonTransparentRegion,
1196                 RegionEq(kFullBoundsNoRotation));
1197     EXPECT_THAT(mLayer.outputLayerState.coveredRegion, RegionEq(kEmptyRegion));
1198     EXPECT_THAT(mLayer.outputLayerState.outputSpaceVisibleRegion, RegionEq(kFullBoundsNoRotation));
1199 }
1200 
TEST_F(OutputEnsureOutputLayerIfVisibleTest,handlesCreatingOutputLayerForTransparentDirtyNotRotatedLayer)1201 TEST_F(OutputEnsureOutputLayerIfVisibleTest,
1202        handlesCreatingOutputLayerForTransparentDirtyNotRotatedLayer) {
1203     mLayer.layerFEState.isOpaque = false;
1204     mLayer.layerFEState.contentDirty = true;
1205     mLayer.layerFEState.geomLayerTransform = ui::Transform(TR_IDENT, 100, 200);
1206 
1207     EXPECT_CALL(mOutput, getOutputLayerCount()).WillOnce(Return(0u));
1208     EXPECT_CALL(mOutput, ensureOutputLayer(Eq(std::nullopt), Eq(mLayer.layerFE)))
1209             .WillOnce(Return(&mLayer.outputLayer));
1210 
1211     ensureOutputLayerIfVisible();
1212 
1213     EXPECT_THAT(mCoverageState.dirtyRegion, RegionEq(kFullBoundsNoRotation));
1214     EXPECT_THAT(mCoverageState.aboveCoveredLayers, RegionEq(kFullBoundsNoRotation));
1215     EXPECT_THAT(mCoverageState.aboveOpaqueLayers, RegionEq(kEmptyRegion));
1216 
1217     EXPECT_THAT(mLayer.outputLayerState.visibleRegion, RegionEq(kFullBoundsNoRotation));
1218     EXPECT_THAT(mLayer.outputLayerState.visibleNonTransparentRegion,
1219                 RegionEq(kRightHalfBoundsNoRotation));
1220     EXPECT_THAT(mLayer.outputLayerState.coveredRegion, RegionEq(kEmptyRegion));
1221     EXPECT_THAT(mLayer.outputLayerState.outputSpaceVisibleRegion, RegionEq(kFullBoundsNoRotation));
1222 }
1223 
TEST_F(OutputEnsureOutputLayerIfVisibleTest,handlesUpdatingOutputLayerForTransparentDirtyNotRotatedLayer)1224 TEST_F(OutputEnsureOutputLayerIfVisibleTest,
1225        handlesUpdatingOutputLayerForTransparentDirtyNotRotatedLayer) {
1226     mLayer.layerFEState.isOpaque = false;
1227     mLayer.layerFEState.contentDirty = true;
1228     mLayer.layerFEState.geomLayerTransform = ui::Transform(TR_IDENT, 100, 200);
1229 
1230     EXPECT_CALL(mOutput, ensureOutputLayer(Eq(0u), Eq(mLayer.layerFE)))
1231             .WillOnce(Return(&mLayer.outputLayer));
1232 
1233     ensureOutputLayerIfVisible();
1234 
1235     EXPECT_THAT(mCoverageState.dirtyRegion, RegionEq(kFullBoundsNoRotation));
1236     EXPECT_THAT(mCoverageState.aboveCoveredLayers, RegionEq(kFullBoundsNoRotation));
1237     EXPECT_THAT(mCoverageState.aboveOpaqueLayers, RegionEq(kEmptyRegion));
1238 
1239     EXPECT_THAT(mLayer.outputLayerState.visibleRegion, RegionEq(kFullBoundsNoRotation));
1240     EXPECT_THAT(mLayer.outputLayerState.visibleNonTransparentRegion,
1241                 RegionEq(kRightHalfBoundsNoRotation));
1242     EXPECT_THAT(mLayer.outputLayerState.coveredRegion, RegionEq(kEmptyRegion));
1243     EXPECT_THAT(mLayer.outputLayerState.outputSpaceVisibleRegion, RegionEq(kFullBoundsNoRotation));
1244 }
1245 
TEST_F(OutputEnsureOutputLayerIfVisibleTest,handlesCreatingOutputLayerForOpaqueNonDirtyNotRotatedLayer)1246 TEST_F(OutputEnsureOutputLayerIfVisibleTest,
1247        handlesCreatingOutputLayerForOpaqueNonDirtyNotRotatedLayer) {
1248     mLayer.layerFEState.isOpaque = true;
1249     mLayer.layerFEState.contentDirty = false;
1250     mLayer.layerFEState.geomLayerTransform = ui::Transform(TR_IDENT, 100, 200);
1251 
1252     EXPECT_CALL(mOutput, getOutputLayerCount()).WillOnce(Return(0u));
1253     EXPECT_CALL(mOutput, ensureOutputLayer(Eq(std::nullopt), Eq(mLayer.layerFE)))
1254             .WillOnce(Return(&mLayer.outputLayer));
1255 
1256     ensureOutputLayerIfVisible();
1257 
1258     EXPECT_THAT(mCoverageState.dirtyRegion, RegionEq(kFullBoundsNoRotation));
1259     EXPECT_THAT(mCoverageState.aboveCoveredLayers, RegionEq(kFullBoundsNoRotation));
1260     EXPECT_THAT(mCoverageState.aboveOpaqueLayers, RegionEq(kFullBoundsNoRotation));
1261 
1262     EXPECT_THAT(mLayer.outputLayerState.visibleRegion, RegionEq(kFullBoundsNoRotation));
1263     EXPECT_THAT(mLayer.outputLayerState.visibleNonTransparentRegion,
1264                 RegionEq(kFullBoundsNoRotation));
1265     EXPECT_THAT(mLayer.outputLayerState.coveredRegion, RegionEq(kEmptyRegion));
1266     EXPECT_THAT(mLayer.outputLayerState.outputSpaceVisibleRegion, RegionEq(kFullBoundsNoRotation));
1267 }
1268 
TEST_F(OutputEnsureOutputLayerIfVisibleTest,handlesUpdatingOutputLayerForOpaqueNonDirtyNotRotatedLayer)1269 TEST_F(OutputEnsureOutputLayerIfVisibleTest,
1270        handlesUpdatingOutputLayerForOpaqueNonDirtyNotRotatedLayer) {
1271     mLayer.layerFEState.isOpaque = true;
1272     mLayer.layerFEState.contentDirty = false;
1273     mLayer.layerFEState.geomLayerTransform = ui::Transform(TR_IDENT, 100, 200);
1274 
1275     EXPECT_CALL(mOutput, ensureOutputLayer(Eq(0u), Eq(mLayer.layerFE)))
1276             .WillOnce(Return(&mLayer.outputLayer));
1277 
1278     ensureOutputLayerIfVisible();
1279 
1280     EXPECT_THAT(mCoverageState.dirtyRegion, RegionEq(kLowerHalfBoundsNoRotation));
1281     EXPECT_THAT(mCoverageState.aboveCoveredLayers, RegionEq(kFullBoundsNoRotation));
1282     EXPECT_THAT(mCoverageState.aboveOpaqueLayers, RegionEq(kFullBoundsNoRotation));
1283 
1284     EXPECT_THAT(mLayer.outputLayerState.visibleRegion, RegionEq(kFullBoundsNoRotation));
1285     EXPECT_THAT(mLayer.outputLayerState.visibleNonTransparentRegion,
1286                 RegionEq(kFullBoundsNoRotation));
1287     EXPECT_THAT(mLayer.outputLayerState.coveredRegion, RegionEq(kEmptyRegion));
1288     EXPECT_THAT(mLayer.outputLayerState.outputSpaceVisibleRegion, RegionEq(kFullBoundsNoRotation));
1289 }
1290 
TEST_F(OutputEnsureOutputLayerIfVisibleTest,handlesCreatingOutputLayerForOpaqueDirtyRotated90Layer)1291 TEST_F(OutputEnsureOutputLayerIfVisibleTest,
1292        handlesCreatingOutputLayerForOpaqueDirtyRotated90Layer) {
1293     mLayer.layerFEState.isOpaque = true;
1294     mLayer.layerFEState.contentDirty = true;
1295     mLayer.layerFEState.geomLayerBounds = FloatRect{0, 0, 200, 100};
1296     mLayer.layerFEState.geomLayerTransform = ui::Transform(TR_ROT_90, 100, 200);
1297     mLayer.outputLayerState.visibleRegion = Region(Rect(0, 0, 100, 100));
1298     mLayer.outputLayerState.coveredRegion = Region(Rect(100, 0, 200, 100));
1299 
1300     EXPECT_CALL(mOutput, getOutputLayerCount()).WillOnce(Return(0u));
1301     EXPECT_CALL(mOutput, ensureOutputLayer(Eq(std::nullopt), Eq(mLayer.layerFE)))
1302             .WillOnce(Return(&mLayer.outputLayer));
1303 
1304     ensureOutputLayerIfVisible();
1305 
1306     EXPECT_THAT(mCoverageState.dirtyRegion, RegionEq(kFullBoundsNoRotation));
1307     EXPECT_THAT(mCoverageState.aboveCoveredLayers, RegionEq(kFullBoundsNoRotation));
1308     EXPECT_THAT(mCoverageState.aboveOpaqueLayers, RegionEq(kFullBoundsNoRotation));
1309 
1310     EXPECT_THAT(mLayer.outputLayerState.visibleRegion, RegionEq(kFullBoundsNoRotation));
1311     EXPECT_THAT(mLayer.outputLayerState.visibleNonTransparentRegion,
1312                 RegionEq(kFullBoundsNoRotation));
1313     EXPECT_THAT(mLayer.outputLayerState.coveredRegion, RegionEq(kEmptyRegion));
1314     EXPECT_THAT(mLayer.outputLayerState.outputSpaceVisibleRegion, RegionEq(kFullBoundsNoRotation));
1315 }
1316 
TEST_F(OutputEnsureOutputLayerIfVisibleTest,handlesUpdatingOutputLayerForOpaqueDirtyRotated90Layer)1317 TEST_F(OutputEnsureOutputLayerIfVisibleTest,
1318        handlesUpdatingOutputLayerForOpaqueDirtyRotated90Layer) {
1319     mLayer.layerFEState.isOpaque = true;
1320     mLayer.layerFEState.contentDirty = true;
1321     mLayer.layerFEState.geomLayerBounds = FloatRect{0, 0, 200, 100};
1322     mLayer.layerFEState.geomLayerTransform = ui::Transform(TR_ROT_90, 100, 200);
1323     mLayer.outputLayerState.visibleRegion = Region(Rect(0, 0, 100, 100));
1324     mLayer.outputLayerState.coveredRegion = Region(Rect(100, 0, 200, 100));
1325 
1326     EXPECT_CALL(mOutput, ensureOutputLayer(Eq(0u), Eq(mLayer.layerFE)))
1327             .WillOnce(Return(&mLayer.outputLayer));
1328 
1329     ensureOutputLayerIfVisible();
1330 
1331     EXPECT_THAT(mCoverageState.dirtyRegion, RegionEq(kFullBoundsNoRotation));
1332     EXPECT_THAT(mCoverageState.aboveCoveredLayers, RegionEq(kFullBoundsNoRotation));
1333     EXPECT_THAT(mCoverageState.aboveOpaqueLayers, RegionEq(kFullBoundsNoRotation));
1334 
1335     EXPECT_THAT(mLayer.outputLayerState.visibleRegion, RegionEq(kFullBoundsNoRotation));
1336     EXPECT_THAT(mLayer.outputLayerState.visibleNonTransparentRegion,
1337                 RegionEq(kFullBoundsNoRotation));
1338     EXPECT_THAT(mLayer.outputLayerState.coveredRegion, RegionEq(kEmptyRegion));
1339     EXPECT_THAT(mLayer.outputLayerState.outputSpaceVisibleRegion, RegionEq(kFullBoundsNoRotation));
1340 }
1341 
TEST_F(OutputEnsureOutputLayerIfVisibleTest,handlesCreatingOutputLayerForOpaqueDirtyNotRotatedLayerRotatedOutput)1342 TEST_F(OutputEnsureOutputLayerIfVisibleTest,
1343        handlesCreatingOutputLayerForOpaqueDirtyNotRotatedLayerRotatedOutput) {
1344     mLayer.layerFEState.isOpaque = true;
1345     mLayer.layerFEState.contentDirty = true;
1346     mLayer.layerFEState.geomLayerTransform = ui::Transform(TR_IDENT, 100, 200);
1347 
1348     mOutput.mState.viewport = Rect(0, 0, 300, 200);
1349     mOutput.mState.transform = ui::Transform(TR_ROT_90, 200, 300);
1350 
1351     EXPECT_CALL(mOutput, getOutputLayerCount()).WillOnce(Return(0u));
1352     EXPECT_CALL(mOutput, ensureOutputLayer(Eq(std::nullopt), Eq(mLayer.layerFE)))
1353             .WillOnce(Return(&mLayer.outputLayer));
1354 
1355     ensureOutputLayerIfVisible();
1356 
1357     EXPECT_THAT(mCoverageState.dirtyRegion, RegionEq(kFullBoundsNoRotation));
1358     EXPECT_THAT(mCoverageState.aboveCoveredLayers, RegionEq(kFullBoundsNoRotation));
1359     EXPECT_THAT(mCoverageState.aboveOpaqueLayers, RegionEq(kFullBoundsNoRotation));
1360 
1361     EXPECT_THAT(mLayer.outputLayerState.visibleRegion, RegionEq(kFullBoundsNoRotation));
1362     EXPECT_THAT(mLayer.outputLayerState.visibleNonTransparentRegion,
1363                 RegionEq(kFullBoundsNoRotation));
1364     EXPECT_THAT(mLayer.outputLayerState.coveredRegion, RegionEq(kEmptyRegion));
1365     EXPECT_THAT(mLayer.outputLayerState.outputSpaceVisibleRegion, RegionEq(kFullBounds90Rotation));
1366 }
1367 
TEST_F(OutputEnsureOutputLayerIfVisibleTest,handlesUpdatingOutputLayerForOpaqueDirtyNotRotatedLayerRotatedOutput)1368 TEST_F(OutputEnsureOutputLayerIfVisibleTest,
1369        handlesUpdatingOutputLayerForOpaqueDirtyNotRotatedLayerRotatedOutput) {
1370     mLayer.layerFEState.isOpaque = true;
1371     mLayer.layerFEState.contentDirty = true;
1372     mLayer.layerFEState.geomLayerTransform = ui::Transform(TR_IDENT, 100, 200);
1373 
1374     mOutput.mState.viewport = Rect(0, 0, 300, 200);
1375     mOutput.mState.transform = ui::Transform(TR_ROT_90, 200, 300);
1376 
1377     EXPECT_CALL(mOutput, ensureOutputLayer(Eq(0u), Eq(mLayer.layerFE)))
1378             .WillOnce(Return(&mLayer.outputLayer));
1379 
1380     ensureOutputLayerIfVisible();
1381 
1382     EXPECT_THAT(mCoverageState.dirtyRegion, RegionEq(kFullBoundsNoRotation));
1383     EXPECT_THAT(mCoverageState.aboveCoveredLayers, RegionEq(kFullBoundsNoRotation));
1384     EXPECT_THAT(mCoverageState.aboveOpaqueLayers, RegionEq(kFullBoundsNoRotation));
1385 
1386     EXPECT_THAT(mLayer.outputLayerState.visibleRegion, RegionEq(kFullBoundsNoRotation));
1387     EXPECT_THAT(mLayer.outputLayerState.visibleNonTransparentRegion,
1388                 RegionEq(kFullBoundsNoRotation));
1389     EXPECT_THAT(mLayer.outputLayerState.coveredRegion, RegionEq(kEmptyRegion));
1390     EXPECT_THAT(mLayer.outputLayerState.outputSpaceVisibleRegion, RegionEq(kFullBounds90Rotation));
1391 }
1392 
TEST_F(OutputEnsureOutputLayerIfVisibleTest,handlesCreatingOutputLayerForOpaqueDirtyArbitraryTransformLayer)1393 TEST_F(OutputEnsureOutputLayerIfVisibleTest,
1394        handlesCreatingOutputLayerForOpaqueDirtyArbitraryTransformLayer) {
1395     ui::Transform arbitraryTransform;
1396     arbitraryTransform.set(1, 1, -1, 1);
1397     arbitraryTransform.set(0, 100);
1398 
1399     mLayer.layerFEState.isOpaque = true;
1400     mLayer.layerFEState.contentDirty = true;
1401     mLayer.layerFEState.geomLayerBounds = FloatRect{0, 0, 100, 200};
1402     mLayer.layerFEState.geomLayerTransform = arbitraryTransform;
1403 
1404     EXPECT_CALL(mOutput, getOutputLayerCount()).WillOnce(Return(0u));
1405     EXPECT_CALL(mOutput, ensureOutputLayer(Eq(std::nullopt), Eq(mLayer.layerFE)))
1406             .WillOnce(Return(&mLayer.outputLayer));
1407 
1408     ensureOutputLayerIfVisible();
1409 
1410     const Region kRegion = Region(Rect(0, 0, 300, 300));
1411     const Region kRegionClipped = Region(Rect(0, 0, 200, 300));
1412 
1413     EXPECT_THAT(mCoverageState.dirtyRegion, RegionEq(kRegion));
1414     EXPECT_THAT(mCoverageState.aboveCoveredLayers, RegionEq(kRegion));
1415     EXPECT_THAT(mCoverageState.aboveOpaqueLayers, RegionEq(kEmptyRegion));
1416 
1417     EXPECT_THAT(mLayer.outputLayerState.visibleRegion, RegionEq(kRegion));
1418     EXPECT_THAT(mLayer.outputLayerState.visibleNonTransparentRegion, RegionEq(kRegion));
1419     EXPECT_THAT(mLayer.outputLayerState.coveredRegion, RegionEq(kEmptyRegion));
1420     EXPECT_THAT(mLayer.outputLayerState.outputSpaceVisibleRegion, RegionEq(kRegionClipped));
1421 }
1422 
TEST_F(OutputEnsureOutputLayerIfVisibleTest,coverageAccumulatesTest)1423 TEST_F(OutputEnsureOutputLayerIfVisibleTest, coverageAccumulatesTest) {
1424     mLayer.layerFEState.isOpaque = false;
1425     mLayer.layerFEState.contentDirty = true;
1426     mLayer.layerFEState.geomLayerTransform = ui::Transform(TR_IDENT, 100, 200);
1427 
1428     mCoverageState.dirtyRegion = Region(Rect(0, 0, 500, 500));
1429     mCoverageState.aboveCoveredLayers = Region(Rect(50, 0, 150, 200));
1430     mCoverageState.aboveOpaqueLayers = Region(Rect(50, 0, 150, 200));
1431 
1432     EXPECT_CALL(mOutput, ensureOutputLayer(Eq(0u), Eq(mLayer.layerFE)))
1433             .WillOnce(Return(&mLayer.outputLayer));
1434 
1435     ensureOutputLayerIfVisible();
1436 
1437     const Region kExpectedDirtyRegion = Region(Rect(0, 0, 500, 500));
1438     const Region kExpectedAboveCoveredRegion = Region(Rect(0, 0, 150, 200));
1439     const Region kExpectedAboveOpaqueRegion = Region(Rect(50, 0, 150, 200));
1440     const Region kExpectedLayerVisibleRegion = Region(Rect(0, 0, 50, 200));
1441     const Region kExpectedLayerCoveredRegion = Region(Rect(50, 0, 100, 200));
1442     const Region kExpectedLayerVisibleNonTransparentRegion = Region(Rect(0, 100, 50, 200));
1443 
1444     EXPECT_THAT(mCoverageState.dirtyRegion, RegionEq(kExpectedDirtyRegion));
1445     EXPECT_THAT(mCoverageState.aboveCoveredLayers, RegionEq(kExpectedAboveCoveredRegion));
1446     EXPECT_THAT(mCoverageState.aboveOpaqueLayers, RegionEq(kExpectedAboveOpaqueRegion));
1447 
1448     EXPECT_THAT(mLayer.outputLayerState.visibleRegion, RegionEq(kExpectedLayerVisibleRegion));
1449     EXPECT_THAT(mLayer.outputLayerState.visibleNonTransparentRegion,
1450                 RegionEq(kExpectedLayerVisibleNonTransparentRegion));
1451     EXPECT_THAT(mLayer.outputLayerState.coveredRegion, RegionEq(kExpectedLayerCoveredRegion));
1452     EXPECT_THAT(mLayer.outputLayerState.outputSpaceVisibleRegion,
1453                 RegionEq(kExpectedLayerVisibleRegion));
1454 }
1455 
TEST_F(OutputEnsureOutputLayerIfVisibleTest,coverageAccumulatesWithShadowsTest)1456 TEST_F(OutputEnsureOutputLayerIfVisibleTest, coverageAccumulatesWithShadowsTest) {
1457     ui::Transform translate;
1458     translate.set(50, 50);
1459     mLayer.layerFEState.geomLayerTransform = translate;
1460     mLayer.layerFEState.shadowRadius = 10.0f;
1461 
1462     mCoverageState.dirtyRegion = Region(Rect(0, 0, 500, 500));
1463     // half of the layer including the casting shadow is covered and opaque
1464     mCoverageState.aboveCoveredLayers = Region(Rect(40, 40, 100, 260));
1465     mCoverageState.aboveOpaqueLayers = Region(Rect(40, 40, 100, 260));
1466 
1467     EXPECT_CALL(mOutput, ensureOutputLayer(Eq(0u), Eq(mLayer.layerFE)))
1468             .WillOnce(Return(&mLayer.outputLayer));
1469 
1470     ensureOutputLayerIfVisible();
1471 
1472     const Region kExpectedDirtyRegion = Region(Rect(0, 0, 500, 500));
1473     const Region kExpectedAboveCoveredRegion = Region(Rect(40, 40, 160, 260));
1474     // add starting opaque region to the opaque half of the casting layer bounds
1475     const Region kExpectedAboveOpaqueRegion =
1476             Region(Rect(40, 40, 100, 260)).orSelf(Rect(100, 50, 150, 250));
1477     const Region kExpectedLayerVisibleRegion = Region(Rect(100, 40, 160, 260));
1478     const Region kExpectedoutputSpaceLayerVisibleRegion = Region(Rect(100, 50, 150, 250));
1479     const Region kExpectedLayerCoveredRegion = Region(Rect(40, 40, 100, 260));
1480     const Region kExpectedLayerVisibleNonTransparentRegion = Region(Rect(100, 40, 160, 260));
1481     const Region kExpectedLayerShadowRegion =
1482             Region(Rect(40, 40, 160, 260)).subtractSelf(Rect(50, 50, 150, 250));
1483 
1484     EXPECT_THAT(mCoverageState.dirtyRegion, RegionEq(kExpectedDirtyRegion));
1485     EXPECT_THAT(mCoverageState.aboveCoveredLayers, RegionEq(kExpectedAboveCoveredRegion));
1486     EXPECT_THAT(mCoverageState.aboveOpaqueLayers, RegionEq(kExpectedAboveOpaqueRegion));
1487 
1488     EXPECT_THAT(mLayer.outputLayerState.visibleRegion, RegionEq(kExpectedLayerVisibleRegion));
1489     EXPECT_THAT(mLayer.outputLayerState.visibleNonTransparentRegion,
1490                 RegionEq(kExpectedLayerVisibleNonTransparentRegion));
1491     EXPECT_THAT(mLayer.outputLayerState.coveredRegion, RegionEq(kExpectedLayerCoveredRegion));
1492     EXPECT_THAT(mLayer.outputLayerState.outputSpaceVisibleRegion,
1493                 RegionEq(kExpectedoutputSpaceLayerVisibleRegion));
1494     EXPECT_THAT(mLayer.outputLayerState.shadowRegion, RegionEq(kExpectedLayerShadowRegion));
1495     EXPECT_FALSE(kExpectedLayerVisibleRegion.subtract(kExpectedLayerShadowRegion).isEmpty());
1496 }
1497 
TEST_F(OutputEnsureOutputLayerIfVisibleTest,shadowRegionOnlyTest)1498 TEST_F(OutputEnsureOutputLayerIfVisibleTest, shadowRegionOnlyTest) {
1499     ui::Transform translate;
1500     translate.set(50, 50);
1501     mLayer.layerFEState.geomLayerTransform = translate;
1502     mLayer.layerFEState.shadowRadius = 10.0f;
1503 
1504     mCoverageState.dirtyRegion = Region(Rect(0, 0, 500, 500));
1505     // Casting layer is covered by an opaque region leaving only part of its shadow to be drawn
1506     mCoverageState.aboveCoveredLayers = Region(Rect(40, 40, 150, 260));
1507     mCoverageState.aboveOpaqueLayers = Region(Rect(40, 40, 150, 260));
1508 
1509     EXPECT_CALL(mOutput, ensureOutputLayer(Eq(0u), Eq(mLayer.layerFE)))
1510             .WillOnce(Return(&mLayer.outputLayer));
1511 
1512     ensureOutputLayerIfVisible();
1513 
1514     const Region kExpectedLayerVisibleRegion = Region(Rect(150, 40, 160, 260));
1515     const Region kExpectedLayerShadowRegion =
1516             Region(Rect(40, 40, 160, 260)).subtractSelf(Rect(50, 50, 150, 250));
1517 
1518     EXPECT_THAT(mLayer.outputLayerState.visibleRegion, RegionEq(kExpectedLayerVisibleRegion));
1519     EXPECT_THAT(mLayer.outputLayerState.shadowRegion, RegionEq(kExpectedLayerShadowRegion));
1520     EXPECT_TRUE(kExpectedLayerVisibleRegion.subtract(kExpectedLayerShadowRegion).isEmpty());
1521 }
1522 
TEST_F(OutputEnsureOutputLayerIfVisibleTest,takesNotSoEarlyOutifLayerWithShadowIsCovered)1523 TEST_F(OutputEnsureOutputLayerIfVisibleTest, takesNotSoEarlyOutifLayerWithShadowIsCovered) {
1524     ui::Transform translate;
1525     translate.set(50, 50);
1526     mLayer.layerFEState.geomLayerTransform = translate;
1527     mLayer.layerFEState.shadowRadius = 10.0f;
1528 
1529     mCoverageState.dirtyRegion = Region(Rect(0, 0, 500, 500));
1530     // Casting layer and its shadows are covered by an opaque region
1531     mCoverageState.aboveCoveredLayers = Region(Rect(40, 40, 160, 260));
1532     mCoverageState.aboveOpaqueLayers = Region(Rect(40, 40, 160, 260));
1533 
1534     ensureOutputLayerIfVisible();
1535 }
1536 
1537 /*
1538  * Output::present()
1539  */
1540 
1541 struct OutputPresentTest : public testing::Test {
1542     struct OutputPartialMock : public OutputPartialMockBase {
1543         // Sets up the helper functions called by the function under test to use
1544         // mock implementations.
1545         MOCK_METHOD1(updateColorProfile, void(const compositionengine::CompositionRefreshArgs&));
1546         MOCK_METHOD1(updateAndWriteCompositionState,
1547                      void(const compositionengine::CompositionRefreshArgs&));
1548         MOCK_METHOD1(setColorTransform, void(const compositionengine::CompositionRefreshArgs&));
1549         MOCK_METHOD0(beginFrame, void());
1550         MOCK_METHOD0(prepareFrame, void());
1551         MOCK_METHOD1(devOptRepaintFlash, void(const compositionengine::CompositionRefreshArgs&));
1552         MOCK_METHOD1(finishFrame, void(const compositionengine::CompositionRefreshArgs&));
1553         MOCK_METHOD0(postFramebuffer, void());
1554     };
1555 
1556     StrictMock<OutputPartialMock> mOutput;
1557 };
1558 
TEST_F(OutputPresentTest,justInvokesChildFunctionsInSequence)1559 TEST_F(OutputPresentTest, justInvokesChildFunctionsInSequence) {
1560     CompositionRefreshArgs args;
1561 
1562     InSequence seq;
1563     EXPECT_CALL(mOutput, updateColorProfile(Ref(args)));
1564     EXPECT_CALL(mOutput, updateAndWriteCompositionState(Ref(args)));
1565     EXPECT_CALL(mOutput, setColorTransform(Ref(args)));
1566     EXPECT_CALL(mOutput, beginFrame());
1567     EXPECT_CALL(mOutput, prepareFrame());
1568     EXPECT_CALL(mOutput, devOptRepaintFlash(Ref(args)));
1569     EXPECT_CALL(mOutput, finishFrame(Ref(args)));
1570     EXPECT_CALL(mOutput, postFramebuffer());
1571 
1572     mOutput.present(args);
1573 }
1574 
1575 /*
1576  * Output::updateColorProfile()
1577  */
1578 
1579 struct OutputUpdateColorProfileTest : public testing::Test {
1580     using TestType = OutputUpdateColorProfileTest;
1581 
1582     struct OutputPartialMock : public OutputPartialMockBase {
1583         // Sets up the helper functions called by the function under test to use
1584         // mock implementations.
1585         MOCK_METHOD1(setColorProfile, void(const ColorProfile&));
1586     };
1587 
1588     struct Layer {
Layerandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest::Layer1589         Layer() {
1590             EXPECT_CALL(mOutputLayer, getLayerFE()).WillRepeatedly(ReturnRef(mLayerFE));
1591             EXPECT_CALL(mLayerFE, getCompositionState()).WillRepeatedly(Return(&mLayerFEState));
1592         }
1593 
1594         StrictMock<mock::OutputLayer> mOutputLayer;
1595         StrictMock<mock::LayerFE> mLayerFE;
1596         LayerFECompositionState mLayerFEState;
1597     };
1598 
OutputUpdateColorProfileTestandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest1599     OutputUpdateColorProfileTest() {
1600         mOutput.setDisplayColorProfileForTest(
1601                 std::unique_ptr<DisplayColorProfile>(mDisplayColorProfile));
1602         mOutput.setRenderSurfaceForTest(std::unique_ptr<RenderSurface>(mRenderSurface));
1603 
1604         EXPECT_CALL(mOutput, getOutputLayerOrderedByZByIndex(0))
1605                 .WillRepeatedly(Return(&mLayer1.mOutputLayer));
1606         EXPECT_CALL(mOutput, getOutputLayerOrderedByZByIndex(1))
1607                 .WillRepeatedly(Return(&mLayer2.mOutputLayer));
1608         EXPECT_CALL(mOutput, getOutputLayerOrderedByZByIndex(2))
1609                 .WillRepeatedly(Return(&mLayer3.mOutputLayer));
1610     }
1611 
1612     struct ExecuteState : public CallOrderStateMachineHelper<TestType, ExecuteState> {
executeandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest::ExecuteState1613         void execute() { getInstance()->mOutput.updateColorProfile(getInstance()->mRefreshArgs); }
1614     };
1615 
1616     mock::DisplayColorProfile* mDisplayColorProfile = new StrictMock<mock::DisplayColorProfile>();
1617     mock::RenderSurface* mRenderSurface = new StrictMock<mock::RenderSurface>();
1618     StrictMock<OutputPartialMock> mOutput;
1619 
1620     Layer mLayer1;
1621     Layer mLayer2;
1622     Layer mLayer3;
1623 
1624     CompositionRefreshArgs mRefreshArgs;
1625 };
1626 
1627 // TODO(b/144522012): Refactor Output::updateColorProfile and the related code
1628 // to make it easier to write unit tests.
1629 
TEST_F(OutputUpdateColorProfileTest,setsAColorProfileWhenUnmanaged)1630 TEST_F(OutputUpdateColorProfileTest, setsAColorProfileWhenUnmanaged) {
1631     // When the outputColorSetting is set to kUnmanaged, the implementation sets
1632     // a simple default color profile without looking at anything else.
1633 
1634     EXPECT_CALL(mOutput, getOutputLayerCount()).WillRepeatedly(Return(3u));
1635     EXPECT_CALL(mOutput,
1636                 setColorProfile(ColorProfileEq(
1637                         ColorProfile{ui::ColorMode::NATIVE, ui::Dataspace::UNKNOWN,
1638                                      ui::RenderIntent::COLORIMETRIC, ui::Dataspace::UNKNOWN})));
1639 
1640     mRefreshArgs.outputColorSetting = OutputColorSetting::kUnmanaged;
1641     mRefreshArgs.colorSpaceAgnosticDataspace = ui::Dataspace::UNKNOWN;
1642 
1643     mOutput.updateColorProfile(mRefreshArgs);
1644 }
1645 
1646 struct OutputUpdateColorProfileTest_GetBestColorModeResultBecomesSetProfile
1647       : public OutputUpdateColorProfileTest {
OutputUpdateColorProfileTest_GetBestColorModeResultBecomesSetProfileandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_GetBestColorModeResultBecomesSetProfile1648     OutputUpdateColorProfileTest_GetBestColorModeResultBecomesSetProfile() {
1649         EXPECT_CALL(mOutput, getOutputLayerCount()).WillRepeatedly(Return(0u));
1650         mRefreshArgs.outputColorSetting = OutputColorSetting::kEnhanced;
1651         mRefreshArgs.colorSpaceAgnosticDataspace = ui::Dataspace::UNKNOWN;
1652     }
1653 
1654     struct ExpectBestColorModeCallResultUsedToSetColorProfileState
1655           : public CallOrderStateMachineHelper<
1656                     TestType, ExpectBestColorModeCallResultUsedToSetColorProfileState> {
expectBestColorModeCallResultUsedToSetColorProfileandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_GetBestColorModeResultBecomesSetProfile::ExpectBestColorModeCallResultUsedToSetColorProfileState1657         [[nodiscard]] auto expectBestColorModeCallResultUsedToSetColorProfile(
1658                 ui::ColorMode colorMode, ui::Dataspace dataspace, ui::RenderIntent renderIntent) {
1659             EXPECT_CALL(*getInstance()->mDisplayColorProfile,
1660                         getBestColorMode(ui::Dataspace::V0_SRGB, ui::RenderIntent::ENHANCE, _, _,
1661                                          _))
1662                     .WillOnce(DoAll(SetArgPointee<2>(dataspace), SetArgPointee<3>(colorMode),
1663                                     SetArgPointee<4>(renderIntent)));
1664             EXPECT_CALL(getInstance()->mOutput,
1665                         setColorProfile(
1666                                 ColorProfileEq(ColorProfile{colorMode, dataspace, renderIntent,
1667                                                             ui::Dataspace::UNKNOWN})));
1668             return nextState<ExecuteState>();
1669         }
1670     };
1671 
1672     // Call this member function to start using the mini-DSL defined above.
verifyandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_GetBestColorModeResultBecomesSetProfile1673     [[nodiscard]] auto verify() {
1674         return ExpectBestColorModeCallResultUsedToSetColorProfileState::make(this);
1675     }
1676 };
1677 
TEST_F(OutputUpdateColorProfileTest_GetBestColorModeResultBecomesSetProfile,Native_Unknown_Colorimetric_Set)1678 TEST_F(OutputUpdateColorProfileTest_GetBestColorModeResultBecomesSetProfile,
1679        Native_Unknown_Colorimetric_Set) {
1680     verify().expectBestColorModeCallResultUsedToSetColorProfile(ui::ColorMode::NATIVE,
1681                                                                 ui::Dataspace::UNKNOWN,
1682                                                                 ui::RenderIntent::COLORIMETRIC)
1683             .execute();
1684 }
1685 
TEST_F(OutputUpdateColorProfileTest_GetBestColorModeResultBecomesSetProfile,DisplayP3_DisplayP3_Enhance_Set)1686 TEST_F(OutputUpdateColorProfileTest_GetBestColorModeResultBecomesSetProfile,
1687        DisplayP3_DisplayP3_Enhance_Set) {
1688     verify().expectBestColorModeCallResultUsedToSetColorProfile(ui::ColorMode::DISPLAY_P3,
1689                                                                 ui::Dataspace::DISPLAY_P3,
1690                                                                 ui::RenderIntent::ENHANCE)
1691             .execute();
1692 }
1693 
1694 struct OutputUpdateColorProfileTest_ColorSpaceAgnosticeDataspaceAffectsSetColorProfile
1695       : public OutputUpdateColorProfileTest {
OutputUpdateColorProfileTest_ColorSpaceAgnosticeDataspaceAffectsSetColorProfileandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_ColorSpaceAgnosticeDataspaceAffectsSetColorProfile1696     OutputUpdateColorProfileTest_ColorSpaceAgnosticeDataspaceAffectsSetColorProfile() {
1697         EXPECT_CALL(mOutput, getOutputLayerCount()).WillRepeatedly(Return(0u));
1698         EXPECT_CALL(*mDisplayColorProfile,
1699                     getBestColorMode(ui::Dataspace::V0_SRGB, ui::RenderIntent::ENHANCE, _, _, _))
1700                 .WillRepeatedly(DoAll(SetArgPointee<2>(ui::Dataspace::UNKNOWN),
1701                                       SetArgPointee<3>(ui::ColorMode::NATIVE),
1702                                       SetArgPointee<4>(ui::RenderIntent::COLORIMETRIC)));
1703         mRefreshArgs.outputColorSetting = OutputColorSetting::kEnhanced;
1704     }
1705 
1706     struct IfColorSpaceAgnosticDataspaceSetToState
1707           : public CallOrderStateMachineHelper<TestType, IfColorSpaceAgnosticDataspaceSetToState> {
ifColorSpaceAgnosticDataspaceSetToandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_ColorSpaceAgnosticeDataspaceAffectsSetColorProfile::IfColorSpaceAgnosticDataspaceSetToState1708         [[nodiscard]] auto ifColorSpaceAgnosticDataspaceSetTo(ui::Dataspace dataspace) {
1709             getInstance()->mRefreshArgs.colorSpaceAgnosticDataspace = dataspace;
1710             return nextState<ThenExpectSetColorProfileCallUsesColorSpaceAgnosticDataspaceState>();
1711         }
1712     };
1713 
1714     struct ThenExpectSetColorProfileCallUsesColorSpaceAgnosticDataspaceState
1715           : public CallOrderStateMachineHelper<
1716                     TestType, ThenExpectSetColorProfileCallUsesColorSpaceAgnosticDataspaceState> {
thenExpectSetColorProfileCallUsesColorSpaceAgnosticDataspaceandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_ColorSpaceAgnosticeDataspaceAffectsSetColorProfile::ThenExpectSetColorProfileCallUsesColorSpaceAgnosticDataspaceState1717         [[nodiscard]] auto thenExpectSetColorProfileCallUsesColorSpaceAgnosticDataspace(
1718                 ui::Dataspace dataspace) {
1719             EXPECT_CALL(getInstance()->mOutput,
1720                         setColorProfile(ColorProfileEq(
1721                                 ColorProfile{ui::ColorMode::NATIVE, ui::Dataspace::UNKNOWN,
1722                                              ui::RenderIntent::COLORIMETRIC, dataspace})));
1723             return nextState<ExecuteState>();
1724         }
1725     };
1726 
1727     // Call this member function to start using the mini-DSL defined above.
verifyandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_ColorSpaceAgnosticeDataspaceAffectsSetColorProfile1728     [[nodiscard]] auto verify() { return IfColorSpaceAgnosticDataspaceSetToState::make(this); }
1729 };
1730 
TEST_F(OutputUpdateColorProfileTest_ColorSpaceAgnosticeDataspaceAffectsSetColorProfile,DisplayP3)1731 TEST_F(OutputUpdateColorProfileTest_ColorSpaceAgnosticeDataspaceAffectsSetColorProfile, DisplayP3) {
1732     verify().ifColorSpaceAgnosticDataspaceSetTo(ui::Dataspace::DISPLAY_P3)
1733             .thenExpectSetColorProfileCallUsesColorSpaceAgnosticDataspace(ui::Dataspace::DISPLAY_P3)
1734             .execute();
1735 }
1736 
TEST_F(OutputUpdateColorProfileTest_ColorSpaceAgnosticeDataspaceAffectsSetColorProfile,V0_SRGB)1737 TEST_F(OutputUpdateColorProfileTest_ColorSpaceAgnosticeDataspaceAffectsSetColorProfile, V0_SRGB) {
1738     verify().ifColorSpaceAgnosticDataspaceSetTo(ui::Dataspace::V0_SRGB)
1739             .thenExpectSetColorProfileCallUsesColorSpaceAgnosticDataspace(ui::Dataspace::V0_SRGB)
1740             .execute();
1741 }
1742 
1743 struct OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference
1744       : public OutputUpdateColorProfileTest {
1745     // Internally the implementation looks through the dataspaces of all the
1746     // visible layers. The topmost one that also has an actual dataspace
1747     // preference set is used to drive subsequent choices.
1748 
OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreferenceandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference1749     OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference() {
1750         mRefreshArgs.outputColorSetting = OutputColorSetting::kEnhanced;
1751         mRefreshArgs.colorSpaceAgnosticDataspace = ui::Dataspace::UNKNOWN;
1752 
1753         EXPECT_CALL(mOutput, getOutputLayerCount()).WillRepeatedly(Return(3u));
1754         EXPECT_CALL(mOutput, setColorProfile(_)).WillRepeatedly(Return());
1755     }
1756 
1757     struct IfTopLayerDataspaceState
1758           : public CallOrderStateMachineHelper<TestType, IfTopLayerDataspaceState> {
ifTopLayerIsandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference::IfTopLayerDataspaceState1759         [[nodiscard]] auto ifTopLayerIs(ui::Dataspace dataspace) {
1760             getInstance()->mLayer3.mLayerFEState.dataspace = dataspace;
1761             return nextState<AndIfMiddleLayerDataspaceState>();
1762         }
ifTopLayerHasNoPreferenceandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference::IfTopLayerDataspaceState1763         [[nodiscard]] auto ifTopLayerHasNoPreference() {
1764             return ifTopLayerIs(ui::Dataspace::UNKNOWN);
1765         }
1766     };
1767 
1768     struct AndIfMiddleLayerDataspaceState
1769           : public CallOrderStateMachineHelper<TestType, AndIfMiddleLayerDataspaceState> {
andIfMiddleLayerIsandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference::AndIfMiddleLayerDataspaceState1770         [[nodiscard]] auto andIfMiddleLayerIs(ui::Dataspace dataspace) {
1771             getInstance()->mLayer2.mLayerFEState.dataspace = dataspace;
1772             return nextState<AndIfBottomLayerDataspaceState>();
1773         }
andIfMiddleLayerHasNoPreferenceandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference::AndIfMiddleLayerDataspaceState1774         [[nodiscard]] auto andIfMiddleLayerHasNoPreference() {
1775             return andIfMiddleLayerIs(ui::Dataspace::UNKNOWN);
1776         }
1777     };
1778 
1779     struct AndIfBottomLayerDataspaceState
1780           : public CallOrderStateMachineHelper<TestType, AndIfBottomLayerDataspaceState> {
andIfBottomLayerIsandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference::AndIfBottomLayerDataspaceState1781         [[nodiscard]] auto andIfBottomLayerIs(ui::Dataspace dataspace) {
1782             getInstance()->mLayer1.mLayerFEState.dataspace = dataspace;
1783             return nextState<ThenExpectBestColorModeCallUsesState>();
1784         }
andIfBottomLayerHasNoPreferenceandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference::AndIfBottomLayerDataspaceState1785         [[nodiscard]] auto andIfBottomLayerHasNoPreference() {
1786             return andIfBottomLayerIs(ui::Dataspace::UNKNOWN);
1787         }
1788     };
1789 
1790     struct ThenExpectBestColorModeCallUsesState
1791           : public CallOrderStateMachineHelper<TestType, ThenExpectBestColorModeCallUsesState> {
thenExpectBestColorModeCallUsesandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference::ThenExpectBestColorModeCallUsesState1792         [[nodiscard]] auto thenExpectBestColorModeCallUses(ui::Dataspace dataspace) {
1793             EXPECT_CALL(*getInstance()->mDisplayColorProfile,
1794                         getBestColorMode(dataspace, _, _, _, _));
1795             return nextState<ExecuteState>();
1796         }
1797     };
1798 
1799     // Call this member function to start using the mini-DSL defined above.
verifyandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference1800     [[nodiscard]] auto verify() { return IfTopLayerDataspaceState::make(this); }
1801 };
1802 
TEST_F(OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference,noStrongLayerPrefenceUses_V0_SRGB)1803 TEST_F(OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference,
1804        noStrongLayerPrefenceUses_V0_SRGB) {
1805     // If none of the layers indicate a preference, then V0_SRGB is the
1806     // preferred choice (subject to additional checks).
1807     verify().ifTopLayerHasNoPreference()
1808             .andIfMiddleLayerHasNoPreference()
1809             .andIfBottomLayerHasNoPreference()
1810             .thenExpectBestColorModeCallUses(ui::Dataspace::V0_SRGB)
1811             .execute();
1812 }
1813 
TEST_F(OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference,ifTopmostUses_DisplayP3_Then_DisplayP3_Chosen)1814 TEST_F(OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference,
1815        ifTopmostUses_DisplayP3_Then_DisplayP3_Chosen) {
1816     // If only the topmost layer has a preference, then that is what is chosen.
1817     verify().ifTopLayerIs(ui::Dataspace::DISPLAY_P3)
1818             .andIfMiddleLayerHasNoPreference()
1819             .andIfBottomLayerHasNoPreference()
1820             .thenExpectBestColorModeCallUses(ui::Dataspace::DISPLAY_P3)
1821             .execute();
1822 }
1823 
TEST_F(OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference,ifMiddleUses_DisplayP3_Then_DisplayP3_Chosen)1824 TEST_F(OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference,
1825        ifMiddleUses_DisplayP3_Then_DisplayP3_Chosen) {
1826     // If only the middle layer has a preference, that that is what is chosen.
1827     verify().ifTopLayerHasNoPreference()
1828             .andIfMiddleLayerIs(ui::Dataspace::DISPLAY_P3)
1829             .andIfBottomLayerHasNoPreference()
1830             .thenExpectBestColorModeCallUses(ui::Dataspace::DISPLAY_P3)
1831             .execute();
1832 }
1833 
TEST_F(OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference,ifBottomUses_DisplayP3_Then_DisplayP3_Chosen)1834 TEST_F(OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference,
1835        ifBottomUses_DisplayP3_Then_DisplayP3_Chosen) {
1836     // If only the middle layer has a preference, that that is what is chosen.
1837     verify().ifTopLayerHasNoPreference()
1838             .andIfMiddleLayerHasNoPreference()
1839             .andIfBottomLayerIs(ui::Dataspace::DISPLAY_P3)
1840             .thenExpectBestColorModeCallUses(ui::Dataspace::DISPLAY_P3)
1841             .execute();
1842 }
1843 
TEST_F(OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference,ifTopUses_DisplayBT2020_AndBottomUses_DisplayP3_Then_DisplayBT2020_Chosen)1844 TEST_F(OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference,
1845        ifTopUses_DisplayBT2020_AndBottomUses_DisplayP3_Then_DisplayBT2020_Chosen) {
1846     // If multiple layers have a preference, the topmost value is what is used.
1847     verify().ifTopLayerIs(ui::Dataspace::DISPLAY_BT2020)
1848             .andIfMiddleLayerHasNoPreference()
1849             .andIfBottomLayerIs(ui::Dataspace::DISPLAY_P3)
1850             .thenExpectBestColorModeCallUses(ui::Dataspace::DISPLAY_BT2020)
1851             .execute();
1852 }
1853 
TEST_F(OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference,ifTopUses_DisplayP3_AndBottomUses_V0_SRGB_Then_DisplayP3_Chosen)1854 TEST_F(OutputUpdateColorProfileTest_TopmostLayerPreferenceSetsOutputPreference,
1855        ifTopUses_DisplayP3_AndBottomUses_V0_SRGB_Then_DisplayP3_Chosen) {
1856     // If multiple layers have a preference, the topmost value is what is used.
1857     verify().ifTopLayerIs(ui::Dataspace::DISPLAY_P3)
1858             .andIfMiddleLayerHasNoPreference()
1859             .andIfBottomLayerIs(ui::Dataspace::DISPLAY_BT2020)
1860             .thenExpectBestColorModeCallUses(ui::Dataspace::DISPLAY_P3)
1861             .execute();
1862 }
1863 
1864 struct OutputUpdateColorProfileTest_ForceOutputColorOverrides
1865       : public OutputUpdateColorProfileTest {
1866     // If CompositionRefreshArgs::forceOutputColorMode is set to some specific
1867     // values, it overrides the layer dataspace choice.
1868 
OutputUpdateColorProfileTest_ForceOutputColorOverridesandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_ForceOutputColorOverrides1869     OutputUpdateColorProfileTest_ForceOutputColorOverrides() {
1870         mRefreshArgs.outputColorSetting = OutputColorSetting::kEnhanced;
1871         mRefreshArgs.colorSpaceAgnosticDataspace = ui::Dataspace::UNKNOWN;
1872 
1873         mLayer1.mLayerFEState.dataspace = ui::Dataspace::DISPLAY_BT2020;
1874 
1875         EXPECT_CALL(mOutput, getOutputLayerCount()).WillRepeatedly(Return(1u));
1876         EXPECT_CALL(mOutput, setColorProfile(_)).WillRepeatedly(Return());
1877     }
1878 
1879     struct IfForceOutputColorModeState
1880           : public CallOrderStateMachineHelper<TestType, IfForceOutputColorModeState> {
ifForceOutputColorModeandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_ForceOutputColorOverrides::IfForceOutputColorModeState1881         [[nodiscard]] auto ifForceOutputColorMode(ui::ColorMode colorMode) {
1882             getInstance()->mRefreshArgs.forceOutputColorMode = colorMode;
1883             return nextState<ThenExpectBestColorModeCallUsesState>();
1884         }
ifNoOverrideandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_ForceOutputColorOverrides::IfForceOutputColorModeState1885         [[nodiscard]] auto ifNoOverride() { return ifForceOutputColorMode(ui::ColorMode::NATIVE); }
1886     };
1887 
1888     struct ThenExpectBestColorModeCallUsesState
1889           : public CallOrderStateMachineHelper<TestType, ThenExpectBestColorModeCallUsesState> {
thenExpectBestColorModeCallUsesandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_ForceOutputColorOverrides::ThenExpectBestColorModeCallUsesState1890         [[nodiscard]] auto thenExpectBestColorModeCallUses(ui::Dataspace dataspace) {
1891             EXPECT_CALL(*getInstance()->mDisplayColorProfile,
1892                         getBestColorMode(dataspace, _, _, _, _));
1893             return nextState<ExecuteState>();
1894         }
1895     };
1896 
1897     // Call this member function to start using the mini-DSL defined above.
verifyandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_ForceOutputColorOverrides1898     [[nodiscard]] auto verify() { return IfForceOutputColorModeState::make(this); }
1899 };
1900 
TEST_F(OutputUpdateColorProfileTest_ForceOutputColorOverrides,NoOverride_DoesNotOverride)1901 TEST_F(OutputUpdateColorProfileTest_ForceOutputColorOverrides, NoOverride_DoesNotOverride) {
1902     // By default the layer state is used to set the preferred dataspace
1903     verify().ifNoOverride()
1904             .thenExpectBestColorModeCallUses(ui::Dataspace::DISPLAY_BT2020)
1905             .execute();
1906 }
1907 
TEST_F(OutputUpdateColorProfileTest_ForceOutputColorOverrides,SRGB_Override_USES_V0_SRGB)1908 TEST_F(OutputUpdateColorProfileTest_ForceOutputColorOverrides, SRGB_Override_USES_V0_SRGB) {
1909     // Setting ui::ColorMode::SRGB overrides it with ui::Dataspace::V0_SRGB
1910     verify().ifForceOutputColorMode(ui::ColorMode::SRGB)
1911             .thenExpectBestColorModeCallUses(ui::Dataspace::V0_SRGB)
1912             .execute();
1913 }
1914 
TEST_F(OutputUpdateColorProfileTest_ForceOutputColorOverrides,DisplayP3_Override_Uses_DisplayP3)1915 TEST_F(OutputUpdateColorProfileTest_ForceOutputColorOverrides, DisplayP3_Override_Uses_DisplayP3) {
1916     // Setting ui::ColorMode::DISPLAY_P3 overrides it with ui::Dataspace::DISPLAY_P3
1917     verify().ifForceOutputColorMode(ui::ColorMode::DISPLAY_P3)
1918             .thenExpectBestColorModeCallUses(ui::Dataspace::DISPLAY_P3)
1919             .execute();
1920 }
1921 
1922 // HDR output requires all layers to be compatible with the chosen HDR
1923 // dataspace, along with there being proper support.
1924 struct OutputUpdateColorProfileTest_Hdr : public OutputUpdateColorProfileTest {
OutputUpdateColorProfileTest_Hdrandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_Hdr1925     OutputUpdateColorProfileTest_Hdr() {
1926         mRefreshArgs.outputColorSetting = OutputColorSetting::kEnhanced;
1927         mRefreshArgs.colorSpaceAgnosticDataspace = ui::Dataspace::UNKNOWN;
1928         EXPECT_CALL(mOutput, getOutputLayerCount()).WillRepeatedly(Return(2u));
1929         EXPECT_CALL(mOutput, setColorProfile(_)).WillRepeatedly(Return());
1930     }
1931 
1932     static constexpr ui::Dataspace kNonHdrDataspace = ui::Dataspace::DISPLAY_P3;
1933     static constexpr ui::Dataspace BT2020_PQ = ui::Dataspace::BT2020_PQ;
1934     static constexpr ui::Dataspace BT2020_HLG = ui::Dataspace::BT2020_HLG;
1935     static constexpr ui::Dataspace DISPLAY_P3 = ui::Dataspace::DISPLAY_P3;
1936 
1937     struct IfTopLayerDataspaceState
1938           : public CallOrderStateMachineHelper<TestType, IfTopLayerDataspaceState> {
ifTopLayerIsandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_Hdr::IfTopLayerDataspaceState1939         [[nodiscard]] auto ifTopLayerIs(ui::Dataspace dataspace) {
1940             getInstance()->mLayer2.mLayerFEState.dataspace = dataspace;
1941             return nextState<AndTopLayerCompositionTypeState>();
1942         }
ifTopLayerIsNotHdrandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_Hdr::IfTopLayerDataspaceState1943         [[nodiscard]] auto ifTopLayerIsNotHdr() { return ifTopLayerIs(kNonHdrDataspace); }
1944     };
1945 
1946     struct AndTopLayerCompositionTypeState
1947           : public CallOrderStateMachineHelper<TestType, AndTopLayerCompositionTypeState> {
andTopLayerIsREComposedandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_Hdr::AndTopLayerCompositionTypeState1948         [[nodiscard]] auto andTopLayerIsREComposed(bool renderEngineComposed) {
1949             getInstance()->mLayer2.mLayerFEState.forceClientComposition = renderEngineComposed;
1950             return nextState<AndIfBottomLayerDataspaceState>();
1951         }
1952     };
1953 
1954     struct AndIfBottomLayerDataspaceState
1955           : public CallOrderStateMachineHelper<TestType, AndIfBottomLayerDataspaceState> {
andIfBottomLayerIsandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_Hdr::AndIfBottomLayerDataspaceState1956         [[nodiscard]] auto andIfBottomLayerIs(ui::Dataspace dataspace) {
1957             getInstance()->mLayer1.mLayerFEState.dataspace = dataspace;
1958             return nextState<AndBottomLayerCompositionTypeState>();
1959         }
andIfBottomLayerIsNotHdrandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_Hdr::AndIfBottomLayerDataspaceState1960         [[nodiscard]] auto andIfBottomLayerIsNotHdr() {
1961             return andIfBottomLayerIs(kNonHdrDataspace);
1962         }
1963     };
1964 
1965     struct AndBottomLayerCompositionTypeState
1966           : public CallOrderStateMachineHelper<TestType, AndBottomLayerCompositionTypeState> {
andBottomLayerIsREComposedandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_Hdr::AndBottomLayerCompositionTypeState1967         [[nodiscard]] auto andBottomLayerIsREComposed(bool renderEngineComposed) {
1968             getInstance()->mLayer1.mLayerFEState.forceClientComposition = renderEngineComposed;
1969             return nextState<AndIfHasLegacySupportState>();
1970         }
1971     };
1972 
1973     struct AndIfHasLegacySupportState
1974           : public CallOrderStateMachineHelper<TestType, AndIfHasLegacySupportState> {
andIfLegacySupportForandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_Hdr::AndIfHasLegacySupportState1975         [[nodiscard]] auto andIfLegacySupportFor(ui::Dataspace dataspace, bool legacySupport) {
1976             EXPECT_CALL(*getInstance()->mDisplayColorProfile, hasLegacyHdrSupport(dataspace))
1977                     .WillOnce(Return(legacySupport));
1978             return nextState<ThenExpectBestColorModeCallUsesState>();
1979         }
1980     };
1981 
1982     struct ThenExpectBestColorModeCallUsesState
1983           : public CallOrderStateMachineHelper<TestType, ThenExpectBestColorModeCallUsesState> {
thenExpectBestColorModeCallUsesandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_Hdr::ThenExpectBestColorModeCallUsesState1984         [[nodiscard]] auto thenExpectBestColorModeCallUses(ui::Dataspace dataspace) {
1985             EXPECT_CALL(*getInstance()->mDisplayColorProfile,
1986                         getBestColorMode(dataspace, _, _, _, _));
1987             return nextState<ExecuteState>();
1988         }
1989     };
1990 
1991     // Call this member function to start using the mini-DSL defined above.
verifyandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfileTest_Hdr1992     [[nodiscard]] auto verify() { return IfTopLayerDataspaceState::make(this); }
1993 };
1994 
TEST_F(OutputUpdateColorProfileTest_Hdr,PQ_HW_On_PQ_HW_Uses_PQ)1995 TEST_F(OutputUpdateColorProfileTest_Hdr, PQ_HW_On_PQ_HW_Uses_PQ) {
1996     // If all layers use BT2020_PQ, and there are no other special conditions,
1997     // BT2020_PQ is used.
1998     verify().ifTopLayerIs(BT2020_PQ)
1999             .andTopLayerIsREComposed(false)
2000             .andIfBottomLayerIs(BT2020_PQ)
2001             .andBottomLayerIsREComposed(false)
2002             .andIfLegacySupportFor(BT2020_PQ, false)
2003             .thenExpectBestColorModeCallUses(BT2020_PQ)
2004             .execute();
2005 }
2006 
TEST_F(OutputUpdateColorProfileTest_Hdr,PQ_HW_On_PQ_HW_IfPQHasLegacySupport_Uses_DisplayP3)2007 TEST_F(OutputUpdateColorProfileTest_Hdr, PQ_HW_On_PQ_HW_IfPQHasLegacySupport_Uses_DisplayP3) {
2008     // BT2020_PQ is not used if there is only legacy support for it.
2009     verify().ifTopLayerIs(BT2020_PQ)
2010             .andTopLayerIsREComposed(false)
2011             .andIfBottomLayerIs(BT2020_PQ)
2012             .andBottomLayerIsREComposed(false)
2013             .andIfLegacySupportFor(BT2020_PQ, true)
2014             .thenExpectBestColorModeCallUses(DISPLAY_P3)
2015             .execute();
2016 }
2017 
TEST_F(OutputUpdateColorProfileTest_Hdr,PQ_HW_On_PQ_RE_Uses_PQ)2018 TEST_F(OutputUpdateColorProfileTest_Hdr, PQ_HW_On_PQ_RE_Uses_PQ) {
2019     // BT2020_PQ is still used if the bottom layer is RenderEngine composed.
2020     verify().ifTopLayerIs(BT2020_PQ)
2021             .andTopLayerIsREComposed(false)
2022             .andIfBottomLayerIs(BT2020_PQ)
2023             .andBottomLayerIsREComposed(true)
2024             .andIfLegacySupportFor(BT2020_PQ, false)
2025             .thenExpectBestColorModeCallUses(BT2020_PQ)
2026             .execute();
2027 }
2028 
TEST_F(OutputUpdateColorProfileTest_Hdr,PQ_RE_On_PQ_HW_Uses_DisplayP3)2029 TEST_F(OutputUpdateColorProfileTest_Hdr, PQ_RE_On_PQ_HW_Uses_DisplayP3) {
2030     // BT2020_PQ is not used if the top layer is RenderEngine composed.
2031     verify().ifTopLayerIs(BT2020_PQ)
2032             .andTopLayerIsREComposed(true)
2033             .andIfBottomLayerIs(BT2020_PQ)
2034             .andBottomLayerIsREComposed(false)
2035             .andIfLegacySupportFor(BT2020_PQ, false)
2036             .thenExpectBestColorModeCallUses(DISPLAY_P3)
2037             .execute();
2038 }
2039 
TEST_F(OutputUpdateColorProfileTest_Hdr,PQ_HW_On_HLG_HW_Uses_PQ)2040 TEST_F(OutputUpdateColorProfileTest_Hdr, PQ_HW_On_HLG_HW_Uses_PQ) {
2041     // If there is mixed HLG/PQ use, and the topmost layer is PQ, then PQ is used if there
2042     // are no other special conditions.
2043     verify().ifTopLayerIs(BT2020_PQ)
2044             .andTopLayerIsREComposed(false)
2045             .andIfBottomLayerIs(BT2020_HLG)
2046             .andBottomLayerIsREComposed(false)
2047             .andIfLegacySupportFor(BT2020_PQ, false)
2048             .thenExpectBestColorModeCallUses(BT2020_PQ)
2049             .execute();
2050 }
2051 
TEST_F(OutputUpdateColorProfileTest_Hdr,PQ_HW_On_HLG_HW_IfPQHasLegacySupport_Uses_DisplayP3)2052 TEST_F(OutputUpdateColorProfileTest_Hdr, PQ_HW_On_HLG_HW_IfPQHasLegacySupport_Uses_DisplayP3) {
2053     // BT2020_PQ is not used if there is only legacy support for it.
2054     verify().ifTopLayerIs(BT2020_PQ)
2055             .andTopLayerIsREComposed(false)
2056             .andIfBottomLayerIs(BT2020_HLG)
2057             .andBottomLayerIsREComposed(false)
2058             .andIfLegacySupportFor(BT2020_PQ, true)
2059             .thenExpectBestColorModeCallUses(DISPLAY_P3)
2060             .execute();
2061 }
2062 
TEST_F(OutputUpdateColorProfileTest_Hdr,PQ_HW_On_HLG_RE_Uses_PQ)2063 TEST_F(OutputUpdateColorProfileTest_Hdr, PQ_HW_On_HLG_RE_Uses_PQ) {
2064     // BT2020_PQ is used if the bottom HLG layer is RenderEngine composed.
2065     verify().ifTopLayerIs(BT2020_PQ)
2066             .andTopLayerIsREComposed(false)
2067             .andIfBottomLayerIs(BT2020_HLG)
2068             .andBottomLayerIsREComposed(true)
2069             .andIfLegacySupportFor(BT2020_PQ, false)
2070             .thenExpectBestColorModeCallUses(BT2020_PQ)
2071             .execute();
2072 }
2073 
TEST_F(OutputUpdateColorProfileTest_Hdr,PQ_RE_On_HLG_HW_Uses_DisplayP3)2074 TEST_F(OutputUpdateColorProfileTest_Hdr, PQ_RE_On_HLG_HW_Uses_DisplayP3) {
2075     // BT2020_PQ is not used if the top PQ layer is RenderEngine composed.
2076     verify().ifTopLayerIs(BT2020_PQ)
2077             .andTopLayerIsREComposed(true)
2078             .andIfBottomLayerIs(BT2020_HLG)
2079             .andBottomLayerIsREComposed(false)
2080             .andIfLegacySupportFor(BT2020_PQ, false)
2081             .thenExpectBestColorModeCallUses(DISPLAY_P3)
2082             .execute();
2083 }
2084 
TEST_F(OutputUpdateColorProfileTest_Hdr,HLG_HW_On_PQ_HW_Uses_PQ)2085 TEST_F(OutputUpdateColorProfileTest_Hdr, HLG_HW_On_PQ_HW_Uses_PQ) {
2086     // If there is mixed HLG/PQ use, and the topmost layer is HLG, then PQ is
2087     // used if there are no other special conditions.
2088     verify().ifTopLayerIs(BT2020_HLG)
2089             .andTopLayerIsREComposed(false)
2090             .andIfBottomLayerIs(BT2020_PQ)
2091             .andBottomLayerIsREComposed(false)
2092             .andIfLegacySupportFor(BT2020_PQ, false)
2093             .thenExpectBestColorModeCallUses(BT2020_PQ)
2094             .execute();
2095 }
2096 
TEST_F(OutputUpdateColorProfileTest_Hdr,HLG_HW_On_PQ_HW_IfPQHasLegacySupport_Uses_DisplayP3)2097 TEST_F(OutputUpdateColorProfileTest_Hdr, HLG_HW_On_PQ_HW_IfPQHasLegacySupport_Uses_DisplayP3) {
2098     // BT2020_PQ is not used if there is only legacy support for it.
2099     verify().ifTopLayerIs(BT2020_HLG)
2100             .andTopLayerIsREComposed(false)
2101             .andIfBottomLayerIs(BT2020_PQ)
2102             .andBottomLayerIsREComposed(false)
2103             .andIfLegacySupportFor(BT2020_PQ, true)
2104             .thenExpectBestColorModeCallUses(DISPLAY_P3)
2105             .execute();
2106 }
2107 
TEST_F(OutputUpdateColorProfileTest_Hdr,HLG_HW_On_PQ_RE_Uses_DisplayP3)2108 TEST_F(OutputUpdateColorProfileTest_Hdr, HLG_HW_On_PQ_RE_Uses_DisplayP3) {
2109     // BT2020_PQ is not used if the bottom PQ layer is RenderEngine composed.
2110     verify().ifTopLayerIs(BT2020_HLG)
2111             .andTopLayerIsREComposed(false)
2112             .andIfBottomLayerIs(BT2020_PQ)
2113             .andBottomLayerIsREComposed(true)
2114             .andIfLegacySupportFor(BT2020_PQ, false)
2115             .thenExpectBestColorModeCallUses(DISPLAY_P3)
2116             .execute();
2117 }
2118 
TEST_F(OutputUpdateColorProfileTest_Hdr,HLG_RE_On_PQ_HW_Uses_PQ)2119 TEST_F(OutputUpdateColorProfileTest_Hdr, HLG_RE_On_PQ_HW_Uses_PQ) {
2120     // BT2020_PQ is still used if the top HLG layer is RenderEngine composed.
2121     verify().ifTopLayerIs(BT2020_HLG)
2122             .andTopLayerIsREComposed(true)
2123             .andIfBottomLayerIs(BT2020_PQ)
2124             .andBottomLayerIsREComposed(false)
2125             .andIfLegacySupportFor(BT2020_PQ, false)
2126             .thenExpectBestColorModeCallUses(BT2020_PQ)
2127             .execute();
2128 }
2129 
TEST_F(OutputUpdateColorProfileTest_Hdr,HLG_HW_On_HLG_HW_Uses_HLG)2130 TEST_F(OutputUpdateColorProfileTest_Hdr, HLG_HW_On_HLG_HW_Uses_HLG) {
2131     // If all layers use HLG then HLG is used if there are no other special
2132     // conditions.
2133     verify().ifTopLayerIs(BT2020_HLG)
2134             .andTopLayerIsREComposed(false)
2135             .andIfBottomLayerIs(BT2020_HLG)
2136             .andBottomLayerIsREComposed(false)
2137             .andIfLegacySupportFor(BT2020_HLG, false)
2138             .thenExpectBestColorModeCallUses(BT2020_HLG)
2139             .execute();
2140 }
2141 
TEST_F(OutputUpdateColorProfileTest_Hdr,HLG_HW_On_HLG_HW_IfPQHasLegacySupport_Uses_DisplayP3)2142 TEST_F(OutputUpdateColorProfileTest_Hdr, HLG_HW_On_HLG_HW_IfPQHasLegacySupport_Uses_DisplayP3) {
2143     // BT2020_HLG is not used if there is legacy support for it.
2144     verify().ifTopLayerIs(BT2020_HLG)
2145             .andTopLayerIsREComposed(false)
2146             .andIfBottomLayerIs(BT2020_HLG)
2147             .andBottomLayerIsREComposed(false)
2148             .andIfLegacySupportFor(BT2020_HLG, true)
2149             .thenExpectBestColorModeCallUses(DISPLAY_P3)
2150             .execute();
2151 }
2152 
TEST_F(OutputUpdateColorProfileTest_Hdr,HLG_HW_On_HLG_RE_Uses_HLG)2153 TEST_F(OutputUpdateColorProfileTest_Hdr, HLG_HW_On_HLG_RE_Uses_HLG) {
2154     // BT2020_HLG is used even if the bottom layer is client composed.
2155     verify().ifTopLayerIs(BT2020_HLG)
2156             .andTopLayerIsREComposed(false)
2157             .andIfBottomLayerIs(BT2020_HLG)
2158             .andBottomLayerIsREComposed(true)
2159             .andIfLegacySupportFor(BT2020_HLG, false)
2160             .thenExpectBestColorModeCallUses(BT2020_HLG)
2161             .execute();
2162 }
2163 
TEST_F(OutputUpdateColorProfileTest_Hdr,HLG_RE_On_HLG_HW_Uses_HLG)2164 TEST_F(OutputUpdateColorProfileTest_Hdr, HLG_RE_On_HLG_HW_Uses_HLG) {
2165     // BT2020_HLG is used even if the top layer is client composed.
2166     verify().ifTopLayerIs(BT2020_HLG)
2167             .andTopLayerIsREComposed(true)
2168             .andIfBottomLayerIs(BT2020_HLG)
2169             .andBottomLayerIsREComposed(false)
2170             .andIfLegacySupportFor(BT2020_HLG, false)
2171             .thenExpectBestColorModeCallUses(BT2020_HLG)
2172             .execute();
2173 }
2174 
TEST_F(OutputUpdateColorProfileTest_Hdr,PQ_HW_On_NonHdr_HW_Uses_PQ)2175 TEST_F(OutputUpdateColorProfileTest_Hdr, PQ_HW_On_NonHdr_HW_Uses_PQ) {
2176     // Even if there are non-HDR layers present, BT2020_PQ can still be used.
2177     verify().ifTopLayerIs(BT2020_PQ)
2178             .andTopLayerIsREComposed(false)
2179             .andIfBottomLayerIsNotHdr()
2180             .andBottomLayerIsREComposed(false)
2181             .andIfLegacySupportFor(BT2020_PQ, false)
2182             .thenExpectBestColorModeCallUses(BT2020_PQ)
2183             .execute();
2184 }
2185 
TEST_F(OutputUpdateColorProfileTest_Hdr,HLG_HW_On_NonHdr_RE_Uses_HLG)2186 TEST_F(OutputUpdateColorProfileTest_Hdr, HLG_HW_On_NonHdr_RE_Uses_HLG) {
2187     // If all layers use HLG then HLG is used if there are no other special
2188     // conditions.
2189     verify().ifTopLayerIs(BT2020_HLG)
2190             .andTopLayerIsREComposed(false)
2191             .andIfBottomLayerIsNotHdr()
2192             .andBottomLayerIsREComposed(true)
2193             .andIfLegacySupportFor(BT2020_HLG, false)
2194             .thenExpectBestColorModeCallUses(BT2020_HLG)
2195             .execute();
2196 }
2197 
2198 struct OutputUpdateColorProfile_AffectsChosenRenderIntentTest
2199       : public OutputUpdateColorProfileTest {
2200     // The various values for CompositionRefreshArgs::outputColorSetting affect
2201     // the chosen renderIntent, along with whether the preferred dataspace is an
2202     // HDR dataspace or not.
2203 
OutputUpdateColorProfile_AffectsChosenRenderIntentTestandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfile_AffectsChosenRenderIntentTest2204     OutputUpdateColorProfile_AffectsChosenRenderIntentTest() {
2205         mRefreshArgs.outputColorSetting = OutputColorSetting::kEnhanced;
2206         mRefreshArgs.colorSpaceAgnosticDataspace = ui::Dataspace::UNKNOWN;
2207         mLayer1.mLayerFEState.dataspace = ui::Dataspace::BT2020_PQ;
2208         EXPECT_CALL(mOutput, getOutputLayerCount()).WillRepeatedly(Return(1u));
2209         EXPECT_CALL(mOutput, setColorProfile(_)).WillRepeatedly(Return());
2210         EXPECT_CALL(*mDisplayColorProfile, hasLegacyHdrSupport(ui::Dataspace::BT2020_PQ))
2211                 .WillRepeatedly(Return(false));
2212     }
2213 
2214     // The tests here involve enough state and GMock setup that using a mini-DSL
2215     // makes the tests much more readable, and allows the test to focus more on
2216     // the intent than on some of the details.
2217 
2218     static constexpr ui::Dataspace kNonHdrDataspace = ui::Dataspace::DISPLAY_P3;
2219     static constexpr ui::Dataspace kHdrDataspace = ui::Dataspace::BT2020_PQ;
2220 
2221     struct IfDataspaceChosenState
2222           : public CallOrderStateMachineHelper<TestType, IfDataspaceChosenState> {
ifDataspaceChosenIsandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfile_AffectsChosenRenderIntentTest::IfDataspaceChosenState2223         [[nodiscard]] auto ifDataspaceChosenIs(ui::Dataspace dataspace) {
2224             getInstance()->mLayer1.mLayerFEState.dataspace = dataspace;
2225             return nextState<AndOutputColorSettingState>();
2226         }
ifDataspaceChosenIsNonHdrandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfile_AffectsChosenRenderIntentTest::IfDataspaceChosenState2227         [[nodiscard]] auto ifDataspaceChosenIsNonHdr() {
2228             return ifDataspaceChosenIs(kNonHdrDataspace);
2229         }
ifDataspaceChosenIsHdrandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfile_AffectsChosenRenderIntentTest::IfDataspaceChosenState2230         [[nodiscard]] auto ifDataspaceChosenIsHdr() { return ifDataspaceChosenIs(kHdrDataspace); }
2231     };
2232 
2233     struct AndOutputColorSettingState
2234           : public CallOrderStateMachineHelper<TestType, AndOutputColorSettingState> {
andOutputColorSettingIsandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfile_AffectsChosenRenderIntentTest::AndOutputColorSettingState2235         [[nodiscard]] auto andOutputColorSettingIs(OutputColorSetting setting) {
2236             getInstance()->mRefreshArgs.outputColorSetting = setting;
2237             return nextState<ThenExpectBestColorModeCallUsesState>();
2238         }
2239     };
2240 
2241     struct ThenExpectBestColorModeCallUsesState
2242           : public CallOrderStateMachineHelper<TestType, ThenExpectBestColorModeCallUsesState> {
thenExpectBestColorModeCallUsesandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfile_AffectsChosenRenderIntentTest::ThenExpectBestColorModeCallUsesState2243         [[nodiscard]] auto thenExpectBestColorModeCallUses(ui::RenderIntent intent) {
2244             EXPECT_CALL(*getInstance()->mDisplayColorProfile,
2245                         getBestColorMode(getInstance()->mLayer1.mLayerFEState.dataspace, intent, _,
2246                                          _, _));
2247             return nextState<ExecuteState>();
2248         }
2249     };
2250 
2251     // Tests call one of these two helper member functions to start using the
2252     // mini-DSL defined above.
verifyandroid::compositionengine::__anon0cff14940111::OutputUpdateColorProfile_AffectsChosenRenderIntentTest2253     [[nodiscard]] auto verify() { return IfDataspaceChosenState::make(this); }
2254 };
2255 
TEST_F(OutputUpdateColorProfile_AffectsChosenRenderIntentTest,Managed_NonHdr_Prefers_Colorimetric)2256 TEST_F(OutputUpdateColorProfile_AffectsChosenRenderIntentTest,
2257        Managed_NonHdr_Prefers_Colorimetric) {
2258     verify().ifDataspaceChosenIsNonHdr()
2259             .andOutputColorSettingIs(OutputColorSetting::kManaged)
2260             .thenExpectBestColorModeCallUses(ui::RenderIntent::COLORIMETRIC)
2261             .execute();
2262 }
2263 
TEST_F(OutputUpdateColorProfile_AffectsChosenRenderIntentTest,Managed_Hdr_Prefers_ToneMapColorimetric)2264 TEST_F(OutputUpdateColorProfile_AffectsChosenRenderIntentTest,
2265        Managed_Hdr_Prefers_ToneMapColorimetric) {
2266     verify().ifDataspaceChosenIsHdr()
2267             .andOutputColorSettingIs(OutputColorSetting::kManaged)
2268             .thenExpectBestColorModeCallUses(ui::RenderIntent::TONE_MAP_COLORIMETRIC)
2269             .execute();
2270 }
2271 
TEST_F(OutputUpdateColorProfile_AffectsChosenRenderIntentTest,Enhanced_NonHdr_Prefers_Enhance)2272 TEST_F(OutputUpdateColorProfile_AffectsChosenRenderIntentTest, Enhanced_NonHdr_Prefers_Enhance) {
2273     verify().ifDataspaceChosenIsNonHdr()
2274             .andOutputColorSettingIs(OutputColorSetting::kEnhanced)
2275             .thenExpectBestColorModeCallUses(ui::RenderIntent::ENHANCE)
2276             .execute();
2277 }
2278 
TEST_F(OutputUpdateColorProfile_AffectsChosenRenderIntentTest,Enhanced_Hdr_Prefers_ToneMapEnhance)2279 TEST_F(OutputUpdateColorProfile_AffectsChosenRenderIntentTest,
2280        Enhanced_Hdr_Prefers_ToneMapEnhance) {
2281     verify().ifDataspaceChosenIsHdr()
2282             .andOutputColorSettingIs(OutputColorSetting::kEnhanced)
2283             .thenExpectBestColorModeCallUses(ui::RenderIntent::TONE_MAP_ENHANCE)
2284             .execute();
2285 }
2286 
TEST_F(OutputUpdateColorProfile_AffectsChosenRenderIntentTest,Vendor_NonHdr_Prefers_Vendor)2287 TEST_F(OutputUpdateColorProfile_AffectsChosenRenderIntentTest, Vendor_NonHdr_Prefers_Vendor) {
2288     verify().ifDataspaceChosenIsNonHdr()
2289             .andOutputColorSettingIs(kVendorSpecifiedOutputColorSetting)
2290             .thenExpectBestColorModeCallUses(
2291                     static_cast<ui::RenderIntent>(kVendorSpecifiedOutputColorSetting))
2292             .execute();
2293 }
2294 
TEST_F(OutputUpdateColorProfile_AffectsChosenRenderIntentTest,Vendor_Hdr_Prefers_Vendor)2295 TEST_F(OutputUpdateColorProfile_AffectsChosenRenderIntentTest, Vendor_Hdr_Prefers_Vendor) {
2296     verify().ifDataspaceChosenIsHdr()
2297             .andOutputColorSettingIs(kVendorSpecifiedOutputColorSetting)
2298             .thenExpectBestColorModeCallUses(
2299                     static_cast<ui::RenderIntent>(kVendorSpecifiedOutputColorSetting))
2300             .execute();
2301 }
2302 
2303 /*
2304  * Output::beginFrame()
2305  */
2306 
2307 struct OutputBeginFrameTest : public ::testing::Test {
2308     using TestType = OutputBeginFrameTest;
2309 
2310     struct OutputPartialMock : public OutputPartialMockBase {
2311         // Sets up the helper functions called by the function under test to use
2312         // mock implementations.
2313         MOCK_CONST_METHOD1(getDirtyRegion, Region(bool));
2314     };
2315 
OutputBeginFrameTestandroid::compositionengine::__anon0cff14940111::OutputBeginFrameTest2316     OutputBeginFrameTest() {
2317         mOutput.setDisplayColorProfileForTest(
2318                 std::unique_ptr<DisplayColorProfile>(mDisplayColorProfile));
2319         mOutput.setRenderSurfaceForTest(std::unique_ptr<RenderSurface>(mRenderSurface));
2320     }
2321 
2322     struct IfGetDirtyRegionExpectationState
2323           : public CallOrderStateMachineHelper<TestType, IfGetDirtyRegionExpectationState> {
ifGetDirtyRegionReturnsandroid::compositionengine::__anon0cff14940111::OutputBeginFrameTest::IfGetDirtyRegionExpectationState2324         [[nodiscard]] auto ifGetDirtyRegionReturns(Region dirtyRegion) {
2325             EXPECT_CALL(getInstance()->mOutput, getDirtyRegion(false))
2326                     .WillOnce(Return(dirtyRegion));
2327             return nextState<AndIfGetOutputLayerCountExpectationState>();
2328         }
2329     };
2330 
2331     struct AndIfGetOutputLayerCountExpectationState
2332           : public CallOrderStateMachineHelper<TestType, AndIfGetOutputLayerCountExpectationState> {
andIfGetOutputLayerCountReturnsandroid::compositionengine::__anon0cff14940111::OutputBeginFrameTest::AndIfGetOutputLayerCountExpectationState2333         [[nodiscard]] auto andIfGetOutputLayerCountReturns(size_t layerCount) {
2334             EXPECT_CALL(getInstance()->mOutput, getOutputLayerCount()).WillOnce(Return(layerCount));
2335             return nextState<AndIfLastCompositionHadVisibleLayersState>();
2336         }
2337     };
2338 
2339     struct AndIfLastCompositionHadVisibleLayersState
2340           : public CallOrderStateMachineHelper<TestType,
2341                                                AndIfLastCompositionHadVisibleLayersState> {
andIfLastCompositionHadVisibleLayersIsandroid::compositionengine::__anon0cff14940111::OutputBeginFrameTest::AndIfLastCompositionHadVisibleLayersState2342         [[nodiscard]] auto andIfLastCompositionHadVisibleLayersIs(bool hadOutputLayers) {
2343             getInstance()->mOutput.mState.lastCompositionHadVisibleLayers = hadOutputLayers;
2344             return nextState<ThenExpectRenderSurfaceBeginFrameCallState>();
2345         }
2346     };
2347 
2348     struct ThenExpectRenderSurfaceBeginFrameCallState
2349           : public CallOrderStateMachineHelper<TestType,
2350                                                ThenExpectRenderSurfaceBeginFrameCallState> {
thenExpectRenderSurfaceBeginFrameCallandroid::compositionengine::__anon0cff14940111::OutputBeginFrameTest::ThenExpectRenderSurfaceBeginFrameCallState2351         [[nodiscard]] auto thenExpectRenderSurfaceBeginFrameCall(bool mustRecompose) {
2352             EXPECT_CALL(*getInstance()->mRenderSurface, beginFrame(mustRecompose));
2353             return nextState<ExecuteState>();
2354         }
2355     };
2356 
2357     struct ExecuteState : public CallOrderStateMachineHelper<TestType, ExecuteState> {
executeandroid::compositionengine::__anon0cff14940111::OutputBeginFrameTest::ExecuteState2358         [[nodiscard]] auto execute() {
2359             getInstance()->mOutput.beginFrame();
2360             return nextState<CheckPostconditionHadVisibleLayersState>();
2361         }
2362     };
2363 
2364     struct CheckPostconditionHadVisibleLayersState
2365           : public CallOrderStateMachineHelper<TestType, CheckPostconditionHadVisibleLayersState> {
checkPostconditionHadVisibleLayersandroid::compositionengine::__anon0cff14940111::OutputBeginFrameTest::CheckPostconditionHadVisibleLayersState2366         void checkPostconditionHadVisibleLayers(bool expected) {
2367             EXPECT_EQ(expected, getInstance()->mOutput.mState.lastCompositionHadVisibleLayers);
2368         }
2369     };
2370 
2371     // Tests call one of these two helper member functions to start using the
2372     // mini-DSL defined above.
verifyandroid::compositionengine::__anon0cff14940111::OutputBeginFrameTest2373     [[nodiscard]] auto verify() { return IfGetDirtyRegionExpectationState::make(this); }
2374 
2375     static const Region kEmptyRegion;
2376     static const Region kNotEmptyRegion;
2377 
2378     mock::DisplayColorProfile* mDisplayColorProfile = new StrictMock<mock::DisplayColorProfile>();
2379     mock::RenderSurface* mRenderSurface = new StrictMock<mock::RenderSurface>();
2380     StrictMock<OutputPartialMock> mOutput;
2381 };
2382 
2383 const Region OutputBeginFrameTest::kEmptyRegion{Rect{0, 0, 0, 0}};
2384 const Region OutputBeginFrameTest::kNotEmptyRegion{Rect{0, 0, 1, 1}};
2385 
TEST_F(OutputBeginFrameTest,hasDirtyHasLayersHadLayersLastFrame)2386 TEST_F(OutputBeginFrameTest, hasDirtyHasLayersHadLayersLastFrame) {
2387     verify().ifGetDirtyRegionReturns(kNotEmptyRegion)
2388             .andIfGetOutputLayerCountReturns(1u)
2389             .andIfLastCompositionHadVisibleLayersIs(true)
2390             .thenExpectRenderSurfaceBeginFrameCall(true)
2391             .execute()
2392             .checkPostconditionHadVisibleLayers(true);
2393 }
2394 
TEST_F(OutputBeginFrameTest,hasDirtyNotHasLayersHadLayersLastFrame)2395 TEST_F(OutputBeginFrameTest, hasDirtyNotHasLayersHadLayersLastFrame) {
2396     verify().ifGetDirtyRegionReturns(kNotEmptyRegion)
2397             .andIfGetOutputLayerCountReturns(0u)
2398             .andIfLastCompositionHadVisibleLayersIs(true)
2399             .thenExpectRenderSurfaceBeginFrameCall(true)
2400             .execute()
2401             .checkPostconditionHadVisibleLayers(false);
2402 }
2403 
TEST_F(OutputBeginFrameTest,hasDirtyHasLayersNotHadLayersLastFrame)2404 TEST_F(OutputBeginFrameTest, hasDirtyHasLayersNotHadLayersLastFrame) {
2405     verify().ifGetDirtyRegionReturns(kNotEmptyRegion)
2406             .andIfGetOutputLayerCountReturns(1u)
2407             .andIfLastCompositionHadVisibleLayersIs(false)
2408             .thenExpectRenderSurfaceBeginFrameCall(true)
2409             .execute()
2410             .checkPostconditionHadVisibleLayers(true);
2411 }
2412 
TEST_F(OutputBeginFrameTest,hasDirtyNotHasLayersNotHadLayersLastFrame)2413 TEST_F(OutputBeginFrameTest, hasDirtyNotHasLayersNotHadLayersLastFrame) {
2414     verify().ifGetDirtyRegionReturns(kNotEmptyRegion)
2415             .andIfGetOutputLayerCountReturns(0u)
2416             .andIfLastCompositionHadVisibleLayersIs(false)
2417             .thenExpectRenderSurfaceBeginFrameCall(false)
2418             .execute()
2419             .checkPostconditionHadVisibleLayers(false);
2420 }
2421 
TEST_F(OutputBeginFrameTest,notHasDirtyHasLayersHadLayersLastFrame)2422 TEST_F(OutputBeginFrameTest, notHasDirtyHasLayersHadLayersLastFrame) {
2423     verify().ifGetDirtyRegionReturns(kEmptyRegion)
2424             .andIfGetOutputLayerCountReturns(1u)
2425             .andIfLastCompositionHadVisibleLayersIs(true)
2426             .thenExpectRenderSurfaceBeginFrameCall(false)
2427             .execute()
2428             .checkPostconditionHadVisibleLayers(true);
2429 }
2430 
TEST_F(OutputBeginFrameTest,notHasDirtyNotHasLayersHadLayersLastFrame)2431 TEST_F(OutputBeginFrameTest, notHasDirtyNotHasLayersHadLayersLastFrame) {
2432     verify().ifGetDirtyRegionReturns(kEmptyRegion)
2433             .andIfGetOutputLayerCountReturns(0u)
2434             .andIfLastCompositionHadVisibleLayersIs(true)
2435             .thenExpectRenderSurfaceBeginFrameCall(false)
2436             .execute()
2437             .checkPostconditionHadVisibleLayers(true);
2438 }
2439 
TEST_F(OutputBeginFrameTest,notHasDirtyHasLayersNotHadLayersLastFrame)2440 TEST_F(OutputBeginFrameTest, notHasDirtyHasLayersNotHadLayersLastFrame) {
2441     verify().ifGetDirtyRegionReturns(kEmptyRegion)
2442             .andIfGetOutputLayerCountReturns(1u)
2443             .andIfLastCompositionHadVisibleLayersIs(false)
2444             .thenExpectRenderSurfaceBeginFrameCall(false)
2445             .execute()
2446             .checkPostconditionHadVisibleLayers(false);
2447 }
2448 
TEST_F(OutputBeginFrameTest,notHasDirtyNotHasLayersNotHadLayersLastFrame)2449 TEST_F(OutputBeginFrameTest, notHasDirtyNotHasLayersNotHadLayersLastFrame) {
2450     verify().ifGetDirtyRegionReturns(kEmptyRegion)
2451             .andIfGetOutputLayerCountReturns(0u)
2452             .andIfLastCompositionHadVisibleLayersIs(false)
2453             .thenExpectRenderSurfaceBeginFrameCall(false)
2454             .execute()
2455             .checkPostconditionHadVisibleLayers(false);
2456 }
2457 
2458 /*
2459  * Output::devOptRepaintFlash()
2460  */
2461 
2462 struct OutputDevOptRepaintFlashTest : public testing::Test {
2463     struct OutputPartialMock : public OutputPartialMockBase {
2464         // Sets up the helper functions called by the function under test to use
2465         // mock implementations.
2466         MOCK_CONST_METHOD1(getDirtyRegion, Region(bool));
2467         MOCK_METHOD2(composeSurfaces,
2468                      std::optional<base::unique_fd>(
2469                              const Region&, const compositionengine::CompositionRefreshArgs&));
2470         MOCK_METHOD0(postFramebuffer, void());
2471         MOCK_METHOD0(prepareFrame, void());
2472     };
2473 
OutputDevOptRepaintFlashTestandroid::compositionengine::__anon0cff14940111::OutputDevOptRepaintFlashTest2474     OutputDevOptRepaintFlashTest() {
2475         mOutput.setDisplayColorProfileForTest(
2476                 std::unique_ptr<DisplayColorProfile>(mDisplayColorProfile));
2477         mOutput.setRenderSurfaceForTest(std::unique_ptr<RenderSurface>(mRenderSurface));
2478     }
2479 
2480     static const Region kEmptyRegion;
2481     static const Region kNotEmptyRegion;
2482 
2483     StrictMock<OutputPartialMock> mOutput;
2484     mock::DisplayColorProfile* mDisplayColorProfile = new StrictMock<mock::DisplayColorProfile>();
2485     mock::RenderSurface* mRenderSurface = new StrictMock<mock::RenderSurface>();
2486     CompositionRefreshArgs mRefreshArgs;
2487 };
2488 
2489 const Region OutputDevOptRepaintFlashTest::kEmptyRegion{Rect{0, 0, 0, 0}};
2490 const Region OutputDevOptRepaintFlashTest::kNotEmptyRegion{Rect{0, 0, 1, 1}};
2491 
TEST_F(OutputDevOptRepaintFlashTest,doesNothingIfFlashDelayNotSet)2492 TEST_F(OutputDevOptRepaintFlashTest, doesNothingIfFlashDelayNotSet) {
2493     mRefreshArgs.devOptFlashDirtyRegionsDelay = {};
2494     mRefreshArgs.repaintEverything = true;
2495     mOutput.mState.isEnabled = true;
2496 
2497     mOutput.devOptRepaintFlash(mRefreshArgs);
2498 }
2499 
TEST_F(OutputDevOptRepaintFlashTest,postsAndPreparesANewFrameIfNotEnabled)2500 TEST_F(OutputDevOptRepaintFlashTest, postsAndPreparesANewFrameIfNotEnabled) {
2501     mRefreshArgs.devOptFlashDirtyRegionsDelay = std::chrono::microseconds(1);
2502     mRefreshArgs.repaintEverything = true;
2503     mOutput.mState.isEnabled = false;
2504 
2505     InSequence seq;
2506     EXPECT_CALL(mOutput, postFramebuffer());
2507     EXPECT_CALL(mOutput, prepareFrame());
2508 
2509     mOutput.devOptRepaintFlash(mRefreshArgs);
2510 }
2511 
TEST_F(OutputDevOptRepaintFlashTest,postsAndPreparesANewFrameIfNotDirty)2512 TEST_F(OutputDevOptRepaintFlashTest, postsAndPreparesANewFrameIfNotDirty) {
2513     mRefreshArgs.devOptFlashDirtyRegionsDelay = std::chrono::microseconds(1);
2514     mRefreshArgs.repaintEverything = true;
2515     mOutput.mState.isEnabled = true;
2516 
2517     InSequence seq;
2518     EXPECT_CALL(mOutput, getDirtyRegion(true)).WillOnce(Return(kEmptyRegion));
2519     EXPECT_CALL(mOutput, postFramebuffer());
2520     EXPECT_CALL(mOutput, prepareFrame());
2521 
2522     mOutput.devOptRepaintFlash(mRefreshArgs);
2523 }
2524 
TEST_F(OutputDevOptRepaintFlashTest,alsoComposesSurfacesAndQueuesABufferIfDirty)2525 TEST_F(OutputDevOptRepaintFlashTest, alsoComposesSurfacesAndQueuesABufferIfDirty) {
2526     mRefreshArgs.devOptFlashDirtyRegionsDelay = std::chrono::microseconds(1);
2527     mRefreshArgs.repaintEverything = false;
2528     mOutput.mState.isEnabled = true;
2529 
2530     InSequence seq;
2531     EXPECT_CALL(mOutput, getDirtyRegion(false)).WillOnce(Return(kNotEmptyRegion));
2532     EXPECT_CALL(mOutput, composeSurfaces(RegionEq(kNotEmptyRegion), Ref(mRefreshArgs)));
2533     EXPECT_CALL(*mRenderSurface, queueBuffer(_));
2534     EXPECT_CALL(mOutput, postFramebuffer());
2535     EXPECT_CALL(mOutput, prepareFrame());
2536 
2537     mOutput.devOptRepaintFlash(mRefreshArgs);
2538 }
2539 
2540 /*
2541  * Output::finishFrame()
2542  */
2543 
2544 struct OutputFinishFrameTest : public testing::Test {
2545     struct OutputPartialMock : public OutputPartialMockBase {
2546         // Sets up the helper functions called by the function under test to use
2547         // mock implementations.
2548         MOCK_METHOD2(composeSurfaces,
2549                      std::optional<base::unique_fd>(
2550                              const Region&, const compositionengine::CompositionRefreshArgs&));
2551         MOCK_METHOD0(postFramebuffer, void());
2552     };
2553 
OutputFinishFrameTestandroid::compositionengine::__anon0cff14940111::OutputFinishFrameTest2554     OutputFinishFrameTest() {
2555         mOutput.setDisplayColorProfileForTest(
2556                 std::unique_ptr<DisplayColorProfile>(mDisplayColorProfile));
2557         mOutput.setRenderSurfaceForTest(std::unique_ptr<RenderSurface>(mRenderSurface));
2558     }
2559 
2560     StrictMock<OutputPartialMock> mOutput;
2561     mock::DisplayColorProfile* mDisplayColorProfile = new StrictMock<mock::DisplayColorProfile>();
2562     mock::RenderSurface* mRenderSurface = new StrictMock<mock::RenderSurface>();
2563     CompositionRefreshArgs mRefreshArgs;
2564 };
2565 
TEST_F(OutputFinishFrameTest,ifNotEnabledDoesNothing)2566 TEST_F(OutputFinishFrameTest, ifNotEnabledDoesNothing) {
2567     mOutput.mState.isEnabled = false;
2568 
2569     mOutput.finishFrame(mRefreshArgs);
2570 }
2571 
TEST_F(OutputFinishFrameTest,takesEarlyOutifComposeSurfacesReturnsNoFence)2572 TEST_F(OutputFinishFrameTest, takesEarlyOutifComposeSurfacesReturnsNoFence) {
2573     mOutput.mState.isEnabled = true;
2574 
2575     InSequence seq;
2576     EXPECT_CALL(mOutput, composeSurfaces(RegionEq(Region::INVALID_REGION), _));
2577 
2578     mOutput.finishFrame(mRefreshArgs);
2579 }
2580 
TEST_F(OutputFinishFrameTest,queuesBufferIfComposeSurfacesReturnsAFence)2581 TEST_F(OutputFinishFrameTest, queuesBufferIfComposeSurfacesReturnsAFence) {
2582     mOutput.mState.isEnabled = true;
2583 
2584     InSequence seq;
2585     EXPECT_CALL(mOutput, composeSurfaces(RegionEq(Region::INVALID_REGION), _))
2586             .WillOnce(Return(ByMove(base::unique_fd())));
2587     EXPECT_CALL(*mRenderSurface, queueBuffer(_));
2588 
2589     mOutput.finishFrame(mRefreshArgs);
2590 }
2591 
2592 /*
2593  * Output::postFramebuffer()
2594  */
2595 
2596 struct OutputPostFramebufferTest : public testing::Test {
2597     struct OutputPartialMock : public OutputPartialMockBase {
2598         // Sets up the helper functions called by the function under test to use
2599         // mock implementations.
2600         MOCK_METHOD0(presentAndGetFrameFences, compositionengine::Output::FrameFences());
2601     };
2602 
2603     struct Layer {
Layerandroid::compositionengine::__anon0cff14940111::OutputPostFramebufferTest::Layer2604         Layer() {
2605             EXPECT_CALL(outputLayer, getLayerFE()).WillRepeatedly(ReturnRef(layerFE));
2606             EXPECT_CALL(outputLayer, getHwcLayer()).WillRepeatedly(Return(&hwc2Layer));
2607         }
2608 
2609         StrictMock<mock::OutputLayer> outputLayer;
2610         StrictMock<mock::LayerFE> layerFE;
2611         StrictMock<HWC2::mock::Layer> hwc2Layer;
2612     };
2613 
OutputPostFramebufferTestandroid::compositionengine::__anon0cff14940111::OutputPostFramebufferTest2614     OutputPostFramebufferTest() {
2615         mOutput.setDisplayColorProfileForTest(
2616                 std::unique_ptr<DisplayColorProfile>(mDisplayColorProfile));
2617         mOutput.setRenderSurfaceForTest(std::unique_ptr<RenderSurface>(mRenderSurface));
2618 
2619         EXPECT_CALL(mOutput, getOutputLayerCount()).WillRepeatedly(Return(3u));
2620         EXPECT_CALL(mOutput, getOutputLayerOrderedByZByIndex(0u))
2621                 .WillRepeatedly(Return(&mLayer1.outputLayer));
2622         EXPECT_CALL(mOutput, getOutputLayerOrderedByZByIndex(1u))
2623                 .WillRepeatedly(Return(&mLayer2.outputLayer));
2624         EXPECT_CALL(mOutput, getOutputLayerOrderedByZByIndex(2u))
2625                 .WillRepeatedly(Return(&mLayer3.outputLayer));
2626     }
2627 
2628     StrictMock<OutputPartialMock> mOutput;
2629     mock::DisplayColorProfile* mDisplayColorProfile = new StrictMock<mock::DisplayColorProfile>();
2630     mock::RenderSurface* mRenderSurface = new StrictMock<mock::RenderSurface>();
2631 
2632     Layer mLayer1;
2633     Layer mLayer2;
2634     Layer mLayer3;
2635 };
2636 
TEST_F(OutputPostFramebufferTest,ifNotEnabledDoesNothing)2637 TEST_F(OutputPostFramebufferTest, ifNotEnabledDoesNothing) {
2638     mOutput.mState.isEnabled = false;
2639 
2640     mOutput.postFramebuffer();
2641 }
2642 
TEST_F(OutputPostFramebufferTest,ifEnabledMustFlipThenPresentThenSendPresentCompleted)2643 TEST_F(OutputPostFramebufferTest, ifEnabledMustFlipThenPresentThenSendPresentCompleted) {
2644     mOutput.mState.isEnabled = true;
2645 
2646     compositionengine::Output::FrameFences frameFences;
2647 
2648     // This should happen even if there are no output layers.
2649     EXPECT_CALL(mOutput, getOutputLayerCount()).WillOnce(Return(0u));
2650 
2651     // For this test in particular we want to make sure the call expectations
2652     // setup below are satisfied in the specific order.
2653     InSequence seq;
2654 
2655     EXPECT_CALL(*mRenderSurface, flip());
2656     EXPECT_CALL(mOutput, presentAndGetFrameFences()).WillOnce(Return(frameFences));
2657     EXPECT_CALL(*mRenderSurface, onPresentDisplayCompleted());
2658 
2659     mOutput.postFramebuffer();
2660 }
2661 
TEST_F(OutputPostFramebufferTest,releaseFencesAreSentToLayerFE)2662 TEST_F(OutputPostFramebufferTest, releaseFencesAreSentToLayerFE) {
2663     // Simulate getting release fences from each layer, and ensure they are passed to the
2664     // front-end layer interface for each layer correctly.
2665 
2666     mOutput.mState.isEnabled = true;
2667 
2668     // Create three unique fence instances
2669     sp<Fence> layer1Fence = new Fence();
2670     sp<Fence> layer2Fence = new Fence();
2671     sp<Fence> layer3Fence = new Fence();
2672 
2673     Output::FrameFences frameFences;
2674     frameFences.layerFences.emplace(&mLayer1.hwc2Layer, layer1Fence);
2675     frameFences.layerFences.emplace(&mLayer2.hwc2Layer, layer2Fence);
2676     frameFences.layerFences.emplace(&mLayer3.hwc2Layer, layer3Fence);
2677 
2678     EXPECT_CALL(*mRenderSurface, flip());
2679     EXPECT_CALL(mOutput, presentAndGetFrameFences()).WillOnce(Return(frameFences));
2680     EXPECT_CALL(*mRenderSurface, onPresentDisplayCompleted());
2681 
2682     // Compare the pointers values of each fence to make sure the correct ones
2683     // are passed. This happens to work with the current implementation, but
2684     // would not survive certain calls like Fence::merge() which would return a
2685     // new instance.
2686     EXPECT_CALL(mLayer1.layerFE,
2687                 onLayerDisplayed(Property(&sp<Fence>::get, Eq(layer1Fence.get()))));
2688     EXPECT_CALL(mLayer2.layerFE,
2689                 onLayerDisplayed(Property(&sp<Fence>::get, Eq(layer2Fence.get()))));
2690     EXPECT_CALL(mLayer3.layerFE,
2691                 onLayerDisplayed(Property(&sp<Fence>::get, Eq(layer3Fence.get()))));
2692 
2693     mOutput.postFramebuffer();
2694 }
2695 
TEST_F(OutputPostFramebufferTest,releaseFencesIncludeClientTargetAcquireFence)2696 TEST_F(OutputPostFramebufferTest, releaseFencesIncludeClientTargetAcquireFence) {
2697     mOutput.mState.isEnabled = true;
2698     mOutput.mState.usesClientComposition = true;
2699 
2700     sp<Fence> clientTargetAcquireFence = new Fence();
2701     sp<Fence> layer1Fence = new Fence();
2702     sp<Fence> layer2Fence = new Fence();
2703     sp<Fence> layer3Fence = new Fence();
2704     Output::FrameFences frameFences;
2705     frameFences.clientTargetAcquireFence = clientTargetAcquireFence;
2706     frameFences.layerFences.emplace(&mLayer1.hwc2Layer, layer1Fence);
2707     frameFences.layerFences.emplace(&mLayer2.hwc2Layer, layer2Fence);
2708     frameFences.layerFences.emplace(&mLayer3.hwc2Layer, layer3Fence);
2709 
2710     EXPECT_CALL(*mRenderSurface, flip());
2711     EXPECT_CALL(mOutput, presentAndGetFrameFences()).WillOnce(Return(frameFences));
2712     EXPECT_CALL(*mRenderSurface, onPresentDisplayCompleted());
2713 
2714     // Fence::merge is called, and since none of the fences are actually valid,
2715     // Fence::NO_FENCE is returned and passed to each onLayerDisplayed() call.
2716     // This is the best we can do without creating a real kernel fence object.
2717     EXPECT_CALL(mLayer1.layerFE, onLayerDisplayed(Fence::NO_FENCE));
2718     EXPECT_CALL(mLayer2.layerFE, onLayerDisplayed(Fence::NO_FENCE));
2719     EXPECT_CALL(mLayer3.layerFE, onLayerDisplayed(Fence::NO_FENCE));
2720 
2721     mOutput.postFramebuffer();
2722 }
2723 
TEST_F(OutputPostFramebufferTest,releasedLayersSentPresentFence)2724 TEST_F(OutputPostFramebufferTest, releasedLayersSentPresentFence) {
2725     mOutput.mState.isEnabled = true;
2726     mOutput.mState.usesClientComposition = true;
2727 
2728     // This should happen even if there are no (current) output layers.
2729     EXPECT_CALL(mOutput, getOutputLayerCount()).WillOnce(Return(0u));
2730 
2731     // Load up the released layers with some mock instances
2732     sp<StrictMock<mock::LayerFE>> releasedLayer1{new StrictMock<mock::LayerFE>()};
2733     sp<StrictMock<mock::LayerFE>> releasedLayer2{new StrictMock<mock::LayerFE>()};
2734     sp<StrictMock<mock::LayerFE>> releasedLayer3{new StrictMock<mock::LayerFE>()};
2735     Output::ReleasedLayers layers;
2736     layers.push_back(releasedLayer1);
2737     layers.push_back(releasedLayer2);
2738     layers.push_back(releasedLayer3);
2739     mOutput.setReleasedLayers(std::move(layers));
2740 
2741     // Set up a fake present fence
2742     sp<Fence> presentFence = new Fence();
2743     Output::FrameFences frameFences;
2744     frameFences.presentFence = presentFence;
2745 
2746     EXPECT_CALL(*mRenderSurface, flip());
2747     EXPECT_CALL(mOutput, presentAndGetFrameFences()).WillOnce(Return(frameFences));
2748     EXPECT_CALL(*mRenderSurface, onPresentDisplayCompleted());
2749 
2750     // Each released layer should be given the presentFence.
2751     EXPECT_CALL(*releasedLayer1,
2752                 onLayerDisplayed(Property(&sp<Fence>::get, Eq(presentFence.get()))));
2753     EXPECT_CALL(*releasedLayer2,
2754                 onLayerDisplayed(Property(&sp<Fence>::get, Eq(presentFence.get()))));
2755     EXPECT_CALL(*releasedLayer3,
2756                 onLayerDisplayed(Property(&sp<Fence>::get, Eq(presentFence.get()))));
2757 
2758     mOutput.postFramebuffer();
2759 
2760     // After the call the list of released layers should have been cleared.
2761     EXPECT_TRUE(mOutput.getReleasedLayersForTest().empty());
2762 }
2763 
2764 /*
2765  * Output::composeSurfaces()
2766  */
2767 
2768 struct OutputComposeSurfacesTest : public testing::Test {
2769     using TestType = OutputComposeSurfacesTest;
2770 
2771     struct OutputPartialMock : public OutputPartialMockBase {
2772         // Sets up the helper functions called by the function under test to use
2773         // mock implementations.
2774         MOCK_CONST_METHOD0(getSkipColorTransform, bool());
2775         MOCK_METHOD3(generateClientCompositionRequests,
2776                      std::vector<LayerFE::LayerSettings>(bool, Region&, ui::Dataspace));
2777         MOCK_METHOD2(appendRegionFlashRequests,
2778                      void(const Region&, std::vector<LayerFE::LayerSettings>&));
2779         MOCK_METHOD1(setExpensiveRenderingExpected, void(bool));
2780     };
2781 
OutputComposeSurfacesTestandroid::compositionengine::__anon0cff14940111::OutputComposeSurfacesTest2782     OutputComposeSurfacesTest() {
2783         mOutput.setDisplayColorProfileForTest(
2784                 std::unique_ptr<DisplayColorProfile>(mDisplayColorProfile));
2785         mOutput.setRenderSurfaceForTest(std::unique_ptr<RenderSurface>(mRenderSurface));
2786         mOutput.cacheClientCompositionRequests(MAX_CLIENT_COMPOSITION_CACHE_SIZE);
2787 
2788         mOutput.mState.frame = kDefaultOutputFrame;
2789         mOutput.mState.viewport = kDefaultOutputViewport;
2790         mOutput.mState.sourceClip = kDefaultOutputSourceClip;
2791         mOutput.mState.destinationClip = kDefaultOutputDestinationClip;
2792         mOutput.mState.transform = ui::Transform{kDefaultOutputOrientation};
2793         mOutput.mState.orientation = kDefaultOutputOrientation;
2794         mOutput.mState.dataspace = kDefaultOutputDataspace;
2795         mOutput.mState.colorTransformMatrix = kDefaultColorTransformMat;
2796         mOutput.mState.isSecure = false;
2797         mOutput.mState.needsFiltering = false;
2798         mOutput.mState.usesClientComposition = true;
2799         mOutput.mState.usesDeviceComposition = false;
2800         mOutput.mState.reusedClientComposition = false;
2801         mOutput.mState.flipClientTarget = false;
2802 
2803         EXPECT_CALL(mOutput, getCompositionEngine()).WillRepeatedly(ReturnRef(mCompositionEngine));
2804         EXPECT_CALL(mCompositionEngine, getRenderEngine()).WillRepeatedly(ReturnRef(mRenderEngine));
2805         EXPECT_CALL(mCompositionEngine, getTimeStats())
2806                 .WillRepeatedly(ReturnRef(*mTimeStats.get()));
2807         EXPECT_CALL(*mDisplayColorProfile, getHdrCapabilities())
2808                 .WillRepeatedly(ReturnRef(kHdrCapabilities));
2809     }
2810 
2811     struct ExecuteState : public CallOrderStateMachineHelper<TestType, ExecuteState> {
executeandroid::compositionengine::__anon0cff14940111::OutputComposeSurfacesTest::ExecuteState2812         auto execute() {
2813             getInstance()->mReadyFence =
2814                     getInstance()->mOutput.composeSurfaces(kDebugRegion, kDefaultRefreshArgs);
2815             return nextState<FenceCheckState>();
2816         }
2817     };
2818 
2819     struct FenceCheckState : public CallOrderStateMachineHelper<TestType, FenceCheckState> {
expectNoFenceWasReturnedandroid::compositionengine::__anon0cff14940111::OutputComposeSurfacesTest::FenceCheckState2820         void expectNoFenceWasReturned() { EXPECT_FALSE(getInstance()->mReadyFence); }
2821 
expectAFenceWasReturnedandroid::compositionengine::__anon0cff14940111::OutputComposeSurfacesTest::FenceCheckState2822         void expectAFenceWasReturned() { EXPECT_TRUE(getInstance()->mReadyFence); }
2823     };
2824 
2825     // Call this member function to start using the mini-DSL defined above.
verifyandroid::compositionengine::__anon0cff14940111::OutputComposeSurfacesTest2826     [[nodiscard]] auto verify() { return ExecuteState::make(this); }
2827 
2828     static constexpr uint32_t kDefaultOutputOrientation = TR_IDENT;
2829     static constexpr ui::Dataspace kDefaultOutputDataspace = ui::Dataspace::UNKNOWN;
2830     static constexpr ui::Dataspace kExpensiveOutputDataspace = ui::Dataspace::DISPLAY_P3;
2831     static constexpr float kDefaultMaxLuminance = 0.9f;
2832     static constexpr float kDefaultAvgLuminance = 0.7f;
2833     static constexpr float kDefaultMinLuminance = 0.1f;
2834 
2835     static const Rect kDefaultOutputFrame;
2836     static const Rect kDefaultOutputViewport;
2837     static const Rect kDefaultOutputSourceClip;
2838     static const Rect kDefaultOutputDestinationClip;
2839     static const mat4 kDefaultColorTransformMat;
2840 
2841     static const Region kDebugRegion;
2842     static const compositionengine::CompositionRefreshArgs kDefaultRefreshArgs;
2843     static const HdrCapabilities kHdrCapabilities;
2844 
2845     StrictMock<mock::CompositionEngine> mCompositionEngine;
2846     StrictMock<renderengine::mock::RenderEngine> mRenderEngine;
2847     // TODO: make this is a proper mock.
2848     std::shared_ptr<TimeStats> mTimeStats = std::make_shared<android::impl::TimeStats>();
2849     mock::DisplayColorProfile* mDisplayColorProfile = new StrictMock<mock::DisplayColorProfile>();
2850     mock::RenderSurface* mRenderSurface = new StrictMock<mock::RenderSurface>();
2851     StrictMock<OutputPartialMock> mOutput;
2852     sp<GraphicBuffer> mOutputBuffer = new GraphicBuffer();
2853 
2854     std::optional<base::unique_fd> mReadyFence;
2855 };
2856 
2857 const Rect OutputComposeSurfacesTest::kDefaultOutputFrame{1001, 1002, 1003, 1004};
2858 const Rect OutputComposeSurfacesTest::kDefaultOutputViewport{1005, 1006, 1007, 1008};
2859 const Rect OutputComposeSurfacesTest::kDefaultOutputSourceClip{1009, 1010, 1011, 1012};
2860 const Rect OutputComposeSurfacesTest::kDefaultOutputDestinationClip{1013, 1014, 1015, 1016};
2861 const mat4 OutputComposeSurfacesTest::kDefaultColorTransformMat{mat4() * 0.5f};
2862 const compositionengine::CompositionRefreshArgs OutputComposeSurfacesTest::kDefaultRefreshArgs;
2863 const Region OutputComposeSurfacesTest::kDebugRegion{Rect{100, 101, 102, 103}};
2864 const HdrCapabilities OutputComposeSurfacesTest::
2865         kHdrCapabilities{{},
2866                          OutputComposeSurfacesTest::kDefaultMaxLuminance,
2867                          OutputComposeSurfacesTest::kDefaultAvgLuminance,
2868                          OutputComposeSurfacesTest::kDefaultMinLuminance};
2869 
TEST_F(OutputComposeSurfacesTest,doesNothingButSignalNoExpensiveRenderingIfNoClientComposition)2870 TEST_F(OutputComposeSurfacesTest, doesNothingButSignalNoExpensiveRenderingIfNoClientComposition) {
2871     mOutput.mState.usesClientComposition = false;
2872 
2873     EXPECT_CALL(mRenderEngine, supportsProtectedContent()).WillRepeatedly(Return(false));
2874 
2875     EXPECT_CALL(mOutput, setExpensiveRenderingExpected(false));
2876 
2877     verify().execute().expectAFenceWasReturned();
2878 }
2879 
TEST_F(OutputComposeSurfacesTest,dequeuesABufferIfNoClientCompositionButFlipClientTargetRequested)2880 TEST_F(OutputComposeSurfacesTest,
2881        dequeuesABufferIfNoClientCompositionButFlipClientTargetRequested) {
2882     mOutput.mState.usesClientComposition = false;
2883     mOutput.mState.flipClientTarget = true;
2884 
2885     EXPECT_CALL(mRenderEngine, supportsProtectedContent()).WillRepeatedly(Return(false));
2886 
2887     EXPECT_CALL(*mRenderSurface, dequeueBuffer(_)).WillOnce(Return(mOutputBuffer));
2888     EXPECT_CALL(mOutput, setExpensiveRenderingExpected(false));
2889 
2890     verify().execute().expectAFenceWasReturned();
2891 }
2892 
TEST_F(OutputComposeSurfacesTest,doesMinimalWorkIfDequeueBufferFailsForClientComposition)2893 TEST_F(OutputComposeSurfacesTest, doesMinimalWorkIfDequeueBufferFailsForClientComposition) {
2894     EXPECT_CALL(mRenderEngine, supportsProtectedContent()).WillRepeatedly(Return(false));
2895 
2896     EXPECT_CALL(*mRenderSurface, dequeueBuffer(_)).WillOnce(Return(nullptr));
2897 
2898     verify().execute().expectNoFenceWasReturned();
2899 }
2900 
TEST_F(OutputComposeSurfacesTest,doesMinimalWorkIfDequeueBufferFailsForNoClientCompositionButFlipClientTargetRequested)2901 TEST_F(OutputComposeSurfacesTest,
2902        doesMinimalWorkIfDequeueBufferFailsForNoClientCompositionButFlipClientTargetRequested) {
2903     mOutput.mState.usesClientComposition = false;
2904     mOutput.mState.flipClientTarget = true;
2905 
2906     EXPECT_CALL(mRenderEngine, supportsProtectedContent()).WillRepeatedly(Return(false));
2907 
2908     EXPECT_CALL(*mRenderSurface, dequeueBuffer(_)).WillOnce(Return(nullptr));
2909 
2910     verify().execute().expectNoFenceWasReturned();
2911 }
2912 
TEST_F(OutputComposeSurfacesTest,handlesZeroCompositionRequests)2913 TEST_F(OutputComposeSurfacesTest, handlesZeroCompositionRequests) {
2914     EXPECT_CALL(mOutput, getSkipColorTransform()).WillRepeatedly(Return(false));
2915     EXPECT_CALL(*mDisplayColorProfile, hasWideColorGamut()).WillRepeatedly(Return(true));
2916     EXPECT_CALL(mRenderEngine, supportsProtectedContent()).WillRepeatedly(Return(false));
2917     EXPECT_CALL(mOutput, generateClientCompositionRequests(_, _, kDefaultOutputDataspace))
2918             .WillRepeatedly(Return(std::vector<LayerFE::LayerSettings>{}));
2919     EXPECT_CALL(mOutput, appendRegionFlashRequests(RegionEq(kDebugRegion), _))
2920             .WillRepeatedly(Return());
2921 
2922     EXPECT_CALL(*mRenderSurface, dequeueBuffer(_)).WillRepeatedly(Return(mOutputBuffer));
2923     EXPECT_CALL(mRenderEngine, drawLayers(_, IsEmpty(), _, true, _, _))
2924             .WillRepeatedly(Return(NO_ERROR));
2925 
2926     verify().execute().expectAFenceWasReturned();
2927 }
2928 
TEST_F(OutputComposeSurfacesTest,buildsAndRendersRequestList)2929 TEST_F(OutputComposeSurfacesTest, buildsAndRendersRequestList) {
2930     LayerFE::LayerSettings r1;
2931     LayerFE::LayerSettings r2;
2932 
2933     r1.geometry.boundaries = FloatRect{1, 2, 3, 4};
2934     r2.geometry.boundaries = FloatRect{5, 6, 7, 8};
2935 
2936     EXPECT_CALL(mOutput, getSkipColorTransform()).WillRepeatedly(Return(false));
2937     EXPECT_CALL(*mDisplayColorProfile, hasWideColorGamut()).WillRepeatedly(Return(true));
2938     EXPECT_CALL(mRenderEngine, supportsProtectedContent()).WillRepeatedly(Return(false));
2939     EXPECT_CALL(mOutput, generateClientCompositionRequests(_, _, kDefaultOutputDataspace))
2940             .WillRepeatedly(Return(std::vector<LayerFE::LayerSettings>{r1}));
2941     EXPECT_CALL(mOutput, appendRegionFlashRequests(RegionEq(kDebugRegion), _))
2942             .WillRepeatedly(
2943                     Invoke([&](const Region&,
2944                                std::vector<LayerFE::LayerSettings>& clientCompositionLayers) {
2945                         clientCompositionLayers.emplace_back(r2);
2946                     }));
2947 
2948     EXPECT_CALL(*mRenderSurface, dequeueBuffer(_)).WillRepeatedly(Return(mOutputBuffer));
2949     EXPECT_CALL(mRenderEngine, drawLayers(_, ElementsAre(Pointee(r1), Pointee(r2)), _, true, _, _))
2950             .WillRepeatedly(Return(NO_ERROR));
2951 
2952     verify().execute().expectAFenceWasReturned();
2953 }
2954 
TEST_F(OutputComposeSurfacesTest,renderDuplicateClientCompositionRequestsWithoutCache)2955 TEST_F(OutputComposeSurfacesTest, renderDuplicateClientCompositionRequestsWithoutCache) {
2956     mOutput.cacheClientCompositionRequests(0);
2957     LayerFE::LayerSettings r1;
2958     LayerFE::LayerSettings r2;
2959 
2960     r1.geometry.boundaries = FloatRect{1, 2, 3, 4};
2961     r2.geometry.boundaries = FloatRect{5, 6, 7, 8};
2962 
2963     EXPECT_CALL(mOutput, getSkipColorTransform()).WillRepeatedly(Return(false));
2964     EXPECT_CALL(*mDisplayColorProfile, hasWideColorGamut()).WillRepeatedly(Return(true));
2965     EXPECT_CALL(mRenderEngine, supportsProtectedContent()).WillRepeatedly(Return(false));
2966     EXPECT_CALL(mOutput, generateClientCompositionRequests(_, _, kDefaultOutputDataspace))
2967             .WillRepeatedly(Return(std::vector<LayerFE::LayerSettings>{r1, r2}));
2968     EXPECT_CALL(mOutput, appendRegionFlashRequests(RegionEq(kDebugRegion), _))
2969             .WillRepeatedly(Return());
2970 
2971     EXPECT_CALL(*mRenderSurface, dequeueBuffer(_)).WillRepeatedly(Return(mOutputBuffer));
2972     EXPECT_CALL(mRenderEngine, drawLayers(_, ElementsAre(Pointee(r1), Pointee(r2)), _, true, _, _))
2973             .Times(2)
2974             .WillOnce(Return(NO_ERROR));
2975 
2976     verify().execute().expectAFenceWasReturned();
2977     EXPECT_FALSE(mOutput.mState.reusedClientComposition);
2978 
2979     verify().execute().expectAFenceWasReturned();
2980     EXPECT_FALSE(mOutput.mState.reusedClientComposition);
2981 }
2982 
TEST_F(OutputComposeSurfacesTest,skipDuplicateClientCompositionRequests)2983 TEST_F(OutputComposeSurfacesTest, skipDuplicateClientCompositionRequests) {
2984     mOutput.cacheClientCompositionRequests(3);
2985     LayerFE::LayerSettings r1;
2986     LayerFE::LayerSettings r2;
2987 
2988     r1.geometry.boundaries = FloatRect{1, 2, 3, 4};
2989     r2.geometry.boundaries = FloatRect{5, 6, 7, 8};
2990 
2991     EXPECT_CALL(mOutput, getSkipColorTransform()).WillRepeatedly(Return(false));
2992     EXPECT_CALL(*mDisplayColorProfile, hasWideColorGamut()).WillRepeatedly(Return(true));
2993     EXPECT_CALL(mRenderEngine, supportsProtectedContent()).WillRepeatedly(Return(false));
2994     EXPECT_CALL(mOutput, generateClientCompositionRequests(_, _, kDefaultOutputDataspace))
2995             .WillRepeatedly(Return(std::vector<LayerFE::LayerSettings>{r1, r2}));
2996     EXPECT_CALL(mOutput, appendRegionFlashRequests(RegionEq(kDebugRegion), _))
2997             .WillRepeatedly(Return());
2998 
2999     EXPECT_CALL(*mRenderSurface, dequeueBuffer(_)).WillRepeatedly(Return(mOutputBuffer));
3000     EXPECT_CALL(mRenderEngine, drawLayers(_, ElementsAre(Pointee(r1), Pointee(r2)), _, true, _, _))
3001             .WillOnce(Return(NO_ERROR));
3002     EXPECT_CALL(mOutput, setExpensiveRenderingExpected(false));
3003 
3004     verify().execute().expectAFenceWasReturned();
3005     EXPECT_FALSE(mOutput.mState.reusedClientComposition);
3006 
3007     // We do not expect another call to draw layers.
3008     verify().execute().expectAFenceWasReturned();
3009     EXPECT_TRUE(mOutput.mState.reusedClientComposition);
3010 }
3011 
TEST_F(OutputComposeSurfacesTest,clientCompositionIfBufferChanges)3012 TEST_F(OutputComposeSurfacesTest, clientCompositionIfBufferChanges) {
3013     LayerFE::LayerSettings r1;
3014     LayerFE::LayerSettings r2;
3015 
3016     r1.geometry.boundaries = FloatRect{1, 2, 3, 4};
3017     r2.geometry.boundaries = FloatRect{5, 6, 7, 8};
3018 
3019     EXPECT_CALL(mOutput, getSkipColorTransform()).WillRepeatedly(Return(false));
3020     EXPECT_CALL(*mDisplayColorProfile, hasWideColorGamut()).WillRepeatedly(Return(true));
3021     EXPECT_CALL(mRenderEngine, supportsProtectedContent()).WillRepeatedly(Return(false));
3022     EXPECT_CALL(mOutput, generateClientCompositionRequests(_, _, kDefaultOutputDataspace))
3023             .WillRepeatedly(Return(std::vector<LayerFE::LayerSettings>{r1, r2}));
3024     EXPECT_CALL(mOutput, appendRegionFlashRequests(RegionEq(kDebugRegion), _))
3025             .WillRepeatedly(Return());
3026 
3027     sp<GraphicBuffer> otherOutputBuffer = new GraphicBuffer();
3028     EXPECT_CALL(*mRenderSurface, dequeueBuffer(_))
3029             .WillOnce(Return(mOutputBuffer))
3030             .WillOnce(Return(otherOutputBuffer));
3031     EXPECT_CALL(mRenderEngine, drawLayers(_, ElementsAre(Pointee(r1), Pointee(r2)), _, true, _, _))
3032             .WillRepeatedly(Return(NO_ERROR));
3033 
3034     verify().execute().expectAFenceWasReturned();
3035     EXPECT_FALSE(mOutput.mState.reusedClientComposition);
3036 
3037     verify().execute().expectAFenceWasReturned();
3038     EXPECT_FALSE(mOutput.mState.reusedClientComposition);
3039 }
3040 
TEST_F(OutputComposeSurfacesTest,clientCompositionIfRequestChanges)3041 TEST_F(OutputComposeSurfacesTest, clientCompositionIfRequestChanges) {
3042     LayerFE::LayerSettings r1;
3043     LayerFE::LayerSettings r2;
3044     LayerFE::LayerSettings r3;
3045 
3046     r1.geometry.boundaries = FloatRect{1, 2, 3, 4};
3047     r2.geometry.boundaries = FloatRect{5, 6, 7, 8};
3048     r3.geometry.boundaries = FloatRect{5, 6, 7, 9};
3049 
3050     EXPECT_CALL(mOutput, getSkipColorTransform()).WillRepeatedly(Return(false));
3051     EXPECT_CALL(*mDisplayColorProfile, hasWideColorGamut()).WillRepeatedly(Return(true));
3052     EXPECT_CALL(mRenderEngine, supportsProtectedContent()).WillRepeatedly(Return(false));
3053     EXPECT_CALL(mOutput, generateClientCompositionRequests(_, _, kDefaultOutputDataspace))
3054             .WillOnce(Return(std::vector<LayerFE::LayerSettings>{r1, r2}))
3055             .WillOnce(Return(std::vector<LayerFE::LayerSettings>{r1, r3}));
3056     EXPECT_CALL(mOutput, appendRegionFlashRequests(RegionEq(kDebugRegion), _))
3057             .WillRepeatedly(Return());
3058 
3059     EXPECT_CALL(*mRenderSurface, dequeueBuffer(_)).WillRepeatedly(Return(mOutputBuffer));
3060     EXPECT_CALL(mRenderEngine, drawLayers(_, ElementsAre(Pointee(r1), Pointee(r2)), _, true, _, _))
3061             .WillOnce(Return(NO_ERROR));
3062     EXPECT_CALL(mRenderEngine, drawLayers(_, ElementsAre(Pointee(r1), Pointee(r3)), _, true, _, _))
3063             .WillOnce(Return(NO_ERROR));
3064 
3065     verify().execute().expectAFenceWasReturned();
3066     EXPECT_FALSE(mOutput.mState.reusedClientComposition);
3067 
3068     verify().execute().expectAFenceWasReturned();
3069     EXPECT_FALSE(mOutput.mState.reusedClientComposition);
3070 }
3071 
3072 struct OutputComposeSurfacesTest_UsesExpectedDisplaySettings : public OutputComposeSurfacesTest {
OutputComposeSurfacesTest_UsesExpectedDisplaySettingsandroid::compositionengine::__anon0cff14940111::OutputComposeSurfacesTest_UsesExpectedDisplaySettings3073     OutputComposeSurfacesTest_UsesExpectedDisplaySettings() {
3074         EXPECT_CALL(mRenderEngine, supportsProtectedContent()).WillRepeatedly(Return(false));
3075         EXPECT_CALL(mOutput, generateClientCompositionRequests(_, _, kDefaultOutputDataspace))
3076                 .WillRepeatedly(Return(std::vector<LayerFE::LayerSettings>{}));
3077         EXPECT_CALL(mOutput, appendRegionFlashRequests(RegionEq(kDebugRegion), _))
3078                 .WillRepeatedly(Return());
3079         EXPECT_CALL(*mRenderSurface, dequeueBuffer(_)).WillRepeatedly(Return(mOutputBuffer));
3080     }
3081 
3082     struct MixedCompositionState
3083           : public CallOrderStateMachineHelper<TestType, MixedCompositionState> {
ifMixedCompositionIsandroid::compositionengine::__anon0cff14940111::OutputComposeSurfacesTest_UsesExpectedDisplaySettings::MixedCompositionState3084         auto ifMixedCompositionIs(bool used) {
3085             getInstance()->mOutput.mState.usesDeviceComposition = used;
3086             return nextState<OutputUsesHdrState>();
3087         }
3088     };
3089 
3090     struct OutputUsesHdrState : public CallOrderStateMachineHelper<TestType, OutputUsesHdrState> {
andIfUsesHdrandroid::compositionengine::__anon0cff14940111::OutputComposeSurfacesTest_UsesExpectedDisplaySettings::OutputUsesHdrState3091         auto andIfUsesHdr(bool used) {
3092             EXPECT_CALL(*getInstance()->mDisplayColorProfile, hasWideColorGamut())
3093                     .WillOnce(Return(used));
3094             return nextState<SkipColorTransformState>();
3095         }
3096     };
3097 
3098     struct SkipColorTransformState
3099           : public CallOrderStateMachineHelper<TestType, SkipColorTransformState> {
andIfSkipColorTransformandroid::compositionengine::__anon0cff14940111::OutputComposeSurfacesTest_UsesExpectedDisplaySettings::SkipColorTransformState3100         auto andIfSkipColorTransform(bool skip) {
3101             // May be called zero or one times.
3102             EXPECT_CALL(getInstance()->mOutput, getSkipColorTransform())
3103                     .WillRepeatedly(Return(skip));
3104             return nextState<ExpectDisplaySettingsState>();
3105         }
3106     };
3107 
3108     struct ExpectDisplaySettingsState
3109           : public CallOrderStateMachineHelper<TestType, ExpectDisplaySettingsState> {
thenExpectDisplaySettingsUsedandroid::compositionengine::__anon0cff14940111::OutputComposeSurfacesTest_UsesExpectedDisplaySettings::ExpectDisplaySettingsState3110         auto thenExpectDisplaySettingsUsed(renderengine::DisplaySettings settings) {
3111             EXPECT_CALL(getInstance()->mRenderEngine, drawLayers(settings, _, _, true, _, _))
3112                     .WillOnce(Return(NO_ERROR));
3113             return nextState<ExecuteState>();
3114         }
3115     };
3116 
3117     // Call this member function to start using the mini-DSL defined above.
verifyandroid::compositionengine::__anon0cff14940111::OutputComposeSurfacesTest_UsesExpectedDisplaySettings3118     [[nodiscard]] auto verify() { return MixedCompositionState::make(this); }
3119 };
3120 
TEST_F(OutputComposeSurfacesTest_UsesExpectedDisplaySettings,forHdrMixedComposition)3121 TEST_F(OutputComposeSurfacesTest_UsesExpectedDisplaySettings, forHdrMixedComposition) {
3122     verify().ifMixedCompositionIs(true)
3123             .andIfUsesHdr(true)
3124             .andIfSkipColorTransform(false)
3125             .thenExpectDisplaySettingsUsed({kDefaultOutputDestinationClip, kDefaultOutputSourceClip,
3126                                             kDefaultMaxLuminance, kDefaultOutputDataspace, mat4(),
3127                                             Region::INVALID_REGION, kDefaultOutputOrientation})
3128             .execute()
3129             .expectAFenceWasReturned();
3130 }
3131 
TEST_F(OutputComposeSurfacesTest_UsesExpectedDisplaySettings,forNonHdrMixedComposition)3132 TEST_F(OutputComposeSurfacesTest_UsesExpectedDisplaySettings, forNonHdrMixedComposition) {
3133     verify().ifMixedCompositionIs(true)
3134             .andIfUsesHdr(false)
3135             .andIfSkipColorTransform(false)
3136             .thenExpectDisplaySettingsUsed({kDefaultOutputDestinationClip, kDefaultOutputSourceClip,
3137                                             kDefaultMaxLuminance, kDefaultOutputDataspace, mat4(),
3138                                             Region::INVALID_REGION, kDefaultOutputOrientation})
3139             .execute()
3140             .expectAFenceWasReturned();
3141 }
3142 
TEST_F(OutputComposeSurfacesTest_UsesExpectedDisplaySettings,forHdrOnlyClientComposition)3143 TEST_F(OutputComposeSurfacesTest_UsesExpectedDisplaySettings, forHdrOnlyClientComposition) {
3144     verify().ifMixedCompositionIs(false)
3145             .andIfUsesHdr(true)
3146             .andIfSkipColorTransform(false)
3147             .thenExpectDisplaySettingsUsed({kDefaultOutputDestinationClip, kDefaultOutputSourceClip,
3148                                             kDefaultMaxLuminance, kDefaultOutputDataspace,
3149                                             kDefaultColorTransformMat, Region::INVALID_REGION,
3150                                             kDefaultOutputOrientation})
3151             .execute()
3152             .expectAFenceWasReturned();
3153 }
3154 
TEST_F(OutputComposeSurfacesTest_UsesExpectedDisplaySettings,forNonHdrOnlyClientComposition)3155 TEST_F(OutputComposeSurfacesTest_UsesExpectedDisplaySettings, forNonHdrOnlyClientComposition) {
3156     verify().ifMixedCompositionIs(false)
3157             .andIfUsesHdr(false)
3158             .andIfSkipColorTransform(false)
3159             .thenExpectDisplaySettingsUsed({kDefaultOutputDestinationClip, kDefaultOutputSourceClip,
3160                                             kDefaultMaxLuminance, kDefaultOutputDataspace,
3161                                             kDefaultColorTransformMat, Region::INVALID_REGION,
3162                                             kDefaultOutputOrientation})
3163             .execute()
3164             .expectAFenceWasReturned();
3165 }
3166 
TEST_F(OutputComposeSurfacesTest_UsesExpectedDisplaySettings,usesExpectedDisplaySettingsForHdrOnlyClientCompositionWithSkipClientTransform)3167 TEST_F(OutputComposeSurfacesTest_UsesExpectedDisplaySettings,
3168        usesExpectedDisplaySettingsForHdrOnlyClientCompositionWithSkipClientTransform) {
3169     verify().ifMixedCompositionIs(false)
3170             .andIfUsesHdr(true)
3171             .andIfSkipColorTransform(true)
3172             .thenExpectDisplaySettingsUsed({kDefaultOutputDestinationClip, kDefaultOutputSourceClip,
3173                                             kDefaultMaxLuminance, kDefaultOutputDataspace, mat4(),
3174                                             Region::INVALID_REGION, kDefaultOutputOrientation})
3175             .execute()
3176             .expectAFenceWasReturned();
3177 }
3178 
3179 struct OutputComposeSurfacesTest_HandlesProtectedContent : public OutputComposeSurfacesTest {
3180     struct Layer {
Layerandroid::compositionengine::__anon0cff14940111::OutputComposeSurfacesTest_HandlesProtectedContent::Layer3181         Layer() {
3182             EXPECT_CALL(mLayerFE, getCompositionState()).WillRepeatedly(Return(&mLayerFEState));
3183             EXPECT_CALL(mOutputLayer, getLayerFE()).WillRepeatedly(ReturnRef(mLayerFE));
3184         }
3185 
3186         StrictMock<mock::OutputLayer> mOutputLayer;
3187         StrictMock<mock::LayerFE> mLayerFE;
3188         LayerFECompositionState mLayerFEState;
3189     };
3190 
OutputComposeSurfacesTest_HandlesProtectedContentandroid::compositionengine::__anon0cff14940111::OutputComposeSurfacesTest_HandlesProtectedContent3191     OutputComposeSurfacesTest_HandlesProtectedContent() {
3192         mLayer1.mLayerFEState.hasProtectedContent = false;
3193         mLayer2.mLayerFEState.hasProtectedContent = false;
3194 
3195         EXPECT_CALL(mOutput, getOutputLayerCount()).WillRepeatedly(Return(2u));
3196         EXPECT_CALL(mOutput, getOutputLayerOrderedByZByIndex(0u))
3197                 .WillRepeatedly(Return(&mLayer1.mOutputLayer));
3198         EXPECT_CALL(mOutput, getOutputLayerOrderedByZByIndex(1u))
3199                 .WillRepeatedly(Return(&mLayer2.mOutputLayer));
3200 
3201         EXPECT_CALL(mOutput, getSkipColorTransform()).WillRepeatedly(Return(false));
3202 
3203         EXPECT_CALL(*mDisplayColorProfile, hasWideColorGamut()).WillRepeatedly(Return(true));
3204 
3205         EXPECT_CALL(mOutput, generateClientCompositionRequests(_, _, _))
3206                 .WillRepeatedly(Return(std::vector<LayerFE::LayerSettings>{}));
3207         EXPECT_CALL(mOutput, appendRegionFlashRequests(RegionEq(kDebugRegion), _))
3208                 .WillRepeatedly(Return());
3209         EXPECT_CALL(*mRenderSurface, dequeueBuffer(_)).WillRepeatedly(Return(mOutputBuffer));
3210         EXPECT_CALL(mRenderEngine, drawLayers(_, _, _, true, _, _))
3211                 .WillRepeatedly(Return(NO_ERROR));
3212     }
3213 
3214     Layer mLayer1;
3215     Layer mLayer2;
3216 };
3217 
TEST_F(OutputComposeSurfacesTest_HandlesProtectedContent,ifDisplayIsNotSecure)3218 TEST_F(OutputComposeSurfacesTest_HandlesProtectedContent, ifDisplayIsNotSecure) {
3219     mOutput.mState.isSecure = false;
3220     mLayer2.mLayerFEState.hasProtectedContent = true;
3221     EXPECT_CALL(mRenderEngine, supportsProtectedContent()).WillRepeatedly(Return(true));
3222 
3223     mOutput.composeSurfaces(kDebugRegion, kDefaultRefreshArgs);
3224 }
3225 
TEST_F(OutputComposeSurfacesTest_HandlesProtectedContent,ifRenderEngineDoesNotSupportIt)3226 TEST_F(OutputComposeSurfacesTest_HandlesProtectedContent, ifRenderEngineDoesNotSupportIt) {
3227     mOutput.mState.isSecure = true;
3228     mLayer2.mLayerFEState.hasProtectedContent = true;
3229     EXPECT_CALL(mRenderEngine, supportsProtectedContent()).WillRepeatedly(Return(false));
3230 
3231     mOutput.composeSurfaces(kDebugRegion, kDefaultRefreshArgs);
3232 }
3233 
TEST_F(OutputComposeSurfacesTest_HandlesProtectedContent,ifNoProtectedContentLayers)3234 TEST_F(OutputComposeSurfacesTest_HandlesProtectedContent, ifNoProtectedContentLayers) {
3235     mOutput.mState.isSecure = true;
3236     mLayer2.mLayerFEState.hasProtectedContent = false;
3237     EXPECT_CALL(mRenderEngine, supportsProtectedContent()).WillRepeatedly(Return(true));
3238     EXPECT_CALL(mRenderEngine, isProtected).WillOnce(Return(true)).WillOnce(Return(false));
3239     EXPECT_CALL(*mRenderSurface, isProtected).WillOnce(Return(true));
3240     EXPECT_CALL(mRenderEngine, useProtectedContext(false));
3241     EXPECT_CALL(*mRenderSurface, setProtected(false));
3242 
3243     mOutput.composeSurfaces(kDebugRegion, kDefaultRefreshArgs);
3244 }
3245 
TEST_F(OutputComposeSurfacesTest_HandlesProtectedContent,ifNotEnabled)3246 TEST_F(OutputComposeSurfacesTest_HandlesProtectedContent, ifNotEnabled) {
3247     mOutput.mState.isSecure = true;
3248     mLayer2.mLayerFEState.hasProtectedContent = true;
3249     EXPECT_CALL(mRenderEngine, supportsProtectedContent()).WillRepeatedly(Return(true));
3250 
3251     // For this test, we also check the call order of key functions.
3252     InSequence seq;
3253 
3254     EXPECT_CALL(mRenderEngine, isProtected).WillOnce(Return(false));
3255     EXPECT_CALL(mRenderEngine, useProtectedContext(true));
3256     EXPECT_CALL(*mRenderSurface, isProtected).WillOnce(Return(false));
3257     EXPECT_CALL(mRenderEngine, isProtected).WillOnce(Return(true));
3258     EXPECT_CALL(*mRenderSurface, setProtected(true));
3259     // Must happen after setting the protected content state.
3260     EXPECT_CALL(*mRenderSurface, dequeueBuffer(_)).WillRepeatedly(Return(mOutputBuffer));
3261     EXPECT_CALL(mRenderEngine, drawLayers(_, _, _, true, _, _)).WillOnce(Return(NO_ERROR));
3262 
3263     mOutput.composeSurfaces(kDebugRegion, kDefaultRefreshArgs);
3264 }
3265 
TEST_F(OutputComposeSurfacesTest_HandlesProtectedContent,ifAlreadyEnabledEverywhere)3266 TEST_F(OutputComposeSurfacesTest_HandlesProtectedContent, ifAlreadyEnabledEverywhere) {
3267     mOutput.mState.isSecure = true;
3268     mLayer2.mLayerFEState.hasProtectedContent = true;
3269     EXPECT_CALL(mRenderEngine, supportsProtectedContent()).WillRepeatedly(Return(true));
3270     EXPECT_CALL(mRenderEngine, isProtected).WillOnce(Return(true));
3271     EXPECT_CALL(*mRenderSurface, isProtected).WillOnce(Return(true));
3272 
3273     mOutput.composeSurfaces(kDebugRegion, kDefaultRefreshArgs);
3274 }
3275 
TEST_F(OutputComposeSurfacesTest_HandlesProtectedContent,ifFailsToEnableInRenderEngine)3276 TEST_F(OutputComposeSurfacesTest_HandlesProtectedContent, ifFailsToEnableInRenderEngine) {
3277     mOutput.mState.isSecure = true;
3278     mLayer2.mLayerFEState.hasProtectedContent = true;
3279     EXPECT_CALL(mRenderEngine, supportsProtectedContent()).WillRepeatedly(Return(true));
3280     EXPECT_CALL(mRenderEngine, isProtected).WillOnce(Return(false)).WillOnce(Return(false));
3281     EXPECT_CALL(*mRenderSurface, isProtected).WillOnce(Return(false));
3282     EXPECT_CALL(mRenderEngine, useProtectedContext(true));
3283 
3284     mOutput.composeSurfaces(kDebugRegion, kDefaultRefreshArgs);
3285 }
3286 
TEST_F(OutputComposeSurfacesTest_HandlesProtectedContent,ifAlreadyEnabledInRenderEngine)3287 TEST_F(OutputComposeSurfacesTest_HandlesProtectedContent, ifAlreadyEnabledInRenderEngine) {
3288     mOutput.mState.isSecure = true;
3289     mLayer2.mLayerFEState.hasProtectedContent = true;
3290     EXPECT_CALL(mRenderEngine, supportsProtectedContent()).WillRepeatedly(Return(true));
3291     EXPECT_CALL(mRenderEngine, isProtected).WillOnce(Return(true)).WillOnce(Return(true));
3292     EXPECT_CALL(*mRenderSurface, isProtected).WillOnce(Return(false));
3293     EXPECT_CALL(*mRenderSurface, setProtected(true));
3294 
3295     mOutput.composeSurfaces(kDebugRegion, kDefaultRefreshArgs);
3296 }
3297 
TEST_F(OutputComposeSurfacesTest_HandlesProtectedContent,ifAlreadyEnabledInRenderSurface)3298 TEST_F(OutputComposeSurfacesTest_HandlesProtectedContent, ifAlreadyEnabledInRenderSurface) {
3299     mOutput.mState.isSecure = true;
3300     mLayer2.mLayerFEState.hasProtectedContent = true;
3301     EXPECT_CALL(mRenderEngine, supportsProtectedContent()).WillRepeatedly(Return(true));
3302     EXPECT_CALL(mRenderEngine, isProtected).WillOnce(Return(false));
3303     EXPECT_CALL(*mRenderSurface, isProtected).WillOnce(Return(true));
3304     EXPECT_CALL(mRenderEngine, useProtectedContext(true));
3305 
3306     mOutput.composeSurfaces(kDebugRegion, kDefaultRefreshArgs);
3307 }
3308 
3309 struct OutputComposeSurfacesTest_SetsExpensiveRendering : public OutputComposeSurfacesTest {
OutputComposeSurfacesTest_SetsExpensiveRenderingandroid::compositionengine::__anon0cff14940111::OutputComposeSurfacesTest_SetsExpensiveRendering3310     OutputComposeSurfacesTest_SetsExpensiveRendering() {
3311         EXPECT_CALL(mOutput, getSkipColorTransform()).WillRepeatedly(Return(false));
3312         EXPECT_CALL(*mDisplayColorProfile, hasWideColorGamut()).WillRepeatedly(Return(true));
3313         EXPECT_CALL(mRenderEngine, supportsProtectedContent()).WillRepeatedly(Return(false));
3314         EXPECT_CALL(mOutput, appendRegionFlashRequests(RegionEq(kDebugRegion), _))
3315                 .WillRepeatedly(Return());
3316         EXPECT_CALL(*mRenderSurface, dequeueBuffer(_)).WillRepeatedly(Return(mOutputBuffer));
3317     }
3318 };
3319 
TEST_F(OutputComposeSurfacesTest_SetsExpensiveRendering,IfExepensiveOutputDataspaceIsUsed)3320 TEST_F(OutputComposeSurfacesTest_SetsExpensiveRendering, IfExepensiveOutputDataspaceIsUsed) {
3321     mOutput.mState.dataspace = kExpensiveOutputDataspace;
3322 
3323     EXPECT_CALL(mOutput, generateClientCompositionRequests(_, _, kExpensiveOutputDataspace))
3324             .WillOnce(Return(std::vector<LayerFE::LayerSettings>{}));
3325 
3326     // For this test, we also check the call order of key functions.
3327     InSequence seq;
3328 
3329     EXPECT_CALL(mOutput, setExpensiveRenderingExpected(true));
3330     EXPECT_CALL(mRenderEngine, drawLayers(_, _, _, true, _, _)).WillOnce(Return(NO_ERROR));
3331 
3332     mOutput.composeSurfaces(kDebugRegion, kDefaultRefreshArgs);
3333 }
3334 
3335 struct OutputComposeSurfacesTest_SetsExpensiveRendering_ForBlur
3336       : public OutputComposeSurfacesTest_SetsExpensiveRendering {
OutputComposeSurfacesTest_SetsExpensiveRendering_ForBlurandroid::compositionengine::__anon0cff14940111::OutputComposeSurfacesTest_SetsExpensiveRendering_ForBlur3337     OutputComposeSurfacesTest_SetsExpensiveRendering_ForBlur() {
3338         mLayer.layerFEState.backgroundBlurRadius = 10;
3339         mOutput.editState().isEnabled = true;
3340 
3341         EXPECT_CALL(mLayer.outputLayer, updateCompositionState(false, true, ui::Transform::ROT_0));
3342         EXPECT_CALL(mLayer.outputLayer, writeStateToHWC(false));
3343         EXPECT_CALL(mOutput, generateClientCompositionRequests(_, _, kDefaultOutputDataspace))
3344                 .WillOnce(Return(std::vector<LayerFE::LayerSettings>{}));
3345         EXPECT_CALL(mRenderEngine, drawLayers(_, _, _, true, _, _)).WillOnce(Return(NO_ERROR));
3346         EXPECT_CALL(mOutput, getOutputLayerCount()).WillRepeatedly(Return(1u));
3347         EXPECT_CALL(mOutput, getOutputLayerOrderedByZByIndex(0u))
3348                 .WillRepeatedly(Return(&mLayer.outputLayer));
3349     }
3350 
3351     NonInjectedLayer mLayer;
3352     compositionengine::CompositionRefreshArgs mRefreshArgs;
3353 };
3354 
TEST_F(OutputComposeSurfacesTest_SetsExpensiveRendering_ForBlur,IfBlursAreExpensive)3355 TEST_F(OutputComposeSurfacesTest_SetsExpensiveRendering_ForBlur, IfBlursAreExpensive) {
3356     mRefreshArgs.blursAreExpensive = true;
3357     mOutput.updateAndWriteCompositionState(mRefreshArgs);
3358 
3359     EXPECT_CALL(mOutput, setExpensiveRenderingExpected(true));
3360     mOutput.composeSurfaces(kDebugRegion, mRefreshArgs);
3361 }
3362 
TEST_F(OutputComposeSurfacesTest_SetsExpensiveRendering_ForBlur,IfBlursAreNotExpensive)3363 TEST_F(OutputComposeSurfacesTest_SetsExpensiveRendering_ForBlur, IfBlursAreNotExpensive) {
3364     mRefreshArgs.blursAreExpensive = false;
3365     mOutput.updateAndWriteCompositionState(mRefreshArgs);
3366 
3367     EXPECT_CALL(mOutput, setExpensiveRenderingExpected(true)).Times(0);
3368     mOutput.composeSurfaces(kDebugRegion, mRefreshArgs);
3369 }
3370 
3371 /*
3372  * Output::generateClientCompositionRequests()
3373  */
3374 
3375 struct GenerateClientCompositionRequestsTest : public testing::Test {
3376     struct OutputPartialMock : public OutputPartialMockBase {
3377         // compositionengine::Output overrides
generateClientCompositionRequestsandroid::compositionengine::__anon0cff14940111::GenerateClientCompositionRequestsTest::OutputPartialMock3378         std::vector<LayerFE::LayerSettings> generateClientCompositionRequests(
3379                 bool supportsProtectedContent, Region& clearRegion,
3380                 ui::Dataspace dataspace) override {
3381             return impl::Output::generateClientCompositionRequests(supportsProtectedContent,
3382                                                                    clearRegion, dataspace);
3383         }
3384     };
3385 
3386     struct Layer {
Layerandroid::compositionengine::__anon0cff14940111::GenerateClientCompositionRequestsTest::Layer3387         Layer() {
3388             EXPECT_CALL(mOutputLayer, getState()).WillRepeatedly(ReturnRef(mOutputLayerState));
3389             EXPECT_CALL(mOutputLayer, editState()).WillRepeatedly(ReturnRef(mOutputLayerState));
3390             EXPECT_CALL(mOutputLayer, getLayerFE()).WillRepeatedly(ReturnRef(mLayerFE));
3391             EXPECT_CALL(mLayerFE, getCompositionState()).WillRepeatedly(Return(&mLayerFEState));
3392         }
3393 
3394         StrictMock<mock::OutputLayer> mOutputLayer;
3395         StrictMock<mock::LayerFE> mLayerFE;
3396         LayerFECompositionState mLayerFEState;
3397         impl::OutputLayerCompositionState mOutputLayerState;
3398         LayerFE::LayerSettings mLayerSettings;
3399     };
3400 
GenerateClientCompositionRequestsTestandroid::compositionengine::__anon0cff14940111::GenerateClientCompositionRequestsTest3401     GenerateClientCompositionRequestsTest() {
3402         mOutput.mState.needsFiltering = false;
3403 
3404         mOutput.setDisplayColorProfileForTest(
3405                 std::unique_ptr<DisplayColorProfile>(mDisplayColorProfile));
3406         mOutput.setRenderSurfaceForTest(std::unique_ptr<RenderSurface>(mRenderSurface));
3407     }
3408 
3409     mock::DisplayColorProfile* mDisplayColorProfile = new StrictMock<mock::DisplayColorProfile>();
3410     mock::RenderSurface* mRenderSurface = new StrictMock<mock::RenderSurface>();
3411     StrictMock<OutputPartialMock> mOutput;
3412 };
3413 
3414 struct GenerateClientCompositionRequestsTest_ThreeLayers
3415       : public GenerateClientCompositionRequestsTest {
GenerateClientCompositionRequestsTest_ThreeLayersandroid::compositionengine::__anon0cff14940111::GenerateClientCompositionRequestsTest_ThreeLayers3416     GenerateClientCompositionRequestsTest_ThreeLayers() {
3417         mOutput.mState.frame = kDisplayFrame;
3418         mOutput.mState.viewport = kDisplayViewport;
3419         mOutput.mState.sourceClip = kDisplaySourceClip;
3420         mOutput.mState.destinationClip = kDisplayDestinationClip;
3421         mOutput.mState.transform = ui::Transform{kDisplayOrientation};
3422         mOutput.mState.orientation = kDisplayOrientation;
3423         mOutput.mState.needsFiltering = false;
3424         mOutput.mState.isSecure = false;
3425 
3426         for (size_t i = 0; i < mLayers.size(); i++) {
3427             mLayers[i].mOutputLayerState.clearClientTarget = false;
3428             mLayers[i].mOutputLayerState.visibleRegion = Region(kDisplayFrame);
3429             mLayers[i].mLayerFEState.isOpaque = true;
3430             mLayers[i].mLayerSettings.geometry.boundaries =
3431                     FloatRect{static_cast<float>(i + 1), 0.f, 0.f, 0.f};
3432             mLayers[i].mLayerSettings.source.solidColor = {1.0f, 1.0f, 1.0f};
3433             mLayers[i].mLayerSettings.alpha = 1.0f;
3434             mLayers[i].mLayerSettings.disableBlending = false;
3435 
3436             EXPECT_CALL(mOutput, getOutputLayerOrderedByZByIndex(i))
3437                     .WillRepeatedly(Return(&mLayers[i].mOutputLayer));
3438             EXPECT_CALL(mLayers[i].mOutputLayer, requiresClientComposition())
3439                     .WillRepeatedly(Return(true));
3440             EXPECT_CALL(mLayers[i].mOutputLayer, needsFiltering()).WillRepeatedly(Return(false));
3441         }
3442 
3443         EXPECT_CALL(mOutput, getOutputLayerCount()).WillRepeatedly(Return(mLayers.size()));
3444     }
3445 
3446     static constexpr uint32_t kDisplayOrientation = TR_IDENT;
3447     static constexpr ui::Dataspace kDisplayDataspace = ui::Dataspace::UNKNOWN;
3448 
3449     static const Rect kDisplayFrame;
3450     static const Rect kDisplayViewport;
3451     static const Rect kDisplaySourceClip;
3452     static const Rect kDisplayDestinationClip;
3453 
3454     std::array<Layer, 3> mLayers;
3455 };
3456 
3457 const Rect GenerateClientCompositionRequestsTest_ThreeLayers::kDisplayFrame(0, 0, 100, 200);
3458 const Rect GenerateClientCompositionRequestsTest_ThreeLayers::kDisplayViewport(0, 0, 101, 201);
3459 const Rect GenerateClientCompositionRequestsTest_ThreeLayers::kDisplaySourceClip(0, 0, 102, 202);
3460 const Rect GenerateClientCompositionRequestsTest_ThreeLayers::kDisplayDestinationClip(0, 0, 103,
3461                                                                                       203);
3462 
TEST_F(GenerateClientCompositionRequestsTest_ThreeLayers,handlesNoClientCompostionLayers)3463 TEST_F(GenerateClientCompositionRequestsTest_ThreeLayers, handlesNoClientCompostionLayers) {
3464     EXPECT_CALL(mLayers[0].mOutputLayer, requiresClientComposition()).WillOnce(Return(false));
3465     EXPECT_CALL(mLayers[1].mOutputLayer, requiresClientComposition()).WillOnce(Return(false));
3466     EXPECT_CALL(mLayers[2].mOutputLayer, requiresClientComposition()).WillOnce(Return(false));
3467 
3468     Region accumClearRegion(Rect(10, 11, 12, 13));
3469     auto requests = mOutput.generateClientCompositionRequests(false /* supportsProtectedContent */,
3470                                                               accumClearRegion, kDisplayDataspace);
3471     EXPECT_EQ(0u, requests.size());
3472     EXPECT_THAT(accumClearRegion, RegionEq(Region(Rect(10, 11, 12, 13))));
3473 }
3474 
TEST_F(GenerateClientCompositionRequestsTest_ThreeLayers,requiresVisibleRegionAfterViewportClip)3475 TEST_F(GenerateClientCompositionRequestsTest_ThreeLayers, requiresVisibleRegionAfterViewportClip) {
3476     mLayers[0].mOutputLayerState.visibleRegion = Region(Rect(10, 10, 10, 10));
3477     mLayers[1].mOutputLayerState.visibleRegion = Region(Rect(4000, 0, 4010, 10));
3478     mLayers[2].mOutputLayerState.visibleRegion = Region(Rect(-10, -10, 0, 0));
3479 
3480     Region accumClearRegion(Rect(10, 11, 12, 13));
3481     auto requests = mOutput.generateClientCompositionRequests(false /* supportsProtectedContent */,
3482                                                               accumClearRegion, kDisplayDataspace);
3483     EXPECT_EQ(0u, requests.size());
3484     EXPECT_THAT(accumClearRegion, RegionEq(Region(Rect(10, 11, 12, 13))));
3485 }
3486 
TEST_F(GenerateClientCompositionRequestsTest_ThreeLayers,gathersClientCompositionRequests)3487 TEST_F(GenerateClientCompositionRequestsTest_ThreeLayers, gathersClientCompositionRequests) {
3488     LayerFE::LayerSettings mShadowSettings;
3489     mShadowSettings.source.solidColor = {0.1f, 0.1f, 0.1f};
3490 
3491     EXPECT_CALL(mLayers[0].mLayerFE, prepareClientCompositionList(_))
3492             .WillOnce(Return(std::vector<LayerFE::LayerSettings>()));
3493     EXPECT_CALL(mLayers[1].mLayerFE, prepareClientCompositionList(_))
3494             .WillOnce(Return(std::vector<LayerFE::LayerSettings>({mLayers[1].mLayerSettings})));
3495     EXPECT_CALL(mLayers[2].mLayerFE, prepareClientCompositionList(_))
3496             .WillOnce(Return(std::vector<LayerFE::LayerSettings>(
3497                     {mShadowSettings, mLayers[2].mLayerSettings})));
3498 
3499     Region accumClearRegion(Rect(10, 11, 12, 13));
3500     auto requests = mOutput.generateClientCompositionRequests(false /* supportsProtectedContent */,
3501                                                               accumClearRegion, kDisplayDataspace);
3502     ASSERT_EQ(3u, requests.size());
3503     EXPECT_EQ(mLayers[1].mLayerSettings, requests[0]);
3504     EXPECT_EQ(mShadowSettings, requests[1]);
3505     EXPECT_EQ(mLayers[2].mLayerSettings, requests[2]);
3506 
3507     EXPECT_THAT(accumClearRegion, RegionEq(Region(Rect(10, 11, 12, 13))));
3508 
3509     // Check that a timestamp was set for the layers that generated requests
3510     EXPECT_TRUE(0 == mLayers[0].mOutputLayerState.clientCompositionTimestamp);
3511     EXPECT_TRUE(0 != mLayers[1].mOutputLayerState.clientCompositionTimestamp);
3512     EXPECT_TRUE(0 != mLayers[2].mOutputLayerState.clientCompositionTimestamp);
3513 }
3514 
TEST_F(GenerateClientCompositionRequestsTest_ThreeLayers,onlyClientComposesClientComposedLayersIfNoClearingNeeded)3515 TEST_F(GenerateClientCompositionRequestsTest_ThreeLayers,
3516        onlyClientComposesClientComposedLayersIfNoClearingNeeded) {
3517     EXPECT_CALL(mLayers[0].mOutputLayer, requiresClientComposition()).WillOnce(Return(false));
3518     EXPECT_CALL(mLayers[1].mOutputLayer, requiresClientComposition()).WillOnce(Return(false));
3519     EXPECT_CALL(mLayers[2].mOutputLayer, requiresClientComposition()).WillOnce(Return(true));
3520 
3521     mLayers[0].mOutputLayerState.clearClientTarget = false;
3522     mLayers[1].mOutputLayerState.clearClientTarget = false;
3523     mLayers[2].mOutputLayerState.clearClientTarget = false;
3524 
3525     mLayers[0].mLayerFEState.isOpaque = true;
3526     mLayers[1].mLayerFEState.isOpaque = true;
3527     mLayers[2].mLayerFEState.isOpaque = true;
3528 
3529     EXPECT_CALL(mLayers[2].mLayerFE, prepareClientCompositionList(_))
3530             .WillOnce(Return(std::vector<LayerFE::LayerSettings>({mLayers[2].mLayerSettings})));
3531 
3532     Region accumClearRegion(Rect(10, 11, 12, 13));
3533     auto requests = mOutput.generateClientCompositionRequests(false /* supportsProtectedContent */,
3534                                                               accumClearRegion, kDisplayDataspace);
3535     ASSERT_EQ(1u, requests.size());
3536     EXPECT_EQ(mLayers[2].mLayerSettings, requests[0]);
3537 
3538     EXPECT_THAT(accumClearRegion, RegionEq(Region(Rect(10, 11, 12, 13))));
3539 }
3540 
TEST_F(GenerateClientCompositionRequestsTest_ThreeLayers,onlyClientComposesClientComposedLayersIfOthersAreNotOpaque)3541 TEST_F(GenerateClientCompositionRequestsTest_ThreeLayers,
3542        onlyClientComposesClientComposedLayersIfOthersAreNotOpaque) {
3543     EXPECT_CALL(mLayers[0].mOutputLayer, requiresClientComposition()).WillOnce(Return(false));
3544     EXPECT_CALL(mLayers[1].mOutputLayer, requiresClientComposition()).WillOnce(Return(false));
3545     EXPECT_CALL(mLayers[2].mOutputLayer, requiresClientComposition()).WillOnce(Return(true));
3546 
3547     mLayers[0].mOutputLayerState.clearClientTarget = true;
3548     mLayers[1].mOutputLayerState.clearClientTarget = true;
3549     mLayers[2].mOutputLayerState.clearClientTarget = true;
3550 
3551     mLayers[0].mLayerFEState.isOpaque = false;
3552     mLayers[1].mLayerFEState.isOpaque = false;
3553     mLayers[2].mLayerFEState.isOpaque = false;
3554 
3555     EXPECT_CALL(mLayers[2].mLayerFE, prepareClientCompositionList(_))
3556             .WillOnce(Return(std::vector<LayerFE::LayerSettings>({mLayers[2].mLayerSettings})));
3557 
3558     Region accumClearRegion(Rect(10, 11, 12, 13));
3559     auto requests = mOutput.generateClientCompositionRequests(false /* supportsProtectedContent */,
3560                                                               accumClearRegion, kDisplayDataspace);
3561     ASSERT_EQ(1u, requests.size());
3562     EXPECT_EQ(mLayers[2].mLayerSettings, requests[0]);
3563 
3564     EXPECT_THAT(accumClearRegion, RegionEq(Region(Rect(10, 11, 12, 13))));
3565 }
3566 
TEST_F(GenerateClientCompositionRequestsTest_ThreeLayers,clearsHWCLayersIfOpaqueAndNotFirst)3567 TEST_F(GenerateClientCompositionRequestsTest_ThreeLayers, clearsHWCLayersIfOpaqueAndNotFirst) {
3568     // If client composition is performed with some layers set to use device
3569     // composition, device layers after the first layer (device or client) will
3570     // clear the frame buffer if they are opaque and if that layer has a flag
3571     // set to do so. The first layer is skipped as the frame buffer is already
3572     // expected to be clear.
3573 
3574     EXPECT_CALL(mLayers[0].mOutputLayer, requiresClientComposition()).WillOnce(Return(false));
3575     EXPECT_CALL(mLayers[1].mOutputLayer, requiresClientComposition()).WillOnce(Return(false));
3576     EXPECT_CALL(mLayers[2].mOutputLayer, requiresClientComposition()).WillOnce(Return(true));
3577 
3578     mLayers[0].mOutputLayerState.clearClientTarget = true;
3579     mLayers[1].mOutputLayerState.clearClientTarget = true;
3580     mLayers[2].mOutputLayerState.clearClientTarget = true;
3581 
3582     mLayers[0].mLayerFEState.isOpaque = true;
3583     mLayers[1].mLayerFEState.isOpaque = true;
3584     mLayers[2].mLayerFEState.isOpaque = true;
3585     Region accumClearRegion(Rect(10, 11, 12, 13));
3586     Region dummyRegion;
3587 
3588     compositionengine::LayerFE::ClientCompositionTargetSettings layer1TargetSettings{
3589             Region(kDisplayFrame),
3590             false,       /* identity transform */
3591             false,       /* needs filtering */
3592             false,       /* secure */
3593             false,       /* supports protected content */
3594             dummyRegion, /* clear region */
3595             kDisplayViewport,
3596             kDisplayDataspace,
3597             false /* realContentIsVisible */,
3598             true /* clearContent */,
3599     };
3600     compositionengine::LayerFE::ClientCompositionTargetSettings layer2TargetSettings{
3601             Region(kDisplayFrame),
3602             false, /* identity transform */
3603             false, /* needs filtering */
3604             false, /* secure */
3605             false, /* supports protected content */
3606             accumClearRegion,
3607             kDisplayViewport,
3608             kDisplayDataspace,
3609             true /* realContentIsVisible */,
3610             false /* clearContent */,
3611     };
3612 
3613     LayerFE::LayerSettings mBlackoutSettings = mLayers[1].mLayerSettings;
3614     mBlackoutSettings.source.buffer.buffer = nullptr;
3615     mBlackoutSettings.source.solidColor = {0.1f, 0.1f, 0.1f};
3616     mBlackoutSettings.alpha = 0.f;
3617     mBlackoutSettings.disableBlending = true;
3618 
3619     EXPECT_CALL(mLayers[1].mLayerFE, prepareClientCompositionList(Eq(ByRef(layer1TargetSettings))))
3620             .WillOnce(Return(std::vector<LayerFE::LayerSettings>({mBlackoutSettings})));
3621     EXPECT_CALL(mLayers[2].mLayerFE, prepareClientCompositionList(Eq(ByRef(layer2TargetSettings))))
3622             .WillOnce(Return(std::vector<LayerFE::LayerSettings>({mLayers[2].mLayerSettings})));
3623 
3624     auto requests = mOutput.generateClientCompositionRequests(false /* supportsProtectedContent */,
3625                                                               accumClearRegion, kDisplayDataspace);
3626     ASSERT_EQ(2u, requests.size());
3627 
3628     // The second layer is expected to be rendered as alpha=0 black with no blending
3629     EXPECT_EQ(mBlackoutSettings, requests[0]);
3630 
3631     EXPECT_EQ(mLayers[2].mLayerSettings, requests[1]);
3632 
3633     EXPECT_THAT(accumClearRegion, RegionEq(Region(Rect(10, 11, 12, 13))));
3634 }
3635 
TEST_F(GenerateClientCompositionRequestsTest_ThreeLayers,clippedVisibleRegionUsedToGenerateRequest)3636 TEST_F(GenerateClientCompositionRequestsTest_ThreeLayers,
3637        clippedVisibleRegionUsedToGenerateRequest) {
3638     mLayers[0].mOutputLayerState.visibleRegion = Region(Rect(10, 10, 20, 20));
3639     mLayers[1].mOutputLayerState.visibleRegion = Region(Rect(-10, -10, 30, 30));
3640     mLayers[2].mOutputLayerState.visibleRegion = Region(Rect(-10, 0, 40, 4000));
3641 
3642     Region accumClearRegion(Rect(10, 11, 12, 13));
3643 
3644     compositionengine::LayerFE::ClientCompositionTargetSettings layer0TargetSettings{
3645             Region(Rect(10, 10, 20, 20)),
3646             false, /* identity transform */
3647             false, /* needs filtering */
3648             false, /* secure */
3649             false, /* supports protected content */
3650             accumClearRegion,
3651             kDisplayViewport,
3652             kDisplayDataspace,
3653             true /* realContentIsVisible */,
3654             false /* clearContent */,
3655     };
3656     compositionengine::LayerFE::ClientCompositionTargetSettings layer1TargetSettings{
3657             Region(Rect(0, 0, 30, 30)),
3658             false, /* identity transform */
3659             false, /* needs filtering */
3660             false, /* secure */
3661             false, /* supports protected content */
3662             accumClearRegion,
3663             kDisplayViewport,
3664             kDisplayDataspace,
3665             true /* realContentIsVisible */,
3666             false /* clearContent */,
3667     };
3668     compositionengine::LayerFE::ClientCompositionTargetSettings layer2TargetSettings{
3669             Region(Rect(0, 0, 40, 201)),
3670             false, /* identity transform */
3671             false, /* needs filtering */
3672             false, /* secure */
3673             false, /* supports protected content */
3674             accumClearRegion,
3675             kDisplayViewport,
3676             kDisplayDataspace,
3677             true /* realContentIsVisible */,
3678             false /* clearContent */,
3679     };
3680 
3681     EXPECT_CALL(mLayers[0].mLayerFE, prepareClientCompositionList(Eq(ByRef(layer0TargetSettings))))
3682             .WillOnce(Return(std::vector<LayerFE::LayerSettings>()));
3683     EXPECT_CALL(mLayers[1].mLayerFE, prepareClientCompositionList(Eq(ByRef(layer1TargetSettings))))
3684             .WillOnce(Return(std::vector<LayerFE::LayerSettings>()));
3685     EXPECT_CALL(mLayers[2].mLayerFE, prepareClientCompositionList(Eq(ByRef(layer2TargetSettings))))
3686             .WillOnce(Return(std::vector<LayerFE::LayerSettings>()));
3687 
3688     static_cast<void>(
3689             mOutput.generateClientCompositionRequests(false /* supportsProtectedContent */,
3690                                                       accumClearRegion, kDisplayDataspace));
3691 }
3692 
TEST_F(GenerateClientCompositionRequestsTest_ThreeLayers,perLayerNeedsFilteringUsedToGenerateRequests)3693 TEST_F(GenerateClientCompositionRequestsTest_ThreeLayers,
3694        perLayerNeedsFilteringUsedToGenerateRequests) {
3695     mOutput.mState.needsFiltering = false;
3696     EXPECT_CALL(mLayers[0].mOutputLayer, needsFiltering()).WillRepeatedly(Return(true));
3697 
3698     Region accumClearRegion(Rect(10, 11, 12, 13));
3699 
3700     compositionengine::LayerFE::ClientCompositionTargetSettings layer0TargetSettings{
3701             Region(kDisplayFrame),
3702             false, /* identity transform */
3703             true,  /* needs filtering */
3704             false, /* secure */
3705             false, /* supports protected content */
3706             accumClearRegion,
3707             kDisplayViewport,
3708             kDisplayDataspace,
3709             true /* realContentIsVisible */,
3710             false /* clearContent */,
3711     };
3712     compositionengine::LayerFE::ClientCompositionTargetSettings layer1TargetSettings{
3713             Region(kDisplayFrame),
3714             false, /* identity transform */
3715             false, /* needs filtering */
3716             false, /* secure */
3717             false, /* supports protected content */
3718             accumClearRegion,
3719             kDisplayViewport,
3720             kDisplayDataspace,
3721             true /* realContentIsVisible */,
3722             false /* clearContent */,
3723     };
3724     compositionengine::LayerFE::ClientCompositionTargetSettings layer2TargetSettings{
3725             Region(kDisplayFrame),
3726             false, /* identity transform */
3727             false, /* needs filtering */
3728             false, /* secure */
3729             false, /* supports protected content */
3730             accumClearRegion,
3731             kDisplayViewport,
3732             kDisplayDataspace,
3733             true /* realContentIsVisible */,
3734             false /* clearContent */,
3735     };
3736 
3737     EXPECT_CALL(mLayers[0].mLayerFE, prepareClientCompositionList(Eq(ByRef(layer0TargetSettings))))
3738             .WillOnce(Return(std::vector<LayerFE::LayerSettings>()));
3739     EXPECT_CALL(mLayers[1].mLayerFE, prepareClientCompositionList(Eq(ByRef(layer1TargetSettings))))
3740             .WillOnce(Return(std::vector<LayerFE::LayerSettings>()));
3741     EXPECT_CALL(mLayers[2].mLayerFE, prepareClientCompositionList(Eq(ByRef(layer2TargetSettings))))
3742             .WillOnce(Return(std::vector<LayerFE::LayerSettings>()));
3743 
3744     static_cast<void>(
3745             mOutput.generateClientCompositionRequests(false /* supportsProtectedContent */,
3746                                                       accumClearRegion, kDisplayDataspace));
3747 }
3748 
TEST_F(GenerateClientCompositionRequestsTest_ThreeLayers,wholeOutputNeedsFilteringUsedToGenerateRequests)3749 TEST_F(GenerateClientCompositionRequestsTest_ThreeLayers,
3750        wholeOutputNeedsFilteringUsedToGenerateRequests) {
3751     mOutput.mState.needsFiltering = true;
3752     EXPECT_CALL(mLayers[0].mOutputLayer, needsFiltering()).WillRepeatedly(Return(true));
3753 
3754     Region accumClearRegion(Rect(10, 11, 12, 13));
3755 
3756     compositionengine::LayerFE::ClientCompositionTargetSettings layer0TargetSettings{
3757             Region(kDisplayFrame),
3758             false, /* identity transform */
3759             true,  /* needs filtering */
3760             false, /* secure */
3761             false, /* supports protected content */
3762             accumClearRegion,
3763             kDisplayViewport,
3764             kDisplayDataspace,
3765             true /* realContentIsVisible */,
3766             false /* clearContent */,
3767 
3768     };
3769     compositionengine::LayerFE::ClientCompositionTargetSettings layer1TargetSettings{
3770             Region(kDisplayFrame),
3771             false, /* identity transform */
3772             true,  /* needs filtering */
3773             false, /* secure */
3774             false, /* supports protected content */
3775             accumClearRegion,
3776             kDisplayViewport,
3777             kDisplayDataspace,
3778             true /* realContentIsVisible */,
3779             false /* clearContent */,
3780     };
3781     compositionengine::LayerFE::ClientCompositionTargetSettings layer2TargetSettings{
3782             Region(kDisplayFrame),
3783             false, /* identity transform */
3784             true,  /* needs filtering */
3785             false, /* secure */
3786             false, /* supports protected content */
3787             accumClearRegion,
3788             kDisplayViewport,
3789             kDisplayDataspace,
3790             true /* realContentIsVisible */,
3791             false /* clearContent */,
3792     };
3793 
3794     EXPECT_CALL(mLayers[0].mLayerFE, prepareClientCompositionList(Eq(ByRef(layer0TargetSettings))))
3795             .WillOnce(Return(std::vector<LayerFE::LayerSettings>()));
3796     EXPECT_CALL(mLayers[1].mLayerFE, prepareClientCompositionList(Eq(ByRef(layer1TargetSettings))))
3797             .WillOnce(Return(std::vector<LayerFE::LayerSettings>()));
3798     EXPECT_CALL(mLayers[2].mLayerFE, prepareClientCompositionList(Eq(ByRef(layer2TargetSettings))))
3799             .WillOnce(Return(std::vector<LayerFE::LayerSettings>()));
3800 
3801     static_cast<void>(
3802             mOutput.generateClientCompositionRequests(false /* supportsProtectedContent */,
3803                                                       accumClearRegion, kDisplayDataspace));
3804 }
3805 
TEST_F(GenerateClientCompositionRequestsTest_ThreeLayers,wholeOutputSecurityUsedToGenerateRequests)3806 TEST_F(GenerateClientCompositionRequestsTest_ThreeLayers,
3807        wholeOutputSecurityUsedToGenerateRequests) {
3808     mOutput.mState.isSecure = true;
3809 
3810     Region accumClearRegion(Rect(10, 11, 12, 13));
3811 
3812     compositionengine::LayerFE::ClientCompositionTargetSettings layer0TargetSettings{
3813             Region(kDisplayFrame),
3814             false, /* identity transform */
3815             false, /* needs filtering */
3816             true,  /* secure */
3817             false, /* supports protected content */
3818             accumClearRegion,
3819             kDisplayViewport,
3820             kDisplayDataspace,
3821             true /* realContentIsVisible */,
3822             false /* clearContent */,
3823     };
3824     compositionengine::LayerFE::ClientCompositionTargetSettings layer1TargetSettings{
3825             Region(kDisplayFrame),
3826             false, /* identity transform */
3827             false, /* needs filtering */
3828             true,  /* secure */
3829             false, /* supports protected content */
3830             accumClearRegion,
3831             kDisplayViewport,
3832             kDisplayDataspace,
3833             true /* realContentIsVisible */,
3834             false /* clearContent */,
3835     };
3836     compositionengine::LayerFE::ClientCompositionTargetSettings layer2TargetSettings{
3837             Region(kDisplayFrame),
3838             false, /* identity transform */
3839             false, /* needs filtering */
3840             true,  /* secure */
3841             false, /* supports protected content */
3842             accumClearRegion,
3843             kDisplayViewport,
3844             kDisplayDataspace,
3845             true /* realContentIsVisible */,
3846             false /* clearContent */,
3847     };
3848 
3849     EXPECT_CALL(mLayers[0].mLayerFE, prepareClientCompositionList(Eq(ByRef(layer0TargetSettings))))
3850             .WillOnce(Return(std::vector<LayerFE::LayerSettings>()));
3851     EXPECT_CALL(mLayers[1].mLayerFE, prepareClientCompositionList(Eq(ByRef(layer1TargetSettings))))
3852             .WillOnce(Return(std::vector<LayerFE::LayerSettings>()));
3853     EXPECT_CALL(mLayers[2].mLayerFE, prepareClientCompositionList(Eq(ByRef(layer2TargetSettings))))
3854             .WillOnce(Return(std::vector<LayerFE::LayerSettings>()));
3855 
3856     static_cast<void>(
3857             mOutput.generateClientCompositionRequests(false /* supportsProtectedContent */,
3858                                                       accumClearRegion, kDisplayDataspace));
3859 }
3860 
TEST_F(GenerateClientCompositionRequestsTest_ThreeLayers,protectedContentSupportUsedToGenerateRequests)3861 TEST_F(GenerateClientCompositionRequestsTest_ThreeLayers,
3862        protectedContentSupportUsedToGenerateRequests) {
3863     Region accumClearRegion(Rect(10, 11, 12, 13));
3864 
3865     compositionengine::LayerFE::ClientCompositionTargetSettings layer0TargetSettings{
3866             Region(kDisplayFrame),
3867             false, /* identity transform */
3868             false, /* needs filtering */
3869             false, /* secure */
3870             true,  /* supports protected content */
3871             accumClearRegion,
3872             kDisplayViewport,
3873             kDisplayDataspace,
3874             true /* realContentIsVisible */,
3875             false /* clearContent */,
3876     };
3877     compositionengine::LayerFE::ClientCompositionTargetSettings layer1TargetSettings{
3878             Region(kDisplayFrame),
3879             false, /* identity transform */
3880             false, /* needs filtering */
3881             false, /* secure */
3882             true,  /* supports protected content */
3883             accumClearRegion,
3884             kDisplayViewport,
3885             kDisplayDataspace,
3886             true /* realContentIsVisible */,
3887             false /* clearContent */,
3888     };
3889     compositionengine::LayerFE::ClientCompositionTargetSettings layer2TargetSettings{
3890             Region(kDisplayFrame),
3891             false, /* identity transform */
3892             false, /* needs filtering */
3893             false, /* secure */
3894             true,  /* supports protected content */
3895             accumClearRegion,
3896             kDisplayViewport,
3897             kDisplayDataspace,
3898             true /* realContentIsVisible */,
3899             false /* clearContent */,
3900     };
3901 
3902     EXPECT_CALL(mLayers[0].mLayerFE, prepareClientCompositionList(Eq(ByRef(layer0TargetSettings))))
3903             .WillOnce(Return(std::vector<LayerFE::LayerSettings>()));
3904     EXPECT_CALL(mLayers[1].mLayerFE, prepareClientCompositionList(Eq(ByRef(layer1TargetSettings))))
3905             .WillOnce(Return(std::vector<LayerFE::LayerSettings>()));
3906     EXPECT_CALL(mLayers[2].mLayerFE, prepareClientCompositionList(Eq(ByRef(layer2TargetSettings))))
3907             .WillOnce(Return(std::vector<LayerFE::LayerSettings>()));
3908 
3909     static_cast<void>(mOutput.generateClientCompositionRequests(true /* supportsProtectedContent */,
3910                                                                 accumClearRegion,
3911                                                                 kDisplayDataspace));
3912 }
3913 
TEST_F(OutputUpdateAndWriteCompositionStateTest,handlesBackgroundBlurRequests)3914 TEST_F(OutputUpdateAndWriteCompositionStateTest, handlesBackgroundBlurRequests) {
3915     InjectedLayer layer1;
3916     InjectedLayer layer2;
3917     InjectedLayer layer3;
3918 
3919     // Layer requesting blur, or below, should request client composition.
3920     EXPECT_CALL(*layer1.outputLayer, updateCompositionState(false, true, ui::Transform::ROT_0));
3921     EXPECT_CALL(*layer1.outputLayer, writeStateToHWC(false));
3922     EXPECT_CALL(*layer2.outputLayer, updateCompositionState(false, true, ui::Transform::ROT_0));
3923     EXPECT_CALL(*layer2.outputLayer, writeStateToHWC(false));
3924     EXPECT_CALL(*layer3.outputLayer, updateCompositionState(false, false, ui::Transform::ROT_0));
3925     EXPECT_CALL(*layer3.outputLayer, writeStateToHWC(false));
3926 
3927     layer2.layerFEState.backgroundBlurRadius = 10;
3928 
3929     injectOutputLayer(layer1);
3930     injectOutputLayer(layer2);
3931     injectOutputLayer(layer3);
3932 
3933     mOutput->editState().isEnabled = true;
3934 
3935     CompositionRefreshArgs args;
3936     args.updatingGeometryThisFrame = false;
3937     args.devOptForceClientComposition = false;
3938     mOutput->updateAndWriteCompositionState(args);
3939 }
3940 
TEST_F(GenerateClientCompositionRequestsTest,handlesLandscapeModeSplitScreenRequests)3941 TEST_F(GenerateClientCompositionRequestsTest, handlesLandscapeModeSplitScreenRequests) {
3942     // In split-screen landscape mode, the screen is rotated 90 degrees, with
3943     // one layer on the left covering the left side of the output, and one layer
3944     // on the right covering that side of the output.
3945 
3946     const Rect kPortraitFrame(0, 0, 1000, 2000);
3947     const Rect kPortraitViewport(0, 0, 2000, 1000);
3948     const Rect kPortraitSourceClip(0, 0, 1000, 2000);
3949     const Rect kPortraitDestinationClip(0, 0, 1000, 2000);
3950     const uint32_t kPortraitOrientation = TR_ROT_90;
3951     constexpr ui::Dataspace kOutputDataspace = ui::Dataspace::DISPLAY_P3;
3952 
3953     mOutput.mState.frame = kPortraitFrame;
3954     mOutput.mState.viewport = kPortraitViewport;
3955     mOutput.mState.sourceClip = kPortraitSourceClip;
3956     mOutput.mState.destinationClip = kPortraitDestinationClip;
3957     mOutput.mState.transform = ui::Transform{kPortraitOrientation};
3958     mOutput.mState.orientation = kPortraitOrientation;
3959     mOutput.mState.needsFiltering = false;
3960     mOutput.mState.isSecure = true;
3961 
3962     Layer leftLayer;
3963     Layer rightLayer;
3964 
3965     leftLayer.mOutputLayerState.clearClientTarget = false;
3966     leftLayer.mOutputLayerState.visibleRegion = Region(Rect(0, 0, 1000, 1000));
3967     leftLayer.mLayerFEState.isOpaque = true;
3968     leftLayer.mLayerSettings.source.solidColor = {1.f, 0.f, 0.f};
3969 
3970     rightLayer.mOutputLayerState.clearClientTarget = false;
3971     rightLayer.mOutputLayerState.visibleRegion = Region(Rect(1000, 0, 2000, 1000));
3972     rightLayer.mLayerFEState.isOpaque = true;
3973     rightLayer.mLayerSettings.source.solidColor = {0.f, 1.f, 0.f};
3974 
3975     EXPECT_CALL(mOutput, getOutputLayerCount()).WillRepeatedly(Return(2u));
3976     EXPECT_CALL(mOutput, getOutputLayerOrderedByZByIndex(0u))
3977             .WillRepeatedly(Return(&leftLayer.mOutputLayer));
3978     EXPECT_CALL(mOutput, getOutputLayerOrderedByZByIndex(1u))
3979             .WillRepeatedly(Return(&rightLayer.mOutputLayer));
3980 
3981     Region accumClearRegion(Rect(10, 11, 12, 13));
3982 
3983     compositionengine::LayerFE::ClientCompositionTargetSettings leftLayerSettings{
3984             Region(Rect(0, 0, 1000, 1000)),
3985             false, /* identity transform */
3986             false, /* needs filtering */
3987             true,  /* secure */
3988             true,  /* supports protected content */
3989             accumClearRegion,
3990             kPortraitViewport,
3991             kOutputDataspace,
3992             true /* realContentIsVisible */,
3993             false /* clearContent */,
3994     };
3995 
3996     EXPECT_CALL(leftLayer.mOutputLayer, requiresClientComposition()).WillRepeatedly(Return(true));
3997     EXPECT_CALL(leftLayer.mOutputLayer, needsFiltering()).WillRepeatedly(Return(false));
3998     EXPECT_CALL(leftLayer.mLayerFE, prepareClientCompositionList(Eq(ByRef(leftLayerSettings))))
3999             .WillOnce(Return(std::vector<LayerFE::LayerSettings>({leftLayer.mLayerSettings})));
4000 
4001     compositionengine::LayerFE::ClientCompositionTargetSettings rightLayerSettings{
4002             Region(Rect(1000, 0, 2000, 1000)),
4003             false, /* identity transform */
4004             false, /* needs filtering */
4005             true,  /* secure */
4006             true,  /* supports protected content */
4007             accumClearRegion,
4008             kPortraitViewport,
4009             kOutputDataspace,
4010             true /* realContentIsVisible */,
4011             false /* clearContent */,
4012     };
4013 
4014     EXPECT_CALL(rightLayer.mOutputLayer, requiresClientComposition()).WillRepeatedly(Return(true));
4015     EXPECT_CALL(rightLayer.mOutputLayer, needsFiltering()).WillRepeatedly(Return(false));
4016     EXPECT_CALL(rightLayer.mLayerFE, prepareClientCompositionList(Eq(ByRef(rightLayerSettings))))
4017             .WillOnce(Return(std::vector<LayerFE::LayerSettings>({rightLayer.mLayerSettings})));
4018 
4019     constexpr bool supportsProtectedContent = true;
4020     auto requests = mOutput.generateClientCompositionRequests(supportsProtectedContent,
4021                                                               accumClearRegion, kOutputDataspace);
4022     ASSERT_EQ(2u, requests.size());
4023     EXPECT_EQ(leftLayer.mLayerSettings, requests[0]);
4024     EXPECT_EQ(rightLayer.mLayerSettings, requests[1]);
4025 }
4026 
TEST_F(GenerateClientCompositionRequestsTest_ThreeLayers,shadowRegionOnlyVisibleSkipsContentComposition)4027 TEST_F(GenerateClientCompositionRequestsTest_ThreeLayers,
4028        shadowRegionOnlyVisibleSkipsContentComposition) {
4029     const Rect kContentWithShadow(40, 40, 70, 90);
4030     const Rect kContent(50, 50, 60, 80);
4031     const Region kShadowRegion = Region(kContentWithShadow).subtract(kContent);
4032     const Region kPartialShadowRegion = Region(kContentWithShadow).subtract(Rect(40, 40, 60, 80));
4033 
4034     Region accumClearRegion(Rect(10, 11, 12, 13));
4035     compositionengine::LayerFE::ClientCompositionTargetSettings layer2Settings{
4036             Region(Rect(60, 40, 70, 80)).merge(Rect(40, 80, 70, 90)), /* visible region */
4037             false,                                                    /* identity transform */
4038             false,                                                    /* needs filtering */
4039             false,                                                    /* secure */
4040             false, /* supports protected content */
4041             accumClearRegion,
4042             kDisplayViewport,
4043             kDisplayDataspace,
4044             false /* realContentIsVisible */,
4045             false /* clearContent */,
4046     };
4047 
4048     LayerFE::LayerSettings mShadowSettings;
4049     mShadowSettings.source.solidColor = {0.1f, 0.1f, 0.1f};
4050 
4051     mLayers[2].mOutputLayerState.visibleRegion = kPartialShadowRegion;
4052     mLayers[2].mOutputLayerState.shadowRegion = kShadowRegion;
4053 
4054     EXPECT_CALL(mLayers[0].mOutputLayer, requiresClientComposition()).WillOnce(Return(false));
4055     EXPECT_CALL(mLayers[1].mOutputLayer, requiresClientComposition()).WillOnce(Return(false));
4056     EXPECT_CALL(mLayers[2].mLayerFE, prepareClientCompositionList(Eq(ByRef(layer2Settings))))
4057             .WillOnce(Return(std::vector<LayerFE::LayerSettings>({mShadowSettings})));
4058 
4059     auto requests = mOutput.generateClientCompositionRequests(false /* supportsProtectedContent */,
4060                                                               accumClearRegion, kDisplayDataspace);
4061     ASSERT_EQ(1u, requests.size());
4062 
4063     EXPECT_EQ(mShadowSettings, requests[0]);
4064 }
4065 
TEST_F(GenerateClientCompositionRequestsTest_ThreeLayers,shadowRegionWithContentVisibleRequestsContentAndShadowComposition)4066 TEST_F(GenerateClientCompositionRequestsTest_ThreeLayers,
4067        shadowRegionWithContentVisibleRequestsContentAndShadowComposition) {
4068     const Rect kContentWithShadow(40, 40, 70, 90);
4069     const Rect kContent(50, 50, 60, 80);
4070     const Region kShadowRegion = Region(kContentWithShadow).subtract(kContent);
4071     const Region kPartialContentWithPartialShadowRegion =
4072             Region(kContentWithShadow).subtract(Rect(40, 40, 50, 80));
4073 
4074     LayerFE::LayerSettings mShadowSettings;
4075     mShadowSettings.source.solidColor = {0.1f, 0.1f, 0.1f};
4076 
4077     mLayers[2].mOutputLayerState.visibleRegion = kPartialContentWithPartialShadowRegion;
4078     mLayers[2].mOutputLayerState.shadowRegion = kShadowRegion;
4079 
4080     Region accumClearRegion(Rect(10, 11, 12, 13));
4081     compositionengine::LayerFE::ClientCompositionTargetSettings layer2Settings{
4082             Region(Rect(50, 40, 70, 80)).merge(Rect(40, 80, 70, 90)), /* visible region */
4083             false,                                                    /* identity transform */
4084             false,                                                    /* needs filtering */
4085             false,                                                    /* secure */
4086             false, /* supports protected content */
4087             accumClearRegion,
4088             kDisplayViewport,
4089             kDisplayDataspace,
4090             true /* realContentIsVisible */,
4091             false /* clearContent */,
4092     };
4093 
4094     EXPECT_CALL(mLayers[0].mOutputLayer, requiresClientComposition()).WillOnce(Return(false));
4095     EXPECT_CALL(mLayers[1].mOutputLayer, requiresClientComposition()).WillOnce(Return(false));
4096     EXPECT_CALL(mLayers[2].mLayerFE, prepareClientCompositionList(Eq(ByRef(layer2Settings))))
4097             .WillOnce(Return(std::vector<LayerFE::LayerSettings>(
4098                     {mShadowSettings, mLayers[2].mLayerSettings})));
4099 
4100     auto requests = mOutput.generateClientCompositionRequests(false /* supportsProtectedContent */,
4101                                                               accumClearRegion, kDisplayDataspace);
4102     ASSERT_EQ(2u, requests.size());
4103 
4104     EXPECT_EQ(mShadowSettings, requests[0]);
4105     EXPECT_EQ(mLayers[2].mLayerSettings, requests[1]);
4106 }
4107 
4108 } // namespace
4109 } // namespace android::compositionengine
4110