• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #undef LOG_TAG
18 #define LOG_TAG "LibSurfaceFlingerUnittests"
19 
20 #include <gmock/gmock.h>
21 #include <gtest/gtest.h>
22 
23 #include <log/log.h>
24 
25 #include "TestableSurfaceFlinger.h"
26 #include "mock/DisplayHardware/MockComposer.h"
27 #include "mock/DisplayHardware/MockDisplaySurface.h"
28 #include "mock/MockEventControlThread.h"
29 #include "mock/MockEventThread.h"
30 #include "mock/MockMessageQueue.h"
31 #include "mock/MockNativeWindowSurface.h"
32 #include "mock/MockSurfaceInterceptor.h"
33 #include "mock/RenderEngine/MockRenderEngine.h"
34 #include "mock/gui/MockGraphicBufferConsumer.h"
35 #include "mock/gui/MockGraphicBufferProducer.h"
36 #include "mock/system/window/MockNativeWindow.h"
37 
38 namespace android {
39 namespace {
40 
41 using testing::_;
42 using testing::ByMove;
43 using testing::DoAll;
44 using testing::Mock;
45 using testing::Return;
46 using testing::SetArgPointee;
47 
48 using android::Hwc2::ColorMode;
49 using android::Hwc2::Error;
50 using android::Hwc2::Hdr;
51 using android::Hwc2::IComposer;
52 using android::Hwc2::IComposerClient;
53 using android::Hwc2::PerFrameMetadataKey;
54 using android::Hwc2::RenderIntent;
55 
56 using FakeDisplayDeviceInjector = TestableSurfaceFlinger::FakeDisplayDeviceInjector;
57 using FakeHwcDisplayInjector = TestableSurfaceFlinger::FakeHwcDisplayInjector;
58 using HotplugEvent = TestableSurfaceFlinger::HotplugEvent;
59 using HWC2Display = TestableSurfaceFlinger::HWC2Display;
60 
61 constexpr int32_t DEFAULT_REFRESH_RATE = 16'666'666;
62 constexpr int32_t DEFAULT_DPI = 320;
63 constexpr int DEFAULT_VIRTUAL_DISPLAY_SURFACE_FORMAT = HAL_PIXEL_FORMAT_RGB_565;
64 
65 constexpr int HWC_POWER_MODE_LEET = 1337; // An out of range power mode value
66 
67 /* ------------------------------------------------------------------------
68  * Boolean avoidance
69  *
70  * To make calls and template instantiations more readable, we define some
71  * local enums along with an implicit bool conversion.
72  */
73 
74 #define BOOL_SUBSTITUTE(TYPENAME) enum class TYPENAME : bool { FALSE = false, TRUE = true };
75 
76 BOOL_SUBSTITUTE(Critical);
77 BOOL_SUBSTITUTE(Async);
78 BOOL_SUBSTITUTE(Secure);
79 
80 /* ------------------------------------------------------------------------
81  *
82  */
83 
84 class DisplayTransactionTest : public testing::Test {
85 public:
86     DisplayTransactionTest();
87     ~DisplayTransactionTest() override;
88 
89     // --------------------------------------------------------------------
90     // Mock/Fake injection
91 
92     void injectMockComposer(int virtualDisplayCount);
93     void injectFakeBufferQueueFactory();
94     void injectFakeNativeWindowSurfaceFactory();
95 
96     // --------------------------------------------------------------------
97     // Postcondition helpers
98 
99     bool hasHwcDisplay(hwc2_display_t displayId);
100     bool hasTransactionFlagSet(int flag);
101     bool hasDisplayDevice(sp<IBinder> displayToken);
102     sp<DisplayDevice> getDisplayDevice(sp<IBinder> displayToken);
103     bool hasCurrentDisplayState(sp<IBinder> displayToken);
104     const DisplayDeviceState& getCurrentDisplayState(sp<IBinder> displayToken);
105     bool hasDrawingDisplayState(sp<IBinder> displayToken);
106     const DisplayDeviceState& getDrawingDisplayState(sp<IBinder> displayToken);
107 
108     // --------------------------------------------------------------------
109     // Test instances
110 
111     TestableSurfaceFlinger mFlinger;
112     mock::EventThread* mEventThread = new mock::EventThread();
113     mock::EventControlThread* mEventControlThread = new mock::EventControlThread();
114 
115     // These mocks are created by the test, but are destroyed by SurfaceFlinger
116     // by virtue of being stored into a std::unique_ptr. However we still need
117     // to keep a reference to them for use in setting up call expectations.
118     RE::mock::RenderEngine* mRenderEngine = new RE::mock::RenderEngine();
119     Hwc2::mock::Composer* mComposer = nullptr;
120     mock::MessageQueue* mMessageQueue = new mock::MessageQueue();
121     mock::SurfaceInterceptor* mSurfaceInterceptor = new mock::SurfaceInterceptor();
122 
123     // These mocks are created only when expected to be created via a factory.
124     sp<mock::GraphicBufferConsumer> mConsumer;
125     sp<mock::GraphicBufferProducer> mProducer;
126     mock::NativeWindowSurface* mNativeWindowSurface = nullptr;
127     sp<mock::NativeWindow> mNativeWindow;
128     RE::mock::Surface* mRenderSurface = nullptr;
129 };
130 
DisplayTransactionTest()131 DisplayTransactionTest::DisplayTransactionTest() {
132     const ::testing::TestInfo* const test_info =
133             ::testing::UnitTest::GetInstance()->current_test_info();
134     ALOGD("**** Setting up for %s.%s\n", test_info->test_case_name(), test_info->name());
135 
136     // Default to no wide color display support configured
137     mFlinger.mutableHasWideColorDisplay() = false;
138     mFlinger.mutableDisplayColorSetting() = DisplayColorSetting::UNMANAGED;
139 
140     // Default to using HWC virtual displays
141     mFlinger.mutableUseHwcVirtualDisplays() = true;
142 
143     mFlinger.setCreateBufferQueueFunction([](auto, auto, auto) {
144         ADD_FAILURE() << "Unexpected request to create a buffer queue.";
145     });
146 
147     mFlinger.setCreateNativeWindowSurface([](auto) {
148         ADD_FAILURE() << "Unexpected request to create a native window surface.";
149         return nullptr;
150     });
151 
152     mFlinger.mutableEventControlThread().reset(mEventControlThread);
153     mFlinger.mutableEventThread().reset(mEventThread);
154     mFlinger.mutableEventQueue().reset(mMessageQueue);
155     mFlinger.setupRenderEngine(std::unique_ptr<RE::RenderEngine>(mRenderEngine));
156     mFlinger.mutableInterceptor().reset(mSurfaceInterceptor);
157 
158     injectMockComposer(0);
159 }
160 
~DisplayTransactionTest()161 DisplayTransactionTest::~DisplayTransactionTest() {
162     const ::testing::TestInfo* const test_info =
163             ::testing::UnitTest::GetInstance()->current_test_info();
164     ALOGD("**** Tearing down after %s.%s\n", test_info->test_case_name(), test_info->name());
165 }
166 
injectMockComposer(int virtualDisplayCount)167 void DisplayTransactionTest::injectMockComposer(int virtualDisplayCount) {
168     mComposer = new Hwc2::mock::Composer();
169     EXPECT_CALL(*mComposer, getCapabilities())
170             .WillOnce(Return(std::vector<IComposer::Capability>()));
171     EXPECT_CALL(*mComposer, getMaxVirtualDisplayCount()).WillOnce(Return(virtualDisplayCount));
172     mFlinger.setupComposer(std::unique_ptr<Hwc2::Composer>(mComposer));
173 
174     Mock::VerifyAndClear(mComposer);
175 }
176 
injectFakeBufferQueueFactory()177 void DisplayTransactionTest::injectFakeBufferQueueFactory() {
178     // This setup is only expected once per test.
179     ASSERT_TRUE(mConsumer == nullptr && mProducer == nullptr);
180 
181     mConsumer = new mock::GraphicBufferConsumer();
182     mProducer = new mock::GraphicBufferProducer();
183 
184     mFlinger.setCreateBufferQueueFunction([this](auto outProducer, auto outConsumer, bool) {
185         *outProducer = mProducer;
186         *outConsumer = mConsumer;
187     });
188 }
189 
injectFakeNativeWindowSurfaceFactory()190 void DisplayTransactionTest::injectFakeNativeWindowSurfaceFactory() {
191     // This setup is only expected once per test.
192     ASSERT_TRUE(mNativeWindowSurface == nullptr);
193 
194     mNativeWindowSurface = new mock::NativeWindowSurface();
195     mNativeWindow = new mock::NativeWindow();
196 
197     mFlinger.setCreateNativeWindowSurface(
198             [this](auto) { return std::unique_ptr<NativeWindowSurface>(mNativeWindowSurface); });
199 }
200 
hasHwcDisplay(hwc2_display_t displayId)201 bool DisplayTransactionTest::hasHwcDisplay(hwc2_display_t displayId) {
202     return mFlinger.mutableHwcDisplaySlots().count(displayId) == 1;
203 }
204 
hasTransactionFlagSet(int flag)205 bool DisplayTransactionTest::hasTransactionFlagSet(int flag) {
206     return mFlinger.mutableTransactionFlags() & flag;
207 }
208 
hasDisplayDevice(sp<IBinder> displayToken)209 bool DisplayTransactionTest::hasDisplayDevice(sp<IBinder> displayToken) {
210     return mFlinger.mutableDisplays().indexOfKey(displayToken) >= 0;
211 }
212 
getDisplayDevice(sp<IBinder> displayToken)213 sp<DisplayDevice> DisplayTransactionTest::getDisplayDevice(sp<IBinder> displayToken) {
214     return mFlinger.mutableDisplays().valueFor(displayToken);
215 }
216 
hasCurrentDisplayState(sp<IBinder> displayToken)217 bool DisplayTransactionTest::hasCurrentDisplayState(sp<IBinder> displayToken) {
218     return mFlinger.mutableCurrentState().displays.indexOfKey(displayToken) >= 0;
219 }
220 
getCurrentDisplayState(sp<IBinder> displayToken)221 const DisplayDeviceState& DisplayTransactionTest::getCurrentDisplayState(sp<IBinder> displayToken) {
222     return mFlinger.mutableCurrentState().displays.valueFor(displayToken);
223 }
224 
hasDrawingDisplayState(sp<IBinder> displayToken)225 bool DisplayTransactionTest::hasDrawingDisplayState(sp<IBinder> displayToken) {
226     return mFlinger.mutableDrawingState().displays.indexOfKey(displayToken) >= 0;
227 }
228 
getDrawingDisplayState(sp<IBinder> displayToken)229 const DisplayDeviceState& DisplayTransactionTest::getDrawingDisplayState(sp<IBinder> displayToken) {
230     return mFlinger.mutableDrawingState().displays.valueFor(displayToken);
231 }
232 
233 /* ------------------------------------------------------------------------
234  *
235  */
236 
237 template <DisplayDevice::DisplayType type, DisplayDevice::DisplayType hwcId, int width, int height,
238           Critical critical, Async async, Secure secure, int grallocUsage>
239 struct DisplayVariant {
240     // The display width and height
241     static constexpr int WIDTH = width;
242     static constexpr int HEIGHT = height;
243 
244     static constexpr int GRALLOC_USAGE = grallocUsage;
245 
246     // The type for this display
247     static constexpr DisplayDevice::DisplayType TYPE = type;
248     static constexpr DisplayDevice::DisplayType HWCOMPOSER_ID = hwcId;
249 
250     // When creating native window surfaces for the framebuffer, whether those should be critical
251     static constexpr Critical CRITICAL = critical;
252 
253     // When creating native window surfaces for the framebuffer, whether those should be async
254     static constexpr Async ASYNC = async;
255 
256     // Whether the display should be treated as secure
257     static constexpr Secure SECURE = secure;
258 
makeFakeExistingDisplayInjectorandroid::__anon52a382c50111::DisplayVariant259     static auto makeFakeExistingDisplayInjector(DisplayTransactionTest* test) {
260         auto injector = FakeDisplayDeviceInjector(test->mFlinger, TYPE, HWCOMPOSER_ID);
261         injector.setSecure(static_cast<bool>(SECURE));
262         return injector;
263     }
264 
265     // Called by tests to set up any native window creation call expectations.
setupNativeWindowSurfaceCreationCallExpectationsandroid::__anon52a382c50111::DisplayVariant266     static void setupNativeWindowSurfaceCreationCallExpectations(DisplayTransactionTest* test) {
267         EXPECT_CALL(*test->mNativeWindowSurface, getNativeWindow())
268                 .WillOnce(Return(test->mNativeWindow));
269         EXPECT_CALL(*test->mNativeWindow, perform(19)).WillRepeatedly(Return(NO_ERROR));
270 
271         // For simplicity, we only expect to create a single render surface for
272         // each test.
273         ASSERT_TRUE(test->mRenderSurface == nullptr);
274         test->mRenderSurface = new RE::mock::Surface();
275         EXPECT_CALL(*test->mRenderEngine, createSurface())
276                 .WillOnce(Return(ByMove(std::unique_ptr<RE::Surface>(test->mRenderSurface))));
277         EXPECT_CALL(*test->mRenderSurface, setAsync(static_cast<bool>(ASYNC))).Times(1);
278         EXPECT_CALL(*test->mRenderSurface, setCritical(static_cast<bool>(CRITICAL))).Times(1);
279         EXPECT_CALL(*test->mRenderSurface, setNativeWindow(test->mNativeWindow.get())).Times(1);
280         EXPECT_CALL(*test->mRenderSurface, queryWidth()).WillOnce(Return(WIDTH));
281         EXPECT_CALL(*test->mRenderSurface, queryHeight()).WillOnce(Return(HEIGHT));
282     }
283 
setupFramebufferConsumerBufferQueueCallExpectationsandroid::__anon52a382c50111::DisplayVariant284     static void setupFramebufferConsumerBufferQueueCallExpectations(DisplayTransactionTest* test) {
285         EXPECT_CALL(*test->mConsumer, consumerConnect(_, false)).WillOnce(Return(NO_ERROR));
286         EXPECT_CALL(*test->mConsumer, setConsumerName(_)).WillRepeatedly(Return(NO_ERROR));
287         EXPECT_CALL(*test->mConsumer, setConsumerUsageBits(GRALLOC_USAGE))
288                 .WillRepeatedly(Return(NO_ERROR));
289         EXPECT_CALL(*test->mConsumer, setDefaultBufferSize(WIDTH, HEIGHT))
290                 .WillRepeatedly(Return(NO_ERROR));
291         EXPECT_CALL(*test->mConsumer, setMaxAcquiredBufferCount(_))
292                 .WillRepeatedly(Return(NO_ERROR));
293     }
294 
setupFramebufferProducerBufferQueueCallExpectationsandroid::__anon52a382c50111::DisplayVariant295     static void setupFramebufferProducerBufferQueueCallExpectations(DisplayTransactionTest* test) {
296         EXPECT_CALL(*test->mProducer, allocateBuffers(0, 0, 0, 0)).WillRepeatedly(Return());
297     }
298 };
299 
300 template <hwc2_display_t hwcDisplayId, HWC2::DisplayType hwcDisplayType, typename DisplayVariant>
301 struct HwcDisplayVariant {
302     // The display id supplied by the HWC
303     static constexpr hwc2_display_t HWC_DISPLAY_ID = hwcDisplayId;
304 
305     // The HWC display type
306     static constexpr HWC2::DisplayType HWC_DISPLAY_TYPE = hwcDisplayType;
307 
308     // The HWC active configuration id
309     static constexpr int HWC_ACTIVE_CONFIG_ID = 2001;
310 
injectPendingHotplugEventandroid::__anon52a382c50111::HwcDisplayVariant311     static void injectPendingHotplugEvent(DisplayTransactionTest* test,
312                                           HWC2::Connection connection) {
313         test->mFlinger.mutablePendingHotplugEvents().emplace_back(
314                 HotplugEvent{HWC_DISPLAY_ID, connection});
315     }
316 
317     // Called by tests to inject a HWC display setup
injectHwcDisplayandroid::__anon52a382c50111::HwcDisplayVariant318     static void injectHwcDisplay(DisplayTransactionTest* test) {
319         FakeHwcDisplayInjector(DisplayVariant::TYPE, HWC_DISPLAY_TYPE)
320                 .setHwcDisplayId(HWC_DISPLAY_ID)
321                 .setWidth(DisplayVariant::WIDTH)
322                 .setHeight(DisplayVariant::HEIGHT)
323                 .setActiveConfig(HWC_ACTIVE_CONFIG_ID)
324                 .inject(&test->mFlinger, test->mComposer);
325     }
326 
setupHwcHotplugCallExpectationsandroid::__anon52a382c50111::HwcDisplayVariant327     static void setupHwcHotplugCallExpectations(DisplayTransactionTest* test) {
328         EXPECT_CALL(*test->mComposer, getDisplayType(HWC_DISPLAY_ID, _))
329                 .WillOnce(DoAll(SetArgPointee<1>(static_cast<IComposerClient::DisplayType>(
330                                         HWC_DISPLAY_TYPE)),
331                                 Return(Error::NONE)));
332         EXPECT_CALL(*test->mComposer, setClientTargetSlotCount(_)).WillOnce(Return(Error::NONE));
333         EXPECT_CALL(*test->mComposer, getDisplayConfigs(HWC_DISPLAY_ID, _))
334                 .WillOnce(DoAll(SetArgPointee<1>(std::vector<unsigned>{HWC_ACTIVE_CONFIG_ID}),
335                                 Return(Error::NONE)));
336         EXPECT_CALL(*test->mComposer,
337                     getDisplayAttribute(HWC_DISPLAY_ID, HWC_ACTIVE_CONFIG_ID,
338                                         IComposerClient::Attribute::WIDTH, _))
339                 .WillOnce(DoAll(SetArgPointee<3>(DisplayVariant::WIDTH), Return(Error::NONE)));
340         EXPECT_CALL(*test->mComposer,
341                     getDisplayAttribute(HWC_DISPLAY_ID, HWC_ACTIVE_CONFIG_ID,
342                                         IComposerClient::Attribute::HEIGHT, _))
343                 .WillOnce(DoAll(SetArgPointee<3>(DisplayVariant::HEIGHT), Return(Error::NONE)));
344         EXPECT_CALL(*test->mComposer,
345                     getDisplayAttribute(HWC_DISPLAY_ID, HWC_ACTIVE_CONFIG_ID,
346                                         IComposerClient::Attribute::VSYNC_PERIOD, _))
347                 .WillOnce(DoAll(SetArgPointee<3>(DEFAULT_REFRESH_RATE), Return(Error::NONE)));
348         EXPECT_CALL(*test->mComposer,
349                     getDisplayAttribute(HWC_DISPLAY_ID, HWC_ACTIVE_CONFIG_ID,
350                                         IComposerClient::Attribute::DPI_X, _))
351                 .WillOnce(DoAll(SetArgPointee<3>(DEFAULT_DPI), Return(Error::NONE)));
352         EXPECT_CALL(*test->mComposer,
353                     getDisplayAttribute(HWC_DISPLAY_ID, HWC_ACTIVE_CONFIG_ID,
354                                         IComposerClient::Attribute::DPI_Y, _))
355                 .WillOnce(DoAll(SetArgPointee<3>(DEFAULT_DPI), Return(Error::NONE)));
356     }
357 
358     // Called by tests to set up HWC call expectations
setupHwcGetActiveConfigCallExpectationsandroid::__anon52a382c50111::HwcDisplayVariant359     static void setupHwcGetActiveConfigCallExpectations(DisplayTransactionTest* test) {
360         EXPECT_CALL(*test->mComposer, getActiveConfig(HWC_DISPLAY_ID, _))
361                 .WillRepeatedly(DoAll(SetArgPointee<1>(HWC_ACTIVE_CONFIG_ID), Return(Error::NONE)));
362     }
363 };
364 
365 struct NonHwcDisplayVariant {
injectHwcDisplayandroid::__anon52a382c50111::NonHwcDisplayVariant366     static void injectHwcDisplay(DisplayTransactionTest*) {}
367 
setupHwcGetActiveConfigCallExpectationsandroid::__anon52a382c50111::NonHwcDisplayVariant368     static void setupHwcGetActiveConfigCallExpectations(DisplayTransactionTest* test) {
369         EXPECT_CALL(*test->mComposer, getActiveConfig(_, _)).Times(0);
370     }
371 };
372 
373 // Physical displays are expected to be synchronous, secure, and have a HWC display for output.
374 constexpr uint32_t GRALLOC_USAGE_PHYSICAL_DISPLAY =
375         GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_FB;
376 
377 template <hwc2_display_t hwcDisplayId, DisplayDevice::DisplayType type, int width, int height,
378           Critical critical>
379 struct PhysicalDisplayVariant
380       : public DisplayVariant<type, type, width, height, critical, Async::FALSE, Secure::TRUE,
381                               GRALLOC_USAGE_PHYSICAL_DISPLAY>,
382         public HwcDisplayVariant<hwcDisplayId, HWC2::DisplayType::Physical,
383                                  DisplayVariant<type, type, width, height, critical, Async::FALSE,
384                                                 Secure::TRUE, GRALLOC_USAGE_PHYSICAL_DISPLAY>> {};
385 
386 // An invalid display
387 using InvalidDisplayVariant =
388         DisplayVariant<DisplayDevice::DISPLAY_ID_INVALID, DisplayDevice::DISPLAY_ID_INVALID, 0, 0,
389                        Critical::FALSE, Async::FALSE, Secure::FALSE, 0>;
390 
391 // A primary display is a physical display that is critical
392 using PrimaryDisplayVariant =
393         PhysicalDisplayVariant<1001, DisplayDevice::DISPLAY_PRIMARY, 3840, 2160, Critical::TRUE>;
394 
395 // An external display is physical display that is not critical.
396 using ExternalDisplayVariant =
397         PhysicalDisplayVariant<1002, DisplayDevice::DISPLAY_EXTERNAL, 1920, 1280, Critical::FALSE>;
398 
399 using TertiaryDisplayVariant =
400         PhysicalDisplayVariant<1003, DisplayDevice::DISPLAY_EXTERNAL, 1600, 1200, Critical::FALSE>;
401 
402 // A virtual display not supported by the HWC.
403 constexpr uint32_t GRALLOC_USAGE_NONHWC_VIRTUAL_DISPLAY = 0;
404 
405 template <int width, int height, Secure secure>
406 struct NonHwcVirtualDisplayVariant
407       : public DisplayVariant<DisplayDevice::DISPLAY_VIRTUAL, DisplayDevice::DISPLAY_ID_INVALID,
408                               width, height, Critical::FALSE, Async::TRUE, secure,
409                               GRALLOC_USAGE_NONHWC_VIRTUAL_DISPLAY>,
410         public NonHwcDisplayVariant {
411     using Base = DisplayVariant<DisplayDevice::DISPLAY_VIRTUAL, DisplayDevice::DISPLAY_ID_INVALID,
412                                 width, height, Critical::FALSE, Async::TRUE, secure,
413                                 GRALLOC_USAGE_NONHWC_VIRTUAL_DISPLAY>;
414 
setupNativeWindowSurfaceCreationCallExpectationsandroid::__anon52a382c50111::NonHwcVirtualDisplayVariant415     static void setupNativeWindowSurfaceCreationCallExpectations(DisplayTransactionTest* test) {
416         Base::setupNativeWindowSurfaceCreationCallExpectations(test);
417         EXPECT_CALL(*test->mNativeWindow, setSwapInterval(0)).Times(1);
418     }
419 };
420 
421 // A virtual display supported by the HWC.
422 constexpr uint32_t GRALLOC_USAGE_HWC_VIRTUAL_DISPLAY = GRALLOC_USAGE_HW_COMPOSER;
423 
424 template <int width, int height, Secure secure>
425 struct HwcVirtualDisplayVariant
426       : public DisplayVariant<DisplayDevice::DISPLAY_VIRTUAL, DisplayDevice::DISPLAY_VIRTUAL, width,
427                               height, Critical::FALSE, Async::TRUE, secure,
428                               GRALLOC_USAGE_HWC_VIRTUAL_DISPLAY>,
429         public HwcDisplayVariant<1010, HWC2::DisplayType::Virtual,
430                                  NonHwcVirtualDisplayVariant<width, height, secure>> {
431     using Base =
432             DisplayVariant<DisplayDevice::DISPLAY_VIRTUAL, DisplayDevice::DISPLAY_VIRTUAL, width,
433                            height, Critical::FALSE, Async::TRUE, secure, GRALLOC_USAGE_HW_COMPOSER>;
434     using Self = HwcVirtualDisplayVariant<width, height, secure>;
435 
setupNativeWindowSurfaceCreationCallExpectationsandroid::__anon52a382c50111::HwcVirtualDisplayVariant436     static void setupNativeWindowSurfaceCreationCallExpectations(DisplayTransactionTest* test) {
437         Base::setupNativeWindowSurfaceCreationCallExpectations(test);
438         EXPECT_CALL(*test->mNativeWindow, setSwapInterval(0)).Times(1);
439     }
440 
setupHwcVirtualDisplayCreationCallExpectationsandroid::__anon52a382c50111::HwcVirtualDisplayVariant441     static void setupHwcVirtualDisplayCreationCallExpectations(DisplayTransactionTest* test) {
442         EXPECT_CALL(*test->mComposer, createVirtualDisplay(Base::WIDTH, Base::HEIGHT, _, _))
443                 .WillOnce(DoAll(SetArgPointee<3>(Self::HWC_DISPLAY_ID), Return(Error::NONE)));
444         EXPECT_CALL(*test->mComposer, setClientTargetSlotCount(_)).WillOnce(Return(Error::NONE));
445     }
446 };
447 
448 // For this variant, SurfaceFlinger should not configure itself with wide
449 // display support, so the display should not be configured for wide-color
450 // support.
451 struct WideColorSupportNotConfiguredVariant {
452     static constexpr bool WIDE_COLOR_SUPPORTED = false;
453 
injectConfigChangeandroid::__anon52a382c50111::WideColorSupportNotConfiguredVariant454     static void injectConfigChange(DisplayTransactionTest* test) {
455         test->mFlinger.mutableHasWideColorDisplay() = false;
456         test->mFlinger.mutableDisplayColorSetting() = DisplayColorSetting::UNMANAGED;
457     }
458 
setupComposerCallExpectationsandroid::__anon52a382c50111::WideColorSupportNotConfiguredVariant459     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
460         EXPECT_CALL(*test->mComposer, getColorModes(_, _)).Times(0);
461         EXPECT_CALL(*test->mComposer, getRenderIntents(_, _, _)).Times(0);
462         EXPECT_CALL(*test->mComposer, setColorMode(_, _, _)).Times(0);
463     }
464 };
465 
466 // For this variant, SurfaceFlinger should configure itself with wide display
467 // support, and the display should respond with an non-empty list of supported
468 // color modes. Wide-color support should be configured.
469 template <typename Display>
470 struct WideColorP3ColorimetricSupportedVariant {
471     static constexpr bool WIDE_COLOR_SUPPORTED = true;
472 
injectConfigChangeandroid::__anon52a382c50111::WideColorP3ColorimetricSupportedVariant473     static void injectConfigChange(DisplayTransactionTest* test) {
474         test->mFlinger.mutableHasWideColorDisplay() = true;
475         test->mFlinger.mutableDisplayColorSetting() = DisplayColorSetting::UNMANAGED;
476     }
477 
setupComposerCallExpectationsandroid::__anon52a382c50111::WideColorP3ColorimetricSupportedVariant478     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
479         EXPECT_CALL(*test->mComposer, getColorModes(Display::HWC_DISPLAY_ID, _))
480                 .WillOnce(DoAll(SetArgPointee<1>(std::vector<ColorMode>({ColorMode::DISPLAY_P3})),
481                                 Return(Error::NONE)));
482         EXPECT_CALL(*test->mComposer,
483                     getRenderIntents(Display::HWC_DISPLAY_ID, ColorMode::DISPLAY_P3, _))
484                 .WillOnce(DoAll(SetArgPointee<2>(
485                                         std::vector<RenderIntent>({RenderIntent::COLORIMETRIC})),
486                                 Return(Error::NONE)));
487         EXPECT_CALL(*test->mComposer,
488                     setColorMode(Display::HWC_DISPLAY_ID, ColorMode::SRGB,
489                                  RenderIntent::COLORIMETRIC))
490                 .WillOnce(Return(Error::NONE));
491     }
492 };
493 
494 // For this variant, SurfaceFlinger should configure itself with wide display
495 // support, but the display should respond with an empty list of supported color
496 // modes. Wide-color support for the display should not be configured.
497 template <typename Display>
498 struct WideColorNotSupportedVariant {
499     static constexpr bool WIDE_COLOR_SUPPORTED = false;
500 
injectConfigChangeandroid::__anon52a382c50111::WideColorNotSupportedVariant501     static void injectConfigChange(DisplayTransactionTest* test) {
502         test->mFlinger.mutableHasWideColorDisplay() = true;
503     }
504 
setupComposerCallExpectationsandroid::__anon52a382c50111::WideColorNotSupportedVariant505     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
506         EXPECT_CALL(*test->mComposer, getColorModes(Display::HWC_DISPLAY_ID, _))
507                 .WillOnce(DoAll(SetArgPointee<1>(std::vector<ColorMode>()), Return(Error::NONE)));
508         EXPECT_CALL(*test->mComposer, setColorMode(_, _, _)).Times(0);
509     }
510 };
511 
512 // For this variant, the display is not a HWC display, so no HDR support should
513 // be configured.
514 struct NonHwcDisplayHdrSupportVariant {
515     static constexpr bool HDR10_SUPPORTED = false;
516     static constexpr bool HDR_HLG_SUPPORTED = false;
517     static constexpr bool HDR_DOLBY_VISION_SUPPORTED = false;
setupComposerCallExpectationsandroid::__anon52a382c50111::NonHwcDisplayHdrSupportVariant518     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
519         EXPECT_CALL(*test->mComposer, getHdrCapabilities(_, _, _, _, _)).Times(0);
520     }
521 };
522 
523 // For this variant, the composer should respond with a non-empty list of HDR
524 // modes containing HDR10, so HDR10 support should be configured.
525 template <typename Display>
526 struct Hdr10SupportedVariant {
527     static constexpr bool HDR10_SUPPORTED = true;
528     static constexpr bool HDR_HLG_SUPPORTED = false;
529     static constexpr bool HDR_DOLBY_VISION_SUPPORTED = false;
setupComposerCallExpectationsandroid::__anon52a382c50111::Hdr10SupportedVariant530     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
531         EXPECT_CALL(*test->mComposer, getHdrCapabilities(Display::HWC_DISPLAY_ID, _, _, _, _))
532                 .WillOnce(DoAll(SetArgPointee<1>(std::vector<Hdr>({Hdr::HDR10})),
533                                 Return(Error::NONE)));
534     }
535 };
536 
537 // For this variant, the composer should respond with a non-empty list of HDR
538 // modes containing HLG, so HLG support should be configured.
539 template <typename Display>
540 struct HdrHlgSupportedVariant {
541     static constexpr bool HDR10_SUPPORTED = false;
542     static constexpr bool HDR_HLG_SUPPORTED = true;
543     static constexpr bool HDR_DOLBY_VISION_SUPPORTED = false;
setupComposerCallExpectationsandroid::__anon52a382c50111::HdrHlgSupportedVariant544     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
545         EXPECT_CALL(*test->mComposer, getHdrCapabilities(Display::HWC_DISPLAY_ID, _, _, _, _))
546                 .WillOnce(
547                         DoAll(SetArgPointee<1>(std::vector<Hdr>({Hdr::HLG})), Return(Error::NONE)));
548     }
549 };
550 
551 // For this variant, the composer should respond with a non-empty list of HDR
552 // modes containing DOLBY_VISION, so DOLBY_VISION support should be configured.
553 template <typename Display>
554 struct HdrDolbyVisionSupportedVariant {
555     static constexpr bool HDR10_SUPPORTED = false;
556     static constexpr bool HDR_HLG_SUPPORTED = false;
557     static constexpr bool HDR_DOLBY_VISION_SUPPORTED = true;
setupComposerCallExpectationsandroid::__anon52a382c50111::HdrDolbyVisionSupportedVariant558     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
559         EXPECT_CALL(*test->mComposer, getHdrCapabilities(Display::HWC_DISPLAY_ID, _, _, _, _))
560                 .WillOnce(DoAll(SetArgPointee<1>(std::vector<Hdr>({Hdr::DOLBY_VISION})),
561                                 Return(Error::NONE)));
562     }
563 };
564 
565 // For this variant, the composer should respond with am empty list of HDR
566 // modes, so no HDR support should be configured.
567 template <typename Display>
568 struct HdrNotSupportedVariant {
569     static constexpr bool HDR10_SUPPORTED = false;
570     static constexpr bool HDR_HLG_SUPPORTED = false;
571     static constexpr bool HDR_DOLBY_VISION_SUPPORTED = false;
setupComposerCallExpectationsandroid::__anon52a382c50111::HdrNotSupportedVariant572     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
573         EXPECT_CALL(*test->mComposer, getHdrCapabilities(Display::HWC_DISPLAY_ID, _, _, _, _))
574                 .WillOnce(DoAll(SetArgPointee<1>(std::vector<Hdr>()), Return(Error::NONE)));
575     }
576 };
577 
578 struct NonHwcPerFrameMetadataSupportVariant {
579     static constexpr int PER_FRAME_METADATA_KEYS = 0;
setupComposerCallExpectationsandroid::__anon52a382c50111::NonHwcPerFrameMetadataSupportVariant580     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
581         EXPECT_CALL(*test->mComposer, getPerFrameMetadataKeys(_, _)).Times(0);
582     }
583 };
584 
585 template <typename Display>
586 struct NoPerFrameMetadataSupportVariant {
587     static constexpr int PER_FRAME_METADATA_KEYS = 0;
setupComposerCallExpectationsandroid::__anon52a382c50111::NoPerFrameMetadataSupportVariant588     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
589         EXPECT_CALL(*test->mComposer, getPerFrameMetadataKeys(Display::HWC_DISPLAY_ID, _))
590                 .WillOnce(DoAll(SetArgPointee<1>(std::vector<PerFrameMetadataKey>()),
591                                 Return(Error::NONE)));
592     }
593 };
594 
595 template <typename Display>
596 struct Smpte2086PerFrameMetadataSupportVariant {
597     static constexpr int PER_FRAME_METADATA_KEYS = HdrMetadata::Type::SMPTE2086;
setupComposerCallExpectationsandroid::__anon52a382c50111::Smpte2086PerFrameMetadataSupportVariant598     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
599         EXPECT_CALL(*test->mComposer, getPerFrameMetadataKeys(Display::HWC_DISPLAY_ID, _))
600                 .WillOnce(DoAll(SetArgPointee<1>(std::vector<PerFrameMetadataKey>({
601                                         PerFrameMetadataKey::DISPLAY_RED_PRIMARY_X,
602                                         PerFrameMetadataKey::DISPLAY_RED_PRIMARY_Y,
603                                         PerFrameMetadataKey::DISPLAY_GREEN_PRIMARY_X,
604                                         PerFrameMetadataKey::DISPLAY_GREEN_PRIMARY_Y,
605                                         PerFrameMetadataKey::DISPLAY_BLUE_PRIMARY_X,
606                                         PerFrameMetadataKey::DISPLAY_BLUE_PRIMARY_Y,
607                                         PerFrameMetadataKey::WHITE_POINT_X,
608                                         PerFrameMetadataKey::WHITE_POINT_Y,
609                                         PerFrameMetadataKey::MAX_LUMINANCE,
610                                         PerFrameMetadataKey::MIN_LUMINANCE,
611                                 })),
612                                 Return(Error::NONE)));
613     }
614 };
615 
616 template <typename Display>
617 struct Cta861_3_PerFrameMetadataSupportVariant {
618     static constexpr int PER_FRAME_METADATA_KEYS = HdrMetadata::Type::CTA861_3;
setupComposerCallExpectationsandroid::__anon52a382c50111::Cta861_3_PerFrameMetadataSupportVariant619     static void setupComposerCallExpectations(DisplayTransactionTest* test) {
620         EXPECT_CALL(*test->mComposer, getPerFrameMetadataKeys(Display::HWC_DISPLAY_ID, _))
621                 .WillOnce(DoAll(SetArgPointee<1>(std::vector<PerFrameMetadataKey>({
622                                         PerFrameMetadataKey::MAX_CONTENT_LIGHT_LEVEL,
623                                         PerFrameMetadataKey::MAX_FRAME_AVERAGE_LIGHT_LEVEL,
624                                 })),
625                                 Return(Error::NONE)));
626     }
627 };
628 
629 /* ------------------------------------------------------------------------
630  * Typical display configurations to test
631  */
632 
633 template <typename DisplayPolicy, typename WideColorSupportPolicy, typename HdrSupportPolicy,
634           typename PerFrameMetadataSupportPolicy>
635 struct Case {
636     using Display = DisplayPolicy;
637     using WideColorSupport = WideColorSupportPolicy;
638     using HdrSupport = HdrSupportPolicy;
639     using PerFrameMetadataSupport = PerFrameMetadataSupportPolicy;
640 };
641 
642 using SimplePrimaryDisplayCase =
643         Case<PrimaryDisplayVariant, WideColorNotSupportedVariant<PrimaryDisplayVariant>,
644              HdrNotSupportedVariant<PrimaryDisplayVariant>,
645              NoPerFrameMetadataSupportVariant<PrimaryDisplayVariant>>;
646 using SimpleExternalDisplayCase =
647         Case<ExternalDisplayVariant, WideColorNotSupportedVariant<ExternalDisplayVariant>,
648              HdrNotSupportedVariant<ExternalDisplayVariant>,
649              NoPerFrameMetadataSupportVariant<ExternalDisplayVariant>>;
650 using SimpleTertiaryDisplayCase =
651         Case<TertiaryDisplayVariant, WideColorNotSupportedVariant<TertiaryDisplayVariant>,
652              HdrNotSupportedVariant<TertiaryDisplayVariant>,
653              NoPerFrameMetadataSupportVariant<TertiaryDisplayVariant>>;
654 using NonHwcVirtualDisplayCase =
655         Case<NonHwcVirtualDisplayVariant<1024, 768, Secure::FALSE>,
656              WideColorSupportNotConfiguredVariant, NonHwcDisplayHdrSupportVariant,
657              NonHwcPerFrameMetadataSupportVariant>;
658 using SimpleHwcVirtualDisplayVariant = HwcVirtualDisplayVariant<1024, 768, Secure::TRUE>;
659 using HwcVirtualDisplayCase =
660         Case<SimpleHwcVirtualDisplayVariant, WideColorSupportNotConfiguredVariant,
661              HdrNotSupportedVariant<SimpleHwcVirtualDisplayVariant>,
662              NoPerFrameMetadataSupportVariant<SimpleHwcVirtualDisplayVariant>>;
663 using WideColorP3ColorimetricDisplayCase =
664         Case<PrimaryDisplayVariant, WideColorP3ColorimetricSupportedVariant<PrimaryDisplayVariant>,
665              HdrNotSupportedVariant<PrimaryDisplayVariant>,
666              NoPerFrameMetadataSupportVariant<PrimaryDisplayVariant>>;
667 using Hdr10DisplayCase =
668         Case<PrimaryDisplayVariant, WideColorNotSupportedVariant<PrimaryDisplayVariant>,
669              Hdr10SupportedVariant<PrimaryDisplayVariant>,
670              NoPerFrameMetadataSupportVariant<PrimaryDisplayVariant>>;
671 using HdrHlgDisplayCase =
672         Case<PrimaryDisplayVariant, WideColorNotSupportedVariant<PrimaryDisplayVariant>,
673              HdrHlgSupportedVariant<PrimaryDisplayVariant>,
674              NoPerFrameMetadataSupportVariant<PrimaryDisplayVariant>>;
675 using HdrDolbyVisionDisplayCase =
676         Case<PrimaryDisplayVariant, WideColorNotSupportedVariant<PrimaryDisplayVariant>,
677              HdrDolbyVisionSupportedVariant<PrimaryDisplayVariant>,
678              NoPerFrameMetadataSupportVariant<PrimaryDisplayVariant>>;
679 using HdrSmpte2086DisplayCase =
680         Case<PrimaryDisplayVariant, WideColorNotSupportedVariant<PrimaryDisplayVariant>,
681              HdrNotSupportedVariant<PrimaryDisplayVariant>,
682              Smpte2086PerFrameMetadataSupportVariant<PrimaryDisplayVariant>>;
683 using HdrCta861_3_DisplayCase =
684         Case<PrimaryDisplayVariant, WideColorNotSupportedVariant<PrimaryDisplayVariant>,
685              HdrNotSupportedVariant<PrimaryDisplayVariant>,
686              Cta861_3_PerFrameMetadataSupportVariant<PrimaryDisplayVariant>>;
687 using InvalidDisplayCase = Case<InvalidDisplayVariant, WideColorSupportNotConfiguredVariant,
688                                 NonHwcDisplayHdrSupportVariant,
689                                 NoPerFrameMetadataSupportVariant<InvalidDisplayVariant>>;
690 /* ------------------------------------------------------------------------
691  *
692  * SurfaceFlinger::onHotplugReceived
693  */
694 
TEST_F(DisplayTransactionTest,hotplugEnqueuesEventsForDisplayTransaction)695 TEST_F(DisplayTransactionTest, hotplugEnqueuesEventsForDisplayTransaction) {
696     constexpr int currentSequenceId = 123;
697     constexpr hwc2_display_t displayId1 = 456;
698     constexpr hwc2_display_t displayId2 = 654;
699 
700     // --------------------------------------------------------------------
701     // Preconditions
702 
703     // Set the current sequence id for accepted events
704     mFlinger.mutableComposerSequenceId() = currentSequenceId;
705 
706     // Set the main thread id so that the current thread does not appear to be
707     // the main thread.
708     mFlinger.mutableMainThreadId() = std::thread::id();
709 
710     // --------------------------------------------------------------------
711     // Call Expectations
712 
713     // We expect invalidate() to be invoked once to trigger display transaction
714     // processing.
715     EXPECT_CALL(*mMessageQueue, invalidate()).Times(1);
716 
717     // --------------------------------------------------------------------
718     // Invocation
719 
720     // Simulate two hotplug events (a connect and a disconnect)
721     mFlinger.onHotplugReceived(currentSequenceId, displayId1, HWC2::Connection::Connected);
722     mFlinger.onHotplugReceived(currentSequenceId, displayId2, HWC2::Connection::Disconnected);
723 
724     // --------------------------------------------------------------------
725     // Postconditions
726 
727     // The display transaction needed flag should be set.
728     EXPECT_TRUE(hasTransactionFlagSet(eDisplayTransactionNeeded));
729 
730     // All events should be in the pending event queue.
731     const auto& pendingEvents = mFlinger.mutablePendingHotplugEvents();
732     ASSERT_EQ(2u, pendingEvents.size());
733     EXPECT_EQ(displayId1, pendingEvents[0].display);
734     EXPECT_EQ(HWC2::Connection::Connected, pendingEvents[0].connection);
735     EXPECT_EQ(displayId2, pendingEvents[1].display);
736     EXPECT_EQ(HWC2::Connection::Disconnected, pendingEvents[1].connection);
737 }
738 
TEST_F(DisplayTransactionTest,hotplugDiscardsUnexpectedEvents)739 TEST_F(DisplayTransactionTest, hotplugDiscardsUnexpectedEvents) {
740     constexpr int currentSequenceId = 123;
741     constexpr int otherSequenceId = 321;
742     constexpr hwc2_display_t displayId = 456;
743 
744     // --------------------------------------------------------------------
745     // Preconditions
746 
747     // Set the current sequence id for accepted events
748     mFlinger.mutableComposerSequenceId() = currentSequenceId;
749 
750     // Set the main thread id so that the current thread does not appear to be
751     // the main thread.
752     mFlinger.mutableMainThreadId() = std::thread::id();
753 
754     // --------------------------------------------------------------------
755     // Call Expectations
756 
757     // We do not expect any calls to invalidate().
758     EXPECT_CALL(*mMessageQueue, invalidate()).Times(0);
759 
760     // --------------------------------------------------------------------
761     // Invocation
762 
763     // Call with an unexpected sequence id
764     mFlinger.onHotplugReceived(otherSequenceId, displayId, HWC2::Connection::Invalid);
765 
766     // --------------------------------------------------------------------
767     // Postconditions
768 
769     // The display transaction needed flag should not be set
770     EXPECT_FALSE(hasTransactionFlagSet(eDisplayTransactionNeeded));
771 
772     // There should be no pending events
773     EXPECT_TRUE(mFlinger.mutablePendingHotplugEvents().empty());
774 }
775 
TEST_F(DisplayTransactionTest,hotplugProcessesEnqueuedEventsIfCalledOnMainThread)776 TEST_F(DisplayTransactionTest, hotplugProcessesEnqueuedEventsIfCalledOnMainThread) {
777     constexpr int currentSequenceId = 123;
778     constexpr hwc2_display_t displayId1 = 456;
779 
780     // --------------------------------------------------------------------
781     // Note:
782     // --------------------------------------------------------------------
783     // This test case is a bit tricky. We want to verify that
784     // onHotplugReceived() calls processDisplayHotplugEventsLocked(), but we
785     // don't really want to provide coverage for everything the later function
786     // does as there are specific tests for it.
787     // --------------------------------------------------------------------
788 
789     // --------------------------------------------------------------------
790     // Preconditions
791 
792     // Set the current sequence id for accepted events
793     mFlinger.mutableComposerSequenceId() = currentSequenceId;
794 
795     // Set the main thread id so that the current thread does appear to be the
796     // main thread.
797     mFlinger.mutableMainThreadId() = std::this_thread::get_id();
798 
799     // --------------------------------------------------------------------
800     // Call Expectations
801 
802     // We expect invalidate() to be invoked once to trigger display transaction
803     // processing.
804     EXPECT_CALL(*mMessageQueue, invalidate()).Times(1);
805 
806     // --------------------------------------------------------------------
807     // Invocation
808 
809     // Simulate a disconnect on a display id that is not connected. This should
810     // be enqueued by onHotplugReceived(), and dequeued by
811     // processDisplayHotplugEventsLocked(), but then ignored as invalid.
812     mFlinger.onHotplugReceived(currentSequenceId, displayId1, HWC2::Connection::Disconnected);
813 
814     // --------------------------------------------------------------------
815     // Postconditions
816 
817     // The display transaction needed flag should be set.
818     EXPECT_TRUE(hasTransactionFlagSet(eDisplayTransactionNeeded));
819 
820     // There should be no event queued on return, as it should have been
821     // processed.
822     EXPECT_TRUE(mFlinger.mutablePendingHotplugEvents().empty());
823 }
824 
825 /* ------------------------------------------------------------------------
826  * SurfaceFlinger::createDisplay
827  */
828 
TEST_F(DisplayTransactionTest,createDisplaySetsCurrentStateForNonsecureDisplay)829 TEST_F(DisplayTransactionTest, createDisplaySetsCurrentStateForNonsecureDisplay) {
830     const String8 name("virtual.test");
831 
832     // --------------------------------------------------------------------
833     // Call Expectations
834 
835     // The call should notify the interceptor that a display was created.
836     EXPECT_CALL(*mSurfaceInterceptor, saveDisplayCreation(_)).Times(1);
837 
838     // --------------------------------------------------------------------
839     // Invocation
840 
841     sp<IBinder> displayToken = mFlinger.createDisplay(name, false);
842 
843     // --------------------------------------------------------------------
844     // Postconditions
845 
846     // The display should have been added to the current state
847     ASSERT_TRUE(hasCurrentDisplayState(displayToken));
848     const auto& display = getCurrentDisplayState(displayToken);
849     EXPECT_EQ(DisplayDevice::DISPLAY_VIRTUAL, display.type);
850     EXPECT_EQ(false, display.isSecure);
851     EXPECT_EQ(name.string(), display.displayName);
852 
853     // --------------------------------------------------------------------
854     // Cleanup conditions
855 
856     // Destroying the display invalidates the display state.
857     EXPECT_CALL(*mMessageQueue, invalidate()).Times(1);
858 }
859 
TEST_F(DisplayTransactionTest,createDisplaySetsCurrentStateForSecureDisplay)860 TEST_F(DisplayTransactionTest, createDisplaySetsCurrentStateForSecureDisplay) {
861     const String8 name("virtual.test");
862 
863     // --------------------------------------------------------------------
864     // Call Expectations
865 
866     // The call should notify the interceptor that a display was created.
867     EXPECT_CALL(*mSurfaceInterceptor, saveDisplayCreation(_)).Times(1);
868 
869     // --------------------------------------------------------------------
870     // Invocation
871 
872     sp<IBinder> displayToken = mFlinger.createDisplay(name, true);
873 
874     // --------------------------------------------------------------------
875     // Postconditions
876 
877     // The display should have been added to the current state
878     ASSERT_TRUE(hasCurrentDisplayState(displayToken));
879     const auto& display = getCurrentDisplayState(displayToken);
880     EXPECT_EQ(DisplayDevice::DISPLAY_VIRTUAL, display.type);
881     EXPECT_EQ(true, display.isSecure);
882     EXPECT_EQ(name.string(), display.displayName);
883 
884     // --------------------------------------------------------------------
885     // Cleanup conditions
886 
887     // Destroying the display invalidates the display state.
888     EXPECT_CALL(*mMessageQueue, invalidate()).Times(1);
889 }
890 
891 /* ------------------------------------------------------------------------
892  * SurfaceFlinger::destroyDisplay
893  */
894 
TEST_F(DisplayTransactionTest,destroyDisplayClearsCurrentStateForDisplay)895 TEST_F(DisplayTransactionTest, destroyDisplayClearsCurrentStateForDisplay) {
896     using Case = NonHwcVirtualDisplayCase;
897 
898     // --------------------------------------------------------------------
899     // Preconditions
900 
901     // A virtual display exists
902     auto existing = Case::Display::makeFakeExistingDisplayInjector(this);
903     existing.inject();
904 
905     // --------------------------------------------------------------------
906     // Call Expectations
907 
908     // The call should notify the interceptor that a display was created.
909     EXPECT_CALL(*mSurfaceInterceptor, saveDisplayDeletion(_)).Times(1);
910 
911     // Destroying the display invalidates the display state.
912     EXPECT_CALL(*mMessageQueue, invalidate()).Times(1);
913 
914     // --------------------------------------------------------------------
915     // Invocation
916 
917     mFlinger.destroyDisplay(existing.token());
918 
919     // --------------------------------------------------------------------
920     // Postconditions
921 
922     // The display should have been removed from the current state
923     EXPECT_FALSE(hasCurrentDisplayState(existing.token()));
924 
925     // Ths display should still exist in the drawing state
926     EXPECT_TRUE(hasDrawingDisplayState(existing.token()));
927 
928     // The display transaction needed flasg should be set
929     EXPECT_TRUE(hasTransactionFlagSet(eDisplayTransactionNeeded));
930 }
931 
TEST_F(DisplayTransactionTest,destroyDisplayHandlesUnknownDisplay)932 TEST_F(DisplayTransactionTest, destroyDisplayHandlesUnknownDisplay) {
933     // --------------------------------------------------------------------
934     // Preconditions
935 
936     sp<BBinder> displayToken = new BBinder();
937 
938     // --------------------------------------------------------------------
939     // Invocation
940 
941     mFlinger.destroyDisplay(displayToken);
942 }
943 
944 /* ------------------------------------------------------------------------
945  * SurfaceFlinger::resetDisplayState
946  */
947 
TEST_F(DisplayTransactionTest,resetDisplayStateClearsState)948 TEST_F(DisplayTransactionTest, resetDisplayStateClearsState) {
949     using Case = NonHwcVirtualDisplayCase;
950 
951     // --------------------------------------------------------------------
952     // Preconditions
953 
954     // vsync is enabled and available
955     mFlinger.mutablePrimaryHWVsyncEnabled() = true;
956     mFlinger.mutableHWVsyncAvailable() = true;
957 
958     // A display exists
959     auto existing = Case::Display::makeFakeExistingDisplayInjector(this);
960     existing.inject();
961 
962     // --------------------------------------------------------------------
963     // Call Expectations
964 
965     // The call disable vsyncs
966     EXPECT_CALL(*mEventControlThread, setVsyncEnabled(false)).Times(1);
967 
968     // The call clears the current render engine surface
969     EXPECT_CALL(*mRenderEngine, resetCurrentSurface());
970 
971     // --------------------------------------------------------------------
972     // Invocation
973 
974     mFlinger.resetDisplayState();
975 
976     // --------------------------------------------------------------------
977     // Postconditions
978 
979     // vsyncs should be off and not available.
980     EXPECT_FALSE(mFlinger.mutablePrimaryHWVsyncEnabled());
981     EXPECT_FALSE(mFlinger.mutableHWVsyncAvailable());
982 
983     // The display should have been removed from the display map.
984     EXPECT_FALSE(hasDisplayDevice(existing.token()));
985 
986     // The display should still exist in the current state
987     EXPECT_TRUE(hasCurrentDisplayState(existing.token()));
988 
989     // The display should have been removed from the drawing state
990     EXPECT_FALSE(hasDrawingDisplayState(existing.token()));
991 }
992 
993 /* ------------------------------------------------------------------------
994  * SurfaceFlinger::setupNewDisplayDeviceInternal
995  */
996 
997 class SetupNewDisplayDeviceInternalTest : public DisplayTransactionTest {
998 public:
999     template <typename T>
1000     void setupNewDisplayDeviceInternalTest();
1001 };
1002 
1003 template <typename Case>
setupNewDisplayDeviceInternalTest()1004 void SetupNewDisplayDeviceInternalTest::setupNewDisplayDeviceInternalTest() {
1005     const sp<BBinder> displayToken = new BBinder();
1006     const sp<mock::DisplaySurface> displaySurface = new mock::DisplaySurface();
1007     const sp<mock::GraphicBufferProducer> producer = new mock::GraphicBufferProducer();
1008 
1009     // --------------------------------------------------------------------
1010     // Preconditions
1011 
1012     // Wide color displays support is configured appropriately
1013     Case::WideColorSupport::injectConfigChange(this);
1014 
1015     // The display is setup with the HWC.
1016     Case::Display::injectHwcDisplay(this);
1017 
1018     // SurfaceFlinger will use a test-controlled factory for native window
1019     // surfaces.
1020     injectFakeNativeWindowSurfaceFactory();
1021 
1022     // --------------------------------------------------------------------
1023     // Call Expectations
1024 
1025     // Various native window calls will be made.
1026     Case::Display::setupNativeWindowSurfaceCreationCallExpectations(this);
1027     Case::Display::setupHwcGetActiveConfigCallExpectations(this);
1028     Case::WideColorSupport::setupComposerCallExpectations(this);
1029     Case::HdrSupport::setupComposerCallExpectations(this);
1030     Case::PerFrameMetadataSupport::setupComposerCallExpectations(this);
1031 
1032     // --------------------------------------------------------------------
1033     // Invocation
1034 
1035     auto state = DisplayDeviceState(Case::Display::TYPE, static_cast<bool>(Case::Display::SECURE));
1036     auto device = mFlinger.setupNewDisplayDeviceInternal(displayToken, Case::Display::TYPE, state,
1037                                                          displaySurface, producer);
1038 
1039     // --------------------------------------------------------------------
1040     // Postconditions
1041 
1042     ASSERT_TRUE(device != nullptr);
1043     EXPECT_EQ(Case::Display::TYPE, device->getDisplayType());
1044     EXPECT_EQ(static_cast<bool>(Case::Display::SECURE), device->isSecure());
1045     EXPECT_EQ(Case::Display::WIDTH, device->getWidth());
1046     EXPECT_EQ(Case::Display::HEIGHT, device->getHeight());
1047     EXPECT_EQ(Case::WideColorSupport::WIDE_COLOR_SUPPORTED, device->hasWideColorGamut());
1048     EXPECT_EQ(Case::HdrSupport::HDR10_SUPPORTED, device->hasHDR10Support());
1049     EXPECT_EQ(Case::HdrSupport::HDR_HLG_SUPPORTED, device->hasHLGSupport());
1050     EXPECT_EQ(Case::HdrSupport::HDR_DOLBY_VISION_SUPPORTED, device->hasDolbyVisionSupport());
1051     // Note: This is not Case::Display::HWC_ACTIVE_CONFIG_ID as the ids are
1052     // remapped, and the test only ever sets up one config. If there were an error
1053     // looking up the remapped index, device->getActiveConfig() would be -1 instead.
1054     EXPECT_EQ(0, device->getActiveConfig());
1055     EXPECT_EQ(Case::PerFrameMetadataSupport::PER_FRAME_METADATA_KEYS,
1056               device->getSupportedPerFrameMetadata());
1057 }
1058 
TEST_F(SetupNewDisplayDeviceInternalTest,createSimplePrimaryDisplay)1059 TEST_F(SetupNewDisplayDeviceInternalTest, createSimplePrimaryDisplay) {
1060     setupNewDisplayDeviceInternalTest<SimplePrimaryDisplayCase>();
1061 }
1062 
TEST_F(SetupNewDisplayDeviceInternalTest,createSimpleExternalDisplay)1063 TEST_F(SetupNewDisplayDeviceInternalTest, createSimpleExternalDisplay) {
1064     setupNewDisplayDeviceInternalTest<SimpleExternalDisplayCase>();
1065 }
1066 
TEST_F(SetupNewDisplayDeviceInternalTest,createNonHwcVirtualDisplay)1067 TEST_F(SetupNewDisplayDeviceInternalTest, createNonHwcVirtualDisplay) {
1068     setupNewDisplayDeviceInternalTest<NonHwcVirtualDisplayCase>();
1069 }
1070 
TEST_F(SetupNewDisplayDeviceInternalTest,createHwcVirtualDisplay)1071 TEST_F(SetupNewDisplayDeviceInternalTest, createHwcVirtualDisplay) {
1072     // We need to resize this so that the HWC thinks the virtual display
1073     // is something it created.
1074     mFlinger.mutableHwcDisplayData().resize(3);
1075 
1076     setupNewDisplayDeviceInternalTest<HwcVirtualDisplayCase>();
1077 }
1078 
TEST_F(SetupNewDisplayDeviceInternalTest,createWideColorP3Display)1079 TEST_F(SetupNewDisplayDeviceInternalTest, createWideColorP3Display) {
1080     setupNewDisplayDeviceInternalTest<WideColorP3ColorimetricDisplayCase>();
1081 }
1082 
TEST_F(SetupNewDisplayDeviceInternalTest,createHdr10Display)1083 TEST_F(SetupNewDisplayDeviceInternalTest, createHdr10Display) {
1084     setupNewDisplayDeviceInternalTest<Hdr10DisplayCase>();
1085 }
1086 
TEST_F(SetupNewDisplayDeviceInternalTest,createHdrHlgDisplay)1087 TEST_F(SetupNewDisplayDeviceInternalTest, createHdrHlgDisplay) {
1088     setupNewDisplayDeviceInternalTest<HdrHlgDisplayCase>();
1089 }
1090 
TEST_F(SetupNewDisplayDeviceInternalTest,createHdrDolbyVisionDisplay)1091 TEST_F(SetupNewDisplayDeviceInternalTest, createHdrDolbyVisionDisplay) {
1092     setupNewDisplayDeviceInternalTest<HdrDolbyVisionDisplayCase>();
1093 }
1094 
TEST_F(SetupNewDisplayDeviceInternalTest,createHdrSmpte2086DisplayCase)1095 TEST_F(SetupNewDisplayDeviceInternalTest, createHdrSmpte2086DisplayCase) {
1096     setupNewDisplayDeviceInternalTest<HdrSmpte2086DisplayCase>();
1097 }
1098 
TEST_F(SetupNewDisplayDeviceInternalTest,createHdrCta816_3_DisplayCase)1099 TEST_F(SetupNewDisplayDeviceInternalTest, createHdrCta816_3_DisplayCase) {
1100     setupNewDisplayDeviceInternalTest<HdrCta861_3_DisplayCase>();
1101 }
1102 
1103 /* ------------------------------------------------------------------------
1104  * SurfaceFlinger::handleTransactionLocked(eDisplayTransactionNeeded)
1105  */
1106 
1107 class HandleTransactionLockedTest : public DisplayTransactionTest {
1108 public:
1109     template <typename Case>
1110     void setupCommonPreconditions();
1111 
1112     template <typename Case>
1113     void setupCommonCallExpectationsForConnectProcessing();
1114 
1115     template <typename Case>
1116     void setupCommonCallExpectationsForDisconnectProcessing();
1117 
1118     template <typename Case>
1119     void processesHotplugConnectCommon();
1120 
1121     template <typename Case>
1122     void ignoresHotplugConnectCommon();
1123 
1124     template <typename Case>
1125     void processesHotplugDisconnectCommon();
1126 
1127     template <typename Case>
1128     void verifyDisplayIsConnected(const sp<IBinder>& displayToken);
1129 
1130     template <typename Case>
1131     void verifyPhysicalDisplayIsConnected();
1132 
1133     void verifyDisplayIsNotConnected(const sp<IBinder>& displayToken);
1134 };
1135 
1136 template <typename Case>
setupCommonPreconditions()1137 void HandleTransactionLockedTest::setupCommonPreconditions() {
1138     // Wide color displays support is configured appropriately
1139     Case::WideColorSupport::injectConfigChange(this);
1140 
1141     // SurfaceFlinger will use a test-controlled factory for BufferQueues
1142     injectFakeBufferQueueFactory();
1143 
1144     // SurfaceFlinger will use a test-controlled factory for native window
1145     // surfaces.
1146     injectFakeNativeWindowSurfaceFactory();
1147 }
1148 
1149 template <typename Case>
setupCommonCallExpectationsForConnectProcessing()1150 void HandleTransactionLockedTest::setupCommonCallExpectationsForConnectProcessing() {
1151     Case::Display::setupHwcHotplugCallExpectations(this);
1152 
1153     Case::Display::setupFramebufferConsumerBufferQueueCallExpectations(this);
1154     Case::Display::setupFramebufferProducerBufferQueueCallExpectations(this);
1155     Case::Display::setupNativeWindowSurfaceCreationCallExpectations(this);
1156     Case::Display::setupHwcGetActiveConfigCallExpectations(this);
1157 
1158     Case::WideColorSupport::setupComposerCallExpectations(this);
1159     Case::HdrSupport::setupComposerCallExpectations(this);
1160     Case::PerFrameMetadataSupport::setupComposerCallExpectations(this);
1161 
1162     EXPECT_CALL(*mSurfaceInterceptor, saveDisplayCreation(_)).Times(1);
1163     EXPECT_CALL(*mEventThread, onHotplugReceived(Case::Display::TYPE, true)).Times(1);
1164 }
1165 
1166 template <typename Case>
setupCommonCallExpectationsForDisconnectProcessing()1167 void HandleTransactionLockedTest::setupCommonCallExpectationsForDisconnectProcessing() {
1168     EXPECT_CALL(*mSurfaceInterceptor, saveDisplayDeletion(_)).Times(1);
1169     EXPECT_CALL(*mEventThread, onHotplugReceived(Case::Display::TYPE, false)).Times(1);
1170 }
1171 
1172 template <typename Case>
verifyDisplayIsConnected(const sp<IBinder> & displayToken)1173 void HandleTransactionLockedTest::verifyDisplayIsConnected(const sp<IBinder>& displayToken) {
1174     // The display device should have been set up in the list of displays.
1175     ASSERT_TRUE(hasDisplayDevice(displayToken));
1176     const auto& device = getDisplayDevice(displayToken);
1177     EXPECT_EQ(static_cast<bool>(Case::Display::SECURE), device->isSecure());
1178     EXPECT_EQ(Case::Display::TYPE == DisplayDevice::DISPLAY_PRIMARY, device->isPrimary());
1179 
1180     // The display should have been set up in the current display state
1181     ASSERT_TRUE(hasCurrentDisplayState(displayToken));
1182     const auto& current = getCurrentDisplayState(displayToken);
1183     EXPECT_EQ(Case::Display::TYPE, current.type);
1184 
1185     // The display should have been set up in the drawing display state
1186     ASSERT_TRUE(hasDrawingDisplayState(displayToken));
1187     const auto& draw = getDrawingDisplayState(displayToken);
1188     EXPECT_EQ(Case::Display::TYPE, draw.type);
1189 }
1190 
1191 template <typename Case>
verifyPhysicalDisplayIsConnected()1192 void HandleTransactionLockedTest::verifyPhysicalDisplayIsConnected() {
1193     // HWComposer should have an entry for the display
1194     EXPECT_TRUE(hasHwcDisplay(Case::Display::HWC_DISPLAY_ID));
1195 
1196     // The display should be set up as a built-in display.
1197     static_assert(0 <= Case::Display::TYPE &&
1198                           Case::Display::TYPE < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES,
1199                   "Must use a valid physical display type index for the fixed-size array");
1200     auto& displayToken = mFlinger.mutableBuiltinDisplays()[Case::Display::TYPE];
1201     ASSERT_TRUE(displayToken != nullptr);
1202 
1203     verifyDisplayIsConnected<Case>(displayToken);
1204 }
1205 
verifyDisplayIsNotConnected(const sp<IBinder> & displayToken)1206 void HandleTransactionLockedTest::verifyDisplayIsNotConnected(const sp<IBinder>& displayToken) {
1207     EXPECT_FALSE(hasDisplayDevice(displayToken));
1208     EXPECT_FALSE(hasCurrentDisplayState(displayToken));
1209     EXPECT_FALSE(hasDrawingDisplayState(displayToken));
1210 }
1211 
1212 template <typename Case>
processesHotplugConnectCommon()1213 void HandleTransactionLockedTest::processesHotplugConnectCommon() {
1214     // --------------------------------------------------------------------
1215     // Preconditions
1216 
1217     setupCommonPreconditions<Case>();
1218 
1219     // A hotplug connect event is enqueued for a display
1220     Case::Display::injectPendingHotplugEvent(this, HWC2::Connection::Connected);
1221 
1222     // --------------------------------------------------------------------
1223     // Call Expectations
1224 
1225     EXPECT_CALL(*mComposer, isUsingVrComposer()).WillOnce(Return(false));
1226 
1227     setupCommonCallExpectationsForConnectProcessing<Case>();
1228 
1229     // --------------------------------------------------------------------
1230     // Invocation
1231 
1232     mFlinger.handleTransactionLocked(eDisplayTransactionNeeded);
1233 
1234     // --------------------------------------------------------------------
1235     // Postconditions
1236 
1237     verifyPhysicalDisplayIsConnected<Case>();
1238 
1239     // --------------------------------------------------------------------
1240     // Cleanup conditions
1241 
1242     EXPECT_CALL(*mComposer,
1243                 setVsyncEnabled(Case::Display::HWC_DISPLAY_ID, IComposerClient::Vsync::DISABLE))
1244             .WillOnce(Return(Error::NONE));
1245     EXPECT_CALL(*mConsumer, consumerDisconnect()).WillOnce(Return(NO_ERROR));
1246 }
1247 
1248 template <typename Case>
ignoresHotplugConnectCommon()1249 void HandleTransactionLockedTest::ignoresHotplugConnectCommon() {
1250     // --------------------------------------------------------------------
1251     // Preconditions
1252 
1253     setupCommonPreconditions<Case>();
1254 
1255     // A hotplug connect event is enqueued for a display
1256     Case::Display::injectPendingHotplugEvent(this, HWC2::Connection::Connected);
1257 
1258     // --------------------------------------------------------------------
1259     // Invocation
1260 
1261     mFlinger.handleTransactionLocked(eDisplayTransactionNeeded);
1262 
1263     // --------------------------------------------------------------------
1264     // Postconditions
1265 
1266     // HWComposer should not have an entry for the display
1267     EXPECT_FALSE(hasHwcDisplay(Case::Display::HWC_DISPLAY_ID));
1268 }
1269 
1270 template <typename Case>
processesHotplugDisconnectCommon()1271 void HandleTransactionLockedTest::processesHotplugDisconnectCommon() {
1272     // --------------------------------------------------------------------
1273     // Preconditions
1274 
1275     setupCommonPreconditions<Case>();
1276 
1277     // A hotplug disconnect event is enqueued for a display
1278     Case::Display::injectPendingHotplugEvent(this, HWC2::Connection::Disconnected);
1279 
1280     // The display is already completely set up.
1281     Case::Display::injectHwcDisplay(this);
1282     auto existing = Case::Display::makeFakeExistingDisplayInjector(this);
1283     existing.inject();
1284 
1285     // --------------------------------------------------------------------
1286     // Call Expectations
1287 
1288     EXPECT_CALL(*mComposer, isUsingVrComposer()).WillRepeatedly(Return(false));
1289 
1290     setupCommonCallExpectationsForDisconnectProcessing<Case>();
1291 
1292     // --------------------------------------------------------------------
1293     // Invocation
1294 
1295     mFlinger.handleTransactionLocked(eDisplayTransactionNeeded);
1296 
1297     // --------------------------------------------------------------------
1298     // Postconditions
1299 
1300     // HWComposer should not have an entry for the display
1301     EXPECT_FALSE(hasHwcDisplay(Case::Display::HWC_DISPLAY_ID));
1302 
1303     // The display should not be set up as a built-in display.
1304     ASSERT_TRUE(0 <= Case::Display::TYPE &&
1305                 Case::Display::TYPE < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES);
1306     auto displayToken = mFlinger.mutableBuiltinDisplays()[Case::Display::TYPE];
1307     EXPECT_TRUE(displayToken == nullptr);
1308 
1309     // The existing token should have been removed
1310     verifyDisplayIsNotConnected(existing.token());
1311 }
1312 
TEST_F(HandleTransactionLockedTest,processesHotplugConnectPrimaryDisplay)1313 TEST_F(HandleTransactionLockedTest, processesHotplugConnectPrimaryDisplay) {
1314     processesHotplugConnectCommon<SimplePrimaryDisplayCase>();
1315 }
1316 
TEST_F(HandleTransactionLockedTest,processesHotplugConnectPrimaryDisplayWithExternalAlreadyConnected)1317 TEST_F(HandleTransactionLockedTest,
1318        processesHotplugConnectPrimaryDisplayWithExternalAlreadyConnected) {
1319     // Inject an external display.
1320     ExternalDisplayVariant::injectHwcDisplay(this);
1321 
1322     processesHotplugConnectCommon<SimplePrimaryDisplayCase>();
1323 }
1324 
TEST_F(HandleTransactionLockedTest,processesHotplugConnectExternalDisplay)1325 TEST_F(HandleTransactionLockedTest, processesHotplugConnectExternalDisplay) {
1326     // Inject a primary display.
1327     PrimaryDisplayVariant::injectHwcDisplay(this);
1328 
1329     processesHotplugConnectCommon<SimpleExternalDisplayCase>();
1330 }
1331 
TEST_F(HandleTransactionLockedTest,ignoresHotplugConnectIfPrimaryAndExternalAlreadyConnected)1332 TEST_F(HandleTransactionLockedTest, ignoresHotplugConnectIfPrimaryAndExternalAlreadyConnected) {
1333     // Inject both a primary and external display.
1334     PrimaryDisplayVariant::injectHwcDisplay(this);
1335     ExternalDisplayVariant::injectHwcDisplay(this);
1336 
1337     EXPECT_CALL(*mComposer, isUsingVrComposer()).WillRepeatedly(Return(false));
1338 
1339     ignoresHotplugConnectCommon<SimpleTertiaryDisplayCase>();
1340 }
1341 
TEST_F(HandleTransactionLockedTest,ignoresHotplugConnectIfExternalForVrComposer)1342 TEST_F(HandleTransactionLockedTest, ignoresHotplugConnectIfExternalForVrComposer) {
1343     // Inject a primary display.
1344     PrimaryDisplayVariant::injectHwcDisplay(this);
1345 
1346     EXPECT_CALL(*mComposer, isUsingVrComposer()).WillRepeatedly(Return(true));
1347 
1348     ignoresHotplugConnectCommon<SimpleExternalDisplayCase>();
1349 }
1350 
TEST_F(HandleTransactionLockedTest,processHotplugDisconnectPrimaryDisplay)1351 TEST_F(HandleTransactionLockedTest, processHotplugDisconnectPrimaryDisplay) {
1352     processesHotplugDisconnectCommon<SimplePrimaryDisplayCase>();
1353 }
1354 
TEST_F(HandleTransactionLockedTest,processHotplugDisconnectExternalDisplay)1355 TEST_F(HandleTransactionLockedTest, processHotplugDisconnectExternalDisplay) {
1356     processesHotplugDisconnectCommon<SimpleExternalDisplayCase>();
1357 }
1358 
TEST_F(HandleTransactionLockedTest,processesHotplugConnectThenDisconnectPrimary)1359 TEST_F(HandleTransactionLockedTest, processesHotplugConnectThenDisconnectPrimary) {
1360     using Case = SimplePrimaryDisplayCase;
1361 
1362     // --------------------------------------------------------------------
1363     // Preconditions
1364 
1365     setupCommonPreconditions<Case>();
1366 
1367     // A hotplug connect event is enqueued for a display
1368     Case::Display::injectPendingHotplugEvent(this, HWC2::Connection::Connected);
1369     // A hotplug disconnect event is also enqueued for the same display
1370     Case::Display::injectPendingHotplugEvent(this, HWC2::Connection::Disconnected);
1371 
1372     // --------------------------------------------------------------------
1373     // Call Expectations
1374 
1375     EXPECT_CALL(*mComposer, isUsingVrComposer()).WillRepeatedly(Return(false));
1376 
1377     setupCommonCallExpectationsForConnectProcessing<Case>();
1378     setupCommonCallExpectationsForDisconnectProcessing<Case>();
1379 
1380     EXPECT_CALL(*mComposer,
1381                 setVsyncEnabled(Case::Display::HWC_DISPLAY_ID, IComposerClient::Vsync::DISABLE))
1382             .WillOnce(Return(Error::NONE));
1383     EXPECT_CALL(*mConsumer, consumerDisconnect()).WillOnce(Return(NO_ERROR));
1384 
1385     // --------------------------------------------------------------------
1386     // Invocation
1387 
1388     mFlinger.handleTransactionLocked(eDisplayTransactionNeeded);
1389 
1390     // --------------------------------------------------------------------
1391     // Postconditions
1392 
1393     // HWComposer should not have an entry for the display
1394     EXPECT_FALSE(hasHwcDisplay(Case::Display::HWC_DISPLAY_ID));
1395 
1396     // The display should not be set up as a primary built-in display.
1397     ASSERT_TRUE(0 <= Case::Display::TYPE &&
1398                 Case::Display::TYPE < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES);
1399     auto displayToken = mFlinger.mutableBuiltinDisplays()[Case::Display::TYPE];
1400     EXPECT_TRUE(displayToken == nullptr);
1401 }
1402 
TEST_F(HandleTransactionLockedTest,processesHotplugDisconnectThenConnectPrimary)1403 TEST_F(HandleTransactionLockedTest, processesHotplugDisconnectThenConnectPrimary) {
1404     using Case = SimplePrimaryDisplayCase;
1405 
1406     // --------------------------------------------------------------------
1407     // Preconditions
1408 
1409     setupCommonPreconditions<Case>();
1410 
1411     // The display is already completely set up.
1412     Case::Display::injectHwcDisplay(this);
1413     auto existing = Case::Display::makeFakeExistingDisplayInjector(this);
1414     existing.inject();
1415 
1416     // A hotplug disconnect event is enqueued for a display
1417     Case::Display::injectPendingHotplugEvent(this, HWC2::Connection::Disconnected);
1418     // A hotplug connect event is also enqueued for the same display
1419     Case::Display::injectPendingHotplugEvent(this, HWC2::Connection::Connected);
1420 
1421     // --------------------------------------------------------------------
1422     // Call Expectations
1423 
1424     EXPECT_CALL(*mComposer, isUsingVrComposer()).WillRepeatedly(Return(false));
1425 
1426     setupCommonCallExpectationsForConnectProcessing<Case>();
1427     setupCommonCallExpectationsForDisconnectProcessing<Case>();
1428 
1429     // --------------------------------------------------------------------
1430     // Invocation
1431 
1432     mFlinger.handleTransactionLocked(eDisplayTransactionNeeded);
1433 
1434     // --------------------------------------------------------------------
1435     // Postconditions
1436 
1437     // The existing token should have been removed
1438     verifyDisplayIsNotConnected(existing.token());
1439     static_assert(0 <= Case::Display::TYPE &&
1440                           Case::Display::TYPE < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES,
1441                   "Display type must be a built-in display");
1442     EXPECT_NE(existing.token(), mFlinger.mutableBuiltinDisplays()[Case::Display::TYPE]);
1443 
1444     // A new display should be connected in its place
1445 
1446     verifyPhysicalDisplayIsConnected<Case>();
1447 
1448     // --------------------------------------------------------------------
1449     // Cleanup conditions
1450 
1451     EXPECT_CALL(*mComposer,
1452                 setVsyncEnabled(Case::Display::HWC_DISPLAY_ID, IComposerClient::Vsync::DISABLE))
1453             .WillOnce(Return(Error::NONE));
1454     EXPECT_CALL(*mConsumer, consumerDisconnect()).WillOnce(Return(NO_ERROR));
1455 }
1456 
TEST_F(HandleTransactionLockedTest,processesVirtualDisplayAdded)1457 TEST_F(HandleTransactionLockedTest, processesVirtualDisplayAdded) {
1458     using Case = HwcVirtualDisplayCase;
1459 
1460     // --------------------------------------------------------------------
1461     // Preconditions
1462 
1463     // The HWC supports at least one virtual display
1464     injectMockComposer(1);
1465 
1466     setupCommonPreconditions<Case>();
1467 
1468     // A virtual display was added to the current state, and it has a
1469     // surface(producer)
1470     sp<BBinder> displayToken = new BBinder();
1471     DisplayDeviceState info(Case::Display::TYPE, static_cast<bool>(Case::Display::SECURE));
1472     sp<mock::GraphicBufferProducer> surface{new mock::GraphicBufferProducer()};
1473     info.surface = surface;
1474     mFlinger.mutableCurrentState().displays.add(displayToken, info);
1475 
1476     // --------------------------------------------------------------------
1477     // Call Expectations
1478 
1479     Case::Display::setupFramebufferConsumerBufferQueueCallExpectations(this);
1480     Case::Display::setupNativeWindowSurfaceCreationCallExpectations(this);
1481 
1482     EXPECT_CALL(*surface, query(NATIVE_WINDOW_WIDTH, _))
1483             .WillRepeatedly(DoAll(SetArgPointee<1>(Case::Display::WIDTH), Return(NO_ERROR)));
1484     EXPECT_CALL(*surface, query(NATIVE_WINDOW_HEIGHT, _))
1485             .WillRepeatedly(DoAll(SetArgPointee<1>(Case::Display::HEIGHT), Return(NO_ERROR)));
1486     EXPECT_CALL(*surface, query(NATIVE_WINDOW_FORMAT, _))
1487             .WillRepeatedly(DoAll(SetArgPointee<1>(DEFAULT_VIRTUAL_DISPLAY_SURFACE_FORMAT),
1488                                   Return(NO_ERROR)));
1489     EXPECT_CALL(*surface, query(NATIVE_WINDOW_CONSUMER_USAGE_BITS, _))
1490             .WillRepeatedly(DoAll(SetArgPointee<1>(0), Return(NO_ERROR)));
1491 
1492     EXPECT_CALL(*surface, setAsyncMode(true)).Times(1);
1493 
1494     EXPECT_CALL(*mProducer, connect(_, _, _, _)).Times(1);
1495     EXPECT_CALL(*mProducer, disconnect(_, _)).Times(1);
1496 
1497     Case::Display::setupHwcVirtualDisplayCreationCallExpectations(this);
1498     Case::WideColorSupport::setupComposerCallExpectations(this);
1499     Case::HdrSupport::setupComposerCallExpectations(this);
1500     Case::PerFrameMetadataSupport::setupComposerCallExpectations(this);
1501 
1502     // --------------------------------------------------------------------
1503     // Invocation
1504 
1505     mFlinger.handleTransactionLocked(eDisplayTransactionNeeded);
1506 
1507     // --------------------------------------------------------------------
1508     // Postconditions
1509 
1510     // The display device should have been set up in the list of displays.
1511     verifyDisplayIsConnected<Case>(displayToken);
1512 
1513     // --------------------------------------------------------------------
1514     // Cleanup conditions
1515 
1516     EXPECT_CALL(*mComposer, destroyVirtualDisplay(Case::Display::HWC_DISPLAY_ID))
1517             .WillOnce(Return(Error::NONE));
1518     EXPECT_CALL(*mConsumer, consumerDisconnect()).WillOnce(Return(NO_ERROR));
1519 }
1520 
TEST_F(HandleTransactionLockedTest,processesVirtualDisplayAddedWithNoSurface)1521 TEST_F(HandleTransactionLockedTest, processesVirtualDisplayAddedWithNoSurface) {
1522     using Case = HwcVirtualDisplayCase;
1523 
1524     // --------------------------------------------------------------------
1525     // Preconditions
1526 
1527     // The HWC supports at least one virtual display
1528     injectMockComposer(1);
1529 
1530     setupCommonPreconditions<Case>();
1531 
1532     // A virtual display was added to the current state, but it does not have a
1533     // surface.
1534     sp<BBinder> displayToken = new BBinder();
1535     DisplayDeviceState info(Case::Display::TYPE, static_cast<bool>(Case::Display::SECURE));
1536     mFlinger.mutableCurrentState().displays.add(displayToken, info);
1537 
1538     // --------------------------------------------------------------------
1539     // Call Expectations
1540 
1541     // --------------------------------------------------------------------
1542     // Invocation
1543 
1544     mFlinger.handleTransactionLocked(eDisplayTransactionNeeded);
1545 
1546     // --------------------------------------------------------------------
1547     // Postconditions
1548 
1549     // There will not be a display device set up.
1550     EXPECT_FALSE(hasDisplayDevice(displayToken));
1551 
1552     // The drawing display state will be set from the current display state.
1553     ASSERT_TRUE(hasDrawingDisplayState(displayToken));
1554     const auto& draw = getDrawingDisplayState(displayToken);
1555     EXPECT_EQ(Case::Display::TYPE, draw.type);
1556 }
1557 
TEST_F(HandleTransactionLockedTest,processesVirtualDisplayRemoval)1558 TEST_F(HandleTransactionLockedTest, processesVirtualDisplayRemoval) {
1559     using Case = HwcVirtualDisplayCase;
1560 
1561     // --------------------------------------------------------------------
1562     // Preconditions
1563 
1564     // A virtual display is set up but is removed from the current state.
1565     mFlinger.mutableHwcDisplayData().resize(3);
1566     Case::Display::injectHwcDisplay(this);
1567     auto existing = Case::Display::makeFakeExistingDisplayInjector(this);
1568     existing.inject();
1569     mFlinger.mutableCurrentState().displays.removeItem(existing.token());
1570 
1571     // --------------------------------------------------------------------
1572     // Call Expectations
1573 
1574     EXPECT_CALL(*mComposer, isUsingVrComposer()).WillRepeatedly(Return(false));
1575 
1576     // --------------------------------------------------------------------
1577     // Invocation
1578 
1579     mFlinger.handleTransactionLocked(eDisplayTransactionNeeded);
1580 
1581     // --------------------------------------------------------------------
1582     // Postconditions
1583 
1584     // The existing token should have been removed
1585     verifyDisplayIsNotConnected(existing.token());
1586 }
1587 
TEST_F(HandleTransactionLockedTest,processesDisplayLayerStackChanges)1588 TEST_F(HandleTransactionLockedTest, processesDisplayLayerStackChanges) {
1589     using Case = NonHwcVirtualDisplayCase;
1590 
1591     constexpr uint32_t oldLayerStack = 0u;
1592     constexpr uint32_t newLayerStack = 123u;
1593 
1594     // --------------------------------------------------------------------
1595     // Preconditions
1596 
1597     // A display is set up
1598     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
1599     display.inject();
1600 
1601     // There is a change to the layerStack state
1602     display.mutableDrawingDisplayState().layerStack = oldLayerStack;
1603     display.mutableCurrentDisplayState().layerStack = newLayerStack;
1604 
1605     // --------------------------------------------------------------------
1606     // Invocation
1607 
1608     mFlinger.handleTransactionLocked(eDisplayTransactionNeeded);
1609 
1610     // --------------------------------------------------------------------
1611     // Postconditions
1612 
1613     EXPECT_EQ(newLayerStack, display.mutableDisplayDevice()->getLayerStack());
1614 }
1615 
TEST_F(HandleTransactionLockedTest,processesDisplayTransformChanges)1616 TEST_F(HandleTransactionLockedTest, processesDisplayTransformChanges) {
1617     using Case = NonHwcVirtualDisplayCase;
1618 
1619     constexpr int oldTransform = 0;
1620     constexpr int newTransform = 2;
1621 
1622     // --------------------------------------------------------------------
1623     // Preconditions
1624 
1625     // A display is set up
1626     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
1627     display.inject();
1628 
1629     // There is a change to the orientation state
1630     display.mutableDrawingDisplayState().orientation = oldTransform;
1631     display.mutableCurrentDisplayState().orientation = newTransform;
1632 
1633     // --------------------------------------------------------------------
1634     // Invocation
1635 
1636     mFlinger.handleTransactionLocked(eDisplayTransactionNeeded);
1637 
1638     // --------------------------------------------------------------------
1639     // Postconditions
1640 
1641     EXPECT_EQ(newTransform, display.mutableDisplayDevice()->getOrientation());
1642 }
1643 
TEST_F(HandleTransactionLockedTest,processesDisplayViewportChanges)1644 TEST_F(HandleTransactionLockedTest, processesDisplayViewportChanges) {
1645     using Case = NonHwcVirtualDisplayCase;
1646 
1647     const Rect oldViewport(0, 0, 0, 0);
1648     const Rect newViewport(0, 0, 123, 456);
1649 
1650     // --------------------------------------------------------------------
1651     // Preconditions
1652 
1653     // A display is set up
1654     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
1655     display.inject();
1656 
1657     // There is a change to the viewport state
1658     display.mutableDrawingDisplayState().viewport = oldViewport;
1659     display.mutableCurrentDisplayState().viewport = newViewport;
1660 
1661     // --------------------------------------------------------------------
1662     // Invocation
1663 
1664     mFlinger.handleTransactionLocked(eDisplayTransactionNeeded);
1665 
1666     // --------------------------------------------------------------------
1667     // Postconditions
1668 
1669     EXPECT_EQ(newViewport, display.mutableDisplayDevice()->getViewport());
1670 }
1671 
TEST_F(HandleTransactionLockedTest,processesDisplayFrameChanges)1672 TEST_F(HandleTransactionLockedTest, processesDisplayFrameChanges) {
1673     using Case = NonHwcVirtualDisplayCase;
1674 
1675     const Rect oldFrame(0, 0, 0, 0);
1676     const Rect newFrame(0, 0, 123, 456);
1677 
1678     // --------------------------------------------------------------------
1679     // Preconditions
1680 
1681     // A display is set up
1682     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
1683     display.inject();
1684 
1685     // There is a change to the viewport state
1686     display.mutableDrawingDisplayState().frame = oldFrame;
1687     display.mutableCurrentDisplayState().frame = newFrame;
1688 
1689     // --------------------------------------------------------------------
1690     // Invocation
1691 
1692     mFlinger.handleTransactionLocked(eDisplayTransactionNeeded);
1693 
1694     // --------------------------------------------------------------------
1695     // Postconditions
1696 
1697     EXPECT_EQ(newFrame, display.mutableDisplayDevice()->getFrame());
1698 }
1699 
TEST_F(HandleTransactionLockedTest,processesDisplayWidthChanges)1700 TEST_F(HandleTransactionLockedTest, processesDisplayWidthChanges) {
1701     using Case = NonHwcVirtualDisplayCase;
1702 
1703     constexpr int oldWidth = 0;
1704     constexpr int oldHeight = 10;
1705     constexpr int newWidth = 123;
1706 
1707     // --------------------------------------------------------------------
1708     // Preconditions
1709 
1710     // A display is set up
1711     auto nativeWindow = new mock::NativeWindow();
1712     auto displaySurface = new mock::DisplaySurface();
1713     auto renderSurface = new RE::mock::Surface();
1714     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
1715     display.setNativeWindow(nativeWindow);
1716     display.setDisplaySurface(displaySurface);
1717     display.setRenderSurface(std::unique_ptr<RE::Surface>(renderSurface));
1718     display.inject();
1719 
1720     // There is a change to the viewport state
1721     display.mutableDrawingDisplayState().width = oldWidth;
1722     display.mutableDrawingDisplayState().height = oldHeight;
1723     display.mutableCurrentDisplayState().width = newWidth;
1724     display.mutableCurrentDisplayState().height = oldHeight;
1725 
1726     // --------------------------------------------------------------------
1727     // Call Expectations
1728 
1729     EXPECT_CALL(*renderSurface, setNativeWindow(nullptr)).Times(1);
1730     EXPECT_CALL(*displaySurface, resizeBuffers(newWidth, oldHeight)).Times(1);
1731     EXPECT_CALL(*renderSurface, setNativeWindow(nativeWindow)).Times(1);
1732     EXPECT_CALL(*renderSurface, queryWidth()).WillOnce(Return(newWidth));
1733     EXPECT_CALL(*renderSurface, queryHeight()).WillOnce(Return(oldHeight));
1734 
1735     // --------------------------------------------------------------------
1736     // Invocation
1737 
1738     mFlinger.handleTransactionLocked(eDisplayTransactionNeeded);
1739 }
1740 
TEST_F(HandleTransactionLockedTest,processesDisplayHeightChanges)1741 TEST_F(HandleTransactionLockedTest, processesDisplayHeightChanges) {
1742     using Case = NonHwcVirtualDisplayCase;
1743 
1744     constexpr int oldWidth = 0;
1745     constexpr int oldHeight = 10;
1746     constexpr int newHeight = 123;
1747 
1748     // --------------------------------------------------------------------
1749     // Preconditions
1750 
1751     // A display is set up
1752     auto nativeWindow = new mock::NativeWindow();
1753     auto displaySurface = new mock::DisplaySurface();
1754     auto renderSurface = new RE::mock::Surface();
1755     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
1756     display.setNativeWindow(nativeWindow);
1757     display.setDisplaySurface(displaySurface);
1758     display.setRenderSurface(std::unique_ptr<RE::Surface>(renderSurface));
1759     display.inject();
1760 
1761     // There is a change to the viewport state
1762     display.mutableDrawingDisplayState().width = oldWidth;
1763     display.mutableDrawingDisplayState().height = oldHeight;
1764     display.mutableCurrentDisplayState().width = oldWidth;
1765     display.mutableCurrentDisplayState().height = newHeight;
1766 
1767     // --------------------------------------------------------------------
1768     // Call Expectations
1769 
1770     EXPECT_CALL(*renderSurface, setNativeWindow(nullptr)).Times(1);
1771     EXPECT_CALL(*displaySurface, resizeBuffers(oldWidth, newHeight)).Times(1);
1772     EXPECT_CALL(*renderSurface, setNativeWindow(nativeWindow)).Times(1);
1773     EXPECT_CALL(*renderSurface, queryWidth()).WillOnce(Return(oldWidth));
1774     EXPECT_CALL(*renderSurface, queryHeight()).WillOnce(Return(newHeight));
1775 
1776     // --------------------------------------------------------------------
1777     // Invocation
1778 
1779     mFlinger.handleTransactionLocked(eDisplayTransactionNeeded);
1780 }
1781 
1782 /* ------------------------------------------------------------------------
1783  * SurfaceFlinger::setDisplayStateLocked
1784  */
1785 
TEST_F(DisplayTransactionTest,setDisplayStateLockedDoesNothingWithUnknownDisplay)1786 TEST_F(DisplayTransactionTest, setDisplayStateLockedDoesNothingWithUnknownDisplay) {
1787     // --------------------------------------------------------------------
1788     // Preconditions
1789 
1790     // We have an unknown display token not associated with a known display
1791     sp<BBinder> displayToken = new BBinder();
1792 
1793     // The requested display state references the unknown display.
1794     DisplayState state;
1795     state.what = DisplayState::eLayerStackChanged;
1796     state.token = displayToken;
1797     state.layerStack = 456;
1798 
1799     // --------------------------------------------------------------------
1800     // Invocation
1801 
1802     uint32_t flags = mFlinger.setDisplayStateLocked(state);
1803 
1804     // --------------------------------------------------------------------
1805     // Postconditions
1806 
1807     // The returned flags are empty
1808     EXPECT_EQ(0u, flags);
1809 
1810     // The display token still doesn't match anything known.
1811     EXPECT_FALSE(hasCurrentDisplayState(displayToken));
1812 }
1813 
TEST_F(DisplayTransactionTest,setDisplayStateLockedDoesNothingWithInvalidDisplay)1814 TEST_F(DisplayTransactionTest, setDisplayStateLockedDoesNothingWithInvalidDisplay) {
1815     using Case = InvalidDisplayCase;
1816 
1817     // --------------------------------------------------------------------
1818     // Preconditions
1819 
1820     // An invalid display is set up
1821     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
1822     display.inject();
1823 
1824     // The invalid display has some state
1825     display.mutableCurrentDisplayState().layerStack = 654u;
1826 
1827     // The requested display state tries to change the display state.
1828     DisplayState state;
1829     state.what = DisplayState::eLayerStackChanged;
1830     state.token = display.token();
1831     state.layerStack = 456;
1832 
1833     // --------------------------------------------------------------------
1834     // Invocation
1835 
1836     uint32_t flags = mFlinger.setDisplayStateLocked(state);
1837 
1838     // --------------------------------------------------------------------
1839     // Postconditions
1840 
1841     // The returned flags are empty
1842     EXPECT_EQ(0u, flags);
1843 
1844     // The current display layer stack value is unchanged.
1845     EXPECT_EQ(654u, getCurrentDisplayState(display.token()).layerStack);
1846 }
1847 
TEST_F(DisplayTransactionTest,setDisplayStateLockedDoesNothingWhenNoChanges)1848 TEST_F(DisplayTransactionTest, setDisplayStateLockedDoesNothingWhenNoChanges) {
1849     using Case = SimplePrimaryDisplayCase;
1850 
1851     // --------------------------------------------------------------------
1852     // Preconditions
1853 
1854     // A display is already set up
1855     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
1856     display.inject();
1857 
1858     // No changes are made to the display
1859     DisplayState state;
1860     state.what = 0;
1861     state.token = display.token();
1862 
1863     // --------------------------------------------------------------------
1864     // Invocation
1865 
1866     uint32_t flags = mFlinger.setDisplayStateLocked(state);
1867 
1868     // --------------------------------------------------------------------
1869     // Postconditions
1870 
1871     // The returned flags are empty
1872     EXPECT_EQ(0u, flags);
1873 }
1874 
TEST_F(DisplayTransactionTest,setDisplayStateLockedDoesNothingIfSurfaceDidNotChange)1875 TEST_F(DisplayTransactionTest, setDisplayStateLockedDoesNothingIfSurfaceDidNotChange) {
1876     using Case = SimplePrimaryDisplayCase;
1877 
1878     // --------------------------------------------------------------------
1879     // Preconditions
1880 
1881     // A display is already set up
1882     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
1883     display.inject();
1884 
1885     // There is a surface that can be set.
1886     sp<mock::GraphicBufferProducer> surface = new mock::GraphicBufferProducer();
1887 
1888     // The current display state has the surface set
1889     display.mutableCurrentDisplayState().surface = surface;
1890 
1891     // The incoming request sets the same surface
1892     DisplayState state;
1893     state.what = DisplayState::eSurfaceChanged;
1894     state.token = display.token();
1895     state.surface = surface;
1896 
1897     // --------------------------------------------------------------------
1898     // Invocation
1899 
1900     uint32_t flags = mFlinger.setDisplayStateLocked(state);
1901 
1902     // --------------------------------------------------------------------
1903     // Postconditions
1904 
1905     // The returned flags are empty
1906     EXPECT_EQ(0u, flags);
1907 
1908     // The current display state is unchanged.
1909     EXPECT_EQ(surface.get(), display.getCurrentDisplayState().surface.get());
1910 }
1911 
TEST_F(DisplayTransactionTest,setDisplayStateLockedRequestsUpdateIfSurfaceChanged)1912 TEST_F(DisplayTransactionTest, setDisplayStateLockedRequestsUpdateIfSurfaceChanged) {
1913     using Case = SimplePrimaryDisplayCase;
1914 
1915     // --------------------------------------------------------------------
1916     // Preconditions
1917 
1918     // A display is already set up
1919     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
1920     display.inject();
1921 
1922     // There is a surface that can be set.
1923     sp<mock::GraphicBufferProducer> surface = new mock::GraphicBufferProducer();
1924 
1925     // The current display state does not have a surface
1926     display.mutableCurrentDisplayState().surface = nullptr;
1927 
1928     // The incoming request sets a surface
1929     DisplayState state;
1930     state.what = DisplayState::eSurfaceChanged;
1931     state.token = display.token();
1932     state.surface = surface;
1933 
1934     // --------------------------------------------------------------------
1935     // Invocation
1936 
1937     uint32_t flags = mFlinger.setDisplayStateLocked(state);
1938 
1939     // --------------------------------------------------------------------
1940     // Postconditions
1941 
1942     // The returned flags indicate a transaction is needed
1943     EXPECT_EQ(eDisplayTransactionNeeded, flags);
1944 
1945     // The current display layer stack state is set to the new value
1946     EXPECT_EQ(surface.get(), display.getCurrentDisplayState().surface.get());
1947 }
1948 
TEST_F(DisplayTransactionTest,setDisplayStateLockedDoesNothingIfLayerStackDidNotChange)1949 TEST_F(DisplayTransactionTest, setDisplayStateLockedDoesNothingIfLayerStackDidNotChange) {
1950     using Case = SimplePrimaryDisplayCase;
1951 
1952     // --------------------------------------------------------------------
1953     // Preconditions
1954 
1955     // A display is already set up
1956     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
1957     display.inject();
1958 
1959     // The display has a layer stack set
1960     display.mutableCurrentDisplayState().layerStack = 456u;
1961 
1962     // The incoming request sets the same layer stack
1963     DisplayState state;
1964     state.what = DisplayState::eLayerStackChanged;
1965     state.token = display.token();
1966     state.layerStack = 456u;
1967 
1968     // --------------------------------------------------------------------
1969     // Invocation
1970 
1971     uint32_t flags = mFlinger.setDisplayStateLocked(state);
1972 
1973     // --------------------------------------------------------------------
1974     // Postconditions
1975 
1976     // The returned flags are empty
1977     EXPECT_EQ(0u, flags);
1978 
1979     // The current display state is unchanged
1980     EXPECT_EQ(456u, display.getCurrentDisplayState().layerStack);
1981 }
1982 
TEST_F(DisplayTransactionTest,setDisplayStateLockedRequestsUpdateIfLayerStackChanged)1983 TEST_F(DisplayTransactionTest, setDisplayStateLockedRequestsUpdateIfLayerStackChanged) {
1984     using Case = SimplePrimaryDisplayCase;
1985 
1986     // --------------------------------------------------------------------
1987     // Preconditions
1988 
1989     // A display is set up
1990     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
1991     display.inject();
1992 
1993     // The display has a layer stack set
1994     display.mutableCurrentDisplayState().layerStack = 654u;
1995 
1996     // The incoming request sets a different layer stack
1997     DisplayState state;
1998     state.what = DisplayState::eLayerStackChanged;
1999     state.token = display.token();
2000     state.layerStack = 456u;
2001 
2002     // --------------------------------------------------------------------
2003     // Invocation
2004 
2005     uint32_t flags = mFlinger.setDisplayStateLocked(state);
2006 
2007     // --------------------------------------------------------------------
2008     // Postconditions
2009 
2010     // The returned flags indicate a transaction is needed
2011     EXPECT_EQ(eDisplayTransactionNeeded, flags);
2012 
2013     // The desired display state has been set to the new value.
2014     EXPECT_EQ(456u, display.getCurrentDisplayState().layerStack);
2015 }
2016 
TEST_F(DisplayTransactionTest,setDisplayStateLockedDoesNothingIfProjectionDidNotChange)2017 TEST_F(DisplayTransactionTest, setDisplayStateLockedDoesNothingIfProjectionDidNotChange) {
2018     using Case = SimplePrimaryDisplayCase;
2019     constexpr int initialOrientation = 180;
2020     const Rect initialFrame = {1, 2, 3, 4};
2021     const Rect initialViewport = {5, 6, 7, 8};
2022 
2023     // --------------------------------------------------------------------
2024     // Preconditions
2025 
2026     // A display is set up
2027     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
2028     display.inject();
2029 
2030     // The current display state projection state is all set
2031     display.mutableCurrentDisplayState().orientation = initialOrientation;
2032     display.mutableCurrentDisplayState().frame = initialFrame;
2033     display.mutableCurrentDisplayState().viewport = initialViewport;
2034 
2035     // The incoming request sets the same projection state
2036     DisplayState state;
2037     state.what = DisplayState::eDisplayProjectionChanged;
2038     state.token = display.token();
2039     state.orientation = initialOrientation;
2040     state.frame = initialFrame;
2041     state.viewport = initialViewport;
2042 
2043     // --------------------------------------------------------------------
2044     // Invocation
2045 
2046     uint32_t flags = mFlinger.setDisplayStateLocked(state);
2047 
2048     // --------------------------------------------------------------------
2049     // Postconditions
2050 
2051     // The returned flags are empty
2052     EXPECT_EQ(0u, flags);
2053 
2054     // The current display state is unchanged
2055     EXPECT_EQ(initialOrientation, display.getCurrentDisplayState().orientation);
2056 
2057     EXPECT_EQ(initialFrame, display.getCurrentDisplayState().frame);
2058     EXPECT_EQ(initialViewport, display.getCurrentDisplayState().viewport);
2059 }
2060 
TEST_F(DisplayTransactionTest,setDisplayStateLockedRequestsUpdateIfOrientationChanged)2061 TEST_F(DisplayTransactionTest, setDisplayStateLockedRequestsUpdateIfOrientationChanged) {
2062     using Case = SimplePrimaryDisplayCase;
2063     constexpr int initialOrientation = 90;
2064     constexpr int desiredOrientation = 180;
2065 
2066     // --------------------------------------------------------------------
2067     // Preconditions
2068 
2069     // A display is set up
2070     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
2071     display.inject();
2072 
2073     // The current display state has an orientation set
2074     display.mutableCurrentDisplayState().orientation = initialOrientation;
2075 
2076     // The incoming request sets a different orientation
2077     DisplayState state;
2078     state.what = DisplayState::eDisplayProjectionChanged;
2079     state.token = display.token();
2080     state.orientation = desiredOrientation;
2081 
2082     // --------------------------------------------------------------------
2083     // Invocation
2084 
2085     uint32_t flags = mFlinger.setDisplayStateLocked(state);
2086 
2087     // --------------------------------------------------------------------
2088     // Postconditions
2089 
2090     // The returned flags indicate a transaction is needed
2091     EXPECT_EQ(eDisplayTransactionNeeded, flags);
2092 
2093     // The current display state has the new value.
2094     EXPECT_EQ(desiredOrientation, display.getCurrentDisplayState().orientation);
2095 }
2096 
TEST_F(DisplayTransactionTest,setDisplayStateLockedRequestsUpdateIfFrameChanged)2097 TEST_F(DisplayTransactionTest, setDisplayStateLockedRequestsUpdateIfFrameChanged) {
2098     using Case = SimplePrimaryDisplayCase;
2099     const Rect initialFrame = {0, 0, 0, 0};
2100     const Rect desiredFrame = {5, 6, 7, 8};
2101 
2102     // --------------------------------------------------------------------
2103     // Preconditions
2104 
2105     // A display is set up
2106     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
2107     display.inject();
2108 
2109     // The current display state does not have a frame
2110     display.mutableCurrentDisplayState().frame = initialFrame;
2111 
2112     // The incoming request sets a frame
2113     DisplayState state;
2114     state.what = DisplayState::eDisplayProjectionChanged;
2115     state.token = display.token();
2116     state.frame = desiredFrame;
2117 
2118     // --------------------------------------------------------------------
2119     // Invocation
2120 
2121     uint32_t flags = mFlinger.setDisplayStateLocked(state);
2122 
2123     // --------------------------------------------------------------------
2124     // Postconditions
2125 
2126     // The returned flags indicate a transaction is needed
2127     EXPECT_EQ(eDisplayTransactionNeeded, flags);
2128 
2129     // The current display state has the new value.
2130     EXPECT_EQ(desiredFrame, display.getCurrentDisplayState().frame);
2131 }
2132 
TEST_F(DisplayTransactionTest,setDisplayStateLockedRequestsUpdateIfViewportChanged)2133 TEST_F(DisplayTransactionTest, setDisplayStateLockedRequestsUpdateIfViewportChanged) {
2134     using Case = SimplePrimaryDisplayCase;
2135     const Rect initialViewport = {0, 0, 0, 0};
2136     const Rect desiredViewport = {5, 6, 7, 8};
2137 
2138     // --------------------------------------------------------------------
2139     // Preconditions
2140 
2141     // A display is set up
2142     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
2143     display.inject();
2144 
2145     // The current display state does not have a viewport
2146     display.mutableCurrentDisplayState().viewport = initialViewport;
2147 
2148     // The incoming request sets a viewport
2149     DisplayState state;
2150     state.what = DisplayState::eDisplayProjectionChanged;
2151     state.token = display.token();
2152     state.viewport = desiredViewport;
2153 
2154     // --------------------------------------------------------------------
2155     // Invocation
2156 
2157     uint32_t flags = mFlinger.setDisplayStateLocked(state);
2158 
2159     // --------------------------------------------------------------------
2160     // Postconditions
2161 
2162     // The returned flags indicate a transaction is needed
2163     EXPECT_EQ(eDisplayTransactionNeeded, flags);
2164 
2165     // The current display state has the new value.
2166     EXPECT_EQ(desiredViewport, display.getCurrentDisplayState().viewport);
2167 }
2168 
TEST_F(DisplayTransactionTest,setDisplayStateLockedDoesNothingIfSizeDidNotChange)2169 TEST_F(DisplayTransactionTest, setDisplayStateLockedDoesNothingIfSizeDidNotChange) {
2170     using Case = SimplePrimaryDisplayCase;
2171     constexpr uint32_t initialWidth = 1024;
2172     constexpr uint32_t initialHeight = 768;
2173 
2174     // --------------------------------------------------------------------
2175     // Preconditions
2176 
2177     // A display is set up
2178     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
2179     display.inject();
2180 
2181     // The current display state has a size set
2182     display.mutableCurrentDisplayState().width = initialWidth;
2183     display.mutableCurrentDisplayState().height = initialHeight;
2184 
2185     // The incoming request sets the same display size
2186     DisplayState state;
2187     state.what = DisplayState::eDisplaySizeChanged;
2188     state.token = display.token();
2189     state.width = initialWidth;
2190     state.height = initialHeight;
2191 
2192     // --------------------------------------------------------------------
2193     // Invocation
2194 
2195     uint32_t flags = mFlinger.setDisplayStateLocked(state);
2196 
2197     // --------------------------------------------------------------------
2198     // Postconditions
2199 
2200     // The returned flags are empty
2201     EXPECT_EQ(0u, flags);
2202 
2203     // The current display state is unchanged
2204     EXPECT_EQ(initialWidth, display.getCurrentDisplayState().width);
2205     EXPECT_EQ(initialHeight, display.getCurrentDisplayState().height);
2206 }
2207 
TEST_F(DisplayTransactionTest,setDisplayStateLockedRequestsUpdateIfWidthChanged)2208 TEST_F(DisplayTransactionTest, setDisplayStateLockedRequestsUpdateIfWidthChanged) {
2209     using Case = SimplePrimaryDisplayCase;
2210     constexpr uint32_t initialWidth = 0;
2211     constexpr uint32_t desiredWidth = 1024;
2212 
2213     // --------------------------------------------------------------------
2214     // Preconditions
2215 
2216     // A display is set up
2217     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
2218     display.inject();
2219 
2220     // The display does not yet have a width
2221     display.mutableCurrentDisplayState().width = initialWidth;
2222 
2223     // The incoming request sets a display width
2224     DisplayState state;
2225     state.what = DisplayState::eDisplaySizeChanged;
2226     state.token = display.token();
2227     state.width = desiredWidth;
2228 
2229     // --------------------------------------------------------------------
2230     // Invocation
2231 
2232     uint32_t flags = mFlinger.setDisplayStateLocked(state);
2233 
2234     // --------------------------------------------------------------------
2235     // Postconditions
2236 
2237     // The returned flags indicate a transaction is needed
2238     EXPECT_EQ(eDisplayTransactionNeeded, flags);
2239 
2240     // The current display state has the new value.
2241     EXPECT_EQ(desiredWidth, display.getCurrentDisplayState().width);
2242 }
2243 
TEST_F(DisplayTransactionTest,setDisplayStateLockedRequestsUpdateIfHeightChanged)2244 TEST_F(DisplayTransactionTest, setDisplayStateLockedRequestsUpdateIfHeightChanged) {
2245     using Case = SimplePrimaryDisplayCase;
2246     constexpr uint32_t initialHeight = 0;
2247     constexpr uint32_t desiredHeight = 768;
2248 
2249     // --------------------------------------------------------------------
2250     // Preconditions
2251 
2252     // A display is set up
2253     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
2254     display.inject();
2255 
2256     // The display does not yet have a height
2257     display.mutableCurrentDisplayState().height = initialHeight;
2258 
2259     // The incoming request sets a display height
2260     DisplayState state;
2261     state.what = DisplayState::eDisplaySizeChanged;
2262     state.token = display.token();
2263     state.height = desiredHeight;
2264 
2265     // --------------------------------------------------------------------
2266     // Invocation
2267 
2268     uint32_t flags = mFlinger.setDisplayStateLocked(state);
2269 
2270     // --------------------------------------------------------------------
2271     // Postconditions
2272 
2273     // The returned flags indicate a transaction is needed
2274     EXPECT_EQ(eDisplayTransactionNeeded, flags);
2275 
2276     // The current display state has the new value.
2277     EXPECT_EQ(desiredHeight, display.getCurrentDisplayState().height);
2278 }
2279 
2280 /* ------------------------------------------------------------------------
2281  * SurfaceFlinger::onInitializeDisplays
2282  */
2283 
TEST_F(DisplayTransactionTest,onInitializeDisplaysSetsUpPrimaryDisplay)2284 TEST_F(DisplayTransactionTest, onInitializeDisplaysSetsUpPrimaryDisplay) {
2285     using Case = SimplePrimaryDisplayCase;
2286 
2287     // --------------------------------------------------------------------
2288     // Preconditions
2289 
2290     // A primary display is set up
2291     Case::Display::injectHwcDisplay(this);
2292     auto primaryDisplay = Case::Display::makeFakeExistingDisplayInjector(this);
2293     primaryDisplay.inject();
2294 
2295     // --------------------------------------------------------------------
2296     // Call Expectations
2297 
2298     // We expect the surface interceptor to possibly be used, but we treat it as
2299     // disabled since it is called as a side effect rather than directly by this
2300     // function.
2301     EXPECT_CALL(*mSurfaceInterceptor, isEnabled()).WillOnce(Return(false));
2302 
2303     // We expect a call to get the active display config.
2304     Case::Display::setupHwcGetActiveConfigCallExpectations(this);
2305 
2306     // We expect invalidate() to be invoked once to trigger display transaction
2307     // processing.
2308     EXPECT_CALL(*mMessageQueue, invalidate()).Times(1);
2309 
2310     // --------------------------------------------------------------------
2311     // Invocation
2312 
2313     mFlinger.onInitializeDisplays();
2314 
2315     // --------------------------------------------------------------------
2316     // Postconditions
2317 
2318     // The primary display should have a current state
2319     ASSERT_TRUE(hasCurrentDisplayState(primaryDisplay.token()));
2320     const auto& primaryDisplayState = getCurrentDisplayState(primaryDisplay.token());
2321     // The layer stack state should be set to zero
2322     EXPECT_EQ(0u, primaryDisplayState.layerStack);
2323     // The orientation state should be set to zero
2324     EXPECT_EQ(0, primaryDisplayState.orientation);
2325 
2326     // The frame state should be set to INVALID
2327     EXPECT_EQ(Rect::INVALID_RECT, primaryDisplayState.frame);
2328 
2329     // The viewport state should be set to INVALID
2330     EXPECT_EQ(Rect::INVALID_RECT, primaryDisplayState.viewport);
2331 
2332     // The width and height should both be zero
2333     EXPECT_EQ(0u, primaryDisplayState.width);
2334     EXPECT_EQ(0u, primaryDisplayState.height);
2335 
2336     // The display should be set to HWC_POWER_MODE_NORMAL
2337     ASSERT_TRUE(hasDisplayDevice(primaryDisplay.token()));
2338     auto displayDevice = primaryDisplay.mutableDisplayDevice();
2339     EXPECT_EQ(HWC_POWER_MODE_NORMAL, displayDevice->getPowerMode());
2340 
2341     // The display refresh period should be set in the frame tracker.
2342     FrameStats stats;
2343     mFlinger.getAnimFrameTracker().getStats(&stats);
2344     EXPECT_EQ(DEFAULT_REFRESH_RATE, stats.refreshPeriodNano);
2345 
2346     // The display transaction needed flag should be set.
2347     EXPECT_TRUE(hasTransactionFlagSet(eDisplayTransactionNeeded));
2348 
2349     // The compositor timing should be set to default values
2350     const auto& compositorTiming = mFlinger.getCompositorTiming();
2351     EXPECT_EQ(-DEFAULT_REFRESH_RATE, compositorTiming.deadline);
2352     EXPECT_EQ(DEFAULT_REFRESH_RATE, compositorTiming.interval);
2353     EXPECT_EQ(DEFAULT_REFRESH_RATE, compositorTiming.presentLatency);
2354 }
2355 
2356 /* ------------------------------------------------------------------------
2357  * SurfaceFlinger::setPowerModeInternal
2358  */
2359 
2360 // Used when we simulate a display that supports doze.
2361 struct DozeIsSupportedVariant {
2362     static constexpr bool DOZE_SUPPORTED = true;
2363     static constexpr IComposerClient::PowerMode ACTUAL_POWER_MODE_FOR_DOZE =
2364             IComposerClient::PowerMode::DOZE;
2365     static constexpr IComposerClient::PowerMode ACTUAL_POWER_MODE_FOR_DOZE_SUSPEND =
2366             IComposerClient::PowerMode::DOZE_SUSPEND;
2367 };
2368 
2369 // Used when we simulate a display that does not support doze.
2370 struct DozeNotSupportedVariant {
2371     static constexpr bool DOZE_SUPPORTED = false;
2372     static constexpr IComposerClient::PowerMode ACTUAL_POWER_MODE_FOR_DOZE =
2373             IComposerClient::PowerMode::ON;
2374     static constexpr IComposerClient::PowerMode ACTUAL_POWER_MODE_FOR_DOZE_SUSPEND =
2375             IComposerClient::PowerMode::ON;
2376 };
2377 
2378 struct EventThreadBaseSupportedVariant {
setupEventAndEventControlThreadNoCallExpectationsandroid::__anon52a382c50111::EventThreadBaseSupportedVariant2379     static void setupEventAndEventControlThreadNoCallExpectations(DisplayTransactionTest* test) {
2380         // The event control thread should not be notified.
2381         EXPECT_CALL(*test->mEventControlThread, setVsyncEnabled(_)).Times(0);
2382 
2383         // The event thread should not be notified.
2384         EXPECT_CALL(*test->mEventThread, onScreenReleased()).Times(0);
2385         EXPECT_CALL(*test->mEventThread, onScreenAcquired()).Times(0);
2386     }
2387 };
2388 
2389 struct EventThreadNotSupportedVariant : public EventThreadBaseSupportedVariant {
setupAcquireAndEnableVsyncCallExpectationsandroid::__anon52a382c50111::EventThreadNotSupportedVariant2390     static void setupAcquireAndEnableVsyncCallExpectations(DisplayTransactionTest* test) {
2391         // These calls are only expected for the primary display.
2392 
2393         // Instead expect no calls.
2394         setupEventAndEventControlThreadNoCallExpectations(test);
2395     }
2396 
setupReleaseAndDisableVsyncCallExpectationsandroid::__anon52a382c50111::EventThreadNotSupportedVariant2397     static void setupReleaseAndDisableVsyncCallExpectations(DisplayTransactionTest* test) {
2398         // These calls are only expected for the primary display.
2399 
2400         // Instead expect no calls.
2401         setupEventAndEventControlThreadNoCallExpectations(test);
2402     }
2403 };
2404 
2405 struct EventThreadIsSupportedVariant : public EventThreadBaseSupportedVariant {
setupAcquireAndEnableVsyncCallExpectationsandroid::__anon52a382c50111::EventThreadIsSupportedVariant2406     static void setupAcquireAndEnableVsyncCallExpectations(DisplayTransactionTest* test) {
2407         // The event control thread should be notified to enable vsyncs
2408         EXPECT_CALL(*test->mEventControlThread, setVsyncEnabled(true)).Times(1);
2409 
2410         // The event thread should be notified that the screen was acquired.
2411         EXPECT_CALL(*test->mEventThread, onScreenAcquired()).Times(1);
2412     }
2413 
setupReleaseAndDisableVsyncCallExpectationsandroid::__anon52a382c50111::EventThreadIsSupportedVariant2414     static void setupReleaseAndDisableVsyncCallExpectations(DisplayTransactionTest* test) {
2415         // There should be a call to setVsyncEnabled(false)
2416         EXPECT_CALL(*test->mEventControlThread, setVsyncEnabled(false)).Times(1);
2417 
2418         // The event thread should not be notified that the screen was released.
2419         EXPECT_CALL(*test->mEventThread, onScreenReleased()).Times(1);
2420     }
2421 };
2422 
2423 // --------------------------------------------------------------------
2424 // Note:
2425 //
2426 // There are a large number of transitions we could test, however we only test a
2427 // selected subset which provides complete test coverage of the implementation.
2428 // --------------------------------------------------------------------
2429 
2430 template <int initialPowerMode, int targetPowerMode>
2431 struct TransitionVariantCommon {
2432     static constexpr auto INITIAL_POWER_MODE = initialPowerMode;
2433     static constexpr auto TARGET_POWER_MODE = targetPowerMode;
2434 
verifyPostconditionsandroid::__anon52a382c50111::TransitionVariantCommon2435     static void verifyPostconditions(DisplayTransactionTest*) {}
2436 };
2437 
2438 struct TransitionOffToOnVariant
2439       : public TransitionVariantCommon<HWC_POWER_MODE_OFF, HWC_POWER_MODE_NORMAL> {
2440     template <typename Case>
setupCallExpectationsandroid::__anon52a382c50111::TransitionOffToOnVariant2441     static void setupCallExpectations(DisplayTransactionTest* test) {
2442         Case::setupComposerCallExpectations(test, IComposerClient::PowerMode::ON);
2443         Case::EventThread::setupAcquireAndEnableVsyncCallExpectations(test);
2444         Case::setupRepaintEverythingCallExpectations(test);
2445     }
2446 
verifyPostconditionsandroid::__anon52a382c50111::TransitionOffToOnVariant2447     static void verifyPostconditions(DisplayTransactionTest* test) {
2448         EXPECT_TRUE(test->mFlinger.getVisibleRegionsDirty());
2449         EXPECT_TRUE(test->mFlinger.getHasPoweredOff());
2450     }
2451 };
2452 
2453 struct TransitionOffToDozeSuspendVariant
2454       : public TransitionVariantCommon<HWC_POWER_MODE_OFF, HWC_POWER_MODE_DOZE_SUSPEND> {
2455     template <typename Case>
setupCallExpectationsandroid::__anon52a382c50111::TransitionOffToDozeSuspendVariant2456     static void setupCallExpectations(DisplayTransactionTest* test) {
2457         Case::setupComposerCallExpectations(test, Case::Doze::ACTUAL_POWER_MODE_FOR_DOZE_SUSPEND);
2458         Case::EventThread::setupEventAndEventControlThreadNoCallExpectations(test);
2459         Case::setupRepaintEverythingCallExpectations(test);
2460     }
2461 
verifyPostconditionsandroid::__anon52a382c50111::TransitionOffToDozeSuspendVariant2462     static void verifyPostconditions(DisplayTransactionTest* test) {
2463         EXPECT_TRUE(test->mFlinger.getVisibleRegionsDirty());
2464         EXPECT_TRUE(test->mFlinger.getHasPoweredOff());
2465     }
2466 };
2467 
2468 struct TransitionOnToOffVariant
2469       : public TransitionVariantCommon<HWC_POWER_MODE_NORMAL, HWC_POWER_MODE_OFF> {
2470     template <typename Case>
setupCallExpectationsandroid::__anon52a382c50111::TransitionOnToOffVariant2471     static void setupCallExpectations(DisplayTransactionTest* test) {
2472         Case::EventThread::setupReleaseAndDisableVsyncCallExpectations(test);
2473         Case::setupComposerCallExpectations(test, IComposerClient::PowerMode::OFF);
2474     }
2475 
verifyPostconditionsandroid::__anon52a382c50111::TransitionOnToOffVariant2476     static void verifyPostconditions(DisplayTransactionTest* test) {
2477         EXPECT_TRUE(test->mFlinger.getVisibleRegionsDirty());
2478     }
2479 };
2480 
2481 struct TransitionDozeSuspendToOffVariant
2482       : public TransitionVariantCommon<HWC_POWER_MODE_DOZE_SUSPEND, HWC_POWER_MODE_OFF> {
2483     template <typename Case>
setupCallExpectationsandroid::__anon52a382c50111::TransitionDozeSuspendToOffVariant2484     static void setupCallExpectations(DisplayTransactionTest* test) {
2485         Case::EventThread::setupEventAndEventControlThreadNoCallExpectations(test);
2486         Case::setupComposerCallExpectations(test, IComposerClient::PowerMode::OFF);
2487     }
2488 
verifyPostconditionsandroid::__anon52a382c50111::TransitionDozeSuspendToOffVariant2489     static void verifyPostconditions(DisplayTransactionTest* test) {
2490         EXPECT_TRUE(test->mFlinger.getVisibleRegionsDirty());
2491     }
2492 };
2493 
2494 struct TransitionOnToDozeVariant
2495       : public TransitionVariantCommon<HWC_POWER_MODE_NORMAL, HWC_POWER_MODE_DOZE> {
2496     template <typename Case>
setupCallExpectationsandroid::__anon52a382c50111::TransitionOnToDozeVariant2497     static void setupCallExpectations(DisplayTransactionTest* test) {
2498         Case::EventThread::setupEventAndEventControlThreadNoCallExpectations(test);
2499         Case::setupComposerCallExpectations(test, Case::Doze::ACTUAL_POWER_MODE_FOR_DOZE);
2500     }
2501 };
2502 
2503 struct TransitionDozeSuspendToDozeVariant
2504       : public TransitionVariantCommon<HWC_POWER_MODE_DOZE_SUSPEND, HWC_POWER_MODE_DOZE> {
2505     template <typename Case>
setupCallExpectationsandroid::__anon52a382c50111::TransitionDozeSuspendToDozeVariant2506     static void setupCallExpectations(DisplayTransactionTest* test) {
2507         Case::EventThread::setupAcquireAndEnableVsyncCallExpectations(test);
2508         Case::setupComposerCallExpectations(test, Case::Doze::ACTUAL_POWER_MODE_FOR_DOZE);
2509     }
2510 };
2511 
2512 struct TransitionDozeToOnVariant
2513       : public TransitionVariantCommon<HWC_POWER_MODE_DOZE, HWC_POWER_MODE_NORMAL> {
2514     template <typename Case>
setupCallExpectationsandroid::__anon52a382c50111::TransitionDozeToOnVariant2515     static void setupCallExpectations(DisplayTransactionTest* test) {
2516         Case::EventThread::setupEventAndEventControlThreadNoCallExpectations(test);
2517         Case::setupComposerCallExpectations(test, IComposerClient::PowerMode::ON);
2518     }
2519 };
2520 
2521 struct TransitionDozeSuspendToOnVariant
2522       : public TransitionVariantCommon<HWC_POWER_MODE_DOZE_SUSPEND, HWC_POWER_MODE_NORMAL> {
2523     template <typename Case>
setupCallExpectationsandroid::__anon52a382c50111::TransitionDozeSuspendToOnVariant2524     static void setupCallExpectations(DisplayTransactionTest* test) {
2525         Case::EventThread::setupAcquireAndEnableVsyncCallExpectations(test);
2526         Case::setupComposerCallExpectations(test, IComposerClient::PowerMode::ON);
2527     }
2528 };
2529 
2530 struct TransitionOnToDozeSuspendVariant
2531       : public TransitionVariantCommon<HWC_POWER_MODE_NORMAL, HWC_POWER_MODE_DOZE_SUSPEND> {
2532     template <typename Case>
setupCallExpectationsandroid::__anon52a382c50111::TransitionOnToDozeSuspendVariant2533     static void setupCallExpectations(DisplayTransactionTest* test) {
2534         Case::EventThread::setupReleaseAndDisableVsyncCallExpectations(test);
2535         Case::setupComposerCallExpectations(test, Case::Doze::ACTUAL_POWER_MODE_FOR_DOZE_SUSPEND);
2536     }
2537 };
2538 
2539 struct TransitionOnToUnknownVariant
2540       : public TransitionVariantCommon<HWC_POWER_MODE_NORMAL, HWC_POWER_MODE_LEET> {
2541     template <typename Case>
setupCallExpectationsandroid::__anon52a382c50111::TransitionOnToUnknownVariant2542     static void setupCallExpectations(DisplayTransactionTest* test) {
2543         Case::EventThread::setupEventAndEventControlThreadNoCallExpectations(test);
2544         Case::setupNoComposerPowerModeCallExpectations(test);
2545     }
2546 };
2547 
2548 // --------------------------------------------------------------------
2549 // Note:
2550 //
2551 // Rather than testing the cartesian product of of
2552 // DozeIsSupported/DozeNotSupported with all other options, we use one for one
2553 // display type, and the other for another display type.
2554 // --------------------------------------------------------------------
2555 
2556 template <typename DisplayVariant, typename DozeVariant, typename EventThreadVariant,
2557           typename TransitionVariant>
2558 struct DisplayPowerCase {
2559     using Display = DisplayVariant;
2560     using Doze = DozeVariant;
2561     using EventThread = EventThreadVariant;
2562     using Transition = TransitionVariant;
2563 
injectDisplayWithInitialPowerModeandroid::__anon52a382c50111::DisplayPowerCase2564     static auto injectDisplayWithInitialPowerMode(DisplayTransactionTest* test, int mode) {
2565         Display::injectHwcDisplay(test);
2566         auto display = Display::makeFakeExistingDisplayInjector(test);
2567         display.inject();
2568         display.mutableDisplayDevice()->setPowerMode(mode);
2569         return display;
2570     }
2571 
setInitialPrimaryHWVsyncEnabledandroid::__anon52a382c50111::DisplayPowerCase2572     static void setInitialPrimaryHWVsyncEnabled(DisplayTransactionTest* test, bool enabled) {
2573         test->mFlinger.mutablePrimaryHWVsyncEnabled() = enabled;
2574     }
2575 
setupRepaintEverythingCallExpectationsandroid::__anon52a382c50111::DisplayPowerCase2576     static void setupRepaintEverythingCallExpectations(DisplayTransactionTest* test) {
2577         EXPECT_CALL(*test->mMessageQueue, invalidate()).Times(1);
2578     }
2579 
setupSurfaceInterceptorCallExpectationsandroid::__anon52a382c50111::DisplayPowerCase2580     static void setupSurfaceInterceptorCallExpectations(DisplayTransactionTest* test, int mode) {
2581         EXPECT_CALL(*test->mSurfaceInterceptor, isEnabled()).WillOnce(Return(true));
2582         EXPECT_CALL(*test->mSurfaceInterceptor, savePowerModeUpdate(_, mode)).Times(1);
2583     }
2584 
setupComposerCallExpectationsandroid::__anon52a382c50111::DisplayPowerCase2585     static void setupComposerCallExpectations(DisplayTransactionTest* test,
2586                                               IComposerClient::PowerMode mode) {
2587         // Any calls to get the active config will return a default value.
2588         EXPECT_CALL(*test->mComposer, getActiveConfig(Display::HWC_DISPLAY_ID, _))
2589                 .WillRepeatedly(DoAll(SetArgPointee<1>(Display::HWC_ACTIVE_CONFIG_ID),
2590                                       Return(Error::NONE)));
2591 
2592         // Any calls to get whether the display supports dozing will return the value set by the
2593         // policy variant.
2594         EXPECT_CALL(*test->mComposer, getDozeSupport(Display::HWC_DISPLAY_ID, _))
2595                 .WillRepeatedly(DoAll(SetArgPointee<1>(Doze::DOZE_SUPPORTED), Return(Error::NONE)));
2596 
2597         EXPECT_CALL(*test->mComposer, setPowerMode(Display::HWC_DISPLAY_ID, mode)).Times(1);
2598     }
2599 
setupNoComposerPowerModeCallExpectationsandroid::__anon52a382c50111::DisplayPowerCase2600     static void setupNoComposerPowerModeCallExpectations(DisplayTransactionTest* test) {
2601         EXPECT_CALL(*test->mComposer, setPowerMode(Display::HWC_DISPLAY_ID, _)).Times(0);
2602     }
2603 };
2604 
2605 // A sample configuration for the primary display.
2606 // In addition to having event thread support, we emulate doze support.
2607 template <typename TransitionVariant>
2608 using PrimaryDisplayPowerCase = DisplayPowerCase<PrimaryDisplayVariant, DozeIsSupportedVariant,
2609                                                  EventThreadIsSupportedVariant, TransitionVariant>;
2610 
2611 // A sample configuration for the external display.
2612 // In addition to not having event thread support, we emulate not having doze
2613 // support.
2614 template <typename TransitionVariant>
2615 using ExternalDisplayPowerCase =
2616         DisplayPowerCase<ExternalDisplayVariant, DozeNotSupportedVariant,
2617                          EventThreadNotSupportedVariant, TransitionVariant>;
2618 
2619 class SetPowerModeInternalTest : public DisplayTransactionTest {
2620 public:
2621     template <typename Case>
2622     void transitionDisplayCommon();
2623 };
2624 
2625 template <int PowerMode>
2626 struct PowerModeInitialVSyncEnabled : public std::false_type {};
2627 
2628 template <>
2629 struct PowerModeInitialVSyncEnabled<HWC_POWER_MODE_NORMAL> : public std::true_type {};
2630 
2631 template <>
2632 struct PowerModeInitialVSyncEnabled<HWC_POWER_MODE_DOZE> : public std::true_type {};
2633 
2634 template <typename Case>
transitionDisplayCommon()2635 void SetPowerModeInternalTest::transitionDisplayCommon() {
2636     // --------------------------------------------------------------------
2637     // Preconditions
2638 
2639     auto display =
2640             Case::injectDisplayWithInitialPowerMode(this, Case::Transition::INITIAL_POWER_MODE);
2641     Case::setInitialPrimaryHWVsyncEnabled(this,
2642                                           PowerModeInitialVSyncEnabled<
2643                                                   Case::Transition::INITIAL_POWER_MODE>::value);
2644 
2645     // --------------------------------------------------------------------
2646     // Call Expectations
2647 
2648     Case::setupSurfaceInterceptorCallExpectations(this, Case::Transition::TARGET_POWER_MODE);
2649     Case::Transition::template setupCallExpectations<Case>(this);
2650 
2651     // --------------------------------------------------------------------
2652     // Invocation
2653 
2654     mFlinger.setPowerModeInternal(display.mutableDisplayDevice(),
2655                                   Case::Transition::TARGET_POWER_MODE);
2656 
2657     // --------------------------------------------------------------------
2658     // Postconditions
2659 
2660     Case::Transition::verifyPostconditions(this);
2661 }
2662 
TEST_F(SetPowerModeInternalTest,setPowerModeInternalDoesNothingIfNoChange)2663 TEST_F(SetPowerModeInternalTest, setPowerModeInternalDoesNothingIfNoChange) {
2664     using Case = SimplePrimaryDisplayCase;
2665 
2666     // --------------------------------------------------------------------
2667     // Preconditions
2668 
2669     // A primary display device is set up
2670     Case::Display::injectHwcDisplay(this);
2671     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
2672     display.inject();
2673 
2674     // The diplay is already set to HWC_POWER_MODE_NORMAL
2675     display.mutableDisplayDevice()->setPowerMode(HWC_POWER_MODE_NORMAL);
2676 
2677     // --------------------------------------------------------------------
2678     // Invocation
2679 
2680     mFlinger.setPowerModeInternal(display.mutableDisplayDevice(), HWC_POWER_MODE_NORMAL);
2681 
2682     // --------------------------------------------------------------------
2683     // Postconditions
2684 
2685     EXPECT_EQ(HWC_POWER_MODE_NORMAL, display.mutableDisplayDevice()->getPowerMode());
2686 }
2687 
TEST_F(SetPowerModeInternalTest,setPowerModeInternalJustSetsInternalStateIfVirtualDisplay)2688 TEST_F(SetPowerModeInternalTest, setPowerModeInternalJustSetsInternalStateIfVirtualDisplay) {
2689     using Case = HwcVirtualDisplayCase;
2690 
2691     // --------------------------------------------------------------------
2692     // Preconditions
2693 
2694     // We need to resize this so that the HWC thinks the virtual display
2695     // is something it created.
2696     mFlinger.mutableHwcDisplayData().resize(3);
2697 
2698     // A virtual display device is set up
2699     Case::Display::injectHwcDisplay(this);
2700     auto display = Case::Display::makeFakeExistingDisplayInjector(this);
2701     display.inject();
2702 
2703     // The display is set to HWC_POWER_MODE_OFF
2704     getDisplayDevice(display.token())->setPowerMode(HWC_POWER_MODE_OFF);
2705 
2706     // --------------------------------------------------------------------
2707     // Invocation
2708 
2709     mFlinger.setPowerModeInternal(display.mutableDisplayDevice(), HWC_POWER_MODE_NORMAL);
2710 
2711     // --------------------------------------------------------------------
2712     // Postconditions
2713 
2714     EXPECT_EQ(HWC_POWER_MODE_NORMAL, display.mutableDisplayDevice()->getPowerMode());
2715 }
2716 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromOffToOnPrimaryDisplay)2717 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromOffToOnPrimaryDisplay) {
2718     transitionDisplayCommon<PrimaryDisplayPowerCase<TransitionOffToOnVariant>>();
2719 }
2720 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromOffToDozeSuspendPrimaryDisplay)2721 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromOffToDozeSuspendPrimaryDisplay) {
2722     transitionDisplayCommon<PrimaryDisplayPowerCase<TransitionOffToDozeSuspendVariant>>();
2723 }
2724 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromOnToOffPrimaryDisplay)2725 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromOnToOffPrimaryDisplay) {
2726     transitionDisplayCommon<PrimaryDisplayPowerCase<TransitionOnToOffVariant>>();
2727 }
2728 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromDozeSuspendToOffPrimaryDisplay)2729 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromDozeSuspendToOffPrimaryDisplay) {
2730     transitionDisplayCommon<PrimaryDisplayPowerCase<TransitionDozeSuspendToOffVariant>>();
2731 }
2732 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromOnToDozePrimaryDisplay)2733 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromOnToDozePrimaryDisplay) {
2734     transitionDisplayCommon<PrimaryDisplayPowerCase<TransitionOnToDozeVariant>>();
2735 }
2736 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromDozeSuspendToDozePrimaryDisplay)2737 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromDozeSuspendToDozePrimaryDisplay) {
2738     transitionDisplayCommon<PrimaryDisplayPowerCase<TransitionDozeSuspendToDozeVariant>>();
2739 }
2740 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromDozeToOnPrimaryDisplay)2741 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromDozeToOnPrimaryDisplay) {
2742     transitionDisplayCommon<PrimaryDisplayPowerCase<TransitionDozeToOnVariant>>();
2743 }
2744 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromDozeSuspendToOnPrimaryDisplay)2745 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromDozeSuspendToOnPrimaryDisplay) {
2746     transitionDisplayCommon<PrimaryDisplayPowerCase<TransitionDozeSuspendToOnVariant>>();
2747 }
2748 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromOnToDozeSuspendPrimaryDisplay)2749 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromOnToDozeSuspendPrimaryDisplay) {
2750     transitionDisplayCommon<PrimaryDisplayPowerCase<TransitionOnToDozeSuspendVariant>>();
2751 }
2752 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromOnToUnknownPrimaryDisplay)2753 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromOnToUnknownPrimaryDisplay) {
2754     transitionDisplayCommon<PrimaryDisplayPowerCase<TransitionOnToUnknownVariant>>();
2755 }
2756 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromOffToOnExternalDisplay)2757 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromOffToOnExternalDisplay) {
2758     transitionDisplayCommon<ExternalDisplayPowerCase<TransitionOffToOnVariant>>();
2759 }
2760 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromOffToDozeSuspendExternalDisplay)2761 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromOffToDozeSuspendExternalDisplay) {
2762     transitionDisplayCommon<ExternalDisplayPowerCase<TransitionOffToDozeSuspendVariant>>();
2763 }
2764 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromOnToOffExternalDisplay)2765 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromOnToOffExternalDisplay) {
2766     transitionDisplayCommon<ExternalDisplayPowerCase<TransitionOnToOffVariant>>();
2767 }
2768 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromDozeSuspendToOffExternalDisplay)2769 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromDozeSuspendToOffExternalDisplay) {
2770     transitionDisplayCommon<ExternalDisplayPowerCase<TransitionDozeSuspendToOffVariant>>();
2771 }
2772 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromOnToDozeExternalDisplay)2773 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromOnToDozeExternalDisplay) {
2774     transitionDisplayCommon<ExternalDisplayPowerCase<TransitionOnToDozeVariant>>();
2775 }
2776 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromDozeSuspendToDozeExternalDisplay)2777 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromDozeSuspendToDozeExternalDisplay) {
2778     transitionDisplayCommon<ExternalDisplayPowerCase<TransitionDozeSuspendToDozeVariant>>();
2779 }
2780 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromDozeToOnExternalDisplay)2781 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromDozeToOnExternalDisplay) {
2782     transitionDisplayCommon<ExternalDisplayPowerCase<TransitionDozeToOnVariant>>();
2783 }
2784 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromDozeSuspendToOnExternalDisplay)2785 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromDozeSuspendToOnExternalDisplay) {
2786     transitionDisplayCommon<ExternalDisplayPowerCase<TransitionDozeSuspendToOnVariant>>();
2787 }
2788 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromOnToDozeSuspendExternalDisplay)2789 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromOnToDozeSuspendExternalDisplay) {
2790     transitionDisplayCommon<ExternalDisplayPowerCase<TransitionOnToDozeSuspendVariant>>();
2791 }
2792 
TEST_F(SetPowerModeInternalTest,transitionsDisplayFromOnToUnknownExternalDisplay)2793 TEST_F(SetPowerModeInternalTest, transitionsDisplayFromOnToUnknownExternalDisplay) {
2794     transitionDisplayCommon<ExternalDisplayPowerCase<TransitionOnToUnknownVariant>>();
2795 }
2796 
2797 } // namespace
2798 } // namespace android
2799