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        _GTK_EDGE_CONSTRAINTS,
  58    }
  59}
  60
  61fn query_render_extent(xcb_connection: &XCBConnection, x_window: xproto::Window) -> gpu::Extent {
  62    let reply = xcb_connection
  63        .get_geometry(x_window)
  64        .unwrap()
  65        .reply()
  66        .unwrap();
  67    gpu::Extent {
  68        width: reply.width as u32,
  69        height: reply.height as u32,
  70        depth: 1,
  71    }
  72}
  73
  74impl ResizeEdge {
  75    fn to_moveresize(&self) -> u32 {
  76        match self {
  77            ResizeEdge::TopLeft => 0,
  78            ResizeEdge::Top => 1,
  79            ResizeEdge::TopRight => 2,
  80            ResizeEdge::Right => 3,
  81            ResizeEdge::BottomRight => 4,
  82            ResizeEdge::Bottom => 5,
  83            ResizeEdge::BottomLeft => 6,
  84            ResizeEdge::Left => 7,
  85        }
  86    }
  87}
  88
  89#[derive(Debug)]
  90struct Visual {
  91    id: xproto::Visualid,
  92    colormap: u32,
  93    depth: u8,
  94}
  95
  96struct VisualSet {
  97    inherit: Visual,
  98    opaque: Option<Visual>,
  99    transparent: Option<Visual>,
 100    root: u32,
 101    black_pixel: u32,
 102}
 103
 104fn find_visuals(xcb_connection: &XCBConnection, screen_index: usize) -> VisualSet {
 105    let screen = &xcb_connection.setup().roots[screen_index];
 106    let mut set = VisualSet {
 107        inherit: Visual {
 108            id: screen.root_visual,
 109            colormap: screen.default_colormap,
 110            depth: screen.root_depth,
 111        },
 112        opaque: None,
 113        transparent: None,
 114        root: screen.root,
 115        black_pixel: screen.black_pixel,
 116    };
 117
 118    for depth_info in screen.allowed_depths.iter() {
 119        for visual_type in depth_info.visuals.iter() {
 120            let visual = Visual {
 121                id: visual_type.visual_id,
 122                colormap: 0,
 123                depth: depth_info.depth,
 124            };
 125            log::debug!("Visual id: {}, class: {:?}, depth: {}, bits_per_value: {}, masks: 0x{:x} 0x{:x} 0x{:x}",
 126                visual_type.visual_id,
 127                visual_type.class,
 128                depth_info.depth,
 129                visual_type.bits_per_rgb_value,
 130                visual_type.red_mask, visual_type.green_mask, visual_type.blue_mask,
 131            );
 132
 133            if (
 134                visual_type.red_mask,
 135                visual_type.green_mask,
 136                visual_type.blue_mask,
 137            ) != (0xFF0000, 0xFF00, 0xFF)
 138            {
 139                continue;
 140            }
 141            let color_mask = visual_type.red_mask | visual_type.green_mask | visual_type.blue_mask;
 142            let alpha_mask = color_mask as usize ^ ((1usize << depth_info.depth) - 1);
 143
 144            if alpha_mask == 0 {
 145                if set.opaque.is_none() {
 146                    set.opaque = Some(visual);
 147                }
 148            } else {
 149                if set.transparent.is_none() {
 150                    set.transparent = Some(visual);
 151                }
 152            }
 153        }
 154    }
 155
 156    set
 157}
 158
 159struct RawWindow {
 160    connection: *mut c_void,
 161    screen_id: usize,
 162    window_id: u32,
 163    visual_id: u32,
 164}
 165
 166#[derive(Default)]
 167pub struct Callbacks {
 168    request_frame: Option<Box<dyn FnMut()>>,
 169    input: Option<Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>>,
 170    active_status_change: Option<Box<dyn FnMut(bool)>>,
 171    resize: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
 172    moved: Option<Box<dyn FnMut()>>,
 173    should_close: Option<Box<dyn FnMut() -> bool>>,
 174    close: Option<Box<dyn FnOnce()>>,
 175    appearance_changed: Option<Box<dyn FnMut()>>,
 176}
 177
 178pub struct X11WindowState {
 179    pub destroyed: bool,
 180    refresh_rate: Duration,
 181    client: X11ClientStatePtr,
 182    executor: ForegroundExecutor,
 183    atoms: XcbAtoms,
 184    x_root_window: xproto::Window,
 185    pub(crate) counter_id: sync::Counter,
 186    pub(crate) last_sync_counter: Option<sync::Int64>,
 187    _raw: RawWindow,
 188    bounds: Bounds<Pixels>,
 189    scale_factor: f32,
 190    renderer: BladeRenderer,
 191    display: Rc<dyn PlatformDisplay>,
 192    input_handler: Option<PlatformInputHandler>,
 193    appearance: WindowAppearance,
 194    background_appearance: WindowBackgroundAppearance,
 195    maximized_vertical: bool,
 196    maximized_horizontal: bool,
 197    hidden: bool,
 198    active: bool,
 199    fullscreen: bool,
 200    decorations: WindowDecorations,
 201    pub handle: AnyWindowHandle,
 202    last_insets: [u32; 4],
 203}
 204
 205impl X11WindowState {
 206    fn is_transparent(&self) -> bool {
 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            // We set it to transparent by default, even if we have client-side
 444            // decorations, since those seem to work on X11 even without `true` here.
 445            // If the window appearance changes, then the renderer will get updated
 446            // too
 447            transparent: false,
 448        };
 449        xcb_connection.map_window(x_window).unwrap();
 450
 451        let screen_resources = xcb_connection
 452            .randr_get_screen_resources(x_window)
 453            .unwrap()
 454            .reply()
 455            .expect("Could not find available screens");
 456
 457        let mode = screen_resources
 458            .crtcs
 459            .iter()
 460            .find_map(|crtc| {
 461                let crtc_info = xcb_connection
 462                    .randr_get_crtc_info(*crtc, x11rb::CURRENT_TIME)
 463                    .ok()?
 464                    .reply()
 465                    .ok()?;
 466
 467                screen_resources
 468                    .modes
 469                    .iter()
 470                    .find(|m| m.id == crtc_info.mode)
 471            })
 472            .expect("Unable to find screen refresh rate");
 473
 474        let refresh_rate = mode_refresh_rate(&mode);
 475
 476        Ok(Self {
 477            client,
 478            executor,
 479            display: Rc::new(
 480                X11Display::new(xcb_connection, scale_factor, x_screen_index).unwrap(),
 481            ),
 482            _raw: raw,
 483            x_root_window: visual_set.root,
 484            bounds: bounds.to_pixels(scale_factor),
 485            scale_factor,
 486            renderer: BladeRenderer::new(gpu, config),
 487            atoms: *atoms,
 488            input_handler: None,
 489            active: false,
 490            fullscreen: false,
 491            maximized_vertical: false,
 492            maximized_horizontal: false,
 493            hidden: false,
 494            appearance,
 495            handle,
 496            background_appearance: WindowBackgroundAppearance::Opaque,
 497            destroyed: false,
 498            decorations: WindowDecorations::Server,
 499            last_insets: [0, 0, 0, 0],
 500            counter_id: sync_request_counter,
 501            last_sync_counter: None,
 502            refresh_rate,
 503        })
 504    }
 505
 506    fn content_size(&self) -> Size<Pixels> {
 507        let size = self.renderer.viewport_size();
 508        Size {
 509            width: size.width.into(),
 510            height: size.height.into(),
 511        }
 512    }
 513}
 514
 515pub(crate) struct X11Window(pub X11WindowStatePtr);
 516
 517impl Drop for X11Window {
 518    fn drop(&mut self) {
 519        let mut state = self.0.state.borrow_mut();
 520        state.renderer.destroy();
 521
 522        let destroy_x_window = maybe!({
 523            self.0.xcb_connection.unmap_window(self.0.x_window)?;
 524            self.0.xcb_connection.destroy_window(self.0.x_window)?;
 525            self.0.xcb_connection.flush()?;
 526
 527            anyhow::Ok(())
 528        })
 529        .context("unmapping and destroying X11 window")
 530        .log_err();
 531
 532        if destroy_x_window.is_some() {
 533            // Mark window as destroyed so that we can filter out when X11 events
 534            // for it still come in.
 535            state.destroyed = true;
 536
 537            let this_ptr = self.0.clone();
 538            let client_ptr = state.client.clone();
 539            state
 540                .executor
 541                .spawn(async move {
 542                    this_ptr.close();
 543                    client_ptr.drop_window(this_ptr.x_window);
 544                })
 545                .detach();
 546        }
 547
 548        drop(state);
 549    }
 550}
 551
 552enum WmHintPropertyState {
 553    // Remove = 0,
 554    // Add = 1,
 555    Toggle = 2,
 556}
 557
 558impl X11Window {
 559    #[allow(clippy::too_many_arguments)]
 560    pub fn new(
 561        handle: AnyWindowHandle,
 562        client: X11ClientStatePtr,
 563        executor: ForegroundExecutor,
 564        params: WindowParams,
 565        xcb_connection: &Rc<XCBConnection>,
 566        x_main_screen_index: usize,
 567        x_window: xproto::Window,
 568        atoms: &XcbAtoms,
 569        scale_factor: f32,
 570        appearance: WindowAppearance,
 571    ) -> anyhow::Result<Self> {
 572        let ptr = X11WindowStatePtr {
 573            state: Rc::new(RefCell::new(X11WindowState::new(
 574                handle,
 575                client,
 576                executor,
 577                params,
 578                xcb_connection,
 579                x_main_screen_index,
 580                x_window,
 581                atoms,
 582                scale_factor,
 583                appearance,
 584            )?)),
 585            callbacks: Rc::new(RefCell::new(Callbacks::default())),
 586            xcb_connection: xcb_connection.clone(),
 587            x_window,
 588        };
 589
 590        let state = ptr.state.borrow_mut();
 591        ptr.set_wm_properties(state);
 592
 593        Ok(Self(ptr))
 594    }
 595
 596    fn set_wm_hints(&self, wm_hint_property_state: WmHintPropertyState, prop1: u32, prop2: u32) {
 597        let state = self.0.state.borrow();
 598        let message = ClientMessageEvent::new(
 599            32,
 600            self.0.x_window,
 601            state.atoms._NET_WM_STATE,
 602            [wm_hint_property_state as u32, prop1, prop2, 1, 0],
 603        );
 604        self.0
 605            .xcb_connection
 606            .send_event(
 607                false,
 608                state.x_root_window,
 609                EventMask::SUBSTRUCTURE_REDIRECT | EventMask::SUBSTRUCTURE_NOTIFY,
 610                message,
 611            )
 612            .unwrap()
 613            .check()
 614            .unwrap();
 615    }
 616
 617    fn get_root_position(&self, position: Point<Pixels>) -> TranslateCoordinatesReply {
 618        let state = self.0.state.borrow();
 619        self.0
 620            .xcb_connection
 621            .translate_coordinates(
 622                self.0.x_window,
 623                state.x_root_window,
 624                (position.x.0 * state.scale_factor) as i16,
 625                (position.y.0 * state.scale_factor) as i16,
 626            )
 627            .unwrap()
 628            .reply()
 629            .unwrap()
 630    }
 631
 632    fn send_moveresize(&self, flag: u32) {
 633        let state = self.0.state.borrow();
 634
 635        self.0
 636            .xcb_connection
 637            .ungrab_pointer(x11rb::CURRENT_TIME)
 638            .unwrap()
 639            .check()
 640            .unwrap();
 641
 642        let pointer = self
 643            .0
 644            .xcb_connection
 645            .query_pointer(self.0.x_window)
 646            .unwrap()
 647            .reply()
 648            .unwrap();
 649        let message = ClientMessageEvent::new(
 650            32,
 651            self.0.x_window,
 652            state.atoms._NET_WM_MOVERESIZE,
 653            [
 654                pointer.root_x as u32,
 655                pointer.root_y as u32,
 656                flag,
 657                0, // Left mouse button
 658                0,
 659            ],
 660        );
 661        self.0
 662            .xcb_connection
 663            .send_event(
 664                false,
 665                state.x_root_window,
 666                EventMask::SUBSTRUCTURE_REDIRECT | EventMask::SUBSTRUCTURE_NOTIFY,
 667                message,
 668            )
 669            .unwrap();
 670
 671        self.0.xcb_connection.flush().unwrap();
 672    }
 673}
 674
 675impl X11WindowStatePtr {
 676    pub fn should_close(&self) -> bool {
 677        let mut cb = self.callbacks.borrow_mut();
 678        if let Some(mut should_close) = cb.should_close.take() {
 679            let result = (should_close)();
 680            cb.should_close = Some(should_close);
 681            result
 682        } else {
 683            true
 684        }
 685    }
 686
 687    pub fn property_notify(&self, event: xproto::PropertyNotifyEvent) {
 688        let mut state = self.state.borrow_mut();
 689        if event.atom == state.atoms._NET_WM_STATE
 690            || event.atom == state.atoms._GTK_EDGE_CONSTRAINTS
 691        {
 692            self.set_wm_properties(state);
 693        }
 694    }
 695
 696    fn set_wm_properties(&self, mut state: std::cell::RefMut<X11WindowState>) {
 697        let reply = self
 698            .xcb_connection
 699            .get_property(
 700                false,
 701                self.x_window,
 702                state.atoms._NET_WM_STATE,
 703                xproto::AtomEnum::ATOM,
 704                0,
 705                u32::MAX,
 706            )
 707            .unwrap()
 708            .reply()
 709            .unwrap();
 710
 711        let atoms = reply
 712            .value
 713            .chunks_exact(4)
 714            .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
 715
 716        state.active = false;
 717        state.fullscreen = false;
 718        state.maximized_vertical = false;
 719        state.maximized_horizontal = false;
 720        state.hidden = true;
 721
 722        for atom in atoms {
 723            if atom == state.atoms._NET_WM_STATE_FOCUSED {
 724                state.active = true;
 725            } else if atom == state.atoms._NET_WM_STATE_FULLSCREEN {
 726                state.fullscreen = true;
 727            } else if atom == state.atoms._NET_WM_STATE_MAXIMIZED_VERT {
 728                state.maximized_vertical = true;
 729            } else if atom == state.atoms._NET_WM_STATE_MAXIMIZED_HORZ {
 730                state.maximized_horizontal = true;
 731            } else if atom == state.atoms._NET_WM_STATE_HIDDEN {
 732                state.hidden = true;
 733            }
 734        }
 735    }
 736
 737    pub fn close(&self) {
 738        let mut callbacks = self.callbacks.borrow_mut();
 739        if let Some(fun) = callbacks.close.take() {
 740            fun()
 741        }
 742    }
 743
 744    pub fn refresh(&self) {
 745        let mut cb = self.callbacks.borrow_mut();
 746        if let Some(ref mut fun) = cb.request_frame {
 747            fun();
 748        }
 749    }
 750
 751    pub fn handle_input(&self, input: PlatformInput) {
 752        if let Some(ref mut fun) = self.callbacks.borrow_mut().input {
 753            if !fun(input.clone()).propagate {
 754                return;
 755            }
 756        }
 757        if let PlatformInput::KeyDown(event) = input {
 758            let mut state = self.state.borrow_mut();
 759            if let Some(mut input_handler) = state.input_handler.take() {
 760                if let Some(ime_key) = &event.keystroke.ime_key {
 761                    drop(state);
 762                    input_handler.replace_text_in_range(None, ime_key);
 763                    state = self.state.borrow_mut();
 764                }
 765                state.input_handler = Some(input_handler);
 766            }
 767        }
 768    }
 769
 770    pub fn handle_ime_commit(&self, text: String) {
 771        let mut state = self.state.borrow_mut();
 772        if let Some(mut input_handler) = state.input_handler.take() {
 773            drop(state);
 774            input_handler.replace_text_in_range(None, &text);
 775            let mut state = self.state.borrow_mut();
 776            state.input_handler = Some(input_handler);
 777        }
 778    }
 779
 780    pub fn handle_ime_preedit(&self, text: String) {
 781        let mut state = self.state.borrow_mut();
 782        if let Some(mut input_handler) = state.input_handler.take() {
 783            drop(state);
 784            input_handler.replace_and_mark_text_in_range(None, &text, None);
 785            let mut state = self.state.borrow_mut();
 786            state.input_handler = Some(input_handler);
 787        }
 788    }
 789
 790    pub fn handle_ime_unmark(&self) {
 791        let mut state = self.state.borrow_mut();
 792        if let Some(mut input_handler) = state.input_handler.take() {
 793            drop(state);
 794            input_handler.unmark_text();
 795            let mut state = self.state.borrow_mut();
 796            state.input_handler = Some(input_handler);
 797        }
 798    }
 799
 800    pub fn handle_ime_delete(&self) {
 801        let mut state = self.state.borrow_mut();
 802        if let Some(mut input_handler) = state.input_handler.take() {
 803            drop(state);
 804            if let Some(marked) = input_handler.marked_text_range() {
 805                input_handler.replace_text_in_range(Some(marked), "");
 806            }
 807            let mut state = self.state.borrow_mut();
 808            state.input_handler = Some(input_handler);
 809        }
 810    }
 811
 812    pub fn get_ime_area(&self) -> Option<Bounds<Pixels>> {
 813        let mut state = self.state.borrow_mut();
 814        let mut bounds: Option<Bounds<Pixels>> = None;
 815        if let Some(mut input_handler) = state.input_handler.take() {
 816            drop(state);
 817            if let Some(range) = input_handler.selected_text_range() {
 818                bounds = input_handler.bounds_for_range(range);
 819            }
 820            let mut state = self.state.borrow_mut();
 821            state.input_handler = Some(input_handler);
 822        };
 823        bounds
 824    }
 825
 826    pub fn configure(&self, bounds: Bounds<i32>) {
 827        let mut resize_args = None;
 828        let is_resize;
 829        {
 830            let mut state = self.state.borrow_mut();
 831            let bounds = bounds.map(|f| px(f as f32 / state.scale_factor));
 832
 833            is_resize = bounds.size.width != state.bounds.size.width
 834                || bounds.size.height != state.bounds.size.height;
 835
 836            // If it's a resize event (only width/height changed), we ignore `bounds.origin`
 837            // because it contains wrong values.
 838            if is_resize {
 839                state.bounds.size = bounds.size;
 840            } else {
 841                state.bounds = bounds;
 842            }
 843
 844            let gpu_size = query_render_extent(&self.xcb_connection, self.x_window);
 845            if true {
 846                state.renderer.update_drawable_size(size(
 847                    DevicePixels(gpu_size.width as i32),
 848                    DevicePixels(gpu_size.height as i32),
 849                ));
 850                resize_args = Some((state.content_size(), state.scale_factor));
 851            }
 852            if let Some(value) = state.last_sync_counter.take() {
 853                sync::set_counter(&self.xcb_connection, state.counter_id, value).unwrap();
 854            }
 855        }
 856
 857        let mut callbacks = self.callbacks.borrow_mut();
 858        if let Some((content_size, scale_factor)) = resize_args {
 859            if let Some(ref mut fun) = callbacks.resize {
 860                fun(content_size, scale_factor)
 861            }
 862        }
 863        if !is_resize {
 864            if let Some(ref mut fun) = callbacks.moved {
 865                fun()
 866            }
 867        }
 868    }
 869
 870    pub fn set_focused(&self, focus: bool) {
 871        if let Some(ref mut fun) = self.callbacks.borrow_mut().active_status_change {
 872            fun(focus);
 873        }
 874    }
 875
 876    pub fn set_appearance(&mut self, appearance: WindowAppearance) {
 877        let mut state = self.state.borrow_mut();
 878        state.appearance = appearance;
 879        let is_transparent = state.is_transparent();
 880        state.renderer.update_transparency(is_transparent);
 881        state.appearance = appearance;
 882        drop(state);
 883        let mut callbacks = self.callbacks.borrow_mut();
 884        if let Some(ref mut fun) = callbacks.appearance_changed {
 885            (fun)()
 886        }
 887    }
 888
 889    pub fn refresh_rate(&self) -> Duration {
 890        self.state.borrow().refresh_rate
 891    }
 892}
 893
 894impl PlatformWindow for X11Window {
 895    fn bounds(&self) -> Bounds<Pixels> {
 896        self.0.state.borrow().bounds
 897    }
 898
 899    fn is_maximized(&self) -> bool {
 900        let state = self.0.state.borrow();
 901
 902        // A maximized window that gets minimized will still retain its maximized state.
 903        !state.hidden && state.maximized_vertical && state.maximized_horizontal
 904    }
 905
 906    fn window_bounds(&self) -> WindowBounds {
 907        let state = self.0.state.borrow();
 908        if self.is_maximized() {
 909            WindowBounds::Maximized(state.bounds)
 910        } else {
 911            WindowBounds::Windowed(state.bounds)
 912        }
 913    }
 914
 915    fn content_size(&self) -> Size<Pixels> {
 916        // We divide by the scale factor here because this value is queried to determine how much to draw,
 917        // but it will be multiplied later by the scale to adjust for scaling.
 918        let state = self.0.state.borrow();
 919        state
 920            .content_size()
 921            .map(|size| size.div(state.scale_factor))
 922    }
 923
 924    fn scale_factor(&self) -> f32 {
 925        self.0.state.borrow().scale_factor
 926    }
 927
 928    fn appearance(&self) -> WindowAppearance {
 929        self.0.state.borrow().appearance
 930    }
 931
 932    fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 933        Some(self.0.state.borrow().display.clone())
 934    }
 935
 936    fn mouse_position(&self) -> Point<Pixels> {
 937        let reply = self
 938            .0
 939            .xcb_connection
 940            .query_pointer(self.0.x_window)
 941            .unwrap()
 942            .reply()
 943            .unwrap();
 944        Point::new((reply.root_x as u32).into(), (reply.root_y as u32).into())
 945    }
 946
 947    fn modifiers(&self) -> Modifiers {
 948        self.0
 949            .state
 950            .borrow()
 951            .client
 952            .0
 953            .upgrade()
 954            .map(|ref_cell| ref_cell.borrow().modifiers)
 955            .unwrap_or_default()
 956    }
 957
 958    fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
 959        self.0.state.borrow_mut().input_handler = Some(input_handler);
 960    }
 961
 962    fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
 963        self.0.state.borrow_mut().input_handler.take()
 964    }
 965
 966    fn prompt(
 967        &self,
 968        _level: PromptLevel,
 969        _msg: &str,
 970        _detail: Option<&str>,
 971        _answers: &[&str],
 972    ) -> Option<futures::channel::oneshot::Receiver<usize>> {
 973        None
 974    }
 975
 976    fn activate(&self) {
 977        let data = [1, xproto::Time::CURRENT_TIME.into(), 0, 0, 0];
 978        let message = xproto::ClientMessageEvent::new(
 979            32,
 980            self.0.x_window,
 981            self.0.state.borrow().atoms._NET_ACTIVE_WINDOW,
 982            data,
 983        );
 984        self.0
 985            .xcb_connection
 986            .send_event(
 987                false,
 988                self.0.state.borrow().x_root_window,
 989                xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
 990                message,
 991            )
 992            .log_err();
 993        self.0
 994            .xcb_connection
 995            .set_input_focus(
 996                xproto::InputFocus::POINTER_ROOT,
 997                self.0.x_window,
 998                xproto::Time::CURRENT_TIME,
 999            )
1000            .log_err();
1001        self.0.xcb_connection.flush().unwrap();
1002    }
1003
1004    fn is_active(&self) -> bool {
1005        self.0.state.borrow().active
1006    }
1007
1008    fn set_title(&mut self, title: &str) {
1009        self.0
1010            .xcb_connection
1011            .change_property8(
1012                xproto::PropMode::REPLACE,
1013                self.0.x_window,
1014                xproto::AtomEnum::WM_NAME,
1015                xproto::AtomEnum::STRING,
1016                title.as_bytes(),
1017            )
1018            .unwrap();
1019
1020        self.0
1021            .xcb_connection
1022            .change_property8(
1023                xproto::PropMode::REPLACE,
1024                self.0.x_window,
1025                self.0.state.borrow().atoms._NET_WM_NAME,
1026                self.0.state.borrow().atoms.UTF8_STRING,
1027                title.as_bytes(),
1028            )
1029            .unwrap();
1030        self.0.xcb_connection.flush().unwrap();
1031    }
1032
1033    fn set_app_id(&mut self, app_id: &str) {
1034        let mut data = Vec::with_capacity(app_id.len() * 2 + 1);
1035        data.extend(app_id.bytes()); // instance https://unix.stackexchange.com/a/494170
1036        data.push(b'\0');
1037        data.extend(app_id.bytes()); // class
1038
1039        self.0
1040            .xcb_connection
1041            .change_property8(
1042                xproto::PropMode::REPLACE,
1043                self.0.x_window,
1044                xproto::AtomEnum::WM_CLASS,
1045                xproto::AtomEnum::STRING,
1046                &data,
1047            )
1048            .unwrap()
1049            .check()
1050            .unwrap();
1051    }
1052
1053    fn set_edited(&mut self, _edited: bool) {
1054        log::info!("ignoring macOS specific set_edited");
1055    }
1056
1057    fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
1058        let mut state = self.0.state.borrow_mut();
1059        state.background_appearance = background_appearance;
1060        let transparent = state.is_transparent();
1061        state.renderer.update_transparency(transparent);
1062    }
1063
1064    fn show_character_palette(&self) {
1065        log::info!("ignoring macOS specific show_character_palette");
1066    }
1067
1068    fn minimize(&self) {
1069        let state = self.0.state.borrow();
1070        const WINDOW_ICONIC_STATE: u32 = 3;
1071        let message = ClientMessageEvent::new(
1072            32,
1073            self.0.x_window,
1074            state.atoms.WM_CHANGE_STATE,
1075            [WINDOW_ICONIC_STATE, 0, 0, 0, 0],
1076        );
1077        self.0
1078            .xcb_connection
1079            .send_event(
1080                false,
1081                state.x_root_window,
1082                EventMask::SUBSTRUCTURE_REDIRECT | EventMask::SUBSTRUCTURE_NOTIFY,
1083                message,
1084            )
1085            .unwrap()
1086            .check()
1087            .unwrap();
1088    }
1089
1090    fn zoom(&self) {
1091        let state = self.0.state.borrow();
1092        self.set_wm_hints(
1093            WmHintPropertyState::Toggle,
1094            state.atoms._NET_WM_STATE_MAXIMIZED_VERT,
1095            state.atoms._NET_WM_STATE_MAXIMIZED_HORZ,
1096        );
1097    }
1098
1099    fn toggle_fullscreen(&self) {
1100        let state = self.0.state.borrow();
1101        self.set_wm_hints(
1102            WmHintPropertyState::Toggle,
1103            state.atoms._NET_WM_STATE_FULLSCREEN,
1104            xproto::AtomEnum::NONE.into(),
1105        );
1106    }
1107
1108    fn is_fullscreen(&self) -> bool {
1109        self.0.state.borrow().fullscreen
1110    }
1111
1112    fn on_request_frame(&self, callback: Box<dyn FnMut()>) {
1113        self.0.callbacks.borrow_mut().request_frame = Some(callback);
1114    }
1115
1116    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>) {
1117        self.0.callbacks.borrow_mut().input = Some(callback);
1118    }
1119
1120    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1121        self.0.callbacks.borrow_mut().active_status_change = Some(callback);
1122    }
1123
1124    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
1125        self.0.callbacks.borrow_mut().resize = Some(callback);
1126    }
1127
1128    fn on_moved(&self, callback: Box<dyn FnMut()>) {
1129        self.0.callbacks.borrow_mut().moved = Some(callback);
1130    }
1131
1132    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
1133        self.0.callbacks.borrow_mut().should_close = Some(callback);
1134    }
1135
1136    fn on_close(&self, callback: Box<dyn FnOnce()>) {
1137        self.0.callbacks.borrow_mut().close = Some(callback);
1138    }
1139
1140    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
1141        self.0.callbacks.borrow_mut().appearance_changed = Some(callback);
1142    }
1143
1144    fn draw(&self, scene: &Scene) {
1145        let mut inner = self.0.state.borrow_mut();
1146        inner.renderer.draw(scene);
1147    }
1148
1149    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
1150        let inner = self.0.state.borrow();
1151        inner.renderer.sprite_atlas().clone()
1152    }
1153
1154    fn show_window_menu(&self, position: Point<Pixels>) {
1155        let state = self.0.state.borrow();
1156        let coords = self.get_root_position(position);
1157        let message = ClientMessageEvent::new(
1158            32,
1159            self.0.x_window,
1160            state.atoms._GTK_SHOW_WINDOW_MENU,
1161            [
1162                XINPUT_MASTER_DEVICE as u32,
1163                coords.dst_x as u32,
1164                coords.dst_y as u32,
1165                0,
1166                0,
1167            ],
1168        );
1169        self.0
1170            .xcb_connection
1171            .send_event(
1172                false,
1173                state.x_root_window,
1174                EventMask::SUBSTRUCTURE_REDIRECT | EventMask::SUBSTRUCTURE_NOTIFY,
1175                message,
1176            )
1177            .unwrap()
1178            .check()
1179            .unwrap();
1180    }
1181
1182    fn start_window_move(&self) {
1183        const MOVERESIZE_MOVE: u32 = 8;
1184        self.send_moveresize(MOVERESIZE_MOVE);
1185    }
1186
1187    fn start_window_resize(&self, edge: ResizeEdge) {
1188        self.send_moveresize(edge.to_moveresize());
1189    }
1190
1191    fn window_decorations(&self) -> crate::Decorations {
1192        let state = self.0.state.borrow();
1193
1194        match state.decorations {
1195            WindowDecorations::Server => Decorations::Server,
1196            WindowDecorations::Client => {
1197                // https://source.chromium.org/chromium/chromium/src/+/main:ui/ozone/platform/x11/x11_window.cc;l=2519;drc=1f14cc876cc5bf899d13284a12c451498219bb2d
1198                Decorations::Client {
1199                    tiling: Tiling {
1200                        top: state.maximized_vertical,
1201                        bottom: state.maximized_vertical,
1202                        left: state.maximized_horizontal,
1203                        right: state.maximized_horizontal,
1204                    },
1205                }
1206            }
1207        }
1208    }
1209
1210    fn set_client_inset(&self, inset: Pixels) {
1211        let mut state = self.0.state.borrow_mut();
1212
1213        let dp = (inset.0 * state.scale_factor) as u32;
1214
1215        let (left, right) = if state.maximized_horizontal {
1216            (0, 0)
1217        } else {
1218            (dp, dp)
1219        };
1220        let (top, bottom) = if state.maximized_vertical {
1221            (0, 0)
1222        } else {
1223            (dp, dp)
1224        };
1225        let insets = [left, right, top, bottom];
1226
1227        if state.last_insets != insets {
1228            state.last_insets = insets;
1229
1230            self.0
1231                .xcb_connection
1232                .change_property(
1233                    xproto::PropMode::REPLACE,
1234                    self.0.x_window,
1235                    state.atoms._GTK_FRAME_EXTENTS,
1236                    xproto::AtomEnum::CARDINAL,
1237                    size_of::<u32>() as u8 * 8,
1238                    4,
1239                    bytemuck::cast_slice::<u32, u8>(&insets),
1240                )
1241                .unwrap()
1242                .check()
1243                .unwrap();
1244        }
1245    }
1246
1247    fn request_decorations(&self, decorations: crate::WindowDecorations) {
1248        // https://github.com/rust-windowing/winit/blob/master/src/platform_impl/linux/x11/util/hint.rs#L53-L87
1249        let hints_data: [u32; 5] = match decorations {
1250            WindowDecorations::Server => [1 << 1, 0, 1, 0, 0],
1251            WindowDecorations::Client => [1 << 1, 0, 0, 0, 0],
1252        };
1253
1254        let mut state = self.0.state.borrow_mut();
1255
1256        self.0
1257            .xcb_connection
1258            .change_property(
1259                xproto::PropMode::REPLACE,
1260                self.0.x_window,
1261                state.atoms._MOTIF_WM_HINTS,
1262                state.atoms._MOTIF_WM_HINTS,
1263                std::mem::size_of::<u32>() as u8 * 8,
1264                5,
1265                bytemuck::cast_slice::<u32, u8>(&hints_data),
1266            )
1267            .unwrap()
1268            .check()
1269            .unwrap();
1270
1271        match decorations {
1272            WindowDecorations::Server => {
1273                state.decorations = WindowDecorations::Server;
1274                let is_transparent = state.is_transparent();
1275                state.renderer.update_transparency(is_transparent);
1276            }
1277            WindowDecorations::Client => {
1278                state.decorations = WindowDecorations::Client;
1279                let is_transparent = state.is_transparent();
1280                state.renderer.update_transparency(is_transparent);
1281            }
1282        }
1283
1284        drop(state);
1285        let mut callbacks = self.0.callbacks.borrow_mut();
1286        if let Some(appearance_changed) = callbacks.appearance_changed.as_mut() {
1287            appearance_changed();
1288        }
1289    }
1290}
1291
1292// Adapted from:
1293// https://docs.rs/winit/0.29.11/src/winit/platform_impl/linux/x11/monitor.rs.html#103-111
1294pub fn mode_refresh_rate(mode: &randr::ModeInfo) -> Duration {
1295    if mode.dot_clock == 0 || mode.htotal == 0 || mode.vtotal == 0 {
1296        return Duration::from_millis(16);
1297    }
1298
1299    let millihertz = mode.dot_clock as u64 * 1_000 / (mode.htotal as u64 * mode.vtotal as u64);
1300    let micros = 1_000_000_000 / millihertz;
1301    log::info!("Refreshing at {} micros", micros);
1302    Duration::from_micros(micros)
1303}