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 bitmap_factory = ManuallyDrop::new(unsafe {
 99            CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER)
100                .context("Error creating bitmap factory.")?
101        });
102        let text_system = Arc::new(
103            DirectWriteTextSystem::new(&bitmap_factory)
104                .context("Error creating DirectWriteTextSystem")?,
105        );
106        let drop_target_helper: IDropTargetHelper = unsafe {
107            CoCreateInstance(&CLSID_DragDropHelper, None, CLSCTX_INPROC_SERVER)
108                .context("Error creating drop target helper.")?
109        };
110        let icon = load_icon().unwrap_or_default();
111        let state = RefCell::new(WindowsPlatformState::new());
112        let raw_window_handles = RwLock::new(SmallVec::new());
113        let windows_version = WindowsVersion::new().context("Error retrieve windows version")?;
114
115        Ok(Self {
116            state,
117            raw_window_handles,
118            icon,
119            main_receiver,
120            background_executor,
121            foreground_executor,
122            text_system,
123            windows_version,
124            bitmap_factory,
125            drop_target_helper,
126            validation_number,
127            main_thread_id_win32,
128        })
129    }
130
131    fn redraw_all(&self) {
132        for handle in self.raw_window_handles.read().iter() {
133            unsafe {
134                RedrawWindow(Some(*handle), None, None, RDW_INVALIDATE | RDW_UPDATENOW)
135                    .ok()
136                    .log_err();
137            }
138        }
139    }
140
141    pub fn try_get_windows_inner_from_hwnd(&self, hwnd: HWND) -> Option<Rc<WindowsWindowStatePtr>> {
142        self.raw_window_handles
143            .read()
144            .iter()
145            .find(|entry| *entry == &hwnd)
146            .and_then(|hwnd| try_get_window_inner(*hwnd))
147    }
148
149    #[inline]
150    fn post_message(&self, message: u32, wparam: WPARAM, lparam: LPARAM) {
151        self.raw_window_handles
152            .read()
153            .iter()
154            .for_each(|handle| unsafe {
155                PostMessageW(Some(*handle), message, wparam, lparam).log_err();
156            });
157    }
158
159    fn close_one_window(&self, target_window: HWND) -> bool {
160        let mut lock = self.raw_window_handles.write();
161        let index = lock
162            .iter()
163            .position(|handle| *handle == target_window)
164            .unwrap();
165        lock.remove(index);
166
167        lock.is_empty()
168    }
169
170    #[inline]
171    fn run_foreground_task(&self) {
172        for runnable in self.main_receiver.drain() {
173            runnable.run();
174        }
175    }
176
177    fn generate_creation_info(&self) -> WindowCreationInfo {
178        WindowCreationInfo {
179            icon: self.icon,
180            executor: self.foreground_executor.clone(),
181            current_cursor: self.state.borrow().current_cursor,
182            windows_version: self.windows_version,
183            drop_target_helper: self.drop_target_helper.clone(),
184            validation_number: self.validation_number,
185            main_receiver: self.main_receiver.clone(),
186            main_thread_id_win32: self.main_thread_id_win32,
187        }
188    }
189
190    fn handle_dock_action_event(&self, action_idx: usize) {
191        let mut lock = self.state.borrow_mut();
192        if let Some(mut callback) = lock.callbacks.app_menu_action.take() {
193            let Some(action) = lock
194                .jump_list
195                .dock_menus
196                .get(action_idx)
197                .map(|dock_menu| dock_menu.action.boxed_clone())
198            else {
199                lock.callbacks.app_menu_action = Some(callback);
200                log::error!("Dock menu for index {action_idx} not found");
201                return;
202            };
203            drop(lock);
204            callback(&*action);
205            self.state.borrow_mut().callbacks.app_menu_action = Some(callback);
206        }
207    }
208
209    fn handle_input_lang_change(&self) {
210        let mut lock = self.state.borrow_mut();
211        if let Some(mut callback) = lock.callbacks.keyboard_layout_change.take() {
212            drop(lock);
213            callback();
214            self.state
215                .borrow_mut()
216                .callbacks
217                .keyboard_layout_change
218                .get_or_insert(callback);
219        }
220    }
221
222    // Returns true if the app should quit.
223    fn handle_events(&self) -> bool {
224        let mut msg = MSG::default();
225        unsafe {
226            while PeekMessageW(&mut msg, None, 0, 0, PM_REMOVE).as_bool() {
227                match msg.message {
228                    WM_QUIT => return true,
229                    WM_INPUTLANGCHANGE
230                    | WM_GPUI_CLOSE_ONE_WINDOW
231                    | WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD
232                    | WM_GPUI_DOCK_MENU_ACTION => {
233                        if self.handle_gpui_evnets(msg.message, msg.wParam, msg.lParam, &msg) {
234                            return true;
235                        }
236                    }
237                    _ => {
238                        DispatchMessageW(&msg);
239                    }
240                }
241            }
242        }
243        false
244    }
245
246    // Returns true if the app should quit.
247    fn handle_gpui_evnets(
248        &self,
249        message: u32,
250        wparam: WPARAM,
251        lparam: LPARAM,
252        msg: *const MSG,
253    ) -> bool {
254        if wparam.0 != self.validation_number {
255            unsafe { DispatchMessageW(msg) };
256            return false;
257        }
258        match message {
259            WM_GPUI_CLOSE_ONE_WINDOW => {
260                if self.close_one_window(HWND(lparam.0 as _)) {
261                    return true;
262                }
263            }
264            WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD => self.run_foreground_task(),
265            WM_GPUI_DOCK_MENU_ACTION => self.handle_dock_action_event(lparam.0 as _),
266            WM_INPUTLANGCHANGE => self.handle_input_lang_change(),
267            _ => unreachable!(),
268        }
269        false
270    }
271
272    fn set_dock_menus(&self, menus: Vec<MenuItem>) {
273        let mut actions = Vec::new();
274        menus.into_iter().for_each(|menu| {
275            if let Some(dock_menu) = DockMenuItem::new(menu).log_err() {
276                actions.push(dock_menu);
277            }
278        });
279        let mut lock = self.state.borrow_mut();
280        lock.jump_list.dock_menus = actions;
281        update_jump_list(&lock.jump_list).log_err();
282    }
283
284    fn update_jump_list(
285        &self,
286        menus: Vec<MenuItem>,
287        entries: Vec<SmallVec<[PathBuf; 2]>>,
288    ) -> Vec<SmallVec<[PathBuf; 2]>> {
289        let mut actions = Vec::new();
290        menus.into_iter().for_each(|menu| {
291            if let Some(dock_menu) = DockMenuItem::new(menu).log_err() {
292                actions.push(dock_menu);
293            }
294        });
295        let mut lock = self.state.borrow_mut();
296        lock.jump_list.dock_menus = actions;
297        lock.jump_list.recent_workspaces = entries;
298        update_jump_list(&lock.jump_list)
299            .log_err()
300            .unwrap_or_default()
301    }
302
303    fn find_current_active_window(&self) -> Option<HWND> {
304        let active_window_hwnd = unsafe { GetActiveWindow() };
305        if active_window_hwnd.is_invalid() {
306            return None;
307        }
308        self.raw_window_handles
309            .read()
310            .iter()
311            .find(|&&hwnd| hwnd == active_window_hwnd)
312            .copied()
313    }
314}
315
316impl Platform for WindowsPlatform {
317    fn background_executor(&self) -> BackgroundExecutor {
318        self.background_executor.clone()
319    }
320
321    fn foreground_executor(&self) -> ForegroundExecutor {
322        self.foreground_executor.clone()
323    }
324
325    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
326        self.text_system.clone()
327    }
328
329    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
330        Box::new(
331            WindowsKeyboardLayout::new()
332                .log_err()
333                .unwrap_or(WindowsKeyboardLayout::unknown()),
334        )
335    }
336
337    fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>) {
338        self.state.borrow_mut().callbacks.keyboard_layout_change = Some(callback);
339    }
340
341    fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>) {
342        on_finish_launching();
343        loop {
344            if self.handle_events() {
345                break;
346            }
347            self.redraw_all();
348        }
349
350        if let Some(ref mut callback) = self.state.borrow_mut().callbacks.quit {
351            callback();
352        }
353    }
354
355    fn quit(&self) {
356        self.foreground_executor()
357            .spawn(async { unsafe { PostQuitMessage(0) } })
358            .detach();
359    }
360
361    fn restart(&self, _: Option<PathBuf>) {
362        let pid = std::process::id();
363        let Some(app_path) = self.app_path().log_err() else {
364            return;
365        };
366        let script = format!(
367            r#"
368            $pidToWaitFor = {}
369            $exePath = "{}"
370
371            while ($true) {{
372                $process = Get-Process -Id $pidToWaitFor -ErrorAction SilentlyContinue
373                if (-not $process) {{
374                    Start-Process -FilePath $exePath
375                    break
376                }}
377                Start-Sleep -Seconds 0.1
378            }}
379            "#,
380            pid,
381            app_path.display(),
382        );
383        let restart_process = util::command::new_std_command("powershell.exe")
384            .arg("-command")
385            .arg(script)
386            .spawn();
387
388        match restart_process {
389            Ok(_) => self.quit(),
390            Err(e) => log::error!("failed to spawn restart script: {:?}", e),
391        }
392    }
393
394    fn activate(&self, _ignoring_other_apps: bool) {}
395
396    fn hide(&self) {}
397
398    // todo(windows)
399    fn hide_other_apps(&self) {
400        unimplemented!()
401    }
402
403    // todo(windows)
404    fn unhide_other_apps(&self) {
405        unimplemented!()
406    }
407
408    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
409        WindowsDisplay::displays()
410    }
411
412    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
413        WindowsDisplay::primary_monitor().map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
414    }
415
416    #[cfg(feature = "screen-capture")]
417    fn is_screen_capture_supported(&self) -> bool {
418        true
419    }
420
421    #[cfg(feature = "screen-capture")]
422    fn screen_capture_sources(
423        &self,
424    ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
425        crate::platform::scap_screen_capture::scap_screen_sources(&self.foreground_executor)
426    }
427
428    fn active_window(&self) -> Option<AnyWindowHandle> {
429        let active_window_hwnd = unsafe { GetActiveWindow() };
430        self.try_get_windows_inner_from_hwnd(active_window_hwnd)
431            .map(|inner| inner.handle)
432    }
433
434    fn open_window(
435        &self,
436        handle: AnyWindowHandle,
437        options: WindowParams,
438    ) -> Result<Box<dyn PlatformWindow>> {
439        let window = WindowsWindow::new(handle, options, self.generate_creation_info())
440            .inspect_err(|err| show_error("Failed to open new window", err.to_string()))?;
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}