window.rs

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