window.rs

   1use anyhow::Context;
   2
   3use crate::{
   4    platform::blade::{BladeRenderer, BladeSurfaceConfig},
   5    px, size, AnyWindowHandle, Bounds, Decorations, DevicePixels, ForegroundExecutor, Modifiers,
   6    Pixels, PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow,
   7    Point, PromptLevel, ResizeEdge, Scene, Size, Tiling, WindowAppearance,
   8    WindowBackgroundAppearance, WindowBounds, WindowDecorations, WindowKind, WindowParams,
   9    X11ClientStatePtr,
  10};
  11
  12use blade_graphics as gpu;
  13use raw_window_handle as rwh;
  14use util::{maybe, ResultExt};
  15use x11rb::{
  16    connection::Connection,
  17    protocol::{
  18        randr::{self, ConnectionExt as _},
  19        sync,
  20        xinput::{self, ConnectionExt as _},
  21        xproto::{self, ClientMessageEvent, ConnectionExt, EventMask, TranslateCoordinatesReply},
  22    },
  23    wrapper::ConnectionExt as _,
  24    xcb_ffi::XCBConnection,
  25};
  26
  27use std::{
  28    cell::RefCell, ffi::c_void, mem::size_of, num::NonZeroU32, ops::Div, ptr::NonNull, rc::Rc,
  29    sync::Arc, time::Duration,
  30};
  31
  32use super::{X11Display, XINPUT_MASTER_DEVICE};
  33x11rb::atom_manager! {
  34    pub XcbAtoms: AtomsCookie {
  35        UTF8_STRING,
  36        WM_PROTOCOLS,
  37        WM_DELETE_WINDOW,
  38        WM_CHANGE_STATE,
  39        _NET_WM_NAME,
  40        _NET_WM_STATE,
  41        _NET_WM_STATE_MAXIMIZED_VERT,
  42        _NET_WM_STATE_MAXIMIZED_HORZ,
  43        _NET_WM_STATE_FULLSCREEN,
  44        _NET_WM_STATE_HIDDEN,
  45        _NET_WM_STATE_FOCUSED,
  46        _NET_ACTIVE_WINDOW,
  47        _NET_WM_SYNC_REQUEST,
  48        _NET_WM_SYNC_REQUEST_COUNTER,
  49        _NET_WM_BYPASS_COMPOSITOR,
  50        _NET_WM_MOVERESIZE,
  51        _NET_WM_WINDOW_TYPE,
  52        _NET_WM_WINDOW_TYPE_NOTIFICATION,
  53        _NET_WM_SYNC,
  54        _MOTIF_WM_HINTS,
  55        _GTK_SHOW_WINDOW_MENU,
  56        _GTK_FRAME_EXTENTS,
  57    }
  58}
  59
  60fn query_render_extent(xcb_connection: &XCBConnection, x_window: xproto::Window) -> gpu::Extent {
  61    let reply = xcb_connection
  62        .get_geometry(x_window)
  63        .unwrap()
  64        .reply()
  65        .unwrap();
  66    gpu::Extent {
  67        width: reply.width as u32,
  68        height: reply.height as u32,
  69        depth: 1,
  70    }
  71}
  72
  73impl ResizeEdge {
  74    fn to_moveresize(&self) -> u32 {
  75        match self {
  76            ResizeEdge::TopLeft => 0,
  77            ResizeEdge::Top => 1,
  78            ResizeEdge::TopRight => 2,
  79            ResizeEdge::Right => 3,
  80            ResizeEdge::BottomRight => 4,
  81            ResizeEdge::Bottom => 5,
  82            ResizeEdge::BottomLeft => 6,
  83            ResizeEdge::Left => 7,
  84        }
  85    }
  86}
  87
  88#[derive(Debug)]
  89struct Visual {
  90    id: xproto::Visualid,
  91    colormap: u32,
  92    depth: u8,
  93}
  94
  95struct VisualSet {
  96    inherit: Visual,
  97    opaque: Option<Visual>,
  98    transparent: Option<Visual>,
  99    root: u32,
 100    black_pixel: u32,
 101}
 102
 103fn find_visuals(xcb_connection: &XCBConnection, screen_index: usize) -> VisualSet {
 104    let screen = &xcb_connection.setup().roots[screen_index];
 105    let mut set = VisualSet {
 106        inherit: Visual {
 107            id: screen.root_visual,
 108            colormap: screen.default_colormap,
 109            depth: screen.root_depth,
 110        },
 111        opaque: None,
 112        transparent: None,
 113        root: screen.root,
 114        black_pixel: screen.black_pixel,
 115    };
 116
 117    for depth_info in screen.allowed_depths.iter() {
 118        for visual_type in depth_info.visuals.iter() {
 119            let visual = Visual {
 120                id: visual_type.visual_id,
 121                colormap: 0,
 122                depth: depth_info.depth,
 123            };
 124            log::debug!("Visual id: {}, class: {:?}, depth: {}, bits_per_value: {}, masks: 0x{:x} 0x{:x} 0x{:x}",
 125                visual_type.visual_id,
 126                visual_type.class,
 127                depth_info.depth,
 128                visual_type.bits_per_rgb_value,
 129                visual_type.red_mask, visual_type.green_mask, visual_type.blue_mask,
 130            );
 131
 132            if (
 133                visual_type.red_mask,
 134                visual_type.green_mask,
 135                visual_type.blue_mask,
 136            ) != (0xFF0000, 0xFF00, 0xFF)
 137            {
 138                continue;
 139            }
 140            let color_mask = visual_type.red_mask | visual_type.green_mask | visual_type.blue_mask;
 141            let alpha_mask = color_mask as usize ^ ((1usize << depth_info.depth) - 1);
 142
 143            if alpha_mask == 0 {
 144                if set.opaque.is_none() {
 145                    set.opaque = Some(visual);
 146                }
 147            } else {
 148                if set.transparent.is_none() {
 149                    set.transparent = Some(visual);
 150                }
 151            }
 152        }
 153    }
 154
 155    set
 156}
 157
 158struct RawWindow {
 159    connection: *mut c_void,
 160    screen_id: usize,
 161    window_id: u32,
 162    visual_id: u32,
 163}
 164
 165#[derive(Default)]
 166pub struct Callbacks {
 167    request_frame: Option<Box<dyn FnMut()>>,
 168    input: Option<Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>>,
 169    active_status_change: Option<Box<dyn FnMut(bool)>>,
 170    resize: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
 171    moved: Option<Box<dyn FnMut()>>,
 172    should_close: Option<Box<dyn FnMut() -> bool>>,
 173    close: Option<Box<dyn FnOnce()>>,
 174    appearance_changed: Option<Box<dyn FnMut()>>,
 175}
 176
 177pub struct X11WindowState {
 178    pub destroyed: bool,
 179    refresh_rate: Duration,
 180    client: X11ClientStatePtr,
 181    executor: ForegroundExecutor,
 182    atoms: XcbAtoms,
 183    x_root_window: xproto::Window,
 184    pub(crate) counter_id: sync::Counter,
 185    pub(crate) last_sync_counter: Option<sync::Int64>,
 186    _raw: RawWindow,
 187    bounds: Bounds<Pixels>,
 188    scale_factor: f32,
 189    renderer: BladeRenderer,
 190    display: Rc<dyn PlatformDisplay>,
 191    input_handler: Option<PlatformInputHandler>,
 192    appearance: WindowAppearance,
 193    background_appearance: WindowBackgroundAppearance,
 194    maximized_vertical: bool,
 195    maximized_horizontal: bool,
 196    hidden: bool,
 197    active: bool,
 198    fullscreen: bool,
 199    decorations: WindowDecorations,
 200    pub handle: AnyWindowHandle,
 201    last_insets: [u32; 4],
 202}
 203
 204impl X11WindowState {
 205    fn is_transparent(&self) -> bool {
 206        self.decorations == WindowDecorations::Client
 207            || self.background_appearance != WindowBackgroundAppearance::Opaque
 208    }
 209}
 210
 211#[derive(Clone)]
 212pub(crate) struct X11WindowStatePtr {
 213    pub state: Rc<RefCell<X11WindowState>>,
 214    pub(crate) callbacks: Rc<RefCell<Callbacks>>,
 215    xcb_connection: Rc<XCBConnection>,
 216    pub x_window: xproto::Window,
 217}
 218
 219impl rwh::HasWindowHandle for RawWindow {
 220    fn window_handle(&self) -> Result<rwh::WindowHandle, rwh::HandleError> {
 221        let non_zero = NonZeroU32::new(self.window_id).unwrap();
 222        let mut handle = rwh::XcbWindowHandle::new(non_zero);
 223        handle.visual_id = NonZeroU32::new(self.visual_id);
 224        Ok(unsafe { rwh::WindowHandle::borrow_raw(handle.into()) })
 225    }
 226}
 227impl rwh::HasDisplayHandle for RawWindow {
 228    fn display_handle(&self) -> Result<rwh::DisplayHandle, rwh::HandleError> {
 229        let non_zero = NonNull::new(self.connection).unwrap();
 230        let handle = rwh::XcbDisplayHandle::new(Some(non_zero), self.screen_id as i32);
 231        Ok(unsafe { rwh::DisplayHandle::borrow_raw(handle.into()) })
 232    }
 233}
 234
 235impl rwh::HasWindowHandle for X11Window {
 236    fn window_handle(&self) -> Result<rwh::WindowHandle, rwh::HandleError> {
 237        unimplemented!()
 238    }
 239}
 240impl rwh::HasDisplayHandle for X11Window {
 241    fn display_handle(&self) -> Result<rwh::DisplayHandle, rwh::HandleError> {
 242        unimplemented!()
 243    }
 244}
 245
 246impl X11WindowState {
 247    #[allow(clippy::too_many_arguments)]
 248    pub fn new(
 249        handle: AnyWindowHandle,
 250        client: X11ClientStatePtr,
 251        executor: ForegroundExecutor,
 252        params: WindowParams,
 253        xcb_connection: &Rc<XCBConnection>,
 254        x_main_screen_index: usize,
 255        x_window: xproto::Window,
 256        atoms: &XcbAtoms,
 257        scale_factor: f32,
 258        appearance: WindowAppearance,
 259    ) -> anyhow::Result<Self> {
 260        let x_screen_index = params
 261            .display_id
 262            .map_or(x_main_screen_index, |did| did.0 as usize);
 263
 264        let visual_set = find_visuals(&xcb_connection, x_screen_index);
 265
 266        let visual = match visual_set.transparent {
 267            Some(visual) => visual,
 268            None => {
 269                log::warn!("Unable to find a transparent visual",);
 270                visual_set.inherit
 271            }
 272        };
 273        log::info!("Using {:?}", visual);
 274
 275        let colormap = if visual.colormap != 0 {
 276            visual.colormap
 277        } else {
 278            let id = xcb_connection.generate_id().unwrap();
 279            log::info!("Creating colormap {}", id);
 280            xcb_connection
 281                .create_colormap(xproto::ColormapAlloc::NONE, id, visual_set.root, visual.id)
 282                .unwrap()
 283                .check()?;
 284            id
 285        };
 286
 287        let win_aux = xproto::CreateWindowAux::new()
 288            // https://stackoverflow.com/questions/43218127/x11-xlib-xcb-creating-a-window-requires-border-pixel-if-specifying-colormap-wh
 289            .border_pixel(visual_set.black_pixel)
 290            .colormap(colormap)
 291            .event_mask(
 292                xproto::EventMask::EXPOSURE
 293                    | xproto::EventMask::STRUCTURE_NOTIFY
 294                    | xproto::EventMask::FOCUS_CHANGE
 295                    | xproto::EventMask::KEY_PRESS
 296                    | xproto::EventMask::KEY_RELEASE
 297                    | EventMask::PROPERTY_CHANGE,
 298            );
 299
 300        let mut bounds = params.bounds.to_device_pixels(scale_factor);
 301        if bounds.size.width.0 == 0 || bounds.size.height.0 == 0 {
 302            log::warn!("Window bounds contain a zero value. height={}, width={}. Falling back to defaults.", bounds.size.height.0, bounds.size.width.0);
 303            bounds.size.width = 800.into();
 304            bounds.size.height = 600.into();
 305        }
 306
 307        xcb_connection
 308            .create_window(
 309                visual.depth,
 310                x_window,
 311                visual_set.root,
 312                (bounds.origin.x.0 + 2) as i16,
 313                bounds.origin.y.0 as i16,
 314                bounds.size.width.0 as u16,
 315                bounds.size.height.0 as u16,
 316                0,
 317                xproto::WindowClass::INPUT_OUTPUT,
 318                visual.id,
 319                &win_aux,
 320            )
 321            .unwrap()
 322            .check().with_context(|| {
 323                format!("CreateWindow request to X server failed. depth: {}, x_window: {}, visual_set.root: {}, bounds.origin.x.0: {}, bounds.origin.y.0: {}, bounds.size.width.0: {}, bounds.size.height.0: {}",
 324                    visual.depth, x_window, visual_set.root, bounds.origin.x.0 + 2, bounds.origin.y.0, bounds.size.width.0, bounds.size.height.0)
 325            })?;
 326
 327        let reply = xcb_connection
 328            .get_geometry(x_window)
 329            .unwrap()
 330            .reply()
 331            .unwrap();
 332        if reply.x == 0 && reply.y == 0 {
 333            bounds.origin.x.0 += 2;
 334            // Work around a bug where our rendered content appears
 335            // outside the window bounds when opened at the default position
 336            // (14px, 49px on X + Gnome + Ubuntu 22).
 337            xcb_connection
 338                .configure_window(
 339                    x_window,
 340                    &xproto::ConfigureWindowAux::new()
 341                        .x(bounds.origin.x.0)
 342                        .y(bounds.origin.y.0),
 343                )
 344                .unwrap();
 345        }
 346        if let Some(titlebar) = params.titlebar {
 347            if let Some(title) = titlebar.title {
 348                xcb_connection
 349                    .change_property8(
 350                        xproto::PropMode::REPLACE,
 351                        x_window,
 352                        xproto::AtomEnum::WM_NAME,
 353                        xproto::AtomEnum::STRING,
 354                        title.as_bytes(),
 355                    )
 356                    .unwrap();
 357            }
 358        }
 359        if params.kind == WindowKind::PopUp {
 360            xcb_connection
 361                .change_property32(
 362                    xproto::PropMode::REPLACE,
 363                    x_window,
 364                    atoms._NET_WM_WINDOW_TYPE,
 365                    xproto::AtomEnum::ATOM,
 366                    &[atoms._NET_WM_WINDOW_TYPE_NOTIFICATION],
 367                )
 368                .unwrap();
 369        }
 370
 371        xcb_connection
 372            .change_property32(
 373                xproto::PropMode::REPLACE,
 374                x_window,
 375                atoms.WM_PROTOCOLS,
 376                xproto::AtomEnum::ATOM,
 377                &[atoms.WM_DELETE_WINDOW, atoms._NET_WM_SYNC_REQUEST],
 378            )
 379            .unwrap();
 380
 381        sync::initialize(xcb_connection, 3, 1).unwrap();
 382        let sync_request_counter = xcb_connection.generate_id().unwrap();
 383        sync::create_counter(
 384            xcb_connection,
 385            sync_request_counter,
 386            sync::Int64 { lo: 0, hi: 0 },
 387        )
 388        .unwrap();
 389
 390        xcb_connection
 391            .change_property32(
 392                xproto::PropMode::REPLACE,
 393                x_window,
 394                atoms._NET_WM_SYNC_REQUEST_COUNTER,
 395                xproto::AtomEnum::CARDINAL,
 396                &[sync_request_counter],
 397            )
 398            .unwrap();
 399
 400        xcb_connection
 401            .xinput_xi_select_events(
 402                x_window,
 403                &[xinput::EventMask {
 404                    deviceid: XINPUT_MASTER_DEVICE,
 405                    mask: vec![
 406                        xinput::XIEventMask::MOTION
 407                            | xinput::XIEventMask::BUTTON_PRESS
 408                            | xinput::XIEventMask::BUTTON_RELEASE
 409                            | xinput::XIEventMask::LEAVE,
 410                    ],
 411                }],
 412            )
 413            .unwrap();
 414
 415        xcb_connection.flush().unwrap();
 416
 417        let raw = RawWindow {
 418            connection: as_raw_xcb_connection::AsRawXcbConnection::as_raw_xcb_connection(
 419                xcb_connection,
 420            ) as *mut _,
 421            screen_id: x_screen_index,
 422            window_id: x_window,
 423            visual_id: visual.id,
 424        };
 425        let gpu = Arc::new(
 426            unsafe {
 427                gpu::Context::init_windowed(
 428                    &raw,
 429                    gpu::ContextDesc {
 430                        validation: false,
 431                        capture: false,
 432                        overlay: false,
 433                    },
 434                )
 435            }
 436            .map_err(|e| anyhow::anyhow!("{:?}", e))?,
 437        );
 438
 439        let config = BladeSurfaceConfig {
 440            // Note: this has to be done after the GPU init, or otherwise
 441            // the sizes are immediately invalidated.
 442            size: query_render_extent(xcb_connection, x_window),
 443            // In case we have window decorations to render
 444            transparent: true,
 445        };
 446        xcb_connection.map_window(x_window).unwrap();
 447
 448        let screen_resources = xcb_connection
 449            .randr_get_screen_resources(x_window)
 450            .unwrap()
 451            .reply()
 452            .expect("Could not find available screens");
 453
 454        let mode = screen_resources
 455            .crtcs
 456            .iter()
 457            .find_map(|crtc| {
 458                let crtc_info = xcb_connection
 459                    .randr_get_crtc_info(*crtc, x11rb::CURRENT_TIME)
 460                    .ok()?
 461                    .reply()
 462                    .ok()?;
 463
 464                screen_resources
 465                    .modes
 466                    .iter()
 467                    .find(|m| m.id == crtc_info.mode)
 468            })
 469            .expect("Unable to find screen refresh rate");
 470
 471        let refresh_rate = mode_refresh_rate(&mode);
 472
 473        Ok(Self {
 474            client,
 475            executor,
 476            display: Rc::new(
 477                X11Display::new(xcb_connection, scale_factor, x_screen_index).unwrap(),
 478            ),
 479            _raw: raw,
 480            x_root_window: visual_set.root,
 481            bounds: bounds.to_pixels(scale_factor),
 482            scale_factor,
 483            renderer: BladeRenderer::new(gpu, config),
 484            atoms: *atoms,
 485            input_handler: None,
 486            active: false,
 487            fullscreen: false,
 488            maximized_vertical: false,
 489            maximized_horizontal: false,
 490            hidden: false,
 491            appearance,
 492            handle,
 493            background_appearance: WindowBackgroundAppearance::Opaque,
 494            destroyed: false,
 495            decorations: WindowDecorations::Server,
 496            last_insets: [0, 0, 0, 0],
 497            counter_id: sync_request_counter,
 498            last_sync_counter: None,
 499            refresh_rate,
 500        })
 501    }
 502
 503    fn content_size(&self) -> Size<Pixels> {
 504        let size = self.renderer.viewport_size();
 505        Size {
 506            width: size.width.into(),
 507            height: size.height.into(),
 508        }
 509    }
 510}
 511
 512pub(crate) struct X11Window(pub X11WindowStatePtr);
 513
 514impl Drop for X11Window {
 515    fn drop(&mut self) {
 516        let mut state = self.0.state.borrow_mut();
 517        state.renderer.destroy();
 518
 519        let destroy_x_window = maybe!({
 520            self.0.xcb_connection.unmap_window(self.0.x_window)?;
 521            self.0.xcb_connection.destroy_window(self.0.x_window)?;
 522            self.0.xcb_connection.flush()?;
 523
 524            anyhow::Ok(())
 525        })
 526        .context("unmapping and destroying X11 window")
 527        .log_err();
 528
 529        if destroy_x_window.is_some() {
 530            // Mark window as destroyed so that we can filter out when X11 events
 531            // for it still come in.
 532            state.destroyed = true;
 533
 534            let this_ptr = self.0.clone();
 535            let client_ptr = state.client.clone();
 536            state
 537                .executor
 538                .spawn(async move {
 539                    this_ptr.close();
 540                    client_ptr.drop_window(this_ptr.x_window);
 541                })
 542                .detach();
 543        }
 544
 545        drop(state);
 546    }
 547}
 548
 549enum WmHintPropertyState {
 550    // Remove = 0,
 551    // Add = 1,
 552    Toggle = 2,
 553}
 554
 555impl X11Window {
 556    #[allow(clippy::too_many_arguments)]
 557    pub fn new(
 558        handle: AnyWindowHandle,
 559        client: X11ClientStatePtr,
 560        executor: ForegroundExecutor,
 561        params: WindowParams,
 562        xcb_connection: &Rc<XCBConnection>,
 563        x_main_screen_index: usize,
 564        x_window: xproto::Window,
 565        atoms: &XcbAtoms,
 566        scale_factor: f32,
 567        appearance: WindowAppearance,
 568    ) -> anyhow::Result<Self> {
 569        let ptr = X11WindowStatePtr {
 570            state: Rc::new(RefCell::new(X11WindowState::new(
 571                handle,
 572                client,
 573                executor,
 574                params,
 575                xcb_connection,
 576                x_main_screen_index,
 577                x_window,
 578                atoms,
 579                scale_factor,
 580                appearance,
 581            )?)),
 582            callbacks: Rc::new(RefCell::new(Callbacks::default())),
 583            xcb_connection: xcb_connection.clone(),
 584            x_window,
 585        };
 586
 587        let state = ptr.state.borrow_mut();
 588        ptr.set_wm_properties(state);
 589
 590        Ok(Self(ptr))
 591    }
 592
 593    fn set_wm_hints(&self, wm_hint_property_state: WmHintPropertyState, prop1: u32, prop2: u32) {
 594        let state = self.0.state.borrow();
 595        let message = ClientMessageEvent::new(
 596            32,
 597            self.0.x_window,
 598            state.atoms._NET_WM_STATE,
 599            [wm_hint_property_state as u32, prop1, prop2, 1, 0],
 600        );
 601        self.0
 602            .xcb_connection
 603            .send_event(
 604                false,
 605                state.x_root_window,
 606                EventMask::SUBSTRUCTURE_REDIRECT | EventMask::SUBSTRUCTURE_NOTIFY,
 607                message,
 608            )
 609            .unwrap();
 610    }
 611
 612    fn get_root_position(&self, position: Point<Pixels>) -> TranslateCoordinatesReply {
 613        let state = self.0.state.borrow();
 614        self.0
 615            .xcb_connection
 616            .translate_coordinates(
 617                self.0.x_window,
 618                state.x_root_window,
 619                (position.x.0 * state.scale_factor) as i16,
 620                (position.y.0 * state.scale_factor) as i16,
 621            )
 622            .unwrap()
 623            .reply()
 624            .unwrap()
 625    }
 626
 627    fn send_moveresize(&self, flag: u32) {
 628        let state = self.0.state.borrow();
 629
 630        self.0
 631            .xcb_connection
 632            .ungrab_pointer(x11rb::CURRENT_TIME)
 633            .unwrap()
 634            .check()
 635            .unwrap();
 636
 637        let pointer = self
 638            .0
 639            .xcb_connection
 640            .query_pointer(self.0.x_window)
 641            .unwrap()
 642            .reply()
 643            .unwrap();
 644        let message = ClientMessageEvent::new(
 645            32,
 646            self.0.x_window,
 647            state.atoms._NET_WM_MOVERESIZE,
 648            [
 649                pointer.root_x as u32,
 650                pointer.root_y as u32,
 651                flag,
 652                0, // Left mouse button
 653                0,
 654            ],
 655        );
 656        self.0
 657            .xcb_connection
 658            .send_event(
 659                false,
 660                state.x_root_window,
 661                EventMask::SUBSTRUCTURE_REDIRECT | EventMask::SUBSTRUCTURE_NOTIFY,
 662                message,
 663            )
 664            .unwrap();
 665
 666        self.0.xcb_connection.flush().unwrap();
 667    }
 668}
 669
 670impl X11WindowStatePtr {
 671    pub fn should_close(&self) -> bool {
 672        let mut cb = self.callbacks.borrow_mut();
 673        if let Some(mut should_close) = cb.should_close.take() {
 674            let result = (should_close)();
 675            cb.should_close = Some(should_close);
 676            result
 677        } else {
 678            true
 679        }
 680    }
 681
 682    pub fn property_notify(&self, event: xproto::PropertyNotifyEvent) {
 683        let mut state = self.state.borrow_mut();
 684        if event.atom == state.atoms._NET_WM_STATE {
 685            self.set_wm_properties(state);
 686        }
 687    }
 688
 689    fn set_wm_properties(&self, mut state: std::cell::RefMut<X11WindowState>) {
 690        let reply = self
 691            .xcb_connection
 692            .get_property(
 693                false,
 694                self.x_window,
 695                state.atoms._NET_WM_STATE,
 696                xproto::AtomEnum::ATOM,
 697                0,
 698                u32::MAX,
 699            )
 700            .unwrap()
 701            .reply()
 702            .unwrap();
 703
 704        let atoms = reply
 705            .value
 706            .chunks_exact(4)
 707            .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
 708
 709        state.active = false;
 710        state.fullscreen = false;
 711        state.maximized_vertical = false;
 712        state.maximized_horizontal = false;
 713        state.hidden = true;
 714
 715        for atom in atoms {
 716            if atom == state.atoms._NET_WM_STATE_FOCUSED {
 717                state.active = true;
 718            } else if atom == state.atoms._NET_WM_STATE_FULLSCREEN {
 719                state.fullscreen = true;
 720            } else if atom == state.atoms._NET_WM_STATE_MAXIMIZED_VERT {
 721                state.maximized_vertical = true;
 722            } else if atom == state.atoms._NET_WM_STATE_MAXIMIZED_HORZ {
 723                state.maximized_horizontal = true;
 724            } else if atom == state.atoms._NET_WM_STATE_HIDDEN {
 725                state.hidden = true;
 726            }
 727        }
 728    }
 729
 730    pub fn close(&self) {
 731        let mut callbacks = self.callbacks.borrow_mut();
 732        if let Some(fun) = callbacks.close.take() {
 733            fun()
 734        }
 735    }
 736
 737    pub fn refresh(&self) {
 738        let mut cb = self.callbacks.borrow_mut();
 739        if let Some(ref mut fun) = cb.request_frame {
 740            fun();
 741        }
 742    }
 743
 744    pub fn handle_input(&self, input: PlatformInput) {
 745        if let Some(ref mut fun) = self.callbacks.borrow_mut().input {
 746            if !fun(input.clone()).propagate {
 747                return;
 748            }
 749        }
 750        if let PlatformInput::KeyDown(event) = input {
 751            let mut state = self.state.borrow_mut();
 752            if let Some(mut input_handler) = state.input_handler.take() {
 753                if let Some(ime_key) = &event.keystroke.ime_key {
 754                    drop(state);
 755                    input_handler.replace_text_in_range(None, ime_key);
 756                    state = self.state.borrow_mut();
 757                }
 758                state.input_handler = Some(input_handler);
 759            }
 760        }
 761    }
 762
 763    pub fn handle_ime_commit(&self, text: String) {
 764        let mut state = self.state.borrow_mut();
 765        if let Some(mut input_handler) = state.input_handler.take() {
 766            drop(state);
 767            input_handler.replace_text_in_range(None, &text);
 768            let mut state = self.state.borrow_mut();
 769            state.input_handler = Some(input_handler);
 770        }
 771    }
 772
 773    pub fn handle_ime_preedit(&self, text: String) {
 774        let mut state = self.state.borrow_mut();
 775        if let Some(mut input_handler) = state.input_handler.take() {
 776            drop(state);
 777            input_handler.replace_and_mark_text_in_range(None, &text, None);
 778            let mut state = self.state.borrow_mut();
 779            state.input_handler = Some(input_handler);
 780        }
 781    }
 782
 783    pub fn handle_ime_unmark(&self) {
 784        let mut state = self.state.borrow_mut();
 785        if let Some(mut input_handler) = state.input_handler.take() {
 786            drop(state);
 787            input_handler.unmark_text();
 788            let mut state = self.state.borrow_mut();
 789            state.input_handler = Some(input_handler);
 790        }
 791    }
 792
 793    pub fn handle_ime_delete(&self) {
 794        let mut state = self.state.borrow_mut();
 795        if let Some(mut input_handler) = state.input_handler.take() {
 796            drop(state);
 797            if let Some(marked) = input_handler.marked_text_range() {
 798                input_handler.replace_text_in_range(Some(marked), "");
 799            }
 800            let mut state = self.state.borrow_mut();
 801            state.input_handler = Some(input_handler);
 802        }
 803    }
 804
 805    pub fn get_ime_area(&self) -> Option<Bounds<Pixels>> {
 806        let mut state = self.state.borrow_mut();
 807        let mut bounds: Option<Bounds<Pixels>> = None;
 808        if let Some(mut input_handler) = state.input_handler.take() {
 809            drop(state);
 810            if let Some(range) = input_handler.selected_text_range() {
 811                bounds = input_handler.bounds_for_range(range);
 812            }
 813            let mut state = self.state.borrow_mut();
 814            state.input_handler = Some(input_handler);
 815        };
 816        bounds
 817    }
 818
 819    pub fn configure(&self, bounds: Bounds<i32>) {
 820        let mut resize_args = None;
 821        let is_resize;
 822        {
 823            let mut state = self.state.borrow_mut();
 824            let bounds = bounds.map(|f| px(f as f32 / state.scale_factor));
 825
 826            is_resize = bounds.size.width != state.bounds.size.width
 827                || bounds.size.height != state.bounds.size.height;
 828
 829            // If it's a resize event (only width/height changed), we ignore `bounds.origin`
 830            // because it contains wrong values.
 831            if is_resize {
 832                state.bounds.size = bounds.size;
 833            } else {
 834                state.bounds = bounds;
 835            }
 836
 837            let gpu_size = query_render_extent(&self.xcb_connection, self.x_window);
 838            if true {
 839                state.renderer.update_drawable_size(size(
 840                    DevicePixels(gpu_size.width as i32),
 841                    DevicePixels(gpu_size.height as i32),
 842                ));
 843                resize_args = Some((state.content_size(), state.scale_factor));
 844            }
 845            if let Some(value) = state.last_sync_counter.take() {
 846                sync::set_counter(&self.xcb_connection, state.counter_id, value).unwrap();
 847            }
 848        }
 849
 850        let mut callbacks = self.callbacks.borrow_mut();
 851        if let Some((content_size, scale_factor)) = resize_args {
 852            if let Some(ref mut fun) = callbacks.resize {
 853                fun(content_size, scale_factor)
 854            }
 855        }
 856        if !is_resize {
 857            if let Some(ref mut fun) = callbacks.moved {
 858                fun()
 859            }
 860        }
 861    }
 862
 863    pub fn set_focused(&self, focus: bool) {
 864        if let Some(ref mut fun) = self.callbacks.borrow_mut().active_status_change {
 865            fun(focus);
 866        }
 867    }
 868
 869    pub fn set_appearance(&mut self, appearance: WindowAppearance) {
 870        let mut state = self.state.borrow_mut();
 871        state.appearance = appearance;
 872        let is_transparent = state.is_transparent();
 873        state.renderer.update_transparency(is_transparent);
 874        state.appearance = appearance;
 875        drop(state);
 876        let mut callbacks = self.callbacks.borrow_mut();
 877        if let Some(ref mut fun) = callbacks.appearance_changed {
 878            (fun)()
 879        }
 880    }
 881
 882    pub fn refresh_rate(&self) -> Duration {
 883        self.state.borrow().refresh_rate
 884    }
 885}
 886
 887impl PlatformWindow for X11Window {
 888    fn bounds(&self) -> Bounds<Pixels> {
 889        self.0.state.borrow().bounds
 890    }
 891
 892    fn is_maximized(&self) -> bool {
 893        let state = self.0.state.borrow();
 894
 895        // A maximized window that gets minimized will still retain its maximized state.
 896        !state.hidden && state.maximized_vertical && state.maximized_horizontal
 897    }
 898
 899    fn window_bounds(&self) -> WindowBounds {
 900        let state = self.0.state.borrow();
 901        if self.is_maximized() {
 902            WindowBounds::Maximized(state.bounds)
 903        } else {
 904            WindowBounds::Windowed(state.bounds)
 905        }
 906    }
 907
 908    fn content_size(&self) -> Size<Pixels> {
 909        // We divide by the scale factor here because this value is queried to determine how much to draw,
 910        // but it will be multiplied later by the scale to adjust for scaling.
 911        let state = self.0.state.borrow();
 912        state
 913            .content_size()
 914            .map(|size| size.div(state.scale_factor))
 915    }
 916
 917    fn scale_factor(&self) -> f32 {
 918        self.0.state.borrow().scale_factor
 919    }
 920
 921    fn appearance(&self) -> WindowAppearance {
 922        self.0.state.borrow().appearance
 923    }
 924
 925    fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 926        Some(self.0.state.borrow().display.clone())
 927    }
 928
 929    fn mouse_position(&self) -> Point<Pixels> {
 930        let reply = self
 931            .0
 932            .xcb_connection
 933            .query_pointer(self.0.x_window)
 934            .unwrap()
 935            .reply()
 936            .unwrap();
 937        Point::new((reply.root_x as u32).into(), (reply.root_y as u32).into())
 938    }
 939
 940    fn modifiers(&self) -> Modifiers {
 941        self.0
 942            .state
 943            .borrow()
 944            .client
 945            .0
 946            .upgrade()
 947            .map(|ref_cell| ref_cell.borrow().modifiers)
 948            .unwrap_or_default()
 949    }
 950
 951    fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
 952        self.0.state.borrow_mut().input_handler = Some(input_handler);
 953    }
 954
 955    fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
 956        self.0.state.borrow_mut().input_handler.take()
 957    }
 958
 959    fn prompt(
 960        &self,
 961        _level: PromptLevel,
 962        _msg: &str,
 963        _detail: Option<&str>,
 964        _answers: &[&str],
 965    ) -> Option<futures::channel::oneshot::Receiver<usize>> {
 966        None
 967    }
 968
 969    fn activate(&self) {
 970        let data = [1, xproto::Time::CURRENT_TIME.into(), 0, 0, 0];
 971        let message = xproto::ClientMessageEvent::new(
 972            32,
 973            self.0.x_window,
 974            self.0.state.borrow().atoms._NET_ACTIVE_WINDOW,
 975            data,
 976        );
 977        self.0
 978            .xcb_connection
 979            .send_event(
 980                false,
 981                self.0.state.borrow().x_root_window,
 982                xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
 983                message,
 984            )
 985            .log_err();
 986        self.0
 987            .xcb_connection
 988            .set_input_focus(
 989                xproto::InputFocus::POINTER_ROOT,
 990                self.0.x_window,
 991                xproto::Time::CURRENT_TIME,
 992            )
 993            .log_err();
 994    }
 995
 996    fn is_active(&self) -> bool {
 997        self.0.state.borrow().active
 998    }
 999
