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