1
    2
    3
    4
    5
    6
    7
    8
    9
   10
   11
   12
   13
   14
   15
   16
   17
   18
   19
   20
   21
   22
   23
   24
   25
   26
   27
   28
   29
   30
   31
   32
   33
   34
   35
   36
   37
   38
   39
   40
   41
   42
   43
   44
   45
   46
   47
   48
   49
   50
   51
   52
   53
   54
   55
   56
   57
   58
   59
   60
   61
   62
   63
   64
   65
   66
   67
   68
   69
   70
   71
   72
   73
   74
   75
   76
   77
   78
   79
   80
   81
   82
   83
   84
   85
   86
   87
   88
   89
   90
   91
   92
   93
   94
   95
   96
   97
   98
   99
  100
  101
  102
  103
  104
  105
  106
  107
  108
  109
  110
  111
  112
  113
  114
  115
  116
  117
  118
  119
  120
  121
  122
  123
  124
  125
  126
  127
  128
  129
  130
  131
  132
  133
  134
  135
  136
  137
  138
  139
  140
  141
  142
  143
  144
  145
  146
  147
  148
  149
  150
  151
  152
  153
  154
  155
  156
  157
  158
  159
  160
  161
  162
  163
  164
  165
  166
  167
  168
  169
  170
  171
  172
  173
  174
  175
  176
  177
  178
  179
  180
  181
  182
  183
  184
  185
  186
  187
  188
  189
  190
  191
  192
  193
  194
  195
  196
  197
  198
  199
  200
  201
  202
  203
  204
  205
  206
  207
  208
  209
  210
  211
  212
  213
  214
  215
  216
  217
  218
  219
  220
  221
  222
  223
  224
  225
  226
  227
  228
  229
  230
  231
  232
  233
  234
  235
  236
  237
  238
  239
  240
  241
  242
  243
  244
  245
  246
  247
  248
  249
  250
  251
  252
  253
  254
  255
  256
  257
  258
  259
  260
  261
  262
  263
  264
  265
  266
  267
  268
  269
  270
  271
  272
  273
  274
  275
  276
  277
  278
  279
  280
  281
  282
  283
  284
  285
  286
  287
  288
  289
  290
  291
  292
  293
  294
  295
  296
  297
  298
  299
  300
  301
  302
  303
  304
  305
  306
  307
  308
  309
  310
  311
  312
  313
  314
  315
  316
  317
  318
  319
  320
  321
  322
  323
  324
  325
  326
  327
  328
  329
  330
  331
  332
  333
  334
  335
  336
  337
  338
  339
  340
  341
  342
  343
  344
  345
  346
  347
  348
  349
  350
  351
  352
  353
  354
  355
  356
  357
  358
  359
  360
  361
  362
  363
  364
  365
  366
  367
  368
  369
  370
  371
  372
  373
  374
  375
  376
  377
  378
  379
  380
  381
  382
  383
  384
  385
  386
  387
  388
  389
  390
  391
  392
  393
  394
  395
  396
  397
  398
  399
  400
  401
  402
  403
  404
  405
  406
  407
  408
  409
  410
  411
  412
  413
  414
  415
  416
  417
  418
  419
  420
  421
  422
  423
  424
  425
  426
  427
  428
  429
  430
  431
  432
  433
  434
  435
  436
  437
  438
  439
  440
  441
  442
  443
  444
  445
  446
  447
  448
  449
  450
  451
  452
  453
  454
  455
  456
  457
  458
  459
  460
  461
  462
  463
  464
  465
  466
  467
  468
  469
  470
  471
  472
  473
  474
  475
  476
  477
  478
  479
  480
  481
  482
  483
  484
  485
  486
  487
  488
  489
  490
  491
  492
  493
  494
  495
  496
  497
  498
  499
  500
  501
  502
  503
  504
  505
  506
  507
  508
  509
  510
  511
  512
  513
  514
  515
  516
  517
  518
  519
  520
  521
  522
  523
  524
  525
  526
  527
  528
  529
  530
  531
  532
  533
  534
  535
  536
  537
  538
  539
  540
  541
  542
  543
  544
  545
  546
  547
  548
  549
  550
  551
  552
  553
  554
  555
  556
  557
  558
  559
  560
  561
  562
  563
  564
  565
  566
  567
  568
  569
  570
  571
  572
  573
  574
  575
  576
  577
  578
  579
  580
  581
  582
  583
  584
  585
  586
  587
  588
  589
  590
  591
  592
  593
  594
  595
  596
  597
  598
  599
  600
  601
  602
  603
  604
  605
  606
  607
  608
  609
  610
  611
  612
  613
  614
  615
  616
  617
  618
  619
  620
  621
  622
  623
  624
  625
  626
  627
  628
  629
  630
  631
  632
  633
  634
  635
  636
  637
  638
  639
  640
  641
  642
  643
  644
  645
  646
  647
  648
  649
  650
  651
  652
  653
  654
  655
  656
  657
  658
  659
  660
  661
  662
  663
  664
  665
  666
  667
  668
  669
  670
  671
  672
  673
  674
  675
  676
  677
  678
  679
  680
  681
  682
  683
  684
  685
  686
  687
  688
  689
  690
  691
  692
  693
  694
  695
  696
  697
  698
  699
  700
  701
  702
  703
  704
  705
  706
  707
  708
  709
  710
  711
  712
  713
  714
  715
  716
  717
  718
  719
  720
  721
  722
  723
  724
  725
  726
  727
  728
  729
  730
  731
  732
  733
  734
  735
  736
  737
  738
  739
  740
  741
  742
  743

