Post Dart message handling tasks directly to the platform task runner for isolates running on the platform thread (flutter/engine#51573)

Some embedders use a custom platform task runner that does not support fml::MessageLoopTaskQueues and may not have an fml::MessageLoop.

To support those embedders, DartIsolate::SetMessageHandlingTaskRunner will not use fml::MessageLoopTaskQueues for platform isolates.

See https://github.com/flutter/engine/pull/48551#issuecomment-1962190896
This commit is contained in:
Jason Simmons
2024-03-22 07:33:03 -07:00
committed by GitHub
parent a697f6e769
commit 171221580e
4 changed files with 110 additions and 20 deletions

View File

@@ -504,9 +504,12 @@ bool DartIsolate::Initialize(Dart_Isolate dart_isolate) {
Dart_SetCurrentUserTag(Dart_NewUserTag("AppStartUp"));
}
SetMessageHandlingTaskRunner(is_platform_isolate_
? GetTaskRunners().GetPlatformTaskRunner()
: GetTaskRunners().GetUITaskRunner());
if (is_platform_isolate_) {
SetMessageHandlingTaskRunner(GetTaskRunners().GetPlatformTaskRunner(),
true);
} else {
SetMessageHandlingTaskRunner(GetTaskRunners().GetUITaskRunner(), false);
}
if (tonic::CheckAndHandleError(
Dart_SetLibraryTagHandler(tonic::DartState::HandleLibraryTag))) {
@@ -562,30 +565,41 @@ void DartIsolate::LoadLoadingUnitError(intptr_t loading_unit_id,
}
void DartIsolate::SetMessageHandlingTaskRunner(
const fml::RefPtr<fml::TaskRunner>& runner) {
const fml::RefPtr<fml::TaskRunner>& runner,
bool post_directly_to_runner) {
if (!runner) {
return;
}
message_handling_task_runner_ = runner;
message_handler().Initialize([runner](std::function<void()> task) {
tonic::DartMessageHandler::TaskDispatcher dispatcher;
#ifdef OS_FUCHSIA
runner->PostTask([task = std::move(task)]() {
TRACE_EVENT0("flutter", "DartIsolate::HandleMessage");
task();
});
#else
auto task_queues = fml::MessageLoopTaskQueues::GetInstance();
task_queues->RegisterTask(
runner->GetTaskQueueId(),
[task = std::move(task)]() {
TRACE_EVENT0("flutter", "DartIsolate::HandleMessage");
task();
},
fml::TimePoint::Now(), fml::TaskSourceGrade::kDartEventLoop);
post_directly_to_runner = true;
#endif
});
if (post_directly_to_runner) {
dispatcher = [runner](std::function<void()> task) {
runner->PostTask([task = std::move(task)]() {
TRACE_EVENT0("flutter", "DartIsolate::HandleMessage");
task();
});
};
} else {
dispatcher = [runner](std::function<void()> task) {
auto task_queues = fml::MessageLoopTaskQueues::GetInstance();
task_queues->RegisterTask(
runner->GetTaskQueueId(),
[task = std::move(task)]() {
TRACE_EVENT0("flutter", "DartIsolate::HandleMessage");
task();
},
fml::TimePoint::Now(), fml::TaskSourceGrade::kDartEventLoop);
};
}
message_handler().Initialize(dispatcher);
}
// Updating thread names here does not change the underlying OS thread names.

View File

@@ -470,7 +470,8 @@ class DartIsolate : public UIDartState {
///
[[nodiscard]] bool Initialize(Dart_Isolate dart_isolate);
void SetMessageHandlingTaskRunner(const fml::RefPtr<fml::TaskRunner>& runner);
void SetMessageHandlingTaskRunner(const fml::RefPtr<fml::TaskRunner>& runner,
bool post_directly_to_runner);
bool LoadKernel(const std::shared_ptr<const fml::Mapping>& mapping,
bool last_piece);

View File

@@ -60,6 +60,12 @@ void invokePlatformTaskRunner() {
PlatformDispatcher.instance.sendPlatformMessage('OhHi', null, null);
}
@pragma('vm:entry-point')
void invokePlatformThreadIsolate() {
signalNativeTest();
runOnPlatformThread(ffiSignalNativeTest);
}
Float64List kTestTransform = () {
final Float64List values = Float64List(16);
values[0] = 1.0; // scaleX
@@ -87,6 +93,9 @@ external void notifyAccessibilityFeatures(bool reduceMotion);
@pragma('vm:external-name', 'NotifySemanticsAction')
external void notifySemanticsAction(int nodeId, int action, List<int> data);
@ffi.Native<ffi.Void Function()>(symbol: 'FFISignalNativeTest')
external void ffiSignalNativeTest();
/// Returns a future that completes when
/// `PlatformDispatcher.instance.onSemanticsEnabledChanged` fires.
Future<void> get semanticsChanged {

View File

@@ -3009,6 +3009,72 @@ TEST_F(EmbedderTest, RegisterChannelListener) {
ASSERT_TRUE(listening);
}
TEST_F(EmbedderTest, PlatformThreadIsolatesWithCustomPlatformTaskRunner) {
auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext);
static fml::AutoResetWaitableEvent latch;
static std::thread::id ffi_call_thread_id;
static void (*ffi_signal_native_test)() = []() -> void {
ffi_call_thread_id = std::this_thread::get_id();
latch.Signal();
};
Dart_FfiNativeResolver ffi_resolver = [](const char* name,
uintptr_t args_n) -> void* {
if (std::string_view(name) == "FFISignalNativeTest") {
return reinterpret_cast<void*>(ffi_signal_native_test);
}
return nullptr;
};
// The test's Dart code will call this native function which overrides the
// FFI resolver. After that, the Dart code will invoke the FFI function
// using runOnPlatformThread.
context.AddNativeCallback(
"SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) {
Dart_SetFfiNativeResolver(Dart_RootLibrary(), ffi_resolver);
}));
auto platform_task_runner = CreateNewThread("test_platform_thread");
UniqueEngine engine;
EmbedderTestTaskRunner test_task_runner(
platform_task_runner, [&](FlutterTask task) {
if (!engine.is_valid()) {
return;
}
FlutterEngineRunTask(engine.get(), &task);
});
std::thread::id platform_thread_id;
platform_task_runner->PostTask([&]() {
platform_thread_id = std::this_thread::get_id();
EmbedderConfigBuilder builder(context);
const auto task_runner_description =
test_task_runner.GetFlutterTaskRunnerDescription();
builder.SetSoftwareRendererConfig();
builder.SetPlatformTaskRunner(&task_runner_description);
builder.SetDartEntrypoint("invokePlatformThreadIsolate");
engine = builder.LaunchEngine();
ASSERT_TRUE(engine.is_valid());
});
latch.Wait();
fml::AutoResetWaitableEvent kill_latch;
platform_task_runner->PostTask(fml::MakeCopyable([&]() mutable {
engine.reset();
platform_task_runner->PostTask([&kill_latch] { kill_latch.Signal(); });
}));
kill_latch.Wait();
// Check that the FFI call was executed on the platform thread.
ASSERT_EQ(platform_thread_id, ffi_call_thread_id);
}
} // namespace testing
} // namespace flutter