platform.rs

  1use std::{
  2    cell::RefCell,
  3    mem::ManuallyDrop,
  4    path::{Path, PathBuf},
  5    rc::Rc,
  6    sync::Arc,
  7};
  8
  9use ::util::{ResultExt, paths::SanitizedPath};
 10use anyhow::{Context as _, Result, anyhow};
 11use async_task::Runnable;
 12use futures::channel::oneshot::{self, Receiver};
 13use itertools::Itertools;
 14use parking_lot::RwLock;
 15use smallvec::SmallVec;
 16use windows::{
 17    UI::{
 18        StartScreen::{JumpList, JumpListItem},
 19        ViewManagement::UISettings,
 20    },
 21    Win32::{
 22        Foundation::*,
 23        Graphics::{
 24            Gdi::*,
 25            Imaging::{CLSID_WICImagingFactory, IWICImagingFactory},
 26        },
 27        Security::Credentials::*,
 28        System::{Com::*, LibraryLoader::*, Ole::*, SystemInformation::*, Threading::*},
 29        UI::{Input::KeyboardAndMouse::*, Shell::*, WindowsAndMessaging::*},
 30    },
 31    core::*,
 32};
 33
 34use crate::{platform::blade::BladeContext, *};
 35
 36pub(crate) struct WindowsPlatform {
 37    state: RefCell<WindowsPlatformState>,
 38    raw_window_handles: RwLock<SmallVec<[HWND; 4]>>,
 39    gpu_context: BladeContext,
 40    // The below members will never change throughout the entire lifecycle of the app.
 41    icon: HICON,
 42    main_receiver: flume::Receiver<Runnable>,
 43    background_executor: BackgroundExecutor,
 44    foreground_executor: ForegroundExecutor,
 45    text_system: Arc<DirectWriteTextSystem>,
 46    windows_version: WindowsVersion,
 47    bitmap_factory: ManuallyDrop<IWICImagingFactory>,
 48    validation_number: usize,
 49    main_thread_id_win32: u32,
 50}
 51
 52pub(crate) struct WindowsPlatformState {
 53    callbacks: PlatformCallbacks,
 54    menus: Vec<OwnedMenu>,
 55    dock_menu_actions: Vec<Box<dyn Action>>,
 56    // NOTE: standard cursor handles don't need to close.
 57    pub(crate) current_cursor: Option<HCURSOR>,
 58}
 59
 60#[derive(Default)]
 61struct PlatformCallbacks {
 62    open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
 63    quit: Option<Box<dyn FnMut()>>,
 64    reopen: Option<Box<dyn FnMut()>>,
 65    app_menu_action: Option<Box<dyn FnMut(&dyn Action)>>,
 66    will_open_app_menu: Option<Box<dyn FnMut()>>,
 67    validate_app_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
 68}
 69
 70impl WindowsPlatformState {
 71    fn new() -> Self {
 72        let callbacks = PlatformCallbacks::default();
 73        let dock_menu_actions = Vec::new();
 74        let current_cursor = load_cursor(CursorStyle::Arrow);
 75
 76        Self {
 77            callbacks,
 78            dock_menu_actions,
 79            current_cursor,
 80            menus: Vec::new(),
 81        }
 82    }
 83}
 84
 85impl WindowsPlatform {
 86    pub(crate) fn new() -> Self {
 87        unsafe {
 88            OleInitialize(None).expect("unable to initialize Windows OLE");
 89        }
 90        let (main_sender, main_receiver) = flume::unbounded::<Runnable>();
 91        let main_thread_id_win32 = unsafe { GetCurrentThreadId() };
 92        let validation_number = rand::random::<usize>();
 93        let dispatcher = Arc::new(WindowsDispatcher::new(
 94            main_sender,
 95            main_thread_id_win32,
 96            validation_number,
 97        ));
 98        let background_executor = BackgroundExecutor::new(dispatcher.clone());
 99        let foreground_executor = ForegroundExecutor::new(dispatcher);
100        let bitmap_factory = ManuallyDrop::new(unsafe {
101            CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER)
102                .expect("Error creating bitmap factory.")
103        });
104        let text_system = Arc::new(
105            DirectWriteTextSystem::new(&bitmap_factory)
106                .expect("Error creating DirectWriteTextSystem"),
107        );
108        let icon = load_icon().unwrap_or_default();
109        let state = RefCell::new(WindowsPlatformState::new());
110        let raw_window_handles = RwLock::new(SmallVec::new());
111        let gpu_context = BladeContext::new().expect("Unable to init GPU context");
112        let windows_version = WindowsVersion::new().expect("Error retrieve windows version");
113
114        Self {
115            state,
116            raw_window_handles,
117            gpu_context,
118            icon,
119            main_receiver,
120            background_executor,
121            foreground_executor,
122            text_system,
123            windows_version,
124            bitmap_factory,
125            validation_number,
126            main_thread_id_win32,
127        }
128    }
129
130    fn redraw_all(&self) {
131        for handle in self.raw_window_handles.read().iter() {
132            unsafe {
133                RedrawWindow(Some(*handle), None, None, RDW_INVALIDATE | RDW_UPDATENOW)
134                    .ok()
135                    .log_err();
136            }
137        }
138    }
139
140    pub fn try_get_windows_inner_from_hwnd(&self, hwnd: HWND) -> Option<Rc<WindowsWindowStatePtr>> {
141        self.raw_window_handles
142            .read()
143            .iter()
144            .find(|entry| *entry == &hwnd)
145            .and_then(|hwnd| try_get_window_inner(*hwnd))
146    }
147
148    #[inline]
149    fn post_message(&self, message: u32, wparam: WPARAM, lparam: LPARAM) {
150        self.raw_window_handles
151            .read()
152            .iter()
153            .for_each(|handle| unsafe {
154                PostMessageW(Some(*handle), message, wparam, lparam).log_err();
155            });
156    }
157
158    fn close_one_window(&self, target_window: HWND) -> bool {
159        let mut lock = self.raw_window_handles.write();
160        let index = lock
161            .iter()
162            .position(|handle| *handle == target_window)
163            .unwrap();
164        lock.remove(index);
165
166        lock.is_empty()
167    }
168
169    #[inline]
170    fn run_foreground_task(&self) {
171        for runnable in self.main_receiver.drain() {
172            runnable.run();
173        }
174    }
175
176    fn generate_creation_info(&self) -> WindowCreationInfo {
177        WindowCreationInfo {
178            icon: self.icon,
179            executor: self.foreground_executor.clone(),
180            current_cursor: self.state.borrow().current_cursor,
181            windows_version: self.windows_version,
182            validation_number: self.validation_number,
183            main_receiver: self.main_receiver.clone(),
184            main_thread_id_win32: self.main_thread_id_win32,
185        }
186    }
187
188    fn handle_dock_action_event(&self, action_idx: usize) {
189        let mut lock = self.state.borrow_mut();
190        if let Some(mut callback) = lock.callbacks.app_menu_action.take() {
191            let Some(action) = lock
192                .dock_menu_actions
193                .get(action_idx)
194                .map(|action| action.boxed_clone())
195            else {
196                lock.callbacks.app_menu_action = Some(callback);
197                log::error!("Dock menu for index {action_idx} not found");
198                return;
199            };
200            drop(lock);
201            callback(&*action);
202            self.state.borrow_mut().callbacks.app_menu_action = Some(callback);
203        }
204    }
205
206    // Returns true if the app should quit.
207    fn handle_events(&self) -> bool {
208        let mut msg = MSG::default();
209        unsafe {
210            while PeekMessageW(&mut msg, None, 0, 0, PM_REMOVE).as_bool() {
211                match msg.message {
212                    WM_QUIT => return true,
213                    WM_GPUI_CLOSE_ONE_WINDOW
214                    | WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD
215                    | WM_GPUI_DOCK_MENU_ACTION => {
216                        if self.handle_gpui_evnets(msg.message, msg.wParam, msg.lParam, &msg) {
217                            return true;
218                        }
219                    }
220                    _ => {
221                        // todo(windows)
222                        // crate `windows 0.56` reports true as Err
223                        TranslateMessage(&msg).as_bool();
224                        DispatchMessageW(&msg);
225                    }
226                }
227            }
228        }
229        false
230    }
231
232    // Returns true if the app should quit.
233    fn handle_gpui_evnets(
234        &self,
235        message: u32,
236        wparam: WPARAM,
237        lparam: LPARAM,
238        msg: *const MSG,
239    ) -> bool {
240        if wparam.0 != self.validation_number {
241            unsafe { DispatchMessageW(msg) };
242            return false;
243        }
244        match message {
245            WM_GPUI_CLOSE_ONE_WINDOW => {
246                if self.close_one_window(HWND(lparam.0 as _)) {
247                    return true;
248                }
249            }
250            WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD => self.run_foreground_task(),
251            WM_GPUI_DOCK_MENU_ACTION => self.handle_dock_action_event(lparam.0 as _),
252            _ => unreachable!(),
253        }
254        false
255    }
256
257    fn configure_jump_list(&self, menus: Vec<MenuItem>) -> Result<()> {
258        let jump_list = JumpList::LoadCurrentAsync()?.get()?;
259        let items = jump_list.Items()?;
260        items.Clear()?;
261        let mut actions = Vec::new();
262        for item in menus.into_iter() {
263            let item = match item {
264                MenuItem::Separator => JumpListItem::CreateSeparator()?,
265                MenuItem::Submenu(_) => {
266                    log::error!("Set `MenuItemSubmenu` for dock menu on Windows is not supported.");
267                    continue;
268                }
269                MenuItem::Action { name, action, .. } => {
270                    let idx = actions.len();
271                    actions.push(action.boxed_clone());
272                    let item_args = format!("--dock-action {}", idx);
273                    JumpListItem::CreateWithArguments(
274                        &HSTRING::from(item_args),
275                        &HSTRING::from(name.as_ref()),
276                    )?
277                }
278            };
279            items.Append(&item)?;
280        }
281        jump_list.SaveAsync()?.get()?;
282        self.state.borrow_mut().dock_menu_actions = actions;
283        Ok(())
284    }
285}
286
287impl Platform for WindowsPlatform {
288    fn background_executor(&self) -> BackgroundExecutor {
289        self.background_executor.clone()
290    }
291
292    fn foreground_executor(&self) -> ForegroundExecutor {
293        self.foreground_executor.clone()
294    }
295
296    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
297        self.text_system.clone()
298    }
299
300    fn keyboard_layout(&self) -> String {
301        "unknown".into()
302    }
303
304    fn on_keyboard_layout_change(&self, _callback: Box<dyn FnMut()>) {
305        // todo(windows)
306    }
307
308    fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>) {
309        on_finish_launching();
310        let vsync_event = unsafe { Owned::new(CreateEventW(None, false, false, None).unwrap()) };
311        begin_vsync(*vsync_event);
312        'a: loop {
313            let wait_result = unsafe {
314                MsgWaitForMultipleObjects(Some(&[*vsync_event]), false, INFINITE, QS_ALLINPUT)
315            };
316
317            match wait_result {
318                // compositor clock ticked so we should draw a frame
319                WAIT_EVENT(0) => self.redraw_all(),
320                // Windows thread messages are posted
321                WAIT_EVENT(1) => {
322                    if self.handle_events() {
323                        break 'a;
324                    }
325                }
326                _ => {
327                    log::error!("Something went wrong while waiting {:?}", wait_result);
328                    break;
329                }
330            }
331        }
332
333        if let Some(ref mut callback) = self.state.borrow_mut().callbacks.quit {
334            callback();
335        }
336    }
337
338    fn quit(&self) {
339        self.foreground_executor()
340            .spawn(async { unsafe { PostQuitMessage(0) } })
341            .detach();
342    }
343
344    fn restart(&self, _: Option<PathBuf>) {
345        let pid = std::process::id();
346        let Some(app_path) = self.app_path().log_err() else {
347            return;
348        };
349        let script = format!(
350            r#"
351            $pidToWaitFor = {}
352            $exePath = "{}"
353
354            while ($true) {{
355                $process = Get-Process -Id $pidToWaitFor -ErrorAction SilentlyContinue
356                if (-not $process) {{
357                    Start-Process -FilePath $exePath
358                    break
359                }}
360                Start-Sleep -Seconds 0.1
361            }}
362            "#,
363            pid,
364            app_path.display(),
365        );
366        let restart_process = util::command::new_std_command("powershell.exe")
367            .arg("-command")
368            .arg(script)
369            .spawn();
370
371        match restart_process {
372            Ok(_) => self.quit(),
373            Err(e) => log::error!("failed to spawn restart script: {:?}", e),
374        }
375    }
376
377    fn activate(&self, _ignoring_other_apps: bool) {}
378
379    fn hide(&self) {}
380
381    // todo(windows)
382    fn hide_other_apps(&self) {
383        unimplemented!()
384    }
385
386    // todo(windows)
387    fn unhide_other_apps(&self) {
388        unimplemented!()
389    }
390
391    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
392        WindowsDisplay::displays()
393    }
394
395    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
396        WindowsDisplay::primary_monitor().map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
397    }
398
399    fn screen_capture_sources(
400        &self,
401    ) -> oneshot::Receiver<Result<Vec<Box<dyn ScreenCaptureSource>>>> {
402        let (mut tx, rx) = oneshot::channel();
403        tx.send(Err(anyhow!("screen capture not implemented"))).ok();
404        rx
405    }
406
407    fn active_window(&self) -> Option<AnyWindowHandle> {
408        let active_window_hwnd = unsafe { GetActiveWindow() };
409        self.try_get_windows_inner_from_hwnd(active_window_hwnd)
410            .map(|inner| inner.handle)
411    }
412
413    fn open_window(
414        &self,
415        handle: AnyWindowHandle,
416        options: WindowParams,
417    ) -> Result<Box<dyn PlatformWindow>> {
418        let window = WindowsWindow::new(
419            handle,
420            options,
421            self.generate_creation_info(),
422            &self.gpu_context,
423        )?;
424        let handle = window.get_raw_handle();
425        self.raw_window_handles.write().push(handle);
426
427        Ok(Box::new(window))
428    }
429
430    fn window_appearance(&self) -> WindowAppearance {
431        system_appearance().log_err().unwrap_or_default()
432    }
433
434    fn open_url(&self, url: &str) {
435        let url_string = url.to_string();
436        self.background_executor()
437            .spawn(async move {
438                if url_string.is_empty() {
439                    return;
440                }
441                open_target(url_string.as_str());
442            })
443            .detach();
444    }
445
446    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
447        self.state.borrow_mut().callbacks.open_urls = Some(callback);
448    }
449
450    fn prompt_for_paths(
451        &self,
452        options: PathPromptOptions,
453    ) -> Receiver<Result<Option<Vec<PathBuf>>>> {
454        let (tx, rx) = oneshot::channel();
455        self.foreground_executor()
456            .spawn(async move {
457                let _ = tx.send(file_open_dialog(options));
458            })
459            .detach();
460
461        rx
462    }
463
464    fn prompt_for_new_path(&self, directory: &Path) -> Receiver<Result<Option<PathBuf>>> {
465        let directory = directory.to_owned();
466        let (tx, rx) = oneshot::channel();
467        self.foreground_executor()
468            .spawn(async move {
469                let _ = tx.send(file_save_dialog(directory));
470            })
471            .detach();
472
473        rx
474    }
475
476    fn can_select_mixed_files_and_dirs(&self) -> bool {
477        // The FOS_PICKFOLDERS flag toggles between "only files" and "only folders".
478        false
479    }
480
481    fn reveal_path(&self, path: &Path) {
482        let Ok(file_full_path) = path.canonicalize() else {
483            log::error!("unable to parse file path");
484            return;
485        };
486        self.background_executor()
487            .spawn(async move {
488                let Some(path) = file_full_path.to_str() else {
489                    return;
490                };
491                if path.is_empty() {
492                    return;
493                }
494                open_target_in_explorer(path);
495            })
496            .detach();
497    }
498
499    fn open_with_system(&self, path: &Path) {
500        let Ok(full_path) = path.canonicalize() else {
501            log::error!("unable to parse file full path: {}", path.display());
502            return;
503        };
504        self.background_executor()
505            .spawn(async move {
506                let Some(full_path_str) = full_path.to_str() else {
507                    return;
508                };
509                if full_path_str.is_empty() {
510                    return;
511                };
512                open_target(full_path_str);
513            })
514            .detach();
515    }
516
517    fn on_quit(&self, callback: Box<dyn FnMut()>) {
518        self.state.borrow_mut().callbacks.quit = Some(callback);
519    }
520
521    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
522        self.state.borrow_mut().callbacks.reopen = Some(callback);
523    }
524
525    fn set_menus(&self, menus: Vec<Menu>, _keymap: &Keymap) {
526        self.state.borrow_mut().menus = menus.into_iter().map(|menu| menu.owned()).collect();
527    }
528
529    fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
530        Some(self.state.borrow().menus.clone())
531    }
532
533    fn set_dock_menu(&self, menus: Vec<MenuItem>, _keymap: &Keymap) {
534        self.configure_jump_list(menus).log_err();
535    }
536
537    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
538        self.state.borrow_mut().callbacks.app_menu_action = Some(callback);
539    }
540
541    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
542        self.state.borrow_mut().callbacks.will_open_app_menu = Some(callback);
543    }
544
545    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
546        self.state.borrow_mut().callbacks.validate_app_menu_command = Some(callback);
547    }
548
549    fn app_path(&self) -> Result<PathBuf> {
550        Ok(std::env::current_exe()?)
551    }
552
553    // todo(windows)
554    fn path_for_auxiliary_executable(&self, _name: &str) -> Result<PathBuf> {
555        Err(anyhow!("not yet implemented"))
556    }
557
558    fn set_cursor_style(&self, style: CursorStyle) {
559        let hcursor = load_cursor(style);
560        let mut lock = self.state.borrow_mut();
561        if lock.current_cursor.map(|c| c.0) != hcursor.map(|c| c.0) {
562            self.post_message(
563                WM_GPUI_CURSOR_STYLE_CHANGED,
564                WPARAM(0),
565                LPARAM(hcursor.map_or(0, |c| c.0 as isize)),
566            );
567            lock.current_cursor = hcursor;
568        }
569    }
570
571    fn should_auto_hide_scrollbars(&self) -> bool {
572        should_auto_hide_scrollbars().log_err().unwrap_or(false)
573    }
574
575    fn write_to_clipboard(&self, item: ClipboardItem) {
576        write_to_clipboard(item);
577    }
578
579    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
580        read_from_clipboard()
581    }
582
583    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
584        let mut password = password.to_vec();
585        let mut username = username.encode_utf16().chain(Some(0)).collect_vec();
586        let mut target_name = windows_credentials_target_name(url)
587            .encode_utf16()
588            .chain(Some(0))
589            .collect_vec();
590        self.foreground_executor().spawn(async move {
591            let credentials = CREDENTIALW {
592                LastWritten: unsafe { GetSystemTimeAsFileTime() },
593                Flags: CRED_FLAGS(0),
594                Type: CRED_TYPE_GENERIC,
595                TargetName: PWSTR::from_raw(target_name.as_mut_ptr()),
596                CredentialBlobSize: password.len() as u32,
597                CredentialBlob: password.as_ptr() as *mut _,
598                Persist: CRED_PERSIST_LOCAL_MACHINE,
599                UserName: PWSTR::from_raw(username.as_mut_ptr()),
600                ..CREDENTIALW::default()
601            };
602            unsafe { CredWriteW(&credentials, 0) }?;
603            Ok(())
604        })
605    }
606
607    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
608        let mut target_name = windows_credentials_target_name(url)
609            .encode_utf16()
610            .chain(Some(0))
611            .collect_vec();
612        self.foreground_executor().spawn(async move {
613            let mut credentials: *mut CREDENTIALW = std::ptr::null_mut();
614            unsafe {
615                CredReadW(
616                    PCWSTR::from_raw(target_name.as_ptr()),
617                    CRED_TYPE_GENERIC,
618                    None,
619                    &mut credentials,
620                )?
621            };
622
623            if credentials.is_null() {
624                Ok(None)
625            } else {
626                let username: String = unsafe { (*credentials).UserName.to_string()? };
627                let credential_blob = unsafe {
628                    std::slice::from_raw_parts(
629                        (*credentials).CredentialBlob,
630                        (*credentials).CredentialBlobSize as usize,
631                    )
632                };
633                let password = credential_blob.to_vec();
634                unsafe { CredFree(credentials as *const _ as _) };
635                Ok(Some((username, password)))
636            }
637        })
638    }
639
640    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
641        let mut target_name = windows_credentials_target_name(url)
642            .encode_utf16()
643            .chain(Some(0))
644            .collect_vec();
645        self.foreground_executor().spawn(async move {
646            unsafe {
647                CredDeleteW(
648                    PCWSTR::from_raw(target_name.as_ptr()),
649                    CRED_TYPE_GENERIC,
650                    None,
651                )?
652            };
653            Ok(())
654        })
655    }
656
657    fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
658        Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
659    }
660
661    fn perform_dock_menu_action(&self, action: usize) {
662        unsafe {
663            PostThreadMessageW(
664                self.main_thread_id_win32,
665                WM_GPUI_DOCK_MENU_ACTION,
666                WPARAM(self.validation_number),
667                LPARAM(action as isize),
668            )
669            .log_err();
670        }
671    }
672}
673
674impl Drop for WindowsPlatform {
675    fn drop(&mut self) {
676        unsafe {
677            ManuallyDrop::drop(&mut self.bitmap_factory);
678            OleUninitialize();
679        }
680    }
681}
682
683pub(crate) struct WindowCreationInfo {
684    pub(crate) icon: HICON,
685    pub(crate) executor: ForegroundExecutor,
686    pub(crate) current_cursor: Option<HCURSOR>,
687    pub(crate) windows_version: WindowsVersion,
688    pub(crate) validation_number: usize,
689    pub(crate) main_receiver: flume::Receiver<Runnable>,
690    pub(crate) main_thread_id_win32: u32,
691}
692
693fn open_target(target: &str) {
694    unsafe {
695        let ret = ShellExecuteW(
696            None,
697            windows::core::w!("open"),
698            &HSTRING::from(target),
699            None,
700            None,
701            SW_SHOWDEFAULT,
702        );
703        if ret.0 as isize <= 32 {
704            log::error!("Unable to open target: {}", std::io::Error::last_os_error());
705        }
706    }
707}
708
709fn open_target_in_explorer(target: &str) {
710    unsafe {
711        let ret = ShellExecuteW(
712            None,
713            windows::core::w!("open"),
714            windows::core::w!("explorer.exe"),
715            &HSTRING::from(format!("/select,{}", target).as_str()),
716            None,
717            SW_SHOWDEFAULT,
718        );
719        if ret.0 as isize <= 32 {
720            log::error!(
721                "Unable to open target in explorer: {}",
722                std::io::Error::last_os_error()
723            );
724        }
725    }
726}
727
728fn file_open_dialog(options: PathPromptOptions) -> Result<Option<Vec<PathBuf>>> {
729    let folder_dialog: IFileOpenDialog =
730        unsafe { CoCreateInstance(&FileOpenDialog, None, CLSCTX_ALL)? };
731
732    let mut dialog_options = FOS_FILEMUSTEXIST;
733    if options.multiple {
734        dialog_options |= FOS_ALLOWMULTISELECT;
735    }
736    if options.directories {
737        dialog_options |= FOS_PICKFOLDERS;
738    }
739
740    unsafe {
741        folder_dialog.SetOptions(dialog_options)?;
742        if folder_dialog.Show(None).is_err() {
743            // User cancelled
744            return Ok(None);
745        }
746    }
747
748    let results = unsafe { folder_dialog.GetResults()? };
749    let file_count = unsafe { results.GetCount()? };
750    if file_count == 0 {
751        return Ok(None);
752    }
753
754    let mut paths = Vec::new();
755    for i in 0..file_count {
756        let item = unsafe { results.GetItemAt(i)? };
757        let path = unsafe { item.GetDisplayName(SIGDN_FILESYSPATH)?.to_string()? };
758        paths.push(PathBuf::from(path));
759    }
760
761    Ok(Some(paths))
762}
763
764fn file_save_dialog(directory: PathBuf) -> Result<Option<PathBuf>> {
765    let dialog: IFileSaveDialog = unsafe { CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)? };
766    if !directory.to_string_lossy().is_empty() {
767        if let Some(full_path) = directory.canonicalize().log_err() {
768            let full_path = SanitizedPath::from(full_path);
769            let full_path_string = full_path.to_string();
770            let path_item: IShellItem =
771                unsafe { SHCreateItemFromParsingName(&HSTRING::from(full_path_string), None)? };
772            unsafe { dialog.SetFolder(&path_item).log_err() };
773        }
774    }
775    unsafe {
776        dialog.SetFileTypes(&[Common::COMDLG_FILTERSPEC {
777            pszName: windows::core::w!("All files"),
778            pszSpec: windows::core::w!("*.*"),
779        }])?;
780        if dialog.Show(None).is_err() {
781            // User cancelled
782            return Ok(None);
783        }
784    }
785    let shell_item = unsafe { dialog.GetResult()? };
786    let file_path_string = unsafe {
787        let pwstr = shell_item.GetDisplayName(SIGDN_FILESYSPATH)?;
788        let string = pwstr.to_string()?;
789        CoTaskMemFree(Some(pwstr.0 as _));
790        string
791    };
792    Ok(Some(PathBuf::from(file_path_string)))
793}
794
795fn begin_vsync(vsync_event: HANDLE) {
796    let event: SafeHandle = vsync_event.into();
797    std::thread::spawn(move || unsafe {
798        loop {
799            windows::Win32::Graphics::Dwm::DwmFlush().log_err();
800            SetEvent(*event).log_err();
801        }
802    });
803}
804
805fn load_icon() -> Result<HICON> {
806    let module = unsafe { GetModuleHandleW(None).context("unable to get module handle")? };
807    let handle = unsafe {
808        LoadImageW(
809            Some(module.into()),
810            windows::core::PCWSTR(1 as _),
811            IMAGE_ICON,
812            0,
813            0,
814            LR_DEFAULTSIZE | LR_SHARED,
815        )
816        .context("unable to load icon file")?
817    };
818    Ok(HICON(handle.0))
819}
820
821#[inline]
822fn should_auto_hide_scrollbars() -> Result<bool> {
823    let ui_settings = UISettings::new()?;
824    Ok(ui_settings.AutoHideScrollBars()?)
825}
826
827#[cfg(test)]
828mod tests {
829    use crate::{ClipboardItem, read_from_clipboard, write_to_clipboard};
830
831    #[test]
832    fn test_clipboard() {
833        let item = ClipboardItem::new_string("你好,我是张小白".to_string());
834        write_to_clipboard(item.clone());
835        assert_eq!(read_from_clipboard(), Some(item));
836
837        let item = ClipboardItem::new_string("12345".to_string());
838        write_to_clipboard(item.clone());
839        assert_eq!(read_from_clipboard(), Some(item));
840
841        let item = ClipboardItem::new_string_with_json_metadata("abcdef".to_string(), vec![3, 4]);
842        write_to_clipboard(item.clone());
843        assert_eq!(read_from_clipboard(), Some(item));
844    }
845}