android_webview / browser / gfx / browser_view_renderer_unittest.cc [blame]

// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "android_webview/browser/gfx/browser_view_renderer.h"

#include <map>
#include <memory>
#include <queue>
#include <utility>

#include "android_webview/browser/gfx/child_frame.h"
#include "android_webview/browser/gfx/compositor_frame_consumer.h"
#include "android_webview/browser/gfx/render_thread_manager.h"
#include "android_webview/browser/gfx/test/rendering_test.h"
#include "base/functional/bind.h"
#include "base/location.h"
#include "base/task/single_thread_task_runner.h"
#include "components/viz/common/quads/compositor_frame.h"
#include "components/viz/common/surfaces/frame_sink_id.h"
#include "content/public/test/test_synchronous_compositor_android.h"

namespace android_webview {

class SmokeTest : public RenderingTest {
  void StartTest() override {
    browser_view_renderer_->PostInvalidate(ActiveCompositor());
  }

  void DidDrawOnRT() override { EndTest(); }
};

RENDERING_TEST_F(SmokeTest);

// Test the case where SynchronousCompositor is constructed after the RVH that
// owns it is switched to be active.
class ActiveCompositorSwitchBeforeConstructionTest : public RenderingTest {
 public:
  ActiveCompositorSwitchBeforeConstructionTest()
      : on_draw_count_(0), new_compositor_(nullptr) {}
  void StartTest() override {
    browser_view_renderer_->PostInvalidate(ActiveCompositor());
  }

  void DidOnDraw(bool success) override {
    on_draw_count_++;
    switch (on_draw_count_) {
      case 1:
        EXPECT_TRUE(success);
        // Change compositor here. And do another ondraw.
        // The previous active compositor id is 1, 0, now change it to 1, 1.
        browser_view_renderer_->SetActiveFrameSinkId(viz::FrameSinkId(1, 1));
        browser_view_renderer_->PostInvalidate(ActiveCompositor());
        break;
      case 2:
        // The 2nd ondraw is skipped because there is no active compositor at
        // the moment.
        EXPECT_FALSE(success);
        new_compositor_ = std::make_unique<content::TestSynchronousCompositor>(
            viz::FrameSinkId(1, 1));
        new_compositor_->SetClient(browser_view_renderer_.get());
        EXPECT_EQ(ActiveCompositor(), new_compositor_.get());
        browser_view_renderer_->PostInvalidate(ActiveCompositor());
        break;
      case 3:
        EXPECT_TRUE(success);
        compositor_ = std::move(new_compositor_);

        EXPECT_EQ(ActiveCompositor(), compositor_.get());
        browser_view_renderer_->PostInvalidate(ActiveCompositor());
        break;
      case 4:
        EXPECT_TRUE(success);
        EndTest();
    }
  }

