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