[M108 Migration][VD] Avoid pending frame counter becoming negative
[platform/framework/web/chromium-efl.git] / cc / tiles / tile_manager_unittest.cc
1 // Copyright 2013 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include <stddef.h>
6 #include <stdint.h>
7
8 #include <utility>
9
10 #include "base/bind.h"
11 #include "base/callback.h"
12 #include "base/callback_helpers.h"
13 #include "base/containers/contains.h"
14 #include "base/memory/raw_ptr.h"
15 #include "base/run_loop.h"
16 #include "base/test/test_simple_task_runner.h"
17 #include "base/threading/thread_task_runner_handle.h"
18 #include "base/trace_event/process_memory_dump.h"
19 #include "cc/layers/recording_source.h"
20 #include "cc/raster/raster_buffer.h"
21 #include "cc/raster/raster_source.h"
22 #include "cc/raster/synchronous_task_graph_runner.h"
23 #include "cc/resources/resource_pool.h"
24 #include "cc/test/fake_impl_task_runner_provider.h"
25 #include "cc/test/fake_layer_tree_frame_sink.h"
26 #include "cc/test/fake_layer_tree_frame_sink_client.h"
27 #include "cc/test/fake_layer_tree_host_impl.h"
28 #include "cc/test/fake_paint_image_generator.h"
29 #include "cc/test/fake_picture_layer_impl.h"
30 #include "cc/test/fake_picture_layer_tiling_client.h"
31 #include "cc/test/fake_raster_query_queue.h"
32 #include "cc/test/fake_raster_source.h"
33 #include "cc/test/fake_recording_source.h"
34 #include "cc/test/fake_tile_manager.h"
35 #include "cc/test/fake_tile_task_manager.h"
36 #include "cc/test/layer_test_common.h"
37 #include "cc/test/skia_common.h"
38 #include "cc/test/test_layer_tree_host_base.h"
39 #include "cc/test/test_task_graph_runner.h"
40 #include "cc/test/test_tile_priorities.h"
41 #include "cc/tiles/eviction_tile_priority_queue.h"
42 #include "cc/tiles/raster_tile_priority_queue.h"
43 #include "cc/tiles/tile.h"
44 #include "cc/tiles/tile_priority.h"
45 #include "cc/tiles/tiling_set_raster_queue_all.h"
46 #include "cc/trees/layer_tree_impl.h"
47 #include "components/viz/common/resources/resource_sizes.h"
48 #include "components/viz/test/begin_frame_args_test.h"
49 #include "testing/gmock/include/gmock/gmock.h"
50 #include "testing/gtest/include/gtest/gtest.h"
51 #include "third_party/skia/include/core/SkImageGenerator.h"
52 #include "third_party/skia/include/core/SkRefCnt.h"
53 #include "third_party/skia/include/core/SkSurface.h"
54
55 using testing::_;
56 using testing::Invoke;
57 using testing::Return;
58 using testing::StrictMock;
59
60 namespace cc {
61 namespace {
62
63 // A version of simple task runner that lets the user control if all tasks
64 // posted should run synchronously.
65 class SynchronousSimpleTaskRunner : public base::TestSimpleTaskRunner {
66  public:
67   bool PostDelayedTask(const base::Location& from_here,
68                        base::OnceClosure task,
69                        base::TimeDelta delay) override {
70     TestSimpleTaskRunner::PostDelayedTask(from_here, std::move(task), delay);
71     if (run_tasks_synchronously_)
72       RunUntilIdle();
73     return true;
74   }
75
76   bool PostNonNestableDelayedTask(const base::Location& from_here,
77                                   base::OnceClosure task,
78                                   base::TimeDelta delay) override {
79     return PostDelayedTask(from_here, std::move(task), delay);
80   }
81
82   void set_run_tasks_synchronously(bool run_tasks_synchronously) {
83     run_tasks_synchronously_ = run_tasks_synchronously;
84   }
85
86  protected:
87   ~SynchronousSimpleTaskRunner() override = default;
88
89   bool run_tasks_synchronously_ = false;
90 };
91
92 class FakeRasterBuffer : public RasterBuffer {
93  public:
94   void Playback(const RasterSource* raster_source,
95                 const gfx::Rect& raster_full_rect,
96                 const gfx::Rect& raster_dirty_rect,
97                 uint64_t new_content_id,
98                 const gfx::AxisTransform2d& transform,
99                 const RasterSource::PlaybackSettings& playback_settings,
100                 const GURL& url) override {}
101
102   bool SupportsBackgroundThreadPriority() const override { return true; }
103 };
104
105 class TileManagerTilePriorityQueueTest : public TestLayerTreeHostBase {
106  public:
107   LayerTreeSettings CreateSettings() override {
108     auto settings = TestLayerTreeHostBase::CreateSettings();
109     settings.create_low_res_tiling = true;
110     return settings;
111   }
112
113   TileManager* tile_manager() { return host_impl()->tile_manager(); }
114
115   class StubGpuBacking : public ResourcePool::GpuBacking {
116    public:
117     void OnMemoryDump(
118         base::trace_event::ProcessMemoryDump* pmd,
119         const base::trace_event::MemoryAllocatorDumpGuid& buffer_dump_guid,
120         uint64_t tracing_process_id,
121         int importance) const override {}
122   };
123 };
124
125 TEST_F(TileManagerTilePriorityQueueTest, RasterTilePriorityQueue) {
126   const gfx::Size layer_bounds(1000, 1000);
127   host_impl()->active_tree()->SetDeviceViewportRect(gfx::Rect(layer_bounds));
128   SetupDefaultTrees(layer_bounds);
129
130   std::unique_ptr<RasterTilePriorityQueue> queue(host_impl()->BuildRasterQueue(
131       SAME_PRIORITY_FOR_BOTH_TREES, RasterTilePriorityQueue::Type::ALL));
132   EXPECT_FALSE(queue->IsEmpty());
133
134   size_t tile_count = 0;
135   std::set<Tile*> all_tiles;
136   while (!queue->IsEmpty()) {
137     EXPECT_TRUE(queue->Top().tile());
138     all_tiles.insert(queue->Top().tile());
139     ++tile_count;
140     queue->Pop();
141   }
142
143   EXPECT_EQ(tile_count, all_tiles.size());
144   EXPECT_EQ(16u, tile_count);
145
146   // Sanity check, all tiles should be visible.
147   std::set<Tile*> smoothness_tiles;
148   queue = host_impl()->BuildRasterQueue(SMOOTHNESS_TAKES_PRIORITY,
149                                         RasterTilePriorityQueue::Type::ALL);
150   bool had_low_res = false;
151   while (!queue->IsEmpty()) {
152     PrioritizedTile prioritized_tile = queue->Top();
153     EXPECT_TRUE(prioritized_tile.tile());
154     EXPECT_EQ(TilePriority::NOW, prioritized_tile.priority().priority_bin);
155     if (prioritized_tile.priority().resolution == LOW_RESOLUTION)
156       had_low_res = true;
157     else
158       smoothness_tiles.insert(prioritized_tile.tile());
159     queue->Pop();
160   }
161   EXPECT_EQ(all_tiles, smoothness_tiles);
162   EXPECT_TRUE(had_low_res);
163
164   // Check that everything is required for activation.
165   queue = host_impl()->BuildRasterQueue(
166       SMOOTHNESS_TAKES_PRIORITY,
167       RasterTilePriorityQueue::Type::REQUIRED_FOR_ACTIVATION);
168   std::set<Tile*> required_for_activation_tiles;
169   while (!queue->IsEmpty()) {
170     PrioritizedTile prioritized_tile = queue->Top();
171     EXPECT_TRUE(prioritized_tile.tile()->required_for_activation());
172     required_for_activation_tiles.insert(prioritized_tile.tile());
173     queue->Pop();
174   }
175   EXPECT_EQ(all_tiles, required_for_activation_tiles);
176
177   // Check that everything is required for draw.
178   queue = host_impl()->BuildRasterQueue(
179       SMOOTHNESS_TAKES_PRIORITY,
180       RasterTilePriorityQueue::Type::REQUIRED_FOR_DRAW);
181   std::set<Tile*> required_for_draw_tiles;
182   while (!queue->IsEmpty()) {
183     PrioritizedTile prioritized_tile = queue->Top();
184     EXPECT_TRUE(prioritized_tile.tile()->required_for_draw());
185     required_for_draw_tiles.insert(prioritized_tile.tile());
186     queue->Pop();
187   }
188   EXPECT_EQ(all_tiles, required_for_draw_tiles);
189
190   Region invalidation(gfx::Rect(0, 0, 500, 500));
191
192   // Invalidate the pending tree.
193   pending_layer()->set_invalidation(invalidation);
194   pending_layer()->HighResTiling()->Invalidate(invalidation);
195
196   // Renew all of the tile priorities.
197   gfx::Rect viewport(50, 50, 100, 100);
198   pending_layer()->picture_layer_tiling_set()->UpdateTilePriorities(
199       viewport, 1.0f, 1.0, Occlusion(), true);
200   active_layer()->picture_layer_tiling_set()->UpdateTilePriorities(
201       viewport, 1.0f, 1.0, Occlusion(), true);
202
203   // Populate all tiles directly from the tilings.
204   all_tiles.clear();
205   std::set<Tile*> high_res_tiles;
206   std::vector<Tile*> pending_high_res_tiles =
207       pending_layer()->HighResTiling()->AllTilesForTesting();
208   for (size_t i = 0; i < pending_high_res_tiles.size(); ++i) {
209     all_tiles.insert(pending_high_res_tiles[i]);
210     high_res_tiles.insert(pending_high_res_tiles[i]);
211   }
212
213   std::vector<Tile*> active_high_res_tiles =
214       active_layer()->HighResTiling()->AllTilesForTesting();
215   for (size_t i = 0; i < active_high_res_tiles.size(); ++i) {
216     all_tiles.insert(active_high_res_tiles[i]);
217     high_res_tiles.insert(active_high_res_tiles[i]);
218   }
219
220   std::vector<Tile*> active_low_res_tiles =
221       active_layer()->LowResTiling()->AllTilesForTesting();
222   for (size_t i = 0; i < active_low_res_tiles.size(); ++i)
223     all_tiles.insert(active_low_res_tiles[i]);
224
225   PrioritizedTile last_tile;
226   smoothness_tiles.clear();
227   tile_count = 0;
228   size_t correct_order_tiles = 0u;
229   // Here we expect to get increasing ACTIVE_TREE priority_bin.
230   queue = host_impl()->BuildRasterQueue(SMOOTHNESS_TAKES_PRIORITY,
231                                         RasterTilePriorityQueue::Type::ALL);
232   std::set<Tile*> expected_required_for_draw_tiles;
233   std::set<Tile*> expected_required_for_activation_tiles;
234   while (!queue->IsEmpty()) {
235     PrioritizedTile prioritized_tile = queue->Top();
236     EXPECT_TRUE(prioritized_tile.tile());
237
238     if (!last_tile.tile())
239       last_tile = prioritized_tile;
240
241     EXPECT_LE(last_tile.priority().priority_bin,
242               prioritized_tile.priority().priority_bin);
243     bool skip_updating_last_tile = false;
244     if (last_tile.priority().priority_bin ==
245         prioritized_tile.priority().priority_bin) {
246       correct_order_tiles += last_tile.priority().distance_to_visible <=
247                              prioritized_tile.priority().distance_to_visible;
248     } else if (prioritized_tile.priority().priority_bin == TilePriority::NOW) {
249       // Since we'd return pending tree now tiles before the eventually tiles on
250       // the active tree, update the value.
251       ++correct_order_tiles;
252       skip_updating_last_tile = true;
253     }
254
255     if (prioritized_tile.priority().priority_bin == TilePriority::NOW &&
256         last_tile.priority().resolution !=
257             prioritized_tile.priority().resolution) {
258       // Low resolution should come first.
259       EXPECT_EQ(LOW_RESOLUTION, last_tile.priority().resolution);
260     }
261
262     if (!skip_updating_last_tile)
263       last_tile = prioritized_tile;
264     ++tile_count;
265     smoothness_tiles.insert(prioritized_tile.tile());
266     if (prioritized_tile.tile()->required_for_draw())
267       expected_required_for_draw_tiles.insert(prioritized_tile.tile());
268     if (prioritized_tile.tile()->required_for_activation())
269       expected_required_for_activation_tiles.insert(prioritized_tile.tile());
270     queue->Pop();
271   }
272
273   EXPECT_EQ(tile_count, smoothness_tiles.size());
274   EXPECT_EQ(all_tiles, smoothness_tiles);
275   // Since we don't guarantee increasing distance due to spiral iterator, we
276   // should check that we're _mostly_ right.
277   EXPECT_GT(correct_order_tiles, 3 * tile_count / 4);
278
279   // Check that we have consistent required_for_activation tiles.
280   queue = host_impl()->BuildRasterQueue(
281       SMOOTHNESS_TAKES_PRIORITY,
282       RasterTilePriorityQueue::Type::REQUIRED_FOR_ACTIVATION);
283   required_for_activation_tiles.clear();
284   while (!queue->IsEmpty()) {
285     PrioritizedTile prioritized_tile = queue->Top();
286     EXPECT_TRUE(prioritized_tile.tile()->required_for_activation());
287     required_for_activation_tiles.insert(prioritized_tile.tile());
288     queue->Pop();
289   }
290   EXPECT_EQ(expected_required_for_activation_tiles,
291             required_for_activation_tiles);
292   EXPECT_NE(all_tiles, required_for_activation_tiles);
293
294   // Check that we have consistent required_for_draw tiles.
295   queue = host_impl()->BuildRasterQueue(
296       SMOOTHNESS_TAKES_PRIORITY,
297       RasterTilePriorityQueue::Type::REQUIRED_FOR_DRAW);
298   required_for_draw_tiles.clear();
299   while (!queue->IsEmpty()) {
300     PrioritizedTile prioritized_tile = queue->Top();
301     EXPECT_TRUE(prioritized_tile.tile()->required_for_draw());
302     required_for_draw_tiles.insert(prioritized_tile.tile());
303     queue->Pop();
304   }
305   EXPECT_EQ(expected_required_for_draw_tiles, required_for_draw_tiles);
306   EXPECT_NE(all_tiles, required_for_draw_tiles);
307
308   std::set<Tile*> new_content_tiles;
309   last_tile = PrioritizedTile();
310   size_t increasing_distance_tiles = 0u;
311   // Here we expect to get increasing PENDING_TREE priority_bin.
312   queue = host_impl()->BuildRasterQueue(NEW_CONTENT_TAKES_PRIORITY,
313                                         RasterTilePriorityQueue::Type::ALL);
314   tile_count = 0;
315   while (!queue->IsEmpty()) {
316     PrioritizedTile prioritized_tile = queue->Top();
317     EXPECT_TRUE(prioritized_tile.tile());
318
319     if (!last_tile.tile())
320       last_tile = prioritized_tile;
321
322     EXPECT_LE(last_tile.priority().priority_bin,
323               prioritized_tile.priority().priority_bin);
324     if (last_tile.priority().priority_bin ==
325         prioritized_tile.priority().priority_bin) {
326       increasing_distance_tiles +=
327           last_tile.priority().distance_to_visible <=
328           prioritized_tile.priority().distance_to_visible;
329     }
330
331     if (prioritized_tile.priority().priority_bin == TilePriority::NOW &&
332         last_tile.priority().resolution !=
333             prioritized_tile.priority().resolution) {
334       // High resolution should come first.
335       EXPECT_EQ(HIGH_RESOLUTION, last_tile.priority().resolution);
336     }
337
338     last_tile = prioritized_tile;
339     new_content_tiles.insert(prioritized_tile.tile());
340     ++tile_count;
341     queue->Pop();
342   }
343
344   EXPECT_EQ(tile_count, new_content_tiles.size());
345   EXPECT_EQ(high_res_tiles, new_content_tiles);
346   // Since we don't guarantee increasing distance due to spiral iterator, we
347   // should check that we're _mostly_ right.
348   EXPECT_GE(increasing_distance_tiles, 3 * tile_count / 4);
349
350   // Check that we have consistent required_for_activation tiles.
351   queue = host_impl()->BuildRasterQueue(
352       NEW_CONTENT_TAKES_PRIORITY,
353       RasterTilePriorityQueue::Type::REQUIRED_FOR_ACTIVATION);
354   required_for_activation_tiles.clear();
355   while (!queue->IsEmpty()) {
356     PrioritizedTile prioritized_tile = queue->Top();
357     EXPECT_TRUE(prioritized_tile.tile()->required_for_activation());
358     required_for_activation_tiles.insert(prioritized_tile.tile());
359     queue->Pop();
360   }
361   EXPECT_EQ(expected_required_for_activation_tiles,
362             required_for_activation_tiles);
363   EXPECT_NE(new_content_tiles, required_for_activation_tiles);
364
365   // Check that we have consistent required_for_draw tiles.
366   queue = host_impl()->BuildRasterQueue(
367       NEW_CONTENT_TAKES_PRIORITY,
368       RasterTilePriorityQueue::Type::REQUIRED_FOR_DRAW);
369   required_for_draw_tiles.clear();
370   while (!queue->IsEmpty()) {
371     PrioritizedTile prioritized_tile = queue->Top();
372     EXPECT_TRUE(prioritized_tile.tile()->required_for_draw());
373     required_for_draw_tiles.insert(prioritized_tile.tile());
374     queue->Pop();
375   }
376   EXPECT_EQ(expected_required_for_draw_tiles, required_for_draw_tiles);
377   EXPECT_NE(new_content_tiles, required_for_draw_tiles);
378 }
379
380 TEST_F(TileManagerTilePriorityQueueTest,
381        RasterTilePriorityQueueHighNonIdealTilings) {
382   const gfx::Size layer_bounds(1000, 1000);
383   const gfx::Size viewport(800, 800);
384   host_impl()->active_tree()->SetDeviceViewportRect(gfx::Rect(viewport));
385   SetupDefaultTrees(layer_bounds);
386
387   pending_layer()->tilings()->AddTiling(
388       gfx::AxisTransform2d(1.5f, gfx::Vector2dF()),
389       pending_layer()->raster_source());
390   active_layer()->tilings()->AddTiling(
391       gfx::AxisTransform2d(1.5f, gfx::Vector2dF()),
392       active_layer()->raster_source());
393   pending_layer()->tilings()->AddTiling(
394       gfx::AxisTransform2d(1.7f, gfx::Vector2dF()),
395       pending_layer()->raster_source());
396   active_layer()->tilings()->AddTiling(
397       gfx::AxisTransform2d(1.7f, gfx::Vector2dF()),
398       active_layer()->raster_source());
399
400   pending_layer()->tilings()->UpdateTilePriorities(gfx::Rect(viewport), 1.f,
401                                                    5.0, Occlusion(), true);
402   active_layer()->tilings()->UpdateTilePriorities(gfx::Rect(viewport), 1.f, 5.0,
403                                                   Occlusion(), true);
404
405   std::set<Tile*> all_expected_tiles;
406   for (size_t i = 0; i < pending_layer()->num_tilings(); ++i) {
407     PictureLayerTiling* tiling = pending_layer()->tilings()->tiling_at(i);
408     if (tiling->contents_scale_key() == 1.f) {
409       tiling->set_resolution(HIGH_RESOLUTION);
410       const auto& all_tiles = tiling->AllTilesForTesting();
411       all_expected_tiles.insert(all_tiles.begin(), all_tiles.end());
412     } else {
413       tiling->set_resolution(NON_IDEAL_RESOLUTION);
414     }
415   }
416
417   for (size_t i = 0; i < active_layer()->num_tilings(); ++i) {
418     PictureLayerTiling* tiling = active_layer()->tilings()->tiling_at(i);
419     if (tiling->contents_scale_key() == 1.5f) {
420       tiling->set_resolution(HIGH_RESOLUTION);
421       const auto& all_tiles = tiling->AllTilesForTesting();
422       all_expected_tiles.insert(all_tiles.begin(), all_tiles.end());
423     } else {
424       tiling->set_resolution(NON_IDEAL_RESOLUTION);
425       // Non ideal tilings with a high res pending twin have to be processed
426       // because of possible activation tiles.
427       if (tiling->contents_scale_key() == 1.f) {
428         tiling->UpdateAndGetAllPrioritizedTilesForTesting();
429         const auto& all_tiles = tiling->AllTilesForTesting();
430         for (auto* tile : all_tiles)
431           EXPECT_TRUE(tile->required_for_activation());
432         all_expected_tiles.insert(all_tiles.begin(), all_tiles.end());
433       }
434     }
435   }
436
437   std::unique_ptr<RasterTilePriorityQueue> queue(host_impl()->BuildRasterQueue(
438       SMOOTHNESS_TAKES_PRIORITY, RasterTilePriorityQueue::Type::ALL));
439   EXPECT_FALSE(queue->IsEmpty());
440
441   size_t tile_count = 0;
442   std::set<Tile*> all_actual_tiles;
443   while (!queue->IsEmpty()) {
444     EXPECT_TRUE(queue->Top().tile());
445     all_actual_tiles.insert(queue->Top().tile());
446     ++tile_count;
447     queue->Pop();
448   }
449
450   EXPECT_EQ(tile_count, all_actual_tiles.size());
451   EXPECT_EQ(all_expected_tiles.size(), all_actual_tiles.size());
452   EXPECT_EQ(all_expected_tiles, all_actual_tiles);
453 }
454
455 TEST_F(TileManagerTilePriorityQueueTest,
456        RasterTilePriorityQueueHighLowTilings) {
457   const gfx::Size layer_bounds(1000, 1000);
458   const gfx::Size viewport(800, 800);
459   host_impl()->active_tree()->SetDeviceViewportRect(gfx::Rect(viewport));
460   SetupDefaultTrees(layer_bounds);
461
462   pending_layer()->tilings()->AddTiling(
463       gfx::AxisTransform2d(1.5f, gfx::Vector2dF()),
464       pending_layer()->raster_source());
465   active_layer()->tilings()->AddTiling(
466       gfx::AxisTransform2d(1.5f, gfx::Vector2dF()),
467       active_layer()->raster_source());
468   pending_layer()->tilings()->AddTiling(
469       gfx::AxisTransform2d(1.7f, gfx::Vector2dF()),
470       pending_layer()->raster_source());
471   active_layer()->tilings()->AddTiling(
472       gfx::AxisTransform2d(1.7f, gfx::Vector2dF()),
473       active_layer()->raster_source());
474
475   pending_layer()->tilings()->UpdateTilePriorities(gfx::Rect(viewport), 1.f,
476                                                    5.0, Occlusion(), true);
477   active_layer()->tilings()->UpdateTilePriorities(gfx::Rect(viewport), 1.f, 5.0,
478                                                   Occlusion(), true);
479
480   std::set<Tile*> all_expected_tiles;
481   for (size_t i = 0; i < pending_layer()->num_tilings(); ++i) {
482     PictureLayerTiling* tiling = pending_layer()->tilings()->tiling_at(i);
483     if (tiling->contents_scale_key() == 1.f) {
484       tiling->set_resolution(HIGH_RESOLUTION);
485       const auto& all_tiles = tiling->AllTilesForTesting();
486       all_expected_tiles.insert(all_tiles.begin(), all_tiles.end());
487     } else {
488       tiling->set_resolution(NON_IDEAL_RESOLUTION);
489     }
490   }
491
492   for (size_t i = 0; i < active_layer()->num_tilings(); ++i) {
493     PictureLayerTiling* tiling = active_layer()->tilings()->tiling_at(i);
494     if (tiling->contents_scale_key() == 1.5f) {
495       tiling->set_resolution(HIGH_RESOLUTION);
496       const auto& all_tiles = tiling->AllTilesForTesting();
497       all_expected_tiles.insert(all_tiles.begin(), all_tiles.end());
498     } else {
499       tiling->set_resolution(LOW_RESOLUTION);
500       // Low res tilings with a high res pending twin have to be processed
501       // because of possible activation tiles.
502       if (tiling->contents_scale_key() == 1.f) {
503         tiling->UpdateAndGetAllPrioritizedTilesForTesting();
504         const auto& all_tiles = tiling->AllTilesForTesting();
505         for (auto* tile : all_tiles)
506           EXPECT_TRUE(tile->required_for_activation());
507         all_expected_tiles.insert(all_tiles.begin(), all_tiles.end());
508       }
509     }
510   }
511
512   std::unique_ptr<RasterTilePriorityQueue> queue(host_impl()->BuildRasterQueue(
513       SAME_PRIORITY_FOR_BOTH_TREES, RasterTilePriorityQueue::Type::ALL));
514   EXPECT_FALSE(queue->IsEmpty());
515
516   size_t tile_count = 0;
517   std::set<Tile*> all_actual_tiles;
518   while (!queue->IsEmpty()) {
519     EXPECT_TRUE(queue->Top().tile());
520     all_actual_tiles.insert(queue->Top().tile());
521     ++tile_count;
522     queue->Pop();
523   }
524
525   EXPECT_EQ(tile_count, all_actual_tiles.size());
526   EXPECT_EQ(all_expected_tiles.size(), all_actual_tiles.size());
527   EXPECT_EQ(all_expected_tiles, all_actual_tiles);
528 }
529
530 TEST_F(TileManagerTilePriorityQueueTest, RasterTilePriorityQueueInvalidation) {
531   const gfx::Size layer_bounds(1000, 1000);
532   host_impl()->active_tree()->SetDeviceViewportRect(gfx::Rect(500, 500));
533   SetupDefaultTrees(layer_bounds);
534
535   // Use a tile's content rect as an invalidation. We should inset it a bit to
536   // ensure that border math doesn't invalidate neighbouring tiles.
537   gfx::Rect invalidation =
538       active_layer()->HighResTiling()->TileAt(1, 0)->content_rect();
539   invalidation.Inset(2);
540
541   pending_layer()->set_invalidation(invalidation);
542   pending_layer()->HighResTiling()->Invalidate(invalidation);
543   pending_layer()->HighResTiling()->CreateMissingTilesInLiveTilesRect();
544
545   // Sanity checks: Tile at 0, 0 not exist on the pending tree (it's not
546   // invalidated). Tile 1, 0 should exist on both.
547   EXPECT_FALSE(pending_layer()->HighResTiling()->TileAt(0, 0));
548   EXPECT_TRUE(active_layer()->HighResTiling()->TileAt(0, 0));
549   EXPECT_TRUE(pending_layer()->HighResTiling()->TileAt(1, 0));
550   EXPECT_TRUE(active_layer()->HighResTiling()->TileAt(1, 0));
551   EXPECT_NE(pending_layer()->HighResTiling()->TileAt(1, 0),
552             active_layer()->HighResTiling()->TileAt(1, 0));
553
554   std::set<Tile*> expected_now_tiles;
555   std::set<Tile*> expected_required_for_draw_tiles;
556   std::set<Tile*> expected_required_for_activation_tiles;
557   for (int i = 0; i <= 1; ++i) {
558     for (int j = 0; j <= 1; ++j) {
559       bool have_pending_tile = false;
560       if (pending_layer()->HighResTiling()->TileAt(i, j)) {
561         expected_now_tiles.insert(
562             pending_layer()->HighResTiling()->TileAt(i, j));
563         expected_required_for_activation_tiles.insert(
564             pending_layer()->HighResTiling()->TileAt(i, j));
565         have_pending_tile = true;
566       }
567       Tile* active_tile = active_layer()->HighResTiling()->TileAt(i, j);
568       EXPECT_TRUE(active_tile);
569       expected_now_tiles.insert(active_tile);
570       expected_required_for_draw_tiles.insert(active_tile);
571       if (!have_pending_tile)
572         expected_required_for_activation_tiles.insert(active_tile);
573     }
574   }
575   // Expect 3 shared tiles and 1 unshared tile in total.
576   EXPECT_EQ(5u, expected_now_tiles.size());
577   // Expect 4 tiles for each draw and activation, but not all the same.
578   EXPECT_EQ(4u, expected_required_for_activation_tiles.size());
579   EXPECT_EQ(4u, expected_required_for_draw_tiles.size());
580   EXPECT_NE(expected_required_for_draw_tiles,
581             expected_required_for_activation_tiles);
582
583   std::set<Tile*> expected_all_tiles;
584   for (int i = 0; i <= 3; ++i) {
585     for (int j = 0; j <= 3; ++j) {
586       if (pending_layer()->HighResTiling()->TileAt(i, j))
587         expected_all_tiles.insert(
588             pending_layer()->HighResTiling()->TileAt(i, j));
589       EXPECT_TRUE(active_layer()->HighResTiling()->TileAt(i, j));
590       expected_all_tiles.insert(active_layer()->HighResTiling()->TileAt(i, j));
591     }
592   }
593   // Expect 15 shared tiles and 1 unshared tile.
594   EXPECT_EQ(17u, expected_all_tiles.size());
595
596   // The actual test will now build different queues and verify that the queues
597   // return the same information as computed manually above.
598   std::unique_ptr<RasterTilePriorityQueue> queue(host_impl()->BuildRasterQueue(
599       SAME_PRIORITY_FOR_BOTH_TREES, RasterTilePriorityQueue::Type::ALL));
600   std::set<Tile*> actual_now_tiles;
601   std::set<Tile*> actual_all_tiles;
602   while (!queue->IsEmpty()) {
603     PrioritizedTile prioritized_tile = queue->Top();
604     queue->Pop();
605     if (prioritized_tile.priority().priority_bin == TilePriority::NOW)
606       actual_now_tiles.insert(prioritized_tile.tile());
607     actual_all_tiles.insert(prioritized_tile.tile());
608   }
609   EXPECT_EQ(expected_now_tiles, actual_now_tiles);
610   EXPECT_EQ(expected_all_tiles, actual_all_tiles);
611
612   queue = host_impl()->BuildRasterQueue(
613       SAME_PRIORITY_FOR_BOTH_TREES,
614       RasterTilePriorityQueue::Type::REQUIRED_FOR_DRAW);
615   std::set<Tile*> actual_required_for_draw_tiles;
616   while (!queue->IsEmpty()) {
617     PrioritizedTile prioritized_tile = queue->Top();
618     queue->Pop();
619     actual_required_for_draw_tiles.insert(prioritized_tile.tile());
620   }
621   EXPECT_EQ(expected_required_for_draw_tiles, actual_required_for_draw_tiles);
622
623   queue = host_impl()->BuildRasterQueue(
624       SAME_PRIORITY_FOR_BOTH_TREES,
625       RasterTilePriorityQueue::Type::REQUIRED_FOR_ACTIVATION);
626   std::set<Tile*> actual_required_for_activation_tiles;
627   while (!queue->IsEmpty()) {
628     Tile* tile = queue->Top().tile();
629     queue->Pop();
630     actual_required_for_activation_tiles.insert(tile);
631   }
632   EXPECT_EQ(expected_required_for_activation_tiles,
633             actual_required_for_activation_tiles);
634 }
635
636 TEST_F(TileManagerTilePriorityQueueTest, ActivationComesBeforeSoon) {
637   host_impl()->AdvanceToNextFrame(base::Milliseconds(1));
638
639   gfx::Size layer_bounds(1000, 1000);
640   SetupDefaultTrees(layer_bounds);
641
642   // Create a pending child layer.
643   scoped_refptr<FakeRasterSource> pending_raster_source =
644       FakeRasterSource::CreateFilled(layer_bounds);
645   auto* pending_child = AddLayer<FakePictureLayerImpl>(
646       host_impl()->pending_tree(), pending_raster_source);
647   pending_child->SetDrawsContent(true);
648   CopyProperties(pending_layer(), pending_child);
649
650   // Set a small viewport, so we have soon and eventually tiles.
651   host_impl()->active_tree()->SetDeviceViewportRect(gfx::Rect(200, 200));
652   host_impl()->AdvanceToNextFrame(base::Milliseconds(1));
653   UpdateDrawProperties(host_impl()->pending_tree());
654
655   host_impl()->SetRequiresHighResToDraw();
656   std::unique_ptr<RasterTilePriorityQueue> queue(host_impl()->BuildRasterQueue(
657       SMOOTHNESS_TAKES_PRIORITY, RasterTilePriorityQueue::Type::ALL));
658   EXPECT_FALSE(queue->IsEmpty());
659
660   // Get all the tiles that are NOW and make sure they are ready to draw.
661   std::vector<Tile*> all_tiles;
662   while (!queue->IsEmpty()) {
663     PrioritizedTile prioritized_tile = queue->Top();
664     if (prioritized_tile.priority().priority_bin >= TilePriority::SOON)
665       break;
666
667     all_tiles.push_back(prioritized_tile.tile());
668     queue->Pop();
669   }
670
671   tile_manager()->InitializeTilesWithResourcesForTesting(
672       std::vector<Tile*>(all_tiles.begin(), all_tiles.end()));
673
674   // Ensure we can activate.
675   EXPECT_TRUE(tile_manager()->IsReadyToActivate());
676 }
677
678 TEST_F(TileManagerTilePriorityQueueTest, EvictionTilePriorityQueue) {
679   const gfx::Size layer_bounds(1000, 1000);
680   host_impl()->active_tree()->SetDeviceViewportRect(gfx::Rect(layer_bounds));
681   SetupDefaultTrees(layer_bounds);
682   ASSERT_TRUE(active_layer()->HighResTiling());
683   ASSERT_TRUE(active_layer()->LowResTiling());
684   ASSERT_TRUE(pending_layer()->HighResTiling());
685   EXPECT_FALSE(pending_layer()->LowResTiling());
686
687   std::unique_ptr<EvictionTilePriorityQueue> empty_queue(
688       host_impl()->BuildEvictionQueue(SAME_PRIORITY_FOR_BOTH_TREES));
689   EXPECT_TRUE(empty_queue->IsEmpty());
690   std::set<Tile*> all_tiles;
691   size_t tile_count = 0;
692
693   std::unique_ptr<RasterTilePriorityQueue> raster_queue(
694       host_impl()->BuildRasterQueue(SAME_PRIORITY_FOR_BOTH_TREES,
695                                     RasterTilePriorityQueue::Type::ALL));
696   while (!raster_queue->IsEmpty()) {
697     ++tile_count;
698     EXPECT_TRUE(raster_queue->Top().tile());
699     all_tiles.insert(raster_queue->Top().tile());
700     raster_queue->Pop();
701   }
702
703   EXPECT_EQ(tile_count, all_tiles.size());
704   EXPECT_EQ(16u, tile_count);
705
706   tile_manager()->InitializeTilesWithResourcesForTesting(
707       std::vector<Tile*>(all_tiles.begin(), all_tiles.end()));
708
709   std::unique_ptr<EvictionTilePriorityQueue> queue(
710       host_impl()->BuildEvictionQueue(SMOOTHNESS_TAKES_PRIORITY));
711   EXPECT_FALSE(queue->IsEmpty());
712
713   // Sanity check, all tiles should be visible.
714   std::set<Tile*> smoothness_tiles;
715   while (!queue->IsEmpty()) {
716     PrioritizedTile prioritized_tile = queue->Top();
717     EXPECT_TRUE(prioritized_tile.tile());
718     EXPECT_EQ(TilePriority::NOW, prioritized_tile.priority().priority_bin);
719     EXPECT_TRUE(prioritized_tile.tile()->draw_info().has_resource());
720     smoothness_tiles.insert(prioritized_tile.tile());
721     queue->Pop();
722   }
723   EXPECT_EQ(all_tiles, smoothness_tiles);
724
725   tile_manager()->ReleaseTileResourcesForTesting(
726       std::vector<Tile*>(all_tiles.begin(), all_tiles.end()));
727
728   Region invalidation(gfx::Rect(0, 0, 500, 500));
729
730   // Invalidate the pending tree.
731   pending_layer()->set_invalidation(invalidation);
732   pending_layer()->HighResTiling()->Invalidate(invalidation);
733   pending_layer()->HighResTiling()->CreateMissingTilesInLiveTilesRect();
734   EXPECT_FALSE(pending_layer()->LowResTiling());
735
736   // Renew all of the tile priorities.
737   gfx::Rect viewport(50, 50, 100, 100);
738   pending_layer()->picture_layer_tiling_set()->UpdateTilePriorities(
739       viewport, 1.0f, 1.0, Occlusion(), true);
740   active_layer()->picture_layer_tiling_set()->UpdateTilePriorities(
741       viewport, 1.0f, 1.0, Occlusion(), true);
742
743   // Populate all tiles directly from the tilings.
744   all_tiles.clear();
745   std::vector<Tile*> pending_high_res_tiles =
746       pending_layer()->HighResTiling()->AllTilesForTesting();
747   for (size_t i = 0; i < pending_high_res_tiles.size(); ++i)
748     all_tiles.insert(pending_high_res_tiles[i]);
749
750   std::vector<Tile*> active_high_res_tiles =
751       active_layer()->HighResTiling()->AllTilesForTesting();
752   for (size_t i = 0; i < active_high_res_tiles.size(); ++i)
753     all_tiles.insert(active_high_res_tiles[i]);
754
755   std::vector<Tile*> active_low_res_tiles =
756       active_layer()->LowResTiling()->AllTilesForTesting();
757   for (size_t i = 0; i < active_low_res_tiles.size(); ++i)
758     all_tiles.insert(active_low_res_tiles[i]);
759
760   tile_manager()->InitializeTilesWithResourcesForTesting(
761       std::vector<Tile*>(all_tiles.begin(), all_tiles.end()));
762
763   PrioritizedTile last_tile;
764   smoothness_tiles.clear();
765   tile_count = 0;
766   // Here we expect to get increasing combined priority_bin.
767   queue = host_impl()->BuildEvictionQueue(SMOOTHNESS_TAKES_PRIORITY);
768   int distance_increasing = 0;
769   int distance_decreasing = 0;
770   while (!queue->IsEmpty()) {
771     PrioritizedTile prioritized_tile = queue->Top();
772     Tile* tile = prioritized_tile.tile();
773     EXPECT_TRUE(tile);
774     EXPECT_TRUE(tile->draw_info().has_resource());
775
776     if (!last_tile.tile())
777       last_tile = prioritized_tile;
778
779     const TilePriority& last_priority = last_tile.priority();
780     const TilePriority& priority = prioritized_tile.priority();
781
782     EXPECT_GE(last_priority.priority_bin, priority.priority_bin);
783     if (last_priority.priority_bin == priority.priority_bin) {
784       EXPECT_LE(last_tile.tile()->required_for_activation(),
785                 tile->required_for_activation());
786       if (last_tile.tile()->required_for_activation() ==
787           tile->required_for_activation()) {
788         if (last_priority.distance_to_visible >= priority.distance_to_visible)
789           ++distance_decreasing;
790         else
791           ++distance_increasing;
792       }
793     }
794
795     last_tile = prioritized_tile;
796     ++tile_count;
797     smoothness_tiles.insert(tile);
798     queue->Pop();
799   }
800
801   // Ensure that the distance is decreasing many more times than increasing.
802   EXPECT_EQ(3, distance_increasing);
803   EXPECT_EQ(16, distance_decreasing);
804   EXPECT_EQ(tile_count, smoothness_tiles.size());
805   EXPECT_EQ(all_tiles, smoothness_tiles);
806
807   std::set<Tile*> new_content_tiles;
808   last_tile = PrioritizedTile();
809   // Again, we expect to get increasing combined priority_bin.
810   queue = host_impl()->BuildEvictionQueue(NEW_CONTENT_TAKES_PRIORITY);
811   distance_decreasing = 0;
812   distance_increasing = 0;
813   while (!queue->IsEmpty()) {
814     PrioritizedTile prioritized_tile = queue->Top();
815     Tile* tile = prioritized_tile.tile();
816     EXPECT_TRUE(tile);
817
818     if (!last_tile.tile())
819       last_tile = prioritized_tile;
820
821     const TilePriority& last_priority = last_tile.priority();
822     const TilePriority& priority = prioritized_tile.priority();
823
824     EXPECT_GE(last_priority.priority_bin, priority.priority_bin);
825     if (last_priority.priority_bin == priority.priority_bin) {
826       EXPECT_LE(last_tile.tile()->required_for_activation(),
827                 tile->required_for_activation());
828       if (last_tile.tile()->required_for_activation() ==
829           tile->required_for_activation()) {
830         if (last_priority.distance_to_visible >= priority.distance_to_visible)
831           ++distance_decreasing;
832         else
833           ++distance_increasing;
834       }
835     }
836
837     last_tile = prioritized_tile;
838     new_content_tiles.insert(tile);
839     queue->Pop();
840   }
841
842   // Ensure that the distance is decreasing many more times than increasing.
843   EXPECT_EQ(3, distance_increasing);
844   EXPECT_EQ(16, distance_decreasing);
845   EXPECT_EQ(tile_count, new_content_tiles.size());
846   EXPECT_EQ(all_tiles, new_content_tiles);
847 }
848
849 // Verifies LayerDebugInfo::name ends up memory dumps.
850 TEST_F(TileManagerTilePriorityQueueTest, DebugNameAppearsInMemoryDump) {
851   host_impl()->AdvanceToNextFrame(base::Milliseconds(1));
852
853   gfx::Size layer_bounds(1000, 1000);
854
855   host_impl()->active_tree()->SetDeviceViewportRect(gfx::Rect(layer_bounds));
856
857   scoped_refptr<FakeRasterSource> pending_raster_source =
858       FakeRasterSource::CreateFilledWithText(layer_bounds);
859   SetupPendingTree(pending_raster_source);
860
861   auto* pending_child_layer = AddLayer<FakePictureLayerImpl>(
862       host_impl()->pending_tree(), pending_raster_source);
863   LayerDebugInfo debug_info;
864   debug_info.name = "debug-name";
865   pending_child_layer->UpdateDebugInfo(&debug_info);
866   pending_child_layer->SetDrawsContent(true);
867   CopyProperties(pending_layer(), pending_child_layer);
868
869   ActivateTree();
870   host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
871
872   base::trace_event::MemoryDumpArgs dump_args = {
873       base::trace_event::MemoryDumpLevelOfDetail::DETAILED};
874   base::trace_event::ProcessMemoryDump memory_dump(dump_args);
875   host_impl()->resource_pool()->OnMemoryDump(dump_args, &memory_dump);
876   bool found_debug_name = false;
877   for (const auto& allocator_map_pair : memory_dump.allocator_dumps()) {
878     if (allocator_map_pair.first.find("debug-name") != std::string::npos) {
879       found_debug_name = true;
880       break;
881     }
882   }
883   EXPECT_TRUE(found_debug_name);
884 }
885
886 TEST_F(TileManagerTilePriorityQueueTest,
887        EvictionTilePriorityQueueWithOcclusion) {
888   host_impl()->AdvanceToNextFrame(base::Milliseconds(1));
889
890   gfx::Size layer_bounds(1000, 1000);
891
892   host_impl()->active_tree()->SetDeviceViewportRect(gfx::Rect(layer_bounds));
893
894   scoped_refptr<FakeRasterSource> pending_raster_source =
895       FakeRasterSource::CreateFilledWithText(layer_bounds);
896   SetupPendingTree(pending_raster_source);
897
898   auto* pending_child_layer = AddLayer<FakePictureLayerImpl>(
899       host_impl()->pending_tree(), pending_raster_source);
900   int child_id = pending_child_layer->id();
901   pending_child_layer->SetDrawsContent(true);
902   CopyProperties(pending_layer(), pending_child_layer);
903
904   host_impl()->AdvanceToNextFrame(base::Milliseconds(1));
905   UpdateDrawProperties(host_impl()->pending_tree());
906
907   ActivateTree();
908   SetupPendingTree(pending_raster_source);
909
910   FakePictureLayerImpl* active_child_layer = static_cast<FakePictureLayerImpl*>(
911       host_impl()->active_tree()->LayerById(child_id));
912
913   std::set<Tile*> all_tiles;
914   size_t tile_count = 0;
915   std::unique_ptr<RasterTilePriorityQueue> raster_queue(
916       host_impl()->BuildRasterQueue(SAME_PRIORITY_FOR_BOTH_TREES,
917                                     RasterTilePriorityQueue::Type::ALL));
918   while (!raster_queue->IsEmpty()) {
919     ++tile_count;
920     EXPECT_TRUE(raster_queue->Top().tile());
921     all_tiles.insert(raster_queue->Top().tile());
922     raster_queue->Pop();
923   }
924   EXPECT_EQ(tile_count, all_tiles.size());
925   EXPECT_EQ(32u, tile_count);
926
927   // Renew all of the tile priorities.
928   gfx::Rect viewport(layer_bounds);
929   pending_layer()->picture_layer_tiling_set()->UpdateTilePriorities(
930       viewport, 1.0f, 1.0, Occlusion(), true);
931   pending_child_layer->picture_layer_tiling_set()->UpdateTilePriorities(
932       viewport, 1.0f, 1.0, Occlusion(), true);
933
934   active_layer()->picture_layer_tiling_set()->UpdateTilePriorities(
935       viewport, 1.0f, 1.0, Occlusion(), true);
936   active_child_layer->picture_layer_tiling_set()->UpdateTilePriorities(
937       viewport, 1.0f, 1.0, Occlusion(), true);
938
939   // Populate all tiles directly from the tilings.
940   all_tiles.clear();
941   std::vector<Tile*> pending_high_res_tiles =
942       pending_layer()->HighResTiling()->AllTilesForTesting();
943   all_tiles.insert(pending_high_res_tiles.begin(),
944                    pending_high_res_tiles.end());
945
946   // Set all tiles on the pending_child_layer as occluded on the pending tree.
947   std::vector<Tile*> pending_child_high_res_tiles =
948       pending_child_layer->HighResTiling()->AllTilesForTesting();
949   pending_child_layer->HighResTiling()->SetAllTilesOccludedForTesting();
950   active_child_layer->HighResTiling()->SetAllTilesOccludedForTesting();
951   active_child_layer->LowResTiling()->SetAllTilesOccludedForTesting();
952
953   tile_manager()->InitializeTilesWithResourcesForTesting(
954       std::vector<Tile*>(all_tiles.begin(), all_tiles.end()));
955
956   // Verify occlusion is considered by EvictionTilePriorityQueue.
957   TreePriority tree_priority = NEW_CONTENT_TAKES_PRIORITY;
958   size_t occluded_count = 0u;
959   PrioritizedTile last_tile;
960   std::unique_ptr<EvictionTilePriorityQueue> queue(
961       host_impl()->BuildEvictionQueue(tree_priority));
962   while (!queue->IsEmpty()) {
963     PrioritizedTile prioritized_tile = queue->Top();
964     if (!last_tile.tile())
965       last_tile = prioritized_tile;
966
967     bool tile_is_occluded = prioritized_tile.is_occluded();
968
969     // The only way we will encounter an occluded tile after an unoccluded
970     // tile is if the priorty bin decreased, the tile is required for
971     // activation, or the scale changed.
972     if (tile_is_occluded) {
973       occluded_count++;
974
975       bool last_tile_is_occluded = last_tile.is_occluded();
976       if (!last_tile_is_occluded) {
977         TilePriority::PriorityBin tile_priority_bin =
978             prioritized_tile.priority().priority_bin;
979         TilePriority::PriorityBin last_tile_priority_bin =
980             last_tile.priority().priority_bin;
981
982         EXPECT_TRUE((tile_priority_bin < last_tile_priority_bin) ||
983                     prioritized_tile.tile()->required_for_activation() ||
984                     (prioritized_tile.tile()->raster_transform() !=
985                      last_tile.tile()->raster_transform()));
986       }
987     }
988     last_tile = prioritized_tile;
989     queue->Pop();
990   }
991   size_t expected_occluded_count = pending_child_high_res_tiles.size();
992   EXPECT_EQ(expected_occluded_count, occluded_count);
993 }
994
995 TEST_F(TileManagerTilePriorityQueueTest,
996        EvictionTilePriorityQueueWithTransparentLayer) {
997   host_impl()->AdvanceToNextFrame(base::Milliseconds(1));
998
999   gfx::Size layer_bounds(1000, 1000);
1000
1001   scoped_refptr<FakeRasterSource> pending_raster_source =
1002       FakeRasterSource::CreateFilled(layer_bounds);
1003   SetupPendingTree(pending_raster_source);
1004
1005   auto* pending_child_layer = AddLayer<FakePictureLayerImpl>(
1006       host_impl()->pending_tree(), pending_raster_source);
1007   pending_child_layer->SetElementId(
1008       LayerIdToElementIdForTesting(pending_child_layer->id()));
1009   CopyProperties(pending_layer(), pending_child_layer);
1010
1011   // Create a fully transparent child layer so that its tile priorities are not
1012   // considered to be valid.
1013   pending_child_layer->SetDrawsContent(true);
1014   CreateEffectNode(pending_child_layer).render_surface_reason =
1015       RenderSurfaceReason::kTest;
1016
1017   host_impl()->AdvanceToNextFrame(base::Milliseconds(1));
1018   UpdateDrawProperties(host_impl()->pending_tree());
1019
1020   host_impl()->pending_tree()->SetOpacityMutated(
1021       pending_child_layer->element_id(), 0.0f);
1022
1023   host_impl()->AdvanceToNextFrame(base::Milliseconds(1));
1024   host_impl()->pending_tree()->UpdateDrawProperties();
1025
1026   // Renew all of the tile priorities.
1027   gfx::Rect viewport(layer_bounds);
1028   pending_layer()->picture_layer_tiling_set()->UpdateTilePriorities(
1029       viewport, 1.0f, 1.0, Occlusion(), true);
1030   pending_child_layer->picture_layer_tiling_set()->UpdateTilePriorities(
1031       viewport, 1.0f, 1.0, Occlusion(), true);
1032
1033   // Populate all tiles directly from the tilings.
1034   std::set<Tile*> all_pending_tiles;
1035   std::vector<Tile*> pending_high_res_tiles =
1036       pending_layer()->HighResTiling()->AllTilesForTesting();
1037   all_pending_tiles.insert(pending_high_res_tiles.begin(),
1038                            pending_high_res_tiles.end());
1039   EXPECT_EQ(16u, pending_high_res_tiles.size());
1040
1041   std::set<Tile*> all_pending_child_tiles;
1042   std::vector<Tile*> pending_child_high_res_tiles =
1043       pending_child_layer->HighResTiling()->AllTilesForTesting();
1044   all_pending_child_tiles.insert(pending_child_high_res_tiles.begin(),
1045                                  pending_child_high_res_tiles.end());
1046   EXPECT_EQ(16u, pending_child_high_res_tiles.size());
1047
1048   std::set<Tile*> all_tiles = all_pending_tiles;
1049   all_tiles.insert(all_pending_child_tiles.begin(),
1050                    all_pending_child_tiles.end());
1051
1052   tile_manager()->InitializeTilesWithResourcesForTesting(
1053       std::vector<Tile*>(all_tiles.begin(), all_tiles.end()));
1054
1055   EXPECT_TRUE(pending_layer()->HasValidTilePriorities());
1056   EXPECT_FALSE(pending_child_layer->HasValidTilePriorities());
1057
1058   // Verify that eviction queue returns tiles also from layers without valid
1059   // tile priorities and that the tile priority bin of those tiles is (at most)
1060   // EVENTUALLY.
1061   TreePriority tree_priority = NEW_CONTENT_TAKES_PRIORITY;
1062   std::set<Tile*> new_content_tiles;
1063   size_t tile_count = 0;
1064   std::unique_ptr<EvictionTilePriorityQueue> queue(
1065       host_impl()->BuildEvictionQueue(tree_priority));
1066   while (!queue->IsEmpty()) {
1067     PrioritizedTile prioritized_tile = queue->Top();
1068     Tile* tile = prioritized_tile.tile();
1069     const TilePriority& pending_priority = prioritized_tile.priority();
1070     EXPECT_NE(std::numeric_limits<float>::infinity(),
1071               pending_priority.distance_to_visible);
1072     if (all_pending_child_tiles.find(tile) != all_pending_child_tiles.end())
1073       EXPECT_EQ(TilePriority::EVENTUALLY, pending_priority.priority_bin);
1074     else
1075       EXPECT_EQ(TilePriority::NOW, pending_priority.priority_bin);
1076     new_content_tiles.insert(tile);
1077     ++tile_count;
1078     queue->Pop();
1079   }
1080   EXPECT_EQ(tile_count, new_content_tiles.size());
1081   EXPECT_EQ(all_tiles, new_content_tiles);
1082 }
1083
1084 TEST_F(TileManagerTilePriorityQueueTest, RasterTilePriorityQueueEmptyLayers) {
1085   const gfx::Size layer_bounds(1000, 1000);
1086   host_impl()->active_tree()->SetDeviceViewportRect(gfx::Rect(layer_bounds));
1087   SetupDefaultTrees(layer_bounds);
1088
1089   std::unique_ptr<RasterTilePriorityQueue> queue(host_impl()->BuildRasterQueue(
1090       SAME_PRIORITY_FOR_BOTH_TREES, RasterTilePriorityQueue::Type::ALL));
1091   EXPECT_FALSE(queue->IsEmpty());
1092
1093   size_t tile_count = 0;
1094   std::set<Tile*> all_tiles;
1095   while (!queue->IsEmpty()) {
1096     EXPECT_TRUE(queue->Top().tile());
1097     all_tiles.insert(queue->Top().tile());
1098     ++tile_count;
1099     queue->Pop();
1100   }
1101
1102   EXPECT_EQ(tile_count, all_tiles.size());
1103   EXPECT_EQ(16u, tile_count);
1104
1105   for (int i = 1; i < 10; ++i) {
1106     auto* pending_child_layer =
1107         AddLayer<FakePictureLayerImpl>(host_impl()->pending_tree());
1108     pending_child_layer->SetDrawsContent(true);
1109     pending_child_layer->set_has_valid_tile_priorities(true);
1110     CopyProperties(pending_layer(), pending_child_layer);
1111   }
1112
1113   queue = host_impl()->BuildRasterQueue(SAME_PRIORITY_FOR_BOTH_TREES,
1114                                         RasterTilePriorityQueue::Type::ALL);
1115   EXPECT_FALSE(queue->IsEmpty());
1116
1117   tile_count = 0;
1118   all_tiles.clear();
1119   while (!queue->IsEmpty()) {
1120     EXPECT_TRUE(queue->Top().tile());
1121     all_tiles.insert(queue->Top().tile());
1122     ++tile_count;
1123     queue->Pop();
1124   }
1125   EXPECT_EQ(tile_count, all_tiles.size());
1126   EXPECT_EQ(16u, tile_count);
1127 }
1128
1129 TEST_F(TileManagerTilePriorityQueueTest, EvictionTilePriorityQueueEmptyLayers) {
1130   const gfx::Size layer_bounds(1000, 1000);
1131   host_impl()->active_tree()->SetDeviceViewportRect(gfx::Rect(layer_bounds));
1132   SetupDefaultTrees(layer_bounds);
1133
1134   std::unique_ptr<RasterTilePriorityQueue> raster_queue(
1135       host_impl()->BuildRasterQueue(SAME_PRIORITY_FOR_BOTH_TREES,
1136                                     RasterTilePriorityQueue::Type::ALL));
1137   EXPECT_FALSE(raster_queue->IsEmpty());
1138
1139   size_t tile_count = 0;
1140   std::set<Tile*> all_tiles;
1141   while (!raster_queue->IsEmpty()) {
1142     EXPECT_TRUE(raster_queue->Top().tile());
1143     all_tiles.insert(raster_queue->Top().tile());
1144     ++tile_count;
1145     raster_queue->Pop();
1146   }
1147   EXPECT_EQ(tile_count, all_tiles.size());
1148   EXPECT_EQ(16u, tile_count);
1149
1150   std::vector<Tile*> tiles(all_tiles.begin(), all_tiles.end());
1151   host_impl()->tile_manager()->InitializeTilesWithResourcesForTesting(tiles);
1152
1153   for (int i = 1; i < 10; ++i) {
1154     auto* pending_child_layer =
1155         AddLayer<FakePictureLayerImpl>(host_impl()->pending_tree());
1156     pending_child_layer->SetDrawsContent(true);
1157     pending_child_layer->set_has_valid_tile_priorities(true);
1158     CopyProperties(pending_layer(), pending_child_layer);
1159   }
1160
1161   std::unique_ptr<EvictionTilePriorityQueue> queue(
1162       host_impl()->BuildEvictionQueue(SAME_PRIORITY_FOR_BOTH_TREES));
1163   EXPECT_FALSE(queue->IsEmpty());
1164
1165   tile_count = 0;
1166   all_tiles.clear();
1167   while (!queue->IsEmpty()) {
1168     EXPECT_TRUE(queue->Top().tile());
1169     all_tiles.insert(queue->Top().tile());
1170     ++tile_count;
1171     queue->Pop();
1172   }
1173   EXPECT_EQ(tile_count, all_tiles.size());
1174   EXPECT_EQ(16u, tile_count);
1175 }
1176
1177 TEST_F(TileManagerTilePriorityQueueTest,
1178        RasterTilePriorityQueueStaticViewport) {
1179   FakePictureLayerTilingClient client;
1180
1181   gfx::Rect viewport(50, 50, 500, 500);
1182   gfx::Size layer_bounds(1600, 1600);
1183
1184   const int soon_border_outset = 312;
1185   gfx::Rect soon_rect = viewport;
1186   soon_rect.Inset(-soon_border_outset);
1187
1188   client.SetTileSize(gfx::Size(30, 30));
1189   LayerTreeSettings settings;
1190
1191   std::unique_ptr<PictureLayerTilingSet> tiling_set =
1192       PictureLayerTilingSet::Create(
1193           ACTIVE_TREE, &client, settings.tiling_interest_area_padding,
1194           settings.skewport_target_time_in_seconds,
1195           settings.skewport_extrapolation_limit_in_screen_pixels,
1196           settings.max_preraster_distance_in_screen_pixels);
1197
1198   scoped_refptr<FakeRasterSource> raster_source =
1199       FakeRasterSource::CreateFilled(layer_bounds);
1200   PictureLayerTiling* tiling =
1201       tiling_set->AddTiling(gfx::AxisTransform2d(), raster_source);
1202   tiling->set_resolution(HIGH_RESOLUTION);
1203
1204   tiling_set->UpdateTilePriorities(viewport, 1.0f, 1.0, Occlusion(), true);
1205   std::vector<Tile*> all_tiles = tiling->AllTilesForTesting();
1206   // Sanity check.
1207   EXPECT_EQ(3364u, all_tiles.size());
1208
1209   // The explanation of each iteration is as follows:
1210   // 1. First iteration tests that we can get all of the tiles correctly.
1211   // 2. Second iteration ensures that we can get all of the tiles again (first
1212   //    iteration didn't change any tiles), as well set all tiles to be ready to
1213   //    draw.
1214   // 3. Third iteration ensures that no tiles are returned, since they were all
1215   //    marked as ready to draw.
1216   for (int i = 0; i < 3; ++i) {
1217     std::unique_ptr<TilingSetRasterQueueAll> queue(
1218         new TilingSetRasterQueueAll(tiling_set.get(), false, false));
1219
1220     // There are 3 bins in TilePriority.
1221     bool have_tiles[3] = {};
1222
1223     // On the third iteration, we should get no tiles since everything was
1224     // marked as ready to draw.
1225     if (i == 2) {
1226       EXPECT_TRUE(queue->IsEmpty());
1227       continue;
1228     }
1229
1230     EXPECT_FALSE(queue->IsEmpty());
1231     std::set<Tile*> unique_tiles;
1232     unique_tiles.insert(queue->Top().tile());
1233     PrioritizedTile last_tile = queue->Top();
1234     have_tiles[last_tile.priority().priority_bin] = true;
1235
1236     // On the second iteration, mark everything as ready to draw (solid color).
1237     if (i == 1) {
1238       TileDrawInfo& draw_info = last_tile.tile()->draw_info();
1239       draw_info.SetSolidColorForTesting(SkColors::kRed);
1240     }
1241     queue->Pop();
1242     int eventually_bin_order_correct_count = 0;
1243     int eventually_bin_order_incorrect_count = 0;
1244     while (!queue->IsEmpty()) {
1245       PrioritizedTile new_tile = queue->Top();
1246       queue->Pop();
1247       unique_tiles.insert(new_tile.tile());
1248
1249       TilePriority last_priority = last_tile.priority();
1250       TilePriority new_priority = new_tile.priority();
1251       EXPECT_LE(last_priority.priority_bin, new_priority.priority_bin);
1252       if (last_priority.priority_bin == new_priority.priority_bin) {
1253         if (last_priority.priority_bin == TilePriority::EVENTUALLY) {
1254           bool order_correct = last_priority.distance_to_visible <=
1255                                new_priority.distance_to_visible;
1256           eventually_bin_order_correct_count += order_correct;
1257           eventually_bin_order_incorrect_count += !order_correct;
1258         } else if (!soon_rect.Intersects(new_tile.tile()->content_rect()) &&
1259                    !soon_rect.Intersects(last_tile.tile()->content_rect())) {
1260           EXPECT_LE(last_priority.distance_to_visible,
1261                     new_priority.distance_to_visible);
1262           EXPECT_EQ(TilePriority::NOW, new_priority.priority_bin);
1263         } else if (new_priority.distance_to_visible > 0.f) {
1264           EXPECT_EQ(TilePriority::SOON, new_priority.priority_bin);
1265         }
1266       }
1267       have_tiles[new_priority.priority_bin] = true;
1268
1269       last_tile = new_tile;
1270
1271       // On the second iteration, mark everything as ready to draw (solid
1272       // color).
1273       if (i == 1) {
1274         TileDrawInfo& draw_info = last_tile.tile()->draw_info();
1275         draw_info.SetSolidColorForTesting(SkColors::kRed);
1276       }
1277     }
1278
1279     EXPECT_GT(eventually_bin_order_correct_count,
1280               eventually_bin_order_incorrect_count);
1281
1282     // We should have now and eventually tiles, as well as soon tiles from
1283     // the border region.
1284     EXPECT_TRUE(have_tiles[TilePriority::NOW]);
1285     EXPECT_TRUE(have_tiles[TilePriority::SOON]);
1286     EXPECT_TRUE(have_tiles[TilePriority::EVENTUALLY]);
1287
1288     EXPECT_EQ(unique_tiles.size(), all_tiles.size());
1289   }
1290 }
1291
1292 TEST_F(TileManagerTilePriorityQueueTest,
1293        RasterTilePriorityQueueMovingViewport) {
1294   FakePictureLayerTilingClient client;
1295
1296   gfx::Rect viewport(50, 0, 100, 100);
1297   gfx::Rect moved_viewport(50, 0, 100, 500);
1298   gfx::Size layer_bounds(1000, 1000);
1299
1300   client.SetTileSize(gfx::Size(30, 30));
1301   LayerTreeSettings settings;
1302
1303   std::unique_ptr<PictureLayerTilingSet> tiling_set =
1304       PictureLayerTilingSet::Create(
1305           ACTIVE_TREE, &client, settings.tiling_interest_area_padding,
1306           settings.skewport_target_time_in_seconds,
1307           settings.skewport_extrapolation_limit_in_screen_pixels,
1308           settings.max_preraster_distance_in_screen_pixels);
1309
1310   scoped_refptr<FakeRasterSource> raster_source =
1311       FakeRasterSource::CreateFilled(layer_bounds);
1312   PictureLayerTiling* tiling =
1313       tiling_set->AddTiling(gfx::AxisTransform2d(), raster_source);
1314   tiling->set_resolution(HIGH_RESOLUTION);
1315
1316   tiling_set->UpdateTilePriorities(viewport, 1.0f, 1.0, Occlusion(), true);
1317   tiling_set->UpdateTilePriorities(moved_viewport, 1.0f, 2.0, Occlusion(),
1318                                    true);
1319
1320   const int soon_border_outset = 312;
1321   gfx::Rect soon_rect = moved_viewport;
1322   soon_rect.Inset(-soon_border_outset);
1323
1324   // There are 3 bins in TilePriority.
1325   bool have_tiles[3] = {};
1326   PrioritizedTile last_tile;
1327   int eventually_bin_order_correct_count = 0;
1328   int eventually_bin_order_incorrect_count = 0;
1329   std::unique_ptr<TilingSetRasterQueueAll> queue(
1330       new TilingSetRasterQueueAll(tiling_set.get(), false, false));
1331   for (; !queue->IsEmpty(); queue->Pop()) {
1332     if (!last_tile.tile())
1333       last_tile = queue->Top();
1334
1335     const PrioritizedTile& new_tile = queue->Top();
1336
1337     TilePriority last_priority = last_tile.priority();
1338     TilePriority new_priority = new_tile.priority();
1339
1340     have_tiles[new_priority.priority_bin] = true;
1341
1342     EXPECT_LE(last_priority.priority_bin, new_priority.priority_bin);
1343     if (last_priority.priority_bin == new_priority.priority_bin) {
1344       if (last_priority.priority_bin == TilePriority::EVENTUALLY) {
1345         bool order_correct = last_priority.distance_to_visible <=
1346                              new_priority.distance_to_visible;
1347         eventually_bin_order_correct_count += order_correct;
1348         eventually_bin_order_incorrect_count += !order_correct;
1349       } else if (!soon_rect.Intersects(new_tile.tile()->content_rect()) &&
1350                  !soon_rect.Intersects(last_tile.tile()->content_rect())) {
1351         EXPECT_LE(last_priority.distance_to_visible,
1352                   new_priority.distance_to_visible);
1353       } else if (new_priority.distance_to_visible > 0.f) {
1354         EXPECT_EQ(TilePriority::SOON, new_priority.priority_bin);
1355       }
1356     }
1357     last_tile = new_tile;
1358   }
1359
1360   EXPECT_GT(eventually_bin_order_correct_count,
1361             eventually_bin_order_incorrect_count);
1362
1363   EXPECT_TRUE(have_tiles[TilePriority::NOW]);
1364   EXPECT_TRUE(have_tiles[TilePriority::SOON]);
1365   EXPECT_TRUE(have_tiles[TilePriority::EVENTUALLY]);
1366 }
1367
1368 TEST_F(TileManagerTilePriorityQueueTest, SetIsLikelyToRequireADraw) {
1369   const gfx::Size layer_bounds(1000, 1000);
1370   host_impl()->active_tree()->SetDeviceViewportRect(gfx::Rect(layer_bounds));
1371   SetupDefaultTrees(layer_bounds);
1372
1373   // Verify that the queue has a required for draw tile at Top.
1374   std::unique_ptr<RasterTilePriorityQueue> queue(host_impl()->BuildRasterQueue(
1375       SAME_PRIORITY_FOR_BOTH_TREES, RasterTilePriorityQueue::Type::ALL));
1376   EXPECT_FALSE(queue->IsEmpty());
1377   EXPECT_TRUE(queue->Top().tile()->required_for_draw());
1378
1379   EXPECT_FALSE(host_impl()->is_likely_to_require_a_draw());
1380   host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
1381   EXPECT_TRUE(host_impl()->is_likely_to_require_a_draw());
1382 }
1383
1384 TEST_F(TileManagerTilePriorityQueueTest,
1385        SetIsLikelyToRequireADrawOnZeroMemoryBudget) {
1386   const gfx::Size layer_bounds(1000, 1000);
1387   host_impl()->active_tree()->SetDeviceViewportRect(gfx::Rect(layer_bounds));
1388   SetupDefaultTrees(layer_bounds);
1389
1390   // Verify that the queue has a required for draw tile at Top.
1391   std::unique_ptr<RasterTilePriorityQueue> queue(host_impl()->BuildRasterQueue(
1392       SAME_PRIORITY_FOR_BOTH_TREES, RasterTilePriorityQueue::Type::ALL));
1393   EXPECT_FALSE(queue->IsEmpty());
1394   EXPECT_TRUE(queue->Top().tile()->required_for_draw());
1395
1396   ManagedMemoryPolicy policy = host_impl()->ActualManagedMemoryPolicy();
1397   policy.bytes_limit_when_visible = 0;
1398   host_impl()->SetMemoryPolicy(policy);
1399
1400   EXPECT_FALSE(host_impl()->is_likely_to_require_a_draw());
1401   host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
1402   EXPECT_FALSE(host_impl()->is_likely_to_require_a_draw());
1403 }
1404
1405 TEST_F(TileManagerTilePriorityQueueTest,
1406        SetIsLikelyToRequireADrawOnLimitedMemoryBudget) {
1407   const gfx::Size layer_bounds(1000, 1000);
1408   host_impl()->active_tree()->SetDeviceViewportRect(gfx::Rect(layer_bounds));
1409   SetupDefaultTrees(layer_bounds);
1410
1411   // Verify that the queue has a required for draw tile at Top.
1412   std::unique_ptr<RasterTilePriorityQueue> queue(host_impl()->BuildRasterQueue(
1413       SAME_PRIORITY_FOR_BOTH_TREES, RasterTilePriorityQueue::Type::ALL));
1414   EXPECT_FALSE(queue->IsEmpty());
1415   EXPECT_TRUE(queue->Top().tile()->required_for_draw());
1416   EXPECT_EQ(gfx::Size(256, 256), queue->Top().tile()->desired_texture_size());
1417
1418   ManagedMemoryPolicy policy = host_impl()->ActualManagedMemoryPolicy();
1419   policy.bytes_limit_when_visible =
1420       viz::ResourceSizes::UncheckedSizeInBytes<size_t>(gfx::Size(256, 256),
1421                                                        viz::RGBA_8888);
1422   host_impl()->SetMemoryPolicy(policy);
1423
1424   EXPECT_FALSE(host_impl()->is_likely_to_require_a_draw());
1425   host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
1426   EXPECT_TRUE(host_impl()->is_likely_to_require_a_draw());
1427
1428   ResourcePool::InUsePoolResource resource =
1429       host_impl()->resource_pool()->AcquireResource(
1430           gfx::Size(256, 256), viz::RGBA_8888, gfx::ColorSpace());
1431   resource.set_gpu_backing(std::make_unique<StubGpuBacking>());
1432
1433   host_impl()->tile_manager()->CheckIfMoreTilesNeedToBePreparedForTesting();
1434   EXPECT_FALSE(host_impl()->is_likely_to_require_a_draw());
1435
1436   host_impl()->resource_pool()->ReleaseResource(std::move(resource));
1437 }
1438
1439 TEST_F(TileManagerTilePriorityQueueTest, DefaultMemoryPolicy) {
1440   const gfx::Size layer_bounds(1000, 1000);
1441   host_impl()->active_tree()->SetDeviceViewportRect(gfx::Rect(layer_bounds));
1442   SetupDefaultTrees(layer_bounds);
1443
1444   host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
1445
1446   // 64MB is the default mem limit.
1447   EXPECT_EQ(67108864u,
1448             host_impl()->global_tile_state().hard_memory_limit_in_bytes);
1449   EXPECT_EQ(TileMemoryLimitPolicy::ALLOW_ANYTHING,
1450             host_impl()->global_tile_state().memory_limit_policy);
1451   EXPECT_EQ(ManagedMemoryPolicy::kDefaultNumResourcesLimit,
1452             host_impl()->global_tile_state().num_resources_limit);
1453 }
1454
1455 TEST_F(TileManagerTilePriorityQueueTest, RasterQueueAllUsesCorrectTileBounds) {
1456   // Verify that we use the real tile bounds when advancing phases during the
1457   // tile iteration.
1458   gfx::Size layer_bounds(1, 1);
1459
1460   scoped_refptr<FakeRasterSource> raster_source =
1461       FakeRasterSource::CreateFilled(layer_bounds);
1462
1463   FakePictureLayerTilingClient pending_client;
1464   pending_client.SetTileSize(gfx::Size(64, 64));
1465
1466   std::unique_ptr<PictureLayerTilingSet> tiling_set =
1467       PictureLayerTilingSet::Create(WhichTree::ACTIVE_TREE, &pending_client,
1468                                     1.0f, 1.0f, 1000, 1000.f);
1469   pending_client.set_twin_tiling_set(tiling_set.get());
1470
1471   auto* tiling = tiling_set->AddTiling(gfx::AxisTransform2d(), raster_source);
1472
1473   tiling->set_resolution(HIGH_RESOLUTION);
1474   tiling->CreateAllTilesForTesting();
1475
1476   // The tile is (0, 0, 1, 1), create an intersecting and non-intersecting
1477   // rectangle to test the advance phase with. The tile size is (64, 64), so
1478   // both rectangles intersect the tile content size, but only one should
1479   // intersect the actual size.
1480   gfx::Rect non_intersecting_rect(2, 2, 10, 10);
1481   gfx::Rect intersecting_rect(0, 0, 10, 10);
1482   {
1483     tiling->SetTilePriorityRectsForTesting(
1484         non_intersecting_rect,  // Visible rect.
1485         intersecting_rect,      // Skewport rect.
1486         intersecting_rect,      // Soon rect.
1487         intersecting_rect);     // Eventually rect.
1488     std::unique_ptr<TilingSetRasterQueueAll> queue(
1489         new TilingSetRasterQueueAll(tiling_set.get(), false, false));
1490     EXPECT_FALSE(queue->IsEmpty());
1491   }
1492   {
1493     tiling->SetTilePriorityRectsForTesting(
1494         non_intersecting_rect,  // Visible rect.
1495         non_intersecting_rect,  // Skewport rect.
1496         intersecting_rect,      // Soon rect.
1497         intersecting_rect);     // Eventually rect.
1498     std::unique_ptr<TilingSetRasterQueueAll> queue(
1499         new TilingSetRasterQueueAll(tiling_set.get(), false, false));
1500     EXPECT_FALSE(queue->IsEmpty());
1501   }
1502   {
1503     tiling->SetTilePriorityRectsForTesting(
1504         non_intersecting_rect,  // Visible rect.
1505         non_intersecting_rect,  // Skewport rect.
1506         non_intersecting_rect,  // Soon rect.
1507         intersecting_rect);     // Eventually rect.
1508     std::unique_ptr<TilingSetRasterQueueAll> queue(
1509         new TilingSetRasterQueueAll(tiling_set.get(), false, false));
1510     EXPECT_FALSE(queue->IsEmpty());
1511   }
1512 }
1513
1514 TEST_F(TileManagerTilePriorityQueueTest, NoRasterTasksforSolidColorTiles) {
1515   gfx::Size size(10, 10);
1516   const gfx::Size layer_bounds(1000, 1000);
1517
1518   std::unique_ptr<FakeRecordingSource> recording_source =
1519       FakeRecordingSource::CreateFilledRecordingSource(layer_bounds);
1520
1521   PaintFlags solid_flags;
1522   SkColor4f solid_color{0.1f, 0.2f, 0.3f, 1.0f};
1523   solid_flags.setColor(solid_color);
1524   recording_source->add_draw_rect_with_flags(gfx::Rect(layer_bounds),
1525                                              solid_flags);
1526
1527   // Create non solid tile as well, otherwise tilings wouldnt be created.
1528   SkColor4f non_solid_color{0.2f, 0.3f, 0.4f, 0.5f};
1529   PaintFlags non_solid_flags;
1530   non_solid_flags.setColor(non_solid_color);
1531
1532   recording_source->add_draw_rect_with_flags(gfx::Rect(0, 0, 10, 10),
1533                                              non_solid_flags);
1534   recording_source->Rerecord();
1535
1536   scoped_refptr<RasterSource> raster_source =
1537       recording_source->CreateRasterSource();
1538
1539   FakePictureLayerTilingClient tiling_client;
1540   tiling_client.SetTileSize(size);
1541
1542   std::unique_ptr<PictureLayerImpl> layer_impl =
1543       PictureLayerImpl::Create(host_impl()->active_tree(), 1);
1544   layer_impl->set_contributes_to_drawn_render_surface(true);
1545   PictureLayerTilingSet* tiling_set = layer_impl->picture_layer_tiling_set();
1546
1547   PictureLayerTiling* tiling =
1548       tiling_set->AddTiling(gfx::AxisTransform2d(), raster_source);
1549   tiling->set_resolution(HIGH_RESOLUTION);
1550   tiling->CreateAllTilesForTesting();
1551   tiling->SetTilePriorityRectsForTesting(
1552       gfx::Rect(layer_bounds),   // Visible rect.
1553       gfx::Rect(layer_bounds),   // Skewport rect.
1554       gfx::Rect(layer_bounds),   // Soon rect.
1555       gfx::Rect(layer_bounds));  // Eventually rect.
1556
1557   host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
1558
1559   std::vector<Tile*> tiles = tiling->AllTilesForTesting();
1560   for (size_t tile_idx = 0; tile_idx < tiles.size(); ++tile_idx) {
1561     Tile* tile = tiles[tile_idx];
1562     if (tile->id() == 1) {
1563       // Non-solid tile.
1564       EXPECT_TRUE(tile->HasRasterTask());
1565       EXPECT_EQ(TileDrawInfo::RESOURCE_MODE, tile->draw_info().mode());
1566     } else {
1567       EXPECT_FALSE(tile->HasRasterTask());
1568       EXPECT_EQ(TileDrawInfo::SOLID_COLOR_MODE, tile->draw_info().mode());
1569       EXPECT_EQ(solid_color, tile->draw_info().solid_color());
1570     }
1571   }
1572 }
1573
1574 class TestSoftwareBacking : public ResourcePool::SoftwareBacking {
1575  public:
1576   // No tracing is done during these tests.
1577   void OnMemoryDump(
1578       base::trace_event::ProcessMemoryDump* pmd,
1579       const base::trace_event::MemoryAllocatorDumpGuid& buffer_dump_guid,
1580       uint64_t tracing_process_id,
1581       int importance) const override {}
1582
1583   std::unique_ptr<uint32_t[]> pixels;
1584 };
1585
1586 // A RasterBufferProvider that allocates software backings with a standard
1587 // array as the backing. Overrides Playback() on the RasterBuffer to raster
1588 // into the pixels in the array.
1589 class TestSoftwareRasterBufferProvider : public FakeRasterBufferProviderImpl {
1590  public:
1591   static constexpr bool kIsGpuCompositing = true;
1592   static constexpr viz::ResourceFormat kResourceFormat = viz::RGBA_8888;
1593
1594   std::unique_ptr<RasterBuffer> AcquireBufferForRaster(
1595       const ResourcePool::InUsePoolResource& resource,
1596       uint64_t resource_content_id,
1597       uint64_t previous_content_id,
1598       bool depends_on_at_raster_decodes,
1599       bool depends_on_hardware_accelerated_jpeg_candidates,
1600       bool depends_on_hardware_accelerated_webp_candidates) override {
1601     if (!resource.software_backing()) {
1602       auto backing = std::make_unique<TestSoftwareBacking>();
1603       backing->shared_bitmap_id = viz::SharedBitmap::GenerateId();
1604       backing->pixels = std::make_unique<uint32_t[]>(
1605           viz::ResourceSizes::CheckedSizeInBytes<size_t>(resource.size(),
1606                                                          kResourceFormat));
1607       resource.set_software_backing(std::move(backing));
1608     }
1609     auto* backing =
1610         static_cast<TestSoftwareBacking*>(resource.software_backing());
1611     return std::make_unique<TestRasterBuffer>(resource.size(),
1612                                               backing->pixels.get());
1613   }
1614
1615  private:
1616   class TestRasterBuffer : public RasterBuffer {
1617    public:
1618     TestRasterBuffer(const gfx::Size& size, void* pixels)
1619         : size_(size), pixels_(pixels) {}
1620
1621     void Playback(const RasterSource* raster_source,
1622                   const gfx::Rect& raster_full_rect,
1623                   const gfx::Rect& raster_dirty_rect,
1624                   uint64_t new_content_id,
1625                   const gfx::AxisTransform2d& transform,
1626                   const RasterSource::PlaybackSettings& playback_settings,
1627                   const GURL& url) override {
1628       RasterBufferProvider::PlaybackToMemory(
1629           pixels_, kResourceFormat, size_, /*stride=*/0, raster_source,
1630           raster_full_rect, /*playback_rect=*/raster_full_rect, transform,
1631           gfx::ColorSpace(), kIsGpuCompositing, playback_settings);
1632     }
1633
1634     bool SupportsBackgroundThreadPriority() const override { return true; }
1635
1636    private:
1637     gfx::Size size_;
1638     raw_ptr<void> pixels_;
1639   };
1640 };
1641
1642 class TileManagerTest : public TestLayerTreeHostBase {
1643  public:
1644   // MockLayerTreeHostImpl allows us to intercept tile manager callbacks.
1645   class MockLayerTreeHostImpl : public FakeLayerTreeHostImpl {
1646    public:
1647     MockLayerTreeHostImpl(const LayerTreeSettings& settings,
1648                           TaskRunnerProvider* task_runner_provider,
1649                           TaskGraphRunner* task_graph_runner)
1650         : FakeLayerTreeHostImpl(settings,
1651                                 task_runner_provider,
1652                                 task_graph_runner) {}
1653
1654     MOCK_METHOD0(NotifyReadyToActivate, void());
1655     MOCK_METHOD0(NotifyReadyToDraw, void());
1656     MOCK_METHOD0(NotifyAllTileTasksCompleted, void());
1657   };
1658
1659   std::unique_ptr<FakeLayerTreeHostImpl> CreateHostImpl(
1660       const LayerTreeSettings& settings,
1661       TaskRunnerProvider* task_runner_provider,
1662       TaskGraphRunner* task_graph_runner) override {
1663     return std::make_unique<testing::NiceMock<MockLayerTreeHostImpl>>(
1664         settings, task_runner_provider, task_graph_runner);
1665   }
1666
1667   // By default use software compositing (no context provider).
1668   std::unique_ptr<LayerTreeFrameSink> CreateLayerTreeFrameSink() override {
1669     return FakeLayerTreeFrameSink::CreateSoftware();
1670   }
1671
1672   MockLayerTreeHostImpl& MockHostImpl() {
1673     return *static_cast<MockLayerTreeHostImpl*>(host_impl());
1674   }
1675 };
1676
1677 // Test to ensure that we call NotifyAllTileTasksCompleted when PrepareTiles is
1678 // called.
1679 TEST_F(TileManagerTest, AllWorkFinished) {
1680   // Check with no tile work enqueued.
1681   {
1682     base::RunLoop run_loop;
1683     EXPECT_FALSE(
1684         host_impl()->tile_manager()->HasScheduledTileTasksForTesting());
1685     EXPECT_CALL(MockHostImpl(), NotifyReadyToDraw());
1686     EXPECT_CALL(MockHostImpl(), NotifyAllTileTasksCompleted())
1687         .WillOnce(testing::Invoke([&run_loop]() { run_loop.Quit(); }));
1688     host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
1689     EXPECT_TRUE(host_impl()->tile_manager()->HasScheduledTileTasksForTesting());
1690     run_loop.Run();
1691   }
1692
1693   // Check that the "schedule more work" path also triggers the expected
1694   // callback.
1695   {
1696     base::RunLoop run_loop;
1697     EXPECT_FALSE(
1698         host_impl()->tile_manager()->HasScheduledTileTasksForTesting());
1699     EXPECT_CALL(MockHostImpl(), NotifyReadyToDraw());
1700     EXPECT_CALL(MockHostImpl(), NotifyAllTileTasksCompleted())
1701         .WillOnce(testing::Invoke([&run_loop]() { run_loop.Quit(); }));
1702     host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
1703     host_impl()->tile_manager()->SetMoreTilesNeedToBeRasterizedForTesting();
1704     EXPECT_TRUE(host_impl()->tile_manager()->HasScheduledTileTasksForTesting());
1705     run_loop.Run();
1706   }
1707
1708   // Check that if callbacks are called by CheckIfMoreTilesNeedToBePrepared if
1709   // they haven't been called already.
1710   {
1711     base::RunLoop run_loop;
1712     EXPECT_FALSE(
1713         host_impl()->tile_manager()->HasScheduledTileTasksForTesting());
1714     EXPECT_CALL(MockHostImpl(), NotifyReadyToDraw());
1715     EXPECT_CALL(MockHostImpl(), NotifyAllTileTasksCompleted())
1716         .WillOnce(testing::Invoke([&run_loop]() { run_loop.Quit(); }));
1717     host_impl()->tile_manager()->ResetSignalsForTesting();
1718     host_impl()->tile_manager()->SetMoreTilesNeedToBeRasterizedForTesting();
1719     host_impl()->tile_manager()->CheckIfMoreTilesNeedToBePreparedForTesting();
1720     run_loop.Run();
1721   }
1722
1723   // Same test as above but with SMOOTHNESS_TAKES_PRIORITY.
1724   {
1725     base::RunLoop run_loop;
1726     EXPECT_FALSE(
1727         host_impl()->tile_manager()->HasScheduledTileTasksForTesting());
1728     EXPECT_CALL(MockHostImpl(), NotifyReadyToDraw());
1729     EXPECT_CALL(MockHostImpl(), NotifyAllTileTasksCompleted())
1730         .WillOnce(testing::Invoke([&run_loop]() { run_loop.Quit(); }));
1731     host_impl()->tile_manager()->ResetSignalsForTesting();
1732     auto global_state = host_impl()->global_tile_state();
1733     global_state.tree_priority = SMOOTHNESS_TAKES_PRIORITY;
1734     host_impl()->tile_manager()->SetGlobalStateForTesting(global_state);
1735     host_impl()->tile_manager()->SetMoreTilesNeedToBeRasterizedForTesting();
1736     host_impl()->tile_manager()->CheckIfMoreTilesNeedToBePreparedForTesting();
1737     run_loop.Run();
1738   }
1739 }
1740
1741 TEST_F(TileManagerTest, ActivateAndDrawWhenOOM) {
1742   SetupDefaultTrees(gfx::Size(1000, 1000));
1743
1744   auto global_state = host_impl()->global_tile_state();
1745   global_state.hard_memory_limit_in_bytes = 1u;
1746   global_state.soft_memory_limit_in_bytes = 1u;
1747
1748   {
1749     base::RunLoop run_loop;
1750     EXPECT_FALSE(
1751         host_impl()->tile_manager()->HasScheduledTileTasksForTesting());
1752     EXPECT_CALL(MockHostImpl(), NotifyReadyToActivate());
1753     EXPECT_CALL(MockHostImpl(), NotifyReadyToDraw());
1754     EXPECT_CALL(MockHostImpl(), NotifyAllTileTasksCompleted())
1755         .WillOnce(testing::Invoke([&run_loop]() { run_loop.Quit(); }));
1756     host_impl()->tile_manager()->PrepareTiles(global_state);
1757     EXPECT_TRUE(host_impl()->tile_manager()->HasScheduledTileTasksForTesting());
1758     run_loop.Run();
1759   }
1760
1761   EXPECT_TRUE(host_impl()->tile_manager()->IsReadyToDraw());
1762   EXPECT_TRUE(host_impl()->tile_manager()->IsReadyToActivate());
1763   EXPECT_TRUE(host_impl()->notify_tile_state_changed_called());
1764
1765   // Next PrepareTiles should skip NotifyTileStateChanged since all tiles
1766   // are marked oom already.
1767   {
1768     base::RunLoop run_loop;
1769     host_impl()->set_notify_tile_state_changed_called(false);
1770     EXPECT_CALL(MockHostImpl(), NotifyReadyToActivate());
1771     EXPECT_CALL(MockHostImpl(), NotifyReadyToDraw());
1772     EXPECT_CALL(MockHostImpl(), NotifyAllTileTasksCompleted())
1773         .WillOnce(testing::Invoke([&run_loop]() { run_loop.Quit(); }));
1774     host_impl()->tile_manager()->PrepareTiles(global_state);
1775     run_loop.Run();
1776     EXPECT_FALSE(host_impl()->notify_tile_state_changed_called());
1777   }
1778 }
1779
1780 class TileManagerOcclusionTest : public TileManagerTest {
1781  public:
1782   LayerTreeSettings CreateSettings() override {
1783     auto settings = TestLayerTreeHostBase::CreateSettings();
1784     settings.create_low_res_tiling = true;
1785     settings.use_occlusion_for_tile_prioritization = true;
1786     return settings;
1787   }
1788
1789   void PrepareTilesAndWaitUntilDone(
1790       const GlobalStateThatImpactsTilePriority& state) {
1791     base::RunLoop run_loop;
1792     EXPECT_CALL(MockHostImpl(), NotifyAllTileTasksCompleted())
1793         .WillOnce(testing::Invoke([&run_loop]() { run_loop.Quit(); }));
1794     tile_manager()->PrepareTiles(state);
1795     run_loop.Run();
1796     tile_manager()->CheckForCompletedTasks();
1797   }
1798
1799   TileManager* tile_manager() { return host_impl()->tile_manager(); }
1800 };
1801
1802 TEST_F(TileManagerOcclusionTest, OccludedTileEvictedForVisibleTile) {
1803   gfx::Size layer_bounds(256, 256);
1804   host_impl()->active_tree()->SetDeviceViewportRect(gfx::Rect(layer_bounds));
1805
1806   SetupPendingTree(FakeRasterSource::CreateFilledWithText(layer_bounds));
1807   const int initial_picture_id = pending_layer()->id();
1808   ActivateTree();
1809
1810   GlobalStateThatImpactsTilePriority global_state =
1811       host_impl()->global_tile_state();
1812   const LayerTreeSettings settings = CreateSettings();
1813   global_state.hard_memory_limit_in_bytes =
1814       global_state.soft_memory_limit_in_bytes =
1815           settings.default_tile_size.GetArea() * 4 + 1;
1816
1817   // Call PrepareTiles and wait for it to complete. It's necessary to wait for
1818   // completion so that the resource is pushed to the tile, which is used
1819   // in calculating eviction.
1820   PrepareTilesAndWaitUntilDone(global_state);
1821
1822   // At this point the initial PictureLayerImpl should have a Tile with a
1823   // resource.
1824   {
1825     PictureLayerImpl* initial_layer = static_cast<PictureLayerImpl*>(
1826         host_impl()->active_tree()->LayerById(initial_picture_id));
1827     ASSERT_NE(initial_layer, nullptr);
1828     ASSERT_EQ(1u, initial_layer->picture_layer_tiling_set()->num_tilings());
1829     std::vector<Tile*> initial_layer_tiles =
1830         initial_layer->picture_layer_tiling_set()
1831             ->tiling_at(0)
1832             ->AllTilesForTesting();
1833     ASSERT_EQ(1u, initial_layer_tiles.size());
1834     EXPECT_TRUE(initial_layer_tiles[0]->draw_info().has_resource());
1835   }
1836
1837   // Add another layer on top. As there is only enough memory for one tile,
1838   // the top most tile should get a raster task and the bottom layer should
1839   // not.
1840   SetupPendingTree(FakeRasterSource::CreateFilledWithText(layer_bounds));
1841
1842   // Advance the frame to ensure PictureLayerTilingSet applies the occlusion to
1843   // the PictureLayerTiling. The amount of time advanced doesn't matter.
1844   host_impl()->AdvanceToNextFrame(base::Seconds(2));
1845
1846   auto* picture_layer = AddLayer<FakePictureLayerImpl>(
1847       host_impl()->pending_tree(),
1848       FakeRasterSource::CreateFilledWithText(layer_bounds));
1849   const int top_most_layer_id = picture_layer->id();
1850   picture_layer->SetDrawsContent(true);
1851   picture_layer->SetContentsOpaque(true);
1852   CopyProperties(pending_layer(), picture_layer);
1853   ActivateTree();
1854   PrepareTilesAndWaitUntilDone(global_state);
1855   {
1856     PictureLayerImpl* initial_layer = static_cast<PictureLayerImpl*>(
1857         host_impl()->active_tree()->LayerById(initial_picture_id));
1858     ASSERT_NE(initial_layer, nullptr);
1859     ASSERT_EQ(1u, initial_layer->picture_layer_tiling_set()->num_tilings());
1860     std::vector<Tile*> initial_layer_tiles =
1861         initial_layer->picture_layer_tiling_set()
1862             ->tiling_at(0)
1863             ->AllTilesForTesting();
1864     ASSERT_EQ(1u, initial_layer_tiles.size());
1865     EXPECT_FALSE(initial_layer_tiles[0]->draw_info().has_resource());
1866
1867     PictureLayerImpl* top_most_layer = static_cast<PictureLayerImpl*>(
1868         host_impl()->active_tree()->LayerById(top_most_layer_id));
1869     ASSERT_NE(top_most_layer, nullptr);
1870     ASSERT_EQ(1u, top_most_layer->picture_layer_tiling_set()->num_tilings());
1871     std::vector<Tile*> top_most_layer_tiles =
1872         top_most_layer->picture_layer_tiling_set()
1873             ->tiling_at(0)
1874             ->AllTilesForTesting();
1875     ASSERT_EQ(1u, top_most_layer_tiles.size());
1876     EXPECT_TRUE(top_most_layer_tiles[0]->draw_info().has_resource());
1877   }
1878 }
1879
1880 class PixelInspectTileManagerTest : public TileManagerTest {
1881  public:
1882   ~PixelInspectTileManagerTest() override {
1883     // Ensure that the host impl doesn't outlive |raster_buffer_provider_|.
1884     TakeHostImpl();
1885   }
1886
1887   void SetUp() override {
1888     TileManagerTest::SetUp();
1889     // Use a RasterBufferProvider that will let us inspect pixels.
1890     host_impl()->tile_manager()->SetRasterBufferProviderForTesting(
1891         &raster_buffer_provider_);
1892   }
1893
1894  private:
1895   TestSoftwareRasterBufferProvider raster_buffer_provider_;
1896 };
1897
1898 TEST_F(PixelInspectTileManagerTest, LowResHasNoImage) {
1899   gfx::Size size(10, 12);
1900   TileResolution resolutions[] = {HIGH_RESOLUTION, LOW_RESOLUTION};
1901
1902   for (size_t i = 0; i < std::size(resolutions); ++i) {
1903     SCOPED_TRACE(resolutions[i]);
1904
1905     // Make a RasterSource that will draw a blue bitmap image.
1906     sk_sp<SkSurface> surface =
1907         SkSurface::MakeRasterN32Premul(size.width(), size.height());
1908     ASSERT_NE(surface, nullptr);
1909     surface->getCanvas()->clear(SK_ColorBLUE);
1910     sk_sp<SkImage> blue_image = surface->makeImageSnapshot();
1911
1912     std::unique_ptr<FakeRecordingSource> recording_source =
1913         FakeRecordingSource::CreateFilledRecordingSource(size);
1914     recording_source->SetBackgroundColor(SkColors::kTransparent);
1915     recording_source->SetRequiresClear(true);
1916     PaintFlags flags;
1917     flags.setColor(SK_ColorGREEN);
1918     recording_source->add_draw_rect_with_flags(gfx::Rect(size), flags);
1919     recording_source->add_draw_image(std::move(blue_image), gfx::Point());
1920     recording_source->Rerecord();
1921     scoped_refptr<RasterSource> raster = recording_source->CreateRasterSource();
1922
1923     FakePictureLayerTilingClient tiling_client;
1924     tiling_client.SetTileSize(size);
1925
1926     std::unique_ptr<PictureLayerImpl> layer =
1927         PictureLayerImpl::Create(host_impl()->active_tree(), 1);
1928     PictureLayerTilingSet* tiling_set = layer->picture_layer_tiling_set();
1929     layer->set_contributes_to_drawn_render_surface(true);
1930
1931     auto* tiling = tiling_set->AddTiling(gfx::AxisTransform2d(), raster);
1932     tiling->set_resolution(resolutions[i]);
1933     tiling->CreateAllTilesForTesting();
1934     tiling->SetTilePriorityRectsForTesting(
1935         gfx::Rect(size),   // Visible rect.
1936         gfx::Rect(size),   // Skewport rect.
1937         gfx::Rect(size),   // Soon rect.
1938         gfx::Rect(size));  // Eventually rect.
1939
1940     // SMOOTHNESS_TAKES_PRIORITY ensures that we will actually raster
1941     // LOW_RESOLUTION tiles, otherwise they are skipped.
1942     host_impl()->SetTreePriority(SMOOTHNESS_TAKES_PRIORITY);
1943
1944     // Call PrepareTiles and wait for it to complete.
1945     auto* tile_manager = host_impl()->tile_manager();
1946     base::RunLoop run_loop;
1947     EXPECT_CALL(MockHostImpl(), NotifyAllTileTasksCompleted())
1948         .WillOnce(testing::Invoke([&run_loop]() { run_loop.Quit(); }));
1949     tile_manager->PrepareTiles(host_impl()->global_tile_state());
1950     run_loop.Run();
1951     tile_manager->CheckForCompletedTasks();
1952
1953     Tile* tile = tiling->TileAt(0, 0);
1954     // The tile in the tiling was rastered.
1955     EXPECT_EQ(TileDrawInfo::RESOURCE_MODE, tile->draw_info().mode());
1956     EXPECT_TRUE(tile->draw_info().IsReadyToDraw());
1957
1958     gfx::Size resource_size = tile->draw_info().resource_size();
1959     SkColorType ct = ResourceFormatToClosestSkColorType(
1960         TestSoftwareRasterBufferProvider::kIsGpuCompositing,
1961         TestSoftwareRasterBufferProvider::kResourceFormat);
1962     auto info = SkImageInfo::Make(resource_size.width(), resource_size.height(),
1963                                   ct, kPremul_SkAlphaType);
1964     // CreateLayerTreeFrameSink() sets up a software compositing, so the
1965     // tile resource will be a bitmap.
1966     auto* backing = static_cast<TestSoftwareBacking*>(
1967         tile->draw_info().GetResource().software_backing());
1968     SkBitmap bitmap;
1969     bitmap.installPixels(info, backing->pixels.get(), info.minRowBytes());
1970
1971     for (int x = 0; x < size.width(); ++x) {
1972       for (int y = 0; y < size.height(); ++y) {
1973         SCOPED_TRACE(y);
1974         SCOPED_TRACE(x);
1975         if (resolutions[i] == LOW_RESOLUTION) {
1976           // Since it's low res, the bitmap was not drawn, and the background
1977           // (green) is visible instead.
1978           ASSERT_EQ(SK_ColorGREEN, bitmap.getColor(x, y));
1979         } else {
1980           EXPECT_EQ(HIGH_RESOLUTION, resolutions[i]);
1981           // Since it's high res, the bitmap (blue) was drawn, and the
1982           // background is not visible.
1983           ASSERT_EQ(SK_ColorBLUE, bitmap.getColor(x, y));
1984         }
1985       }
1986     }
1987   }
1988 }
1989
1990 class ActivationTasksDoNotBlockReadyToDrawTest : public TileManagerTest {
1991  protected:
1992   std::unique_ptr<TaskGraphRunner> CreateTaskGraphRunner() override {
1993     return std::make_unique<SynchronousTaskGraphRunner>();
1994   }
1995
1996   std::unique_ptr<LayerTreeFrameSink> CreateLayerTreeFrameSink() override {
1997     return FakeLayerTreeFrameSink::Create3dForGpuRasterization();
1998   }
1999 };
2000
2001 TEST_F(ActivationTasksDoNotBlockReadyToDrawTest,
2002        ActivationTasksDoNotBlockReadyToDraw) {
2003   const gfx::Size layer_bounds(1000, 1000);
2004
2005   EXPECT_TRUE(host_impl()->use_gpu_rasterization());
2006
2007   // Active tree has no non-solid tiles, so it will generate no tile tasks.
2008   std::unique_ptr<FakeRecordingSource> active_tree_recording_source =
2009       FakeRecordingSource::CreateFilledRecordingSource(layer_bounds);
2010
2011   PaintFlags solid_flags;
2012   SkColor solid_color = SkColorSetARGB(255, 12, 23, 34);
2013   solid_flags.setColor(solid_color);
2014   active_tree_recording_source->add_draw_rect_with_flags(
2015       gfx::Rect(layer_bounds), solid_flags);
2016
2017   active_tree_recording_source->Rerecord();
2018
2019   // Pending tree has non-solid tiles, so it will generate tile tasks.
2020   std::unique_ptr<FakeRecordingSource> pending_tree_recording_source =
2021       FakeRecordingSource::CreateFilledRecordingSource(layer_bounds);
2022   SkColor non_solid_color = SkColorSetARGB(128, 45, 56, 67);
2023   PaintFlags non_solid_flags;
2024   non_solid_flags.setColor(non_solid_color);
2025
2026   pending_tree_recording_source->add_draw_rect_with_flags(
2027       gfx::Rect(5, 5, 10, 10), non_solid_flags);
2028   pending_tree_recording_source->Rerecord();
2029
2030   scoped_refptr<RasterSource> active_tree_raster_source =
2031       active_tree_recording_source->CreateRasterSource();
2032   scoped_refptr<RasterSource> pending_tree_raster_source =
2033       pending_tree_recording_source->CreateRasterSource();
2034
2035   SetupTrees(pending_tree_raster_source, active_tree_raster_source);
2036   host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
2037
2038   // The first task to run should be ReadyToDraw (this should not be blocked by
2039   // the tasks required for activation).
2040   base::RunLoop run_loop;
2041   EXPECT_CALL(MockHostImpl(), NotifyReadyToDraw())
2042       .WillOnce(testing::Invoke([&run_loop]() { run_loop.Quit(); }));
2043   static_cast<SynchronousTaskGraphRunner*>(task_graph_runner())
2044       ->RunSingleTaskForTesting();
2045   run_loop.Run();
2046 }
2047
2048 class PartialRasterTileManagerTest : public TileManagerTest {
2049  public:
2050   LayerTreeSettings CreateSettings() override {
2051     auto settings = TileManagerTest::CreateSettings();
2052     settings.use_partial_raster = true;
2053     return settings;
2054   }
2055 };
2056
2057 // Ensures that if a raster task is cancelled, it gets returned to the resource
2058 // pool with an invalid content ID, not with its invalidated content ID.
2059 TEST_F(PartialRasterTileManagerTest, CancelledTasksHaveNoContentId) {
2060   // Create a FakeTileTaskManagerImpl and set it on the tile manager so that all
2061   // scheduled work is immediately cancelled.
2062
2063   host_impl()->tile_manager()->SetTileTaskManagerForTesting(
2064       std::make_unique<FakeTileTaskManagerImpl>());
2065
2066   // Pick arbitrary IDs - they don't really matter as long as they're constant.
2067   const int kLayerId = 7;
2068   const uint64_t kInvalidatedId = 43;
2069   const gfx::Size kTileSize(128, 128);
2070
2071   scoped_refptr<FakeRasterSource> pending_raster_source =
2072       FakeRasterSource::CreateFilled(kTileSize);
2073   host_impl()->CreatePendingTree();
2074   LayerTreeImpl* pending_tree = host_impl()->pending_tree();
2075   pending_tree->SetDeviceViewportRect(
2076       host_impl()->active_tree()->GetDeviceViewport());
2077
2078   // Steal from the recycled tree.
2079   std::unique_ptr<FakePictureLayerImpl> pending_layer =
2080       FakePictureLayerImpl::Create(pending_tree, kLayerId,
2081                                    pending_raster_source);
2082   pending_layer->SetDrawsContent(true);
2083
2084   // The bounds() just mirror the raster source size.
2085   pending_layer->SetBounds(pending_layer->raster_source()->GetSize());
2086   SetupRootProperties(pending_layer.get());
2087   pending_tree->SetRootLayerForTesting(std::move(pending_layer));
2088
2089   // Add tilings/tiles for the layer.
2090   UpdateDrawProperties(host_impl()->pending_tree());
2091
2092   // Build the raster queue and invalidate the top tile.
2093   std::unique_ptr<RasterTilePriorityQueue> queue(host_impl()->BuildRasterQueue(
2094       SAME_PRIORITY_FOR_BOTH_TREES, RasterTilePriorityQueue::Type::ALL));
2095   EXPECT_FALSE(queue->IsEmpty());
2096   queue->Top().tile()->SetInvalidated(gfx::Rect(), kInvalidatedId);
2097
2098   // PrepareTiles to schedule tasks. Due to the FakeTileTaskManagerImpl,
2099   // these tasks will immediately be canceled.
2100   host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
2101
2102   // Make sure that the tile we invalidated above was not returned to the pool
2103   // with its invalidated resource ID.
2104   gfx::Rect total_invalidated_rect;
2105   EXPECT_FALSE(host_impl()->resource_pool()->TryAcquireResourceForPartialRaster(
2106       kInvalidatedId + 1, gfx::Rect(), kInvalidatedId, &total_invalidated_rect,
2107       gfx::ColorSpace::CreateSRGB()));
2108   EXPECT_EQ(gfx::Rect(), total_invalidated_rect);
2109
2110   // Free our host_impl_ before the tile_task_manager we passed it, as it
2111   // will use that class in clean up.
2112   TakeHostImpl();
2113 }
2114
2115 // FakeRasterBufferProviderImpl that verifies the resource content ID of raster
2116 // tasks.
2117 class VerifyResourceContentIdRasterBufferProvider
2118     : public FakeRasterBufferProviderImpl {
2119  public:
2120   explicit VerifyResourceContentIdRasterBufferProvider(
2121       uint64_t expected_content_id)
2122       : expected_content_id_(expected_content_id) {}
2123   ~VerifyResourceContentIdRasterBufferProvider() override = default;
2124
2125   // RasterBufferProvider methods.
2126   std::unique_ptr<RasterBuffer> AcquireBufferForRaster(
2127       const ResourcePool::InUsePoolResource& resource,
2128       uint64_t resource_content_id,
2129       uint64_t previous_content_id,
2130       bool depends_on_at_raster_decodes,
2131       bool depends_on_hardware_accelerated_jpeg_candidates,
2132       bool depends_on_hardware_accelerated_webp_candidates) override {
2133     EXPECT_EQ(expected_content_id_, resource_content_id);
2134     return nullptr;
2135   }
2136
2137  private:
2138   uint64_t expected_content_id_;
2139 };
2140
2141 // Runs a test to ensure that partial raster is either enabled or disabled,
2142 // depending on |partial_raster_enabled|'s value. Takes ownership of host_impl
2143 // so that cleanup order can be controlled.
2144 void RunPartialRasterCheck(std::unique_ptr<LayerTreeHostImpl> host_impl,
2145                            bool partial_raster_enabled) {
2146   // Pick arbitrary IDs - they don't really matter as long as they're constant.
2147   const int kLayerId = 7;
2148   const uint64_t kInvalidatedId = 43;
2149   const uint64_t kExpectedId = partial_raster_enabled ? kInvalidatedId : 0u;
2150   const gfx::Size kTileSize(128, 128);
2151
2152   // Create a VerifyResourceContentIdTileTaskManager to ensure that the
2153   // raster task we see is created with |kExpectedId|.
2154   host_impl->tile_manager()->SetTileTaskManagerForTesting(
2155       std::make_unique<FakeTileTaskManagerImpl>());
2156
2157   VerifyResourceContentIdRasterBufferProvider raster_buffer_provider(
2158       kExpectedId);
2159   host_impl->tile_manager()->SetRasterBufferProviderForTesting(
2160       &raster_buffer_provider);
2161
2162   // Ensure there's a resource with our |kInvalidatedId| in the resource pool.
2163   ResourcePool::InUsePoolResource resource =
2164       host_impl->resource_pool()->AcquireResource(
2165           kTileSize, viz::RGBA_8888, gfx::ColorSpace::CreateSRGB());
2166
2167   resource.set_software_backing(std::make_unique<TestSoftwareBacking>());
2168   host_impl->resource_pool()->PrepareForExport(resource);
2169
2170   host_impl->resource_pool()->OnContentReplaced(resource, kInvalidatedId);
2171   host_impl->resource_pool()->ReleaseResource(std::move(resource));
2172
2173   scoped_refptr<FakeRasterSource> pending_raster_source =
2174       FakeRasterSource::CreateFilled(kTileSize);
2175   host_impl->CreatePendingTree();
2176   LayerTreeImpl* pending_tree = host_impl->pending_tree();
2177   pending_tree->SetDeviceViewportRect(
2178       host_impl->active_tree()->GetDeviceViewport());
2179
2180   std::unique_ptr<FakePictureLayerImpl> pending_layer =
2181       FakePictureLayerImpl::Create(pending_tree, kLayerId,
2182                                    pending_raster_source);
2183   pending_layer->SetDrawsContent(true);
2184
2185   // The bounds() just mirror the raster source size.
2186   pending_layer->SetBounds(pending_layer->raster_source()->GetSize());
2187   SetupRootProperties(pending_layer.get());
2188   pending_tree->SetRootLayerForTesting(std::move(pending_layer));
2189
2190   // Add tilings/tiles for the layer.
2191   UpdateDrawProperties(pending_tree);
2192
2193   // Build the raster queue and invalidate the top tile.
2194   std::unique_ptr<RasterTilePriorityQueue> queue(host_impl->BuildRasterQueue(
2195       SAME_PRIORITY_FOR_BOTH_TREES, RasterTilePriorityQueue::Type::ALL));
2196   EXPECT_FALSE(queue->IsEmpty());
2197   queue->Top().tile()->SetInvalidated(gfx::Rect(), kInvalidatedId);
2198
2199   // PrepareTiles to schedule tasks. Due to the
2200   // VerifyPreviousContentRasterBufferProvider, these tasks will verified and
2201   // cancelled.
2202   host_impl->tile_manager()->PrepareTiles(host_impl->global_tile_state());
2203
2204   // Free our host_impl before the verifying_task_manager we passed it, as it
2205   // will use that class in clean up.
2206   host_impl = nullptr;
2207 }
2208
2209 void RunPartialTileDecodeCheck(std::unique_ptr<LayerTreeHostImpl> host_impl,
2210                                bool partial_raster_enabled) {
2211   // Pick arbitrary IDs - they don't really matter as long as they're constant.
2212   const int kLayerId = 7;
2213   const uint64_t kInvalidatedId = 43;
2214   const uint64_t kExpectedId = partial_raster_enabled ? kInvalidatedId : 0u;
2215   const gfx::Size kTileSize(400, 400);
2216
2217   host_impl->tile_manager()->SetTileTaskManagerForTesting(
2218       std::make_unique<FakeTileTaskManagerImpl>());
2219
2220   // Create a VerifyResourceContentIdTileTaskManager to ensure that the
2221   // raster task we see is created with |kExpectedId|.
2222   VerifyResourceContentIdRasterBufferProvider raster_buffer_provider(
2223       kExpectedId);
2224   host_impl->tile_manager()->SetRasterBufferProviderForTesting(
2225       &raster_buffer_provider);
2226
2227   // Ensure there's a resource with our |kInvalidatedId| in the resource pool.
2228   ResourcePool::InUsePoolResource resource =
2229       host_impl->resource_pool()->AcquireResource(
2230           kTileSize, viz::RGBA_8888, gfx::ColorSpace::CreateSRGB());
2231   host_impl->resource_pool()->OnContentReplaced(resource, kInvalidatedId);
2232   host_impl->resource_pool()->ReleaseResource(std::move(resource));
2233
2234   const gfx::Size layer_bounds(500, 500);
2235
2236   std::unique_ptr<FakeRecordingSource> recording_source =
2237       FakeRecordingSource::CreateFilledRecordingSource(layer_bounds);
2238   recording_source->set_fill_with_nonsolid_color(true);
2239
2240   int dimension = 250;
2241   PaintImage image1 =
2242       CreateDiscardablePaintImage(gfx::Size(dimension, dimension));
2243   PaintImage image2 =
2244       CreateDiscardablePaintImage(gfx::Size(dimension, dimension));
2245   PaintImage image3 =
2246       CreateDiscardablePaintImage(gfx::Size(dimension, dimension));
2247   PaintImage image4 =
2248       CreateDiscardablePaintImage(gfx::Size(dimension, dimension));
2249   recording_source->add_draw_image(image1, gfx::Point(0, 0));
2250   recording_source->add_draw_image(image2, gfx::Point(300, 0));
2251   recording_source->add_draw_image(image3, gfx::Point(0, 300));
2252   recording_source->add_draw_image(image4, gfx::Point(300, 300));
2253
2254   recording_source->Rerecord();
2255
2256   scoped_refptr<FakeRasterSource> pending_raster_source =
2257       FakeRasterSource::CreateFromRecordingSource(recording_source.get());
2258
2259   host_impl->CreatePendingTree();
2260   LayerTreeImpl* pending_tree = host_impl->pending_tree();
2261   pending_tree->SetDeviceViewportRect(
2262       host_impl->active_tree()->GetDeviceViewport());
2263
2264   // Steal from the recycled tree.
2265   std::unique_ptr<FakePictureLayerImpl> pending_layer =
2266       FakePictureLayerImpl::Create(pending_tree, kLayerId,
2267                                    pending_raster_source);
2268   pending_layer->SetDrawsContent(true);
2269
2270   // The bounds() just mirror the raster source size.
2271   pending_layer->SetBounds(pending_layer->raster_source()->GetSize());
2272   SetupRootProperties(pending_layer.get());
2273   pending_tree->SetRootLayerForTesting(std::move(pending_layer));
2274
2275   // Add tilings/tiles for the layer.
2276   UpdateDrawProperties(pending_tree);
2277
2278   // Build the raster queue and invalidate the top tile if partial raster is
2279   // enabled.
2280   std::unique_ptr<RasterTilePriorityQueue> queue(host_impl->BuildRasterQueue(
2281       SAME_PRIORITY_FOR_BOTH_TREES, RasterTilePriorityQueue::Type::ALL));
2282   ASSERT_FALSE(queue->IsEmpty());
2283   Tile* tile = queue->Top().tile();
2284   if (partial_raster_enabled)
2285     tile->SetInvalidated(gfx::Rect(200, 200), kInvalidatedId);
2286
2287   // PrepareTiles to schedule tasks. Due to the
2288   // VerifyPreviousContentRasterBufferProvider, these tasks will verified and
2289   // cancelled.
2290   host_impl->tile_manager()->PrepareTiles(host_impl->global_tile_state());
2291
2292   // Tile will have 1 dependent decode task if we decode images only in the
2293   // invalidated rect. Otherwise it will have 4.
2294   EXPECT_EQ(
2295       host_impl->tile_manager()->decode_tasks_for_testing(tile->id()).size(),
2296       partial_raster_enabled ? 1u : 4u);
2297
2298   // Free our host_impl before the verifying_task_manager we passed it, as it
2299   // will use that class in clean up.
2300   host_impl = nullptr;
2301 }
2302
2303 // Ensures that the tile manager successfully reuses tiles when partial
2304 // raster is enabled.
2305 TEST_F(PartialRasterTileManagerTest, PartialRasterSuccessfullyEnabled) {
2306   RunPartialRasterCheck(TakeHostImpl(), true /* partial_raster_enabled */);
2307 }
2308
2309 TEST_F(PartialRasterTileManagerTest, PartialTileImageDecode) {
2310   RunPartialTileDecodeCheck(TakeHostImpl(), true /* partial_raster_enabled */);
2311 }
2312
2313 TEST_F(PartialRasterTileManagerTest, CompleteTileImageDecode) {
2314   RunPartialTileDecodeCheck(TakeHostImpl(),
2315                             false /* partial_raster_disabled */);
2316 }
2317
2318 // Ensures that the tile manager does not attempt to reuse tiles when partial
2319 // raster is disabled.
2320 TEST_F(TileManagerTest, PartialRasterSuccessfullyDisabled) {
2321   RunPartialRasterCheck(TakeHostImpl(), false /* partial_raster_enabled */);
2322 }
2323
2324 class InvalidResourceRasterBufferProvider
2325     : public FakeRasterBufferProviderImpl {
2326  public:
2327   std::unique_ptr<RasterBuffer> AcquireBufferForRaster(
2328       const ResourcePool::InUsePoolResource& resource,
2329       uint64_t resource_content_id,
2330       uint64_t previous_content_id,
2331       bool depends_on_at_raster_decodes,
2332       bool depends_on_hardware_accelerated_jpeg_candidates,
2333       bool depends_on_hardware_accelerated_webp_candidates) override {
2334     if (!resource.gpu_backing()) {
2335       auto backing = std::make_unique<StubGpuBacking>();
2336       // Don't set a mailbox to signal invalid resource.
2337       backing->texture_target = 5;
2338       resource.set_gpu_backing(std::move(backing));
2339     }
2340     return std::make_unique<FakeRasterBuffer>();
2341   }
2342
2343  private:
2344   class StubGpuBacking : public ResourcePool::GpuBacking {
2345    public:
2346     void OnMemoryDump(
2347         base::trace_event::ProcessMemoryDump* pmd,
2348         const base::trace_event::MemoryAllocatorDumpGuid& buffer_dump_guid,
2349         uint64_t tracing_process_id,
2350         int importance) const override {}
2351   };
2352 };
2353
2354 class InvalidResourceTileManagerTest : public TileManagerTest {
2355  protected:
2356   std::unique_ptr<LayerTreeFrameSink> CreateLayerTreeFrameSink() override {
2357     return FakeLayerTreeFrameSink::Create3d();
2358   }
2359 };
2360
2361 TEST_F(InvalidResourceTileManagerTest, InvalidResource) {
2362   auto* tile_manager = host_impl()->tile_manager();
2363   InvalidResourceRasterBufferProvider raster_buffer_provider;
2364   tile_manager->SetRasterBufferProviderForTesting(&raster_buffer_provider);
2365
2366   gfx::Size size(10, 12);
2367   FakePictureLayerTilingClient tiling_client;
2368   tiling_client.SetTileSize(size);
2369
2370   std::unique_ptr<PictureLayerImpl> layer =
2371       PictureLayerImpl::Create(host_impl()->active_tree(), 1);
2372   layer->set_contributes_to_drawn_render_surface(true);
2373
2374   auto* tiling = layer->picture_layer_tiling_set()->AddTiling(
2375       gfx::AxisTransform2d(), FakeRasterSource::CreateFilled(size));
2376   tiling->set_resolution(HIGH_RESOLUTION);
2377   tiling->CreateAllTilesForTesting();
2378   tiling->SetTilePriorityRectsForTesting(gfx::Rect(size),   // Visible rect.
2379                                          gfx::Rect(size),   // Skewport rect.
2380                                          gfx::Rect(size),   // Soon rect.
2381                                          gfx::Rect(size));  // Eventually rect.
2382
2383   base::RunLoop run_loop;
2384   EXPECT_CALL(MockHostImpl(), NotifyAllTileTasksCompleted())
2385       .WillOnce(testing::Invoke([&run_loop]() { run_loop.Quit(); }));
2386   tile_manager->PrepareTiles(host_impl()->global_tile_state());
2387   run_loop.Run();
2388   tile_manager->CheckForCompletedTasks();
2389
2390   Tile* tile = tiling->TileAt(0, 0);
2391   ASSERT_TRUE(tile);
2392   // The tile in the tiling was rastered, but didn't get a resource.
2393   EXPECT_TRUE(tile->draw_info().IsReadyToDraw());
2394   EXPECT_EQ(TileDrawInfo::OOM_MODE, tile->draw_info().mode());
2395
2396   // Ensure that the host impl doesn't outlive |raster_buffer_provider|.
2397   layer = nullptr;
2398   TakeHostImpl();
2399 }
2400
2401 // FakeRasterBufferProviderImpl that allows us to mock ready to draw
2402 // functionality.
2403 class MockReadyToDrawRasterBufferProviderImpl
2404     : public FakeRasterBufferProviderImpl {
2405  public:
2406   MOCK_CONST_METHOD1(IsResourceReadyToDraw,
2407                      bool(const ResourcePool::InUsePoolResource& resource));
2408   MOCK_CONST_METHOD3(
2409       SetReadyToDrawCallback,
2410       uint64_t(
2411           const std::vector<const ResourcePool::InUsePoolResource*>& resources,
2412           base::OnceClosure callback,
2413           uint64_t pending_callback_id));
2414
2415   std::unique_ptr<RasterBuffer> AcquireBufferForRaster(
2416       const ResourcePool::InUsePoolResource& resource,
2417       uint64_t resource_content_id,
2418       uint64_t previous_content_id,
2419       bool depends_on_at_raster_decodes,
2420       bool depends_on_hardware_accelerated_jpeg_candidates,
2421       bool depends_on_hardware_accelerated_webp_candidates) override {
2422     if (!resource.software_backing())
2423       resource.set_software_backing(std::make_unique<TestSoftwareBacking>());
2424     return std::make_unique<FakeRasterBuffer>();
2425   }
2426 };
2427
2428 class TileManagerReadyToDrawTest : public TileManagerTest {
2429  public:
2430   ~TileManagerReadyToDrawTest() override {
2431     // Ensure that the host impl doesn't outlive |raster_buffer_provider_|.
2432     TakeHostImpl();
2433   }
2434
2435   void SetUp() override {
2436     TileManagerTest::SetUp();
2437     host_impl()->tile_manager()->SetRasterBufferProviderForTesting(
2438         &mock_raster_buffer_provider_);
2439
2440     const gfx::Size layer_bounds(1000, 1000);
2441
2442     solid_color_recording_source_ =
2443         FakeRecordingSource::CreateFilledRecordingSource(layer_bounds);
2444
2445     PaintFlags solid_flags;
2446     SkColor solid_color = SkColorSetARGB(255, 12, 23, 34);
2447     solid_flags.setColor(solid_color);
2448     solid_color_recording_source_->add_draw_rect_with_flags(
2449         gfx::Rect(layer_bounds), solid_flags);
2450
2451     solid_color_recording_source_->Rerecord();
2452
2453     recording_source_ =
2454         FakeRecordingSource::CreateFilledRecordingSource(layer_bounds);
2455     SkColor non_solid_color = SkColorSetARGB(128, 45, 56, 67);
2456     PaintFlags non_solid_flags;
2457     non_solid_flags.setColor(non_solid_color);
2458
2459     for (int i = 0; i < 100; ++i) {
2460       for (int j = 0; j < 100; ++j) {
2461         recording_source_->add_draw_rect_with_flags(
2462             gfx::Rect(10 * i, 10 * j, 5, 5), non_solid_flags);
2463       }
2464     }
2465     recording_source_->Rerecord();
2466   }
2467
2468   void SetupTreesWithActiveTreeTiles() {
2469     scoped_refptr<RasterSource> active_tree_raster_source =
2470         recording_source_->CreateRasterSource();
2471     scoped_refptr<RasterSource> pending_tree_raster_source =
2472         solid_color_recording_source_->CreateRasterSource();
2473
2474     SetupTrees(pending_tree_raster_source, active_tree_raster_source);
2475   }
2476
2477   void SetupTreesWithPendingTreeTiles() {
2478     scoped_refptr<RasterSource> active_tree_raster_source =
2479         solid_color_recording_source_->CreateRasterSource();
2480     scoped_refptr<RasterSource> pending_tree_raster_source =
2481         recording_source_->CreateRasterSource();
2482
2483     SetupTrees(pending_tree_raster_source, active_tree_raster_source);
2484   }
2485
2486   TileManager* tile_manager() { return host_impl()->tile_manager(); }
2487   MockReadyToDrawRasterBufferProviderImpl* mock_raster_buffer_provider() {
2488     return &mock_raster_buffer_provider_;
2489   }
2490
2491  private:
2492   StrictMock<MockReadyToDrawRasterBufferProviderImpl>
2493       mock_raster_buffer_provider_;
2494   std::unique_ptr<FakeRecordingSource> recording_source_;
2495   std::unique_ptr<FakeRecordingSource> solid_color_recording_source_;
2496 };
2497
2498 TEST_F(TileManagerReadyToDrawTest, SmoothActivationWaitsOnCallback) {
2499   host_impl()->SetTreePriority(SMOOTHNESS_TAKES_PRIORITY);
2500   SetupTreesWithPendingTreeTiles();
2501
2502   base::OnceClosure callback;
2503   {
2504     base::RunLoop run_loop;
2505
2506     // Until we activate our ready to draw callback, treat all resources as not
2507     // ready to draw.
2508     EXPECT_CALL(*mock_raster_buffer_provider(),
2509                 IsResourceReadyToDraw(testing::_))
2510         .WillRepeatedly(Return(false));
2511
2512     EXPECT_CALL(*mock_raster_buffer_provider(), SetReadyToDrawCallback(_, _, 0))
2513         .WillOnce([&run_loop, &callback](
2514                       const std::vector<const ResourcePool::InUsePoolResource*>&
2515                           resources,
2516                       base::OnceClosure callback_in,
2517                       uint64_t pending_callback_id) {
2518           callback = std::move(callback_in);
2519           run_loop.Quit();
2520           return 1;
2521         });
2522     host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
2523     run_loop.Run();
2524   }
2525
2526   EXPECT_TRUE(host_impl()->tile_manager()->IsReadyToDraw());
2527   EXPECT_FALSE(host_impl()->tile_manager()->IsReadyToActivate());
2528
2529   {
2530     base::RunLoop run_loop;
2531     EXPECT_CALL(MockHostImpl(), NotifyReadyToActivate())
2532         .WillOnce(Invoke([&run_loop]() { run_loop.Quit(); }));
2533     EXPECT_CALL(*mock_raster_buffer_provider(),
2534                 IsResourceReadyToDraw(testing::_))
2535         .WillRepeatedly(Return(true));
2536     std::move(callback).Run();
2537     run_loop.Run();
2538   }
2539
2540   EXPECT_TRUE(host_impl()->tile_manager()->IsReadyToDraw());
2541   EXPECT_TRUE(host_impl()->tile_manager()->IsReadyToActivate());
2542 }
2543
2544 TEST_F(TileManagerReadyToDrawTest, NonSmoothActivationDoesNotWaitOnCallback) {
2545   SetupTreesWithPendingTreeTiles();
2546
2547   // We're using a StrictMock on the RasterBufferProvider, so any function call
2548   // will cause a test failure.
2549   base::RunLoop run_loop;
2550
2551   host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
2552   EXPECT_CALL(MockHostImpl(), NotifyReadyToActivate())
2553       .WillOnce(Invoke([&run_loop]() { run_loop.Quit(); }));
2554   run_loop.Run();
2555
2556   EXPECT_TRUE(host_impl()->tile_manager()->IsReadyToDraw());
2557   EXPECT_TRUE(host_impl()->tile_manager()->IsReadyToActivate());
2558 }
2559
2560 TEST_F(TileManagerReadyToDrawTest, SmoothDrawWaitsOnCallback) {
2561   host_impl()->SetTreePriority(SMOOTHNESS_TAKES_PRIORITY);
2562   SetupTreesWithActiveTreeTiles();
2563
2564   base::OnceClosure callback;
2565   {
2566     base::RunLoop run_loop;
2567
2568     // Until we activate our ready to draw callback, treat all resources as not
2569     // ready to draw.
2570     EXPECT_CALL(*mock_raster_buffer_provider(),
2571                 IsResourceReadyToDraw(testing::_))
2572         .WillRepeatedly(Return(false));
2573
2574     EXPECT_CALL(*mock_raster_buffer_provider(), SetReadyToDrawCallback(_, _, 0))
2575         .WillOnce([&run_loop, &callback](
2576                       const std::vector<const ResourcePool::InUsePoolResource*>&
2577                           resources,
2578                       base::OnceClosure callback_in,
2579                       uint64_t pending_callback_id) {
2580           callback = std::move(callback_in);
2581           run_loop.Quit();
2582           return 1;
2583         });
2584     host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
2585     run_loop.Run();
2586   }
2587
2588   EXPECT_FALSE(host_impl()->tile_manager()->IsReadyToDraw());
2589   EXPECT_TRUE(host_impl()->tile_manager()->IsReadyToActivate());
2590
2591   {
2592     base::RunLoop run_loop;
2593     EXPECT_CALL(MockHostImpl(), NotifyReadyToDraw())
2594         .WillOnce(testing::Invoke([&run_loop]() { run_loop.Quit(); }));
2595     EXPECT_CALL(*mock_raster_buffer_provider(),
2596                 IsResourceReadyToDraw(testing::_))
2597         .WillRepeatedly(Return(true));
2598     std::move(callback).Run();
2599     run_loop.Run();
2600   }
2601
2602   EXPECT_TRUE(host_impl()->tile_manager()->IsReadyToDraw());
2603   EXPECT_TRUE(host_impl()->tile_manager()->IsReadyToActivate());
2604 }
2605
2606 TEST_F(TileManagerReadyToDrawTest, NonSmoothDrawDoesNotWaitOnCallback) {
2607   SetupTreesWithActiveTreeTiles();
2608
2609   // We're using a StrictMock on the RasterBufferProvider, so any function call
2610   // will cause a test failure.
2611   base::RunLoop run_loop;
2612
2613   host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
2614   EXPECT_CALL(MockHostImpl(), NotifyReadyToDraw())
2615       .WillOnce(Invoke([&run_loop]() { run_loop.Quit(); }));
2616   run_loop.Run();
2617
2618   EXPECT_TRUE(host_impl()->tile_manager()->IsReadyToDraw());
2619   EXPECT_TRUE(host_impl()->tile_manager()->IsReadyToActivate());
2620 }
2621
2622 TEST_F(TileManagerReadyToDrawTest, NoCallbackWhenAlreadyReadyToDraw) {
2623   host_impl()->SetTreePriority(SMOOTHNESS_TAKES_PRIORITY);
2624   SetupTreesWithPendingTreeTiles();
2625
2626   base::RunLoop run_loop;
2627   host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
2628   EXPECT_CALL(MockHostImpl(), NotifyReadyToActivate())
2629       .WillOnce(Invoke([&run_loop]() { run_loop.Quit(); }));
2630   EXPECT_CALL(*mock_raster_buffer_provider(), IsResourceReadyToDraw(_))
2631       .WillRepeatedly(Return(true));
2632   run_loop.Run();
2633
2634   EXPECT_TRUE(host_impl()->tile_manager()->IsReadyToDraw());
2635   EXPECT_TRUE(host_impl()->tile_manager()->IsReadyToActivate());
2636 }
2637
2638 TEST_F(TileManagerReadyToDrawTest, TilePrioritiesUpdated) {
2639   // Use smoothness as that's a mode in which we wait on resources to be
2640   // ready instead of marking them ready immediately.
2641   host_impl()->SetTreePriority(SMOOTHNESS_TAKES_PRIORITY);
2642   gfx::Size very_small(1, 1);
2643   host_impl()->active_tree()->SetDeviceViewportRect(gfx::Rect(very_small));
2644
2645   gfx::Size layer_bounds(1000, 1000);
2646   SetupDefaultTrees(layer_bounds);
2647
2648   // Run until all tile tasks are complete, but don't let any draw callbacks
2649   // finish.
2650   {
2651     base::RunLoop run_loop;
2652     EXPECT_CALL(MockHostImpl(), NotifyAllTileTasksCompleted())
2653         .WillOnce(testing::Invoke([&run_loop]() { run_loop.Quit(); }));
2654
2655     // Until we activate our ready to draw callback, treat all resources as not
2656     // ready to draw.
2657     EXPECT_CALL(*mock_raster_buffer_provider(),
2658                 IsResourceReadyToDraw(testing::_))
2659         .WillRepeatedly(Return(false));
2660     EXPECT_CALL(*mock_raster_buffer_provider(), SetReadyToDrawCallback(_, _, _))
2661         .WillRepeatedly(Return(1));
2662     host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
2663     run_loop.Run();
2664   }
2665
2666   // Inspect the current state of tiles in this world of cpu done but gpu
2667   // not ready yet.
2668   size_t orig_num_required = 0;
2669   size_t orig_num_prepaint = 0;
2670   std::vector<Tile*> prepaint_tiles;
2671   for (auto* tile : host_impl()->tile_manager()->AllTilesForTesting()) {
2672     if (tile->draw_info().has_resource()) {
2673       if (tile->is_prepaint()) {
2674         orig_num_prepaint++;
2675         prepaint_tiles.push_back(tile);
2676       } else {
2677         orig_num_required++;
2678       }
2679     }
2680   }
2681
2682   // Verify that there exist some prepaint tiles here.
2683   EXPECT_GT(orig_num_prepaint, 0u);
2684   EXPECT_GT(orig_num_required, 0u);
2685
2686   host_impl()->active_tree()->SetDeviceViewportRect(gfx::Rect(layer_bounds));
2687   UpdateDrawProperties(host_impl()->active_tree());
2688   UpdateDrawProperties(host_impl()->pending_tree());
2689
2690   // Rerun prepare tiles.
2691   {
2692     base::RunLoop run_loop;
2693     EXPECT_CALL(MockHostImpl(), NotifyAllTileTasksCompleted())
2694         .WillOnce(testing::Invoke([&run_loop]() { run_loop.Quit(); }));
2695     host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
2696     run_loop.Run();
2697   }
2698
2699   // Make sure tiles priorities are updated.
2700   size_t final_num_required = 0;
2701   size_t final_num_prepaint = 0;
2702   bool found_one_prepaint_to_required_transition = false;
2703   for (auto* tile : host_impl()->tile_manager()->AllTilesForTesting()) {
2704     if (tile->draw_info().has_resource()) {
2705       if (tile->is_prepaint()) {
2706         final_num_prepaint++;
2707       } else {
2708         final_num_required++;
2709         if (base::Contains(prepaint_tiles, tile)) {
2710           found_one_prepaint_to_required_transition = true;
2711         }
2712       }
2713     }
2714   }
2715
2716   // Tile priorities should be updated and we should have more required
2717   // and fewer prepaint now that the viewport has changed.
2718   EXPECT_GT(final_num_required, orig_num_required);
2719   EXPECT_LT(final_num_prepaint, orig_num_prepaint);
2720   EXPECT_TRUE(found_one_prepaint_to_required_transition);
2721 }
2722
2723 void UpdateVisibleRect(FakePictureLayerImpl* layer,
2724                        const gfx::Rect visible_rect) {
2725   PictureLayerTilingSet* tiling_set = layer->tilings();
2726   for (size_t j = 0; j < tiling_set->num_tilings(); ++j) {
2727     PictureLayerTiling* tiling = tiling_set->tiling_at(j);
2728     tiling->SetTilePriorityRectsForTesting(
2729         visible_rect,                  // Visible rect.
2730         visible_rect,                  // Skewport rect.
2731         visible_rect,                  // Soon rect.
2732         gfx::Rect(0, 0, 1000, 1000));  // Eventually rect.
2733   }
2734 }
2735
2736 TEST_F(TileManagerReadyToDrawTest, ReadyToDrawRespectsRequirementChange) {
2737   host_impl()->SetTreePriority(SMOOTHNESS_TAKES_PRIORITY);
2738   SetupTreesWithPendingTreeTiles();
2739
2740   // Initially create a tiling with a visible rect of (0, 0, 100, 100) and
2741   // a soon rect of the rest of the layer.
2742   UpdateVisibleRect(pending_layer(), gfx::Rect(0, 0, 100, 100));
2743
2744   // Mark all these tiles as ready to draw.
2745   {
2746     base::RunLoop run_loop;
2747     host_impl()->tile_manager()->DidModifyTilePriorities();
2748     host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
2749     EXPECT_CALL(MockHostImpl(), NotifyReadyToActivate())
2750         .WillOnce(Invoke([&run_loop]() { run_loop.Quit(); }));
2751     EXPECT_CALL(*mock_raster_buffer_provider(), IsResourceReadyToDraw(_))
2752         .WillRepeatedly(Return(true));
2753     run_loop.Run();
2754   }
2755
2756   EXPECT_TRUE(host_impl()->tile_manager()->IsReadyToDraw());
2757   EXPECT_TRUE(host_impl()->tile_manager()->IsReadyToActivate());
2758
2759   // Move the viewport to (900, 900, 100, 100), so that we need a different set
2760   // of tilings.
2761   UpdateVisibleRect(pending_layer(), gfx::Rect(900, 900, 100, 100));
2762
2763   EXPECT_CALL(*mock_raster_buffer_provider(), IsResourceReadyToDraw(testing::_))
2764       .WillRepeatedly(Return(false));
2765
2766   base::OnceClosure callback;
2767   {
2768     base::RunLoop run_loop;
2769
2770     EXPECT_CALL(*mock_raster_buffer_provider(), SetReadyToDrawCallback(_, _, 0))
2771         .WillOnce([&run_loop, &callback](
2772                       const std::vector<const ResourcePool::InUsePoolResource*>&
2773                           resources,
2774                       base::OnceClosure callback_in,
2775                       uint64_t pending_callback_id) {
2776           callback = std::move(callback_in);
2777           run_loop.Quit();
2778           return 1;
2779         });
2780     host_impl()->tile_manager()->DidModifyTilePriorities();
2781     host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
2782     run_loop.Run();
2783   }
2784
2785   EXPECT_TRUE(host_impl()->tile_manager()->IsReadyToDraw());
2786   EXPECT_FALSE(host_impl()->tile_manager()->IsReadyToActivate());
2787
2788   // Now switch back to our original tiling. We should be immediately able to
2789   // activate, as we still have the original tile, and no longer need the
2790   // tiles from the previous callback.
2791   UpdateVisibleRect(pending_layer(), gfx::Rect(0, 0, 100, 100));
2792
2793   {
2794     base::RunLoop run_loop;
2795     host_impl()->tile_manager()->DidModifyTilePriorities();
2796     host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
2797     EXPECT_CALL(MockHostImpl(), NotifyReadyToActivate())
2798         .WillOnce(Invoke([&run_loop]() { run_loop.Quit(); }));
2799     run_loop.Run();
2800   }
2801
2802   EXPECT_TRUE(host_impl()->tile_manager()->IsReadyToDraw());
2803   EXPECT_TRUE(host_impl()->tile_manager()->IsReadyToActivate());
2804 }
2805
2806 PaintImage MakeCheckerablePaintImage(const gfx::Size& size) {
2807   auto image = CreateDiscardablePaintImage(size);
2808   return PaintImageBuilder::WithCopy(image)
2809       .set_decoding_mode(PaintImage::DecodingMode::kAsync)
2810       .TakePaintImage();
2811 }
2812
2813 class CheckerImagingTileManagerTest : public TestLayerTreeHostBase {
2814  public:
2815   class MockImageGenerator : public FakePaintImageGenerator {
2816    public:
2817     explicit MockImageGenerator(const gfx::Size& size)
2818         : FakePaintImageGenerator(
2819               SkImageInfo::MakeN32Premul(size.width(), size.height())) {}
2820
2821     MOCK_METHOD6(GetPixels,
2822                  bool(const SkImageInfo&,
2823                       void*,
2824                       size_t,
2825                       size_t,
2826                       PaintImage::GeneratorClientId,
2827                       uint32_t));
2828   };
2829
2830   void TearDown() override {
2831     // Allow all tasks on the image worker to run now. Any scheduled decodes
2832     // will be aborted.
2833     task_runner_->set_run_tasks_synchronously(true);
2834   }
2835
2836   LayerTreeSettings CreateSettings() override {
2837     auto settings = TestLayerTreeHostBase::CreateSettings();
2838     settings.commit_to_active_tree = false;
2839     settings.enable_checker_imaging = true;
2840     settings.min_image_bytes_to_checker = 512 * 1024;
2841     return settings;
2842   }
2843
2844   std::unique_ptr<FakeLayerTreeHostImpl> CreateHostImpl(
2845       const LayerTreeSettings& settings,
2846       TaskRunnerProvider* task_runner_provider,
2847       TaskGraphRunner* task_graph_runner) override {
2848     task_runner_ = base::MakeRefCounted<SynchronousSimpleTaskRunner>();
2849     return std::make_unique<FakeLayerTreeHostImpl>(
2850         settings, task_runner_provider, task_graph_runner, task_runner_);
2851   }
2852
2853   std::unique_ptr<TaskGraphRunner> CreateTaskGraphRunner() override {
2854     return std::make_unique<SynchronousTaskGraphRunner>();
2855   }
2856
2857   void FlushDecodeTasks() {
2858     while (task_runner_->HasPendingTask()) {
2859       task_runner_->RunUntilIdle();
2860       base::RunLoop().RunUntilIdle();
2861     }
2862   }
2863
2864   void CleanUpTileManager() {
2865     task_runner_->set_run_tasks_synchronously(true);
2866     host_impl()->tile_manager()->FinishTasksAndCleanUp();
2867     task_runner_->set_run_tasks_synchronously(false);
2868   }
2869
2870  private:
2871   scoped_refptr<SynchronousSimpleTaskRunner> task_runner_;
2872 };
2873
2874 TEST_F(CheckerImagingTileManagerTest,
2875        NoImageDecodeDependencyForCheckeredTiles) {
2876   const gfx::Size layer_bounds(512, 512);
2877
2878   std::unique_ptr<FakeRecordingSource> recording_source =
2879       FakeRecordingSource::CreateFilledRecordingSource(layer_bounds);
2880   recording_source->set_fill_with_nonsolid_color(true);
2881
2882   auto generator =
2883       sk_make_sp<testing::StrictMock<MockImageGenerator>>(gfx::Size(512, 512));
2884   PaintImage image = PaintImageBuilder::WithDefault()
2885                          .set_id(PaintImage::GetNextId())
2886                          .set_paint_image_generator(generator)
2887                          .set_decoding_mode(PaintImage::DecodingMode::kAsync)
2888                          .TakePaintImage();
2889   recording_source->add_draw_image(image, gfx::Point(0, 0));
2890
2891   recording_source->Rerecord();
2892   scoped_refptr<RasterSource> raster_source =
2893       recording_source->CreateRasterSource();
2894
2895   Region invalidation((gfx::Rect(layer_bounds)));
2896   SetupPendingTree(raster_source, layer_bounds, invalidation);
2897
2898   PictureLayerTilingSet* tiling_set =
2899       pending_layer()->picture_layer_tiling_set();
2900   PictureLayerTiling* tiling = tiling_set->tiling_at(0);
2901   tiling->set_resolution(HIGH_RESOLUTION);
2902   tiling->CreateAllTilesForTesting();
2903   tiling->SetTilePriorityRectsForTesting(
2904       gfx::Rect(layer_bounds),   // Visible rect.
2905       gfx::Rect(layer_bounds),   // Skewport rect.
2906       gfx::Rect(layer_bounds),   // Soon rect.
2907       gfx::Rect(layer_bounds));  // Eventually rect.
2908   tiling->set_can_require_tiles_for_activation(true);
2909
2910   // PrepareTiles and synchronously run all tasks added to the TaskGraph. Since
2911   // we are using a strict mock for the SkImageGenerator, if the decode runs as
2912   // a part of raster tasks, the test should fail.
2913   host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
2914   EXPECT_TRUE(host_impl()->tile_manager()->HasScheduledTileTasksForTesting());
2915   static_cast<SynchronousTaskGraphRunner*>(task_graph_runner())->RunUntilIdle();
2916   base::RunLoop().RunUntilIdle();
2917   EXPECT_FALSE(host_impl()->tile_manager()->HasScheduledTileTasksForTesting());
2918 }
2919
2920 class EmptyCacheTileManagerTest : public TileManagerTest {
2921  public:
2922   LayerTreeSettings CreateSettings() override {
2923     auto settings = TileManagerTest::CreateSettings();
2924     settings.decoded_image_working_set_budget_bytes = 0;
2925     return settings;
2926   }
2927 };
2928
2929 TEST_F(EmptyCacheTileManagerTest, AtRasterOnScreenTileRasterTasks) {
2930   const gfx::Size layer_bounds(500, 500);
2931
2932   std::unique_ptr<FakeRecordingSource> recording_source =
2933       FakeRecordingSource::CreateFilledRecordingSource(layer_bounds);
2934   recording_source->set_fill_with_nonsolid_color(true);
2935
2936   int dimension = 500;
2937   PaintImage image = MakeCheckerablePaintImage(gfx::Size(dimension, dimension));
2938   recording_source->add_draw_image(image, gfx::Point(0, 0));
2939
2940   recording_source->Rerecord();
2941   scoped_refptr<RasterSource> raster_source =
2942       recording_source->CreateRasterSource();
2943
2944   gfx::Size tile_size(500, 500);
2945   Region invalidation((gfx::Rect(layer_bounds)));
2946   SetupPendingTree(raster_source, tile_size, invalidation);
2947
2948   PictureLayerTilingSet* tiling_set =
2949       pending_layer()->picture_layer_tiling_set();
2950   PictureLayerTiling* pending_tiling = tiling_set->tiling_at(0);
2951   pending_tiling->set_resolution(HIGH_RESOLUTION);
2952   pending_tiling->CreateAllTilesForTesting();
2953   pending_tiling->SetTilePriorityRectsForTesting(
2954       gfx::Rect(layer_bounds),   // Visible rect.
2955       gfx::Rect(layer_bounds),   // Skewport rect.
2956       gfx::Rect(layer_bounds),   // Soon rect.
2957       gfx::Rect(layer_bounds));  // Eventually rect.
2958
2959   host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
2960   // There will be a tile raster task and an image decode task.
2961   EXPECT_TRUE(pending_tiling->TileAt(0, 0)->HasRasterTask());
2962   EXPECT_TRUE(host_impl()->tile_manager()->HasScheduledTileTasksForTesting());
2963 }
2964
2965 TEST_F(EmptyCacheTileManagerTest, AtRasterPrepaintTileRasterTasksSkipped) {
2966   const gfx::Size layer_bounds(500, 500);
2967
2968   std::unique_ptr<FakeRecordingSource> recording_source =
2969       FakeRecordingSource::CreateFilledRecordingSource(layer_bounds);
2970   recording_source->set_fill_with_nonsolid_color(true);
2971
2972   int dimension = 500;
2973   PaintImage image = MakeCheckerablePaintImage(gfx::Size(dimension, dimension));
2974   recording_source->add_draw_image(image, gfx::Point(0, 0));
2975
2976   recording_source->Rerecord();
2977   scoped_refptr<RasterSource> raster_source =
2978       recording_source->CreateRasterSource();
2979
2980   gfx::Size tile_size(500, 500);
2981   Region invalidation((gfx::Rect(layer_bounds)));
2982   SetupPendingTree(raster_source, tile_size, invalidation);
2983
2984   PictureLayerTilingSet* tiling_set =
2985       pending_layer()->picture_layer_tiling_set();
2986   PictureLayerTiling* pending_tiling = tiling_set->tiling_at(0);
2987   pending_tiling->set_resolution(HIGH_RESOLUTION);
2988   pending_tiling->CreateAllTilesForTesting();
2989   pending_tiling->SetTilePriorityRectsForTesting(
2990       gfx::Rect(),  // An empty visual rect leads to the tile being pre-paint.
2991       gfx::Rect(layer_bounds),   // Skewport rect.
2992       gfx::Rect(layer_bounds),   // Soon rect.
2993       gfx::Rect(layer_bounds));  // Eventually rect.
2994
2995   host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
2996   // There will be no tile raster task, but there will be an image decode task.
2997   EXPECT_FALSE(pending_tiling->TileAt(0, 0)->HasRasterTask());
2998   EXPECT_TRUE(host_impl()->tile_manager()->HasScheduledTileTasksForTesting());
2999 }
3000
3001 TEST_F(CheckerImagingTileManagerTest, BuildsImageDecodeQueueAsExpected) {
3002   const gfx::Size layer_bounds(900, 900);
3003
3004   std::unique_ptr<FakeRecordingSource> recording_source =
3005       FakeRecordingSource::CreateFilledRecordingSource(layer_bounds);
3006   recording_source->set_fill_with_nonsolid_color(true);
3007
3008   int dimension = 450;
3009   PaintImage image1 =
3010       MakeCheckerablePaintImage(gfx::Size(dimension, dimension));
3011   PaintImage image2 =
3012       MakeCheckerablePaintImage(gfx::Size(dimension, dimension));
3013   PaintImage image3 =
3014       MakeCheckerablePaintImage(gfx::Size(dimension, dimension));
3015   recording_source->add_draw_image(image1, gfx::Point(0, 0));
3016   recording_source->add_draw_image(image2, gfx::Point(600, 0));
3017   recording_source->add_draw_image(image3, gfx::Point(0, 600));
3018
3019   recording_source->Rerecord();
3020   scoped_refptr<RasterSource> raster_source =
3021       recording_source->CreateRasterSource();
3022
3023   gfx::Size tile_size(500, 500);
3024   Region invalidation((gfx::Rect(layer_bounds)));
3025   SetupPendingTree(raster_source, tile_size, invalidation);
3026
3027   PictureLayerTilingSet* tiling_set =
3028       pending_layer()->picture_layer_tiling_set();
3029   PictureLayerTiling* pending_tiling = tiling_set->tiling_at(0);
3030   pending_tiling->set_resolution(HIGH_RESOLUTION);
3031   pending_tiling->CreateAllTilesForTesting();
3032   pending_tiling->SetTilePriorityRectsForTesting(
3033       gfx::Rect(layer_bounds),   // Visible rect.
3034       gfx::Rect(layer_bounds),   // Skewport rect.
3035       gfx::Rect(layer_bounds),   // Soon rect.
3036       gfx::Rect(layer_bounds));  // Eventually rect.
3037
3038   // PrepareTiles and make sure we account correctly for tiles that have been
3039   // scheduled with checkered images.
3040   host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
3041   EXPECT_TRUE(host_impl()->tile_manager()->HasScheduledTileTasksForTesting());
3042
3043   for (int i = 0; i < 2; i++) {
3044     for (int j = 0; j < 2; j++) {
3045       const Tile* tile = pending_tiling->TileAt(i, j);
3046       EXPECT_TRUE(tile->HasRasterTask());
3047       if (i == 1 && j == 1)
3048         EXPECT_FALSE(tile->raster_task_scheduled_with_checker_images());
3049       else
3050         EXPECT_TRUE(tile->raster_task_scheduled_with_checker_images());
3051     }
3052   }
3053   EXPECT_EQ(host_impl()->tile_manager()->num_of_tiles_with_checker_images(), 3);
3054
3055   // Now raster all the tiles and make sure these tiles are still accounted for
3056   // with checkered images.
3057   static_cast<SynchronousTaskGraphRunner*>(task_graph_runner())->RunUntilIdle();
3058   base::RunLoop().RunUntilIdle();
3059   EXPECT_FALSE(host_impl()->tile_manager()->HasScheduledTileTasksForTesting());
3060   for (int i = 0; i < 2; i++) {
3061     for (int j = 0; j < 2; j++) {
3062       const Tile* tile = pending_tiling->TileAt(i, j);
3063       EXPECT_FALSE(tile->HasRasterTask());
3064       EXPECT_FALSE(tile->raster_task_scheduled_with_checker_images());
3065       EXPECT_TRUE(tile->draw_info().has_resource());
3066       if (i == 1 && j == 1)
3067         EXPECT_FALSE(tile->draw_info().is_checker_imaged());
3068       else
3069         EXPECT_TRUE(tile->draw_info().is_checker_imaged());
3070     }
3071   }
3072   EXPECT_EQ(host_impl()->tile_manager()->num_of_tiles_with_checker_images(), 3);
3073
3074   // Activate the pending tree.
3075   ActivateTree();
3076
3077   // Set empty tile priority rects so an empty image decode queue is used.
3078   gfx::Rect empty_rect;
3079   PictureLayerTiling* active_tiling =
3080       active_layer()->picture_layer_tiling_set()->tiling_at(0);
3081   active_tiling->SetTilePriorityRectsForTesting(
3082       gfx::Rect(empty_rect),   // Visible rect.
3083       gfx::Rect(empty_rect),   // Skewport rect.
3084       gfx::Rect(empty_rect),   // Soon rect.
3085       gfx::Rect(empty_rect));  // Eventually rect.
3086   host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
3087
3088   // Run the decode tasks. Since the first decode is always scheduled, the
3089   // completion for it should be triggered.
3090   FlushDecodeTasks();
3091
3092   // Create a new pending tree to invalidate tiles for decoded images and verify
3093   // that only tiles for |image1| are invalidated.
3094   EXPECT_TRUE(host_impl()->client()->did_request_impl_side_invalidation());
3095   PerformImplSideInvalidation();
3096   for (int i = 0; i < 2; i++) {
3097     for (int j = 0; j < 2; j++) {
3098       const Tile* tile = pending_tiling->TileAt(i, j);
3099       if (i == 0 && j == 0)
3100         EXPECT_TRUE(tile);
3101       else
3102         EXPECT_FALSE(tile);
3103     }
3104   }
3105   host_impl()->client()->reset_did_request_impl_side_invalidation();
3106
3107   // Activating the tree replaces the checker-imaged tile.
3108   EXPECT_EQ(host_impl()->tile_manager()->num_of_tiles_with_checker_images(), 3);
3109   ActivateTree();
3110   EXPECT_EQ(host_impl()->tile_manager()->num_of_tiles_with_checker_images(), 2);
3111
3112   // Set the tile priority rects such that only the tile with the second image
3113   // is scheduled for decodes, since it is checker-imaged.
3114   gfx::Rect rect_to_raster(600, 0, 300, 900);
3115   active_tiling->SetTilePriorityRectsForTesting(
3116       gfx::Rect(rect_to_raster),   // Visible rect.
3117       gfx::Rect(rect_to_raster),   // Skewport rect.
3118       gfx::Rect(rect_to_raster),   // Soon rect.
3119       gfx::Rect(rect_to_raster));  // Eventually rect.
3120   host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
3121
3122   // Finish all raster and dispatch completion callback so that the decode work
3123   // for checkered images can be scheduled.
3124   static_cast<SynchronousTaskGraphRunner*>(task_graph_runner())->RunUntilIdle();
3125   base::RunLoop().RunUntilIdle();
3126
3127   // Run decode tasks to trigger completion of any pending decodes.
3128   FlushDecodeTasks();
3129
3130   // Create a new pending tree to invalidate tiles for decoded images and verify
3131   // that only tiles for |image2| are invalidated.
3132   EXPECT_TRUE(host_impl()->client()->did_request_impl_side_invalidation());
3133   PerformImplSideInvalidation();
3134   for (int i = 0; i < 2; i++) {
3135     for (int j = 0; j < 2; j++) {
3136       const Tile* tile = pending_tiling->TileAt(i, j);
3137       if (i == 1 && j == 0)
3138         EXPECT_TRUE(tile);
3139       else
3140         EXPECT_FALSE(tile);
3141     }
3142   }
3143   host_impl()->client()->reset_did_request_impl_side_invalidation();
3144
3145   // Activating the tree replaces the checker-imaged tile.
3146   EXPECT_EQ(host_impl()->tile_manager()->num_of_tiles_with_checker_images(), 2);
3147   ActivateTree();
3148   EXPECT_EQ(host_impl()->tile_manager()->num_of_tiles_with_checker_images(), 1);
3149
3150   // Set the tile priority rects to cover the complete tiling and change the
3151   // visibility. While |image3| has not yet been decoded, since we are
3152   // invisible no decodes should have been scheduled.
3153   active_tiling->SetTilePriorityRectsForTesting(
3154       gfx::Rect(layer_bounds),   // Visible rect.
3155       gfx::Rect(layer_bounds),   // Skewport rect.
3156       gfx::Rect(layer_bounds),   // Soon rect.
3157       gfx::Rect(layer_bounds));  // Eventually rect.
3158   host_impl()->SetVisible(false);
3159   host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
3160   FlushDecodeTasks();
3161   EXPECT_FALSE(host_impl()->client()->did_request_impl_side_invalidation());
3162 }
3163
3164 TEST_F(CheckerImagingTileManagerTest,
3165        TileManagerCleanupClearsCheckerImagedDecodes) {
3166   const gfx::Size layer_bounds(512, 512);
3167
3168   std::unique_ptr<FakeRecordingSource> recording_source =
3169       FakeRecordingSource::CreateFilledRecordingSource(layer_bounds);
3170   recording_source->set_fill_with_nonsolid_color(true);
3171   PaintImage image = MakeCheckerablePaintImage(gfx::Size(512, 512));
3172   recording_source->add_draw_image(image, gfx::Point(0, 0));
3173   recording_source->Rerecord();
3174   scoped_refptr<RasterSource> raster_source =
3175       recording_source->CreateRasterSource();
3176
3177   SetupPendingTree(raster_source, gfx::Size(100, 100),
3178                    Region(gfx::Rect(0, 0, 500, 500)));
3179
3180   host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
3181   // Finish all raster and dispatch completion callback so that the decode work
3182   // for checkered images can be scheduled.
3183   static_cast<SynchronousTaskGraphRunner*>(task_graph_runner())->RunUntilIdle();
3184   base::RunLoop().RunUntilIdle();
3185   FlushDecodeTasks();
3186
3187   EXPECT_TRUE(host_impl()
3188                   ->tile_manager()
3189                   ->checker_image_tracker()
3190                   .has_locked_decodes_for_testing());
3191
3192   host_impl()->pending_tree()->ReleaseTileResources();
3193   CleanUpTileManager();
3194
3195   EXPECT_FALSE(host_impl()
3196                    ->tile_manager()
3197                    ->checker_image_tracker()
3198                    .has_locked_decodes_for_testing());
3199   EXPECT_TRUE(
3200       host_impl()->tile_manager()->TakeImagesToInvalidateOnSyncTree().empty());
3201 }
3202
3203 TEST_F(CheckerImagingTileManagerTest,
3204        TileManagerCorrectlyPrioritizesCheckerImagedDecodes) {
3205   gfx::Size layer_bounds(500, 500);
3206
3207   std::unique_ptr<FakeRecordingSource> recording_source =
3208       FakeRecordingSource::CreateFilledRecordingSource(layer_bounds);
3209   recording_source->set_fill_with_nonsolid_color(true);
3210   PaintImage image = MakeCheckerablePaintImage(gfx::Size(512, 512));
3211   recording_source->add_draw_image(image, gfx::Point(0, 0));
3212   recording_source->Rerecord();
3213   scoped_refptr<RasterSource> raster_source =
3214       recording_source->CreateRasterSource();
3215
3216   // Required for activation tiles block checker-imaged decodes.
3217   SetupPendingTree(raster_source, gfx::Size(100, 100),
3218                    Region(gfx::Rect(0, 0, 500, 500)));
3219   host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
3220   EXPECT_TRUE(host_impl()->tile_manager()->HasScheduledTileTasksForTesting());
3221   EXPECT_TRUE(host_impl()
3222                   ->tile_manager()
3223                   ->checker_image_tracker()
3224                   .no_decodes_allowed_for_testing());
3225   while (!host_impl()->client()->ready_to_activate()) {
3226     static_cast<SynchronousTaskGraphRunner*>(task_graph_runner())
3227         ->RunSingleTaskForTesting();
3228     base::RunLoop().RunUntilIdle();
3229   }
3230   EXPECT_EQ(host_impl()
3231                 ->tile_manager()
3232                 ->checker_image_tracker()
3233                 .decode_priority_allowed_for_testing(),
3234             CheckerImageTracker::DecodeType::kRaster);
3235
3236   // Finishing all tasks allows pre-decodes.
3237   static_cast<SynchronousTaskGraphRunner*>(task_graph_runner())->RunUntilIdle();
3238   base::RunLoop().RunUntilIdle();
3239   EXPECT_EQ(host_impl()
3240                 ->tile_manager()
3241                 ->checker_image_tracker()
3242                 .decode_priority_allowed_for_testing(),
3243             CheckerImageTracker::DecodeType::kPreDecode);
3244
3245   // Required for draw tiles block checker-imaged decodes.
3246   // Free all tile resources and perform another PrepareTiles.
3247   ActivateTree();
3248   EXPECT_TRUE(host_impl()->tile_manager()->IsReadyToDraw());
3249   host_impl()->tile_manager()->PrepareTiles(
3250       GlobalStateThatImpactsTilePriority());
3251   EXPECT_FALSE(host_impl()->tile_manager()->IsReadyToDraw());
3252
3253   host_impl()->client()->reset_ready_to_draw();
3254   host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
3255   EXPECT_TRUE(host_impl()->tile_manager()->HasScheduledTileTasksForTesting());
3256   EXPECT_TRUE(host_impl()
3257                   ->tile_manager()
3258                   ->checker_image_tracker()
3259                   .no_decodes_allowed_for_testing());
3260   while (!host_impl()->tile_manager()->IsReadyToDraw()) {
3261     static_cast<SynchronousTaskGraphRunner*>(task_graph_runner())
3262         ->RunSingleTaskForTesting();
3263     base::RunLoop().RunUntilIdle();
3264   }
3265   EXPECT_EQ(host_impl()
3266                 ->tile_manager()
3267                 ->checker_image_tracker()
3268                 .decode_priority_allowed_for_testing(),
3269             CheckerImageTracker::DecodeType::kRaster);
3270 }
3271
3272 class CheckerImagingTileManagerMemoryTest
3273     : public CheckerImagingTileManagerTest {
3274  public:
3275   std::unique_ptr<FakeLayerTreeHostImpl> CreateHostImpl(
3276       const LayerTreeSettings& settings,
3277       TaskRunnerProvider* task_runner_provider,
3278       TaskGraphRunner* task_graph_runner) override {
3279     LayerTreeSettings new_settings = settings;
3280     new_settings.memory_policy.num_resources_limit = 4;
3281     return CheckerImagingTileManagerTest::CreateHostImpl(
3282         new_settings, task_runner_provider, task_graph_runner);
3283   }
3284 };
3285
3286 TEST_F(CheckerImagingTileManagerMemoryTest, AddsAllNowTilesToImageDecodeQueue) {
3287   const gfx::Size layer_bounds(900, 1400);
3288
3289   std::unique_ptr<FakeRecordingSource> recording_source =
3290       FakeRecordingSource::CreateFilledRecordingSource(layer_bounds);
3291   recording_source->set_fill_with_nonsolid_color(true);
3292
3293   int dimension = 450;
3294   PaintImage image1 =
3295       MakeCheckerablePaintImage(gfx::Size(dimension, dimension));
3296   PaintImage image2 =
3297       MakeCheckerablePaintImage(gfx::Size(dimension, dimension));
3298   recording_source->add_draw_image(image1, gfx::Point(0, 515));
3299   recording_source->add_draw_image(image2, gfx::Point(515, 515));
3300
3301   recording_source->Rerecord();
3302   scoped_refptr<RasterSource> raster_source =
3303       recording_source->CreateRasterSource();
3304
3305   gfx::Size tile_size(500, 500);
3306   Region invalidation((gfx::Rect(layer_bounds)));
3307   SetupPendingTree(raster_source, tile_size, invalidation);
3308
3309   PictureLayerTilingSet* tiling_set =
3310       pending_layer()->picture_layer_tiling_set();
3311   PictureLayerTiling* pending_tiling = tiling_set->tiling_at(0);
3312   pending_tiling->set_resolution(HIGH_RESOLUTION);
3313   pending_tiling->CreateAllTilesForTesting();
3314
3315   // Use a rect that only rasterizes the bottom 2 rows of tiles.
3316   gfx::Rect rect_to_raster(0, 500, 900, 900);
3317   pending_tiling->SetTilePriorityRectsForTesting(
3318       rect_to_raster,   // Visible rect.
3319       rect_to_raster,   // Skewport rect.
3320       rect_to_raster,   // Soon rect.
3321       rect_to_raster);  // Eventually rect.
3322
3323   // PrepareTiles, rasterize all scheduled tiles and activate while no images
3324   // have been decoded.
3325   host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
3326   static_cast<SynchronousTaskGraphRunner*>(task_graph_runner())->RunUntilIdle();
3327   base::RunLoop().RunUntilIdle();
3328   ActivateTree();
3329
3330   // Expand the visible rect to include the complete tiling. The tile iteration
3331   // will not go beyond the first tile since there are no resources with a lower
3332   // priority that can be evicted. But we should still see image decodes
3333   // scheduled for all visible tiles.
3334   gfx::Rect complete_tiling_rect(layer_bounds);
3335   PictureLayerTiling* active_tiling =
3336       active_layer()->picture_layer_tiling_set()->tiling_at(0);
3337   active_tiling->SetTilePriorityRectsForTesting(
3338       complete_tiling_rect,   // Visible rect.
3339       complete_tiling_rect,   // Skewport rect.
3340       complete_tiling_rect,   // Soon rect.
3341       complete_tiling_rect);  // Eventually rect.
3342   host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
3343
3344   // Finish all raster work so the decode work for checkered images can be
3345   // scheduled.
3346   static_cast<SynchronousTaskGraphRunner*>(task_graph_runner())->RunUntilIdle();
3347   base::RunLoop().RunUntilIdle();
3348
3349   // Flush all decode tasks. The tiles with checkered images should be
3350   // invalidated.
3351   FlushDecodeTasks();
3352   EXPECT_TRUE(host_impl()->client()->did_request_impl_side_invalidation());
3353   PerformImplSideInvalidation();
3354   for (int i = 0; i < 2; i++) {
3355     for (int j = 0; j < 3; j++) {
3356       const Tile* tile = pending_tiling->TileAt(i, j);
3357       if (j == 1)
3358         EXPECT_TRUE(tile);
3359       else
3360         EXPECT_FALSE(tile);
3361     }
3362   }
3363   host_impl()->client()->reset_did_request_impl_side_invalidation();
3364 }
3365
3366 class VerifyImageProviderRasterBuffer : public RasterBuffer {
3367  public:
3368   VerifyImageProviderRasterBuffer() = default;
3369   ~VerifyImageProviderRasterBuffer() override { EXPECT_TRUE(did_raster_); }
3370
3371   void Playback(const RasterSource* raster_source,
3372                 const gfx::Rect& raster_full_rect,
3373                 const gfx::Rect& raster_dirty_rect,
3374                 uint64_t new_content_id,
3375                 const gfx::AxisTransform2d& transform,
3376                 const RasterSource::PlaybackSettings& playback_settings,
3377                 const GURL& url) override {
3378     did_raster_ = true;
3379     EXPECT_TRUE(playback_settings.image_provider);
3380   }
3381
3382   bool SupportsBackgroundThreadPriority() const override { return true; }
3383
3384  private:
3385   bool did_raster_ = false;
3386 };
3387
3388 class VerifyImageProviderRasterBufferProvider
3389     : public FakeRasterBufferProviderImpl {
3390  public:
3391   VerifyImageProviderRasterBufferProvider() = default;
3392   ~VerifyImageProviderRasterBufferProvider() override {
3393     EXPECT_GT(buffer_count_, 0);
3394   }
3395
3396   std::unique_ptr<RasterBuffer> AcquireBufferForRaster(
3397       const ResourcePool::InUsePoolResource& resource,
3398       uint64_t resource_content_id,
3399       uint64_t previous_content_id,
3400       bool depends_on_at_raster_decodes,
3401       bool depends_on_hardware_accelerated_jpeg_candidates,
3402       bool depends_on_hardware_accelerated_webp_candidates) override {
3403     buffer_count_++;
3404     return std::make_unique<VerifyImageProviderRasterBuffer>();
3405   }
3406
3407  private:
3408   int buffer_count_ = 0;
3409 };
3410
3411 class SynchronousRasterTileManagerTest : public TileManagerTest {
3412  public:
3413   std::unique_ptr<TaskGraphRunner> CreateTaskGraphRunner() override {
3414     return std::make_unique<SynchronousTaskGraphRunner>();
3415   }
3416 };
3417
3418 TEST_F(SynchronousRasterTileManagerTest, AlwaysUseImageCache) {
3419   // Tests that we always use the ImageDecodeCache during raster.
3420   VerifyImageProviderRasterBufferProvider raster_buffer_provider;
3421   host_impl()->tile_manager()->SetRasterBufferProviderForTesting(
3422       &raster_buffer_provider);
3423
3424   gfx::Size layer_bounds(500, 500);
3425   scoped_refptr<FakeRasterSource> raster_source =
3426       FakeRasterSource::CreateFilled(layer_bounds);
3427   Region invalidation((gfx::Rect(layer_bounds)));
3428   SetupPendingTree(raster_source, layer_bounds, invalidation);
3429   PictureLayerTilingSet* tiling_set =
3430       pending_layer()->picture_layer_tiling_set();
3431   PictureLayerTiling* pending_tiling = tiling_set->tiling_at(0);
3432   pending_tiling->set_resolution(HIGH_RESOLUTION);
3433   pending_tiling->CreateAllTilesForTesting();
3434   pending_tiling->SetTilePriorityRectsForTesting(
3435       gfx::Rect(layer_bounds),   // Visible rect.
3436       gfx::Rect(layer_bounds),   // Skewport rect.
3437       gfx::Rect(layer_bounds),   // Soon rect.
3438       gfx::Rect(layer_bounds));  // Eventually rect.
3439
3440   host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
3441   static_cast<SynchronousTaskGraphRunner*>(task_graph_runner())->RunUntilIdle();
3442
3443   // Destroy the LTHI since it accesses the RasterBufferProvider during cleanup.
3444   TakeHostImpl();
3445 }
3446
3447 class DecodedImageTrackerTileManagerTest : public TestLayerTreeHostBase {
3448  public:
3449   void TearDown() override {
3450     // Allow all tasks on the image worker to run now. Any scheduled decodes
3451     // will be aborted.
3452     task_runner_->set_run_tasks_synchronously(true);
3453   }
3454
3455   LayerTreeSettings CreateSettings() override {
3456     auto settings = TestLayerTreeHostBase::CreateSettings();
3457     settings.max_preraster_distance_in_screen_pixels = 100;
3458     return settings;
3459   }
3460
3461   std::unique_ptr<FakeLayerTreeHostImpl> CreateHostImpl(
3462       const LayerTreeSettings& settings,
3463       TaskRunnerProvider* task_runner_provider,
3464       TaskGraphRunner* task_graph_runner) override {
3465     task_runner_ = base::MakeRefCounted<SynchronousSimpleTaskRunner>();
3466     return std::make_unique<FakeLayerTreeHostImpl>(
3467         settings, task_runner_provider, task_graph_runner, task_runner_);
3468   }
3469
3470   std::unique_ptr<TaskGraphRunner> CreateTaskGraphRunner() override {
3471     return std::make_unique<SynchronousTaskGraphRunner>();
3472   }
3473
3474   void FlushDecodeTasks() {
3475     while (task_runner_->HasPendingTask()) {
3476       task_runner_->RunUntilIdle();
3477       base::RunLoop().RunUntilIdle();
3478     }
3479   }
3480
3481  private:
3482   scoped_refptr<SynchronousSimpleTaskRunner> task_runner_;
3483 };
3484
3485 TEST_F(DecodedImageTrackerTileManagerTest, DecodedImageTrackerDropsLocksOnUse) {
3486   // Pick arbitrary IDs - they don't really matter as long as they're constant.
3487   const int kLayerId = 7;
3488
3489   host_impl()->tile_manager()->SetTileTaskManagerForTesting(
3490       std::make_unique<FakeTileTaskManagerImpl>());
3491
3492   // Create two test images, one will be positioned to be needed NOW, the other
3493   // will be positioned to be prepaint.
3494   int dimension = 250;
3495   PaintImage image1 =
3496       CreateDiscardablePaintImage(gfx::Size(dimension, dimension));
3497   PaintImage image2 =
3498       CreateDiscardablePaintImage(gfx::Size(dimension, dimension));
3499
3500   // Add the images to our decoded_image_tracker.
3501   host_impl()->tile_manager()->decoded_image_tracker().QueueImageDecode(
3502       image1, TargetColorParams(), base::DoNothing());
3503   host_impl()->tile_manager()->decoded_image_tracker().QueueImageDecode(
3504       image2, TargetColorParams(), base::DoNothing());
3505   EXPECT_EQ(0u, host_impl()
3506                     ->tile_manager()
3507                     ->decoded_image_tracker()
3508                     .NumLockedImagesForTesting());
3509   FlushDecodeTasks();
3510   EXPECT_EQ(2u, host_impl()
3511                     ->tile_manager()
3512                     ->decoded_image_tracker()
3513                     .NumLockedImagesForTesting());
3514
3515   // Add images to a fake recording source.
3516   const gfx::Size layer_bounds(1000, 500);
3517   std::unique_ptr<FakeRecordingSource> recording_source =
3518       FakeRecordingSource::CreateFilledRecordingSource(layer_bounds);
3519   recording_source->set_fill_with_nonsolid_color(true);
3520   recording_source->add_draw_image(image1, gfx::Point(0, 0));
3521   recording_source->add_draw_image(image2, gfx::Point(700, 0));
3522   recording_source->Rerecord();
3523
3524   scoped_refptr<FakeRasterSource> pending_raster_source =
3525       FakeRasterSource::CreateFromRecordingSource(recording_source.get());
3526
3527   host_impl()->CreatePendingTree();
3528   LayerTreeImpl* pending_tree = host_impl()->pending_tree();
3529   pending_tree->SetDeviceViewportRect(
3530       host_impl()->active_tree()->GetDeviceViewport());
3531
3532   // Steal from the recycled tree.
3533   std::unique_ptr<FakePictureLayerImpl> pending_layer =
3534       FakePictureLayerImpl::Create(pending_tree, kLayerId,
3535                                    pending_raster_source);
3536   pending_layer->SetDrawsContent(true);
3537
3538   // The bounds() are half the recording source size, allowing for prepaint
3539   // images.
3540   pending_layer->SetBounds(gfx::Size(500, 500));
3541   SetupRootProperties(pending_layer.get());
3542   pending_tree->SetRootLayerForTesting(std::move(pending_layer));
3543
3544   // Add tilings/tiles for the layer.
3545   UpdateDrawProperties(host_impl()->pending_tree());
3546
3547   // Build the raster queue and invalidate the top tile if partial raster is
3548   // enabled.
3549   std::unique_ptr<RasterTilePriorityQueue> queue(host_impl()->BuildRasterQueue(
3550       SAME_PRIORITY_FOR_BOTH_TREES, RasterTilePriorityQueue::Type::ALL));
3551   ASSERT_FALSE(queue->IsEmpty());
3552
3553   // PrepareTiles to schedule tasks. This should cause the decoded image tracker
3554   // to release its lock.
3555   EXPECT_EQ(2u, host_impl()
3556                     ->tile_manager()
3557                     ->decoded_image_tracker()
3558                     .NumLockedImagesForTesting());
3559   host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
3560   EXPECT_EQ(0u, host_impl()
3561                     ->tile_manager()
3562                     ->decoded_image_tracker()
3563                     .NumLockedImagesForTesting());
3564 }
3565
3566 class HdrImageTileManagerTest : public CheckerImagingTileManagerTest {
3567  public:
3568   void DecodeHdrImage(const gfx::ColorSpace& output_cs) {
3569     auto color_space = gfx::ColorSpace::CreateHDR10();
3570     auto size = gfx::Size(250, 250);
3571     auto info =
3572         SkImageInfo::Make(size.width(), size.height(), kRGBA_F16_SkColorType,
3573                           kPremul_SkAlphaType, color_space.ToSkColorSpace());
3574     SkBitmap bitmap;
3575     bitmap.allocPixels(info);
3576     PaintImage hdr_image = PaintImageBuilder::WithDefault()
3577                                .set_id(PaintImage::kInvalidId)
3578                                .set_is_high_bit_depth(true)
3579                                .set_image(SkImage::MakeFromBitmap(bitmap),
3580                                           PaintImage::GetNextContentId())
3581                                .TakePaintImage();
3582
3583     // Add the image to our decoded_image_tracker.
3584     TargetColorParams target_color_params;
3585     target_color_params.color_space = output_cs;
3586     host_impl()->tile_manager()->decoded_image_tracker().QueueImageDecode(
3587         hdr_image, target_color_params, base::DoNothing());
3588     FlushDecodeTasks();
3589
3590     // Add images to a fake recording source.
3591     constexpr gfx::Size kLayerBounds(1000, 500);
3592     auto recording_source =
3593         FakeRecordingSource::CreateFilledRecordingSource(kLayerBounds);
3594     recording_source->set_fill_with_nonsolid_color(true);
3595     recording_source->add_draw_image(hdr_image, gfx::Point(0, 0));
3596     recording_source->Rerecord();
3597
3598     auto raster_source = recording_source->CreateRasterSource();
3599
3600     constexpr gfx::Size kTileSize(500, 500);
3601     Region invalidation((gfx::Rect(kLayerBounds)));
3602     SetupPendingTree(raster_source, kTileSize, invalidation);
3603
3604     constexpr float kCustomWhiteLevel = 200.f;
3605     auto display_cs = gfx::DisplayColorSpaces(output_cs);
3606     if (output_cs.IsHDR())
3607       display_cs.SetSDRMaxLuminanceNits(kCustomWhiteLevel);
3608
3609     pending_layer()->layer_tree_impl()->SetDisplayColorSpaces(display_cs);
3610     PictureLayerTilingSet* tiling_set =
3611         pending_layer()->picture_layer_tiling_set();
3612     PictureLayerTiling* pending_tiling = tiling_set->tiling_at(0);
3613     pending_tiling->set_resolution(HIGH_RESOLUTION);
3614     pending_tiling->CreateAllTilesForTesting();
3615     pending_tiling->SetTilePriorityRectsForTesting(
3616         gfx::Rect(kLayerBounds),   // Visible rect.
3617         gfx::Rect(kLayerBounds),   // Skewport rect.
3618         gfx::Rect(kLayerBounds),   // Soon rect.
3619         gfx::Rect(kLayerBounds));  // Eventually rect.
3620
3621     host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
3622     ASSERT_TRUE(host_impl()->tile_manager()->HasScheduledTileTasksForTesting());
3623
3624     auto pending_tiles = pending_tiling->AllTilesForTesting();
3625     ASSERT_FALSE(pending_tiles.empty());
3626
3627     const auto raster_cs = gfx::ColorSpace::CreateExtendedSRGB();
3628     if (output_cs.IsHDR()) {
3629       // Only the last tile will have any pending tasks.
3630       const auto& pending_tasks =
3631           host_impl()->tile_manager()->decode_tasks_for_testing(
3632               pending_tiles.back()->id());
3633       EXPECT_FALSE(pending_tasks.empty());
3634       for (const auto& draw_info : pending_tasks) {
3635         EXPECT_EQ(draw_info.target_color_space(), raster_cs);
3636         EXPECT_FLOAT_EQ(draw_info.sdr_white_level(), kCustomWhiteLevel);
3637       }
3638     }
3639
3640     // Raster all tiles.
3641     static_cast<SynchronousTaskGraphRunner*>(task_graph_runner())
3642         ->RunUntilIdle();
3643     base::RunLoop().RunUntilIdle();
3644     ASSERT_FALSE(
3645         host_impl()->tile_manager()->HasScheduledTileTasksForTesting());
3646
3647     auto expected_format = output_cs.IsHDR() ? viz::RGBA_F16 : viz::RGBA_8888;
3648     auto all_tiles = host_impl()->tile_manager()->AllTilesForTesting();
3649     for (const auto* tile : all_tiles)
3650       EXPECT_EQ(expected_format, tile->draw_info().resource_format());
3651   }
3652 };
3653
3654 TEST_F(HdrImageTileManagerTest, DecodeHdrImagesToHdrPq) {
3655   DecodeHdrImage(gfx::ColorSpace::CreateHDR10());
3656 }
3657
3658 TEST_F(HdrImageTileManagerTest, DecodeHdrImagesToHdrHlg) {
3659   DecodeHdrImage(gfx::ColorSpace::CreateHLG());
3660 }
3661
3662 TEST_F(HdrImageTileManagerTest, DecodeHdrImagesToSdrSrgb) {
3663   DecodeHdrImage(gfx::ColorSpace::CreateSRGB());
3664 }
3665
3666 TEST_F(HdrImageTileManagerTest, DecodeHdrImagesToSdrP3) {
3667   DecodeHdrImage(gfx::ColorSpace::CreateDisplayP3D65());
3668 }
3669
3670 class TileManagerCheckRasterQueriesTest : public TileManagerTest {
3671  public:
3672   TileManagerCheckRasterQueriesTest()
3673       : pending_raster_queries_(
3674             viz::TestContextProvider::CreateWorker().get()) {}
3675   ~TileManagerCheckRasterQueriesTest() override {
3676     // Ensure that the host impl doesn't outlive |raster_buffer_provider_|.
3677     TakeHostImpl();
3678   }
3679   void SetUp() override {
3680     TileManagerTest::SetUp();
3681     host_impl()->tile_manager()->SetPendingRasterQueriesForTesting(
3682         &pending_raster_queries_);
3683   }
3684
3685  protected:
3686   class MockRasterQueryQueue : public FakeRasterQueryQueue {
3687    public:
3688     explicit MockRasterQueryQueue(
3689         viz::RasterContextProvider* const worker_context_provider)
3690         : FakeRasterQueryQueue(worker_context_provider) {}
3691     MOCK_METHOD0(CheckRasterFinishedQueries, bool());
3692   };
3693
3694   MockRasterQueryQueue pending_raster_queries_;
3695 };
3696
3697 TEST_F(TileManagerCheckRasterQueriesTest,
3698        ChecksRasterQueriesInAllTilesDoneTask) {
3699   base::RunLoop run_loop;
3700   EXPECT_FALSE(host_impl()->tile_manager()->HasScheduledTileTasksForTesting());
3701   EXPECT_CALL(MockHostImpl(), NotifyAllTileTasksCompleted())
3702       .WillOnce(testing::Invoke([&run_loop]() { run_loop.Quit(); }));
3703   EXPECT_CALL(pending_raster_queries_, CheckRasterFinishedQueries()).Times(1);
3704   host_impl()->tile_manager()->PrepareTiles(host_impl()->global_tile_state());
3705   EXPECT_TRUE(host_impl()->tile_manager()->HasScheduledTileTasksForTesting());
3706   run_loop.Run();
3707 }
3708
3709 }  // namespace
3710 }  // namespace cc