 private:
  int on_draw_count_;
  std::unique_ptr<content::TestSynchronousCompositor> new_compositor_;
};

RENDERING_TEST_F(ActiveCompositorSwitchBeforeConstructionTest);

// Test the case where SynchronousCompositor is constructed before the RVH that
// owns it is switched to be active.
class ActiveCompositorSwitchAfterConstructionTest : public RenderingTest {
 public:
  ActiveCompositorSwitchAfterConstructionTest()
      : on_draw_count_(0), new_compositor_(nullptr) {}
  void StartTest() override {
    browser_view_renderer_->PostInvalidate(ActiveCompositor());
  }

  void DidOnDraw(bool success) override {
    on_draw_count_++;
    switch (on_draw_count_) {
      case 1:
        EXPECT_TRUE(success);
        // Create a new compositor here. And switch it to be active.  And then
        // do another ondraw.
        new_compositor_ = std::make_unique<content::TestSynchronousCompositor>(
            viz::FrameSinkId(1, 1));
        new_compositor_->SetClient(browser_view_renderer_.get());
        browser_view_renderer_->SetActiveFrameSinkId(viz::FrameSinkId(1, 1));

        EXPECT_EQ(ActiveCompositor(), new_compositor_.get());
        browser_view_renderer_->PostInvalidate(ActiveCompositor());
        break;
      case 2:
        EXPECT_TRUE(success);
        compositor_ = std::move(new_compositor_);

        EXPECT_EQ(ActiveCompositor(), compositor_.get());
        browser_view_renderer_->PostInvalidate(ActiveCompositor());
        break;
      case 3:
        EXPECT_TRUE(success);
        EndTest();
    }
  }

 private:
  int on_draw_count_;
  std::unique_ptr<content::TestSynchronousCompositor> new_compositor_;
};

RENDERING_TEST_F(ActiveCompositorSwitchAfterConstructionTest);

class ClearViewTest : public RenderingTest {
 public:
  ClearViewTest() : on_draw_count_(0) {}

  void StartTest() override {
    browser_view_renderer_->PostInvalidate(ActiveCompositor());
    browser_view_renderer_->ClearView();
  }

  void DidOnDraw(bool success) override {
    on_draw_count_++;
    if (on_draw_count_ == 1) {
      // First OnDraw should be skipped due to ClearView.
      EXPECT_FALSE(success);
      browser_view_renderer_->DidUpdateContent(
          ActiveCompositor());  // Unset ClearView.
      browser_view_renderer_->PostInvalidate(ActiveCompositor());
    } else {
      // Following OnDraws should succeed.
      EXPECT_TRUE(success);
    }
  }

  void DidDrawOnRT() override { EndTest(); }

 private:
  int on_draw_count_;
};

RENDERING_TEST_F(ClearViewTest);

class TestAnimateInAndOutOfScreen : public RenderingTest {
 public:
  TestAnimateInAndOutOfScreen() : on_draw_count_(0), draw_gl_count_on_rt_(0) {}

  void StartTest() override {
    initial_constraints_ = ParentCompositorDrawConstraints(
        window_->surface_size(), gfx::Transform());
    new_constraints_ = ParentCompositorDrawConstraints(window_->surface_size(),
                                                       gfx::Transform());
    new_constraints_.transform.Scale(2.0, 2.0);
    browser_view_renderer_->PostInvalidate(ActiveCompositor());
  }

  void WillOnDraw() override {
    RenderingTest::WillOnDraw();
    // Step 0: A single onDraw on screen. The parent draw constraints
    // of the BVR will updated to be the initial constraints.
    // Step 1: A single onDrraw off screen. The parent draw constraints of the
    // BVR will be updated to the new constraints.
    // Step 2: This onDraw is to introduce the DrawGL that animates the
    // webview onto the screen on render thread. End the test when the parent
    // draw constraints of BVR is updated to initial constraints.
    if (on_draw_count_ == 1 || on_draw_count_ == 2)
      browser_view_renderer_->PrepareToDraw(gfx::Point(), gfx::Rect());
  }

