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