window.rs

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