  void DidOnDraw(bool success) override {
    EXPECT_TRUE(success);
    on_draw_count_++;
  }

  bool WillDrawOnRT(HardwareRendererDrawParams* params) override {
    if (draw_gl_count_on_rt_ == 1) {
      draw_gl_count_on_rt_++;
      ui_task_runner_->PostTask(
          FROM_HERE,
          base::BindOnce(&RenderingTest::PostInvalidate, base::Unretained(this),
                         /*inside_vsync=*/false));
      return false;
    }

    params->width = window_->surface_size().width();
    params->height = window_->surface_size().height();

    gfx::Transform transform;
    if (draw_gl_count_on_rt_ == 0)
      transform = new_constraints_.transform;

    transform.GetColMajorF(params->transform);
    return true;
  }

  void DidDrawOnRT() override { draw_gl_count_on_rt_++; }

  bool DrawConstraintsEquals(
      const ParentCompositorDrawConstraints& constraints1,
      const ParentCompositorDrawConstraints& constraints2) {
    return constraints1 == constraints2;
  }

  void OnParentDrawDataUpdated() override {
    ParentCompositorDrawConstraints constraints;
    viz::FrameSinkId frame_sink_id;
    viz::FrameTimingDetailsMap timing_details;
    uint32_t frame_token = 0u;
    base::TimeDelta preferred_frame_interval;
    GetCompositorFrameConsumer()->TakeParentDrawDataOnUI(
        &constraints, &frame_sink_id, &timing_details, &frame_token,
        &preferred_frame_interval);
    switch (on_draw_count_) {
      case 0u:
        // This OnParentDrawDataUpdated is generated by
        // connecting the compositor frame consumer to the producer.
        break;
      case 1u:
        EXPECT_TRUE(DrawConstraintsEquals(constraints, new_constraints_));
        break;
      case 3u:
        EXPECT_TRUE(DrawConstraintsEquals(constraints, initial_constraints_));
        EndTest();
        break;
      // There will be a following 4th onDraw. But the hardware renderer won't
      // post back the draw constraints in DrawGL because the constraints
      // don't change.
      default:
        FAIL();
    }
  }

 private:
  int on_draw_count_;
  int draw_gl_count_on_rt_;
  ParentCompositorDrawConstraints initial_constraints_;
  ParentCompositorDrawConstraints new_constraints_;
};

RENDERING_TEST_F(TestAnimateInAndOutOfScreen);

class TestAnimateOnScreenWithoutOnDraw : public RenderingTest {
 public:
  void StartTest() override {
    browser_view_renderer_->PostInvalidate(ActiveCompositor());
  }

  void WillOnDraw() override {
    RenderingTest::WillOnDraw();
    // Set empty tile viewport on first frame.
    browser_view_renderer_->PrepareToDraw(gfx::Point(), gfx::Rect());
  }

  void DidOnDraw(bool success) override {
    EXPECT_TRUE(success);
    on_draw_count_++;
  }

  bool WillDrawOnRT(HardwareRendererDrawParams* params) override {
    will_draw_on_rt_count_++;
    // What happens in practice is draw functor is skipped initially since
    // it is offscreen so entirely clipped. Then later, the webview is moved
    // onscreen without another OnDrawon UI thread, and draw functor is called
    // with non-empty clip. Here in the test we pretend this second draw happens
    // immediately.
    bool result = RenderingTest::WillDrawOnRT(params);
    assertNonEmptyClip(params);
    return result;
  }

  void OnParentDrawDataUpdated() override {
    switch (on_draw_count_) {
      case 0:
        // This OnParentDrawDataUpdated is generated by
        // connecting the compositor frame consumer to the producer.
        break;
      case 1:
        // DrawOnRT skipped for frame 1 so this should not happen.
        EXPECT_TRUE(window_->on_draw_hardware_pending());
        EndTest();
        break;
      case 2:
        // Might happen due to invalidate on_draw_hardware_pending from
        // previous frame.
        break;
      default:
        FAIL();
    }
  }

