• 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 #pragma once
18 
19 #include <compositionengine/Display.h>
20 #include <compositionengine/LayerFECompositionState.h>
21 #include <compositionengine/OutputLayer.h>
22 #include <compositionengine/impl/CompositionEngine.h>
23 #include <compositionengine/impl/Display.h>
24 #include <compositionengine/impl/OutputLayerCompositionState.h>
25 #include <compositionengine/mock/DisplaySurface.h>
26 #include <gui/ScreenCaptureResults.h>
27 
28 #include "BufferQueueLayer.h"
29 #include "BufferStateLayer.h"
30 #include "ContainerLayer.h"
31 #include "DisplayDevice.h"
32 #include "EffectLayer.h"
33 #include "FakeVsyncConfiguration.h"
34 #include "FrameTracer/FrameTracer.h"
35 #include "Layer.h"
36 #include "NativeWindowSurface.h"
37 #include "Scheduler/MessageQueue.h"
38 #include "Scheduler/RefreshRateConfigs.h"
39 #include "StartPropertySetThread.h"
40 #include "SurfaceFlinger.h"
41 #include "SurfaceFlingerDefaultFactory.h"
42 #include "SurfaceInterceptor.h"
43 #include "TestableScheduler.h"
44 #include "mock/DisplayHardware/MockComposer.h"
45 #include "mock/MockFrameTimeline.h"
46 #include "mock/MockFrameTracer.h"
47 
48 namespace android {
49 
50 class EventThread;
51 
52 namespace renderengine {
53 
54 class RenderEngine;
55 
56 } // namespace renderengine
57 
58 namespace Hwc2 {
59 
60 class Composer;
61 
62 } // namespace Hwc2
63 
64 namespace hal = android::hardware::graphics::composer::hal;
65 
66 namespace surfaceflinger::test {
67 
68 class Factory final : public surfaceflinger::Factory {
69 public:
70     ~Factory() = default;
71 
createHWComposer(const std::string &)72     std::unique_ptr<HWComposer> createHWComposer(const std::string&) override {
73         return nullptr;
74     }
75 
createMessageQueue()76     std::unique_ptr<MessageQueue> createMessageQueue() override {
77         return std::make_unique<android::impl::MessageQueue>();
78     }
79 
createVsyncConfiguration(Fps)80     std::unique_ptr<scheduler::VsyncConfiguration> createVsyncConfiguration(
81             Fps /*currentRefreshRate*/) override {
82         return std::make_unique<scheduler::FakePhaseOffsets>();
83     }
84 
createScheduler(const scheduler::RefreshRateConfigs &,ISchedulerCallback &)85     std::unique_ptr<Scheduler> createScheduler(const scheduler::RefreshRateConfigs&,
86                                                ISchedulerCallback&) override {
87         return nullptr;
88     }
89 
createSurfaceInterceptor()90     sp<SurfaceInterceptor> createSurfaceInterceptor() override {
91         return new android::impl::SurfaceInterceptor();
92     }
93 
createStartPropertySetThread(bool timestampPropertyValue)94     sp<StartPropertySetThread> createStartPropertySetThread(bool timestampPropertyValue) override {
95         return new StartPropertySetThread(timestampPropertyValue);
96     }
97 
createDisplayDevice(DisplayDeviceCreationArgs & creationArgs)98     sp<DisplayDevice> createDisplayDevice(DisplayDeviceCreationArgs& creationArgs) override {
99         return new DisplayDevice(creationArgs);
100     }
101 
createGraphicBuffer(uint32_t width,uint32_t height,PixelFormat format,uint32_t layerCount,uint64_t usage,std::string requestorName)102     sp<GraphicBuffer> createGraphicBuffer(uint32_t width, uint32_t height, PixelFormat format,
103                                           uint32_t layerCount, uint64_t usage,
104                                           std::string requestorName) override {
105         return new GraphicBuffer(width, height, format, layerCount, usage, requestorName);
106     }
107 
createBufferQueue(sp<IGraphicBufferProducer> * outProducer,sp<IGraphicBufferConsumer> * outConsumer,bool consumerIsSurfaceFlinger)108     void createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
109                            sp<IGraphicBufferConsumer>* outConsumer,
110                            bool consumerIsSurfaceFlinger) override {
111         if (!mCreateBufferQueue) {
112             BufferQueue::createBufferQueue(outProducer, outConsumer, consumerIsSurfaceFlinger);
113             return;
114         }
115         mCreateBufferQueue(outProducer, outConsumer, consumerIsSurfaceFlinger);
116     }
117 
createMonitoredProducer(const sp<IGraphicBufferProducer> & producer,const sp<SurfaceFlinger> & flinger,const wp<Layer> & layer)118     sp<IGraphicBufferProducer> createMonitoredProducer(const sp<IGraphicBufferProducer>& producer,
119                                                        const sp<SurfaceFlinger>& flinger,
120                                                        const wp<Layer>& layer) override {
121         return new MonitoredProducer(producer, flinger, layer);
122     }
123 
createBufferLayerConsumer(const sp<IGraphicBufferConsumer> & consumer,renderengine::RenderEngine & renderEngine,uint32_t textureName,Layer * layer)124     sp<BufferLayerConsumer> createBufferLayerConsumer(const sp<IGraphicBufferConsumer>& consumer,
125                                                       renderengine::RenderEngine& renderEngine,
126                                                       uint32_t textureName, Layer* layer) override {
127         return new BufferLayerConsumer(consumer, renderEngine, textureName, layer);
128     }
129 
createNativeWindowSurface(const sp<IGraphicBufferProducer> & producer)130     std::unique_ptr<surfaceflinger::NativeWindowSurface> createNativeWindowSurface(
131             const sp<IGraphicBufferProducer>& producer) override {
132         if (!mCreateNativeWindowSurface) return nullptr;
133         return mCreateNativeWindowSurface(producer);
134     }
135 
createCompositionEngine()136     std::unique_ptr<compositionengine::CompositionEngine> createCompositionEngine() override {
137         return compositionengine::impl::createCompositionEngine();
138     }
139 
createBufferQueueLayer(const LayerCreationArgs &)140     sp<BufferQueueLayer> createBufferQueueLayer(const LayerCreationArgs&) override {
141         return nullptr;
142     }
143 
createBufferStateLayer(const LayerCreationArgs &)144     sp<BufferStateLayer> createBufferStateLayer(const LayerCreationArgs&) override {
145         return nullptr;
146     }
147 
createEffectLayer(const LayerCreationArgs &)148     sp<EffectLayer> createEffectLayer(const LayerCreationArgs&) override { return nullptr; }
149 
createContainerLayer(const LayerCreationArgs &)150     sp<ContainerLayer> createContainerLayer(const LayerCreationArgs&) override {
151         return nullptr;
152     }
153 
createFrameTracer()154     std::unique_ptr<FrameTracer> createFrameTracer() override {
155         return std::make_unique<mock::FrameTracer>();
156     }
157 
158     std::unique_ptr<frametimeline::FrameTimeline> createFrameTimeline(
159             std::shared_ptr<TimeStats> timeStats, pid_t surfaceFlingerPid = 0) override {
160         return std::make_unique<mock::FrameTimeline>(timeStats, surfaceFlingerPid);
161     }
162 
163     using CreateBufferQueueFunction =
164             std::function<void(sp<IGraphicBufferProducer>* /* outProducer */,
165                                sp<IGraphicBufferConsumer>* /* outConsumer */,
166                                bool /* consumerIsSurfaceFlinger */)>;
167     CreateBufferQueueFunction mCreateBufferQueue;
168 
169     using CreateNativeWindowSurfaceFunction =
170             std::function<std::unique_ptr<surfaceflinger::NativeWindowSurface>(
171                     const sp<IGraphicBufferProducer>&)>;
172     CreateNativeWindowSurfaceFunction mCreateNativeWindowSurface;
173 
174     using CreateCompositionEngineFunction =
175             std::function<std::unique_ptr<compositionengine::CompositionEngine>()>;
176     CreateCompositionEngineFunction mCreateCompositionEngine;
177 };
178 
179 } // namespace surfaceflinger::test
180 
181 class TestableSurfaceFlinger final : private ISchedulerCallback {
182 public:
183     using HotplugEvent = SurfaceFlinger::HotplugEvent;
184 
flinger()185     SurfaceFlinger* flinger() { return mFlinger.get(); }
scheduler()186     TestableScheduler* scheduler() { return mScheduler; }
187 
188     // Extend this as needed for accessing SurfaceFlinger private (and public)
189     // functions.
190 
setupRenderEngine(std::unique_ptr<renderengine::RenderEngine> renderEngine)191     void setupRenderEngine(std::unique_ptr<renderengine::RenderEngine> renderEngine) {
192         mFlinger->mCompositionEngine->setRenderEngine(std::move(renderEngine));
193     }
194 
setupComposer(std::unique_ptr<Hwc2::Composer> composer)195     void setupComposer(std::unique_ptr<Hwc2::Composer> composer) {
196         mFlinger->mCompositionEngine->setHwComposer(
197                 std::make_unique<impl::HWComposer>(std::move(composer)));
198     }
199 
setupTimeStats(const std::shared_ptr<TimeStats> & timeStats)200     void setupTimeStats(const std::shared_ptr<TimeStats>& timeStats) {
201         mFlinger->mCompositionEngine->setTimeStats(timeStats);
202     }
203 
204     // The ISchedulerCallback argument can be nullptr for a no-op implementation.
205     void setupScheduler(std::unique_ptr<scheduler::VsyncController> vsyncController,
206                         std::unique_ptr<scheduler::VSyncTracker> vsyncTracker,
207                         std::unique_ptr<EventThread> appEventThread,
208                         std::unique_ptr<EventThread> sfEventThread,
209                         ISchedulerCallback* callback = nullptr, bool hasMultipleModes = false) {
210         DisplayModes modes{DisplayMode::Builder(0)
211                                    .setId(DisplayModeId(0))
212                                    .setVsyncPeriod(16'666'667)
213                                    .setGroup(0)
214                                    .build()};
215 
216         if (hasMultipleModes) {
217             modes.emplace_back(DisplayMode::Builder(1)
218                                        .setId(DisplayModeId(1))
219                                        .setVsyncPeriod(11'111'111)
220                                        .setGroup(0)
221                                        .build());
222         }
223 
224         const auto currMode = DisplayModeId(0);
225         mFlinger->mRefreshRateConfigs =
226                 std::make_unique<scheduler::RefreshRateConfigs>(modes, currMode);
227         const auto currFps =
228                 mFlinger->mRefreshRateConfigs->getRefreshRateFromModeId(currMode).getFps();
229         mFlinger->mRefreshRateStats =
230                 std::make_unique<scheduler::RefreshRateStats>(*mFlinger->mTimeStats, currFps,
231                                                               /*powerMode=*/hal::PowerMode::OFF);
232         mFlinger->mVsyncConfiguration = mFactory.createVsyncConfiguration(currFps);
233         mFlinger->mVsyncModulator = sp<scheduler::VsyncModulator>::make(
234                 mFlinger->mVsyncConfiguration->getCurrentConfigs());
235 
236         mScheduler = new TestableScheduler(std::move(vsyncController), std::move(vsyncTracker),
237                                            *mFlinger->mRefreshRateConfigs, *(callback ?: this));
238 
239         mFlinger->mAppConnectionHandle = mScheduler->createConnection(std::move(appEventThread));
240         mFlinger->mSfConnectionHandle = mScheduler->createConnection(std::move(sfEventThread));
241         resetScheduler(mScheduler);
242     }
243 
resetScheduler(Scheduler * scheduler)244     void resetScheduler(Scheduler* scheduler) { mFlinger->mScheduler.reset(scheduler); }
245 
mutableScheduler()246     TestableScheduler& mutableScheduler() const { return *mScheduler; }
247 
248     using CreateBufferQueueFunction = surfaceflinger::test::Factory::CreateBufferQueueFunction;
setCreateBufferQueueFunction(CreateBufferQueueFunction f)249     void setCreateBufferQueueFunction(CreateBufferQueueFunction f) {
250         mFactory.mCreateBufferQueue = f;
251     }
252 
253     using CreateNativeWindowSurfaceFunction =
254             surfaceflinger::test::Factory::CreateNativeWindowSurfaceFunction;
setCreateNativeWindowSurface(CreateNativeWindowSurfaceFunction f)255     void setCreateNativeWindowSurface(CreateNativeWindowSurfaceFunction f) {
256         mFactory.mCreateNativeWindowSurface = f;
257     }
258 
setInternalDisplayPrimaries(const ui::DisplayPrimaries & primaries)259     void setInternalDisplayPrimaries(const ui::DisplayPrimaries& primaries) {
260         memcpy(&mFlinger->mInternalDisplayPrimaries, &primaries, sizeof(ui::DisplayPrimaries));
261     }
262 
mutableLayerDrawingState(const sp<Layer> & layer)263     static auto& mutableLayerDrawingState(const sp<Layer>& layer) { return layer->mDrawingState; }
264 
mutableStateLock()265     auto& mutableStateLock() { return mFlinger->mStateLock; }
266 
findOutputLayerForDisplay(const sp<Layer> & layer,const sp<const DisplayDevice> & display)267     static auto findOutputLayerForDisplay(const sp<Layer>& layer,
268                                           const sp<const DisplayDevice>& display) {
269         return layer->findOutputLayerForDisplay(display.get());
270     }
271 
setLayerSidebandStream(const sp<Layer> & layer,const sp<NativeHandle> & sidebandStream)272     static void setLayerSidebandStream(const sp<Layer>& layer,
273                                        const sp<NativeHandle>& sidebandStream) {
274         layer->mDrawingState.sidebandStream = sidebandStream;
275         layer->mSidebandStream = sidebandStream;
276         layer->editCompositionState()->sidebandStream = sidebandStream;
277     }
278 
setLayerCompositionType(const sp<Layer> & layer,hal::Composition type)279     void setLayerCompositionType(const sp<Layer>& layer, hal::Composition type) {
280         auto outputLayer = findOutputLayerForDisplay(layer, mFlinger->getDefaultDisplayDevice());
281         LOG_ALWAYS_FATAL_IF(!outputLayer);
282         auto& state = outputLayer->editState();
283         LOG_ALWAYS_FATAL_IF(!outputLayer->getState().hwc);
284         (*state.hwc).hwcCompositionType = type;
285     }
286 
setLayerPotentialCursor(const sp<Layer> & layer,bool potentialCursor)287     static void setLayerPotentialCursor(const sp<Layer>& layer, bool potentialCursor) {
288         layer->mPotentialCursor = potentialCursor;
289     }
290 
setLayerDrawingParent(const sp<Layer> & layer,const sp<Layer> & drawingParent)291     static void setLayerDrawingParent(const sp<Layer>& layer, const sp<Layer>& drawingParent) {
292         layer->mDrawingParent = drawingParent;
293     }
294 
295     /* ------------------------------------------------------------------------
296      * Forwarding for functions being tested
297      */
298 
createDisplay(const String8 & displayName,bool secure)299     auto createDisplay(const String8& displayName, bool secure) {
300         return mFlinger->createDisplay(displayName, secure);
301     }
302 
destroyDisplay(const sp<IBinder> & displayToken)303     auto destroyDisplay(const sp<IBinder>& displayToken) {
304         return mFlinger->destroyDisplay(displayToken);
305     }
306 
enableHalVirtualDisplays(bool enable)307     void enableHalVirtualDisplays(bool enable) { mFlinger->enableHalVirtualDisplays(enable); }
308 
setupNewDisplayDeviceInternal(const wp<IBinder> & displayToken,std::shared_ptr<compositionengine::Display> compositionDisplay,const DisplayDeviceState & state,const sp<compositionengine::DisplaySurface> & dispSurface,const sp<IGraphicBufferProducer> & producer)309     auto setupNewDisplayDeviceInternal(
310             const wp<IBinder>& displayToken,
311             std::shared_ptr<compositionengine::Display> compositionDisplay,
312             const DisplayDeviceState& state,
313             const sp<compositionengine::DisplaySurface>& dispSurface,
314             const sp<IGraphicBufferProducer>& producer) NO_THREAD_SAFETY_ANALYSIS {
315         return mFlinger->setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
316                                                        dispSurface, producer);
317     }
318 
handleTransactionLocked(uint32_t transactionFlags)319     auto handleTransactionLocked(uint32_t transactionFlags) {
320         Mutex::Autolock _l(mFlinger->mStateLock);
321         return mFlinger->handleTransactionLocked(transactionFlags);
322     }
323 
onComposerHalHotplug(hal::HWDisplayId hwcDisplayId,hal::Connection connection)324     void onComposerHalHotplug(hal::HWDisplayId hwcDisplayId, hal::Connection connection) {
325         mFlinger->onComposerHalHotplug(hwcDisplayId, connection);
326     }
327 
setDisplayStateLocked(const DisplayState & s)328     auto setDisplayStateLocked(const DisplayState& s) {
329         Mutex::Autolock _l(mFlinger->mStateLock);
330         return mFlinger->setDisplayStateLocked(s);
331     }
332 
333     // Allow reading display state without locking, as if called on the SF main thread.
onInitializeDisplays()334     auto onInitializeDisplays() NO_THREAD_SAFETY_ANALYSIS {
335         return mFlinger->onInitializeDisplays();
336     }
337 
notifyPowerBoost(int32_t boostId)338     auto notifyPowerBoost(int32_t boostId) { return mFlinger->notifyPowerBoost(boostId); }
339 
340     // Allow reading display state without locking, as if called on the SF main thread.
setPowerModeInternal(const sp<DisplayDevice> & display,hal::PowerMode mode)341     auto setPowerModeInternal(const sp<DisplayDevice>& display,
342                               hal::PowerMode mode) NO_THREAD_SAFETY_ANALYSIS {
343         return mFlinger->setPowerModeInternal(display, mode);
344     }
345 
onMessageReceived(int32_t what)346     auto onMessageReceived(int32_t what) {
347         return mFlinger->onMessageReceived(what, /*vsyncId=*/0, systemTime());
348     }
349 
renderScreenImplLocked(const RenderArea & renderArea,SurfaceFlinger::TraverseLayersFunction traverseLayers,const std::shared_ptr<renderengine::ExternalTexture> & buffer,bool forSystem,bool regionSampling)350     auto renderScreenImplLocked(const RenderArea& renderArea,
351                                 SurfaceFlinger::TraverseLayersFunction traverseLayers,
352                                 const std::shared_ptr<renderengine::ExternalTexture>& buffer,
353                                 bool forSystem, bool regionSampling) {
354         ScreenCaptureResults captureResults;
355         return mFlinger->renderScreenImplLocked(renderArea, traverseLayers, buffer, forSystem,
356                                                 regionSampling, false /* grayscale */,
357                                                 captureResults);
358     }
359 
traverseLayersInLayerStack(ui::LayerStack layerStack,int32_t uid,const LayerVector::Visitor & visitor)360     auto traverseLayersInLayerStack(ui::LayerStack layerStack, int32_t uid,
361                                     const LayerVector::Visitor& visitor) {
362         return mFlinger->SurfaceFlinger::traverseLayersInLayerStack(layerStack, uid, visitor);
363     }
364 
getDisplayNativePrimaries(const sp<IBinder> & displayToken,ui::DisplayPrimaries & primaries)365     auto getDisplayNativePrimaries(const sp<IBinder>& displayToken,
366                                    ui::DisplayPrimaries &primaries) {
367         return mFlinger->SurfaceFlinger::getDisplayNativePrimaries(displayToken, primaries);
368     }
369 
getTransactionQueue()370     auto& getTransactionQueue() { return mFlinger->mTransactionQueue; }
getPendingTransactionQueue()371     auto& getPendingTransactionQueue() { return mFlinger->mPendingTransactionQueues; }
372 
setTransactionState(const FrameTimelineInfo & frameTimelineInfo,const Vector<ComposerState> & states,const Vector<DisplayState> & displays,uint32_t flags,const sp<IBinder> & applyToken,const InputWindowCommands & inputWindowCommands,int64_t desiredPresentTime,bool isAutoTimestamp,const client_cache_t & uncacheBuffer,bool hasListenerCallbacks,std::vector<ListenerCallbacks> & listenerCallbacks,uint64_t transactionId)373     auto setTransactionState(
374             const FrameTimelineInfo& frameTimelineInfo, const Vector<ComposerState>& states,
375             const Vector<DisplayState>& displays, uint32_t flags, const sp<IBinder>& applyToken,
376             const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime,
377             bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
378             std::vector<ListenerCallbacks>& listenerCallbacks, uint64_t transactionId) {
379         return mFlinger->setTransactionState(frameTimelineInfo, states, displays, flags, applyToken,
380                                              inputWindowCommands, desiredPresentTime,
381                                              isAutoTimestamp, uncacheBuffer, hasListenerCallbacks,
382                                              listenerCallbacks, transactionId);
383     }
384 
flushTransactionQueues()385     auto flushTransactionQueues() { return mFlinger->flushTransactionQueues(); };
386 
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)387     auto onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
388         return mFlinger->onTransact(code, data, reply, flags);
389     }
390 
getGPUContextPriority()391     auto getGPUContextPriority() { return mFlinger->getGPUContextPriority(); }
392 
calculateMaxAcquiredBufferCount(Fps refreshRate,std::chrono::nanoseconds presentLatency)393     auto calculateMaxAcquiredBufferCount(Fps refreshRate,
394                                          std::chrono::nanoseconds presentLatency) const {
395         return SurfaceFlinger::calculateMaxAcquiredBufferCount(refreshRate, presentLatency);
396     }
397 
398     /* ------------------------------------------------------------------------
399      * Read-only access to private data to assert post-conditions.
400      */
401 
getAnimFrameTracker()402     const auto& getAnimFrameTracker() const { return mFlinger->mAnimFrameTracker; }
getHasPoweredOff()403     const auto& getHasPoweredOff() const { return mFlinger->mHasPoweredOff; }
getVisibleRegionsDirty()404     const auto& getVisibleRegionsDirty() const { return mFlinger->mVisibleRegionsDirty; }
getHwComposer()405     auto& getHwComposer() const {
406         return static_cast<impl::HWComposer&>(mFlinger->getHwComposer());
407     }
getCompositionEngine()408     auto& getCompositionEngine() const { return mFlinger->getCompositionEngine(); }
409 
getCompositorTiming()410     const auto& getCompositorTiming() const { return mFlinger->getBE().mCompositorTiming; }
411 
getFrameTracer()412     mock::FrameTracer* getFrameTracer() const {
413         return static_cast<mock::FrameTracer*>(mFlinger->mFrameTracer.get());
414     }
415 
416     /* ------------------------------------------------------------------------
417      * Read-write access to private data to set up preconditions and assert
418      * post-conditions.
419      */
420 
mutableHasWideColorDisplay()421     auto& mutableHasWideColorDisplay() { return SurfaceFlinger::hasWideColorDisplay; }
mutableUseColorManagement()422     auto& mutableUseColorManagement() { return SurfaceFlinger::useColorManagement; }
423 
mutableCurrentState()424     auto& mutableCurrentState() { return mFlinger->mCurrentState; }
mutableDisplayColorSetting()425     auto& mutableDisplayColorSetting() { return mFlinger->mDisplayColorSetting; }
mutableDisplays()426     auto& mutableDisplays() { return mFlinger->mDisplays; }
mutableDrawingState()427     auto& mutableDrawingState() { return mFlinger->mDrawingState; }
mutableEventQueue()428     auto& mutableEventQueue() { return mFlinger->mEventQueue; }
mutableGeometryInvalid()429     auto& mutableGeometryInvalid() { return mFlinger->mGeometryInvalid; }
mutableInterceptor()430     auto& mutableInterceptor() { return mFlinger->mInterceptor; }
mutableMainThreadId()431     auto& mutableMainThreadId() { return mFlinger->mMainThreadId; }
mutablePendingHotplugEvents()432     auto& mutablePendingHotplugEvents() { return mFlinger->mPendingHotplugEvents; }
mutablePhysicalDisplayTokens()433     auto& mutablePhysicalDisplayTokens() { return mFlinger->mPhysicalDisplayTokens; }
mutableTexturePool()434     auto& mutableTexturePool() { return mFlinger->mTexturePool; }
mutableTransactionFlags()435     auto& mutableTransactionFlags() { return mFlinger->mTransactionFlags; }
mutablePowerAdvisor()436     auto& mutablePowerAdvisor() { return mFlinger->mPowerAdvisor; }
mutableDebugDisableHWC()437     auto& mutableDebugDisableHWC() { return mFlinger->mDebugDisableHWC; }
438 
mutableHwcDisplayData()439     auto& mutableHwcDisplayData() { return getHwComposer().mDisplayData; }
mutableHwcPhysicalDisplayIdMap()440     auto& mutableHwcPhysicalDisplayIdMap() { return getHwComposer().mPhysicalDisplayIdMap; }
mutableInternalHwcDisplayId()441     auto& mutableInternalHwcDisplayId() { return getHwComposer().mInternalHwcDisplayId; }
mutableExternalHwcDisplayId()442     auto& mutableExternalHwcDisplayId() { return getHwComposer().mExternalHwcDisplayId; }
mutableUseFrameRateApi()443     auto& mutableUseFrameRateApi() { return mFlinger->useFrameRateApi; }
444 
fromHandle(const sp<IBinder> & handle)445     auto fromHandle(const sp<IBinder>& handle) {
446         return mFlinger->fromHandle(handle);
447     }
448 
~TestableSurfaceFlinger()449     ~TestableSurfaceFlinger() {
450         // All these pointer and container clears help ensure that GMock does
451         // not report a leaked object, since the SurfaceFlinger instance may
452         // still be referenced by something despite our best efforts to destroy
453         // it after each test is done.
454         mutableDisplays().clear();
455         mutableCurrentState().displays.clear();
456         mutableDrawingState().displays.clear();
457         mutableEventQueue().reset();
458         mutableInterceptor().clear();
459         mFlinger->mScheduler.reset();
460         mFlinger->mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
461         mFlinger->mCompositionEngine->setRenderEngine(
462                 std::unique_ptr<renderengine::RenderEngine>());
463     }
464 
465     /* ------------------------------------------------------------------------
466      * Wrapper classes for Read-write access to private data to set up
467      * preconditions and assert post-conditions.
468      */
469     struct HWC2Display : public HWC2::impl::Display {
HWC2DisplayHWC2Display470         HWC2Display(Hwc2::Composer& composer,
471                     const std::unordered_set<hal::Capability>& capabilities, hal::HWDisplayId id,
472                     hal::DisplayType type)
473               : HWC2::impl::Display(composer, capabilities, id, type) {}
~HWC2DisplayHWC2Display474         ~HWC2Display() {
475             // Prevents a call to disable vsyncs.
476             mType = hal::DisplayType::INVALID;
477         }
478 
mutableIsConnectedHWC2Display479         auto& mutableIsConnected() { return this->mIsConnected; }
mutableLayersHWC2Display480         auto& mutableLayers() { return this->mLayers; }
481     };
482 
483     class FakeHwcDisplayInjector {
484     public:
485         static constexpr hal::HWDisplayId DEFAULT_HWC_DISPLAY_ID = 1000;
486         static constexpr int32_t DEFAULT_WIDTH = 1920;
487         static constexpr int32_t DEFAULT_HEIGHT = 1280;
488         static constexpr int32_t DEFAULT_VSYNC_PERIOD = 16'666'666;
489         static constexpr int32_t DEFAULT_CONFIG_GROUP = 7;
490         static constexpr int32_t DEFAULT_DPI = 320;
491         static constexpr hal::HWConfigId DEFAULT_ACTIVE_CONFIG = 0;
492         static constexpr hal::PowerMode DEFAULT_POWER_MODE = hal::PowerMode::ON;
493 
FakeHwcDisplayInjector(HalDisplayId displayId,hal::DisplayType hwcDisplayType,bool isPrimary)494         FakeHwcDisplayInjector(HalDisplayId displayId, hal::DisplayType hwcDisplayType,
495                                bool isPrimary)
496               : mDisplayId(displayId), mHwcDisplayType(hwcDisplayType), mIsPrimary(isPrimary) {}
497 
setHwcDisplayId(hal::HWDisplayId displayId)498         auto& setHwcDisplayId(hal::HWDisplayId displayId) {
499             mHwcDisplayId = displayId;
500             return *this;
501         }
502 
setWidth(int32_t width)503         auto& setWidth(int32_t width) {
504             mWidth = width;
505             return *this;
506         }
507 
setHeight(int32_t height)508         auto& setHeight(int32_t height) {
509             mHeight = height;
510             return *this;
511         }
512 
setVsyncPeriod(int32_t vsyncPeriod)513         auto& setVsyncPeriod(int32_t vsyncPeriod) {
514             mVsyncPeriod = vsyncPeriod;
515             return *this;
516         }
517 
setDpiX(int32_t dpi)518         auto& setDpiX(int32_t dpi) {
519             mDpiX = dpi;
520             return *this;
521         }
522 
setDpiY(int32_t dpi)523         auto& setDpiY(int32_t dpi) {
524             mDpiY = dpi;
525             return *this;
526         }
527 
setActiveConfig(hal::HWConfigId config)528         auto& setActiveConfig(hal::HWConfigId config) {
529             mActiveConfig = config;
530             return *this;
531         }
532 
setCapabilities(const std::unordered_set<hal::Capability> * capabilities)533         auto& setCapabilities(const std::unordered_set<hal::Capability>* capabilities) {
534             mCapabilities = capabilities;
535             return *this;
536         }
537 
setPowerMode(hal::PowerMode mode)538         auto& setPowerMode(hal::PowerMode mode) {
539             mPowerMode = mode;
540             return *this;
541         }
542 
inject(TestableSurfaceFlinger * flinger,Hwc2::mock::Composer * composer)543         void inject(TestableSurfaceFlinger* flinger, Hwc2::mock::Composer* composer) {
544             using ::testing::_;
545             using ::testing::DoAll;
546             using ::testing::Return;
547             using ::testing::SetArgPointee;
548 
549             static const std::unordered_set<hal::Capability> defaultCapabilities;
550             if (mCapabilities == nullptr) mCapabilities = &defaultCapabilities;
551 
552             // Caution - Make sure that any values passed by reference here do
553             // not refer to an instance owned by FakeHwcDisplayInjector. This
554             // class has temporary lifetime, while the constructed HWC2::Display
555             // is much longer lived.
556             auto display = std::make_unique<HWC2Display>(*composer, *mCapabilities, mHwcDisplayId,
557                                                          mHwcDisplayType);
558 
559             display->mutableIsConnected() = true;
560             display->setPowerMode(mPowerMode);
561             flinger->mutableHwcDisplayData()[mDisplayId].hwcDisplay = std::move(display);
562 
563             EXPECT_CALL(*composer, getDisplayConfigs(mHwcDisplayId, _))
564                     .WillRepeatedly(
565                             DoAll(SetArgPointee<1>(std::vector<hal::HWConfigId>{mActiveConfig}),
566                                   Return(hal::Error::NONE)));
567 
568             EXPECT_CALL(*composer,
569                         getDisplayAttribute(mHwcDisplayId, mActiveConfig, hal::Attribute::WIDTH, _))
570                     .WillRepeatedly(DoAll(SetArgPointee<3>(mWidth), Return(hal::Error::NONE)));
571 
572             EXPECT_CALL(*composer,
573                         getDisplayAttribute(mHwcDisplayId, mActiveConfig, hal::Attribute::HEIGHT,
574                                             _))
575                     .WillRepeatedly(DoAll(SetArgPointee<3>(mHeight), Return(hal::Error::NONE)));
576 
577             EXPECT_CALL(*composer,
578                         getDisplayAttribute(mHwcDisplayId, mActiveConfig,
579                                             hal::Attribute::VSYNC_PERIOD, _))
580                     .WillRepeatedly(
581                             DoAll(SetArgPointee<3>(mVsyncPeriod), Return(hal::Error::NONE)));
582 
583             EXPECT_CALL(*composer,
584                         getDisplayAttribute(mHwcDisplayId, mActiveConfig, hal::Attribute::DPI_X, _))
585                     .WillRepeatedly(DoAll(SetArgPointee<3>(mDpiX), Return(hal::Error::NONE)));
586 
587             EXPECT_CALL(*composer,
588                         getDisplayAttribute(mHwcDisplayId, mActiveConfig, hal::Attribute::DPI_Y, _))
589                     .WillRepeatedly(DoAll(SetArgPointee<3>(mDpiY), Return(hal::Error::NONE)));
590 
591             EXPECT_CALL(*composer,
592                         getDisplayAttribute(mHwcDisplayId, mActiveConfig,
593                                             hal::Attribute::CONFIG_GROUP, _))
594                     .WillRepeatedly(
595                             DoAll(SetArgPointee<3>(mConfigGroup), Return(hal::Error::NONE)));
596 
597             if (mHwcDisplayType == hal::DisplayType::PHYSICAL) {
598                 const auto physicalId = PhysicalDisplayId::tryCast(mDisplayId);
599                 LOG_ALWAYS_FATAL_IF(!physicalId);
600                 flinger->mutableHwcPhysicalDisplayIdMap().emplace(mHwcDisplayId, *physicalId);
601                 if (mIsPrimary) {
602                     flinger->mutableInternalHwcDisplayId() = mHwcDisplayId;
603                 } else {
604                     // If there is an external HWC display there should always be an internal ID
605                     // as well. Set it to some arbitrary value.
606                     auto& internalId = flinger->mutableInternalHwcDisplayId();
607                     if (!internalId) internalId = mHwcDisplayId - 1;
608                     flinger->mutableExternalHwcDisplayId() = mHwcDisplayId;
609                 }
610             }
611         }
612 
613     private:
614         const HalDisplayId mDisplayId;
615         const hal::DisplayType mHwcDisplayType;
616         const bool mIsPrimary;
617 
618         hal::HWDisplayId mHwcDisplayId = DEFAULT_HWC_DISPLAY_ID;
619         int32_t mWidth = DEFAULT_WIDTH;
620         int32_t mHeight = DEFAULT_HEIGHT;
621         int32_t mVsyncPeriod = DEFAULT_VSYNC_PERIOD;
622         int32_t mDpiX = DEFAULT_DPI;
623         int32_t mDpiY = DEFAULT_DPI;
624         int32_t mConfigGroup = DEFAULT_CONFIG_GROUP;
625         hal::HWConfigId mActiveConfig = DEFAULT_ACTIVE_CONFIG;
626         hal::PowerMode mPowerMode = DEFAULT_POWER_MODE;
627         const std::unordered_set<hal::Capability>* mCapabilities = nullptr;
628     };
629 
630     class FakeDisplayDeviceInjector {
631     public:
FakeDisplayDeviceInjector(TestableSurfaceFlinger & flinger,std::shared_ptr<compositionengine::Display> compositionDisplay,std::optional<ui::DisplayConnectionType> connectionType,std::optional<hal::HWDisplayId> hwcDisplayId,bool isPrimary)632         FakeDisplayDeviceInjector(TestableSurfaceFlinger& flinger,
633                                   std::shared_ptr<compositionengine::Display> compositionDisplay,
634                                   std::optional<ui::DisplayConnectionType> connectionType,
635                                   std::optional<hal::HWDisplayId> hwcDisplayId, bool isPrimary)
636               : mFlinger(flinger),
637                 mCreationArgs(flinger.mFlinger.get(), flinger.mFlinger->getHwComposer(),
638                               mDisplayToken, compositionDisplay),
639                 mHwcDisplayId(hwcDisplayId) {
640             mCreationArgs.connectionType = connectionType;
641             mCreationArgs.isPrimary = isPrimary;
642 
643             mActiveModeId = DisplayModeId(0);
644             DisplayModePtr activeMode =
645                     DisplayMode::Builder(FakeHwcDisplayInjector::DEFAULT_ACTIVE_CONFIG)
646                             .setId(mActiveModeId)
647                             .setWidth(FakeHwcDisplayInjector::DEFAULT_WIDTH)
648                             .setHeight(FakeHwcDisplayInjector::DEFAULT_HEIGHT)
649                             .setVsyncPeriod(FakeHwcDisplayInjector::DEFAULT_VSYNC_PERIOD)
650                             .setDpiX(FakeHwcDisplayInjector::DEFAULT_DPI)
651                             .setDpiY(FakeHwcDisplayInjector::DEFAULT_DPI)
652                             .setGroup(0)
653                             .build();
654 
655             DisplayModes modes{activeMode};
656             mCreationArgs.supportedModes = modes;
657         }
658 
token()659         sp<IBinder> token() const { return mDisplayToken; }
660 
mutableDrawingDisplayState()661         DisplayDeviceState& mutableDrawingDisplayState() {
662             return mFlinger.mutableDrawingState().displays.editValueFor(mDisplayToken);
663         }
664 
mutableCurrentDisplayState()665         DisplayDeviceState& mutableCurrentDisplayState() {
666             return mFlinger.mutableCurrentState().displays.editValueFor(mDisplayToken);
667         }
668 
getDrawingDisplayState()669         const auto& getDrawingDisplayState() {
670             return mFlinger.mutableDrawingState().displays.valueFor(mDisplayToken);
671         }
672 
getCurrentDisplayState()673         const auto& getCurrentDisplayState() {
674             return mFlinger.mutableCurrentState().displays.valueFor(mDisplayToken);
675         }
676 
mutableDisplayDevice()677         auto& mutableDisplayDevice() { return mFlinger.mutableDisplays()[mDisplayToken]; }
678 
setActiveMode(DisplayModeId mode)679         auto& setActiveMode(DisplayModeId mode) {
680             mActiveModeId = mode;
681             return *this;
682         }
683 
setSupportedModes(DisplayModes mode)684         auto& setSupportedModes(DisplayModes mode) {
685             mCreationArgs.supportedModes = mode;
686             return *this;
687         }
688 
setNativeWindow(const sp<ANativeWindow> & nativeWindow)689         auto& setNativeWindow(const sp<ANativeWindow>& nativeWindow) {
690             mCreationArgs.nativeWindow = nativeWindow;
691             return *this;
692         }
693 
setDisplaySurface(const sp<compositionengine::DisplaySurface> & displaySurface)694         auto& setDisplaySurface(const sp<compositionengine::DisplaySurface>& displaySurface) {
695             mCreationArgs.displaySurface = displaySurface;
696             return *this;
697         }
698 
setSecure(bool secure)699         auto& setSecure(bool secure) {
700             mCreationArgs.isSecure = secure;
701             return *this;
702         }
703 
setPowerMode(hal::PowerMode mode)704         auto& setPowerMode(hal::PowerMode mode) {
705             mCreationArgs.initialPowerMode = mode;
706             return *this;
707         }
708 
setHwcColorModes(const std::unordered_map<ui::ColorMode,std::vector<ui::RenderIntent>> hwcColorModes)709         auto& setHwcColorModes(
710                 const std::unordered_map<ui::ColorMode, std::vector<ui::RenderIntent>>
711                         hwcColorModes) {
712             mCreationArgs.hwcColorModes = hwcColorModes;
713             return *this;
714         }
715 
setHasWideColorGamut(bool hasWideColorGamut)716         auto& setHasWideColorGamut(bool hasWideColorGamut) {
717             mCreationArgs.hasWideColorGamut = hasWideColorGamut;
718             return *this;
719         }
720 
setPhysicalOrientation(ui::Rotation orientation)721         auto& setPhysicalOrientation(ui::Rotation orientation) {
722             mCreationArgs.physicalOrientation = orientation;
723             return *this;
724         }
725 
inject()726         sp<DisplayDevice> inject() {
727             const auto displayId = mCreationArgs.compositionDisplay->getDisplayId();
728 
729             DisplayDeviceState state;
730             if (const auto type = mCreationArgs.connectionType) {
731                 LOG_ALWAYS_FATAL_IF(!displayId);
732                 const auto physicalId = PhysicalDisplayId::tryCast(*displayId);
733                 LOG_ALWAYS_FATAL_IF(!physicalId);
734                 LOG_ALWAYS_FATAL_IF(!mHwcDisplayId);
735                 state.physical = {.id = *physicalId, .type = *type, .hwcDisplayId = *mHwcDisplayId};
736             }
737 
738             state.isSecure = mCreationArgs.isSecure;
739 
740             sp<DisplayDevice> device = new DisplayDevice(mCreationArgs);
741             if (!device->isVirtual()) {
742                 device->setActiveMode(mActiveModeId);
743             }
744             mFlinger.mutableDisplays().emplace(mDisplayToken, device);
745             mFlinger.mutableCurrentState().displays.add(mDisplayToken, state);
746             mFlinger.mutableDrawingState().displays.add(mDisplayToken, state);
747 
748             if (const auto& physical = state.physical) {
749                 mFlinger.mutablePhysicalDisplayTokens()[physical->id] = mDisplayToken;
750             }
751 
752             return device;
753         }
754 
755     private:
756         TestableSurfaceFlinger& mFlinger;
757         sp<BBinder> mDisplayToken = new BBinder();
758         DisplayDeviceCreationArgs mCreationArgs;
759         const std::optional<hal::HWDisplayId> mHwcDisplayId;
760         DisplayModeId mActiveModeId;
761     };
762 
763 private:
setVsyncEnabled(bool)764     void setVsyncEnabled(bool) override {}
changeRefreshRate(const Scheduler::RefreshRate &,Scheduler::ModeEvent)765     void changeRefreshRate(const Scheduler::RefreshRate&, Scheduler::ModeEvent) override {}
repaintEverythingForHWC()766     void repaintEverythingForHWC() override {}
kernelTimerChanged(bool)767     void kernelTimerChanged(bool) override {}
triggerOnFrameRateOverridesChanged()768     void triggerOnFrameRateOverridesChanged() {}
769 
770     surfaceflinger::test::Factory mFactory;
771     sp<SurfaceFlinger> mFlinger = new SurfaceFlinger(mFactory, SurfaceFlinger::SkipInitialization);
772     TestableScheduler* mScheduler = nullptr;
773 };
774 
775 } // namespace android
776