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_events(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_events(
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(
494        &self,
495        directory: &Path,
496        suggested_name: Option<&str>,
497    ) -> Receiver<Result<Option<PathBuf>>> {
498        let directory = directory.to_owned();
499        let suggested_name = suggested_name.map(|s| s.to_owned());
500        let (tx, rx) = oneshot::channel();
501        let window = self.find_current_active_window();
502        self.foreground_executor()
503            .spawn(async move {
504                let _ = tx.send(file_save_dialog(directory, suggested_name, window));
505            })
506            .detach();
507
508        rx
509    }
510
511    fn can_select_mixed_files_and_dirs(&self) -> bool {
512        // The FOS_PICKFOLDERS flag toggles between "only files" and "only folders".
513        false
514    }
515
516    fn reveal_path(&self, path: &Path) {
517        let Ok(file_full_path) = path.canonicalize() else {
518            log::error!("unable to parse file path");
519            return;
520        };
521        self.background_executor()
522            .spawn(async move {
523                let Some(path) = file_full_path.to_str() else {
524                    return;
525                };
526                if path.is_empty() {
527                    return;
528                }
529                open_target_in_explorer(path);
530            })
531            .detach();
532    }
533
534    fn open_with_system(&self, path: &Path) {
535        let Ok(full_path) = path.canonicalize() else {
536            log::error!("unable to parse file full path: {}", path.display());
537            return;
538        };
539        self.background_executor()
540            .spawn(async move {
541                let Some(full_path_str) = full_path.to_str() else {
542                    return;
543                };
544                if full_path_str.is_empty() {
545                    return;
546                };
547                open_target(full_path_str);
548            })
549            .detach();
550    }
551
552    fn on_quit(&self, callback: Box<dyn FnMut()>) {
553        self.state.borrow_mut().callbacks.quit = Some(callback);
554    }
555
556    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
557        self.state.borrow_mut().callbacks.reopen = Some(callback);
558    }
559
560    fn set_menus(&self, menus: Vec<Menu>, _keymap: &Keymap) {
561        self.state.borrow_mut().menus = menus.into_iter().map(|menu| menu.owned()).collect();
562    }
563
564    fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
565        Some(self.state.borrow().menus.clone())
566    }
567
568    fn set_dock_menu(&self, menus: Vec<MenuItem>, _keymap: &Keymap) {
569        self.set_dock_menus(menus);
570    }
571
572    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
573        self.state.borrow_mut().callbacks.app_menu_action = Some(callback);
574    }
575
576    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
577        self.state.borrow_mut().callbacks.will_open_app_menu = Some(callback);
578    }
579
580    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
581        self.state.borrow_mut().callbacks.validate_app_menu_command = Some(callback);
582    }
583
584    fn app_path(&self) -> Result<PathBuf> {
585        Ok(std::env::current_exe()?)
586    }
587
588    // todo(windows)
589    fn path_for_auxiliary_executable(&self, _name: &str) -> Result<PathBuf> {
590        anyhow::bail!("not yet implemented");
591    }
592
593    fn set_cursor_style(&self, style: CursorStyle) {
594        let hcursor = load_cursor(style);
595        let mut lock = self.state.borrow_mut();
596        if lock.current_cursor.map(|c| c.0) != hcursor.map(|c| c.0) {
597            self.post_message(
598                WM_GPUI_CURSOR_STYLE_CHANGED,
599                WPARAM(0),
600                LPARAM(hcursor.map_or(0, |c| c.0 as isize)),
601            );
602            lock.current_cursor = hcursor;
603        }
604    }
605
606    fn should_auto_hide_scrollbars(&self) -> bool {
607        should_auto_hide_scrollbars().log_err().unwrap_or(false)
608    }
609
610    fn write_to_clipboard(&self, item: ClipboardItem) {
611        write_to_clipboard(item);
612    }
613
614    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
615        read_from_clipboard()
616    }
617
618    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
619        let mut password = password.to_vec();
620        let mut username = username.encode_utf16().chain(Some(0)).collect_vec();
621        let mut target_name = windows_credentials_target_name(url)
622            .encode_utf16()
623            .chain(Some(0))
624            .collect_vec();
625        self.foreground_executor().spawn(async move {
626            let credentials = CREDENTIALW {
627                LastWritten: unsafe { GetSystemTimeAsFileTime() },
628                Flags: CRED_FLAGS(0),
629                Type: CRED_TYPE_GENERIC,
630                TargetName: PWSTR::from_raw(target_name.as_mut_ptr()),
631                CredentialBlobSize: password.len() as u32,
632                CredentialBlob: password.as_ptr() as *mut _,
633                Persist: CRED_PERSIST_LOCAL_MACHINE,
634                UserName: PWSTR::from_raw(username.as_mut_ptr()),
635                ..CREDENTIALW::default()
636            };
637            unsafe { CredWriteW(&credentials, 0) }?;
638            Ok(())
639        })
640    }
641
642    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
643        let mut target_name = windows_credentials_target_name(url)
644            .encode_utf16()
645            .chain(Some(0))
646            .collect_vec();
647        self.foreground_executor().spawn(async move {
648            let mut credentials: *mut CREDENTIALW = std::ptr::null_mut();
649            unsafe {
650                CredReadW(
651                    PCWSTR::from_raw(target_name.as_ptr()),
652                    CRED_TYPE_GENERIC,
653                    None,
654                    &mut credentials,
655                )?
656            };
657
658            if credentials.is_null() {
659                Ok(None)
660            } else {
661                let username: String = unsafe { (*credentials).UserName.to_string()? };
662                let credential_blob = unsafe {
663                    std::slice::from_raw_parts(
664                        (*credentials).CredentialBlob,
665                        (*credentials).CredentialBlobSize as usize,
666                    )
667                };
668                let password = credential_blob.to_vec();
669                unsafe { CredFree(credentials as *const _ as _) };
670                Ok(Some((username, password)))
671            }
672        })
673    }
674
675    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
676        let mut target_name = windows_credentials_target_name(url)
677            .encode_utf16()
678            .chain(Some(0))
679            .collect_vec();
680        self.foreground_executor().spawn(async move {
681            unsafe {
682                CredDeleteW(
683                    PCWSTR::from_raw(target_name.as_ptr()),
684                    CRED_TYPE_GENERIC,
685                    None,
686                )?
687            };
688            Ok(())
689        })
690    }
691
692    fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
693        Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
694    }
695
696    fn perform_dock_menu_action(&self, action: usize) {
697        unsafe {
698            PostThreadMessageW(
699                self.main_thread_id_win32,
700                WM_GPUI_DOCK_MENU_ACTION,
701                WPARAM(self.validation_number),
702                LPARAM(action as isize),
703            )
704            .log_err();
705        }
706    }
707
708    fn update_jump_list(
709        &self,
710        menus: Vec<MenuItem>,
711        entries: Vec<SmallVec<[PathBuf; 2]>>,
712    ) -> Vec<SmallVec<[PathBuf; 2]>> {
713        self.update_jump_list(menus, entries)
714    }
715}
716
717impl Drop for WindowsPlatform {
718    fn drop(&mut self) {
719        unsafe {
720            ManuallyDrop::drop(&mut self.bitmap_factory);
721            OleUninitialize();
722        }
723    }
724}
725
726pub(crate) struct WindowCreationInfo {
727    pub(crate) icon: HICON,
728    pub(crate) executor: ForegroundExecutor,
729    pub(crate) current_cursor: Option<HCURSOR>,
730    pub(crate) windows_version: WindowsVersion,
731    pub(crate) drop_target_helper: IDropTargetHelper,
732    pub(crate) validation_number: usize,
733    pub(crate) main_receiver: flume::Receiver<Runnable>,
734    pub(crate) main_thread_id_win32: u32,
735    pub(crate) disable_direct_composition: bool,
736}
737
738fn open_target(target: &str) {
739    unsafe {
740        let ret = ShellExecuteW(
741            None,
742            windows::core::w!("open"),
743            &HSTRING::from(target),
744            None,
745            None,
746            SW_SHOWDEFAULT,
747        );
748        if ret.0 as isize <= 32 {
749            log::error!("Unable to open target: {}", std::io::Error::last_os_error());
750        }
751    }
752}
753
754fn open_target_in_explorer(target: &str) {
755    unsafe {
756        let ret = ShellExecuteW(
757            None,
758            windows::core::w!("open"),
759            windows::core::w!("explorer.exe"),
760            &HSTRING::from(format!("/select,{}", target).as_str()),
761            None,
762            SW_SHOWDEFAULT,
763        );
764        if ret.0 as isize <= 32 {
765            log::error!(
766                "Unable to open target in explorer: {}",
767                std::io::Error::last_os_error()
768            );
769        }
770    }
771}
772
773fn file_open_dialog(
774    options: PathPromptOptions,
775    window: Option<HWND>,
776) -> Result<Option<Vec<PathBuf>>> {
777    let folder_dialog: IFileOpenDialog =
778        unsafe { CoCreateInstance(&FileOpenDialog, None, CLSCTX_ALL)? };
779
780    let mut dialog_options = FOS_FILEMUSTEXIST;
781    if options.multiple {
782        dialog_options |= FOS_ALLOWMULTISELECT;
783    }
784    if options.directories {
785        dialog_options |= FOS_PICKFOLDERS;
786    }
787
788    unsafe {
789        folder_dialog.SetOptions(dialog_options)?;
790        if folder_dialog.Show(window).is_err() {
791            // User cancelled
792            return Ok(None);
793        }
794    }
795
796    let results = unsafe { folder_dialog.GetResults()? };
797    let file_count = unsafe { results.GetCount()? };
798    if file_count == 0 {
799        return Ok(None);
800    }
801
802    let mut paths = Vec::with_capacity(file_count as usize);
803    for i in 0..file_count {
804        let item = unsafe { results.GetItemAt(i)? };
805        let path = unsafe { item.GetDisplayName(SIGDN_FILESYSPATH)?.to_string()? };
806        paths.push(PathBuf::from(path));
807    }
808
809    Ok(Some(paths))
810}
811
812fn file_save_dialog(
813    directory: PathBuf,
814    suggested_name: Option<String>,
815    window: Option<HWND>,
816) -> Result<Option<PathBuf>> {
817    let dialog: IFileSaveDialog = unsafe { CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)? };
818    if !directory.to_string_lossy().is_empty() {
819        if let Some(full_path) = directory.canonicalize().log_err() {
820            let full_path = SanitizedPath::from(full_path);
821            let full_path_string = full_path.to_string();
822            let path_item: IShellItem =
823                unsafe { SHCreateItemFromParsingName(&HSTRING::from(full_path_string), None)? };
824            unsafe { dialog.SetFolder(&path_item).log_err() };
825        }
826    }
827
828    if let Some(suggested_name) = suggested_name {
829        unsafe { dialog.SetFileName(&HSTRING::from(suggested_name)).log_err() };
830    }
831
832    unsafe {
833        dialog.SetFileTypes(&[Common::COMDLG_FILTERSPEC {
834            pszName: windows::core::w!("All files"),
835            pszSpec: windows::core::w!("*.*"),
836        }])?;
837        if dialog.Show(window).is_err() {
838            // User cancelled
839            return Ok(None);
840        }
841    }
842    let shell_item = unsafe { dialog.GetResult()? };
843    let file_path_string = unsafe {
844        let pwstr = shell_item.GetDisplayName(SIGDN_FILESYSPATH)?;
845        let string = pwstr.to_string()?;
846        CoTaskMemFree(Some(pwstr.0 as _));
847        string
848    };
849    Ok(Some(PathBuf::from(file_path_string)))
850}
851
852fn load_icon() -> Result<HICON> {
853    let module = unsafe { GetModuleHandleW(None).context("unable to get module handle")? };
854    let handle = unsafe {
855        LoadImageW(
856            Some(module.into()),
857            windows::core::PCWSTR(1 as _),
858            IMAGE_ICON,
859            0,
860            0,
861            LR_DEFAULTSIZE | LR_SHARED,
862        )
863        .context("unable to load icon file")?
864    };
865    Ok(HICON(handle.0))
866}
867
868#[inline]
869fn should_auto_hide_scrollbars() -> Result<bool> {
870    let ui_settings = UISettings::new()?;
871    Ok(ui_settings.AutoHideScrollBars()?)
872}
873
874#[cfg(test)]
875mod tests {
876    use crate::{ClipboardItem, read_from_clipboard, write_to_clipboard};
877
878    #[test]
879    fn test_clipboard() {
880        let item = ClipboardItem::new_string("你好,我是张小白".to_string());
881        write_to_clipboard(item.clone());
882        assert_eq!(read_from_clipboard(), Some(item));
883
884        let item = ClipboardItem::new_string("12345".to_string());
885        write_to_clipboard(item.clone());
886        assert_eq!(read_from_clipboard(), Some(item));
887
888        let item = ClipboardItem::new_string_with_json_metadata("abcdef".to_string(), vec![3, 4]);
889        write_to_clipboard(item.clone());
890        assert_eq!(read_from_clipboard(), Some(item));
891    }
892}