 private:
  void assertNonEmptyClip(HardwareRendererDrawParams* params) {
    gfx::Rect clip(params->clip_left, params->clip_top,
                   params->clip_right - params->clip_left,
                   params->clip_bottom - params->clip_top);
    ASSERT_FALSE(clip.IsEmpty());
  }

  int on_draw_count_ = 0;
  int will_draw_on_rt_count_ = 0;
};

RENDERING_TEST_F(TestAnimateOnScreenWithoutOnDraw);

class CompositorNoFrameTest : public RenderingTest {
 public:
  CompositorNoFrameTest() : on_draw_count_(0) {}

  void StartTest() override {
    browser_view_renderer_->PostInvalidate(ActiveCompositor());
  }

  void WillOnDraw() override {
    if (0 == on_draw_count_) {
      // No frame from compositor.
    } else if (1 == on_draw_count_) {
      compositor_->SetHardwareFrame(0u, ConstructEmptyFrame());
    } else if (2 == on_draw_count_) {
      // No frame from compositor.
    }
    // There may be trailing invalidates.
  }

  void DidOnDraw(bool success) override {
    // OnDraw should succeed even when there are no frames from compositor.
    EXPECT_TRUE(success);
    if (0 == on_draw_count_) {
      browser_view_renderer_->PostInvalidate(ActiveCompositor());
    } else if (1 == on_draw_count_) {
      browser_view_renderer_->PostInvalidate(ActiveCompositor());
    } else if (2 == on_draw_count_) {
      EndTest();
    }
    on_draw_count_++;
  }

 private:
  int on_draw_count_;
};

RENDERING_TEST_F(CompositorNoFrameTest);

class ClientIsVisibleOnConstructionTest : public RenderingTest {
  void SetUpTestHarness() override {
    browser_view_renderer_ = std::make_unique<BrowserViewRenderer>(
        this, base::SingleThreadTaskRunner::GetCurrentDefault(),
        base::SingleThreadTaskRunner::GetCurrentDefault());
  }

  void StartTest() override {
    EXPECT_FALSE(browser_view_renderer_->attached_to_window());
    EXPECT_FALSE(browser_view_renderer_->window_visible_for_tests());
    EXPECT_TRUE(browser_view_renderer_->IsClientVisible());
    EndTest();
  }
};

RENDERING_TEST_F(ClientIsVisibleOnConstructionTest);

class ClientIsVisibleAfterAttachTest : public RenderingTest {
  void StartTest() override {
    EXPECT_TRUE(browser_view_renderer_->attached_to_window());
    EXPECT_TRUE(browser_view_renderer_->window_visible_for_tests());

    EXPECT_TRUE(browser_view_renderer_->IsClientVisible());
    EndTest();
  }
};

RENDERING_TEST_F(ClientIsVisibleAfterAttachTest);

class ClientIsInvisibleAfterWindowGoneTest : public RenderingTest {
  void StartTest() override {
    browser_view_renderer_->SetWindowVisibility(false);
    EXPECT_FALSE(browser_view_renderer_->IsClientVisible());
    EndTest();
  }
};

RENDERING_TEST_F(ClientIsInvisibleAfterWindowGoneTest);

class ClientIsInvisibleAfterDetachTest : public RenderingTest {
  void StartTest() override {
    browser_view_renderer_->OnDetachedFromWindow();
    EXPECT_FALSE(browser_view_renderer_->IsClientVisible());
    EndTest();
  }
};

RENDERING_TEST_F(ClientIsInvisibleAfterDetachTest);

class ResourceRenderingTest : public RenderingTest {
 public:
  using ResourceCountMap = std::map<viz::ResourceId, int>;
  using LayerTreeFrameSinkResourceCountMap =
      std::map<uint32_t, ResourceCountMap>;

  virtual std::unique_ptr<content::SynchronousCompositor::Frame> GetFrame(
      int frame_number) = 0;

  void StartTest() override {
    frame_number_ = 0;
    AdvanceFrame();
  }

