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    iter::once,
  8    mem::transmute,
  9    os::windows::ffi::{OsStrExt, OsStringExt},
 10    path::{Path, PathBuf},
 11    rc::Rc,
 12    sync::{Arc, OnceLock},
 13    time::Duration,
 14};
 15
 16use ::util::{ResultExt, SemanticVersion};
 17use anyhow::{anyhow, Result};
 18use async_task::Runnable;
 19use copypasta::{ClipboardContext, ClipboardProvider};
 20use futures::channel::oneshot::{self, Receiver};
 21use itertools::Itertools;
 22use parking_lot::{Mutex, RwLock};
 23use smallvec::SmallVec;
 24use time::UtcOffset;
 25use windows::{
 26    core::*,
 27    Wdk::System::SystemServices::*,
 28    Win32::{
 29        Foundation::*,
 30        Graphics::Gdi::*,
 31        Media::*,
 32        Security::Credentials::*,
 33        System::{Com::*, LibraryLoader::*, Ole::*, SystemInformation::*, Threading::*, Time::*},
 34        UI::{Input::KeyboardAndMouse::*, Shell::*, WindowsAndMessaging::*},
 35    },
 36};
 37
 38use crate::*;
 39
 40pub(crate) struct WindowsPlatform {
 41    inner: Rc<WindowsPlatformInner>,
 42}
 43
 44/// Windows settings pulled from SystemParametersInfo
 45/// https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-systemparametersinfow
 46#[derive(Default, Debug)]
 47pub(crate) struct WindowsPlatformSystemSettings {
 48    /// SEE: SPI_GETWHEELSCROLLCHARS
 49    pub(crate) wheel_scroll_chars: u32,
 50
 51    /// SEE: SPI_GETWHEELSCROLLLINES
 52    pub(crate) wheel_scroll_lines: u32,
 53}
 54
 55pub(crate) struct WindowsPlatformInner {
 56    background_executor: BackgroundExecutor,
 57    pub(crate) foreground_executor: ForegroundExecutor,
 58    main_receiver: flume::Receiver<Runnable>,
 59    text_system: Arc<WindowsTextSystem>,
 60    callbacks: Mutex<Callbacks>,
 61    pub raw_window_handles: RwLock<SmallVec<[HWND; 4]>>,
 62    pub(crate) dispatch_event: OwnedHandle,
 63    pub(crate) settings: RefCell<WindowsPlatformSystemSettings>,
 64}
 65
 66impl WindowsPlatformInner {
 67    pub(crate) fn try_get_windows_inner_from_hwnd(
 68        &self,
 69        hwnd: HWND,
 70    ) -> Option<Rc<WindowsWindowInner>> {
 71        self.raw_window_handles
 72            .read()
 73            .iter()
 74            .find(|entry| *entry == &hwnd)
 75            .and_then(|hwnd| try_get_window_inner(*hwnd))
 76    }
 77}
 78
 79#[derive(Default)]
 80struct Callbacks {
 81    open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
 82    become_active: Option<Box<dyn FnMut()>>,
 83    resign_active: Option<Box<dyn FnMut()>>,
 84    quit: Option<Box<dyn FnMut()>>,
 85    reopen: Option<Box<dyn FnMut()>>,
 86    event: Option<Box<dyn FnMut(PlatformInput) -> bool>>,
 87    app_menu_action: Option<Box<dyn FnMut(&dyn Action)>>,
 88    will_open_app_menu: Option<Box<dyn FnMut()>>,
 89    validate_app_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
 90}
 91
 92enum WindowsMessageWaitResult {
 93    ForegroundExecution,
 94    WindowsMessage(MSG),
 95    Error,
 96}
 97
 98impl WindowsPlatformSystemSettings {
 99    fn new() -> Self {
100        let mut settings = Self::default();
101        settings.update_all();
102        settings
103    }
104
105    pub(crate) fn update_all(&mut self) {
106        self.update_wheel_scroll_lines();
107        self.update_wheel_scroll_chars();
108    }
109
110    pub(crate) fn update_wheel_scroll_lines(&mut self) {
111        let mut value = c_uint::default();
112        let result = unsafe {
113            SystemParametersInfoW(
114                SPI_GETWHEELSCROLLLINES,
115                0,
116                Some((&mut value) as *mut c_uint as *mut c_void),
117                SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS::default(),
118            )
119        };
120
121        if result.log_err() != None {
122            self.wheel_scroll_lines = value;
123        }
124    }
125
126    pub(crate) fn update_wheel_scroll_chars(&mut self) {
127        let mut value = c_uint::default();
128        let result = unsafe {
129            SystemParametersInfoW(
130                SPI_GETWHEELSCROLLCHARS,
131                0,
132                Some((&mut value) as *mut c_uint as *mut c_void),
133                SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS::default(),
134            )
135        };
136
137        if result.log_err() != None {
138            self.wheel_scroll_chars = value;
139        }
140    }
141}
142
143impl WindowsPlatform {
144    pub(crate) fn new() -> Self {
145        unsafe {
146            OleInitialize(None).expect("unable to initialize Windows OLE");
147        }
148        let (main_sender, main_receiver) = flume::unbounded::<Runnable>();
149        let dispatch_event =
150            OwnedHandle::new(unsafe { CreateEventW(None, false, false, None) }.unwrap());
151        let dispatcher = Arc::new(WindowsDispatcher::new(main_sender, dispatch_event.to_raw()));
152        let background_executor = BackgroundExecutor::new(dispatcher.clone());
153        let foreground_executor = ForegroundExecutor::new(dispatcher);
154        let text_system = Arc::new(WindowsTextSystem::new());
155        let callbacks = Mutex::new(Callbacks::default());
156        let raw_window_handles = RwLock::new(SmallVec::new());
157        let settings = RefCell::new(WindowsPlatformSystemSettings::new());
158        let inner = Rc::new(WindowsPlatformInner {
159            background_executor,
160            foreground_executor,
161            main_receiver,
162            text_system,
163            callbacks,
164            raw_window_handles,
165            dispatch_event,
166            settings,
167        });
168        Self { inner }
169    }
170
171    fn run_foreground_tasks(&self) {
172        for runnable in self.inner.main_receiver.drain() {
173            runnable.run();
174        }
175    }
176
177    fn redraw_all(&self) {
178        for handle in self.inner.raw_window_handles.read().iter() {
179            unsafe {
180                RedrawWindow(
181                    *handle,
182                    None,
183                    HRGN::default(),
184                    RDW_INVALIDATE | RDW_UPDATENOW,
185                );
186            }
187        }
188    }
189}
190
191impl Platform for WindowsPlatform {
192    fn background_executor(&self) -> BackgroundExecutor {
193        self.inner.background_executor.clone()
194    }
195
196    fn foreground_executor(&self) -> ForegroundExecutor {
197        self.inner.foreground_executor.clone()
198    }
199
200    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
201        self.inner.text_system.clone()
202    }
203
204    fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>) {
205        on_finish_launching();
206        let dispatch_event = self.inner.dispatch_event.to_raw();
207        let vsync_event = create_event().unwrap();
208        let timer_stop_event = create_event().unwrap();
209        let raw_timer_stop_event = timer_stop_event.to_raw();
210        begin_vsync_timer(vsync_event.to_raw(), timer_stop_event);
211        'a: loop {
212            let wait_result = unsafe {
213                MsgWaitForMultipleObjects(
214                    Some(&[vsync_event.to_raw(), dispatch_event]),
215                    false,
216                    INFINITE,
217                    QS_ALLINPUT,
218                )
219            };
220
221            match wait_result {
222                // compositor clock ticked so we should draw a frame
223                WAIT_EVENT(0) => {
224                    self.redraw_all();
225                }
226                // foreground tasks are dispatched
227                WAIT_EVENT(1) => {
228                    self.run_foreground_tasks();
229                }
230                // Windows thread messages are posted
231                WAIT_EVENT(2) => {
232                    let mut msg = MSG::default();
233                    unsafe {
234                        while PeekMessageW(&mut msg, HWND::default(), 0, 0, PM_REMOVE).as_bool() {
235                            if msg.message == WM_QUIT {
236                                break 'a;
237                            }
238                            if msg.message == WM_SETTINGCHANGE {
239                                self.inner.settings.borrow_mut().update_all();
240                                continue;
241                            }
242                            TranslateMessage(&msg);
243                            DispatchMessageW(&msg);
244                        }
245                    }
246
247                    // foreground tasks may have been queued in the message handlers
248                    self.run_foreground_tasks();
249                }
250                _ => {
251                    log::error!("Something went wrong while waiting {:?}", wait_result);
252                    break;
253                }
254            }
255        }
256        end_vsync_timer(raw_timer_stop_event);
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    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
610        let mut password = password.to_vec();
611        let mut username = username.encode_utf16().chain(once(0)).collect_vec();
612        let mut target_name = windows_credentials_target_name(url)
613            .encode_utf16()
614            .chain(once(0))
615            .collect_vec();
616        self.foreground_executor().spawn(async move {
617            let credentials = CREDENTIALW {
618                LastWritten: unsafe { GetSystemTimeAsFileTime() },
619                Flags: CRED_FLAGS(0),
620                Type: CRED_TYPE_GENERIC,
621                TargetName: PWSTR::from_raw(target_name.as_mut_ptr()),
622                CredentialBlobSize: password.len() as u32,
623                CredentialBlob: password.as_ptr() as *mut _,
624                Persist: CRED_PERSIST_LOCAL_MACHINE,
625                UserName: PWSTR::from_raw(username.as_mut_ptr()),
626                ..CREDENTIALW::default()
627            };
628            unsafe { CredWriteW(&credentials, 0) }?;
629            Ok(())
630        })
631    }
632
633    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
634        let mut target_name = windows_credentials_target_name(url)
635            .encode_utf16()
636            .chain(once(0))
637            .collect_vec();
638        self.foreground_executor().spawn(async move {
639            let mut credentials: *mut CREDENTIALW = std::ptr::null_mut();
640            unsafe {
641                CredReadW(
642                    PCWSTR::from_raw(target_name.as_ptr()),
643                    CRED_TYPE_GENERIC,
644                    0,
645                    &mut credentials,
646                )?
647            };
648
649            if credentials.is_null() {
650                Ok(None)
651            } else {
652                let username: String = unsafe { (*credentials).UserName.to_string()? };
653                let credential_blob = unsafe {
654                    std::slice::from_raw_parts(
655                        (*credentials).CredentialBlob,
656                        (*credentials).CredentialBlobSize as usize,
657                    )
658                };
659                let mut password: Vec<u8> = Vec::with_capacity(credential_blob.len());
660                password.resize(password.capacity(), 0);
661                password.clone_from_slice(&credential_blob);
662                unsafe { CredFree(credentials as *const c_void) };
663                Ok(Some((username, password)))
664            }
665        })
666    }
667
668    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
669        let mut target_name = windows_credentials_target_name(url)
670            .encode_utf16()
671            .chain(once(0))
672            .collect_vec();
673        self.foreground_executor().spawn(async move {
674            unsafe { CredDeleteW(PCWSTR::from_raw(target_name.as_ptr()), CRED_TYPE_GENERIC, 0)? };
675            Ok(())
676        })
677    }
678
679    fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
680        Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
681    }
682}
683
684impl Drop for WindowsPlatform {
685    fn drop(&mut self) {
686        unsafe {
687            OleUninitialize();
688        }
689    }
690}
691
692unsafe fn load_cursor(name: PCWSTR) -> Result<HANDLE> {
693    LoadImageW(None, name, IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE | LR_SHARED).map_err(|e| anyhow!(e))
694}
695
696fn open_target(target: &str) {
697    unsafe {
698        let ret = ShellExecuteW(
699            None,
700            windows::core::w!("open"),
701            &HSTRING::from(target),
702            None,
703            None,
704            SW_SHOWDEFAULT,
705        );
706        if ret.0 <= 32 {
707            log::error!("Unable to open target: {}", std::io::Error::last_os_error());
708        }
709    }
710}
711
712unsafe fn show_savefile_dialog(directory: PathBuf) -> Result<IFileSaveDialog> {
713    let dialog: IFileSaveDialog = CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)?;
714    let bind_context = CreateBindCtx(0)?;
715    let Ok(full_path) = directory.canonicalize() else {
716        return Ok(dialog);
717    };
718    let dir_str = full_path.into_os_string();
719    if dir_str.is_empty() {
720        return Ok(dialog);
721    }
722    let dir_vec = dir_str.encode_wide().collect_vec();
723    let ret = SHCreateItemFromParsingName(PCWSTR::from_raw(dir_vec.as_ptr()), &bind_context)
724        .inspect_err(|e| log::error!("unable to create IShellItem: {}", e));
725    if ret.is_ok() {
726        let dir_shell_item: IShellItem = ret.unwrap();
727        let _ = dialog
728            .SetFolder(&dir_shell_item)
729            .inspect_err(|e| log::error!("unable to set folder for save file dialog: {}", e));
730    }
731
732    Ok(dialog)
733}
734
735fn begin_vsync_timer(vsync_event: HANDLE, timer_stop_event: OwnedHandle) {
736    let vsync_fn = select_vsync_fn();
737    std::thread::spawn(move || {
738        while vsync_fn(timer_stop_event.to_raw()) {
739            if unsafe { SetEvent(vsync_event) }.log_err().is_none() {
740                break;
741            }
742        }
743    });
744}
745
746fn end_vsync_timer(timer_stop_event: HANDLE) {
747    unsafe { SetEvent(timer_stop_event) }.log_err();
748}
749
750fn select_vsync_fn() -> Box<dyn Fn(HANDLE) -> bool + Send> {
751    if let Some(dcomp_fn) = load_dcomp_vsync_fn() {
752        log::info!("use DCompositionWaitForCompositorClock for vsync");
753        return Box::new(move |timer_stop_event| {
754            // will be 0 if woken up by timer_stop_event or 1 if the compositor clock ticked
755            // SEE: https://learn.microsoft.com/en-us/windows/win32/directcomp/compositor-clock/compositor-clock
756            (unsafe { dcomp_fn(1, &timer_stop_event, INFINITE) }) == 1
757        });
758    }
759    log::info!("use fallback vsync function");
760    Box::new(fallback_vsync_fn())
761}
762
763fn load_dcomp_vsync_fn() -> Option<unsafe extern "system" fn(u32, *const HANDLE, u32) -> u32> {
764    static FN: OnceLock<Option<unsafe extern "system" fn(u32, *const HANDLE, u32) -> u32>> =
765        OnceLock::new();
766    *FN.get_or_init(|| {
767        let hmodule = unsafe { LoadLibraryW(windows::core::w!("dcomp.dll")) }.ok()?;
768        let address = unsafe {
769            GetProcAddress(
770                hmodule,
771                windows::core::s!("DCompositionWaitForCompositorClock"),
772            )
773        }?;
774        Some(unsafe { transmute(address) })
775    })
776}
777
778fn fallback_vsync_fn() -> impl Fn(HANDLE) -> bool + Send {
779    let freq = WindowsDisplay::primary_monitor()
780        .and_then(|monitor| monitor.frequency())
781        .unwrap_or(60);
782    log::info!("primaly refresh rate is {freq}Hz");
783
784    let interval = (1000 / freq).max(1);
785    log::info!("expected interval is {interval}ms");
786
787    unsafe { timeBeginPeriod(1) };
788
789    struct TimePeriod;
790    impl Drop for TimePeriod {
791        fn drop(&mut self) {
792            unsafe { timeEndPeriod(1) };
793        }
794    }
795    let period = TimePeriod;
796
797    move |timer_stop_event| {
798        let _ = (&period,);
799        (unsafe { WaitForSingleObject(timer_stop_event, interval) }) == WAIT_TIMEOUT
800    }
801}