window.rs

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