  void WillOnDraw() override {
    if (next_frame_) {
      compositor_->SetHardwareFrame(next_frame_->layer_tree_frame_sink_id,
                                    std::move(next_frame_->frame));
    }
  }

  void DidOnDraw(bool success) override {
    EXPECT_EQ(next_frame_ != nullptr, success);
    if (!AdvanceFrame()) {
      ui_task_runner_->PostTask(
          FROM_HERE, base::BindOnce(&ResourceRenderingTest::CheckResults,
                                    base::Unretained(this)));
    }
  }

  LayerTreeFrameSinkResourceCountMap GetReturnedResourceCounts() {
    LayerTreeFrameSinkResourceCountMap counts;
    content::TestSynchronousCompositor::FrameAckArray returned_resources_array;
    compositor_->SwapReturnedResources(&returned_resources_array);
    for (const auto& resources : returned_resources_array) {
      for (const auto& returned_resource : resources.resources) {
        counts[resources.layer_tree_frame_sink_id][returned_resource.id] +=
            returned_resource.count;
      }
    }
    return counts;
  }

  virtual void CheckResults() = 0;

 private:
  bool AdvanceFrame() {
    next_frame_ = GetFrame(frame_number_++);
    if (next_frame_) {
      browser_view_renderer_->PostInvalidate(ActiveCompositor());
      return true;
    }
    return false;
  }

  std::unique_ptr<content::SynchronousCompositor::Frame> next_frame_;
  int frame_number_;
};

class SwitchLayerTreeFrameSinkIdTest : public ResourceRenderingTest {
  struct FrameInfo {
    FrameInfo(uint32_t frame_sink_id, viz::ResourceId id)
        : layer_tree_frame_sink_id(frame_sink_id), resource_id(id) {}

    uint32_t layer_tree_frame_sink_id;
    viz::ResourceId resource_id;  // Each frame contains a single resource.
  };

  std::unique_ptr<content::SynchronousCompositor::Frame> GetFrame(
      int frame_number) override {
    static const FrameInfo infos[] = {
        // First output surface.
        {0u, viz::ResourceId(1u)},
        {0u, viz::ResourceId(1u)},
        {0u, viz::ResourceId(2u)},
        {0u, viz::ResourceId(2u)},
        {0u, viz::ResourceId(3u)},
        {0u, viz::ResourceId(3u)},
        {0u, viz::ResourceId(4u)},
        // Second output surface.
        {1u, viz::ResourceId(1u)},
        {1u, viz::ResourceId(1u)},
        {1u, viz::ResourceId(2u)},
        {1u, viz::ResourceId(2u)},
        {1u, viz::ResourceId(3u)},
        {1u, viz::ResourceId(3u)},
        {1u, viz::ResourceId(4u)},
    };
    if (frame_number >= static_cast<int>(std::size(infos))) {
      return nullptr;
    }

    std::unique_ptr<content::SynchronousCompositor::Frame> frame(
        new content::SynchronousCompositor::Frame);
    frame->layer_tree_frame_sink_id =
        infos[frame_number].layer_tree_frame_sink_id;
    frame->frame = ConstructFrame(infos[frame_number].resource_id);

    if (last_layer_tree_frame_sink_id_ !=
        infos[frame_number].layer_tree_frame_sink_id) {
      expected_return_count_.clear();
      last_layer_tree_frame_sink_id_ =
          infos[frame_number].layer_tree_frame_sink_id;
    }
    ++expected_return_count_[infos[frame_number].resource_id];
    return frame;
  }

  void StartTest() override {
    last_layer_tree_frame_sink_id_ = -1U;
    ResourceRenderingTest::StartTest();
  }

  void CheckResults() override {
    window_->Detach();
    functor_->ReleaseOnUIWithInvoke();
    ui_task_runner_->PostTask(
        FROM_HERE,
        base::BindOnce(&SwitchLayerTreeFrameSinkIdTest::PostedCheckResults,
                       base::Unretained(this)));
  }

  void PostedCheckResults() {
    // Make sure resources for the last output surface are returned.
    EXPECT_EQ(expected_return_count_,
              GetReturnedResourceCounts()[last_layer_tree_frame_sink_id_]);
    EndTest();
  }

