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