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