platform.rs

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