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 #ifndef FLUTTER_SHELL_PLATFORM_GLFW_GLFW_EVENT_LOOP_H_ 6 #define FLUTTER_SHELL_PLATFORM_GLFW_GLFW_EVENT_LOOP_H_ 7 8 #include <chrono> 9 #include <deque> 10 #include <mutex> 11 #include <queue> 12 #include <thread> 13 #include <condition_variable> 14 15 #include "flutter/shell/platform/embedder/embedder.h" 16 17 namespace flutter { 18 19 // An event loop implementation that supports Flutter Engine tasks scheduling in 20 // the GLFW event loop. 21 class GLFWEventLoop { 22 public: 23 using TaskExpiredCallback = std::function<void(const FlutterTask*)>; 24 GLFWEventLoop(std::thread::id main_thread_id, 25 TaskExpiredCallback on_task_expired); 26 27 ~GLFWEventLoop(); 28 29 // Returns if the current thread is the thread used by the GLFW event loop. 30 bool RunsTasksOnCurrentThread() const; 31 32 // Wait for an any GLFW or pending Flutter Engine events and returns when 33 // either is encountered. Expired engine events are processed. The optional 34 // timeout should only be used when non-GLFW or engine events need to be 35 // processed in a polling manner. 36 void WaitForEvents( 37 std::chrono::nanoseconds max_wait = std::chrono::nanoseconds::max()); 38 39 // Post a Flutter engine tasks to the event loop for delayed execution. 40 void PostTask(FlutterTask flutter_task, uint64_t flutter_target_time_nanos); 41 42 private: 43 using TaskTimePoint = std::chrono::steady_clock::time_point; 44 struct Task { 45 uint64_t order; 46 TaskTimePoint fire_time; 47 FlutterTask task; 48 49 struct Comparer { operatorTask::Comparer50 bool operator()(const Task& a, const Task& b) { 51 if (a.fire_time == b.fire_time) { 52 return a.order > b.order; 53 } 54 return a.fire_time > b.fire_time; 55 } 56 }; 57 }; 58 std::thread::id main_thread_id_; 59 TaskExpiredCallback on_task_expired_; 60 std::mutex task_queue_mutex_; 61 std::priority_queue<Task, std::deque<Task>, Task::Comparer> task_queue_; 62 std::condition_variable task_queue_cv_; 63 64 GLFWEventLoop(const GLFWEventLoop&) = delete; 65 66 GLFWEventLoop& operator=(const GLFWEventLoop&) = delete; 67 68 static TaskTimePoint TimePointFromFlutterTime( 69 uint64_t flutter_target_time_nanos); 70 }; 71 72 } // namespace flutter 73 74 #endif // FLUTTER_SHELL_PLATFORM_GLFW_GLFW_EVENT_LOOP_H_ 75