platform.rs

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