1 /*
2  * Copyright (C) 2018 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 #undef LOG_TAG
18 #define LOG_TAG "LibSurfaceFlingerUnittests"
19 
20 #include <type_traits>
21 
22 #include <compositionengine/Display.h>
23 #include <compositionengine/DisplayColorProfile.h>
24 #include <compositionengine/mock/DisplaySurface.h>
25 #include <gmock/gmock.h>
26 #include <gtest/gtest.h>
27 #include <log/log.h>
28 #include <renderengine/mock/RenderEngine.h>
29 #include <ui/DebugUtils.h>
30 
31 #include "DisplayIdentificationTest.h"
32 #include "TestableScheduler.h"
33 #include "TestableSurfaceFlinger.h"
34 #include "mock/DisplayHardware/MockComposer.h"
35 #include "mock/MockDispSync.h"
36 #include "mock/MockEventControlThread.h"
37 #include "mock/MockEventThread.h"
38 #include "mock/MockMessageQueue.h"
39 #include "mock/MockNativeWindowSurface.h"
40 #include "mock/MockSurfaceInterceptor.h"
41 #include "mock/gui/MockGraphicBufferConsumer.h"
42 #include "mock/gui/MockGraphicBufferProducer.h"
43 #include "mock/system/window/MockNativeWindow.h"
44 
45 namespace android {
46 namespace {
47 
48 using testing::_;
49 using testing::DoAll;
50 using testing::Mock;
51 using testing::ResultOf;
52 using testing::Return;
53 using testing::SetArgPointee;
54 
55 using android::Hwc2::ColorMode;
56 using android::Hwc2::Error;
57 using android::Hwc2::Hdr;
58 using android::Hwc2::IComposer;
59 using android::Hwc2::IComposerClient;
60 using android::Hwc2::PerFrameMetadataKey;
61 using android::Hwc2::RenderIntent;
62 
63 using FakeDisplayDeviceInjector = TestableSurfaceFlinger::FakeDisplayDeviceInjector;
64 using FakeHwcDisplayInjector = TestableSurfaceFlinger::FakeHwcDisplayInjector;
65 using HotplugEvent = TestableSurfaceFlinger::HotplugEvent;
66 using HWC2Display = TestableSurfaceFlinger::HWC2Display;
67 
68 constexpr int32_t DEFAULT_REFRESH_RATE = 16'666'666;
69 constexpr int32_t DEFAULT_DPI = 320;
70 constexpr int DEFAULT_VIRTUAL_DISPLAY_SURFACE_FORMAT = HAL_PIXEL_FORMAT_RGB_565;
71 
72 constexpr int HWC_POWER_MODE_LEET = 1337; // An out of range power mode value
73 
74 /* ------------------------------------------------------------------------
75  * Boolean avoidance
76  *
77  * To make calls and template instantiations more readable, we define some
78  * local enums along with an implicit bool conversion.
79  */
80 
81 #define BOOL_SUBSTITUTE(TYPENAME) enum class TYPENAME : bool { FALSE = false, TRUE = true };
82 
83 BOOL_SUBSTITUTE(Async);
84 BOOL_SUBSTITUTE(Critical);
85 BOOL_SUBSTITUTE(Primary);
86 BOOL_SUBSTITUTE(Secure);
87 BOOL_SUBSTITUTE(Virtual);
88 
89 /* ------------------------------------------------------------------------
90  *
91  */
92 
93 class DisplayTransactionTest : public testing::Test {
94 public:
95     DisplayTransactionTest();
96     ~DisplayTransactionTest() override;
97 
98     void setupScheduler();
99 
100     // --------------------------------------------------------------------
101     // Mock/Fake injection
102 
103     void injectMockComposer(int virtualDisplayCount);
104     void injectFakeBufferQueueFactory();
105     void injectFakeNativeWindowSurfaceFactory();
106 
107     // --------------------------------------------------------------------
108     // Postcondition helpers
109 
110     bool hasPhysicalHwcDisplay(hwc2_display_t hwcDisplayId);
111     bool hasTransactionFlagSet(int flag);
112     bool hasDisplayDevice(sp<IBinder> displayToken);
113     sp<DisplayDevice> getDisplayDevice(sp<IBinder> displayToken);
114     bool hasCurrentDisplayState(sp<IBinder> displayToken);
115     const DisplayDeviceState& getCurrentDisplayState(sp<IBinder> displayToken);
116     bool hasDrawingDisplayState(sp<IBinder> displayToken);
117     const DisplayDeviceState& getDrawingDisplayState(sp<IBinder> displayToken);
118 
119     // --------------------------------------------------------------------
120     // Test instances
121 
122     TestableScheduler* mScheduler;
123     TestableSurfaceFlinger mFlinger;
124     mock::EventThread* mEventThread = new mock::EventThread();
125     mock::EventThread* mSFEventThread = new mock::EventThread();
126     mock::EventControlThread* mEventControlThread = new mock::EventControlThread();
127     sp<mock::NativeWindow> mNativeWindow = new mock::NativeWindow();
128     sp<GraphicBuffer> mBuffer = new GraphicBuffer();
129 
130     // These mocks are created by the test, but are destroyed by SurfaceFlinger
131     // by virtue of being stored into a std::unique_ptr. However we still need
132     // to keep a reference to them for use in setting up call expectations.
133     renderengine::mock::RenderEngine* mRenderEngine = new renderengine::mock::RenderEngine();
134     Hwc2::mock::Composer* mComposer = nullptr;
135     mock::MessageQueue* mMessageQueue = new mock::MessageQueue();
136     mock::SurfaceInterceptor* mSurfaceInterceptor = new mock::SurfaceInterceptor();
137     mock::DispSync* mPrimaryDispSync = new mock::DispSync();
138 
139     // These mocks are created only when expected to be created via a factory.
140     sp<mock::GraphicBufferConsumer> mConsumer;
141     sp<mock::GraphicBufferProducer> mProducer;
142     surfaceflinger::mock::NativeWindowSurface* mNativeWindowSurface = nullptr;
143 };
144 
DisplayTransactionTest()145 DisplayTransactionTest::DisplayTransactionTest() {
146     const ::testing::TestInfo* const test_info =
147             ::testing::UnitTest::GetInstance()->current_test_info();
148     ALOGD("**** Setting up for %s.%s\n", test_info->test_case_name(), test_info->name());
149 
150     // Default to no wide color display support configured
151     mFlinger.mutableHasWideColorDisplay() = false;
152     mFlinger.mutableUseColorManagement() = false;
153     mFlinger.mutableDisplayColorSetting() = DisplayColorSetting::UNMANAGED;
154 
155     // Default to using HWC virtual displays
156     mFlinger.mutableUseHwcVirtualDisplays() = true;
157 
158     mFlinger.setCreateBufferQueueFunction([](auto, auto, auto) {
159         ADD_FAILURE() << "Unexpected request to create a buffer queue.";
160     });
161 
162     mFlinger.setCreateNativeWindowSurface([](auto) {
163         ADD_FAILURE() << "Unexpected request to create a native window surface.";
164         return nullptr;
165     });
166 
167     setupScheduler();
168     mFlinger.mutableEventQueue().reset(mMessageQueue);
169     mFlinger.setupRenderEngine(std::unique_ptr<renderengine::RenderEngine>(mRenderEngine));
170     mFlinger.mutableInterceptor().reset(mSurfaceInterceptor);
171 
172     injectMockComposer(0);
173 }
174 
~DisplayTransactionTest()175 DisplayTransactionTest::~DisplayTransactionTest() {
176     const ::testing::TestInfo* const test_info =
177             ::testing::UnitTest::GetInstance()->current_test_info();
178     ALOGD("**** Tearing down after %s.%s\n", test_info->test_case_name(), test_info->name());
179 }
180 
setupScheduler()181 void DisplayTransactionTest::setupScheduler() {
182     mScheduler = new TestableScheduler(mFlinger.mutableRefreshRateConfigs());
183     mScheduler->mutableEventControlThread().reset(mEventControlThread);
184     mScheduler->mutablePrimaryDispSync().reset(mPrimaryDispSync);
185     EXPECT_CALL(*mEventThread, registerDisplayEventConnection(_));
186     EXPECT_CALL(*mSFEventThread, registerDisplayEventConnection(_));
187 
188     sp<Scheduler::ConnectionHandle> sfConnectionHandle =
189             mScheduler->addConnection(std::unique_ptr<EventThread>(mSFEventThread));
190     mFlinger.mutableSfConnectionHandle() = std::move(sfConnectionHandle);
191     sp<Scheduler::ConnectionHandle> appConnectionHandle =
192             mScheduler->addConnection(std::unique_ptr<EventThread>(mEventThread));
193     mFlinger.mutableAppConnectionHandle() = std::move(appConnectionHandle);
194     mFlinger.mutableScheduler().reset(mScheduler);
195 }
196 
injectMockComposer(int virtualDisplayCount)197 void DisplayTransactionTest::injectMockComposer(int virtualDisplayCount) {
198     mComposer = new Hwc2::mock::Composer();
199     EXPECT_CALL(*mComposer, getCapabilities())
200             .WillOnce(Return(std::vector<IComposer::Capability>()));
201     EXPECT_CALL(*mComposer, getMaxVirtualDisplayCount()).WillOnce(Return(virtualDisplayCount));
202     mFlinger.setupComposer(std::unique_ptr<Hwc2::Composer>(mComposer));
203 
204     Mock::VerifyAndClear(mComposer);
205 }
206 
injectFakeBufferQueueFactory()207 void DisplayTransactionTest::injectFakeBufferQueueFactory() {
208     // This setup is only expected once per test.
209     ASSERT_TRUE(mConsumer == nullptr && mProducer == nullptr);
210 
211     mConsumer = new mock::GraphicBufferConsumer();
212     mProducer = new mock::GraphicBufferProducer();
213 
214     mFlinger.setCreateBufferQueueFunction([this](auto outProducer, auto outConsumer, bool) {
215         *outProducer = mProducer;
216         *outConsumer = mConsumer;
217     });
218 }
219 
injectFakeNativeWindowSurfaceFactory()220 void DisplayTransactionTest::injectFakeNativeWindowSurfaceFactory() {
221     // This setup is only expected once per test.
222     ASSERT_TRUE(mNativeWindowSurface == nullptr);
223 
224     mNativeWindowSurface = new surfaceflinger::mock::NativeWindowSurface();
225 
226     mFlinger.setCreateNativeWindowSurface([this](auto) {
227         return std::unique_ptr<surfaceflinger::NativeWindowSurface>(mNativeWindowSurface);
228     });
229 }
230 
hasPhysicalHwcDisplay(hwc2_display_t hwcDisplayId)231 bool DisplayTransactionTest::hasPhysicalHwcDisplay(hwc2_display_t hwcDisplayId) {
232     return mFlinger.mutableHwcPhysicalDisplayIdMap().count(hwcDisplayId) == 1;
233 }
234 
hasTransactionFlagSet(int flag)235 bool DisplayTransactionTest::hasTransactionFlagSet(int flag) {
236     return mFlinger.mutableTransactionFlags() & flag;
237 }
238 
hasDisplayDevice(sp<IBinder> displayToken)239 bool DisplayTransactionTest::hasDisplayDevice(sp<IBinder> displayToken) {
240     return mFlinger.mutableDisplays().count(displayToken) == 1;
241 }
242 
getDisplayDevice(sp<IBinder> displayToken)243 sp<DisplayDevice> DisplayTransactionTest::getDisplayDevice(sp<IBinder> displayToken) {
244     return mFlinger.mutableDisplays()[displayToken];
245 }
246 
hasCurrentDisplayState(sp<IBinder> displayToken)247 bool DisplayTransactionTest::hasCurrentDisplayState(sp<IBinder> displayToken) {
248     return mFlinger.mutableCurrentState().displays.indexOfKey(displayToken) >= 0;
249 }
250 
getCurrentDisplayState(sp<IBinder> displayToken)251 const DisplayDeviceState& DisplayTransactionTest::getCurrentDisplayState(sp<IBinder> displayToken) {
252     return mFlinger.mutableCurrentState().displays.valueFor(displayToken);
253 }
254 
hasDrawingDisplayState(sp<IBinder> displayToken)255 bool DisplayTransactionTest::hasDrawingDisplayState(sp<IBinder> displayToken) {
256     return mFlinger.mutableDrawingState().displays.indexOfKey(displayToken) >= 0;
257 }
258 
getDrawingDisplayState(sp<IBinder> displayToken)259 const DisplayDeviceState& DisplayTransactionTest::getDrawingDisplayState(sp<IBinder> displayToken) {
260     return mFlinger.mutableDrawingState().displays.valueFor(displayToken);
261 }
262 
263 /* ------------------------------------------------------------------------
264  *
265  */
266 
267 template <typename PhysicalDisplay>
268 struct PhysicalDisplayId {};
269 
270 template <DisplayId::Type displayId>
271 using VirtualDisplayId = std::integral_constant<DisplayId::Type, displayId>;
272 
273 struct NoDisplayId {};
274 
275 template <typename>
276 struct IsPhysicalDisplayId : std::bool_constant<false> {};
277 
278 template <typename PhysicalDisplay>
279 struct IsPhysicalDisplayId<PhysicalDisplayId<PhysicalDisplay>> : std::bool_constant<true> {};
280 
281 template <typename>
282 struct DisplayIdGetter;
283 
284 template <typename PhysicalDisplay>
285 struct DisplayIdGetter<PhysicalDisplayId<PhysicalDisplay>> {
getandroid::__anon968546880111::DisplayIdGetter286     static std::optional<DisplayId> get() {
287         if (!PhysicalDisplay::HAS_IDENTIFICATION_DATA) {
288             return getFallbackDisplayId(static_cast<bool>(PhysicalDisplay::PRIMARY)
289                                                 ? HWC_DISPLAY_PRIMARY
290                                                 : HWC_DISPLAY_EXTERNAL);
291         }
292 
293         const auto info =
294                 parseDisplayIdentificationData(PhysicalDisplay::PORT,
295                                                PhysicalDisplay::GET_IDENTIFICATION_DATA());
296         return info ? std::make_optional(info->id) : std::nullopt;
297     }
298 };
299 
300 template <DisplayId::Type displayId>
301 struct DisplayIdGetter<VirtualDisplayId<displayId>> {
getandroid::__anon968546880111::DisplayIdGetter302     static std::optional<DisplayId> get() { return DisplayId{displayId}; }
303 };
304 
305 template <>
306 struct DisplayIdGetter<NoDisplayId> {
getandroid::__anon968546880111::DisplayIdGetter307     static std::optional<DisplayId> get() { return {}; }
308 };
309 
310 // DisplayIdType can be:
311 //     1) PhysicalDisplayId<...> for generated ID of physical display backed by HWC.
312 //     2) VirtualDisplayId<...> for hard-coded ID of virtual display backed by HWC.
313 //     3) NoDisplayId for virtual display without HWC backing.
314 template <typename DisplayIdType, int width, int height, Critical critical, Async async,
315           Secure secure, Primary primary, int grallocUsage>
316 struct DisplayVariant {
317     using DISPLAY_ID = DisplayIdGetter<DisplayIdType>;
318 
319     // The display width and height
320     static constexpr int WIDTH = width;
321     static constexpr int HEIGHT = height;
322 
323     static constexpr int GRALLOC_USAGE = grallocUsage;
324 
325     // Whether the display is virtual or physical
326     static constexpr Virtual VIRTUAL =
327             IsPhysicalDisplayId<DisplayIdType>{} ? Virtual::FALSE : Virtual::TRUE;
328 
329     // When creating native window surfaces for the framebuffer, whether those should be critical
330     static constexpr Critical CRITICAL = critical;
331 
332     // When creating native window surfaces for the framebuffer, whether those should be async
333     static constexpr Async ASYNC = async;
334 
335     // Whether the display should be treated as secure
336     static constexpr Secure SECURE = secure;
337 
338     // Whether the display is primary
339     static constexpr Primary PRIMARY = primary;
340 
makeFakeExistingDisplayInjectorandroid::__anon968546880111::DisplayVariant341     static auto makeFakeExistingDisplayInjector(DisplayTransactionTest* test) {
342         auto injector =
343                 FakeDisplayDeviceInjector(test->mFlinger, DISPLAY_ID::get(),
344                                           static_cast<bool>(VIRTUAL), static_cast<bool>(PRIMARY));
345 
346         injector.setSecure(static_cast<bool>(SECURE));
347         injector.setNativeWindow(test->mNativeWindow);
348 
349         // Creating a DisplayDevice requires getting default dimensions from the
350         // native window along with some other initial setup.
351         EXPECT_CALL(*test->mNativeWindow, query(NATIVE_WINDOW_WIDTH, _))
352                 .WillRepeatedly(DoAll(SetArgPointee<1>(WIDTH), Return(0)));
353         EXPECT_CALL(*test->mNativeWindow, query(NATIVE_WINDOW_HEIGHT, _))
354                 .WillRepeatedly(DoAll(SetArgPointee<1>(HEIGHT), Return(0)));
355         EXPECT_CALL(*test->mNativeWindow, perform(NATIVE_WINDOW_SET_BUFFERS_FORMAT))
356                 .WillRepeatedly(Return(0));
357         EXPECT_CALL(*test->mNativeWindow, perform(NATIVE_WINDOW_API_CONNECT))
358                 .WillRepeatedly(Return(0));
359         EXPECT_CALL(*test->mNativeWindow, perform(NATIVE_WINDOW_SET_USAGE64))
360                 .WillRepeatedly(Return(0));
361         EXPECT_CALL(*test->mNativeWindow, perform(NATIVE_WINDOW_API_DISCONNECT))
362                 .WillRepeatedly(Return(0));
363 
364         return injector;
365     }
366 
367     // Called by tests to set up any native window creation call expectations.
setupNativeWindowSurfaceCreationCallExpectationsandroid::__anon968546880111::DisplayVariant368     static void setupNativeWindowSurfaceCreationCallExpectations(DisplayTransactionTest* test) {
369         EXPECT_CALL(*test->mNativeWindowSurface, getNativeWindow())
370                 .WillOnce(Return(test->mNativeWindow));
371 
372         EXPECT_CALL(*test->mNativeWindow, query(NATIVE_WINDOW_WIDTH, _))
373                 .WillRepeatedly(DoAll(SetArgPointee<1>(WIDTH), Return(0)));
374         EXPECT_CALL(*test->mNativeWindow, query(NATIVE_WINDOW_HEIGHT, _))
375                 .WillRepeatedly(DoAll(SetArgPointee<1>(HEIGHT), Return(0)));
376         EXPECT_CALL(*test->mNativeWindow, perform(NATIVE_WINDOW_SET_BUFFERS_FORMAT))
377                 .WillRepeatedly(Return(0));
378         EXPECT_CALL(*test->mNativeWindow, perform(NATIVE_WINDOW_API_CONNECT))
379                 .WillRepeatedly(Return(0));
380         EXPECT_CALL(*test->mNativeWindow, perform(NATIVE_WINDOW_SET_USAGE64))
381                 .WillRepeatedly(Return(0));
382         EXPECT_CALL(*test->mNativeWindow, perform(NATIVE_WINDOW_API_DISCONNECT))
383                 .WillRepeatedly(Return(0));
384     }
385 
setupFramebufferConsumerBufferQueueCallExpectationsandroid::__anon968546880111::DisplayVariant386     static void setupFramebufferConsumerBufferQueueCallExpectations(DisplayTransactionTest* test) {
387         EXPECT_CALL(*test->mConsumer, consumerConnect(_, false)).WillOnce(Return(NO_ERROR));
388         EXPECT_CALL(*test->mConsumer, setConsumerName(_)).WillRepeatedly(Return(NO_ERROR));
389         EXPECT_CALL(*test->mConsumer, setConsumerUsageBits(GRALLOC_USAGE))
390                 .WillRepeatedly(Return(NO_ERROR));
391         EXPECT_CALL(*test->mConsumer, setDefaultBufferSize(WIDTH, HEIGHT))
392                 .WillRepeatedly(Return(NO_ERROR));
393         EXPECT_CALL(*test->mConsumer, setMaxAcquiredBufferCount(_))
394                 .WillRepeatedly(Return(NO_ERROR));
395     }
396 
setupFramebufferProducerBufferQueueCallExpectationsandroid::__anon968546880111::DisplayVariant397     static void setupFramebufferProducerBufferQueueCallExpectations(DisplayTransactionTest* test) {
398         EXPECT_CALL(*test->mProducer, allocateBuffers(0, 0, 0, 0)).WillRepeatedly(Return());
399     }
400 };
401 
402 template <hwc2_display_t hwcDisplayId, HWC2::DisplayType hwcDisplayType, typename DisplayVariant,
403           typename PhysicalDisplay = void>
404 struct HwcDisplayVariant {
405     // The display id supplied by the HWC
406     static constexpr hwc2_display_t HWC_DISPLAY_ID = hwcDisplayId;
407 
408     // The HWC display type
409     static constexpr HWC2::DisplayType HWC_DISPLAY_TYPE = hwcDisplayType;
410 
411     // The HWC active configuration id
412     static constexpr int HWC_ACTIVE_CONFIG_ID = 2001;
413     static constexpr int INIT_POWER_MODE = HWC_POWER_MODE_NORMAL;
414 
injectPendingHotplugEventandroid::__anon968546880111::HwcDisplayVariant415     static void injectPendingHotplugEvent(DisplayTransactionTest* test,
416                                           HWC2::Connection connection) {
417         test->mFlinger.mutablePendingHotplugEvents().emplace_back(
418                 HotplugEvent{HWC_DISPLAY_ID, connection});
419     }
420 
421     // Called by tests to inject a HWC display setup
injectHwcDisplayWithNoDefaultCapabilitiesandroid::__anon968546880111::HwcDisplayVariant422     static void injectHwcDisplayWithNoDefaultCapabilities(DisplayTransactionTest* test) {
423         const auto displayId = DisplayVariant::DISPLAY_ID::get();
424         ASSERT_TRUE(displayId);
425         FakeHwcDisplayInjector(*displayId, HWC_DISPLAY_TYPE,
426                                static_cast<bool>(DisplayVariant::PRIMARY))
427                 .setHwcDisplayId(HWC_DISPLAY_ID)
428                 .setWidth(DisplayVariant::WIDTH)
429                 .setHeight(DisplayVariant::HEIGHT)
430                 .setActiveConfig(HWC_ACTIVE_CONFIG_ID)
431                 .setPowerMode(INIT_POWER_MODE)
432                 .inject(&test->mFlinger, test->mComposer);
433     }
434 
435     // Called by tests to inject a HWC display setup
injectHwcDisplayandroid::__anon968546880111::HwcDisplayVariant436     static void injectHwcDisplay(DisplayTransactionTest* test) {
437         EXPECT_CALL(*test->mComposer, getDisplayCapabilities(HWC_DISPLAY_ID, _))
438                 .WillOnce(DoAll(SetArgPointee<1>(std::vector<Hwc2::DisplayCapability>({})),
439                                 Return(Error::NONE)));
440         EXPECT_CALL(*test->mComposer,
441                     setPowerMode(HWC_DISPLAY_ID,
442                                  static_cast<Hwc2::IComposerClient::PowerMode>(INIT_POWER_MODE)))
443                 .WillOnce(Return(Error::NONE));
444         injectHwcDisplayWithNoDefaultCapabilities(test);
445     }
446 
setupHwcHotplugCallExpectationsandroid::__anon968546880111::HwcDisplayVariant447     static void setupHwcHotplugCallExpectations(DisplayTransactionTest* test) {
448         EXPECT_CALL(*test->mComposer, getDisplayType(HWC_DISPLAY_ID, _))
449                 .WillOnce(DoAll(SetArgPointee<1>(static_cast<IComposerClient::DisplayType>(
450                                         HWC_DISPLAY_TYPE)),
451                                 Return(Error::NONE)));
452         EXPECT_CALL(*test->mComposer, setClientTargetSlotCount(_)).WillOnce(Return(Error::NONE));
453         EXPECT_CALL(*test->mComposer, getDisplayConfigs(HWC_DISPLAY_ID, _))
454                 .WillOnce(DoAll(SetArgPointee<1>(std::vector<unsigned>{HWC_ACTIVE_CONFIG_ID}),
455                                 Return(Error::NONE)));
456         EXPECT_CALL(*test->mComposer,
457                     getDisplayAttribute(HWC_DISPLAY_ID, HWC_ACTIVE_CONFIG_ID,
458                                         IComposerClient::Attribute::WIDTH, _))
459                 .WillOnce(DoAll(SetArgPointee<3>(DisplayVariant::WIDTH), Return(Error::NONE)));
460         EXPECT_CALL(*test->mComposer,
461                     getDisplayAttribute(HWC_DISPLAY_ID, HWC_ACTIVE_CONFIG_ID,
462                                         IComposerClient::Attribute::HEIGHT, _))
463                 .WillOnce(DoAll(SetArgPointee<3>(DisplayVariant::HEIGHT), Return(Error::NONE)));
464         EXPECT_CALL(*test->mComposer,
465                     getDisplayAttribute(HWC_DISPLAY_ID, HWC_ACTIVE_CONFIG_ID,
466                                         IComposerClient::Attribute::VSYNC_PERIOD, _))
467                 .WillOnce(DoAll(SetArgPointee<3>(DEFAULT_REFRESH_RATE), Return(Error::NONE)));
468         EXPECT_CALL(*test->mComposer,
469                     getDisplayAttribute(HWC_DISPLAY_ID, HWC_ACTIVE_CONFIG_ID,
470                                         IComposerClient::Attribute::DPI_X, _))
471                 .WillOnce(DoAll(SetArgPointee<3>(DEFAULT_DPI), Return(Error::NONE)));
472         EXPECT_CALL(*test->mComposer,
473                     getDisplayAttribute(HWC_DISPLAY_ID, HWC_ACTIVE_CONFIG_ID,
474                                         IComposerClient::Attribute::DPI_Y, _))
475                 .WillOnce(DoAll(SetArgPointee<3>(DEFAULT_DPI), Return(Error::NONE)));
476 
477         if (PhysicalDisplay::HAS_IDENTIFICATION_DATA) {
478             EXPECT_CALL(*test->mComposer, getDisplayIdentificationData(HWC_DISPLAY_ID, _, _))
479                     .WillOnce(DoAll(SetArgPointee<1>(PhysicalDisplay::PORT),
480                                     SetArgPointee<2>(PhysicalDisplay::GET_IDENTIFICATION_DATA()),
481                                     Return(Error::NONE)));
482         } else {
483             EXPECT_CALL(*test->mComposer, getDisplayIdentificationData(HWC_DISPLAY_ID, _, _))
484                     .WillOnce(Return(Error::UNSUPPORTED));
485         }
486     }
487 
488     // Called by tests to set up HWC call expectations
setupHwcGetActiveConfigCallExpectationsandroid::__anon968546880111::HwcDisplayVariant489     static void setupHwcGetActiveConfigCallExpectations(DisplayTransactionTest* test) {
490         EXPECT_CALL(*test->mComposer, getActiveConfig(HWC_DISPLAY_ID, _))
491                 .WillRepeatedly(DoAll(SetArgPointee<1>(HWC_ACTIVE_CONFIG_ID), Return(Error::NONE)));
492     }
493 };
494 
495 // Physical displays are expected to be synchronous, secure, and have a HWC display for output.
496 constexpr uint32_t GRALLOC_USAGE_PHYSICAL_DISPLAY =
497         GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_FB;
498 
499 template <hwc2_display_t hwcDisplayId, typename PhysicalDisplay, int width, int height,
500           Critical critical>
501 struct PhysicalDisplayVariant
502       : DisplayVariant<PhysicalDisplayId<PhysicalDisplay>, width, height, critical, Async::FALSE,
503                        Secure::TRUE, PhysicalDisplay::PRIMARY, GRALLOC_USAGE_PHYSICAL_DISPLAY>,
504         HwcDisplayVariant<hwcDisplayId, HWC2::DisplayType::Physical,
505                           DisplayVariant<PhysicalDisplayId<PhysicalDisplay>, width, height,
506                                          critical, Async::FALSE, Secure::TRUE,
507                                          PhysicalDisplay::PRIMARY, GRALLOC_USAGE_PHYSICAL_DISPLAY>,
508                           PhysicalDisplay> {};
509 
510 template <bool hasIdentificationData>
511 struct PrimaryDisplay {
512     static constexpr Primary PRIMARY = Primary::TRUE;
513     static constexpr uint8_t PORT = 255;
514     static constexpr bool HAS_IDENTIFICATION_DATA = hasIdentificationData;
515     static constexpr auto GET_IDENTIFICATION_DATA = getInternalEdid;
516 };
517 
518 template <bool hasIdentificationData>
519 struct ExternalDisplay {
520     static constexpr Primary PRIMARY = Primary::FALSE;
521     static constexpr uint8_t PORT = 254;
522     static constexpr bool HAS_IDENTIFICATION_DATA = hasIdentificationData;
523     static constexpr auto GET_IDENTIFICATION_DATA = getExternalEdid;
524 };
525 
526 struct TertiaryDisplay {
527     static constexpr Primary PRIMARY = Primary::FALSE;
528     static constexpr uint8_t PORT = 253;
529     static constexpr auto GET_IDENTIFICATION_DATA = getExternalEdid;
530 };
531 
532 // A primary display is a physical display that is critical
533 using PrimaryDisplayVariant =
534         PhysicalDisplayVariant<1001, PrimaryDisplay<false>, 3840, 2160, Critical::TRUE>;
535 
536 // An external display is physical display that is not critical.
537 using ExternalDisplayVariant =
538         PhysicalDisplayVariant<1002, ExternalDisplay<false>, 1920, 1280, Critical::FALSE>;
539 
540 using TertiaryDisplayVariant =
541         PhysicalDisplayVariant<1003, TertiaryDisplay, 1600, 1200, Critical::FALSE>;
542 
543 // A virtual display not supported by the HWC.
544 constexpr uint32_t GRALLOC_USAGE_NONHWC_VIRTUAL_DISPLAY = 0;
545 
546 template <int width, int height, Secure secure>
547 struct NonHwcVirtualDisplayVariant
548       : DisplayVariant<NoDisplayId, width, height, Critical::FALSE, Async::TRUE, secure,
549                        Primary::FALSE, GRALLOC_USAGE_NONHWC_VIRTUAL_DISPLAY> {
550     using Base = DisplayVariant<NoDisplayId, width, height, Critical::FALSE, Async::TRUE, secure,
551                                 Primary::FALSE, GRALLOC_USAGE_NONHWC_VIRTUAL_DISPLAY>;
552 
injectHwcDisplayandroid::__anon968546880111::NonHwcVirtualDisplayVariant553     static void injectHwcDisplay(DisplayTransactionTest*) {}
554 
setupHwcGetActiveConfigCallExpectationsandroid::__anon968546880111::NonHwcVirtualDisplayVariant555     static void setupHwcGetActiveConfigCallExpectations(DisplayTransactionTest* test) {
556         EXPECT_CALL(*test->mComposer, getActiveConfig(_, _)).Times(0);
557     }
558 
setupNativeWindowSurfaceCreationCallExpectationsandroid::__anon968546880111::NonHwcVirtualDisplayVariant559     static void setupNativeWindowSurfaceCreationCallExpectations(DisplayTransactionTest* test) {
560         Base::setupNativeWindowSurfaceCreationCallExpectations(test);
561         EXPECT_CALL(*test->mNativeWindow, setSwapInterval(0)).Times(1);
562     }
563 };
564 
565 // A virtual display supported by the HWC.
566 constexpr uint32_t GRALLOC_USAGE_HWC_VIRTUAL_DISPLAY = GRALLOC_USAGE_HW_COMPOSER;
567 
568 template <int width, int height, Secure secure>
569 struct HwcVirtualDisplayVariant
570       : DisplayVariant<VirtualDisplayId<42>, width, height, Critical::FALSE, Async::TRUE, secure,
571                        Primary::FALSE, GRALLOC_USAGE_HWC_VIRTUAL_DISPLAY>,
572         HwcDisplayVariant<
573                 1010, HWC2::DisplayType::Virtual,
574                 DisplayVariant<VirtualDisplayId<42>, width, height, Critical::FALSE, Async::TRUE,
575                                secure, Primary::FALSE, GRALLOC_USAGE_HWC_VIRTUAL_DISPLAY>> {
576     using Base = DisplayVariant<VirtualDisplayId<42>, width, height, Critical::FALSE, Async::TRUE,
577                                 secure, Primary::FALSE, GRALLOC_USAGE_HW_COMPOSER>;
578     using Self = HwcVirtualDisplayVariant<width, height, secure>;
579 
setupNativeWindowSurfaceCreationCallExpectationsandroid::__anon968546880111::HwcVirtualDisplayVariant580     static void setupNativeWindowSurfaceCreationCallExpectations(DisplayTransactionTest* test) {
581         Base::setupNativeWindowSurfaceCreationCallExpectations(test);
582         EXPECT_CALL(*test->mNativeWindow, setSwapInterval(0)).Times(1);
583     }
584 
setupHwcVirtualDisplayCreationCallExpectationsandroid::__anon968546880111::HwcVirtualDisplayVariant585     static void setupHwcVirtualDisplayCreationCallExpectations(DisplayTransactionTest* test) {
586         EXPECT_CALL(*test->mComposer, createVirtualDisplay(Base::WIDTH, Base::HEIGHT, _, _))
587                 .WillOnce(DoAll(SetArgPointee<3>(Self::HWC_DISPLAY_ID), Return(Error::NONE)));
588         EXPECT_CALL(*test->mComposer, setClientTargetSlotCount(_)).WillOnce(Return(Error::NONE));
589     }
590 };
591 
592 // For this variant, SurfaceFlinger should not configure itself with wide
593 // display support, so the display should not be configured for wide-color
594 // support.
595 struct WideColorSupportNotConfiguredVariant {
596     static constexpr bool WIDE_COLOR_SUPPORTED = false;
597 
injectConfigChangeandroid::__anon968546880111::WideColorSupportNotConfiguredVariant598     static void injectConfigChange(DisplayTransactionTest* test) {
599         test->mFlinger.mutableHasWideColorDisplay() = false;
600         test->mFlinger.mutableUseColorManagement() = false;
601         test->mFlinger.mutableDisplayColorSetting() = DisplayColorSetting::UNMANAGED;
602     }
603 
setupComposerCallExpectationsandroid::__anon968546880111::WideColorSupportNotConfiguredVariant604     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
605         EXPECT_CALL(*test->mComposer, getColorModes(_, _)).Times(0);
606         EXPECT_CALL(*test->mComposer, getRenderIntents(_, _, _)).Times(0);
607         EXPECT_CALL(*test->mComposer, setColorMode(_, _, _)).Times(0);
608     }
609 };
610 
611 // For this variant, SurfaceFlinger should configure itself with wide display
612 // support, and the display should respond with an non-empty list of supported
613 // color modes. Wide-color support should be configured.
614 template <typename Display>
615 struct WideColorP3ColorimetricSupportedVariant {
616     static constexpr bool WIDE_COLOR_SUPPORTED = true;
617 
injectConfigChangeandroid::__anon968546880111::WideColorP3ColorimetricSupportedVariant618     static void injectConfigChange(DisplayTransactionTest* test) {
619         test->mFlinger.mutableUseColorManagement() = true;
620         test->mFlinger.mutableHasWideColorDisplay() = true;
621         test->mFlinger.mutableDisplayColorSetting() = DisplayColorSetting::UNMANAGED;
622     }
623 
setupComposerCallExpectationsandroid::__anon968546880111::WideColorP3ColorimetricSupportedVariant624     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
625         EXPECT_CALL(*test->mNativeWindow, perform(NATIVE_WINDOW_SET_BUFFERS_DATASPACE)).Times(1);
626 
627         EXPECT_CALL(*test->mComposer, getColorModes(Display::HWC_DISPLAY_ID, _))
628                 .WillOnce(DoAll(SetArgPointee<1>(std::vector<ColorMode>({ColorMode::DISPLAY_P3})),
629                                 Return(Error::NONE)));
630         EXPECT_CALL(*test->mComposer,
631                     getRenderIntents(Display::HWC_DISPLAY_ID, ColorMode::DISPLAY_P3, _))
632                 .WillOnce(DoAll(SetArgPointee<2>(
633                                         std::vector<RenderIntent>({RenderIntent::COLORIMETRIC})),
634                                 Return(Error::NONE)));
635         EXPECT_CALL(*test->mComposer,
636                     setColorMode(Display::HWC_DISPLAY_ID, ColorMode::SRGB,
637                                  RenderIntent::COLORIMETRIC))
638                 .WillOnce(Return(Error::NONE));
639     }
640 };
641 
642 // For this variant, SurfaceFlinger should configure itself with wide display
643 // support, but the display should respond with an empty list of supported color
644 // modes. Wide-color support for the display should not be configured.
645 template <typename Display>
646 struct WideColorNotSupportedVariant {
647     static constexpr bool WIDE_COLOR_SUPPORTED = false;
648 
injectConfigChangeandroid::__anon968546880111::WideColorNotSupportedVariant649     static void injectConfigChange(DisplayTransactionTest* test) {
650         test->mFlinger.mutableUseColorManagement() = true;
651         test->mFlinger.mutableHasWideColorDisplay() = true;
652     }
653 
setupComposerCallExpectationsandroid::__anon968546880111::WideColorNotSupportedVariant654     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
655         EXPECT_CALL(*test->mComposer, getColorModes(Display::HWC_DISPLAY_ID, _))
656                 .WillOnce(DoAll(SetArgPointee<1>(std::vector<ColorMode>()), Return(Error::NONE)));
657         EXPECT_CALL(*test->mComposer, setColorMode(_, _, _)).Times(0);
658     }
659 };
660 
661 // For this variant, the display is not a HWC display, so no HDR support should
662 // be configured.
663 struct NonHwcDisplayHdrSupportVariant {
664     static constexpr bool HDR10_PLUS_SUPPORTED = false;
665     static constexpr bool HDR10_SUPPORTED = false;
666     static constexpr bool HDR_HLG_SUPPORTED = false;
667     static constexpr bool HDR_DOLBY_VISION_SUPPORTED = false;
setupComposerCallExpectationsandroid::__anon968546880111::NonHwcDisplayHdrSupportVariant668     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
669         EXPECT_CALL(*test->mComposer, getHdrCapabilities(_, _, _, _, _)).Times(0);
670     }
671 };
672 
673 template <typename Display>
674 struct Hdr10PlusSupportedVariant {
675     static constexpr bool HDR10_PLUS_SUPPORTED = true;
676     static constexpr bool HDR10_SUPPORTED = true;
677     static constexpr bool HDR_HLG_SUPPORTED = false;
678     static constexpr bool HDR_DOLBY_VISION_SUPPORTED = false;
setupComposerCallExpectationsandroid::__anon968546880111::Hdr10PlusSupportedVariant679     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
680         EXPECT_CALL(*test->mComposer, getHdrCapabilities(_, _, _, _, _))
681                 .WillOnce(DoAll(SetArgPointee<1>(std::vector<Hdr>({
682                                         Hdr::HDR10_PLUS,
683                                         Hdr::HDR10,
684                                 })),
685                                 Return(Error::NONE)));
686     }
687 };
688 
689 // For this variant, the composer should respond with a non-empty list of HDR
690 // modes containing HDR10, so HDR10 support should be configured.
691 template <typename Display>
692 struct Hdr10SupportedVariant {
693     static constexpr bool HDR10_PLUS_SUPPORTED = false;
694     static constexpr bool HDR10_SUPPORTED = true;
695     static constexpr bool HDR_HLG_SUPPORTED = false;
696     static constexpr bool HDR_DOLBY_VISION_SUPPORTED = false;
setupComposerCallExpectationsandroid::__anon968546880111::Hdr10SupportedVariant697     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
698         EXPECT_CALL(*test->mComposer, getHdrCapabilities(Display::HWC_DISPLAY_ID, _, _, _, _))
699                 .WillOnce(DoAll(SetArgPointee<1>(std::vector<Hdr>({Hdr::HDR10})),
700                                 Return(Error::NONE)));
701     }
702 };
703 
704 // For this variant, the composer should respond with a non-empty list of HDR
705 // modes containing HLG, so HLG support should be configured.
706 template <typename Display>
707 struct HdrHlgSupportedVariant {
708     static constexpr bool HDR10_PLUS_SUPPORTED = false;
709     static constexpr bool HDR10_SUPPORTED = false;
710     static constexpr bool HDR_HLG_SUPPORTED = true;
711     static constexpr bool HDR_DOLBY_VISION_SUPPORTED = false;
setupComposerCallExpectationsandroid::__anon968546880111::HdrHlgSupportedVariant712     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
713         EXPECT_CALL(*test->mComposer, getHdrCapabilities(Display::HWC_DISPLAY_ID, _, _, _, _))
714                 .WillOnce(
715                         DoAll(SetArgPointee<1>(std::vector<Hdr>({Hdr::HLG})), Return(Error::NONE)));
716     }
717 };
718 
719 // For this variant, the composer should respond with a non-empty list of HDR
720 // modes containing DOLBY_VISION, so DOLBY_VISION support should be configured.
721 template <typename Display>
722 struct HdrDolbyVisionSupportedVariant {
723     static constexpr bool HDR10_PLUS_SUPPORTED = false;
724     static constexpr bool HDR10_SUPPORTED = false;
725     static constexpr bool HDR_HLG_SUPPORTED = false;
726     static constexpr bool HDR_DOLBY_VISION_SUPPORTED = true;
setupComposerCallExpectationsandroid::__anon968546880111::HdrDolbyVisionSupportedVariant727     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
728         EXPECT_CALL(*test->mComposer, getHdrCapabilities(Display::HWC_DISPLAY_ID, _, _, _, _))
729                 .WillOnce(DoAll(SetArgPointee<1>(std::vector<Hdr>({Hdr::DOLBY_VISION})),
730                                 Return(Error::NONE)));
731     }
732 };
733 
734 // For this variant, the composer should respond with am empty list of HDR
735 // modes, so no HDR support should be configured.
736 template <typename Display>
737 struct HdrNotSupportedVariant {
738     static constexpr bool HDR10_PLUS_SUPPORTED = false;
739     static constexpr bool HDR10_SUPPORTED = false;
740     static constexpr bool HDR_HLG_SUPPORTED = false;
741     static constexpr bool HDR_DOLBY_VISION_SUPPORTED = false;
setupComposerCallExpectationsandroid::__anon968546880111::HdrNotSupportedVariant742     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
743         EXPECT_CALL(*test->mComposer, getHdrCapabilities(Display::HWC_DISPLAY_ID, _, _, _, _))
744                 .WillOnce(DoAll(SetArgPointee<1>(std::vector<Hdr>()), Return(Error::NONE)));
745     }
746 };
747 
748 struct NonHwcPerFrameMetadataSupportVariant {
749     static constexpr int PER_FRAME_METADATA_KEYS = 0;
setupComposerCallExpectationsandroid::__anon968546880111::NonHwcPerFrameMetadataSupportVariant750     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
751         EXPECT_CALL(*test->mComposer, getPerFrameMetadataKeys(_)).Times(0);
752     }
753 };
754 
755 template <typename Display>
756 struct NoPerFrameMetadataSupportVariant {
757     static constexpr int PER_FRAME_METADATA_KEYS = 0;
setupComposerCallExpectationsandroid::__anon968546880111::NoPerFrameMetadataSupportVariant758     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
759         EXPECT_CALL(*test->mComposer, getPerFrameMetadataKeys(Display::HWC_DISPLAY_ID))
760                 .WillOnce(Return(std::vector<PerFrameMetadataKey>()));
761     }
762 };
763 
764 template <typename Display>
765 struct Smpte2086PerFrameMetadataSupportVariant {
766     static constexpr int PER_FRAME_METADATA_KEYS = HdrMetadata::Type::SMPTE2086;
setupComposerCallExpectationsandroid::__anon968546880111::Smpte2086PerFrameMetadataSupportVariant767     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
768         EXPECT_CALL(*test->mComposer, getPerFrameMetadataKeys(Display::HWC_DISPLAY_ID))
769                 .WillOnce(Return(std::vector<PerFrameMetadataKey>({
770                         PerFrameMetadataKey::DISPLAY_RED_PRIMARY_X,
771                         PerFrameMetadataKey::DISPLAY_RED_PRIMARY_Y,
772                         PerFrameMetadataKey::DISPLAY_GREEN_PRIMARY_X,
773                         PerFrameMetadataKey::DISPLAY_GREEN_PRIMARY_Y,
774                         PerFrameMetadataKey::DISPLAY_BLUE_PRIMARY_X,
775                         PerFrameMetadataKey::DISPLAY_BLUE_PRIMARY_Y,
776                         PerFrameMetadataKey::WHITE_POINT_X,
777                         PerFrameMetadataKey::WHITE_POINT_Y,
778                         PerFrameMetadataKey::MAX_LUMINANCE,
779                         PerFrameMetadataKey::MIN_LUMINANCE,
780                 })));
781     }
782 };
783 
784 template <typename Display>
785 struct Cta861_3_PerFrameMetadataSupportVariant {
786     static constexpr int PER_FRAME_METADATA_KEYS = HdrMetadata::Type::CTA861_3;
setupComposerCallExpectationsandroid::__anon968546880111::Cta861_3_PerFrameMetadataSupportVariant787     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
788         EXPECT_CALL(*test->mComposer, getPerFrameMetadataKeys(Display::HWC_DISPLAY_ID))
789                 .WillOnce(Return(std::vector<PerFrameMetadataKey>({
790                         PerFrameMetadataKey::MAX_CONTENT_LIGHT_LEVEL,
791                         PerFrameMetadataKey::MAX_FRAME_AVERAGE_LIGHT_LEVEL,
792                 })));
793     }
794 };
795 
796 template <typename Display>
797 struct Hdr10_Plus_PerFrameMetadataSupportVariant {
798     static constexpr int PER_FRAME_METADATA_KEYS = HdrMetadata::Type::HDR10PLUS;
setupComposerCallExpectationsandroid::__anon968546880111::Hdr10_Plus_PerFrameMetadataSupportVariant799     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
800         EXPECT_CALL(*test->mComposer, getPerFrameMetadataKeys(Display::HWC_DISPLAY_ID))
801                 .WillOnce(Return(std::vector<PerFrameMetadataKey>({
802                         PerFrameMetadataKey::HDR10_PLUS_SEI,
803                 })));
804     }
805 };
806 /* ------------------------------------------------------------------------
807  * Typical display configurations to test
808  */
809 
810 template <typename DisplayPolicy, typename WideColorSupportPolicy, typename HdrSupportPolicy,
811           typename PerFrameMetadataSupportPolicy>
812 struct Case {
813     using Display = DisplayPolicy;
814     using WideColorSupport = WideColorSupportPolicy;
815     using HdrSupport = HdrSupportPolicy;
816     using PerFrameMetadataSupport = PerFrameMetadataSupportPolicy;
817 };
818 
819 using SimplePrimaryDisplayCase =
820         Case<PrimaryDisplayVariant, WideColorNotSupportedVariant<PrimaryDisplayVariant>,
821              HdrNotSupportedVariant<PrimaryDisplayVariant>,
822              NoPerFrameMetadataSupportVariant<PrimaryDisplayVariant>>;
823 using SimpleExternalDisplayCase =
824         Case<ExternalDisplayVariant, WideColorNotSupportedVariant<ExternalDisplayVariant>,
825              HdrNotSupportedVariant<ExternalDisplayVariant>,
826              NoPerFrameMetadataSupportVariant<ExternalDisplayVariant>>;
827 using SimpleTertiaryDisplayCase =
828         Case<TertiaryDisplayVariant, WideColorNotSupportedVariant<TertiaryDisplayVariant>,
829              HdrNotSupportedVariant<TertiaryDisplayVariant>,
830              NoPerFrameMetadataSupportVariant<TertiaryDisplayVariant>>;
831 using NonHwcVirtualDisplayCase =
832         Case<NonHwcVirtualDisplayVariant<1024, 768, Secure::FALSE>,
833              WideColorSupportNotConfiguredVariant, NonHwcDisplayHdrSupportVariant,
834              NonHwcPerFrameMetadataSupportVariant>;
835 using SimpleHwcVirtualDisplayVariant = HwcVirtualDisplayVariant<1024, 768, Secure::TRUE>;
836 using HwcVirtualDisplayCase =
837         Case<SimpleHwcVirtualDisplayVariant, WideColorSupportNotConfiguredVariant,
838              HdrNotSupportedVariant<SimpleHwcVirtualDisplayVariant>,
839              NoPerFrameMetadataSupportVariant<SimpleHwcVirtualDisplayVariant>>;
840 using WideColorP3ColorimetricDisplayCase =
841         Case<PrimaryDisplayVariant, WideColorP3ColorimetricSupportedVariant<PrimaryDisplayVariant>,
842              HdrNotSupportedVariant<PrimaryDisplayVariant>,
843              NoPerFrameMetadataSupportVariant<PrimaryDisplayVariant>>;
844 using Hdr10PlusDisplayCase =
845         Case<PrimaryDisplayVariant, WideColorNotSupportedVariant<PrimaryDisplayVariant>,
846              Hdr10SupportedVariant<PrimaryDisplayVariant>,
847              Hdr10_Plus_PerFrameMetadataSupportVariant<PrimaryDisplayVariant>>;
848 using Hdr10DisplayCase =
849         Case<PrimaryDisplayVariant, WideColorNotSupportedVariant<PrimaryDisplayVariant>,
850              Hdr10SupportedVariant<PrimaryDisplayVariant>,
851              NoPerFrameMetadataSupportVariant<PrimaryDisplayVariant>>;
852 using HdrHlgDisplayCase =
853         Case<PrimaryDisplayVariant, WideColorNotSupportedVariant<PrimaryDisplayVariant>,
854              HdrHlgSupportedVariant<PrimaryDisplayVariant>,
855              NoPerFrameMetadataSupportVariant<PrimaryDisplayVariant>>;
856 using HdrDolbyVisionDisplayCase =
857         Case<PrimaryDisplayVariant, WideColorNotSupportedVariant<PrimaryDisplayVariant>,
858              HdrDolbyVisionSupportedVariant<PrimaryDisplayVariant>,
859              NoPerFrameMetadataSupportVariant<PrimaryDisplayVariant>>;
860 using HdrSmpte2086DisplayCase =
861         Case<PrimaryDisplayVariant, WideColorNotSupportedVariant<PrimaryDisplayVariant>,
862              HdrNotSupportedVariant<PrimaryDisplayVariant>,
863              Smpte2086PerFrameMetadataSupportVariant<PrimaryDisplayVariant>>;
864 using HdrCta861_3_DisplayCase =
865         Case<PrimaryDisplayVariant, WideColorNotSupportedVariant<PrimaryDisplayVariant>,
866              HdrNotSupportedVariant<PrimaryDisplayVariant>,
867              Cta861_3_PerFrameMetadataSupportVariant<PrimaryDisplayVariant>>;
868 
869 /* ------------------------------------------------------------------------
870  *
871  * SurfaceFlinger::onHotplugReceived
872  */
873 
TEST_F(DisplayTransactionTest,hotplugEnqueuesEventsForDisplayTransaction)874 TEST_F(DisplayTransactionTest, hotplugEnqueuesEventsForDisplayTransaction) {
875     constexpr int currentSequenceId = 123;
876     constexpr hwc2_display_t hwcDisplayId1 = 456;
877     constexpr hwc2_display_t hwcDisplayId2 = 654;
878 
879     // --------------------------------------------------------------------
880     // Preconditions
881 
882     // Set the current sequence id for accepted events
883     mFlinger.mutableComposerSequenceId() = currentSequenceId;
884 
885     // Set the main thread id so that the current thread does not appear to be
886     // the main thread.
887     mFlinger.mutableMainThreadId() = std::thread::id();
888 
889     // --------------------------------------------------------------------
890     // Call Expectations
891 
892     // We expect invalidate() to be invoked once to trigger display transaction
893     // processing.
894     EXPECT_CALL(*mMessageQueue, invalidate()).Times(1);
895 
896     // --------------------------------------------------------------------
897     // Invocation
898 
899     // Simulate two hotplug events (a connect and a disconnect)
900     mFlinger.onHotplugReceived(currentSequenceId, hwcDisplayId1, HWC2::Connection::Connected);
901     mFlinger.onHotplugReceived(currentSequenceId, hwcDisplayId2, HWC2::Connection::Disconnected);
902 
903     // --------------------------------------------------------------------
904     // Postconditions
905 
906     // The display transaction needed flag should be set.
907     EXPECT_TRUE(hasTransactionFlagSet(eDisplayTransactionNeeded));
908 
909     // All events should be in the pending event queue.
910     const auto& pendingEvents = mFlinger.mutablePendingHotplugEvents();
911     ASSERT_EQ(2u, pendingEvents.size());
912     EXPECT_EQ(hwcDisplayId1, pendingEvents[0].hwcDisplayId);
913     EXPECT_EQ(HWC2::Connection::Connected, pendingEvents[0].connection);
914     EXPECT_EQ(hwcDisplayId2, pendingEvents[1].hwcDisplayId);
915     EXPECT_EQ(HWC2::Connection::Disconnected, pendingEvents[1].connection);
916 }
917 
TEST_F(DisplayTransactionTest,hotplugDiscardsUnexpectedEvents)918 TEST_F(DisplayTransactionTest, hotplugDiscardsUnexpectedEvents) {
919     constexpr int currentSequenceId = 123;
920     constexpr int otherSequenceId = 321;
921     constexpr hwc2_display_t displayId = 456;
922 
923     // --------------------------------------------------------------------
924     // Preconditions
925 
926     // Set the current sequence id for accepted events
927     mFlinger.mutableComposerSequenceId() = currentSequenceId;
928 
929     // Set the main thread id so that the current thread does not appear to be
930     // the main thread.
931     mFlinger.mutableMainThreadId() = std::thread::id();
932 
933     // --------------------------------------------------------------------
934     // Call Expectations
935 
936     // We do not expect any calls to invalidate().
937     EXPECT_CALL(*mMessageQueue, invalidate()).Times(0);
938 
939     // --------------------------------------------------------------------
940     // Invocation
941 
942     // Call with an unexpected sequence id
943     mFlinger.onHotplugReceived(otherSequenceId, displayId, HWC2::Connection::Invalid);
944 
945     // --------------------------------------------------------------------
946     // Postconditions
947 
948     // The display transaction needed flag should not be set
949     EXPECT_FALSE(hasTransactionFlagSet(eDisplayTransactionNeeded));
950 
951     // There should be no pending events
952     EXPECT_TRUE(mFlinger.mutablePendingHotplugEvents().empty());
953 }
954 
TEST_F(DisplayTransactionTest,hotplugProcessesEnqueuedEventsIfCalledOnMainThread)955 TEST_F(DisplayTransactionTest, hotplugProcessesEnqueuedEventsIfCalledOnMainThread) {
956     constexpr int currentSequenceId = 123;
957     constexpr hwc2_display_t displayId1 = 456;
958 
959     // --------------------------------------------------------------------
960     // Note:
961     // --------------------------------------------------------------------
962     // This test case is a bit tricky. We want to verify that
963     // onHotplugReceived() calls processDisplayHotplugEventsLocked(), but we
964     // don't really want to provide coverage for everything the later function
965     // does as there are specific tests for it.
966     // --------------------------------------------------------------------
967 
968     // --------------------------------------------------------------------
969     // Preconditions
970 
971     // Set the current sequence id for accepted events
972     mFlinger.mutableComposerSequenceId() = currentSequenceId;
973 
974     // Set the main thread id so that the current thread does appear to be the
975     // main thread.
976     mFlinger.mutableMainThreadId() = std::this_thread::get_id();
977 
978     // --------------------------------------------------------------------
979     // Call Expectations
980 
981     // We expect invalidate() to be invoked once to trigger display transaction
982     // processing.
983     EXPECT_CALL(*mMessageQueue, invalidate()).Times(1);
984 
985     // --------------------------------------------------------------------
986     // Invocation
987 
988     // Simulate a disconnect on a display id that is not connected. This should
989     // be enqueued by onHotplugReceived(), and dequeued by
990     // processDisplayHotplugEventsLocked(), but then ignored as invalid.
991     mFlinger.onHotplugReceived(currentSequenceId, displayId1, HWC2::Connection::Disconnected);
992 
993     // --------------------------------------------------------------------
994     // Postconditions
995 
996     // The display transaction needed flag should be set.
997     EXPECT_TRUE(hasTransactionFlagSet(eDisplayTransactionNeeded));
998 
999     // There should be no event queued on return, as it should have been
1000     // processed.
1001     EXPECT_TRUE(mFlinger.mutablePendingHotplugEvents().empty());
1002 }
1003 
1004 /* ------------------------------------------------------------------------
1005  * SurfaceFlinger::createDisplay
1006  */
1007 
TEST_F(DisplayTransactionTest,createDisplaySetsCurrentStateForNonsecureDisplay)1008 TEST_F(DisplayTransactionTest, createDisplaySetsCurrentStateForNonsecureDisplay) {
1009     const String8 name("virtual.test");
1010 
1011     // --------------------------------------------------------------------
1012     // Call Expectations
1013 
1014     // The call should notify the interceptor that a display was created.
1015     EXPECT_CALL(*mSurfaceInterceptor, saveDisplayCreation(_)).Times(1);
1016 
1017     // --------------------------------------------------------------------
1018     // Invocation
1019 
1020     sp<IBinder> displayToken = mFlinger.createDisplay(name, false);
1021 
1022     // --------------------------------------------------------------------
1023     // Postconditions
1024 
1025     // The display should have been added to the current state
1026     ASSERT_TRUE(hasCurrentDisplayState(displayToken));
1027     const auto& display = getCurrentDisplayState(displayToken);
1028     EXPECT_TRUE(display.isVirtual());
1029     EXPECT_FALSE(display.isSecure);
1030     EXPECT_EQ(name.string(), display.displayName);
1031 
1032     // --------------------------------------------------------------------
1033     // Cleanup conditions
1034 
1035     // Destroying the display invalidates the display state.
1036     EXPECT_CALL(*mMessageQueue, invalidate()).Times(1);
1037 }
1038 
TEST_F(DisplayTransactionTest,createDisplaySetsCurrentStateForSecureDisplay)1039 TEST_F(DisplayTransactionTest, createDisplaySetsCurrentStateForSecureDisplay) {
1040     const String8 name("virtual.test");
1041 
1042     // --------------------------------------------------------------------
1043     // Call Expectations
1044 
1045     // The call should notify the interceptor that a display was created.
1046     EXPECT_CALL(*mSurfaceInterceptor, saveDisplayCreation(_)).Times(1);
1047 
1048     // --------------------------------------------------------------------
1049     // Invocation
1050 
1051     sp<IBinder> displayToken = mFlinger.createDisplay(name, true);
1052 
1053     // --------------------------------------------------------------------
1054     // Postconditions
1055 
1056     // The display should have been added to the current state
1057     ASSERT_TRUE(hasCurrentDisplayState(displayToken));
1058     const auto& display = getCurrentDisplayState(displayToken);
1059     EXPECT_TRUE(display.isVirtual());
1060     EXPECT_TRUE(display.isSecure);
1061     EXPECT_EQ(name.string(), display.displayName);
1062 
1063     // --------------------------------------------------------------------
1064     // Cleanup conditions
1065 
1066     // Destroying the display invalidates the display state.
1067     EXPECT_CALL(*mMessageQueue, invalidate()).Times(1);
1068 }
1069 
1070 /* ------------------------------------------------------------------------
1071  * SurfaceFlinger::destroyDisplay
1072  */
1073 
TEST_F(DisplayTransactionTest,destroyDisplayClearsCurrentStateForDisplay)1074 TEST_F(DisplayTransactionTest, destroyDisplayClearsCurrentStateForDisplay) {
1075     using Case = NonHwcVirtualDisplayCase;
1076 
1077     // --------------------------------------------------------------------
1078     // Preconditions
1079 
1080     // A virtual display exists
1081     auto existing = Case::Display::makeFakeExistingDisplayInjector(this);
1082     existing.inject();
1083 
1084     // --------------------------------------------------------------------
1085     // Call Expectations
1086 
1087     // The call should notify the interceptor that a display was created.
1088     EXPECT_CALL(*mSurfaceInterceptor, saveDisplayDeletion(_)).Times(1);
1089 
1090     // Destroying the display invalidates the display state.
1091     EXPECT_CALL(*mMessageQueue, invalidate()).Times(1);
1092 
1093     // --------------------------------------------------------------------
1094     // Invocation
1095 
1096     mFlinger.destroyDisplay(existing.token());
1097 
1098     // --------------------------------------------------------------------
1099     // Postconditions
1100 
1101     // The display should have been removed from the current state
1102     EXPECT_FALSE(hasCurrentDisplayState(existing.token()));
1103 
1104     // Ths display should still exist in the drawing state
1105     EXPECT_TRUE(hasDrawingDisplayState(existing.token()));
1106 
1107     // The display transaction needed flasg should be set
1108     EXPECT_TRUE(hasTransactionFlagSet(eDisplayTransactionNeeded));
1109 }
1110 
TEST_F(DisplayTransactionTest,destroyDisplayHandlesUnknownDisplay)1111 TEST_F(DisplayTransactionTest, destroyDisplayHandlesUnknownDisplay) {
1112     // --------------------------------------------------------------------
1113     // Preconditions
1114 
1115     sp<BBinder> displayToken = new BBinder();
1116 
1117     // --------------------------------------------------------------------
1118     // Invocation
1119 
1120     mFlinger.destroyDisplay(displayToken);
1121 }
1122 
1123 /* ------------------------------------------------------------------------
1124  * SurfaceFlinger::resetDisplayState
1125  */
1126 
TEST_F(DisplayTransactionTest,resetDisplayStateClearsState)1127 TEST_F(DisplayTransactionTest, resetDisplayStateClearsState) {
1128     using Case = NonHwcVirtualDisplayCase;
1129 
1130     // --------------------------------------------------------------------
1131     // Preconditions
1132 
1133     // vsync is enabled and available
1134     mScheduler->mutablePrimaryHWVsyncEnabled() = true;
1135     mScheduler->mutableHWVsyncAvailable() = true;
1136 
1137     // A display exists
1138     auto existing = Case::Display::makeFakeExistingDisplayInjector(this);
1139     existing.inject();
1140 
1141     // --------------------------------------------------------------------
1142     // Call Expectations
1143 
1144     // The call disable vsyncs
1145     EXPECT_CALL(*mEventControlThread, setVsyncEnabled(false)).Times(1);
1146 
1147     // The call ends any display resyncs
1148     EXPECT_CALL(*mPrimaryDispSync, endResync()).Times(1);
1149 
1150     // --------------------------------------------------------------------
1151     // Invocation
1152 
1153     mFlinger.resetDisplayState();
1154 
1155     // --------------------------------------------------------------------
1156     // Postconditions
1157 
1158     // vsyncs should be off and not available.
1159     EXPECT_FALSE(mScheduler->mutablePrimaryHWVsyncEnabled());
1160     EXPECT_FALSE(mScheduler->mutableHWVsyncAvailable());
1161 
1162     // The display should have been removed from the display map.
1163     EXPECT_FALSE(hasDisplayDevice(existing.token()));
1164 
1165     // The display should still exist in the current state
1166     EXPECT_TRUE(hasCurrentDisplayState(existing.token()));
1167 
1168     // The display should have been removed from the drawing state
1169     EXPECT_FALSE(hasDrawingDisplayState(existing.token()));
1170 }
1171 
1172 /* ------------------------------------------------------------------------
1173  * DisplayDevice::GetBestColorMode
1174  */
1175 class GetBestColorModeTest : public DisplayTransactionTest {
1176 public:
1177     static constexpr DisplayId DEFAULT_DISPLAY_ID = DisplayId{777};
1178 
GetBestColorModeTest()1179     GetBestColorModeTest()
1180           : DisplayTransactionTest(),
1181             mInjector(FakeDisplayDeviceInjector(mFlinger, DEFAULT_DISPLAY_ID, false /* isVirtual */,
1182                                                 true /* isPrimary */)) {}
1183 
setHasWideColorGamut(bool hasWideColorGamut)1184     void setHasWideColorGamut(bool hasWideColorGamut) { mHasWideColorGamut = hasWideColorGamut; }
1185 
addHwcColorModesMapping(ui::ColorMode colorMode,std::vector<ui::RenderIntent> renderIntents)1186     void addHwcColorModesMapping(ui::ColorMode colorMode,
1187                                  std::vector<ui::RenderIntent> renderIntents) {
1188         mHwcColorModes[colorMode] = renderIntents;
1189     }
1190 
setInputDataspace(ui::Dataspace dataspace)1191     void setInputDataspace(ui::Dataspace dataspace) { mInputDataspace = dataspace; }
1192 
setInputRenderIntent(ui::RenderIntent renderIntent)1193     void setInputRenderIntent(ui::RenderIntent renderIntent) { mInputRenderIntent = renderIntent; }
1194 
getBestColorMode()1195     void getBestColorMode() {
1196         mInjector.setHwcColorModes(mHwcColorModes);
1197         mInjector.setHasWideColorGamut(mHasWideColorGamut);
1198         mInjector.setNativeWindow(mNativeWindow);
1199 
1200         // Creating a DisplayDevice requires getting default dimensions from the
1201         // native window.
1202         EXPECT_CALL(*mNativeWindow, query(NATIVE_WINDOW_WIDTH, _))
1203                 .WillRepeatedly(DoAll(SetArgPointee<1>(1080 /* arbitrary */), Return(0)));
1204         EXPECT_CALL(*mNativeWindow, query(NATIVE_WINDOW_HEIGHT, _))
1205                 .WillRepeatedly(DoAll(SetArgPointee<1>(1920 /* arbitrary */), Return(0)));
1206         EXPECT_CALL(*mNativeWindow, perform(NATIVE_WINDOW_SET_BUFFERS_FORMAT)).Times(1);
1207         EXPECT_CALL(*mNativeWindow, perform(NATIVE_WINDOW_API_CONNECT)).Times(1);
1208         EXPECT_CALL(*mNativeWindow, perform(NATIVE_WINDOW_SET_USAGE64)).Times(1);
1209         EXPECT_CALL(*mNativeWindow, perform(NATIVE_WINDOW_API_DISCONNECT)).Times(1);
1210         auto displayDevice = mInjector.inject();
1211 
1212         displayDevice->getCompositionDisplay()
1213                 ->getDisplayColorProfile()
1214                 ->getBestColorMode(mInputDataspace, mInputRenderIntent, &mOutDataspace,
1215                                    &mOutColorMode, &mOutRenderIntent);
1216     }
1217 
1218     ui::Dataspace mOutDataspace;
1219     ui::ColorMode mOutColorMode;
1220     ui::RenderIntent mOutRenderIntent;
1221 
1222 private:
1223     ui::Dataspace mInputDataspace;
1224     ui::RenderIntent mInputRenderIntent;
1225     bool mHasWideColorGamut = false;
1226     std::unordered_map<ui::ColorMode, std::vector<ui::RenderIntent>> mHwcColorModes;
1227     FakeDisplayDeviceInjector mInjector;
1228 };
1229 
TEST_F(GetBestColorModeTest,DataspaceDisplayP3_ColorModeSRGB)1230 TEST_F(GetBestColorModeTest, DataspaceDisplayP3_ColorModeSRGB) {
1231     addHwcColorModesMapping(ui::ColorMode::SRGB,
1232                             std::vector<ui::RenderIntent>(1, RenderIntent::COLORIMETRIC));
1233     setInputDataspace(ui::Dataspace::DISPLAY_P3);
1234     setInputRenderIntent(ui::RenderIntent::COLORIMETRIC);
1235     setHasWideColorGamut(true);
1236 
1237     getBestColorMode();
1238 
1239     ASSERT_EQ(ui::Dataspace::V0_SRGB, mOutDataspace);
1240     ASSERT_EQ(ui::ColorMode::SRGB, mOutColorMode);
1241     ASSERT_EQ(ui::RenderIntent::COLORIMETRIC, mOutRenderIntent);
1242 }
1243 
TEST_F(GetBestColorModeTest,DataspaceDisplayP3_ColorModeDisplayP3)1244 TEST_F(GetBestColorModeTest, DataspaceDisplayP3_ColorModeDisplayP3) {
1245     addHwcColorModesMapping(ui::ColorMode::DISPLAY_P3,
1246                             std::vector<ui::RenderIntent>(1, RenderIntent::COLORIMETRIC));
1247     addHwcColorModesMapping(ui::ColorMode::SRGB,
1248                             std::vector<ui::RenderIntent>(1, RenderIntent::COLORIMETRIC));
1249     addHwcColorModesMapping(ui::ColorMode::DISPLAY_BT2020,
1250                             std::vector<ui::RenderIntent>(1, RenderIntent::COLORIMETRIC));
1251     setInputDataspace(ui::Dataspace::DISPLAY_P3);
1252     setInputRenderIntent(ui::RenderIntent::COLORIMETRIC);
1253     setHasWideColorGamut(true);
1254 
1255     getBestColorMode();
1256 
1257     ASSERT_EQ(ui::Dataspace::DISPLAY_P3, mOutDataspace);
1258     ASSERT_EQ(ui::ColorMode::DISPLAY_P3, mOutColorMode);
1259     ASSERT_EQ(ui::RenderIntent::COLORIMETRIC, mOutRenderIntent);
1260 }
1261 
TEST_F(GetBestColorModeTest,DataspaceDisplayP3_ColorModeDISPLAY_BT2020)1262 TEST_F(GetBestColorModeTest, DataspaceDisplayP3_ColorModeDISPLAY_BT2020) {
1263     addHwcColorModesMapping(ui::ColorMode::DISPLAY_BT2020,
1264                             std::vector<ui::RenderIntent>(1, RenderIntent::COLORIMETRIC));
1265     setInputDataspace(ui::Dataspace::DISPLAY_P3);
1266     setInputRenderIntent(ui::RenderIntent::COLORIMETRIC);
1267     setHasWideColorGamut(true);
1268 
1269     getBestColorMode();
1270 
1271     ASSERT_EQ(ui::Dataspace::DISPLAY_BT2020, mOutDataspace);
1272     ASSERT_EQ(ui::ColorMode::DISPLAY_BT2020, mOutColorMode);
1273     ASSERT_EQ(ui::RenderIntent::COLORIMETRIC, mOutRenderIntent);
1274 }
1275 
1276 /* ------------------------------------------------------------------------
1277  * SurfaceFlinger::getDisplayNativePrimaries
1278  */
1279 
1280 class GetDisplayNativePrimaries : public DisplayTransactionTest {
1281 public:
1282     GetDisplayNativePrimaries();
1283     void populateDummyDisplayNativePrimaries(ui::DisplayPrimaries& primaries);
1284     void checkDummyDisplayNativePrimaries(const ui::DisplayPrimaries& primaries);
1285 
1286 private:
1287     static constexpr float mStartingTestValue = 1.0f;
1288 };
1289 
GetDisplayNativePrimaries()1290 GetDisplayNativePrimaries::GetDisplayNativePrimaries() {
1291     SimplePrimaryDisplayCase::Display::injectHwcDisplay(this);
1292     injectFakeNativeWindowSurfaceFactory();
1293 }
1294 
populateDummyDisplayNativePrimaries(ui::DisplayPrimaries & primaries)1295 void GetDisplayNativePrimaries::populateDummyDisplayNativePrimaries(
1296         ui::DisplayPrimaries& primaries) {
1297     float startingVal = mStartingTestValue;
1298     primaries.red.X = startingVal++;
1299     primaries.red.Y = startingVal++;
1300     primaries.red.Z = startingVal++;
1301     primaries.green.X = startingVal++;
1302     primaries.green.Y = startingVal++;
1303     primaries.green.Z = startingVal++;
1304     primaries.blue.X = startingVal++;
1305     primaries.blue.Y = startingVal++;
1306     primaries.blue.Z = startingVal++;
1307     primaries.white.X = startingVal++;
1308     primaries.white.Y = startingVal++;
1309     primaries.white.Z = startingVal++;
1310 }
1311 
checkDummyDisplayNativePrimaries(const ui::DisplayPrimaries & primaries)1312 void GetDisplayNativePrimaries::checkDummyDisplayNativePrimaries(
1313         const ui::DisplayPrimaries& primaries) {
1314     float startingVal = mStartingTestValue;
1315     EXPECT_EQ(primaries.red.X, startingVal++);
1316     EXPECT_EQ(primaries.red.Y, startingVal++);
1317     EXPECT_EQ(primaries.red.Z, startingVal++);
1318     EXPECT_EQ(primaries.green.X, startingVal++);
1319     EXPECT_EQ(primaries.green.Y, startingVal++);
1320     EXPECT_EQ(primaries.green.Z, startingVal++);
1321     EXPECT_EQ(primaries.blue.X, startingVal++);
1322     EXPECT_EQ(primaries.blue.Y, startingVal++);
1323     EXPECT_EQ(primaries.blue.Z, startingVal++);
1324     EXPECT_EQ(primaries.white.X, startingVal++);
1325     EXPECT_EQ(primaries.white.Y, startingVal++);
1326     EXPECT_EQ(primaries.white.Z, startingVal++);
1327 }
1328 
TEST_F(GetDisplayNativePrimaries,nullDisplayToken)1329 TEST_F(GetDisplayNativePrimaries, nullDisplayToken) {
1330     ui::DisplayPrimaries primaries;
1331     EXPECT_EQ(BAD_VALUE, mFlinger.getDisplayNativePrimaries(nullptr, primaries));
1332 }
1333 
TEST_F(GetDisplayNativePrimaries,internalDisplayWithPrimariesData)1334 TEST_F(GetDisplayNativePrimaries, internalDisplayWithPrimariesData) {
1335     auto injector = SimplePrimaryDisplayCase::Display::makeFakeExistingDisplayInjector(this);
1336     injector.inject();
1337     auto internalDisplayToken = injector.token();
1338 
1339     ui::DisplayPrimaries expectedPrimaries;
1340     populateDummyDisplayNativePrimaries(expectedPrimaries);
1341     mFlinger.setInternalDisplayPrimaries(expectedPrimaries);
1342 
1343     ui::DisplayPrimaries primaries;
1344     EXPECT_EQ(NO_ERROR, mFlinger.getDisplayNativePrimaries(internalDisplayToken, primaries));
1345 
1346     checkDummyDisplayNativePrimaries(primaries);
1347 }
1348 
TEST_F(GetDisplayNativePrimaries,notInternalDisplayToken)1349 TEST_F(GetDisplayNativePrimaries, notInternalDisplayToken) {
1350     sp<BBinder> notInternalDisplayToken = new BBinder();
1351 
1352     ui::DisplayPrimaries primaries;
1353     populateDummyDisplayNativePrimaries(primaries);
1354     EXPECT_EQ(BAD_VALUE, mFlinger.getDisplayNativePrimaries(notInternalDisplayToken, primaries));
1355 
1356     // Check primaries argument wasn't modified in case of failure
1357     checkDummyDisplayNativePrimaries(primaries);
1358 }
1359 
1360 /* ------------------------------------------------------------------------
1361  * SurfaceFlinger::setupNewDisplayDeviceInternal
1362  */
1363 
1364 class SetupNewDisplayDeviceInternalTest : public DisplayTransactionTest {
1365 public:
1366     template <typename T>
1367     void setupNewDisplayDeviceInternalTest();
1368 };
1369 
1370 template <typename Case>
setupNewDisplayDeviceInternalTest()1371 void SetupNewDisplayDeviceInternalTest::setupNewDisplayDeviceInternalTest() {
1372     const sp<BBinder> displayToken = new BBinder();
1373     const sp<compositionengine::mock::DisplaySurface> displaySurface =
1374             new compositionengine::mock::DisplaySurface();
1375     const sp<mock::GraphicBufferProducer> producer = new mock::GraphicBufferProducer();
1376 
1377     // --------------------------------------------------------------------
1378     // Preconditions
1379 
1380     // Wide color displays support is configured appropriately
1381     Case::WideColorSupport::injectConfigChange(this);
1382 
1383     // The display is setup with the HWC.
1384     Case::Display::injectHwcDisplay(this);
1385 
1386     // SurfaceFlinger will use a test-controlled factory for native window
1387     // surfaces.
1388     injectFakeNativeWindowSurfaceFactory();
1389 
1390     // --------------------------------------------------------------------
1391     // Call Expectations
1392 
1393     // Various native window calls will be made.
1394     Case::Display::setupNativeWindowSurfaceCreationCallExpectations(this);
1395     Case::Display::setupHwcGetActiveConfigCallExpectations(this);
1396     Case::WideColorSupport::setupComposerCallExpectations(this);
1397     Case::HdrSupport::setupComposerCallExpectations(this);
1398     Case::PerFrameMetadataSupport::setupComposerCallExpectations(this);
1399 
1400     // --------------------------------------------------------------------
1401     // Invocation
1402 
1403     DisplayDeviceState state;
1404     state.displayId = static_cast<bool>(Case::Display::VIRTUAL) ? std::nullopt
1405                                                                 : Case::Display::DISPLAY_ID::get();
1406     state.isSecure = static_cast<bool>(Case::Display::SECURE);
1407 
1408     auto device =
1409             mFlinger.setupNewDisplayDeviceInternal(displayToken, Case::Display::DISPLAY_ID::get(),
1410                                                    state, displaySurface, producer);
1411 
1412     // --------------------------------------------------------------------
1413     // Postconditions
1414 
1415     ASSERT_TRUE(device != nullptr);
1416     EXPECT_EQ(Case::Display::DISPLAY_ID::get(), device->getId());
1417     EXPECT_EQ(static_cast<bool>(Case::Display::VIRTUAL), device->isVirtual());
1418     EXPECT_EQ(static_cast<bool>(Case::Display::SECURE), device->isSecure());
1419     EXPECT_EQ(static_cast<bool>(Case::Display::PRIMARY), device->isPrimary());
1420     EXPECT_EQ(Case::Display::WIDTH, device->getWidth());
1421     EXPECT_EQ(Case::Display::HEIGHT, device->getHeight());
1422     EXPECT_EQ(Case::WideColorSupport::WIDE_COLOR_SUPPORTED, device->hasWideColorGamut());
1423     EXPECT_EQ(Case::HdrSupport::HDR10_PLUS_SUPPORTED, device->hasHDR10PlusSupport());
1424     EXPECT_EQ(Case::HdrSupport::HDR10_SUPPORTED, device->hasHDR10Support());
1425     EXPECT_EQ(Case::HdrSupport::HDR_HLG_SUPPORTED, device->hasHLGSupport());
1426     EXPECT_EQ(Case::HdrSupport::HDR_DOLBY_VISION_SUPPORTED, device->hasDolbyVisionSupport());
1427     // Note: This is not Case::Display::HWC_ACTIVE_CONFIG_ID as the ids are
1428     // remapped, and the test only ever sets up one config. If there were an error
1429     // looking up the remapped index, device->getActiveConfig() would be -1 instead.
1430     EXPECT_EQ(0, device->getActiveConfig());
1431     EXPECT_EQ(Case::PerFrameMetadataSupport::PER_FRAME_METADATA_KEYS,
1432               device->getSupportedPerFrameMetadata());
1433 }
1434 
TEST_F(SetupNewDisplayDeviceInternalTest,createSimplePrimaryDisplay)1435 TEST_F(SetupNewDisplayDeviceInternalTest, createSimplePrimaryDisplay) {
1436     setupNewDisplayDeviceInternalTest<SimplePrimaryDisplayCase>();
1437 }
1438 
TEST_F(SetupNewDisplayDeviceInternalTest,createSimpleExternalDisplay)1439 TEST_F(SetupNewDisplayDeviceInternalTest, createSimpleExternalDisplay) {
1440     setupNewDisplayDeviceInternalTest<SimpleExternalDisplayCase>();
1441 }
1442 
TEST_F(SetupNewDisplayDeviceInternalTest,createNonHwcVirtualDisplay)1443 TEST_F(SetupNewDisplayDeviceInternalTest, createNonHwcVirtualDisplay) {
1444     setupNewDisplayDeviceInternalTest<NonHwcVirtualDisplayCase>();
1445 }
1446 
TEST_F(SetupNewDisplayDeviceInternalTest,createHwcVirtualDisplay)1447 TEST_F(SetupNewDisplayDeviceInternalTest, createHwcVirtualDisplay) {
1448     using Case = HwcVirtualDisplayCase;
1449 
1450     // Insert display data so that the HWC thinks it created the virtual display.
1451     const auto displayId = Case::Display::DISPLAY_ID::get();
1452     ASSERT_TRUE(displayId);
1453     mFlinger.mutableHwcDisplayData().try_emplace(*displayId);
1454 
1455     setupNewDisplayDeviceInternalTest<Case>();
1456 }
1457 
TEST_F(SetupNewDisplayDeviceInternalTest,createWideColorP3Display)1458 TEST_F(SetupNewDisplayDeviceInternalTest, createWideColorP3Display) {
1459     setupNewDisplayDeviceInternalTest<WideColorP3ColorimetricDisplayCase>();
1460 }
1461 
TEST_F(SetupNewDisplayDeviceInternalTest,createHdr10PlusDisplay)1462 TEST_F(SetupNewDisplayDeviceInternalTest, createHdr10PlusDisplay) {
1463     setupNewDisplayDeviceInternalTest<Hdr10PlusDisplayCase>();
1464 }
1465 
TEST_F(SetupNewDisplayDeviceInternalTest,createHdr10Display)1466 TEST_F(SetupNewDisplayDeviceInternalTest, createHdr10Display) {
1467     setupNewDisplayDeviceInternalTest<Hdr10DisplayCase>();
1468 }
1469 
TEST_F(SetupNewDisplayDeviceInternalTest,createHdrHlgDisplay)1470 TEST_F(SetupNewDisplayDeviceInternalTest, createHdrHlgDisplay) {
1471     setupNewDisplayDeviceInternalTest<HdrHlgDisplayCase>();
1472 }
1473 
TEST_F(SetupNewDisplayDeviceInternalTest,createHdrDolbyVisionDisplay)1474 TEST_F(SetupNewDisplayDeviceInternalTest, createHdrDolbyVisionDisplay) {
1475     setupNewDisplayDeviceInternalTest<HdrDolbyVisionDisplayCase>();
1476 }
1477 
TEST_F(SetupNewDisplayDeviceInternalTest,createHdrSmpte2086DisplayCase)1478 TEST_F(SetupNewDisplayDeviceInternalTest, createHdrSmpte2086DisplayCase) {
1479     setupNewDisplayDeviceInternalTest<HdrSmpte2086DisplayCase>();
1480 }
1481 
TEST_F(SetupNewDisplayDeviceInternalTest,createHdrCta816_3_DisplayCase)1482 TEST_F(SetupNewDisplayDeviceInternalTest, createHdrCta816_3_DisplayCase) {
1483     setupNewDisplayDeviceInternalTest<HdrCta861_3_DisplayCase>();
1484 }
1485 
1486 /* ------------------------------------------------------------------------
1487  * SurfaceFlinger::handleTransactionLocked(eDisplayTransactionNeeded)
1488  */
1489 
1490 class HandleTransactionLockedTest : public DisplayTransactionTest {
1491 public:
1492     template <typename Case>
1493     void setupCommonPreconditions();
1494 
1495     template <typename Case, bool connected>
1496     static void expectHotplugReceived(mock::EventThread*);
1497 
1498     template <typename Case>
1499     void setupCommonCallExpectationsForConnectProcessing();
1500 
1501     template <typename Case>
1502     void setupCommonCallExpectationsForDisconnectProcessing();
1503 
1504     template <typename Case>
1505     void processesHotplugConnectCommon();
1506 
1507     template <typename Case>
1508     void ignoresHotplugConnectCommon();
1509 
1510     template <typename Case>
1511     void processesHotplugDisconnectCommon();
1512 
1513     template <typename Case>
1514     void verifyDisplayIsConnected(const sp<IBinder>& displayToken);
1515 
1516     template <typename Case>
1517     void verifyPhysicalDisplayIsConnected();
1518 
1519     void verifyDisplayIsNotConnected(const sp<IBinder>& displayToken);
1520 };
1521 
1522 template <typename Case>
setupCommonPreconditions()1523 void HandleTransactionLockedTest::setupCommonPreconditions() {
1524     // Wide color displays support is configured appropriately
1525     Case::WideColorSupport::injectConfigChange(this);
1526 
1527     // SurfaceFlinger will use a test-controlled factory for BufferQueues
1528     injectFakeBufferQueueFactory();
1529 
1530     // SurfaceFlinger will use a test-controlled factory for native window
1531     // surfaces.
1532     injectFakeNativeWindowSurfaceFactory();
1533 }
1534 
1535 template <typename Case, bool connected>
expectHotplugReceived(mock::EventThread * eventThread)1536 void HandleTransactionLockedTest::expectHotplugReceived(mock::EventThread* eventThread) {
1537     const auto convert = [](auto physicalDisplayId) {
1538         return std::make_optional(DisplayId{physicalDisplayId});
1539     };
1540 
1541     EXPECT_CALL(*eventThread,
1542                 onHotplugReceived(ResultOf(convert, Case::Display::DISPLAY_ID::get()), connected))
1543             .Times(1);
1544 }
1545 
1546 template <typename Case>
setupCommonCallExpectationsForConnectProcessing()1547 void HandleTransactionLockedTest::setupCommonCallExpectationsForConnectProcessing() {
1548     Case::Display::setupHwcHotplugCallExpectations(this);
1549 
1550     Case::Display::setupFramebufferConsumerBufferQueueCallExpectations(this);
1551     Case::Display::setupFramebufferProducerBufferQueueCallExpectations(this);
1552     Case::Display::setupNativeWindowSurfaceCreationCallExpectations(this);
1553     Case::Display::setupHwcGetActiveConfigCallExpectations(this);
1554 
1555     Case::WideColorSupport::setupComposerCallExpectations(this);
1556     Case::HdrSupport::setupComposerCallExpectations(this);
1557     Case::PerFrameMetadataSupport::setupComposerCallExpectations(this);
1558 
1559     EXPECT_CALL(*mSurfaceInterceptor, saveDisplayCreation(_)).Times(1);
1560     expectHotplugReceived<Case, true>(mEventThread);
1561     expectHotplugReceived<Case, true>(mSFEventThread);
1562 }
1563 
1564 template <typename Case>
setupCommonCallExpectationsForDisconnectProcessing()1565 void HandleTransactionLockedTest::setupCommonCallExpectationsForDisconnectProcessing() {
1566     EXPECT_CALL(*mSurfaceInterceptor, saveDisplayDeletion(_)).Times(1);
1567 
1568     expectHotplugReceived<Case, false>(mEventThread);
1569     expectHotplugReceived<Case, false>(mSFEventThread);
1570 }
1571 
1572 template <typename Case>
verifyDisplayIsConnected(const sp<IBinder> & displayToken)1573 void HandleTransactionLockedTest::verifyDisplayIsConnected(const sp<IBinder>& displayToken) {
1574     // The display device should have been set up in the list of displays.
1575     ASSERT_TRUE(hasDisplayDevice(displayToken));
1576     const auto& device = getDisplayDevice(displayToken);
1577     EXPECT_EQ(static_cast<bool>(Case::Display::SECURE), device->isSecure());
1578     EXPECT_EQ(static_cast<bool>(Case::Display::PRIMARY), device->isPrimary());
1579 
1580     // The display should have been set up in the current display state
1581     ASSERT_TRUE(hasCurrentDisplayState(displayToken));
1582     const auto& current = getCurrentDisplayState(displayToken);
1583     EXPECT_EQ(static_cast<bool>(Case::Display::VIRTUAL), current.isVirtual());
1584     EXPECT_EQ(static_cast<bool>(Case::Display::VIRTUAL) ? std::nullopt
1585                                                         : Case::Display::DISPLAY_ID::get(),
1586               current.displayId);
1587 
1588     // The display should have been set up in the drawing display state
1589     ASSERT_TRUE(hasDrawingDisplayState(displayToken));
1590     const auto& draw = getDrawingDisplayState(displayToken);
1591     EXPECT_EQ(static_cast<bool>(Case::Display::VIRTUAL), draw.isVirtual());
1592     EXPECT_EQ(static_cast<bool>(Case::Display::VIRTUAL) ? std::nullopt
1593                                                         : Case::Display::DISPLAY_ID::get(),
1594               draw.displayId);
1595 }
1596 
1597 template <typename Case>
verifyPhysicalDisplayIsConnected()1598 void HandleTransactionLockedTest::verifyPhysicalDisplayIsConnected() {
1599     // HWComposer should have an entry for the display
1600     EXPECT_TRUE(hasPhysicalHwcDisplay(Case::Display::HWC_DISPLAY_ID));
1601 
1602     // SF should have a display token.
1603     const auto displayId = Case::Display::DISPLAY_ID::get();
1604     ASSERT_TRUE(displayId);
1605     ASSERT_TRUE(mFlinger.mutablePhysicalDisplayTokens().count(*displayId) == 1);
1606     auto& displayToken = mFlinger.mutablePhysicalDisplayTokens()[*displayId];
1607 
1608     verifyDisplayIsConnected<Case>(displayToken);
1609 }
1610 
verifyDisplayIsNotConnected(const sp<IBinder> & displayToken)1611 void HandleTransactionLockedTest::verifyDisplayIsNotConnected(const sp<IBinder>& displayToken) {
1612     EXPECT_FALSE(hasDisplayDevice(displayToken));
1613     EXPECT_FALSE(hasCurrentDisplayState(displayToken));
1614     EXPECT_FALSE(hasDrawingDisplayState(displayToken));
1615 }
1616 
1617 template <typename Case>
processesHotplugConnectCommon()1618 void HandleTransactionLockedTest::processesHotplugConnectCommon() {
1619     // --------------------------------------------------------------------
1620     // Preconditions
1621 
1622     setupCommonPreconditions<Case>();
1623 
1624     // A hotplug connect event is enqueued for a display
1625     Case::Display::injectPendingHotplugEvent(this, HWC2::Connection::Connected);
1626 
1627     // --------------------------------------------------------------------
1628     // Call Expectations
1629 
1630     EXPECT_CALL(*mComposer, isUsingVrComposer()).WillOnce(Return(false));
1631 
1632     setupCommonCallExpectationsForConnectProcessing<Case>();
1633 
1634     // --------------------------------------------------------------------
1635     // Invocation
1636 
1637     mFlinger.handleTransactionLocked(eDisplayTransactionNeeded);
1638 
1639     // --------------------------------------------------------------------
1640     // Postconditions
1641 
1642     verifyPhysicalDisplayIsConnected<Case>();
1643 
1644     // --------------------------------------------------------------------
1645     // Cleanup conditions
1646 
1647     EXPECT_CALL(*mComposer,
1648                 setVsyncEnabled(Case::Display::HWC_DISPLAY_ID, IComposerClient::Vsync::DISABLE))
1649             .WillOnce(Return(Error::NONE));
1650     EXPECT_CALL(*mConsumer, consumerDisconnect()).WillOnce(Return(NO_ERROR));
1651 }
1652 
1653 template <typename Case>
ignoresHotplugConnectCommon()1654 void HandleTransactionLockedTest::ignoresHotplugConnectCommon() {
1655     // --------------------------------------------------------------------
1656     // Preconditions
1657 
1658     setupCommonPreconditions<Case>();
1659 
1660     // A hotplug connect event is enqueued for a display
1661     Case::Display::injectPendingHotplugEvent(this, HWC2::Connection::Connected);
1662 
1663     // --------------------------------------------------------------------
1664     // Invocation
1665 
1666     mFlinger.handleTransactionLocked(eDisplayTransactionNeeded);
1667 
1668     // --------------------------------------------------------------------
1669     // Postconditions
1670 
1671     // HWComposer should not have an entry for the display
1672     EXPECT_FALSE(hasPhysicalHwcDisplay(Case::Display::HWC_DISPLAY_ID));
1673 }
1674 
1675 template <typename Case>
processesHotplugDisconnectCommon()1676 void HandleTransactionLockedTest::processesHotplugDisconnectCommon() {
1677     // --------------------------------------------------------------------
1678     // Preconditions
1679 
1680     setupCommonPreconditions<Case>();
1681 
1682     // A hotplug disconnect event is enqueued for a display
1683     Case::Display::injectPendingHotplugEvent(this, HWC2::Connection::Disconnected);
1684 
1685     // The display is already completely set up.
1686     Case::Display::injectHwcDisplay(this);
1687     auto existing = Case::Display::makeFakeExistingDisplayInjector(this);
1688     existing.inject();
1689 
1690     // --------------------------------------------------------------------
1691     // Call Expectations
1692 
1693     EXPECT_CALL(*mComposer, isUsingVrComposer()).WillRepeatedly(Return(false));
1694     EXPECT_CALL(*mComposer, getDisplayIdentificationData(Case::Display::HWC_DISPLAY_ID, _, _))
1695             .Times(0);
1696 
1697     setupCommonCallExpectationsForDisconnectProcessing<Case>();
1698 
1699     // --------------------------------------------------------------------
1700     // Invocation
1701 
1702     mFlinger.handleTransactionLocked(eDisplayTransactionNeeded);
1703 
1704     // --------------------------------------------------------------------
1705     // Postconditions
1706 
1707     // HWComposer should not have an entry for the display
1708     EXPECT_FALSE(hasPhysicalHwcDisplay(Case::Display::HWC_DISPLAY_ID));
1709 
1710     // SF should not have a display token.
1711     const auto displayId = Case::Display::DISPLAY_ID::get();
1712     ASSERT_TRUE(displayId);
1713     ASSERT_TRUE(mFlinger.mutablePhysicalDisplayTokens().count(*displayId) == 0);
1714 
1715     // The existing token should have been removed
1716     verifyDisplayIsNotConnected(existing.token());
1717 }
1718 
TEST_F(HandleTransactionLockedTest,processesHotplugConnectPrimaryDisplay)1719 TEST_F(HandleTransactionLockedTest, processesHotplugConnectPrimaryDisplay) {
1720     processesHotplugConnectCommon<SimplePrimaryDisplayCase>();
1721 }
1722 
TEST_F(HandleTransactionLockedTest,processesHotplugConnectPrimaryDisplayWithExternalAlreadyConnected)1723 TEST_F(HandleTransactionLockedTest,
1724        processesHotplugConnectPrimaryDisplayWithExternalAlreadyConnected) {
1725     // Inject an external display.
1726     ExternalDisplayVariant::injectHwcDisplay(this);
1727 
1728     processesHotplugConnectCommon<SimplePrimaryDisplayCase>();
1729 }
1730 
TEST_F(HandleTransactionLockedTest,processesHotplugConnectExternalDisplay)1731 TEST_F(HandleTransactionLockedTest, processesHotplugConnectExternalDisplay) {
1732     // Inject a primary display.
1733     PrimaryDisplayVariant::injectHwcDisplay(this);
1734 
1735     processesHotplugConnectCommon<SimpleExternalDisplayCase>();
1736 }
1737 
TEST_F(HandleTransactionLockedTest,ignoresHotplugConnectIfPrimaryAndExternalAlreadyConnected)1738 TEST_F(HandleTransactionLockedTest, ignoresHotplugConnectIfPrimaryAndExternalAlreadyConnected) {
1739     // Inject both a primary and external display.
1740     PrimaryDisplayVariant::injectHwcDisplay(this);
1741     ExternalDisplayVariant::injectHwcDisplay(this);
1742 
1743     // TODO: This is an unnecessary call.
1744     EXPECT_CALL(*mComposer,
1745                 getDisplayIdentificationData(TertiaryDisplayVariant::HWC_DISPLAY_ID, _, _))
1746             .WillOnce(DoAll(SetArgPointee<1>(TertiaryDisplay::PORT),
1747                             SetArgPointee<2>(TertiaryDisplay::GET_IDENTIFICATION_DATA()),
1748                             Return(Error::NONE)));
1749 
1750     EXPECT_CALL(*mComposer, isUsingVrComposer()).WillRepeatedly(Return(false));
1751 
1752     ignoresHotplugConnectCommon<SimpleTertiaryDisplayCase>();
1753 }
1754 
TEST_F(HandleTransactionLockedTest,ignoresHotplugConnectIfExternalForVrComposer)1755 TEST_F(HandleTransactionLockedTest, ignoresHotplugConnectIfExternalForVrComposer) {
1756     // Inject a primary display.
1757     PrimaryDisplayVariant::injectHwcDisplay(this);
1758 
1759     EXPECT_CALL(*mComposer, isUsingVrComposer()).WillRepeatedly(Return(true));
1760 
1761     ignoresHotplugConnectCommon<SimpleExternalDisplayCase>();
1762 }
1763 
TEST_F(HandleTransactionLockedTest,processHotplugDisconnectPrimaryDisplay)1764 TEST_F(HandleTransactionLockedTest, processHotplugDisconnectPrimaryDisplay) {
1765     processesHotplugDisconnectCommon<SimplePrimaryDisplayCase>();
1766 }
1767 
TEST_F(HandleTransactionLockedTest,processHotplugDisconnectExternalDisplay)1768 TEST_F(HandleTransactionLockedTest, processHotplugDisconnectExternalDisplay) {
1769     processesHotplugDisconnectCommon<SimpleExternalDisplayCase>();
1770 }
1771 
TEST_F(HandleTransactionLockedTest,processesHotplugConnectThenDisconnectPrimary)1772 TEST_F(HandleTransactionLockedTest, processesHotplugConnectThenDisconnectPrimary) {
1773     using Case = SimplePrimaryDisplayCase;
1774 
1775     // --------------------------------------------------------------------
1776     // Preconditions
1777 
1778     setupCommonPreconditions<Case>();
1779 
1780     // A hotplug connect event is enqueued for a display
1781     Case::Display::injectPendingHotplugEvent(this, HWC2::Connection::Connected);
1782     // A hotplug disconnect event is also enqueued for the same display
1783     Case::Display::injectPendingHotplugEvent(this, HWC2::Connection::Disconnected);
1784 
1785     // --------------------------------------------------------------------
1786     // Call Expectations
1787 
1788     EXPECT_CALL(*mComposer, isUsingVrComposer()).WillRepeatedly(Return(false));
1789 
1790     setupCommonCallExpectationsForConnectProcessing<Case>();
1791     setupCommonCallExpectationsForDisconnectProcessing<Case>();
1792 
1793     EXPECT_CALL(*mComposer,
1794                 setVsyncEnabled(Case::Display::HWC_DISPLAY_ID, IComposerClient::Vsync::DISABLE))
1795             .WillOnce(Return(Error::NONE));
1796     EXPECT_CALL(*mConsumer, consumerDisconnect()).WillOnce(Return(NO_ERROR));
1797 
1798     // --------------------------------------------------------------------
1799     // Invocation
1800 
1801     mFlinger.handleTransactionLocked(eDisplayTransactionNeeded);
1802 
1803     // --------------------------------------------------------------------
1804     // Postconditions
1805 
1806     // HWComposer should not have an entry for the display
1807     EXPECT_FALSE(hasPhysicalHwcDisplay(Case::Display::HWC_DISPLAY_ID));
1808 
1809     // SF should not have a display token.
1810     const auto displayId = Case::Display::DISPLAY_ID::get();
1811     ASSERT_TRUE(displayId);
1812     ASSERT_TRUE(mFlinger.mutablePhysicalDisplayTokens().count(*displayId) == 0);
1813 }
1814 
TEST_F(HandleTransactionLockedTest,processesHotplugDisconnectThenConnectPrimary)1815 TEST_F(HandleTransactionLockedTest, processesHotplugDisconnectThenConnectPrimary) {
1816     using Case = SimplePrimaryDisplayCase;
1817 
1818     // --------------------------------------------------------------------
1819     // Preconditions
1820 
1821     setupCommonPreconditions<Case>();
1822 
1823     // The display is already completely set up.
1824     Case::Display::injectHwcDisplay(this);
1825     auto existing = Case::Display::makeFakeExistingDisplayInjector(this);
1826     existing.inject();
1827 
1828     // A hotplug disconnect event is enqueued for a display
1829     Case::Display::injectPendingHotplugEvent(this, HWC2::Connection::Disconnected);
1830     // A hotplug connect event is also enqueued for the same display
1831     Case::Display::injectPendingHotplugEvent(this, HWC2::Connection::Connected);
1832 
1833     // --------------------------------------------------------------------
1834     // Call Expectations
1835 
1836     EXPECT_CALL(*mComposer, isUsingVrComposer()).WillRepeatedly(Return(false));
1837 
1838     setupCommonCallExpectationsForConnectProcessing<Case>();
1839     setupCommonCallExpectationsForDisconnectProcessing<Case>();
1840 
1841     // --------------------------------------------------------------------
1842     // Invocation
1843 
1844     mFlinger.handleTransactionLocked(eDisplayTransactionNeeded);
1845 
1846     // --------------------------------------------------------------------
1847     // Postconditions
1848 
1849     // The existing token should have been removed
1850     verifyDisplayIsNotConnected(existing.token());
1851     const auto displayId = Case::Display::DISPLAY_ID::get();
1852     ASSERT_TRUE(displayId);
1853     ASSERT_TRUE(mFlinger.mutablePhysicalDisplayTokens().count(*displayId) == 1);
1854     EXPECT_NE(existing.token(), mFlinger.mutablePhysicalDisplayTokens()[*displayId]);
1855 
1856     // A new display should be connected in its place
1857 
1858     verifyPhysicalDisplayIsConnected<Case>();
1859 
1860     // --------------------------------------------------------------------
1861     // Cleanup conditions
1862 
1863     EXPECT_CALL(*mComposer,
1864                 setVsyncEnabled(Case::Display::HWC_DISPLAY_ID, IComposerClient::Vsync::DISABLE))
1865             .WillOnce(Return(Error::NONE));
1866     EXPECT_CALL(*mConsumer, consumerDisconnect()).WillOnce(Return(NO_ERROR));
1867 }
1868 
TEST_F(HandleTransactionLockedTest,processesVirtualDisplayAdded)1869 TEST_F(HandleTransactionLockedTest, processesVirtualDisplayAdded) {
1870     using Case = HwcVirtualDisplayCase;
1871 
1872     // --------------------------------------------------------------------
1873     // Preconditions
1874 
1875     // The HWC supports at least one virtual display
1876     injectMockComposer(1);
1877 
1878     setupCommonPreconditions<Case>();
1879 
1880     // A virtual display was added to the current state, and it has a
1881     // surface(producer)
1882     sp<BBinder> displayToken = new BBinder();
1883 
1884     DisplayDeviceState state;
1885     state.isSecure = static_cast<bool>(Case::Display::SECURE);
1886 
1887     sp<mock::GraphicBufferProducer> surface{new mock::GraphicBufferProducer()};
1888     state.surface = surface;
1889     mFlinger.mutableCurrentState().displays.add(displayToken, state);
1890 
1891     // --------------------------------------------------------------------
1892     // Call Expectations
1893 
1894     Case::Display::setupFramebufferConsumerBufferQueueCallExpectations(this);
1895     Case::Display::setupNativeWindowSurfaceCreationCallExpectations(this);
1896 
1897     EXPECT_CALL(*surface, query(NATIVE_WINDOW_WIDTH, _))
1898             .WillRepeatedly(DoAll(SetArgPointee<1>(Case::Display::WIDTH), Return(NO_ERROR)));
1899     EXPECT_CALL(*surface, query(NATIVE_WINDOW_HEIGHT, _))
1900             .WillRepeatedly(DoAll(SetArgPointee<1>(Case::Display::HEIGHT), Return(NO_ERROR)));
1901     EXPECT_CALL(*surface, query(NATIVE_WINDOW_FORMAT, _))
1902             .WillRepeatedly(DoAll(SetArgPointee<1>(DEFAULT_VIRTUAL_DISPLAY_SURFACE_FORMAT),
1903                                   Return(NO_ERROR)));
1904     EXPECT_CALL(*surface, query(NATIVE_WINDOW_CONSUMER_USAGE_BITS, _))
1905             .WillRepeatedly(DoAll(SetArgPointee<1>(0), Return(NO_ERROR)));
1906 
1907     EXPECT_CALL(*surface, setAsyncMode(true)).Times(1);
1908 
1909     EXPECT_CALL(*mProducer, connect(_, NATIVE_WINDOW_API_EGL, false, _)).Times(1);
1910     EXPECT_CALL(*mProducer, disconnect(_, _)).Times(1);
1911 
1912     Case::Display::setupHwcVirtualDisplayCreationCallExpectations(this);
1913     Case::WideColorSupport::setupComposerCallExpectations(this);
1914     Case::HdrSupport::setupComposerCallExpectations(this);
1915     Case::PerFrameMetadataSupport::setupComposerCallExpectations(this);
1916 
1917     // --------------------------------------------------------------------
1918     // Invocation
1919 
1920     mFlinger.handleTransactionLocked(eDisplayTransactionNeeded);
1921 
1922     // --------------------------------------------------------------------
1923     // Postconditions
1924 
1925     // The display device should have been set up in the list of displays.
1926     verifyDisplayIsConnected<Case>(displayToken);
1927 
1928     // --------------------------------------------------------------------
1929     // Cleanup conditions
1930 
1931     EXPECT_CALL(*mComposer, destroyVirtualDisplay(Case::Display::HWC_DISPLAY_ID))
1932             .WillOnce(Return(Error::NONE));
1933     EXPECT_CALL(*mConsumer, consumerDisconnect()).WillOnce(Return(NO_ERROR));
1934 
1935     // Cleanup
1936     mFlinger.mutableCurrentState().displays.removeItem(displayToken);
1937     mFlinger.mutableDrawingState().displays.removeItem(displayToken);
1938 }
1939 
TEST_F(HandleTransactionLockedTest,processesVirtualDisplayAddedWithNoSurface)1940 TEST_F(HandleTransactionLockedTest, processesVirtualDisplayAddedWithNoSurface) {
1941     using Case = HwcVirtualDisplayCase;
1942 
1943     // --------------------------------------------------------------------
1944     // Preconditions
1945 
1946     // The HWC supports at least one virtual display
1947     injectMockComposer(1);
1948 
1949     setupCommonPreconditions<Case>();
1950 
1951     // A virtual display was added to the current state, but it does not have a
1952     // surface.
1953     sp<BBinder> displayToken = new BBinder();
1954 
1955     DisplayDeviceState state;
1956     state.isSecure = static_cast<bool>(Case::Display::SECURE);
1957 
1958     mFlinger.mutableCurrentState().displays.add(displayToken, state);
1959 
1960     // --------------------------------------------------------------------
1961     // Call Expectations
1962 
1963     // --------------------------------------------------------------------
1964     // Invocation
1965 
1966     mFlinger.handleTransactionLocked(eDisplayTransactionNeeded);
1967 
1968     // --------------------------------------------------------------------
1969     // Postconditions
1970 
1971     // There will not be a display device set up.
1972     EXPECT_FALSE(hasDisplayDevice(displayToken));
1973 
1974     // The drawing display state will be set from the current display state.
1975     ASSERT_TRUE(hasDrawingDisplayState(displayToken));
1976     const auto& draw = getDrawingDisplayState(displayToken);
1977     EXPECT_EQ(static_cast<bool>(Case::Display::VIRTUAL), draw.isVirtual());
1978 }
1979 
TEST_F(HandleTransactionLockedTest,processesVirtualDisplayRemoval)1980 TEST_F(HandleTransactionLockedTest, processesVirtualDisplayRemoval) {
1981     using Case = HwcVirtualDisplayCase;
1982 
1983     // --------------------------------------------------------------------
1984     // Preconditions
1985 
1986     // A virtual display is set up but is removed from the current state.
1987     const auto displayId = Case::Display::DISPLAY_ID::get();
1988     ASSERT_TRUE(displayId);
1989     mFlinger.mutableHwcDisplayData().try_emplace(*displayId);
1990     Case::Display::injectHwcDisplay(this);
1991     auto existing = Case::Display::makeFakeExistingDisplayInjector(this);
1992     existing.inject();
1993     mFlinger.mutableCurrentState().displays.removeItem(existing.token());
1994 
1995     // --------------------------------------------------------------------
1996     // Call Expectations
1997 
1998     EXPECT_CALL(*mComposer, isUsingVrComposer()).WillRepeatedly(Return(false));
1999 
2000     // --------------------------------------------------------------------
2001     // Invocation
2002 
2003     mFlinger.handleTransactionLocked(eDisplayTransactionNeeded);
2004 
2005     // --------------------------------------------------------------------
2006     // Postconditions
2007 
2008     // The existing token should have been removed
2009     verifyDisplayIsNotConnected(existing.token());
2010 }
2011 
TEST_F(HandleTransactionLockedTest,processesDisplayLayerStackChanges)2012 TEST_F(HandleTransactionLockedTest, processesDisplayLayerStackChanges) {
2013     using Case = NonHwcVirtualDisplayCase;
2014 
2015     constexpr uint32_t oldLayerStack = 0u;
2016     constexpr uint32_t newLayerStack = 123u;
2017 
2018     // --------------------------------------------------------------------
2019     // Preconditions
2020 
2021     // A display is set up
2022     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
2023     display.inject();
2024 
2025     // There is a change to the layerStack state
2026     display.mutableDrawingDisplayState().layerStack = oldLayerStack;
2027     display.mutableCurrentDisplayState().layerStack = newLayerStack;
2028 
2029     // --------------------------------------------------------------------
2030     // Invocation
2031 
2032     mFlinger.handleTransactionLocked(eDisplayTransactionNeeded);
2033 
2034     // --------------------------------------------------------------------
2035     // Postconditions
2036 
2037     EXPECT_EQ(newLayerStack, display.mutableDisplayDevice()->getLayerStack());
2038 }
2039 
TEST_F(HandleTransactionLockedTest,processesDisplayTransformChanges)2040 TEST_F(HandleTransactionLockedTest, processesDisplayTransformChanges) {
2041     using Case = NonHwcVirtualDisplayCase;
2042 
2043     constexpr int oldTransform = 0;
2044     constexpr int newTransform = 2;
2045 
2046     // --------------------------------------------------------------------
2047     // Preconditions
2048 
2049     // A display is set up
2050     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
2051     display.inject();
2052 
2053     // There is a change to the orientation state
2054     display.mutableDrawingDisplayState().orientation = oldTransform;
2055     display.mutableCurrentDisplayState().orientation = newTransform;
2056 
2057     // --------------------------------------------------------------------
2058     // Invocation
2059 
2060     mFlinger.handleTransactionLocked(eDisplayTransactionNeeded);
2061 
2062     // --------------------------------------------------------------------
2063     // Postconditions
2064 
2065     EXPECT_EQ(newTransform, display.mutableDisplayDevice()->getOrientation());
2066 }
2067 
TEST_F(HandleTransactionLockedTest,processesDisplayViewportChanges)2068 TEST_F(HandleTransactionLockedTest, processesDisplayViewportChanges) {
2069     using Case = NonHwcVirtualDisplayCase;
2070 
2071     const Rect oldViewport(0, 0, 0, 0);
2072     const Rect newViewport(0, 0, 123, 456);
2073 
2074     // --------------------------------------------------------------------
2075     // Preconditions
2076 
2077     // A display is set up
2078     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
2079     display.inject();
2080 
2081     // There is a change to the viewport state
2082     display.mutableDrawingDisplayState().viewport = oldViewport;
2083     display.mutableCurrentDisplayState().viewport = newViewport;
2084 
2085     // --------------------------------------------------------------------
2086     // Invocation
2087 
2088     mFlinger.handleTransactionLocked(eDisplayTransactionNeeded);
2089 
2090     // --------------------------------------------------------------------
2091     // Postconditions
2092 
2093     EXPECT_EQ(newViewport, display.mutableDisplayDevice()->getViewport());
2094 }
2095 
TEST_F(HandleTransactionLockedTest,processesDisplayFrameChanges)2096 TEST_F(HandleTransactionLockedTest, processesDisplayFrameChanges) {
2097     using Case = NonHwcVirtualDisplayCase;
2098 
2099     const Rect oldFrame(0, 0, 0, 0);
2100     const Rect newFrame(0, 0, 123, 456);
2101 
2102     // --------------------------------------------------------------------
2103     // Preconditions
2104 
2105     // A display is set up
2106     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
2107     display.inject();
2108 
2109     // There is a change to the viewport state
2110     display.mutableDrawingDisplayState().frame = oldFrame;
2111     display.mutableCurrentDisplayState().frame = newFrame;
2112 
2113     // --------------------------------------------------------------------
2114     // Invocation
2115 
2116     mFlinger.handleTransactionLocked(eDisplayTransactionNeeded);
2117 
2118     // --------------------------------------------------------------------
2119     // Postconditions
2120 
2121     EXPECT_EQ(newFrame, display.mutableDisplayDevice()->getFrame());
2122 }
2123 
TEST_F(HandleTransactionLockedTest,processesDisplayWidthChanges)2124 TEST_F(HandleTransactionLockedTest, processesDisplayWidthChanges) {
2125     using Case = NonHwcVirtualDisplayCase;
2126 
2127     constexpr int oldWidth = 0;
2128     constexpr int oldHeight = 10;
2129     constexpr int newWidth = 123;
2130 
2131     // --------------------------------------------------------------------
2132     // Preconditions
2133 
2134     // A display is set up
2135     auto nativeWindow = new mock::NativeWindow();
2136     auto displaySurface = new compositionengine::mock::DisplaySurface();
2137     sp<GraphicBuffer> buf = new GraphicBuffer();
2138     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
2139     display.setNativeWindow(nativeWindow);
2140     display.setDisplaySurface(displaySurface);
2141     // Setup injection expections
2142     EXPECT_CALL(*nativeWindow, query(NATIVE_WINDOW_WIDTH, _))
2143             .WillOnce(DoAll(SetArgPointee<1>(oldWidth), Return(0)));
2144     EXPECT_CALL(*nativeWindow, query(NATIVE_WINDOW_HEIGHT, _))
2145             .WillOnce(DoAll(SetArgPointee<1>(oldHeight), Return(0)));
2146     EXPECT_CALL(*nativeWindow, perform(NATIVE_WINDOW_SET_BUFFERS_FORMAT)).Times(1);
2147     EXPECT_CALL(*nativeWindow, perform(NATIVE_WINDOW_API_CONNECT)).Times(1);
2148     EXPECT_CALL(*nativeWindow, perform(NATIVE_WINDOW_SET_USAGE64)).Times(1);
2149     EXPECT_CALL(*nativeWindow, perform(NATIVE_WINDOW_API_DISCONNECT)).Times(1);
2150     display.inject();
2151 
2152     // There is a change to the viewport state
2153     display.mutableDrawingDisplayState().width = oldWidth;
2154     display.mutableDrawingDisplayState().height = oldHeight;
2155     display.mutableCurrentDisplayState().width = newWidth;
2156     display.mutableCurrentDisplayState().height = oldHeight;
2157 
2158     // --------------------------------------------------------------------
2159     // Call Expectations
2160 
2161     EXPECT_CALL(*displaySurface, resizeBuffers(newWidth, oldHeight)).Times(1);
2162 
2163     // --------------------------------------------------------------------
2164     // Invocation
2165 
2166     mFlinger.handleTransactionLocked(eDisplayTransactionNeeded);
2167 }
2168 
TEST_F(HandleTransactionLockedTest,processesDisplayHeightChanges)2169 TEST_F(HandleTransactionLockedTest, processesDisplayHeightChanges) {
2170     using Case = NonHwcVirtualDisplayCase;
2171 
2172     constexpr int oldWidth = 0;
2173     constexpr int oldHeight = 10;
2174     constexpr int newHeight = 123;
2175 
2176     // --------------------------------------------------------------------
2177     // Preconditions
2178 
2179     // A display is set up
2180     auto nativeWindow = new mock::NativeWindow();
2181     auto displaySurface = new compositionengine::mock::DisplaySurface();
2182     sp<GraphicBuffer> buf = new GraphicBuffer();
2183     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
2184     display.setNativeWindow(nativeWindow);
2185     display.setDisplaySurface(displaySurface);
2186     // Setup injection expections
2187     EXPECT_CALL(*nativeWindow, query(NATIVE_WINDOW_WIDTH, _))
2188             .WillOnce(DoAll(SetArgPointee<1>(oldWidth), Return(0)));
2189     EXPECT_CALL(*nativeWindow, query(NATIVE_WINDOW_HEIGHT, _))
2190             .WillOnce(DoAll(SetArgPointee<1>(oldHeight), Return(0)));
2191     EXPECT_CALL(*nativeWindow, perform(NATIVE_WINDOW_SET_BUFFERS_FORMAT)).Times(1);
2192     EXPECT_CALL(*nativeWindow, perform(NATIVE_WINDOW_API_CONNECT)).Times(1);
2193     EXPECT_CALL(*nativeWindow, perform(NATIVE_WINDOW_SET_USAGE64)).Times(1);
2194     EXPECT_CALL(*nativeWindow, perform(NATIVE_WINDOW_API_DISCONNECT)).Times(1);
2195     display.inject();
2196 
2197     // There is a change to the viewport state
2198     display.mutableDrawingDisplayState().width = oldWidth;
2199     display.mutableDrawingDisplayState().height = oldHeight;
2200     display.mutableCurrentDisplayState().width = oldWidth;
2201     display.mutableCurrentDisplayState().height = newHeight;
2202 
2203     // --------------------------------------------------------------------
2204     // Call Expectations
2205 
2206     EXPECT_CALL(*displaySurface, resizeBuffers(oldWidth, newHeight)).Times(1);
2207 
2208     // --------------------------------------------------------------------
2209     // Invocation
2210 
2211     mFlinger.handleTransactionLocked(eDisplayTransactionNeeded);
2212 }
2213 
2214 /* ------------------------------------------------------------------------
2215  * SurfaceFlinger::setDisplayStateLocked
2216  */
2217 
TEST_F(DisplayTransactionTest,setDisplayStateLockedDoesNothingWithUnknownDisplay)2218 TEST_F(DisplayTransactionTest, setDisplayStateLockedDoesNothingWithUnknownDisplay) {
2219     // --------------------------------------------------------------------
2220     // Preconditions
2221 
2222     // We have an unknown display token not associated with a known display
2223     sp<BBinder> displayToken = new BBinder();
2224 
2225     // The requested display state references the unknown display.
2226     DisplayState state;
2227     state.what = DisplayState::eLayerStackChanged;
2228     state.token = displayToken;
2229     state.layerStack = 456;
2230 
2231     // --------------------------------------------------------------------
2232     // Invocation
2233 
2234     uint32_t flags = mFlinger.setDisplayStateLocked(state);
2235 
2236     // --------------------------------------------------------------------
2237     // Postconditions
2238 
2239     // The returned flags are empty
2240     EXPECT_EQ(0u, flags);
2241 
2242     // The display token still doesn't match anything known.
2243     EXPECT_FALSE(hasCurrentDisplayState(displayToken));
2244 }
2245 
TEST_F(DisplayTransactionTest,setDisplayStateLockedDoesNothingWhenNoChanges)2246 TEST_F(DisplayTransactionTest, setDisplayStateLockedDoesNothingWhenNoChanges) {
2247     using Case = SimplePrimaryDisplayCase;
2248 
2249     // --------------------------------------------------------------------
2250     // Preconditions
2251 
2252     // A display is already set up
2253     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
2254     display.inject();
2255 
2256     // No changes are made to the display
2257     DisplayState state;
2258     state.what = 0;
2259     state.token = display.token();
2260 
2261     // --------------------------------------------------------------------
2262     // Invocation
2263 
2264     uint32_t flags = mFlinger.setDisplayStateLocked(state);
2265 
2266     // --------------------------------------------------------------------
2267     // Postconditions
2268 
2269     // The returned flags are empty
2270     EXPECT_EQ(0u, flags);
2271 }
2272 
TEST_F(DisplayTransactionTest,setDisplayStateLockedDoesNothingIfSurfaceDidNotChange)2273 TEST_F(DisplayTransactionTest, setDisplayStateLockedDoesNothingIfSurfaceDidNotChange) {
2274     using Case = SimplePrimaryDisplayCase;
2275 
2276     // --------------------------------------------------------------------
2277     // Preconditions
2278 
2279     // A display is already set up
2280     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
2281     display.inject();
2282 
2283     // There is a surface that can be set.
2284     sp<mock::GraphicBufferProducer> surface = new mock::GraphicBufferProducer();
2285 
2286     // The current display state has the surface set
2287     display.mutableCurrentDisplayState().surface = surface;
2288 
2289     // The incoming request sets the same surface
2290     DisplayState state;
2291     state.what = DisplayState::eSurfaceChanged;
2292     state.token = display.token();
2293     state.surface = surface;
2294 
2295     // --------------------------------------------------------------------
2296     // Invocation
2297 
2298     uint32_t flags = mFlinger.setDisplayStateLocked(state);
2299 
2300     // --------------------------------------------------------------------
2301     // Postconditions
2302 
2303     // The returned flags are empty
2304     EXPECT_EQ(0u, flags);
2305 
2306     // The current display state is unchanged.
2307     EXPECT_EQ(surface.get(), display.getCurrentDisplayState().surface.get());
2308 }
2309 
TEST_F(DisplayTransactionTest,setDisplayStateLockedRequestsUpdateIfSurfaceChanged)2310 TEST_F(DisplayTransactionTest, setDisplayStateLockedRequestsUpdateIfSurfaceChanged) {
2311     using Case = SimplePrimaryDisplayCase;
2312 
2313     // --------------------------------------------------------------------
2314     // Preconditions
2315 
2316     // A display is already set up
2317     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
2318     display.inject();
2319 
2320     // There is a surface that can be set.
2321     sp<mock::GraphicBufferProducer> surface = new mock::GraphicBufferProducer();
2322 
2323     // The current display state does not have a surface
2324     display.mutableCurrentDisplayState().surface = nullptr;
2325 
2326     // The incoming request sets a surface
2327     DisplayState state;
2328     state.what = DisplayState::eSurfaceChanged;
2329     state.token = display.token();
2330     state.surface = surface;
2331 
2332     // --------------------------------------------------------------------
2333     // Invocation
2334 
2335     uint32_t flags = mFlinger.setDisplayStateLocked(state);
2336 
2337     // --------------------------------------------------------------------
2338     // Postconditions
2339 
2340     // The returned flags indicate a transaction is needed
2341     EXPECT_EQ(eDisplayTransactionNeeded, flags);
2342 
2343     // The current display layer stack state is set to the new value
2344     EXPECT_EQ(surface.get(), display.getCurrentDisplayState().surface.get());
2345 }
2346 
TEST_F(DisplayTransactionTest,setDisplayStateLockedDoesNothingIfLayerStackDidNotChange)2347 TEST_F(DisplayTransactionTest, setDisplayStateLockedDoesNothingIfLayerStackDidNotChange) {
2348     using Case = SimplePrimaryDisplayCase;
2349 
2350     // --------------------------------------------------------------------
2351     // Preconditions
2352 
2353     // A display is already set up
2354     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
2355     display.inject();
2356 
2357     // The display has a layer stack set
2358     display.mutableCurrentDisplayState().layerStack = 456u;
2359 
2360     // The incoming request sets the same layer stack
2361     DisplayState state;
2362     state.what = DisplayState::eLayerStackChanged;
2363     state.token = display.token();
2364     state.layerStack = 456u;
2365 
2366     // --------------------------------------------------------------------
2367     // Invocation
2368 
2369     uint32_t flags = mFlinger.setDisplayStateLocked(state);
2370 
2371     // --------------------------------------------------------------------
2372     // Postconditions
2373 
2374     // The returned flags are empty
2375     EXPECT_EQ(0u, flags);
2376 
2377     // The current display state is unchanged
2378     EXPECT_EQ(456u, display.getCurrentDisplayState().layerStack);
2379 }
2380 
TEST_F(DisplayTransactionTest,setDisplayStateLockedRequestsUpdateIfLayerStackChanged)2381 TEST_F(DisplayTransactionTest, setDisplayStateLockedRequestsUpdateIfLayerStackChanged) {
2382     using Case = SimplePrimaryDisplayCase;
2383 
2384     // --------------------------------------------------------------------
2385     // Preconditions
2386 
2387     // A display is set up
2388     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
2389     display.inject();
2390 
2391     // The display has a layer stack set
2392     display.mutableCurrentDisplayState().layerStack = 654u;
2393 
2394     // The incoming request sets a different layer stack
2395     DisplayState state;
2396     state.what = DisplayState::eLayerStackChanged;
2397     state.token = display.token();
2398     state.layerStack = 456u;
2399 
2400     // --------------------------------------------------------------------
2401     // Invocation
2402 
2403     uint32_t flags = mFlinger.setDisplayStateLocked(state);
2404 
2405     // --------------------------------------------------------------------
2406     // Postconditions
2407 
2408     // The returned flags indicate a transaction is needed
2409     EXPECT_EQ(eDisplayTransactionNeeded, flags);
2410 
2411     // The desired display state has been set to the new value.
2412     EXPECT_EQ(456u, display.getCurrentDisplayState().layerStack);
2413 }
2414 
TEST_F(DisplayTransactionTest,setDisplayStateLockedDoesNothingIfProjectionDidNotChange)2415 TEST_F(DisplayTransactionTest, setDisplayStateLockedDoesNothingIfProjectionDidNotChange) {
2416     using Case = SimplePrimaryDisplayCase;
2417     constexpr int initialOrientation = 180;
2418     const Rect initialFrame = {1, 2, 3, 4};
2419     const Rect initialViewport = {5, 6, 7, 8};
2420 
2421     // --------------------------------------------------------------------
2422     // Preconditions
2423 
2424     // A display is set up
2425     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
2426     display.inject();
2427 
2428     // The current display state projection state is all set
2429     display.mutableCurrentDisplayState().orientation = initialOrientation;
2430     display.mutableCurrentDisplayState().frame = initialFrame;
2431     display.mutableCurrentDisplayState().viewport = initialViewport;
2432 
2433     // The incoming request sets the same projection state
2434     DisplayState state;
2435     state.what = DisplayState::eDisplayProjectionChanged;
2436     state.token = display.token();
2437     state.orientation = initialOrientation;
2438     state.frame = initialFrame;
2439     state.viewport = initialViewport;
2440 
2441     // --------------------------------------------------------------------
2442     // Invocation
2443 
2444     uint32_t flags = mFlinger.setDisplayStateLocked(state);
2445 
2446     // --------------------------------------------------------------------
2447     // Postconditions
2448 
2449     // The returned flags are empty
2450     EXPECT_EQ(0u, flags);
2451 
2452     // The current display state is unchanged
2453     EXPECT_EQ(initialOrientation, display.getCurrentDisplayState().orientation);
2454 
2455     EXPECT_EQ(initialFrame, display.getCurrentDisplayState().frame);
2456     EXPECT_EQ(initialViewport, display.getCurrentDisplayState().viewport);
2457 }
2458 
TEST_F(DisplayTransactionTest,setDisplayStateLockedRequestsUpdateIfOrientationChanged)2459 TEST_F(DisplayTransactionTest, setDisplayStateLockedRequestsUpdateIfOrientationChanged) {
2460     using Case = SimplePrimaryDisplayCase;
2461     constexpr int initialOrientation = 90;
2462     constexpr int desiredOrientation = 180;
2463 
2464     // --------------------------------------------------------------------
2465     // Preconditions
2466 
2467     // A display is set up
2468     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
2469     display.inject();
2470 
2471     // The current display state has an orientation set
2472     display.mutableCurrentDisplayState().orientation = initialOrientation;
2473 
2474     // The incoming request sets a different orientation
2475     DisplayState state;
2476     state.what = DisplayState::eDisplayProjectionChanged;
2477     state.token = display.token();
2478     state.orientation = desiredOrientation;
2479 
2480     // --------------------------------------------------------------------
2481     // Invocation
2482 
2483     uint32_t flags = mFlinger.setDisplayStateLocked(state);
2484 
2485     // --------------------------------------------------------------------
2486     // Postconditions
2487 
2488     // The returned flags indicate a transaction is needed
2489     EXPECT_EQ(eDisplayTransactionNeeded, flags);
2490 
2491     // The current display state has the new value.
2492     EXPECT_EQ(desiredOrientation, display.getCurrentDisplayState().orientation);
2493 }
2494 
TEST_F(DisplayTransactionTest,setDisplayStateLockedRequestsUpdateIfFrameChanged)2495 TEST_F(DisplayTransactionTest, setDisplayStateLockedRequestsUpdateIfFrameChanged) {
2496     using Case = SimplePrimaryDisplayCase;
2497     const Rect initialFrame = {0, 0, 0, 0};
2498     const Rect desiredFrame = {5, 6, 7, 8};
2499 
2500     // --------------------------------------------------------------------
2501     // Preconditions
2502 
2503     // A display is set up
2504     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
2505     display.inject();
2506 
2507     // The current display state does not have a frame
2508     display.mutableCurrentDisplayState().frame = initialFrame;
2509 
2510     // The incoming request sets a frame
2511     DisplayState state;
2512     state.what = DisplayState::eDisplayProjectionChanged;
2513     state.token = display.token();
2514     state.frame = desiredFrame;
2515 
2516     // --------------------------------------------------------------------
2517     // Invocation
2518 
2519     uint32_t flags = mFlinger.setDisplayStateLocked(state);
2520 
2521     // --------------------------------------------------------------------
2522     // Postconditions
2523 
2524     // The returned flags indicate a transaction is needed
2525     EXPECT_EQ(eDisplayTransactionNeeded, flags);
2526 
2527     // The current display state has the new value.
2528     EXPECT_EQ(desiredFrame, display.getCurrentDisplayState().frame);
2529 }
2530 
TEST_F(DisplayTransactionTest,setDisplayStateLockedRequestsUpdateIfViewportChanged)2531 TEST_F(DisplayTransactionTest, setDisplayStateLockedRequestsUpdateIfViewportChanged) {
2532     using Case = SimplePrimaryDisplayCase;
2533     const Rect initialViewport = {0, 0, 0, 0};
2534     const Rect desiredViewport = {5, 6, 7, 8};
2535 
2536     // --------------------------------------------------------------------
2537     // Preconditions
2538 
2539     // A display is set up
2540     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
2541     display.inject();
2542 
2543     // The current display state does not have a viewport
2544     display.mutableCurrentDisplayState().viewport = initialViewport;
2545 
2546     // The incoming request sets a viewport
2547     DisplayState state;
2548     state.what = DisplayState::eDisplayProjectionChanged;
2549     state.token = display.token();
2550     state.viewport = desiredViewport;
2551 
2552     // --------------------------------------------------------------------
2553     // Invocation
2554 
2555     uint32_t flags = mFlinger.setDisplayStateLocked(state);
2556 
2557     // --------------------------------------------------------------------
2558     // Postconditions
2559 
2560     // The returned flags indicate a transaction is needed
2561     EXPECT_EQ(eDisplayTransactionNeeded, flags);
2562 
2563     // The current display state has the new value.
2564     EXPECT_EQ(desiredViewport, display.getCurrentDisplayState().viewport);
2565 }
2566 
TEST_F(DisplayTransactionTest,setDisplayStateLockedDoesNothingIfSizeDidNotChange)2567 TEST_F(DisplayTransactionTest, setDisplayStateLockedDoesNothingIfSizeDidNotChange) {
2568     using Case = SimplePrimaryDisplayCase;
2569     constexpr uint32_t initialWidth = 1024;
2570     constexpr uint32_t initialHeight = 768;
2571 
2572     // --------------------------------------------------------------------
2573     // Preconditions
2574 
2575     // A display is set up
2576     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
2577     display.inject();
2578 
2579     // The current display state has a size set
2580     display.mutableCurrentDisplayState().width = initialWidth;
2581     display.mutableCurrentDisplayState().height = initialHeight;
2582 
2583     // The incoming request sets the same display size
2584     DisplayState state;
2585     state.what = DisplayState::eDisplaySizeChanged;
2586     state.token = display.token();
2587     state.width = initialWidth;
2588     state.height = initialHeight;
2589 
2590     // --------------------------------------------------------------------
2591     // Invocation
2592 
2593     uint32_t flags = mFlinger.setDisplayStateLocked(state);
2594 
2595     // --------------------------------------------------------------------
2596     // Postconditions
2597 
2598     // The returned flags are empty
2599     EXPECT_EQ(0u, flags);
2600 
2601     // The current display state is unchanged
2602     EXPECT_EQ(initialWidth, display.getCurrentDisplayState().width);
2603     EXPECT_EQ(initialHeight, display.getCurrentDisplayState().height);
2604 }
2605 
TEST_F(DisplayTransactionTest,setDisplayStateLockedRequestsUpdateIfWidthChanged)2606 TEST_F(DisplayTransactionTest, setDisplayStateLockedRequestsUpdateIfWidthChanged) {
2607     using Case = SimplePrimaryDisplayCase;
2608     constexpr uint32_t initialWidth = 0;
2609     constexpr uint32_t desiredWidth = 1024;
2610 
2611     // --------------------------------------------------------------------
2612     // Preconditions
2613 
2614     // A display is set up
2615     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
2616     display.inject();
2617 
2618     // The display does not yet have a width
2619     display.mutableCurrentDisplayState().width = initialWidth;
2620 
2621     // The incoming request sets a display width
2622     DisplayState state;
2623     state.what = DisplayState::eDisplaySizeChanged;
2624     state.token = display.token();
2625     state.width = desiredWidth;
2626 
2627     // --------------------------------------------------------------------
2628     // Invocation
2629 
2630     uint32_t flags = mFlinger.setDisplayStateLocked(state);
2631 
2632     // --------------------------------------------------------------------
2633     // Postconditions
2634 
2635     // The returned flags indicate a transaction is needed
2636     EXPECT_EQ(eDisplayTransactionNeeded, flags);
2637 
2638     // The current display state has the new value.
2639     EXPECT_EQ(desiredWidth, display.getCurrentDisplayState().width);
2640 }
2641 
TEST_F(DisplayTransactionTest,setDisplayStateLockedRequestsUpdateIfHeightChanged)2642 TEST_F(DisplayTransactionTest, setDisplayStateLockedRequestsUpdateIfHeightChanged) {
2643     using Case = SimplePrimaryDisplayCase;
2644     constexpr uint32_t initialHeight = 0;
2645     constexpr uint32_t desiredHeight = 768;
2646 
2647     // --------------------------------------------------------------------
2648     // Preconditions
2649 
2650     // A display is set up
2651     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
2652     display.inject();
2653 
2654     // The display does not yet have a height
2655     display.mutableCurrentDisplayState().height = initialHeight;
2656 
2657     // The incoming request sets a display height
2658     DisplayState state;
2659     state.what = DisplayState::eDisplaySizeChanged;
2660     state.token = display.token();
2661     state.height = desiredHeight;
2662 
2663     // --------------------------------------------------------------------
2664     // Invocation
2665 
2666     uint32_t flags = mFlinger.setDisplayStateLocked(state);
2667 
2668     // --------------------------------------------------------------------
2669     // Postconditions
2670 
2671     // The returned flags indicate a transaction is needed
2672     EXPECT_EQ(eDisplayTransactionNeeded, flags);
2673 
2674     // The current display state has the new value.
2675     EXPECT_EQ(desiredHeight, display.getCurrentDisplayState().height);
2676 }
2677 
2678 /* ------------------------------------------------------------------------
2679  * SurfaceFlinger::onInitializeDisplays
2680  */
2681 
TEST_F(DisplayTransactionTest,onInitializeDisplaysSetsUpPrimaryDisplay)2682 TEST_F(DisplayTransactionTest, onInitializeDisplaysSetsUpPrimaryDisplay) {
2683     using Case = SimplePrimaryDisplayCase;
2684 
2685     // --------------------------------------------------------------------
2686     // Preconditions
2687 
2688     // A primary display is set up
2689     Case::Display::injectHwcDisplay(this);
2690     auto primaryDisplay = Case::Display::makeFakeExistingDisplayInjector(this);
2691     primaryDisplay.inject();
2692 
2693     // --------------------------------------------------------------------
2694     // Call Expectations
2695 
2696     // We expect the surface interceptor to possibly be used, but we treat it as
2697     // disabled since it is called as a side effect rather than directly by this
2698     // function.
2699     EXPECT_CALL(*mSurfaceInterceptor, isEnabled()).WillOnce(Return(false));
2700 
2701     // We expect a call to get the active display config.
2702     Case::Display::setupHwcGetActiveConfigCallExpectations(this);
2703 
2704     // We expect invalidate() to be invoked once to trigger display transaction
2705     // processing.
2706     EXPECT_CALL(*mMessageQueue, invalidate()).Times(1);
2707 
2708     EXPECT_CALL(*mPrimaryDispSync, expectedPresentTime()).WillRepeatedly(Return(0));
2709 
2710     // --------------------------------------------------------------------
2711     // Invocation
2712 
2713     mFlinger.onInitializeDisplays();
2714 
2715     // --------------------------------------------------------------------
2716     // Postconditions
2717 
2718     // The primary display should have a current state
2719     ASSERT_TRUE(hasCurrentDisplayState(primaryDisplay.token()));
2720     const auto& primaryDisplayState = getCurrentDisplayState(primaryDisplay.token());
2721     // The layer stack state should be set to zero
2722     EXPECT_EQ(0u, primaryDisplayState.layerStack);
2723     // The orientation state should be set to zero
2724     EXPECT_EQ(0, primaryDisplayState.orientation);
2725 
2726     // The frame state should be set to INVALID
2727     EXPECT_EQ(Rect::INVALID_RECT, primaryDisplayState.frame);
2728 
2729     // The viewport state should be set to INVALID
2730     EXPECT_EQ(Rect::INVALID_RECT, primaryDisplayState.viewport);
2731 
2732     // The width and height should both be zero
2733     EXPECT_EQ(0u, primaryDisplayState.width);
2734     EXPECT_EQ(0u, primaryDisplayState.height);
2735 
2736     // The display should be set to HWC_POWER_MODE_NORMAL
2737     ASSERT_TRUE(hasDisplayDevice(primaryDisplay.token()));
2738     auto displayDevice = primaryDisplay.mutableDisplayDevice();
2739     EXPECT_EQ(HWC_POWER_MODE_NORMAL, displayDevice->getPowerMode());
2740 
2741     // The display refresh period should be set in the frame tracker.
2742     FrameStats stats;
2743     mFlinger.getAnimFrameTracker().getStats(&stats);
2744     EXPECT_EQ(DEFAULT_REFRESH_RATE, stats.refreshPeriodNano);
2745 
2746     // The display transaction needed flag should be set.
2747     EXPECT_TRUE(hasTransactionFlagSet(eDisplayTransactionNeeded));
2748 
2749     // The compositor timing should be set to default values
2750     const auto& compositorTiming = mFlinger.getCompositorTiming();
2751     EXPECT_EQ(-DEFAULT_REFRESH_RATE, compositorTiming.deadline);
2752     EXPECT_EQ(DEFAULT_REFRESH_RATE, compositorTiming.interval);
2753     EXPECT_EQ(DEFAULT_REFRESH_RATE, compositorTiming.presentLatency);
2754 }
2755 
2756 /* ------------------------------------------------------------------------
2757  * SurfaceFlinger::setPowerModeInternal
2758  */
2759 
2760 // Used when we simulate a display that supports doze.
2761 template <typename Display>
2762 struct DozeIsSupportedVariant {
2763     static constexpr bool DOZE_SUPPORTED = true;
2764     static constexpr IComposerClient::PowerMode ACTUAL_POWER_MODE_FOR_DOZE =
2765             IComposerClient::PowerMode::DOZE;
2766     static constexpr IComposerClient::PowerMode ACTUAL_POWER_MODE_FOR_DOZE_SUSPEND =
2767             IComposerClient::PowerMode::DOZE_SUSPEND;
2768 
setupComposerCallExpectationsandroid::__anon968546880111::DozeIsSupportedVariant2769     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
2770         EXPECT_CALL(*test->mComposer, getDisplayCapabilities(Display::HWC_DISPLAY_ID, _))
2771                 .WillOnce(DoAll(SetArgPointee<1>(std::vector<Hwc2::DisplayCapability>(
2772                                         {Hwc2::DisplayCapability::DOZE})),
2773                                 Return(Error::NONE)));
2774     }
2775 };
2776 
2777 template <typename Display>
2778 // Used when we simulate a display that does not support doze.
2779 struct DozeNotSupportedVariant {
2780     static constexpr bool DOZE_SUPPORTED = false;
2781     static constexpr IComposerClient::PowerMode ACTUAL_POWER_MODE_FOR_DOZE =
2782             IComposerClient::PowerMode::ON;
2783     static constexpr IComposerClient::PowerMode ACTUAL_POWER_MODE_FOR_DOZE_SUSPEND =
2784             IComposerClient::PowerMode::ON;
2785 
setupComposerCallExpectationsandroid::__anon968546880111::DozeNotSupportedVariant2786     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
2787         EXPECT_CALL(*test->mComposer, getDisplayCapabilities(Display::HWC_DISPLAY_ID, _))
2788                 .WillOnce(DoAll(SetArgPointee<1>(std::vector<Hwc2::DisplayCapability>({})),
2789                                 Return(Error::NONE)));
2790     }
2791 };
2792 
2793 struct EventThreadBaseSupportedVariant {
setupEventAndEventControlThreadNoCallExpectationsandroid::__anon968546880111::EventThreadBaseSupportedVariant2794     static void setupEventAndEventControlThreadNoCallExpectations(DisplayTransactionTest* test) {
2795         // The event control thread should not be notified.
2796         EXPECT_CALL(*test->mEventControlThread, setVsyncEnabled(_)).Times(0);
2797 
2798         // The event thread should not be notified.
2799         EXPECT_CALL(*test->mEventThread, onScreenReleased()).Times(0);
2800         EXPECT_CALL(*test->mEventThread, onScreenAcquired()).Times(0);
2801     }
2802 };
2803 
2804 struct EventThreadNotSupportedVariant : public EventThreadBaseSupportedVariant {
setupAcquireAndEnableVsyncCallExpectationsandroid::__anon968546880111::EventThreadNotSupportedVariant2805     static void setupAcquireAndEnableVsyncCallExpectations(DisplayTransactionTest* test) {
2806         // These calls are only expected for the primary display.
2807 
2808         // Instead expect no calls.
2809         setupEventAndEventControlThreadNoCallExpectations(test);
2810     }
2811 
setupReleaseAndDisableVsyncCallExpectationsandroid::__anon968546880111::EventThreadNotSupportedVariant2812     static void setupReleaseAndDisableVsyncCallExpectations(DisplayTransactionTest* test) {
2813         // These calls are only expected for the primary display.
2814 
2815         // Instead expect no calls.
2816         setupEventAndEventControlThreadNoCallExpectations(test);
2817     }
2818 };
2819 
2820 struct EventThreadIsSupportedVariant : public EventThreadBaseSupportedVariant {
setupAcquireAndEnableVsyncCallExpectationsandroid::__anon968546880111::EventThreadIsSupportedVariant2821     static void setupAcquireAndEnableVsyncCallExpectations(DisplayTransactionTest* test) {
2822         // The event control thread should be notified to enable vsyncs
2823         EXPECT_CALL(*test->mEventControlThread, setVsyncEnabled(true)).Times(1);
2824 
2825         // The event thread should be notified that the screen was acquired.
2826         EXPECT_CALL(*test->mEventThread, onScreenAcquired()).Times(1);
2827     }
2828 
setupReleaseAndDisableVsyncCallExpectationsandroid::__anon968546880111::EventThreadIsSupportedVariant2829     static void setupReleaseAndDisableVsyncCallExpectations(DisplayTransactionTest* test) {
2830         // There should be a call to setVsyncEnabled(false)
2831         EXPECT_CALL(*test->mEventControlThread, setVsyncEnabled(false)).Times(1);
2832 
2833         // The event thread should not be notified that the screen was released.
2834         EXPECT_CALL(*test->mEventThread, onScreenReleased()).Times(1);
2835     }
2836 };
2837 
2838 struct DispSyncIsSupportedVariant {
setupBeginResyncCallExpectationsandroid::__anon968546880111::DispSyncIsSupportedVariant2839     static void setupBeginResyncCallExpectations(DisplayTransactionTest* test) {
2840         EXPECT_CALL(*test->mPrimaryDispSync, setPeriod(DEFAULT_REFRESH_RATE)).Times(1);
2841         EXPECT_CALL(*test->mPrimaryDispSync, beginResync()).Times(1);
2842     }
2843 
setupEndResyncCallExpectationsandroid::__anon968546880111::DispSyncIsSupportedVariant2844     static void setupEndResyncCallExpectations(DisplayTransactionTest* test) {
2845         EXPECT_CALL(*test->mPrimaryDispSync, endResync()).Times(1);
2846     }
2847 };
2848 
2849 struct DispSyncNotSupportedVariant {
setupBeginResyncCallExpectationsandroid::__anon968546880111::DispSyncNotSupportedVariant2850     static void setupBeginResyncCallExpectations(DisplayTransactionTest* /* test */) {}
2851 
setupEndResyncCallExpectationsandroid::__anon968546880111::DispSyncNotSupportedVariant2852     static void setupEndResyncCallExpectations(DisplayTransactionTest* /* test */) {}
2853 };
2854 
2855 // --------------------------------------------------------------------
2856 // Note:
2857 //
2858 // There are a large number of transitions we could test, however we only test a
2859 // selected subset which provides complete test coverage of the implementation.
2860 // --------------------------------------------------------------------
2861 
2862 template <int initialPowerMode, int targetPowerMode>
2863 struct TransitionVariantCommon {
2864     static constexpr auto INITIAL_POWER_MODE = initialPowerMode;
2865     static constexpr auto TARGET_POWER_MODE = targetPowerMode;
2866 
verifyPostconditionsandroid::__anon968546880111::TransitionVariantCommon2867     static void verifyPostconditions(DisplayTransactionTest*) {}
2868 };
2869 
2870 struct TransitionOffToOnVariant
2871       : public TransitionVariantCommon<HWC_POWER_MODE_OFF, HWC_POWER_MODE_NORMAL> {
2872     template <typename Case>
setupCallExpectationsandroid::__anon968546880111::TransitionOffToOnVariant2873     static void setupCallExpectations(DisplayTransactionTest* test) {
2874         Case::setupComposerCallExpectations(test, IComposerClient::PowerMode::ON);
2875         Case::EventThread::setupAcquireAndEnableVsyncCallExpectations(test);
2876         Case::DispSync::setupBeginResyncCallExpectations(test);
2877         Case::setupRepaintEverythingCallExpectations(test);
2878     }
2879 
verifyPostconditionsandroid::__anon968546880111::TransitionOffToOnVariant2880     static void verifyPostconditions(DisplayTransactionTest* test) {
2881         EXPECT_TRUE(test->mFlinger.getVisibleRegionsDirty());
2882         EXPECT_TRUE(test->mFlinger.getHasPoweredOff());
2883     }
2884 };
2885 
2886 struct TransitionOffToDozeSuspendVariant
2887       : public TransitionVariantCommon<HWC_POWER_MODE_OFF, HWC_POWER_MODE_DOZE_SUSPEND> {
2888     template <typename Case>
setupCallExpectationsandroid::__anon968546880111::TransitionOffToDozeSuspendVariant2889     static void setupCallExpectations(DisplayTransactionTest* test) {
2890         Case::setupComposerCallExpectations(test, Case::Doze::ACTUAL_POWER_MODE_FOR_DOZE_SUSPEND);
2891         Case::EventThread::setupEventAndEventControlThreadNoCallExpectations(test);
2892         Case::setupRepaintEverythingCallExpectations(test);
2893     }
2894 
verifyPostconditionsandroid::__anon968546880111::TransitionOffToDozeSuspendVariant2895     static void verifyPostconditions(DisplayTransactionTest* test) {
2896         EXPECT_TRUE(test->mFlinger.getVisibleRegionsDirty());
2897         EXPECT_TRUE(test->mFlinger.getHasPoweredOff());
2898     }
2899 };
2900 
2901 struct TransitionOnToOffVariant
2902       : public TransitionVariantCommon<HWC_POWER_MODE_NORMAL, HWC_POWER_MODE_OFF> {
2903     template <typename Case>
setupCallExpectationsandroid::__anon968546880111::TransitionOnToOffVariant2904     static void setupCallExpectations(DisplayTransactionTest* test) {
2905         Case::EventThread::setupReleaseAndDisableVsyncCallExpectations(test);
2906         Case::DispSync::setupEndResyncCallExpectations(test);
2907         Case::setupComposerCallExpectations(test, IComposerClient::PowerMode::OFF);
2908     }
2909 
verifyPostconditionsandroid::__anon968546880111::TransitionOnToOffVariant2910     static void verifyPostconditions(DisplayTransactionTest* test) {
2911         EXPECT_TRUE(test->mFlinger.getVisibleRegionsDirty());
2912     }
2913 };
2914 
2915 struct TransitionDozeSuspendToOffVariant
2916       : public TransitionVariantCommon<HWC_POWER_MODE_DOZE_SUSPEND, HWC_POWER_MODE_OFF> {
2917     template <typename Case>
setupCallExpectationsandroid::__anon968546880111::TransitionDozeSuspendToOffVariant2918     static void setupCallExpectations(DisplayTransactionTest* test) {
2919         Case::EventThread::setupEventAndEventControlThreadNoCallExpectations(test);
2920         Case::setupComposerCallExpectations(test, IComposerClient::PowerMode::OFF);
2921     }
2922 
verifyPostconditionsandroid::__anon968546880111::TransitionDozeSuspendToOffVariant2923     static void verifyPostconditions(DisplayTransactionTest* test) {
2924         EXPECT_TRUE(test->mFlinger.getVisibleRegionsDirty());
2925     }
2926 };
2927 
2928 struct TransitionOnToDozeVariant
2929       : public TransitionVariantCommon<HWC_POWER_MODE_NORMAL, HWC_POWER_MODE_DOZE> {
2930     template <typename Case>
setupCallExpectationsandroid::__anon968546880111::TransitionOnToDozeVariant2931     static void setupCallExpectations(DisplayTransactionTest* test) {
2932         Case::EventThread::setupEventAndEventControlThreadNoCallExpectations(test);
2933         Case::setupComposerCallExpectations(test, Case::Doze::ACTUAL_POWER_MODE_FOR_DOZE);
2934     }
2935 };
2936 
2937 struct TransitionDozeSuspendToDozeVariant
2938       : public TransitionVariantCommon<HWC_POWER_MODE_DOZE_SUSPEND, HWC_POWER_MODE_DOZE> {
2939     template <typename Case>
setupCallExpectationsandroid::__anon968546880111::TransitionDozeSuspendToDozeVariant2940     static void setupCallExpectations(DisplayTransactionTest* test) {
2941         Case::EventThread::setupAcquireAndEnableVsyncCallExpectations(test);
2942         Case::DispSync::setupBeginResyncCallExpectations(test);
2943         Case::setupComposerCallExpectations(test, Case::Doze::ACTUAL_POWER_MODE_FOR_DOZE);
2944     }
2945 };
2946 
2947 struct TransitionDozeToOnVariant
2948       : public TransitionVariantCommon<HWC_POWER_MODE_DOZE, HWC_POWER_MODE_NORMAL> {
2949     template <typename Case>
setupCallExpectationsandroid::__anon968546880111::TransitionDozeToOnVariant2950     static void setupCallExpectations(DisplayTransactionTest* test) {
2951         Case::EventThread::setupEventAndEventControlThreadNoCallExpectations(test);
2952         Case::setupComposerCallExpectations(test, IComposerClient::PowerMode::ON);
2953     }
2954 };
2955 
2956 struct TransitionDozeSuspendToOnVariant
2957       : public TransitionVariantCommon<HWC_POWER_MODE_DOZE_SUSPEND, HWC_POWER_MODE_NORMAL> {
2958     template <typename Case>
setupCallExpectationsandroid::__anon968546880111::TransitionDozeSuspendToOnVariant2959     static void setupCallExpectations(DisplayTransactionTest* test) {
2960         Case::EventThread::setupAcquireAndEnableVsyncCallExpectations(test);
2961         Case::DispSync::setupBeginResyncCallExpectations(test);
2962         Case::setupComposerCallExpectations(test, IComposerClient::PowerMode::ON);
2963     }
2964 };
2965 
2966 struct TransitionOnToDozeSuspendVariant
2967       : public TransitionVariantCommon<HWC_POWER_MODE_NORMAL, HWC_POWER_MODE_DOZE_SUSPEND> {
2968     template <typename Case>
setupCallExpectationsandroid::__anon968546880111::TransitionOnToDozeSuspendVariant2969     static void setupCallExpectations(DisplayTransactionTest* test) {
2970         Case::EventThread::setupReleaseAndDisableVsyncCallExpectations(test);
2971         Case::DispSync::setupEndResyncCallExpectations(test);
2972         Case::setupComposerCallExpectations(test, Case::Doze::ACTUAL_POWER_MODE_FOR_DOZE_SUSPEND);
2973     }
2974 };
2975 
2976 struct TransitionOnToUnknownVariant
2977       : public TransitionVariantCommon<HWC_POWER_MODE_NORMAL, HWC_POWER_MODE_LEET> {
2978     template <typename Case>
setupCallExpectationsandroid::__anon968546880111::TransitionOnToUnknownVariant2979     static void setupCallExpectations(DisplayTransactionTest* test) {
2980         Case::EventThread::setupEventAndEventControlThreadNoCallExpectations(test);
2981         Case::setupNoComposerPowerModeCallExpectations(test);
2982     }
2983 };
2984 
2985 // --------------------------------------------------------------------
2986 // Note:
2987 //
2988 // Rather than testing the cartesian product of of
2989 // DozeIsSupported/DozeNotSupported with all other options, we use one for one
2990 // display type, and the other for another display type.
2991 // --------------------------------------------------------------------
2992 
2993 template <typename DisplayVariant, typename DozeVariant, typename EventThreadVariant,
2994           typename DispSyncVariant, typename TransitionVariant>
2995 struct DisplayPowerCase {
2996     using Display = DisplayVariant;
2997     using Doze = DozeVariant;
2998     using EventThread = EventThreadVariant;
2999     using DispSync = DispSyncVariant;
3000     using Transition = TransitionVariant;
3001 
injectDisplayWithInitialPowerModeandroid::__anon968546880111::DisplayPowerCase3002     static auto injectDisplayWithInitialPowerMode(DisplayTransactionTest* test, int mode) {
3003         Display::injectHwcDisplayWithNoDefaultCapabilities(test);
3004         auto display = Display::makeFakeExistingDisplayInjector(test);
3005         display.inject();
3006         display.mutableDisplayDevice()->setPowerMode(mode);
3007         return display;
3008     }
3009 
setInitialPrimaryHWVsyncEnabledandroid::__anon968546880111::DisplayPowerCase3010     static void setInitialPrimaryHWVsyncEnabled(DisplayTransactionTest* test, bool enabled) {
3011         test->mScheduler->mutablePrimaryHWVsyncEnabled() = enabled;
3012     }
3013 
setupRepaintEverythingCallExpectationsandroid::__anon968546880111::DisplayPowerCase3014     static void setupRepaintEverythingCallExpectations(DisplayTransactionTest* test) {
3015         EXPECT_CALL(*test->mMessageQueue, invalidate()).Times(1);
3016     }
3017 
setupSurfaceInterceptorCallExpectationsandroid::__anon968546880111::DisplayPowerCase3018     static void setupSurfaceInterceptorCallExpectations(DisplayTransactionTest* test, int mode) {
3019         EXPECT_CALL(*test->mSurfaceInterceptor, isEnabled()).WillOnce(Return(true));
3020         EXPECT_CALL(*test->mSurfaceInterceptor, savePowerModeUpdate(_, mode)).Times(1);
3021     }
3022 
setupComposerCallExpectationsandroid::__anon968546880111::DisplayPowerCase3023     static void setupComposerCallExpectations(DisplayTransactionTest* test,
3024                                               IComposerClient::PowerMode mode) {
3025         // Any calls to get the active config will return a default value.
3026         EXPECT_CALL(*test->mComposer, getActiveConfig(Display::HWC_DISPLAY_ID, _))
3027                 .WillRepeatedly(DoAll(SetArgPointee<1>(Display::HWC_ACTIVE_CONFIG_ID),
3028                                       Return(Error::NONE)));
3029 
3030         // Any calls to get whether the display supports dozing will return the value set by the
3031         // policy variant.
3032         EXPECT_CALL(*test->mComposer, getDozeSupport(Display::HWC_DISPLAY_ID, _))
3033                 .WillRepeatedly(DoAll(SetArgPointee<1>(Doze::DOZE_SUPPORTED), Return(Error::NONE)));
3034 
3035         EXPECT_CALL(*test->mComposer, setPowerMode(Display::HWC_DISPLAY_ID, mode)).Times(1);
3036     }
3037 
setupNoComposerPowerModeCallExpectationsandroid::__anon968546880111::DisplayPowerCase3038     static void setupNoComposerPowerModeCallExpectations(DisplayTransactionTest* test) {
3039         EXPECT_CALL(*test->mComposer, setPowerMode(Display::HWC_DISPLAY_ID, _)).Times(0);
3040     }
3041 };
3042 
3043 // A sample configuration for the primary display.
3044 // In addition to having event thread support, we emulate doze support.
3045 template <typename TransitionVariant>
3046 using PrimaryDisplayPowerCase =
3047         DisplayPowerCase<PrimaryDisplayVariant, DozeIsSupportedVariant<PrimaryDisplayVariant>,
3048                          EventThreadIsSupportedVariant, DispSyncIsSupportedVariant,
3049                          TransitionVariant>;
3050 
3051 // A sample configuration for the external display.
3052 // In addition to not having event thread support, we emulate not having doze
3053 // support.
3054 template <typename TransitionVariant>
3055 using ExternalDisplayPowerCase =
3056         DisplayPowerCase<ExternalDisplayVariant, DozeNotSupportedVariant<ExternalDisplayVariant>,
3057                          EventThreadNotSupportedVariant, DispSyncNotSupportedVariant,
3058                          TransitionVariant>;
3059 
3060 class SetPowerModeInternalTest : public DisplayTransactionTest {
3061 public:
3062     template <typename Case>
3063     void transitionDisplayCommon();
3064 };
3065 
3066 template <int PowerMode>
3067 struct PowerModeInitialVSyncEnabled : public std::false_type {};
3068 
3069 template <>
3070 struct PowerModeInitialVSyncEnabled<HWC_POWER_MODE_NORMAL> : public std::true_type {};
3071 
3072 template <>
3073 struct PowerModeInitialVSyncEnabled<HWC_POWER_MODE_DOZE> : public std::true_type {};
3074 
3075 template <typename Case>
transitionDisplayCommon()3076 void SetPowerModeInternalTest::transitionDisplayCommon() {
3077     // --------------------------------------------------------------------
3078     // Preconditions
3079 
3080     Case::Doze::setupComposerCallExpectations(this);
3081     auto display =
3082             Case::injectDisplayWithInitialPowerMode(this, Case::Transition::INITIAL_POWER_MODE);
3083     Case::setInitialPrimaryHWVsyncEnabled(this,
3084                                           PowerModeInitialVSyncEnabled<
3085                                                   Case::Transition::INITIAL_POWER_MODE>::value);
3086 
3087     // --------------------------------------------------------------------
3088     // Call Expectations
3089 
3090     Case::setupSurfaceInterceptorCallExpectations(this, Case::Transition::TARGET_POWER_MODE);
3091     Case::Transition::template setupCallExpectations<Case>(this);
3092 
3093     // --------------------------------------------------------------------
3094     // Invocation
3095 
3096     mFlinger.setPowerModeInternal(display.mutableDisplayDevice(),
3097                                   Case::Transition::TARGET_POWER_MODE);
3098 
3099     // --------------------------------------------------------------------
3100     // Postconditions
3101 
3102     Case::Transition::verifyPostconditions(this);
3103 }
3104 
TEST_F(SetPowerModeInternalTest,setPowerModeInternalDoesNothingIfNoChange)3105 TEST_F(SetPowerModeInternalTest, setPowerModeInternalDoesNothingIfNoChange) {
3106     using Case = SimplePrimaryDisplayCase;
3107 
3108     // --------------------------------------------------------------------
3109     // Preconditions
3110 
3111     // A primary display device is set up
3112     Case::Display::injectHwcDisplay(this);
3113     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
3114     display.inject();
3115 
3116     // The display is already set to HWC_POWER_MODE_NORMAL
3117     display.mutableDisplayDevice()->setPowerMode(HWC_POWER_MODE_NORMAL);
3118 
3119     // --------------------------------------------------------------------
3120     // Invocation
3121 
3122     mFlinger.setPowerModeInternal(display.mutableDisplayDevice(), HWC_POWER_MODE_NORMAL);
3123 
3124     // --------------------------------------------------------------------
3125     // Postconditions
3126 
3127     EXPECT_EQ(HWC_POWER_MODE_NORMAL, display.mutableDisplayDevice()->getPowerMode());
3128 }
3129 
TEST_F(SetPowerModeInternalTest,setPowerModeInternalDoesNothingIfVirtualDisplay)3130 TEST_F(SetPowerModeInternalTest, setPowerModeInternalDoesNothingIfVirtualDisplay) {
3131     using Case = HwcVirtualDisplayCase;
3132 
3133     // --------------------------------------------------------------------
3134     // Preconditions
3135 
3136     // Insert display data so that the HWC thinks it created the virtual display.
3137     const auto displayId = Case::Display::DISPLAY_ID::get();
3138     ASSERT_TRUE(displayId);
3139     mFlinger.mutableHwcDisplayData().try_emplace(*displayId);
3140 
3141     // A virtual display device is set up
3142     Case::Display::injectHwcDisplay(this);
3143     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
3144     display.inject();
3145 
3146     // The display is set to HWC_POWER_MODE_NORMAL
3147     getDisplayDevice(display.token())->setPowerMode(HWC_POWER_MODE_NORMAL);
3148 
3149     // --------------------------------------------------------------------
3150     // Invocation
3151 
3152     mFlinger.setPowerModeInternal(display.mutableDisplayDevice(), HWC_POWER_MODE_OFF);
3153 
3154     // --------------------------------------------------------------------
3155     // Postconditions
3156 
3157     EXPECT_EQ(HWC_POWER_MODE_NORMAL, display.mutableDisplayDevice()->getPowerMode());
3158 }
3159 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromOffToOnPrimaryDisplay)3160 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromOffToOnPrimaryDisplay) {
3161     transitionDisplayCommon<PrimaryDisplayPowerCase<TransitionOffToOnVariant>>();
3162 }
3163 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromOffToDozeSuspendPrimaryDisplay)3164 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromOffToDozeSuspendPrimaryDisplay) {
3165     transitionDisplayCommon<PrimaryDisplayPowerCase<TransitionOffToDozeSuspendVariant>>();
3166 }
3167 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromOnToOffPrimaryDisplay)3168 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromOnToOffPrimaryDisplay) {
3169     transitionDisplayCommon<PrimaryDisplayPowerCase<TransitionOnToOffVariant>>();
3170 }
3171 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromDozeSuspendToOffPrimaryDisplay)3172 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromDozeSuspendToOffPrimaryDisplay) {
3173     transitionDisplayCommon<PrimaryDisplayPowerCase<TransitionDozeSuspendToOffVariant>>();
3174 }
3175 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromOnToDozePrimaryDisplay)3176 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromOnToDozePrimaryDisplay) {
3177     transitionDisplayCommon<PrimaryDisplayPowerCase<TransitionOnToDozeVariant>>();
3178 }
3179 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromDozeSuspendToDozePrimaryDisplay)3180 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromDozeSuspendToDozePrimaryDisplay) {
3181     transitionDisplayCommon<PrimaryDisplayPowerCase<TransitionDozeSuspendToDozeVariant>>();
3182 }
3183 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromDozeToOnPrimaryDisplay)3184 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromDozeToOnPrimaryDisplay) {
3185     transitionDisplayCommon<PrimaryDisplayPowerCase<TransitionDozeToOnVariant>>();
3186 }
3187 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromDozeSuspendToOnPrimaryDisplay)3188 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromDozeSuspendToOnPrimaryDisplay) {
3189     transitionDisplayCommon<PrimaryDisplayPowerCase<TransitionDozeSuspendToOnVariant>>();
3190 }
3191 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromOnToDozeSuspendPrimaryDisplay)3192 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromOnToDozeSuspendPrimaryDisplay) {
3193     transitionDisplayCommon<PrimaryDisplayPowerCase<TransitionOnToDozeSuspendVariant>>();
3194 }
3195 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromOnToUnknownPrimaryDisplay)3196 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromOnToUnknownPrimaryDisplay) {
3197     transitionDisplayCommon<PrimaryDisplayPowerCase<TransitionOnToUnknownVariant>>();
3198 }
3199 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromOffToOnExternalDisplay)3200 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromOffToOnExternalDisplay) {
3201     transitionDisplayCommon<ExternalDisplayPowerCase<TransitionOffToOnVariant>>();
3202 }
3203 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromOffToDozeSuspendExternalDisplay)3204 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromOffToDozeSuspendExternalDisplay) {
3205     transitionDisplayCommon<ExternalDisplayPowerCase<TransitionOffToDozeSuspendVariant>>();
3206 }
3207 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromOnToOffExternalDisplay)3208 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromOnToOffExternalDisplay) {
3209     transitionDisplayCommon<ExternalDisplayPowerCase<TransitionOnToOffVariant>>();
3210 }
3211 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromDozeSuspendToOffExternalDisplay)3212 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromDozeSuspendToOffExternalDisplay) {
3213     transitionDisplayCommon<ExternalDisplayPowerCase<TransitionDozeSuspendToOffVariant>>();
3214 }
3215 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromOnToDozeExternalDisplay)3216 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromOnToDozeExternalDisplay) {
3217     transitionDisplayCommon<ExternalDisplayPowerCase<TransitionOnToDozeVariant>>();
3218 }
3219 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromDozeSuspendToDozeExternalDisplay)3220 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromDozeSuspendToDozeExternalDisplay) {
3221     transitionDisplayCommon<ExternalDisplayPowerCase<TransitionDozeSuspendToDozeVariant>>();
3222 }
3223 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromDozeToOnExternalDisplay)3224 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromDozeToOnExternalDisplay) {
3225     transitionDisplayCommon<ExternalDisplayPowerCase<TransitionDozeToOnVariant>>();
3226 }
3227 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromDozeSuspendToOnExternalDisplay)3228 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromDozeSuspendToOnExternalDisplay) {
3229     transitionDisplayCommon<ExternalDisplayPowerCase<TransitionDozeSuspendToOnVariant>>();
3230 }
3231 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromOnToDozeSuspendExternalDisplay)3232 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromOnToDozeSuspendExternalDisplay) {
3233     transitionDisplayCommon<ExternalDisplayPowerCase<TransitionOnToDozeSuspendVariant>>();
3234 }
3235 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromOnToUnknownExternalDisplay)3236 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromOnToUnknownExternalDisplay) {
3237     transitionDisplayCommon<ExternalDisplayPowerCase<TransitionOnToUnknownVariant>>();
3238 }
3239 
3240 } // namespace
3241 } // namespace android
3242