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