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