Skip to repository content2012 lines · 68.6 KB · rust
tenant.openagents/omega
No repository description is available.
OpenAgents Git authority 2026-07-28T05:01:30.837Z Public web read
NIP-34 coordinate
30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omegaMaintainersHidden in public view
References2 branches · 1 tag
Read-only clone
git clone https://openagents.com/git/tenant.openagents/omega.gitBrowse files
window.rs
1use anyhow::{Context as _, anyhow};
2use x11rb::connection::RequestConnection;
3
4use crate::linux::X11ClientStatePtr;
5use gpui::{
6 AnyWindowHandle, Bounds, Decorations, DevicePixels, ForegroundExecutor, GpuSpecs, Modifiers,
7 Pixels, PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow,
8 Point, PromptButton, PromptLevel, RequestFrameOptions, ResizeEdge, ScaledPixels, Scene, Size,
9 Tiling, WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowControlArea,
10 WindowDecorations, WindowKind, WindowParams, popup::PopupNotSupportedError, px,
11};
12use gpui_wgpu::{CompositorGpuHint, WgpuRenderer, WgpuSurfaceConfig};
13
14use collections::FxHashSet;
15use gpui_util::{ResultExt, maybe};
16use raw_window_handle as rwh;
17use x11rb::{
18 connection::Connection,
19 cookie::{Cookie, VoidCookie},
20 errors::ConnectionError,
21 properties::{WmHints, WmSizeHints},
22 protocol::{
23 sync,
24 xinput::{self, ConnectionExt as _},
25 xproto::{self, ClientMessageEvent, ConnectionExt, TranslateCoordinatesReply},
26 },
27 wrapper::ConnectionExt as _,
28 xcb_ffi::XCBConnection,
29};
30
31use std::{
32 cell::RefCell, ffi::c_void, fmt::Display, num::NonZeroU32, ptr::NonNull, rc::Rc, sync::Arc,
33};
34
35use super::{X11Display, XINPUT_ALL_DEVICE_GROUPS, XINPUT_ALL_DEVICES};
36
37x11rb::atom_manager! {
38 pub XcbAtoms: AtomsCookie {
39 XA_ATOM,
40 XdndAware,
41 XdndStatus,
42 XdndEnter,
43 XdndLeave,
44 XdndPosition,
45 XdndSelection,
46 XdndDrop,
47 XdndFinished,
48 XdndTypeList,
49 XdndActionCopy,
50 TextUriList: b"text/uri-list",
51 UTF8_STRING,
52 TEXT,
53 STRING,
54 TEXT_PLAIN_UTF8: b"text/plain;charset=utf-8",
55 TEXT_PLAIN: b"text/plain",
56 XDND_DATA,
57 WM_PROTOCOLS,
58 WM_DELETE_WINDOW,
59 WM_CHANGE_STATE,
60 WM_TRANSIENT_FOR,
61 _NET_WM_PID,
62 _NET_WM_NAME,
63 _NET_WM_ICON,
64 _NET_WM_STATE,
65 _NET_WM_STATE_MAXIMIZED_VERT,
66 _NET_WM_STATE_MAXIMIZED_HORZ,
67 _NET_WM_STATE_FULLSCREEN,
68 _NET_WM_STATE_HIDDEN,
69 _NET_WM_STATE_FOCUSED,
70 _NET_ACTIVE_WINDOW,
71 _NET_WM_SYNC_REQUEST,
72 _NET_WM_SYNC_REQUEST_COUNTER,
73 _NET_WM_BYPASS_COMPOSITOR,
74 _NET_WM_MOVERESIZE,
75 _NET_WM_WINDOW_TYPE,
76 _NET_WM_WINDOW_TYPE_NOTIFICATION,
77 _NET_WM_WINDOW_TYPE_DIALOG,
78 _NET_WM_STATE_MODAL,
79 _NET_WM_SYNC,
80 _NET_SUPPORTED,
81 _MOTIF_WM_HINTS,
82 _GTK_SHOW_WINDOW_MENU,
83 _GTK_FRAME_EXTENTS,
84 _GTK_EDGE_CONSTRAINTS,
85 _NET_CLIENT_LIST_STACKING,
86 }
87}
88
89fn query_render_extent(
90 xcb: &Rc<XCBConnection>,
91 x_window: xproto::Window,
92) -> anyhow::Result<Size<DevicePixels>> {
93 let reply = get_reply(|| "X11 GetGeometry failed.", xcb.get_geometry(x_window))?;
94 Ok(Size {
95 width: DevicePixels(reply.width as i32),
96 height: DevicePixels(reply.height as i32),
97 })
98}
99
100fn resize_edge_to_moveresize(edge: ResizeEdge) -> u32 {
101 match edge {
102 ResizeEdge::TopLeft => 0,
103 ResizeEdge::Top => 1,
104 ResizeEdge::TopRight => 2,
105 ResizeEdge::Right => 3,
106 ResizeEdge::BottomRight => 4,
107 ResizeEdge::Bottom => 5,
108 ResizeEdge::BottomLeft => 6,
109 ResizeEdge::Left => 7,
110 }
111}
112
113#[derive(Debug)]
114struct EdgeConstraints {
115 top_tiled: bool,
116 #[allow(dead_code)]
117 top_resizable: bool,
118
119 right_tiled: bool,
120 #[allow(dead_code)]
121 right_resizable: bool,
122
123 bottom_tiled: bool,
124 #[allow(dead_code)]
125 bottom_resizable: bool,
126
127 left_tiled: bool,
128 #[allow(dead_code)]
129 left_resizable: bool,
130}
131
132impl EdgeConstraints {
133 fn from_atom(atom: u32) -> Self {
134 EdgeConstraints {
135 top_tiled: (atom & (1 << 0)) != 0,
136 top_resizable: (atom & (1 << 1)) != 0,
137 right_tiled: (atom & (1 << 2)) != 0,
138 right_resizable: (atom & (1 << 3)) != 0,
139 bottom_tiled: (atom & (1 << 4)) != 0,
140 bottom_resizable: (atom & (1 << 5)) != 0,
141 left_tiled: (atom & (1 << 6)) != 0,
142 left_resizable: (atom & (1 << 7)) != 0,
143 }
144 }
145
146 fn to_tiling(&self) -> Tiling {
147 Tiling {
148 top: self.top_tiled,
149 right: self.right_tiled,
150 bottom: self.bottom_tiled,
151 left: self.left_tiled,
152 }
153 }
154}
155
156#[derive(Copy, Clone, Debug)]
157struct Visual {
158 id: xproto::Visualid,
159 colormap: u32,
160 depth: u8,
161}
162
163struct VisualSet {
164 inherit: Visual,
165 opaque: Option<Visual>,
166 transparent: Option<Visual>,
167 root: u32,
168 black_pixel: u32,
169}
170
171fn find_visuals(xcb: &XCBConnection, screen_index: usize) -> VisualSet {
172 let screen = &xcb.setup().roots[screen_index];
173 let mut set = VisualSet {
174 inherit: Visual {
175 id: screen.root_visual,
176 colormap: screen.default_colormap,
177 depth: screen.root_depth,
178 },
179 opaque: None,
180 transparent: None,
181 root: screen.root,
182 black_pixel: screen.black_pixel,
183 };
184
185 for depth_info in screen.allowed_depths.iter() {
186 for visual_type in depth_info.visuals.iter() {
187 let visual = Visual {
188 id: visual_type.visual_id,
189 colormap: 0,
190 depth: depth_info.depth,
191 };
192 log::debug!(
193 "Visual id: {}, class: {:?}, depth: {}, bits_per_value: {}, masks: 0x{:x} 0x{:x} 0x{:x}",
194 visual_type.visual_id,
195 visual_type.class,
196 depth_info.depth,
197 visual_type.bits_per_rgb_value,
198 visual_type.red_mask,
199 visual_type.green_mask,
200 visual_type.blue_mask,
201 );
202
203 if (
204 visual_type.red_mask,
205 visual_type.green_mask,
206 visual_type.blue_mask,
207 ) != (0xFF0000, 0xFF00, 0xFF)
208 {
209 continue;
210 }
211 let color_mask = visual_type.red_mask | visual_type.green_mask | visual_type.blue_mask;
212 let alpha_mask = color_mask as usize ^ ((1usize << depth_info.depth) - 1);
213
214 if alpha_mask == 0 {
215 if set.opaque.is_none() {
216 set.opaque = Some(visual);
217 }
218 } else {
219 if set.transparent.is_none() {
220 set.transparent = Some(visual);
221 }
222 }
223 }
224 }
225
226 set
227}
228
229#[derive(Debug, Clone, Copy)]
230struct RawWindow {
231 connection: *mut c_void,
232 screen_id: usize,
233 window_id: u32,
234 visual_id: u32,
235}
236
237// Safety: The raw pointers in RawWindow point to X11 connection
238// which is valid for the window's lifetime. These are used only for
239// passing to wgpu which needs Send+Sync for surface creation.
240unsafe impl Send for RawWindow {}
241unsafe impl Sync for RawWindow {}
242
243#[derive(Default)]
244pub struct Callbacks {
245 request_frame: Option<Box<dyn FnMut(RequestFrameOptions)>>,
246 input: Option<Box<dyn FnMut(PlatformInput) -> gpui::DispatchEventResult>>,
247 active_status_change: Option<Box<dyn FnMut(bool)>>,
248 hovered_status_change: Option<Box<dyn FnMut(bool)>>,
249 resize: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
250 moved: Option<Box<dyn FnMut()>>,
251 should_close: Option<Box<dyn FnMut() -> bool>>,
252 close: Option<Box<dyn FnOnce()>>,
253 appearance_changed: Option<Box<dyn FnMut()>>,
254 button_layout_changed: Option<Box<dyn FnMut()>>,
255}
256
257pub struct X11WindowState {
258 pub destroyed: bool,
259 parent: Option<X11WindowStatePtr>,
260 children: FxHashSet<xproto::Window>,
261 client: X11ClientStatePtr,
262 executor: ForegroundExecutor,
263 atoms: XcbAtoms,
264 x_root_window: xproto::Window,
265 x_screen_index: usize,
266 visual_id: u32,
267 pub(crate) counter_id: sync::Counter,
268 pub(crate) last_sync_counter: Option<sync::Int64>,
269 bounds: Bounds<Pixels>,
270 scale_factor: f32,
271 renderer: WgpuRenderer,
272 display: Rc<dyn PlatformDisplay>,
273 input_handler: Option<PlatformInputHandler>,
274 appearance: WindowAppearance,
275 background_appearance: WindowBackgroundAppearance,
276 maximized_vertical: bool,
277 maximized_horizontal: bool,
278 hidden: bool,
279 active: bool,
280 hovered: bool,
281 pub(crate) force_render_after_recovery: bool,
282 fullscreen: bool,
283 client_side_decorations_supported: bool,
284 decorations: WindowDecorations,
285 edge_constraints: Option<EdgeConstraints>,
286 pub handle: AnyWindowHandle,
287 last_insets: [u32; 4],
288 accesskit_adapter: Option<accesskit_unix::Adapter>,
289}
290
291impl X11WindowState {
292 fn is_transparent(&self) -> bool {
293 self.background_appearance != WindowBackgroundAppearance::Opaque
294 }
295}
296
297#[derive(Clone)]
298pub(crate) struct X11WindowStatePtr {
299 pub state: Rc<RefCell<X11WindowState>>,
300 pub(crate) callbacks: Rc<RefCell<Callbacks>>,
301 xcb: Rc<XCBConnection>,
302 pub(crate) x_window: xproto::Window,
303}
304
305impl rwh::HasWindowHandle for RawWindow {
306 fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
307 let Some(non_zero) = NonZeroU32::new(self.window_id) else {
308 log::error!("RawWindow.window_id zero when getting window handle.");
309 return Err(rwh::HandleError::Unavailable);
310 };
311 let mut handle = rwh::XcbWindowHandle::new(non_zero);
312 handle.visual_id = NonZeroU32::new(self.visual_id);
313 Ok(unsafe { rwh::WindowHandle::borrow_raw(handle.into()) })
314 }
315}
316impl rwh::HasDisplayHandle for RawWindow {
317 fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
318 let Some(non_zero) = NonNull::new(self.connection) else {
319 log::error!("Null RawWindow.connection when getting display handle.");
320 return Err(rwh::HandleError::Unavailable);
321 };
322 let handle = rwh::XcbDisplayHandle::new(Some(non_zero), self.screen_id as i32);
323 Ok(unsafe { rwh::DisplayHandle::borrow_raw(handle.into()) })
324 }
325}
326
327impl rwh::HasWindowHandle for X11Window {
328 fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
329 let Some(non_zero) = NonZeroU32::new(self.0.x_window) else {
330 return Err(rwh::HandleError::Unavailable);
331 };
332 let handle = rwh::XcbWindowHandle::new(non_zero);
333 Ok(unsafe { rwh::WindowHandle::borrow_raw(handle.into()) })
334 }
335}
336
337impl rwh::HasDisplayHandle for X11Window {
338 fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
339 let connection =
340 as_raw_xcb_connection::AsRawXcbConnection::as_raw_xcb_connection(&*self.0.xcb)
341 as *mut _;
342 let Some(non_zero) = NonNull::new(connection) else {
343 return Err(rwh::HandleError::Unavailable);
344 };
345 let screen_id = {
346 let state = self.0.state.borrow();
347 u64::from(state.display.id()) as i32
348 };
349 let handle = rwh::XcbDisplayHandle::new(Some(non_zero), screen_id);
350 Ok(unsafe { rwh::DisplayHandle::borrow_raw(handle.into()) })
351 }
352}
353
354pub(crate) fn xcb_flush(xcb: &XCBConnection) {
355 xcb.flush()
356 .map_err(handle_connection_error)
357 .context("X11 flush failed")
358 .log_err();
359}
360
361pub(crate) fn check_reply<E, F, C>(
362 failure_context: F,
363 result: Result<VoidCookie<'_, C>, ConnectionError>,
364) -> anyhow::Result<()>
365where
366 E: Display + Send + Sync + 'static,
367 F: FnOnce() -> E,
368 C: RequestConnection,
369{
370 result
371 .map_err(handle_connection_error)
372 .and_then(|response| response.check().map_err(|reply_error| anyhow!(reply_error)))
373 .with_context(failure_context)
374}
375
376pub(crate) fn get_reply<E, F, C, O>(
377 failure_context: F,
378 result: Result<Cookie<'_, C, O>, ConnectionError>,
379) -> anyhow::Result<O>
380where
381 E: Display + Send + Sync + 'static,
382 F: FnOnce() -> E,
383 C: RequestConnection,
384 O: x11rb::x11_utils::TryParse,
385{
386 result
387 .map_err(handle_connection_error)
388 .and_then(|response| response.reply().map_err(|reply_error| anyhow!(reply_error)))
389 .with_context(failure_context)
390}
391
392/// Convert X11 connection errors to `anyhow::Error` and panic for unrecoverable errors.
393pub(crate) fn handle_connection_error(err: ConnectionError) -> anyhow::Error {
394 match err {
395 ConnectionError::UnknownError => anyhow!("X11 connection: Unknown error"),
396 ConnectionError::UnsupportedExtension => anyhow!("X11 connection: Unsupported extension"),
397 ConnectionError::MaximumRequestLengthExceeded => {
398 anyhow!("X11 connection: Maximum request length exceeded")
399 }
400 ConnectionError::FdPassingFailed => {
401 panic!("X11 connection: File descriptor passing failed")
402 }
403 ConnectionError::ParseError(parse_error) => {
404 anyhow!(parse_error).context("Parse error in X11 response")
405 }
406 ConnectionError::InsufficientMemory => panic!("X11 connection: Insufficient memory"),
407 ConnectionError::IoError(err) => anyhow!(err).context("X11 connection: IOError"),
408 _ => anyhow!(err),
409 }
410}
411
412impl X11WindowState {
413 pub fn new(
414 handle: AnyWindowHandle,
415 client: X11ClientStatePtr,
416 executor: ForegroundExecutor,
417 gpu_context: gpui_wgpu::GpuContext,
418 compositor_gpu: Option<CompositorGpuHint>,
419 params: WindowParams,
420 xcb: &Rc<XCBConnection>,
421 client_side_decorations_supported: bool,
422 x_main_screen_index: usize,
423 x_window: xproto::Window,
424 atoms: &XcbAtoms,
425 scale_factor: f32,
426 appearance: WindowAppearance,
427 parent_window: Option<X11WindowStatePtr>,
428 supports_xinput_gestures: bool,
429 is_bgr: bool,
430 ) -> anyhow::Result<Self> {
431 // Native popups are not implemented on X11 yet. Rejecting lets callers fall back to
432 // gpui's in-window popovers.
433 if let WindowKind::AnchoredPopup(_) = params.kind {
434 return Err(PopupNotSupportedError.into());
435 }
436
437 let x_screen_index = params
438 .display_id
439 .map_or(x_main_screen_index, |did| u64::from(did) as usize);
440
441 let visual_set = find_visuals(xcb, x_screen_index);
442
443 let visual = match visual_set.transparent {
444 Some(visual) => visual,
445 None => {
446 log::warn!("Unable to find a transparent visual",);
447 visual_set.inherit
448 }
449 };
450 log::info!("Using {:?}", visual);
451
452 let colormap = if visual.colormap != 0 {
453 visual.colormap
454 } else {
455 let id = xcb.generate_id()?;
456 log::info!("Creating colormap {}", id);
457 check_reply(
458 || format!("X11 CreateColormap failed. id: {}", id),
459 xcb.create_colormap(xproto::ColormapAlloc::NONE, id, visual_set.root, visual.id),
460 )?;
461 id
462 };
463
464 let win_aux = xproto::CreateWindowAux::new()
465 // https://stackoverflow.com/questions/43218127/x11-xlib-xcb-creating-a-window-requires-border-pixel-if-specifying-colormap-wh
466 .border_pixel(visual_set.black_pixel)
467 .colormap(colormap)
468 .override_redirect((params.kind == WindowKind::PopUp) as u32)
469 .event_mask(
470 xproto::EventMask::EXPOSURE
471 | xproto::EventMask::STRUCTURE_NOTIFY
472 | xproto::EventMask::FOCUS_CHANGE
473 | xproto::EventMask::KEY_PRESS
474 | xproto::EventMask::KEY_RELEASE
475 | xproto::EventMask::PROPERTY_CHANGE
476 | xproto::EventMask::VISIBILITY_CHANGE,
477 );
478
479 let mut bounds = params.bounds.to_device_pixels(scale_factor);
480 if bounds.size.width.0 == 0 || bounds.size.height.0 == 0 {
481 log::warn!(
482 "Window bounds contain a zero value. height={}, width={}. Falling back to defaults.",
483 bounds.size.height.0,
484 bounds.size.width.0
485 );
486 bounds.size.width = 800.into();
487 bounds.size.height = 600.into();
488 }
489
490 check_reply(
491 || {
492 format!(
493 "X11 CreateWindow failed. depth: {}, x_window: {}, visual_set.root: {}, bounds.origin.x.0: {}, bounds.origin.y.0: {}, bounds.size.width.0: {}, bounds.size.height.0: {}",
494 visual.depth,
495 x_window,
496 visual_set.root,
497 bounds.origin.x.0 + 2,
498 bounds.origin.y.0,
499 bounds.size.width.0,
500 bounds.size.height.0
501 )
502 },
503 xcb.create_window(
504 visual.depth,
505 x_window,
506 visual_set.root,
507 (bounds.origin.x.0 + 2) as i16,
508 bounds.origin.y.0 as i16,
509 bounds.size.width.0 as u16,
510 bounds.size.height.0 as u16,
511 0,
512 xproto::WindowClass::INPUT_OUTPUT,
513 visual.id,
514 &win_aux,
515 ),
516 )?;
517
518 // Collect errors during setup, so that window can be destroyed on failure.
519 let setup_result = maybe!({
520 let pid = std::process::id();
521 check_reply(
522 || "X11 ChangeProperty for _NET_WM_PID failed.",
523 xcb.change_property32(
524 xproto::PropMode::REPLACE,
525 x_window,
526 atoms._NET_WM_PID,
527 xproto::AtomEnum::CARDINAL,
528 &[pid],
529 ),
530 )?;
531
532 let reply = get_reply(|| "X11 GetGeometry failed.", xcb.get_geometry(x_window))?;
533 if reply.x == 0 && reply.y == 0 {
534 bounds.origin.x.0 += 2;
535 // Work around a bug where our rendered content appears
536 // outside the window bounds when opened at the default position
537 // (14px, 49px on X + Gnome + Ubuntu 22).
538 let x = bounds.origin.x.0;
539 let y = bounds.origin.y.0;
540 check_reply(
541 || format!("X11 ConfigureWindow failed. x: {}, y: {}", x, y),
542 xcb.configure_window(x_window, &xproto::ConfigureWindowAux::new().x(x).y(y)),
543 )?;
544 }
545 if let Some(titlebar) = params.titlebar
546 && let Some(title) = titlebar.title
547 {
548 check_reply(
549 || "X11 ChangeProperty8 on WM_NAME failed.",
550 xcb.change_property8(
551 xproto::PropMode::REPLACE,
552 x_window,
553 xproto::AtomEnum::WM_NAME,
554 xproto::AtomEnum::STRING,
555 title.as_bytes(),
556 ),
557 )?;
558 check_reply(
559 || "X11 ChangeProperty8 on _NET_WM_NAME failed.",
560 xcb.change_property8(
561 xproto::PropMode::REPLACE,
562 x_window,
563 atoms._NET_WM_NAME,
564 atoms.UTF8_STRING,
565 title.as_bytes(),
566 ),
567 )?;
568 }
569
570 if params.kind == WindowKind::PopUp {
571 check_reply(
572 || "X11 ChangeProperty32 setting window type for pop-up failed.",
573 xcb.change_property32(
574 xproto::PropMode::REPLACE,
575 x_window,
576 atoms._NET_WM_WINDOW_TYPE,
577 xproto::AtomEnum::ATOM,
578 &[atoms._NET_WM_WINDOW_TYPE_NOTIFICATION],
579 ),
580 )?;
581 }
582
583 if params.kind == WindowKind::Floating || params.kind == WindowKind::Dialog {
584 if let Some(parent_window) = parent_window.as_ref().map(|w| w.x_window) {
585 // WM_TRANSIENT_FOR hint indicating the main application window. For floating windows, we set
586 // a parent window (WM_TRANSIENT_FOR) such that the window manager knows where to
587 // place the floating window in relation to the main window.
588 // https://specifications.freedesktop.org/wm-spec/1.4/ar01s05.html
589 check_reply(
590 || "X11 ChangeProperty32 setting WM_TRANSIENT_FOR for floating window failed.",
591 xcb.change_property32(
592 xproto::PropMode::REPLACE,
593 x_window,
594 atoms.WM_TRANSIENT_FOR,
595 xproto::AtomEnum::WINDOW,
596 &[parent_window],
597 ),
598 )?;
599 }
600 }
601
602 let parent = if params.kind == WindowKind::Dialog
603 && let Some(parent) = parent_window
604 {
605 parent.add_child(x_window);
606
607 Some(parent)
608 } else {
609 None
610 };
611
612 if params.kind == WindowKind::Dialog {
613 // _NET_WM_WINDOW_TYPE_DIALOG indicates that this is a dialog (floating) window
614 // https://specifications.freedesktop.org/wm-spec/1.4/ar01s05.html
615 check_reply(
616 || "X11 ChangeProperty32 setting window type for dialog window failed.",
617 xcb.change_property32(
618 xproto::PropMode::REPLACE,
619 x_window,
620 atoms._NET_WM_WINDOW_TYPE,
621 xproto::AtomEnum::ATOM,
622 &[atoms._NET_WM_WINDOW_TYPE_DIALOG],
623 ),
624 )?;
625
626 // We set the modal state for dialog windows, so that the window manager
627 // can handle it appropriately (e.g., prevent interaction with the parent window
628 // while the dialog is open).
629 check_reply(
630 || "X11 ChangeProperty32 setting modal state for dialog window failed.",
631 xcb.change_property32(
632 xproto::PropMode::REPLACE,
633 x_window,
634 atoms._NET_WM_STATE,
635 xproto::AtomEnum::ATOM,
636 &[atoms._NET_WM_STATE_MODAL],
637 ),
638 )?;
639 }
640
641 check_reply(
642 || "X11 ChangeProperty32 setting protocols failed.",
643 xcb.change_property32(
644 xproto::PropMode::REPLACE,
645 x_window,
646 atoms.WM_PROTOCOLS,
647 xproto::AtomEnum::ATOM,
648 &[atoms.WM_DELETE_WINDOW, atoms._NET_WM_SYNC_REQUEST],
649 ),
650 )?;
651
652 get_reply(
653 || "X11 sync protocol initialize failed.",
654 sync::initialize(xcb, 3, 1),
655 )?;
656 let sync_request_counter = xcb.generate_id()?;
657 check_reply(
658 || "X11 sync CreateCounter failed.",
659 sync::create_counter(xcb, sync_request_counter, sync::Int64 { lo: 0, hi: 0 }),
660 )?;
661
662 check_reply(
663 || "X11 ChangeProperty32 setting sync request counter failed.",
664 xcb.change_property32(
665 xproto::PropMode::REPLACE,
666 x_window,
667 atoms._NET_WM_SYNC_REQUEST_COUNTER,
668 xproto::AtomEnum::CARDINAL,
669 &[sync_request_counter],
670 ),
671 )?;
672
673 let mut xi_event_mask = xinput::XIEventMask::MOTION
674 | xinput::XIEventMask::BUTTON_PRESS
675 | xinput::XIEventMask::BUTTON_RELEASE
676 | xinput::XIEventMask::ENTER
677 | xinput::XIEventMask::LEAVE;
678 if supports_xinput_gestures {
679 // x11rb 0.13 doesn't define XIEventMask constants for gesture
680 // events, so we construct them from the event opcodes (each
681 // XInput event type N maps to mask bit N).
682 xi_event_mask |=
683 xinput::XIEventMask::from(1u32 << xinput::GESTURE_PINCH_BEGIN_EVENT)
684 | xinput::XIEventMask::from(1u32 << xinput::GESTURE_PINCH_UPDATE_EVENT)
685 | xinput::XIEventMask::from(1u32 << xinput::GESTURE_PINCH_END_EVENT);
686 }
687 check_reply(
688 || "X11 XiSelectEvents failed.",
689 xcb.xinput_xi_select_events(
690 x_window,
691 &[xinput::EventMask {
692 deviceid: XINPUT_ALL_DEVICE_GROUPS,
693 mask: vec![xi_event_mask],
694 }],
695 ),
696 )?;
697
698 check_reply(
699 || "X11 XiSelectEvents for device changes failed.",
700 xcb.xinput_xi_select_events(
701 x_window,
702 &[xinput::EventMask {
703 deviceid: XINPUT_ALL_DEVICES,
704 mask: vec![
705 xinput::XIEventMask::HIERARCHY | xinput::XIEventMask::DEVICE_CHANGED,
706 ],
707 }],
708 ),
709 )?;
710
711 xcb_flush(xcb);
712
713 let mut renderer = {
714 let raw_window = RawWindow {
715 connection: as_raw_xcb_connection::AsRawXcbConnection::as_raw_xcb_connection(
716 xcb,
717 ) as *mut _,
718 screen_id: x_screen_index,
719 window_id: x_window,
720 visual_id: visual.id,
721 };
722 let config = WgpuSurfaceConfig {
723 // Note: this has to be done after the GPU init, or otherwise
724 // the sizes are immediately invalidated.
725 size: query_render_extent(xcb, x_window)?,
726 // We set it to transparent by default, even if we have client-side
727 // decorations, since those seem to work on X11 even without `true` here.
728 // If the window appearance changes, then the renderer will get updated
729 // too
730 transparent: false,
731 preferred_present_mode: None,
732 };
733 WgpuRenderer::new(gpu_context, &raw_window, config, compositor_gpu)?
734 };
735
736 renderer.set_subpixel_layout(is_bgr);
737
738 // Set max window size hints based on the GPU's maximum texture dimension.
739 // This prevents the window from being resized larger than what the GPU can render.
740 let max_texture_size = renderer.max_texture_size();
741 let mut size_hints = WmSizeHints::new();
742 if let Some(size) = params.window_min_size {
743 size_hints.min_size =
744 Some((f32::from(size.width) as i32, f32::from(size.height) as i32));
745 }
746 size_hints.max_size = Some((max_texture_size as i32, max_texture_size as i32));
747 check_reply(
748 || {
749 format!(
750 "X11 change of WM_SIZE_HINTS failed. max_size: {:?}",
751 max_texture_size
752 )
753 },
754 size_hints.set_normal_hints(xcb, x_window),
755 )?;
756
757 if let Some(image) = params.icon {
758 // https://specifications.freedesktop.org/wm-spec/1.4/ar01s05.html#id-1.6.13
759 let property_size = 2 + (image.width() * image.height()) as usize;
760 let mut property_data: Vec<u32> = Vec::with_capacity(property_size);
761 property_data.push(image.width());
762 property_data.push(image.height());
763 property_data.extend(image.pixels().map(|px| {
764 let [r, g, b, a]: [u8; 4] = px.0;
765 u32::from_le_bytes([b, g, r, a])
766 }));
767
768 check_reply(
769 || "X11 ChangeProperty32 for _NET_ICON_NAME failed.",
770 xcb.change_property32(
771 xproto::PropMode::REPLACE,
772 x_window,
773 atoms._NET_WM_ICON,
774 xproto::AtomEnum::CARDINAL,
775 &property_data,
776 ),
777 )?;
778 }
779
780 let display = Rc::new(X11Display::new(xcb, scale_factor, x_screen_index)?);
781
782 Ok(Self {
783 parent,
784 children: FxHashSet::default(),
785 client,
786 executor,
787 display,
788 x_root_window: visual_set.root,
789 x_screen_index,
790 visual_id: visual.id,
791 bounds: bounds.to_pixels(scale_factor),
792 scale_factor,
793 renderer,
794 atoms: *atoms,
795 input_handler: None,
796 active: false,
797 hovered: false,
798 force_render_after_recovery: false,
799 fullscreen: false,
800 maximized_vertical: false,
801 maximized_horizontal: false,
802 hidden: false,
803 appearance,
804 handle,
805 background_appearance: WindowBackgroundAppearance::Opaque,
806 destroyed: false,
807 client_side_decorations_supported,
808 decorations: WindowDecorations::Server,
809 last_insets: [0, 0, 0, 0],
810 edge_constraints: None,
811 accesskit_adapter: None,
812 counter_id: sync_request_counter,
813 last_sync_counter: None,
814 })
815 });
816
817 if setup_result.is_err() {
818 check_reply(
819 || "X11 DestroyWindow failed while cleaning it up after setup failure.",
820 xcb.destroy_window(x_window),
821 )?;
822 xcb_flush(xcb);
823 }
824
825 setup_result
826 }
827
828 fn content_size(&self) -> Size<Pixels> {
829 self.bounds.size
830 }
831}
832
833pub(crate) struct X11Window(pub X11WindowStatePtr);
834
835impl Drop for X11Window {
836 fn drop(&mut self) {
837 let mut state = self.0.state.borrow_mut();
838
839 if let Some(parent) = state.parent.as_ref() {
840 parent.state.borrow_mut().children.remove(&self.0.x_window);
841 }
842
843 state.renderer.destroy();
844
845 let destroy_x_window = maybe!({
846 check_reply(
847 || "X11 DestroyWindow failure.",
848 self.0.xcb.destroy_window(self.0.x_window),
849 )?;
850 xcb_flush(&self.0.xcb);
851
852 anyhow::Ok(())
853 })
854 .log_err();
855
856 if destroy_x_window.is_some() {
857 state.destroyed = true;
858
859 let this_ptr = self.0.clone();
860 let client_ptr = state.client.clone();
861 state
862 .executor
863 .spawn(async move {
864 this_ptr.close();
865 client_ptr.drop_window(this_ptr.x_window);
866 })
867 .detach();
868 }
869
870 drop(state);
871 }
872}
873
874enum WmHintPropertyState {
875 // Remove = 0,
876 // Add = 1,
877 Toggle = 2,
878}
879
880impl X11Window {
881 pub fn new(
882 handle: AnyWindowHandle,
883 client: X11ClientStatePtr,
884 executor: ForegroundExecutor,
885 gpu_context: gpui_wgpu::GpuContext,
886 compositor_gpu: Option<CompositorGpuHint>,
887 params: WindowParams,
888 xcb: &Rc<XCBConnection>,
889 client_side_decorations_supported: bool,
890 x_main_screen_index: usize,
891 x_window: xproto::Window,
892 atoms: &XcbAtoms,
893 scale_factor: f32,
894 appearance: WindowAppearance,
895 parent_window: Option<X11WindowStatePtr>,
896 supports_xinput_gestures: bool,
897 is_bgr: bool,
898 ) -> anyhow::Result<Self> {
899 let ptr = X11WindowStatePtr {
900 state: Rc::new(RefCell::new(X11WindowState::new(
901 handle,
902 client,
903 executor,
904 gpu_context,
905 compositor_gpu,
906 params,
907 xcb,
908 client_side_decorations_supported,
909 x_main_screen_index,
910 x_window,
911 atoms,
912 scale_factor,
913 appearance,
914 parent_window,
915 supports_xinput_gestures,
916 is_bgr,
917 )?)),
918 callbacks: Rc::new(RefCell::new(Callbacks::default())),
919 xcb: xcb.clone(),
920 x_window,
921 };
922
923 let state = ptr.state.borrow_mut();
924 ptr.set_wm_properties(state)?;
925
926 Ok(Self(ptr))
927 }
928
929 fn set_wm_hints<C: Display + Send + Sync + 'static, F: FnOnce() -> C>(
930 &self,
931 failure_context: F,
932 wm_hint_property_state: WmHintPropertyState,
933 prop1: u32,
934 prop2: u32,
935 ) -> anyhow::Result<()> {
936 let state = self.0.state.borrow();
937 let message = ClientMessageEvent::new(
938 32,
939 self.0.x_window,
940 state.atoms._NET_WM_STATE,
941 [wm_hint_property_state as u32, prop1, prop2, 1, 0],
942 );
943 check_reply(
944 failure_context,
945 self.0.xcb.send_event(
946 false,
947 state.x_root_window,
948 xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
949 message,
950 ),
951 )?;
952 xcb_flush(&self.0.xcb);
953 Ok(())
954 }
955
956 fn get_root_position(
957 &self,
958 position: Point<Pixels>,
959 ) -> anyhow::Result<TranslateCoordinatesReply> {
960 let state = self.0.state.borrow();
961 get_reply(
962 || "X11 TranslateCoordinates failed.",
963 self.0.xcb.translate_coordinates(
964 self.0.x_window,
965 state.x_root_window,
966 (f32::from(position.x) * state.scale_factor) as i16,
967 (f32::from(position.y) * state.scale_factor) as i16,
968 ),
969 )
970 }
971
972 fn send_moveresize(&self, flag: u32) -> anyhow::Result<()> {
973 let state = self.0.state.borrow();
974
975 check_reply(
976 || "X11 UngrabPointer before move/resize of window failed.",
977 self.0.xcb.ungrab_pointer(x11rb::CURRENT_TIME),
978 )?;
979
980 let pointer = get_reply(
981 || "X11 QueryPointer before move/resize of window failed.",
982 self.0.xcb.query_pointer(self.0.x_window),
983 )?;
984 let message = ClientMessageEvent::new(
985 32,
986 self.0.x_window,
987 state.atoms._NET_WM_MOVERESIZE,
988 [
989 pointer.root_x as u32,
990 pointer.root_y as u32,
991 flag,
992 0, // Left mouse button
993 0,
994 ],
995 );
996 check_reply(
997 || "X11 SendEvent to move/resize window failed.",
998 self.0.xcb.send_event(
999 false,
1000 state.x_root_window,
1001 xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
1002 message,
1003 ),
1004 )?;
1005
1006 xcb_flush(&self.0.xcb);
1007 Ok(())
1008 }
1009}
1010
1011impl X11WindowStatePtr {
1012 pub fn should_close(&self) -> bool {
1013 let mut cb = self.callbacks.borrow_mut();
1014 if let Some(mut should_close) = cb.should_close.take() {
1015 let result = (should_close)();
1016 cb.should_close = Some(should_close);
1017 result
1018 } else {
1019 true
1020 }
1021 }
1022
1023 pub fn property_notify(&self, event: xproto::PropertyNotifyEvent) -> anyhow::Result<()> {
1024 let state = self.state.borrow_mut();
1025 if event.atom == state.atoms._NET_WM_STATE {
1026 self.set_wm_properties(state)?;
1027 } else if event.atom == state.atoms._GTK_EDGE_CONSTRAINTS {
1028 self.set_edge_constraints(state)?;
1029 }
1030 Ok(())
1031 }
1032
1033 fn set_edge_constraints(
1034 &self,
1035 mut state: std::cell::RefMut<X11WindowState>,
1036 ) -> anyhow::Result<()> {
1037 let reply = get_reply(
1038 || "X11 GetProperty for _GTK_EDGE_CONSTRAINTS failed.",
1039 self.xcb.get_property(
1040 false,
1041 self.x_window,
1042 state.atoms._GTK_EDGE_CONSTRAINTS,
1043 xproto::AtomEnum::CARDINAL,
1044 0,
1045 4,
1046 ),
1047 )?;
1048
1049 if reply.value_len != 0 {
1050 if let Ok(bytes) = reply.value[0..4].try_into() {
1051 let atom = u32::from_ne_bytes(bytes);
1052 let edge_constraints = EdgeConstraints::from_atom(atom);
1053 state.edge_constraints.replace(edge_constraints);
1054 } else {
1055 log::error!("Failed to parse GTK_EDGE_CONSTRAINTS");
1056 }
1057 }
1058
1059 Ok(())
1060 }
1061
1062 fn set_wm_properties(
1063 &self,
1064 mut state: std::cell::RefMut<X11WindowState>,
1065 ) -> anyhow::Result<()> {
1066 let reply = get_reply(
1067 || "X11 GetProperty for _NET_WM_STATE failed.",
1068 self.xcb.get_property(
1069 false,
1070 self.x_window,
1071 state.atoms._NET_WM_STATE,
1072 xproto::AtomEnum::ATOM,
1073 0,
1074 u32::MAX,
1075 ),
1076 )?;
1077
1078 let atoms = reply
1079 .value
1080 .chunks_exact(4)
1081 .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
1082
1083 state.active = false;
1084 state.fullscreen = false;
1085 state.maximized_vertical = false;
1086 state.maximized_horizontal = false;
1087 state.hidden = false;
1088
1089 for atom in atoms {
1090 if atom == state.atoms._NET_WM_STATE_FOCUSED {
1091 state.active = true;
1092 } else if atom == state.atoms._NET_WM_STATE_FULLSCREEN {
1093 state.fullscreen = true;
1094 } else if atom == state.atoms._NET_WM_STATE_MAXIMIZED_VERT {
1095 state.maximized_vertical = true;
1096 } else if atom == state.atoms._NET_WM_STATE_MAXIMIZED_HORZ {
1097 state.maximized_horizontal = true;
1098 } else if atom == state.atoms._NET_WM_STATE_HIDDEN {
1099 state.hidden = true;
1100 }
1101 }
1102
1103 Ok(())
1104 }
1105
1106 pub fn add_child(&self, child: xproto::Window) {
1107 let mut state = self.state.borrow_mut();
1108 state.children.insert(child);
1109 }
1110
1111 pub fn is_blocked(&self) -> bool {
1112 let state = self.state.borrow();
1113 !state.children.is_empty()
1114 }
1115
1116 pub fn close(&self) {
1117 let state = self.state.borrow();
1118 let client = state.client.clone();
1119 #[allow(clippy::mutable_key_type)]
1120 let children = state.children.clone();
1121 drop(state);
1122
1123 if let Some(client) = client.get_client() {
1124 for child in children {
1125 if let Some(child_window) = client.get_window(child) {
1126 child_window.close();
1127 }
1128 }
1129 }
1130
1131 let mut callbacks = self.callbacks.borrow_mut();
1132 if let Some(fun) = callbacks.close.take() {
1133 fun()
1134 }
1135 }
1136
1137 pub fn refresh(&self, request_frame_options: RequestFrameOptions) {
1138 let callback = self.callbacks.borrow_mut().request_frame.take();
1139 if let Some(mut fun) = callback {
1140 fun(request_frame_options);
1141 self.callbacks.borrow_mut().request_frame = Some(fun);
1142 }
1143 }
1144
1145 pub fn handle_input(&self, input: PlatformInput) {
1146 if self.is_blocked() {
1147 return;
1148 }
1149 let callback = self.callbacks.borrow_mut().input.take();
1150 if let Some(mut fun) = callback {
1151 let result = fun(input.clone());
1152 self.callbacks.borrow_mut().input = Some(fun);
1153 if !result.propagate {
1154 return;
1155 }
1156 }
1157 if let PlatformInput::KeyDown(event) = input {
1158 // only allow shift modifier when inserting text
1159 if event.keystroke.modifiers.is_subset_of(&Modifiers::shift()) {
1160 let mut state = self.state.borrow_mut();
1161 if let Some(mut input_handler) = state.input_handler.take() {
1162 if let Some(key_char) = &event.keystroke.key_char {
1163 drop(state);
1164 input_handler.replace_text_in_range(None, key_char);
1165 state = self.state.borrow_mut();
1166 }
1167 state.input_handler = Some(input_handler);
1168 }
1169 }
1170 }
1171 }
1172
1173 pub fn handle_ime_commit(&self, text: String) {
1174 if self.is_blocked() {
1175 return;
1176 }
1177 let mut state = self.state.borrow_mut();
1178 if let Some(mut input_handler) = state.input_handler.take() {
1179 drop(state);
1180 input_handler.replace_text_in_range(None, &text);
1181 let mut state = self.state.borrow_mut();
1182 state.input_handler = Some(input_handler);
1183 }
1184 }
1185
1186 pub fn handle_ime_preedit(&self, text: String) {
1187 if self.is_blocked() {
1188 return;
1189 }
1190 let mut state = self.state.borrow_mut();
1191 if let Some(mut input_handler) = state.input_handler.take() {
1192 drop(state);
1193 input_handler.replace_and_mark_text_in_range(None, &text, None);
1194 let mut state = self.state.borrow_mut();
1195 state.input_handler = Some(input_handler);
1196 }
1197 }
1198
1199 pub fn handle_ime_unmark(&self) {
1200 if self.is_blocked() {
1201 return;
1202 }
1203 let mut state = self.state.borrow_mut();
1204 if let Some(mut input_handler) = state.input_handler.take() {
1205 drop(state);
1206 input_handler.unmark_text();
1207 let mut state = self.state.borrow_mut();
1208 state.input_handler = Some(input_handler);
1209 }
1210 }
1211
1212 pub fn handle_ime_delete(&self) {
1213 if self.is_blocked() {
1214 return;
1215 }
1216 let mut state = self.state.borrow_mut();
1217 if let Some(mut input_handler) = state.input_handler.take() {
1218 drop(state);
1219 if let Some(marked) = input_handler.marked_text_range() {
1220 input_handler.replace_text_in_range(Some(marked), "");
1221 }
1222 let mut state = self.state.borrow_mut();
1223 state.input_handler = Some(input_handler);
1224 }
1225 }
1226
1227 pub fn get_ime_area(&self) -> Option<Bounds<ScaledPixels>> {
1228 let mut state = self.state.borrow_mut();
1229 let scale_factor = state.scale_factor;
1230 let mut bounds: Option<Bounds<Pixels>> = None;
1231 if let Some(mut input_handler) = state.input_handler.take() {
1232 drop(state);
1233 if let Some(selection) = input_handler.selected_text_range(true) {
1234 bounds = input_handler.bounds_for_range(selection.range);
1235 }
1236 let mut state = self.state.borrow_mut();
1237 state.input_handler = Some(input_handler);
1238 };
1239 bounds.map(|b| b.scale(scale_factor))
1240 }
1241
1242 pub fn set_bounds(&self, bounds: Bounds<i32>) -> anyhow::Result<()> {
1243 let (is_resize, content_size, scale_factor) = {
1244 let mut state = self.state.borrow_mut();
1245 let bounds = bounds.map(|f| px(f as f32 / state.scale_factor));
1246
1247 let is_resize = bounds.size.width != state.bounds.size.width
1248 || bounds.size.height != state.bounds.size.height;
1249
1250 // If it's a resize event (only width/height changed), we ignore `bounds.origin`
1251 // because it contains wrong values.
1252 if is_resize {
1253 state.bounds.size = bounds.size;
1254 } else {
1255 state.bounds = bounds;
1256 }
1257
1258 let gpu_size = query_render_extent(&self.xcb, self.x_window)?;
1259 state.renderer.update_drawable_size(gpu_size);
1260 let result = (is_resize, state.content_size(), state.scale_factor);
1261 if let Some(value) = state.last_sync_counter.take() {
1262 check_reply(
1263 || "X11 sync SetCounter failed.",
1264 sync::set_counter(&self.xcb, state.counter_id, value),
1265 )?;
1266 }
1267 result
1268 };
1269
1270 let mut callbacks = self.callbacks.borrow_mut();
1271 if let Some(ref mut fun) = callbacks.resize {
1272 fun(content_size, scale_factor)
1273 }
1274
1275 if !is_resize && let Some(ref mut fun) = callbacks.moved {
1276 fun();
1277 }
1278
1279 Ok(())
1280 }
1281
1282 pub fn set_active(&self, focus: bool) {
1283 let callback = self.callbacks.borrow_mut().active_status_change.take();
1284 if let Some(mut fun) = callback {
1285 fun(focus);
1286 self.callbacks.borrow_mut().active_status_change = Some(fun);
1287 }
1288 if let Some(adapter) = self.state.borrow_mut().accesskit_adapter.as_mut() {
1289 adapter.update_window_focus_state(focus);
1290 }
1291 }
1292
1293 pub fn set_hovered(&self, focus: bool) {
1294 let callback = self.callbacks.borrow_mut().hovered_status_change.take();
1295 if let Some(mut fun) = callback {
1296 fun(focus);
1297 self.callbacks.borrow_mut().hovered_status_change = Some(fun);
1298 }
1299 }
1300
1301 pub fn set_appearance(&mut self, appearance: WindowAppearance) {
1302 let mut state = self.state.borrow_mut();
1303 state.appearance = appearance;
1304 let is_transparent = state.is_transparent();
1305 state.renderer.update_transparency(is_transparent);
1306 state.appearance = appearance;
1307 drop(state);
1308 let callback = self.callbacks.borrow_mut().appearance_changed.take();
1309 if let Some(mut fun) = callback {
1310 fun();
1311 self.callbacks.borrow_mut().appearance_changed = Some(fun);
1312 }
1313 }
1314
1315 pub fn set_button_layout(&self) {
1316 let callback = self.callbacks.borrow_mut().button_layout_changed.take();
1317 if let Some(mut fun) = callback {
1318 fun();
1319 self.callbacks.borrow_mut().button_layout_changed = Some(fun);
1320 }
1321 }
1322}
1323
1324impl PlatformWindow for X11Window {
1325 fn bounds(&self) -> Bounds<Pixels> {
1326 self.0.state.borrow().bounds
1327 }
1328
1329 fn is_maximized(&self) -> bool {
1330 let state = self.0.state.borrow();
1331
1332 // A maximized window that gets minimized will still retain its maximized state.
1333 !state.hidden && state.maximized_vertical && state.maximized_horizontal
1334 }
1335
1336 fn window_bounds(&self) -> WindowBounds {
1337 let state = self.0.state.borrow();
1338 if self.is_maximized() {
1339 WindowBounds::Maximized(state.bounds)
1340 } else {
1341 WindowBounds::Windowed(state.bounds)
1342 }
1343 }
1344
1345 fn inner_window_bounds(&self) -> WindowBounds {
1346 let state = self.0.state.borrow();
1347 if self.is_maximized() {
1348 WindowBounds::Maximized(state.bounds)
1349 } else {
1350 let mut bounds = state.bounds;
1351 let [left, right, top, bottom] = state.last_insets;
1352
1353 let [left, right, top, bottom] = [
1354 px((left as f32) / state.scale_factor),
1355 px((right as f32) / state.scale_factor),
1356 px((top as f32) / state.scale_factor),
1357 px((bottom as f32) / state.scale_factor),
1358 ];
1359
1360 bounds.origin.x += left;
1361 bounds.origin.y += top;
1362 bounds.size.width -= left + right;
1363 bounds.size.height -= top + bottom;
1364
1365 WindowBounds::Windowed(bounds)
1366 }
1367 }
1368
1369 fn content_size(&self) -> Size<Pixels> {
1370 // After the wgpu migration, X11WindowState::content_size() returns logical pixels
1371 // (bounds.size is already divided by scale_factor in set_bounds), so no further
1372 // division is needed here. This matches the Wayland implementation.
1373 self.0.state.borrow().content_size()
1374 }
1375
1376 fn resize(&mut self, size: Size<Pixels>) {
1377 let state = self.0.state.borrow();
1378 let size = size.to_device_pixels(state.scale_factor);
1379 let width = size.width.0 as u32;
1380 let height = size.height.0 as u32;
1381
1382 check_reply(
1383 || {
1384 format!(
1385 "X11 ConfigureWindow failed. width: {}, height: {}",
1386 width, height
1387 )
1388 },
1389 self.0.xcb.configure_window(
1390 self.0.x_window,
1391 &xproto::ConfigureWindowAux::new()
1392 .width(width)
1393 .height(height),
1394 ),
1395 )
1396 .log_err();
1397 xcb_flush(&self.0.xcb);
1398 }
1399
1400 fn scale_factor(&self) -> f32 {
1401 self.0.state.borrow().scale_factor
1402 }
1403
1404 fn appearance(&self) -> WindowAppearance {
1405 self.0.state.borrow().appearance
1406 }
1407
1408 fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1409 Some(self.0.state.borrow().display.clone())
1410 }
1411
1412 fn mouse_position(&self) -> Point<Pixels> {
1413 get_reply(
1414 || "X11 QueryPointer failed.",
1415 self.0.xcb.query_pointer(self.0.x_window),
1416 )
1417 .log_err()
1418 .map_or(Point::new(Pixels::ZERO, Pixels::ZERO), |reply| {
1419 let scale_factor = self.0.state.borrow().scale_factor;
1420 Point::new(
1421 px(reply.win_x as f32 / scale_factor),
1422 px(reply.win_y as f32 / scale_factor),
1423 )
1424 })
1425 }
1426
1427 fn modifiers(&self) -> Modifiers {
1428 self.0
1429 .state
1430 .borrow()
1431 .client
1432 .0
1433 .upgrade()
1434 .map(|ref_cell| ref_cell.borrow().modifiers)
1435 .unwrap_or_default()
1436 }
1437
1438 fn capslock(&self) -> gpui::Capslock {
1439 self.0
1440 .state
1441 .borrow()
1442 .client
1443 .0
1444 .upgrade()
1445 .map(|ref_cell| ref_cell.borrow().capslock)
1446 .unwrap_or_default()
1447 }
1448
1449 fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
1450 self.0.state.borrow_mut().input_handler = Some(input_handler);
1451 }
1452
1453 fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
1454 self.0.state.borrow_mut().input_handler.take()
1455 }
1456
1457 fn prompt(
1458 &self,
1459 _level: PromptLevel,
1460 _msg: &str,
1461 _detail: Option<&str>,
1462 _answers: &[PromptButton],
1463 ) -> Option<futures::channel::oneshot::Receiver<usize>> {
1464 None
1465 }
1466
1467 fn activate(&self) {
1468 let data = [1, xproto::Time::CURRENT_TIME.into(), 0, 0, 0];
1469 let message = xproto::ClientMessageEvent::new(
1470 32,
1471 self.0.x_window,
1472 self.0.state.borrow().atoms._NET_ACTIVE_WINDOW,
1473 data,
1474 );
1475 self.0
1476 .xcb
1477 .send_event(
1478 false,
1479 self.0.state.borrow().x_root_window,
1480 xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
1481 message,
1482 )
1483 .log_err();
1484 self.0
1485 .xcb
1486 .set_input_focus(
1487 xproto::InputFocus::POINTER_ROOT,
1488 self.0.x_window,
1489 xproto::Time::CURRENT_TIME,
1490 )
1491 .log_err();
1492 xcb_flush(&self.0.xcb);
1493 }
1494
1495 fn request_attention(&self) {
1496 if self.is_active() {
1497 return;
1498 }
1499
1500 let mut hints = WmHints::new();
1501 match WmHints::get(&*self.0.xcb, self.0.x_window) {
1502 Ok(cookie) => match cookie.reply() {
1503 Ok(Some(existing_hints)) => hints = existing_hints,
1504 Ok(None) => {}
1505 Err(error) => {
1506 log::debug!("failed to read X11 WM_HINTS before setting urgency: {error}")
1507 }
1508 },
1509 Err(error) => {
1510 log::debug!("failed to request X11 WM_HINTS before setting urgency: {error}")
1511 }
1512 }
1513 hints.urgent = true;
1514 check_reply(
1515 || "X11 ChangeProperty for WM_HINTS urgency failed.",
1516 hints.set(&*self.0.xcb, self.0.x_window),
1517 )
1518 .log_err();
1519 xcb_flush(&self.0.xcb);
1520 }
1521
1522 fn is_active(&self) -> bool {
1523 self.0.state.borrow().active
1524 }
1525
1526 fn is_hovered(&self) -> bool {
1527 self.0.state.borrow().hovered
1528 }
1529
1530 fn set_title(&mut self, title: &str) {
1531 check_reply(
1532 || "X11 ChangeProperty8 on WM_NAME failed.",
1533 self.0.xcb.change_property8(
1534 xproto::PropMode::REPLACE,
1535 self.0.x_window,
1536 xproto::AtomEnum::WM_NAME,
1537 xproto::AtomEnum::STRING,
1538 title.as_bytes(),
1539 ),
1540 )
1541 .log_err();
1542
1543 check_reply(
1544 || "X11 ChangeProperty8 on _NET_WM_NAME failed.",
1545 self.0.xcb.change_property8(
1546 xproto::PropMode::REPLACE,
1547 self.0.x_window,
1548 self.0.state.borrow().atoms._NET_WM_NAME,
1549 self.0.state.borrow().atoms.UTF8_STRING,
1550 title.as_bytes(),
1551 ),
1552 )
1553 .log_err();
1554 xcb_flush(&self.0.xcb);
1555 }
1556
1557 fn set_app_id(&mut self, app_id: &str) {
1558 let mut data = Vec::with_capacity(app_id.len() * 2 + 1);
1559 data.extend(app_id.bytes()); // instance https://unix.stackexchange.com/a/494170
1560 data.push(b'\0');
1561 data.extend(app_id.bytes()); // class
1562
1563 check_reply(
1564 || "X11 ChangeProperty8 for WM_CLASS failed.",
1565 self.0.xcb.change_property8(
1566 xproto::PropMode::REPLACE,
1567 self.0.x_window,
1568 xproto::AtomEnum::WM_CLASS,
1569 xproto::AtomEnum::STRING,
1570 &data,
1571 ),
1572 )
1573 .log_err();
1574 }
1575
1576 fn map_window(&mut self) -> anyhow::Result<()> {
1577 check_reply(
1578 || "X11 MapWindow failed.",
1579 self.0.xcb.map_window(self.0.x_window),
1580 )?;
1581 Ok(())
1582 }
1583
1584 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
1585 let mut state = self.0.state.borrow_mut();
1586 state.background_appearance = background_appearance;
1587 let transparent = state.is_transparent();
1588 state.renderer.update_transparency(transparent);
1589 }
1590
1591 fn background_appearance(&self) -> WindowBackgroundAppearance {
1592 self.0.state.borrow().background_appearance
1593 }
1594
1595 fn is_subpixel_rendering_supported(&self) -> bool {
1596 self.0
1597 .state
1598 .borrow()
1599 .client
1600 .0
1601 .upgrade()
1602 .map(|ref_cell| {
1603 let state = ref_cell.borrow();
1604 state
1605 .gpu_context
1606 .borrow()
1607 .as_ref()
1608 .is_some_and(|ctx| ctx.supports_dual_source_blending())
1609 })
1610 .unwrap_or_default()
1611 }
1612
1613 fn minimize(&self) {
1614 let state = self.0.state.borrow();
1615 const WINDOW_ICONIC_STATE: u32 = 3;
1616 let message = ClientMessageEvent::new(
1617 32,
1618 self.0.x_window,
1619 state.atoms.WM_CHANGE_STATE,
1620 [WINDOW_ICONIC_STATE, 0, 0, 0, 0],
1621 );
1622 check_reply(
1623 || "X11 SendEvent to minimize window failed.",
1624 self.0.xcb.send_event(
1625 false,
1626 state.x_root_window,
1627 xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
1628 message,
1629 ),
1630 )
1631 .log_err();
1632 }
1633
1634 fn zoom(&self) {
1635 let state = self.0.state.borrow();
1636 self.set_wm_hints(
1637 || "X11 SendEvent to maximize a window failed.",
1638 WmHintPropertyState::Toggle,
1639 state.atoms._NET_WM_STATE_MAXIMIZED_VERT,
1640 state.atoms._NET_WM_STATE_MAXIMIZED_HORZ,
1641 )
1642 .log_err();
1643 }
1644
1645 fn toggle_fullscreen(&self) {
1646 let state = self.0.state.borrow();
1647 self.set_wm_hints(
1648 || "X11 SendEvent to fullscreen a window failed.",
1649 WmHintPropertyState::Toggle,
1650 state.atoms._NET_WM_STATE_FULLSCREEN,
1651 xproto::AtomEnum::NONE.into(),
1652 )
1653 .log_err();
1654 }
1655
1656 fn is_fullscreen(&self) -> bool {
1657 self.0.state.borrow().fullscreen
1658 }
1659
1660 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
1661 self.0.callbacks.borrow_mut().request_frame = Some(callback);
1662 }
1663
1664 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> gpui::DispatchEventResult>) {
1665 self.0.callbacks.borrow_mut().input = Some(callback);
1666 }
1667
1668 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1669 self.0.callbacks.borrow_mut().active_status_change = Some(callback);
1670 }
1671
1672 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1673 self.0.callbacks.borrow_mut().hovered_status_change = Some(callback);
1674 }
1675
1676 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
1677 self.0.callbacks.borrow_mut().resize = Some(callback);
1678 }
1679
1680 fn on_moved(&self, callback: Box<dyn FnMut()>) {
1681 self.0.callbacks.borrow_mut().moved = Some(callback);
1682 }
1683
1684 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
1685 self.0.callbacks.borrow_mut().should_close = Some(callback);
1686 }
1687
1688 fn on_close(&self, callback: Box<dyn FnOnce()>) {
1689 self.0.callbacks.borrow_mut().close = Some(callback);
1690 }
1691
1692 fn on_hit_test_window_control(&self, _callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
1693 }
1694
1695 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
1696 self.0.callbacks.borrow_mut().appearance_changed = Some(callback);
1697 }
1698
1699 fn on_button_layout_changed(&self, callback: Box<dyn FnMut()>) {
1700 self.0.callbacks.borrow_mut().button_layout_changed = Some(callback);
1701 }
1702
1703 fn draw(&self, scene: &Scene) {
1704 let mut inner = self.0.state.borrow_mut();
1705
1706 if inner.renderer.device_lost() {
1707 let raw_window = RawWindow {
1708 connection: as_raw_xcb_connection::AsRawXcbConnection::as_raw_xcb_connection(
1709 &*self.0.xcb,
1710 ) as *mut _,
1711 screen_id: inner.x_screen_index,
1712 window_id: self.0.x_window,
1713 visual_id: inner.visual_id,
1714 };
1715 match inner.renderer.recover(&raw_window) {
1716 Ok(()) => {}
1717 Err(err) => {
1718 log::warn!("GPU recovery failed, will retry on next frame: {err}");
1719 }
1720 }
1721
1722 inner.force_render_after_recovery = true;
1723 return;
1724 }
1725
1726 inner.renderer.draw(scene);
1727
1728 if inner.renderer.needs_redraw() {
1729 inner.force_render_after_recovery = true;
1730 }
1731 }
1732
1733 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
1734 let inner = self.0.state.borrow();
1735 inner.renderer.sprite_atlas().clone()
1736 }
1737
1738 fn show_window_menu(&self, position: Point<Pixels>) {
1739 let state = self.0.state.borrow();
1740
1741 check_reply(
1742 || "X11 UngrabPointer failed.",
1743 self.0.xcb.ungrab_pointer(x11rb::CURRENT_TIME),
1744 )
1745 .log_err();
1746
1747 let Some(coords) = self.get_root_position(position).log_err() else {
1748 return;
1749 };
1750 let message = ClientMessageEvent::new(
1751 32,
1752 self.0.x_window,
1753 state.atoms._GTK_SHOW_WINDOW_MENU,
1754 [
1755 XINPUT_ALL_DEVICE_GROUPS as u32,
1756 coords.dst_x as u32,
1757 coords.dst_y as u32,
1758 0,
1759 0,
1760 ],
1761 );
1762 check_reply(
1763 || "X11 SendEvent to show window menu failed.",
1764 self.0.xcb.send_event(
1765 false,
1766 state.x_root_window,
1767 xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
1768 message,
1769 ),
1770 )
1771 .log_err();
1772 }
1773
1774 fn start_window_move(&self) {
1775 const MOVERESIZE_MOVE: u32 = 8;
1776 self.send_moveresize(MOVERESIZE_MOVE).log_err();
1777 }
1778
1779 fn start_window_resize(&self, edge: ResizeEdge) {
1780 self.send_moveresize(resize_edge_to_moveresize(edge))
1781 .log_err();
1782 }
1783
1784 fn window_decorations(&self) -> gpui::Decorations {
1785 let state = self.0.state.borrow();
1786
1787 // Client window decorations require compositor support
1788 if !state.client_side_decorations_supported {
1789 return Decorations::Server;
1790 }
1791
1792 match state.decorations {
1793 WindowDecorations::Server => Decorations::Server,
1794 WindowDecorations::Client => {
1795 let tiling = if state.fullscreen {
1796 Tiling::tiled()
1797 } else if let Some(edge_constraints) = &state.edge_constraints {
1798 edge_constraints.to_tiling()
1799 } else {
1800 // https://source.chromium.org/chromium/chromium/src/+/main:ui/ozone/platform/x11/x11_window.cc;l=2519;drc=1f14cc876cc5bf899d13284a12c451498219bb2d
1801 Tiling {
1802 top: state.maximized_vertical,
1803 bottom: state.maximized_vertical,
1804 left: state.maximized_horizontal,
1805 right: state.maximized_horizontal,
1806 }
1807 };
1808 Decorations::Client { tiling }
1809 }
1810 }
1811 }
1812
1813 fn set_client_inset(&self, inset: Pixels) {
1814 let mut state = self.0.state.borrow_mut();
1815
1816 let dp = (f32::from(inset) * state.scale_factor) as u32;
1817
1818 let insets = if state.fullscreen {
1819 [0, 0, 0, 0]
1820 } else if let Some(edge_constraints) = &state.edge_constraints {
1821 let left = if edge_constraints.left_tiled { 0 } else { dp };
1822 let top = if edge_constraints.top_tiled { 0 } else { dp };
1823 let right = if edge_constraints.right_tiled { 0 } else { dp };
1824 let bottom = if edge_constraints.bottom_tiled { 0 } else { dp };
1825
1826 [left, right, top, bottom]
1827 } else {
1828 let (left, right) = if state.maximized_horizontal {
1829 (0, 0)
1830 } else {
1831 (dp, dp)
1832 };
1833 let (top, bottom) = if state.maximized_vertical {
1834 (0, 0)
1835 } else {
1836 (dp, dp)
1837 };
1838 [left, right, top, bottom]
1839 };
1840
1841 if state.last_insets != insets {
1842 state.last_insets = insets;
1843
1844 check_reply(
1845 || "X11 ChangeProperty for _GTK_FRAME_EXTENTS failed.",
1846 self.0.xcb.change_property(
1847 xproto::PropMode::REPLACE,
1848 self.0.x_window,
1849 state.atoms._GTK_FRAME_EXTENTS,
1850 xproto::AtomEnum::CARDINAL,
1851 size_of::<u32>() as u8 * 8,
1852 4,
1853 bytemuck::cast_slice::<u32, u8>(&insets),
1854 ),
1855 )
1856 .log_err();
1857 }
1858 }
1859
1860 fn request_decorations(&self, mut decorations: gpui::WindowDecorations) {
1861 let mut state = self.0.state.borrow_mut();
1862
1863 if matches!(decorations, gpui::WindowDecorations::Client)
1864 && !state.client_side_decorations_supported
1865 {
1866 log::info!(
1867 "x11: no compositor present, falling back to server-side window decorations"
1868 );
1869 decorations = gpui::WindowDecorations::Server;
1870 }
1871
1872 // https://github.com/rust-windowing/winit/blob/master/src/platform_impl/linux/x11/util/hint.rs#L53-L87
1873 let hints_data: [u32; 5] = match decorations {
1874 WindowDecorations::Server => [1 << 1, 0, 1, 0, 0],
1875 WindowDecorations::Client => [1 << 1, 0, 0, 0, 0],
1876 };
1877
1878 let success = check_reply(
1879 || "X11 ChangeProperty for _MOTIF_WM_HINTS failed.",
1880 self.0.xcb.change_property(
1881 xproto::PropMode::REPLACE,
1882 self.0.x_window,
1883 state.atoms._MOTIF_WM_HINTS,
1884 state.atoms._MOTIF_WM_HINTS,
1885 size_of::<u32>() as u8 * 8,
1886 5,
1887 bytemuck::cast_slice::<u32, u8>(&hints_data),
1888 ),
1889 )
1890 .log_err();
1891
1892 let Some(()) = success else {
1893 return;
1894 };
1895
1896 match decorations {
1897 WindowDecorations::Server => {
1898 state.decorations = WindowDecorations::Server;
1899 let is_transparent = state.is_transparent();
1900 state.renderer.update_transparency(is_transparent);
1901 }
1902 WindowDecorations::Client => {
1903 state.decorations = WindowDecorations::Client;
1904 let is_transparent = state.is_transparent();
1905 state.renderer.update_transparency(is_transparent);
1906 }
1907 }
1908
1909 drop(state);
1910 let mut callbacks = self.0.callbacks.borrow_mut();
1911 if let Some(appearance_changed) = callbacks.appearance_changed.as_mut() {
1912 appearance_changed();
1913 }
1914 }
1915
1916 fn update_ime_position(&self, bounds: Bounds<Pixels>) {
1917 let state = self.0.state.borrow();
1918 let client = state.client.clone();
1919 drop(state);
1920 client.update_ime_position(bounds);
1921 }
1922
1923 fn gpu_specs(&self) -> Option<GpuSpecs> {
1924 self.0.state.borrow().renderer.gpu_specs().into()
1925 }
1926
1927 fn play_system_bell(&self) {
1928 // Volume 0% means don't increase or decrease from system volume
1929 let _ = self.0.xcb.bell(0);
1930 }
1931
1932 fn a11y_init(&self, callbacks: gpui::A11yCallbacks) {
1933 let activation_handler = TrivialActivationHandler {
1934 callback: callbacks.activation,
1935 };
1936 let action_handler = TrivialActionHandler(callbacks.action);
1937 let deactivation_handler = TrivialDeactivationHandler {
1938 callback: callbacks.deactivation,
1939 };
1940
1941 let adapter =
1942 accesskit_unix::Adapter::new(activation_handler, action_handler, deactivation_handler);
1943
1944 self.0.state.borrow_mut().accesskit_adapter = Some(adapter);
1945 }
1946
1947 fn a11y_tree_update(&self, tree_update: accesskit::TreeUpdate) {
1948 let mut state = self.0.state.borrow_mut();
1949 if let Some(adapter) = state.accesskit_adapter.as_mut() {
1950 adapter.update_if_active(|| tree_update);
1951 }
1952 }
1953
1954 fn a11y_update_window_bounds(&self) {
1955 let mut state = self.0.state.borrow_mut();
1956 let scale = state.scale_factor;
1957 let bounds = state.bounds;
1958 let [left, right, top, bottom] = state.last_insets;
1959
1960 let x = f32::from(bounds.origin.x);
1961 let y = f32::from(bounds.origin.y);
1962 let width = f32::from(bounds.size.width);
1963 let height = f32::from(bounds.size.height);
1964
1965 let outer = accesskit::Rect {
1966 x0: (x * scale) as f64,
1967 y0: (y * scale) as f64,
1968 x1: ((x + width) * scale) as f64,
1969 y1: ((y + height) * scale) as f64,
1970 };
1971
1972 let inner = accesskit::Rect {
1973 x0: (x * scale) as f64 + left as f64,
1974 y0: (y * scale) as f64 + top as f64,
1975 x1: ((x + width) * scale) as f64 - right as f64,
1976 y1: ((y + height) * scale) as f64 - bottom as f64,
1977 };
1978
1979 if let Some(adapter) = state.accesskit_adapter.as_mut() {
1980 adapter.set_root_window_bounds(outer, inner);
1981 }
1982 }
1983}
1984
1985struct TrivialActivationHandler {
1986 callback: Box<dyn Fn() -> Option<accesskit::TreeUpdate> + Send + 'static>,
1987}
1988
1989impl accesskit::ActivationHandler for TrivialActivationHandler {
1990 fn request_initial_tree(&mut self) -> Option<accesskit::TreeUpdate> {
1991 (self.callback)()
1992 }
1993}
1994
1995struct TrivialActionHandler(Box<dyn Fn(accesskit::ActionRequest) + Send + 'static>);
1996
1997impl accesskit::ActionHandler for TrivialActionHandler {
1998 fn do_action(&mut self, request: accesskit::ActionRequest) {
1999 (self.0)(request);
2000 }
2001}
2002
2003struct TrivialDeactivationHandler {
2004 callback: Box<dyn Fn() + Send + 'static>,
2005}
2006
2007impl accesskit::DeactivationHandler for TrivialDeactivationHandler {
2008 fn deactivate_accessibility(&mut self) {
2009 (self.callback)();
2010 }
2011}
2012