Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / cc / trees / layer_tree_host_unittest.cc
1 // Copyright 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "cc/trees/layer_tree_host.h"
6
7 #include <algorithm>
8
9 #include "base/auto_reset.h"
10 #include "base/synchronization/lock.h"
11 #include "cc/animation/timing_function.h"
12 #include "cc/base/swap_promise.h"
13 #include "cc/debug/frame_rate_counter.h"
14 #include "cc/layers/content_layer.h"
15 #include "cc/layers/content_layer_client.h"
16 #include "cc/layers/io_surface_layer.h"
17 #include "cc/layers/layer_impl.h"
18 #include "cc/layers/painted_scrollbar_layer.h"
19 #include "cc/layers/picture_layer.h"
20 #include "cc/layers/solid_color_layer.h"
21 #include "cc/layers/video_layer.h"
22 #include "cc/output/begin_frame_args.h"
23 #include "cc/output/copy_output_request.h"
24 #include "cc/output/copy_output_result.h"
25 #include "cc/output/output_surface.h"
26 #include "cc/quads/draw_quad.h"
27 #include "cc/quads/io_surface_draw_quad.h"
28 #include "cc/resources/prioritized_resource.h"
29 #include "cc/resources/prioritized_resource_manager.h"
30 #include "cc/resources/resource_update_queue.h"
31 #include "cc/test/fake_content_layer.h"
32 #include "cc/test/fake_content_layer_client.h"
33 #include "cc/test/fake_content_layer_impl.h"
34 #include "cc/test/fake_layer_tree_host_client.h"
35 #include "cc/test/fake_output_surface.h"
36 #include "cc/test/fake_painted_scrollbar_layer.h"
37 #include "cc/test/fake_picture_layer.h"
38 #include "cc/test/fake_picture_layer_impl.h"
39 #include "cc/test/fake_proxy.h"
40 #include "cc/test/fake_scoped_ui_resource.h"
41 #include "cc/test/fake_video_frame_provider.h"
42 #include "cc/test/geometry_test_utils.h"
43 #include "cc/test/layer_tree_test.h"
44 #include "cc/test/test_shared_bitmap_manager.h"
45 #include "cc/test/test_web_graphics_context_3d.h"
46 #include "cc/trees/layer_tree_host_impl.h"
47 #include "cc/trees/layer_tree_impl.h"
48 #include "cc/trees/single_thread_proxy.h"
49 #include "cc/trees/thread_proxy.h"
50 #include "gpu/GLES2/gl2extchromium.h"
51 #include "skia/ext/refptr.h"
52 #include "testing/gmock/include/gmock/gmock.h"
53 #include "third_party/khronos/GLES2/gl2.h"
54 #include "third_party/khronos/GLES2/gl2ext.h"
55 #include "third_party/skia/include/core/SkPicture.h"
56 #include "ui/gfx/frame_time.h"
57 #include "ui/gfx/point_conversions.h"
58 #include "ui/gfx/size_conversions.h"
59 #include "ui/gfx/vector2d_conversions.h"
60
61 using testing::_;
62 using testing::AnyNumber;
63 using testing::AtLeast;
64 using testing::Mock;
65
66 namespace cc {
67 namespace {
68
69 class LayerTreeHostTest : public LayerTreeTest {};
70
71 // Two setNeedsCommits in a row should lead to at least 1 commit and at least 1
72 // draw with frame 0.
73 class LayerTreeHostTestSetNeedsCommit1 : public LayerTreeHostTest {
74  public:
75   LayerTreeHostTestSetNeedsCommit1() : num_commits_(0), num_draws_(0) {}
76
77   virtual void BeginTest() OVERRIDE {
78     PostSetNeedsCommitToMainThread();
79     PostSetNeedsCommitToMainThread();
80   }
81
82   virtual void DrawLayersOnThread(LayerTreeHostImpl* impl) OVERRIDE {
83     num_draws_++;
84     if (!impl->active_tree()->source_frame_number())
85       EndTest();
86   }
87
88   virtual void CommitCompleteOnThread(LayerTreeHostImpl* impl) OVERRIDE {
89     num_commits_++;
90   }
91
92   virtual void AfterTest() OVERRIDE {
93     EXPECT_GE(1, num_commits_);
94     EXPECT_GE(1, num_draws_);
95   }
96
97  private:
98   int num_commits_;
99   int num_draws_;
100 };
101
102 SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostTestSetNeedsCommit1);
103
104 // A SetNeedsCommit should lead to 1 commit. Issuing a second commit after that
105 // first committed frame draws should lead to another commit.
106 class LayerTreeHostTestSetNeedsCommit2 : public LayerTreeHostTest {
107  public:
108   LayerTreeHostTestSetNeedsCommit2() : num_commits_(0), num_draws_(0) {}
109
110   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
111
112   virtual void DrawLayersOnThread(LayerTreeHostImpl* impl) OVERRIDE {
113     ++num_draws_;
114   }
115
116   virtual void CommitCompleteOnThread(LayerTreeHostImpl* impl) OVERRIDE {
117     ++num_commits_;
118     switch (num_commits_) {
119       case 1:
120         PostSetNeedsCommitToMainThread();
121         break;
122       case 2:
123         EndTest();
124         break;
125       default:
126         NOTREACHED();
127     }
128   }
129
130   virtual void AfterTest() OVERRIDE {
131     EXPECT_EQ(2, num_commits_);
132     EXPECT_LE(1, num_draws_);
133   }
134
135  private:
136   int num_commits_;
137   int num_draws_;
138 };
139
140 MULTI_THREAD_TEST_F(LayerTreeHostTestSetNeedsCommit2);
141
142 // Verify that we pass property values in PushPropertiesTo.
143 class LayerTreeHostTestPushPropertiesTo : public LayerTreeHostTest {
144  protected:
145   virtual void SetupTree() OVERRIDE {
146     scoped_refptr<Layer> root = Layer::Create();
147     root->SetBounds(gfx::Size(10, 10));
148     layer_tree_host()->SetRootLayer(root);
149     LayerTreeHostTest::SetupTree();
150   }
151
152   enum Properties {
153     STARTUP,
154     BOUNDS,
155     HIDE_LAYER_AND_SUBTREE,
156     DRAWS_CONTENT,
157     DONE,
158   };
159
160   virtual void BeginTest() OVERRIDE {
161     index_ = STARTUP;
162     PostSetNeedsCommitToMainThread();
163   }
164
165   virtual void DrawLayersOnThread(LayerTreeHostImpl* impl) OVERRIDE {
166     VerifyAfterValues(impl->active_tree()->root_layer());
167   }
168
169   virtual void DidCommitAndDrawFrame() OVERRIDE {
170     SetBeforeValues(layer_tree_host()->root_layer());
171     VerifyBeforeValues(layer_tree_host()->root_layer());
172
173     ++index_;
174     if (index_ == DONE) {
175       EndTest();
176       return;
177     }
178
179     SetAfterValues(layer_tree_host()->root_layer());
180   }
181
182   virtual void AfterTest() OVERRIDE {}
183
184   void VerifyBeforeValues(Layer* layer) {
185     EXPECT_EQ(gfx::Size(10, 10).ToString(), layer->bounds().ToString());
186     EXPECT_FALSE(layer->hide_layer_and_subtree());
187     EXPECT_FALSE(layer->DrawsContent());
188   }
189
190   void SetBeforeValues(Layer* layer) {
191     layer->SetBounds(gfx::Size(10, 10));
192     layer->SetHideLayerAndSubtree(false);
193     layer->SetIsDrawable(false);
194   }
195
196   void VerifyAfterValues(LayerImpl* layer) {
197     switch (static_cast<Properties>(index_)) {
198       case STARTUP:
199       case DONE:
200         break;
201       case BOUNDS:
202         EXPECT_EQ(gfx::Size(20, 20).ToString(), layer->bounds().ToString());
203         break;
204       case HIDE_LAYER_AND_SUBTREE:
205         EXPECT_TRUE(layer->hide_layer_and_subtree());
206         break;
207       case DRAWS_CONTENT:
208         EXPECT_TRUE(layer->DrawsContent());
209         break;
210     }
211   }
212
213   void SetAfterValues(Layer* layer) {
214     switch (static_cast<Properties>(index_)) {
215       case STARTUP:
216       case DONE:
217         break;
218       case BOUNDS:
219         layer->SetBounds(gfx::Size(20, 20));
220         break;
221       case HIDE_LAYER_AND_SUBTREE:
222         layer->SetHideLayerAndSubtree(true);
223         break;
224       case DRAWS_CONTENT:
225         layer->SetIsDrawable(true);
226         break;
227     }
228   }
229
230   int index_;
231 };
232
233 SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostTestPushPropertiesTo);
234
235 // 1 setNeedsRedraw after the first commit has completed should lead to 1
236 // additional draw.
237 class LayerTreeHostTestSetNeedsRedraw : public LayerTreeHostTest {
238  public:
239   LayerTreeHostTestSetNeedsRedraw() : num_commits_(0), num_draws_(0) {}
240
241   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
242
243   virtual void DrawLayersOnThread(LayerTreeHostImpl* impl) OVERRIDE {
244     EXPECT_EQ(0, impl->active_tree()->source_frame_number());
245     if (!num_draws_) {
246       // Redraw again to verify that the second redraw doesn't commit.
247       PostSetNeedsRedrawToMainThread();
248     } else {
249       EndTest();
250     }
251     num_draws_++;
252   }
253
254   virtual void CommitCompleteOnThread(LayerTreeHostImpl* impl) OVERRIDE {
255     EXPECT_EQ(0, num_draws_);
256     num_commits_++;
257   }
258
259   virtual void AfterTest() OVERRIDE {
260     EXPECT_GE(2, num_draws_);
261     EXPECT_EQ(1, num_commits_);
262   }
263
264  private:
265   int num_commits_;
266   int num_draws_;
267 };
268
269 MULTI_THREAD_TEST_F(LayerTreeHostTestSetNeedsRedraw);
270
271 // After setNeedsRedrawRect(invalid_rect) the final damage_rect
272 // must contain invalid_rect.
273 class LayerTreeHostTestSetNeedsRedrawRect : public LayerTreeHostTest {
274  public:
275   LayerTreeHostTestSetNeedsRedrawRect()
276       : num_draws_(0),
277         bounds_(50, 50),
278         invalid_rect_(10, 10, 20, 20),
279         root_layer_(ContentLayer::Create(&client_)) {}
280
281   virtual void BeginTest() OVERRIDE {
282     root_layer_->SetIsDrawable(true);
283     root_layer_->SetBounds(bounds_);
284     layer_tree_host()->SetRootLayer(root_layer_);
285     layer_tree_host()->SetViewportSize(bounds_);
286     PostSetNeedsCommitToMainThread();
287   }
288
289   virtual DrawSwapReadbackResult::DrawResult PrepareToDrawOnThread(
290       LayerTreeHostImpl* host_impl,
291       LayerTreeHostImpl::FrameData* frame_data,
292       DrawSwapReadbackResult::DrawResult draw_result) OVERRIDE {
293     EXPECT_EQ(DrawSwapReadbackResult::DRAW_SUCCESS, draw_result);
294
295     gfx::RectF root_damage_rect;
296     if (!frame_data->render_passes.empty())
297       root_damage_rect = frame_data->render_passes.back()->damage_rect;
298
299     if (!num_draws_) {
300       // If this is the first frame, expect full frame damage.
301       EXPECT_RECT_EQ(root_damage_rect, gfx::Rect(bounds_));
302     } else {
303       // Check that invalid_rect_ is indeed repainted.
304       EXPECT_TRUE(root_damage_rect.Contains(invalid_rect_));
305     }
306
307     return draw_result;
308   }
309
310   virtual void DrawLayersOnThread(LayerTreeHostImpl* impl) OVERRIDE {
311     if (!num_draws_) {
312       PostSetNeedsRedrawRectToMainThread(invalid_rect_);
313     } else {
314       EndTest();
315     }
316     num_draws_++;
317   }
318
319   virtual void AfterTest() OVERRIDE { EXPECT_EQ(2, num_draws_); }
320
321  private:
322   int num_draws_;
323   const gfx::Size bounds_;
324   const gfx::Rect invalid_rect_;
325   FakeContentLayerClient client_;
326   scoped_refptr<ContentLayer> root_layer_;
327 };
328
329 SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostTestSetNeedsRedrawRect);
330
331 class LayerTreeHostTestNoExtraCommitFromInvalidate : public LayerTreeHostTest {
332  public:
333   virtual void InitializeSettings(LayerTreeSettings* settings) OVERRIDE {
334     settings->layer_transforms_should_scale_layer_contents = true;
335   }
336
337   virtual void SetupTree() OVERRIDE {
338     root_layer_ = Layer::Create();
339     root_layer_->SetBounds(gfx::Size(10, 20));
340
341     scaled_layer_ = FakeContentLayer::Create(&client_);
342     scaled_layer_->SetBounds(gfx::Size(1, 1));
343     root_layer_->AddChild(scaled_layer_);
344
345     layer_tree_host()->SetRootLayer(root_layer_);
346     LayerTreeHostTest::SetupTree();
347   }
348
349   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
350
351   virtual void DrawLayersOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
352     if (host_impl->active_tree()->source_frame_number() == 1)
353       EndTest();
354   }
355
356   virtual void DidCommit() OVERRIDE {
357     switch (layer_tree_host()->source_frame_number()) {
358       case 1:
359         // Changing the device scale factor causes a commit. It also changes
360         // the content bounds of |scaled_layer_|, which should not generate
361         // a second commit as a result.
362         layer_tree_host()->SetDeviceScaleFactor(4.f);
363         break;
364       default:
365         // No extra commits.
366         EXPECT_EQ(2, layer_tree_host()->source_frame_number());
367     }
368   }
369
370   virtual void AfterTest() OVERRIDE {
371     EXPECT_EQ(gfx::Size(4, 4).ToString(),
372               scaled_layer_->content_bounds().ToString());
373   }
374
375  private:
376   FakeContentLayerClient client_;
377   scoped_refptr<Layer> root_layer_;
378   scoped_refptr<FakeContentLayer> scaled_layer_;
379 };
380
381 SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostTestNoExtraCommitFromInvalidate);
382
383 class LayerTreeHostTestNoExtraCommitFromScrollbarInvalidate
384     : public LayerTreeHostTest {
385  public:
386   virtual void InitializeSettings(LayerTreeSettings* settings) OVERRIDE {
387     settings->layer_transforms_should_scale_layer_contents = true;
388   }
389
390   virtual void SetupTree() OVERRIDE {
391     root_layer_ = Layer::Create();
392     root_layer_->SetBounds(gfx::Size(10, 20));
393
394     bool paint_scrollbar = true;
395     bool has_thumb = false;
396     scrollbar_ = FakePaintedScrollbarLayer::Create(
397         paint_scrollbar, has_thumb, root_layer_->id());
398     scrollbar_->SetPosition(gfx::Point(0, 10));
399     scrollbar_->SetBounds(gfx::Size(10, 10));
400
401     root_layer_->AddChild(scrollbar_);
402
403     layer_tree_host()->SetRootLayer(root_layer_);
404     LayerTreeHostTest::SetupTree();
405   }
406
407   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
408
409   virtual void DrawLayersOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
410     if (host_impl->active_tree()->source_frame_number() == 1)
411       EndTest();
412   }
413
414   virtual void DidCommit() OVERRIDE {
415     switch (layer_tree_host()->source_frame_number()) {
416       case 1:
417         // Changing the device scale factor causes a commit. It also changes
418         // the content bounds of |scrollbar_|, which should not generate
419         // a second commit as a result.
420         layer_tree_host()->SetDeviceScaleFactor(4.f);
421         break;
422       default:
423         // No extra commits.
424         EXPECT_EQ(2, layer_tree_host()->source_frame_number());
425     }
426   }
427
428   virtual void AfterTest() OVERRIDE {
429     EXPECT_EQ(gfx::Size(40, 40).ToString(),
430               scrollbar_->content_bounds().ToString());
431   }
432
433  private:
434   FakeContentLayerClient client_;
435   scoped_refptr<Layer> root_layer_;
436   scoped_refptr<FakePaintedScrollbarLayer> scrollbar_;
437 };
438
439 SINGLE_AND_MULTI_THREAD_TEST_F(
440     LayerTreeHostTestNoExtraCommitFromScrollbarInvalidate);
441
442 class LayerTreeHostTestCompositeAndReadback : public LayerTreeHostTest {
443  public:
444   LayerTreeHostTestCompositeAndReadback() : num_commits_(0) {}
445
446   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
447
448   virtual void DidCommit() OVERRIDE {
449     num_commits_++;
450     if (num_commits_ == 1) {
451       char pixels[4];
452       layer_tree_host()->CompositeAndReadback(&pixels, gfx::Rect(0, 0, 1, 1));
453     } else if (num_commits_ == 2) {
454       // This is inside the readback. We should get another commit after it.
455     } else if (num_commits_ == 3) {
456       EndTest();
457     } else {
458       NOTREACHED();
459     }
460   }
461
462   virtual void AfterTest() OVERRIDE {}
463
464  private:
465   int num_commits_;
466 };
467
468 MULTI_THREAD_TEST_F(LayerTreeHostTestCompositeAndReadback);
469
470 class LayerTreeHostTestCompositeAndReadbackBeforePreviousCommitDraws
471     : public LayerTreeHostTest {
472  public:
473   LayerTreeHostTestCompositeAndReadbackBeforePreviousCommitDraws()
474       : num_commits_(0) {}
475
476   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
477
478   virtual void DidCommit() OVERRIDE {
479     num_commits_++;
480     if (num_commits_ == 1) {
481       layer_tree_host()->SetNeedsCommit();
482     } else if (num_commits_ == 2) {
483       char pixels[4];
484       layer_tree_host()->CompositeAndReadback(&pixels, gfx::Rect(0, 0, 1, 1));
485     } else if (num_commits_ == 3) {
486       // This is inside the readback. We should get another commit after it.
487     } else if (num_commits_ == 4) {
488       EndTest();
489     } else {
490       NOTREACHED();
491     }
492   }
493
494   virtual void AfterTest() OVERRIDE {}
495
496  private:
497   int num_commits_;
498 };
499
500 MULTI_THREAD_TEST_F(
501     LayerTreeHostTestCompositeAndReadbackBeforePreviousCommitDraws);
502
503 class LayerTreeHostTestCompositeAndReadbackDuringForcedDraw
504     : public LayerTreeHostTest {
505  protected:
506   static const int kFirstCommitSourceFrameNumber = 0;
507   static const int kReadbackSourceFrameNumber = 1;
508   static const int kReadbackReplacementAndForcedDrawSourceFrameNumber = 2;
509
510   LayerTreeHostTestCompositeAndReadbackDuringForcedDraw()
511       : did_post_readback_(false) {}
512
513   virtual void InitializeSettings(LayerTreeSettings* settings) OVERRIDE {
514     // This enables forced draws after a single prepare to draw failure.
515     settings->timeout_and_draw_when_animation_checkerboards = true;
516     settings->maximum_number_of_failed_draws_before_draw_is_forced_ = 1;
517   }
518
519   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
520
521   virtual DrawSwapReadbackResult::DrawResult PrepareToDrawOnThread(
522       LayerTreeHostImpl* host_impl,
523       LayerTreeHostImpl::FrameData* frame_data,
524       DrawSwapReadbackResult::DrawResult draw_result) OVERRIDE {
525     int sfn = host_impl->active_tree()->source_frame_number();
526     EXPECT_TRUE(sfn == kFirstCommitSourceFrameNumber ||
527                 sfn == kReadbackSourceFrameNumber ||
528                 sfn == kReadbackReplacementAndForcedDrawSourceFrameNumber)
529         << sfn;
530
531     // Before we react to the failed draw by initiating the forced draw
532     // sequence, start a readback on the main thread.
533     if (sfn == kFirstCommitSourceFrameNumber && !did_post_readback_) {
534       did_post_readback_ = true;
535       PostReadbackToMainThread();
536     }
537
538     // Aborting for checkerboarding animations will result in a forced draw.
539     return DrawSwapReadbackResult::DRAW_ABORTED_CHECKERBOARD_ANIMATIONS;
540   }
541
542   virtual void DrawLayersOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
543     // We should only draw for the readback and the forced draw.
544     int sfn = host_impl->active_tree()->source_frame_number();
545     EXPECT_TRUE(sfn == kReadbackSourceFrameNumber ||
546                 sfn == kReadbackReplacementAndForcedDrawSourceFrameNumber)
547         << sfn;
548   }
549
550   virtual void SwapBuffersOnThread(LayerTreeHostImpl* host_impl,
551                                    bool result) OVERRIDE {
552     // We should only swap for the forced draw.
553     int sfn = host_impl->active_tree()->source_frame_number();
554     EXPECT_TRUE(sfn == kReadbackReplacementAndForcedDrawSourceFrameNumber)
555         << sfn;
556     EndTest();
557   }
558
559   virtual void AfterTest() OVERRIDE {}
560
561   bool did_post_readback_;
562 };
563
564 MULTI_THREAD_TEST_F(LayerTreeHostTestCompositeAndReadbackDuringForcedDraw);
565
566 class LayerTreeHostTestCompositeAndReadbackAfterForcedDraw
567     : public LayerTreeHostTest {
568  protected:
569   static const int kFirstCommitSourceFrameNumber = 0;
570   static const int kForcedDrawSourceFrameNumber = 1;
571   static const int kReadbackSourceFrameNumber = 2;
572   static const int kReadbackReplacementSourceFrameNumber = 3;
573
574   virtual void InitializeSettings(LayerTreeSettings* settings) OVERRIDE {
575     // This enables forced draws after a single prepare to draw failure.
576     settings->timeout_and_draw_when_animation_checkerboards = true;
577     settings->maximum_number_of_failed_draws_before_draw_is_forced_ = 1;
578   }
579
580   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
581
582   virtual DrawSwapReadbackResult::DrawResult PrepareToDrawOnThread(
583       LayerTreeHostImpl* host_impl,
584       LayerTreeHostImpl::FrameData* frame_data,
585       DrawSwapReadbackResult::DrawResult draw_result) OVERRIDE {
586     int sfn = host_impl->active_tree()->source_frame_number();
587     EXPECT_TRUE(sfn == kFirstCommitSourceFrameNumber ||
588                 sfn == kForcedDrawSourceFrameNumber ||
589                 sfn == kReadbackSourceFrameNumber ||
590                 sfn == kReadbackReplacementSourceFrameNumber)
591         << sfn;
592
593     // Aborting for checkerboarding animations will result in a forced draw.
594     return DrawSwapReadbackResult::DRAW_ABORTED_CHECKERBOARD_ANIMATIONS;
595   }
596
597   virtual void DidCommit() OVERRIDE {
598     if (layer_tree_host()->source_frame_number() ==
599         kForcedDrawSourceFrameNumber) {
600       // Avoid aborting the forced draw commit so source_frame_number
601       // increments.
602       layer_tree_host()->SetNeedsCommit();
603     } else if (layer_tree_host()->source_frame_number() ==
604                kReadbackSourceFrameNumber) {
605       // Perform a readback immediately after the forced draw's commit.
606       char pixels[4];
607       layer_tree_host()->CompositeAndReadback(&pixels, gfx::Rect(0, 0, 1, 1));
608     }
609   }
610
611   virtual void DrawLayersOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
612     // We should only draw for the the forced draw, readback, and
613     // replacement commit.
614     int sfn = host_impl->active_tree()->source_frame_number();
615     EXPECT_TRUE(sfn == kForcedDrawSourceFrameNumber ||
616                 sfn == kReadbackSourceFrameNumber ||
617                 sfn == kReadbackReplacementSourceFrameNumber)
618         << sfn;
619   }
620
621   virtual void SwapBuffersOnThread(LayerTreeHostImpl* host_impl,
622                                    bool result) OVERRIDE {
623     // We should only swap for the forced draw and replacement commit.
624     int sfn = host_impl->active_tree()->source_frame_number();
625     EXPECT_TRUE(sfn == kForcedDrawSourceFrameNumber ||
626                 sfn == kReadbackReplacementSourceFrameNumber)
627         << sfn;
628
629     if (sfn == kReadbackReplacementSourceFrameNumber)
630       EndTest();
631   }
632
633   virtual void AfterTest() OVERRIDE {}
634 };
635
636 MULTI_THREAD_TEST_F(LayerTreeHostTestCompositeAndReadbackAfterForcedDraw);
637
638 class LayerTreeHostTestSetNextCommitForcesRedraw : public LayerTreeHostTest {
639  public:
640   LayerTreeHostTestSetNextCommitForcesRedraw()
641       : num_draws_(0),
642         bounds_(50, 50),
643         invalid_rect_(10, 10, 20, 20),
644         root_layer_(ContentLayer::Create(&client_)) {}
645
646   virtual void BeginTest() OVERRIDE {
647     root_layer_->SetIsDrawable(true);
648     root_layer_->SetBounds(bounds_);
649     layer_tree_host()->SetRootLayer(root_layer_);
650     layer_tree_host()->SetViewportSize(bounds_);
651     PostSetNeedsCommitToMainThread();
652   }
653
654   virtual void CommitCompleteOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
655     if (num_draws_ == 3 && host_impl->settings().impl_side_painting)
656       host_impl->SetNeedsRedrawRect(invalid_rect_);
657   }
658
659   virtual DrawSwapReadbackResult::DrawResult PrepareToDrawOnThread(
660       LayerTreeHostImpl* host_impl,
661       LayerTreeHostImpl::FrameData* frame_data,
662       DrawSwapReadbackResult::DrawResult draw_result) OVERRIDE {
663     EXPECT_EQ(DrawSwapReadbackResult::DRAW_SUCCESS, draw_result);
664
665     gfx::RectF root_damage_rect;
666     if (!frame_data->render_passes.empty())
667       root_damage_rect = frame_data->render_passes.back()->damage_rect;
668
669     switch (num_draws_) {
670       case 0:
671         EXPECT_RECT_EQ(gfx::Rect(bounds_), root_damage_rect);
672         break;
673       case 1:
674       case 2:
675         EXPECT_RECT_EQ(gfx::Rect(0, 0, 0, 0), root_damage_rect);
676         break;
677       case 3:
678         EXPECT_RECT_EQ(invalid_rect_, root_damage_rect);
679         break;
680       case 4:
681         EXPECT_RECT_EQ(gfx::Rect(bounds_), root_damage_rect);
682         break;
683       default:
684         NOTREACHED();
685     }
686
687     return draw_result;
688   }
689
690   virtual void DrawLayersOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
691     switch (num_draws_) {
692       case 0:
693       case 1:
694         // Cycle through a couple of empty commits to ensure we're observing the
695         // right behavior
696         PostSetNeedsCommitToMainThread();
697         break;
698       case 2:
699         // Should force full frame damage on the next commit
700         PostSetNextCommitForcesRedrawToMainThread();
701         PostSetNeedsCommitToMainThread();
702         if (host_impl->settings().impl_side_painting)
703           host_impl->BlockNotifyReadyToActivateForTesting(true);
704         else
705           num_draws_++;
706         break;
707       case 3:
708         host_impl->BlockNotifyReadyToActivateForTesting(false);
709         break;
710       default:
711         EndTest();
712         break;
713     }
714     num_draws_++;
715   }
716
717   virtual void AfterTest() OVERRIDE { EXPECT_EQ(5, num_draws_); }
718
719  private:
720   int num_draws_;
721   const gfx::Size bounds_;
722   const gfx::Rect invalid_rect_;
723   FakeContentLayerClient client_;
724   scoped_refptr<ContentLayer> root_layer_;
725 };
726
727 SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostTestSetNextCommitForcesRedraw);
728
729 // Tests that if a layer is not drawn because of some reason in the parent then
730 // its damage is preserved until the next time it is drawn.
731 class LayerTreeHostTestUndrawnLayersDamageLater : public LayerTreeHostTest {
732  public:
733   LayerTreeHostTestUndrawnLayersDamageLater()
734       : root_layer_(ContentLayer::Create(&client_)) {}
735
736   virtual void SetupTree() OVERRIDE {
737     root_layer_->SetIsDrawable(true);
738     root_layer_->SetBounds(gfx::Size(50, 50));
739     layer_tree_host()->SetRootLayer(root_layer_);
740
741     // The initially transparent layer has a larger child layer, which is
742     // not initially drawn because of the this (parent) layer.
743     parent_layer_ = FakeContentLayer::Create(&client_);
744     parent_layer_->SetBounds(gfx::Size(15, 15));
745     parent_layer_->SetOpacity(0.0f);
746     root_layer_->AddChild(parent_layer_);
747
748     child_layer_ = FakeContentLayer::Create(&client_);
749     child_layer_->SetBounds(gfx::Size(25, 25));
750     parent_layer_->AddChild(child_layer_);
751
752     LayerTreeHostTest::SetupTree();
753   }
754
755   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
756
757   virtual DrawSwapReadbackResult::DrawResult PrepareToDrawOnThread(
758       LayerTreeHostImpl* host_impl,
759       LayerTreeHostImpl::FrameData* frame_data,
760       DrawSwapReadbackResult::DrawResult draw_result) OVERRIDE {
761     EXPECT_EQ(DrawSwapReadbackResult::DRAW_SUCCESS, draw_result);
762
763     gfx::RectF root_damage_rect;
764     if (!frame_data->render_passes.empty())
765       root_damage_rect = frame_data->render_passes.back()->damage_rect;
766
767     // The first time, the whole view needs be drawn.
768     // Afterwards, just the opacity of surface_layer1 is changed a few times,
769     // and each damage should be the bounding box of it and its child. If this
770     // was working improperly, the damage might not include its childs bounding
771     // box.
772     switch (layer_tree_host()->source_frame_number()) {
773       case 1:
774         EXPECT_RECT_EQ(gfx::Rect(root_layer_->bounds()), root_damage_rect);
775         break;
776       case 2:
777       case 3:
778       case 4:
779         EXPECT_RECT_EQ(gfx::Rect(child_layer_->bounds()), root_damage_rect);
780         break;
781       default:
782         NOTREACHED();
783     }
784
785     return draw_result;
786   }
787
788   virtual void DidCommitAndDrawFrame() OVERRIDE {
789     switch (layer_tree_host()->source_frame_number()) {
790       case 1:
791         // Test not owning the surface.
792         parent_layer_->SetOpacity(1.0f);
793         break;
794       case 2:
795         parent_layer_->SetOpacity(0.0f);
796         break;
797       case 3:
798         // Test owning the surface.
799         parent_layer_->SetOpacity(0.5f);
800         parent_layer_->SetForceRenderSurface(true);
801         break;
802       case 4:
803         EndTest();
804         break;
805       default:
806         NOTREACHED();
807     }
808   }
809
810   virtual void AfterTest() OVERRIDE {}
811
812  private:
813   FakeContentLayerClient client_;
814   scoped_refptr<ContentLayer> root_layer_;
815   scoped_refptr<FakeContentLayer> parent_layer_;
816   scoped_refptr<FakeContentLayer> child_layer_;
817 };
818
819 SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostTestUndrawnLayersDamageLater);
820
821 // Tests that if a layer is not drawn because of some reason in the parent,
822 // causing its content bounds to not be computed, then when it is later drawn,
823 // its content bounds get pushed.
824 class LayerTreeHostTestUndrawnLayersPushContentBoundsLater
825     : public LayerTreeHostTest {
826  public:
827   LayerTreeHostTestUndrawnLayersPushContentBoundsLater()
828       : root_layer_(Layer::Create()) {}
829
830   virtual void SetupTree() OVERRIDE {
831     root_layer_->SetIsDrawable(true);
832     root_layer_->SetBounds(gfx::Size(20, 20));
833     layer_tree_host()->SetRootLayer(root_layer_);
834
835     parent_layer_ = Layer::Create();
836     parent_layer_->SetBounds(gfx::Size(20, 20));
837     parent_layer_->SetOpacity(0.0f);
838     root_layer_->AddChild(parent_layer_);
839
840     child_layer_ = Layer::Create();
841     child_layer_->SetBounds(gfx::Size(15, 15));
842     parent_layer_->AddChild(child_layer_);
843
844     LayerTreeHostTest::SetupTree();
845   }
846
847   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
848
849   virtual void DidActivateTreeOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
850     LayerImpl* root = host_impl->active_tree()->root_layer();
851     LayerImpl* parent = root->children()[0];
852     LayerImpl* child = parent->children()[0];
853
854     switch (host_impl->active_tree()->source_frame_number()) {
855       case 0:
856         EXPECT_EQ(0.f, parent->opacity());
857         EXPECT_EQ(gfx::SizeF(), child->content_bounds());
858         break;
859       case 1:
860         EXPECT_EQ(1.f, parent->opacity());
861         EXPECT_EQ(gfx::SizeF(15.f, 15.f), child->content_bounds());
862         EndTest();
863         break;
864       default:
865         NOTREACHED();
866     }
867   }
868
869   virtual void DidCommit() OVERRIDE {
870     switch (layer_tree_host()->source_frame_number()) {
871       case 1:
872         parent_layer_->SetOpacity(1.0f);
873         break;
874       case 2:
875         break;
876       default:
877         NOTREACHED();
878     }
879   }
880
881   virtual void AfterTest() OVERRIDE {}
882
883  private:
884   scoped_refptr<Layer> root_layer_;
885   scoped_refptr<Layer> parent_layer_;
886   scoped_refptr<Layer> child_layer_;
887 };
888
889 SINGLE_AND_MULTI_THREAD_TEST_F(
890     LayerTreeHostTestUndrawnLayersPushContentBoundsLater);
891
892 // If the layerTreeHost says it can't draw, Then we should not try to draw.
893 class LayerTreeHostTestCanDrawBlocksDrawing : public LayerTreeHostTest {
894  public:
895   LayerTreeHostTestCanDrawBlocksDrawing() : done_(false) {}
896
897   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
898
899   virtual void DrawLayersOnThread(LayerTreeHostImpl* impl) OVERRIDE {
900     if (done_)
901       return;
902     // Only the initial draw should bring us here.
903     EXPECT_TRUE(impl->CanDraw());
904     EXPECT_EQ(0, impl->active_tree()->source_frame_number());
905   }
906
907   virtual void CommitCompleteOnThread(LayerTreeHostImpl* impl) OVERRIDE {
908     if (done_)
909       return;
910     if (LastCommittedSourceFrameNumber(impl) >= 1) {
911       // After the first commit, we should not be able to draw.
912       EXPECT_FALSE(impl->CanDraw());
913     }
914   }
915
916   virtual void DidCommit() OVERRIDE {
917     switch (layer_tree_host()->source_frame_number()) {
918       case 1:
919         // Make the viewport empty so the host says it can't draw.
920         layer_tree_host()->SetViewportSize(gfx::Size(0, 0));
921         break;
922       case 2: {
923         char pixels[4];
924         layer_tree_host()->CompositeAndReadback(&pixels, gfx::Rect(0, 0, 1, 1));
925         break;
926       }
927       case 3:
928         // Let it draw so we go idle and end the test.
929         layer_tree_host()->SetViewportSize(gfx::Size(1, 1));
930         done_ = true;
931         EndTest();
932         break;
933     }
934   }
935
936   virtual void AfterTest() OVERRIDE {}
937
938  private:
939   bool done_;
940 };
941
942 SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostTestCanDrawBlocksDrawing);
943
944 // A compositeAndReadback while invisible should force a normal commit without
945 // assertion.
946 class LayerTreeHostTestCompositeAndReadbackWhileInvisible
947     : public LayerTreeHostTest {
948  public:
949   LayerTreeHostTestCompositeAndReadbackWhileInvisible() : num_commits_(0) {}
950
951   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
952
953   virtual void DidCommitAndDrawFrame() OVERRIDE {
954     num_commits_++;
955     if (num_commits_ == 1) {
956       layer_tree_host()->SetVisible(false);
957       layer_tree_host()->SetNeedsCommit();
958       layer_tree_host()->SetNeedsCommit();
959       char pixels[4];
960       layer_tree_host()->CompositeAndReadback(&pixels, gfx::Rect(0, 0, 1, 1));
961     } else {
962       EndTest();
963     }
964   }
965
966   virtual void AfterTest() OVERRIDE {}
967
968  private:
969   int num_commits_;
970 };
971
972 MULTI_THREAD_TEST_F(LayerTreeHostTestCompositeAndReadbackWhileInvisible);
973
974 class LayerTreeHostTestAbortFrameWhenInvisible : public LayerTreeHostTest {
975  public:
976   LayerTreeHostTestAbortFrameWhenInvisible() {}
977
978   virtual void BeginTest() OVERRIDE {
979     // Request a commit (from the main thread), Which will trigger the commit
980     // flow from the impl side.
981     layer_tree_host()->SetNeedsCommit();
982     // Then mark ourselves as not visible before processing any more messages
983     // on the main thread.
984     layer_tree_host()->SetVisible(false);
985     // If we make it without kicking a frame, we pass!
986     EndTestAfterDelay(1);
987   }
988
989   virtual void Layout() OVERRIDE {
990     ASSERT_FALSE(true);
991     EndTest();
992   }
993
994   virtual void AfterTest() OVERRIDE {}
995 };
996
997 MULTI_THREAD_TEST_F(LayerTreeHostTestAbortFrameWhenInvisible);
998
999 // This test verifies that properties on the layer tree host are commited
1000 // to the impl side.
1001 class LayerTreeHostTestCommit : public LayerTreeHostTest {
1002  public:
1003   LayerTreeHostTestCommit() {}
1004
1005   virtual void BeginTest() OVERRIDE {
1006     layer_tree_host()->SetViewportSize(gfx::Size(20, 20));
1007     layer_tree_host()->set_background_color(SK_ColorGRAY);
1008
1009     PostSetNeedsCommitToMainThread();
1010   }
1011
1012   virtual void DidActivateTreeOnThread(LayerTreeHostImpl* impl) OVERRIDE {
1013     EXPECT_EQ(gfx::Size(20, 20), impl->DrawViewportSize());
1014     EXPECT_EQ(SK_ColorGRAY, impl->active_tree()->background_color());
1015
1016     EndTest();
1017   }
1018
1019   virtual void AfterTest() OVERRIDE {}
1020 };
1021
1022 MULTI_THREAD_TEST_F(LayerTreeHostTestCommit);
1023
1024 // This test verifies that LayerTreeHostImpl's current frame time gets
1025 // updated in consecutive frames when it doesn't draw due to tree
1026 // activation failure.
1027 class LayerTreeHostTestFrameTimeUpdatesAfterActivationFails
1028     : public LayerTreeHostTest {
1029  public:
1030   LayerTreeHostTestFrameTimeUpdatesAfterActivationFails()
1031       : frame_count_with_pending_tree_(0) {}
1032
1033   virtual void BeginTest() OVERRIDE {
1034     layer_tree_host()->SetViewportSize(gfx::Size(20, 20));
1035     layer_tree_host()->set_background_color(SK_ColorGRAY);
1036
1037     PostSetNeedsCommitToMainThread();
1038   }
1039
1040   virtual void BeginCommitOnThread(LayerTreeHostImpl* impl) OVERRIDE {
1041     EXPECT_EQ(frame_count_with_pending_tree_, 0);
1042     impl->BlockNotifyReadyToActivateForTesting(true);
1043   }
1044
1045   virtual void WillBeginImplFrameOnThread(LayerTreeHostImpl* impl,
1046                                           const BeginFrameArgs& args) OVERRIDE {
1047     if (impl->pending_tree())
1048       frame_count_with_pending_tree_++;
1049
1050     if (frame_count_with_pending_tree_ == 1) {
1051       EXPECT_EQ(first_frame_time_.ToInternalValue(), 0);
1052       first_frame_time_ = impl->CurrentFrameTimeTicks();
1053     } else if (frame_count_with_pending_tree_ == 2) {
1054       impl->BlockNotifyReadyToActivateForTesting(false);
1055     }
1056   }
1057
1058   virtual void DrawLayersOnThread(LayerTreeHostImpl* impl) OVERRIDE {
1059     if (frame_count_with_pending_tree_ > 1) {
1060       EXPECT_NE(first_frame_time_.ToInternalValue(), 0);
1061       EXPECT_NE(first_frame_time_.ToInternalValue(),
1062                 impl->CurrentFrameTimeTicks().ToInternalValue());
1063       EndTest();
1064       return;
1065     }
1066
1067     EXPECT_FALSE(impl->settings().impl_side_painting);
1068     EndTest();
1069   }
1070   virtual void DidActivateTreeOnThread(LayerTreeHostImpl* impl) OVERRIDE {
1071     if (impl->settings().impl_side_painting)
1072       EXPECT_NE(frame_count_with_pending_tree_, 1);
1073   }
1074
1075   virtual void AfterTest() OVERRIDE {}
1076
1077  private:
1078   int frame_count_with_pending_tree_;
1079   base::TimeTicks first_frame_time_;
1080 };
1081
1082 SINGLE_AND_MULTI_THREAD_TEST_F(
1083     LayerTreeHostTestFrameTimeUpdatesAfterActivationFails);
1084
1085 // This test verifies that LayerTreeHostImpl's current frame time gets
1086 // updated in consecutive frames when it draws in each frame.
1087 class LayerTreeHostTestFrameTimeUpdatesAfterDraw : public LayerTreeHostTest {
1088  public:
1089   LayerTreeHostTestFrameTimeUpdatesAfterDraw() : frame_(0) {}
1090
1091   virtual void BeginTest() OVERRIDE {
1092     layer_tree_host()->SetViewportSize(gfx::Size(20, 20));
1093     layer_tree_host()->set_background_color(SK_ColorGRAY);
1094
1095     PostSetNeedsCommitToMainThread();
1096   }
1097
1098   virtual void DrawLayersOnThread(LayerTreeHostImpl* impl) OVERRIDE {
1099     frame_++;
1100     if (frame_ == 1) {
1101       first_frame_time_ = impl->CurrentFrameTimeTicks();
1102       impl->SetNeedsRedraw();
1103
1104       // Since we might use a low-resolution clock on Windows, we need to
1105       // make sure that the clock has incremented past first_frame_time_.
1106       while (first_frame_time_ == gfx::FrameTime::Now()) {
1107       }
1108
1109       return;
1110     }
1111
1112     EXPECT_NE(first_frame_time_, impl->CurrentFrameTimeTicks());
1113     EndTest();
1114   }
1115
1116   virtual void CommitCompleteOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
1117     // Ensure there isn't a commit between the two draws, to ensure that a
1118     // commit isn't required for updating the current frame time. We can
1119     // only check for this in the multi-threaded case, since in the single-
1120     // threaded case there will always be a commit between consecutive draws.
1121     if (HasImplThread())
1122       EXPECT_EQ(0, frame_);
1123   }
1124
1125   virtual void AfterTest() OVERRIDE {}
1126
1127  private:
1128   int frame_;
1129   base::TimeTicks first_frame_time_;
1130 };
1131
1132 SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostTestFrameTimeUpdatesAfterDraw);
1133
1134 // Verifies that StartPageScaleAnimation events propagate correctly
1135 // from LayerTreeHost to LayerTreeHostImpl in the MT compositor.
1136 class LayerTreeHostTestStartPageScaleAnimation : public LayerTreeHostTest {
1137  public:
1138   LayerTreeHostTestStartPageScaleAnimation() {}
1139
1140   virtual void SetupTree() OVERRIDE {
1141     LayerTreeHostTest::SetupTree();
1142
1143     if (layer_tree_host()->settings().impl_side_painting) {
1144       scoped_refptr<FakePictureLayer> layer =
1145           FakePictureLayer::Create(&client_);
1146       layer->set_always_update_resources(true);
1147       scroll_layer_ = layer;
1148     } else {
1149       scroll_layer_ = FakeContentLayer::Create(&client_);
1150     }
1151
1152     Layer* root_layer = layer_tree_host()->root_layer();
1153     scroll_layer_->SetScrollClipLayerId(root_layer->id());
1154     scroll_layer_->SetIsContainerForFixedPositionLayers(true);
1155     scroll_layer_->SetBounds(gfx::Size(2 * root_layer->bounds().width(),
1156                                        2 * root_layer->bounds().height()));
1157     scroll_layer_->SetScrollOffset(gfx::Vector2d());
1158     layer_tree_host()->root_layer()->AddChild(scroll_layer_);
1159     // This test requires the page_scale and inner viewport layers to be
1160     // identified.
1161     layer_tree_host()->RegisterViewportLayers(
1162         root_layer, scroll_layer_.get(), NULL);
1163     layer_tree_host()->SetPageScaleFactorAndLimits(1.f, 0.5f, 2.f);
1164   }
1165
1166   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
1167
1168   virtual void ApplyScrollAndScale(const gfx::Vector2d& scroll_delta,
1169                                    float scale) OVERRIDE {
1170     gfx::Vector2d offset = scroll_layer_->scroll_offset();
1171     scroll_layer_->SetScrollOffset(offset + scroll_delta);
1172     layer_tree_host()->SetPageScaleFactorAndLimits(scale, 0.5f, 2.f);
1173   }
1174
1175   virtual void DidActivateTreeOnThread(LayerTreeHostImpl* impl) OVERRIDE {
1176     // We get one commit before the first draw, and the animation doesn't happen
1177     // until the second draw.
1178     switch (impl->active_tree()->source_frame_number()) {
1179       case 0:
1180         EXPECT_EQ(1.f, impl->active_tree()->page_scale_factor());
1181         // We'll start an animation when we get back to the main thread.
1182         break;
1183       case 1:
1184         EXPECT_EQ(1.f, impl->active_tree()->page_scale_factor());
1185         break;
1186       case 2:
1187         EXPECT_EQ(1.25f, impl->active_tree()->page_scale_factor());
1188         EndTest();
1189         break;
1190       default:
1191         NOTREACHED();
1192     }
1193   }
1194
1195   virtual void DidCommitAndDrawFrame() OVERRIDE {
1196     switch (layer_tree_host()->source_frame_number()) {
1197       case 1:
1198         layer_tree_host()->StartPageScaleAnimation(
1199             gfx::Vector2d(), false, 1.25f, base::TimeDelta());
1200         break;
1201     }
1202   }
1203
1204   virtual void AfterTest() OVERRIDE {}
1205
1206   FakeContentLayerClient client_;
1207   scoped_refptr<Layer> scroll_layer_;
1208 };
1209
1210 MULTI_THREAD_TEST_F(LayerTreeHostTestStartPageScaleAnimation);
1211
1212 class LayerTreeHostTestSetVisible : public LayerTreeHostTest {
1213  public:
1214   LayerTreeHostTestSetVisible() : num_draws_(0) {}
1215
1216   virtual void BeginTest() OVERRIDE {
1217     PostSetNeedsCommitToMainThread();
1218     PostSetVisibleToMainThread(false);
1219     // This is suppressed while we're invisible.
1220     PostSetNeedsRedrawToMainThread();
1221     // Triggers the redraw.
1222     PostSetVisibleToMainThread(true);
1223   }
1224
1225   virtual void DrawLayersOnThread(LayerTreeHostImpl* impl) OVERRIDE {
1226     EXPECT_TRUE(impl->visible());
1227     ++num_draws_;
1228     EndTest();
1229   }
1230
1231   virtual void AfterTest() OVERRIDE { EXPECT_EQ(1, num_draws_); }
1232
1233  private:
1234   int num_draws_;
1235 };
1236
1237 MULTI_THREAD_TEST_F(LayerTreeHostTestSetVisible);
1238
1239 class TestOpacityChangeLayerDelegate : public ContentLayerClient {
1240  public:
1241   TestOpacityChangeLayerDelegate() : test_layer_(0) {}
1242
1243   void SetTestLayer(Layer* test_layer) { test_layer_ = test_layer; }
1244
1245   virtual void PaintContents(
1246       SkCanvas* canvas,
1247       const gfx::Rect& clip,
1248       gfx::RectF* opaque,
1249       ContentLayerClient::GraphicsContextStatus gc_status) OVERRIDE {
1250     // Set layer opacity to 0.
1251     if (test_layer_)
1252       test_layer_->SetOpacity(0.f);
1253   }
1254   virtual void DidChangeLayerCanUseLCDText() OVERRIDE {}
1255   virtual bool FillsBoundsCompletely() const OVERRIDE { return false; }
1256
1257  private:
1258   Layer* test_layer_;
1259 };
1260
1261 class ContentLayerWithUpdateTracking : public ContentLayer {
1262  public:
1263   static scoped_refptr<ContentLayerWithUpdateTracking> Create(
1264       ContentLayerClient* client) {
1265     return make_scoped_refptr(new ContentLayerWithUpdateTracking(client));
1266   }
1267
1268   int PaintContentsCount() { return paint_contents_count_; }
1269   void ResetPaintContentsCount() { paint_contents_count_ = 0; }
1270
1271   virtual bool Update(ResourceUpdateQueue* queue,
1272                       const OcclusionTracker<Layer>* occlusion) OVERRIDE {
1273     bool updated = ContentLayer::Update(queue, occlusion);
1274     paint_contents_count_++;
1275     return updated;
1276   }
1277
1278  private:
1279   explicit ContentLayerWithUpdateTracking(ContentLayerClient* client)
1280       : ContentLayer(client), paint_contents_count_(0) {
1281     SetAnchorPoint(gfx::PointF(0.f, 0.f));
1282     SetBounds(gfx::Size(10, 10));
1283     SetIsDrawable(true);
1284   }
1285   virtual ~ContentLayerWithUpdateTracking() {}
1286
1287   int paint_contents_count_;
1288 };
1289
1290 // Layer opacity change during paint should not prevent compositor resources
1291 // from being updated during commit.
1292 class LayerTreeHostTestOpacityChange : public LayerTreeHostTest {
1293  public:
1294   LayerTreeHostTestOpacityChange()
1295       : test_opacity_change_delegate_(),
1296         update_check_layer_(ContentLayerWithUpdateTracking::Create(
1297             &test_opacity_change_delegate_)) {
1298     test_opacity_change_delegate_.SetTestLayer(update_check_layer_.get());
1299   }
1300
1301   virtual void BeginTest() OVERRIDE {
1302     layer_tree_host()->SetViewportSize(gfx::Size(10, 10));
1303     layer_tree_host()->root_layer()->AddChild(update_check_layer_);
1304
1305     PostSetNeedsCommitToMainThread();
1306   }
1307
1308   virtual void CommitCompleteOnThread(LayerTreeHostImpl* impl) OVERRIDE {
1309     EndTest();
1310   }
1311
1312   virtual void AfterTest() OVERRIDE {
1313     // Update() should have been called once.
1314     EXPECT_EQ(1, update_check_layer_->PaintContentsCount());
1315   }
1316
1317  private:
1318   TestOpacityChangeLayerDelegate test_opacity_change_delegate_;
1319   scoped_refptr<ContentLayerWithUpdateTracking> update_check_layer_;
1320 };
1321
1322 MULTI_THREAD_TEST_F(LayerTreeHostTestOpacityChange);
1323
1324 class NoScaleContentLayer : public ContentLayer {
1325  public:
1326   static scoped_refptr<NoScaleContentLayer> Create(ContentLayerClient* client) {
1327     return make_scoped_refptr(new NoScaleContentLayer(client));
1328   }
1329
1330   virtual void CalculateContentsScale(float ideal_contents_scale,
1331                                       float device_scale_factor,
1332                                       float page_scale_factor,
1333                                       float maximum_animation_contents_scale,
1334                                       bool animating_transform_to_screen,
1335                                       float* contents_scale_x,
1336                                       float* contents_scale_y,
1337                                       gfx::Size* contentBounds) OVERRIDE {
1338     // Skip over the ContentLayer's method to the base Layer class.
1339     Layer::CalculateContentsScale(ideal_contents_scale,
1340                                   device_scale_factor,
1341                                   page_scale_factor,
1342                                   maximum_animation_contents_scale,
1343                                   animating_transform_to_screen,
1344                                   contents_scale_x,
1345                                   contents_scale_y,
1346                                   contentBounds);
1347   }
1348
1349  private:
1350   explicit NoScaleContentLayer(ContentLayerClient* client)
1351       : ContentLayer(client) {}
1352   virtual ~NoScaleContentLayer() {}
1353 };
1354
1355 class LayerTreeHostTestDeviceScaleFactorScalesViewportAndLayers
1356     : public LayerTreeHostTest {
1357  public:
1358   LayerTreeHostTestDeviceScaleFactorScalesViewportAndLayers()
1359       : root_layer_(NoScaleContentLayer::Create(&client_)),
1360         child_layer_(ContentLayer::Create(&client_)) {}
1361
1362   virtual void BeginTest() OVERRIDE {
1363     layer_tree_host()->SetViewportSize(gfx::Size(60, 60));
1364     layer_tree_host()->SetDeviceScaleFactor(1.5);
1365     EXPECT_EQ(gfx::Size(60, 60), layer_tree_host()->device_viewport_size());
1366
1367     root_layer_->AddChild(child_layer_);
1368
1369     root_layer_->SetIsDrawable(true);
1370     root_layer_->SetBounds(gfx::Size(30, 30));
1371     root_layer_->SetAnchorPoint(gfx::PointF(0.f, 0.f));
1372
1373     child_layer_->SetIsDrawable(true);
1374     child_layer_->SetPosition(gfx::Point(2, 2));
1375     child_layer_->SetBounds(gfx::Size(10, 10));
1376     child_layer_->SetAnchorPoint(gfx::PointF(0.f, 0.f));
1377
1378     layer_tree_host()->SetRootLayer(root_layer_);
1379
1380     PostSetNeedsCommitToMainThread();
1381   }
1382
1383   virtual void DidActivateTreeOnThread(LayerTreeHostImpl* impl) OVERRIDE {
1384     // Should only do one commit.
1385     EXPECT_EQ(0, impl->active_tree()->source_frame_number());
1386     // Device scale factor should come over to impl.
1387     EXPECT_NEAR(impl->device_scale_factor(), 1.5f, 0.00001f);
1388
1389     // Both layers are on impl.
1390     ASSERT_EQ(1u, impl->active_tree()->root_layer()->children().size());
1391
1392     // Device viewport is scaled.
1393     EXPECT_EQ(gfx::Size(60, 60), impl->DrawViewportSize());
1394
1395     LayerImpl* root = impl->active_tree()->root_layer();
1396     LayerImpl* child = impl->active_tree()->root_layer()->children()[0];
1397
1398     // Positions remain in layout pixels.
1399     EXPECT_EQ(gfx::Point(0, 0), root->position());
1400     EXPECT_EQ(gfx::Point(2, 2), child->position());
1401
1402     // Compute all the layer transforms for the frame.
1403     LayerTreeHostImpl::FrameData frame_data;
1404     impl->PrepareToDraw(&frame_data, gfx::Rect());
1405     impl->DidDrawAllLayers(frame_data);
1406
1407     const LayerImplList& render_surface_layer_list =
1408         *frame_data.render_surface_layer_list;
1409
1410     // Both layers should be drawing into the root render surface.
1411     ASSERT_EQ(1u, render_surface_layer_list.size());
1412     ASSERT_EQ(root->render_surface(),
1413               render_surface_layer_list[0]->render_surface());
1414     ASSERT_EQ(2u, root->render_surface()->layer_list().size());
1415
1416     // The root render surface is the size of the viewport.
1417     EXPECT_RECT_EQ(gfx::Rect(0, 0, 60, 60),
1418                    root->render_surface()->content_rect());
1419
1420     // The content bounds of the child should be scaled.
1421     gfx::Size child_bounds_scaled =
1422         gfx::ToCeiledSize(gfx::ScaleSize(child->bounds(), 1.5));
1423     EXPECT_EQ(child_bounds_scaled, child->content_bounds());
1424
1425     gfx::Transform scale_transform;
1426     scale_transform.Scale(impl->device_scale_factor(),
1427                           impl->device_scale_factor());
1428
1429     // The root layer is scaled by 2x.
1430     gfx::Transform root_screen_space_transform = scale_transform;
1431     gfx::Transform root_draw_transform = scale_transform;
1432
1433     EXPECT_EQ(root_draw_transform, root->draw_transform());
1434     EXPECT_EQ(root_screen_space_transform, root->screen_space_transform());
1435
1436     // The child is at position 2,2, which is transformed to 3,3 after the scale
1437     gfx::Transform child_screen_space_transform;
1438     child_screen_space_transform.Translate(3.f, 3.f);
1439     gfx::Transform child_draw_transform = child_screen_space_transform;
1440
1441     EXPECT_TRANSFORMATION_MATRIX_EQ(child_draw_transform,
1442                                     child->draw_transform());
1443     EXPECT_TRANSFORMATION_MATRIX_EQ(child_screen_space_transform,
1444                                     child->screen_space_transform());
1445
1446     EndTest();
1447   }
1448
1449   virtual void AfterTest() OVERRIDE {}
1450
1451  private:
1452   FakeContentLayerClient client_;
1453   scoped_refptr<NoScaleContentLayer> root_layer_;
1454   scoped_refptr<ContentLayer> child_layer_;
1455 };
1456
1457 MULTI_THREAD_TEST_F(LayerTreeHostTestDeviceScaleFactorScalesViewportAndLayers);
1458
1459 // Verify atomicity of commits and reuse of textures.
1460 class LayerTreeHostTestDirectRendererAtomicCommit : public LayerTreeHostTest {
1461  public:
1462   virtual void InitializeSettings(LayerTreeSettings* settings) OVERRIDE {
1463     settings->texture_id_allocation_chunk_size = 1;
1464     // Make sure partial texture updates are turned off.
1465     settings->max_partial_texture_updates = 0;
1466     // Linear fade animator prevents scrollbars from drawing immediately.
1467     settings->scrollbar_animator = LayerTreeSettings::NoAnimator;
1468   }
1469
1470   virtual void SetupTree() OVERRIDE {
1471     layer_ = FakeContentLayer::Create(&client_);
1472     layer_->SetBounds(gfx::Size(10, 20));
1473
1474     bool paint_scrollbar = true;
1475     bool has_thumb = false;
1476     scrollbar_ = FakePaintedScrollbarLayer::Create(
1477         paint_scrollbar, has_thumb, layer_->id());
1478     scrollbar_->SetPosition(gfx::Point(0, 10));
1479     scrollbar_->SetBounds(gfx::Size(10, 10));
1480
1481     layer_->AddChild(scrollbar_);
1482
1483     layer_tree_host()->SetRootLayer(layer_);
1484     LayerTreeHostTest::SetupTree();
1485   }
1486
1487   virtual void BeginTest() OVERRIDE {
1488     drew_frame_ = -1;
1489     PostSetNeedsCommitToMainThread();
1490   }
1491
1492   virtual void DidActivateTreeOnThread(LayerTreeHostImpl* impl) OVERRIDE {
1493     ASSERT_EQ(0u, layer_tree_host()->settings().max_partial_texture_updates);
1494
1495     TestWebGraphicsContext3D* context = TestContext();
1496
1497     switch (impl->active_tree()->source_frame_number()) {
1498       case 0:
1499         // Number of textures should be one for each layer
1500         ASSERT_EQ(2u, context->NumTextures());
1501         // Number of textures used for commit should be one for each layer.
1502         EXPECT_EQ(2u, context->NumUsedTextures());
1503         // Verify that used texture is correct.
1504         EXPECT_TRUE(context->UsedTexture(context->TextureAt(0)));
1505         EXPECT_TRUE(context->UsedTexture(context->TextureAt(1)));
1506
1507         context->ResetUsedTextures();
1508         break;
1509       case 1:
1510         // Number of textures should be one for scrollbar layer since it was
1511         // requested and deleted on the impl-thread, and double for the content
1512         // layer since its first texture is used by impl thread and cannot by
1513         // used for update.
1514         ASSERT_EQ(3u, context->NumTextures());
1515         // Number of textures used for commit should be one for each layer.
1516         EXPECT_EQ(2u, context->NumUsedTextures());
1517         // First textures should not have been used.
1518         EXPECT_FALSE(context->UsedTexture(context->TextureAt(0)));
1519         EXPECT_TRUE(context->UsedTexture(context->TextureAt(1)));
1520         // New textures should have been used.
1521         EXPECT_TRUE(context->UsedTexture(context->TextureAt(2)));
1522         context->ResetUsedTextures();
1523         break;
1524       case 2:
1525         EndTest();
1526         break;
1527       default:
1528         NOTREACHED();
1529         break;
1530     }
1531   }
1532
1533   virtual void DrawLayersOnThread(LayerTreeHostImpl* impl) OVERRIDE {
1534     TestWebGraphicsContext3D* context = TestContext();
1535
1536     if (drew_frame_ == impl->active_tree()->source_frame_number()) {
1537       EXPECT_EQ(0u, context->NumUsedTextures()) << "For frame " << drew_frame_;
1538       return;
1539     }
1540     drew_frame_ = impl->active_tree()->source_frame_number();
1541
1542     // We draw/ship one texture each frame for each layer.
1543     EXPECT_EQ(2u, context->NumUsedTextures());
1544     context->ResetUsedTextures();
1545
1546     if (!TestEnded())
1547       PostSetNeedsCommitToMainThread();
1548   }
1549
1550   virtual void Layout() OVERRIDE {
1551     layer_->SetNeedsDisplay();
1552     scrollbar_->SetNeedsDisplay();
1553   }
1554
1555   virtual void AfterTest() OVERRIDE {}
1556
1557  protected:
1558   FakeContentLayerClient client_;
1559   scoped_refptr<FakeContentLayer> layer_;
1560   scoped_refptr<FakePaintedScrollbarLayer> scrollbar_;
1561   int drew_frame_;
1562 };
1563
1564 MULTI_THREAD_DIRECT_RENDERER_NOIMPL_TEST_F(
1565     LayerTreeHostTestDirectRendererAtomicCommit);
1566
1567 class LayerTreeHostTestDelegatingRendererAtomicCommit
1568     : public LayerTreeHostTestDirectRendererAtomicCommit {
1569  public:
1570   virtual void DidActivateTreeOnThread(LayerTreeHostImpl* impl) OVERRIDE {
1571     ASSERT_EQ(0u, layer_tree_host()->settings().max_partial_texture_updates);
1572
1573     TestWebGraphicsContext3D* context = TestContext();
1574
1575     switch (impl->active_tree()->source_frame_number()) {
1576       case 0:
1577         // Number of textures should be one for each layer
1578         ASSERT_EQ(2u, context->NumTextures());
1579         // Number of textures used for commit should be one for each layer.
1580         EXPECT_EQ(2u, context->NumUsedTextures());
1581         // Verify that used texture is correct.
1582         EXPECT_TRUE(context->UsedTexture(context->TextureAt(0)));
1583         EXPECT_TRUE(context->UsedTexture(context->TextureAt(1)));
1584         context->ResetUsedTextures();
1585         break;
1586       case 1:
1587         // Number of textures should be doubled as the first context layer
1588         // texture is being used by the impl-thread and cannot be used for
1589         // update.  The scrollbar behavior is different direct renderer because
1590         // UI resource deletion with delegating renderer occurs after tree
1591         // activation.
1592         ASSERT_EQ(4u, context->NumTextures());
1593         // Number of textures used for commit should still be
1594         // one for each layer.
1595         EXPECT_EQ(2u, context->NumUsedTextures());
1596         // First textures should not have been used.
1597         EXPECT_FALSE(context->UsedTexture(context->TextureAt(0)));
1598         EXPECT_FALSE(context->UsedTexture(context->TextureAt(1)));
1599         // New textures should have been used.
1600         EXPECT_TRUE(context->UsedTexture(context->TextureAt(2)));
1601         EXPECT_TRUE(context->UsedTexture(context->TextureAt(3)));
1602         context->ResetUsedTextures();
1603         break;
1604       case 2:
1605         EndTest();
1606         break;
1607       default:
1608         NOTREACHED();
1609         break;
1610     }
1611   }
1612 };
1613
1614 MULTI_THREAD_DELEGATING_RENDERER_NOIMPL_TEST_F(
1615     LayerTreeHostTestDelegatingRendererAtomicCommit);
1616
1617 static void SetLayerPropertiesForTesting(Layer* layer,
1618                                          Layer* parent,
1619                                          const gfx::Transform& transform,
1620                                          const gfx::PointF& anchor,
1621                                          const gfx::PointF& position,
1622                                          const gfx::Size& bounds,
1623                                          bool opaque) {
1624   layer->RemoveAllChildren();
1625   if (parent)
1626     parent->AddChild(layer);
1627   layer->SetTransform(transform);
1628   layer->SetAnchorPoint(anchor);
1629   layer->SetPosition(position);
1630   layer->SetBounds(bounds);
1631   layer->SetContentsOpaque(opaque);
1632 }
1633
1634 class LayerTreeHostTestAtomicCommitWithPartialUpdate
1635     : public LayerTreeHostTest {
1636  public:
1637   virtual void InitializeSettings(LayerTreeSettings* settings) OVERRIDE {
1638     settings->texture_id_allocation_chunk_size = 1;
1639     // Allow one partial texture update.
1640     settings->max_partial_texture_updates = 1;
1641     // No partial updates when impl side painting is enabled.
1642     settings->impl_side_painting = false;
1643   }
1644
1645   virtual void SetupTree() OVERRIDE {
1646     parent_ = FakeContentLayer::Create(&client_);
1647     parent_->SetBounds(gfx::Size(10, 20));
1648
1649     child_ = FakeContentLayer::Create(&client_);
1650     child_->SetPosition(gfx::Point(0, 10));
1651     child_->SetBounds(gfx::Size(3, 10));
1652
1653     parent_->AddChild(child_);
1654
1655     layer_tree_host()->SetRootLayer(parent_);
1656     LayerTreeHostTest::SetupTree();
1657   }
1658
1659   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
1660
1661   virtual void DidCommitAndDrawFrame() OVERRIDE {
1662     switch (layer_tree_host()->source_frame_number()) {
1663       case 1:
1664         parent_->SetNeedsDisplay();
1665         child_->SetNeedsDisplay();
1666         break;
1667       case 2:
1668         // Damage part of layers.
1669         parent_->SetNeedsDisplayRect(gfx::RectF(0.f, 0.f, 5.f, 5.f));
1670         child_->SetNeedsDisplayRect(gfx::RectF(0.f, 0.f, 5.f, 5.f));
1671         break;
1672       case 3:
1673         child_->SetNeedsDisplay();
1674         layer_tree_host()->SetViewportSize(gfx::Size(10, 10));
1675         break;
1676       case 4:
1677         layer_tree_host()->SetViewportSize(gfx::Size(10, 20));
1678         break;
1679       case 5:
1680         EndTest();
1681         break;
1682       default:
1683         NOTREACHED() << layer_tree_host()->source_frame_number();
1684         break;
1685     }
1686   }
1687
1688   virtual void CommitCompleteOnThread(LayerTreeHostImpl* impl) OVERRIDE {
1689     ASSERT_EQ(1u, layer_tree_host()->settings().max_partial_texture_updates);
1690
1691     TestWebGraphicsContext3D* context = TestContext();
1692
1693     switch (impl->active_tree()->source_frame_number()) {
1694       case 0:
1695         // Number of textures should be one for each layer.
1696         ASSERT_EQ(2u, context->NumTextures());
1697         // Number of textures used for commit should be one for each layer.
1698         EXPECT_EQ(2u, context->NumUsedTextures());
1699         // Verify that used textures are correct.
1700         EXPECT_TRUE(context->UsedTexture(context->TextureAt(0)));
1701         EXPECT_TRUE(context->UsedTexture(context->TextureAt(1)));
1702         context->ResetUsedTextures();
1703         break;
1704       case 1:
1705         if (HasImplThread()) {
1706           // Number of textures should be two for each content layer.
1707           ASSERT_EQ(4u, context->NumTextures());
1708         } else {
1709           // In single thread we can always do partial updates, so the limit has
1710           // no effect.
1711           ASSERT_EQ(2u, context->NumTextures());
1712         }
1713         // Number of textures used for commit should be one for each content
1714         // layer.
1715         EXPECT_EQ(2u, context->NumUsedTextures());
1716
1717         if (HasImplThread()) {
1718           // First content textures should not have been used.
1719           EXPECT_FALSE(context->UsedTexture(context->TextureAt(0)));
1720           EXPECT_FALSE(context->UsedTexture(context->TextureAt(1)));
1721           // New textures should have been used.
1722           EXPECT_TRUE(context->UsedTexture(context->TextureAt(2)));
1723           EXPECT_TRUE(context->UsedTexture(context->TextureAt(3)));
1724         } else {
1725           // In single thread we can always do partial updates, so the limit has
1726           // no effect.
1727           EXPECT_TRUE(context->UsedTexture(context->TextureAt(0)));
1728           EXPECT_TRUE(context->UsedTexture(context->TextureAt(1)));
1729         }
1730
1731         context->ResetUsedTextures();
1732         break;
1733       case 2:
1734         if (HasImplThread()) {
1735           // Number of textures should be two for each content layer.
1736           ASSERT_EQ(4u, context->NumTextures());
1737         } else {
1738           // In single thread we can always do partial updates, so the limit has
1739           // no effect.
1740           ASSERT_EQ(2u, context->NumTextures());
1741         }
1742         // Number of textures used for commit should be one for each content
1743         // layer.
1744         EXPECT_EQ(2u, context->NumUsedTextures());
1745
1746         if (HasImplThread()) {
1747           // One content layer does a partial update also.
1748           EXPECT_TRUE(context->UsedTexture(context->TextureAt(2)));
1749           EXPECT_FALSE(context->UsedTexture(context->TextureAt(3)));
1750         } else {
1751           // In single thread we can always do partial updates, so the limit has
1752           // no effect.
1753           EXPECT_TRUE(context->UsedTexture(context->TextureAt(0)));
1754           EXPECT_TRUE(context->UsedTexture(context->TextureAt(1)));
1755         }
1756
1757         context->ResetUsedTextures();
1758         break;
1759       case 3:
1760         // No textures should be used for commit.
1761         EXPECT_EQ(0u, context->NumUsedTextures());
1762
1763         context->ResetUsedTextures();
1764         break;
1765       case 4:
1766         // Number of textures used for commit should be one, for the
1767         // content layer.
1768         EXPECT_EQ(1u, context->NumUsedTextures());
1769
1770         context->ResetUsedTextures();
1771         break;
1772       default:
1773         NOTREACHED();
1774         break;
1775     }
1776   }
1777
1778   virtual void DrawLayersOnThread(LayerTreeHostImpl* impl) OVERRIDE {
1779     EXPECT_LT(impl->active_tree()->source_frame_number(), 5);
1780
1781     TestWebGraphicsContext3D* context = TestContext();
1782
1783     // Number of textures used for drawing should one per layer except for
1784     // frame 3 where the viewport only contains one layer.
1785     if (impl->active_tree()->source_frame_number() == 3) {
1786       EXPECT_EQ(1u, context->NumUsedTextures());
1787     } else {
1788       EXPECT_EQ(2u, context->NumUsedTextures())
1789           << "For frame " << impl->active_tree()->source_frame_number();
1790     }
1791
1792     context->ResetUsedTextures();
1793   }
1794
1795   virtual void AfterTest() OVERRIDE {}
1796
1797  private:
1798   FakeContentLayerClient client_;
1799   scoped_refptr<FakeContentLayer> parent_;
1800   scoped_refptr<FakeContentLayer> child_;
1801 };
1802
1803 // Partial updates are not possible with a delegating renderer.
1804 SINGLE_AND_MULTI_THREAD_DIRECT_RENDERER_TEST_F(
1805     LayerTreeHostTestAtomicCommitWithPartialUpdate);
1806
1807 class LayerTreeHostTestFinishAllRendering : public LayerTreeHostTest {
1808  public:
1809   LayerTreeHostTestFinishAllRendering() : once_(false), draw_count_(0) {}
1810
1811   virtual void BeginTest() OVERRIDE {
1812     layer_tree_host()->SetNeedsRedraw();
1813     PostSetNeedsCommitToMainThread();
1814   }
1815
1816   virtual void DidCommitAndDrawFrame() OVERRIDE {
1817     if (once_)
1818       return;
1819     once_ = true;
1820     layer_tree_host()->SetNeedsRedraw();
1821     {
1822       base::AutoLock lock(lock_);
1823       draw_count_ = 0;
1824     }
1825     layer_tree_host()->FinishAllRendering();
1826     {
1827       base::AutoLock lock(lock_);
1828       EXPECT_EQ(0, draw_count_);
1829     }
1830     EndTest();
1831   }
1832
1833   virtual void DrawLayersOnThread(LayerTreeHostImpl* impl) OVERRIDE {
1834     base::AutoLock lock(lock_);
1835     ++draw_count_;
1836   }
1837
1838   virtual void AfterTest() OVERRIDE {}
1839
1840  private:
1841   bool once_;
1842   base::Lock lock_;
1843   int draw_count_;
1844 };
1845
1846 SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostTestFinishAllRendering);
1847
1848 class LayerTreeHostTestCompositeAndReadbackCleanup : public LayerTreeHostTest {
1849  public:
1850   virtual void BeginTest() OVERRIDE {
1851     Layer* root_layer = layer_tree_host()->root_layer();
1852
1853     char pixels[4];
1854     layer_tree_host()->CompositeAndReadback(static_cast<void*>(&pixels),
1855                                             gfx::Rect(0, 0, 1, 1));
1856     EXPECT_FALSE(root_layer->render_surface());
1857
1858     EndTest();
1859   }
1860
1861   virtual void AfterTest() OVERRIDE {}
1862 };
1863
1864 SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostTestCompositeAndReadbackCleanup);
1865
1866 class LayerTreeHostTestSurfaceNotAllocatedForLayersOutsideMemoryLimit
1867     : public LayerTreeHostTest {
1868  protected:
1869   virtual void SetupTree() OVERRIDE {
1870     root_layer_ = FakeContentLayer::Create(&client_);
1871     root_layer_->SetBounds(gfx::Size(100, 100));
1872
1873     surface_layer1_ = FakeContentLayer::Create(&client_);
1874     surface_layer1_->SetBounds(gfx::Size(100, 100));
1875     surface_layer1_->SetForceRenderSurface(true);
1876     surface_layer1_->SetOpacity(0.5f);
1877     root_layer_->AddChild(surface_layer1_);
1878
1879     surface_layer2_ = FakeContentLayer::Create(&client_);
1880     surface_layer2_->SetBounds(gfx::Size(100, 100));
1881     surface_layer2_->SetForceRenderSurface(true);
1882     surface_layer2_->SetOpacity(0.5f);
1883     surface_layer1_->AddChild(surface_layer2_);
1884
1885     replica_layer1_ = FakeContentLayer::Create(&client_);
1886     surface_layer1_->SetReplicaLayer(replica_layer1_.get());
1887
1888     replica_layer2_ = FakeContentLayer::Create(&client_);
1889     surface_layer2_->SetReplicaLayer(replica_layer2_.get());
1890
1891     layer_tree_host()->SetRootLayer(root_layer_);
1892     LayerTreeHostTest::SetupTree();
1893   }
1894
1895   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
1896
1897   virtual void DrawLayersOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
1898     Renderer* renderer = host_impl->renderer();
1899     RenderPass::Id surface1_render_pass_id = host_impl->active_tree()
1900                                                  ->root_layer()
1901                                                  ->children()[0]
1902                                                  ->render_surface()
1903                                                  ->RenderPassId();
1904     RenderPass::Id surface2_render_pass_id = host_impl->active_tree()
1905                                                  ->root_layer()
1906                                                  ->children()[0]
1907                                                  ->children()[0]
1908                                                  ->render_surface()
1909                                                  ->RenderPassId();
1910
1911     switch (host_impl->active_tree()->source_frame_number()) {
1912       case 0:
1913         EXPECT_TRUE(
1914             renderer->HasAllocatedResourcesForTesting(surface1_render_pass_id));
1915         EXPECT_TRUE(
1916             renderer->HasAllocatedResourcesForTesting(surface2_render_pass_id));
1917
1918         // Reduce the memory limit to only fit the root layer and one render
1919         // surface. This prevents any contents drawing into surfaces
1920         // from being allocated.
1921         host_impl->SetMemoryPolicy(ManagedMemoryPolicy(100 * 100 * 4 * 2));
1922         break;
1923       case 1:
1924         EXPECT_FALSE(
1925             renderer->HasAllocatedResourcesForTesting(surface1_render_pass_id));
1926         EXPECT_FALSE(
1927             renderer->HasAllocatedResourcesForTesting(surface2_render_pass_id));
1928
1929         EndTest();
1930         break;
1931     }
1932   }
1933
1934   virtual void DidCommitAndDrawFrame() OVERRIDE {
1935     if (layer_tree_host()->source_frame_number() < 2)
1936       root_layer_->SetNeedsDisplay();
1937   }
1938
1939   virtual void AfterTest() OVERRIDE {
1940     EXPECT_LE(2u, root_layer_->update_count());
1941     EXPECT_LE(2u, surface_layer1_->update_count());
1942     EXPECT_LE(2u, surface_layer2_->update_count());
1943   }
1944
1945   FakeContentLayerClient client_;
1946   scoped_refptr<FakeContentLayer> root_layer_;
1947   scoped_refptr<FakeContentLayer> surface_layer1_;
1948   scoped_refptr<FakeContentLayer> replica_layer1_;
1949   scoped_refptr<FakeContentLayer> surface_layer2_;
1950   scoped_refptr<FakeContentLayer> replica_layer2_;
1951 };
1952
1953 // Surfaces don't exist with a delegated renderer.
1954 SINGLE_AND_MULTI_THREAD_DIRECT_RENDERER_NOIMPL_TEST_F(
1955     LayerTreeHostTestSurfaceNotAllocatedForLayersOutsideMemoryLimit);
1956
1957 class EvictionTestLayer : public Layer {
1958  public:
1959   static scoped_refptr<EvictionTestLayer> Create() {
1960     return make_scoped_refptr(new EvictionTestLayer());
1961   }
1962
1963   virtual bool Update(ResourceUpdateQueue*,
1964                       const OcclusionTracker<Layer>*) OVERRIDE;
1965   virtual bool DrawsContent() const OVERRIDE { return true; }
1966
1967   virtual scoped_ptr<LayerImpl> CreateLayerImpl(LayerTreeImpl* tree_impl)
1968       OVERRIDE;
1969   virtual void PushPropertiesTo(LayerImpl* impl) OVERRIDE;
1970   virtual void SetTexturePriorities(const PriorityCalculator&) OVERRIDE;
1971
1972   bool HaveBackingTexture() const {
1973     return texture_.get() ? texture_->have_backing_texture() : false;
1974   }
1975
1976  private:
1977   EvictionTestLayer() : Layer() {}
1978   virtual ~EvictionTestLayer() {}
1979
1980   void CreateTextureIfNeeded() {
1981     if (texture_)
1982       return;
1983     texture_ = PrioritizedResource::Create(
1984         layer_tree_host()->contents_texture_manager());
1985     texture_->SetDimensions(gfx::Size(10, 10), RGBA_8888);
1986     bitmap_.allocN32Pixels(10, 10);
1987   }
1988
1989   scoped_ptr<PrioritizedResource> texture_;
1990   SkBitmap bitmap_;
1991 };
1992
1993 class EvictionTestLayerImpl : public LayerImpl {
1994  public:
1995   static scoped_ptr<EvictionTestLayerImpl> Create(LayerTreeImpl* tree_impl,
1996                                                   int id) {
1997     return make_scoped_ptr(new EvictionTestLayerImpl(tree_impl, id));
1998   }
1999   virtual ~EvictionTestLayerImpl() {}
2000
2001   virtual void AppendQuads(QuadSink* quad_sink,
2002                            AppendQuadsData* append_quads_data) OVERRIDE {
2003     ASSERT_TRUE(has_texture_);
2004     ASSERT_NE(0u, layer_tree_impl()->resource_provider()->num_resources());
2005   }
2006
2007   void SetHasTexture(bool has_texture) { has_texture_ = has_texture; }
2008
2009  private:
2010   EvictionTestLayerImpl(LayerTreeImpl* tree_impl, int id)
2011       : LayerImpl(tree_impl, id), has_texture_(false) {}
2012
2013   bool has_texture_;
2014 };
2015
2016 void EvictionTestLayer::SetTexturePriorities(const PriorityCalculator&) {
2017   CreateTextureIfNeeded();
2018   if (!texture_)
2019     return;
2020   texture_->set_request_priority(PriorityCalculator::UIPriority(true));
2021 }
2022
2023 bool EvictionTestLayer::Update(ResourceUpdateQueue* queue,
2024                                const OcclusionTracker<Layer>* occlusion) {
2025   CreateTextureIfNeeded();
2026   if (!texture_)
2027     return false;
2028
2029   gfx::Rect full_rect(0, 0, 10, 10);
2030   ResourceUpdate upload = ResourceUpdate::Create(
2031       texture_.get(), &bitmap_, full_rect, full_rect, gfx::Vector2d());
2032   queue->AppendFullUpload(upload);
2033   return true;
2034 }
2035
2036 scoped_ptr<LayerImpl> EvictionTestLayer::CreateLayerImpl(
2037     LayerTreeImpl* tree_impl) {
2038   return EvictionTestLayerImpl::Create(tree_impl, layer_id_)
2039       .PassAs<LayerImpl>();
2040 }
2041
2042 void EvictionTestLayer::PushPropertiesTo(LayerImpl* layer_impl) {
2043   Layer::PushPropertiesTo(layer_impl);
2044
2045   EvictionTestLayerImpl* test_layer_impl =
2046       static_cast<EvictionTestLayerImpl*>(layer_impl);
2047   test_layer_impl->SetHasTexture(texture_->have_backing_texture());
2048 }
2049
2050 class LayerTreeHostTestEvictTextures : public LayerTreeHostTest {
2051  public:
2052   LayerTreeHostTestEvictTextures()
2053       : layer_(EvictionTestLayer::Create()),
2054         impl_for_evict_textures_(0),
2055         num_commits_(0) {}
2056
2057   virtual void BeginTest() OVERRIDE {
2058     layer_tree_host()->SetRootLayer(layer_);
2059     layer_tree_host()->SetViewportSize(gfx::Size(10, 20));
2060
2061     gfx::Transform identity_matrix;
2062     SetLayerPropertiesForTesting(layer_.get(),
2063                                  0,
2064                                  identity_matrix,
2065                                  gfx::PointF(0.f, 0.f),
2066                                  gfx::PointF(0.f, 0.f),
2067                                  gfx::Size(10, 20),
2068                                  true);
2069
2070     PostSetNeedsCommitToMainThread();
2071   }
2072
2073   void PostEvictTextures() {
2074     ImplThreadTaskRunner()->PostTask(
2075         FROM_HERE,
2076         base::Bind(&LayerTreeHostTestEvictTextures::EvictTexturesOnImplThread,
2077                    base::Unretained(this)));
2078   }
2079
2080   void EvictTexturesOnImplThread() {
2081     DCHECK(impl_for_evict_textures_);
2082     impl_for_evict_textures_->EvictTexturesForTesting();
2083   }
2084
2085   // Commit 1: Just commit and draw normally, then post an eviction at the end
2086   // that will trigger a commit.
2087   // Commit 2: Triggered by the eviction, let it go through and then set
2088   // needsCommit.
2089   // Commit 3: Triggered by the setNeedsCommit. In Layout(), post an eviction
2090   // task, which will be handled before the commit. Don't set needsCommit, it
2091   // should have been posted. A frame should not be drawn (note,
2092   // didCommitAndDrawFrame may be called anyway).
2093   // Commit 4: Triggered by the eviction, let it go through and then set
2094   // needsCommit.
2095   // Commit 5: Triggered by the setNeedsCommit, post an eviction task in
2096   // Layout(), a frame should not be drawn but a commit will be posted.
2097   // Commit 6: Triggered by the eviction, post an eviction task in
2098   // Layout(), which will be a noop, letting the commit (which recreates the
2099   // textures) go through and draw a frame, then end the test.
2100   //
2101   // Commits 1+2 test the eviction recovery path where eviction happens outside
2102   // of the beginFrame/commit pair.
2103   // Commits 3+4 test the eviction recovery path where eviction happens inside
2104   // the beginFrame/commit pair.
2105   // Commits 5+6 test the path where an eviction happens during the eviction
2106   // recovery path.
2107   virtual void DidCommit() OVERRIDE {
2108     switch (num_commits_) {
2109       case 1:
2110         EXPECT_TRUE(layer_->HaveBackingTexture());
2111         PostEvictTextures();
2112         break;
2113       case 2:
2114         EXPECT_TRUE(layer_->HaveBackingTexture());
2115         layer_tree_host()->SetNeedsCommit();
2116         break;
2117       case 3:
2118         break;
2119       case 4:
2120         EXPECT_TRUE(layer_->HaveBackingTexture());
2121         layer_tree_host()->SetNeedsCommit();
2122         break;
2123       case 5:
2124         break;
2125       case 6:
2126         EXPECT_TRUE(layer_->HaveBackingTexture());
2127         EndTest();
2128         break;
2129       default:
2130         NOTREACHED();
2131         break;
2132     }
2133   }
2134
2135   virtual void CommitCompleteOnThread(LayerTreeHostImpl* impl) OVERRIDE {
2136     impl_for_evict_textures_ = impl;
2137   }
2138
2139   virtual void Layout() OVERRIDE {
2140     ++num_commits_;
2141     switch (num_commits_) {
2142       case 1:
2143       case 2:
2144         break;
2145       case 3:
2146         PostEvictTextures();
2147         break;
2148       case 4:
2149         // We couldn't check in didCommitAndDrawFrame on commit 3,
2150         // so check here.
2151         EXPECT_FALSE(layer_->HaveBackingTexture());
2152         break;
2153       case 5:
2154         PostEvictTextures();
2155         break;
2156       case 6:
2157         // We couldn't check in didCommitAndDrawFrame on commit 5,
2158         // so check here.
2159         EXPECT_FALSE(layer_->HaveBackingTexture());
2160         PostEvictTextures();
2161         break;
2162       default:
2163         NOTREACHED();
2164         break;
2165     }
2166   }
2167
2168   virtual void AfterTest() OVERRIDE {}
2169
2170  private:
2171   FakeContentLayerClient client_;
2172   scoped_refptr<EvictionTestLayer> layer_;
2173   LayerTreeHostImpl* impl_for_evict_textures_;
2174   int num_commits_;
2175 };
2176
2177 MULTI_THREAD_NOIMPL_TEST_F(LayerTreeHostTestEvictTextures);
2178
2179 class LayerTreeHostTestContinuousCommit : public LayerTreeHostTest {
2180  public:
2181   LayerTreeHostTestContinuousCommit()
2182       : num_commit_complete_(0), num_draw_layers_(0) {}
2183
2184   virtual void BeginTest() OVERRIDE {
2185     layer_tree_host()->SetViewportSize(gfx::Size(10, 10));
2186     layer_tree_host()->root_layer()->SetBounds(gfx::Size(10, 10));
2187
2188     PostSetNeedsCommitToMainThread();
2189   }
2190
2191   virtual void DidCommit() OVERRIDE {
2192     if (num_draw_layers_ == 2)
2193       return;
2194     layer_tree_host()->SetNeedsCommit();
2195   }
2196
2197   virtual void CommitCompleteOnThread(LayerTreeHostImpl* impl) OVERRIDE {
2198     if (num_draw_layers_ == 1)
2199       num_commit_complete_++;
2200   }
2201
2202   virtual void DrawLayersOnThread(LayerTreeHostImpl* impl) OVERRIDE {
2203     num_draw_layers_++;
2204     if (num_draw_layers_ == 2)
2205       EndTest();
2206   }
2207
2208   virtual void AfterTest() OVERRIDE {
2209     // Check that we didn't commit twice between first and second draw.
2210     EXPECT_EQ(1, num_commit_complete_);
2211   }
2212
2213  private:
2214   int num_commit_complete_;
2215   int num_draw_layers_;
2216 };
2217
2218 MULTI_THREAD_TEST_F(LayerTreeHostTestContinuousCommit);
2219
2220 class LayerTreeHostTestContinuousInvalidate : public LayerTreeHostTest {
2221  public:
2222   LayerTreeHostTestContinuousInvalidate()
2223       : num_commit_complete_(0), num_draw_layers_(0) {}
2224
2225   virtual void BeginTest() OVERRIDE {
2226     layer_tree_host()->SetViewportSize(gfx::Size(10, 10));
2227     layer_tree_host()->root_layer()->SetBounds(gfx::Size(10, 10));
2228
2229     content_layer_ = ContentLayer::Create(&client_);
2230     content_layer_->SetBounds(gfx::Size(10, 10));
2231     content_layer_->SetPosition(gfx::PointF(0.f, 0.f));
2232     content_layer_->SetAnchorPoint(gfx::PointF(0.f, 0.f));
2233     content_layer_->SetIsDrawable(true);
2234     layer_tree_host()->root_layer()->AddChild(content_layer_);
2235
2236     PostSetNeedsCommitToMainThread();
2237   }
2238
2239   virtual void DidCommitAndDrawFrame() OVERRIDE {
2240     if (num_draw_layers_ == 2)
2241       return;
2242     content_layer_->SetNeedsDisplay();
2243   }
2244
2245   virtual void CommitCompleteOnThread(LayerTreeHostImpl* impl) OVERRIDE {
2246     if (num_draw_layers_ == 1)
2247       num_commit_complete_++;
2248   }
2249
2250   virtual void DrawLayersOnThread(LayerTreeHostImpl* impl) OVERRIDE {
2251     num_draw_layers_++;
2252     if (num_draw_layers_ == 2)
2253       EndTest();
2254   }
2255
2256   virtual void AfterTest() OVERRIDE {
2257     // Check that we didn't commit twice between first and second draw.
2258     EXPECT_EQ(1, num_commit_complete_);
2259   }
2260
2261  private:
2262   FakeContentLayerClient client_;
2263   scoped_refptr<Layer> content_layer_;
2264   int num_commit_complete_;
2265   int num_draw_layers_;
2266 };
2267
2268 MULTI_THREAD_NOIMPL_TEST_F(LayerTreeHostTestContinuousInvalidate);
2269
2270 class LayerTreeHostTestDeferCommits : public LayerTreeHostTest {
2271  public:
2272   LayerTreeHostTestDeferCommits()
2273       : num_commits_deferred_(0), num_complete_commits_(0) {}
2274
2275   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
2276
2277   virtual void DidDeferCommit() OVERRIDE {
2278     num_commits_deferred_++;
2279     layer_tree_host()->SetDeferCommits(false);
2280   }
2281
2282   virtual void DidCommit() OVERRIDE {
2283     num_complete_commits_++;
2284     switch (num_complete_commits_) {
2285       case 1:
2286         EXPECT_EQ(0, num_commits_deferred_);
2287         layer_tree_host()->SetDeferCommits(true);
2288         PostSetNeedsCommitToMainThread();
2289         break;
2290       case 2:
2291         EndTest();
2292         break;
2293       default:
2294         NOTREACHED();
2295         break;
2296     }
2297   }
2298
2299   virtual void AfterTest() OVERRIDE {
2300     EXPECT_EQ(1, num_commits_deferred_);
2301     EXPECT_EQ(2, num_complete_commits_);
2302   }
2303
2304  private:
2305   int num_commits_deferred_;
2306   int num_complete_commits_;
2307 };
2308
2309 MULTI_THREAD_TEST_F(LayerTreeHostTestDeferCommits);
2310
2311 class LayerTreeHostWithProxy : public LayerTreeHost {
2312  public:
2313   LayerTreeHostWithProxy(FakeLayerTreeHostClient* client,
2314                          const LayerTreeSettings& settings,
2315                          scoped_ptr<FakeProxy> proxy)
2316       : LayerTreeHost(client, NULL, settings) {
2317     proxy->SetLayerTreeHost(this);
2318     InitializeForTesting(proxy.PassAs<Proxy>());
2319   }
2320 };
2321
2322 TEST(LayerTreeHostTest, LimitPartialUpdates) {
2323   // When partial updates are not allowed, max updates should be 0.
2324   {
2325     FakeLayerTreeHostClient client(FakeLayerTreeHostClient::DIRECT_3D);
2326
2327     scoped_ptr<FakeProxy> proxy(new FakeProxy);
2328     proxy->GetRendererCapabilities().allow_partial_texture_updates = false;
2329     proxy->SetMaxPartialTextureUpdates(5);
2330
2331     LayerTreeSettings settings;
2332     settings.max_partial_texture_updates = 10;
2333
2334     LayerTreeHostWithProxy host(&client, settings, proxy.Pass());
2335     EXPECT_TRUE(host.InitializeOutputSurfaceIfNeeded());
2336
2337     EXPECT_EQ(0u, host.MaxPartialTextureUpdates());
2338   }
2339
2340   // When partial updates are allowed,
2341   // max updates should be limited by the proxy.
2342   {
2343     FakeLayerTreeHostClient client(FakeLayerTreeHostClient::DIRECT_3D);
2344
2345     scoped_ptr<FakeProxy> proxy(new FakeProxy);
2346     proxy->GetRendererCapabilities().allow_partial_texture_updates = true;
2347     proxy->SetMaxPartialTextureUpdates(5);
2348
2349     LayerTreeSettings settings;
2350     settings.max_partial_texture_updates = 10;
2351
2352     LayerTreeHostWithProxy host(&client, settings, proxy.Pass());
2353     EXPECT_TRUE(host.InitializeOutputSurfaceIfNeeded());
2354
2355     EXPECT_EQ(5u, host.MaxPartialTextureUpdates());
2356   }
2357
2358   // When partial updates are allowed,
2359   // max updates should also be limited by the settings.
2360   {
2361     FakeLayerTreeHostClient client(FakeLayerTreeHostClient::DIRECT_3D);
2362
2363     scoped_ptr<FakeProxy> proxy(new FakeProxy);
2364     proxy->GetRendererCapabilities().allow_partial_texture_updates = true;
2365     proxy->SetMaxPartialTextureUpdates(20);
2366
2367     LayerTreeSettings settings;
2368     settings.max_partial_texture_updates = 10;
2369
2370     LayerTreeHostWithProxy host(&client, settings, proxy.Pass());
2371     EXPECT_TRUE(host.InitializeOutputSurfaceIfNeeded());
2372
2373     EXPECT_EQ(10u, host.MaxPartialTextureUpdates());
2374   }
2375 }
2376
2377 TEST(LayerTreeHostTest, PartialUpdatesWithGLRenderer) {
2378   FakeLayerTreeHostClient client(FakeLayerTreeHostClient::DIRECT_3D);
2379
2380   LayerTreeSettings settings;
2381   settings.max_partial_texture_updates = 4;
2382
2383   scoped_ptr<SharedBitmapManager> shared_bitmap_manager(
2384       new TestSharedBitmapManager());
2385   scoped_ptr<LayerTreeHost> host = LayerTreeHost::CreateSingleThreaded(
2386       &client, &client, shared_bitmap_manager.get(), settings);
2387   EXPECT_TRUE(host->InitializeOutputSurfaceIfNeeded());
2388   EXPECT_EQ(4u, host->settings().max_partial_texture_updates);
2389 }
2390
2391 TEST(LayerTreeHostTest, PartialUpdatesWithSoftwareRenderer) {
2392   FakeLayerTreeHostClient client(FakeLayerTreeHostClient::DIRECT_SOFTWARE);
2393
2394   LayerTreeSettings settings;
2395   settings.max_partial_texture_updates = 4;
2396
2397   scoped_ptr<SharedBitmapManager> shared_bitmap_manager(
2398       new TestSharedBitmapManager());
2399   scoped_ptr<LayerTreeHost> host = LayerTreeHost::CreateSingleThreaded(
2400       &client, &client, shared_bitmap_manager.get(), settings);
2401   EXPECT_TRUE(host->InitializeOutputSurfaceIfNeeded());
2402   EXPECT_EQ(4u, host->settings().max_partial_texture_updates);
2403 }
2404
2405 TEST(LayerTreeHostTest, PartialUpdatesWithDelegatingRendererAndGLContent) {
2406   FakeLayerTreeHostClient client(FakeLayerTreeHostClient::DELEGATED_3D);
2407
2408   LayerTreeSettings settings;
2409   settings.max_partial_texture_updates = 4;
2410
2411   scoped_ptr<SharedBitmapManager> shared_bitmap_manager(
2412       new TestSharedBitmapManager());
2413   scoped_ptr<LayerTreeHost> host = LayerTreeHost::CreateSingleThreaded(
2414       &client, &client, shared_bitmap_manager.get(), settings);
2415   EXPECT_TRUE(host->InitializeOutputSurfaceIfNeeded());
2416   EXPECT_EQ(0u, host->MaxPartialTextureUpdates());
2417 }
2418
2419 TEST(LayerTreeHostTest,
2420      PartialUpdatesWithDelegatingRendererAndSoftwareContent) {
2421   FakeLayerTreeHostClient client(FakeLayerTreeHostClient::DELEGATED_SOFTWARE);
2422
2423   LayerTreeSettings settings;
2424   settings.max_partial_texture_updates = 4;
2425
2426   scoped_ptr<SharedBitmapManager> shared_bitmap_manager(
2427       new TestSharedBitmapManager());
2428   scoped_ptr<LayerTreeHost> host = LayerTreeHost::CreateSingleThreaded(
2429       &client, &client, shared_bitmap_manager.get(), settings);
2430   EXPECT_TRUE(host->InitializeOutputSurfaceIfNeeded());
2431   EXPECT_EQ(0u, host->MaxPartialTextureUpdates());
2432 }
2433
2434 class LayerTreeHostTestShutdownWithOnlySomeResourcesEvicted
2435     : public LayerTreeHostTest {
2436  public:
2437   LayerTreeHostTestShutdownWithOnlySomeResourcesEvicted()
2438       : root_layer_(FakeContentLayer::Create(&client_)),
2439         child_layer1_(FakeContentLayer::Create(&client_)),
2440         child_layer2_(FakeContentLayer::Create(&client_)),
2441         num_commits_(0) {}
2442
2443   virtual void BeginTest() OVERRIDE {
2444     layer_tree_host()->SetViewportSize(gfx::Size(100, 100));
2445     root_layer_->SetBounds(gfx::Size(100, 100));
2446     child_layer1_->SetBounds(gfx::Size(100, 100));
2447     child_layer2_->SetBounds(gfx::Size(100, 100));
2448     root_layer_->AddChild(child_layer1_);
2449     root_layer_->AddChild(child_layer2_);
2450     layer_tree_host()->SetRootLayer(root_layer_);
2451     PostSetNeedsCommitToMainThread();
2452   }
2453
2454   virtual void DidSetVisibleOnImplTree(LayerTreeHostImpl* host_impl,
2455                                        bool visible) OVERRIDE {
2456     if (visible) {
2457       // One backing should remain unevicted.
2458       EXPECT_EQ(
2459           100u * 100u * 4u * 1u,
2460           layer_tree_host()->contents_texture_manager()->MemoryUseBytes());
2461     } else {
2462       EXPECT_EQ(
2463           0u, layer_tree_host()->contents_texture_manager()->MemoryUseBytes());
2464     }
2465
2466     // Make sure that contents textures are marked as having been
2467     // purged.
2468     EXPECT_TRUE(host_impl->active_tree()->ContentsTexturesPurged());
2469     // End the test in this state.
2470     EndTest();
2471   }
2472
2473   virtual void DidActivateTreeOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
2474     ++num_commits_;
2475     switch (num_commits_) {
2476       case 1:
2477         // All three backings should have memory.
2478         EXPECT_EQ(
2479             100u * 100u * 4u * 3u,
2480             layer_tree_host()->contents_texture_manager()->MemoryUseBytes());
2481         // Set a new policy that will kick out 1 of the 3 resources.
2482         // Because a resource was evicted, a commit will be kicked off.
2483         host_impl->SetMemoryPolicy(
2484             ManagedMemoryPolicy(100 * 100 * 4 * 2,
2485                                 gpu::MemoryAllocation::CUTOFF_ALLOW_EVERYTHING,
2486                                 1000));
2487         break;
2488       case 2:
2489         // Only two backings should have memory.
2490         EXPECT_EQ(
2491             100u * 100u * 4u * 2u,
2492             layer_tree_host()->contents_texture_manager()->MemoryUseBytes());
2493         // Become backgrounded, which will cause 1 more resource to be
2494         // evicted.
2495         PostSetVisibleToMainThread(false);
2496         break;
2497       default:
2498         // No further commits should happen because this is not visible
2499         // anymore.
2500         NOTREACHED();
2501         break;
2502     }
2503   }
2504
2505   virtual void AfterTest() OVERRIDE {}
2506
2507  private:
2508   FakeContentLayerClient client_;
2509   scoped_refptr<FakeContentLayer> root_layer_;
2510   scoped_refptr<FakeContentLayer> child_layer1_;
2511   scoped_refptr<FakeContentLayer> child_layer2_;
2512   int num_commits_;
2513 };
2514
2515 SINGLE_AND_MULTI_THREAD_NOIMPL_TEST_F(
2516     LayerTreeHostTestShutdownWithOnlySomeResourcesEvicted);
2517
2518 class LayerTreeHostTestLCDNotification : public LayerTreeHostTest {
2519  public:
2520   class NotificationClient : public ContentLayerClient {
2521    public:
2522     NotificationClient()
2523         : layer_(0), paint_count_(0), lcd_notification_count_(0) {}
2524
2525     void set_layer(Layer* layer) { layer_ = layer; }
2526     int paint_count() const { return paint_count_; }
2527     int lcd_notification_count() const { return lcd_notification_count_; }
2528
2529     virtual void PaintContents(
2530         SkCanvas* canvas,
2531         const gfx::Rect& clip,
2532         gfx::RectF* opaque,
2533         ContentLayerClient::GraphicsContextStatus gc_status) OVERRIDE {
2534       ++paint_count_;
2535     }
2536     virtual void DidChangeLayerCanUseLCDText() OVERRIDE {
2537       ++lcd_notification_count_;
2538       layer_->SetNeedsDisplay();
2539     }
2540     virtual bool FillsBoundsCompletely() const OVERRIDE { return false; }
2541
2542    private:
2543     Layer* layer_;
2544     int paint_count_;
2545     int lcd_notification_count_;
2546   };
2547
2548   virtual void SetupTree() OVERRIDE {
2549     scoped_refptr<ContentLayer> root_layer = ContentLayer::Create(&client_);
2550     root_layer->SetIsDrawable(true);
2551     root_layer->SetBounds(gfx::Size(1, 1));
2552
2553     layer_tree_host()->SetRootLayer(root_layer);
2554     client_.set_layer(root_layer.get());
2555
2556     // The expecations are based on the assumption that the default
2557     // LCD settings are:
2558     EXPECT_TRUE(layer_tree_host()->settings().can_use_lcd_text);
2559     EXPECT_FALSE(root_layer->can_use_lcd_text());
2560
2561     LayerTreeHostTest::SetupTree();
2562   }
2563
2564   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
2565   virtual void AfterTest() OVERRIDE {}
2566
2567   virtual void DidCommit() OVERRIDE {
2568     switch (layer_tree_host()->source_frame_number()) {
2569       case 1:
2570         // The first update consists one LCD notification and one paint.
2571         EXPECT_EQ(1, client_.lcd_notification_count());
2572         EXPECT_EQ(1, client_.paint_count());
2573         // LCD text must have been enabled on the layer.
2574         EXPECT_TRUE(layer_tree_host()->root_layer()->can_use_lcd_text());
2575         PostSetNeedsCommitToMainThread();
2576         break;
2577       case 2:
2578         // Since nothing changed on layer, there should be no notification
2579         // or paint on the second update.
2580         EXPECT_EQ(1, client_.lcd_notification_count());
2581         EXPECT_EQ(1, client_.paint_count());
2582         // LCD text must not have changed.
2583         EXPECT_TRUE(layer_tree_host()->root_layer()->can_use_lcd_text());
2584         // Change layer opacity that should trigger lcd notification.
2585         layer_tree_host()->root_layer()->SetOpacity(.5f);
2586         // No need to request a commit - setting opacity will do it.
2587         break;
2588       default:
2589         // Verify that there is not extra commit due to layer invalidation.
2590         EXPECT_EQ(3, layer_tree_host()->source_frame_number());
2591         // LCD notification count should have incremented due to
2592         // change in layer opacity.
2593         EXPECT_EQ(2, client_.lcd_notification_count());
2594         // Paint count should be incremented due to invalidation.
2595         EXPECT_EQ(2, client_.paint_count());
2596         // LCD text must have been disabled on the layer due to opacity.
2597         EXPECT_FALSE(layer_tree_host()->root_layer()->can_use_lcd_text());
2598         EndTest();
2599         break;
2600     }
2601   }
2602
2603  private:
2604   NotificationClient client_;
2605 };
2606
2607 SINGLE_THREAD_TEST_F(LayerTreeHostTestLCDNotification);
2608
2609 // Verify that the BeginFrame notification is used to initiate rendering.
2610 class LayerTreeHostTestBeginFrameNotification : public LayerTreeHostTest {
2611  public:
2612   virtual void InitializeSettings(LayerTreeSettings* settings) OVERRIDE {
2613     settings->begin_frame_scheduling_enabled = true;
2614   }
2615
2616   virtual void BeginTest() OVERRIDE {
2617     // This will trigger a SetNeedsBeginFrame which will trigger a
2618     // BeginFrame.
2619     PostSetNeedsCommitToMainThread();
2620   }
2621
2622   virtual DrawSwapReadbackResult::DrawResult PrepareToDrawOnThread(
2623       LayerTreeHostImpl* host_impl,
2624       LayerTreeHostImpl::FrameData* frame,
2625       DrawSwapReadbackResult::DrawResult draw_result) OVERRIDE {
2626     EndTest();
2627     return DrawSwapReadbackResult::DRAW_SUCCESS;
2628   }
2629
2630   virtual void AfterTest() OVERRIDE {}
2631
2632  private:
2633   base::TimeTicks frame_time_;
2634 };
2635
2636 MULTI_THREAD_TEST_F(LayerTreeHostTestBeginFrameNotification);
2637
2638 class LayerTreeHostTestBeginFrameNotificationShutdownWhileEnabled
2639     : public LayerTreeHostTest {
2640  public:
2641   virtual void InitializeSettings(LayerTreeSettings* settings) OVERRIDE {
2642     settings->begin_frame_scheduling_enabled = true;
2643     settings->using_synchronous_renderer_compositor = true;
2644   }
2645
2646   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
2647
2648   virtual void CommitCompleteOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
2649     // The BeginFrame notification is turned off now but will get enabled
2650     // once we return. End test while it's enabled.
2651     ImplThreadTaskRunner()->PostTask(
2652         FROM_HERE,
2653         base::Bind(&LayerTreeHostTestBeginFrameNotification::EndTest,
2654                    base::Unretained(this)));
2655   }
2656
2657   virtual void AfterTest() OVERRIDE {}
2658 };
2659
2660 MULTI_THREAD_TEST_F(
2661     LayerTreeHostTestBeginFrameNotificationShutdownWhileEnabled);
2662
2663 class LayerTreeHostTestAbortedCommitDoesntStall : public LayerTreeHostTest {
2664  protected:
2665   LayerTreeHostTestAbortedCommitDoesntStall()
2666       : commit_count_(0), commit_abort_count_(0), commit_complete_count_(0) {}
2667
2668   virtual void InitializeSettings(LayerTreeSettings* settings) OVERRIDE {
2669     settings->begin_frame_scheduling_enabled = true;
2670   }
2671
2672   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
2673
2674   virtual void DidCommit() OVERRIDE {
2675     commit_count_++;
2676     if (commit_count_ == 4) {
2677       // After two aborted commits, request a real commit now to make sure a
2678       // real commit following an aborted commit will still complete and
2679       // end the test even when the Impl thread is idle.
2680       layer_tree_host()->SetNeedsCommit();
2681     }
2682   }
2683
2684   virtual void BeginMainFrameAbortedOnThread(LayerTreeHostImpl* host_impl,
2685                                              bool did_handle) OVERRIDE {
2686     commit_abort_count_++;
2687     // Initiate another abortable commit.
2688     host_impl->SetNeedsCommit();
2689   }
2690
2691   virtual void CommitCompleteOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
2692     commit_complete_count_++;
2693     if (commit_complete_count_ == 1) {
2694       // Initiate an abortable commit after the first commit.
2695       host_impl->SetNeedsCommit();
2696     } else {
2697       EndTest();
2698     }
2699   }
2700
2701   virtual void AfterTest() OVERRIDE {
2702     EXPECT_EQ(commit_count_, 5);
2703     EXPECT_EQ(commit_abort_count_, 3);
2704     EXPECT_EQ(commit_complete_count_, 2);
2705   }
2706
2707   int commit_count_;
2708   int commit_abort_count_;
2709   int commit_complete_count_;
2710 };
2711
2712 class LayerTreeHostTestAbortedCommitDoesntStallSynchronousCompositor
2713     : public LayerTreeHostTestAbortedCommitDoesntStall {
2714   virtual void InitializeSettings(LayerTreeSettings* settings) OVERRIDE {
2715     LayerTreeHostTestAbortedCommitDoesntStall::InitializeSettings(settings);
2716     settings->using_synchronous_renderer_compositor = true;
2717   }
2718 };
2719
2720 MULTI_THREAD_TEST_F(
2721     LayerTreeHostTestAbortedCommitDoesntStallSynchronousCompositor);
2722
2723 class LayerTreeHostTestAbortedCommitDoesntStallDisabledVsync
2724     : public LayerTreeHostTestAbortedCommitDoesntStall {
2725   virtual void InitializeSettings(LayerTreeSettings* settings) OVERRIDE {
2726     LayerTreeHostTestAbortedCommitDoesntStall::InitializeSettings(settings);
2727     settings->throttle_frame_production = false;
2728   }
2729 };
2730
2731 MULTI_THREAD_TEST_F(LayerTreeHostTestAbortedCommitDoesntStallDisabledVsync);
2732
2733 class LayerTreeHostTestUninvertibleTransformDoesNotBlockActivation
2734     : public LayerTreeHostTest {
2735  protected:
2736   virtual void InitializeSettings(LayerTreeSettings* settings) OVERRIDE {
2737     settings->impl_side_painting = true;
2738   }
2739
2740   virtual void SetupTree() OVERRIDE {
2741     LayerTreeHostTest::SetupTree();
2742
2743     scoped_refptr<Layer> layer = PictureLayer::Create(&client_);
2744     layer->SetTransform(gfx::Transform(0.0, 0.0, 0.0, 0.0, 0.0, 0.0));
2745     layer->SetBounds(gfx::Size(10, 10));
2746     layer_tree_host()->root_layer()->AddChild(layer);
2747   }
2748
2749   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
2750
2751   virtual void DidActivateTreeOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
2752     EndTest();
2753   }
2754
2755   virtual void AfterTest() OVERRIDE {}
2756
2757   FakeContentLayerClient client_;
2758 };
2759
2760 MULTI_THREAD_TEST_F(
2761     LayerTreeHostTestUninvertibleTransformDoesNotBlockActivation);
2762
2763 class LayerTreeHostTestChangeLayerPropertiesInPaintContents
2764     : public LayerTreeHostTest {
2765  public:
2766   class SetBoundsClient : public ContentLayerClient {
2767    public:
2768     SetBoundsClient() : layer_(0) {}
2769
2770     void set_layer(Layer* layer) { layer_ = layer; }
2771
2772     virtual void PaintContents(
2773         SkCanvas* canvas,
2774         const gfx::Rect& clip,
2775         gfx::RectF* opaque,
2776         ContentLayerClient::GraphicsContextStatus gc_status) OVERRIDE {
2777       layer_->SetBounds(gfx::Size(2, 2));
2778     }
2779
2780     virtual void DidChangeLayerCanUseLCDText() OVERRIDE {}
2781
2782     virtual bool FillsBoundsCompletely() const OVERRIDE { return false; }
2783
2784    private:
2785     Layer* layer_;
2786   };
2787
2788   LayerTreeHostTestChangeLayerPropertiesInPaintContents() : num_commits_(0) {}
2789
2790   virtual void SetupTree() OVERRIDE {
2791     scoped_refptr<ContentLayer> root_layer = ContentLayer::Create(&client_);
2792     root_layer->SetIsDrawable(true);
2793     root_layer->SetBounds(gfx::Size(1, 1));
2794
2795     layer_tree_host()->SetRootLayer(root_layer);
2796     client_.set_layer(root_layer.get());
2797
2798     LayerTreeHostTest::SetupTree();
2799   }
2800
2801   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
2802   virtual void AfterTest() OVERRIDE {}
2803
2804   virtual void CommitCompleteOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
2805     num_commits_++;
2806     if (num_commits_ == 1) {
2807       LayerImpl* root_layer = host_impl->active_tree()->root_layer();
2808       EXPECT_SIZE_EQ(gfx::Size(1, 1), root_layer->bounds());
2809     } else {
2810       LayerImpl* root_layer = host_impl->active_tree()->root_layer();
2811       EXPECT_SIZE_EQ(gfx::Size(2, 2), root_layer->bounds());
2812       EndTest();
2813     }
2814   }
2815
2816  private:
2817   SetBoundsClient client_;
2818   int num_commits_;
2819 };
2820
2821 SINGLE_THREAD_TEST_F(LayerTreeHostTestChangeLayerPropertiesInPaintContents);
2822
2823 class MockIOSurfaceWebGraphicsContext3D : public TestWebGraphicsContext3D {
2824  public:
2825   MockIOSurfaceWebGraphicsContext3D() {
2826     test_capabilities_.gpu.iosurface = true;
2827     test_capabilities_.gpu.texture_rectangle = true;
2828   }
2829
2830   virtual GLuint createTexture() OVERRIDE {
2831     return 1;
2832   }
2833   MOCK_METHOD1(activeTexture, void(GLenum texture));
2834   MOCK_METHOD2(bindTexture, void(GLenum target,
2835                                  GLuint texture_id));
2836   MOCK_METHOD3(texParameteri, void(GLenum target,
2837                                    GLenum pname,
2838                                    GLint param));
2839   MOCK_METHOD5(texImageIOSurface2DCHROMIUM, void(GLenum target,
2840                                                  GLint width,
2841                                                  GLint height,
2842                                                  GLuint ioSurfaceId,
2843                                                  GLuint plane));
2844   MOCK_METHOD4(drawElements, void(GLenum mode,
2845                                   GLsizei count,
2846                                   GLenum type,
2847                                   GLintptr offset));
2848   MOCK_METHOD1(deleteTexture, void(GLenum texture));
2849   MOCK_METHOD2(produceTextureCHROMIUM,
2850                void(GLenum target, const GLbyte* mailbox));
2851 };
2852
2853 class LayerTreeHostTestIOSurfaceDrawing : public LayerTreeHostTest {
2854  protected:
2855   virtual scoped_ptr<FakeOutputSurface> CreateFakeOutputSurface(bool fallback)
2856       OVERRIDE {
2857     scoped_ptr<MockIOSurfaceWebGraphicsContext3D> mock_context_owned(
2858         new MockIOSurfaceWebGraphicsContext3D);
2859     mock_context_ = mock_context_owned.get();
2860
2861     if (delegating_renderer()) {
2862       return FakeOutputSurface::CreateDelegating3d(
2863           mock_context_owned.PassAs<TestWebGraphicsContext3D>());
2864     } else {
2865       return FakeOutputSurface::Create3d(
2866           mock_context_owned.PassAs<TestWebGraphicsContext3D>());
2867     }
2868   }
2869
2870   virtual void SetupTree() OVERRIDE {
2871     LayerTreeHostTest::SetupTree();
2872
2873     layer_tree_host()->root_layer()->SetIsDrawable(false);
2874
2875     io_surface_id_ = 9;
2876     io_surface_size_ = gfx::Size(6, 7);
2877
2878     scoped_refptr<IOSurfaceLayer> io_surface_layer = IOSurfaceLayer::Create();
2879     io_surface_layer->SetBounds(gfx::Size(10, 10));
2880     io_surface_layer->SetAnchorPoint(gfx::PointF());
2881     io_surface_layer->SetIsDrawable(true);
2882     io_surface_layer->SetContentsOpaque(true);
2883     io_surface_layer->SetIOSurfaceProperties(io_surface_id_, io_surface_size_);
2884     layer_tree_host()->root_layer()->AddChild(io_surface_layer);
2885   }
2886
2887   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
2888
2889   virtual void DidActivateTreeOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
2890     EXPECT_EQ(0u, host_impl->resource_provider()->num_resources());
2891     // In WillDraw, the IOSurfaceLayer sets up the io surface texture.
2892
2893     EXPECT_CALL(*mock_context_, activeTexture(_)).Times(0);
2894     EXPECT_CALL(*mock_context_, bindTexture(GL_TEXTURE_RECTANGLE_ARB, 1))
2895         .Times(AtLeast(1));
2896     EXPECT_CALL(*mock_context_,
2897                 texParameteri(
2898                     GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR))
2899         .Times(1);
2900     EXPECT_CALL(*mock_context_,
2901                 texParameteri(
2902                     GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR))
2903         .Times(1);
2904     EXPECT_CALL(*mock_context_,
2905                 texParameteri(GL_TEXTURE_RECTANGLE_ARB,
2906                               GL_TEXTURE_POOL_CHROMIUM,
2907                               GL_TEXTURE_POOL_UNMANAGED_CHROMIUM)).Times(1);
2908     EXPECT_CALL(*mock_context_,
2909                 texParameteri(GL_TEXTURE_RECTANGLE_ARB,
2910                               GL_TEXTURE_WRAP_S,
2911                               GL_CLAMP_TO_EDGE)).Times(1);
2912     EXPECT_CALL(*mock_context_,
2913                 texParameteri(GL_TEXTURE_RECTANGLE_ARB,
2914                               GL_TEXTURE_WRAP_T,
2915                               GL_CLAMP_TO_EDGE)).Times(1);
2916
2917     EXPECT_CALL(*mock_context_,
2918                 texImageIOSurface2DCHROMIUM(GL_TEXTURE_RECTANGLE_ARB,
2919                                             io_surface_size_.width(),
2920                                             io_surface_size_.height(),
2921                                             io_surface_id_,
2922                                             0)).Times(1);
2923
2924     EXPECT_CALL(*mock_context_, bindTexture(_, 0)).Times(AnyNumber());
2925   }
2926
2927   virtual DrawSwapReadbackResult::DrawResult PrepareToDrawOnThread(
2928       LayerTreeHostImpl* host_impl,
2929       LayerTreeHostImpl::FrameData* frame,
2930       DrawSwapReadbackResult::DrawResult draw_result) OVERRIDE {
2931     Mock::VerifyAndClearExpectations(&mock_context_);
2932     ResourceProvider* resource_provider = host_impl->resource_provider();
2933     EXPECT_EQ(1u, resource_provider->num_resources());
2934     CHECK_EQ(1u, frame->render_passes.size());
2935     CHECK_LE(1u, frame->render_passes[0]->quad_list.size());
2936     const DrawQuad* quad = frame->render_passes[0]->quad_list[0];
2937     CHECK_EQ(DrawQuad::IO_SURFACE_CONTENT, quad->material);
2938     const IOSurfaceDrawQuad* io_surface_draw_quad =
2939         IOSurfaceDrawQuad::MaterialCast(quad);
2940     EXPECT_SIZE_EQ(io_surface_size_, io_surface_draw_quad->io_surface_size);
2941     EXPECT_NE(0u, io_surface_draw_quad->io_surface_resource_id);
2942     EXPECT_EQ(static_cast<GLenum>(GL_TEXTURE_RECTANGLE_ARB),
2943               resource_provider->TargetForTesting(
2944                   io_surface_draw_quad->io_surface_resource_id));
2945
2946     EXPECT_CALL(*mock_context_, bindTexture(GL_TEXTURE_RECTANGLE_ARB, 1))
2947         .Times(1);
2948     if (delegating_renderer()) {
2949       // The io surface layer's resource should be sent to the parent.
2950       EXPECT_CALL(*mock_context_,
2951                   produceTextureCHROMIUM(GL_TEXTURE_RECTANGLE_ARB, _)).Times(1);
2952     } else {
2953       // The io surface layer's texture is drawn.
2954       EXPECT_CALL(*mock_context_, activeTexture(GL_TEXTURE0)).Times(AtLeast(1));
2955       EXPECT_CALL(*mock_context_, drawElements(GL_TRIANGLES, 6, _, _))
2956           .Times(AtLeast(1));
2957     }
2958
2959     return draw_result;
2960   }
2961
2962   virtual void DrawLayersOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
2963     Mock::VerifyAndClearExpectations(&mock_context_);
2964
2965     EXPECT_CALL(*mock_context_, deleteTexture(1)).Times(AtLeast(1));
2966     EndTest();
2967   }
2968
2969   virtual void AfterTest() OVERRIDE {}
2970
2971   int io_surface_id_;
2972   MockIOSurfaceWebGraphicsContext3D* mock_context_;
2973   gfx::Size io_surface_size_;
2974 };
2975
2976 SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostTestIOSurfaceDrawing);
2977
2978 class LayerTreeHostTestNumFramesPending : public LayerTreeHostTest {
2979  public:
2980   virtual void BeginTest() OVERRIDE {
2981     frame_ = 0;
2982     PostSetNeedsCommitToMainThread();
2983   }
2984
2985   // Round 1: commit + draw
2986   // Round 2: commit only (no draw/swap)
2987   // Round 3: draw only (no commit)
2988   // Round 4: composite & readback (2 commits, no draw/swap)
2989   // Round 5: commit + draw
2990
2991   virtual void DidCommit() OVERRIDE {
2992     int commit = layer_tree_host()->source_frame_number();
2993     switch (commit) {
2994       case 2:
2995         // Round 2 done.
2996         EXPECT_EQ(1, frame_);
2997         layer_tree_host()->SetNeedsRedraw();
2998         break;
2999       case 3:
3000         // CompositeAndReadback in Round 4, first commit.
3001         EXPECT_EQ(2, frame_);
3002         break;
3003       case 4:
3004         // Round 4 done.
3005         EXPECT_EQ(2, frame_);
3006         layer_tree_host()->SetNeedsCommit();
3007         layer_tree_host()->SetNeedsRedraw();
3008         break;
3009     }
3010   }
3011
3012   virtual void DidCompleteSwapBuffers() OVERRIDE {
3013     int commit = layer_tree_host()->source_frame_number();
3014     ++frame_;
3015     char pixels[4] = {0};
3016     switch (frame_) {
3017       case 1:
3018         // Round 1 done.
3019         EXPECT_EQ(1, commit);
3020         layer_tree_host()->SetNeedsCommit();
3021         break;
3022       case 2:
3023         // Round 3 done.
3024         EXPECT_EQ(2, commit);
3025         layer_tree_host()->CompositeAndReadback(pixels, gfx::Rect(0, 0, 1, 1));
3026         break;
3027       case 3:
3028         // Round 5 done.
3029         EXPECT_EQ(5, commit);
3030         EndTest();
3031         break;
3032     }
3033   }
3034
3035   virtual void AfterTest() OVERRIDE {}
3036
3037  protected:
3038   int frame_;
3039 };
3040
3041 // Flaky on all platforms: http://crbug.com/327498
3042 TEST_F(LayerTreeHostTestNumFramesPending, DISABLED_DelegatingRenderer) {
3043   RunTest(true, true, true);
3044 }
3045
3046 TEST_F(LayerTreeHostTestNumFramesPending, DISABLED_GLRenderer) {
3047   RunTest(true, false, true);
3048 }
3049
3050 class LayerTreeHostTestDeferredInitialize : public LayerTreeHostTest {
3051  public:
3052   virtual void InitializeSettings(LayerTreeSettings* settings) OVERRIDE {
3053     // PictureLayer can only be used with impl side painting enabled.
3054     settings->impl_side_painting = true;
3055   }
3056
3057   virtual void SetupTree() OVERRIDE {
3058     layer_ = FakePictureLayer::Create(&client_);
3059     // Force commits to not be aborted so new frames get drawn, otherwise
3060     // the renderer gets deferred initialized but nothing new needs drawing.
3061     layer_->set_always_update_resources(true);
3062     layer_tree_host()->SetRootLayer(layer_);
3063     LayerTreeHostTest::SetupTree();
3064   }
3065
3066   virtual void BeginTest() OVERRIDE {
3067     did_initialize_gl_ = false;
3068     did_release_gl_ = false;
3069     last_source_frame_number_drawn_ = -1;  // Never drawn.
3070     PostSetNeedsCommitToMainThread();
3071   }
3072
3073   virtual scoped_ptr<FakeOutputSurface> CreateFakeOutputSurface(bool fallback)
3074       OVERRIDE {
3075     scoped_ptr<TestWebGraphicsContext3D> context3d(
3076         TestWebGraphicsContext3D::Create());
3077
3078     return FakeOutputSurface::CreateDeferredGL(
3079         scoped_ptr<SoftwareOutputDevice>(new SoftwareOutputDevice));
3080   }
3081
3082   virtual void DrawLayersOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
3083     ASSERT_TRUE(host_impl->RootLayer());
3084     FakePictureLayerImpl* layer_impl =
3085         static_cast<FakePictureLayerImpl*>(host_impl->RootLayer());
3086
3087     // The same frame can be draw multiple times if new visible tiles are
3088     // rasterized. But we want to make sure we only post DeferredInitialize
3089     // and ReleaseGL once, so early out if the same frame is drawn again.
3090     if (last_source_frame_number_drawn_ ==
3091         host_impl->active_tree()->source_frame_number())
3092       return;
3093
3094     last_source_frame_number_drawn_ =
3095         host_impl->active_tree()->source_frame_number();
3096
3097     if (!did_initialize_gl_) {
3098       EXPECT_LE(1u, layer_impl->append_quads_count());
3099       ImplThreadTaskRunner()->PostTask(
3100           FROM_HERE,
3101           base::Bind(
3102               &LayerTreeHostTestDeferredInitialize::DeferredInitializeAndRedraw,
3103               base::Unretained(this),
3104               base::Unretained(host_impl)));
3105     } else if (did_initialize_gl_ && !did_release_gl_) {
3106       EXPECT_LE(2u, layer_impl->append_quads_count());
3107       ImplThreadTaskRunner()->PostTask(
3108           FROM_HERE,
3109           base::Bind(&LayerTreeHostTestDeferredInitialize::ReleaseGLAndRedraw,
3110                      base::Unretained(this),
3111                      base::Unretained(host_impl)));
3112     } else if (did_initialize_gl_ && did_release_gl_) {
3113       EXPECT_LE(3u, layer_impl->append_quads_count());
3114       EndTest();
3115     }
3116   }
3117
3118   void DeferredInitializeAndRedraw(LayerTreeHostImpl* host_impl) {
3119     EXPECT_FALSE(did_initialize_gl_);
3120     // SetAndInitializeContext3D calls SetNeedsCommit.
3121     FakeOutputSurface* fake_output_surface =
3122         static_cast<FakeOutputSurface*>(host_impl->output_surface());
3123     scoped_refptr<TestContextProvider> context_provider =
3124         TestContextProvider::Create();  // Not bound to thread.
3125     EXPECT_TRUE(
3126         fake_output_surface->InitializeAndSetContext3d(context_provider));
3127     did_initialize_gl_ = true;
3128   }
3129
3130   void ReleaseGLAndRedraw(LayerTreeHostImpl* host_impl) {
3131     EXPECT_TRUE(did_initialize_gl_);
3132     EXPECT_FALSE(did_release_gl_);
3133     // ReleaseGL calls SetNeedsCommit.
3134     static_cast<FakeOutputSurface*>(host_impl->output_surface())->ReleaseGL();
3135     did_release_gl_ = true;
3136   }
3137
3138   virtual void AfterTest() OVERRIDE {
3139     EXPECT_TRUE(did_initialize_gl_);
3140     EXPECT_TRUE(did_release_gl_);
3141   }
3142
3143  private:
3144   FakeContentLayerClient client_;
3145   scoped_refptr<FakePictureLayer> layer_;
3146   bool did_initialize_gl_;
3147   bool did_release_gl_;
3148   int last_source_frame_number_drawn_;
3149 };
3150
3151 MULTI_THREAD_DIRECT_RENDERER_TEST_F(LayerTreeHostTestDeferredInitialize);
3152
3153 // Test for UI Resource management.
3154 class LayerTreeHostTestUIResource : public LayerTreeHostTest {
3155  public:
3156   LayerTreeHostTestUIResource() : num_ui_resources_(0) {}
3157
3158   virtual void InitializeSettings(LayerTreeSettings* settings) OVERRIDE {
3159     settings->texture_id_allocation_chunk_size = 1;
3160   }
3161
3162   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
3163
3164   virtual void DidCommit() OVERRIDE {
3165     int frame = layer_tree_host()->source_frame_number();
3166     switch (frame) {
3167       case 1:
3168         CreateResource();
3169         CreateResource();
3170         PostSetNeedsCommitToMainThread();
3171         break;
3172       case 2:
3173         // Usually ScopedUIResource are deleted from the manager in their
3174         // destructor.  Here we just want to test that a direct call to
3175         // DeleteUIResource works.
3176         layer_tree_host()->DeleteUIResource(ui_resources_[0]->id());
3177         PostSetNeedsCommitToMainThread();
3178         break;
3179       case 3:
3180         // DeleteUIResource can be called with an invalid id.
3181         layer_tree_host()->DeleteUIResource(ui_resources_[0]->id());
3182         PostSetNeedsCommitToMainThread();
3183         break;
3184       case 4:
3185         CreateResource();
3186         CreateResource();
3187         PostSetNeedsCommitToMainThread();
3188         break;
3189       case 5:
3190         ClearResources();
3191         EndTest();
3192         break;
3193     }
3194   }
3195
3196   void PerformTest(LayerTreeHostImpl* impl) {
3197     TestWebGraphicsContext3D* context = TestContext();
3198
3199     int frame = impl->active_tree()->source_frame_number();
3200     switch (frame) {
3201       case 0:
3202         ASSERT_EQ(0u, context->NumTextures());
3203         break;
3204       case 1:
3205         // Created two textures.
3206         ASSERT_EQ(2u, context->NumTextures());
3207         break;
3208       case 2:
3209         // One texture left after one deletion.
3210         ASSERT_EQ(1u, context->NumTextures());
3211         break;
3212       case 3:
3213         // Resource manager state should not change when delete is called on an
3214         // invalid id.
3215         ASSERT_EQ(1u, context->NumTextures());
3216         break;
3217       case 4:
3218         // Creation after deletion: two more creates should total up to
3219         // three textures.
3220         ASSERT_EQ(3u, context->NumTextures());
3221         break;
3222     }
3223   }
3224
3225   virtual void CommitCompleteOnThread(LayerTreeHostImpl* impl) OVERRIDE {
3226     if (!layer_tree_host()->settings().impl_side_painting)
3227       PerformTest(impl);
3228   }
3229
3230   virtual void DidActivateTreeOnThread(LayerTreeHostImpl* impl) OVERRIDE {
3231     if (layer_tree_host()->settings().impl_side_painting)
3232       PerformTest(impl);
3233   }
3234
3235   virtual void AfterTest() OVERRIDE {}
3236
3237  private:
3238   // Must clear all resources before exiting.
3239   void ClearResources() {
3240     for (int i = 0; i < num_ui_resources_; i++)
3241       ui_resources_[i].reset();
3242   }
3243
3244   void CreateResource() {
3245     ui_resources_[num_ui_resources_++] =
3246         FakeScopedUIResource::Create(layer_tree_host());
3247   }
3248
3249   scoped_ptr<FakeScopedUIResource> ui_resources_[5];
3250   int num_ui_resources_;
3251 };
3252
3253 MULTI_THREAD_TEST_F(LayerTreeHostTestUIResource);
3254
3255 class PushPropertiesCountingLayerImpl : public LayerImpl {
3256  public:
3257   static scoped_ptr<PushPropertiesCountingLayerImpl> Create(
3258       LayerTreeImpl* tree_impl, int id) {
3259     return make_scoped_ptr(new PushPropertiesCountingLayerImpl(tree_impl, id));
3260   }
3261
3262   virtual ~PushPropertiesCountingLayerImpl() {}
3263
3264   virtual void PushPropertiesTo(LayerImpl* layer) OVERRIDE {
3265     LayerImpl::PushPropertiesTo(layer);
3266     push_properties_count_++;
3267     // Push state to the active tree because we can only access it from there.
3268     static_cast<PushPropertiesCountingLayerImpl*>(
3269         layer)->push_properties_count_ = push_properties_count_;
3270   }
3271
3272   virtual scoped_ptr<LayerImpl> CreateLayerImpl(LayerTreeImpl* tree_impl)
3273       OVERRIDE {
3274     return PushPropertiesCountingLayerImpl::Create(tree_impl, id()).
3275         PassAs<LayerImpl>();
3276   }
3277
3278   size_t push_properties_count() const { return push_properties_count_; }
3279   void reset_push_properties_count() { push_properties_count_ = 0; }
3280
3281  private:
3282   size_t push_properties_count_;
3283
3284   PushPropertiesCountingLayerImpl(LayerTreeImpl* tree_impl, int id)
3285       : LayerImpl(tree_impl, id),
3286         push_properties_count_(0) {
3287     SetAnchorPoint(gfx::PointF());
3288     SetBounds(gfx::Size(1, 1));
3289   }
3290 };
3291
3292 class PushPropertiesCountingLayer : public Layer {
3293  public:
3294   static scoped_refptr<PushPropertiesCountingLayer> Create() {
3295     return new PushPropertiesCountingLayer();
3296   }
3297
3298   virtual void PushPropertiesTo(LayerImpl* layer) OVERRIDE {
3299     Layer::PushPropertiesTo(layer);
3300     push_properties_count_++;
3301     if (persist_needs_push_properties_)
3302       needs_push_properties_ = true;
3303   }
3304
3305   virtual scoped_ptr<LayerImpl> CreateLayerImpl(LayerTreeImpl* tree_impl)
3306       OVERRIDE {
3307     return PushPropertiesCountingLayerImpl::Create(tree_impl, id()).
3308         PassAs<LayerImpl>();
3309   }
3310
3311   size_t push_properties_count() const { return push_properties_count_; }
3312   void reset_push_properties_count() { push_properties_count_ = 0; }
3313
3314   void set_persist_needs_push_properties(bool persist) {
3315     persist_needs_push_properties_ = persist;
3316   }
3317
3318  private:
3319   PushPropertiesCountingLayer()
3320       : push_properties_count_(0), persist_needs_push_properties_(false) {
3321     SetAnchorPoint(gfx::PointF());
3322     SetBounds(gfx::Size(1, 1));
3323     SetIsDrawable(true);
3324   }
3325   virtual ~PushPropertiesCountingLayer() {}
3326
3327   size_t push_properties_count_;
3328   bool persist_needs_push_properties_;
3329 };
3330
3331 class LayerTreeHostTestLayersPushProperties : public LayerTreeHostTest {
3332  protected:
3333   virtual void BeginTest() OVERRIDE {
3334     num_commits_ = 0;
3335     expected_push_properties_root_ = 0;
3336     expected_push_properties_child_ = 0;
3337     expected_push_properties_grandchild_ = 0;
3338     expected_push_properties_child2_ = 0;
3339     expected_push_properties_other_root_ = 0;
3340     expected_push_properties_leaf_layer_ = 0;
3341     PostSetNeedsCommitToMainThread();
3342   }
3343
3344   virtual void SetupTree() OVERRIDE {
3345     root_ = PushPropertiesCountingLayer::Create();
3346     child_ = PushPropertiesCountingLayer::Create();
3347     child2_ = PushPropertiesCountingLayer::Create();
3348     grandchild_ = PushPropertiesCountingLayer::Create();
3349     leaf_always_pushing_layer_ = PushPropertiesCountingLayer::Create();
3350     leaf_always_pushing_layer_->set_persist_needs_push_properties(true);
3351
3352     root_->AddChild(child_);
3353     root_->AddChild(child2_);
3354     child_->AddChild(grandchild_);
3355     child2_->AddChild(leaf_always_pushing_layer_);
3356
3357     other_root_ = PushPropertiesCountingLayer::Create();
3358
3359     // Don't set the root layer here.
3360     LayerTreeHostTest::SetupTree();
3361   }
3362
3363   virtual void DidCommitAndDrawFrame() OVERRIDE {
3364     ++num_commits_;
3365
3366     EXPECT_EQ(expected_push_properties_root_, root_->push_properties_count());
3367     EXPECT_EQ(expected_push_properties_child_, child_->push_properties_count());
3368     EXPECT_EQ(expected_push_properties_grandchild_,
3369               grandchild_->push_properties_count());
3370     EXPECT_EQ(expected_push_properties_child2_,
3371               child2_->push_properties_count());
3372     EXPECT_EQ(expected_push_properties_other_root_,
3373               other_root_->push_properties_count());
3374     EXPECT_EQ(expected_push_properties_leaf_layer_,
3375               leaf_always_pushing_layer_->push_properties_count());
3376
3377     // The scrollbar layer always needs to be pushed.
3378     if (root_->layer_tree_host()) {
3379       EXPECT_TRUE(root_->descendant_needs_push_properties());
3380       EXPECT_FALSE(root_->needs_push_properties());
3381     }
3382     if (child2_->layer_tree_host()) {
3383       EXPECT_TRUE(child2_->descendant_needs_push_properties());
3384       EXPECT_FALSE(child2_->needs_push_properties());
3385     }
3386     if (leaf_always_pushing_layer_->layer_tree_host()) {
3387       EXPECT_FALSE(
3388           leaf_always_pushing_layer_->descendant_needs_push_properties());
3389       EXPECT_TRUE(leaf_always_pushing_layer_->needs_push_properties());
3390     }
3391
3392     // child_ and grandchild_ don't persist their need to push properties.
3393     if (child_->layer_tree_host()) {
3394       EXPECT_FALSE(child_->descendant_needs_push_properties());
3395       EXPECT_FALSE(child_->needs_push_properties());
3396     }
3397     if (grandchild_->layer_tree_host()) {
3398       EXPECT_FALSE(grandchild_->descendant_needs_push_properties());
3399       EXPECT_FALSE(grandchild_->needs_push_properties());
3400     }
3401
3402     if (other_root_->layer_tree_host()) {
3403       EXPECT_FALSE(other_root_->descendant_needs_push_properties());
3404       EXPECT_FALSE(other_root_->needs_push_properties());
3405     }
3406
3407     switch (num_commits_) {
3408       case 1:
3409         layer_tree_host()->SetRootLayer(root_);
3410         // Layers added to the tree get committed.
3411         ++expected_push_properties_root_;
3412         ++expected_push_properties_child_;
3413         ++expected_push_properties_grandchild_;
3414         ++expected_push_properties_child2_;
3415         break;
3416       case 2:
3417         layer_tree_host()->SetNeedsCommit();
3418         // No layers need commit.
3419         break;
3420       case 3:
3421         layer_tree_host()->SetRootLayer(other_root_);
3422         // Layers added to the tree get committed.
3423         ++expected_push_properties_other_root_;
3424         break;
3425       case 4:
3426         layer_tree_host()->SetRootLayer(root_);
3427         // Layers added to the tree get committed.
3428         ++expected_push_properties_root_;
3429         ++expected_push_properties_child_;
3430         ++expected_push_properties_grandchild_;
3431         ++expected_push_properties_child2_;
3432         break;
3433       case 5:
3434         layer_tree_host()->SetNeedsCommit();
3435         // No layers need commit.
3436         break;
3437       case 6:
3438         child_->RemoveFromParent();
3439         // No layers need commit.
3440         break;
3441       case 7:
3442         root_->AddChild(child_);
3443         // Layers added to the tree get committed.
3444         ++expected_push_properties_child_;
3445         ++expected_push_properties_grandchild_;
3446         break;
3447       case 8:
3448         grandchild_->RemoveFromParent();
3449         // No layers need commit.
3450         break;
3451       case 9:
3452         child_->AddChild(grandchild_);
3453         // Layers added to the tree get committed.
3454         ++expected_push_properties_grandchild_;
3455         break;
3456       case 10:
3457         layer_tree_host()->SetViewportSize(gfx::Size(20, 20));
3458         // No layers need commit.
3459         break;
3460       case 11:
3461         layer_tree_host()->SetPageScaleFactorAndLimits(1.f, 0.8f, 1.1f);
3462         // No layers need commit.
3463         break;
3464       case 12:
3465         child_->SetPosition(gfx::Point(1, 1));
3466         // The modified layer needs commit
3467         ++expected_push_properties_child_;
3468         break;
3469       case 13:
3470         child2_->SetPosition(gfx::Point(1, 1));
3471         // The modified layer needs commit
3472         ++expected_push_properties_child2_;
3473         break;
3474       case 14:
3475         child_->RemoveFromParent();
3476         root_->AddChild(child_);
3477         // Layers added to the tree get committed.
3478         ++expected_push_properties_child_;
3479         ++expected_push_properties_grandchild_;
3480         break;
3481       case 15:
3482         grandchild_->SetPosition(gfx::Point(1, 1));
3483         // The modified layer needs commit
3484         ++expected_push_properties_grandchild_;
3485         break;
3486       case 16:
3487         // SetNeedsDisplay does not always set needs commit (so call it
3488         // explicitly), but is a property change.
3489         child_->SetNeedsDisplay();
3490         ++expected_push_properties_child_;
3491         layer_tree_host()->SetNeedsCommit();
3492         break;
3493       case 17:
3494         EndTest();
3495         break;
3496     }
3497
3498     // The leaf layer always pushes.
3499     if (leaf_always_pushing_layer_->layer_tree_host())
3500       ++expected_push_properties_leaf_layer_;
3501   }
3502
3503   virtual void AfterTest() OVERRIDE {}
3504
3505   int num_commits_;
3506   FakeContentLayerClient client_;
3507   scoped_refptr<PushPropertiesCountingLayer> root_;
3508   scoped_refptr<PushPropertiesCountingLayer> child_;
3509   scoped_refptr<PushPropertiesCountingLayer> child2_;
3510   scoped_refptr<PushPropertiesCountingLayer> grandchild_;
3511   scoped_refptr<PushPropertiesCountingLayer> other_root_;
3512   scoped_refptr<PushPropertiesCountingLayer> leaf_always_pushing_layer_;
3513   size_t expected_push_properties_root_;
3514   size_t expected_push_properties_child_;
3515   size_t expected_push_properties_child2_;
3516   size_t expected_push_properties_grandchild_;
3517   size_t expected_push_properties_other_root_;
3518   size_t expected_push_properties_leaf_layer_;
3519 };
3520
3521 MULTI_THREAD_TEST_F(LayerTreeHostTestLayersPushProperties);
3522
3523 class LayerTreeHostTestImplLayersPushProperties
3524     : public LayerTreeHostTestLayersPushProperties {
3525  protected:
3526   virtual void BeginTest() OVERRIDE {
3527     expected_push_properties_root_impl_ = 0;
3528     expected_push_properties_child_impl_ = 0;
3529     expected_push_properties_grandchild_impl_ = 0;
3530     expected_push_properties_child2_impl_ = 0;
3531     expected_push_properties_grandchild2_impl_ = 0;
3532     LayerTreeHostTestLayersPushProperties::BeginTest();
3533   }
3534
3535   virtual void DidActivateTreeOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
3536     // These commits are in response to the changes made in
3537     // LayerTreeHostTestLayersPushProperties::DidCommitAndDrawFrame()
3538     switch (num_commits_) {
3539       case 0:
3540         // Tree hasn't been setup yet don't bother to check anything.
3541         return;
3542       case 1:
3543         // Root gets set up, Everyone is initialized.
3544         ++expected_push_properties_root_impl_;
3545         ++expected_push_properties_child_impl_;
3546         ++expected_push_properties_grandchild_impl_;
3547         ++expected_push_properties_child2_impl_;
3548         ++expected_push_properties_grandchild2_impl_;
3549         break;
3550       case 2:
3551         // Tree doesn't change but the one leaf that always pushes is pushed.
3552         ++expected_push_properties_grandchild2_impl_;
3553         break;
3554       case 3:
3555         // Root is swapped here.
3556         // Clear the expected push properties the tree will be rebuilt.
3557         expected_push_properties_root_impl_ = 0;
3558         expected_push_properties_child_impl_ = 0;
3559         expected_push_properties_grandchild_impl_ = 0;
3560         expected_push_properties_child2_impl_ = 0;
3561         expected_push_properties_grandchild2_impl_ = 0;
3562
3563         // Make sure the new root is pushed.
3564         EXPECT_EQ(1u, static_cast<PushPropertiesCountingLayerImpl*>(
3565                 host_impl->RootLayer())->push_properties_count());
3566         return;
3567       case 4:
3568         // Root is swapped back all of the layers in the tree get pushed.
3569         ++expected_push_properties_root_impl_;
3570         ++expected_push_properties_child_impl_;
3571         ++expected_push_properties_grandchild_impl_;
3572         ++expected_push_properties_child2_impl_;
3573         ++expected_push_properties_grandchild2_impl_;
3574         break;
3575       case 5:
3576         // Tree doesn't change but the one leaf that always pushes is pushed.
3577         ++expected_push_properties_grandchild2_impl_;
3578         break;
3579       case 6:
3580         // First child is removed. Structure of the tree changes here so swap
3581         // some of the values. child_impl becomes child2_impl.
3582         expected_push_properties_child_impl_ =
3583             expected_push_properties_child2_impl_;
3584         expected_push_properties_child2_impl_ = 0;
3585         // grandchild_impl becomes grandchild2_impl.
3586         expected_push_properties_grandchild_impl_ =
3587             expected_push_properties_grandchild2_impl_;
3588         expected_push_properties_grandchild2_impl_ = 0;
3589
3590         // grandchild_impl is now the leaf that always pushes. It is pushed.
3591         ++expected_push_properties_grandchild_impl_;
3592         break;
3593       case 7:
3594         // The leaf that always pushes is pushed.
3595         ++expected_push_properties_grandchild_impl_;
3596
3597         // Child is added back. New layers are initialized.
3598         ++expected_push_properties_grandchild2_impl_;
3599         ++expected_push_properties_child2_impl_;
3600         break;
3601       case 8:
3602         // Leaf is removed.
3603         expected_push_properties_grandchild2_impl_ = 0;
3604
3605         // Always pushing.
3606         ++expected_push_properties_grandchild_impl_;
3607         break;
3608       case 9:
3609         // Leaf is added back
3610         ++expected_push_properties_grandchild2_impl_;
3611
3612         // The leaf that always pushes is pushed.
3613         ++expected_push_properties_grandchild_impl_;
3614         break;
3615       case 10:
3616         // The leaf that always pushes is pushed.
3617         ++expected_push_properties_grandchild_impl_;
3618         break;
3619       case 11:
3620         // The leaf that always pushes is pushed.
3621         ++expected_push_properties_grandchild_impl_;
3622         break;
3623       case 12:
3624         // The leaf that always pushes is pushed.
3625         ++expected_push_properties_grandchild_impl_;
3626
3627         // This child position was changed.
3628         ++expected_push_properties_child2_impl_;
3629         break;
3630       case 13:
3631         // The position of this child was changed.
3632         ++expected_push_properties_child_impl_;
3633
3634         // The leaf that always pushes is pushed.
3635         ++expected_push_properties_grandchild_impl_;
3636         break;
3637       case 14:
3638         // Second child is removed from tree. Don't discard counts because
3639         // they are added back before commit.
3640
3641         // The leaf that always pushes is pushed.
3642         ++expected_push_properties_grandchild_impl_;
3643
3644         // Second child added back.
3645         ++expected_push_properties_child2_impl_;
3646         ++expected_push_properties_grandchild2_impl_;
3647
3648         break;
3649       case 15:
3650         // The position of this child was changed.
3651         ++expected_push_properties_grandchild2_impl_;
3652
3653         // The leaf that always pushes is pushed.
3654         ++expected_push_properties_grandchild_impl_;
3655         break;
3656       case 16:
3657         // Second child is invalidated with SetNeedsDisplay
3658         ++expected_push_properties_child2_impl_;
3659
3660         // The leaf that always pushed is pushed.
3661         ++expected_push_properties_grandchild_impl_;
3662         break;
3663     }
3664
3665     PushPropertiesCountingLayerImpl* root_impl_ = NULL;
3666     PushPropertiesCountingLayerImpl* child_impl_ = NULL;
3667     PushPropertiesCountingLayerImpl* child2_impl_ = NULL;
3668     PushPropertiesCountingLayerImpl* grandchild_impl_ = NULL;
3669     PushPropertiesCountingLayerImpl* leaf_always_pushing_layer_impl_ = NULL;
3670
3671     // Pull the layers that we need from the tree assuming the same structure
3672     // as LayerTreeHostTestLayersPushProperties
3673     root_impl_ = static_cast<PushPropertiesCountingLayerImpl*>(
3674         host_impl->RootLayer());
3675
3676     if (root_impl_ && root_impl_->children().size() > 0) {
3677       child_impl_ = static_cast<PushPropertiesCountingLayerImpl*>(
3678           root_impl_->children()[0]);
3679
3680       if (child_impl_ && child_impl_->children().size() > 0)
3681         grandchild_impl_ = static_cast<PushPropertiesCountingLayerImpl*>(
3682             child_impl_->children()[0]);
3683     }
3684
3685     if (root_impl_ && root_impl_->children().size() > 1) {
3686       child2_impl_ = static_cast<PushPropertiesCountingLayerImpl*>(
3687           root_impl_->children()[1]);
3688
3689       if (child2_impl_ && child2_impl_->children().size() > 0)
3690         leaf_always_pushing_layer_impl_ =
3691             static_cast<PushPropertiesCountingLayerImpl*>(
3692                 child2_impl_->children()[0]);
3693     }
3694
3695     if (root_impl_)
3696       EXPECT_EQ(expected_push_properties_root_impl_,
3697                 root_impl_->push_properties_count());
3698     if (child_impl_)
3699       EXPECT_EQ(expected_push_properties_child_impl_,
3700                 child_impl_->push_properties_count());
3701     if (grandchild_impl_)
3702       EXPECT_EQ(expected_push_properties_grandchild_impl_,
3703                 grandchild_impl_->push_properties_count());
3704     if (child2_impl_)
3705       EXPECT_EQ(expected_push_properties_child2_impl_,
3706                 child2_impl_->push_properties_count());
3707     if (leaf_always_pushing_layer_impl_)
3708       EXPECT_EQ(expected_push_properties_grandchild2_impl_,
3709                 leaf_always_pushing_layer_impl_->push_properties_count());
3710   }
3711
3712   size_t expected_push_properties_root_impl_;
3713   size_t expected_push_properties_child_impl_;
3714   size_t expected_push_properties_child2_impl_;
3715   size_t expected_push_properties_grandchild_impl_;
3716   size_t expected_push_properties_grandchild2_impl_;
3717 };
3718
3719 TEST_F(LayerTreeHostTestImplLayersPushProperties, DelegatingRenderer) {
3720   RunTestWithImplSidePainting();
3721 }
3722
3723 class LayerTreeHostTestPropertyChangesDuringUpdateArePushed
3724     : public LayerTreeHostTest {
3725  protected:
3726   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
3727
3728   virtual void SetupTree() OVERRIDE {
3729     root_ = Layer::Create();
3730     root_->SetBounds(gfx::Size(1, 1));
3731
3732     bool paint_scrollbar = true;
3733     bool has_thumb = false;
3734     scrollbar_layer_ = FakePaintedScrollbarLayer::Create(
3735         paint_scrollbar, has_thumb, root_->id());
3736
3737     root_->AddChild(scrollbar_layer_);
3738
3739     layer_tree_host()->SetRootLayer(root_);
3740     LayerTreeHostTest::SetupTree();
3741   }
3742
3743   virtual void DidCommitAndDrawFrame() OVERRIDE {
3744     switch (layer_tree_host()->source_frame_number()) {
3745       case 0:
3746         break;
3747       case 1: {
3748         // During update, the ignore_set_needs_commit_ bit is set to true to
3749         // avoid causing a second commit to be scheduled. If a property change
3750         // is made during this, however, it needs to be pushed in the upcoming
3751         // commit.
3752         scoped_ptr<base::AutoReset<bool> > ignore =
3753             scrollbar_layer_->IgnoreSetNeedsCommit();
3754
3755         scrollbar_layer_->SetBounds(gfx::Size(30, 30));
3756
3757         EXPECT_TRUE(scrollbar_layer_->needs_push_properties());
3758         EXPECT_TRUE(root_->descendant_needs_push_properties());
3759         layer_tree_host()->SetNeedsCommit();
3760
3761         scrollbar_layer_->reset_push_properties_count();
3762         EXPECT_EQ(0u, scrollbar_layer_->push_properties_count());
3763         break;
3764       }
3765       case 2:
3766         EXPECT_EQ(1u, scrollbar_layer_->push_properties_count());
3767         EndTest();
3768         break;
3769     }
3770   }
3771
3772   virtual void AfterTest() OVERRIDE {}
3773
3774   scoped_refptr<Layer> root_;
3775   scoped_refptr<FakePaintedScrollbarLayer> scrollbar_layer_;
3776 };
3777
3778 MULTI_THREAD_TEST_F(LayerTreeHostTestPropertyChangesDuringUpdateArePushed);
3779
3780 class LayerTreeHostTestCasePushPropertiesThreeGrandChildren
3781     : public LayerTreeHostTest {
3782  protected:
3783   virtual void BeginTest() OVERRIDE {
3784     expected_push_properties_root_ = 0;
3785     expected_push_properties_child_ = 0;
3786     expected_push_properties_grandchild1_ = 0;
3787     expected_push_properties_grandchild2_ = 0;
3788     expected_push_properties_grandchild3_ = 0;
3789     PostSetNeedsCommitToMainThread();
3790   }
3791
3792   virtual void SetupTree() OVERRIDE {
3793     root_ = PushPropertiesCountingLayer::Create();
3794     child_ = PushPropertiesCountingLayer::Create();
3795     grandchild1_ = PushPropertiesCountingLayer::Create();
3796     grandchild2_ = PushPropertiesCountingLayer::Create();
3797     grandchild3_ = PushPropertiesCountingLayer::Create();
3798
3799     root_->AddChild(child_);
3800     child_->AddChild(grandchild1_);
3801     child_->AddChild(grandchild2_);
3802     child_->AddChild(grandchild3_);
3803
3804     // Don't set the root layer here.
3805     LayerTreeHostTest::SetupTree();
3806   }
3807
3808   virtual void AfterTest() OVERRIDE {}
3809
3810   FakeContentLayerClient client_;
3811   scoped_refptr<PushPropertiesCountingLayer> root_;
3812   scoped_refptr<PushPropertiesCountingLayer> child_;
3813   scoped_refptr<PushPropertiesCountingLayer> grandchild1_;
3814   scoped_refptr<PushPropertiesCountingLayer> grandchild2_;
3815   scoped_refptr<PushPropertiesCountingLayer> grandchild3_;
3816   size_t expected_push_properties_root_;
3817   size_t expected_push_properties_child_;
3818   size_t expected_push_properties_grandchild1_;
3819   size_t expected_push_properties_grandchild2_;
3820   size_t expected_push_properties_grandchild3_;
3821 };
3822
3823 class LayerTreeHostTestPushPropertiesAddingToTreeRequiresPush
3824     : public LayerTreeHostTestCasePushPropertiesThreeGrandChildren {
3825  protected:
3826   virtual void DidCommitAndDrawFrame() OVERRIDE {
3827     int last_source_frame_number = layer_tree_host()->source_frame_number() - 1;
3828     switch (last_source_frame_number) {
3829       case 0:
3830         EXPECT_FALSE(root_->needs_push_properties());
3831         EXPECT_FALSE(root_->descendant_needs_push_properties());
3832         EXPECT_FALSE(child_->needs_push_properties());
3833         EXPECT_FALSE(child_->descendant_needs_push_properties());
3834         EXPECT_FALSE(grandchild1_->needs_push_properties());
3835         EXPECT_FALSE(grandchild1_->descendant_needs_push_properties());
3836         EXPECT_FALSE(grandchild2_->needs_push_properties());
3837         EXPECT_FALSE(grandchild2_->descendant_needs_push_properties());
3838         EXPECT_FALSE(grandchild3_->needs_push_properties());
3839         EXPECT_FALSE(grandchild3_->descendant_needs_push_properties());
3840
3841         layer_tree_host()->SetRootLayer(root_);
3842
3843         EXPECT_TRUE(root_->needs_push_properties());
3844         EXPECT_TRUE(root_->descendant_needs_push_properties());
3845         EXPECT_TRUE(child_->needs_push_properties());
3846         EXPECT_TRUE(child_->descendant_needs_push_properties());
3847         EXPECT_TRUE(grandchild1_->needs_push_properties());
3848         EXPECT_FALSE(grandchild1_->descendant_needs_push_properties());
3849         EXPECT_TRUE(grandchild2_->needs_push_properties());
3850         EXPECT_FALSE(grandchild2_->descendant_needs_push_properties());
3851         EXPECT_TRUE(grandchild3_->needs_push_properties());
3852         EXPECT_FALSE(grandchild3_->descendant_needs_push_properties());
3853         break;
3854       case 1:
3855         EndTest();
3856         break;
3857     }
3858   }
3859 };
3860
3861 MULTI_THREAD_TEST_F(LayerTreeHostTestPushPropertiesAddingToTreeRequiresPush);
3862
3863 class LayerTreeHostTestPushPropertiesRemovingChildStopsRecursion
3864     : public LayerTreeHostTestCasePushPropertiesThreeGrandChildren {
3865  protected:
3866   virtual void DidCommitAndDrawFrame() OVERRIDE {
3867     int last_source_frame_number = layer_tree_host()->source_frame_number() - 1;
3868     switch (last_source_frame_number) {
3869       case 0:
3870         layer_tree_host()->SetRootLayer(root_);
3871         break;
3872       case 1:
3873         EXPECT_FALSE(root_->needs_push_properties());
3874         EXPECT_FALSE(root_->descendant_needs_push_properties());
3875         EXPECT_FALSE(child_->needs_push_properties());
3876         EXPECT_FALSE(child_->descendant_needs_push_properties());
3877         EXPECT_FALSE(grandchild1_->needs_push_properties());
3878         EXPECT_FALSE(grandchild1_->descendant_needs_push_properties());
3879         EXPECT_FALSE(grandchild2_->needs_push_properties());
3880         EXPECT_FALSE(grandchild2_->descendant_needs_push_properties());
3881         EXPECT_FALSE(grandchild3_->needs_push_properties());
3882         EXPECT_FALSE(grandchild3_->descendant_needs_push_properties());
3883
3884         grandchild1_->RemoveFromParent();
3885         grandchild1_->SetPosition(gfx::Point(1, 1));
3886
3887         EXPECT_FALSE(root_->needs_push_properties());
3888         EXPECT_FALSE(root_->descendant_needs_push_properties());
3889         EXPECT_FALSE(child_->needs_push_properties());
3890         EXPECT_FALSE(child_->descendant_needs_push_properties());
3891         EXPECT_FALSE(grandchild2_->needs_push_properties());
3892         EXPECT_FALSE(grandchild2_->descendant_needs_push_properties());
3893         EXPECT_FALSE(grandchild3_->needs_push_properties());
3894         EXPECT_FALSE(grandchild3_->descendant_needs_push_properties());
3895
3896         child_->AddChild(grandchild1_);
3897
3898         EXPECT_FALSE(root_->needs_push_properties());
3899         EXPECT_TRUE(root_->descendant_needs_push_properties());
3900         EXPECT_FALSE(child_->needs_push_properties());
3901         EXPECT_TRUE(child_->descendant_needs_push_properties());
3902         EXPECT_TRUE(grandchild1_->needs_push_properties());
3903         EXPECT_FALSE(grandchild1_->descendant_needs_push_properties());
3904         EXPECT_FALSE(grandchild2_->needs_push_properties());
3905         EXPECT_FALSE(grandchild2_->descendant_needs_push_properties());
3906         EXPECT_FALSE(grandchild3_->needs_push_properties());
3907         EXPECT_FALSE(grandchild3_->descendant_needs_push_properties());
3908
3909         grandchild2_->SetPosition(gfx::Point(1, 1));
3910
3911         EXPECT_FALSE(root_->needs_push_properties());
3912         EXPECT_TRUE(root_->descendant_needs_push_properties());
3913         EXPECT_FALSE(child_->needs_push_properties());
3914         EXPECT_TRUE(child_->descendant_needs_push_properties());
3915         EXPECT_TRUE(grandchild1_->needs_push_properties());
3916         EXPECT_FALSE(grandchild1_->descendant_needs_push_properties());
3917         EXPECT_TRUE(grandchild2_->needs_push_properties());
3918         EXPECT_FALSE(grandchild2_->descendant_needs_push_properties());
3919         EXPECT_FALSE(grandchild3_->needs_push_properties());
3920         EXPECT_FALSE(grandchild3_->descendant_needs_push_properties());
3921
3922         // grandchild2_ will still need a push properties.
3923         grandchild1_->RemoveFromParent();
3924
3925         EXPECT_FALSE(root_->needs_push_properties());
3926         EXPECT_TRUE(root_->descendant_needs_push_properties());
3927         EXPECT_FALSE(child_->needs_push_properties());
3928         EXPECT_TRUE(child_->descendant_needs_push_properties());
3929
3930         // grandchild3_ does not need a push properties, so recursing should
3931         // no longer be needed.
3932         grandchild2_->RemoveFromParent();
3933
3934         EXPECT_FALSE(root_->needs_push_properties());
3935         EXPECT_FALSE(root_->descendant_needs_push_properties());
3936         EXPECT_FALSE(child_->needs_push_properties());
3937         EXPECT_FALSE(child_->descendant_needs_push_properties());
3938         EndTest();
3939         break;
3940     }
3941   }
3942 };
3943
3944 MULTI_THREAD_TEST_F(LayerTreeHostTestPushPropertiesRemovingChildStopsRecursion);
3945
3946 class LayerTreeHostTestPushPropertiesRemovingChildStopsRecursionWithPersistence
3947     : public LayerTreeHostTestCasePushPropertiesThreeGrandChildren {
3948  protected:
3949   virtual void DidCommitAndDrawFrame() OVERRIDE {
3950     int last_source_frame_number = layer_tree_host()->source_frame_number() - 1;
3951     switch (last_source_frame_number) {
3952       case 0:
3953         layer_tree_host()->SetRootLayer(root_);
3954         grandchild1_->set_persist_needs_push_properties(true);
3955         grandchild2_->set_persist_needs_push_properties(true);
3956         break;
3957       case 1:
3958         EXPECT_FALSE(root_->needs_push_properties());
3959         EXPECT_TRUE(root_->descendant_needs_push_properties());
3960         EXPECT_FALSE(child_->needs_push_properties());
3961         EXPECT_TRUE(child_->descendant_needs_push_properties());
3962         EXPECT_TRUE(grandchild1_->needs_push_properties());
3963         EXPECT_FALSE(grandchild1_->descendant_needs_push_properties());
3964         EXPECT_TRUE(grandchild2_->needs_push_properties());
3965         EXPECT_FALSE(grandchild2_->descendant_needs_push_properties());
3966         EXPECT_FALSE(grandchild3_->needs_push_properties());
3967         EXPECT_FALSE(grandchild3_->descendant_needs_push_properties());
3968
3969         // grandchild2_ will still need a push properties.
3970         grandchild1_->RemoveFromParent();
3971
3972         EXPECT_FALSE(root_->needs_push_properties());
3973         EXPECT_TRUE(root_->descendant_needs_push_properties());
3974         EXPECT_FALSE(child_->needs_push_properties());
3975         EXPECT_TRUE(child_->descendant_needs_push_properties());
3976
3977         // grandchild3_ does not need a push properties, so recursing should
3978         // no longer be needed.
3979         grandchild2_->RemoveFromParent();
3980
3981         EXPECT_FALSE(root_->needs_push_properties());
3982         EXPECT_FALSE(root_->descendant_needs_push_properties());
3983         EXPECT_FALSE(child_->needs_push_properties());
3984         EXPECT_FALSE(child_->descendant_needs_push_properties());
3985         EndTest();
3986         break;
3987     }
3988   }
3989 };
3990
3991 MULTI_THREAD_TEST_F(
3992     LayerTreeHostTestPushPropertiesRemovingChildStopsRecursionWithPersistence);
3993
3994 class LayerTreeHostTestPushPropertiesSetPropertiesWhileOutsideTree
3995     : public LayerTreeHostTestCasePushPropertiesThreeGrandChildren {
3996  protected:
3997   virtual void DidCommitAndDrawFrame() OVERRIDE {
3998     int last_source_frame_number = layer_tree_host()->source_frame_number() - 1;
3999     switch (last_source_frame_number) {
4000       case 0:
4001         layer_tree_host()->SetRootLayer(root_);
4002         break;
4003       case 1:
4004         EXPECT_FALSE(root_->needs_push_properties());
4005         EXPECT_FALSE(root_->descendant_needs_push_properties());
4006         EXPECT_FALSE(child_->needs_push_properties());
4007         EXPECT_FALSE(child_->descendant_needs_push_properties());
4008         EXPECT_FALSE(grandchild1_->needs_push_properties());
4009         EXPECT_FALSE(grandchild1_->descendant_needs_push_properties());
4010         EXPECT_FALSE(grandchild2_->needs_push_properties());
4011         EXPECT_FALSE(grandchild2_->descendant_needs_push_properties());
4012         EXPECT_FALSE(grandchild3_->needs_push_properties());
4013         EXPECT_FALSE(grandchild3_->descendant_needs_push_properties());
4014
4015         // Change grandchildren while their parent is not in the tree.
4016         child_->RemoveFromParent();
4017         grandchild1_->SetPosition(gfx::Point(1, 1));
4018         grandchild2_->SetPosition(gfx::Point(1, 1));
4019         root_->AddChild(child_);
4020
4021         EXPECT_FALSE(root_->needs_push_properties());
4022         EXPECT_TRUE(root_->descendant_needs_push_properties());
4023         EXPECT_TRUE(child_->needs_push_properties());
4024         EXPECT_TRUE(child_->descendant_needs_push_properties());
4025         EXPECT_TRUE(grandchild1_->needs_push_properties());
4026         EXPECT_FALSE(grandchild1_->descendant_needs_push_properties());
4027         EXPECT_TRUE(grandchild2_->needs_push_properties());
4028         EXPECT_FALSE(grandchild2_->descendant_needs_push_properties());
4029         EXPECT_TRUE(grandchild3_->needs_push_properties());
4030         EXPECT_FALSE(grandchild3_->descendant_needs_push_properties());
4031
4032         grandchild1_->RemoveFromParent();
4033
4034         EXPECT_FALSE(root_->needs_push_properties());
4035         EXPECT_TRUE(root_->descendant_needs_push_properties());
4036         EXPECT_TRUE(child_->needs_push_properties());
4037         EXPECT_TRUE(child_->descendant_needs_push_properties());
4038
4039         grandchild2_->RemoveFromParent();
4040
4041         EXPECT_FALSE(root_->needs_push_properties());
4042         EXPECT_TRUE(root_->descendant_needs_push_properties());
4043         EXPECT_TRUE(child_->needs_push_properties());
4044         EXPECT_TRUE(child_->descendant_needs_push_properties());
4045
4046         grandchild3_->RemoveFromParent();
4047
4048         EXPECT_FALSE(root_->needs_push_properties());
4049         EXPECT_TRUE(root_->descendant_needs_push_properties());
4050         EXPECT_TRUE(child_->needs_push_properties());
4051         EXPECT_FALSE(child_->descendant_needs_push_properties());
4052
4053         EndTest();
4054         break;
4055     }
4056   }
4057 };
4058
4059 MULTI_THREAD_TEST_F(
4060     LayerTreeHostTestPushPropertiesSetPropertiesWhileOutsideTree);
4061
4062 class LayerTreeHostTestPushPropertiesSetPropertyInParentThenChild
4063     : public LayerTreeHostTestCasePushPropertiesThreeGrandChildren {
4064  protected:
4065   virtual void DidCommitAndDrawFrame() OVERRIDE {
4066     int last_source_frame_number = layer_tree_host()->source_frame_number() - 1;
4067     switch (last_source_frame_number) {
4068       case 0:
4069         layer_tree_host()->SetRootLayer(root_);
4070         break;
4071       case 1:
4072         EXPECT_FALSE(root_->needs_push_properties());
4073         EXPECT_FALSE(root_->descendant_needs_push_properties());
4074         EXPECT_FALSE(child_->needs_push_properties());
4075         EXPECT_FALSE(child_->descendant_needs_push_properties());
4076         EXPECT_FALSE(grandchild1_->needs_push_properties());
4077         EXPECT_FALSE(grandchild1_->descendant_needs_push_properties());
4078         EXPECT_FALSE(grandchild2_->needs_push_properties());
4079         EXPECT_FALSE(grandchild2_->descendant_needs_push_properties());
4080         EXPECT_FALSE(grandchild3_->needs_push_properties());
4081         EXPECT_FALSE(grandchild3_->descendant_needs_push_properties());
4082
4083         child_->SetPosition(gfx::Point(1, 1));
4084         grandchild1_->SetPosition(gfx::Point(1, 1));
4085         grandchild2_->SetPosition(gfx::Point(1, 1));
4086
4087         EXPECT_FALSE(root_->needs_push_properties());
4088         EXPECT_TRUE(root_->descendant_needs_push_properties());
4089         EXPECT_TRUE(child_->needs_push_properties());
4090         EXPECT_TRUE(child_->descendant_needs_push_properties());
4091         EXPECT_TRUE(grandchild1_->needs_push_properties());
4092         EXPECT_FALSE(grandchild1_->descendant_needs_push_properties());
4093         EXPECT_TRUE(grandchild2_->needs_push_properties());
4094         EXPECT_FALSE(grandchild2_->descendant_needs_push_properties());
4095         EXPECT_FALSE(grandchild3_->needs_push_properties());
4096         EXPECT_FALSE(grandchild3_->descendant_needs_push_properties());
4097
4098         grandchild1_->RemoveFromParent();
4099
4100         EXPECT_FALSE(root_->needs_push_properties());
4101         EXPECT_TRUE(root_->descendant_needs_push_properties());
4102         EXPECT_TRUE(child_->needs_push_properties());
4103         EXPECT_TRUE(child_->descendant_needs_push_properties());
4104
4105         grandchild2_->RemoveFromParent();
4106
4107         EXPECT_FALSE(root_->needs_push_properties());
4108         EXPECT_TRUE(root_->descendant_needs_push_properties());
4109         EXPECT_TRUE(child_->needs_push_properties());
4110         EXPECT_FALSE(child_->descendant_needs_push_properties());
4111
4112         child_->RemoveFromParent();
4113
4114         EXPECT_FALSE(root_->needs_push_properties());
4115         EXPECT_FALSE(root_->descendant_needs_push_properties());
4116
4117         EndTest();
4118         break;
4119     }
4120   }
4121 };
4122
4123 MULTI_THREAD_TEST_F(
4124     LayerTreeHostTestPushPropertiesSetPropertyInParentThenChild);
4125
4126 class LayerTreeHostTestPushPropertiesSetPropertyInChildThenParent
4127     : public LayerTreeHostTestCasePushPropertiesThreeGrandChildren {
4128  protected:
4129   virtual void DidCommitAndDrawFrame() OVERRIDE {
4130     int last_source_frame_number = layer_tree_host()->source_frame_number() - 1;
4131     switch (last_source_frame_number) {
4132       case 0:
4133         layer_tree_host()->SetRootLayer(root_);
4134         break;
4135       case 1:
4136         EXPECT_FALSE(root_->needs_push_properties());
4137         EXPECT_FALSE(root_->descendant_needs_push_properties());
4138         EXPECT_FALSE(child_->needs_push_properties());
4139         EXPECT_FALSE(child_->descendant_needs_push_properties());
4140         EXPECT_FALSE(grandchild1_->needs_push_properties());
4141         EXPECT_FALSE(grandchild1_->descendant_needs_push_properties());
4142         EXPECT_FALSE(grandchild2_->needs_push_properties());
4143         EXPECT_FALSE(grandchild2_->descendant_needs_push_properties());
4144         EXPECT_FALSE(grandchild3_->needs_push_properties());
4145         EXPECT_FALSE(grandchild3_->descendant_needs_push_properties());
4146
4147         grandchild1_->SetPosition(gfx::Point(1, 1));
4148         grandchild2_->SetPosition(gfx::Point(1, 1));
4149         child_->SetPosition(gfx::Point(1, 1));
4150
4151         EXPECT_FALSE(root_->needs_push_properties());
4152         EXPECT_TRUE(root_->descendant_needs_push_properties());
4153         EXPECT_TRUE(child_->needs_push_properties());
4154         EXPECT_TRUE(child_->descendant_needs_push_properties());
4155         EXPECT_TRUE(grandchild1_->needs_push_properties());
4156         EXPECT_FALSE(grandchild1_->descendant_needs_push_properties());
4157         EXPECT_TRUE(grandchild2_->needs_push_properties());
4158         EXPECT_FALSE(grandchild2_->descendant_needs_push_properties());
4159         EXPECT_FALSE(grandchild3_->needs_push_properties());
4160         EXPECT_FALSE(grandchild3_->descendant_needs_push_properties());
4161
4162         grandchild1_->RemoveFromParent();
4163
4164         EXPECT_FALSE(root_->needs_push_properties());
4165         EXPECT_TRUE(root_->descendant_needs_push_properties());
4166         EXPECT_TRUE(child_->needs_push_properties());
4167         EXPECT_TRUE(child_->descendant_needs_push_properties());
4168
4169         grandchild2_->RemoveFromParent();
4170
4171         EXPECT_FALSE(root_->needs_push_properties());
4172         EXPECT_TRUE(root_->descendant_needs_push_properties());
4173         EXPECT_TRUE(child_->needs_push_properties());
4174         EXPECT_FALSE(child_->descendant_needs_push_properties());
4175
4176         child_->RemoveFromParent();
4177
4178         EXPECT_FALSE(root_->needs_push_properties());
4179         EXPECT_FALSE(root_->descendant_needs_push_properties());
4180
4181         EndTest();
4182         break;
4183     }
4184   }
4185 };
4186
4187 MULTI_THREAD_TEST_F(
4188     LayerTreeHostTestPushPropertiesSetPropertyInChildThenParent);
4189
4190 // This test verifies that the tree activation callback is invoked correctly.
4191 class LayerTreeHostTestTreeActivationCallback : public LayerTreeHostTest {
4192  public:
4193   LayerTreeHostTestTreeActivationCallback()
4194       : num_commits_(0), callback_count_(0) {}
4195
4196   virtual void BeginTest() OVERRIDE {
4197     EXPECT_TRUE(HasImplThread());
4198     PostSetNeedsCommitToMainThread();
4199   }
4200
4201   virtual DrawSwapReadbackResult::DrawResult PrepareToDrawOnThread(
4202       LayerTreeHostImpl* host_impl,
4203       LayerTreeHostImpl::FrameData* frame_data,
4204       DrawSwapReadbackResult::DrawResult draw_result) OVERRIDE {
4205     ++num_commits_;
4206     switch (num_commits_) {
4207       case 1:
4208         EXPECT_EQ(0, callback_count_);
4209         callback_count_ = 0;
4210         SetCallback(true);
4211         PostSetNeedsCommitToMainThread();
4212         break;
4213       case 2:
4214         EXPECT_EQ(1, callback_count_);
4215         callback_count_ = 0;
4216         SetCallback(false);
4217         PostSetNeedsCommitToMainThread();
4218         break;
4219       case 3:
4220         EXPECT_EQ(0, callback_count_);
4221         callback_count_ = 0;
4222         EndTest();
4223         break;
4224       default:
4225         ADD_FAILURE() << num_commits_;
4226         EndTest();
4227         break;
4228     }
4229     return LayerTreeHostTest::PrepareToDrawOnThread(
4230         host_impl, frame_data, draw_result);
4231   }
4232
4233   virtual void AfterTest() OVERRIDE { EXPECT_EQ(3, num_commits_); }
4234
4235   void SetCallback(bool enable) {
4236     output_surface()->SetTreeActivationCallback(
4237         enable
4238             ? base::Bind(
4239                   &LayerTreeHostTestTreeActivationCallback::ActivationCallback,
4240                   base::Unretained(this))
4241             : base::Closure());
4242   }
4243
4244   void ActivationCallback() { ++callback_count_; }
4245
4246   int num_commits_;
4247   int callback_count_;
4248 };
4249
4250 TEST_F(LayerTreeHostTestTreeActivationCallback, DirectRenderer) {
4251   RunTest(true, false, true);
4252 }
4253
4254 TEST_F(LayerTreeHostTestTreeActivationCallback, DelegatingRenderer) {
4255   RunTest(true, true, true);
4256 }
4257
4258 class LayerInvalidateCausesDraw : public LayerTreeHostTest {
4259  public:
4260   LayerInvalidateCausesDraw() : num_commits_(0), num_draws_(0) {}
4261
4262   virtual void BeginTest() OVERRIDE {
4263     ASSERT_TRUE(!!invalidate_layer_)
4264         << "Derived tests must set this in SetupTree";
4265
4266     // One initial commit.
4267     PostSetNeedsCommitToMainThread();
4268   }
4269
4270   virtual void DidCommitAndDrawFrame() OVERRIDE {
4271     // After commit, invalidate the layer.  This should cause a commit.
4272     if (layer_tree_host()->source_frame_number() == 1)
4273       invalidate_layer_->SetNeedsDisplay();
4274   }
4275
4276   virtual void DrawLayersOnThread(LayerTreeHostImpl* impl) OVERRIDE {
4277     num_draws_++;
4278     if (impl->active_tree()->source_frame_number() == 1)
4279       EndTest();
4280   }
4281
4282   virtual void CommitCompleteOnThread(LayerTreeHostImpl* impl) OVERRIDE {
4283     num_commits_++;
4284   }
4285
4286   virtual void AfterTest() OVERRIDE {
4287     EXPECT_GE(2, num_commits_);
4288     EXPECT_GE(2, num_draws_);
4289   }
4290
4291  protected:
4292   scoped_refptr<Layer> invalidate_layer_;
4293
4294  private:
4295   int num_commits_;
4296   int num_draws_;
4297 };
4298
4299 // VideoLayer must support being invalidated and then passing that along
4300 // to the compositor thread, even though no resources are updated in
4301 // response to that invalidation.
4302 class LayerTreeHostTestVideoLayerInvalidate : public LayerInvalidateCausesDraw {
4303  public:
4304   virtual void SetupTree() OVERRIDE {
4305     LayerTreeHostTest::SetupTree();
4306     scoped_refptr<VideoLayer> video_layer = VideoLayer::Create(&provider_);
4307     video_layer->SetBounds(gfx::Size(10, 10));
4308     video_layer->SetIsDrawable(true);
4309     layer_tree_host()->root_layer()->AddChild(video_layer);
4310
4311     invalidate_layer_ = video_layer;
4312   }
4313
4314  private:
4315   FakeVideoFrameProvider provider_;
4316 };
4317
4318 SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostTestVideoLayerInvalidate);
4319
4320 // IOSurfaceLayer must support being invalidated and then passing that along
4321 // to the compositor thread, even though no resources are updated in
4322 // response to that invalidation.
4323 class LayerTreeHostTestIOSurfaceLayerInvalidate
4324     : public LayerInvalidateCausesDraw {
4325  public:
4326   virtual void SetupTree() OVERRIDE {
4327     LayerTreeHostTest::SetupTree();
4328     scoped_refptr<IOSurfaceLayer> layer = IOSurfaceLayer::Create();
4329     layer->SetBounds(gfx::Size(10, 10));
4330     uint32_t fake_io_surface_id = 7;
4331     layer->SetIOSurfaceProperties(fake_io_surface_id, layer->bounds());
4332     layer->SetIsDrawable(true);
4333     layer_tree_host()->root_layer()->AddChild(layer);
4334
4335     invalidate_layer_ = layer;
4336   }
4337 };
4338
4339 // TODO(danakj): IOSurface layer can not be transported. crbug.com/239335
4340 SINGLE_AND_MULTI_THREAD_DIRECT_RENDERER_TEST_F(
4341     LayerTreeHostTestIOSurfaceLayerInvalidate);
4342
4343 class LayerTreeHostTestPushHiddenLayer : public LayerTreeHostTest {
4344  protected:
4345   virtual void SetupTree() OVERRIDE {
4346     root_layer_ = Layer::Create();
4347     root_layer_->SetAnchorPoint(gfx::PointF());
4348     root_layer_->SetPosition(gfx::Point());
4349     root_layer_->SetBounds(gfx::Size(10, 10));
4350
4351     parent_layer_ = SolidColorLayer::Create();
4352     parent_layer_->SetAnchorPoint(gfx::PointF());
4353     parent_layer_->SetPosition(gfx::Point());
4354     parent_layer_->SetBounds(gfx::Size(10, 10));
4355     parent_layer_->SetIsDrawable(true);
4356     root_layer_->AddChild(parent_layer_);
4357
4358     child_layer_ = SolidColorLayer::Create();
4359     child_layer_->SetAnchorPoint(gfx::PointF());
4360     child_layer_->SetPosition(gfx::Point());
4361     child_layer_->SetBounds(gfx::Size(10, 10));
4362     child_layer_->SetIsDrawable(true);
4363     parent_layer_->AddChild(child_layer_);
4364
4365     layer_tree_host()->SetRootLayer(root_layer_);
4366     LayerTreeHostTest::SetupTree();
4367   }
4368
4369   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
4370
4371   virtual void DidCommitAndDrawFrame() OVERRIDE {
4372     switch (layer_tree_host()->source_frame_number()) {
4373       case 1:
4374         // The layer type used does not need to push properties every frame.
4375         EXPECT_FALSE(child_layer_->needs_push_properties());
4376
4377         // Change the bounds of the child layer, but make it skipped
4378         // by CalculateDrawProperties.
4379         parent_layer_->SetOpacity(0.f);
4380         child_layer_->SetBounds(gfx::Size(5, 5));
4381         break;
4382       case 2:
4383         // The bounds of the child layer were pushed to the impl side.
4384         EXPECT_FALSE(child_layer_->needs_push_properties());
4385
4386         EndTest();
4387         break;
4388     }
4389   }
4390
4391   virtual void DidActivateTreeOnThread(LayerTreeHostImpl* impl) OVERRIDE {
4392     LayerImpl* root = impl->active_tree()->root_layer();
4393     LayerImpl* parent = root->children()[0];
4394     LayerImpl* child = parent->children()[0];
4395
4396     switch (impl->active_tree()->source_frame_number()) {
4397       case 1:
4398         EXPECT_EQ(gfx::Size(5, 5).ToString(), child->bounds().ToString());
4399         break;
4400     }
4401   }
4402
4403   virtual void AfterTest() OVERRIDE {}
4404
4405   scoped_refptr<Layer> root_layer_;
4406   scoped_refptr<SolidColorLayer> parent_layer_;
4407   scoped_refptr<SolidColorLayer> child_layer_;
4408 };
4409
4410 SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostTestPushHiddenLayer);
4411
4412 class LayerTreeHostTestUpdateLayerInEmptyViewport : public LayerTreeHostTest {
4413  protected:
4414   virtual void InitializeSettings(LayerTreeSettings* settings) OVERRIDE {
4415     settings->impl_side_painting = true;
4416   }
4417
4418   virtual void SetupTree() OVERRIDE {
4419     root_layer_ = FakePictureLayer::Create(&client_);
4420     root_layer_->SetAnchorPoint(gfx::PointF());
4421     root_layer_->SetBounds(gfx::Size(10, 10));
4422
4423     layer_tree_host()->SetRootLayer(root_layer_);
4424     LayerTreeHostTest::SetupTree();
4425   }
4426
4427   virtual void BeginTest() OVERRIDE {
4428     // The viewport is empty, but we still need to update layers on the main
4429     // thread.
4430     layer_tree_host()->SetViewportSize(gfx::Size(0, 0));
4431     PostSetNeedsCommitToMainThread();
4432   }
4433
4434   virtual void DidCommit() OVERRIDE {
4435     // The layer should be updated even though the viewport is empty, so we
4436     // are capable of drawing it on the impl tree.
4437     EXPECT_GT(root_layer_->update_count(), 0u);
4438     EndTest();
4439   }
4440
4441   virtual void AfterTest() OVERRIDE {}
4442
4443   FakeContentLayerClient client_;
4444   scoped_refptr<FakePictureLayer> root_layer_;
4445 };
4446
4447 MULTI_THREAD_TEST_F(LayerTreeHostTestUpdateLayerInEmptyViewport);
4448
4449 class LayerTreeHostTestAbortEvictedTextures : public LayerTreeHostTest {
4450  public:
4451   LayerTreeHostTestAbortEvictedTextures()
4452       : num_will_begin_main_frames_(0), num_impl_commits_(0) {}
4453
4454  protected:
4455   virtual void SetupTree() OVERRIDE {
4456     scoped_refptr<SolidColorLayer> root_layer = SolidColorLayer::Create();
4457     root_layer->SetBounds(gfx::Size(200, 200));
4458     root_layer->SetIsDrawable(true);
4459
4460     layer_tree_host()->SetRootLayer(root_layer);
4461     LayerTreeHostTest::SetupTree();
4462   }
4463
4464   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
4465
4466   virtual void WillBeginMainFrame() OVERRIDE {
4467     num_will_begin_main_frames_++;
4468     switch (num_will_begin_main_frames_) {
4469       case 2:
4470         // Send a redraw to the compositor thread.  This will (wrongly) be
4471         // ignored unless aborting resets the texture state.
4472         layer_tree_host()->SetNeedsRedraw();
4473         break;
4474     }
4475   }
4476
4477   virtual void BeginCommitOnThread(LayerTreeHostImpl* impl) OVERRIDE {
4478     num_impl_commits_++;
4479   }
4480
4481   virtual void DrawLayersOnThread(LayerTreeHostImpl* impl) OVERRIDE {
4482     switch (impl->SourceAnimationFrameNumber()) {
4483       case 1:
4484         // Prevent draws until commit.
4485         impl->active_tree()->SetContentsTexturesPurged();
4486         EXPECT_FALSE(impl->CanDraw());
4487         // Trigger an abortable commit.
4488         impl->SetNeedsCommit();
4489         break;
4490       case 2:
4491         EndTest();
4492         break;
4493     }
4494   }
4495
4496   virtual void AfterTest() OVERRIDE {
4497     // Ensure that the commit was truly aborted.
4498     EXPECT_EQ(2, num_will_begin_main_frames_);
4499     EXPECT_EQ(1, num_impl_commits_);
4500   }
4501
4502  private:
4503   int num_will_begin_main_frames_;
4504   int num_impl_commits_;
4505 };
4506
4507 // Commits can only be aborted when using the thread proxy.
4508 MULTI_THREAD_TEST_F(LayerTreeHostTestAbortEvictedTextures);
4509
4510 class LayerTreeHostTestMaxTransferBufferUsageBytes : public LayerTreeHostTest {
4511  protected:
4512   virtual void InitializeSettings(LayerTreeSettings* settings) OVERRIDE {
4513     settings->impl_side_painting = true;
4514   }
4515
4516   virtual scoped_ptr<FakeOutputSurface> CreateFakeOutputSurface(bool fallback)
4517       OVERRIDE {
4518     scoped_refptr<TestContextProvider> context_provider =
4519         TestContextProvider::Create();
4520     context_provider->SetMaxTransferBufferUsageBytes(1024 * 1024);
4521     if (delegating_renderer())
4522       return FakeOutputSurface::CreateDelegating3d(context_provider);
4523     else
4524       return FakeOutputSurface::Create3d(context_provider);
4525   }
4526
4527   virtual void SetupTree() OVERRIDE {
4528     scoped_refptr<FakePictureLayer> root_layer =
4529         FakePictureLayer::Create(&client_);
4530     root_layer->SetBounds(gfx::Size(6000, 6000));
4531     root_layer->SetIsDrawable(true);
4532
4533     layer_tree_host()->SetRootLayer(root_layer);
4534     LayerTreeHostTest::SetupTree();
4535   }
4536
4537   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
4538
4539   virtual void DidActivateTreeOnThread(LayerTreeHostImpl* impl) OVERRIDE {
4540     TestWebGraphicsContext3D* context = TestContext();
4541
4542     // Expect that the transfer buffer memory used is equal to the
4543     // MaxTransferBufferUsageBytes value set in CreateOutputSurface.
4544     EXPECT_EQ(1024 * 1024u, context->GetTransferBufferMemoryUsedBytes());
4545     EndTest();
4546   }
4547
4548   virtual void AfterTest() OVERRIDE {}
4549
4550  private:
4551   FakeContentLayerClient client_;
4552 };
4553
4554 // Impl-side painting is a multi-threaded compositor feature.
4555 MULTI_THREAD_TEST_F(LayerTreeHostTestMaxTransferBufferUsageBytes);
4556
4557 // Test ensuring that memory limits are sent to the prioritized resource
4558 // manager.
4559 class LayerTreeHostTestMemoryLimits : public LayerTreeHostTest {
4560  public:
4561   LayerTreeHostTestMemoryLimits() : num_commits_(0) {}
4562
4563   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
4564
4565   virtual void WillCommit() OVERRIDE {
4566     // Some commits are aborted, so increment number of attempted commits here.
4567     num_commits_++;
4568   }
4569
4570   virtual void DidCommit() OVERRIDE {
4571     switch (num_commits_) {
4572       case 1:
4573         // Verify default values.
4574         EXPECT_EQ(PrioritizedResourceManager::DefaultMemoryAllocationLimit(),
4575                   layer_tree_host()
4576                       ->contents_texture_manager()
4577                       ->MaxMemoryLimitBytes());
4578         EXPECT_EQ(PriorityCalculator::AllowEverythingCutoff(),
4579                   layer_tree_host()
4580                       ->contents_texture_manager()
4581                       ->ExternalPriorityCutoff());
4582         PostSetNeedsCommitToMainThread();
4583         break;
4584       case 2:
4585         // The values should remain the same until the commit after the policy
4586         // is changed.
4587         EXPECT_EQ(PrioritizedResourceManager::DefaultMemoryAllocationLimit(),
4588                   layer_tree_host()
4589                       ->contents_texture_manager()
4590                       ->MaxMemoryLimitBytes());
4591         EXPECT_EQ(PriorityCalculator::AllowEverythingCutoff(),
4592                   layer_tree_host()
4593                       ->contents_texture_manager()
4594                       ->ExternalPriorityCutoff());
4595         break;
4596       case 3:
4597         // Verify values were correctly passed.
4598         EXPECT_EQ(16u * 1024u * 1024u,
4599                   layer_tree_host()
4600                       ->contents_texture_manager()
4601                       ->MaxMemoryLimitBytes());
4602         EXPECT_EQ(PriorityCalculator::AllowVisibleAndNearbyCutoff(),
4603                   layer_tree_host()
4604                       ->contents_texture_manager()
4605                       ->ExternalPriorityCutoff());
4606         EndTest();
4607         break;
4608       case 4:
4609         // Make sure no extra commits happen.
4610         NOTREACHED();
4611         break;
4612     }
4613   }
4614
4615   virtual void CommitCompleteOnThread(LayerTreeHostImpl* impl) OVERRIDE {
4616     switch (num_commits_) {
4617       case 1:
4618         break;
4619       case 2:
4620         // This will trigger a commit because the priority cutoff has changed.
4621         impl->SetMemoryPolicy(ManagedMemoryPolicy(
4622             16u * 1024u * 1024u,
4623             gpu::MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE,
4624             1000));
4625         break;
4626       case 3:
4627         // This will not trigger a commit because the priority cutoff has not
4628         // changed, and there is already enough memory for all allocations.
4629         impl->SetMemoryPolicy(ManagedMemoryPolicy(
4630             32u * 1024u * 1024u,
4631             gpu::MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE,
4632             1000));
4633         break;
4634       case 4:
4635         NOTREACHED();
4636         break;
4637     }
4638   }
4639
4640   virtual void AfterTest() OVERRIDE {}
4641
4642  private:
4643   int num_commits_;
4644 };
4645
4646 SINGLE_AND_MULTI_THREAD_NOIMPL_TEST_F(LayerTreeHostTestMemoryLimits);
4647
4648 class LayerTreeHostTestNoQuadsForEmptyLayer : public LayerTreeHostTest {
4649  protected:
4650   virtual void SetupTree() OVERRIDE {
4651     LayerTreeHostTest::SetupTree();
4652     root_layer_ = FakeContentLayer::Create(&client_);
4653     root_layer_->SetBounds(gfx::Size(10, 10));
4654     root_layer_->SetIsDrawable(false);
4655     root_layer_->SetHaveWheelEventHandlers(true);
4656     layer_tree_host()->SetRootLayer(root_layer_);
4657     LayerTreeHostTest::SetupTree();
4658   }
4659
4660   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
4661
4662   virtual void DidActivateTreeOnThread(LayerTreeHostImpl* impl) OVERRIDE {
4663     FakeContentLayerImpl* layer_impl =
4664         static_cast<FakeContentLayerImpl*>(impl->RootLayer());
4665     EXPECT_FALSE(layer_impl->DrawsContent());
4666     EXPECT_EQ(0u, layer_impl->append_quads_count());
4667   }
4668
4669   virtual void DidCommit() OVERRIDE {
4670     // The layer is not drawable, so it should not be updated.
4671     EXPECT_EQ(0u, root_layer_->update_count());
4672     EndTest();
4673   }
4674   virtual void AfterTest() OVERRIDE {}
4675
4676  private:
4677   FakeContentLayerClient client_;
4678   scoped_refptr<FakeContentLayer> root_layer_;
4679 };
4680
4681 SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostTestNoQuadsForEmptyLayer);
4682
4683 }  // namespace
4684
4685 class LayerTreeHostTestSetMemoryPolicyOnLostOutputSurface
4686     : public LayerTreeHostTest {
4687  protected:
4688   LayerTreeHostTestSetMemoryPolicyOnLostOutputSurface()
4689       : first_output_surface_memory_limit_(4321234),
4690         second_output_surface_memory_limit_(1234321) {}
4691
4692   virtual scoped_ptr<FakeOutputSurface> CreateFakeOutputSurface(bool fallback)
4693       OVERRIDE {
4694     if (!first_context_provider_) {
4695       first_context_provider_ = TestContextProvider::Create();
4696     } else {
4697       EXPECT_FALSE(second_context_provider_);
4698       second_context_provider_ = TestContextProvider::Create();
4699     }
4700
4701     scoped_refptr<TestContextProvider> provider(second_context_provider_
4702                                                     ? second_context_provider_
4703                                                     : first_context_provider_);
4704     scoped_ptr<FakeOutputSurface> output_surface;
4705     if (delegating_renderer())
4706       output_surface = FakeOutputSurface::CreateDelegating3d(provider);
4707     else
4708       output_surface = FakeOutputSurface::Create3d(provider);
4709     output_surface->SetMemoryPolicyToSetAtBind(
4710         make_scoped_ptr(new ManagedMemoryPolicy(
4711             second_context_provider_ ? second_output_surface_memory_limit_
4712                                      : first_output_surface_memory_limit_,
4713             gpu::MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE,
4714             ManagedMemoryPolicy::kDefaultNumResourcesLimit)));
4715     return output_surface.Pass();
4716   }
4717
4718   virtual void SetupTree() OVERRIDE {
4719     root_ = FakeContentLayer::Create(&client_);
4720     root_->SetBounds(gfx::Size(20, 20));
4721     layer_tree_host()->SetRootLayer(root_);
4722     LayerTreeHostTest::SetupTree();
4723   }
4724
4725   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
4726
4727   virtual void DidCommitAndDrawFrame() OVERRIDE {
4728     // Lost context sometimes takes two frames to recreate. The third frame
4729     // is sometimes aborted, so wait until the fourth frame to verify that
4730     // the memory has been set, and the fifth frame to end the test.
4731     if (layer_tree_host()->source_frame_number() < 5) {
4732       layer_tree_host()->SetNeedsCommit();
4733     } else if (layer_tree_host()->source_frame_number() == 5) {
4734       EndTest();
4735     }
4736   }
4737
4738   virtual void SwapBuffersOnThread(LayerTreeHostImpl* impl,
4739                                    bool result) OVERRIDE {
4740     switch (impl->active_tree()->source_frame_number()) {
4741       case 1:
4742         EXPECT_EQ(first_output_surface_memory_limit_,
4743                   impl->memory_allocation_limit_bytes());
4744         // Lose the output surface.
4745         first_context_provider_->TestContext3d()->loseContextCHROMIUM(
4746             GL_GUILTY_CONTEXT_RESET_ARB, GL_INNOCENT_CONTEXT_RESET_ARB);
4747         break;
4748       case 4:
4749         EXPECT_EQ(second_output_surface_memory_limit_,
4750                   impl->memory_allocation_limit_bytes());
4751         break;
4752     }
4753   }
4754
4755   virtual void AfterTest() OVERRIDE {}
4756
4757   scoped_refptr<TestContextProvider> first_context_provider_;
4758   scoped_refptr<TestContextProvider> second_context_provider_;
4759   size_t first_output_surface_memory_limit_;
4760   size_t second_output_surface_memory_limit_;
4761   FakeContentLayerClient client_;
4762   scoped_refptr<FakeContentLayer> root_;
4763 };
4764
4765 // No output to copy for delegated renderers.
4766 SINGLE_AND_MULTI_THREAD_TEST_F(
4767     LayerTreeHostTestSetMemoryPolicyOnLostOutputSurface);
4768
4769 struct TestSwapPromiseResult {
4770   TestSwapPromiseResult()
4771       : did_swap_called(false),
4772         did_not_swap_called(false),
4773         dtor_called(false),
4774         reason(SwapPromise::DID_NOT_SWAP_UNKNOWN) {}
4775
4776   bool did_swap_called;
4777   bool did_not_swap_called;
4778   bool dtor_called;
4779   SwapPromise::DidNotSwapReason reason;
4780   base::Lock lock;
4781 };
4782
4783 class TestSwapPromise : public SwapPromise {
4784  public:
4785   explicit TestSwapPromise(TestSwapPromiseResult* result) : result_(result) {}
4786
4787   virtual ~TestSwapPromise() {
4788     base::AutoLock lock(result_->lock);
4789     result_->dtor_called = true;
4790   }
4791
4792   virtual void DidSwap(CompositorFrameMetadata* metadata) OVERRIDE {
4793     base::AutoLock lock(result_->lock);
4794     EXPECT_FALSE(result_->did_swap_called);
4795     EXPECT_FALSE(result_->did_not_swap_called);
4796     result_->did_swap_called = true;
4797   }
4798
4799   virtual void DidNotSwap(DidNotSwapReason reason) OVERRIDE {
4800     base::AutoLock lock(result_->lock);
4801     EXPECT_FALSE(result_->did_swap_called);
4802     EXPECT_FALSE(result_->did_not_swap_called);
4803     result_->did_not_swap_called = true;
4804     result_->reason = reason;
4805   }
4806
4807  private:
4808   // Not owned.
4809   TestSwapPromiseResult* result_;
4810 };
4811
4812 class LayerTreeHostTestBreakSwapPromise : public LayerTreeHostTest {
4813  protected:
4814   LayerTreeHostTestBreakSwapPromise()
4815       : commit_count_(0), commit_complete_count_(0) {}
4816
4817   virtual void WillBeginMainFrame() OVERRIDE {
4818     ASSERT_LE(commit_count_, 2);
4819     scoped_ptr<SwapPromise> swap_promise(
4820         new TestSwapPromise(&swap_promise_result_[commit_count_]));
4821     layer_tree_host()->QueueSwapPromise(swap_promise.Pass());
4822   }
4823
4824   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
4825
4826   virtual void DidCommit() OVERRIDE {
4827     commit_count_++;
4828     if (commit_count_ == 2) {
4829       // This commit will finish.
4830       layer_tree_host()->SetNeedsCommit();
4831     }
4832   }
4833
4834   virtual void CommitCompleteOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
4835     commit_complete_count_++;
4836     if (commit_complete_count_ == 1) {
4837       // This commit will be aborted because no actual update.
4838       PostSetNeedsUpdateLayersToMainThread();
4839     } else {
4840       EndTest();
4841     }
4842   }
4843
4844   virtual void AfterTest() OVERRIDE {
4845     // 3 commits are scheduled. 2 completes. 1 is aborted.
4846     EXPECT_EQ(commit_count_, 3);
4847     EXPECT_EQ(commit_complete_count_, 2);
4848
4849     {
4850       // The first commit completes and causes swap buffer which finishes
4851       // the promise.
4852       base::AutoLock lock(swap_promise_result_[0].lock);
4853       EXPECT_TRUE(swap_promise_result_[0].did_swap_called);
4854       EXPECT_FALSE(swap_promise_result_[0].did_not_swap_called);
4855       EXPECT_TRUE(swap_promise_result_[0].dtor_called);
4856     }
4857
4858     {
4859       // The second commit aborts.
4860       base::AutoLock lock(swap_promise_result_[1].lock);
4861       EXPECT_FALSE(swap_promise_result_[1].did_swap_called);
4862       EXPECT_TRUE(swap_promise_result_[1].did_not_swap_called);
4863       EXPECT_EQ(SwapPromise::COMMIT_FAILS, swap_promise_result_[1].reason);
4864       EXPECT_TRUE(swap_promise_result_[1].dtor_called);
4865     }
4866
4867     {
4868       // The last commit completes but it does not cause swap buffer because
4869       // there is no damage in the frame data.
4870       base::AutoLock lock(swap_promise_result_[2].lock);
4871       EXPECT_FALSE(swap_promise_result_[2].did_swap_called);
4872       EXPECT_TRUE(swap_promise_result_[2].did_not_swap_called);
4873       EXPECT_EQ(SwapPromise::SWAP_FAILS, swap_promise_result_[2].reason);
4874       EXPECT_TRUE(swap_promise_result_[2].dtor_called);
4875     }
4876   }
4877
4878   int commit_count_;
4879   int commit_complete_count_;
4880   TestSwapPromiseResult swap_promise_result_[3];
4881 };
4882
4883 MULTI_THREAD_TEST_F(LayerTreeHostTestBreakSwapPromise);
4884
4885 class SimpleSwapPromiseMonitor : public SwapPromiseMonitor {
4886  public:
4887   SimpleSwapPromiseMonitor(LayerTreeHost* layer_tree_host,
4888                            LayerTreeHostImpl* layer_tree_host_impl,
4889                            int* set_needs_commit_count,
4890                            int* set_needs_redraw_count)
4891       : SwapPromiseMonitor(layer_tree_host, layer_tree_host_impl),
4892         set_needs_commit_count_(set_needs_commit_count),
4893         set_needs_redraw_count_(set_needs_redraw_count) {}
4894
4895   virtual ~SimpleSwapPromiseMonitor() {}
4896
4897   virtual void OnSetNeedsCommitOnMain() OVERRIDE {
4898     (*set_needs_commit_count_)++;
4899   }
4900
4901   virtual void OnSetNeedsRedrawOnImpl() OVERRIDE {
4902     (*set_needs_redraw_count_)++;
4903   }
4904
4905  private:
4906   int* set_needs_commit_count_;
4907   int* set_needs_redraw_count_;
4908 };
4909
4910 class LayerTreeHostTestSimpleSwapPromiseMonitor : public LayerTreeHostTest {
4911  public:
4912   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
4913
4914   virtual void WillBeginMainFrame() OVERRIDE {
4915     int set_needs_commit_count = 0;
4916     int set_needs_redraw_count = 0;
4917
4918     {
4919       scoped_ptr<SimpleSwapPromiseMonitor> swap_promise_monitor(
4920           new SimpleSwapPromiseMonitor(layer_tree_host(),
4921                                        NULL,
4922                                        &set_needs_commit_count,
4923                                        &set_needs_redraw_count));
4924       layer_tree_host()->SetNeedsCommit();
4925       EXPECT_EQ(1, set_needs_commit_count);
4926       EXPECT_EQ(0, set_needs_redraw_count);
4927     }
4928
4929     // Now the monitor is destroyed, SetNeedsCommit() is no longer being
4930     // monitored.
4931     layer_tree_host()->SetNeedsCommit();
4932     EXPECT_EQ(1, set_needs_commit_count);
4933     EXPECT_EQ(0, set_needs_redraw_count);
4934
4935     {
4936       scoped_ptr<SimpleSwapPromiseMonitor> swap_promise_monitor(
4937           new SimpleSwapPromiseMonitor(layer_tree_host(),
4938                                        NULL,
4939                                        &set_needs_commit_count,
4940                                        &set_needs_redraw_count));
4941       layer_tree_host()->SetNeedsUpdateLayers();
4942       EXPECT_EQ(2, set_needs_commit_count);
4943       EXPECT_EQ(0, set_needs_redraw_count);
4944     }
4945
4946     {
4947       scoped_ptr<SimpleSwapPromiseMonitor> swap_promise_monitor(
4948           new SimpleSwapPromiseMonitor(layer_tree_host(),
4949                                        NULL,
4950                                        &set_needs_commit_count,
4951                                        &set_needs_redraw_count));
4952       layer_tree_host()->SetNeedsAnimate();
4953       EXPECT_EQ(3, set_needs_commit_count);
4954       EXPECT_EQ(0, set_needs_redraw_count);
4955     }
4956
4957     EndTest();
4958   }
4959
4960   virtual void AfterTest() OVERRIDE {}
4961 };
4962
4963 MULTI_THREAD_TEST_F(LayerTreeHostTestSimpleSwapPromiseMonitor);
4964
4965 class LayerTreeHostTestHighResRequiredAfterEvictingUIResources
4966     : public LayerTreeHostTest {
4967  protected:
4968   virtual void InitializeSettings(LayerTreeSettings* settings) OVERRIDE {
4969     settings->impl_side_painting = true;
4970   }
4971
4972   virtual void SetupTree() OVERRIDE {
4973     LayerTreeHostTest::SetupTree();
4974     ui_resource_ = FakeScopedUIResource::Create(layer_tree_host());
4975   }
4976
4977   virtual void BeginTest() OVERRIDE { PostSetNeedsCommitToMainThread(); }
4978
4979   virtual void DidActivateTreeOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
4980     host_impl->EvictAllUIResources();
4981     // Existence of evicted UI resources will trigger NEW_CONTENT_TAKES_PRIORITY
4982     // mode. Active tree should require high-res to draw after entering this
4983     // mode to ensure that high-res tiles are also required for a pending tree
4984     // to be activated.
4985     EXPECT_TRUE(host_impl->active_tree()->RequiresHighResToDraw());
4986   }
4987
4988   virtual void DidCommit() OVERRIDE {
4989     int frame = layer_tree_host()->source_frame_number();
4990     switch (frame) {
4991       case 1:
4992         PostSetNeedsCommitToMainThread();
4993         break;
4994       case 2:
4995         ui_resource_.reset();
4996         EndTest();
4997         break;
4998     }
4999   }
5000
5001   virtual void AfterTest() OVERRIDE {}
5002
5003   FakeContentLayerClient client_;
5004   scoped_ptr<FakeScopedUIResource> ui_resource_;
5005 };
5006
5007 MULTI_THREAD_TEST_F(LayerTreeHostTestHighResRequiredAfterEvictingUIResources);
5008
5009 class LayerTreeHostTestGpuRasterizationDefault : public LayerTreeHostTest {
5010  protected:
5011   virtual void InitializeSettings(LayerTreeSettings* settings) OVERRIDE {
5012     settings->impl_side_painting = true;
5013
5014     EXPECT_FALSE(settings->gpu_rasterization_enabled);
5015     EXPECT_FALSE(settings->gpu_rasterization_forced);
5016   }
5017
5018   virtual void SetupTree() OVERRIDE {
5019     LayerTreeHostTest::SetupTree();
5020
5021     scoped_refptr<PictureLayer> layer = PictureLayer::Create(&layer_client_);
5022     layer->SetBounds(gfx::Size(10, 10));
5023     layer->SetIsDrawable(true);
5024     layer_tree_host()->root_layer()->AddChild(layer);
5025   }
5026
5027   virtual void BeginTest() OVERRIDE {
5028     Layer* root = layer_tree_host()->root_layer();
5029     PictureLayer* layer = static_cast<PictureLayer*>(root->child_at(0));
5030     PicturePile* pile = layer->GetPicturePileForTesting();
5031
5032     // Verify default values.
5033     EXPECT_TRUE(root->IsSuitableForGpuRasterization());
5034     EXPECT_TRUE(layer->IsSuitableForGpuRasterization());
5035     EXPECT_TRUE(pile->is_suitable_for_gpu_rasterization());
5036     EXPECT_FALSE(layer_tree_host()->has_gpu_rasterization_trigger());
5037     EXPECT_FALSE(layer_tree_host()->UseGpuRasterization());
5038
5039     // Setting gpu rasterization trigger does not enable gpu rasterization.
5040     layer_tree_host()->set_has_gpu_rasterization_trigger(true);
5041     EXPECT_TRUE(layer_tree_host()->has_gpu_rasterization_trigger());
5042     EXPECT_FALSE(layer_tree_host()->UseGpuRasterization());
5043
5044     PostSetNeedsCommitToMainThread();
5045   }
5046
5047   virtual void CommitCompleteOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
5048     LayerImpl* root = host_impl->pending_tree()->root_layer();
5049     PictureLayerImpl* layer_impl =
5050         static_cast<PictureLayerImpl*>(root->children()[0]);
5051
5052     EXPECT_FALSE(layer_impl->use_gpu_rasterization());
5053   }
5054
5055   virtual void DidActivateTreeOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
5056     LayerImpl* root = host_impl->active_tree()->root_layer();
5057     PictureLayerImpl* layer_impl =
5058         static_cast<PictureLayerImpl*>(root->children()[0]);
5059
5060     EXPECT_FALSE(layer_impl->use_gpu_rasterization());
5061     EndTest();
5062   }
5063
5064   virtual void AfterTest() OVERRIDE {}
5065
5066   FakeContentLayerClient layer_client_;
5067 };
5068
5069 MULTI_THREAD_TEST_F(LayerTreeHostTestGpuRasterizationDefault);
5070
5071 class LayerTreeHostTestGpuRasterizationEnabled : public LayerTreeHostTest {
5072  protected:
5073   virtual void InitializeSettings(LayerTreeSettings* settings) OVERRIDE {
5074     settings->impl_side_painting = true;
5075
5076     EXPECT_FALSE(settings->gpu_rasterization_enabled);
5077     settings->gpu_rasterization_enabled = true;
5078   }
5079
5080   virtual void SetupTree() OVERRIDE {
5081     LayerTreeHostTest::SetupTree();
5082
5083     scoped_refptr<PictureLayer> layer = PictureLayer::Create(&layer_client_);
5084     layer->SetBounds(gfx::Size(10, 10));
5085     layer->SetIsDrawable(true);
5086     layer_tree_host()->root_layer()->AddChild(layer);
5087   }
5088
5089   virtual void BeginTest() OVERRIDE {
5090     Layer* root = layer_tree_host()->root_layer();
5091     PictureLayer* layer = static_cast<PictureLayer*>(root->child_at(0));
5092     PicturePile* pile = layer->GetPicturePileForTesting();
5093
5094     // Verify default values.
5095     EXPECT_TRUE(root->IsSuitableForGpuRasterization());
5096     EXPECT_TRUE(layer->IsSuitableForGpuRasterization());
5097     EXPECT_TRUE(pile->is_suitable_for_gpu_rasterization());
5098     EXPECT_FALSE(layer_tree_host()->has_gpu_rasterization_trigger());
5099     EXPECT_FALSE(layer_tree_host()->UseGpuRasterization());
5100
5101     // Gpu rasterization trigger is relevant.
5102     layer_tree_host()->set_has_gpu_rasterization_trigger(true);
5103     EXPECT_TRUE(layer_tree_host()->has_gpu_rasterization_trigger());
5104     EXPECT_TRUE(layer_tree_host()->UseGpuRasterization());
5105
5106     // Content-based veto is relevant as well.
5107     pile->SetUnsuitableForGpuRasterizationForTesting();
5108     EXPECT_FALSE(pile->is_suitable_for_gpu_rasterization());
5109     EXPECT_FALSE(layer->IsSuitableForGpuRasterization());
5110     // Veto will take effect when layers are updated.
5111     // The results will be verified after commit is completed below.
5112     // Since we are manually marking picture pile as unsuitable,
5113     // make sure that the layer gets a chance to update.
5114     layer->SetNeedsDisplay();
5115     PostSetNeedsCommitToMainThread();
5116   }
5117
5118   virtual void CommitCompleteOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
5119     LayerImpl* root = host_impl->pending_tree()->root_layer();
5120     PictureLayerImpl* layer_impl =
5121         static_cast<PictureLayerImpl*>(root->children()[0]);
5122
5123     EXPECT_FALSE(layer_impl->use_gpu_rasterization());
5124   }
5125
5126   virtual void DidActivateTreeOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
5127     LayerImpl* root = host_impl->active_tree()->root_layer();
5128     PictureLayerImpl* layer_impl =
5129         static_cast<PictureLayerImpl*>(root->children()[0]);
5130
5131     EXPECT_FALSE(layer_impl->use_gpu_rasterization());
5132     EndTest();
5133   }
5134
5135   virtual void AfterTest() OVERRIDE {}
5136
5137   FakeContentLayerClient layer_client_;
5138 };
5139
5140 MULTI_THREAD_TEST_F(LayerTreeHostTestGpuRasterizationEnabled);
5141
5142 class LayerTreeHostTestGpuRasterizationForced : public LayerTreeHostTest {
5143  protected:
5144   virtual void InitializeSettings(LayerTreeSettings* settings) OVERRIDE {
5145     settings->impl_side_painting = true;
5146
5147     EXPECT_FALSE(settings->gpu_rasterization_forced);
5148     settings->gpu_rasterization_forced = true;
5149   }
5150
5151   virtual void SetupTree() OVERRIDE {
5152     LayerTreeHostTest::SetupTree();
5153
5154     scoped_refptr<PictureLayer> layer = PictureLayer::Create(&layer_client_);
5155     layer->SetBounds(gfx::Size(10, 10));
5156     layer->SetIsDrawable(true);
5157     layer_tree_host()->root_layer()->AddChild(layer);
5158   }
5159
5160   virtual void BeginTest() OVERRIDE {
5161     Layer* root = layer_tree_host()->root_layer();
5162     PictureLayer* layer = static_cast<PictureLayer*>(root->child_at(0));
5163     PicturePile* pile = layer->GetPicturePileForTesting();
5164
5165     // Verify default values.
5166     EXPECT_TRUE(root->IsSuitableForGpuRasterization());
5167     EXPECT_TRUE(layer->IsSuitableForGpuRasterization());
5168     EXPECT_TRUE(pile->is_suitable_for_gpu_rasterization());
5169     EXPECT_FALSE(layer_tree_host()->has_gpu_rasterization_trigger());
5170
5171     // With gpu rasterization forced, gpu rasterization trigger is irrelevant.
5172     EXPECT_TRUE(layer_tree_host()->UseGpuRasterization());
5173     layer_tree_host()->set_has_gpu_rasterization_trigger(true);
5174     EXPECT_TRUE(layer_tree_host()->has_gpu_rasterization_trigger());
5175     EXPECT_TRUE(layer_tree_host()->UseGpuRasterization());
5176
5177     // Content-based veto is irrelevant as well.
5178     pile->SetUnsuitableForGpuRasterizationForTesting();
5179     EXPECT_FALSE(pile->is_suitable_for_gpu_rasterization());
5180     EXPECT_FALSE(layer->IsSuitableForGpuRasterization());
5181     // Veto will take effect when layers are updated.
5182     // The results will be verified after commit is completed below.
5183     // Since we are manually marking picture pile as unsuitable,
5184     // make sure that the layer gets a chance to update.
5185     layer->SetNeedsDisplay();
5186     PostSetNeedsCommitToMainThread();
5187   }
5188
5189   virtual void CommitCompleteOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
5190     LayerImpl* root = host_impl->pending_tree()->root_layer();
5191     PictureLayerImpl* layer_impl =
5192         static_cast<PictureLayerImpl*>(root->children()[0]);
5193
5194     EXPECT_TRUE(layer_impl->use_gpu_rasterization());
5195   }
5196
5197   virtual void DidActivateTreeOnThread(LayerTreeHostImpl* host_impl) OVERRIDE {
5198     LayerImpl* root = host_impl->active_tree()->root_layer();
5199     PictureLayerImpl* layer_impl =
5200         static_cast<PictureLayerImpl*>(root->children()[0]);
5201
5202     EXPECT_TRUE(layer_impl->use_gpu_rasterization());
5203     EndTest();
5204   }
5205
5206   virtual void AfterTest() OVERRIDE {}
5207
5208   FakeContentLayerClient layer_client_;
5209 };
5210
5211 MULTI_THREAD_TEST_F(LayerTreeHostTestGpuRasterizationForced);
5212
5213 class LayerTreeHostTestContinuousPainting : public LayerTreeHostTest {
5214  public:
5215   LayerTreeHostTestContinuousPainting()
5216       : num_commits_(0), num_draws_(0), bounds_(20, 20), child_layer_(NULL) {}
5217
5218  protected:
5219   enum { kExpectedNumCommits = 10 };
5220
5221   virtual void SetupTree() OVERRIDE {
5222     scoped_refptr<Layer> root_layer = Layer::Create();
5223     root_layer->SetBounds(bounds_);
5224
5225     if (layer_tree_host()->settings().impl_side_painting) {
5226       picture_layer_ = FakePictureLayer::Create(&client_);
5227       child_layer_ = picture_layer_.get();
5228     } else {
5229       content_layer_ = ContentLayerWithUpdateTracking::Create(&client_);
5230       child_layer_ = content_layer_.get();
5231     }
5232     child_layer_->SetBounds(bounds_);
5233     child_layer_->SetIsDrawable(true);
5234     root_layer->AddChild(child_layer_);
5235
5236     layer_tree_host()->SetRootLayer(root_layer);
5237     layer_tree_host()->SetViewportSize(bounds_);
5238     LayerTreeHostTest::SetupTree();
5239   }
5240
5241   virtual void BeginTest() OVERRIDE {
5242     // Wait 50x longer than expected.
5243     double milliseconds_per_frame =
5244         1000 / layer_tree_host()->settings().refresh_rate;
5245     EndTestAfterDelay(50 * kExpectedNumCommits * milliseconds_per_frame);
5246     MainThreadTaskRunner()->PostTask(
5247         FROM_HERE,
5248         base::Bind(
5249             &LayerTreeHostTestContinuousPainting::EnableContinuousPainting,
5250             base::Unretained(this)));
5251   }
5252
5253   virtual void Animate(base::TimeTicks monotonic_time) OVERRIDE {
5254     child_layer_->SetNeedsDisplay();
5255   }
5256
5257   virtual void AfterTest() OVERRIDE {
5258     EXPECT_LE(kExpectedNumCommits, num_commits_);
5259     EXPECT_LE(kExpectedNumCommits, num_draws_);
5260     int update_count = content_layer_ ? content_layer_->PaintContentsCount()
5261                                       : picture_layer_->update_count();
5262     EXPECT_LE(kExpectedNumCommits, update_count);
5263   }
5264
5265   virtual void DrawLayersOnThread(LayerTreeHostImpl* impl) OVERRIDE {
5266     if (++num_draws_ == kExpectedNumCommits)
5267       EndTest();
5268   }
5269
5270   virtual void CommitCompleteOnThread(LayerTreeHostImpl* impl) OVERRIDE {
5271     ++num_commits_;
5272   }
5273
5274  private:
5275   void EnableContinuousPainting() {
5276     LayerTreeDebugState debug_state = layer_tree_host()->debug_state();
5277     debug_state.continuous_painting = true;
5278     layer_tree_host()->SetDebugState(debug_state);
5279   }
5280
5281   int num_commits_;
5282   int num_draws_;
5283   const gfx::Size bounds_;
5284   FakeContentLayerClient client_;
5285   scoped_refptr<ContentLayerWithUpdateTracking> content_layer_;
5286   scoped_refptr<FakePictureLayer> picture_layer_;
5287   Layer* child_layer_;
5288 };
5289
5290 MULTI_THREAD_TEST_F(LayerTreeHostTestContinuousPainting);
5291
5292 }  // namespace cc