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