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