 private:
  uint32_t last_layer_tree_frame_sink_id_;
  ResourceCountMap expected_return_count_;
};

RENDERING_TEST_F(SwitchLayerTreeFrameSinkIdTest);

class RenderThreadManagerDeletionTest : public ResourceRenderingTest {
  std::unique_ptr<content::SynchronousCompositor::Frame> GetFrame(
      int frame_number) override {
    if (frame_number > 0) {
      return nullptr;
    }

    const uint32_t layer_tree_frame_sink_id = 0u;
    const viz::ResourceId resource_id =
        static_cast<viz::ResourceId>(frame_number);

    std::unique_ptr<content::SynchronousCompositor::Frame> frame(
        new content::SynchronousCompositor::Frame);
    frame->layer_tree_frame_sink_id = layer_tree_frame_sink_id;
    frame->frame = ConstructFrame(resource_id);
    ++expected_return_count_[layer_tree_frame_sink_id][resource_id];
    return frame;
  }

  void CheckResults() override {
    functor_.reset();
    ui_task_runner_->PostTask(
        FROM_HERE,
        base::BindOnce(&RenderThreadManagerDeletionTest::PostedCheckResults,
                       base::Unretained(this)));
  }

  void PostedCheckResults() {
    // Make sure resources for the last frame are returned.
    EXPECT_EQ(expected_return_count_, GetReturnedResourceCounts());
    EndTest();
  }

 private:
  LayerTreeFrameSinkResourceCountMap expected_return_count_;
};

RENDERING_TEST_F(RenderThreadManagerDeletionTest);

class RenderThreadManagerDeletionOnRTTest : public ResourceRenderingTest {
  std::unique_ptr<content::SynchronousCompositor::Frame> GetFrame(
      int frame_number) override {
    if (frame_number > 0) {
      return nullptr;
    }

    const uint32_t layer_tree_frame_sink_id = 0u;
    const viz::ResourceId resource_id =
        static_cast<viz::ResourceId>(frame_number);

    std::unique_ptr<content::SynchronousCompositor::Frame> frame(
        new content::SynchronousCompositor::Frame);
    frame->layer_tree_frame_sink_id = layer_tree_frame_sink_id;
    frame->frame = ConstructFrame(resource_id);
    ++expected_return_count_[layer_tree_frame_sink_id][resource_id];
    return frame;
  }

  void CheckResults() override {
    functor_->ReleaseOnUIWithoutInvoke(
        base::BindOnce(&RenderThreadManagerDeletionOnRTTest::PostedCheckResults,
                       base::Unretained(this)));
  }

  void PostedCheckResults() {
    // Make sure resources for the last frame are returned.
    EXPECT_EQ(expected_return_count_, GetReturnedResourceCounts());
    EndTest();
  }

 private:
  LayerTreeFrameSinkResourceCountMap expected_return_count_;
};

RENDERING_TEST_F(RenderThreadManagerDeletionOnRTTest);

class RenderThreadManagerSwitchTest : public ResourceRenderingTest {
  std::unique_ptr<content::SynchronousCompositor::Frame> GetFrame(
      int frame_number) override {
    switch (frame_number) {
      case 0: {
        // Draw a frame with initial RTM.
        break;
      }
      case 1: {
        // Switch to new RTM.
        std::unique_ptr<FakeFunctor> functor(new FakeFunctor);
        functor->Init(window_.get(),
                      std::make_unique<RenderThreadManager>(
                          base::SingleThreadTaskRunner::GetCurrentDefault()));
        browser_view_renderer_->SetCurrentCompositorFrameConsumer(
            functor->GetCompositorFrameConsumer());
        saved_functor_ = std::move(functor_);
        functor_ = std::move(functor);
        break;
      }
      case 2: {
        // Draw a frame with the new RTM, but also redraw the initial RTM.
        window_->RequestDrawGL(saved_functor_.get());
        break;
      }
      case 3: {
        // Switch back to the initial RTM, allowing the new RTM to be destroyed.
        functor_ = std::move(saved_functor_);
        browser_view_renderer_->SetCurrentCompositorFrameConsumer(
            functor_->GetCompositorFrameConsumer());
        break;
      }
      default:
        return nullptr;
    }

    const uint32_t layer_tree_frame_sink_id = 0u;
    const viz::ResourceId resource_id =
        static_cast<viz::ResourceId>(frame_number);

    std::unique_ptr<content::SynchronousCompositor::Frame> frame(
        new content::SynchronousCompositor::Frame);
    frame->layer_tree_frame_sink_id = layer_tree_frame_sink_id;
    frame->frame = ConstructFrame(resource_id);
    ++expected_return_count_[layer_tree_frame_sink_id][resource_id];
    return frame;
  }

