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