Skip to repository content

tenant.openagents/omega

No repository description is available.

OpenAgents Git authority 2026-07-28T02:57:03.846Z Public web read
NIP-34 coordinate30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omega
MaintainersHidden in public view
References2 branches · 1 tag
Read-only clonegit clone https://openagents.com/git/tenant.openagents/omega.git
Browse files

platform.rs

1514 lines · 52.2 KB · rust
1use std::{
2    cell::{Cell, RefCell},
3    ffi::OsStr,
4    path::{Path, PathBuf},
5    rc::{Rc, Weak},
6    sync::{
7        Arc,
8        atomic::{AtomicBool, Ordering},
9    },
10};
11
12use anyhow::{Context as _, Result, anyhow};
13use futures::channel::oneshot::{self, Receiver};
14use gpui_util::{ResultExt, get_windows_system_shell, new_std_command};
15use itertools::Itertools;
16use parking_lot::RwLock;
17use smallvec::SmallVec;
18use windows::{
19    UI::ViewManagement::UISettings,
20    Win32::{
21        Foundation::*,
22        Graphics::{Direct3D11::ID3D11Device, Gdi::*},
23        Security::Credentials::*,
24        System::{Com::*, LibraryLoader::*, Ole::*, Power::*, SystemInformation::*},
25        UI::{Input::KeyboardAndMouse::*, Shell::*, WindowsAndMessaging::*},
26    },
27    core::*,
28};
29
30use crate::*;
31use gpui::*;
32
33pub struct WindowsPlatform {
34    inner: Rc<WindowsPlatformInner>,
35    raw_window_handles: Arc<RwLock<SmallVec<[SafeHwnd; 4]>>>,
36    // The below members will never change throughout the entire lifecycle of the app.
37    headless: bool,
38    icon: HICON,
39    background_executor: BackgroundExecutor,
40    foreground_executor: ForegroundExecutor,
41    text_system: Arc<dyn PlatformTextSystem>,
42    direct_write_text_system: Option<Arc<DirectWriteTextSystem>>,
43    drop_target_helper: Option<IDropTargetHelper>,
44    /// Flag to instruct the `VSyncProvider` thread to invalidate the directx devices
45    /// as resizing them has failed, causing us to have lost at least the render target.
46    invalidate_devices: Arc<AtomicBool>,
47    handle: HWND,
48    suspend_resume_notification: RefCell<Option<HPOWERNOTIFY>>,
49    disable_direct_composition: bool,
50    has_package_identity: bool,
51    app_identity: RefCell<Option<(String, String)>>,
52    system_notifications: RefCell<SystemNotificationState>,
53}
54
55struct WindowsPlatformInner {
56    state: WindowsPlatformState,
57    raw_window_handles: std::sync::Weak<RwLock<SmallVec<[SafeHwnd; 4]>>>,
58    // The below members will never change throughout the entire lifecycle of the app.
59    validation_number: usize,
60    main_receiver: PriorityQueueReceiver<RunnableVariant>,
61    dispatcher: Arc<WindowsDispatcher>,
62}
63
64pub(crate) struct WindowsPlatformState {
65    callbacks: PlatformCallbacks,
66    menus: RefCell<Vec<OwnedMenu>>,
67    jump_list: RefCell<JumpList>,
68    // NOTE: standard cursor handles don't need to close.
69    pub(crate) current_cursor: Cell<Option<HCURSOR>>,
70    /// Shared with each window so `WM_SETCURSOR` can read it directly.
71    pub(crate) cursor_visible: Arc<AtomicBool>,
72    /// Shared with each window to coordinate draws across windows on the UI
73    /// thread; see [`DrawCoordinator`].
74    pub(crate) draw_coordinator: Rc<DrawCoordinator>,
75    directx_devices: RefCell<Option<DirectXDevices>>,
76}
77
78#[derive(Default)]
79struct PlatformCallbacks {
80    open_urls: Cell<Option<Box<dyn FnMut(Vec<String>)>>>,
81    quit: Cell<Option<Box<dyn FnMut()>>>,
82    reopen: Cell<Option<Box<dyn FnMut()>>>,
83    app_menu_action: Cell<Option<Box<dyn FnMut(&dyn Action)>>>,
84    will_open_app_menu: Cell<Option<Box<dyn FnMut()>>>,
85    validate_app_menu_command: Cell<Option<Box<dyn FnMut(&dyn Action) -> bool>>>,
86    keyboard_layout_change: Cell<Option<Box<dyn FnMut()>>>,
87    system_wake: Cell<Option<Box<dyn FnMut()>>>,
88}
89
90impl WindowsPlatformState {
91    fn new(directx_devices: Option<DirectXDevices>) -> Self {
92        let callbacks = PlatformCallbacks::default();
93        let jump_list = JumpList::new();
94        let current_cursor = load_cursor(CursorStyle::Arrow);
95
96        Self {
97            callbacks,
98            jump_list: RefCell::new(jump_list),
99            current_cursor: Cell::new(current_cursor),
100            cursor_visible: Arc::new(AtomicBool::new(true)),
101            draw_coordinator: Rc::new(DrawCoordinator::new()),
102            directx_devices: RefCell::new(directx_devices),
103            menus: RefCell::new(Vec::new()),
104        }
105    }
106}
107
108impl WindowsPlatform {
109    pub fn new(headless: bool) -> Result<Self> {
110        unsafe {
111            OleInitialize(None).context("unable to initialize Windows OLE")?;
112        }
113        let (directx_devices, text_system, direct_write_text_system) = if !headless {
114            let devices = DirectXDevices::new().context("Creating DirectX devices")?;
115            let dw_text_system = Arc::new(
116                DirectWriteTextSystem::new(&devices)
117                    .context("Error creating DirectWriteTextSystem")?,
118            );
119            (
120                Some(devices),
121                dw_text_system.clone() as Arc<dyn PlatformTextSystem>,
122                Some(dw_text_system),
123            )
124        } else {
125            (
126                None,
127                Arc::new(gpui::NoopTextSystem::new()) as Arc<dyn PlatformTextSystem>,
128                None,
129            )
130        };
131
132        let (main_sender, main_receiver) = PriorityQueueReceiver::new();
133        let validation_number = if usize::BITS == 64 {
134            rand::random::<u64>() as usize
135        } else {
136            rand::random::<u32>() as usize
137        };
138        let raw_window_handles = Arc::new(RwLock::new(SmallVec::new()));
139
140        register_platform_window_class();
141        let mut context = PlatformWindowCreateContext {
142            inner: None,
143            raw_window_handles: Arc::downgrade(&raw_window_handles),
144            validation_number,
145            main_sender: Some(main_sender),
146            main_receiver: Some(main_receiver),
147            directx_devices,
148            dispatcher: None,
149        };
150        let result = unsafe {
151            CreateWindowExW(
152                WINDOW_EX_STYLE(0),
153                PLATFORM_WINDOW_CLASS_NAME,
154                None,
155                WINDOW_STYLE(0),
156                0,
157                0,
158                0,
159                0,
160                Some(HWND_MESSAGE),
161                None,
162                None,
163                Some(&raw const context as *const _),
164            )
165        };
166        let inner = context
167            .inner
168            .take()
169            .context("CreateWindowExW did not run correctly")??;
170        let dispatcher = context
171            .dispatcher
172            .take()
173            .context("CreateWindowExW did not run correctly")?;
174        let handle = result?;
175
176        let disable_direct_composition = std::env::var(DISABLE_DIRECT_COMPOSITION)
177            .is_ok_and(|value| value == "true" || value == "1");
178        let background_executor = BackgroundExecutor::new(dispatcher.clone());
179        let foreground_executor = ForegroundExecutor::new(dispatcher);
180
181        let drop_target_helper: Option<IDropTargetHelper> = if !headless {
182            Some(unsafe {
183                CoCreateInstance(&CLSID_DragDropHelper, None, CLSCTX_INPROC_SERVER)
184                    .context("Error creating drop target helper.")?
185            })
186        } else {
187            None
188        };
189        let icon = if !headless {
190            load_icon().unwrap_or_default()
191        } else {
192            HICON::default()
193        };
194
195        Ok(Self {
196            inner,
197            handle,
198            raw_window_handles,
199            headless,
200            icon,
201            background_executor,
202            foreground_executor,
203            text_system,
204            direct_write_text_system,
205            suspend_resume_notification: RefCell::new(None),
206            disable_direct_composition,
207            has_package_identity: has_package_identity(),
208            drop_target_helper,
209            invalidate_devices: Arc::new(AtomicBool::new(false)),
210            app_identity: RefCell::new(None),
211            system_notifications: RefCell::new(SystemNotificationState::new()),
212        })
213    }
214
215    pub(crate) fn window_from_hwnd(&self, hwnd: HWND) -> Option<Rc<WindowsWindowInner>> {
216        self.raw_window_handles
217            .read()
218            .iter()
219            .find(|entry| entry.as_raw() == hwnd)
220            .and_then(|hwnd| window_from_hwnd(hwnd.as_raw()))
221    }
222
223    #[inline]
224    fn post_message(&self, message: u32, wparam: WPARAM, lparam: LPARAM) {
225        self.raw_window_handles
226            .read()
227            .iter()
228            .for_each(|handle| unsafe {
229                PostMessageW(Some(handle.as_raw()), message, wparam, lparam).log_err();
230            });
231    }
232
233    fn generate_creation_info(&self) -> WindowCreationInfo {
234        WindowCreationInfo {
235            icon: self.icon,
236            executor: self.foreground_executor.clone(),
237            current_cursor: self.inner.state.current_cursor.get(),
238            cursor_visible: self.inner.state.cursor_visible.clone(),
239            drop_target_helper: self.drop_target_helper.clone().unwrap(),
240            validation_number: self.inner.validation_number,
241            main_receiver: self.inner.main_receiver.clone(),
242            platform_window_handle: self.handle,
243            disable_direct_composition: self.disable_direct_composition,
244            directx_devices: self.inner.state.directx_devices.borrow().clone().unwrap(),
245            invalidate_devices: self.invalidate_devices.clone(),
246            draw_coordinator: self.inner.state.draw_coordinator.clone(),
247        }
248    }
249
250    fn set_dock_menus(&self, menus: Vec<MenuItem>) {
251        let mut actions = Vec::new();
252        menus.into_iter().for_each(|menu| {
253            if let Some(dock_menu) = DockMenuItem::new(menu).log_err() {
254                actions.push(dock_menu);
255            }
256        });
257        self.inner.state.jump_list.borrow_mut().dock_menus = actions;
258        let borrow = self.inner.state.jump_list.borrow();
259        let dock_menus = borrow
260            .dock_menus
261            .iter()
262            .map(|menu| (menu.name.clone(), menu.description.clone()))
263            .collect::<Vec<_>>();
264        let recent_workspaces = borrow.recent_workspaces.clone();
265        self.background_executor
266            .spawn(async move {
267                update_jump_list(&recent_workspaces, &dock_menus).log_err();
268            })
269            .detach();
270    }
271
272    fn update_jump_list(
273        &self,
274        menus: Vec<MenuItem>,
275        entries: Vec<SmallVec<[PathBuf; 2]>>,
276    ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
277        let mut actions = Vec::new();
278        menus.into_iter().for_each(|menu| {
279            if let Some(dock_menu) = DockMenuItem::new(menu).log_err() {
280                actions.push(dock_menu);
281            }
282        });
283        let mut jump_list = self.inner.state.jump_list.borrow_mut();
284        jump_list.dock_menus = actions;
285        jump_list.recent_workspaces = entries.into();
286        let dock_menus = jump_list
287            .dock_menus
288            .iter()
289            .map(|menu| (menu.name.clone(), menu.description.clone()))
290            .collect::<Vec<_>>();
291        let recent_workspaces = jump_list.recent_workspaces.clone();
292        self.background_executor.spawn(async move {
293            update_jump_list(&recent_workspaces, &dock_menus)
294                .log_err()
295                .unwrap_or_default()
296        })
297    }
298
299    fn find_current_active_window(&self) -> Option<HWND> {
300        let active_window_hwnd = unsafe { GetActiveWindow() };
301        if active_window_hwnd.is_invalid() {
302            return None;
303        }
304        self.raw_window_handles
305            .read()
306            .iter()
307            .find(|hwnd| hwnd.as_raw() == active_window_hwnd)
308            .map(|hwnd| hwnd.as_raw())
309    }
310
311    fn begin_vsync_thread(&self) {
312        let Some(directx_devices) = self.inner.state.directx_devices.borrow().clone() else {
313            return;
314        };
315        let Some(direct_write_text_system) = &self.direct_write_text_system else {
316            return;
317        };
318        let mut directx_device = directx_devices;
319        let platform_window: SafeHwnd = self.handle.into();
320        let validation_number = self.inner.validation_number;
321        let all_windows = Arc::downgrade(&self.raw_window_handles);
322        let text_system = Arc::downgrade(direct_write_text_system);
323        let invalidate_devices = self.invalidate_devices.clone();
324
325        std::thread::Builder::new()
326            .name("VSyncProvider".to_owned())
327            .spawn(move || {
328                let vsync_provider = VSyncProvider::new();
329                loop {
330                    vsync_provider.wait_for_vsync();
331                    if check_device_lost(&directx_device.device)
332                        || invalidate_devices.fetch_and(false, Ordering::Acquire)
333                    {
334                        if let Err(err) = handle_gpu_device_lost(
335                            &mut directx_device,
336                            platform_window.as_raw(),
337                            validation_number,
338                            &all_windows,
339                            &text_system,
340                        ) {
341                            panic!("Device lost: {err}");
342                        }
343                    }
344                    let Some(all_windows) = all_windows.upgrade() else {
345                        break;
346                    };
347                    for hwnd in all_windows.read().iter() {
348                        unsafe {
349                            let _ = RedrawWindow(Some(hwnd.as_raw()), None, None, RDW_INVALIDATE);
350                        }
351                    }
352                }
353            })
354            .unwrap();
355    }
356}
357
358fn translate_accelerator(msg: &MSG) -> Option<()> {
359    if msg.message != WM_KEYDOWN && msg.message != WM_SYSKEYDOWN {
360        return None;
361    }
362
363    let result = unsafe {
364        SendMessageW(
365            msg.hwnd,
366            WM_GPUI_KEYDOWN,
367            Some(msg.wParam),
368            Some(msg.lParam),
369        )
370    };
371    (result.0 == 0).then_some(())
372}
373
374impl Platform for WindowsPlatform {
375    fn background_executor(&self) -> BackgroundExecutor {
376        self.background_executor.clone()
377    }
378
379    fn foreground_executor(&self) -> ForegroundExecutor {
380        self.foreground_executor.clone()
381    }
382
383    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
384        self.text_system.clone()
385    }
386
387    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
388        Box::new(
389            WindowsKeyboardLayout::new()
390                .log_err()
391                .unwrap_or(WindowsKeyboardLayout::unknown()),
392        )
393    }
394
395    fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper> {
396        Rc::new(WindowsKeyboardMapper::new())
397    }
398
399    fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>) {
400        self.inner
401            .state
402            .callbacks
403            .keyboard_layout_change
404            .set(Some(callback));
405    }
406
407    fn on_thermal_state_change(&self, _callback: Box<dyn FnMut()>) {}
408
409    fn thermal_state(&self) -> ThermalState {
410        ThermalState::Nominal
411    }
412
413    fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>) {
414        on_finish_launching();
415        if !self.headless {
416            self.begin_vsync_thread();
417        }
418
419        let mut msg = MSG::default();
420        unsafe {
421            while GetMessageW(&mut msg, None, 0, 0).as_bool() {
422                if translate_accelerator(&msg).is_none() {
423                    _ = TranslateMessage(&msg);
424                    DispatchMessageW(&msg);
425                }
426            }
427        }
428
429        self.inner
430            .with_callback(|callbacks| &callbacks.quit, |callback| callback());
431    }
432
433    fn quit(&self) {
434        self.foreground_executor()
435            .spawn(async { unsafe { PostQuitMessage(0) } })
436            .detach();
437    }
438
439    fn restart(&self, binary_path: Option<PathBuf>) {
440        let pid = std::process::id();
441        let Some(app_path) = binary_path.or(self.app_path().log_err()) else {
442            return;
443        };
444        let script = format!(
445            r#"
446            $pidToWaitFor = {}
447            $exePath = "{}"
448
449            while ($true) {{
450                $process = Get-Process -Id $pidToWaitFor -ErrorAction SilentlyContinue
451                if (-not $process) {{
452                    Start-Process -FilePath $exePath
453                    break
454                }}
455                Start-Sleep -Seconds 0.1
456            }}
457            "#,
458            pid,
459            app_path.display(),
460        );
461
462        // Defer spawning to the foreground executor so it runs after the
463        // current `AppCell` borrow is released. On Windows, `Command::spawn()`
464        // can pump the Win32 message loop (via `CreateProcessW`), which
465        // re-enters message handling possibly resulting in another mutable
466        // borrow of the `AppCell` ending up with a double borrow panic
467        self.foreground_executor
468            .spawn(async move {
469                #[allow(
470                    clippy::disallowed_methods,
471                    reason = "We are restarting ourselves, using std command thus is fine"
472                )]
473                let restart_process = new_std_command(get_windows_system_shell())
474                    .arg("-command")
475                    .arg(script)
476                    .spawn();
477
478                match restart_process {
479                    Ok(_) => unsafe { PostQuitMessage(0) },
480                    Err(e) => log::error!("failed to spawn restart script: {:?}", e),
481                }
482            })
483            .detach();
484    }
485
486    fn activate(&self, _ignoring_other_apps: bool) {}
487
488    fn hide(&self) {}
489
490    // todo(windows)
491    fn hide_other_apps(&self) {
492        unimplemented!()
493    }
494
495    // todo(windows)
496    fn unhide_other_apps(&self) {
497        unimplemented!()
498    }
499
500    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
501        WindowsDisplay::displays()
502    }
503
504    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
505        WindowsDisplay::primary_monitor().map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
506    }
507
508    #[cfg(feature = "screen-capture")]
509    fn is_screen_capture_supported(&self) -> bool {
510        true
511    }
512
513    #[cfg(feature = "screen-capture")]
514    fn screen_capture_sources(
515        &self,
516    ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
517        gpui::scap_screen_capture::scap_screen_sources(&self.foreground_executor)
518    }
519
520    fn active_window(&self) -> Option<AnyWindowHandle> {
521        let active_window_hwnd = unsafe { GetActiveWindow() };
522        self.window_from_hwnd(active_window_hwnd)
523            .map(|inner| inner.handle)
524    }
525
526    fn open_window(
527        &self,
528        handle: AnyWindowHandle,
529        options: WindowParams,
530    ) -> Result<Box<dyn PlatformWindow>> {
531        let window = WindowsWindow::new(handle, options, self.generate_creation_info())?;
532        let handle = window.get_raw_handle();
533        self.raw_window_handles.write().push(handle.into());
534
535        Ok(Box::new(window))
536    }
537
538    fn window_appearance(&self) -> WindowAppearance {
539        system_appearance().log_err().unwrap_or_default()
540    }
541
542    fn open_url(&self, url: &str) {
543        if url.is_empty() {
544            return;
545        }
546        let url_string = url.to_string();
547        self.background_executor()
548            .spawn(async move {
549                open_target(&url_string)
550                    .with_context(|| format!("Opening url: {}", url_string))
551                    .log_err();
552            })
553            .detach();
554    }
555
556    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
557        self.inner.state.callbacks.open_urls.set(Some(callback));
558    }
559
560    fn prompt_for_paths(
561        &self,
562        options: PathPromptOptions,
563    ) -> Receiver<Result<Option<Vec<PathBuf>>>> {
564        let (tx, rx) = oneshot::channel();
565        let window = self.find_current_active_window();
566        self.foreground_executor()
567            .spawn(async move {
568                let _ = tx.send(file_open_dialog(options, window));
569            })
570            .detach();
571
572        rx
573    }
574
575    fn prompt_for_new_path(
576        &self,
577        directory: &Path,
578        suggested_name: Option<&str>,
579    ) -> Receiver<Result<Option<PathBuf>>> {
580        let directory = directory.to_owned();
581        let suggested_name = suggested_name.map(|s| s.to_owned());
582        let (tx, rx) = oneshot::channel();
583        let window = self.find_current_active_window();
584        self.foreground_executor()
585            .spawn(async move {
586                let _ = tx.send(file_save_dialog(directory, suggested_name, window));
587            })
588            .detach();
589
590        rx
591    }
592
593    fn can_select_mixed_files_and_dirs(&self) -> bool {
594        // The FOS_PICKFOLDERS flag toggles between "only files" and "only folders".
595        false
596    }
597
598    fn reveal_path(&self, path: &Path) {
599        if path.as_os_str().is_empty() {
600            return;
601        }
602        let path = path.to_path_buf();
603        self.background_executor()
604            .spawn(async move {
605                open_target_in_explorer(&path)
606                    .with_context(|| format!("Revealing path {} in explorer", path.display()))
607                    .log_err();
608            })
609            .detach();
610    }
611
612    fn open_with_system(&self, path: &Path) {
613        if path.as_os_str().is_empty() {
614            return;
615        }
616        let path = path.to_path_buf();
617        self.background_executor()
618            .spawn(async move {
619                open_target(&path)
620                    .with_context(|| format!("Opening {} with system", path.display()))
621                    .log_err();
622            })
623            .detach();
624    }
625
626    fn on_quit(&self, callback: Box<dyn FnMut()>) {
627        self.inner.state.callbacks.quit.set(Some(callback));
628    }
629
630    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
631        self.inner.state.callbacks.reopen.set(Some(callback));
632    }
633
634    fn on_system_wake(&self, callback: Box<dyn FnMut()>) {
635        self.inner.state.callbacks.system_wake.set(Some(callback));
636        let mut notification = self.suspend_resume_notification.borrow_mut();
637        if notification.is_none() {
638            *notification = unsafe {
639                // SAFETY: self.handle is the platform window receiving WM_POWERBROADCAST.
640                RegisterSuspendResumeNotification(
641                    HANDLE(self.handle.0),
642                    DEVICE_NOTIFY_WINDOW_HANDLE,
643                )
644                .log_err()
645            };
646        }
647    }
648
649    fn set_app_identity(&self, identifier: &str, name: &str) {
650        // If the process has package identity, it's automatally granted an AUMID by the system.
651        if self.has_package_identity {
652            return;
653        }
654
655        let identifier_utf16 = windows::core::HSTRING::from(identifier);
656        // SAFETY: `identifier_utf16` outlives the call and is null-terminated.
657        if let Err(error) = unsafe {
658            windows::Win32::UI::Shell::SetCurrentProcessExplicitAppUserModelID(
659                windows::core::PCWSTR(identifier_utf16.as_ptr()),
660            )
661        } {
662            log::warn!("failed to set the process AppUserModelID: {error}");
663        }
664        *self.app_identity.borrow_mut() = Some((identifier.to_string(), name.to_string()));
665    }
666
667    fn show_system_notification(&self, notification: gpui::SystemNotification) {
668        let app_identity = self.app_identity.borrow().clone();
669        self.system_notifications
670            .borrow_mut()
671            .show(
672                self.has_package_identity,
673                app_identity
674                    .as_ref()
675                    .map(|(identifier, name)| (identifier.as_str(), name.as_str())),
676                notification,
677            )
678            .log_err();
679    }
680
681    fn dismiss_system_notification(&self, tag: &str) {
682        self.system_notifications.borrow_mut().dismiss(tag);
683    }
684
685    fn on_system_notification_response(
686        &self,
687        callback: Box<dyn FnMut(gpui::SystemNotificationResponse)>,
688    ) {
689        self.system_notifications
690            .borrow_mut()
691            .on_response(&self.foreground_executor, callback);
692    }
693
694    fn set_menus(&self, menus: Vec<Menu>, _keymap: &Keymap) {
695        *self.inner.state.menus.borrow_mut() = menus.into_iter().map(|menu| menu.owned()).collect();
696    }
697
698    fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
699        Some(self.inner.state.menus.borrow().clone())
700    }
701
702    fn set_dock_menu(&self, menus: Vec<MenuItem>, _keymap: &Keymap) {
703        self.set_dock_menus(menus);
704    }
705
706    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
707        self.inner
708            .state
709            .callbacks
710            .app_menu_action
711            .set(Some(callback));
712    }
713
714    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
715        self.inner
716            .state
717            .callbacks
718            .will_open_app_menu
719            .set(Some(callback));
720    }
721
722    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
723        self.inner
724            .state
725            .callbacks
726            .validate_app_menu_command
727            .set(Some(callback));
728    }
729
730    fn app_path(&self) -> Result<PathBuf> {
731        Ok(std::env::current_exe()?)
732    }
733
734    // todo(windows)
735    fn path_for_auxiliary_executable(&self, _name: &str) -> Result<PathBuf> {
736        anyhow::bail!("not yet implemented");
737    }
738
739    fn set_cursor_style(&self, style: CursorStyle) {
740        let hcursor = load_cursor(style);
741        if self.inner.state.current_cursor.get().map(|c| c.0) != hcursor.map(|c| c.0) {
742            self.post_message(
743                WM_GPUI_CURSOR_STYLE_CHANGED,
744                WPARAM(0),
745                LPARAM(hcursor.map_or(0, |c| c.0 as isize)),
746            );
747            self.inner.state.current_cursor.set(hcursor);
748        }
749    }
750
751    fn hide_cursor_until_mouse_moves(&self) {
752        if !self
753            .inner
754            .state
755            .cursor_visible
756            .swap(false, Ordering::Relaxed)
757        {
758            return;
759        }
760
761        for handle in self.raw_window_handles.read().iter() {
762            let Some(window) = window_from_hwnd(handle.as_raw()) else {
763                continue;
764            };
765            if window.state.hovered.get() {
766                unsafe { SetCursor(None) };
767                break;
768            }
769        }
770    }
771
772    fn is_cursor_visible(&self) -> bool {
773        self.inner.state.cursor_visible.load(Ordering::Relaxed)
774    }
775
776    fn should_auto_hide_scrollbars(&self) -> bool {
777        should_auto_hide_scrollbars().log_err().unwrap_or(false)
778    }
779
780    fn write_to_clipboard(&self, item: ClipboardItem) {
781        write_to_clipboard(item);
782    }
783
784    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
785        read_from_clipboard()
786    }
787
788    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
789        // CredWriteW rejects larger blobs with the opaque RPC error
790        // 0x800706F7 "The stub received bad data", so fail with a clear
791        // message instead.
792        if password.len() > CRED_MAX_CREDENTIAL_BLOB_SIZE as usize {
793            return Task::ready(Err(anyhow!(
794                "credential for {url} is {} bytes, which exceeds the Windows Credential Manager limit of {CRED_MAX_CREDENTIAL_BLOB_SIZE} bytes",
795                password.len()
796            )));
797        }
798        let password = password.to_vec();
799        let mut username = username.encode_utf16().chain(Some(0)).collect_vec();
800        let mut target_name = windows_credentials_target_name(url)
801            .encode_utf16()
802            .chain(Some(0))
803            .collect_vec();
804        self.foreground_executor().spawn(async move {
805            let credentials = CREDENTIALW {
806                LastWritten: unsafe { GetSystemTimeAsFileTime() },
807                Flags: CRED_FLAGS(0),
808                Type: CRED_TYPE_GENERIC,
809                TargetName: PWSTR::from_raw(target_name.as_mut_ptr()),
810                CredentialBlobSize: password.len() as u32,
811                CredentialBlob: password.as_ptr() as *mut _,
812                Persist: CRED_PERSIST_LOCAL_MACHINE,
813                UserName: PWSTR::from_raw(username.as_mut_ptr()),
814                ..CREDENTIALW::default()
815            };
816            unsafe {
817                CredWriteW(&credentials, 0).map_err(|err| {
818                    anyhow!(
819                        "Failed to write credentials to Windows Credential Manager: {}",
820                        err,
821                    )
822                })?;
823            }
824            Ok(())
825        })
826    }
827
828    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
829        let target_name = windows_credentials_target_name(url)
830            .encode_utf16()
831            .chain(Some(0))
832            .collect_vec();
833        self.foreground_executor().spawn(async move {
834            let mut credentials: *mut CREDENTIALW = std::ptr::null_mut();
835            let result = unsafe {
836                CredReadW(
837                    PCWSTR::from_raw(target_name.as_ptr()),
838                    CRED_TYPE_GENERIC,
839                    None,
840                    &mut credentials,
841                )
842            };
843
844            if let Err(err) = result {
845                // ERROR_NOT_FOUND means the credential doesn't exist.
846                // Return Ok(None) to match macOS and Linux behavior.
847                if err.code() == ERROR_NOT_FOUND.to_hresult() {
848                    return Ok(None);
849                }
850                return Err(err.into());
851            }
852
853            if credentials.is_null() {
854                Ok(None)
855            } else {
856                let username: String = unsafe { (*credentials).UserName.to_string()? };
857                let credential_blob = unsafe {
858                    std::slice::from_raw_parts(
859                        (*credentials).CredentialBlob,
860                        (*credentials).CredentialBlobSize as usize,
861                    )
862                };
863                let password = credential_blob.to_vec();
864                unsafe { CredFree(credentials as *const _ as _) };
865                Ok(Some((username, password)))
866            }
867        })
868    }
869
870    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
871        let target_name = windows_credentials_target_name(url)
872            .encode_utf16()
873            .chain(Some(0))
874            .collect_vec();
875        self.foreground_executor().spawn(async move {
876            unsafe {
877                CredDeleteW(
878                    PCWSTR::from_raw(target_name.as_ptr()),
879                    CRED_TYPE_GENERIC,
880                    None,
881                )?
882            };
883            Ok(())
884        })
885    }
886
887    fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
888        Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
889    }
890
891    fn perform_dock_menu_action(&self, action: usize) {
892        unsafe {
893            PostMessageW(
894                Some(self.handle),
895                WM_GPUI_DOCK_MENU_ACTION,
896                WPARAM(self.inner.validation_number),
897                LPARAM(action as isize),
898            )
899            .log_err();
900        }
901    }
902
903    fn update_jump_list(
904        &self,
905        menus: Vec<MenuItem>,
906        entries: Vec<SmallVec<[PathBuf; 2]>>,
907    ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
908        self.update_jump_list(menus, entries)
909    }
910}
911
912impl WindowsPlatformInner {
913    fn new(context: &mut PlatformWindowCreateContext) -> Result<Rc<Self>> {
914        let state = WindowsPlatformState::new(context.directx_devices.take());
915        Ok(Rc::new(Self {
916            state,
917            raw_window_handles: context.raw_window_handles.clone(),
918            dispatcher: context
919                .dispatcher
920                .as_ref()
921                .context("missing dispatcher")?
922                .clone(),
923            validation_number: context.validation_number,
924            main_receiver: context
925                .main_receiver
926                .take()
927                .context("missing main receiver")?,
928        }))
929    }
930
931    /// Calls `project` to project to the corresponding callback field, removes it from callbacks, calls `f` with the callback and then puts the callback back.
932    fn with_callback<T>(
933        &self,
934        project: impl Fn(&PlatformCallbacks) -> &Cell<Option<T>>,
935        f: impl FnOnce(&mut T),
936    ) {
937        let callback = project(&self.state.callbacks).take();
938        if let Some(mut callback) = callback {
939            f(&mut callback);
940            project(&self.state.callbacks).set(Some(callback));
941        }
942    }
943
944    fn handle_msg(
945        self: &Rc<Self>,
946        handle: HWND,
947        msg: u32,
948        wparam: WPARAM,
949        lparam: LPARAM,
950    ) -> LRESULT {
951        let handled = match msg {
952            WM_GPUI_CLOSE_ONE_WINDOW
953            | WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD
954            | WM_GPUI_DOCK_MENU_ACTION
955            | WM_GPUI_KEYBOARD_LAYOUT_CHANGED
956            | WM_GPUI_GPU_DEVICE_LOST => self.handle_gpui_events(msg, wparam, lparam),
957            WM_POWERBROADCAST => self.handle_power_broadcast(wparam),
958            _ => None,
959        };
960        if let Some(result) = handled {
961            LRESULT(result)
962        } else {
963            unsafe { DefWindowProcW(handle, msg, wparam, lparam) }
964        }
965    }
966
967    fn handle_gpui_events(&self, message: u32, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {
968        if wparam.0 != self.validation_number {
969            log::error!("Wrong validation number while processing message: {message}");
970            return None;
971        }
972        match message {
973            WM_GPUI_CLOSE_ONE_WINDOW => {
974                self.close_one_window(HWND(lparam.0 as _));
975                Some(0)
976            }
977            WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD => self.run_foreground_task(),
978            WM_GPUI_DOCK_MENU_ACTION => self.handle_dock_action_event(lparam.0 as _),
979            WM_GPUI_KEYBOARD_LAYOUT_CHANGED => self.handle_keyboard_layout_change(),
980            WM_GPUI_GPU_DEVICE_LOST => self.handle_device_lost(lparam),
981            _ => unreachable!(),
982        }
983    }
984
985    fn close_one_window(&self, target_window: HWND) -> bool {
986        let Some(all_windows) = self.raw_window_handles.upgrade() else {
987            log::error!("Failed to upgrade raw window handles");
988            return false;
989        };
990        let mut lock = all_windows.write();
991        let index = lock
992            .iter()
993            .position(|handle| handle.as_raw() == target_window)
994            .unwrap();
995        lock.remove(index);
996
997        lock.is_empty()
998    }
999
1000    #[inline]
1001    fn run_foreground_task(&self) -> Option<isize> {
1002        const MAIN_TASK_TIMEOUT: u128 = 10;
1003
1004        let start = std::time::Instant::now();
1005        'tasks: loop {
1006            'timeout_loop: loop {
1007                if start.elapsed().as_millis() >= MAIN_TASK_TIMEOUT {
1008                    log::debug!("foreground task timeout reached");
1009                    // we spent our budget on gpui tasks, we likely have a lot of work queued so drain system events first to stay responsive
1010                    // then quit out of foreground work to allow us to process other gpui events first before returning back to foreground task work
1011                    // if we don't we might not for example process window quit events
1012                    let mut msg = MSG::default();
1013                    let process_message = |msg: &_| {
1014                        if translate_accelerator(msg).is_none() {
1015                            _ = unsafe { TranslateMessage(msg) };
1016                            unsafe { DispatchMessageW(msg) };
1017                        }
1018                    };
1019                    let peek_msg = |msg: &mut _, msg_kind| unsafe {
1020                        PeekMessageW(msg, None, 0, 0, PM_REMOVE | msg_kind).as_bool()
1021                    };
1022                    // We need to process a paint message here as otherwise we will re-enter `run_foreground_task` before painting if we have work remaining.
1023                    // The reason for this is that windows prefers custom application message processing over system messages.
1024                    if peek_msg(&mut msg, PM_QS_PAINT) {
1025                        process_message(&msg);
1026                    }
1027                    while peek_msg(&mut msg, PM_QS_INPUT) {
1028                        process_message(&msg);
1029                    }
1030                    // Allow the main loop to process other gpui events before going back into `run_foreground_task`
1031                    unsafe {
1032                        if let Err(_) = PostMessageW(
1033                            Some(self.dispatcher.platform_window_handle.as_raw()),
1034                            WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD,
1035                            WPARAM(self.validation_number),
1036                            LPARAM(0),
1037                        ) {
1038                            self.dispatcher.wake_posted.store(false, Ordering::Release);
1039                        };
1040                    }
1041                    break 'tasks;
1042                }
1043                let mut main_receiver = self.main_receiver.clone();
1044                match main_receiver.try_pop() {
1045                    Ok(Some(runnable)) => WindowsDispatcher::execute_runnable(runnable),
1046                    _ => break 'timeout_loop,
1047                }
1048            }
1049
1050            // Someone could enqueue a Runnable here. The flag is still true, so they will not PostMessage.
1051            // We need to check for those Runnables after we clear the flag.
1052            self.dispatcher.wake_posted.store(false, Ordering::Release);
1053            let mut main_receiver = self.main_receiver.clone();
1054            match main_receiver.try_pop() {
1055                Ok(Some(runnable)) => {
1056                    self.dispatcher.wake_posted.store(true, Ordering::Release);
1057
1058                    WindowsDispatcher::execute_runnable(runnable);
1059                }
1060                _ => break 'tasks,
1061            }
1062        }
1063
1064        Some(0)
1065    }
1066
1067    fn handle_dock_action_event(&self, action_idx: usize) -> Option<isize> {
1068        let Some(action) = self
1069            .state
1070            .jump_list
1071            .borrow()
1072            .dock_menus
1073            .get(action_idx)
1074            .map(|dock_menu| dock_menu.action.boxed_clone())
1075        else {
1076            log::error!("Dock menu for index {action_idx} not found");
1077            return Some(1);
1078        };
1079        self.with_callback(
1080            |callbacks| &callbacks.app_menu_action,
1081            |callback| callback(&*action),
1082        );
1083        Some(0)
1084    }
1085
1086    fn handle_keyboard_layout_change(&self) -> Option<isize> {
1087        self.with_callback(
1088            |callbacks| &callbacks.keyboard_layout_change,
1089            |callback| callback(),
1090        );
1091        Some(0)
1092    }
1093
1094    fn handle_power_broadcast(&self, wparam: WPARAM) -> Option<isize> {
1095        if wparam.0 as u32 == PBT_APMRESUMEAUTOMATIC {
1096            self.with_callback(|callbacks| &callbacks.system_wake, |callback| callback());
1097        }
1098        Some(1)
1099    }
1100
1101    fn handle_device_lost(&self, lparam: LPARAM) -> Option<isize> {
1102        let directx_devices = lparam.0 as *const DirectXDevices;
1103        let directx_devices = unsafe { &*directx_devices };
1104        self.state.directx_devices.borrow_mut().take();
1105        *self.state.directx_devices.borrow_mut() = Some(directx_devices.clone());
1106
1107        Some(0)
1108    }
1109}
1110
1111impl Drop for WindowsPlatform {
1112    fn drop(&mut self) {
1113        unsafe {
1114            if let Some(notification) = self.suspend_resume_notification.borrow_mut().take() {
1115                // SAFETY: notification was returned by RegisterSuspendResumeNotification.
1116                UnregisterSuspendResumeNotification(notification).log_err();
1117            }
1118            DestroyWindow(self.handle)
1119                .context("Destroying platform window")
1120                .log_err();
1121            OleUninitialize();
1122        }
1123    }
1124}
1125
1126pub(crate) struct WindowCreationInfo {
1127    pub(crate) icon: HICON,
1128    pub(crate) executor: ForegroundExecutor,
1129    pub(crate) current_cursor: Option<HCURSOR>,
1130    pub(crate) cursor_visible: Arc<AtomicBool>,
1131    pub(crate) drop_target_helper: IDropTargetHelper,
1132    pub(crate) validation_number: usize,
1133    pub(crate) main_receiver: PriorityQueueReceiver<RunnableVariant>,
1134    pub(crate) platform_window_handle: HWND,
1135    pub(crate) disable_direct_composition: bool,
1136    pub(crate) directx_devices: DirectXDevices,
1137    /// Flag to instruct the `VSyncProvider` thread to invalidate the directx devices
1138    /// as resizing them has failed, causing us to have lost at least the render target.
1139    pub(crate) invalidate_devices: Arc<AtomicBool>,
1140    /// Shared with [`WindowsPlatformState::draw_coordinator`] and every other window.
1141    pub(crate) draw_coordinator: Rc<DrawCoordinator>,
1142}
1143
1144struct PlatformWindowCreateContext {
1145    inner: Option<Result<Rc<WindowsPlatformInner>>>,
1146    raw_window_handles: std::sync::Weak<RwLock<SmallVec<[SafeHwnd; 4]>>>,
1147    validation_number: usize,
1148    main_sender: Option<PriorityQueueSender<RunnableVariant>>,
1149    main_receiver: Option<PriorityQueueReceiver<RunnableVariant>>,
1150    directx_devices: Option<DirectXDevices>,
1151    dispatcher: Option<Arc<WindowsDispatcher>>,
1152}
1153
1154fn has_package_identity() -> bool {
1155    let mut package_full_name_length = 0;
1156    let result = unsafe {
1157        windows::Win32::Storage::Packaging::Appx::GetCurrentPackageFullName(
1158            &mut package_full_name_length,
1159            None,
1160        )
1161    };
1162    if result == ERROR_INSUFFICIENT_BUFFER {
1163        true
1164    } else if result == APPMODEL_ERROR_NO_PACKAGE {
1165        false
1166    } else {
1167        log::warn!("failed to determine whether the process has package identity: {result:?}");
1168        false
1169    }
1170}
1171
1172fn open_target(target: impl AsRef<OsStr>) -> Result<()> {
1173    let target = target.as_ref();
1174    let ret = unsafe {
1175        ShellExecuteW(
1176            None,
1177            windows::core::w!("open"),
1178            &HSTRING::from(target),
1179            None,
1180            None,
1181            SW_SHOWDEFAULT,
1182        )
1183    };
1184    if ret.0 as isize <= 32 {
1185        Err(anyhow::anyhow!(
1186            "Unable to open target: {}",
1187            std::io::Error::last_os_error()
1188        ))
1189    } else {
1190        Ok(())
1191    }
1192}
1193
1194fn open_target_in_explorer(target: &Path) -> Result<()> {
1195    let dir = target.parent().context("No parent folder found")?;
1196    let desktop = unsafe { SHGetDesktopFolder()? };
1197
1198    let mut dir_item = std::ptr::null_mut();
1199    unsafe {
1200        desktop.ParseDisplayName(
1201            HWND::default(),
1202            None,
1203            &HSTRING::from(dir),
1204            None,
1205            &mut dir_item,
1206            std::ptr::null_mut(),
1207        )?;
1208    }
1209
1210    let mut file_item = std::ptr::null_mut();
1211    unsafe {
1212        desktop.ParseDisplayName(
1213            HWND::default(),
1214            None,
1215            &HSTRING::from(target),
1216            None,
1217            &mut file_item,
1218            std::ptr::null_mut(),
1219        )?;
1220    }
1221
1222    let highlight = [file_item as *const _];
1223    unsafe { SHOpenFolderAndSelectItems(dir_item as _, Some(&highlight), 0) }.or_else(|err| {
1224        if err.code().0 == ERROR_FILE_NOT_FOUND.0 as i32 {
1225            // On some systems, the above call mysteriously fails with "file not
1226            // found" even though the file is there.  In these cases, ShellExecute()
1227            // seems to work as a fallback (although it won't select the file).
1228            open_target(dir).context("Opening target parent folder")
1229        } else {
1230            Err(anyhow::anyhow!("Can not open target path: {}", err))
1231        }
1232    })
1233}
1234
1235fn file_open_dialog(
1236    options: PathPromptOptions,
1237    window: Option<HWND>,
1238) -> Result<Option<Vec<PathBuf>>> {
1239    let folder_dialog: IFileOpenDialog =
1240        unsafe { CoCreateInstance(&FileOpenDialog, None, CLSCTX_ALL)? };
1241
1242    let mut dialog_options = FOS_FILEMUSTEXIST;
1243    if options.multiple {
1244        dialog_options |= FOS_ALLOWMULTISELECT;
1245    }
1246    if options.directories {
1247        dialog_options |= FOS_PICKFOLDERS;
1248    }
1249
1250    unsafe {
1251        folder_dialog.SetOptions(dialog_options)?;
1252
1253        if let Some(prompt) = options.prompt {
1254            let prompt: &str = &prompt;
1255            folder_dialog.SetOkButtonLabel(&HSTRING::from(prompt))?;
1256        }
1257
1258        if folder_dialog.Show(window).is_err() {
1259            // User cancelled
1260            return Ok(None);
1261        }
1262    }
1263
1264    let results = unsafe { folder_dialog.GetResults()? };
1265    let file_count = unsafe { results.GetCount()? };
1266    if file_count == 0 {
1267        return Ok(None);
1268    }
1269
1270    let mut paths = Vec::with_capacity(file_count as usize);
1271    for i in 0..file_count {
1272        let item = unsafe { results.GetItemAt(i)? };
1273        let path = unsafe { item.GetDisplayName(SIGDN_FILESYSPATH)?.to_string()? };
1274        paths.push(PathBuf::from(path));
1275    }
1276
1277    Ok(Some(paths))
1278}
1279
1280fn file_save_dialog(
1281    directory: PathBuf,
1282    suggested_name: Option<String>,
1283    window: Option<HWND>,
1284) -> Result<Option<PathBuf>> {
1285    let dialog: IFileSaveDialog = unsafe { CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)? };
1286    if !directory.to_string_lossy().is_empty()
1287        && let Some(full_path) = directory
1288            .canonicalize()
1289            .context("failed to canonicalize directory")
1290            .log_err()
1291    {
1292        let full_path = dunce::simplified(&full_path);
1293        let full_path_string = full_path.display().to_string();
1294        let path_item: IShellItem =
1295            unsafe { SHCreateItemFromParsingName(&HSTRING::from(full_path_string), None)? };
1296        unsafe {
1297            dialog
1298                .SetFolder(&path_item)
1299                .context("failed to set dialog folder")
1300                .log_err()
1301        };
1302    }
1303
1304    if let Some(suggested_name) = suggested_name {
1305        unsafe {
1306            dialog
1307                .SetFileName(&HSTRING::from(suggested_name))
1308                .context("failed to set file name")
1309                .log_err()
1310        };
1311    }
1312
1313    unsafe {
1314        dialog.SetFileTypes(&[Common::COMDLG_FILTERSPEC {
1315            pszName: windows::core::w!("All files"),
1316            pszSpec: windows::core::w!("*.*"),
1317        }])?;
1318        if dialog.Show(window).is_err() {
1319            // User cancelled
1320            return Ok(None);
1321        }
1322    }
1323    let shell_item = unsafe { dialog.GetResult()? };
1324    let file_path_string = unsafe {
1325        let pwstr = shell_item.GetDisplayName(SIGDN_FILESYSPATH)?;
1326        let string = pwstr.to_string()?;
1327        CoTaskMemFree(Some(pwstr.0 as _));
1328        string
1329    };
1330    Ok(Some(PathBuf::from(file_path_string)))
1331}
1332
1333fn load_icon() -> Result<HICON> {
1334    let module = unsafe { GetModuleHandleW(None).context("unable to get module handle")? };
1335    let handle = unsafe {
1336        LoadImageW(
1337            Some(module.into()),
1338            windows::core::PCWSTR(1 as _),
1339            IMAGE_ICON,
1340            0,
1341            0,
1342            LR_DEFAULTSIZE | LR_SHARED,
1343        )
1344        .context("unable to load icon file")?
1345    };
1346    Ok(HICON(handle.0))
1347}
1348
1349#[inline]
1350fn should_auto_hide_scrollbars() -> Result<bool> {
1351    let ui_settings = UISettings::new()?;
1352    Ok(ui_settings.AutoHideScrollBars()?)
1353}
1354
1355fn check_device_lost(device: &ID3D11Device) -> bool {
1356    let device_state = unsafe { device.GetDeviceRemovedReason() };
1357    match device_state {
1358        Ok(_) => false,
1359        Err(err) => {
1360            log::error!("DirectX device lost detected: {:?}", err);
1361            true
1362        }
1363    }
1364}
1365
1366fn handle_gpu_device_lost(
1367    directx_devices: &mut DirectXDevices,
1368    platform_window: HWND,
1369    validation_number: usize,
1370    all_windows: &std::sync::Weak<RwLock<SmallVec<[SafeHwnd; 4]>>>,
1371    text_system: &std::sync::Weak<DirectWriteTextSystem>,
1372) -> Result<()> {
1373    // Here we wait a bit to ensure the system has time to recover from the device lost state.
1374    // If we don't wait, the final drawing result will be blank.
1375    std::thread::sleep(std::time::Duration::from_millis(350));
1376
1377    *directx_devices = try_to_recover_from_device_lost(|| {
1378        DirectXDevices::new().context("Failed to recreate new DirectX devices after device lost")
1379    })?;
1380    log::info!("DirectX devices successfully recreated.");
1381
1382    let lparam = LPARAM(directx_devices as *const _ as _);
1383    unsafe {
1384        SendMessageW(
1385            platform_window,
1386            WM_GPUI_GPU_DEVICE_LOST,
1387            Some(WPARAM(validation_number)),
1388            Some(lparam),
1389        );
1390    }
1391
1392    if let Some(text_system) = text_system.upgrade() {
1393        text_system.handle_gpu_lost(&directx_devices)?;
1394    }
1395    if let Some(all_windows) = all_windows.upgrade() {
1396        for window in all_windows.read().iter() {
1397            unsafe {
1398                SendMessageW(
1399                    window.as_raw(),
1400                    WM_GPUI_GPU_DEVICE_LOST,
1401                    Some(WPARAM(validation_number)),
1402                    Some(lparam),
1403                );
1404            }
1405        }
1406        std::thread::sleep(std::time::Duration::from_millis(200));
1407        for window in all_windows.read().iter() {
1408            unsafe {
1409                SendMessageW(
1410                    window.as_raw(),
1411                    WM_GPUI_FORCE_UPDATE_WINDOW,
1412                    Some(WPARAM(validation_number)),
1413                    None,
1414                );
1415            }
1416        }
1417    }
1418    Ok(())
1419}
1420
1421const PLATFORM_WINDOW_CLASS_NAME: PCWSTR = w!("Zed::PlatformWindow");
1422
1423fn register_platform_window_class() {
1424    let wc = WNDCLASSW {
1425        lpfnWndProc: Some(window_procedure),
1426        lpszClassName: PCWSTR(PLATFORM_WINDOW_CLASS_NAME.as_ptr()),
1427        ..Default::default()
1428    };
1429    unsafe { RegisterClassW(&wc) };
1430}
1431
1432unsafe extern "system" fn window_procedure(
1433    hwnd: HWND,
1434    msg: u32,
1435    wparam: WPARAM,
1436    lparam: LPARAM,
1437) -> LRESULT {
1438    if msg == WM_NCCREATE {
1439        let params = unsafe { &*(lparam.0 as *const CREATESTRUCTW) };
1440        let creation_context = params.lpCreateParams as *mut PlatformWindowCreateContext;
1441        let creation_context = unsafe { &mut *creation_context };
1442
1443        let Some(main_sender) = creation_context.main_sender.take() else {
1444            creation_context.inner = Some(Err(anyhow!("missing main sender")));
1445            return LRESULT(0);
1446        };
1447        creation_context.dispatcher = Some(Arc::new(WindowsDispatcher::new(
1448            main_sender,
1449            hwnd,
1450            creation_context.validation_number,
1451        )));
1452
1453        return match WindowsPlatformInner::new(creation_context) {
1454            Ok(inner) => {
1455                let weak = Box::new(Rc::downgrade(&inner));
1456                unsafe { set_window_long(hwnd, GWLP_USERDATA, Box::into_raw(weak) as isize) };
1457                creation_context.inner = Some(Ok(inner));
1458                unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
1459            }
1460            Err(error) => {
1461                creation_context.inner = Some(Err(error));
1462                LRESULT(0)
1463            }
1464        };
1465    }
1466
1467    let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsPlatformInner>;
1468    if ptr.is_null() {
1469        return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
1470    }
1471    let inner = unsafe { &*ptr };
1472    let result = if let Some(inner) = inner.upgrade() {
1473        if cfg!(debug_assertions) {
1474            let inner = std::panic::AssertUnwindSafe(inner);
1475            match std::panic::catch_unwind(|| { inner }.handle_msg(hwnd, msg, wparam, lparam)) {
1476                Ok(result) => result,
1477                Err(_) => std::process::abort(),
1478            }
1479        } else {
1480            inner.handle_msg(hwnd, msg, wparam, lparam)
1481        }
1482    } else {
1483        unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
1484    };
1485
1486    if msg == WM_NCDESTROY {
1487        unsafe { set_window_long(hwnd, GWLP_USERDATA, 0) };
1488        unsafe { drop(Box::from_raw(ptr)) };
1489    }
1490
1491    result
1492}
1493
1494#[cfg(test)]
1495mod tests {
1496    use crate::{read_from_clipboard, write_to_clipboard};
1497    use gpui::ClipboardItem;
1498
1499    #[test]
1500    fn test_clipboard() {
1501        let item = ClipboardItem::new_string("你好,我是张小白".to_string());
1502        write_to_clipboard(item.clone());
1503        assert_eq!(read_from_clipboard(), Some(item));
1504
1505        let item = ClipboardItem::new_string("12345".to_string());
1506        write_to_clipboard(item.clone());
1507        assert_eq!(read_from_clipboard(), Some(item));
1508
1509        let item = ClipboardItem::new_string_with_json_metadata("abcdef".to_string(), vec![3, 4]);
1510        write_to_clipboard(item.clone());
1511        assert_eq!(read_from_clipboard(), Some(item));
1512    }
1513}
1514
Served at tenant.openagents/omega Member data and write actions are omitted.