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 <algorithm>
20 #include <chrono>
21 #include <memory>
22 #include <variant>
23 
24 #include <ftl/fake_guard.h>
25 #include <ftl/match.h>
26 #include <gui/LayerMetadata.h>
27 #include <gui/ScreenCaptureResults.h>
28 #include <ui/DynamicDisplayInfo.h>
29 
30 #include <compositionengine/Display.h>
31 #include <compositionengine/LayerFECompositionState.h>
32 #include <compositionengine/OutputLayer.h>
33 #include <compositionengine/impl/CompositionEngine.h>
34 #include <compositionengine/impl/Display.h>
35 #include <compositionengine/impl/OutputLayerCompositionState.h>
36 #include <compositionengine/mock/DisplaySurface.h>
37 
38 #include "DisplayDevice.h"
39 #include "FakeVsyncConfiguration.h"
40 #include "FrameTracer/FrameTracer.h"
41 #include "FrontEnd/LayerCreationArgs.h"
42 #include "FrontEnd/LayerHandle.h"
43 #include "FrontEnd/RequestedLayerState.h"
44 #include "Layer.h"
45 #include "NativeWindowSurface.h"
46 #include "RenderArea.h"
47 #include "Scheduler/MessageQueue.h"
48 #include "Scheduler/RefreshRateSelector.h"
49 #include "SurfaceFlinger.h"
50 #include "TestableScheduler.h"
51 #include "android/gui/ISurfaceComposerClient.h"
52 #include "mock/DisplayHardware/MockComposer.h"
53 #include "mock/DisplayHardware/MockDisplayMode.h"
54 #include "mock/DisplayHardware/MockPowerAdvisor.h"
55 #include "mock/MockEventThread.h"
56 #include "mock/MockFrameTimeline.h"
57 #include "mock/MockFrameTracer.h"
58 #include "mock/MockSchedulerCallback.h"
59 #include "mock/system/window/MockNativeWindow.h"
60 
61 #include "Scheduler/VSyncTracker.h"
62 #include "Scheduler/VsyncController.h"
63 #include "mock/MockVSyncDispatch.h"
64 #include "mock/MockVSyncTracker.h"
65 #include "mock/MockVsyncController.h"
66 
67 namespace android {
68 
69 struct DisplayStatInfo;
70 
71 namespace renderengine {
72 
73 class RenderEngine;
74 
75 } // namespace renderengine
76 
77 namespace Hwc2 {
78 
79 class Composer;
80 
81 } // namespace Hwc2
82 
83 namespace hal = android::hardware::graphics::composer::hal;
84 
85 namespace surfaceflinger::test {
86 
87 class Factory final : public surfaceflinger::Factory {
88 public:
89     ~Factory() = default;
90 
createHWComposer(const std::string &)91     std::unique_ptr<HWComposer> createHWComposer(const std::string&) override {
92         return nullptr;
93     }
94 
createVsyncConfiguration(Fps)95     std::unique_ptr<scheduler::VsyncConfiguration> createVsyncConfiguration(
96             Fps /*currentRefreshRate*/) override {
97         return std::make_unique<scheduler::FakePhaseOffsets>();
98     }
99 
createDisplayDevice(DisplayDeviceCreationArgs & creationArgs)100     sp<DisplayDevice> createDisplayDevice(DisplayDeviceCreationArgs& creationArgs) override {
101         return sp<DisplayDevice>::make(creationArgs);
102     }
103 
createGraphicBuffer(uint32_t width,uint32_t height,PixelFormat format,uint32_t layerCount,uint64_t usage,std::string requestorName)104     sp<GraphicBuffer> createGraphicBuffer(uint32_t width, uint32_t height, PixelFormat format,
105                                           uint32_t layerCount, uint64_t usage,
106                                           std::string requestorName) override {
107         return sp<GraphicBuffer>::make(width, height, format, layerCount, usage, requestorName);
108     }
109 
createBufferQueue(sp<IGraphicBufferProducer> * outProducer,sp<IGraphicBufferConsumer> * outConsumer,bool consumerIsSurfaceFlinger)110     void createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
111                            sp<IGraphicBufferConsumer>* outConsumer,
112                            bool consumerIsSurfaceFlinger) override {
113         if (!mCreateBufferQueue) {
114             BufferQueue::createBufferQueue(outProducer, outConsumer, consumerIsSurfaceFlinger);
115             return;
116         }
117         mCreateBufferQueue(outProducer, outConsumer, consumerIsSurfaceFlinger);
118     }
119 
createNativeWindowSurface(const sp<IGraphicBufferProducer> & producer)120     std::unique_ptr<surfaceflinger::NativeWindowSurface> createNativeWindowSurface(
121             const sp<IGraphicBufferProducer>& producer) override {
122         if (!mCreateNativeWindowSurface) return nullptr;
123         return mCreateNativeWindowSurface(producer);
124     }
125 
createCompositionEngine()126     std::unique_ptr<compositionengine::CompositionEngine> createCompositionEngine() override {
127         return compositionengine::impl::createCompositionEngine();
128     }
129 
createBufferStateLayer(const LayerCreationArgs &)130     sp<Layer> createBufferStateLayer(const LayerCreationArgs&) override { return nullptr; }
131 
createEffectLayer(const LayerCreationArgs &)132     sp<Layer> createEffectLayer(const LayerCreationArgs&) override { return nullptr; }
133 
createLayerFE(const std::string & layerName,const Layer *)134     sp<LayerFE> createLayerFE(const std::string& layerName, const Layer* /* owner */) override {
135         return sp<LayerFE>::make(layerName);
136     }
137 
createFrameTracer()138     std::unique_ptr<FrameTracer> createFrameTracer() override {
139         return std::make_unique<mock::FrameTracer>();
140     }
141 
142     std::unique_ptr<frametimeline::FrameTimeline> createFrameTimeline(
143             std::shared_ptr<TimeStats> timeStats, pid_t surfaceFlingerPid = 0) override {
144         return std::make_unique<mock::FrameTimeline>(timeStats, surfaceFlingerPid);
145     }
146 
147     using CreateBufferQueueFunction =
148             std::function<void(sp<IGraphicBufferProducer>* /* outProducer */,
149                                sp<IGraphicBufferConsumer>* /* outConsumer */,
150                                bool /* consumerIsSurfaceFlinger */)>;
151     CreateBufferQueueFunction mCreateBufferQueue;
152 
153     using CreateNativeWindowSurfaceFunction =
154             std::function<std::unique_ptr<surfaceflinger::NativeWindowSurface>(
155                     const sp<IGraphicBufferProducer>&)>;
156     CreateNativeWindowSurfaceFunction mCreateNativeWindowSurface;
157 
158     using CreateCompositionEngineFunction =
159             std::function<std::unique_ptr<compositionengine::CompositionEngine>()>;
160     CreateCompositionEngineFunction mCreateCompositionEngine;
161 };
162 
163 struct MockSchedulerOptions {
164     PhysicalDisplayId displayId = PhysicalDisplayId::fromPort(0);
165     bool useNiceMock = false;
166 };
167 
168 } // namespace surfaceflinger::test
169 
170 class TestableSurfaceFlinger {
171 public:
172     using HotplugEvent = SurfaceFlinger::HotplugEvent;
173 
mFlinger(flinger)174     TestableSurfaceFlinger(sp<SurfaceFlinger> flinger = nullptr) : mFlinger(flinger) {
175         if (!mFlinger) {
176             mFlinger = sp<SurfaceFlinger>::make(mFactory, SurfaceFlinger::SkipInitialization);
177         }
178     }
179 
flinger()180     SurfaceFlinger* flinger() { return mFlinger.get(); }
scheduler()181     scheduler::TestableScheduler* scheduler() { return mScheduler; }
182 
183     // Extend this as needed for accessing SurfaceFlinger private (and public)
184     // functions.
185 
setupRenderEngine(std::unique_ptr<renderengine::RenderEngine> renderEngine)186     void setupRenderEngine(std::unique_ptr<renderengine::RenderEngine> renderEngine) {
187         mFlinger->mRenderEngine = std::move(renderEngine);
188         mFlinger->mCompositionEngine->setRenderEngine(mFlinger->mRenderEngine.get());
189     }
190 
setupComposer(std::unique_ptr<Hwc2::Composer> composer)191     void setupComposer(std::unique_ptr<Hwc2::Composer> composer) {
192         mFlinger->mCompositionEngine->setHwComposer(
193                 std::make_unique<impl::HWComposer>(std::move(composer)));
194         mFlinger->mDisplayModeController.setHwComposer(
195                 &mFlinger->mCompositionEngine->getHwComposer());
196     }
197 
setupPowerAdvisor(std::unique_ptr<Hwc2::PowerAdvisor> powerAdvisor)198     void setupPowerAdvisor(std::unique_ptr<Hwc2::PowerAdvisor> powerAdvisor) {
199         mFlinger->mPowerAdvisor = std::move(powerAdvisor);
200     }
201 
setupTimeStats(const std::shared_ptr<TimeStats> & timeStats)202     void setupTimeStats(const std::shared_ptr<TimeStats>& timeStats) {
203         mFlinger->mCompositionEngine->setTimeStats(timeStats);
204     }
205 
setupCompositionEngine(std::unique_ptr<compositionengine::CompositionEngine> compositionEngine)206     void setupCompositionEngine(
207             std::unique_ptr<compositionengine::CompositionEngine> compositionEngine) {
208         mFlinger->mCompositionEngine = std::move(compositionEngine);
209     }
210 
211     enum class SchedulerCallbackImpl { kNoOp, kMock };
212 
213     struct DefaultDisplayMode {
214         // The ID of the injected RefreshRateSelector and its default display mode.
215         PhysicalDisplayId displayId;
216     };
217 
218     using RefreshRateSelectorPtr = scheduler::Scheduler::RefreshRateSelectorPtr;
219 
220     using DisplayModesVariant = std::variant<DefaultDisplayMode, RefreshRateSelectorPtr>;
221 
getFactory()222     surfaceflinger::Factory& getFactory() { return mFactory; }
223 
getTimeStats()224     TimeStats& getTimeStats() { return *mFlinger->mTimeStats; }
225 
226     void setupScheduler(std::unique_ptr<scheduler::VsyncController> vsyncController,
227                         std::shared_ptr<scheduler::VSyncTracker> vsyncTracker,
228                         std::unique_ptr<EventThread> appEventThread,
229                         std::unique_ptr<EventThread> sfEventThread,
230                         DisplayModesVariant modesVariant,
231                         SchedulerCallbackImpl callbackImpl = SchedulerCallbackImpl::kNoOp,
232                         bool useNiceMock = false) {
233         RefreshRateSelectorPtr selectorPtr = ftl::match(
234                 modesVariant,
235                 [](DefaultDisplayMode arg) {
236                     constexpr DisplayModeId kModeId60{0};
237                     return std::make_shared<scheduler::RefreshRateSelector>(
238                             makeModes(mock::createDisplayMode(arg.displayId, kModeId60, 60_Hz)),
239                             kModeId60);
240                 },
241                 [](RefreshRateSelectorPtr selectorPtr) { return selectorPtr; });
242 
243         mTokenManager = std::make_unique<frametimeline::impl::TokenManager>();
244 
245         using ISchedulerCallback = scheduler::ISchedulerCallback;
246         ISchedulerCallback& schedulerCallback = callbackImpl == SchedulerCallbackImpl::kNoOp
247                 ? static_cast<ISchedulerCallback&>(mNoOpSchedulerCallback)
248                 : static_cast<ISchedulerCallback&>(mSchedulerCallback);
249 
250         if (useNiceMock) {
251             mScheduler =
252                     new testing::NiceMock<scheduler::TestableScheduler>(std::move(vsyncController),
253                                                                         std::move(vsyncTracker),
254                                                                         std::move(selectorPtr),
255                                                                         mFactory,
256                                                                         *mFlinger->mTimeStats,
257                                                                         schedulerCallback);
258         } else {
259             mScheduler = new scheduler::TestableScheduler(std::move(vsyncController),
260                                                           std::move(vsyncTracker),
261                                                           std::move(selectorPtr), mFactory,
262                                                           *mFlinger->mTimeStats, schedulerCallback);
263         }
264 
265         mScheduler->initVsync(*mTokenManager, 0ms);
266 
267         mScheduler->setEventThread(scheduler::Cycle::Render, std::move(appEventThread));
268         mScheduler->setEventThread(scheduler::Cycle::LastComposite, std::move(sfEventThread));
269 
270         resetScheduler(mScheduler);
271     }
272 
273     void setupMockScheduler(surfaceflinger::test::MockSchedulerOptions options = {}) {
274         using testing::_;
275         using testing::Return;
276 
277         auto eventThread = makeMock<mock::EventThread>(options.useNiceMock);
278         auto sfEventThread = makeMock<mock::EventThread>(options.useNiceMock);
279 
280         EXPECT_CALL(*eventThread, registerDisplayEventConnection(_));
281         EXPECT_CALL(*eventThread, createEventConnection(_, _))
282                 .WillOnce(Return(sp<EventThreadConnection>::make(eventThread.get(),
283                                                                  mock::EventThread::kCallingUid)));
284 
285         EXPECT_CALL(*sfEventThread, registerDisplayEventConnection(_));
286         EXPECT_CALL(*sfEventThread, createEventConnection(_, _))
287                 .WillOnce(Return(sp<EventThreadConnection>::make(sfEventThread.get(),
288                                                                  mock::EventThread::kCallingUid)));
289 
290         auto vsyncController = makeMock<mock::VsyncController>(options.useNiceMock);
291         auto vsyncTracker = makeSharedMock<mock::VSyncTracker>(options.useNiceMock);
292 
293         EXPECT_CALL(*vsyncTracker, nextAnticipatedVSyncTimeFrom(_, _)).WillRepeatedly(Return(0));
294         EXPECT_CALL(*vsyncTracker, currentPeriod())
295                 .WillRepeatedly(Return(FakeHwcDisplayInjector::DEFAULT_VSYNC_PERIOD));
296         EXPECT_CALL(*vsyncTracker, minFramePeriod())
297                 .WillRepeatedly(
298                         Return(Period::fromNs(FakeHwcDisplayInjector::DEFAULT_VSYNC_PERIOD)));
299         EXPECT_CALL(*vsyncTracker, nextAnticipatedVSyncTimeFrom(_, _)).WillRepeatedly(Return(0));
300         setupScheduler(std::move(vsyncController), std::move(vsyncTracker), std::move(eventThread),
301                        std::move(sfEventThread), DefaultDisplayMode{options.displayId},
302                        SchedulerCallbackImpl::kNoOp, options.useNiceMock);
303     }
304 
resetScheduler(scheduler::Scheduler * scheduler)305     void resetScheduler(scheduler::Scheduler* scheduler) { mFlinger->mScheduler.reset(scheduler); }
306 
mutableScheduler()307     scheduler::TestableScheduler& mutableScheduler() { return *mScheduler; }
mockSchedulerCallback()308     scheduler::mock::SchedulerCallback& mockSchedulerCallback() { return mSchedulerCallback; }
309 
310     using CreateBufferQueueFunction = surfaceflinger::test::Factory::CreateBufferQueueFunction;
setCreateBufferQueueFunction(CreateBufferQueueFunction f)311     void setCreateBufferQueueFunction(CreateBufferQueueFunction f) {
312         mFactory.mCreateBufferQueue = f;
313     }
314 
315     using CreateNativeWindowSurfaceFunction =
316             surfaceflinger::test::Factory::CreateNativeWindowSurfaceFunction;
setCreateNativeWindowSurface(CreateNativeWindowSurfaceFunction f)317     void setCreateNativeWindowSurface(CreateNativeWindowSurfaceFunction f) {
318         mFactory.mCreateNativeWindowSurface = f;
319     }
320 
setInternalDisplayPrimaries(const ui::DisplayPrimaries & primaries)321     void setInternalDisplayPrimaries(const ui::DisplayPrimaries& primaries) {
322         memcpy(&mFlinger->mInternalDisplayPrimaries, &primaries, sizeof(ui::DisplayPrimaries));
323     }
324 
mutableLayerDrawingState(const sp<Layer> & layer)325     static auto& mutableLayerDrawingState(const sp<Layer>& layer) { return layer->mDrawingState; }
326 
mutableStateLock()327     auto& mutableStateLock() { return mFlinger->mStateLock; }
328 
findOutputLayerForDisplay(const sp<Layer> & layer,const sp<const DisplayDevice> & display)329     static auto findOutputLayerForDisplay(const sp<Layer>& layer,
330                                           const sp<const DisplayDevice>& display) {
331         return layer->findOutputLayerForDisplay(display.get());
332     }
333 
setLayerSidebandStream(const sp<Layer> & layer,const sp<NativeHandle> & sidebandStream)334     static void setLayerSidebandStream(const sp<Layer>& layer,
335                                        const sp<NativeHandle>& sidebandStream) {
336         layer->mDrawingState.sidebandStream = sidebandStream;
337         layer->mSidebandStream = sidebandStream;
338         layer->editLayerSnapshot()->sidebandStream = sidebandStream;
339     }
340 
setLayerCompositionType(const sp<Layer> & layer,aidl::android::hardware::graphics::composer3::Composition type)341     void setLayerCompositionType(const sp<Layer>& layer,
342                                  aidl::android::hardware::graphics::composer3::Composition type) {
343         auto outputLayer = findOutputLayerForDisplay(layer, mFlinger->getDefaultDisplayDevice());
344         LOG_ALWAYS_FATAL_IF(!outputLayer);
345         auto& state = outputLayer->editState();
346         LOG_ALWAYS_FATAL_IF(!outputLayer->getState().hwc);
347         (*state.hwc).hwcCompositionType = type;
348     }
349 
setLayerPotentialCursor(const sp<Layer> & layer,bool potentialCursor)350     static void setLayerPotentialCursor(const sp<Layer>& layer, bool potentialCursor) {
351         layer->mPotentialCursor = potentialCursor;
352     }
353 
setLayerDrawingParent(const sp<Layer> & layer,const sp<Layer> & drawingParent)354     static void setLayerDrawingParent(const sp<Layer>& layer, const sp<Layer>& drawingParent) {
355         layer->mDrawingParent = drawingParent;
356     }
357 
358     /* ------------------------------------------------------------------------
359      * Forwarding for functions being tested
360      */
361 
configure()362     void configure() {
363         ftl::FakeGuard guard(kMainThreadContext);
364         mFlinger->configure();
365     }
366 
configureAndCommit()367     void configureAndCommit() {
368         configure();
369         commitTransactionsLocked(eDisplayTransactionNeeded);
370     }
371 
372     void commit(TimePoint frameTime, VsyncId vsyncId, TimePoint expectedVsyncTime,
373                 bool composite = false) {
374         ftl::FakeGuard guard(kMainThreadContext);
375 
376         const auto displayIdOpt = mScheduler->pacesetterDisplayId();
377         LOG_ALWAYS_FATAL_IF(!displayIdOpt);
378         const auto displayId = *displayIdOpt;
379 
380         scheduler::FrameTargeter frameTargeter(displayId,
381                                                scheduler::Feature::kBackpressureGpuComposition);
382 
383         frameTargeter.beginFrame({.frameBeginTime = frameTime,
384                                   .vsyncId = vsyncId,
385                                   .expectedVsyncTime = expectedVsyncTime,
386                                   .sfWorkDuration = 10ms,
387                                   .hwcMinWorkDuration = 10ms},
388                                  *mScheduler->getVsyncSchedule());
389 
390         scheduler::FrameTargets targets;
391         scheduler::FrameTargeters targeters;
392 
393         for (const auto& [id, display] :
394              FTL_FAKE_GUARD(mFlinger->mStateLock, mFlinger->mPhysicalDisplays)) {
395             targets.try_emplace(id, &frameTargeter.target());
396             targeters.try_emplace(id, &frameTargeter);
397         }
398 
399         mFlinger->commit(displayId, targets);
400 
401         if (composite) {
402             mFlinger->composite(displayId, targeters);
403         }
404     }
405 
406     void commit(TimePoint frameTime, VsyncId vsyncId, bool composite = false) {
407         return commit(frameTime, vsyncId, frameTime + Period(10ms), composite);
408     }
409 
410     void commit(bool composite = false) {
411         const TimePoint frameTime = scheduler::SchedulerClock::now();
412         commit(frameTime, kVsyncId, composite);
413     }
414 
commitAndComposite(TimePoint frameTime,VsyncId vsyncId,TimePoint expectedVsyncTime)415     void commitAndComposite(TimePoint frameTime, VsyncId vsyncId, TimePoint expectedVsyncTime) {
416         constexpr bool kComposite = true;
417         commit(frameTime, vsyncId, expectedVsyncTime, kComposite);
418     }
419 
commitAndComposite()420     void commitAndComposite() {
421         constexpr bool kComposite = true;
422         commit(kComposite);
423     }
424 
425     auto createVirtualDisplay(const std::string& displayName, bool isSecure,
426                               float requestedRefreshRate = 0.0f) {
427         static const std::string kTestId =
428                 "virtual:libsurfaceflinger_unittest:TestableSurfaceFlinger";
429         return mFlinger->createVirtualDisplay(displayName, isSecure, kTestId, requestedRefreshRate);
430     }
431 
432     auto createVirtualDisplay(const std::string& displayName, bool isSecure,
433                               const std::string& uniqueId, float requestedRefreshRate = 0.0f) {
434         return mFlinger->createVirtualDisplay(displayName, isSecure, uniqueId,
435                                               requestedRefreshRate);
436     }
437 
destroyVirtualDisplay(const sp<IBinder> & displayToken)438     auto destroyVirtualDisplay(const sp<IBinder>& displayToken) {
439         return mFlinger->destroyVirtualDisplay(displayToken);
440     }
441 
getDisplay(const sp<IBinder> & displayToken)442     auto getDisplay(const sp<IBinder>& displayToken) {
443         Mutex::Autolock lock(mFlinger->mStateLock);
444         return mFlinger->getDisplayDeviceLocked(displayToken);
445     }
446 
enableHalVirtualDisplays(bool enable)447     void enableHalVirtualDisplays(bool enable) { mFlinger->enableHalVirtualDisplays(enable); }
448 
setupNewDisplayDeviceInternal(const wp<IBinder> & displayToken,std::shared_ptr<compositionengine::Display> compositionDisplay,const DisplayDeviceState & state,const sp<compositionengine::DisplaySurface> & dispSurface,const sp<IGraphicBufferProducer> & producer)449     auto setupNewDisplayDeviceInternal(
450             const wp<IBinder>& displayToken,
451             std::shared_ptr<compositionengine::Display> compositionDisplay,
452             const DisplayDeviceState& state,
453             const sp<compositionengine::DisplaySurface>& dispSurface,
454             const sp<IGraphicBufferProducer>& producer) NO_THREAD_SAFETY_ANALYSIS {
455         return mFlinger->setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
456                                                        dispSurface, producer);
457     }
458 
commitTransactionsLocked(uint32_t transactionFlags)459     void commitTransactionsLocked(uint32_t transactionFlags) {
460         Mutex::Autolock lock(mFlinger->mStateLock);
461         ftl::FakeGuard guard(kMainThreadContext);
462         mFlinger->processDisplayChangesLocked();
463         mFlinger->commitTransactionsLocked(transactionFlags);
464     }
465 
onComposerHalHotplugEvent(hal::HWDisplayId hwcDisplayId,DisplayHotplugEvent event)466     void onComposerHalHotplugEvent(hal::HWDisplayId hwcDisplayId, DisplayHotplugEvent event) {
467         mFlinger->onComposerHalHotplugEvent(hwcDisplayId, event);
468     }
469 
setDisplayStateLocked(const DisplayState & s)470     auto setDisplayStateLocked(const DisplayState& s) {
471         Mutex::Autolock lock(mFlinger->mStateLock);
472         return mFlinger->setDisplayStateLocked(s);
473     }
474 
initializeDisplays()475     void initializeDisplays() FTL_FAKE_GUARD(kMainThreadContext) { mFlinger->initializeDisplays(); }
476 
notifyPowerBoost(int32_t boostId)477     auto notifyPowerBoost(int32_t boostId) { return mFlinger->notifyPowerBoost(boostId); }
478 
setDisplayBrightness(const sp<IBinder> & display,const gui::DisplayBrightness & brightness)479     auto setDisplayBrightness(const sp<IBinder>& display,
480                               const gui::DisplayBrightness& brightness) {
481         return mFlinger->setDisplayBrightness(display, brightness);
482     }
483 
484     // Allow reading display state without locking, as if called on the SF main thread.
setPowerModeInternal(const sp<DisplayDevice> & display,hal::PowerMode mode)485     auto setPowerModeInternal(const sp<DisplayDevice>& display,
486                               hal::PowerMode mode) NO_THREAD_SAFETY_ANALYSIS {
487         return mFlinger->setPowerModeInternal(display, mode);
488     }
489 
renderScreenImpl(const sp<DisplayDevice> display,std::unique_ptr<const RenderArea> renderArea,SurfaceFlinger::GetLayerSnapshotsFunction getLayerSnapshotsFn,const std::shared_ptr<renderengine::ExternalTexture> & buffer,bool regionSampling)490     auto renderScreenImpl(const sp<DisplayDevice> display,
491                           std::unique_ptr<const RenderArea> renderArea,
492                           SurfaceFlinger::GetLayerSnapshotsFunction getLayerSnapshotsFn,
493                           const std::shared_ptr<renderengine::ExternalTexture>& buffer,
494                           bool regionSampling) {
495         Mutex::Autolock lock(mFlinger->mStateLock);
496         ftl::FakeGuard guard(kMainThreadContext);
497 
498         ScreenCaptureResults captureResults;
499         auto displayState = std::optional{display->getCompositionDisplay()->getState()};
500         auto layers = getLayerSnapshotsFn();
501         auto layerFEs = mFlinger->extractLayerFEs(layers);
502 
503         return mFlinger->renderScreenImpl(std::move(renderArea), buffer, regionSampling,
504                                           false /* grayscale */, false /* isProtected */,
505                                           captureResults, displayState, layers, layerFEs);
506     }
507 
traverseLayersInLayerStack(ui::LayerStack layerStack,int32_t uid,std::unordered_set<uint32_t> excludeLayerIds,const LayerVector::Visitor & visitor)508     auto traverseLayersInLayerStack(ui::LayerStack layerStack, int32_t uid,
509                                     std::unordered_set<uint32_t> excludeLayerIds,
510                                     const LayerVector::Visitor& visitor) {
511         return mFlinger->traverseLayersInLayerStack(layerStack, uid, excludeLayerIds, visitor);
512     }
513 
getDisplayNativePrimaries(const sp<IBinder> & displayToken,ui::DisplayPrimaries & primaries)514     auto getDisplayNativePrimaries(const sp<IBinder>& displayToken,
515                                    ui::DisplayPrimaries &primaries) {
516         return mFlinger->SurfaceFlinger::getDisplayNativePrimaries(displayToken, primaries);
517     }
518 
getTransactionQueue()519     auto& getTransactionQueue() { return mFlinger->mTransactionHandler.mLocklessTransactionQueue; }
getPendingTransactionQueue()520     auto& getPendingTransactionQueue() {
521         ftl::FakeGuard guard(kMainThreadContext);
522         return mFlinger->mTransactionHandler.mPendingTransactionQueues;
523     }
getPendingTransactionCount()524     size_t getPendingTransactionCount() {
525         ftl::FakeGuard guard(kMainThreadContext);
526         return mFlinger->mTransactionHandler.mPendingTransactionCount.load();
527     }
528 
setTransactionState(const FrameTimelineInfo & frameTimelineInfo,Vector<ComposerState> & states,const Vector<DisplayState> & displays,uint32_t flags,const sp<IBinder> & applyToken,const InputWindowCommands & inputWindowCommands,int64_t desiredPresentTime,bool isAutoTimestamp,const std::vector<client_cache_t> & uncacheBuffers,bool hasListenerCallbacks,std::vector<ListenerCallbacks> & listenerCallbacks,uint64_t transactionId,const std::vector<uint64_t> & mergedTransactionIds)529     auto setTransactionState(
530             const FrameTimelineInfo& frameTimelineInfo, Vector<ComposerState>& states,
531             const Vector<DisplayState>& displays, uint32_t flags, const sp<IBinder>& applyToken,
532             const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime,
533             bool isAutoTimestamp, const std::vector<client_cache_t>& uncacheBuffers,
534             bool hasListenerCallbacks, std::vector<ListenerCallbacks>& listenerCallbacks,
535             uint64_t transactionId, const std::vector<uint64_t>& mergedTransactionIds) {
536         return mFlinger->setTransactionState(frameTimelineInfo, states, displays, flags, applyToken,
537                                              inputWindowCommands, desiredPresentTime,
538                                              isAutoTimestamp, uncacheBuffers, hasListenerCallbacks,
539                                              listenerCallbacks, transactionId,
540                                              mergedTransactionIds);
541     }
542 
setTransactionStateInternal(TransactionState & transaction)543     auto setTransactionStateInternal(TransactionState& transaction) {
544         return FTL_FAKE_GUARD(kMainThreadContext,
545                               mFlinger->mTransactionHandler.queueTransaction(
546                                       std::move(transaction)));
547     }
548 
flushTransactionQueues()549     auto flushTransactionQueues() {
550         return FTL_FAKE_GUARD(kMainThreadContext, mFlinger->flushTransactionQueues(kVsyncId));
551     }
552 
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)553     auto onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
554         return mFlinger->onTransact(code, data, reply, flags);
555     }
556 
getGpuContextPriority()557     auto getGpuContextPriority() { return mFlinger->getGpuContextPriority(); }
558 
calculateMaxAcquiredBufferCount(Fps refreshRate,std::chrono::nanoseconds presentLatency)559     auto calculateMaxAcquiredBufferCount(Fps refreshRate,
560                                          std::chrono::nanoseconds presentLatency) const {
561         return SurfaceFlinger::calculateMaxAcquiredBufferCount(refreshRate, presentLatency);
562     }
563 
setDesiredDisplayModeSpecs(const sp<IBinder> & displayToken,const gui::DisplayModeSpecs & specs)564     auto setDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
565                                     const gui::DisplayModeSpecs& specs) {
566         return mFlinger->setDesiredDisplayModeSpecs(displayToken, specs);
567     }
568 
onActiveDisplayChanged(const DisplayDevice * inactiveDisplayPtr,const DisplayDevice & activeDisplay)569     void onActiveDisplayChanged(const DisplayDevice* inactiveDisplayPtr,
570                                 const DisplayDevice& activeDisplay) {
571         Mutex::Autolock lock(mFlinger->mStateLock);
572         ftl::FakeGuard guard(kMainThreadContext);
573         mFlinger->onActiveDisplayChangedLocked(inactiveDisplayPtr, activeDisplay);
574     }
575 
createLayer(LayerCreationArgs & args,const sp<IBinder> & parentHandle,gui::CreateSurfaceResult & outResult)576     auto createLayer(LayerCreationArgs& args, const sp<IBinder>& parentHandle,
577                      gui::CreateSurfaceResult& outResult) {
578         args.parentHandle = parentHandle;
579         return mFlinger->createLayer(args, outResult);
580     }
581 
mirrorLayer(const LayerCreationArgs & args,const sp<IBinder> & mirrorFromHandle,gui::CreateSurfaceResult & outResult)582     auto mirrorLayer(const LayerCreationArgs& args, const sp<IBinder>& mirrorFromHandle,
583                      gui::CreateSurfaceResult& outResult) {
584         return mFlinger->mirrorLayer(args, mirrorFromHandle, outResult);
585     }
586 
updateLayerMetadataSnapshot()587     void updateLayerMetadataSnapshot() { mFlinger->updateLayerMetadataSnapshot(); }
588 
getDynamicDisplayInfoFromToken(const sp<IBinder> & displayToken,ui::DynamicDisplayInfo * dynamicDisplayInfo)589     void getDynamicDisplayInfoFromToken(const sp<IBinder>& displayToken,
590                                         ui::DynamicDisplayInfo* dynamicDisplayInfo) {
591         mFlinger->getDynamicDisplayInfoFromToken(displayToken, dynamicDisplayInfo);
592     }
593 
createVirtualDisplayDevice(const sp<IBinder> displayToken,VirtualDisplayId displayId,float requestedRefreshRate)594     sp<DisplayDevice> createVirtualDisplayDevice(const sp<IBinder> displayToken,
595                                                  VirtualDisplayId displayId,
596                                                  float requestedRefreshRate) {
597         constexpr ui::Size kResolution = {1080, 1920};
598         auto compositionDisplay = compositionengine::impl::
599                 createDisplay(mFlinger->getCompositionEngine(),
600                               compositionengine::DisplayCreationArgsBuilder()
601                                       .setId(displayId)
602                                       .setPixels(kResolution)
603                                       .setPowerAdvisor(&mPowerAdvisor)
604                                       .build());
605         DisplayDeviceCreationArgs creationArgs(mFlinger, mFlinger->getHwComposer(), displayToken,
606                                                compositionDisplay);
607         creationArgs.requestedRefreshRate = Fps::fromValue(requestedRefreshRate);
608         creationArgs.nativeWindow = sp<mock::NativeWindow>::make();
609         return sp<DisplayDevice>::make(creationArgs);
610     }
611 
getDisplayStats(const sp<IBinder> & displayToken,DisplayStatInfo * outInfo)612     status_t getDisplayStats(const sp<IBinder>& displayToken, DisplayStatInfo* outInfo) {
613         return mFlinger->getDisplayStats(displayToken, outInfo);
614     }
615 
616     // Used to add a layer before updateLayerSnapshots is called.
617     // Must have transactionsFlushed enabled for the new layer to be updated.
addLayer(std::unique_ptr<frontend::RequestedLayerState> & layer)618     void addLayer(std::unique_ptr<frontend::RequestedLayerState>& layer) {
619         std::scoped_lock<std::mutex> lock(mFlinger->mCreatedLayersLock);
620         mFlinger->mNewLayers.emplace_back(std::move(layer));
621     }
622 
623     /* ------------------------------------------------------------------------
624      * Read-only access to private data to assert post-conditions.
625      */
626 
getVisibleRegionsDirty()627     const auto& getVisibleRegionsDirty() const { return mFlinger->mVisibleRegionsDirty; }
getHwComposer()628     auto& getHwComposer() const {
629         return static_cast<impl::HWComposer&>(mFlinger->getHwComposer());
630     }
getCompositionEngine()631     auto& getCompositionEngine() const { return mFlinger->getCompositionEngine(); }
632 
getFrameTracer()633     mock::FrameTracer* getFrameTracer() const {
634         return static_cast<mock::FrameTracer*>(mFlinger->mFrameTracer.get());
635     }
636 
injectLegacyLayer(sp<Layer> layer)637     void injectLegacyLayer(sp<Layer> layer) {
638         FTL_FAKE_GUARD(kMainThreadContext,
639                        mFlinger->mLegacyLayers[static_cast<uint32_t>(layer->sequence)] = layer);
640     };
641 
releaseLegacyLayer(uint32_t sequence)642     void releaseLegacyLayer(uint32_t sequence) {
643         FTL_FAKE_GUARD(kMainThreadContext, mFlinger->mLegacyLayers.erase(sequence));
644     };
645 
setLayerHistoryDisplayArea(uint32_t displayArea)646     auto setLayerHistoryDisplayArea(uint32_t displayArea) {
647         return mFlinger->mScheduler->onActiveDisplayAreaChanged(displayArea);
648     };
updateLayerHistory(nsecs_t now)649     auto updateLayerHistory(nsecs_t now) {
650         return FTL_FAKE_GUARD(kMainThreadContext, mFlinger->updateLayerHistory(now));
651     };
setDaltonizerType(ColorBlindnessType type)652     auto setDaltonizerType(ColorBlindnessType type) {
653         mFlinger->mDaltonizer.setType(type);
654         return mFlinger->updateColorMatrixLocked();
655     }
updateLayerSnapshots(VsyncId vsyncId,nsecs_t frameTimeNs,bool transactionsFlushed,bool & out)656     auto updateLayerSnapshots(VsyncId vsyncId, nsecs_t frameTimeNs, bool transactionsFlushed,
657                               bool& out) {
658         ftl::FakeGuard guard(kMainThreadContext);
659         return mFlinger->updateLayerSnapshots(vsyncId, frameTimeNs, transactionsFlushed, out);
660     }
661     /* ------------------------------------------------------------------------
662      * Read-write access to private data to set up preconditions and assert
663      * post-conditions.
664      */
665 
displays()666     const auto& displays() const { return mFlinger->mDisplays; }
physicalDisplays()667     const auto& physicalDisplays() const { return mFlinger->mPhysicalDisplays; }
currentState()668     const auto& currentState() const { return mFlinger->mCurrentState; }
drawingState()669     const auto& drawingState() const { return mFlinger->mDrawingState; }
transactionFlags()670     const auto& transactionFlags() const { return mFlinger->mTransactionFlags; }
671 
hwcPhysicalDisplayIdMap()672     const auto& hwcPhysicalDisplayIdMap() const { return getHwComposer().mPhysicalDisplayIdMap; }
hwcDisplayData()673     const auto& hwcDisplayData() const { return getHwComposer().mDisplayData; }
674 
mutableSupportsWideColor()675     auto& mutableSupportsWideColor() { return mFlinger->mSupportsWideColor; }
676 
mutableDisplayModeController()677     auto& mutableDisplayModeController() { return mFlinger->mDisplayModeController; }
mutableCurrentState()678     auto& mutableCurrentState() { return mFlinger->mCurrentState; }
mutableDisplayColorSetting()679     auto& mutableDisplayColorSetting() { return mFlinger->mDisplayColorSetting; }
mutableDisplays()680     auto& mutableDisplays() { return mFlinger->mDisplays; }
mutablePhysicalDisplays()681     auto& mutablePhysicalDisplays() { return mFlinger->mPhysicalDisplays; }
mutableDrawingState()682     auto& mutableDrawingState() { return mFlinger->mDrawingState; }
mutableGeometryDirty()683     auto& mutableGeometryDirty() { return mFlinger->mGeometryDirty; }
mutableVisibleRegionsDirty()684     auto& mutableVisibleRegionsDirty() { return mFlinger->mVisibleRegionsDirty; }
mutableMainThreadId()685     auto& mutableMainThreadId() { return mFlinger->mMainThreadId; }
mutablePendingHotplugEvents()686     auto& mutablePendingHotplugEvents() { return mFlinger->mPendingHotplugEvents; }
mutableTransactionFlags()687     auto& mutableTransactionFlags() { return mFlinger->mTransactionFlags; }
mutableDebugDisableHWC()688     auto& mutableDebugDisableHWC() { return mFlinger->mDebugDisableHWC; }
mutableMaxRenderTargetSize()689     auto& mutableMaxRenderTargetSize() { return mFlinger->mMaxRenderTargetSize; }
690 
mutableHwcDisplayData()691     auto& mutableHwcDisplayData() { return getHwComposer().mDisplayData; }
mutableHwcPhysicalDisplayIdMap()692     auto& mutableHwcPhysicalDisplayIdMap() { return getHwComposer().mPhysicalDisplayIdMap; }
mutablePrimaryHwcDisplayId()693     auto& mutablePrimaryHwcDisplayId() { return getHwComposer().mPrimaryHwcDisplayId; }
mutableActiveDisplayId()694     auto& mutableActiveDisplayId() { return mFlinger->mActiveDisplayId; }
mutablePreviouslyComposedLayers()695     auto& mutablePreviouslyComposedLayers() { return mFlinger->mPreviouslyComposedLayers; }
696 
mutableActiveDisplayRotationFlags()697     auto& mutableActiveDisplayRotationFlags() {
698         return SurfaceFlinger::sActiveDisplayRotationFlags;
699     }
700 
mutableMinAcquiredBuffers()701     auto& mutableMinAcquiredBuffers() { return SurfaceFlinger::minAcquiredBuffers; }
mutableLayersPendingRemoval()702     auto& mutableLayersPendingRemoval() { return mFlinger->mLayersPendingRemoval; }
mutableLayerSnapshotBuilder()703     auto& mutableLayerSnapshotBuilder() { return mFlinger->mLayerSnapshotBuilder; };
704 
fromHandle(const sp<IBinder> & handle)705     auto fromHandle(const sp<IBinder>& handle) { return LayerHandle::getLayer(handle); }
706 
initTransactionTraceWriter()707     auto initTransactionTraceWriter() {
708         mFlinger->mTransactionTracing.emplace();
709         return mFlinger->initTransactionTraceWriter();
710     }
711 
712     // Needed since mLayerLifecycleManagerEnabled is false by default and must
713     // be enabled for tests to go through the new front end path.
enableLayerLifecycleManager()714     void enableLayerLifecycleManager() { mFlinger->mLayerLifecycleManagerEnabled = true; }
715 
notifyExpectedPresentIfRequired(PhysicalDisplayId displayId,Period vsyncPeriod,TimePoint expectedPresentTime,Fps frameInterval,std::optional<Period> timeoutOpt)716     void notifyExpectedPresentIfRequired(PhysicalDisplayId displayId, Period vsyncPeriod,
717                                          TimePoint expectedPresentTime, Fps frameInterval,
718                                          std::optional<Period> timeoutOpt) {
719         mFlinger->notifyExpectedPresentIfRequired(displayId, vsyncPeriod, expectedPresentTime,
720                                                   frameInterval, timeoutOpt);
721     }
722 
sendNotifyExpectedPresentHint(PhysicalDisplayId displayId)723     void sendNotifyExpectedPresentHint(PhysicalDisplayId displayId) {
724         ftl::FakeGuard guard(kMainThreadContext);
725         mFlinger->sendNotifyExpectedPresentHint(displayId);
726     }
727 
verifyHintIsScheduledOnPresent(PhysicalDisplayId displayId)728     bool verifyHintIsScheduledOnPresent(PhysicalDisplayId displayId) {
729         return mFlinger->mNotifyExpectedPresentMap.at(displayId).hintStatus ==
730                 SurfaceFlinger::NotifyExpectedPresentHintStatus::ScheduleOnPresent;
731     }
732 
verifyHintIsSent(PhysicalDisplayId displayId)733     bool verifyHintIsSent(PhysicalDisplayId displayId) {
734         return mFlinger->mNotifyExpectedPresentMap.at(displayId).hintStatus ==
735                 SurfaceFlinger::NotifyExpectedPresentHintStatus::Sent;
736     }
737 
verifyHintStatusIsStart(PhysicalDisplayId displayId)738     bool verifyHintStatusIsStart(PhysicalDisplayId displayId) {
739         return mFlinger->mNotifyExpectedPresentMap.at(displayId).hintStatus ==
740                 SurfaceFlinger::NotifyExpectedPresentHintStatus::Start;
741     }
742 
verifyHintStatusIsScheduledOnTx(PhysicalDisplayId displayId)743     bool verifyHintStatusIsScheduledOnTx(PhysicalDisplayId displayId) {
744         return mFlinger->mNotifyExpectedPresentMap.at(displayId).hintStatus ==
745                 SurfaceFlinger::NotifyExpectedPresentHintStatus::ScheduleOnTx;
746     }
747 
verifyLastExpectedPresentTime(PhysicalDisplayId displayId,nsecs_t expectedPresentTime)748     bool verifyLastExpectedPresentTime(PhysicalDisplayId displayId, nsecs_t expectedPresentTime) {
749         return mFlinger->mNotifyExpectedPresentMap.at(displayId)
750                        .lastExpectedPresentTimestamp.ns() == expectedPresentTime;
751     }
752 
setNotifyExpectedPresentData(PhysicalDisplayId displayId,TimePoint lastExpectedPresentTimestamp,Fps lastFrameInterval)753     void setNotifyExpectedPresentData(PhysicalDisplayId displayId,
754                                       TimePoint lastExpectedPresentTimestamp,
755                                       Fps lastFrameInterval) {
756         auto& displayData = mFlinger->mNotifyExpectedPresentMap[displayId];
757         displayData.lastExpectedPresentTimestamp = lastExpectedPresentTimestamp;
758         displayData.lastFrameInterval = lastFrameInterval;
759     }
760 
resetNotifyExpectedPresentHintState(PhysicalDisplayId displayId)761     void resetNotifyExpectedPresentHintState(PhysicalDisplayId displayId) {
762         mFlinger->mNotifyExpectedPresentMap.at(displayId).hintStatus =
763                 SurfaceFlinger::NotifyExpectedPresentHintStatus::Start;
764     }
765 
~TestableSurfaceFlinger()766     ~TestableSurfaceFlinger() {
767         // All these pointer and container clears help ensure that GMock does
768         // not report a leaked object, since the SurfaceFlinger instance may
769         // still be referenced by something despite our best efforts to destroy
770         // it after each test is done.
771         mutableDisplays().clear();
772         mutableCurrentState().displays.clear();
773         mutableDrawingState().displays.clear();
774         mFlinger->mLayersPendingRemoval.clear();
775         mFlinger->mScheduler.reset();
776         mFlinger->mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
777         mFlinger->mRenderEngine = std::unique_ptr<renderengine::RenderEngine>();
778         mFlinger->mCompositionEngine->setRenderEngine(mFlinger->mRenderEngine.get());
779         mFlinger->mTransactionTracing.reset();
780     }
781 
782     /* ------------------------------------------------------------------------
783      * Wrapper classes for Read-write access to private data to set up
784      * preconditions and assert post-conditions.
785      */
786     struct HWC2Display : public HWC2::impl::Display {
HWC2DisplayHWC2Display787         HWC2Display(
788                 Hwc2::Composer& composer,
789                 const std::unordered_set<aidl::android::hardware::graphics::composer3::Capability>&
790                         capabilities,
791                 hal::HWDisplayId id, hal::DisplayType type)
792               : HWC2::impl::Display(composer, capabilities, id, type) {}
~HWC2DisplayHWC2Display793         ~HWC2Display() {
794             // Prevents a call to disable vsyncs.
795             mType = hal::DisplayType::INVALID;
796         }
797 
mutableIsConnectedHWC2Display798         auto& mutableIsConnected() { return this->mIsConnected; }
mutableLayersHWC2Display799         auto& mutableLayers() { return this->mLayers; }
800     };
801 
802     class FakeHwcDisplayInjector {
803     public:
804         static constexpr hal::HWDisplayId DEFAULT_HWC_DISPLAY_ID = 1000;
805         static constexpr ui::Size DEFAULT_RESOLUTION{1920, 1280};
806         static constexpr int32_t DEFAULT_VSYNC_PERIOD = 16'666'667;
807         static constexpr int32_t DEFAULT_CONFIG_GROUP = 7;
808         static constexpr int32_t DEFAULT_DPI = 320;
809         static constexpr hal::HWConfigId DEFAULT_ACTIVE_CONFIG = 0;
810 
FakeHwcDisplayInjector(HalDisplayId displayId,hal::DisplayType hwcDisplayType,bool isPrimary)811         FakeHwcDisplayInjector(HalDisplayId displayId, hal::DisplayType hwcDisplayType,
812                                bool isPrimary)
813               : mDisplayId(displayId), mHwcDisplayType(hwcDisplayType), mIsPrimary(isPrimary) {}
814 
setHwcDisplayId(hal::HWDisplayId displayId)815         auto& setHwcDisplayId(hal::HWDisplayId displayId) {
816             mHwcDisplayId = displayId;
817             return *this;
818         }
819 
setResolution(ui::Size resolution)820         auto& setResolution(ui::Size resolution) {
821             mResolution = resolution;
822             return *this;
823         }
824 
setVsyncPeriod(nsecs_t vsyncPeriod)825         auto& setVsyncPeriod(nsecs_t vsyncPeriod) {
826             mVsyncPeriod = vsyncPeriod;
827             return *this;
828         }
829 
setDpiX(int32_t dpi)830         auto& setDpiX(int32_t dpi) {
831             mDpiX = dpi;
832             return *this;
833         }
834 
setDpiY(int32_t dpi)835         auto& setDpiY(int32_t dpi) {
836             mDpiY = dpi;
837             return *this;
838         }
839 
setActiveConfig(hal::HWConfigId config)840         auto& setActiveConfig(hal::HWConfigId config) {
841             mActiveConfig = config;
842             return *this;
843         }
844 
setCapabilities(const std::unordered_set<aidl::android::hardware::graphics::composer3::Capability> * capabilities)845         auto& setCapabilities(
846                 const std::unordered_set<aidl::android::hardware::graphics::composer3::Capability>*
847                         capabilities) {
848             mCapabilities = capabilities;
849             return *this;
850         }
851 
setPowerMode(hal::PowerMode mode)852         auto& setPowerMode(hal::PowerMode mode) {
853             mPowerMode = mode;
854             return *this;
855         }
856 
inject(TestableSurfaceFlinger * flinger,Hwc2::mock::Composer * composer)857         void inject(TestableSurfaceFlinger* flinger, Hwc2::mock::Composer* composer) {
858             using ::testing::_;
859             using ::testing::DoAll;
860             using ::testing::Return;
861             using ::testing::SetArgPointee;
862 
863             static const std::unordered_set<
864                     aidl::android::hardware::graphics::composer3::Capability>
865                     defaultCapabilities;
866             if (mCapabilities == nullptr) mCapabilities = &defaultCapabilities;
867 
868             // Caution - Make sure that any values passed by reference here do
869             // not refer to an instance owned by FakeHwcDisplayInjector. This
870             // class has temporary lifetime, while the constructed HWC2::Display
871             // is much longer lived.
872             auto display = std::make_unique<HWC2Display>(*composer, *mCapabilities, mHwcDisplayId,
873                                                          mHwcDisplayType);
874             display->mutableIsConnected() = true;
875 
876             display->setPowerMode(mPowerMode);
877 
878             flinger->mutableHwcDisplayData()[mDisplayId].hwcDisplay = std::move(display);
879 
880             EXPECT_CALL(*composer, getDisplayConfigs(mHwcDisplayId, _))
881                     .WillRepeatedly(
882                             DoAll(SetArgPointee<1>(std::vector<hal::HWConfigId>{mActiveConfig}),
883                                   Return(hal::Error::NONE)));
884             EXPECT_CALL(*composer,
885                         getDisplayAttribute(mHwcDisplayId, mActiveConfig, hal::Attribute::WIDTH, _))
886                     .WillRepeatedly(DoAll(SetArgPointee<3>(mResolution.getWidth()),
887                                           Return(hal::Error::NONE)));
888 
889             EXPECT_CALL(*composer,
890                         getDisplayAttribute(mHwcDisplayId, mActiveConfig, hal::Attribute::HEIGHT,
891                                             _))
892                     .WillRepeatedly(DoAll(SetArgPointee<3>(mResolution.getHeight()),
893                                           Return(hal::Error::NONE)));
894 
895             EXPECT_CALL(*composer,
896                         getDisplayAttribute(mHwcDisplayId, mActiveConfig,
897                                             hal::Attribute::VSYNC_PERIOD, _))
898                     .WillRepeatedly(DoAll(SetArgPointee<3>(static_cast<int32_t>(mVsyncPeriod)),
899                                           Return(hal::Error::NONE)));
900 
901             EXPECT_CALL(*composer,
902                         getDisplayAttribute(mHwcDisplayId, mActiveConfig, hal::Attribute::DPI_X, _))
903                     .WillRepeatedly(DoAll(SetArgPointee<3>(mDpiX), Return(hal::Error::NONE)));
904 
905             EXPECT_CALL(*composer,
906                         getDisplayAttribute(mHwcDisplayId, mActiveConfig, hal::Attribute::DPI_Y, _))
907                     .WillRepeatedly(DoAll(SetArgPointee<3>(mDpiY), Return(hal::Error::NONE)));
908 
909             EXPECT_CALL(*composer,
910                         getDisplayAttribute(mHwcDisplayId, mActiveConfig,
911                                             hal::Attribute::CONFIG_GROUP, _))
912                     .WillRepeatedly(
913                             DoAll(SetArgPointee<3>(mConfigGroup), Return(hal::Error::NONE)));
914 
915             if (mHwcDisplayType == hal::DisplayType::PHYSICAL) {
916                 const auto physicalId = PhysicalDisplayId::tryCast(mDisplayId);
917                 LOG_ALWAYS_FATAL_IF(!physicalId);
918                 flinger->mutableHwcPhysicalDisplayIdMap().emplace(mHwcDisplayId, *physicalId);
919                 if (mIsPrimary) {
920                     flinger->mutablePrimaryHwcDisplayId() = mHwcDisplayId;
921                 } else {
922                     // If there is an external HWC display, there should always be a primary ID
923                     // as well. Set it to some arbitrary value.
924                     auto& primaryId = flinger->mutablePrimaryHwcDisplayId();
925                     if (!primaryId) primaryId = mHwcDisplayId - 1;
926                 }
927             }
928         }
929 
930     private:
931         const HalDisplayId mDisplayId;
932         const hal::DisplayType mHwcDisplayType;
933         const bool mIsPrimary;
934 
935         hal::HWDisplayId mHwcDisplayId = DEFAULT_HWC_DISPLAY_ID;
936         ui::Size mResolution = DEFAULT_RESOLUTION;
937         nsecs_t mVsyncPeriod = DEFAULT_VSYNC_PERIOD;
938         int32_t mDpiX = DEFAULT_DPI;
939         int32_t mDpiY = DEFAULT_DPI;
940         int32_t mConfigGroup = DEFAULT_CONFIG_GROUP;
941         hal::HWConfigId mActiveConfig = DEFAULT_ACTIVE_CONFIG;
942         hal::PowerMode mPowerMode = hal::PowerMode::ON;
943         const std::unordered_set<aidl::android::hardware::graphics::composer3::Capability>*
944                 mCapabilities = nullptr;
945     };
946 
947     class FakeDisplayDeviceInjector {
948     public:
FakeDisplayDeviceInjector(TestableSurfaceFlinger & flinger,std::shared_ptr<compositionengine::Display> display,std::optional<ui::DisplayConnectionType> connectionType,std::optional<hal::HWDisplayId> hwcDisplayId,bool isPrimary)949         FakeDisplayDeviceInjector(TestableSurfaceFlinger& flinger,
950                                   std::shared_ptr<compositionengine::Display> display,
951                                   std::optional<ui::DisplayConnectionType> connectionType,
952                                   std::optional<hal::HWDisplayId> hwcDisplayId, bool isPrimary)
953               : mFlinger(flinger),
954                 mCreationArgs(flinger.mFlinger, flinger.mFlinger->getHwComposer(), mDisplayToken,
955                               display),
956                 mConnectionType(connectionType),
957                 mHwcDisplayId(hwcDisplayId) {
958             mCreationArgs.isPrimary = isPrimary;
959             mCreationArgs.initialPowerMode = hal::PowerMode::ON;
960         }
961 
token()962         sp<IBinder> token() const { return mDisplayToken; }
963 
physicalDisplay()964         auto physicalDisplay() const {
965             return ftl::Optional(mCreationArgs.compositionDisplay->getDisplayId())
966                     .and_then(&PhysicalDisplayId::tryCast)
967                     .and_then(display::getPhysicalDisplay(mFlinger.physicalDisplays()));
968         }
969 
mutableDrawingDisplayState()970         DisplayDeviceState& mutableDrawingDisplayState() {
971             return mFlinger.mutableDrawingState().displays.editValueFor(mDisplayToken);
972         }
973 
mutableCurrentDisplayState()974         DisplayDeviceState& mutableCurrentDisplayState() {
975             return mFlinger.mutableCurrentState().displays.editValueFor(mDisplayToken);
976         }
977 
getDrawingDisplayState()978         const auto& getDrawingDisplayState() {
979             return mFlinger.mutableDrawingState().displays.valueFor(mDisplayToken);
980         }
981 
getCurrentDisplayState()982         const auto& getCurrentDisplayState() {
983             return mFlinger.mutableCurrentState().displays.valueFor(mDisplayToken);
984         }
985 
mutableDisplayDevice()986         const sp<DisplayDevice>& mutableDisplayDevice() {
987             return mFlinger.mutableDisplays().get(mDisplayToken)->get();
988         }
989 
setDisplayModes(DisplayModes modes,DisplayModeId activeModeId)990         auto& setDisplayModes(DisplayModes modes, DisplayModeId activeModeId) {
991             mDisplayModes = std::move(modes);
992             mActiveModeId = activeModeId;
993             mCreationArgs.refreshRateSelector = nullptr;
994             return *this;
995         }
996 
setRefreshRateSelector(RefreshRateSelectorPtr selectorPtr)997         auto& setRefreshRateSelector(RefreshRateSelectorPtr selectorPtr) {
998             mDisplayModes = selectorPtr->displayModes();
999             mActiveModeId = selectorPtr->getActiveMode().modePtr->getId();
1000             mCreationArgs.refreshRateSelector = std::move(selectorPtr);
1001             return *this;
1002         }
1003 
setNativeWindow(const sp<ANativeWindow> & nativeWindow)1004         auto& setNativeWindow(const sp<ANativeWindow>& nativeWindow) {
1005             mCreationArgs.nativeWindow = nativeWindow;
1006             return *this;
1007         }
1008 
setDisplaySurface(const sp<compositionengine::DisplaySurface> & displaySurface)1009         auto& setDisplaySurface(const sp<compositionengine::DisplaySurface>& displaySurface) {
1010             mCreationArgs.displaySurface = displaySurface;
1011             return *this;
1012         }
1013 
setSecure(bool secure)1014         auto& setSecure(bool secure) {
1015             mCreationArgs.isSecure = secure;
1016             return *this;
1017         }
1018 
setPowerMode(hal::PowerMode mode)1019         auto& setPowerMode(hal::PowerMode mode) {
1020             mCreationArgs.initialPowerMode = mode;
1021             return *this;
1022         }
1023 
setHwcColorModes(const std::unordered_map<ui::ColorMode,std::vector<ui::RenderIntent>> hwcColorModes)1024         auto& setHwcColorModes(
1025                 const std::unordered_map<ui::ColorMode, std::vector<ui::RenderIntent>>
1026                         hwcColorModes) {
1027             mCreationArgs.hwcColorModes = hwcColorModes;
1028             return *this;
1029         }
1030 
setHasWideColorGamut(bool hasWideColorGamut)1031         auto& setHasWideColorGamut(bool hasWideColorGamut) {
1032             mCreationArgs.hasWideColorGamut = hasWideColorGamut;
1033             return *this;
1034         }
1035 
setPhysicalOrientation(ui::Rotation orientation)1036         auto& setPhysicalOrientation(ui::Rotation orientation) {
1037             mCreationArgs.physicalOrientation = orientation;
1038             return *this;
1039         }
1040 
1041         // Used to avoid overwriting mocks injected by TestableSurfaceFlinger::setupMockScheduler.
skipSchedulerRegistration()1042         auto& skipSchedulerRegistration() {
1043             mSchedulerRegistration = false;
1044             return *this;
1045         }
1046 
inject()1047         sp<DisplayDevice> inject() NO_THREAD_SAFETY_ANALYSIS {
1048             return inject(std::make_unique<mock::VsyncController>(),
1049                           std::make_shared<mock::VSyncTracker>());
1050         }
1051 
inject(std::unique_ptr<android::scheduler::VsyncController> controller,std::shared_ptr<android::scheduler::VSyncTracker> tracker)1052         sp<DisplayDevice> inject(std::unique_ptr<android::scheduler::VsyncController> controller,
1053                                  std::shared_ptr<android::scheduler::VSyncTracker> tracker)
1054                 NO_THREAD_SAFETY_ANALYSIS {
1055             const auto displayId = mCreationArgs.compositionDisplay->getDisplayId();
1056             LOG_ALWAYS_FATAL_IF(!displayId);
1057 
1058             auto& modes = mDisplayModes;
1059             auto& activeModeId = mActiveModeId;
1060 
1061             DisplayDeviceState state;
1062             state.isSecure = mCreationArgs.isSecure;
1063 
1064             if (const auto physicalId = PhysicalDisplayId::tryCast(*displayId)) {
1065                 LOG_ALWAYS_FATAL_IF(!mConnectionType);
1066                 LOG_ALWAYS_FATAL_IF(!mHwcDisplayId);
1067 
1068                 if (mCreationArgs.isPrimary) {
1069                     mFlinger.mutableActiveDisplayId() = *physicalId;
1070                 }
1071 
1072                 if (!mCreationArgs.refreshRateSelector) {
1073                     if (modes.empty()) {
1074                         constexpr DisplayModeId kModeId{0};
1075                         DisplayModePtr mode =
1076                                 DisplayMode::Builder(FakeHwcDisplayInjector::DEFAULT_ACTIVE_CONFIG)
1077                                         .setId(kModeId)
1078                                         .setPhysicalDisplayId(*physicalId)
1079                                         .setResolution(FakeHwcDisplayInjector::DEFAULT_RESOLUTION)
1080                                         .setVsyncPeriod(
1081                                                 FakeHwcDisplayInjector::DEFAULT_VSYNC_PERIOD)
1082                                         .setDpiX(FakeHwcDisplayInjector::DEFAULT_DPI)
1083                                         .setDpiY(FakeHwcDisplayInjector::DEFAULT_DPI)
1084                                         .setGroup(FakeHwcDisplayInjector::DEFAULT_CONFIG_GROUP)
1085                                         .build();
1086 
1087                         modes = ftl::init::map(kModeId, std::move(mode));
1088                         activeModeId = kModeId;
1089                     }
1090 
1091                     mCreationArgs.refreshRateSelector =
1092                             std::make_shared<scheduler::RefreshRateSelector>(modes, activeModeId);
1093                 }
1094 
1095                 const auto activeModeOpt = modes.get(activeModeId);
1096                 LOG_ALWAYS_FATAL_IF(!activeModeOpt);
1097 
1098                 // Save a copy for use after `modes` is consumed.
1099                 const Fps refreshRate = activeModeOpt->get()->getPeakFps();
1100 
1101                 state.physical = {.id = *physicalId,
1102                                   .hwcDisplayId = *mHwcDisplayId,
1103                                   .activeMode = activeModeOpt->get()};
1104 
1105                 const auto it = mFlinger.mutablePhysicalDisplays()
1106                                         .emplace_or_replace(*physicalId, mDisplayToken, *physicalId,
1107                                                             *mConnectionType, std::move(modes),
1108                                                             ui::ColorModes(), std::nullopt)
1109                                         .first;
1110 
1111                 mFlinger.mutableDisplayModeController()
1112                         .registerDisplay(*physicalId, it->second.snapshot(),
1113                                          mCreationArgs.refreshRateSelector);
1114 
1115                 mFlinger.mutableDisplayModeController().setActiveMode(*physicalId, activeModeId,
1116                                                                       refreshRate, refreshRate);
1117 
1118                 if (mFlinger.scheduler() && mSchedulerRegistration) {
1119                     mFlinger.scheduler()->registerDisplay(*physicalId,
1120                                                           mCreationArgs.refreshRateSelector,
1121                                                           std::move(controller), std::move(tracker),
1122                                                           mFlinger.mutableActiveDisplayId());
1123                 }
1124             }
1125 
1126             sp<DisplayDevice> display = sp<DisplayDevice>::make(mCreationArgs);
1127             mFlinger.mutableDisplays().emplace_or_replace(mDisplayToken, display);
1128 
1129             mFlinger.mutableCurrentState().displays.add(mDisplayToken, state);
1130             mFlinger.mutableDrawingState().displays.add(mDisplayToken, state);
1131 
1132             return display;
1133         }
1134 
1135     private:
1136         TestableSurfaceFlinger& mFlinger;
1137         sp<BBinder> mDisplayToken = sp<BBinder>::make();
1138         DisplayDeviceCreationArgs mCreationArgs;
1139         DisplayModes mDisplayModes;
1140         DisplayModeId mActiveModeId;
1141         bool mSchedulerRegistration = true;
1142         const std::optional<ui::DisplayConnectionType> mConnectionType;
1143         const std::optional<hal::HWDisplayId> mHwcDisplayId;
1144     };
1145 
1146 private:
1147     template <typename T>
makeMock(bool useNiceMock)1148     static std::unique_ptr<T> makeMock(bool useNiceMock) {
1149         return useNiceMock ? std::make_unique<testing::NiceMock<T>>() : std::make_unique<T>();
1150     }
1151 
1152     template <typename T>
makeSharedMock(bool useNiceMock)1153     static std::shared_ptr<T> makeSharedMock(bool useNiceMock) {
1154         return useNiceMock ? std::make_shared<testing::NiceMock<T>>() : std::make_shared<T>();
1155     }
1156 
1157     static constexpr VsyncId kVsyncId{123};
1158 
1159     surfaceflinger::test::Factory mFactory;
1160     sp<SurfaceFlinger> mFlinger;
1161     scheduler::mock::SchedulerCallback mSchedulerCallback;
1162     scheduler::mock::NoOpSchedulerCallback mNoOpSchedulerCallback;
1163     std::unique_ptr<frametimeline::impl::TokenManager> mTokenManager;
1164     scheduler::TestableScheduler* mScheduler = nullptr;
1165     Hwc2::mock::PowerAdvisor mPowerAdvisor;
1166 };
1167 
1168 } // namespace android
1169