platform.rs

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