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