Add invoke_global_callback to the C++ interpreter API

This commit is contained in:
Olivier Goffart 2021-08-27 12:05:23 +02:00 committed by Olivier Goffart
parent 00cc8ec693
commit 70c57844b7
3 changed files with 65 additions and 1 deletions

View file

@ -774,6 +774,24 @@ public:
sixtyfps::private_api::string_to_slice(name), actual_cb, new F(std::move(callback)),
[](void *data) { delete reinterpret_cast<F *>(data); });
}
// FIXME! Slice in public API? Should be std::span (c++20) or we need to improve the Slice API
/// Invoke the specified callback declared in an exported global
std::optional<Value> invoke_global_callback(std::string_view global,
std::string_view callback_name,
Slice<Value> args) const
{
using namespace cbindgen_private;
Slice<ValueOpaque> args_view { reinterpret_cast<ValueOpaque *>(args.ptr), args.len };
ValueOpaque out;
if (sixtyfps_interpreter_component_instance_invoke_global_callback(
inner(), sixtyfps::private_api::string_to_slice(global),
sixtyfps::private_api::string_to_slice(callback_name), args_view, &out)) {
return Value(out);
} else {
return {};
}
}
};
#if !defined(DOXYGEN)

View file

@ -541,7 +541,7 @@ SCENARIO("Global properties")
REQUIRE(value->to_string().has_value());
REQUIRE(value->to_string().value() == "§§§");
}
SECTION("set callback")
SECTION("set/invoke callback")
{
REQUIRE(instance->set_global_callback("The-Global", "to_uppercase", [](auto args) {
std::string arg1(*args[0].to_string());
@ -552,5 +552,20 @@ SCENARIO("Global properties")
REQUIRE(result.has_value());
REQUIRE(result->to_string().has_value());
REQUIRE(result->to_string().value() == "ABC");
Value args[] = { SharedString("Hello") };
auto res = instance->invoke_global_callback("The_Global", "to-uppercase",
Slice<Value> { args, 1 });
REQUIRE(res.has_value());
REQUIRE(*res->to_string() == SharedString("HELLO"));
}
SECTION("callback errors")
{
REQUIRE(!instance->set_global_callback("TheGlobal", "to_uppercase",
[](auto) { return Value {}; }));
REQUIRE(!instance->set_global_callback("The-Global", "touppercase",
[](auto) { return Value {}; }));
REQUIRE(!instance->invoke_global_callback("TheGlobal", "touppercase", {}));
REQUIRE(!instance->invoke_global_callback("The-Global", "touppercase", {}));
}
}