client.rs

   1use std::cell::RefCell;
   2use std::collections::HashSet;
   3use std::ops::Deref;
   4use std::path::PathBuf;
   5use std::rc::{Rc, Weak};
   6use std::time::{Duration, Instant};
   7
   8use calloop::generic::{FdWrapper, Generic};
   9use calloop::{EventLoop, LoopHandle, RegistrationToken};
  10
  11use collections::HashMap;
  12use util::ResultExt;
  13
  14use x11rb::connection::{Connection, RequestConnection};
  15use x11rb::cursor;
  16use x11rb::errors::ConnectionError;
  17use x11rb::protocol::randr::ConnectionExt as _;
  18use x11rb::protocol::xinput::ConnectionExt;
  19use x11rb::protocol::xkb::ConnectionExt as _;
  20use x11rb::protocol::xproto::{ChangeWindowAttributesAux, ConnectionExt as _, KeyPressEvent};
  21use x11rb::protocol::{randr, render, xinput, xkb, xproto, Event};
  22use x11rb::resource_manager::Database;
  23use x11rb::xcb_ffi::XCBConnection;
  24use xim::{x11rb::X11rbClient, Client};
  25use xim::{AttributeName, InputStyle};
  26use xkbc::x11::ffi::{XKB_X11_MIN_MAJOR_XKB_VERSION, XKB_X11_MIN_MINOR_XKB_VERSION};
  27use xkbcommon::xkb::{self as xkbc, LayoutIndex, ModMask};
  28
  29use crate::platform::linux::LinuxClient;
  30use crate::platform::{LinuxCommon, PlatformWindow};
  31use crate::{
  32    modifiers_from_xinput_info, point, px, AnyWindowHandle, Bounds, ClipboardItem, CursorStyle,
  33    DisplayId, Keystroke, Modifiers, ModifiersChangedEvent, Pixels, Platform, PlatformDisplay,
  34    PlatformInput, Point, ScrollDelta, Size, TouchPhase, WindowParams, X11Window,
  35};
  36
  37use super::{button_of_key, modifiers_from_state, pressed_button_from_mask};
  38use super::{X11Display, X11WindowStatePtr, XcbAtoms};
  39use super::{XimCallbackEvent, XimHandler};
  40use crate::platform::linux::platform::{DOUBLE_CLICK_INTERVAL, SCROLL_LINES};
  41use crate::platform::linux::xdg_desktop_portal::{Event as XDPEvent, XDPEventSource};
  42use crate::platform::linux::{
  43    get_xkb_compose_state, is_within_click_distance, open_uri_internal, reveal_path_internal,
  44};
  45
  46pub(super) const XINPUT_MASTER_DEVICE: u16 = 1;
  47
  48pub(crate) struct WindowRef {
  49    window: X11WindowStatePtr,
  50    refresh_event_token: RegistrationToken,
  51}
  52
  53impl WindowRef {
  54    pub fn handle(&self) -> AnyWindowHandle {
  55        self.window.state.borrow().handle
  56    }
  57}
  58
  59impl Deref for WindowRef {
  60    type Target = X11WindowStatePtr;
  61
  62    fn deref(&self) -> &Self::Target {
  63        &self.window
  64    }
  65}
  66
  67#[derive(Debug)]
  68#[non_exhaustive]
  69pub enum EventHandlerError {
  70    XCBConnectionError(ConnectionError),
  71    XIMClientError(xim::ClientError),
  72}
  73
  74impl std::error::Error for EventHandlerError {}
  75
  76impl std::fmt::Display for EventHandlerError {
  77    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  78        match self {
  79            EventHandlerError::XCBConnectionError(err) => err.fmt(f),
  80            EventHandlerError::XIMClientError(err) => err.fmt(f),
  81        }
  82    }
  83}
  84
  85impl From<ConnectionError> for EventHandlerError {
  86    fn from(err: ConnectionError) -> Self {
  87        EventHandlerError::XCBConnectionError(err)
  88    }
  89}
  90
  91impl From<xim::ClientError> for EventHandlerError {
  92    fn from(err: xim::ClientError) -> Self {
  93        EventHandlerError::XIMClientError(err)
  94    }
  95}
  96
  97#[derive(Debug, Default, Clone)]
  98struct XKBStateNotiy {
  99    depressed_layout: LayoutIndex,
 100    latched_layout: LayoutIndex,
 101    locked_layout: LayoutIndex,
 102}
 103
 104pub struct X11ClientState {
 105    pub(crate) loop_handle: LoopHandle<'static, X11Client>,
 106    pub(crate) event_loop: Option<calloop::EventLoop<'static, X11Client>>,
 107
 108    pub(crate) last_click: Instant,
 109    pub(crate) last_location: Point<Pixels>,
 110    pub(crate) current_count: usize,
 111
 112    pub(crate) scale_factor: f32,
 113
 114    pub(crate) xcb_connection: Rc<XCBConnection>,
 115    client_side_decorations_supported: bool,
 116    pub(crate) x_root_index: usize,
 117    pub(crate) _resource_database: Database,
 118    pub(crate) atoms: XcbAtoms,
 119    pub(crate) windows: HashMap<xproto::Window, WindowRef>,
 120    pub(crate) mouse_focused_window: Option<xproto::Window>,
 121    pub(crate) keyboard_focused_window: Option<xproto::Window>,
 122    pub(crate) xkb: xkbc::State,
 123    previous_xkb_state: XKBStateNotiy,
 124    pub(crate) ximc: Option<X11rbClient<Rc<XCBConnection>>>,
 125    pub(crate) xim_handler: Option<XimHandler>,
 126    pub modifiers: Modifiers,
 127
 128    pub(crate) compose_state: Option<xkbc::compose::State>,
 129    pub(crate) pre_edit_text: Option<String>,
 130    pub(crate) composing: bool,
 131    pub(crate) pre_ime_key_down: Option<Keystroke>,
 132    pub(crate) cursor_handle: cursor::Handle,
 133    pub(crate) cursor_styles: HashMap<xproto::Window, CursorStyle>,
 134    pub(crate) cursor_cache: HashMap<CursorStyle, xproto::Cursor>,
 135
 136    pub(crate) scroll_class_data: Vec<xinput::DeviceClassDataScroll>,
 137    pub(crate) scroll_x: Option<f32>,
 138    pub(crate) scroll_y: Option<f32>,
 139
 140    pub(crate) common: LinuxCommon,
 141    pub(crate) clipboard: x11_clipboard::Clipboard,
 142    pub(crate) clipboard_item: Option<ClipboardItem>,
 143}
 144
 145#[derive(Clone)]
 146pub struct X11ClientStatePtr(pub Weak<RefCell<X11ClientState>>);
 147
 148impl X11ClientStatePtr {
 149    pub fn drop_window(&self, x_window: u32) {
 150        let client = X11Client(self.0.upgrade().expect("client already dropped"));
 151        let mut state = client.0.borrow_mut();
 152
 153        if let Some(window_ref) = state.windows.remove(&x_window) {
 154            state.loop_handle.remove(window_ref.refresh_event_token);
 155        }
 156        if state.mouse_focused_window == Some(x_window) {
 157            state.mouse_focused_window = None;
 158        }
 159        if state.keyboard_focused_window == Some(x_window) {
 160            state.keyboard_focused_window = None;
 161        }
 162        state.cursor_styles.remove(&x_window);
 163
 164        if state.windows.is_empty() {
 165            state.common.signal.stop();
 166        }
 167    }
 168}
 169
 170#[derive(Clone)]
 171pub(crate) struct X11Client(Rc<RefCell<X11ClientState>>);
 172
 173impl X11Client {
 174    pub(crate) fn new() -> Self {
 175        let event_loop = EventLoop::try_new().unwrap();
 176
 177        let (common, main_receiver) = LinuxCommon::new(event_loop.get_signal());
 178
 179        let handle = event_loop.handle();
 180
 181        handle
 182            .insert_source(main_receiver, {
 183                let handle = handle.clone();
 184                move |event, _, _: &mut X11Client| {
 185                    if let calloop::channel::Event::Msg(runnable) = event {
 186                        // Insert the runnables as idle callbacks, so we make sure that user-input and X11
 187                        // events have higher priority and runnables are only worked off after the event
 188                        // callbacks.
 189                        handle.insert_idle(|_| {
 190                            runnable.run();
 191                        });
 192                    }
 193                }
 194            })
 195            .unwrap();
 196
 197        let (xcb_connection, x_root_index) = XCBConnection::connect(None).unwrap();
 198        xcb_connection
 199            .prefetch_extension_information(xkb::X11_EXTENSION_NAME)
 200            .unwrap();
 201        xcb_connection
 202            .prefetch_extension_information(randr::X11_EXTENSION_NAME)
 203            .unwrap();
 204        xcb_connection
 205            .prefetch_extension_information(render::X11_EXTENSION_NAME)
 206            .unwrap();
 207        xcb_connection
 208            .prefetch_extension_information(xinput::X11_EXTENSION_NAME)
 209            .unwrap();
 210
 211        let xinput_version = xcb_connection
 212            .xinput_xi_query_version(2, 0)
 213            .unwrap()
 214            .reply()
 215            .unwrap();
 216        assert!(
 217            xinput_version.major_version >= 2,
 218            "XInput Extension v2 not supported."
 219        );
 220
 221        let master_device_query = xcb_connection
 222            .xinput_xi_query_device(XINPUT_MASTER_DEVICE)
 223            .unwrap()
 224            .reply()
 225            .unwrap();
 226        let scroll_class_data = master_device_query
 227            .infos
 228            .iter()
 229            .find(|info| info.type_ == xinput::DeviceType::MASTER_POINTER)
 230            .unwrap()
 231            .classes
 232            .iter()
 233            .filter_map(|class| class.data.as_scroll())
 234            .map(|class| *class)
 235            .collect::<Vec<_>>();
 236
 237        let atoms = XcbAtoms::new(&xcb_connection).unwrap().reply().unwrap();
 238
 239        let root = xcb_connection.setup().roots[0].root;
 240        let compositor_present = check_compositor_present(&xcb_connection, root);
 241        let gtk_frame_extents_supported =
 242            check_gtk_frame_extents_supported(&xcb_connection, &atoms, root);
 243        let client_side_decorations_supported = compositor_present && gtk_frame_extents_supported;
 244        log::info!(
 245            "x11: compositor present: {}, gtk_frame_extents_supported: {}",
 246            compositor_present,
 247            gtk_frame_extents_supported
 248        );
 249
 250        let xkb = xcb_connection
 251            .xkb_use_extension(XKB_X11_MIN_MAJOR_XKB_VERSION, XKB_X11_MIN_MINOR_XKB_VERSION)
 252            .unwrap()
 253            .reply()
 254            .unwrap();
 255
 256        let events = xkb::EventType::STATE_NOTIFY;
 257        xcb_connection
 258            .xkb_select_events(
 259                xkb::ID::USE_CORE_KBD.into(),
 260                0u8.into(),
 261                events,
 262                0u8.into(),
 263                0u8.into(),
 264                &xkb::SelectEventsAux::new(),
 265            )
 266            .unwrap();
 267        assert!(xkb.supported);
 268
 269        let xkb_context = xkbc::Context::new(xkbc::CONTEXT_NO_FLAGS);
 270        let xkb_state = {
 271            let xkb_device_id = xkbc::x11::get_core_keyboard_device_id(&xcb_connection);
 272            let xkb_keymap = xkbc::x11::keymap_new_from_device(
 273                &xkb_context,
 274                &xcb_connection,
 275                xkb_device_id,
 276                xkbc::KEYMAP_COMPILE_NO_FLAGS,
 277            );
 278            xkbc::x11::state_new_from_device(&xkb_keymap, &xcb_connection, xkb_device_id)
 279        };
 280        let compose_state = get_xkb_compose_state(&xkb_context);
 281        let resource_database = x11rb::resource_manager::new_from_default(&xcb_connection).unwrap();
 282
 283        let scale_factor = resource_database
 284            .get_value("Xft.dpi", "Xft.dpi")
 285            .ok()
 286            .flatten()
 287            .map(|dpi: f32| dpi / 96.0)
 288            .unwrap_or(1.0);
 289
 290        let cursor_handle = cursor::Handle::new(&xcb_connection, x_root_index, &resource_database)
 291            .unwrap()
 292            .reply()
 293            .unwrap();
 294
 295        let clipboard = x11_clipboard::Clipboard::new().unwrap();
 296
 297        let xcb_connection = Rc::new(xcb_connection);
 298
 299        let ximc = X11rbClient::init(Rc::clone(&xcb_connection), x_root_index, None).ok();
 300        let xim_handler = if ximc.is_some() {
 301            Some(XimHandler::new())
 302        } else {
 303            None
 304        };
 305
 306        // Safety: Safe if xcb::Connection always returns a valid fd
 307        let fd = unsafe { FdWrapper::new(Rc::clone(&xcb_connection)) };
 308
 309        handle
 310            .insert_source(
 311                Generic::new_with_error::<EventHandlerError>(
 312                    fd,
 313                    calloop::Interest::READ,
 314                    calloop::Mode::Level,
 315                ),
 316                {
 317                    let xcb_connection = xcb_connection.clone();
 318                    move |_readiness, _, client| {
 319                        client.process_x11_events(&xcb_connection)?;
 320                        Ok(calloop::PostAction::Continue)
 321                    }
 322                },
 323            )
 324            .expect("Failed to initialize x11 event source");
 325
 326        handle
 327            .insert_source(XDPEventSource::new(&common.background_executor), {
 328                move |event, _, client| match event {
 329                    XDPEvent::WindowAppearance(appearance) => {
 330                        client.with_common(|common| common.appearance = appearance);
 331                        for (_, window) in &mut client.0.borrow_mut().windows {
 332                            window.window.set_appearance(appearance);
 333                        }
 334                    }
 335                    XDPEvent::CursorTheme(_) | XDPEvent::CursorSize(_) => {
 336                        // noop, X11 manages this for us.
 337                    }
 338                }
 339            })
 340            .unwrap();
 341
 342        X11Client(Rc::new(RefCell::new(X11ClientState {
 343            modifiers: Modifiers::default(),
 344            event_loop: Some(event_loop),
 345            loop_handle: handle,
 346            common,
 347            last_click: Instant::now(),
 348            last_location: Point::new(px(0.0), px(0.0)),
 349            current_count: 0,
 350            scale_factor,
 351
 352            xcb_connection,
 353            client_side_decorations_supported,
 354            x_root_index,
 355            _resource_database: resource_database,
 356            atoms,
 357            windows: HashMap::default(),
 358            mouse_focused_window: None,
 359            keyboard_focused_window: None,
 360            xkb: xkb_state,
 361            previous_xkb_state: XKBStateNotiy::default(),
 362            ximc,
 363            xim_handler,
 364
 365            compose_state,
 366            pre_edit_text: None,
 367            pre_ime_key_down: None,
 368            composing: false,
 369
 370            cursor_handle,
 371            cursor_styles: HashMap::default(),
 372            cursor_cache: HashMap::default(),
 373
 374            scroll_class_data,
 375            scroll_x: None,
 376            scroll_y: None,
 377
 378            clipboard,
 379            clipboard_item: None,
 380        })))
 381    }
 382
 383    pub fn process_x11_events(
 384        &self,
 385        xcb_connection: &XCBConnection,
 386    ) -> Result<(), EventHandlerError> {
 387        loop {
 388            let mut events = Vec::new();
 389            let mut windows_to_refresh = HashSet::new();
 390
 391            let mut last_key_release = None;
 392            let mut last_key_press: Option<KeyPressEvent> = None;
 393
 394            loop {
 395                match xcb_connection.poll_for_event() {
 396                    Ok(Some(event)) => {
 397                        match event {
 398                            Event::Expose(expose_event) => {
 399                                windows_to_refresh.insert(expose_event.window);
 400                            }
 401                            Event::KeyRelease(_) => {
 402                                last_key_release = Some(event);
 403                            }
 404                            Event::KeyPress(key_press) => {
 405                                if let Some(last_press) = last_key_press.as_ref() {
 406                                    if last_press.detail == key_press.detail {
 407                                        continue;
 408                                    }
 409                                }
 410
 411                                if let Some(Event::KeyRelease(key_release)) =
 412                                    last_key_release.take()
 413                                {
 414                                    // We ignore that last KeyRelease if it's too close to this KeyPress,
 415                                    // suggesting that it's auto-generated by X11 as a key-repeat event.
 416                                    if key_release.detail != key_press.detail
 417                                        || key_press.time.saturating_sub(key_release.time) > 20
 418                                    {
 419                                        events.push(Event::KeyRelease(key_release));
 420                                    }
 421                                }
 422                                events.push(Event::KeyPress(key_press));
 423                                last_key_press = Some(key_press);
 424                            }
 425                            _ => {
 426                                if let Some(release_event) = last_key_release.take() {
 427                                    events.push(release_event);
 428                                }
 429                                events.push(event);
 430                            }
 431                        }
 432                    }
 433                    Ok(None) => {
 434                        // Add any remaining stored KeyRelease event
 435                        if let Some(release_event) = last_key_release.take() {
 436                            events.push(release_event);
 437                        }
 438                        break;
 439                    }
 440                    Err(e) => {
 441                        log::warn!("error polling for X11 events: {e:?}");
 442                        break;
 443                    }
 444                }
 445            }
 446
 447            if events.is_empty() && windows_to_refresh.is_empty() {
 448                break;
 449            }
 450
 451            for window in windows_to_refresh.into_iter() {
 452                if let Some(window) = self.get_window(window) {
 453                    window.refresh();
 454                }
 455            }
 456
 457            for event in events.into_iter() {
 458                let mut state = self.0.borrow_mut();
 459                if state.ximc.is_none() || state.xim_handler.is_none() {
 460                    drop(state);
 461                    self.handle_event(event);
 462                    continue;
 463                }
 464
 465                let mut ximc = state.ximc.take().unwrap();
 466                let mut xim_handler = state.xim_handler.take().unwrap();
 467                let xim_connected = xim_handler.connected;
 468                drop(state);
 469
 470                let xim_filtered = match ximc.filter_event(&event, &mut xim_handler) {
 471                    Ok(handled) => handled,
 472                    Err(err) => {
 473                        log::error!("XIMClientError: {}", err);
 474                        false
 475                    }
 476                };
 477                let xim_callback_event = xim_handler.last_callback_event.take();
 478
 479                let mut state = self.0.borrow_mut();
 480                state.ximc = Some(ximc);
 481                state.xim_handler = Some(xim_handler);
 482                drop(state);
 483
 484                if let Some(event) = xim_callback_event {
 485                    self.handle_xim_callback_event(event);
 486                }
 487
 488                if xim_filtered {
 489                    continue;
 490                }
 491
 492                if xim_connected {
 493                    self.xim_handle_event(event);
 494                } else {
 495                    self.handle_event(event);
 496                }
 497            }
 498        }
 499        Ok(())
 500    }
 501
 502    pub fn enable_ime(&self) {
 503        let mut state = self.0.borrow_mut();
 504        if state.ximc.is_none() {
 505            return;
 506        }
 507
 508        let mut ximc = state.ximc.take().unwrap();
 509        let mut xim_handler = state.xim_handler.take().unwrap();
 510        let mut ic_attributes = ximc
 511            .build_ic_attributes()
 512            .push(
 513                AttributeName::InputStyle,
 514                InputStyle::PREEDIT_CALLBACKS
 515                    | InputStyle::STATUS_NOTHING
 516                    | InputStyle::PREEDIT_NONE,
 517            )
 518            .push(AttributeName::ClientWindow, xim_handler.window)
 519            .push(AttributeName::FocusWindow, xim_handler.window);
 520
 521        let window_id = state.keyboard_focused_window;
 522        drop(state);
 523        if let Some(window_id) = window_id {
 524            let window = self.get_window(window_id).unwrap();
 525            if let Some(area) = window.get_ime_area() {
 526                ic_attributes =
 527                    ic_attributes.nested_list(xim::AttributeName::PreeditAttributes, |b| {
 528                        b.push(
 529                            xim::AttributeName::SpotLocation,
 530                            xim::Point {
 531                                x: u32::from(area.origin.x + area.size.width) as i16,
 532                                y: u32::from(area.origin.y + area.size.height) as i16,
 533                            },
 534                        );
 535                    });
 536            }
 537        }
 538        ximc.create_ic(xim_handler.im_id, ic_attributes.build())
 539            .ok();
 540        state = self.0.borrow_mut();
 541        state.xim_handler = Some(xim_handler);
 542        state.ximc = Some(ximc);
 543    }
 544
 545    pub fn disable_ime(&self) {
 546        let mut state = self.0.borrow_mut();
 547        state.composing = false;
 548        if let Some(mut ximc) = state.ximc.take() {
 549            let xim_handler = state.xim_handler.as_ref().unwrap();
 550            ximc.destroy_ic(xim_handler.im_id, xim_handler.ic_id).ok();
 551            state.ximc = Some(ximc);
 552        }
 553    }
 554
 555    fn get_window(&self, win: xproto::Window) -> Option<X11WindowStatePtr> {
 556        let state = self.0.borrow();
 557        state
 558            .windows
 559            .get(&win)
 560            .filter(|window_reference| !window_reference.window.state.borrow().destroyed)
 561            .map(|window_reference| window_reference.window.clone())
 562    }
 563
 564    fn handle_event(&self, event: Event) -> Option<()> {
 565        match event {
 566            Event::ClientMessage(event) => {
 567                let window = self.get_window(event.window)?;
 568                let [atom, _arg1, arg2, arg3, _arg4] = event.data.as_data32();
 569                let mut state = self.0.borrow_mut();
 570
 571                if atom == state.atoms.WM_DELETE_WINDOW {
 572                    // window "x" button clicked by user
 573                    if window.should_close() {
 574                        // Rest of the close logic is handled in drop_window()
 575                        window.close();
 576                    }
 577                } else if atom == state.atoms._NET_WM_SYNC_REQUEST {
 578                    window.state.borrow_mut().last_sync_counter =
 579                        Some(x11rb::protocol::sync::Int64 {
 580                            lo: arg2,
 581                            hi: arg3 as i32,
 582                        })
 583                }
 584            }
 585            Event::ConfigureNotify(event) => {
 586                let bounds = Bounds {
 587                    origin: Point {
 588                        x: event.x.into(),
 589                        y: event.y.into(),
 590                    },
 591                    size: Size {
 592                        width: event.width.into(),
 593                        height: event.height.into(),
 594                    },
 595                };
 596                let window = self.get_window(event.window)?;
 597                window.configure(bounds);
 598            }
 599            Event::PropertyNotify(event) => {
 600                let window = self.get_window(event.window)?;
 601                window.property_notify(event);
 602            }
 603            Event::FocusIn(event) => {
 604                let window = self.get_window(event.event)?;
 605                window.set_active(true);
 606                let mut state = self.0.borrow_mut();
 607                state.keyboard_focused_window = Some(event.event);
 608                drop(state);
 609                self.enable_ime();
 610            }
 611            Event::FocusOut(event) => {
 612                let window = self.get_window(event.event)?;
 613                window.set_active(false);
 614                let mut state = self.0.borrow_mut();
 615                state.keyboard_focused_window = None;
 616                if let Some(compose_state) = state.compose_state.as_mut() {
 617                    compose_state.reset();
 618                }
 619                state.pre_edit_text.take();
 620                drop(state);
 621                self.disable_ime();
 622                window.handle_ime_delete();
 623            }
 624            Event::XkbStateNotify(event) => {
 625                let mut state = self.0.borrow_mut();
 626                state.xkb.update_mask(
 627                    event.base_mods.into(),
 628                    event.latched_mods.into(),
 629                    event.locked_mods.into(),
 630                    event.base_group as u32,
 631                    event.latched_group as u32,
 632                    event.locked_group.into(),
 633                );
 634                state.previous_xkb_state = XKBStateNotiy {
 635                    depressed_layout: event.base_group as u32,
 636                    latched_layout: event.latched_group as u32,
 637                    locked_layout: event.locked_group.into(),
 638                };
 639                let modifiers = Modifiers::from_xkb(&state.xkb);
 640                if state.modifiers == modifiers {
 641                    drop(state);
 642                } else {
 643                    let focused_window_id = state.keyboard_focused_window?;
 644                    state.modifiers = modifiers;
 645                    drop(state);
 646
 647                    let focused_window = self.get_window(focused_window_id)?;
 648                    focused_window.handle_input(PlatformInput::ModifiersChanged(
 649                        ModifiersChangedEvent { modifiers },
 650                    ));
 651                }
 652            }
 653            Event::KeyPress(event) => {
 654                let window = self.get_window(event.event)?;
 655                let mut state = self.0.borrow_mut();
 656
 657                let modifiers = modifiers_from_state(event.state);
 658                state.modifiers = modifiers;
 659                state.pre_ime_key_down.take();
 660                let keystroke = {
 661                    let code = event.detail.into();
 662                    let xkb_state = state.previous_xkb_state.clone();
 663                    state.xkb.update_mask(
 664                        event.state.bits() as ModMask,
 665                        0,
 666                        0,
 667                        xkb_state.depressed_layout,
 668                        xkb_state.latched_layout,
 669                        xkb_state.locked_layout,
 670                    );
 671                    let mut keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
 672                    let keysym = state.xkb.key_get_one_sym(code);
 673                    if keysym.is_modifier_key() {
 674                        return Some(());
 675                    }
 676                    if let Some(mut compose_state) = state.compose_state.take() {
 677                        compose_state.feed(keysym);
 678                        match compose_state.status() {
 679                            xkbc::Status::Composed => {
 680                                state.pre_edit_text.take();
 681                                keystroke.ime_key = compose_state.utf8();
 682                                if let Some(keysym) = compose_state.keysym() {
 683                                    keystroke.key = xkbc::keysym_get_name(keysym);
 684                                }
 685                            }
 686                            xkbc::Status::Composing => {
 687                                keystroke.ime_key = None;
 688                                state.pre_edit_text = compose_state
 689                                    .utf8()
 690                                    .or(crate::Keystroke::underlying_dead_key(keysym));
 691                                let pre_edit =
 692                                    state.pre_edit_text.clone().unwrap_or(String::default());
 693                                drop(state);
 694                                window.handle_ime_preedit(pre_edit);
 695                                state = self.0.borrow_mut();
 696                            }
 697                            xkbc::Status::Cancelled => {
 698                                let pre_edit = state.pre_edit_text.take();
 699                                drop(state);
 700                                if let Some(pre_edit) = pre_edit {
 701                                    window.handle_ime_commit(pre_edit);
 702                                }
 703                                if let Some(current_key) = Keystroke::underlying_dead_key(keysym) {
 704                                    window.handle_ime_preedit(current_key);
 705                                }
 706                                state = self.0.borrow_mut();
 707                                compose_state.feed(keysym);
 708                            }
 709                            _ => {}
 710                        }
 711                        state.compose_state = Some(compose_state);
 712                    }
 713                    keystroke
 714                };
 715                drop(state);
 716                window.handle_input(PlatformInput::KeyDown(crate::KeyDownEvent {
 717                    keystroke,
 718                    is_held: false,
 719                }));
 720            }
 721            Event::KeyRelease(event) => {
 722                let window = self.get_window(event.event)?;
 723                let mut state = self.0.borrow_mut();
 724
 725                let modifiers = modifiers_from_state(event.state);
 726                state.modifiers = modifiers;
 727
 728                let keystroke = {
 729                    let code = event.detail.into();
 730                    let xkb_state = state.previous_xkb_state.clone();
 731                    state.xkb.update_mask(
 732                        event.state.bits() as ModMask,
 733                        0,
 734                        0,
 735                        xkb_state.depressed_layout,
 736                        xkb_state.latched_layout,
 737                        xkb_state.locked_layout,
 738                    );
 739                    let keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
 740                    let keysym = state.xkb.key_get_one_sym(code);
 741                    if keysym.is_modifier_key() {
 742                        return Some(());
 743                    }
 744                    keystroke
 745                };
 746                drop(state);
 747                window.handle_input(PlatformInput::KeyUp(crate::KeyUpEvent { keystroke }));
 748            }
 749            Event::XinputButtonPress(event) => {
 750                let window = self.get_window(event.event)?;
 751                let mut state = self.0.borrow_mut();
 752
 753                let modifiers = modifiers_from_xinput_info(event.mods);
 754                state.modifiers = modifiers;
 755
 756                let position = point(
 757                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
 758                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
 759                );
 760
 761                if state.composing && state.ximc.is_some() {
 762                    drop(state);
 763                    self.disable_ime();
 764                    self.enable_ime();
 765                    window.handle_ime_unmark();
 766                    state = self.0.borrow_mut();
 767                } else if let Some(text) = state.pre_edit_text.take() {
 768                    if let Some(compose_state) = state.compose_state.as_mut() {
 769                        compose_state.reset();
 770                    }
 771                    drop(state);
 772                    window.handle_ime_commit(text);
 773                    state = self.0.borrow_mut();
 774                }
 775                if let Some(button) = button_of_key(event.detail.try_into().unwrap()) {
 776                    let click_elapsed = state.last_click.elapsed();
 777
 778                    if click_elapsed < DOUBLE_CLICK_INTERVAL
 779                        && is_within_click_distance(state.last_location, position)
 780                    {
 781                        state.current_count += 1;
 782                    } else {
 783                        state.current_count = 1;
 784                    }
 785
 786                    state.last_click = Instant::now();
 787                    state.last_location = position;
 788                    let current_count = state.current_count;
 789
 790                    drop(state);
 791                    window.handle_input(PlatformInput::MouseDown(crate::MouseDownEvent {
 792                        button,
 793                        position,
 794                        modifiers,
 795                        click_count: current_count,
 796                        first_mouse: false,
 797                    }));
 798                } else {
 799                    log::warn!("Unknown button press: {event:?}");
 800                }
 801            }
 802            Event::XinputButtonRelease(event) => {
 803                let window = self.get_window(event.event)?;
 804                let mut state = self.0.borrow_mut();
 805                let modifiers = modifiers_from_xinput_info(event.mods);
 806                state.modifiers = modifiers;
 807
 808                let position = point(
 809                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
 810                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
 811                );
 812                if let Some(button) = button_of_key(event.detail.try_into().unwrap()) {
 813                    let click_count = state.current_count;
 814                    drop(state);
 815                    window.handle_input(PlatformInput::MouseUp(crate::MouseUpEvent {
 816                        button,
 817                        position,
 818                        modifiers,
 819                        click_count,
 820                    }));
 821                }
 822            }
 823            Event::XinputMotion(event) => {
 824                let window = self.get_window(event.event)?;
 825                let mut state = self.0.borrow_mut();
 826                let pressed_button = pressed_button_from_mask(event.button_mask[0]);
 827                let position = point(
 828                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
 829                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
 830                );
 831                let modifiers = modifiers_from_xinput_info(event.mods);
 832                state.modifiers = modifiers;
 833                drop(state);
 834
 835                let axisvalues = event
 836                    .axisvalues
 837                    .iter()
 838                    .map(|axisvalue| fp3232_to_f32(*axisvalue))
 839                    .collect::<Vec<_>>();
 840
 841                if event.valuator_mask[0] & 3 != 0 {
 842                    window.handle_input(PlatformInput::MouseMove(crate::MouseMoveEvent {
 843                        position,
 844                        pressed_button,
 845                        modifiers,
 846                    }));
 847                }
 848
 849                let mut valuator_idx = 0;
 850                let scroll_class_data = self.0.borrow().scroll_class_data.clone();
 851                for shift in 0..32 {
 852                    if (event.valuator_mask[0] >> shift) & 1 == 0 {
 853                        continue;
 854                    }
 855
 856                    for scroll_class in &scroll_class_data {
 857                        if scroll_class.scroll_type == xinput::ScrollType::HORIZONTAL
 858                            && scroll_class.number == shift
 859                        {
 860                            let new_scroll = axisvalues[valuator_idx]
 861                                / fp3232_to_f32(scroll_class.increment)
 862                                * SCROLL_LINES as f32;
 863                            let old_scroll = self.0.borrow().scroll_x;
 864                            self.0.borrow_mut().scroll_x = Some(new_scroll);
 865
 866                            if let Some(old_scroll) = old_scroll {
 867                                let delta_scroll = old_scroll - new_scroll;
 868                                window.handle_input(PlatformInput::ScrollWheel(
 869                                    crate::ScrollWheelEvent {
 870                                        position,
 871                                        delta: ScrollDelta::Lines(Point::new(delta_scroll, 0.0)),
 872                                        modifiers,
 873                                        touch_phase: TouchPhase::default(),
 874                                    },
 875                                ));
 876                            }
 877                        } else if scroll_class.scroll_type == xinput::ScrollType::VERTICAL
 878                            && scroll_class.number == shift
 879                        {
 880                            // the `increment` is the valuator delta equivalent to one positive unit of scrolling. Here that means SCROLL_LINES lines.
 881                            let new_scroll = axisvalues[valuator_idx]
 882                                / fp3232_to_f32(scroll_class.increment)
 883                                * SCROLL_LINES as f32;
 884                            let old_scroll = self.0.borrow().scroll_y;
 885                            self.0.borrow_mut().scroll_y = Some(new_scroll);
 886
 887                            if let Some(old_scroll) = old_scroll {
 888                                let delta_scroll = old_scroll - new_scroll;
 889                                let (x, y) = if !modifiers.shift {
 890                                    (0.0, delta_scroll)
 891                                } else {
 892                                    (delta_scroll, 0.0)
 893                                };
 894                                window.handle_input(PlatformInput::ScrollWheel(
 895                                    crate::ScrollWheelEvent {
 896                                        position,
 897                                        delta: ScrollDelta::Lines(Point::new(x, y)),
 898                                        modifiers,
 899                                        touch_phase: TouchPhase::default(),
 900                                    },
 901                                ));
 902                            }
 903                        }
 904                    }
 905
 906                    valuator_idx += 1;
 907                }
 908            }
 909            Event::XinputEnter(event) if event.mode == xinput::NotifyMode::NORMAL => {
 910                let window = self.get_window(event.event)?;
 911                window.set_hovered(true);
 912                let mut state = self.0.borrow_mut();
 913                state.mouse_focused_window = Some(event.event);
 914            }
 915            Event::XinputLeave(event) if event.mode == xinput::NotifyMode::NORMAL => {
 916                self.0.borrow_mut().scroll_x = None; // Set last scroll to `None` so that a large delta isn't created if scrolling is done outside the window (the valuator is global)
 917                self.0.borrow_mut().scroll_y = None;
 918
 919                let mut state = self.0.borrow_mut();
 920                state.mouse_focused_window = None;
 921                let pressed_button = pressed_button_from_mask(event.buttons[0]);
 922                let position = point(
 923                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
 924                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
 925                );
 926                let modifiers = modifiers_from_xinput_info(event.mods);
 927                state.modifiers = modifiers;
 928                drop(state);
 929
 930                let window = self.get_window(event.event)?;
 931                window.handle_input(PlatformInput::MouseExited(crate::MouseExitEvent {
 932                    pressed_button,
 933                    position,
 934                    modifiers,
 935                }));
 936                window.set_hovered(false);
 937            }
 938            _ => {}
 939        };
 940
 941        Some(())
 942    }
 943
 944    fn handle_xim_callback_event(&self, event: XimCallbackEvent) {
 945        match event {
 946            XimCallbackEvent::XimXEvent(event) => {
 947                self.handle_event(event);
 948            }
 949            XimCallbackEvent::XimCommitEvent(window, text) => {
 950                self.xim_handle_commit(window, text);
 951            }
 952            XimCallbackEvent::XimPreeditEvent(window, text) => {
 953                self.xim_handle_preedit(window, text);
 954            }
 955        };
 956    }
 957
 958    fn xim_handle_event(&self, event: Event) -> Option<()> {
 959        match event {
 960            Event::KeyPress(event) | Event::KeyRelease(event) => {
 961                let mut state = self.0.borrow_mut();
 962                state.pre_ime_key_down = Some(Keystroke::from_xkb(
 963                    &state.xkb,
 964                    state.modifiers,
 965                    event.detail.into(),
 966                ));
 967                let mut ximc = state.ximc.take().unwrap();
 968                let mut xim_handler = state.xim_handler.take().unwrap();
 969                drop(state);
 970                xim_handler.window = event.event;
 971                ximc.forward_event(
 972                    xim_handler.im_id,
 973                    xim_handler.ic_id,
 974                    xim::ForwardEventFlag::empty(),
 975                    &event,
 976                )
 977                .unwrap();
 978                let mut state = self.0.borrow_mut();
 979                state.ximc = Some(ximc);
 980                state.xim_handler = Some(xim_handler);
 981                drop(state);
 982            }
 983            event => {
 984                self.handle_event(event);
 985            }
 986        }
 987        Some(())
 988    }
 989
 990    fn xim_handle_commit(&self, window: xproto::Window, text: String) -> Option<()> {
 991        let window = self.get_window(window).unwrap();
 992        let mut state = self.0.borrow_mut();
 993        if !state.composing {
 994            if let Some(keystroke) = state.pre_ime_key_down.take() {
 995                drop(state);
 996                window.handle_input(PlatformInput::KeyDown(crate::KeyDownEvent {
 997                    keystroke,
 998                    is_held: false,
 999                }));
1000                return Some(());
1001            }
1002        }
1003        state.composing = false;
1004        drop(state);
1005
1006        window.handle_ime_commit(text);
1007        Some(())
1008    }
1009
1010    fn xim_handle_preedit(&self, window: xproto::Window, text: String) -> Option<()> {
1011        let window = self.get_window(window).unwrap();
1012        window.handle_ime_preedit(text);
1013
1014        let mut state = self.0.borrow_mut();
1015        let mut ximc = state.ximc.take().unwrap();
1016        let mut xim_handler = state.xim_handler.take().unwrap();
1017        state.composing = true;
1018        drop(state);
1019
1020        if let Some(area) = window.get_ime_area() {
1021            let ic_attributes = ximc
1022                .build_ic_attributes()
1023                .push(
1024                    xim::AttributeName::InputStyle,
1025                    xim::InputStyle::PREEDIT_CALLBACKS
1026                        | xim::InputStyle::STATUS_NOTHING
1027                        | xim::InputStyle::PREEDIT_POSITION,
1028                )
1029                .push(xim::AttributeName::ClientWindow, xim_handler.window)
1030                .push(xim::AttributeName::FocusWindow, xim_handler.window)
1031                .nested_list(xim::AttributeName::PreeditAttributes, |b| {
1032                    b.push(
1033                        xim::AttributeName::SpotLocation,
1034                        xim::Point {
1035                            x: u32::from(area.origin.x + area.size.width) as i16,
1036                            y: u32::from(area.origin.y + area.size.height) as i16,
1037                        },
1038                    );
1039                })
1040                .build();
1041            ximc.set_ic_values(xim_handler.im_id, xim_handler.ic_id, ic_attributes)
1042                .ok();
1043        }
1044        let mut state = self.0.borrow_mut();
1045        state.ximc = Some(ximc);
1046        state.xim_handler = Some(xim_handler);
1047        drop(state);
1048        Some(())
1049    }
1050}
1051
1052impl LinuxClient for X11Client {
1053    fn compositor_name(&self) -> &'static str {
1054        "X11"
1055    }
1056
1057    fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
1058        f(&mut self.0.borrow_mut().common)
1059    }
1060
1061    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1062        let state = self.0.borrow();
1063        let setup = state.xcb_connection.setup();
1064        setup
1065            .roots
1066            .iter()
1067            .enumerate()
1068            .filter_map(|(root_id, _)| {
1069                Some(Rc::new(X11Display::new(
1070                    &state.xcb_connection,
1071                    state.scale_factor,
1072                    root_id,
1073                )?) as Rc<dyn PlatformDisplay>)
1074            })
1075            .collect()
1076    }
1077
1078    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1079        let state = self.0.borrow();
1080
1081        Some(Rc::new(
1082            X11Display::new(
1083                &state.xcb_connection,
1084                state.scale_factor,
1085                state.x_root_index,
1086            )
1087            .expect("There should always be a root index"),
1088        ))
1089    }
1090
1091    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1092        let state = self.0.borrow();
1093
1094        Some(Rc::new(X11Display::new(
1095            &state.xcb_connection,
1096            state.scale_factor,
1097            id.0 as usize,
1098        )?))
1099    }
1100
1101    fn open_window(
1102        &self,
1103        handle: AnyWindowHandle,
1104        params: WindowParams,
1105    ) -> anyhow::Result<Box<dyn PlatformWindow>> {
1106        let mut state = self.0.borrow_mut();
1107        let x_window = state.xcb_connection.generate_id().unwrap();
1108
1109        let window = X11Window::new(
1110            handle,
1111            X11ClientStatePtr(Rc::downgrade(&self.0)),
1112            state.common.foreground_executor.clone(),
1113            params,
1114            &state.xcb_connection,
1115            state.client_side_decorations_supported,
1116            state.x_root_index,
1117            x_window,
1118            &state.atoms,
1119            state.scale_factor,
1120            state.common.appearance,
1121        )?;
1122
1123        let screen_resources = state
1124            .xcb_connection
1125            .randr_get_screen_resources(x_window)
1126            .unwrap()
1127            .reply()
1128            .expect("Could not find available screens");
1129
1130        let mode = screen_resources
1131            .crtcs
1132            .iter()
1133            .find_map(|crtc| {
1134                let crtc_info = state
1135                    .xcb_connection
1136                    .randr_get_crtc_info(*crtc, x11rb::CURRENT_TIME)
1137                    .ok()?
1138                    .reply()
1139                    .ok()?;
1140
1141                screen_resources
1142                    .modes
1143                    .iter()
1144                    .find(|m| m.id == crtc_info.mode)
1145            })
1146            .expect("Unable to find screen refresh rate");
1147
1148        let refresh_event_token = state
1149            .loop_handle
1150            .insert_source(calloop::timer::Timer::immediate(), {
1151                let refresh_duration = mode_refresh_rate(mode);
1152                move |mut instant, (), client| {
1153                    let xcb_connection = {
1154                        let state = client.0.borrow_mut();
1155                        let xcb_connection = state.xcb_connection.clone();
1156                        if let Some(window) = state.windows.get(&x_window) {
1157                            let window = window.window.clone();
1158                            drop(state);
1159                            window.refresh();
1160                        }
1161                        xcb_connection
1162                    };
1163                    client.process_x11_events(&xcb_connection).log_err();
1164
1165                    // Take into account that some frames have been skipped
1166                    let now = Instant::now();
1167                    while instant < now {
1168                        instant += refresh_duration;
1169                    }
1170                    calloop::timer::TimeoutAction::ToInstant(instant)
1171                }
1172            })
1173            .expect("Failed to initialize refresh timer");
1174
1175        let window_ref = WindowRef {
1176            window: window.0.clone(),
1177            refresh_event_token,
1178        };
1179
1180        state.windows.insert(x_window, window_ref);
1181        Ok(Box::new(window))
1182    }
1183
1184    fn set_cursor_style(&self, style: CursorStyle) {
1185        let mut state = self.0.borrow_mut();
1186        let Some(focused_window) = state.mouse_focused_window else {
1187            return;
1188        };
1189        let current_style = state
1190            .cursor_styles
1191            .get(&focused_window)
1192            .unwrap_or(&CursorStyle::Arrow);
1193        if *current_style == style {
1194            return;
1195        }
1196
1197        let cursor = match state.cursor_cache.get(&style) {
1198            Some(cursor) => *cursor,
1199            None => {
1200                let Some(cursor) = state
1201                    .cursor_handle
1202                    .load_cursor(&state.xcb_connection, &style.to_icon_name())
1203                    .log_err()
1204                else {
1205                    return;
1206                };
1207                state.cursor_cache.insert(style, cursor);
1208                cursor
1209            }
1210        };
1211
1212        state.cursor_styles.insert(focused_window, style);
1213        state
1214            .xcb_connection
1215            .change_window_attributes(
1216                focused_window,
1217                &ChangeWindowAttributesAux {
1218                    cursor: Some(cursor),
1219                    ..Default::default()
1220                },
1221            )
1222            .expect("failed to change window cursor")
1223            .check()
1224            .unwrap();
1225    }
1226
1227    fn open_uri(&self, uri: &str) {
1228        open_uri_internal(self.background_executor(), uri, None);
1229    }
1230
1231    fn reveal_path(&self, path: PathBuf) {
1232        reveal_path_internal(self.background_executor(), path, None);
1233    }
1234
1235    fn write_to_primary(&self, item: crate::ClipboardItem) {
1236        let state = self.0.borrow_mut();
1237        state
1238            .clipboard
1239            .store(
1240                state.clipboard.setter.atoms.primary,
1241                state.clipboard.setter.atoms.utf8_string,
1242                item.text().as_bytes(),
1243            )
1244            .ok();
1245    }
1246
1247    fn write_to_clipboard(&self, item: crate::ClipboardItem) {
1248        let mut state = self.0.borrow_mut();
1249        state
1250            .clipboard
1251            .store(
1252                state.clipboard.setter.atoms.clipboard,
1253                state.clipboard.setter.atoms.utf8_string,
1254                item.text().as_bytes(),
1255            )
1256            .ok();
1257        state.clipboard_item.replace(item);
1258    }
1259
1260    fn read_from_primary(&self) -> Option<crate::ClipboardItem> {
1261        let state = self.0.borrow_mut();
1262        state
1263            .clipboard
1264            .load(
1265                state.clipboard.getter.atoms.primary,
1266                state.clipboard.getter.atoms.utf8_string,
1267                state.clipboard.getter.atoms.property,
1268                Duration::from_secs(3),
1269            )
1270            .map(|text| crate::ClipboardItem {
1271                text: String::from_utf8(text).unwrap(),
1272                metadata: None,
1273            })
1274            .ok()
1275    }
1276
1277    fn read_from_clipboard(&self) -> Option<crate::ClipboardItem> {
1278        let state = self.0.borrow_mut();
1279        // if the last copy was from this app, return our cached item
1280        // which has metadata attached.
1281        if state
1282            .clipboard
1283            .setter
1284            .connection
1285            .get_selection_owner(state.clipboard.setter.atoms.clipboard)
1286            .ok()
1287            .and_then(|r| r.reply().ok())
1288            .map(|reply| reply.owner == state.clipboard.setter.window)
1289            .unwrap_or(false)
1290        {
1291            return state.clipboard_item.clone();
1292        }
1293        state
1294            .clipboard
1295            .load(
1296                state.clipboard.getter.atoms.clipboard,
1297                state.clipboard.getter.atoms.utf8_string,
1298                state.clipboard.getter.atoms.property,
1299                Duration::from_secs(3),
1300            )
1301            .map(|text| crate::ClipboardItem {
1302                text: String::from_utf8(text).unwrap(),
1303                metadata: None,
1304            })
1305            .ok()
1306    }
1307
1308    fn run(&self) {
1309        let mut event_loop = self
1310            .0
1311            .borrow_mut()
1312            .event_loop
1313            .take()
1314            .expect("App is already running");
1315
1316        event_loop.run(None, &mut self.clone(), |_| {}).log_err();
1317    }
1318
1319    fn active_window(&self) -> Option<AnyWindowHandle> {
1320        let state = self.0.borrow();
1321        state.keyboard_focused_window.and_then(|focused_window| {
1322            state
1323                .windows
1324                .get(&focused_window)
1325                .map(|window| window.handle())
1326        })
1327    }
1328}
1329
1330// Adatpted from:
1331// https://docs.rs/winit/0.29.11/src/winit/platform_impl/linux/x11/monitor.rs.html#103-111
1332pub fn mode_refresh_rate(mode: &randr::ModeInfo) -> Duration {
1333    if mode.dot_clock == 0 || mode.htotal == 0 || mode.vtotal == 0 {
1334        return Duration::from_millis(16);
1335    }
1336
1337    let millihertz = mode.dot_clock as u64 * 1_000 / (mode.htotal as u64 * mode.vtotal as u64);
1338    let micros = 1_000_000_000 / millihertz;
1339    log::info!("Refreshing at {} micros", micros);
1340    Duration::from_micros(micros)
1341}
1342
1343fn fp3232_to_f32(value: xinput::Fp3232) -> f32 {
1344    value.integral as f32 + value.frac as f32 / u32::MAX as f32
1345}
1346
1347fn check_compositor_present(xcb_connection: &XCBConnection, root: u32) -> bool {
1348    // Method 1: Check for _NET_WM_CM_S{root}
1349    let atom_name = format!("_NET_WM_CM_S{}", root);
1350    let atom = xcb_connection
1351        .intern_atom(false, atom_name.as_bytes())
1352        .unwrap()
1353        .reply()
1354        .map(|reply| reply.atom)
1355        .unwrap_or(0);
1356
1357    let method1 = if atom != 0 {
1358        xcb_connection
1359            .get_selection_owner(atom)
1360            .unwrap()
1361            .reply()
1362            .map(|reply| reply.owner != 0)
1363            .unwrap_or(false)
1364    } else {
1365        false
1366    };
1367
1368    // Method 2: Check for _NET_WM_CM_OWNER
1369    let atom_name = "_NET_WM_CM_OWNER";
1370    let atom = xcb_connection
1371        .intern_atom(false, atom_name.as_bytes())
1372        .unwrap()
1373        .reply()
1374        .map(|reply| reply.atom)
1375        .unwrap_or(0);
1376
1377    let method2 = if atom != 0 {
1378        xcb_connection
1379            .get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1)
1380            .unwrap()
1381            .reply()
1382            .map(|reply| reply.value_len > 0)
1383            .unwrap_or(false)
1384    } else {
1385        false
1386    };
1387
1388    // Method 3: Check for _NET_SUPPORTING_WM_CHECK
1389    let atom_name = "_NET_SUPPORTING_WM_CHECK";
1390    let atom = xcb_connection
1391        .intern_atom(false, atom_name.as_bytes())
1392        .unwrap()
1393        .reply()
1394        .map(|reply| reply.atom)
1395        .unwrap_or(0);
1396
1397    let method3 = if atom != 0 {
1398        xcb_connection
1399            .get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1)
1400            .unwrap()
1401            .reply()
1402            .map(|reply| reply.value_len > 0)
1403            .unwrap_or(false)
1404    } else {
1405        false
1406    };
1407
1408    // TODO: Remove this
1409    log::info!(
1410        "Compositor detection: _NET_WM_CM_S?={}, _NET_WM_CM_OWNER={}, _NET_SUPPORTING_WM_CHECK={}",
1411        method1,
1412        method2,
1413        method3
1414    );
1415
1416    method1 || method2 || method3
1417}
1418
1419fn check_gtk_frame_extents_supported(
1420    xcb_connection: &XCBConnection,
1421    atoms: &XcbAtoms,
1422    root: xproto::Window,
1423) -> bool {
1424    let supported_atoms = xcb_connection
1425        .get_property(
1426            false,
1427            root,
1428            atoms._NET_SUPPORTED,
1429            xproto::AtomEnum::ATOM,
1430            0,
1431            1024,
1432        )
1433        .unwrap()
1434        .reply()
1435        .map(|reply| {
1436            // Convert Vec<u8> to Vec<u32>
1437            reply
1438                .value
1439                .chunks_exact(4)
1440                .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
1441                .collect::<Vec<u32>>()
1442        })
1443        .unwrap_or_default();
1444
1445    supported_atoms.contains(&atoms._GTK_FRAME_EXTENTS)
1446}