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