1 // Copyright 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef CC_TEST_LAYER_TREE_TEST_H_
6 #define CC_TEST_LAYER_TREE_TEST_H_
7 
8 #include <memory>
9 #include <string>
10 
11 #include "base/memory/ref_counted.h"
12 #include "base/test/scoped_feature_list.h"
13 #include "base/threading/thread.h"
14 #include "build/build_config.h"
15 #include "cc/animation/animation_delegate.h"
16 #include "cc/base/features.h"
17 #include "cc/test/property_tree_test_utils.h"
18 #include "cc/test/test_hooks.h"
19 #include "cc/test/test_task_graph_runner.h"
20 #include "cc/test/test_types.h"
21 #include "cc/trees/compositor_mode.h"
22 #include "cc/trees/layer_tree_host.h"
23 #include "cc/trees/layer_tree_host_impl.h"
24 #include "components/viz/common/surfaces/parent_local_surface_id_allocator.h"
25 #include "components/viz/test/test_gpu_memory_buffer_manager.h"
26 #include "components/viz/test/test_gpu_service_holder.h"
27 #include "testing/gtest/include/gtest/gtest.h"
28 
29 namespace base {
30 namespace test {
31 class ScopedFeatureList;
32 }
33 }  // namespace base
34 
35 namespace viz {
36 class BeginFrameSource;
37 class TestContextProvider;
38 }
39 
40 namespace cc {
41 
42 class Animation;
43 class AnimationHost;
44 class LayerTreeHost;
45 class LayerTreeHostForTesting;
46 class LayerTreeTestLayerTreeFrameSinkClient;
47 class Proxy;
48 class TestLayerTreeFrameSink;
49 class TestTaskGraphRunner;
50 
51 class LayerTreeHostClientForTesting;
52 
53 // The LayerTreeTests runs with the main loop running. It instantiates a single
54 // LayerTreeHostForTesting and associated LayerTreeHostImplForTesting and
55 // LayerTreeHostClientForTesting.
56 //
57 // BeginTest() is called once the main message loop is running and the layer
58 // tree host is initialized.
59 //
60 // Key stages of the drawing loop, e.g. drawing or commiting, redirect to
61 // LayerTreeTest methods of similar names. To track the commit process, override
62 // these functions.
63 //
64 // The test continues until someone calls EndTest. EndTest can be called on any
65 // thread, but be aware that ending the test is an asynchronous process.
66 class LayerTreeTest : public testing::Test, public TestHooks {
67  public:
TestTypeToString()68   std::string TestTypeToString() {
69     switch (renderer_type_) {
70       case viz::RendererType::kGL:
71         return "GL";
72       case viz::RendererType::kSkiaGL:
73         return "Skia GL";
74       case viz::RendererType::kSkiaVk:
75         return "Skia Vulkan";
76       case viz::RendererType::kSkiaDawn:
77         return "Skia Dawn";
78       case viz::RendererType::kSoftware:
79         return "Software";
80     }
81   }
82 
83   ~LayerTreeTest() override;
84 
85   virtual void EndTest();
86   void EndTestAfterDelayMs(int delay_milliseconds);
87 
88   void PostAddNoDamageAnimationToMainThread(
89       Animation* animation_to_receive_animation);
90   void PostAddOpacityAnimationToMainThread(
91       Animation* animation_to_receive_animation);
92   void PostAddOpacityAnimationToMainThreadInstantly(
93       Animation* animation_to_receive_animation);
94   void PostAddOpacityAnimationToMainThreadDelayed(
95       Animation* animation_to_receive_animation);
96   void PostSetLocalSurfaceIdToMainThread(
97       const viz::LocalSurfaceId& local_surface_id);
98   void PostRequestNewLocalSurfaceIdToMainThread();
99   void PostGetDeferMainFrameUpdateToMainThread(
100       std::unique_ptr<ScopedDeferMainFrameUpdate>*
101           scoped_defer_main_frame_update);
102   void PostReturnDeferMainFrameUpdateToMainThread(
103       std::unique_ptr<ScopedDeferMainFrameUpdate>
104           scoped_defer_main_frame_update);
105   void PostSetNeedsCommitToMainThread();
106   void PostSetNeedsUpdateLayersToMainThread();
107   void PostSetNeedsRedrawToMainThread();
108   void PostSetNeedsRedrawRectToMainThread(const gfx::Rect& damage_rect);
109   void PostSetVisibleToMainThread(bool visible);
110   void PostSetNeedsCommitWithForcedRedrawToMainThread();
111   void PostCompositeImmediatelyToMainThread();
112   void PostNextCommitWaitsForActivationToMainThread();
113 
114   void DoBeginTest();
115   void Timeout();
116 
animation_host()117   AnimationHost* animation_host() const { return animation_host_.get(); }
118 
SetUseLayerLists()119   void SetUseLayerLists() { settings_.use_layer_lists = true; }
120 
121  protected:
122   explicit LayerTreeTest(
123       viz::RendererType renderer_type = viz::RendererType::kGL);
124 
125   void SkipAllocateInitialLocalSurfaceId();
126   const viz::LocalSurfaceId& GetCurrentLocalSurfaceId() const;
127   void GenerateNewLocalSurfaceId();
128 
InitializeSettings(LayerTreeSettings * settings)129   virtual void InitializeSettings(LayerTreeSettings* settings) {}
130 
131   void RealEndTest();
132 
133   std::unique_ptr<LayerTreeFrameSink>
134   ReleaseLayerTreeFrameSinkOnLayerTreeHost();
135   void SetVisibleOnLayerTreeHost(bool visible);
SetInitialDeviceScaleFactor(float initial_device_scale_factor)136   void SetInitialDeviceScaleFactor(float initial_device_scale_factor) {
137     initial_device_scale_factor_ = initial_device_scale_factor;
138   }
139   // Used when LayerTreeTest::SetupTree() creates the root layer. Not used if
140   // the root layer is created before LayerTreeTest::SetupTree() is called.
141   // The default is 1x1.
SetInitialRootBounds(const gfx::Size & bounds)142   void SetInitialRootBounds(const gfx::Size& bounds) {
143     initial_root_bounds_ = bounds;
144   }
145 
AfterTest()146   virtual void AfterTest() {}
147   virtual void WillBeginTest();
148   virtual void BeginTest() = 0;
149   virtual void SetupTree();
150 
151   virtual void RunTest(CompositorMode mode);
152 
HasImplThread()153   bool HasImplThread() const { return !!impl_thread_; }
ImplThreadTaskRunner()154   base::SingleThreadTaskRunner* ImplThreadTaskRunner() {
155     return impl_task_runner_.get();
156   }
MainThreadTaskRunner()157   base::SingleThreadTaskRunner* MainThreadTaskRunner() const {
158     return main_task_runner_.get();
159   }
160   Proxy* proxy();
161   TaskRunnerProvider* task_runner_provider() const;
task_graph_runner()162   TaskGraphRunner* task_graph_runner() const {
163     return task_graph_runner_.get();
164   }
TestEnded()165   bool TestEnded() const {
166     base::AutoLock hold(test_ended_lock_);
167     return ended_;
168   }
169 
170   LayerTreeHost* layer_tree_host() const;
gpu_memory_buffer_manager()171   gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager() {
172     return gpu_memory_buffer_manager_.get();
173   }
174 
175   void DestroyLayerTreeHost();
176 
177   // By default, output surface recreation is synchronous.
178   void RequestNewLayerTreeFrameSink() override;
179   // Override this to modify the TestContextProviders before they are bound
180   // and used. Override CreateLayerTreeFrameSink() instead if the test does not
181   // want to use TestContextProviders.
182   virtual void SetUpUnboundContextProviders(
183       viz::TestContextProvider* context_provider,
184       viz::TestContextProvider* worker_context_provider);
185   // Override this and call the base class to change what viz::ContextProviders
186   // will be used (such as for pixel tests). Or override it and create your own
187   // TestLayerTreeFrameSink to control how it is created.
188   virtual std::unique_ptr<TestLayerTreeFrameSink> CreateLayerTreeFrameSink(
189       const viz::RendererSettings& renderer_settings,
190       double refresh_rate,
191       scoped_refptr<viz::ContextProvider> compositor_context_provider,
192       scoped_refptr<viz::RasterContextProvider> worker_context_provider);
193   std::unique_ptr<viz::DisplayCompositorMemoryAndTaskController>
194   CreateDisplayControllerOnThread() override;
195   std::unique_ptr<viz::SkiaOutputSurface>
196   CreateDisplaySkiaOutputSurfaceOnThread(
197       viz::DisplayCompositorMemoryAndTaskController*) override;
198   // Override this and call the base class to change what viz::ContextProvider
199   // will be used, such as to prevent sharing the context with the
200   // LayerTreeFrameSink. Or override it and create your own OutputSurface to
201   // change what type of OutputSurface is used, such as a real OutputSurface for
202   // pixel tests or a software-compositing OutputSurface.
203   std::unique_ptr<viz::OutputSurface> CreateDisplayOutputSurfaceOnThread(
204       scoped_refptr<viz::ContextProvider> compositor_context_provider) override;
205 
image_worker_task_runner()206   base::SingleThreadTaskRunner* image_worker_task_runner() const {
207     return image_worker_->task_runner().get();
208   }
209 
UseBeginFrameSource(viz::BeginFrameSource * begin_frame_source)210   void UseBeginFrameSource(viz::BeginFrameSource* begin_frame_source) {
211     begin_frame_source_ = begin_frame_source;
212   }
213 
use_skia_renderer()214   bool use_skia_renderer() const {
215     return renderer_type_ == viz::RendererType::kSkiaGL ||
216            renderer_type_ == viz::RendererType::kSkiaVk ||
217            renderer_type_ == viz::RendererType::kSkiaDawn;
218   }
use_software_renderer()219   bool use_software_renderer() const {
220     return renderer_type_ == viz::RendererType::kSoftware;
221   }
use_skia_vulkan()222   bool use_skia_vulkan() const {
223     return renderer_type_ == viz::RendererType::kSkiaVk;
224   }
use_d3d12()225   bool use_d3d12() const {
226 #if defined(OS_WIN)
227     return renderer_type_ == viz::RendererType::kSkiaDawn;
228 #else
229     return false;
230 #endif
231   }
232 
233   const viz::RendererType renderer_type_;
234 
235   const viz::DebugRendererSettings debug_settings_;
236 
237  private:
238   virtual void DispatchAddNoDamageAnimation(
239       Animation* animation_to_receive_animation,
240       double animation_duration);
241   virtual void DispatchAddOpacityAnimation(
242       Animation* animation_to_receive_animation,
243       double animation_duration);
244   void DispatchSetLocalSurfaceId(const viz::LocalSurfaceId& local_surface_id);
245   void DispatchRequestNewLocalSurfaceId();
246   void DispatchGetDeferMainFrameUpdate(
247       std::unique_ptr<ScopedDeferMainFrameUpdate>*
248           scoped_defer_main_frame_update);
249   void DispatchReturnDeferMainFrameUpdate(
250       std::unique_ptr<ScopedDeferMainFrameUpdate>
251           scoped_defer_main_frame_update);
252   void DispatchSetNeedsCommit();
253   void DispatchSetNeedsUpdateLayers();
254   void DispatchSetNeedsRedraw();
255   void DispatchSetNeedsRedrawRect(const gfx::Rect& damage_rect);
256   void DispatchSetVisible(bool visible);
257   void DispatchSetNeedsCommitWithForcedRedraw();
258   void DispatchDidAddAnimation();
259   void DispatchCompositeImmediately();
260   void DispatchNextCommitWaitsForActivation();
261 
262   // |scoped_feature_list_| must be the first member to ensure that it is
263   // destroyed after any member that might be using it.
264   base::test::ScopedFeatureList scoped_feature_list_;
265   viz::TestGpuServiceHolder::ScopedResetter gpu_service_resetter_;
266 
267   LayerTreeSettings settings_;
268   float initial_device_scale_factor_ = 1.f;
269   gfx::Size initial_root_bounds_;
270 
271   CompositorMode mode_;
272 
273   std::unique_ptr<LayerTreeHostClientForTesting> client_;
274   std::unique_ptr<LayerTreeHost> layer_tree_host_;
275   std::unique_ptr<AnimationHost> animation_host_;
276 
277   bool beginning_ = false;
278   bool end_when_begin_returns_ = false;
279   bool timed_out_ = false;
280   bool scheduled_ = false;
281   bool started_ = false;
282 
283   mutable base::Lock test_ended_lock_;
284   bool ended_ = false;
285 
286   int timeout_seconds_ = 0;
287 
288   viz::BeginFrameSource* begin_frame_source_ = nullptr;  // NOT OWNED.
289 
290   std::unique_ptr<LayerTreeTestLayerTreeFrameSinkClient>
291       layer_tree_frame_sink_client_;
292   scoped_refptr<base::SingleThreadTaskRunner> main_task_runner_;
293   scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner_;
294   std::unique_ptr<base::Thread> impl_thread_;
295   std::unique_ptr<base::Thread> image_worker_;
296   std::unique_ptr<viz::TestGpuMemoryBufferManager> gpu_memory_buffer_manager_;
297   std::unique_ptr<TestTaskGraphRunner> task_graph_runner_;
298   base::CancelableOnceClosure timeout_;
299   scoped_refptr<viz::TestContextProvider> compositor_contexts_;
300   bool skip_allocate_initial_local_surface_id_ = false;
301   viz::ParentLocalSurfaceIdAllocator allocator_;
302   base::WeakPtr<LayerTreeTest> main_thread_weak_ptr_;
303   base::WeakPtrFactory<LayerTreeTest> weak_factory_{this};
304 };
305 
306 }  // namespace cc
307 
308 // Do not change this macro to disable a test, it will disable half of
309 // the unit test suite. Instead, comment out the usage of this macro for
310 // a specific test name. eg.
311 // // TODO(crbug.com/abcd): Disabled for some reasons stated here.
312 // // SINGLE_AND_MULTI_THREAD_TEST_F(SomeRandomTest)
313 #define SINGLE_THREAD_TEST_F(TEST_FIXTURE_NAME)                                \
314   TEST_F(TEST_FIXTURE_NAME, RunSingleThread_DelegatingRenderer) {              \
315     RunTest(CompositorMode::SINGLE_THREADED);                                  \
316   }                                                                            \
317   TEST_F(TEST_FIXTURE_NAME, RunSingleThread_DelegatingRendererUnifiedScroll) { \
318     base::test::ScopedFeatureList scoped_feature_list;                         \
319     scoped_feature_list.InitAndEnableFeature(features::kScrollUnification);    \
320     RunTest(CompositorMode::SINGLE_THREADED);                                  \
321   }                                                                            \
322   class SingleThreadDelegatingImplNeedsSemicolon##TEST_FIXTURE_NAME {}
323 
324 // Do not change this macro to disable a test, it will disable half of
325 // the unit test suite. Instead, comment out the usage of this macro for
326 // a specific test name. eg.
327 // // TODO(crbug.com/abcd): Disabled for some reasons stated here.
328 // // SINGLE_AND_MULTI_THREAD_TEST_F(SomeRandomTest)
329 #define MULTI_THREAD_TEST_F(TEST_FIXTURE_NAME)                                \
330   TEST_F(TEST_FIXTURE_NAME, RunMultiThread_DelegatingRenderer) {              \
331     RunTest(CompositorMode::THREADED);                                        \
332   }                                                                           \
333   TEST_F(TEST_FIXTURE_NAME, RunMultiThread_DelegatingRendererUnifiedScroll) { \
334     base::test::ScopedFeatureList scoped_feature_list;                        \
335     scoped_feature_list.InitAndEnableFeature(features::kScrollUnification);   \
336     RunTest(CompositorMode::THREADED);                                        \
337   }                                                                           \
338   class MultiThreadDelegatingImplNeedsSemicolon##TEST_FIXTURE_NAME {}
339 
340 // Do not change this macro to disable a test, it will disable half of
341 // the unit test suite. Instead, comment out the usage of this macro for
342 // a specific test name. eg.
343 // // TODO(crbug.com/abcd): Disabled for some reasons stated here.
344 // // SINGLE_AND_MULTI_THREAD_TEST_F(SomeRandomTest)
345 #define SINGLE_AND_MULTI_THREAD_TEST_F(TEST_FIXTURE_NAME) \
346   SINGLE_THREAD_TEST_F(TEST_FIXTURE_NAME);                \
347   MULTI_THREAD_TEST_F(TEST_FIXTURE_NAME)
348 
349 // Some tests want to control when notify ready for activation occurs,
350 // but this is not supported in the single-threaded case.
351 //
352 // Do not change this macro to disable a test, it will disable half of
353 // the unit test suite. Instead, comment out the usage of this macro for
354 // a specific test name. eg.
355 // // TODO(crbug.com/abcd): Disabled for some reasons stated here.
356 // // MULTI_THREAD_BLOCKNOTIFY_TEST_F(SomeRandomTest)
357 #define MULTI_THREAD_BLOCKNOTIFY_TEST_F(TEST_FIXTURE_NAME) \
358   MULTI_THREAD_TEST_F(TEST_FIXTURE_NAME)
359 
360 #endif  // CC_TEST_LAYER_TREE_TEST_H_
361