fuchsia: Improve FakeSession & add tests (flutter/engine#28139)

This commit is contained in:
David Worsham
2021-08-26 13:16:02 -07:00
committed by GitHub
parent 6239e74b25
commit 341a0f2f24
7 changed files with 2537 additions and 29 deletions

View File

@@ -463,6 +463,7 @@ executable("flutter_runner_unittests") {
"platform_view_unittest.cc",
"runner_unittest.cc",
"tests/engine_unittests.cc",
"tests/fake_session_unittests.cc",
"tests/flutter_runner_product_configuration_unittests.cc",
"tests/gfx_session_connection_unittests.cc",
]

View File

@@ -0,0 +1,459 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "fakes/scenic/fake_session.h"
#include <fuchsia/ui/scenic/cpp/fidl.h>
#include <fuchsia/ui/views/cpp/fidl.h>
#include <lib/async-testing/test_loop.h>
#include <lib/async/dispatcher.h>
#include <lib/ui/scenic/cpp/resources.h>
#include <lib/ui/scenic/cpp/session.h>
#include <lib/ui/scenic/cpp/view_ref_pair.h>
#include <lib/ui/scenic/cpp/view_token_pair.h>
#include <zircon/types.h>
#include <memory>
#include <string>
#include <type_traits>
#include <vector>
#include "flutter/fml/logging.h"
#include "gmock/gmock.h" // For EXPECT_THAT and matchers
#include "gtest/gtest.h"
#include "fakes/scenic/fake_resources.h"
using ::testing::_;
using ::testing::AllOf;
using ::testing::ElementsAre;
using ::testing::FieldsAre;
using ::testing::IsEmpty;
using ::testing::Matcher;
using ::testing::Not;
using ::testing::Pair;
using ::testing::Pointee;
using ::testing::SizeIs;
using ::testing::VariantWith;
namespace flutter_runner::testing {
namespace {
std::string GetCurrentTestName() {
return ::testing::UnitTest::GetInstance()->current_test_info()->name();
}
zx_koid_t GetKoid(zx_handle_t handle) {
if (handle == ZX_HANDLE_INVALID) {
return ZX_KOID_INVALID;
}
zx_info_handle_basic_t info;
zx_status_t status = zx_object_get_info(handle, ZX_INFO_HANDLE_BASIC, &info,
sizeof(info), nullptr, nullptr);
return status == ZX_OK ? info.koid : ZX_KOID_INVALID;
}
zx_koid_t GetPeerKoid(zx_handle_t handle) {
if (handle == ZX_HANDLE_INVALID) {
return ZX_KOID_INVALID;
}
zx_info_handle_basic_t info;
zx_status_t status = zx_object_get_info(handle, ZX_INFO_HANDLE_BASIC, &info,
sizeof(info), nullptr, nullptr);
return status == ZX_OK ? info.related_koid : ZX_KOID_INVALID;
}
Matcher<FakeResource> IsEntityNode(
Matcher<decltype(FakeResource::id)> id,
Matcher<decltype(FakeResource::label)> label,
Matcher<decltype(FakeNode::children)> children) {
return FieldsAre(
id, label, FakeResource::kDefaultEmptyEventMask,
VariantWith<FakeEntityNode>(FieldsAre(
FieldsAre(children, FakeNode::kDefaultZeroRotation,
FakeNode::kDefaultOneScale,
FakeNode::kDefaultZeroTranslation,
FakeNode::kDefaultZeroAnchor, FakeNode::kIsHitTestable,
FakeNode::kIsSemanticallyVisible),
IsEmpty())));
}
Matcher<FakeSceneGraph> IsEmptySceneGraph() {
return FieldsAre(IsEmpty(), IsEmpty(), IsEmpty(), kInvalidFakeResourceId);
}
MATCHER_P5(IsBasicSceneGraph,
debug_label,
node_label,
view_holder_koid,
view_ref_control_koid,
view_ref_koid,
"") {
static_assert(std::is_same_v<FakeSceneGraph, std::decay_t<decltype(arg)>>);
static_assert(
std::is_same_v<std::string, std::decay_t<decltype(debug_label)>>);
static_assert(
std::is_same_v<std::string, std::decay_t<decltype(node_label)>>);
static_assert(
std::is_same_v<zx_koid_t, std::decay_t<decltype(view_holder_koid)>>);
static_assert(
std::is_same_v<zx_koid_t, std::decay_t<decltype(view_ref_control_koid)>>);
static_assert(
std::is_same_v<zx_koid_t, std::decay_t<decltype(view_ref_koid)>>);
return ExplainMatchResult(
FieldsAre(
IsEmpty(),
AllOf(SizeIs(2u),
Contains(Pair(arg.root_view_id,
Pointee(FieldsAre(
arg.root_view_id, "",
FakeResource::kDefaultEmptyEventMask,
VariantWith<FakeView>(FieldsAre(
view_holder_koid, view_ref_control_koid,
view_ref_koid, debug_label,
ElementsAre(Pointee(IsEntityNode(
_, node_label, IsEmpty()))),
FakeView::kDebugBoundsDisbaled))))))),
_, AllOf(Not(kInvalidFakeResourceId), arg.root_view_id)),
arg, result_listener);
}
} // namespace
class FakeSessionTest : public ::testing::Test,
public fuchsia::ui::scenic::SessionListener {
protected:
FakeSessionTest()
: session_listener_(this), session_subloop_(loop_.StartNewLoop()) {}
~FakeSessionTest() override = default;
async::TestLoop& loop() { return loop_; }
FakeSession& fake_session() { return fake_session_; }
scenic::Session CreateSession() {
FML_CHECK(!fake_session_.is_bound());
FML_CHECK(!session_listener_.is_bound());
auto [session, session_listener] =
fake_session_.Bind(session_subloop_->dispatcher());
session_listener_.Bind(std::move(session_listener));
return scenic::Session(session.Bind());
}
private:
// |fuchsia::ui::scenic::SessionListener|
void OnScenicError(std::string error) override { FML_CHECK(false); }
// |fuchsia::ui::scenic::SessionListener|
void OnScenicEvent(std::vector<fuchsia::ui::scenic::Event> events) override {
FML_CHECK(false);
}
async::TestLoop loop_; // Must come before FIDL bindings.
fuchsia::ui::scenic::SessionPtr session_ptr_;
fidl::Binding<fuchsia::ui::scenic::SessionListener> session_listener_;
std::unique_ptr<async::LoopInterface> session_subloop_;
FakeSession fake_session_;
};
TEST_F(FakeSessionTest, Initialization) {
EXPECT_EQ(fake_session().debug_name(), "");
EXPECT_EQ(fake_session().command_queue().size(), 0u);
EXPECT_THAT(fake_session().SceneGraph(), IsEmptySceneGraph());
// Pump the loop one time; the session should retain its initial state.
loop().RunUntilIdle();
EXPECT_EQ(fake_session().debug_name(), "");
EXPECT_EQ(fake_session().command_queue().size(), 0u);
EXPECT_THAT(fake_session().SceneGraph(), IsEmptySceneGraph());
}
TEST_F(FakeSessionTest, DebugLabel) {
const std::string debug_label = GetCurrentTestName();
scenic::Session session = CreateSession();
// Set the session's debug name. The `SetDebugName` hasn't been processed
// yet, so the session's view of the debug name is still empty.
session.SetDebugName(debug_label);
EXPECT_EQ(fake_session().debug_name(), "");
// Pump the loop; the contents of the initial `SetDebugName` should be
// processed.
loop().RunUntilIdle();
EXPECT_EQ(fake_session().debug_name(), debug_label);
}
TEST_F(FakeSessionTest, SimpleResourceLifecycle) {
const std::string node_label = "EntityNode";
scenic::Session session = CreateSession();
// Create entity node for testing; no creation commands have been processed
// yet, so the session's view of the scene graph is empty.
std::optional<scenic::EntityNode> node(&session);
EXPECT_EQ(fake_session().command_queue().size(), 0u);
EXPECT_THAT(fake_session().SceneGraph(), IsEmptySceneGraph());
// Pump the loop; the initial creation command should be enqueued but still
// not processed yet, so the session's view of the scene graph is empty.
loop().RunUntilIdle();
EXPECT_GE(fake_session().command_queue().size(), 0u);
EXPECT_THAT(fake_session().SceneGraph(), IsEmptySceneGraph());
// Present initial scene graph. The `Present` hasn't been processed yet, so
// the session's view of the scene graph is still empty.
session.Present2(0u, 0u, [](auto...) {});
EXPECT_GE(fake_session().command_queue().size(), 0u);
EXPECT_THAT(fake_session().SceneGraph(), IsEmptySceneGraph());
// Pump the loop; the contents of the initial `Present` should be processed.
loop().RunUntilIdle();
EXPECT_EQ(fake_session().command_queue().size(), 0u);
{
auto scene_graph = fake_session().SceneGraph();
EXPECT_EQ(scene_graph.root_view_id, kInvalidFakeResourceId);
EXPECT_EQ(scene_graph.buffer_collection_map.size(), 0u);
EXPECT_EQ(scene_graph.resource_map.size(), 1u);
EXPECT_EQ(scene_graph.labels_map.size(), 1u);
ASSERT_EQ(scene_graph.labels_map.count(""), 1u);
const auto first_resource_it = scene_graph.resource_map.begin();
const auto null_label_resources = scene_graph.labels_map[""];
EXPECT_EQ(null_label_resources.size(), 1u);
EXPECT_FALSE(null_label_resources[0].expired());
EXPECT_EQ(null_label_resources[0].lock(), first_resource_it->second);
EXPECT_THAT(first_resource_it->second,
Pointee(IsEntityNode(_, "", IsEmpty())));
}
// Present a simple property update on the test entity node.
node->SetLabel(node_label);
session.Present2(0u, 0u, [](auto...) {});
loop().RunUntilIdle();
EXPECT_EQ(fake_session().command_queue().size(), 0u);
{
auto scene_graph = fake_session().SceneGraph();
EXPECT_EQ(scene_graph.root_view_id, kInvalidFakeResourceId);
EXPECT_EQ(scene_graph.buffer_collection_map.size(), 0u);
EXPECT_EQ(scene_graph.resource_map.size(), 1u);
EXPECT_EQ(scene_graph.labels_map.size(), 1u);
ASSERT_EQ(scene_graph.labels_map.count(""), 0u);
ASSERT_EQ(scene_graph.labels_map.count(node_label), 1u);
const auto first_resource_it = scene_graph.resource_map.begin();
const auto node_label_resources = scene_graph.labels_map[node_label];
EXPECT_EQ(node_label_resources.size(), 1u);
EXPECT_FALSE(node_label_resources[0].expired());
EXPECT_EQ(node_label_resources[0].lock(), first_resource_it->second);
EXPECT_THAT(first_resource_it->second,
Pointee(IsEntityNode(_, node_label, IsEmpty())));
}
// Present the destruction of the entity node.
node.reset();
session.Present2(0u, 0u, [](auto...) {});
loop().RunUntilIdle();
EXPECT_EQ(fake_session().command_queue().size(), 0u);
EXPECT_THAT(fake_session().SceneGraph(), IsEmptySceneGraph());
}
TEST_F(FakeSessionTest, ResourceReferenceCounting) {
const std::string node_label = "EntityNode";
scenic::Session session = CreateSession();
// Present a chain of 4 entity nodes for testing.
std::array<std::optional<scenic::EntityNode>, 4> nodes{
std::optional<scenic::EntityNode>(&session),
std::optional<scenic::EntityNode>(&session),
std::optional<scenic::EntityNode>(&session),
std::optional<scenic::EntityNode>(&session)};
for (size_t i = 0; i < 4; i++) {
nodes[i]->SetLabel(node_label + std::string(1, '0' + i));
if (i < 3) {
nodes[i]->AddChild(*nodes[i + 1]);
}
}
session.Present2(0u, 0u, [](auto...) {});
loop().RunUntilIdle();
{
auto scene_graph = fake_session().SceneGraph();
EXPECT_EQ(scene_graph.root_view_id, kInvalidFakeResourceId);
EXPECT_EQ(scene_graph.buffer_collection_map.size(), 0u);
EXPECT_EQ(scene_graph.resource_map.size(), 4u);
EXPECT_EQ(scene_graph.labels_map.size(), 4u);
for (size_t i = 0; i < 4; i++) {
const std::string node_i_label = node_label + std::string(1, '0' + i);
ASSERT_EQ(scene_graph.resource_map.count(nodes[i]->id()), 1u);
ASSERT_EQ(scene_graph.labels_map.count(node_i_label), 1u);
const auto node_i = scene_graph.resource_map[nodes[i]->id()];
const auto node_i_label_resources = scene_graph.labels_map[node_i_label];
EXPECT_EQ(node_i_label_resources.size(), 1u);
EXPECT_FALSE(node_i_label_resources[0].expired());
EXPECT_EQ(node_i_label_resources[0].lock(), node_i);
}
EXPECT_THAT(
scene_graph.resource_map[nodes[0]->id()],
Pointee(IsEntityNode(
nodes[0]->id(), node_label + std::string(1, '0'),
ElementsAre(Pointee(IsEntityNode(
nodes[1]->id(), node_label + std::string(1, '1'),
ElementsAre(Pointee(IsEntityNode(
nodes[2]->id(), node_label + std::string(1, '2'),
ElementsAre(Pointee(IsEntityNode(
nodes[3]->id(), node_label + std::string(1, '3'),
IsEmpty()))))))))))));
}
// Destroy node #0. It should be dropped immediately since it has no parent.
nodes[0].reset();
session.Present2(0u, 0u, [](auto...) {});
loop().RunUntilIdle();
{
auto scene_graph = fake_session().SceneGraph();
EXPECT_EQ(scene_graph.root_view_id, kInvalidFakeResourceId);
EXPECT_EQ(scene_graph.buffer_collection_map.size(), 0u);
EXPECT_EQ(scene_graph.resource_map.size(), 3u);
EXPECT_EQ(scene_graph.labels_map.size(), 3u);
for (size_t i = 1; i < 4; i++) {
const std::string node_i_label = node_label + std::string(1, '0' + i);
ASSERT_EQ(scene_graph.resource_map.count(nodes[i]->id()), 1u);
ASSERT_EQ(scene_graph.labels_map.count(node_i_label), 1u);
const auto node_i = scene_graph.resource_map[nodes[i]->id()];
const auto node_i_label_resources = scene_graph.labels_map[node_i_label];
EXPECT_EQ(node_i_label_resources.size(), 1u);
EXPECT_FALSE(node_i_label_resources[0].expired());
EXPECT_EQ(node_i_label_resources[0].lock(), node_i);
}
EXPECT_EQ(scene_graph.resource_map.count(nodes[0]->id()), 0u);
EXPECT_THAT(scene_graph.resource_map[nodes[1]->id()],
Pointee(IsEntityNode(
nodes[1]->id(), node_label + std::string(1, '1'),
ElementsAre(Pointee(IsEntityNode(
nodes[2]->id(), node_label + std::string(1, '2'),
ElementsAre(Pointee(IsEntityNode(
nodes[3]->id(), node_label + std::string(1, '3'),
IsEmpty())))))))));
}
// Destroy node #2. It should still exist in the tree and the labels map
// because it has a parent, but it is removed from the resource map.
nodes[2].reset();
session.Present2(0u, 0u, [](auto...) {});
loop().RunUntilIdle();
{
auto scene_graph = fake_session().SceneGraph();
EXPECT_EQ(scene_graph.root_view_id, kInvalidFakeResourceId);
EXPECT_EQ(scene_graph.buffer_collection_map.size(), 0u);
EXPECT_EQ(scene_graph.resource_map.size(), 2u);
EXPECT_EQ(scene_graph.labels_map.size(), 3u);
for (size_t i = 1; i < 4; i++) {
const std::string node_i_label = node_label + std::string(1, '0' + i);
ASSERT_EQ(scene_graph.labels_map.count(node_i_label), 1u);
ASSERT_EQ(scene_graph.resource_map.count(nodes[i]->id()),
i != 2 ? 1u : 0u);
const auto node_i_label_resources = scene_graph.labels_map[node_i_label];
EXPECT_EQ(node_i_label_resources.size(), 1u);
EXPECT_FALSE(node_i_label_resources[0].expired());
if (i != 2) {
const auto node_i = scene_graph.resource_map[nodes[i]->id()];
EXPECT_EQ(node_i_label_resources[0].lock(), node_i);
} else {
EXPECT_EQ(scene_graph.resource_map.count(nodes[i]->id()), 0u);
}
}
EXPECT_THAT(scene_graph.resource_map[nodes[1]->id()],
Pointee(IsEntityNode(
nodes[1]->id(), node_label + std::string(1, '1'),
ElementsAre(Pointee(IsEntityNode(
nodes[2]->id(), node_label + std::string(1, '2'),
ElementsAre(Pointee(IsEntityNode(
nodes[3]->id(), node_label + std::string(1, '3'),
IsEmpty())))))))));
}
// Destroy node #3. It should still exist in the tree and the labels map
// because it has a grand-parent, but it is removed from the resource map.
nodes[3].reset();
session.Present2(0u, 0u, [](auto...) {});
loop().RunUntilIdle();
{
auto scene_graph = fake_session().SceneGraph();
EXPECT_EQ(scene_graph.root_view_id, kInvalidFakeResourceId);
EXPECT_EQ(scene_graph.buffer_collection_map.size(), 0u);
EXPECT_EQ(scene_graph.resource_map.size(), 1u);
EXPECT_EQ(scene_graph.labels_map.size(), 3u);
for (size_t i = 1; i < 4; i++) {
const std::string node_i_label = node_label + std::string(1, '0' + i);
ASSERT_EQ(scene_graph.labels_map.count(node_i_label), 1u);
ASSERT_EQ(scene_graph.resource_map.count(nodes[i]->id()),
i < 2 ? 1u : 0u);
const auto node_i_label_resources = scene_graph.labels_map[node_i_label];
EXPECT_EQ(node_i_label_resources.size(), 1u);
EXPECT_FALSE(node_i_label_resources[0].expired());
if (i < 2) {
const auto node_i = scene_graph.resource_map[nodes[i]->id()];
EXPECT_EQ(node_i_label_resources[0].lock(), node_i);
} else {
EXPECT_EQ(scene_graph.resource_map.count(nodes[i]->id()), 0u);
}
}
EXPECT_THAT(scene_graph.resource_map[nodes[1]->id()],
Pointee(IsEntityNode(
nodes[1]->id(), node_label + std::string(1, '1'),
ElementsAre(Pointee(IsEntityNode(
nodes[2]->id(), node_label + std::string(1, '2'),
ElementsAre(Pointee(IsEntityNode(
nodes[3]->id(), node_label + std::string(1, '3'),
IsEmpty())))))))));
}
}
TEST_F(FakeSessionTest, BasicSceneGraph) {
const std::string debug_label = GetCurrentTestName();
const std::string node_label = "ChildNode";
scenic::Session session = CreateSession();
// Create and present initial scene graph. The `Present` hasn't been
// processed yet, so the session's view of the scene graph is still empty.
fuchsia::ui::views::ViewRef view_ref;
auto [view_token, view_holder_token] = scenic::ViewTokenPair::New();
auto view_ref_pair = scenic::ViewRefPair::New();
view_ref_pair.view_ref.Clone(&view_ref);
scenic::View root_view(&session, std::move(view_token),
std::move(view_ref_pair.control_ref),
std::move(view_ref_pair.view_ref), debug_label);
scenic::EntityNode child_node(&session);
child_node.SetLabel(node_label);
root_view.AddChild(child_node);
session.Present2(0u, 0u, [](auto...) {});
EXPECT_GE(fake_session().command_queue().size(), 0u);
EXPECT_THAT(fake_session().SceneGraph(), IsEmptySceneGraph());
// Pump the loop; the contents of the initial `Present` should be processed.
loop().RunUntilIdle();
EXPECT_EQ(fake_session().command_queue().size(), 0u);
EXPECT_THAT(fake_session().SceneGraph(),
IsBasicSceneGraph(debug_label, node_label,
GetPeerKoid(view_holder_token.value.get()),
GetPeerKoid(view_ref.reference.get()),
GetKoid(view_ref.reference.get())));
}
} // namespace flutter_runner::testing

View File

@@ -8,14 +8,19 @@ source_set("scenic") {
testonly = true
sources = [
"fake_resources.cc",
"fake_resources.h",
"fake_session.cc",
"fake_session.h",
]
public_deps = [
"//build/fuchsia/fidl:fuchsia.images",
"//build/fuchsia/fidl:fuchsia.scenic.scheduling",
"//build/fuchsia/fidl:fuchsia.ui.composition",
"//build/fuchsia/fidl:fuchsia.ui.gfx",
"//build/fuchsia/fidl:fuchsia.ui.scenic",
"//build/fuchsia/fidl:fuchsia.ui.views",
"//build/fuchsia/pkg:async-cpp",
"//build/fuchsia/pkg:async-testing",
"//build/fuchsia/pkg:fidl_cpp",

View File

@@ -0,0 +1,315 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "fake_resources.h"
#include "flutter/fml/logging.h"
namespace flutter_runner::testing {
namespace {
using FakeResourceCache =
std::unordered_map<FakeResourceState*, std::shared_ptr<FakeResource>>;
std::shared_ptr<FakeResource> ResourceFromState(
const std::shared_ptr<FakeResourceState>& resource,
FakeResourceCache& cache);
std::vector<std::shared_ptr<FakeResource>> ResourcesFromStates(
const std::vector<std::shared_ptr<FakeResourceState>>& resources,
FakeResourceCache& cache);
FakeNode NodeFromState(FakeNodeState* node, FakeResourceCache& cache) {
FML_CHECK(node);
return FakeNode{
.children = ResourcesFromStates(node->children, cache),
.rotation_quaternion = node->rotation_quaternion,
.scale_vector = node->scale_vector,
.translation_vector = node->translation_vector,
.anchor_vector = node->anchor_vector,
.hit_testable = node->hit_testable,
.semantically_visible = node->semantically_visible,
};
}
FakeEntityNode EntityNodeFromState(FakeEntityNodeState* entity_node,
FakeResourceCache& cache) {
FML_CHECK(entity_node);
// Convert clip planes.
std::vector<FakeEntityNode::ClipPlane> clip_planes;
for (auto& clip_plane : entity_node->clip_planes) {
clip_planes.emplace_back(FakeEntityNode::ClipPlane{
.dir = clip_plane.dir,
.dist = clip_plane.dist,
});
}
return FakeEntityNode{
.node_state = NodeFromState(&entity_node->node_state, cache),
.clip_planes = std::move(clip_planes),
};
}
FakeOpacityNode OpacityNodeFromState(FakeOpacityNodeState* opacity_node,
FakeResourceCache& cache) {
FML_CHECK(opacity_node);
return FakeOpacityNode{
.node_state = NodeFromState(&opacity_node->node_state, cache),
.opacity = opacity_node->opacity,
};
}
FakeShapeNode ShapeNodeFromState(FakeShapeNodeState* shape_node,
FakeResourceCache& cache) {
FML_CHECK(shape_node);
return FakeShapeNode{
.node_state = NodeFromState(&shape_node->node_state, cache),
.shape = ResourceFromState(shape_node->shape, cache),
.material = ResourceFromState(shape_node->material, cache),
};
}
FakeView ViewFromState(FakeViewState* view, FakeResourceCache& cache) {
FML_CHECK(view);
return FakeView{
.token = view->token.koid,
.control_ref = view->control_ref.koid,
.view_ref = view->view_ref.koid,
.debug_name = view->debug_name,
.children = ResourcesFromStates(view->children, cache),
.enable_debug_bounds = view->enable_debug_bounds,
};
}
FakeViewHolder ViewHolderFromState(FakeViewHolderState* view_holder,
FakeResourceCache& cache) {
FML_CHECK(view_holder);
return FakeViewHolder{
.token = view_holder->token.koid,
.debug_name = view_holder->debug_name,
.properties = view_holder->properties,
.bounds_color = view_holder->bounds_color,
};
}
FakeShape ShapeFromState(FakeShapeState* shape, FakeResourceCache& cache) {
FML_CHECK(shape);
auto snapshot = FakeShape{};
std::visit(
[&snapshot](auto&& shape_def) {
using T = std::decay_t<decltype(shape_def)>;
if constexpr (std::is_same_v<T, FakeShapeState::CircleDef>) {
snapshot.shape_def = FakeShape::CircleDef{
.radius = shape_def.radius,
};
} else if constexpr (std::is_same_v<T, FakeShapeState::RectangleDef>) {
snapshot.shape_def = FakeShape::RectangleDef{
.width = shape_def.width,
.height = shape_def.height,
};
} else if constexpr (std::is_same_v<
T, FakeShapeState::RoundedRectangleDef>) {
snapshot.shape_def = FakeShape::RoundedRectangleDef{
.width = shape_def.width,
.height = shape_def.height,
.top_left_radius = shape_def.top_left_radius,
.top_right_radius = shape_def.top_right_radius,
.bottom_right_radius = shape_def.bottom_right_radius,
.bottom_left_radius = shape_def.bottom_left_radius,
};
} else {
FML_CHECK(false);
}
},
shape->shape_def);
return snapshot;
}
FakeMaterial MaterialFromState(FakeMaterialState* material,
FakeResourceCache& cache) {
FML_CHECK(material);
return FakeMaterial{
.image = ResourceFromState(material->image, cache),
.color = material->color,
};
}
FakeImage ImageFromState(FakeImageState* image, FakeResourceCache& cache) {
FML_CHECK(image);
auto snapshot = FakeImage{
.memory = ResourceFromState(image->memory, cache),
};
std::visit(
[&snapshot](auto&& image_def) {
using T = std::decay_t<decltype(image_def)>;
if constexpr (std::is_same_v<T, FakeImageState::ImageDef>) {
snapshot.image_def = FakeImage::ImageDef{
.info = image_def.info,
.memory_offset = image_def.memory_offset,
};
} else if constexpr (std::is_same_v<T, FakeImageState::Image2Def>) {
snapshot.image_def = FakeImage::Image2Def{
.buffer_collection_id = image_def.buffer_collection_id,
.buffer_collection_index = image_def.buffer_collection_index,
.width = image_def.width,
.height = image_def.height,
};
} else if constexpr (std::is_same_v<T, FakeImageState::Image3Def>) {
snapshot.image_def = FakeImage::Image3Def{
.import_token = image_def.import_token.koid,
.buffer_collection_index = image_def.buffer_collection_index,
.width = image_def.width,
.height = image_def.height,
};
} else if constexpr (std::is_same_v<T, FakeImageState::ImagePipeDef>) {
snapshot.image_def = FakeImage::ImagePipeDef{
.image_pipe_request = image_def.image_pipe_request.koid,
};
} else if constexpr (std::is_same_v<T, FakeImageState::ImagePipe2Def>) {
snapshot.image_def = FakeImage::ImagePipe2Def{
.image_pipe_request = image_def.image_pipe_request.koid,
};
} else {
FML_CHECK(false);
}
},
image->image_def);
return snapshot;
}
FakeMemory MemoryFromState(FakeMemoryState* memory, FakeResourceCache& cache) {
FML_CHECK(memory);
return FakeMemory{
.vmo = memory->vmo.koid,
.allocation_size = memory->allocation_size,
.is_device_memory = memory->is_device_memory,
};
}
std::shared_ptr<FakeResource> ResourceFromState(
const std::shared_ptr<FakeResourceState>& resource,
FakeResourceCache& cache) {
if (!resource) {
return std::shared_ptr<FakeResource>();
}
// Try to hit the cache first...
auto cache_it = cache.find(resource.get());
if (cache_it != cache.end()) {
return cache_it->second;
}
// Otherwise create a brand-new snapshot.
std::shared_ptr<FakeResource> snapshot =
std::make_shared<FakeResource>(FakeResource{
.id = resource->id,
.label = resource->label,
.event_mask = resource->event_mask,
});
std::visit(
[&snapshot, &resource, &cache](auto&& state) {
using T = std::decay_t<decltype(state)>;
if constexpr (std::is_same_v<T, FakeEntityNodeState>) {
snapshot->state = EntityNodeFromState(
std::get_if<FakeEntityNodeState>(&resource->state), cache);
} else if constexpr (std::is_same_v<T, FakeOpacityNodeState>) {
snapshot->state = OpacityNodeFromState(
std::get_if<FakeOpacityNodeState>(&resource->state), cache);
} else if constexpr (std::is_same_v<T, FakeShapeNodeState>) {
snapshot->state = ShapeNodeFromState(
std::get_if<FakeShapeNodeState>(&resource->state), cache);
} else if constexpr (std::is_same_v<T, FakeViewState>) {
snapshot->state = ViewFromState(
std::get_if<FakeViewState>(&resource->state), cache);
} else if constexpr (std::is_same_v<T, FakeViewHolderState>) {
snapshot->state = ViewHolderFromState(
std::get_if<FakeViewHolderState>(&resource->state), cache);
} else if constexpr (std::is_same_v<T, FakeShapeState>) {
snapshot->state = ShapeFromState(
std::get_if<FakeShapeState>(&resource->state), cache);
} else if constexpr (std::is_same_v<T, FakeMaterialState>) {
snapshot->state = MaterialFromState(
std::get_if<FakeMaterialState>(&resource->state), cache);
} else if constexpr (std::is_same_v<T, FakeImageState>) {
snapshot->state = ImageFromState(
std::get_if<FakeImageState>(&resource->state), cache);
} else if constexpr (std::is_same_v<T, FakeMemoryState>) {
snapshot->state = MemoryFromState(
std::get_if<FakeMemoryState>(&resource->state), cache);
} else {
FML_CHECK(false);
}
},
resource->state);
auto [_, cache_success] =
cache.emplace(std::make_pair(resource.get(), snapshot));
FML_CHECK(cache_success);
return snapshot;
}
std::vector<std::shared_ptr<FakeResource>> ResourcesFromStates(
const std::vector<std::shared_ptr<FakeResourceState>>& resources,
FakeResourceCache& cache) {
std::vector<std::shared_ptr<FakeResource>> snapshots;
for (auto& resource : resources) {
snapshots.emplace_back(ResourceFromState(resource, cache));
}
return snapshots;
}
} // namespace
FakeSceneGraph SceneGraphFromState(const FakeSceneGraphState& state) {
FakeResourceCache resource_cache;
FakeSceneGraph scene_graph;
// Snapshot all buffer collections.
for (auto& buffer_collection : state.buffer_collection_map) {
scene_graph.buffer_collection_map.emplace(
std::make_pair(buffer_collection.first, buffer_collection.second.koid));
}
// Snapshot resources in the map recursively.
for (auto& resource : state.resource_map) {
scene_graph.resource_map.emplace(std::make_pair(
resource.first, ResourceFromState(resource.second, resource_cache)));
}
// Snapshot labels in the map.
for (auto& label_resources : state.labels_map) {
auto [label_iter, label_success] =
scene_graph.labels_map.emplace(std::make_pair(
label_resources.first, std::vector<std::weak_ptr<FakeResource>>()));
FML_CHECK(label_success);
auto& snapshot_label_resources = label_iter->second;
for (auto& resource : label_resources.second) {
auto resource_ptr = resource.lock();
FML_CHECK(resource_ptr);
snapshot_label_resources.emplace_back(
ResourceFromState(resource_ptr, resource_cache));
}
}
// Snapshot the view id.
scene_graph.root_view_id = state.root_view_id;
return scene_graph;
}
} // namespace flutter_runner::testing

View File

@@ -0,0 +1,555 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_SCENIC_FAKE_RESOURCES_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_SCENIC_FAKE_RESOURCES_H_
#include <fuchsia/images/cpp/fidl.h>
#include <fuchsia/sysmem/cpp/fidl.h>
#include <fuchsia/ui/composition/cpp/fidl.h>
#include <fuchsia/ui/gfx/cpp/fidl.h>
#include <fuchsia/ui/views/cpp/fidl.h>
#include <lib/fidl/cpp/interface_handle.h>
#include <lib/fidl/cpp/interface_request.h>
#include <lib/zx/vmo.h>
#include <zircon/types.h>
#include <array>
#include <memory>
#include <string>
#include <unordered_map>
#include <variant>
#include <vector>
inline bool operator==(const fuchsia::images::ImageInfo& a,
const fuchsia::images::ImageInfo& b) {
return a.height == b.height && a.width == b.width && a.stride == b.stride &&
a.tiling == b.tiling && a.transform == b.transform &&
a.alpha_format == b.alpha_format && a.pixel_format == b.pixel_format &&
a.color_space == b.color_space;
}
inline bool operator==(const fuchsia::ui::gfx::vec3& a,
const fuchsia::ui::gfx::vec3& b) {
return a.x == b.x && a.y == b.y && a.z == b.z;
}
inline bool operator==(const fuchsia::ui::gfx::BoundingBox& a,
const fuchsia::ui::gfx::BoundingBox& b) {
return a.min == b.min && a.max == b.max;
}
inline bool operator==(const fuchsia::ui::gfx::ViewProperties& a,
const fuchsia::ui::gfx::ViewProperties& b) {
return a.downward_input == b.downward_input &&
a.focus_change == b.focus_change && a.bounding_box == b.bounding_box &&
a.inset_from_min == b.inset_from_min &&
a.inset_from_max == b.inset_from_max;
}
namespace flutter_runner::testing {
// Forward declarations
template <typename S>
struct FakeResourceT;
// Unique (within a Session) identifier for a Resource.
using FakeResourceId = decltype(fuchsia::ui::gfx::CreateResourceCmd::id);
constexpr FakeResourceId kInvalidFakeResourceId = 0u;
// Tag type for a Resource "state". The Resource state keeps alive any handles
// associated with a resource e.g. view token or sysmem token.
//
// "snapshot" Resources are generated from "state" Resources during
// `SceneGraphFromState()` calls.
//
// The `FakeSession` stores `FakeResourceT<StateT>` internally.
struct StateT {
using ResourceT = FakeResourceT<StateT>;
template <typename T>
struct HandleT {
T value;
zx_koid_t koid;
};
template <typename T>
static bool HandlesAreEqual(const HandleT<T>& token,
const HandleT<T>& other_token) {
return token.koid == other_token.koid;
}
};
// Tag type for a Resource "snapshot". The Resource snapshot only stores koids
// for any handles assocaites with the resource; in this way it doesn't have any
// control over the underlying handle lifetime.
//
// "snapshot" Resources are generated from "state" Resources during
// `SceneGraphFromState()` calls.
//
// The `FakeSession` returns `FakeResourceT<SnapshotT>` from its `SceneGraph()`
// accessor.
struct SnapshotT {
using ResourceT = FakeResourceT<SnapshotT>;
template <typename T>
using HandleT = zx_koid_t;
template <typename T>
static bool HandlesAreEqual(const HandleT<T>& token,
const HandleT<T>& other_token) {
return token == other_token;
}
};
// Common state for Node-typed Resources: EntityNode, OpacityNode, ShapeNode,
// ViewHolder.
//
// FakeNodeT's are never used directly, only as an embedded field of a
// Node-typed resource.
template <typename S>
struct FakeNodeT {
bool operator==(const FakeNodeT& other) const;
constexpr static std::array<float, 4> kDefaultZeroRotation{0.f, 0.f, 0.f,
1.f};
constexpr static std::array<float, 3> kDefaultOneScale{1.f, 1.f, 1.f};
constexpr static std::array<float, 3> kDefaultZeroTranslation{0.f, 0.f, 0.f};
constexpr static std::array<float, 3> kDefaultZeroAnchor{0.f, 0.f, 0.f};
constexpr static bool kIsHitTestable{true};
constexpr static bool kIsNotHitTestable{false};
constexpr static bool kIsSemanticallyVisible{true};
constexpr static bool kIsNotSemanticallyVisible{false};
std::vector<std::shared_ptr<typename S::ResourceT>> children;
std::array<float, 4> rotation_quaternion{kDefaultZeroRotation};
std::array<float, 3> scale_vector{kDefaultOneScale};
std::array<float, 3> translation_vector{kDefaultZeroTranslation};
std::array<float, 3> anchor_vector{kDefaultZeroAnchor};
bool hit_testable{kIsHitTestable};
bool semantically_visible{kIsSemanticallyVisible};
};
using FakeNodeState = FakeNodeT<StateT>;
using FakeNode = FakeNodeT<SnapshotT>;
// EntityNode Resource state.
template <typename S>
struct FakeEntityNodeT {
struct ClipPlane {
bool operator==(const ClipPlane& other) const;
constexpr static std::array<float, 3> kDefaultZeroDir{0.f, 0.f, 0.f};
constexpr static float kDefaultZeroDist{0.f};
std::array<float, 3> dir{kDefaultZeroDir};
float dist{kDefaultZeroDist};
};
bool operator==(const FakeEntityNodeT& other) const;
FakeNodeT<S> node_state;
std::vector<ClipPlane> clip_planes;
};
using FakeEntityNodeState = FakeEntityNodeT<StateT>;
using FakeEntityNode = FakeEntityNodeT<SnapshotT>;
// OpacityNode Resource state.
template <typename S>
struct FakeOpacityNodeT {
bool operator==(const FakeOpacityNodeT& other) const;
FakeNodeT<S> node_state;
constexpr static float kDefaultOneOpacity{1.f};
float opacity{kDefaultOneOpacity};
};
using FakeOpacityNodeState = FakeOpacityNodeT<StateT>;
using FakeOpacityNode = FakeOpacityNodeT<SnapshotT>;
// ShapeNode Resource state.
template <typename S>
struct FakeShapeNodeT {
bool operator==(const FakeShapeNodeT& other) const;
FakeNodeT<S> node_state;
std::shared_ptr<typename S::ResourceT> shape;
std::shared_ptr<typename S::ResourceT> material;
};
using FakeShapeNodeState = FakeShapeNodeT<StateT>;
using FakeShapeNode = FakeShapeNodeT<SnapshotT>;
// View Resource state.
template <typename S>
struct FakeViewT {
bool operator==(const FakeViewT& other) const;
constexpr static bool kDebugBoundsEnabled{true};
constexpr static bool kDebugBoundsDisbaled{false};
typename S::template HandleT<fuchsia::ui::views::ViewToken> token{};
typename S::template HandleT<fuchsia::ui::views::ViewRefControl>
control_ref{};
typename S::template HandleT<fuchsia::ui::views::ViewRef> view_ref{};
std::string debug_name{};
std::vector<std::shared_ptr<typename S::ResourceT>> children;
bool enable_debug_bounds{kDebugBoundsDisbaled};
};
using FakeViewState = FakeViewT<StateT>;
using FakeView = FakeViewT<SnapshotT>;
// ViewHolder Resource state.
template <typename S>
struct FakeViewHolderT {
bool operator==(const FakeViewHolderT& other) const;
FakeNodeT<S> node_state;
constexpr static std::array<float, 4> kDefaultBoundsColorWhite{1.f, 1.f, 1.f,
1.f};
typename S::template HandleT<fuchsia::ui::views::ViewHolderToken> token{};
std::string debug_name{};
fuchsia::ui::gfx::ViewProperties properties;
std::array<float, 4> bounds_color{kDefaultBoundsColorWhite};
};
using FakeViewHolderState = FakeViewHolderT<StateT>;
using FakeViewHolder = FakeViewHolderT<SnapshotT>;
// Shape Resource state.
template <typename S>
struct FakeShapeT {
bool operator==(const FakeShapeT& other) const;
struct CircleDef {
bool operator==(const CircleDef& other) const;
float radius{0.f};
};
struct RectangleDef {
bool operator==(const RectangleDef& other) const;
float width{0.f};
float height{0.f};
};
struct RoundedRectangleDef {
bool operator==(const RoundedRectangleDef& other) const;
float width{0.f};
float height{0.f};
float top_left_radius{0.f};
float top_right_radius{0.f};
float bottom_right_radius{0.f};
float bottom_left_radius{0.f};
};
std::variant<CircleDef, RectangleDef, RoundedRectangleDef> shape_def;
};
using FakeShapeState = FakeShapeT<StateT>;
using FakeShape = FakeShapeT<SnapshotT>;
// Material Resource state.
template <typename S>
struct FakeMaterialT {
bool operator==(const FakeMaterialT& other) const;
constexpr static std::array<float, 4> kDefaultColorWhite{1.f, 1.f, 1.f, 1.f};
std::shared_ptr<typename S::ResourceT> image;
std::array<float, 4> color{kDefaultColorWhite};
};
using FakeMaterialState = FakeMaterialT<StateT>;
using FakeMaterial = FakeMaterialT<SnapshotT>;
// Image Resource state.
template <typename S>
struct FakeImageT {
struct ImageDef {
bool operator==(const ImageDef& other) const;
fuchsia::images::ImageInfo info{};
uint32_t memory_offset{};
};
struct Image2Def {
bool operator==(const Image2Def& other) const;
uint32_t buffer_collection_id{};
uint32_t buffer_collection_index{};
uint32_t width{};
uint32_t height{};
};
struct Image3Def {
bool operator==(const Image3Def& other) const;
typename S::template HandleT<
fuchsia::ui::composition::BufferCollectionImportToken>
import_token{};
uint32_t buffer_collection_index{};
uint32_t width{};
uint32_t height{};
};
struct ImagePipeDef {
bool operator==(const ImagePipeDef& other) const;
typename S::template HandleT<
fidl::InterfaceRequest<fuchsia::images::ImagePipe>>
image_pipe_request{};
};
struct ImagePipe2Def {
bool operator==(const ImagePipe2Def& other) const;
typename S::template HandleT<
fidl::InterfaceRequest<fuchsia::images::ImagePipe2>>
image_pipe_request{};
};
bool operator==(const FakeImageT& other) const;
std::variant<ImageDef, Image2Def, Image3Def, ImagePipeDef, ImagePipe2Def>
image_def;
std::shared_ptr<typename S::ResourceT> memory;
};
using FakeImageState = FakeImageT<StateT>;
using FakeImage = FakeImageT<SnapshotT>;
// Memory Resource state.
template <typename S>
struct FakeMemoryT {
bool operator==(const FakeMemoryT& other) const;
constexpr static bool kIsDeviceMemory{true};
constexpr static bool kIsNotDeviceMemory{false};
typename S::template HandleT<zx::vmo> vmo{};
uint64_t allocation_size{};
bool is_device_memory{kIsNotDeviceMemory};
};
using FakeMemoryState = FakeMemoryT<StateT>;
using FakeMemory = FakeMemoryT<SnapshotT>;
// A complete Resource which records common Resource data and stores it's
// type-specific state inside of a variant.
template <typename S>
struct FakeResourceT {
bool operator==(const FakeResourceT& other) const;
constexpr static uint32_t kDefaultEmptyEventMask{0};
FakeResourceId id{kInvalidFakeResourceId};
std::string label{};
uint32_t event_mask{kDefaultEmptyEventMask};
std::variant<FakeEntityNodeT<S>,
FakeOpacityNodeT<S>,
FakeShapeNodeT<S>,
FakeViewT<S>,
FakeViewHolderT<S>,
FakeShapeT<S>,
FakeMaterialT<S>,
FakeImageT<S>,
FakeMemoryT<S>>
state;
};
using FakeResourceState = FakeResourceT<StateT>;
using FakeResource = FakeResourceT<SnapshotT>;
// A complete scene graph which records a forest of Resource trees.
//
// It also records auxiliary data like buffer collection IDs and resource labels
// for fast lookup.
//
// Each Session / scene graph may only have a single View Resource which is
// treated as the root of that scene. The root View and all Resources
// descending from it are what the real scenic implementation would submit for
// rendering.
template <typename S>
struct FakeSceneGraphT {
bool operator==(const FakeSceneGraphT& other) const;
std::unordered_map<uint32_t,
typename S::template HandleT<fidl::InterfaceHandle<
fuchsia::sysmem::BufferCollectionToken>>>
buffer_collection_map;
std::unordered_map<FakeResourceId, std::shared_ptr<FakeResourceT<S>>>
resource_map;
std::unordered_map<std::string, std::vector<std::weak_ptr<FakeResourceT<S>>>>
labels_map;
FakeResourceId root_view_id{kInvalidFakeResourceId};
};
using FakeSceneGraphState = FakeSceneGraphT<StateT>;
using FakeSceneGraph = FakeSceneGraphT<SnapshotT>;
// Generate a snapshot of a scene graph from that scene graph's state.
//
// The lifetime of the snapshot and its Resources has no influence on the
// lifetime of the source scene graph or its Resources.
FakeSceneGraph SceneGraphFromState(const FakeSceneGraphState& state);
template <typename S>
bool FakeEntityNodeT<S>::ClipPlane::operator==(
const FakeEntityNodeT<S>::ClipPlane& other) const {
return dir == other.dir && dist == other.dist;
}
template <typename S>
bool FakeNodeT<S>::operator==(const FakeNodeT<S>& other) const {
return children == other.children &&
rotation_quaternion == other.rotation_quaternion &&
scale_vector == other.scale_vector &&
translation_vector == other.translation_vector &&
anchor_vector == other.anchor_vector &&
hit_testable == other.hit_testable &&
semantically_visible == other.semantically_visible;
}
template <typename S>
bool FakeEntityNodeT<S>::operator==(const FakeEntityNodeT<S>& other) const {
return node_state == other.node_state && clip_planes == other.clip_planes;
}
template <typename S>
bool FakeOpacityNodeT<S>::operator==(const FakeOpacityNodeT<S>& other) const {
return node_state == other.node_state && opacity == other.opacity;
}
template <typename S>
bool FakeShapeNodeT<S>::operator==(const FakeShapeNodeT<S>& other) const {
return node_state == other.node_state && shape == other.shape &&
material == other.material;
}
template <typename S>
bool FakeViewT<S>::operator==(const FakeViewT<S>& other) const {
return S::template HandlesAreEqual<fuchsia::ui::views::ViewToken>(
token, other.token) &&
S::template HandlesAreEqual<fuchsia::ui::views::ViewRefControl>(
control_ref, other.control_ref) &&
S::template HandlesAreEqual<fuchsia::ui::views::ViewRef>(
view_ref, other.view_ref) &&
children == other.children && debug_name == other.debug_name &&
enable_debug_bounds == other.enable_debug_bounds;
}
template <typename S>
bool FakeViewHolderT<S>::operator==(const FakeViewHolderT<S>& other) const {
return FakeNodeT<S>::operator==(other) &&
S::template HandlesAreEqual<fuchsia::ui::views::ViewHolderToken>(
token, other.token) &&
debug_name == other.debug_name && properties == other.properties &&
bounds_color == other.bounds_color;
}
template <typename S>
bool FakeShapeT<S>::CircleDef::operator==(
const FakeShapeT<S>::CircleDef& other) const {
return radius == other.radius;
}
template <typename S>
bool FakeShapeT<S>::RectangleDef::operator==(
const FakeShapeT<S>::RectangleDef& other) const {
return width == other.width && height == other.height;
}
template <typename S>
bool FakeShapeT<S>::RoundedRectangleDef::operator==(
const FakeShapeT<S>::RoundedRectangleDef& other) const {
return width == other.width && height == other.height &&
top_left_radius == other.top_left_radius &&
top_right_radius == other.top_right_radius &&
bottom_right_radius == other.bottom_right_radius &&
bottom_left_radius == other.bottom_left_radius;
}
template <typename S>
bool FakeShapeT<S>::operator==(const FakeShapeT<S>& other) const {
return shape_def == other.shape_def;
}
template <typename S>
bool FakeMaterialT<S>::operator==(const FakeMaterialT<S>& other) const {
return image == other.image && color == other.color;
}
template <typename S>
bool FakeImageT<S>::ImageDef::operator==(
const FakeImageT<S>::ImageDef& other) const {
return info == other.info && memory_offset == other.memory_offset;
}
template <typename S>
bool FakeImageT<S>::Image2Def::operator==(
const FakeImageT<S>::Image2Def& other) const {
return buffer_collection_id == other.buffer_collection_id &&
buffer_collection_index == other.buffer_collection_index &&
width == other.width && height == other.height;
}
template <typename S>
bool FakeImageT<S>::Image3Def::operator==(
const FakeImageT<S>::Image3Def& other) const {
return S::template HandlesAreEqual<
fuchsia::ui::composition::BufferCollectionImportToken>(
import_token, other.import_token) &&
buffer_collection_index == other.buffer_collection_index &&
width == other.width && height == other.height;
}
template <typename S>
bool FakeImageT<S>::ImagePipeDef::operator==(
const FakeImageT<S>::ImagePipeDef& other) const {
return S::template HandlesAreEqual<
fidl::InterfaceRequest<fuchsia::images::ImagePipe>>(
image_pipe_request, other.image_pipe_request);
}
template <typename S>
bool FakeImageT<S>::ImagePipe2Def::operator==(
const FakeImageT<S>::ImagePipe2Def& other) const {
return S::template HandlesAreEqual<
fidl::InterfaceRequest<fuchsia::images::ImagePipe2>>(
image_pipe_request, other.image_pipe_request);
}
template <typename S>
bool FakeImageT<S>::operator==(const FakeImageT<S>& other) const {
return image_def == other.image_def && memory == other.memory;
}
template <typename S>
bool FakeMemoryT<S>::operator==(const FakeMemoryT<S>& other) const {
return S::template HandlesAreEqual<zx::vmo>(vmo, other.vmo) &&
allocation_size == other.allocation_size &&
is_device_memory == other.is_device_memory;
}
template <typename S>
bool FakeResourceT<S>::operator==(const FakeResourceT<S>& other) const {
return id == other.id && label == other.label &&
event_mask == other.event_mask && state == other.state;
}
template <typename S>
bool FakeSceneGraphT<S>::operator==(const FakeSceneGraphT<S>& other) const {
return buffer_collection_map == other.buffer_collection_map &&
resource_map ==
other.resource_map && // labels_map == other.labels_map &&
root_view_id == other.root_view_id;
}
} // namespace flutter_runner::testing
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_SCENIC_FAKE_RESOURCES_H_

View File

@@ -7,6 +7,8 @@
#include <fuchsia/images/cpp/fidl.h>
#include <fuchsia/scenic/scheduling/cpp/fidl.h>
#include <fuchsia/sysmem/cpp/fidl.h>
#include <fuchsia/ui/gfx/cpp/fidl.h>
#include <fuchsia/ui/scenic/cpp/fidl.h>
#include <fuchsia/ui/scenic/cpp/fidl_test_base.h>
#include <lib/async/dispatcher.h>
@@ -14,15 +16,58 @@
#include <lib/fidl/cpp/interface_handle.h>
#include <lib/fidl/cpp/interface_request.h>
#include <deque>
#include <functional>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility> // For std::pair
#include <vector>
#include "flutter/fml/macros.h"
#include "fake_resources.h"
namespace flutter_runner::testing {
// A lightweight fake implementation of the scenic Session API, also called
// the "gfx API". The fake has no side effects besides mutating its own
// internal state.
//
// The fake allows tests to do a few things that would be difficult using either
// a mock implementation or the real implementation:
// + It allows the user to hook `Present` invocations and respond with
// stubbed-out `FuturePresentationTimes`, but more crucially it mimics the
// real scenic behavior of only processing commands when a `Present` is
// invoked.
// + It allows the user to inspect a snapshot of the scene graph at any moment
// in time, via the `SceneGraph()` accessor.
// + It stores the various session resources generated by commands into a
// std::unordered_map, and also correctly manages the resource lifetimes via
// reference counting. This allows a resource to stay alive if its parent
// still holds a reference to it, in the same way the real scenic
// implementation would.
// + The resources returned by `SceneGraph()` that the test uses for
// inspection are decoupled from the resources managed internally by the
// `FakeSession` itself -- they are a snapshot of the scene graph at that
// moment in time, with all snapshot state being cloned from the underlying
// scene graph state. This allows the `FakeSession` and test to naturally use
// `shared_ptr` for reference counting and mimic the real scenic behavior
// exactly, instead of an awkward index-based API.
//
// Error handling / session disconnection is still WIP. FakeSession will likely
// generate a CHECK in any place where the real scenic would disconnect the
// session or send a ScenicError.
//
// root_presenter-only commands e.g. CreateLayer are not handled.
//
// Deprecated / obsolete commands are not handled.
//
// Input is not handled.
//
// Rendering is not handled.
//
// Cross-session links are not handled.
class FakeSession : public fuchsia::ui::scenic::testing::Session_TestBase {
public:
using PresentHandler =
@@ -46,29 +91,37 @@ class FakeSession : public fuchsia::ui::scenic::testing::Session_TestBase {
const std::string& debug_name() const { return debug_name_; }
const std::vector<fuchsia::ui::scenic::Command>& command_queue() {
const std::deque<fuchsia::ui::scenic::Command>& command_queue() const {
return command_queue_;
}
// Bind method. Call to bind this session's FIDL channels to the |dispatcher|
// and allow processing of incoming FIDL requests.
// Generate a snapshot of the underlying scene graph for test inspection.
FakeSceneGraph SceneGraph() const {
return SceneGraphFromState(scene_graph_);
}
// Bind this session's FIDL channels to the `dispatcher` and allow processing
// of incoming FIDL requests.
SessionAndListenerClientPair Bind(async_dispatcher_t* dispatcher = nullptr);
// Stub methods. Call these to set a handler for the specified FIDL calls'
// return values.
// Set a handler for `Present`-related FIDL calls' return values.
void SetPresentHandler(PresentHandler present_handler);
void SetPresent2Handler(Present2Handler present2_handler);
void SetRequestPresentationTimesHandler(
RequestPresentationTimesHandler request_presentation_times_handler);
// Event methods. Call these to fire the associated FIDL event.
// Fire an `OnFramePresented` event.
void FireOnFramePresentedEvent(
fuchsia::scenic::scheduling::FramePresentedInfo frame_presented_info);
// Error method. Call to disconnect the session with an error.
// Disconnect the session with an error.
// TODO: Call this internally upon command error, instead of CHECK'ing.
void DisconnectSession();
private:
// |fuchsia::ui::scenic::testing::Session_TestBase|
void NotImplemented_(const std::string& name) override;
// |fuchsia::ui::scenic::Session|
void Enqueue(std::vector<fuchsia::ui::scenic::Command> cmds) override;
@@ -99,15 +152,80 @@ class FakeSession : public fuchsia::ui::scenic::testing::Session_TestBase {
// |fuchsia::ui::scenic::Session|
void SetDebugName(std::string debug_name) override;
// |fuchsia::ui::scenic::testing::Session_TestBase|
void NotImplemented_(const std::string& name) override;
// Resource management.
std::shared_ptr<FakeResourceState> GetResource(FakeResourceId id);
void AddResource(FakeResourceState&& resource);
void DetachResourceFromParent(
std::shared_ptr<FakeResourceState> resource_ptr,
std::shared_ptr<FakeResourceState> new_parent_ptr = nullptr);
void PruneDeletedResourceRefs();
// Apply queued commands and mutate the resource map.
void ApplyCommands();
void ApplyCreateResourceCmd(fuchsia::ui::gfx::CreateResourceCmd command);
void ApplyReleaseResourceCmd(fuchsia::ui::gfx::ReleaseResourceCmd command);
void ApplyAddChildCmd(fuchsia::ui::gfx::AddChildCmd command);
void ApplyDetachCmd(fuchsia::ui::gfx::DetachCmd command);
void ApplyDetachChildrenCmd(fuchsia::ui::gfx::DetachChildrenCmd command);
void ApplySetTranslationCmd(fuchsia::ui::gfx::SetTranslationCmd command);
void ApplySetScaleCmd(fuchsia::ui::gfx::SetScaleCmd command);
void ApplySetRotationCmd(fuchsia::ui::gfx::SetRotationCmd command);
void ApplySetAnchorCmd(fuchsia::ui::gfx::SetAnchorCmd command);
void ApplySetOpacityCmd(fuchsia::ui::gfx::SetOpacityCmd command);
void ApplySetShapeCmd(fuchsia::ui::gfx::SetShapeCmd command);
void ApplySetMaterialCmd(fuchsia::ui::gfx::SetMaterialCmd command);
void ApplySetClipPlanesCmd(fuchsia::ui::gfx::SetClipPlanesCmd command);
void ApplySetViewPropertiesCmd(
fuchsia::ui::gfx::SetViewPropertiesCmd command);
void ApplySetHitTestBehaviorCmd(
fuchsia::ui::gfx::SetHitTestBehaviorCmd command);
void ApplySetSemanticVisibilityCmd(
fuchsia::ui::gfx::SetSemanticVisibilityCmd command);
void ApplySetTextureCmd(fuchsia::ui::gfx::SetTextureCmd command);
void ApplySetColorCmd(fuchsia::ui::gfx::SetColorCmd command);
void ApplySetEventMaskCmd(fuchsia::ui::gfx::SetEventMaskCmd command);
void ApplySetLabelCmd(fuchsia::ui::gfx::SetLabelCmd command);
void ApplySetEnableViewDebugBoundsCmd(
fuchsia::ui::gfx::SetEnableDebugViewBoundsCmd command);
void ApplySetViewHolderBoundsColorCmd(
fuchsia::ui::gfx::SetViewHolderBoundsColorCmd command);
void ApplyCreateMemory(FakeResourceId id, fuchsia::ui::gfx::MemoryArgs args);
void ApplyCreateImage(FakeResourceId id, fuchsia::ui::gfx::ImageArgs args);
void ApplyCreateImage2(FakeResourceId id, fuchsia::ui::gfx::ImageArgs2 args);
void ApplyCreateImage3(FakeResourceId id, fuchsia::ui::gfx::ImageArgs3 args);
void ApplyCreateImagePipe(FakeResourceId id,
fuchsia::ui::gfx::ImagePipeArgs args);
void ApplyCreateImagePipe2(FakeResourceId id,
fuchsia::ui::gfx::ImagePipe2Args args);
void ApplyCreateRectangle(FakeResourceId id,
fuchsia::ui::gfx::RectangleArgs args);
void ApplyCreateRoundedRectangle(FakeResourceId id,
fuchsia::ui::gfx::RoundedRectangleArgs args);
void ApplyCreateCircle(FakeResourceId id, fuchsia::ui::gfx::CircleArgs args);
void ApplyCreateMaterial(FakeResourceId id,
fuchsia::ui::gfx::MaterialArgs args);
void ApplyCreateView(FakeResourceId id, fuchsia::ui::gfx::ViewArgs args);
void ApplyCreateViewHolder(FakeResourceId id,
fuchsia::ui::gfx::ViewHolderArgs args);
void ApplyCreateView(FakeResourceId id, fuchsia::ui::gfx::ViewArgs3 args);
void ApplyCreateEntityNode(FakeResourceId id,
fuchsia::ui::gfx::EntityNodeArgs args);
void ApplyCreateOpacityNode(FakeResourceId id,
fuchsia::ui::gfx::OpacityNodeArgsHACK args);
void ApplyCreateShapeNode(FakeResourceId id,
fuchsia::ui::gfx::ShapeNodeArgs args);
fidl::Binding<fuchsia::ui::scenic::Session> binding_;
fuchsia::ui::scenic::SessionListenerPtr listener_;
std::string debug_name_;
std::vector<fuchsia::ui::scenic::Command> command_queue_;
std::deque<fuchsia::ui::scenic::Command> command_queue_;
std::unordered_map<FakeResourceState*,
std::pair<std::weak_ptr<FakeResourceState>,
std::weak_ptr<FakeResourceState>>>
parents_map_; // Used to cache parent refs for `AddChildCmd`
FakeSceneGraphState scene_graph_;
PresentHandler present_handler_;
Present2Handler present2_handler_;