platform.rs

  1// todo(windows): remove
  2#![allow(unused_variables)]
  3
  4use std::{
  5    cell::{Cell, RefCell},
  6    ffi::{c_uint, c_void, OsString},
  7    mem::transmute,
  8    os::windows::ffi::{OsStrExt, OsStringExt},
  9    path::{Path, PathBuf},
 10    rc::Rc,
 11    sync::{Arc, OnceLock},
 12    time::Duration,
 13};
 14
 15use ::util::{ResultExt, SemanticVersion};
 16use anyhow::{anyhow, Result};
 17use async_task::Runnable;
 18use copypasta::{ClipboardContext, ClipboardProvider};
 19use futures::channel::oneshot::{self, Receiver};
 20use itertools::Itertools;
 21use parking_lot::{Mutex, RwLock};
 22use smallvec::SmallVec;
 23use time::UtcOffset;
 24use windows::{
 25    core::*,
 26    Wdk::System::SystemServices::*,
 27    Win32::{
 28        Foundation::*,
 29        Graphics::Gdi::*,
 30        Media::*,
 31        System::{Com::*, LibraryLoader::*, Ole::*, Threading::*, Time::*},
 32        UI::{Input::KeyboardAndMouse::*, Shell::*, WindowsAndMessaging::*},
 33    },
 34};
 35
 36use crate::*;
 37
 38pub(crate) struct WindowsPlatform {
 39    inner: Rc<WindowsPlatformInner>,
 40}
 41
 42/// Windows settings pulled from SystemParametersInfo
 43/// https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-systemparametersinfow
 44#[derive(Default, Debug)]
 45pub(crate) struct WindowsPlatformSystemSettings {
 46    /// SEE: SPI_GETWHEELSCROLLCHARS
 47    pub(crate) wheel_scroll_chars: u32,
 48
 49    /// SEE: SPI_GETWHEELSCROLLLINES
 50    pub(crate) wheel_scroll_lines: u32,
 51}
 52
 53pub(crate) struct WindowsPlatformInner {
 54    background_executor: BackgroundExecutor,
 55    pub(crate) foreground_executor: ForegroundExecutor,
 56    main_receiver: flume::Receiver<Runnable>,
 57    text_system: Arc<WindowsTextSystem>,
 58    callbacks: Mutex<Callbacks>,
 59    pub raw_window_handles: RwLock<SmallVec<[HWND; 4]>>,
 60    pub(crate) dispatch_event: HANDLE,
 61    pub(crate) settings: RefCell<WindowsPlatformSystemSettings>,
 62}
 63
 64impl WindowsPlatformInner {
 65    pub(crate) fn try_get_windows_inner_from_hwnd(
 66        &self,
 67        hwnd: HWND,
 68    ) -> Option<Rc<WindowsWindowInner>> {
 69        self.raw_window_handles
 70            .read()
 71            .iter()
 72            .find(|entry| *entry == &hwnd)
 73            .and_then(|hwnd| try_get_window_inner(*hwnd))
 74    }
 75}
 76
 77impl Drop for WindowsPlatformInner {
 78    fn drop(&mut self) {
 79        unsafe { CloseHandle(self.dispatch_event) }.ok();
 80    }
 81}
 82
 83#[derive(Default)]
 84struct Callbacks {
 85    open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
 86    become_active: Option<Box<dyn FnMut()>>,
 87    resign_active: Option<Box<dyn FnMut()>>,
 88    quit: Option<Box<dyn FnMut()>>,
 89    reopen: Option<Box<dyn FnMut()>>,
 90    event: Option<Box<dyn FnMut(PlatformInput) -> bool>>,
 91    app_menu_action: Option<Box<dyn FnMut(&dyn Action)>>,
 92    will_open_app_menu: Option<Box<dyn FnMut()>>,
 93    validate_app_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
 94}
 95
 96enum WindowsMessageWaitResult {
 97    ForegroundExecution,
 98    WindowsMessage(MSG),
 99    Error,
100}
101
102impl WindowsPlatformSystemSettings {
103    fn new() -> Self {
104        let mut settings = Self::default();
105        settings.update_all();
106        settings
107    }
108
109    pub(crate) fn update_all(&mut self) {
110        self.update_wheel_scroll_lines();
111        self.update_wheel_scroll_chars();
112    }
113
114    pub(crate) fn update_wheel_scroll_lines(&mut self) {
115        let mut value = c_uint::default();
116        let result = unsafe {
117            SystemParametersInfoW(
118                SPI_GETWHEELSCROLLLINES,
119                0,
120                Some((&mut value) as *mut c_uint as *mut c_void),
121                SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS::default(),
122            )
123        };
124
125        if result.log_err() != None {
126            self.wheel_scroll_lines = value;
127        }
128    }
129
130    pub(crate) fn update_wheel_scroll_chars(&mut self) {
131        let mut value = c_uint::default();
132        let result = unsafe {
133            SystemParametersInfoW(
134                SPI_GETWHEELSCROLLCHARS,
135                0,
136                Some((&mut value) as *mut c_uint as *mut c_void),
137                SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS::default(),
138            )
139        };
140
141        if result.log_err() != None {
142            self.wheel_scroll_chars = value;
143        }
144    }
145}
146
147impl WindowsPlatform {
148    pub(crate) fn new() -> Self {
149        unsafe {
150            OleInitialize(None).expect("unable to initialize Windows OLE");
151        }
152        let (main_sender, main_receiver) = flume::unbounded::<Runnable>();
153        let dispatch_event = unsafe { CreateEventW(None, false, false, None) }.unwrap();
154        let dispatcher = Arc::new(WindowsDispatcher::new(main_sender, dispatch_event));
155        let background_executor = BackgroundExecutor::new(dispatcher.clone());
156        let foreground_executor = ForegroundExecutor::new(dispatcher);
157        let text_system = Arc::new(WindowsTextSystem::new());
158        let callbacks = Mutex::new(Callbacks::default());
159        let raw_window_handles = RwLock::new(SmallVec::new());
160        let settings = RefCell::new(WindowsPlatformSystemSettings::new());
161        let inner = Rc::new(WindowsPlatformInner {
162            background_executor,
163            foreground_executor,
164            main_receiver,
165            text_system,
166            callbacks,
167            raw_window_handles,
168            dispatch_event,
169            settings,
170        });
171        Self { inner }
172    }
173
174    fn run_foreground_tasks(&self) {
175        for runnable in self.inner.main_receiver.drain() {
176            runnable.run();
177        }
178    }
179
180    fn redraw_all(&self) {
181        for handle in self.inner.raw_window_handles.read().iter() {
182            unsafe {
183                RedrawWindow(
184                    *handle,
185                    None,
186                    HRGN::default(),
187                    RDW_INVALIDATE | RDW_UPDATENOW,
188                );
189            }
190        }
191    }
192}
193
194impl Platform for WindowsPlatform {
195    fn background_executor(&self) -> BackgroundExecutor {
196        self.inner.background_executor.clone()
197    }
198
199    fn foreground_executor(&self) -> ForegroundExecutor {
200        self.inner.foreground_executor.clone()
201    }
202
203    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
204        self.inner.text_system.clone()
205    }
206
207    fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>) {
208        on_finish_launching();
209        let dispatch_event = self.inner.dispatch_event;
210        let vsync_event = unsafe { CreateEventW(None, false, false, None) }.unwrap();
211        let timer_stop_event = unsafe { CreateEventW(None, false, false, None) }.unwrap();
212        begin_vsync_timer(vsync_event, timer_stop_event);
213        'a: loop {
214            let wait_result = unsafe {
215                MsgWaitForMultipleObjects(
216                    Some(&[vsync_event, dispatch_event]),
217                    false,
218                    INFINITE,
219                    QS_ALLINPUT,
220                )
221            };
222
223            match wait_result {
224                // compositor clock ticked so we should draw a frame
225                WAIT_EVENT(0) => {
226                    self.redraw_all();
227                }
228                // foreground tasks are dispatched
229                WAIT_EVENT(1) => {
230                    self.run_foreground_tasks();
231                }
232                // Windows thread messages are posted
233                WAIT_EVENT(2) => {
234                    let mut msg = MSG::default();
235                    unsafe {
236                        while PeekMessageW(&mut msg, HWND::default(), 0, 0, PM_REMOVE).as_bool() {
237                            if msg.message == WM_QUIT {
238                                break 'a;
239                            }
240                            if msg.message == WM_SETTINGCHANGE {
241                                self.inner.settings.borrow_mut().update_all();
242                                continue;
243                            }
244                            TranslateMessage(&msg);
245                            DispatchMessageW(&msg);
246                        }
247                    }
248                }
249                _ => {
250                    log::error!("Something went wrong while waiting {:?}", wait_result);
251                    break;
252                }
253            }
254        }
255        end_vsync_timer(timer_stop_event);
256        unsafe { CloseHandle(dispatch_event) }.log_err();
257
258        let mut callbacks = self.inner.callbacks.lock();
259        if let Some(callback) = callbacks.quit.as_mut() {
260            callback()
261        }
262    }
263
264    fn quit(&self) {
265        self.foreground_executor()
266            .spawn(async { unsafe { PostQuitMessage(0) } })
267            .detach();
268    }
269
270    // todo(windows)
271    fn restart(&self) {
272        unimplemented!()
273    }
274
275    // todo(windows)
276    fn activate(&self, ignoring_other_apps: bool) {}
277
278    // todo(windows)
279    fn hide(&self) {
280        unimplemented!()
281    }
282
283    // todo(windows)
284    fn hide_other_apps(&self) {
285        unimplemented!()
286    }
287
288    // todo(windows)
289    fn unhide_other_apps(&self) {
290        unimplemented!()
291    }
292
293    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
294        WindowsDisplay::displays()
295    }
296
297    fn display(&self, id: crate::DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
298        if let Some(display) = WindowsDisplay::new(id) {
299            Some(Rc::new(display) as Rc<dyn PlatformDisplay>)
300        } else {
301            None
302        }
303    }
304
305    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
306        if let Some(display) = WindowsDisplay::primary_monitor() {
307            Some(Rc::new(display) as Rc<dyn PlatformDisplay>)
308        } else {
309            None
310        }
311    }
312
313    fn active_window(&self) -> Option<AnyWindowHandle> {
314        let active_window_hwnd = unsafe { GetActiveWindow() };
315        self.inner
316            .try_get_windows_inner_from_hwnd(active_window_hwnd)
317            .map(|inner| inner.handle)
318    }
319
320    fn open_window(
321        &self,
322        handle: AnyWindowHandle,
323        options: WindowParams,
324    ) -> Box<dyn PlatformWindow> {
325        Box::new(WindowsWindow::new(self.inner.clone(), handle, options))
326    }
327
328    // todo(windows)
329    fn window_appearance(&self) -> WindowAppearance {
330        WindowAppearance::Dark
331    }
332
333    fn open_url(&self, url: &str) {
334        let url_string = url.to_string();
335        self.background_executor()
336            .spawn(async move {
337                if url_string.is_empty() {
338                    return;
339                }
340                open_target(url_string.as_str());
341            })
342            .detach();
343    }
344
345    // todo(windows)
346    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
347        self.inner.callbacks.lock().open_urls = Some(callback);
348    }
349
350    fn prompt_for_paths(&self, options: PathPromptOptions) -> Receiver<Option<Vec<PathBuf>>> {
351        let (tx, rx) = oneshot::channel();
352
353        self.foreground_executor()
354            .spawn(async move {
355                let tx = Cell::new(Some(tx));
356
357                // create file open dialog
358                let folder_dialog: IFileOpenDialog = unsafe {
359                    CoCreateInstance::<std::option::Option<&IUnknown>, IFileOpenDialog>(
360                        &FileOpenDialog,
361                        None,
362                        CLSCTX_ALL,
363                    )
364                    .unwrap()
365                };
366
367                // dialog options
368                let mut dialog_options: FILEOPENDIALOGOPTIONS = FOS_FILEMUSTEXIST;
369                if options.multiple {
370                    dialog_options |= FOS_ALLOWMULTISELECT;
371                }
372                if options.directories {
373                    dialog_options |= FOS_PICKFOLDERS;
374                }
375
376                unsafe {
377                    folder_dialog.SetOptions(dialog_options).unwrap();
378                    folder_dialog
379                        .SetTitle(&HSTRING::from(OsString::from("Select a folder")))
380                        .unwrap();
381                }
382
383                let hr = unsafe { folder_dialog.Show(None) };
384
385                if hr.is_err() {
386                    if hr.unwrap_err().code() == HRESULT(0x800704C7u32 as i32) {
387                        // user canceled error
388                        if let Some(tx) = tx.take() {
389                            tx.send(None).unwrap();
390                        }
391                        return;
392                    }
393                }
394
395                let mut results = unsafe { folder_dialog.GetResults().unwrap() };
396
397                let mut paths: Vec<PathBuf> = Vec::new();
398                for i in 0..unsafe { results.GetCount().unwrap() } {
399                    let mut item: IShellItem = unsafe { results.GetItemAt(i).unwrap() };
400                    let mut path: PWSTR =
401                        unsafe { item.GetDisplayName(SIGDN_FILESYSPATH).unwrap() };
402                    let mut path_os_string = OsString::from_wide(unsafe { path.as_wide() });
403
404                    paths.push(PathBuf::from(path_os_string));
405                }
406
407                if let Some(tx) = tx.take() {
408                    if paths.len() == 0 {
409                        tx.send(None).unwrap();
410                    } else {
411                        tx.send(Some(paths)).unwrap();
412                    }
413                }
414            })
415            .detach();
416
417        rx
418    }
419
420    fn prompt_for_new_path(&self, directory: &Path) -> Receiver<Option<PathBuf>> {
421        let directory = directory.to_owned();
422        let (tx, rx) = oneshot::channel();
423        self.foreground_executor()
424            .spawn(async move {
425                unsafe {
426                    let Ok(dialog) = show_savefile_dialog(directory) else {
427                        let _ = tx.send(None);
428                        return;
429                    };
430                    let Ok(_) = dialog.Show(None) else {
431                        let _ = tx.send(None); // user cancel
432                        return;
433                    };
434                    if let Ok(shell_item) = dialog.GetResult() {
435                        if let Ok(file) = shell_item.GetDisplayName(SIGDN_FILESYSPATH) {
436                            let _ = tx.send(Some(PathBuf::from(file.to_string().unwrap())));
437                            return;
438                        }
439                    }
440                    let _ = tx.send(None);
441                }
442            })
443            .detach();
444
445        rx
446    }
447
448    fn reveal_path(&self, path: &Path) {
449        let Ok(file_full_path) = path.canonicalize() else {
450            log::error!("unable to parse file path");
451            return;
452        };
453        self.background_executor()
454            .spawn(async move {
455                let Some(path) = file_full_path.to_str() else {
456                    return;
457                };
458                if path.is_empty() {
459                    return;
460                }
461                open_target(path);
462            })
463            .detach();
464    }
465
466    fn on_become_active(&self, callback: Box<dyn FnMut()>) {
467        self.inner.callbacks.lock().become_active = Some(callback);
468    }
469
470    fn on_resign_active(&self, callback: Box<dyn FnMut()>) {
471        self.inner.callbacks.lock().resign_active = Some(callback);
472    }
473
474    fn on_quit(&self, callback: Box<dyn FnMut()>) {
475        self.inner.callbacks.lock().quit = Some(callback);
476    }
477
478    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
479        self.inner.callbacks.lock().reopen = Some(callback);
480    }
481
482    fn on_event(&self, callback: Box<dyn FnMut(PlatformInput) -> bool>) {
483        self.inner.callbacks.lock().event = Some(callback);
484    }
485
486    // todo(windows)
487    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {}
488
489    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
490        self.inner.callbacks.lock().app_menu_action = Some(callback);
491    }
492
493    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
494        self.inner.callbacks.lock().will_open_app_menu = Some(callback);
495    }
496
497    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
498        self.inner.callbacks.lock().validate_app_menu_command = Some(callback);
499    }
500
501    fn os_name(&self) -> &'static str {
502        "Windows"
503    }
504
505    fn os_version(&self) -> Result<SemanticVersion> {
506        let mut info = unsafe { std::mem::zeroed() };
507        let status = unsafe { RtlGetVersion(&mut info) };
508        if status.is_ok() {
509            Ok(SemanticVersion {
510                major: info.dwMajorVersion as _,
511                minor: info.dwMinorVersion as _,
512                patch: info.dwBuildNumber as _,
513            })
514        } else {
515            Err(anyhow::anyhow!(
516                "unable to get Windows version: {}",
517                std::io::Error::last_os_error()
518            ))
519        }
520    }
521
522    fn app_version(&self) -> Result<SemanticVersion> {
523        Ok(SemanticVersion {
524            major: 1,
525            minor: 0,
526            patch: 0,
527        })
528    }
529
530    // todo(windows)
531    fn app_path(&self) -> Result<PathBuf> {
532        Err(anyhow!("not yet implemented"))
533    }
534
535    fn local_timezone(&self) -> UtcOffset {
536        let mut info = unsafe { std::mem::zeroed() };
537        let ret = unsafe { GetTimeZoneInformation(&mut info) };
538        if ret == TIME_ZONE_ID_INVALID {
539            log::error!(
540                "Unable to get local timezone: {}",
541                std::io::Error::last_os_error()
542            );
543            return UtcOffset::UTC;
544        }
545        // Windows treat offset as:
546        // UTC = localtime + offset
547        // so we add a minus here
548        let hours = -info.Bias / 60;
549        let minutes = -info.Bias % 60;
550
551        UtcOffset::from_hms(hours as _, minutes as _, 0).unwrap()
552    }
553
554    fn double_click_interval(&self) -> Duration {
555        let millis = unsafe { GetDoubleClickTime() };
556        Duration::from_millis(millis as _)
557    }
558
559    // todo(windows)
560    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
561        Err(anyhow!("not yet implemented"))
562    }
563
564    fn set_cursor_style(&self, style: CursorStyle) {
565        let handle = match style {
566            CursorStyle::IBeam | CursorStyle::IBeamCursorForVerticalLayout => unsafe {
567                load_cursor(IDC_IBEAM)
568            },
569            CursorStyle::Crosshair => unsafe { load_cursor(IDC_CROSS) },
570            CursorStyle::PointingHand | CursorStyle::DragLink => unsafe { load_cursor(IDC_HAND) },
571            CursorStyle::ResizeLeft | CursorStyle::ResizeRight | CursorStyle::ResizeLeftRight => unsafe {
572                load_cursor(IDC_SIZEWE)
573            },
574            CursorStyle::ResizeUp | CursorStyle::ResizeDown | CursorStyle::ResizeUpDown => unsafe {
575                load_cursor(IDC_SIZENS)
576            },
577            CursorStyle::OperationNotAllowed => unsafe { load_cursor(IDC_NO) },
578            _ => unsafe { load_cursor(IDC_ARROW) },
579        };
580        if handle.is_err() {
581            log::error!(
582                "Error loading cursor image: {}",
583                std::io::Error::last_os_error()
584            );
585            return;
586        }
587        let _ = unsafe { SetCursor(HCURSOR(handle.unwrap().0)) };
588    }
589
590    // todo(windows)
591    fn should_auto_hide_scrollbars(&self) -> bool {
592        false
593    }
594
595    fn write_to_clipboard(&self, item: ClipboardItem) {
596        let mut ctx = ClipboardContext::new().unwrap();
597        ctx.set_contents(item.text().to_owned()).unwrap();
598    }
599
600    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
601        let mut ctx = ClipboardContext::new().unwrap();
602        let content = ctx.get_contents().unwrap();
603        Some(ClipboardItem {
604            text: content,
605            metadata: None,
606        })
607    }
608
609    // todo(windows)
610    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
611        Task::Ready(Some(Err(anyhow!("not implemented yet."))))
612    }
613
614    // todo(windows)
615    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
616        Task::Ready(Some(Err(anyhow!("not implemented yet."))))
617    }
618
619    // todo(windows)
620    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
621        Task::Ready(Some(Err(anyhow!("not implemented yet."))))
622    }
623
624    fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
625        Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
626    }
627}
628
629impl Drop for WindowsPlatform {
630    fn drop(&mut self) {
631        unsafe {
632            OleUninitialize();
633        }
634    }
635}
636
637unsafe fn load_cursor(name: PCWSTR) -> Result<HANDLE> {
638    LoadImageW(None, name, IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE | LR_SHARED).map_err(|e| anyhow!(e))
639}
640
641fn open_target(target: &str) {
642    unsafe {
643        let ret = ShellExecuteW(
644            None,
645            windows::core::w!("open"),
646            &HSTRING::from(target),
647            None,
648            None,
649            SW_SHOWDEFAULT,
650        );
651        if ret.0 <= 32 {
652            log::error!("Unable to open target: {}", std::io::Error::last_os_error());
653        }
654    }
655}
656
657unsafe fn show_savefile_dialog(directory: PathBuf) -> Result<IFileSaveDialog> {
658    let dialog: IFileSaveDialog = CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)?;
659    let bind_context = CreateBindCtx(0)?;
660    let Ok(full_path) = directory.canonicalize() else {
661        return Ok(dialog);
662    };
663    let dir_str = full_path.into_os_string();
664    if dir_str.is_empty() {
665        return Ok(dialog);
666    }
667    let dir_vec = dir_str.encode_wide().collect_vec();
668    let ret = SHCreateItemFromParsingName(PCWSTR::from_raw(dir_vec.as_ptr()), &bind_context)
669        .inspect_err(|e| log::error!("unable to create IShellItem: {}", e));
670    if ret.is_ok() {
671        let dir_shell_item: IShellItem = ret.unwrap();
672        let _ = dialog
673            .SetFolder(&dir_shell_item)
674            .inspect_err(|e| log::error!("unable to set folder for save file dialog: {}", e));
675    }
676
677    Ok(dialog)
678}
679
680fn begin_vsync_timer(vsync_event: HANDLE, timer_stop_event: HANDLE) {
681    let vsync_fn = select_vsync_fn();
682    std::thread::spawn(move || {
683        while vsync_fn(timer_stop_event) {
684            if unsafe { SetEvent(vsync_event) }.log_err().is_none() {
685                break;
686            }
687        }
688        unsafe { CloseHandle(timer_stop_event) }.log_err();
689    });
690}
691
692fn end_vsync_timer(timer_stop_event: HANDLE) {
693    unsafe { SetEvent(timer_stop_event) }.log_err();
694}
695
696fn select_vsync_fn() -> Box<dyn Fn(HANDLE) -> bool + Send> {
697    if let Some(dcomp_fn) = load_dcomp_vsync_fn() {
698        log::info!("use DCompositionWaitForCompositorClock for vsync");
699        return Box::new(move |timer_stop_event| {
700            // will be 0 if woken up by timer_stop_event or 1 if the compositor clock ticked
701            // SEE: https://learn.microsoft.com/en-us/windows/win32/directcomp/compositor-clock/compositor-clock
702            (unsafe { dcomp_fn(1, &timer_stop_event, INFINITE) }) == 1
703        });
704    }
705    log::info!("use fallback vsync function");
706    Box::new(fallback_vsync_fn())
707}
708
709fn load_dcomp_vsync_fn() -> Option<unsafe extern "system" fn(u32, *const HANDLE, u32) -> u32> {
710    static FN: OnceLock<Option<unsafe extern "system" fn(u32, *const HANDLE, u32) -> u32>> =
711        OnceLock::new();
712    *FN.get_or_init(|| {
713        let hmodule = unsafe { LoadLibraryW(windows::core::w!("dcomp.dll")) }.ok()?;
714        let address = unsafe {
715            GetProcAddress(
716                hmodule,
717                windows::core::s!("DCompositionWaitForCompositorClock"),
718            )
719        }?;
720        Some(unsafe { transmute(address) })
721    })
722}
723
724fn fallback_vsync_fn() -> impl Fn(HANDLE) -> bool + Send {
725    let freq = WindowsDisplay::primary_monitor()
726        .and_then(|monitor| monitor.frequency())
727        .unwrap_or(60);
728    log::info!("primaly refresh rate is {freq}Hz");
729
730    let interval = (1000 / freq).max(1);
731    log::info!("expected interval is {interval}ms");
732
733    unsafe { timeBeginPeriod(1) };
734
735    struct TimePeriod;
736    impl Drop for TimePeriod {
737        fn drop(&mut self) {
738            unsafe { timeEndPeriod(1) };
739        }
740    }
741    let period = TimePeriod;
742
743    move |timer_stop_event| {
744        let _ = (&period,);
745        (unsafe { WaitForSingleObject(timer_stop_event, interval) }) == WAIT_TIMEOUT
746    }
747}