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