1use std::{
2 sync::atomic::{AtomicBool, Ordering},
3 thread::{ThreadId, current},
4 time::{Duration, Instant},
5};
6
7use flume::Sender;
8use util::ResultExt;
9use windows::{
10 System::Threading::{ThreadPool, ThreadPoolTimer, TimerElapsedHandler, WorkItemHandler},
11 Win32::{
12 Foundation::{LPARAM, WPARAM},
13 UI::WindowsAndMessaging::PostMessageW,
14 },
15};
16
17use crate::{
18 GLOBAL_THREAD_TIMINGS, HWND, PlatformDispatcher, RunnableVariant, SafeHwnd, THREAD_TIMINGS,
19 TaskLabel, TaskTiming, ThreadTaskTimings, WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD,
20};
21
22pub(crate) struct WindowsDispatcher {
23 pub(crate) wake_posted: AtomicBool,
24 main_sender: Sender<RunnableVariant>,
25 main_thread_id: ThreadId,
26 pub(crate) platform_window_handle: SafeHwnd,
27 validation_number: usize,
28}
29
30impl WindowsDispatcher {
31 pub(crate) fn new(
32 main_sender: Sender<RunnableVariant>,
33 platform_window_handle: HWND,
34 validation_number: usize,
35 ) -> Self {
36 let main_thread_id = current().id();
37 let platform_window_handle = platform_window_handle.into();
38
39 WindowsDispatcher {
40 main_sender,
41 main_thread_id,
42 platform_window_handle,
43 validation_number,
44 wake_posted: AtomicBool::new(false),
45 }
46 }
47
48 fn dispatch_on_threadpool(&self, runnable: RunnableVariant) {
49 let handler = {
50 let mut task_wrapper = Some(runnable);
51 WorkItemHandler::new(move |_| {
52 Self::execute_runnable(task_wrapper.take().unwrap());
53 Ok(())
54 })
55 };
56 ThreadPool::RunAsync(&handler).log_err();
57 }
58
59 fn dispatch_on_threadpool_after(&self, runnable: RunnableVariant, duration: Duration) {
60 let handler = {
61 let mut task_wrapper = Some(runnable);
62 TimerElapsedHandler::new(move |_| {
63 Self::execute_runnable(task_wrapper.take().unwrap());
64 Ok(())
65 })
66 };
67 ThreadPoolTimer::CreateTimer(&handler, duration.into()).log_err();
68 }
69
70 #[inline(always)]
71 pub(crate) fn execute_runnable(runnable: RunnableVariant) {
72 let start = Instant::now();
73
74 let mut timing = match runnable {
75 RunnableVariant::Meta(runnable) => {
76 let location = runnable.metadata().location;
77 let timing = TaskTiming {
78 location,
79 start,
80 end: None,
81 };
82 Self::add_task_timing(timing);
83
84 runnable.run();
85
86 timing
87 }
88 RunnableVariant::Compat(runnable) => {
89 let timing = TaskTiming {
90 location: core::panic::Location::caller(),
91 start,
92 end: None,
93 };
94 Self::add_task_timing(timing);
95
96 runnable.run();
97
98 timing
99 }
100 };
101
102 let end = Instant::now();
103 timing.end = Some(end);
104
105 Self::add_task_timing(timing);
106 }
107
108 pub(crate) fn add_task_timing(timing: TaskTiming) {
109 THREAD_TIMINGS.with(|timings| {
110 let mut timings = timings.lock();
111 let timings = &mut timings.timings;
112
113 if let Some(last_timing) = timings.iter_mut().rev().next() {
114 if last_timing.location == timing.location {
115 last_timing.end = timing.end;
116 return;
117 }
118 }
119
120 timings.push_back(timing);
121 });
122 }
123}
124
125impl PlatformDispatcher for WindowsDispatcher {
126 fn get_all_timings(&self) -> Vec<ThreadTaskTimings> {
127 let global_thread_timings = GLOBAL_THREAD_TIMINGS.lock();
128 ThreadTaskTimings::convert(&global_thread_timings)
129 }
130
131 fn get_current_thread_timings(&self) -> Vec<crate::TaskTiming> {
132 THREAD_TIMINGS.with(|timings| {
133 let timings = timings.lock();
134 let timings = &timings.timings;
135
136 let mut vec = Vec::with_capacity(timings.len());
137
138 let (s1, s2) = timings.as_slices();
139 vec.extend_from_slice(s1);
140 vec.extend_from_slice(s2);
141 vec
142 })
143 }
144
145 fn is_main_thread(&self) -> bool {
146 current().id() == self.main_thread_id
147 }
148
149 fn dispatch(
150 &self,
151 runnable: RunnableVariant,
152 label: Option<TaskLabel>,
153 _priority: gpui::Priority,
154 ) {
155 self.dispatch_on_threadpool(runnable);
156 if let Some(label) = label {
157 log::debug!("TaskLabel: {label:?}");
158 }
159 }
160
161 fn dispatch_on_main_thread(&self, runnable: RunnableVariant, _priority: gpui::Priority) {
162 match self.main_sender.send(runnable) {
163 Ok(_) => {
164 if !self.wake_posted.swap(true, Ordering::AcqRel) {
165 unsafe {
166 PostMessageW(
167 Some(self.platform_window_handle.as_raw()),
168 WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD,
169 WPARAM(self.validation_number),
170 LPARAM(0),
171 )
172 .log_err();
173 }
174 }
175 }
176 Err(runnable) => {
177 // NOTE: Runnable may wrap a Future that is !Send.
178 //
179 // This is usually safe because we only poll it on the main thread.
180 // However if the send fails, we know that:
181 // 1. main_receiver has been dropped (which implies the app is shutting down)
182 // 2. we are on a background thread.
183 // It is not safe to drop something !Send on the wrong thread, and
184 // the app will exit soon anyway, so we must forget the runnable.
185 std::mem::forget(runnable);
186 }
187 }
188 }
189
190 fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant) {
191 self.dispatch_on_threadpool_after(runnable, duration);
192 }
193
194 fn spawn_realtime(&self, _priority: crate::RealtimePriority, _f: Box<dyn FnOnce() + Send>) {
195 // disabled on windows for now.
196 unimplemented!();
197 }
198}