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