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                && let Some(title) = titlebar.title
 520            {
 521                check_reply(
 522                    || "X11 ChangeProperty8 on window title failed.",
 523                    xcb.change_property8(
 524                        xproto::PropMode::REPLACE,
 525                        x_window,
 526                        xproto::AtomEnum::WM_NAME,
 527                        xproto::AtomEnum::STRING,
 528                        title.as_bytes(),
 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
 682pub(crate) struct X11Window(pub X11WindowStatePtr);
 683
 684impl Drop for X11Window {
 685    fn drop(&mut self) {
 686        let mut state = self.0.state.borrow_mut();
 687        state.renderer.destroy();
 688
 689        let destroy_x_window = maybe!({
 690            check_reply(
 691                || "X11 DestroyWindow failure.",
 692                self.0.xcb.destroy_window(self.0.x_window),
 693            )?;
 694            xcb_flush(&self.0.xcb);
 695
 696            anyhow::Ok(())
 697        })
 698        .log_err();
 699
 700        if destroy_x_window.is_some() {
 701            // Mark window as destroyed so that we can filter out when X11 events
 702            // for it still come in.
 703            state.destroyed = true;
 704
 705            let this_ptr = self.0.clone();
 706            let client_ptr = state.client.clone();
 707            state
 708                .executor
 709                .spawn(async move {
 710                    this_ptr.close();
 711                    client_ptr.drop_window(this_ptr.x_window);
 712                })
 713                .detach();
 714        }
 715
 716        drop(state);
 717    }
 718}
 719
 720enum WmHintPropertyState {
 721    // Remove = 0,
 722    // Add = 1,
 723    Toggle = 2,
 724}
 725
 726impl X11Window {
 727    pub fn new(
 728        handle: AnyWindowHandle,
 729        client: X11ClientStatePtr,
 730        executor: ForegroundExecutor,
 731        gpu_context: &BladeContext,
 732        params: WindowParams,
 733        xcb: &Rc<XCBConnection>,
 734        client_side_decorations_supported: bool,
 735        x_main_screen_index: usize,
 736        x_window: xproto::Window,
 737        atoms: &XcbAtoms,
 738        scale_factor: f32,
 739        appearance: WindowAppearance,
 740    ) -> anyhow::Result<Self> {
 741        let ptr = X11WindowStatePtr {
 742            state: Rc::new(RefCell::new(X11WindowState::new(
 743                handle,
 744                client,
 745                executor,
 746                gpu_context,
 747                params,
 748                xcb,
 749                client_side_decorations_supported,
 750                x_main_screen_index,
 751                x_window,
 752                atoms,
 753                scale_factor,
 754                appearance,
 755            )?)),
 756            callbacks: Rc::new(RefCell::new(Callbacks::default())),
 757            xcb: xcb.clone(),
 758            x_window,
 759        };
 760
 761        let state = ptr.state.borrow_mut();
 762        ptr.set_wm_properties(state)?;
 763
 764        Ok(Self(ptr))
 765    }
 766
 767    fn set_wm_hints<C: Display + Send + Sync + 'static, F: FnOnce() -> C>(
 768        &self,
 769        failure_context: F,
 770        wm_hint_property_state: WmHintPropertyState,
 771        prop1: u32,
 772        prop2: u32,
 773    ) -> anyhow::Result<()> {
 774        let state = self.0.state.borrow();
 775        let message = ClientMessageEvent::new(
 776            32,
 777            self.0.x_window,
 778            state.atoms._NET_WM_STATE,
 779            [wm_hint_property_state as u32, prop1, prop2, 1, 0],
 780        );
 781        check_reply(
 782            failure_context,
 783            self.0.xcb.send_event(
 784                false,
 785                state.x_root_window,
 786                xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
 787                message,
 788            ),
 789        )?;
 790        xcb_flush(&self.0.xcb);
 791        Ok(())
 792    }
 793
 794    fn get_root_position(
 795        &self,
 796        position: Point<Pixels>,
 797    ) -> anyhow::Result<TranslateCoordinatesReply> {
 798        let state = self.0.state.borrow();
 799        get_reply(
 800            || "X11 TranslateCoordinates failed.",
 801            self.0.xcb.translate_coordinates(
 802                self.0.x_window,
 803                state.x_root_window,
 804                (position.x.0 * state.scale_factor) as i16,
 805                (position.y.0 * state.scale_factor) as i16,
 806            ),
 807        )
 808    }
 809
 810    fn send_moveresize(&self, flag: u32) -> anyhow::Result<()> {
 811        let state = self.0.state.borrow();
 812
 813        check_reply(
 814            || "X11 UngrabPointer before move/resize of window failed.",
 815            self.0.xcb.ungrab_pointer(x11rb::CURRENT_TIME),
 816        )?;
 817
 818        let pointer = get_reply(
 819            || "X11 QueryPointer before move/resize of window failed.",
 820            self.0.xcb.query_pointer(self.0.x_window),
 821        )?;
 822        let message = ClientMessageEvent::new(
 823            32,
 824            self.0.x_window,
 825            state.atoms._NET_WM_MOVERESIZE,
 826            [
 827                pointer.root_x as u32,
 828                pointer.root_y as u32,
 829                flag,
 830                0, // Left mouse button
 831                0,
 832            ],
 833        );
 834        check_reply(
 835            || "X11 SendEvent to move/resize window failed.",
 836            self.0.xcb.send_event(
 837                false,
 838                state.x_root_window,
 839                xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
 840                message,
 841            ),
 842        )?;
 843
 844        xcb_flush(&self.0.xcb);
 845        Ok(())
 846    }
 847}
 848
 849impl X11WindowStatePtr {
 850    pub fn should_close(&self) -> bool {
 851        let mut cb = self.callbacks.borrow_mut();
 852        if let Some(mut should_close) = cb.should_close.take() {
 853            let result = (should_close)();
 854            cb.should_close = Some(should_close);
 855            result
 856        } else {
 857            true
 858        }
 859    }
 860
 861    pub fn property_notify(&self, event: xproto::PropertyNotifyEvent) -> anyhow::Result<()> {
 862        let mut state = self.state.borrow_mut();
 863        if event.atom == state.atoms._NET_WM_STATE {
 864            self.set_wm_properties(state)?;
 865        } else if event.atom == state.atoms._GTK_EDGE_CONSTRAINTS {
 866            self.set_edge_constraints(state)?;
 867        }
 868        Ok(())
 869    }
 870
 871    fn set_edge_constraints(
 872        &self,
 873        mut state: std::cell::RefMut<X11WindowState>,
 874    ) -> anyhow::Result<()> {
 875        let reply = get_reply(
 876            || "X11 GetProperty for _GTK_EDGE_CONSTRAINTS failed.",
 877            self.xcb.get_property(
 878                false,
 879                self.x_window,
 880                state.atoms._GTK_EDGE_CONSTRAINTS,
 881                xproto::AtomEnum::CARDINAL,
 882                0,
 883                4,
 884            ),
 885        )?;
 886
 887        if reply.value_len != 0 {
 888            if let Ok(bytes) = reply.value[0..4].try_into() {
 889                let atom = u32::from_ne_bytes(bytes);
 890                let edge_constraints = EdgeConstraints::from_atom(atom);
 891                state.edge_constraints.replace(edge_constraints);
 892            } else {
 893                log::error!("Failed to parse GTK_EDGE_CONSTRAINTS");
 894            }
 895        }
 896
 897        Ok(())
 898    }
 899
 900    fn set_wm_properties(
 901        &self,
 902        mut state: std::cell::RefMut<X11WindowState>,
 903    ) -> anyhow::Result<()> {
 904        let reply = get_reply(
 905            || "X11 GetProperty for _NET_WM_STATE failed.",
 906            self.xcb.get_property(
 907                false,
 908                self.x_window,
 909                state.atoms._NET_WM_STATE,
 910                xproto::AtomEnum::ATOM,
 911                0,
 912                u32::MAX,
 913            ),
 914        )?;
 915
 916        let atoms = reply
 917            .value
 918            .chunks_exact(4)
 919            .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
 920
 921        state.active = false;
 922        state.fullscreen = false;
 923        state.maximized_vertical = false;
 924        state.maximized_horizontal = false;
 925        state.hidden = false;
 926
 927        for atom in atoms {
 928            if atom == state.atoms._NET_WM_STATE_FOCUSED {
 929                state.active = true;
 930            } else if atom == state.atoms._NET_WM_STATE_FULLSCREEN {
 931                state.fullscreen = true;
 932            } else if atom == state.atoms._NET_WM_STATE_MAXIMIZED_VERT {
 933                state.maximized_vertical = true;
 934            } else if atom == state.atoms._NET_WM_STATE_MAXIMIZED_HORZ {
 935                state.maximized_horizontal = true;
 936            } else if atom == state.atoms._NET_WM_STATE_HIDDEN {
 937                state.hidden = true;
 938            }
 939        }
 940
 941        Ok(())
 942    }
 943
 944    pub fn close(&self) {
 945        let mut callbacks = self.callbacks.borrow_mut();
 946        if let Some(fun) = callbacks.close.take() {
 947            fun()
 948        }
 949    }
 950
 951    pub fn refresh(&self, request_frame_options: RequestFrameOptions) {
 952        let mut cb = self.callbacks.borrow_mut();
 953        if let Some(ref mut fun) = cb.request_frame {
 954            fun(request_frame_options);
 955        }
 956    }
 957
 958    pub fn handle_input(&self, input: PlatformInput) {
 959        if let Some(ref mut fun) = self.callbacks.borrow_mut().input
 960            && !fun(input.clone()).propagate
 961        {
 962            return;
 963        }
 964        if let PlatformInput::KeyDown(event) = input {
 965            // only allow shift modifier when inserting text
 966            if event.keystroke.modifiers.is_subset_of(&Modifiers::shift()) {
 967                let mut state = self.state.borrow_mut();
 968                if let Some(mut input_handler) = state.input_handler.take() {
 969                    if let Some(key_char) = &event.keystroke.key_char {
 970                        drop(state);
 971                        input_handler.replace_text_in_range(None, key_char);
 972                        state = self.state.borrow_mut();
 973                    }
 974                    state.input_handler = Some(input_handler);
 975                }
 976            }
 977        }
 978    }
 979
 980    pub fn handle_ime_commit(&self, text: String) {
 981        let mut state = self.state.borrow_mut();
 982        if let Some(mut input_handler) = state.input_handler.take() {
 983            drop(state);
 984            input_handler.replace_text_in_range(None, &text);
 985            let mut state = self.state.borrow_mut();
 986            state.input_handler = Some(input_handler);
 987        }
 988    }
 989
 990    pub fn handle_ime_preedit(&self, text: String) {
 991        let mut state = self.state.borrow_mut();
 992        if let Some(mut input_handler) = state.input_handler.take() {
 993            drop(state);
 994            input_handler.replace_and_mark_text_in_range(None, &text, None);
 995            let mut state = self.state.borrow_mut();
 996            state.input_handler = Some(input_handler);
 997        }
 998    }
 999
1000    pub fn handle_ime_unmark(&self) {
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.unmark_text();
1005            let mut state = self.state.borrow_mut();
1006            state.input_handler = Some(input_handler);
1007        }
1008    }
1009
1010    pub fn handle_ime_delete(&self) {
1011        let mut state = self.state.borrow_mut();
1012        if let Some(mut input_handler) = state.input_handler.take() {
1013            drop(state);
1014            if let Some(marked) = input_handler.marked_text_range() {
1015                input_handler.replace_text_in_range(Some(marked), "");
1016            }
1017            let mut state = self.state.borrow_mut();
1018            state.input_handler = Some(input_handler);
1019        }
1020    }
1021
1022    pub fn get_ime_area(&self) -> Option<Bounds<Pixels>> {
1023        let mut state = self.state.borrow_mut();
1024        let mut bounds: Option<Bounds<Pixels>> = None;
1025        if let Some(mut input_handler) = state.input_handler.take() {
1026            drop(state);
1027            if let Some(selection) = input_handler.selected_text_range(true) {
1028                bounds = input_handler.bounds_for_range(selection.range);
1029            }
1030            let mut state = self.state.borrow_mut();
1031            state.input_handler = Some(input_handler);
1032        };
1033        bounds
1034    }
1035
1036    pub fn set_bounds(&self, bounds: Bounds<i32>) -> anyhow::Result<()> {
1037        let mut resize_args = None;
1038        let is_resize;
1039        {
1040            let mut state = self.state.borrow_mut();
1041            let bounds = bounds.map(|f| px(f as f32 / state.scale_factor));
1042
1043            is_resize = bounds.size.width != state.bounds.size.width
1044                || bounds.size.height != state.bounds.size.height;
1045
1046            // If it's a resize event (only width/height changed), we ignore `bounds.origin`
1047            // because it contains wrong values.
1048            if is_resize {
1049                state.bounds.size = bounds.size;
1050            } else {
1051                state.bounds = bounds;
1052            }
1053
1054            let gpu_size = query_render_extent(&self.xcb, self.x_window)?;
1055            if true {
1056                state.renderer.update_drawable_size(size(
1057                    DevicePixels(gpu_size.width as i32),
1058                    DevicePixels(gpu_size.height as i32),
1059                ));
1060                resize_args = Some((state.content_size(), state.scale_factor));
1061            }
1062            if let Some(value) = state.last_sync_counter.take() {
1063                check_reply(
1064                    || "X11 sync SetCounter failed.",
1065                    sync::set_counter(&self.xcb, state.counter_id, value),
1066                )?;
1067            }
1068        }
1069
1070        let mut callbacks = self.callbacks.borrow_mut();
1071        if let Some((content_size, scale_factor)) = resize_args
1072            && let Some(ref mut fun) = callbacks.resize
1073        {
1074            fun(content_size, scale_factor)
1075        }
1076
1077        if !is_resize && let Some(ref mut fun) = callbacks.moved {
1078            fun();
1079        }
1080
1081        Ok(())
1082    }
1083
1084    pub fn set_active(&self, focus: bool) {
1085        if let Some(ref mut fun) = self.callbacks.borrow_mut().active_status_change {
1086            fun(focus);
1087        }
1088    }
1089
1090    pub fn set_hovered(&self, focus: bool) {
1091        if let Some(ref mut fun) = self.callbacks.borrow_mut().hovered_status_change {
1092            fun(focus);
1093        }
1094    }
1095
1096    pub fn set_appearance(&mut self, appearance: WindowAppearance) {
1097        let mut state = self.state.borrow_mut();
1098        state.appearance = appearance;
1099        let is_transparent = state.is_transparent();
1100        state.renderer.update_transparency(is_transparent);
1101        state.appearance = appearance;
1102        drop(state);
1103        let mut callbacks = self.callbacks.borrow_mut();
1104        if let Some(ref mut fun) = callbacks.appearance_changed {
1105            (fun)()
1106        }
1107    }
1108}
1109
1110impl PlatformWindow for X11Window {
1111    fn bounds(&self) -> Bounds<Pixels> {
1112        self.0.state.borrow().bounds
1113    }
1114
1115    fn is_maximized(&self) -> bool {
1116        let state = self.0.state.borrow();
1117
1118        // A maximized window that gets minimized will still retain its maximized state.
1119        !state.hidden && state.maximized_vertical && state.maximized_horizontal
1120    }
1121
1122    fn window_bounds(&self) -> WindowBounds {
1123        let state = self.0.state.borrow();
1124        if self.is_maximized() {
1125            WindowBounds::Maximized(state.bounds)
1126        } else {
1127            WindowBounds::Windowed(state.bounds)
1128        }
1129    }
1130
1131    fn inner_window_bounds(&self) -> WindowBounds {
1132        let state = self.0.state.borrow();
1133        if self.is_maximized() {
1134            WindowBounds::Maximized(state.bounds)
1135        } else {
1136            let mut bounds = state.bounds;
1137            let [left, right, top, bottom] = state.last_insets;
1138
1139            let [left, right, top, bottom] = [
1140                Pixels((left as f32) / state.scale_factor),
1141                Pixels((right as f32) / state.scale_factor),
1142                Pixels((top as f32) / state.scale_factor),
1143                Pixels((bottom as f32) / state.scale_factor),
1144            ];
1145
1146            bounds.origin.x += left;
1147            bounds.origin.y += top;
1148            bounds.size.width -= left + right;
1149            bounds.size.height -= top + bottom;
1150
1151            WindowBounds::Windowed(bounds)
1152        }
1153    }
1154
1155    fn content_size(&self) -> Size<Pixels> {
1156        // We divide by the scale factor here because this value is queried to determine how much to draw,
1157        // but it will be multiplied later by the scale to adjust for scaling.
1158        let state = self.0.state.borrow();
1159        state
1160            .content_size()
1161            .map(|size| size.div(state.scale_factor))
1162    }
1163
1164    fn resize(&mut self, size: Size<Pixels>) {
1165        let state = self.0.state.borrow();
1166        let size = size.to_device_pixels(state.scale_factor);
1167        let width = size.width.0 as u32;
1168        let height = size.height.0 as u32;
1169
1170        check_reply(
1171            || {
1172                format!(
1173                    "X11 ConfigureWindow failed. width: {}, height: {}",
1174                    width, height
1175                )
1176            },
1177            self.0.xcb.configure_window(
1178                self.0.x_window,
1179                &xproto::ConfigureWindowAux::new()
1180                    .width(width)
1181                    .height(height),
1182            ),
1183        )
1184        .log_err();
1185        xcb_flush(&self.0.xcb);
1186    }
1187
1188    fn scale_factor(&self) -> f32 {
1189        self.0.state.borrow().scale_factor
1190    }
1191
1192    fn appearance(&self) -> WindowAppearance {
1193        self.0.state.borrow().appearance
1194    }
1195
1196    fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1197        Some(self.0.state.borrow().display.clone())
1198    }
1199
1200    fn mouse_position(&self) -> Point<Pixels> {
1201        get_reply(
1202            || "X11 QueryPointer failed.",
1203            self.0.xcb.query_pointer(self.0.x_window),
1204        )
1205        .log_err()
1206        .map_or(Point::new(Pixels(0.0), Pixels(0.0)), |reply| {
1207            Point::new((reply.root_x as u32).into(), (reply.root_y as u32).into())
1208        })
1209    }
1210
1211    fn modifiers(&self) -> Modifiers {
1212        self.0
1213            .state
1214            .borrow()
1215            .client
1216            .0
1217            .upgrade()
1218            .map(|ref_cell| ref_cell.borrow().modifiers)
1219            .unwrap_or_default()
1220    }
1221
1222    fn capslock(&self) -> crate::Capslock {
1223        self.0
1224            .state
1225            .borrow()
1226            .client
1227            .0
1228            .upgrade()
1229            .map(|ref_cell| ref_cell.borrow().capslock)
1230            .unwrap_or_default()
1231    }
1232
1233    fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
1234        self.0.state.borrow_mut().input_handler = Some(input_handler);
1235    }
1236
1237    fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
1238        self.0.state.borrow_mut().input_handler.take()
1239    }
1240
1241    fn prompt(
1242        &self,
1243        _level: PromptLevel,
1244        _msg: &str,
1245        _detail: Option<&str>,
1246        _answers: &[PromptButton],
1247    ) -> Option<futures::channel::oneshot::Receiver<usize>> {
1248        None
1249    }
1250
1251    fn activate(&self) {
1252        let data = [1, xproto::Time::CURRENT_TIME.into(), 0, 0, 0];
1253        let message = xproto::ClientMessageEvent::new(
1254            32,
1255            self.0.x_window,
1256            self.0.state.borrow().atoms._NET_ACTIVE_WINDOW,
1257            data,
1258        );
1259        self.0
1260            .xcb
1261            .send_event(
1262                false,
1263                self.0.state.borrow().x_root_window,
1264                xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
1265                message,
1266            )
1267            .log_err();
1268        self.0
1269            .xcb
1270            .set_input_focus(
1271                xproto::InputFocus::POINTER_ROOT,
1272                self.0.x_window,
1273                xproto::Time::CURRENT_TIME,
1274            )
1275            .log_err();
1276        xcb_flush(&self.0.xcb);
1277    }
1278
1279    fn is_active(&self) -> bool {
1280        self.0.state.borrow().active
1281    }
1282
1283    fn is_hovered(&self) -> bool {
1284        self.0.state.borrow().hovered
1285    }
1286
1287    fn set_title(&mut self, title: &str) {
1288        check_reply(
1289            || "X11 ChangeProperty8 on WM_NAME failed.",
1290            self.0.xcb.change_property8(
1291                xproto::PropMode::REPLACE,
1292                self.0.x_window,
1293                xproto::AtomEnum::WM_NAME,
1294                xproto::AtomEnum::STRING,
1295                title.as_bytes(),
1296            ),
1297        )
1298        .log_err();
1299
1300        check_reply(
1301            || "X11 ChangeProperty8 on _NET_WM_NAME failed.",
1302            self.0.xcb.change_property8(
1303                xproto::PropMode::REPLACE,
1304                self.0.x_window,
1305                self.0.state.borrow().atoms._NET_WM_NAME,
1306                self.0.state.borrow().atoms.UTF8_STRING,
1307                title.as_bytes(),
1308            ),
1309        )
1310        .log_err();
1311        xcb_flush(&self.0.xcb);
1312    }
1313
1314    fn set_app_id(&mut self, app_id: &str) {
1315        let mut data = Vec::with_capacity(app_id.len() * 2 + 1);
1316        data.extend(app_id.bytes()); // instance https://unix.stackexchange.com/a/494170
1317        data.push(b'\0');
1318        data.extend(app_id.bytes()); // class
1319
1320        check_reply(
1321            || "X11 ChangeProperty8 for WM_CLASS failed.",
1322            self.0.xcb.change_property8(
1323                xproto::PropMode::REPLACE,
1324                self.0.x_window,
1325                xproto::AtomEnum::WM_CLASS,
1326                xproto::AtomEnum::STRING,
1327                &data,
1328            ),
1329        )
1330        .log_err();
1331    }
1332
1333    fn map_window(&mut self) -> anyhow::Result<()> {
1334        check_reply(
1335            || "X11 MapWindow failed.",
1336            self.0.xcb.map_window(self.0.x_window),
1337        )?;
1338        Ok(())
1339    }
1340
1341    fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
1342        let mut state = self.0.state.borrow_mut();
1343        state.background_appearance = background_appearance;
1344        let transparent = state.is_transparent();
1345        state.renderer.update_transparency(transparent);
1346    }
1347
1348    fn minimize(&self) {
1349        let state = self.0.state.borrow();
1350        const WINDOW_ICONIC_STATE: u32 = 3;
1351        let message = ClientMessageEvent::new(
1352            32,
1353            self.0.x_window,
1354            state.atoms.WM_CHANGE_STATE,
1355            [WINDOW_ICONIC_STATE, 0, 0, 0, 0],
1356        );
1357        check_reply(
1358            || "X11 SendEvent to minimize window failed.",
1359            self.0.xcb.send_event(
1360                false,
1361                state.x_root_window,
1362                xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
1363                message,
1364            ),
1365        )
1366        .log_err();
1367    }
1368
1369    fn zoom(&self) {
1370        let state = self.0.state.borrow();
1371        self.set_wm_hints(
1372            || "X11 SendEvent to maximize a window failed.",
1373            WmHintPropertyState::Toggle,
1374            state.atoms._NET_WM_STATE_MAXIMIZED_VERT,
1375            state.atoms._NET_WM_STATE_MAXIMIZED_HORZ,
1376        )
1377        .log_err();
1378    }
1379
1380    fn toggle_fullscreen(&self) {
1381        let state = self.0.state.borrow();
1382        self.set_wm_hints(
1383            || "X11 SendEvent to fullscreen a window failed.",
1384            WmHintPropertyState::Toggle,
1385            state.atoms._NET_WM_STATE_FULLSCREEN,
1386            xproto::AtomEnum::NONE.into(),
1387        )
1388        .log_err();
1389    }
1390
1391    fn is_fullscreen(&self) -> bool {
1392        self.0.state.borrow().fullscreen
1393    }
1394
1395    fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
1396        self.0.callbacks.borrow_mut().request_frame = Some(callback);
1397    }
1398
1399    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>) {
1400        self.0.callbacks.borrow_mut().input = Some(callback);
1401    }
1402
1403    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1404        self.0.callbacks.borrow_mut().active_status_change = Some(callback);
1405    }
1406
1407    fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1408        self.0.callbacks.borrow_mut().hovered_status_change = Some(callback);
1409    }
1410
1411    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
1412        self.0.callbacks.borrow_mut().resize = Some(callback);
1413    }
1414
1415    fn on_moved(&self, callback: Box<dyn FnMut()>) {
1416        self.0.callbacks.borrow_mut().moved = Some(callback);
1417    }
1418
1419    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
1420        self.0.callbacks.borrow_mut().should_close = Some(callback);
1421    }
1422
1423    fn on_close(&self, callback: Box<dyn FnOnce()>) {
1424        self.0.callbacks.borrow_mut().close = Some(callback);
1425    }
1426
1427    fn on_hit_test_window_control(&self, _callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
1428    }
1429
1430    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
1431        self.0.callbacks.borrow_mut().appearance_changed = Some(callback);
1432    }
1433
1434    fn draw(&self, scene: &Scene) {
1435        let mut inner = self.0.state.borrow_mut();
1436        inner.renderer.draw(scene);
1437    }
1438
1439    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
1440        let inner = self.0.state.borrow();
1441        inner.renderer.sprite_atlas().clone()
1442    }
1443
1444    fn show_window_menu(&self, position: Point<Pixels>) {
1445        let state = self.0.state.borrow();
1446
1447        check_reply(
1448            || "X11 UngrabPointer failed.",
1449            self.0.xcb.ungrab_pointer(x11rb::CURRENT_TIME),
1450        )
1451        .log_err();
1452
1453        let Some(coords) = self.get_root_position(position).log_err() else {
1454            return;
1455        };
1456        let message = ClientMessageEvent::new(
1457            32,
1458            self.0.x_window,
1459            state.atoms._GTK_SHOW_WINDOW_MENU,
1460            [
1461                XINPUT_ALL_DEVICE_GROUPS as u32,
1462                coords.dst_x as u32,
1463                coords.dst_y as u32,
1464                0,
1465                0,
1466            ],
1467        );
1468        check_reply(
1469            || "X11 SendEvent to show window menu failed.",
1470            self.0.xcb.send_event(
1471                false,
1472                state.x_root_window,
1473                xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
1474                message,
1475            ),
1476        )
1477        .log_err();
1478    }
1479
1480    fn start_window_move(&self) {
1481        const MOVERESIZE_MOVE: u32 = 8;
1482        self.send_moveresize(MOVERESIZE_MOVE).log_err();
1483    }
1484
1485    fn start_window_resize(&self, edge: ResizeEdge) {
1486        self.send_moveresize(edge.to_moveresize()).log_err();
1487    }
1488
1489    fn window_decorations(&self) -> crate::Decorations {
1490        let state = self.0.state.borrow();
1491
1492        // Client window decorations require compositor support
1493        if !state.client_side_decorations_supported {
1494            return Decorations::Server;
1495        }
1496
1497        match state.decorations {
1498            WindowDecorations::Server => Decorations::Server,
1499            WindowDecorations::Client => {
1500                let tiling = if state.fullscreen {
1501                    Tiling::tiled()
1502                } else if let Some(edge_constraints) = &state.edge_constraints {
1503                    edge_constraints.to_tiling()
1504                } else {
1505                    // https://source.chromium.org/chromium/chromium/src/+/main:ui/ozone/platform/x11/x11_window.cc;l=2519;drc=1f14cc876cc5bf899d13284a12c451498219bb2d
1506                    Tiling {
1507                        top: state.maximized_vertical,
1508                        bottom: state.maximized_vertical,
1509                        left: state.maximized_horizontal,
1510                        right: state.maximized_horizontal,
1511                    }
1512                };
1513                Decorations::Client { tiling }
1514            }
1515        }
1516    }
1517
1518    fn set_client_inset(&self, inset: Pixels) {
1519        let mut state = self.0.state.borrow_mut();
1520
1521        let dp = (inset.0 * state.scale_factor) as u32;
1522
1523        let insets = if state.fullscreen {
1524            [0, 0, 0, 0]
1525        } else if let Some(edge_constraints) = &state.edge_constraints {
1526            let left = if edge_constraints.left_tiled { 0 } else { dp };
1527            let top = if edge_constraints.top_tiled { 0 } else { dp };
1528            let right = if edge_constraints.right_tiled { 0 } else { dp };
1529            let bottom = if edge_constraints.bottom_tiled { 0 } else { dp };
1530
1531            [left, right, top, bottom]
1532        } else {
1533            let (left, right) = if state.maximized_horizontal {
1534                (0, 0)
1535            } else {
1536                (dp, dp)
1537            };
1538            let (top, bottom) = if state.maximized_vertical {
1539                (0, 0)
1540            } else {
1541                (dp, dp)
1542            };
1543            [left, right, top, bottom]
1544        };
1545
1546        if state.last_insets != insets {
1547            state.last_insets = insets;
1548
1549            check_reply(
1550                || "X11 ChangeProperty for _GTK_FRAME_EXTENTS failed.",
1551                self.0.xcb.change_property(
1552                    xproto::PropMode::REPLACE,
1553                    self.0.x_window,
1554                    state.atoms._GTK_FRAME_EXTENTS,
1555                    xproto::AtomEnum::CARDINAL,
1556                    size_of::<u32>() as u8 * 8,
1557                    4,
1558                    bytemuck::cast_slice::<u32, u8>(&insets),
1559                ),
1560            )
1561            .log_err();
1562        }
1563    }
1564
1565    fn request_decorations(&self, mut decorations: crate::WindowDecorations) {
1566        let mut state = self.0.state.borrow_mut();
1567
1568        if matches!(decorations, crate::WindowDecorations::Client)
1569            && !state.client_side_decorations_supported
1570        {
1571            log::info!(
1572                "x11: no compositor present, falling back to server-side window decorations"
1573            );
1574            decorations = crate::WindowDecorations::Server;
1575        }
1576
1577        // https://github.com/rust-windowing/winit/blob/master/src/platform_impl/linux/x11/util/hint.rs#L53-L87
1578        let hints_data: [u32; 5] = match decorations {
1579            WindowDecorations::Server => [1 << 1, 0, 1, 0, 0],
1580            WindowDecorations::Client => [1 << 1, 0, 0, 0, 0],
1581        };
1582
1583        let success = check_reply(
1584            || "X11 ChangeProperty for _MOTIF_WM_HINTS failed.",
1585            self.0.xcb.change_property(
1586                xproto::PropMode::REPLACE,
1587                self.0.x_window,
1588                state.atoms._MOTIF_WM_HINTS,
1589                state.atoms._MOTIF_WM_HINTS,
1590                size_of::<u32>() as u8 * 8,
1591                5,
1592                bytemuck::cast_slice::<u32, u8>(&hints_data),
1593            ),
1594        )
1595        .log_err();
1596
1597        let Some(()) = success else {
1598            return;
1599        };
1600
1601        match decorations {
1602            WindowDecorations::Server => {
1603                state.decorations = WindowDecorations::Server;
1604                let is_transparent = state.is_transparent();
1605                state.renderer.update_transparency(is_transparent);
1606            }
1607            WindowDecorations::Client => {
1608                state.decorations = WindowDecorations::Client;
1609                let is_transparent = state.is_transparent();
1610                state.renderer.update_transparency(is_transparent);
1611            }
1612        }
1613
1614        drop(state);
1615        let mut callbacks = self.0.callbacks.borrow_mut();
1616        if let Some(appearance_changed) = callbacks.appearance_changed.as_mut() {
1617            appearance_changed();
1618        }
1619    }
1620
1621    fn update_ime_position(&self, bounds: Bounds<ScaledPixels>) {
1622        let mut state = self.0.state.borrow_mut();
1623        let client = state.client.clone();
1624        drop(state);
1625        client.update_ime_position(bounds);
1626    }
1627
1628    fn gpu_specs(&self) -> Option<GpuSpecs> {
1629        self.0.state.borrow().renderer.gpu_specs().into()
1630    }
1631}