  void CheckResults() override {
    functor_.reset();
    ui_task_runner_->PostTask(
        FROM_HERE,
        base::BindOnce(&RenderThreadManagerSwitchTest::PostedCheckResults,
                       base::Unretained(this)));
  }

  void PostedCheckResults() {
    // Make sure resources for all frames are returned.
    EXPECT_EQ(expected_return_count_, GetReturnedResourceCounts());
    EndTest();
  }

 private:
  std::unique_ptr<FakeFunctor> saved_functor_;
  LayerTreeFrameSinkResourceCountMap expected_return_count_;
};

RENDERING_TEST_F(RenderThreadManagerSwitchTest);

// Test for https://crbug.com/881458, this test is to make sure we will reach
// the maximal scroll offset.
class DidReachMaximalScrollOffsetTest : public RenderingTest {
 public:
  void StartTest() override {
    browser_view_renderer_->SetDipScale(kDipScale);
    gfx::PointF total_scroll_offset = kTotalScrollOffset;
    gfx::PointF total_max_scroll_offset = kTotalMaxScrollOffset;
    gfx::SizeF scrollable_size = kScrollableSize;
    total_scroll_offset.Scale(kDipScale);
    total_max_scroll_offset.Scale(kDipScale);
    scrollable_size.Scale(kDipScale);
    // |UpdateRootLayerState()| will call |SetTotalRootLayerScrollOffset()|.
    browser_view_renderer_->UpdateRootLayerState(
        ActiveCompositor(), total_scroll_offset, total_max_scroll_offset,
        scrollable_size, kPageScaleFactor, kMinPageScaleFactor,
        kMaxPageScaleFactor);
  }

  void ScrollContainerViewTo(const gfx::Point& new_value) override {
    EXPECT_EQ(kExpectedScrollOffset, new_value);
    EndTest();
  }

 private:
  static constexpr float kDipScale = 2.625f;
  static const gfx::PointF kTotalScrollOffset;
  static const gfx::PointF kTotalMaxScrollOffset;
  static const gfx::SizeF kScrollableSize;
  static constexpr float kPageScaleFactor = 1.f;
  // These two are not used in this test.
  static constexpr float kMinPageScaleFactor = 1.f;
  static constexpr float kMaxPageScaleFactor = 5.f;

  static const gfx::Point kExpectedScrollOffset;
};

// The current scroll offset in logical pixel, which is at the end.
const gfx::PointF DidReachMaximalScrollOffsetTest::kTotalScrollOffset =
    gfx::PointF(0.f, 6132.f);
// The maximum possible scroll offset in logical pixel.
const gfx::PointF DidReachMaximalScrollOffsetTest::kTotalMaxScrollOffset =
    gfx::PointF(0.f, 6132.f);
// This is what passed to CTS test, not used for this test.
const gfx::SizeF DidReachMaximalScrollOffsetTest::kScrollableSize =
    gfx::SizeF(412.f, 6712.f);
// In max_scroll_offset() we are using ceiling rounding for scaled scroll
// offset. Therefore ceiling(2.625 * 6132 = 16096.5) = 16097.
const gfx::Point DidReachMaximalScrollOffsetTest::kExpectedScrollOffset =
    gfx::Point(0, 16097);

RENDERING_TEST_F(DidReachMaximalScrollOffsetTest);

}  // namespace android_webview