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