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