platform.rs

  1// todo(windows): remove
  2#![allow(unused_variables)]
  3
  4use std::{
  5    cell::{Cell, RefCell},
  6    ffi::{c_void, OsString},
  7    mem::transmute,
  8    os::windows::ffi::{OsStrExt, OsStringExt},
  9    path::{Path, PathBuf},
 10    rc::Rc,
 11    sync::{Arc, OnceLock},
 12};
 13
 14use ::util::ResultExt;
 15use anyhow::{anyhow, Context, Result};
 16use copypasta::{ClipboardContext, ClipboardProvider};
 17use futures::channel::oneshot::{self, Receiver};
 18use itertools::Itertools;
 19use parking_lot::RwLock;
 20use semantic_version::SemanticVersion;
 21use smallvec::SmallVec;
 22use time::UtcOffset;
 23use windows::{
 24    core::*,
 25    Wdk::System::SystemServices::*,
 26    Win32::{
 27        Foundation::*,
 28        Graphics::Gdi::*,
 29        Media::*,
 30        Security::Credentials::*,
 31        Storage::FileSystem::*,
 32        System::{Com::*, LibraryLoader::*, Ole::*, SystemInformation::*, Threading::*, Time::*},
 33        UI::{Input::KeyboardAndMouse::*, Shell::*, WindowsAndMessaging::*},
 34    },
 35};
 36
 37use crate::*;
 38
 39pub(crate) struct WindowsPlatform {
 40    state: RefCell<WindowsPlatformState>,
 41    raw_window_handles: RwLock<SmallVec<[HWND; 4]>>,
 42    // The below members will never change throughout the entire lifecycle of the app.
 43    icon: HICON,
 44    background_executor: BackgroundExecutor,
 45    foreground_executor: ForegroundExecutor,
 46    text_system: Arc<dyn PlatformTextSystem>,
 47}
 48
 49pub(crate) struct WindowsPlatformState {
 50    callbacks: PlatformCallbacks,
 51    // NOTE: standard cursor handles don't need to close.
 52    pub(crate) current_cursor: HCURSOR,
 53}
 54
 55#[derive(Default)]
 56struct PlatformCallbacks {
 57    open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
 58    quit: Option<Box<dyn FnMut()>>,
 59    reopen: Option<Box<dyn FnMut()>>,
 60    app_menu_action: Option<Box<dyn FnMut(&dyn Action)>>,
 61    will_open_app_menu: Option<Box<dyn FnMut()>>,
 62    validate_app_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
 63}
 64
 65impl WindowsPlatformState {
 66    fn new() -> Self {
 67        let callbacks = PlatformCallbacks::default();
 68        let current_cursor = load_cursor(CursorStyle::Arrow);
 69
 70        Self {
 71            callbacks,
 72            current_cursor,
 73        }
 74    }
 75}
 76
 77impl WindowsPlatform {
 78    pub(crate) fn new() -> Self {
 79        unsafe {
 80            OleInitialize(None).expect("unable to initialize Windows OLE");
 81        }
 82        let dispatcher = Arc::new(WindowsDispatcher::new());
 83        let background_executor = BackgroundExecutor::new(dispatcher.clone());
 84        let foreground_executor = ForegroundExecutor::new(dispatcher);
 85        let text_system = if let Some(direct_write) = DirectWriteTextSystem::new().log_err() {
 86            log::info!("Using direct write text system.");
 87            Arc::new(direct_write) as Arc<dyn PlatformTextSystem>
 88        } else {
 89            log::info!("Using cosmic text system.");
 90            Arc::new(CosmicTextSystem::new()) as Arc<dyn PlatformTextSystem>
 91        };
 92        let icon = load_icon().unwrap_or_default();
 93        let state = RefCell::new(WindowsPlatformState::new());
 94        let raw_window_handles = RwLock::new(SmallVec::new());
 95
 96        Self {
 97            state,
 98            raw_window_handles,
 99            icon,
100            background_executor,
101            foreground_executor,
102            text_system,
103        }
104    }
105
106    fn redraw_all(&self) {
107        for handle in self.raw_window_handles.read().iter() {
108            unsafe {
109                RedrawWindow(
110                    *handle,
111                    None,
112                    HRGN::default(),
113                    RDW_INVALIDATE | RDW_UPDATENOW,
114                )
115                .ok()
116                .log_err();
117            }
118        }
119    }
120
121    pub fn try_get_windows_inner_from_hwnd(&self, hwnd: HWND) -> Option<Rc<WindowsWindowStatePtr>> {
122        self.raw_window_handles
123            .read()
124            .iter()
125            .find(|entry| *entry == &hwnd)
126            .and_then(|hwnd| try_get_window_inner(*hwnd))
127    }
128
129    #[inline]
130    fn post_message(&self, message: u32, wparam: WPARAM, lparam: LPARAM) {
131        self.raw_window_handles
132            .read()
133            .iter()
134            .for_each(|handle| unsafe {
135                PostMessageW(*handle, message, wparam, lparam).log_err();
136            });
137    }
138
139    fn close_one_window(&self, target_window: HWND) -> bool {
140        let mut lock = self.raw_window_handles.write();
141        let index = lock
142            .iter()
143            .position(|handle| *handle == target_window)
144            .unwrap();
145        lock.remove(index);
146
147        lock.is_empty()
148    }
149}
150
151impl Platform for WindowsPlatform {
152    fn background_executor(&self) -> BackgroundExecutor {
153        self.background_executor.clone()
154    }
155
156    fn foreground_executor(&self) -> ForegroundExecutor {
157        self.foreground_executor.clone()
158    }
159
160    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
161        self.text_system.clone()
162    }
163
164    fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>) {
165        on_finish_launching();
166        let vsync_event = create_event().unwrap();
167        let timer_stop_event = create_event().unwrap();
168        let raw_timer_stop_event = timer_stop_event.to_raw();
169        begin_vsync_timer(vsync_event.to_raw(), timer_stop_event);
170        'a: loop {
171            let wait_result = unsafe {
172                MsgWaitForMultipleObjects(
173                    Some(&[vsync_event.to_raw()]),
174                    false,
175                    INFINITE,
176                    QS_ALLINPUT,
177                )
178            };
179
180            match wait_result {
181                // compositor clock ticked so we should draw a frame
182                WAIT_EVENT(0) => {
183                    self.redraw_all();
184                }
185                // Windows thread messages are posted
186                WAIT_EVENT(1) => {
187                    let mut msg = MSG::default();
188                    unsafe {
189                        while PeekMessageW(&mut msg, None, 0, 0, PM_REMOVE).as_bool() {
190                            match msg.message {
191                                WM_QUIT => break 'a,
192                                CLOSE_ONE_WINDOW => {
193                                    if self.close_one_window(HWND(msg.lParam.0)) {
194                                        break 'a;
195                                    }
196                                }
197                                _ => {
198                                    // todo(windows)
199                                    // crate `windows 0.56` reports true as Err
200                                    TranslateMessage(&msg).as_bool();
201                                    DispatchMessageW(&msg);
202                                }
203                            }
204                        }
205                    }
206                }
207                _ => {
208                    log::error!("Something went wrong while waiting {:?}", wait_result);
209                    break;
210                }
211            }
212        }
213        end_vsync_timer(raw_timer_stop_event);
214
215        if let Some(ref mut callback) = self.state.borrow_mut().callbacks.quit {
216            callback();
217        }
218    }
219
220    fn quit(&self) {
221        self.foreground_executor()
222            .spawn(async { unsafe { PostQuitMessage(0) } })
223            .detach();
224    }
225
226    fn restart(&self, _: Option<PathBuf>) {
227        let pid = std::process::id();
228        let Some(app_path) = self.app_path().log_err() else {
229            return;
230        };
231        let script = format!(
232            r#"
233            $pidToWaitFor = {}
234            $exePath = "{}"
235
236            while ($true) {{
237                $process = Get-Process -Id $pidToWaitFor -ErrorAction SilentlyContinue
238                if (-not $process) {{
239                    Start-Process -FilePath $exePath
240                    break
241                }}
242                Start-Sleep -Seconds 0.1
243            }}
244            "#,
245            pid,
246            app_path.display(),
247        );
248        let restart_process = std::process::Command::new("powershell.exe")
249            .arg("-command")
250            .arg(script)
251            .spawn();
252
253        match restart_process {
254            Ok(_) => self.quit(),
255            Err(e) => log::error!("failed to spawn restart script: {:?}", e),
256        }
257    }
258
259    // todo(windows)
260    fn activate(&self, ignoring_other_apps: bool) {}
261
262    // todo(windows)
263    fn hide(&self) {
264        unimplemented!()
265    }
266
267    // todo(windows)
268    fn hide_other_apps(&self) {
269        unimplemented!()
270    }
271
272    // todo(windows)
273    fn unhide_other_apps(&self) {
274        unimplemented!()
275    }
276
277    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
278        WindowsDisplay::displays()
279    }
280
281    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
282        WindowsDisplay::primary_monitor().map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
283    }
284
285    fn active_window(&self) -> Option<AnyWindowHandle> {
286        let active_window_hwnd = unsafe { GetActiveWindow() };
287        self.try_get_windows_inner_from_hwnd(active_window_hwnd)
288            .map(|inner| inner.handle)
289    }
290
291    fn open_window(
292        &self,
293        handle: AnyWindowHandle,
294        options: WindowParams,
295    ) -> Box<dyn PlatformWindow> {
296        let lock = self.state.borrow();
297        let window = WindowsWindow::new(
298            handle,
299            options,
300            self.icon,
301            self.foreground_executor.clone(),
302            lock.current_cursor,
303        );
304        drop(lock);
305        let handle = window.get_raw_handle();
306        self.raw_window_handles.write().push(handle);
307
308        Box::new(window)
309    }
310
311    // todo(windows)
312    fn window_appearance(&self) -> WindowAppearance {
313        WindowAppearance::Dark
314    }
315
316    fn open_url(&self, url: &str) {
317        let url_string = url.to_string();
318        self.background_executor()
319            .spawn(async move {
320                if url_string.is_empty() {
321                    return;
322                }
323                open_target(url_string.as_str());
324            })
325            .detach();
326    }
327
328    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
329        self.state.borrow_mut().callbacks.open_urls = Some(callback);
330    }
331
332    fn prompt_for_paths(&self, options: PathPromptOptions) -> Receiver<Option<Vec<PathBuf>>> {
333        let (tx, rx) = oneshot::channel();
334
335        self.foreground_executor()
336            .spawn(async move {
337                let tx = Cell::new(Some(tx));
338
339                // create file open dialog
340                let folder_dialog: IFileOpenDialog = unsafe {
341                    CoCreateInstance::<std::option::Option<&IUnknown>, IFileOpenDialog>(
342                        &FileOpenDialog,
343                        None,
344                        CLSCTX_ALL,
345                    )
346                    .unwrap()
347                };
348
349                // dialog options
350                let mut dialog_options: FILEOPENDIALOGOPTIONS = FOS_FILEMUSTEXIST;
351                if options.multiple {
352                    dialog_options |= FOS_ALLOWMULTISELECT;
353                }
354                if options.directories {
355                    dialog_options |= FOS_PICKFOLDERS;
356                }
357
358                unsafe {
359                    folder_dialog.SetOptions(dialog_options).unwrap();
360                    folder_dialog
361                        .SetTitle(&HSTRING::from(OsString::from("Select a folder")))
362                        .unwrap();
363                }
364
365                let hr = unsafe { folder_dialog.Show(None) };
366
367                if hr.is_err() {
368                    if hr.unwrap_err().code() == HRESULT(0x800704C7u32 as i32) {
369                        // user canceled error
370                        if let Some(tx) = tx.take() {
371                            tx.send(None).unwrap();
372                        }
373                        return;
374                    }
375                }
376
377                let mut results = unsafe { folder_dialog.GetResults().unwrap() };
378
379                let mut paths: Vec<PathBuf> = Vec::new();
380                for i in 0..unsafe { results.GetCount().unwrap() } {
381                    let mut item: IShellItem = unsafe { results.GetItemAt(i).unwrap() };
382                    let mut path: PWSTR =
383                        unsafe { item.GetDisplayName(SIGDN_FILESYSPATH).unwrap() };
384                    let mut path_os_string = OsString::from_wide(unsafe { path.as_wide() });
385
386                    paths.push(PathBuf::from(path_os_string));
387                }
388
389                if let Some(tx) = tx.take() {
390                    if paths.len() == 0 {
391                        tx.send(None).unwrap();
392                    } else {
393                        tx.send(Some(paths)).unwrap();
394                    }
395                }
396            })
397            .detach();
398
399        rx
400    }
401
402    fn prompt_for_new_path(&self, directory: &Path) -> Receiver<Option<PathBuf>> {
403        let directory = directory.to_owned();
404        let (tx, rx) = oneshot::channel();
405        self.foreground_executor()
406            .spawn(async move {
407                unsafe {
408                    let Ok(dialog) = show_savefile_dialog(directory) else {
409                        let _ = tx.send(None);
410                        return;
411                    };
412                    let Ok(_) = dialog.Show(None) else {
413                        let _ = tx.send(None); // user cancel
414                        return;
415                    };
416                    if let Ok(shell_item) = dialog.GetResult() {
417                        if let Ok(file) = shell_item.GetDisplayName(SIGDN_FILESYSPATH) {
418                            let _ = tx.send(Some(PathBuf::from(file.to_string().unwrap())));
419                            return;
420                        }
421                    }
422                    let _ = tx.send(None);
423                }
424            })
425            .detach();
426
427        rx
428    }
429
430    fn reveal_path(&self, path: &Path) {
431        let Ok(file_full_path) = path.canonicalize() else {
432            log::error!("unable to parse file path");
433            return;
434        };
435        self.background_executor()
436            .spawn(async move {
437                let Some(path) = file_full_path.to_str() else {
438                    return;
439                };
440                if path.is_empty() {
441                    return;
442                }
443                open_target(path);
444            })
445            .detach();
446    }
447
448    fn on_quit(&self, callback: Box<dyn FnMut()>) {
449        self.state.borrow_mut().callbacks.quit = Some(callback);
450    }
451
452    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
453        self.state.borrow_mut().callbacks.reopen = Some(callback);
454    }
455
456    // todo(windows)
457    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {}
458
459    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
460        self.state.borrow_mut().callbacks.app_menu_action = Some(callback);
461    }
462
463    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
464        self.state.borrow_mut().callbacks.will_open_app_menu = Some(callback);
465    }
466
467    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
468        self.state.borrow_mut().callbacks.validate_app_menu_command = Some(callback);
469    }
470
471    fn os_name(&self) -> &'static str {
472        "Windows"
473    }
474
475    fn os_version(&self) -> Result<SemanticVersion> {
476        let mut info = unsafe { std::mem::zeroed() };
477        let status = unsafe { RtlGetVersion(&mut info) };
478        if status.is_ok() {
479            Ok(SemanticVersion::new(
480                info.dwMajorVersion as _,
481                info.dwMinorVersion as _,
482                info.dwBuildNumber as _,
483            ))
484        } else {
485            Err(anyhow::anyhow!(
486                "unable to get Windows version: {}",
487                std::io::Error::last_os_error()
488            ))
489        }
490    }
491
492    fn app_version(&self) -> Result<SemanticVersion> {
493        let mut file_name_buffer = vec![0u16; MAX_PATH as usize];
494        let file_name = {
495            let mut file_name_buffer_capacity = MAX_PATH as usize;
496            let mut file_name_length;
497            loop {
498                file_name_length =
499                    unsafe { GetModuleFileNameW(None, &mut file_name_buffer) } as usize;
500                if file_name_length < file_name_buffer_capacity {
501                    break;
502                }
503                // buffer too small
504                file_name_buffer_capacity *= 2;
505                file_name_buffer = vec![0u16; file_name_buffer_capacity];
506            }
507            PCWSTR::from_raw(file_name_buffer[0..(file_name_length + 1)].as_ptr())
508        };
509
510        let version_info_block = {
511            let mut version_handle = 0;
512            let version_info_size =
513                unsafe { GetFileVersionInfoSizeW(file_name, Some(&mut version_handle)) } as usize;
514            if version_info_size == 0 {
515                log::error!(
516                    "unable to get version info size: {}",
517                    std::io::Error::last_os_error()
518                );
519                return Err(anyhow!("unable to get version info size"));
520            }
521            let mut version_data = vec![0u8; version_info_size + 2];
522            unsafe {
523                GetFileVersionInfoW(
524                    file_name,
525                    version_handle,
526                    version_info_size as u32,
527                    version_data.as_mut_ptr() as _,
528                )
529            }
530            .inspect_err(|_| {
531                log::error!(
532                    "unable to retrieve version info: {}",
533                    std::io::Error::last_os_error()
534                )
535            })?;
536            version_data
537        };
538
539        let version_info_raw = {
540            let mut buffer = unsafe { std::mem::zeroed() };
541            let mut size = 0;
542            let entry = "\\".encode_utf16().chain(Some(0)).collect_vec();
543            if !unsafe {
544                VerQueryValueW(
545                    version_info_block.as_ptr() as _,
546                    PCWSTR::from_raw(entry.as_ptr()),
547                    &mut buffer,
548                    &mut size,
549                )
550            }
551            .as_bool()
552            {
553                log::error!(
554                    "unable to query version info data: {}",
555                    std::io::Error::last_os_error()
556                );
557                return Err(anyhow!("the specified resource is not valid"));
558            }
559            if size == 0 {
560                log::error!(
561                    "unable to query version info data: {}",
562                    std::io::Error::last_os_error()
563                );
564                return Err(anyhow!("no value is available for the specified name"));
565            }
566            buffer
567        };
568
569        let version_info = unsafe { &*(version_info_raw as *mut VS_FIXEDFILEINFO) };
570        // https://learn.microsoft.com/en-us/windows/win32/api/verrsrc/ns-verrsrc-vs_fixedfileinfo
571        if version_info.dwSignature == 0xFEEF04BD {
572            return Ok(SemanticVersion::new(
573                ((version_info.dwProductVersionMS >> 16) & 0xFFFF) as usize,
574                (version_info.dwProductVersionMS & 0xFFFF) as usize,
575                ((version_info.dwProductVersionLS >> 16) & 0xFFFF) as usize,
576            ));
577        } else {
578            log::error!(
579                "no version info present: {}",
580                std::io::Error::last_os_error()
581            );
582            return Err(anyhow!("no version info present"));
583        }
584    }
585
586    fn app_path(&self) -> Result<PathBuf> {
587        Ok(std::env::current_exe()?)
588    }
589
590    fn local_timezone(&self) -> UtcOffset {
591        let mut info = unsafe { std::mem::zeroed() };
592        let ret = unsafe { GetTimeZoneInformation(&mut info) };
593        if ret == TIME_ZONE_ID_INVALID {
594            log::error!(
595                "Unable to get local timezone: {}",
596                std::io::Error::last_os_error()
597            );
598            return UtcOffset::UTC;
599        }
600        // Windows treat offset as:
601        // UTC = localtime + offset
602        // so we add a minus here
603        let hours = -info.Bias / 60;
604        let minutes = -info.Bias % 60;
605
606        UtcOffset::from_hms(hours as _, minutes as _, 0).unwrap()
607    }
608
609    // todo(windows)
610    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
611        Err(anyhow!("not yet implemented"))
612    }
613
614    fn set_cursor_style(&self, style: CursorStyle) {
615        let hcursor = load_cursor(style);
616        let mut lock = self.state.borrow_mut();
617        if lock.current_cursor.0 != hcursor.0 {
618            self.post_message(CURSOR_STYLE_CHANGED, WPARAM(0), LPARAM(hcursor.0));
619            lock.current_cursor = hcursor;
620        }
621    }
622
623    // todo(windows)
624    fn should_auto_hide_scrollbars(&self) -> bool {
625        false
626    }
627
628    fn write_to_primary(&self, _item: ClipboardItem) {}
629
630    fn write_to_clipboard(&self, item: ClipboardItem) {
631        if item.text.len() > 0 {
632            let mut ctx = ClipboardContext::new().unwrap();
633            ctx.set_contents(item.text().to_owned()).unwrap();
634        }
635    }
636
637    fn read_from_primary(&self) -> Option<ClipboardItem> {
638        None
639    }
640
641    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
642        let mut ctx = ClipboardContext::new().unwrap();
643        let content = ctx.get_contents().ok()?;
644        Some(ClipboardItem {
645            text: content,
646            metadata: None,
647        })
648    }
649
650    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
651        let mut password = password.to_vec();
652        let mut username = username.encode_utf16().chain(Some(0)).collect_vec();
653        let mut target_name = windows_credentials_target_name(url)
654            .encode_utf16()
655            .chain(Some(0))
656            .collect_vec();
657        self.foreground_executor().spawn(async move {
658            let credentials = CREDENTIALW {
659                LastWritten: unsafe { GetSystemTimeAsFileTime() },
660                Flags: CRED_FLAGS(0),
661                Type: CRED_TYPE_GENERIC,
662                TargetName: PWSTR::from_raw(target_name.as_mut_ptr()),
663                CredentialBlobSize: password.len() as u32,
664                CredentialBlob: password.as_ptr() as *mut _,
665                Persist: CRED_PERSIST_LOCAL_MACHINE,
666                UserName: PWSTR::from_raw(username.as_mut_ptr()),
667                ..CREDENTIALW::default()
668            };
669            unsafe { CredWriteW(&credentials, 0) }?;
670            Ok(())
671        })
672    }
673
674    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
675        let mut target_name = windows_credentials_target_name(url)
676            .encode_utf16()
677            .chain(Some(0))
678            .collect_vec();
679        self.foreground_executor().spawn(async move {
680            let mut credentials: *mut CREDENTIALW = std::ptr::null_mut();
681            unsafe {
682                CredReadW(
683                    PCWSTR::from_raw(target_name.as_ptr()),
684                    CRED_TYPE_GENERIC,
685                    0,
686                    &mut credentials,
687                )?
688            };
689
690            if credentials.is_null() {
691                Ok(None)
692            } else {
693                let username: String = unsafe { (*credentials).UserName.to_string()? };
694                let credential_blob = unsafe {
695                    std::slice::from_raw_parts(
696                        (*credentials).CredentialBlob,
697                        (*credentials).CredentialBlobSize as usize,
698                    )
699                };
700                let password = credential_blob.to_vec();
701                unsafe { CredFree(credentials as *const c_void) };
702                Ok(Some((username, password)))
703            }
704        })
705    }
706
707    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
708        let mut target_name = windows_credentials_target_name(url)
709            .encode_utf16()
710            .chain(Some(0))
711            .collect_vec();
712        self.foreground_executor().spawn(async move {
713            unsafe { CredDeleteW(PCWSTR::from_raw(target_name.as_ptr()), CRED_TYPE_GENERIC, 0)? };
714            Ok(())
715        })
716    }
717
718    fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
719        Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
720    }
721}
722
723impl Drop for WindowsPlatform {
724    fn drop(&mut self) {
725        unsafe {
726            OleUninitialize();
727        }
728    }
729}
730
731fn open_target(target: &str) {
732    unsafe {
733        let ret = ShellExecuteW(
734            None,
735            windows::core::w!("open"),
736            &HSTRING::from(target),
737            None,
738            None,
739            SW_SHOWDEFAULT,
740        );
741        if ret.0 <= 32 {
742            log::error!("Unable to open target: {}", std::io::Error::last_os_error());
743        }
744    }
745}
746
747unsafe fn show_savefile_dialog(directory: PathBuf) -> Result<IFileSaveDialog> {
748    let dialog: IFileSaveDialog = CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)?;
749    let bind_context = CreateBindCtx(0)?;
750    let Ok(full_path) = directory.canonicalize() else {
751        return Ok(dialog);
752    };
753    let dir_str = full_path.into_os_string();
754    if dir_str.is_empty() {
755        return Ok(dialog);
756    }
757    let dir_vec = dir_str.encode_wide().collect_vec();
758    let ret = SHCreateItemFromParsingName(PCWSTR::from_raw(dir_vec.as_ptr()), &bind_context)
759        .inspect_err(|e| log::error!("unable to create IShellItem: {}", e));
760    if ret.is_ok() {
761        let dir_shell_item: IShellItem = ret.unwrap();
762        let _ = dialog
763            .SetFolder(&dir_shell_item)
764            .inspect_err(|e| log::error!("unable to set folder for save file dialog: {}", e));
765    }
766
767    Ok(dialog)
768}
769
770fn begin_vsync_timer(vsync_event: HANDLE, timer_stop_event: OwnedHandle) {
771    let vsync_fn = select_vsync_fn();
772    std::thread::spawn(move || loop {
773        if vsync_fn(timer_stop_event.to_raw()) {
774            if unsafe { SetEvent(vsync_event) }.log_err().is_none() {
775                break;
776            }
777        }
778    });
779}
780
781fn end_vsync_timer(timer_stop_event: HANDLE) {
782    unsafe { SetEvent(timer_stop_event) }.log_err();
783}
784
785fn select_vsync_fn() -> Box<dyn Fn(HANDLE) -> bool + Send> {
786    if let Some(dcomp_fn) = load_dcomp_vsync_fn() {
787        log::info!("use DCompositionWaitForCompositorClock for vsync");
788        return Box::new(move |timer_stop_event| {
789            // will be 0 if woken up by timer_stop_event or 1 if the compositor clock ticked
790            // SEE: https://learn.microsoft.com/en-us/windows/win32/directcomp/compositor-clock/compositor-clock
791            (unsafe { dcomp_fn(1, &timer_stop_event, INFINITE) }) == 1
792        });
793    }
794    log::info!("use fallback vsync function");
795    Box::new(fallback_vsync_fn())
796}
797
798fn load_dcomp_vsync_fn() -> Option<unsafe extern "system" fn(u32, *const HANDLE, u32) -> u32> {
799    static FN: OnceLock<Option<unsafe extern "system" fn(u32, *const HANDLE, u32) -> u32>> =
800        OnceLock::new();
801    *FN.get_or_init(|| {
802        let hmodule = unsafe { LoadLibraryW(windows::core::w!("dcomp.dll")) }.ok()?;
803        let address = unsafe {
804            GetProcAddress(
805                hmodule,
806                windows::core::s!("DCompositionWaitForCompositorClock"),
807            )
808        }?;
809        Some(unsafe { transmute(address) })
810    })
811}
812
813fn fallback_vsync_fn() -> impl Fn(HANDLE) -> bool + Send {
814    let freq = WindowsDisplay::primary_monitor()
815        .and_then(|monitor| monitor.frequency())
816        .unwrap_or(60);
817    log::info!("primaly refresh rate is {freq}Hz");
818
819    let interval = (1000 / freq).max(1);
820    log::info!("expected interval is {interval}ms");
821
822    unsafe { timeBeginPeriod(1) };
823
824    struct TimePeriod;
825    impl Drop for TimePeriod {
826        fn drop(&mut self) {
827            unsafe { timeEndPeriod(1) };
828        }
829    }
830    let period = TimePeriod;
831
832    move |timer_stop_event| {
833        let _ = (&period,);
834        (unsafe { WaitForSingleObject(timer_stop_event, interval) }) == WAIT_TIMEOUT
835    }
836}
837
838fn load_icon() -> Result<HICON> {
839    let module = unsafe { GetModuleHandleW(None).context("unable to get module handle")? };
840    let handle = unsafe {
841        LoadImageW(
842            module,
843            IDI_APPLICATION,
844            IMAGE_ICON,
845            0,
846            0,
847            LR_DEFAULTSIZE | LR_SHARED,
848        )
849        .context("unable to load icon file")?
850    };
851    Ok(HICON(handle.0))
852}