platform.rs

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