window.rs

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