1000    fn set_title(&mut self, title: &str) {
1001        self.0
1002            .xcb_connection
1003            .change_property8(
1004                xproto::PropMode::REPLACE,
1005                self.0.x_window,
1006                xproto::AtomEnum::WM_NAME,
1007                xproto::AtomEnum::STRING,
1008                title.as_bytes(),
1009            )
1010            .unwrap();
1011
1012        self.0
1013            .xcb_connection
1014            .change_property8(
1015                xproto::PropMode::REPLACE,
1016                self.0.x_window,
1017                self.0.state.borrow().atoms._NET_WM_NAME,
1018                self.0.state.borrow().atoms.UTF8_STRING,
1019                title.as_bytes(),
1020            )
1021            .unwrap();
1022    }
1023
1024    fn set_app_id(&mut self, app_id: &str) {
1025        let mut data = Vec::with_capacity(app_id.len() * 2 + 1);
1026        data.extend(app_id.bytes()); // instance https://unix.stackexchange.com/a/494170
1027        data.push(b'\0');
1028        data.extend(app_id.bytes()); // class
1029
1030        self.0
1031            .xcb_connection
1032            .change_property8(
1033                xproto::PropMode::REPLACE,
1034                self.0.x_window,
1035                xproto::AtomEnum::WM_CLASS,
1036                xproto::AtomEnum::STRING,
1037                &data,
1038            )
1039            .unwrap();
1040    }
1041
1042    fn set_edited(&mut self, _edited: bool) {
1043        log::info!("ignoring macOS specific set_edited");
1044    }
1045
1046    fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
1047        let mut state = self.0.state.borrow_mut();
1048        state.background_appearance = background_appearance;
1049        let transparent = state.is_transparent();
1050        state.renderer.update_transparency(transparent);
1051    }
1052
1053    fn show_character_palette(&self) {
1054        log::info!("ignoring macOS specific show_character_palette");
1055    }
1056
1057    fn minimize(&self) {
1058        let state = self.0.state.borrow();
1059        const WINDOW_ICONIC_STATE: u32 = 3;
1060        let message = ClientMessageEvent::new(
1061            32,
1062            self.0.x_window,
1063            state.atoms.WM_CHANGE_STATE,
1064            [WINDOW_ICONIC_STATE, 0, 0, 0, 0],
1065        );
1066        self.0
1067            .xcb_connection
1068            .send_event(
1069                false,
1070                state.x_root_window,
1071                EventMask::SUBSTRUCTURE_REDIRECT | EventMask::SUBSTRUCTURE_NOTIFY,
1072                message,
1073            )
1074            .unwrap();
1075    }
1076
1077    fn zoom(&self) {
1078        let state = self.0.state.borrow();
1079        self.set_wm_hints(
1080            WmHintPropertyState::Toggle,
1081            state.atoms._NET_WM_STATE_MAXIMIZED_VERT,
1082            state.atoms._NET_WM_STATE_MAXIMIZED_HORZ,
1083        );
1084    }
1085
1086    fn toggle_fullscreen(&self) {
1087        let state = self.0.state.borrow();
1088        self.set_wm_hints(
1089            WmHintPropertyState::Toggle,
1090            state.atoms._NET_WM_STATE_FULLSCREEN,
1091            xproto::AtomEnum::NONE.into(),
1092        );
1093    }
1094
1095    fn is_fullscreen(&self) -> bool {
1096        self.0.state.borrow().fullscreen
1097    }
1098
1099    fn on_request_frame(&self, callback: Box<dyn FnMut()>) {
1100        self.0.callbacks.borrow_mut().request_frame = Some(callback);
1101    }
1102
1103    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>) {
1104        self.0.callbacks.borrow_mut().input = Some(callback);
1105    }
1106
1107    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1108        self.0.callbacks.borrow_mut().active_status_change = Some(callback);
1109    }
1110
1111    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
1112        self.0.callbacks.borrow_mut().resize = Some(callback);
1113    }
1114
1115    fn on_moved(&self, callback: Box<dyn FnMut()>) {
1116        self.0.callbacks.borrow_mut().moved = Some(callback);
1117    }
1118
1119    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
1120        self.0.callbacks.borrow_mut().should_close = Some(callback);
1121    }
1122
1123    fn on_close(&self, callback: Box<dyn FnOnce()>) {
1124        self.0.callbacks.borrow_mut().close = Some(callback);
1125    }
1126
1127    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
1128        self.0.callbacks.borrow_mut().appearance_changed = Some(callback);
1129    }
1130
1131    fn draw(&self, scene: &Scene) {
1132        let mut inner = self.0.state.borrow_mut();
1133        inner.renderer.draw(scene);
1134    }
1135
1136    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
1137        let inner = self.0.state.borrow();
1138        inner.renderer.sprite_atlas().clone()
1139    }
1140
1141    fn show_window_menu(&self, position: Point<Pixels>) {
1142        let state = self.0.state.borrow();
1143        let coords = self.get_root_position(position);
1144        let message = ClientMessageEvent::new(
1145            32,
1146            self.0.x_window,
1147            state.atoms._GTK_SHOW_WINDOW_MENU,
1148            [
1149                XINPUT_MASTER_DEVICE as u32,
1150                coords.dst_x as u32,
1151                coords.dst_y as u32,
1152                0,
1153                0,
1154            ],
1155        );
1156        self.0
1157            .xcb_connection
1158            .send_event(
1159                false,
1160                state.x_root_window,
1161                EventMask::SUBSTRUCTURE_REDIRECT | EventMask::SUBSTRUCTURE_NOTIFY,
1162                message,
1163            )
1164            .unwrap();
1165    }
1166
1167    fn start_window_move(&self) {
1168        const MOVERESIZE_MOVE: u32 = 8;
1169        self.send_moveresize(MOVERESIZE_MOVE);
1170    }
1171
1172    fn start_window_resize(&self, edge: ResizeEdge) {
1173        self.send_moveresize(edge.to_moveresize());
1174    }
1175
1176    fn window_decorations(&self) -> crate::Decorations {
1177        let state = self.0.state.borrow();
1178
1179        match state.decorations {
1180            WindowDecorations::Server => Decorations::Server,
1181            WindowDecorations::Client => {
1182                // https://source.chromium.org/chromium/chromium/src/+/main:ui/ozone/platform/x11/x11_window.cc;l=2519;drc=1f14cc876cc5bf899d13284a12c451498219bb2d
1183                Decorations::Client {
1184                    tiling: Tiling {
1185                        top: state.maximized_vertical,
1186                        bottom: state.maximized_vertical,
1187                        left: state.maximized_horizontal,
1188                        right: state.maximized_horizontal,
1189                    },
1190                }
1191            }
1192        }
1193    }
1194
1195    fn set_client_inset(&self, inset: Pixels) {
1196        let mut state = self.0.state.borrow_mut();
1197
1198        let dp = (inset.0 * state.scale_factor) as u32;
1199
1200        let (left, right) = if state.maximized_horizontal {
1201            (0, 0)
1202        } else {
1203            (dp, dp)
1204        };
1205        let (top, bottom) = if state.maximized_vertical {
1206            (0, 0)
1207        } else {
1208            (dp, dp)
1209        };
1210        let insets = [left, right, top, bottom];
1211
1212        if state.last_insets != insets {
1213            state.last_insets = insets;
1214
1215            self.0
1216                .xcb_connection
1217                .change_property(
1218                    xproto::PropMode::REPLACE,
1219                    self.0.x_window,
1220                    state.atoms._GTK_FRAME_EXTENTS,
1221                    xproto::AtomEnum::CARDINAL,
1222                    size_of::<u32>() as u8 * 8,
1223                    4,
1224                    bytemuck::cast_slice::<u32, u8>(&insets),
1225                )
1226                .unwrap();
1227        }
1228    }
1229
1230    fn request_decorations(&self, decorations: crate::WindowDecorations) {
1231        // https://github.com/rust-windowing/winit/blob/master/src/platform_impl/linux/x11/util/hint.rs#L53-L87
1232        let hints_data: [u32; 5] = match decorations {
1233            WindowDecorations::Server => [1 << 1, 0, 1, 0, 0],
1234            WindowDecorations::Client => [1 << 1, 0, 0, 0, 0],
1235        };
1236
1237        let mut state = self.0.state.borrow_mut();
1238
1239        self.0
1240            .xcb_connection
1241            .change_property(
1242                xproto::PropMode::REPLACE,
1243                self.0.x_window,
1244                state.atoms._MOTIF_WM_HINTS,
1245                state.atoms._MOTIF_WM_HINTS,
1246                std::mem::size_of::<u32>() as u8 * 8,
1247                5,
1248                bytemuck::cast_slice::<u32, u8>(&hints_data),
1249            )
1250            .unwrap();
1251
1252        match decorations {
1253            WindowDecorations::Server => {
1254                state.decorations = WindowDecorations::Server;
1255                let is_transparent = state.is_transparent();
1256                state.renderer.update_transparency(is_transparent);
1257            }
1258            WindowDecorations::Client => {
1259                state.decorations = WindowDecorations::Client;
1260                let is_transparent = state.is_transparent();
1261                state.renderer.update_transparency(is_transparent);
1262            }
1263        }
1264
1265        drop(state);
1266        let mut callbacks = self.0.callbacks.borrow_mut();
1267        if let Some(appearance_changed) = callbacks.appearance_changed.as_mut() {
1268            appearance_changed();
1269        }
1270    }
1271}
1272
1273// Adapted from:
1274// https://docs.rs/winit/0.29.11/src/winit/platform_impl/linux/x11/monitor.rs.html#103-111
1275pub fn mode_refresh_rate(mode: &randr::ModeInfo) -> Duration {
1276    if mode.dot_clock == 0 || mode.htotal == 0 || mode.vtotal == 0 {
1277        return Duration::from_millis(16);
1278    }
1279
1280    let millihertz = mode.dot_clock as u64 * 1_000 / (mode.htotal as u64 * mode.vtotal as u64);
1281    let micros = 1_000_000_000 / millihertz;
1282    log::info!("Refreshing at {} micros", micros);
1283    Duration::from_micros(micros)
1284}