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