dispatcher.rs

  1use std::{
  2    thread::{ThreadId, current},
  3    time::Duration,
  4};
  5
  6use async_task::Runnable;
  7use flume::Sender;
  8use parking::Parker;
  9use parking_lot::Mutex;
 10use util::ResultExt;
 11use windows::{
 12    System::Threading::{
 13        ThreadPool, ThreadPoolTimer, TimerElapsedHandler, WorkItemHandler, WorkItemPriority,
 14    },
 15    Win32::{
 16        Foundation::{LPARAM, WPARAM},
 17        UI::WindowsAndMessaging::PostMessageW,
 18    },
 19};
 20
 21use crate::{
 22    HWND, PlatformDispatcher, SafeHwnd, TaskLabel, WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD,
 23};
 24
 25pub(crate) struct WindowsDispatcher {
 26    main_sender: Sender<Runnable>,
 27    parker: Mutex<Parker>,
 28    main_thread_id: ThreadId,
 29    platform_window_handle: SafeHwnd,
 30    validation_number: usize,
 31}
 32
 33impl WindowsDispatcher {
 34    pub(crate) fn new(
 35        main_sender: Sender<Runnable>,
 36        platform_window_handle: HWND,
 37        validation_number: usize,
 38    ) -> Self {
 39        let parker = Mutex::new(Parker::new());
 40        let main_thread_id = current().id();
 41        let platform_window_handle = platform_window_handle.into();
 42
 43        WindowsDispatcher {
 44            main_sender,
 45            parker,
 46            main_thread_id,
 47            platform_window_handle,
 48            validation_number,
 49        }
 50    }
 51
 52    fn dispatch_on_threadpool(&self, runnable: Runnable) {
 53        let handler = {
 54            let mut task_wrapper = Some(runnable);
 55            WorkItemHandler::new(move |_| {
 56                task_wrapper.take().unwrap().run();
 57                Ok(())
 58            })
 59        };
 60        ThreadPool::RunWithPriorityAsync(&handler, WorkItemPriority::High).log_err();
 61    }
 62
 63    fn dispatch_on_threadpool_after(&self, runnable: Runnable, duration: Duration) {
 64        let handler = {
 65            let mut task_wrapper = Some(runnable);
 66            TimerElapsedHandler::new(move |_| {
 67                task_wrapper.take().unwrap().run();
 68                Ok(())
 69            })
 70        };
 71        ThreadPoolTimer::CreateTimer(&handler, duration.into()).log_err();
 72    }
 73}
 74
 75impl PlatformDispatcher for WindowsDispatcher {
 76    fn is_main_thread(&self) -> bool {
 77        current().id() == self.main_thread_id
 78    }
 79
 80    fn dispatch(&self, runnable: Runnable, label: Option<TaskLabel>) {
 81        self.dispatch_on_threadpool(runnable);
 82        if let Some(label) = label {
 83            log::debug!("TaskLabel: {label:?}");
 84        }
 85    }
 86
 87    fn dispatch_on_main_thread(&self, runnable: Runnable) {
 88        match self.main_sender.send(runnable) {
 89            Ok(_) => unsafe {
 90                PostMessageW(
 91                    Some(self.platform_window_handle.as_raw()),
 92                    WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD,
 93                    WPARAM(self.validation_number),
 94                    LPARAM(0),
 95                )
 96                .log_err();
 97            },
 98            Err(runnable) => {
 99                // NOTE: Runnable may wrap a Future that is !Send.
100                //
101                // This is usually safe because we only poll it on the main thread.
102                // However if the send fails, we know that:
103                // 1. main_receiver has been dropped (which implies the app is shutting down)
104                // 2. we are on a background thread.
105                // It is not safe to drop something !Send on the wrong thread, and
106                // the app will exit soon anyway, so we must forget the runnable.
107                std::mem::forget(runnable);
108            }
109        }
110    }
111
112    fn dispatch_after(&self, duration: Duration, runnable: Runnable) {
113        self.dispatch_on_threadpool_after(runnable, duration);
114    }
115
116    fn park(&self, timeout: Option<Duration>) -> bool {
117        if let Some(timeout) = timeout {
118            self.parker.lock().park_timeout(timeout)
119        } else {
120            self.parker.lock().park();
121            true
122        }
123    }
124
125    fn unparker(&self) -> parking::Unparker {
126        self.parker.lock().unparker()
127    }
128}