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, WindowParams,
 57    WindowsDispatcher, 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 primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
332        Some(Rc::new(WindowsDisplay::new()))
333    }
334
335    // todo(windows)
336    fn active_window(&self) -> Option<AnyWindowHandle> {
337        None
338    }
339
340    fn open_window(
341        &self,
342        handle: AnyWindowHandle,
343        options: WindowParams,
344    ) -> Box<dyn PlatformWindow> {
345        Box::new(WindowsWindow::new(self.inner.clone(), handle, options))
346    }
347
348    // todo(windows)
349    fn window_appearance(&self) -> WindowAppearance {
350        WindowAppearance::Dark
351    }
352
353    fn open_url(&self, url: &str) {
354        let url_string = url.to_string();
355        self.background_executor()
356            .spawn(async move {
357                if url_string.is_empty() {
358                    return;
359                }
360                open_target(url_string.as_str());
361            })
362            .detach();
363    }
364
365    // todo(windows)
366    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
367        self.inner.callbacks.lock().open_urls = Some(callback);
368    }
369
370    fn prompt_for_paths(&self, options: PathPromptOptions) -> Receiver<Option<Vec<PathBuf>>> {
371        let (tx, rx) = oneshot::channel();
372
373        self.foreground_executor()
374            .spawn(async move {
375                let tx = Cell::new(Some(tx));
376
377                // create file open dialog
378                let folder_dialog: IFileOpenDialog = unsafe {
379                    CoCreateInstance::<std::option::Option<&IUnknown>, IFileOpenDialog>(
380                        &FileOpenDialog,
381                        None,
382                        CLSCTX_ALL,
383                    )
384                    .unwrap()
385                };
386
387                // dialog options
388                let mut dialog_options: FILEOPENDIALOGOPTIONS = FOS_FILEMUSTEXIST;
389                if options.multiple {
390                    dialog_options |= FOS_ALLOWMULTISELECT;
391                }
392                if options.directories {
393                    dialog_options |= FOS_PICKFOLDERS;
394                }
395
396                unsafe {
397                    folder_dialog.SetOptions(dialog_options).unwrap();
398                    folder_dialog
399                        .SetTitle(&HSTRING::from(OsString::from("Select a folder")))
400                        .unwrap();
401                }
402
403                let hr = unsafe { folder_dialog.Show(None) };
404
405                if hr.is_err() {
406                    if hr.unwrap_err().code() == HRESULT(0x800704C7u32 as i32) {
407                        // user canceled error
408                        if let Some(tx) = tx.take() {
409                            tx.send(None).unwrap();
410                        }
411                        return;
412                    }
413                }
414
415                let mut results = unsafe { folder_dialog.GetResults().unwrap() };
416
417                let mut paths: Vec<PathBuf> = Vec::new();
418                for i in 0..unsafe { results.GetCount().unwrap() } {
419                    let mut item: IShellItem = unsafe { results.GetItemAt(i).unwrap() };
420                    let mut path: PWSTR =
421                        unsafe { item.GetDisplayName(SIGDN_FILESYSPATH).unwrap() };
422                    let mut path_os_string = OsString::from_wide(unsafe { path.as_wide() });
423
424                    paths.push(PathBuf::from(path_os_string));
425                }
426
427                if let Some(tx) = tx.take() {
428                    if paths.len() == 0 {
429                        tx.send(None).unwrap();
430                    } else {
431                        tx.send(Some(paths)).unwrap();
432                    }
433                }
434            })
435            .detach();
436
437        rx
438    }
439
440    fn prompt_for_new_path(&self, directory: &Path) -> Receiver<Option<PathBuf>> {
441        let directory = directory.to_owned();
442        let (tx, rx) = oneshot::channel();
443        self.foreground_executor()
444            .spawn(async move {
445                unsafe {
446                    let Ok(dialog) = show_savefile_dialog(directory) else {
447                        let _ = tx.send(None);
448                        return;
449                    };
450                    let Ok(_) = dialog.Show(None) else {
451                        let _ = tx.send(None); // user cancel
452                        return;
453                    };
454                    if let Ok(shell_item) = dialog.GetResult() {
455                        if let Ok(file) = shell_item.GetDisplayName(SIGDN_FILESYSPATH) {
456                            let _ = tx.send(Some(PathBuf::from(file.to_string().unwrap())));
457                            return;
458                        }
459                    }
460                    let _ = tx.send(None);
461                }
462            })
463            .detach();
464
465        rx
466    }
467
468    fn reveal_path(&self, path: &Path) {
469        let Ok(file_full_path) = path.canonicalize() else {
470            log::error!("unable to parse file path");
471            return;
472        };
473        self.background_executor()
474            .spawn(async move {
475                let Some(path) = file_full_path.to_str() else {
476                    return;
477                };
478                if path.is_empty() {
479                    return;
480                }
481                open_target(path);
482            })
483            .detach();
484    }
485
486    fn on_become_active(&self, callback: Box<dyn FnMut()>) {
487        self.inner.callbacks.lock().become_active = Some(callback);
488    }
489
490    fn on_resign_active(&self, callback: Box<dyn FnMut()>) {
491        self.inner.callbacks.lock().resign_active = Some(callback);
492    }
493
494    fn on_quit(&self, callback: Box<dyn FnMut()>) {
495        self.inner.callbacks.lock().quit = Some(callback);
496    }
497
498    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
499        self.inner.callbacks.lock().reopen = Some(callback);
500    }
501
502    fn on_event(&self, callback: Box<dyn FnMut(PlatformInput) -> bool>) {
503        self.inner.callbacks.lock().event = Some(callback);
504    }
505
506    // todo(windows)
507    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {}
508
509    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
510        self.inner.callbacks.lock().app_menu_action = Some(callback);
511    }
512
513    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
514        self.inner.callbacks.lock().will_open_app_menu = Some(callback);
515    }
516
517    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
518        self.inner.callbacks.lock().validate_app_menu_command = Some(callback);
519    }
520
521    fn os_name(&self) -> &'static str {
522        "Windows"
523    }
524
525    fn os_version(&self) -> Result<SemanticVersion> {
526        let mut info = unsafe { std::mem::zeroed() };
527        let status = unsafe { RtlGetVersion(&mut info) };
528        if status.is_ok() {
529            Ok(SemanticVersion {
530                major: info.dwMajorVersion as _,
531                minor: info.dwMinorVersion as _,
532                patch: info.dwBuildNumber as _,
533            })
534        } else {
535            Err(anyhow::anyhow!(
536                "unable to get Windows version: {}",
537                std::io::Error::last_os_error()
538            ))
539        }
540    }
541
542    fn app_version(&self) -> Result<SemanticVersion> {
543        Ok(SemanticVersion {
544            major: 1,
545            minor: 0,
546            patch: 0,
547        })
548    }
549
550    // todo(windows)
551    fn app_path(&self) -> Result<PathBuf> {
552        Err(anyhow!("not yet implemented"))
553    }
554
555    fn local_timezone(&self) -> UtcOffset {
556        let mut info = unsafe { std::mem::zeroed() };
557        let ret = unsafe { GetTimeZoneInformation(&mut info) };
558        if ret == TIME_ZONE_ID_INVALID {
559            log::error!(
560                "Unable to get local timezone: {}",
561                std::io::Error::last_os_error()
562            );
563            return UtcOffset::UTC;
564        }
565        // Windows treat offset as:
566        // UTC = localtime + offset
567        // so we add a minus here
568        let hours = -info.Bias / 60;
569        let minutes = -info.Bias % 60;
570
571        UtcOffset::from_hms(hours as _, minutes as _, 0).unwrap()
572    }
573
574    fn double_click_interval(&self) -> Duration {
575        let millis = unsafe { GetDoubleClickTime() };
576        Duration::from_millis(millis as _)
577    }
578
579    // todo(windows)
580    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
581        Err(anyhow!("not yet implemented"))
582    }
583
584    fn set_cursor_style(&self, style: CursorStyle) {
585        let handle = match style {
586            CursorStyle::IBeam | CursorStyle::IBeamCursorForVerticalLayout => unsafe {
587                load_cursor(IDC_IBEAM)
588            },
589            CursorStyle::Crosshair => unsafe { load_cursor(IDC_CROSS) },
590            CursorStyle::PointingHand | CursorStyle::DragLink => unsafe { load_cursor(IDC_HAND) },
591            CursorStyle::ResizeLeft | CursorStyle::ResizeRight | CursorStyle::ResizeLeftRight => unsafe {
592                load_cursor(IDC_SIZEWE)
593            },
594            CursorStyle::ResizeUp | CursorStyle::ResizeDown | CursorStyle::ResizeUpDown => unsafe {
595                load_cursor(IDC_SIZENS)
596            },
597            CursorStyle::OperationNotAllowed => unsafe { load_cursor(IDC_NO) },
598            _ => unsafe { load_cursor(IDC_ARROW) },
599        };
600        if handle.is_err() {
601            log::error!(
602                "Error loading cursor image: {}",
603                std::io::Error::last_os_error()
604            );
605            return;
606        }
607        let _ = unsafe { SetCursor(HCURSOR(handle.unwrap().0)) };
608    }
609
610    // todo(windows)
611    fn should_auto_hide_scrollbars(&self) -> bool {
612        false
613    }
614
615    fn write_to_clipboard(&self, item: ClipboardItem) {
616        let mut ctx = ClipboardContext::new().unwrap();
617        ctx.set_contents(item.text().to_owned()).unwrap();
618    }
619
620    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
621        let mut ctx = ClipboardContext::new().unwrap();
622        let content = ctx.get_contents().unwrap();
623        Some(ClipboardItem {
624            text: content,
625            metadata: None,
626        })
627    }
628
629    // todo(windows)
630    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
631        Task::Ready(Some(Err(anyhow!("not implemented yet."))))
632    }
633
634    // todo(windows)
635    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
636        Task::Ready(Some(Err(anyhow!("not implemented yet."))))
637    }
638
639    // todo(windows)
640    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
641        Task::Ready(Some(Err(anyhow!("not implemented yet."))))
642    }
643
644    fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
645        Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
646    }
647}
648
649impl Drop for WindowsPlatform {
650    fn drop(&mut self) {
651        unsafe {
652            OleUninitialize();
653        }
654    }
655}
656
657unsafe fn load_cursor(name: PCWSTR) -> Result<HANDLE> {
658    LoadImageW(None, name, IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE | LR_SHARED).map_err(|e| anyhow!(e))
659}
660
661fn open_target(target: &str) {
662    unsafe {
663        let ret = ShellExecuteW(
664            None,
665            windows::core::w!("open"),
666            &HSTRING::from(target),
667            None,
668            None,
669            SW_SHOWDEFAULT,
670        );
671        if ret.0 <= 32 {
672            log::error!("Unable to open target: {}", std::io::Error::last_os_error());
673        }
674    }
675}
676
677unsafe fn show_savefile_dialog(directory: PathBuf) -> Result<IFileSaveDialog> {
678    let dialog: IFileSaveDialog = CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)?;
679    let bind_context = CreateBindCtx(0)?;
680    let Ok(full_path) = directory.canonicalize() else {
681        return Ok(dialog);
682    };
683    let dir_str = full_path.into_os_string();
684    if dir_str.is_empty() {
685        return Ok(dialog);
686    }
687    let dir_vec = dir_str.encode_wide().collect_vec();
688    let ret = SHCreateItemFromParsingName(PCWSTR::from_raw(dir_vec.as_ptr()), &bind_context)
689        .inspect_err(|e| log::error!("unable to create IShellItem: {}", e));
690    if ret.is_ok() {
691        let dir_shell_item: IShellItem = ret.unwrap();
692        let _ = dialog
693            .SetFolder(&dir_shell_item)
694            .inspect_err(|e| log::error!("unable to set folder for save file dialog: {}", e));
695    }
696
697    Ok(dialog)
698}