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 // x11rb 0.13 doesn't define XIEventMask constants for gesture
676 // events, so we construct them from the event opcodes (each
677 // XInput event type N maps to mask bit N).
678 | xinput::XIEventMask::from(1u32 << xinput::GESTURE_PINCH_BEGIN_EVENT)
679 | xinput::XIEventMask::from(1u32 << xinput::GESTURE_PINCH_UPDATE_EVENT)
680 | xinput::XIEventMask::from(1u32 << xinput::GESTURE_PINCH_END_EVENT),
681 ],
682 }],
683 ),
684 )?;
685
686 check_reply(
687 || "X11 XiSelectEvents for device changes failed.",
688 xcb.xinput_xi_select_events(
689 x_window,
690 &[xinput::EventMask {
691 deviceid: XINPUT_ALL_DEVICES,
692 mask: vec![
693 xinput::XIEventMask::HIERARCHY | xinput::XIEventMask::DEVICE_CHANGED,
694 ],
695 }],
696 ),
697 )?;
698
699 xcb_flush(xcb);
700
701 let renderer = {
702 let raw_window = RawWindow {
703 connection: as_raw_xcb_connection::AsRawXcbConnection::as_raw_xcb_connection(
704 xcb,
705 ) as *mut _,
706 screen_id: x_screen_index,
707 window_id: x_window,
708 visual_id: visual.id,
709 };
710 let config = WgpuSurfaceConfig {
711 // Note: this has to be done after the GPU init, or otherwise
712 // the sizes are immediately invalidated.
713 size: query_render_extent(xcb, x_window)?,
714 // We set it to transparent by default, even if we have client-side
715 // decorations, since those seem to work on X11 even without `true` here.
716 // If the window appearance changes, then the renderer will get updated
717 // too
718 transparent: false,
719 preferred_present_mode: None,
720 };
721 WgpuRenderer::new(gpu_context, &raw_window, config, compositor_gpu)?
722 };
723
724 // Set max window size hints based on the GPU's maximum texture dimension.
725 // This prevents the window from being resized larger than what the GPU can render.
726 let max_texture_size = renderer.max_texture_size();
727 let mut size_hints = WmSizeHints::new();
728 if let Some(size) = params.window_min_size {
729 size_hints.min_size =
730 Some((f32::from(size.width) as i32, f32::from(size.height) as i32));
731 }
732 size_hints.max_size = Some((max_texture_size as i32, max_texture_size as i32));
733 check_reply(
734 || {
735 format!(
736 "X11 change of WM_SIZE_HINTS failed. max_size: {:?}",
737 max_texture_size
738 )
739 },
740 size_hints.set_normal_hints(xcb, x_window),
741 )?;
742
743 let display = Rc::new(X11Display::new(xcb, scale_factor, x_screen_index)?);
744
745 Ok(Self {
746 parent,
747 children: FxHashSet::default(),
748 client,
749 executor,
750 display,
751 x_root_window: visual_set.root,
752 x_screen_index,
753 visual_id: visual.id,
754 bounds: bounds.to_pixels(scale_factor),
755 scale_factor,
756 renderer,
757 atoms: *atoms,
758 input_handler: None,
759 active: false,
760 hovered: false,
761 force_render_after_recovery: false,
762 fullscreen: false,
763 maximized_vertical: false,
764 maximized_horizontal: false,
765 hidden: false,
766 appearance,
767 handle,
768 background_appearance: WindowBackgroundAppearance::Opaque,
769 destroyed: false,
770 client_side_decorations_supported,
771 decorations: WindowDecorations::Server,
772 last_insets: [0, 0, 0, 0],
773 edge_constraints: None,
774 counter_id: sync_request_counter,
775 last_sync_counter: None,
776 })
777 });
778
779 if setup_result.is_err() {
780 check_reply(
781 || "X11 DestroyWindow failed while cleaning it up after setup failure.",
782 xcb.destroy_window(x_window),
783 )?;
784 xcb_flush(xcb);
785 }
786
787 setup_result
788 }
789
790 fn content_size(&self) -> Size<Pixels> {
791 self.bounds.size
792 }
793}
794
795pub(crate) struct X11Window(pub X11WindowStatePtr);
796
797impl Drop for X11Window {
798 fn drop(&mut self) {
799 let mut state = self.0.state.borrow_mut();
800
801 if let Some(parent) = state.parent.as_ref() {
802 parent.state.borrow_mut().children.remove(&self.0.x_window);
803 }
804
805 state.renderer.destroy();
806
807 let destroy_x_window = maybe!({
808 check_reply(
809 || "X11 DestroyWindow failure.",
810 self.0.xcb.destroy_window(self.0.x_window),
811 )?;
812 xcb_flush(&self.0.xcb);
813
814 anyhow::Ok(())
815 })
816 .log_err();
817
818 if destroy_x_window.is_some() {
819 state.destroyed = true;
820
821 let this_ptr = self.0.clone();
822 let client_ptr = state.client.clone();
823 state
824 .executor
825 .spawn(async move {
826 this_ptr.close();
827 client_ptr.drop_window(this_ptr.x_window);
828 })
829 .detach();
830 }
831
832 drop(state);
833 }
834}
835
836enum WmHintPropertyState {
837 // Remove = 0,
838 // Add = 1,
839 Toggle = 2,
840}
841
842impl X11Window {
843 pub fn new(
844 handle: AnyWindowHandle,
845 client: X11ClientStatePtr,
846 executor: ForegroundExecutor,
847 gpu_context: gpui_wgpu::GpuContext,
848 compositor_gpu: Option<CompositorGpuHint>,
849 params: WindowParams,
850 xcb: &Rc<XCBConnection>,
851 client_side_decorations_supported: bool,
852 x_main_screen_index: usize,
853 x_window: xproto::Window,
854 atoms: &XcbAtoms,
855 scale_factor: f32,
856 appearance: WindowAppearance,
857 parent_window: Option<X11WindowStatePtr>,
858 ) -> anyhow::Result<Self> {
859 let ptr = X11WindowStatePtr {
860 state: Rc::new(RefCell::new(X11WindowState::new(
861 handle,
862 client,
863 executor,
864 gpu_context,
865 compositor_gpu,
866 params,
867 xcb,
868 client_side_decorations_supported,
869 x_main_screen_index,
870 x_window,
871 atoms,
872 scale_factor,
873 appearance,
874 parent_window,
875 )?)),
876 callbacks: Rc::new(RefCell::new(Callbacks::default())),
877 xcb: xcb.clone(),
878 x_window,
879 };
880
881 let state = ptr.state.borrow_mut();
882 ptr.set_wm_properties(state)?;
883
884 Ok(Self(ptr))
885 }
886
887 fn set_wm_hints<C: Display + Send + Sync + 'static, F: FnOnce() -> C>(
888 &self,
889 failure_context: F,
890 wm_hint_property_state: WmHintPropertyState,
891 prop1: u32,
892 prop2: u32,
893 ) -> anyhow::Result<()> {
894 let state = self.0.state.borrow();
895 let message = ClientMessageEvent::new(
896 32,
897 self.0.x_window,
898 state.atoms._NET_WM_STATE,
899 [wm_hint_property_state as u32, prop1, prop2, 1, 0],
900 );
901 check_reply(
902 failure_context,
903 self.0.xcb.send_event(
904 false,
905 state.x_root_window,
906 xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
907 message,
908 ),
909 )?;
910 xcb_flush(&self.0.xcb);
911 Ok(())
912 }
913
914 fn get_root_position(
915 &self,
916 position: Point<Pixels>,
917 ) -> anyhow::Result<TranslateCoordinatesReply> {
918 let state = self.0.state.borrow();
919 get_reply(
920 || "X11 TranslateCoordinates failed.",
921 self.0.xcb.translate_coordinates(
922 self.0.x_window,
923 state.x_root_window,
924 (f32::from(position.x) * state.scale_factor) as i16,
925 (f32::from(position.y) * state.scale_factor) as i16,
926 ),
927 )
928 }
929
930 fn send_moveresize(&self, flag: u32) -> anyhow::Result<()> {
931 let state = self.0.state.borrow();
932
933 check_reply(
934 || "X11 UngrabPointer before move/resize of window failed.",
935 self.0.xcb.ungrab_pointer(x11rb::CURRENT_TIME),
936 )?;
937
938 let pointer = get_reply(
939 || "X11 QueryPointer before move/resize of window failed.",
940 self.0.xcb.query_pointer(self.0.x_window),
941 )?;
942 let message = ClientMessageEvent::new(
943 32,
944 self.0.x_window,
945 state.atoms._NET_WM_MOVERESIZE,
946 [
947 pointer.root_x as u32,
948 pointer.root_y as u32,
949 flag,
950 0, // Left mouse button
951 0,
952 ],
953 );
954 check_reply(
955 || "X11 SendEvent to move/resize window failed.",
956 self.0.xcb.send_event(
957 false,
958 state.x_root_window,
959 xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
960 message,
961 ),
962 )?;
963
964 xcb_flush(&self.0.xcb);
965 Ok(())
966 }
967}
968
969impl X11WindowStatePtr {
970 pub fn should_close(&self) -> bool {
971 let mut cb = self.callbacks.borrow_mut();
972 if let Some(mut should_close) = cb.should_close.take() {
973 let result = (should_close)();
974 cb.should_close = Some(should_close);
975 result
976 } else {
977 true
978 }
979 }
980
981 pub fn property_notify(&self, event: xproto::PropertyNotifyEvent) -> anyhow::Result<()> {
982 let state = self.state.borrow_mut();
983 if event.atom == state.atoms._NET_WM_STATE {
984 self.set_wm_properties(state)?;
985 } else if event.atom == state.atoms._GTK_EDGE_CONSTRAINTS {
986 self.set_edge_constraints(state)?;
987 }
988 Ok(())
989 }
990
991 fn set_edge_constraints(
992 &self,
993 mut state: std::cell::RefMut<X11WindowState>,
994 ) -> anyhow::Result<()> {
995 let reply = get_reply(
996 || "X11 GetProperty for _GTK_EDGE_CONSTRAINTS failed.",
997 self.xcb.get_property(
998 false,
999 self.x_window,
1000 state.atoms._GTK_EDGE_CONSTRAINTS,
1001 xproto::AtomEnum::CARDINAL,
1002 0,
1003 4,
1004 ),
1005 )?;
1006
1007 if reply.value_len != 0 {
1008 if let Ok(bytes) = reply.value[0..4].try_into() {
1009 let atom = u32::from_ne_bytes(bytes);
1010 let edge_constraints = EdgeConstraints::from_atom(atom);
1011 state.edge_constraints.replace(edge_constraints);
1012 } else {
1013 log::error!("Failed to parse GTK_EDGE_CONSTRAINTS");
1014 }
1015 }
1016
1017 Ok(())
1018 }
1019
1020 fn set_wm_properties(
1021 &self,
1022 mut state: std::cell::RefMut<X11WindowState>,
1023 ) -> anyhow::Result<()> {
1024 let reply = get_reply(
1025 || "X11 GetProperty for _NET_WM_STATE failed.",
1026 self.xcb.get_property(
1027 false,
1028 self.x_window,
1029 state.atoms._NET_WM_STATE,
1030 xproto::AtomEnum::ATOM,
1031 0,
1032 u32::MAX,
1033 ),
1034 )?;
1035
1036 let atoms = reply
1037 .value
1038 .chunks_exact(4)
1039 .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
1040
1041 state.active = false;
1042 state.fullscreen = false;
1043 state.maximized_vertical = false;
1044 state.maximized_horizontal = false;
1045 state.hidden = false;
1046
1047 for atom in atoms {
1048 if atom == state.atoms._NET_WM_STATE_FOCUSED {
1049 state.active = true;
1050 } else if atom == state.atoms._NET_WM_STATE_FULLSCREEN {
1051 state.fullscreen = true;
1052 } else if atom == state.atoms._NET_WM_STATE_MAXIMIZED_VERT {
1053 state.maximized_vertical = true;
1054 } else if atom == state.atoms._NET_WM_STATE_MAXIMIZED_HORZ {
1055 state.maximized_horizontal = true;
1056 } else if atom == state.atoms._NET_WM_STATE_HIDDEN {
1057 state.hidden = true;
1058 }
1059 }
1060
1061 Ok(())
1062 }
1063
1064 pub fn add_child(&self, child: xproto::Window) {
1065 let mut state = self.state.borrow_mut();
1066 state.children.insert(child);
1067 }
1068
1069 pub fn is_blocked(&self) -> bool {
1070 let state = self.state.borrow();
1071 !state.children.is_empty()
1072 }
1073
1074 pub fn close(&self) {
1075 let state = self.state.borrow();
1076 let client = state.client.clone();
1077 #[allow(clippy::mutable_key_type)]
1078 let children = state.children.clone();
1079 drop(state);
1080
1081 if let Some(client) = client.get_client() {
1082 for child in children {
1083 if let Some(child_window) = client.get_window(child) {
1084 child_window.close();
1085 }
1086 }
1087 }
1088
1089 let mut callbacks = self.callbacks.borrow_mut();
1090 if let Some(fun) = callbacks.close.take() {
1091 fun()
1092 }
1093 }
1094
1095 pub fn refresh(&self, request_frame_options: RequestFrameOptions) {
1096 let callback = self.callbacks.borrow_mut().request_frame.take();
1097 if let Some(mut fun) = callback {
1098 fun(request_frame_options);
1099 self.callbacks.borrow_mut().request_frame = Some(fun);
1100 }
1101 }
1102
1103 pub fn handle_input(&self, input: PlatformInput) {
1104 if self.is_blocked() {
1105 return;
1106 }
1107 let callback = self.callbacks.borrow_mut().input.take();
1108 if let Some(mut fun) = callback {
1109 let result = fun(input.clone());
1110 self.callbacks.borrow_mut().input = Some(fun);
1111 if !result.propagate {
1112 return;
1113 }
1114 }
1115 if let PlatformInput::KeyDown(event) = input {
1116 // only allow shift modifier when inserting text
1117 if event.keystroke.modifiers.is_subset_of(&Modifiers::shift()) {
1118 let mut state = self.state.borrow_mut();
1119 if let Some(mut input_handler) = state.input_handler.take() {
1120 if let Some(key_char) = &event.keystroke.key_char {
1121 drop(state);
1122 input_handler.replace_text_in_range(None, key_char);
1123 state = self.state.borrow_mut();
1124 }
1125 state.input_handler = Some(input_handler);
1126 }
1127 }
1128 }
1129 }
1130
1131 pub fn handle_ime_commit(&self, text: String) {
1132 if self.is_blocked() {
1133 return;
1134 }
1135 let mut state = self.state.borrow_mut();
1136 if let Some(mut input_handler) = state.input_handler.take() {
1137 drop(state);
1138 input_handler.replace_text_in_range(None, &text);
1139 let mut state = self.state.borrow_mut();
1140 state.input_handler = Some(input_handler);
1141 }
1142 }
1143
1144 pub fn handle_ime_preedit(&self, text: String) {
1145 if self.is_blocked() {
1146 return;
1147 }
1148 let mut state = self.state.borrow_mut();
1149 if let Some(mut input_handler) = state.input_handler.take() {
1150 drop(state);
1151 input_handler.replace_and_mark_text_in_range(None, &text, None);
1152 let mut state = self.state.borrow_mut();
1153 state.input_handler = Some(input_handler);
1154 }
1155 }
1156
1157 pub fn handle_ime_unmark(&self) {
1158 if self.is_blocked() {
1159 return;
1160 }
1161 let mut state = self.state.borrow_mut();
1162 if let Some(mut input_handler) = state.input_handler.take() {
1163 drop(state);
1164 input_handler.unmark_text();
1165 let mut state = self.state.borrow_mut();
1166 state.input_handler = Some(input_handler);
1167 }
1168 }
1169
1170 pub fn handle_ime_delete(&self) {
1171 if self.is_blocked() {
1172 return;
1173 }
1174 let mut state = self.state.borrow_mut();
1175 if let Some(mut input_handler) = state.input_handler.take() {
1176 drop(state);
1177 if let Some(marked) = input_handler.marked_text_range() {
1178 input_handler.replace_text_in_range(Some(marked), "");
1179 }
1180 let mut state = self.state.borrow_mut();
1181 state.input_handler = Some(input_handler);
1182 }
1183 }
1184
1185 pub fn get_ime_area(&self) -> Option<Bounds<ScaledPixels>> {
1186 let mut state = self.state.borrow_mut();
1187 let scale_factor = state.scale_factor;
1188 let mut bounds: Option<Bounds<Pixels>> = None;
1189 if let Some(mut input_handler) = state.input_handler.take() {
1190 drop(state);
1191 if let Some(selection) = input_handler.selected_text_range(true) {
1192 bounds = input_handler.bounds_for_range(selection.range);
1193 }
1194 let mut state = self.state.borrow_mut();
1195 state.input_handler = Some(input_handler);
1196 };
1197 bounds.map(|b| b.scale(scale_factor))
1198 }
1199
1200 pub fn set_bounds(&self, bounds: Bounds<i32>) -> anyhow::Result<()> {
1201 let (is_resize, content_size, scale_factor) = {
1202 let mut state = self.state.borrow_mut();
1203 let bounds = bounds.map(|f| px(f as f32 / state.scale_factor));
1204
1205 let is_resize = bounds.size.width != state.bounds.size.width
1206 || bounds.size.height != state.bounds.size.height;
1207
1208 // If it's a resize event (only width/height changed), we ignore `bounds.origin`
1209 // because it contains wrong values.
1210 if is_resize {
1211 state.bounds.size = bounds.size;
1212 } else {
1213 state.bounds = bounds;
1214 }
1215
1216 let gpu_size = query_render_extent(&self.xcb, self.x_window)?;
1217 state.renderer.update_drawable_size(gpu_size);
1218 let result = (is_resize, state.content_size(), state.scale_factor);
1219 if let Some(value) = state.last_sync_counter.take() {
1220 check_reply(
1221 || "X11 sync SetCounter failed.",
1222 sync::set_counter(&self.xcb, state.counter_id, value),
1223 )?;
1224 }
1225 result
1226 };
1227
1228 let mut callbacks = self.callbacks.borrow_mut();
1229 if let Some(ref mut fun) = callbacks.resize {
1230 fun(content_size, scale_factor)
1231 }
1232
1233 if !is_resize && let Some(ref mut fun) = callbacks.moved {
1234 fun();
1235 }
1236
1237 Ok(())
1238 }
1239
1240 pub fn set_active(&self, focus: bool) {
1241 let callback = self.callbacks.borrow_mut().active_status_change.take();
1242 if let Some(mut fun) = callback {
1243 fun(focus);
1244 self.callbacks.borrow_mut().active_status_change = Some(fun);
1245 }
1246 }
1247
1248 pub fn set_hovered(&self, focus: bool) {
1249 let callback = self.callbacks.borrow_mut().hovered_status_change.take();
1250 if let Some(mut fun) = callback {
1251 fun(focus);
1252 self.callbacks.borrow_mut().hovered_status_change = Some(fun);
1253 }
1254 }
1255
1256 pub fn set_appearance(&mut self, appearance: WindowAppearance) {
1257 let mut state = self.state.borrow_mut();
1258 state.appearance = appearance;
1259 let is_transparent = state.is_transparent();
1260 state.renderer.update_transparency(is_transparent);
1261 state.appearance = appearance;
1262 drop(state);
1263 let callback = self.callbacks.borrow_mut().appearance_changed.take();
1264 if let Some(mut fun) = callback {
1265 fun();
1266 self.callbacks.borrow_mut().appearance_changed = Some(fun);
1267 }
1268 }
1269
1270 pub fn set_button_layout(&self) {
1271 let callback = self.callbacks.borrow_mut().button_layout_changed.take();
1272 if let Some(mut fun) = callback {
1273 fun();
1274 self.callbacks.borrow_mut().button_layout_changed = Some(fun);
1275 }
1276 }
1277}
1278
1279impl PlatformWindow for X11Window {
1280 fn bounds(&self) -> Bounds<Pixels> {
1281 self.0.state.borrow().bounds
1282 }
1283
1284 fn is_maximized(&self) -> bool {
1285 let state = self.0.state.borrow();
1286
1287 // A maximized window that gets minimized will still retain its maximized state.
1288 !state.hidden && state.maximized_vertical && state.maximized_horizontal
1289 }
1290
1291 fn window_bounds(&self) -> WindowBounds {
1292 let state = self.0.state.borrow();
1293 if self.is_maximized() {
1294 WindowBounds::Maximized(state.bounds)
1295 } else {
1296 WindowBounds::Windowed(state.bounds)
1297 }
1298 }
1299
1300 fn inner_window_bounds(&self) -> WindowBounds {
1301 let state = self.0.state.borrow();
1302 if self.is_maximized() {
1303 WindowBounds::Maximized(state.bounds)
1304 } else {
1305 let mut bounds = state.bounds;
1306 let [left, right, top, bottom] = state.last_insets;
1307
1308 let [left, right, top, bottom] = [
1309 px((left as f32) / state.scale_factor),
1310 px((right as f32) / state.scale_factor),
1311 px((top as f32) / state.scale_factor),
1312 px((bottom as f32) / state.scale_factor),
1313 ];
1314
1315 bounds.origin.x += left;
1316 bounds.origin.y += top;
1317 bounds.size.width -= left + right;
1318 bounds.size.height -= top + bottom;
1319
1320 WindowBounds::Windowed(bounds)
1321 }
1322 }
1323
1324 fn content_size(&self) -> Size<Pixels> {
1325 // After the wgpu migration, X11WindowState::content_size() returns logical pixels
1326 // (bounds.size is already divided by scale_factor in set_bounds), so no further
1327 // division is needed here. This matches the Wayland implementation.
1328 self.0.state.borrow().content_size()
1329 }
1330
1331 fn resize(&mut self, size: Size<Pixels>) {
1332 let state = self.0.state.borrow();
1333 let size = size.to_device_pixels(state.scale_factor);
1334 let width = size.width.0 as u32;
1335 let height = size.height.0 as u32;
1336
1337 check_reply(
1338 || {
1339 format!(
1340 "X11 ConfigureWindow failed. width: {}, height: {}",
1341 width, height
1342 )
1343 },
1344 self.0.xcb.configure_window(
1345 self.0.x_window,
1346 &xproto::ConfigureWindowAux::new()
1347 .width(width)
1348 .height(height),
1349 ),
1350 )
1351 .log_err();
1352 xcb_flush(&self.0.xcb);
1353 }
1354
1355 fn scale_factor(&self) -> f32 {
1356 self.0.state.borrow().scale_factor
1357 }
1358
1359 fn appearance(&self) -> WindowAppearance {
1360 self.0.state.borrow().appearance
1361 }
1362
1363 fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1364 Some(self.0.state.borrow().display.clone())
1365 }
1366
1367 fn mouse_position(&self) -> Point<Pixels> {
1368 get_reply(
1369 || "X11 QueryPointer failed.",
1370 self.0.xcb.query_pointer(self.0.x_window),
1371 )
1372 .log_err()
1373 .map_or(Point::new(Pixels::ZERO, Pixels::ZERO), |reply| {
1374 Point::new((reply.root_x as u32).into(), (reply.root_y as u32).into())
1375 })
1376 }
1377
1378 fn modifiers(&self) -> Modifiers {
1379 self.0
1380 .state
1381 .borrow()
1382 .client
1383 .0
1384 .upgrade()
1385 .map(|ref_cell| ref_cell.borrow().modifiers)
1386 .unwrap_or_default()
1387 }
1388
1389 fn capslock(&self) -> gpui::Capslock {
1390 self.0
1391 .state
1392 .borrow()
1393 .client
1394 .0
1395 .upgrade()
1396 .map(|ref_cell| ref_cell.borrow().capslock)
1397 .unwrap_or_default()
1398 }
1399
1400 fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
1401 self.0.state.borrow_mut().input_handler = Some(input_handler);
1402 }
1403
1404 fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
1405 self.0.state.borrow_mut().input_handler.take()
1406 }
1407
1408 fn prompt(
1409 &self,
1410 _level: PromptLevel,
1411 _msg: &str,
1412 _detail: Option<&str>,
1413 _answers: &[PromptButton],
1414 ) -> Option<futures::channel::oneshot::Receiver<usize>> {
1415 None
1416 }
1417
1418 fn activate(&self) {
1419 let data = [1, xproto::Time::CURRENT_TIME.into(), 0, 0, 0];
1420 let message = xproto::ClientMessageEvent::new(
1421 32,
1422 self.0.x_window,
1423 self.0.state.borrow().atoms._NET_ACTIVE_WINDOW,
1424 data,
1425 );
1426 self.0
1427 .xcb
1428 .send_event(
1429 false,
1430 self.0.state.borrow().x_root_window,
1431 xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
1432 message,
1433 )
1434 .log_err();
1435 self.0
1436 .xcb
1437 .set_input_focus(
1438 xproto::InputFocus::POINTER_ROOT,
1439 self.0.x_window,
1440 xproto::Time::CURRENT_TIME,
1441 )
1442 .log_err();
1443 xcb_flush(&self.0.xcb);
1444 }
1445
1446 fn is_active(&self) -> bool {
1447 self.0.state.borrow().active
1448 }
1449
1450 fn is_hovered(&self) -> bool {
1451 self.0.state.borrow().hovered
1452 }
1453
1454 fn set_title(&mut self, title: &str) {
1455 check_reply(
1456 || "X11 ChangeProperty8 on WM_NAME failed.",
1457 self.0.xcb.change_property8(
1458 xproto::PropMode::REPLACE,
1459 self.0.x_window,
1460 xproto::AtomEnum::WM_NAME,
1461 xproto::AtomEnum::STRING,
1462 title.as_bytes(),
1463 ),
1464 )
1465 .log_err();
1466
1467 check_reply(
1468 || "X11 ChangeProperty8 on _NET_WM_NAME failed.",
1469 self.0.xcb.change_property8(
1470 xproto::PropMode::REPLACE,
1471 self.0.x_window,
1472 self.0.state.borrow().atoms._NET_WM_NAME,
1473 self.0.state.borrow().atoms.UTF8_STRING,
1474 title.as_bytes(),
1475 ),
1476 )
1477 .log_err();
1478 xcb_flush(&self.0.xcb);
1479 }
1480
1481 fn set_app_id(&mut self, app_id: &str) {
1482 let mut data = Vec::with_capacity(app_id.len() * 2 + 1);
1483 data.extend(app_id.bytes()); // instance https://unix.stackexchange.com/a/494170
1484 data.push(b'\0');
1485 data.extend(app_id.bytes()); // class
1486
1487 check_reply(
1488 || "X11 ChangeProperty8 for WM_CLASS failed.",
1489 self.0.xcb.change_property8(
1490 xproto::PropMode::REPLACE,
1491 self.0.x_window,
1492 xproto::AtomEnum::WM_CLASS,
1493 xproto::AtomEnum::STRING,
1494 &data,
1495 ),
1496 )
1497 .log_err();
1498 }
1499
1500 fn map_window(&mut self) -> anyhow::Result<()> {
1501 check_reply(
1502 || "X11 MapWindow failed.",
1503 self.0.xcb.map_window(self.0.x_window),
1504 )?;
1505 Ok(())
1506 }
1507
1508 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
1509 let mut state = self.0.state.borrow_mut();
1510 state.background_appearance = background_appearance;
1511 let transparent = state.is_transparent();
1512 state.renderer.update_transparency(transparent);
1513 }
1514
1515 fn background_appearance(&self) -> WindowBackgroundAppearance {
1516 self.0.state.borrow().background_appearance
1517 }
1518
1519 fn is_subpixel_rendering_supported(&self) -> bool {
1520 self.0
1521 .state
1522 .borrow()
1523 .client
1524 .0
1525 .upgrade()
1526 .map(|ref_cell| {
1527 let state = ref_cell.borrow();
1528 state
1529 .gpu_context
1530 .borrow()
1531 .as_ref()
1532 .is_some_and(|ctx| ctx.supports_dual_source_blending())
1533 })
1534 .unwrap_or_default()
1535 }
1536
1537 fn minimize(&self) {
1538 let state = self.0.state.borrow();
1539 const WINDOW_ICONIC_STATE: u32 = 3;
1540 let message = ClientMessageEvent::new(
1541 32,
1542 self.0.x_window,
1543 state.atoms.WM_CHANGE_STATE,
1544 [WINDOW_ICONIC_STATE, 0, 0, 0, 0],
1545 );
1546 check_reply(
1547 || "X11 SendEvent to minimize window failed.",
1548 self.0.xcb.send_event(
1549 false,
1550 state.x_root_window,
1551 xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
1552 message,
1553 ),
1554 )
1555 .log_err();
1556 }
1557
1558 fn zoom(&self) {
1559 let state = self.0.state.borrow();
1560 self.set_wm_hints(
1561 || "X11 SendEvent to maximize a window failed.",
1562 WmHintPropertyState::Toggle,
1563 state.atoms._NET_WM_STATE_MAXIMIZED_VERT,
1564 state.atoms._NET_WM_STATE_MAXIMIZED_HORZ,
1565 )
1566 .log_err();
1567 }
1568
1569 fn toggle_fullscreen(&self) {
1570 let state = self.0.state.borrow();
1571 self.set_wm_hints(
1572 || "X11 SendEvent to fullscreen a window failed.",
1573 WmHintPropertyState::Toggle,
1574 state.atoms._NET_WM_STATE_FULLSCREEN,
1575 xproto::AtomEnum::NONE.into(),
1576 )
1577 .log_err();
1578 }
1579
1580 fn is_fullscreen(&self) -> bool {
1581 self.0.state.borrow().fullscreen
1582 }
1583
1584 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
1585 self.0.callbacks.borrow_mut().request_frame = Some(callback);
1586 }
1587
1588 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> gpui::DispatchEventResult>) {
1589 self.0.callbacks.borrow_mut().input = Some(callback);
1590 }
1591
1592 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1593 self.0.callbacks.borrow_mut().active_status_change = Some(callback);
1594 }
1595
1596 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1597 self.0.callbacks.borrow_mut().hovered_status_change = Some(callback);
1598 }
1599
1600 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
1601 self.0.callbacks.borrow_mut().resize = Some(callback);
1602 }
1603
1604 fn on_moved(&self, callback: Box<dyn FnMut()>) {
1605 self.0.callbacks.borrow_mut().moved = Some(callback);
1606 }
1607
1608 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
1609 self.0.callbacks.borrow_mut().should_close = Some(callback);
1610 }
1611
1612 fn on_close(&self, callback: Box<dyn FnOnce()>) {
1613 self.0.callbacks.borrow_mut().close = Some(callback);
1614 }
1615
1616 fn on_hit_test_window_control(&self, _callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
1617 }
1618
1619 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
1620 self.0.callbacks.borrow_mut().appearance_changed = Some(callback);
1621 }
1622
1623 fn on_button_layout_changed(&self, callback: Box<dyn FnMut()>) {
1624 self.0.callbacks.borrow_mut().button_layout_changed = Some(callback);
1625 }
1626
1627 fn draw(&self, scene: &Scene) {
1628 let mut inner = self.0.state.borrow_mut();
1629
1630 if inner.renderer.device_lost() {
1631 let raw_window = RawWindow {
1632 connection: as_raw_xcb_connection::AsRawXcbConnection::as_raw_xcb_connection(
1633 &*self.0.xcb,
1634 ) as *mut _,
1635 screen_id: inner.x_screen_index,
1636 window_id: self.0.x_window,
1637 visual_id: inner.visual_id,
1638 };
1639 inner.renderer.recover(&raw_window).unwrap_or_else(|err| {
1640 panic!(
1641 "GPU device lost and recovery failed. \
1642 This may happen after system suspend/resume. \
1643 Please restart the application.\n\nError: {err}"
1644 )
1645 });
1646
1647 // The current scene references atlas textures that were cleared during recovery.
1648 // Skip this frame and let the next frame rebuild the scene with fresh textures.
1649 inner.force_render_after_recovery = true;
1650 return;
1651 }
1652
1653 inner.renderer.draw(scene);
1654 }
1655
1656 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
1657 let inner = self.0.state.borrow();
1658 inner.renderer.sprite_atlas().clone()
1659 }
1660
1661 fn show_window_menu(&self, position: Point<Pixels>) {
1662 let state = self.0.state.borrow();
1663
1664 check_reply(
1665 || "X11 UngrabPointer failed.",
1666 self.0.xcb.ungrab_pointer(x11rb::CURRENT_TIME),
1667 )
1668 .log_err();
1669
1670 let Some(coords) = self.get_root_position(position).log_err() else {
1671 return;
1672 };
1673 let message = ClientMessageEvent::new(
1674 32,
1675 self.0.x_window,
1676 state.atoms._GTK_SHOW_WINDOW_MENU,
1677 [
1678 XINPUT_ALL_DEVICE_GROUPS as u32,
1679 coords.dst_x as u32,
1680 coords.dst_y as u32,
1681 0,
1682 0,
1683 ],
1684 );
1685 check_reply(
1686 || "X11 SendEvent to show window menu failed.",
1687 self.0.xcb.send_event(
1688 false,
1689 state.x_root_window,
1690 xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
1691 message,
1692 ),
1693 )
1694 .log_err();
1695 }
1696
1697 fn start_window_move(&self) {
1698 const MOVERESIZE_MOVE: u32 = 8;
1699 self.send_moveresize(MOVERESIZE_MOVE).log_err();
1700 }
1701
1702 fn start_window_resize(&self, edge: ResizeEdge) {
1703 self.send_moveresize(resize_edge_to_moveresize(edge))
1704 .log_err();
1705 }
1706
1707 fn window_decorations(&self) -> gpui::Decorations {
1708 let state = self.0.state.borrow();
1709
1710 // Client window decorations require compositor support
1711 if !state.client_side_decorations_supported {
1712 return Decorations::Server;
1713 }
1714
1715 match state.decorations {
1716 WindowDecorations::Server => Decorations::Server,
1717 WindowDecorations::Client => {
1718 let tiling = if state.fullscreen {
1719 Tiling::tiled()
1720 } else if let Some(edge_constraints) = &state.edge_constraints {
1721 edge_constraints.to_tiling()
1722 } else {
1723 // https://source.chromium.org/chromium/chromium/src/+/main:ui/ozone/platform/x11/x11_window.cc;l=2519;drc=1f14cc876cc5bf899d13284a12c451498219bb2d
1724 Tiling {
1725 top: state.maximized_vertical,
1726 bottom: state.maximized_vertical,
1727 left: state.maximized_horizontal,
1728 right: state.maximized_horizontal,
1729 }
1730 };
1731 Decorations::Client { tiling }
1732 }
1733 }
1734 }
1735
1736 fn set_client_inset(&self, inset: Pixels) {
1737 let mut state = self.0.state.borrow_mut();
1738
1739 let dp = (f32::from(inset) * state.scale_factor) as u32;
1740
1741 let insets = if state.fullscreen {
1742 [0, 0, 0, 0]
1743 } else if let Some(edge_constraints) = &state.edge_constraints {
1744 let left = if edge_constraints.left_tiled { 0 } else { dp };
1745 let top = if edge_constraints.top_tiled { 0 } else { dp };
1746 let right = if edge_constraints.right_tiled { 0 } else { dp };
1747 let bottom = if edge_constraints.bottom_tiled { 0 } else { dp };
1748
1749 [left, right, top, bottom]
1750 } else {
1751 let (left, right) = if state.maximized_horizontal {
1752 (0, 0)
1753 } else {
1754 (dp, dp)
1755 };
1756 let (top, bottom) = if state.maximized_vertical {
1757 (0, 0)
1758 } else {
1759 (dp, dp)
1760 };
1761 [left, right, top, bottom]
1762 };
1763
1764 if state.last_insets != insets {
1765 state.last_insets = insets;
1766
1767 check_reply(
1768 || "X11 ChangeProperty for _GTK_FRAME_EXTENTS failed.",
1769 self.0.xcb.change_property(
1770 xproto::PropMode::REPLACE,
1771 self.0.x_window,
1772 state.atoms._GTK_FRAME_EXTENTS,
1773 xproto::AtomEnum::CARDINAL,
1774 size_of::<u32>() as u8 * 8,
1775 4,
1776 bytemuck::cast_slice::<u32, u8>(&insets),
1777 ),
1778 )
1779 .log_err();
1780 }
1781 }
1782
1783 fn request_decorations(&self, mut decorations: gpui::WindowDecorations) {
1784 let mut state = self.0.state.borrow_mut();
1785
1786 if matches!(decorations, gpui::WindowDecorations::Client)
1787 && !state.client_side_decorations_supported
1788 {
1789 log::info!(
1790 "x11: no compositor present, falling back to server-side window decorations"
1791 );
1792 decorations = gpui::WindowDecorations::Server;
1793 }
1794
1795 // https://github.com/rust-windowing/winit/blob/master/src/platform_impl/linux/x11/util/hint.rs#L53-L87
1796 let hints_data: [u32; 5] = match decorations {
1797 WindowDecorations::Server => [1 << 1, 0, 1, 0, 0],
1798 WindowDecorations::Client => [1 << 1, 0, 0, 0, 0],
1799 };
1800
1801 let success = check_reply(
1802 || "X11 ChangeProperty for _MOTIF_WM_HINTS failed.",
1803 self.0.xcb.change_property(
1804 xproto::PropMode::REPLACE,
1805 self.0.x_window,
1806 state.atoms._MOTIF_WM_HINTS,
1807 state.atoms._MOTIF_WM_HINTS,
1808 size_of::<u32>() as u8 * 8,
1809 5,
1810 bytemuck::cast_slice::<u32, u8>(&hints_data),
1811 ),
1812 )
1813 .log_err();
1814
1815 let Some(()) = success else {
1816 return;
1817 };
1818
1819 match decorations {
1820 WindowDecorations::Server => {
1821 state.decorations = WindowDecorations::Server;
1822 let is_transparent = state.is_transparent();
1823 state.renderer.update_transparency(is_transparent);
1824 }
1825 WindowDecorations::Client => {
1826 state.decorations = WindowDecorations::Client;
1827 let is_transparent = state.is_transparent();
1828 state.renderer.update_transparency(is_transparent);
1829 }
1830 }
1831
1832 drop(state);
1833 let mut callbacks = self.0.callbacks.borrow_mut();
1834 if let Some(appearance_changed) = callbacks.appearance_changed.as_mut() {
1835 appearance_changed();
1836 }
1837 }
1838
1839 fn update_ime_position(&self, bounds: Bounds<Pixels>) {
1840 let state = self.0.state.borrow();
1841 let client = state.client.clone();
1842 drop(state);
1843 client.update_ime_position(bounds);
1844 }
1845
1846 fn gpu_specs(&self) -> Option<GpuSpecs> {
1847 self.0.state.borrow().renderer.gpu_specs().into()
1848 }
1849
1850 fn play_system_bell(&self) {
1851 // Volume 0% means don't increase or decrease from system volume
1852 let _ = self.0.xcb.bell(0);
1853 }
1854}