window.rs

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