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 #pragma once
18 
19 #include <compositionengine/Display.h>
20 #include <compositionengine/Layer.h>
21 #include <compositionengine/OutputLayer.h>
22 #include <compositionengine/impl/CompositionEngine.h>
23 #include <compositionengine/impl/LayerCompositionState.h>
24 #include <compositionengine/impl/OutputLayerCompositionState.h>
25 
26 #include "BufferQueueLayer.h"
27 #include "BufferStateLayer.h"
28 #include "ColorLayer.h"
29 #include "ContainerLayer.h"
30 #include "DisplayDevice.h"
31 #include "FakePhaseOffsets.h"
32 #include "Layer.h"
33 #include "NativeWindowSurface.h"
34 #include "Scheduler/MessageQueue.h"
35 #include "Scheduler/RefreshRateConfigs.h"
36 #include "StartPropertySetThread.h"
37 #include "SurfaceFlinger.h"
38 #include "SurfaceFlingerFactory.h"
39 #include "SurfaceInterceptor.h"
40 #include "TimeStats/TimeStats.h"
41 
42 namespace android {
43 
44 class EventThread;
45 
46 namespace renderengine {
47 
48 class RenderEngine;
49 
50 } // namespace renderengine
51 
52 namespace Hwc2 {
53 
54 class Composer;
55 
56 } // namespace Hwc2
57 
58 namespace surfaceflinger::test {
59 
60 class Factory final : public surfaceflinger::Factory {
61 public:
62     ~Factory() = default;
63 
createDispSync(const char *,bool,int64_t)64     std::unique_ptr<DispSync> createDispSync(const char*, bool, int64_t) override {
65         // TODO: Use test-fixture controlled factory
66         return nullptr;
67     }
68 
createEventControlThread(std::function<void (bool)>)69     std::unique_ptr<EventControlThread> createEventControlThread(
70             std::function<void(bool)>) override {
71         // TODO: Use test-fixture controlled factory
72         return nullptr;
73     }
74 
createHWComposer(const std::string &)75     std::unique_ptr<HWComposer> createHWComposer(const std::string&) override {
76         // TODO: Use test-fixture controlled factory
77         return nullptr;
78     }
79 
createMessageQueue()80     std::unique_ptr<MessageQueue> createMessageQueue() override {
81         // TODO: Use test-fixture controlled factory
82         return std::make_unique<android::impl::MessageQueue>();
83     }
84 
createPhaseOffsets()85     std::unique_ptr<scheduler::PhaseOffsets> createPhaseOffsets() override {
86         return std::make_unique<scheduler::FakePhaseOffsets>();
87     }
88 
createScheduler(std::function<void (bool)>,const scheduler::RefreshRateConfigs &)89     std::unique_ptr<Scheduler> createScheduler(std::function<void(bool)>,
90                                                const scheduler::RefreshRateConfigs&) override {
91         // TODO: Use test-fixture controlled factory
92         return nullptr;
93     }
94 
createSurfaceInterceptor(SurfaceFlinger * flinger)95     std::unique_ptr<SurfaceInterceptor> createSurfaceInterceptor(SurfaceFlinger* flinger) override {
96         // TODO: Use test-fixture controlled factory
97         return std::make_unique<android::impl::SurfaceInterceptor>(flinger);
98     }
99 
createStartPropertySetThread(bool timestampPropertyValue)100     sp<StartPropertySetThread> createStartPropertySetThread(bool timestampPropertyValue) override {
101         // TODO: Use test-fixture controlled factory
102         return new StartPropertySetThread(timestampPropertyValue);
103     }
104 
createDisplayDevice(DisplayDeviceCreationArgs && creationArgs)105     sp<DisplayDevice> createDisplayDevice(DisplayDeviceCreationArgs&& creationArgs) override {
106         // TODO: Use test-fixture controlled factory
107         return new DisplayDevice(std::move(creationArgs));
108     }
109 
createGraphicBuffer(uint32_t width,uint32_t height,PixelFormat format,uint32_t layerCount,uint64_t usage,std::string requestorName)110     sp<GraphicBuffer> createGraphicBuffer(uint32_t width, uint32_t height, PixelFormat format,
111                                           uint32_t layerCount, uint64_t usage,
112                                           std::string requestorName) override {
113         // TODO: Use test-fixture controlled factory
114         return new GraphicBuffer(width, height, format, layerCount, usage, requestorName);
115     }
116 
createBufferQueue(sp<IGraphicBufferProducer> * outProducer,sp<IGraphicBufferConsumer> * outConsumer,bool consumerIsSurfaceFlinger)117     void createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
118                            sp<IGraphicBufferConsumer>* outConsumer,
119                            bool consumerIsSurfaceFlinger) override {
120         if (!mCreateBufferQueue) return;
121         mCreateBufferQueue(outProducer, outConsumer, consumerIsSurfaceFlinger);
122     }
123 
createNativeWindowSurface(const sp<IGraphicBufferProducer> & producer)124     std::unique_ptr<surfaceflinger::NativeWindowSurface> createNativeWindowSurface(
125             const sp<IGraphicBufferProducer>& producer) override {
126         if (!mCreateNativeWindowSurface) return nullptr;
127         return mCreateNativeWindowSurface(producer);
128     }
129 
createCompositionEngine()130     std::unique_ptr<compositionengine::CompositionEngine> createCompositionEngine() override {
131         return compositionengine::impl::createCompositionEngine();
132     }
133 
createBufferQueueLayer(const LayerCreationArgs &)134     sp<BufferQueueLayer> createBufferQueueLayer(const LayerCreationArgs&) override {
135         // TODO: Use test-fixture controlled factory
136         return nullptr;
137     }
138 
createBufferStateLayer(const LayerCreationArgs &)139     sp<BufferStateLayer> createBufferStateLayer(const LayerCreationArgs&) override {
140         // TODO: Use test-fixture controlled factory
141         return nullptr;
142     }
143 
createColorLayer(const LayerCreationArgs &)144     sp<ColorLayer> createColorLayer(const LayerCreationArgs&) override {
145         // TODO: Use test-fixture controlled factory
146         return nullptr;
147     }
148 
createContainerLayer(const LayerCreationArgs &)149     sp<ContainerLayer> createContainerLayer(const LayerCreationArgs&) override {
150         // TODO: Use test-fixture controlled factory
151         return nullptr;
152     }
153 
createTimeStats()154     std::shared_ptr<TimeStats> createTimeStats() override {
155         // TODO: Use test-fixture controlled factory
156         return std::make_shared<android::impl::TimeStats>();
157     }
158 
159     using CreateBufferQueueFunction =
160             std::function<void(sp<IGraphicBufferProducer>* /* outProducer */,
161                                sp<IGraphicBufferConsumer>* /* outConsumer */,
162                                bool /* consumerIsSurfaceFlinger */)>;
163     CreateBufferQueueFunction mCreateBufferQueue;
164 
165     using CreateNativeWindowSurfaceFunction =
166             std::function<std::unique_ptr<surfaceflinger::NativeWindowSurface>(
167                     const sp<IGraphicBufferProducer>&)>;
168     CreateNativeWindowSurfaceFunction mCreateNativeWindowSurface;
169 
170     using CreateCompositionEngineFunction =
171             std::function<std::unique_ptr<compositionengine::CompositionEngine>()>;
172     CreateCompositionEngineFunction mCreateCompositionEngine;
173 };
174 
175 } // namespace surfaceflinger::test
176 
177 class TestableSurfaceFlinger {
178 public:
179     // Extend this as needed for accessing SurfaceFlinger private (and public)
180     // functions.
181 
setupRenderEngine(std::unique_ptr<renderengine::RenderEngine> renderEngine)182     void setupRenderEngine(std::unique_ptr<renderengine::RenderEngine> renderEngine) {
183         mFlinger->mCompositionEngine->setRenderEngine(std::move(renderEngine));
184     }
185 
setupComposer(std::unique_ptr<Hwc2::Composer> composer)186     void setupComposer(std::unique_ptr<Hwc2::Composer> composer) {
187         mFlinger->mCompositionEngine->setHwComposer(
188                 std::make_unique<impl::HWComposer>(std::move(composer)));
189     }
190 
191     using CreateBufferQueueFunction = surfaceflinger::test::Factory::CreateBufferQueueFunction;
setCreateBufferQueueFunction(CreateBufferQueueFunction f)192     void setCreateBufferQueueFunction(CreateBufferQueueFunction f) {
193         mFactory.mCreateBufferQueue = f;
194     }
195 
196     using CreateNativeWindowSurfaceFunction =
197             surfaceflinger::test::Factory::CreateNativeWindowSurfaceFunction;
setCreateNativeWindowSurface(CreateNativeWindowSurfaceFunction f)198     void setCreateNativeWindowSurface(CreateNativeWindowSurfaceFunction f) {
199         mFactory.mCreateNativeWindowSurface = f;
200     }
201 
setInternalDisplayPrimaries(const ui::DisplayPrimaries & primaries)202     void setInternalDisplayPrimaries(const ui::DisplayPrimaries& primaries) {
203         memcpy(&mFlinger->mInternalDisplayPrimaries, &primaries, sizeof(ui::DisplayPrimaries));
204     }
205 
206     using HotplugEvent = SurfaceFlinger::HotplugEvent;
207 
mutableLayerCurrentState(sp<Layer> layer)208     auto& mutableLayerCurrentState(sp<Layer> layer) { return layer->mCurrentState; }
mutableLayerDrawingState(sp<Layer> layer)209     auto& mutableLayerDrawingState(sp<Layer> layer) { return layer->mDrawingState; }
210 
setLayerSidebandStream(sp<Layer> layer,sp<NativeHandle> sidebandStream)211     void setLayerSidebandStream(sp<Layer> layer, sp<NativeHandle> sidebandStream) {
212         layer->mDrawingState.sidebandStream = sidebandStream;
213         layer->mSidebandStream = sidebandStream;
214         layer->getCompositionLayer()->editState().frontEnd.sidebandStream = sidebandStream;
215     }
216 
setLayerCompositionType(sp<Layer> layer,HWC2::Composition type)217     void setLayerCompositionType(sp<Layer> layer, HWC2::Composition type) {
218         auto outputLayer = layer->findOutputLayerForDisplay(mFlinger->getDefaultDisplayDevice());
219         LOG_ALWAYS_FATAL_IF(!outputLayer);
220         auto& state = outputLayer->editState();
221         LOG_ALWAYS_FATAL_IF(!outputLayer->getState().hwc);
222         (*state.hwc).hwcCompositionType = static_cast<Hwc2::IComposerClient::Composition>(type);
223     };
224 
setLayerPotentialCursor(sp<Layer> layer,bool potentialCursor)225     void setLayerPotentialCursor(sp<Layer> layer, bool potentialCursor) {
226         layer->mPotentialCursor = potentialCursor;
227     }
228 
229     /* ------------------------------------------------------------------------
230      * Forwarding for functions being tested
231      */
232 
createDisplay(const String8 & displayName,bool secure)233     auto createDisplay(const String8& displayName, bool secure) {
234         return mFlinger->createDisplay(displayName, secure);
235     }
236 
destroyDisplay(const sp<IBinder> & displayToken)237     auto destroyDisplay(const sp<IBinder>& displayToken) {
238         return mFlinger->destroyDisplay(displayToken);
239     }
240 
resetDisplayState()241     auto resetDisplayState() { return mFlinger->resetDisplayState(); }
242 
setupNewDisplayDeviceInternal(const wp<IBinder> & displayToken,const std::optional<DisplayId> & displayId,const DisplayDeviceState & state,const sp<compositionengine::DisplaySurface> & dispSurface,const sp<IGraphicBufferProducer> & producer)243     auto setupNewDisplayDeviceInternal(const wp<IBinder>& displayToken,
244                                        const std::optional<DisplayId>& displayId,
245                                        const DisplayDeviceState& state,
246                                        const sp<compositionengine::DisplaySurface>& dispSurface,
247                                        const sp<IGraphicBufferProducer>& producer) {
248         return mFlinger->setupNewDisplayDeviceInternal(displayToken, displayId, state, dispSurface,
249                                                        producer);
250     }
251 
handleTransactionLocked(uint32_t transactionFlags)252     auto handleTransactionLocked(uint32_t transactionFlags) {
253         Mutex::Autolock _l(mFlinger->mStateLock);
254         return mFlinger->handleTransactionLocked(transactionFlags);
255     }
256 
onHotplugReceived(int32_t sequenceId,hwc2_display_t display,HWC2::Connection connection)257     auto onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
258                            HWC2::Connection connection) {
259         return mFlinger->onHotplugReceived(sequenceId, display, connection);
260     }
261 
setDisplayStateLocked(const DisplayState & s)262     auto setDisplayStateLocked(const DisplayState& s) {
263         Mutex::Autolock _l(mFlinger->mStateLock);
264         return mFlinger->setDisplayStateLocked(s);
265     }
266 
267     // Allow reading display state without locking, as if called on the SF main thread.
onInitializeDisplays()268     auto onInitializeDisplays() NO_THREAD_SAFETY_ANALYSIS {
269         return mFlinger->onInitializeDisplays();
270     }
271 
272     // Allow reading display state without locking, as if called on the SF main thread.
setPowerModeInternal(const sp<DisplayDevice> & display,int mode)273     auto setPowerModeInternal(const sp<DisplayDevice>& display,
274                               int mode) NO_THREAD_SAFETY_ANALYSIS {
275         return mFlinger->setPowerModeInternal(display, mode);
276     }
277 
onMessageReceived(int32_t what)278     auto onMessageReceived(int32_t what) { return mFlinger->onMessageReceived(what); }
279 
captureScreenImplLocked(const RenderArea & renderArea,SurfaceFlinger::TraverseLayersFunction traverseLayers,ANativeWindowBuffer * buffer,bool useIdentityTransform,bool forSystem,int * outSyncFd)280     auto captureScreenImplLocked(
281             const RenderArea& renderArea, SurfaceFlinger::TraverseLayersFunction traverseLayers,
282             ANativeWindowBuffer* buffer, bool useIdentityTransform, bool forSystem, int* outSyncFd) {
283         bool ignored;
284         return mFlinger->captureScreenImplLocked(renderArea, traverseLayers, buffer,
285                                                  useIdentityTransform, forSystem, outSyncFd,
286                                                  ignored);
287     }
288 
traverseLayersInDisplay(const sp<const DisplayDevice> & display,const LayerVector::Visitor & visitor)289     auto traverseLayersInDisplay(const sp<const DisplayDevice>& display,
290                                  const LayerVector::Visitor& visitor) {
291         return mFlinger->SurfaceFlinger::traverseLayersInDisplay(display, visitor);
292     }
293 
getDisplayNativePrimaries(const sp<IBinder> & displayToken,ui::DisplayPrimaries & primaries)294     auto getDisplayNativePrimaries(const sp<IBinder>& displayToken,
295                                    ui::DisplayPrimaries &primaries) {
296         return mFlinger->SurfaceFlinger::getDisplayNativePrimaries(displayToken, primaries);
297     }
298 
299     /* ------------------------------------------------------------------------
300      * Read-only access to private data to assert post-conditions.
301      */
302 
getAnimFrameTracker()303     const auto& getAnimFrameTracker() const { return mFlinger->mAnimFrameTracker; }
getHasPoweredOff()304     const auto& getHasPoweredOff() const { return mFlinger->mHasPoweredOff; }
getVisibleRegionsDirty()305     const auto& getVisibleRegionsDirty() const { return mFlinger->mVisibleRegionsDirty; }
getHwComposer()306     auto& getHwComposer() const {
307         return static_cast<impl::HWComposer&>(mFlinger->getHwComposer());
308     }
309 
getCompositorTiming()310     const auto& getCompositorTiming() const { return mFlinger->getBE().mCompositorTiming; }
311 
312     /* ------------------------------------------------------------------------
313      * Read-write access to private data to set up preconditions and assert
314      * post-conditions.
315      */
316 
mutableHasWideColorDisplay()317     auto& mutableHasWideColorDisplay() { return SurfaceFlinger::hasWideColorDisplay; }
mutablePrimaryDisplayOrientation()318     auto& mutablePrimaryDisplayOrientation() { return SurfaceFlinger::primaryDisplayOrientation; }
mutableUseColorManagement()319     auto& mutableUseColorManagement() { return SurfaceFlinger::useColorManagement; }
320 
mutableCurrentState()321     auto& mutableCurrentState() { return mFlinger->mCurrentState; }
mutableDisplayColorSetting()322     auto& mutableDisplayColorSetting() { return mFlinger->mDisplayColorSetting; }
mutableDisplays()323     auto& mutableDisplays() { return mFlinger->mDisplays; }
mutableDrawingState()324     auto& mutableDrawingState() { return mFlinger->mDrawingState; }
mutableEventQueue()325     auto& mutableEventQueue() { return mFlinger->mEventQueue; }
mutableGeometryInvalid()326     auto& mutableGeometryInvalid() { return mFlinger->mGeometryInvalid; }
mutableInterceptor()327     auto& mutableInterceptor() { return mFlinger->mInterceptor; }
mutableMainThreadId()328     auto& mutableMainThreadId() { return mFlinger->mMainThreadId; }
mutablePendingHotplugEvents()329     auto& mutablePendingHotplugEvents() { return mFlinger->mPendingHotplugEvents; }
mutablePhysicalDisplayTokens()330     auto& mutablePhysicalDisplayTokens() { return mFlinger->mPhysicalDisplayTokens; }
mutableTexturePool()331     auto& mutableTexturePool() { return mFlinger->mTexturePool; }
mutableTransactionFlags()332     auto& mutableTransactionFlags() { return mFlinger->mTransactionFlags; }
mutableUseHwcVirtualDisplays()333     auto& mutableUseHwcVirtualDisplays() { return mFlinger->mUseHwcVirtualDisplays; }
mutablePowerAdvisor()334     auto& mutablePowerAdvisor() { return mFlinger->mPowerAdvisor; }
335 
mutableComposerSequenceId()336     auto& mutableComposerSequenceId() { return mFlinger->getBE().mComposerSequenceId; }
mutableHwcDisplayData()337     auto& mutableHwcDisplayData() { return getHwComposer().mDisplayData; }
mutableHwcPhysicalDisplayIdMap()338     auto& mutableHwcPhysicalDisplayIdMap() { return getHwComposer().mPhysicalDisplayIdMap; }
mutableInternalHwcDisplayId()339     auto& mutableInternalHwcDisplayId() { return getHwComposer().mInternalHwcDisplayId; }
mutableExternalHwcDisplayId()340     auto& mutableExternalHwcDisplayId() { return getHwComposer().mExternalHwcDisplayId; }
mutableScheduler()341     auto& mutableScheduler() { return mFlinger->mScheduler; }
mutableAppConnectionHandle()342     auto& mutableAppConnectionHandle() { return mFlinger->mAppConnectionHandle; }
mutableSfConnectionHandle()343     auto& mutableSfConnectionHandle() { return mFlinger->mSfConnectionHandle; }
mutableRefreshRateConfigs()344     auto& mutableRefreshRateConfigs() { return mFlinger->mRefreshRateConfigs; }
mutableRefreshRateStats()345     auto& mutableRefreshRateStats() { return mFlinger->mRefreshRateStats; }
mutableTimeStats()346     auto& mutableTimeStats() { return mFlinger->mTimeStats; }
347 
~TestableSurfaceFlinger()348     ~TestableSurfaceFlinger() {
349         // All these pointer and container clears help ensure that GMock does
350         // not report a leaked object, since the SurfaceFlinger instance may
351         // still be referenced by something despite our best efforts to destroy
352         // it after each test is done.
353         mutableDisplays().clear();
354         mutableCurrentState().displays.clear();
355         mutableDrawingState().displays.clear();
356         mutableEventQueue().reset();
357         mutableInterceptor().reset();
358         mutableScheduler().reset();
359         mFlinger->mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
360         mFlinger->mCompositionEngine->setRenderEngine(
361                 std::unique_ptr<renderengine::RenderEngine>());
362     }
363 
364     /* ------------------------------------------------------------------------
365      * Wrapper classes for Read-write access to private data to set up
366      * preconditions and assert post-conditions.
367      */
368     struct HWC2Display : public HWC2::impl::Display {
HWC2DisplayHWC2Display369         HWC2Display(Hwc2::Composer& composer,
370                     const std::unordered_set<HWC2::Capability>& capabilities, hwc2_display_t id,
371                     HWC2::DisplayType type)
372               : HWC2::impl::Display(composer, capabilities, id, type) {}
~HWC2DisplayHWC2Display373         ~HWC2Display() {
374             // Prevents a call to disable vsyncs.
375             mType = HWC2::DisplayType::Invalid;
376         }
377 
mutableIsConnectedHWC2Display378         auto& mutableIsConnected() { return this->mIsConnected; }
mutableConfigsHWC2Display379         auto& mutableConfigs() { return this->mConfigs; }
mutableLayersHWC2Display380         auto& mutableLayers() { return this->mLayers; }
381     };
382 
383     class FakeHwcDisplayInjector {
384     public:
385         static constexpr hwc2_display_t DEFAULT_HWC_DISPLAY_ID = 1000;
386         static constexpr int32_t DEFAULT_WIDTH = 1920;
387         static constexpr int32_t DEFAULT_HEIGHT = 1280;
388         static constexpr int32_t DEFAULT_REFRESH_RATE = 16'666'666;
389         static constexpr int32_t DEFAULT_DPI = 320;
390         static constexpr int32_t DEFAULT_ACTIVE_CONFIG = 0;
391         static constexpr int32_t DEFAULT_POWER_MODE = 2;
392 
FakeHwcDisplayInjector(DisplayId displayId,HWC2::DisplayType hwcDisplayType,bool isPrimary)393         FakeHwcDisplayInjector(DisplayId displayId, HWC2::DisplayType hwcDisplayType,
394                                bool isPrimary)
395               : mDisplayId(displayId), mHwcDisplayType(hwcDisplayType), mIsPrimary(isPrimary) {}
396 
setHwcDisplayId(hwc2_display_t displayId)397         auto& setHwcDisplayId(hwc2_display_t displayId) {
398             mHwcDisplayId = displayId;
399             return *this;
400         }
401 
setWidth(int32_t width)402         auto& setWidth(int32_t width) {
403             mWidth = width;
404             return *this;
405         }
406 
setHeight(int32_t height)407         auto& setHeight(int32_t height) {
408             mHeight = height;
409             return *this;
410         }
411 
setRefreshRate(int32_t refreshRate)412         auto& setRefreshRate(int32_t refreshRate) {
413             mRefreshRate = refreshRate;
414             return *this;
415         }
416 
setDpiX(int32_t dpi)417         auto& setDpiX(int32_t dpi) {
418             mDpiX = dpi;
419             return *this;
420         }
421 
setDpiY(int32_t dpi)422         auto& setDpiY(int32_t dpi) {
423             mDpiY = dpi;
424             return *this;
425         }
426 
setActiveConfig(int32_t config)427         auto& setActiveConfig(int32_t config) {
428             mActiveConfig = config;
429             return *this;
430         }
431 
setCapabilities(const std::unordered_set<HWC2::Capability> * capabilities)432         auto& setCapabilities(const std::unordered_set<HWC2::Capability>* capabilities) {
433             mCapabilities = capabilities;
434             return *this;
435         }
436 
setPowerMode(int mode)437         auto& setPowerMode(int mode) {
438             mPowerMode = mode;
439             return *this;
440         }
441 
inject(TestableSurfaceFlinger * flinger,Hwc2::Composer * composer)442         void inject(TestableSurfaceFlinger* flinger, Hwc2::Composer* composer) {
443             static const std::unordered_set<HWC2::Capability> defaultCapabilities;
444             if (mCapabilities == nullptr) mCapabilities = &defaultCapabilities;
445 
446             // Caution - Make sure that any values passed by reference here do
447             // not refer to an instance owned by FakeHwcDisplayInjector. This
448             // class has temporary lifetime, while the constructed HWC2::Display
449             // is much longer lived.
450             auto display = std::make_unique<HWC2Display>(*composer, *mCapabilities, mHwcDisplayId,
451                                                          mHwcDisplayType);
452 
453             auto config = HWC2::Display::Config::Builder(*display, mActiveConfig);
454             config.setWidth(mWidth);
455             config.setHeight(mHeight);
456             config.setVsyncPeriod(mRefreshRate);
457             config.setDpiX(mDpiX);
458             config.setDpiY(mDpiY);
459             display->mutableConfigs().emplace(mActiveConfig, config.build());
460             display->mutableIsConnected() = true;
461             display->setPowerMode(static_cast<HWC2::PowerMode>(mPowerMode));
462 
463             flinger->mutableHwcDisplayData()[mDisplayId].hwcDisplay = display.get();
464 
465             if (mHwcDisplayType == HWC2::DisplayType::Physical) {
466                 flinger->mutableHwcPhysicalDisplayIdMap().emplace(mHwcDisplayId, mDisplayId);
467                 (mIsPrimary ? flinger->mutableInternalHwcDisplayId()
468                             : flinger->mutableExternalHwcDisplayId()) = mHwcDisplayId;
469             }
470 
471             flinger->mFakeHwcDisplays.push_back(std::move(display));
472         }
473 
474     private:
475         const DisplayId mDisplayId;
476         const HWC2::DisplayType mHwcDisplayType;
477         const bool mIsPrimary;
478 
479         hwc2_display_t mHwcDisplayId = DEFAULT_HWC_DISPLAY_ID;
480         int32_t mWidth = DEFAULT_WIDTH;
481         int32_t mHeight = DEFAULT_HEIGHT;
482         int32_t mRefreshRate = DEFAULT_REFRESH_RATE;
483         int32_t mDpiX = DEFAULT_DPI;
484         int32_t mDpiY = DEFAULT_DPI;
485         int32_t mActiveConfig = DEFAULT_ACTIVE_CONFIG;
486         int32_t mPowerMode = DEFAULT_POWER_MODE;
487         const std::unordered_set<HWC2::Capability>* mCapabilities = nullptr;
488     };
489 
490     class FakeDisplayDeviceInjector {
491     public:
FakeDisplayDeviceInjector(TestableSurfaceFlinger & flinger,const std::optional<DisplayId> & displayId,bool isVirtual,bool isPrimary)492         FakeDisplayDeviceInjector(TestableSurfaceFlinger& flinger,
493                                   const std::optional<DisplayId>& displayId, bool isVirtual,
494                                   bool isPrimary)
495               : mFlinger(flinger), mCreationArgs(flinger.mFlinger.get(), mDisplayToken, displayId) {
496             mCreationArgs.isVirtual = isVirtual;
497             mCreationArgs.isPrimary = isPrimary;
498         }
499 
token()500         sp<IBinder> token() const { return mDisplayToken; }
501 
mutableDrawingDisplayState()502         DisplayDeviceState& mutableDrawingDisplayState() {
503             return mFlinger.mutableDrawingState().displays.editValueFor(mDisplayToken);
504         }
505 
mutableCurrentDisplayState()506         DisplayDeviceState& mutableCurrentDisplayState() {
507             return mFlinger.mutableCurrentState().displays.editValueFor(mDisplayToken);
508         }
509 
getDrawingDisplayState()510         const auto& getDrawingDisplayState() {
511             return mFlinger.mutableDrawingState().displays.valueFor(mDisplayToken);
512         }
513 
getCurrentDisplayState()514         const auto& getCurrentDisplayState() {
515             return mFlinger.mutableCurrentState().displays.valueFor(mDisplayToken);
516         }
517 
mutableDisplayDevice()518         auto& mutableDisplayDevice() { return mFlinger.mutableDisplays()[mDisplayToken]; }
519 
setNativeWindow(const sp<ANativeWindow> & nativeWindow)520         auto& setNativeWindow(const sp<ANativeWindow>& nativeWindow) {
521             mCreationArgs.nativeWindow = nativeWindow;
522             return *this;
523         }
524 
setDisplaySurface(const sp<compositionengine::DisplaySurface> & displaySurface)525         auto& setDisplaySurface(const sp<compositionengine::DisplaySurface>& displaySurface) {
526             mCreationArgs.displaySurface = displaySurface;
527             return *this;
528         }
529 
setSecure(bool secure)530         auto& setSecure(bool secure) {
531             mCreationArgs.isSecure = secure;
532             return *this;
533         }
534 
setPowerMode(int mode)535         auto& setPowerMode(int mode) {
536             mCreationArgs.initialPowerMode = mode;
537             return *this;
538         }
539 
setHwcColorModes(const std::unordered_map<ui::ColorMode,std::vector<ui::RenderIntent>> hwcColorModes)540         auto& setHwcColorModes(
541                 const std::unordered_map<ui::ColorMode, std::vector<ui::RenderIntent>>
542                         hwcColorModes) {
543             mCreationArgs.hwcColorModes = hwcColorModes;
544             return *this;
545         }
546 
setHasWideColorGamut(bool hasWideColorGamut)547         auto& setHasWideColorGamut(bool hasWideColorGamut) {
548             mCreationArgs.hasWideColorGamut = hasWideColorGamut;
549             return *this;
550         }
551 
inject()552         sp<DisplayDevice> inject() {
553             DisplayDeviceState state;
554             state.displayId = mCreationArgs.isVirtual ? std::nullopt : mCreationArgs.displayId;
555             state.isSecure = mCreationArgs.isSecure;
556 
557             sp<DisplayDevice> device = new DisplayDevice(std::move(mCreationArgs));
558             mFlinger.mutableDisplays().emplace(mDisplayToken, device);
559             mFlinger.mutableCurrentState().displays.add(mDisplayToken, state);
560             mFlinger.mutableDrawingState().displays.add(mDisplayToken, state);
561 
562             if (!mCreationArgs.isVirtual) {
563                 LOG_ALWAYS_FATAL_IF(!state.displayId);
564                 mFlinger.mutablePhysicalDisplayTokens()[*state.displayId] = mDisplayToken;
565             }
566 
567             return device;
568         }
569 
570     private:
571         TestableSurfaceFlinger& mFlinger;
572         sp<BBinder> mDisplayToken = new BBinder();
573         DisplayDeviceCreationArgs mCreationArgs;
574     };
575 
576     surfaceflinger::test::Factory mFactory;
577     sp<SurfaceFlinger> mFlinger = new SurfaceFlinger(mFactory, SurfaceFlinger::SkipInitialization);
578 
579     // We need to keep a reference to these so they are properly destroyed.
580     std::vector<std::unique_ptr<HWC2Display>> mFakeHwcDisplays;
581 };
582 
583 } // namespace android
584