1// Copyright 2013 The Flutter 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#define FML_USED_ON_EMBEDDER
6
7#include "flutter/fml/task_runner.h"
8#include "flutter/fml/memory/task_runner_checker.h"
9
10#include <utility>
11
12#include "flutter/fml/logging.h"
13#include "flutter/fml/message_loop.h"
14#include "flutter/fml/message_loop_impl.h"
15#include "flutter/fml/message_loop_task_queues.h"
16
17namespace fml {
18
19TaskRunner::TaskRunner(fml::RefPtr<MessageLoopImpl> loop)
20 : loop_(std::move(loop)) {}
21
22TaskRunner::~TaskRunner() = default;
23
24void TaskRunner::PostTask(const fml::closure& task) {
25 loop_->PostTask(task, fml::TimePoint::Now());
26}
27
28void TaskRunner::PostTaskForTime(const fml::closure& task,
29 fml::TimePoint target_time) {
30 loop_->PostTask(task, target_time);
31}
32
33void TaskRunner::PostDelayedTask(const fml::closure& task,
34 fml::TimeDelta delay) {
35 loop_->PostTask(task, fml::TimePoint::Now() + delay);
36}
37
38TaskQueueId TaskRunner::GetTaskQueueId() {
39 FML_DCHECK(loop_);
40 return loop_->GetTaskQueueId();
41}
42
43bool TaskRunner::RunsTasksOnCurrentThread() {
44 if (!fml::MessageLoop::IsInitializedForCurrentThread()) {
45 return false;
46 }
47
48 const auto current_queue_id = MessageLoop::GetCurrentTaskQueueId();
49 const auto loop_queue_id = loop_->GetTaskQueueId();
50
51 return TaskRunnerChecker::RunsOnTheSameThread(current_queue_id,
52 loop_queue_id);
53}
54
55void TaskRunner::RunNowOrPostTask(fml::RefPtr<fml::TaskRunner> runner,
56 const fml::closure& task) {
57 FML_DCHECK(runner);
58 if (runner->RunsTasksOnCurrentThread()) {
59 task();
60 } else {
61 runner->PostTask(std::move(task));
62 }
63}
64
65} // namespace fml
66