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        let keystroke = state.pre_ime_key_down.take();
 994        state.composing = false;
 995        drop(state);
 996        if let Some(mut keystroke) = keystroke {
 997            keystroke.ime_key = Some(text.clone());
 998            window.handle_input(PlatformInput::KeyDown(crate::KeyDownEvent {
 999                keystroke,
1000                is_held: false,
1001            }));
1002        }
1003
1004        Some(())
1005    }
1006
1007    fn xim_handle_preedit(&self, window: xproto::Window, text: String) -> Option<()> {
1008        let window = self.get_window(window).unwrap();
1009        window.handle_ime_preedit(text);
1010
1011        let mut state = self.0.borrow_mut();
1012        let mut ximc = state.ximc.take().unwrap();
1013        let mut xim_handler = state.xim_handler.take().unwrap();
1014        state.composing = true;
1015        drop(state);
1016
1017        if let Some(area) = window.get_ime_area() {
1018            let ic_attributes = ximc
1019                .build_ic_attributes()
1020                .push(
1021                    xim::AttributeName::InputStyle,
1022                    xim::InputStyle::PREEDIT_CALLBACKS
1023                        | xim::InputStyle::STATUS_NOTHING
1024                        | xim::InputStyle::PREEDIT_POSITION,
1025                )
1026                .push(xim::AttributeName::ClientWindow, xim_handler.window)
1027                .push(xim::AttributeName::FocusWindow, xim_handler.window)
1028                .nested_list(xim::AttributeName::PreeditAttributes, |b| {
1029                    b.push(
1030                        xim::AttributeName::SpotLocation,
1031                        xim::Point {
1032                            x: u32::from(area.origin.x + area.size.width) as i16,
1033                            y: u32::from(area.origin.y + area.size.height) as i16,
1034                        },
1035                    );
1036                })
1037                .build();
1038            ximc.set_ic_values(xim_handler.im_id, xim_handler.ic_id, ic_attributes)
1039                .ok();
1040        }
1041        let mut state = self.0.borrow_mut();
1042        state.ximc = Some(ximc);
1043        state.xim_handler = Some(xim_handler);
1044        drop(state);
1045        Some(())
1046    }
1047}
1048
1049impl LinuxClient for X11Client {
1050    fn compositor_name(&self) -> &'static str {
1051        "X11"
1052    }
1053
1054    fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
1055        f(&mut self.0.borrow_mut().common)
1056    }
1057
1058    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1059        let state = self.0.borrow();
1060        let setup = state.xcb_connection.setup();
1061        setup
1062            .roots
1063            .iter()
1064            .enumerate()
1065            .filter_map(|(root_id, _)| {
1066                Some(Rc::new(X11Display::new(
1067                    &state.xcb_connection,
1068                    state.scale_factor,
1069                    root_id,
1070                )?) as Rc<dyn PlatformDisplay>)
1071            })
1072            .collect()
1073    }
1074
1075    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1076        let state = self.0.borrow();
1077
1078        Some(Rc::new(
1079            X11Display::new(
1080                &state.xcb_connection,
1081                state.scale_factor,
1082                state.x_root_index,
1083            )
1084            .expect("There should always be a root index"),
1085        ))
1086    }
1087
1088    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1089        let state = self.0.borrow();
1090
1091        Some(Rc::new(X11Display::new(
1092            &state.xcb_connection,
1093            state.scale_factor,
1094            id.0 as usize,
1095        )?))
1096    }
1097
1098    fn open_window(
1099        &self,
1100        handle: AnyWindowHandle,
1101        params: WindowParams,
1102    ) -> anyhow::Result<Box<dyn PlatformWindow>> {
1103        let mut state = self.0.borrow_mut();
1104        let x_window = state.xcb_connection.generate_id().unwrap();
1105
1106        let window = X11Window::new(
1107            handle,
1108            X11ClientStatePtr(Rc::downgrade(&self.0)),
1109            state.common.foreground_executor.clone(),
1110            params,
1111            &state.xcb_connection,
1112            state.client_side_decorations_supported,
1113            state.x_root_index,
1114            x_window,
1115            &state.atoms,
1116            state.scale_factor,
1117            state.common.appearance,
1118        )?;
1119
1120        let screen_resources = state
1121            .xcb_connection
1122            .randr_get_screen_resources(x_window)
1123            .unwrap()
1124            .reply()
1125            .expect("Could not find available screens");
1126
1127        let mode = screen_resources
1128            .crtcs
1129            .iter()
1130            .find_map(|crtc| {
1131                let crtc_info = state
1132                    .xcb_connection
1133                    .randr_get_crtc_info(*crtc, x11rb::CURRENT_TIME)
1134                    .ok()?
1135                    .reply()
1136                    .ok()?;
1137
1138                screen_resources
1139                    .modes
1140                    .iter()
1141                    .find(|m| m.id == crtc_info.mode)
1142            })
1143            .expect("Unable to find screen refresh rate");
1144
1145        let refresh_event_token = state
1146            .loop_handle
1147            .insert_source(calloop::timer::Timer::immediate(), {
1148                let refresh_duration = mode_refresh_rate(mode);
1149                move |mut instant, (), client| {
1150                    let xcb_connection = {
1151                        let state = client.0.borrow_mut();
1152                        let xcb_connection = state.xcb_connection.clone();
1153                        if let Some(window) = state.windows.get(&x_window) {
1154                            let window = window.window.clone();
1155                            drop(state);
1156                            window.refresh();
1157                        }
1158                        xcb_connection
1159                    };
1160                    client.process_x11_events(&xcb_connection).log_err();
1161
1162                    // Take into account that some frames have been skipped
1163                    let now = Instant::now();
1164                    while instant < now {
1165                        instant += refresh_duration;
1166                    }
1167                    calloop::timer::TimeoutAction::ToInstant(instant)
1168                }
1169            })
1170            .expect("Failed to initialize refresh timer");
1171
1172        let window_ref = WindowRef {
1173            window: window.0.clone(),
1174            refresh_event_token,
1175        };
1176
1177        state.windows.insert(x_window, window_ref);
1178        Ok(Box::new(window))
1179    }
1180
1181    fn set_cursor_style(&self, style: CursorStyle) {
1182        let mut state = self.0.borrow_mut();
1183        let Some(focused_window) = state.mouse_focused_window else {
1184            return;
1185        };
1186        let current_style = state
1187            .cursor_styles
1188            .get(&focused_window)
1189            .unwrap_or(&CursorStyle::Arrow);
1190        if *current_style == style {
1191            return;
1192        }
1193
1194        let cursor = match state.cursor_cache.get(&style) {
1195            Some(cursor) => *cursor,
1196            None => {
1197                let Some(cursor) = state
1198                    .cursor_handle
1199                    .load_cursor(&state.xcb_connection, &style.to_icon_name())
1200                    .log_err()
1201                else {
1202                    return;
1203                };
1204                state.cursor_cache.insert(style, cursor);
1205                cursor
1206            }
1207        };
1208
1209        state.cursor_styles.insert(focused_window, style);
1210        state
1211            .xcb_connection
1212            .change_window_attributes(
1213                focused_window,
1214                &ChangeWindowAttributesAux {
1215                    cursor: Some(cursor),
1216                    ..Default::default()
1217                },
1218            )
1219            .expect("failed to change window cursor")
1220            .check()
1221            .unwrap();
1222    }
1223
1224    fn open_uri(&self, uri: &str) {
1225        open_uri_internal(self.background_executor(), uri, None);
1226    }
1227
1228    fn reveal_path(&self, path: PathBuf) {
1229        reveal_path_internal(self.background_executor(), path, None);
1230    }
1231
1232    fn write_to_primary(&self, item: crate::ClipboardItem) {
1233        let state = self.0.borrow_mut();
1234        state
1235            .clipboard
1236            .store(
1237                state.clipboard.setter.atoms.primary,
1238                state.clipboard.setter.atoms.utf8_string,
1239                item.text().as_bytes(),
1240            )
1241            .ok();
1242    }
1243
1244    fn write_to_clipboard(&self, item: crate::ClipboardItem) {
1245        let mut state = self.0.borrow_mut();
1246        state
1247            .clipboard
1248            .store(
1249                state.clipboard.setter.atoms.clipboard,
1250                state.clipboard.setter.atoms.utf8_string,
1251                item.text().as_bytes(),
1252            )
1253            .ok();
1254        state.clipboard_item.replace(item);
1255    }
1256
1257    fn read_from_primary(&self) -> Option<crate::ClipboardItem> {
1258        let state = self.0.borrow_mut();
1259        state
1260            .clipboard
1261            .load(
1262                state.clipboard.getter.atoms.primary,
1263                state.clipboard.getter.atoms.utf8_string,
1264                state.clipboard.getter.atoms.property,
1265                Duration::from_secs(3),
1266            )
1267            .map(|text| crate::ClipboardItem {
1268                text: String::from_utf8(text).unwrap(),
1269                metadata: None,
1270            })
1271            .ok()
1272    }
1273
1274    fn read_from_clipboard(&self) -> Option<crate::ClipboardItem> {
1275        let state = self.0.borrow_mut();
1276        // if the last copy was from this app, return our cached item
1277        // which has metadata attached.
1278        if state
1279            .clipboard
1280            .setter
1281            .connection
1282            .get_selection_owner(state.clipboard.setter.atoms.clipboard)
1283            .ok()
1284            .and_then(|r| r.reply().ok())
1285            .map(|reply| reply.owner == state.clipboard.setter.window)
1286            .unwrap_or(false)
1287        {
1288            return state.clipboard_item.clone();
1289        }
1290        state
1291            .clipboard
1292            .load(
1293                state.clipboard.getter.atoms.clipboard,
1294                state.clipboard.getter.atoms.utf8_string,
1295                state.clipboard.getter.atoms.property,
1296                Duration::from_secs(3),
1297            )
1298            .map(|text| crate::ClipboardItem {
1299                text: String::from_utf8(text).unwrap(),
1300                metadata: None,
1301            })
1302            .ok()
1303    }
1304
1305    fn run(&self) {
1306        let mut event_loop = self
1307            .0
1308            .borrow_mut()
1309            .event_loop
1310            .take()
1311            .expect("App is already running");
1312
1313        event_loop.run(None, &mut self.clone(), |_| {}).log_err();
1314    }
1315
1316    fn active_window(&self) -> Option<AnyWindowHandle> {
1317        let state = self.0.borrow();
1318        state.keyboard_focused_window.and_then(|focused_window| {
1319            state
1320                .windows
1321                .get(&focused_window)
1322                .map(|window| window.handle())
1323        })
1324    }
1325}
1326
1327// Adatpted from:
1328// https://docs.rs/winit/0.29.11/src/winit/platform_impl/linux/x11/monitor.rs.html#103-111
1329pub fn mode_refresh_rate(mode: &randr::ModeInfo) -> Duration {
1330    if mode.dot_clock == 0 || mode.htotal == 0 || mode.vtotal == 0 {
1331        return Duration::from_millis(16);
1332    }
1333
1334    let millihertz = mode.dot_clock as u64 * 1_000 / (mode.htotal as u64 * mode.vtotal as u64);
1335    let micros = 1_000_000_000 / millihertz;
1336    log::info!("Refreshing at {} micros", micros);
1337    Duration::from_micros(micros)
1338}
1339
1340fn fp3232_to_f32(value: xinput::Fp3232) -> f32 {
1341    value.integral as f32 + value.frac as f32 / u32::MAX as f32
1342}
1343
1344fn check_compositor_present(xcb_connection: &XCBConnection, root: u32) -> bool {
1345    // Method 1: Check for _NET_WM_CM_S{root}
1346    let atom_name = format!("_NET_WM_CM_S{}", root);
1347    let atom = xcb_connection
1348        .intern_atom(false, atom_name.as_bytes())
1349        .unwrap()
1350        .reply()
1351        .map(|reply| reply.atom)
1352        .unwrap_or(0);
1353
1354    let method1 = if atom != 0 {
1355        xcb_connection
1356            .get_selection_owner(atom)
1357            .unwrap()
1358            .reply()
1359            .map(|reply| reply.owner != 0)
1360            .unwrap_or(false)
1361    } else {
1362        false
1363    };
1364
1365    // Method 2: Check for _NET_WM_CM_OWNER
1366    let atom_name = "_NET_WM_CM_OWNER";
1367    let atom = xcb_connection
1368        .intern_atom(false, atom_name.as_bytes())
1369        .unwrap()
1370        .reply()
1371        .map(|reply| reply.atom)
1372        .unwrap_or(0);
1373
1374    let method2 = if atom != 0 {
1375        xcb_connection
1376            .get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1)
1377            .unwrap()
1378            .reply()
1379            .map(|reply| reply.value_len > 0)
1380            .unwrap_or(false)
1381    } else {
1382        false
1383    };
1384
1385    // Method 3: Check for _NET_SUPPORTING_WM_CHECK
1386    let atom_name = "_NET_SUPPORTING_WM_CHECK";
1387    let atom = xcb_connection
1388        .intern_atom(false, atom_name.as_bytes())
1389        .unwrap()
1390        .reply()
1391        .map(|reply| reply.atom)
1392        .unwrap_or(0);
1393
1394    let method3 = if atom != 0 {
1395        xcb_connection
1396            .get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1)
1397            .unwrap()
1398            .reply()
1399            .map(|reply| reply.value_len > 0)
1400            .unwrap_or(false)
1401    } else {
1402        false
1403    };
1404
1405    // TODO: Remove this
1406    log::info!(
1407        "Compositor detection: _NET_WM_CM_S?={}, _NET_WM_CM_OWNER={}, _NET_SUPPORTING_WM_CHECK={}",
1408        method1,
1409        method2,
1410        method3
1411    );
1412
1413    method1 || method2 || method3
1414}
1415
1416fn check_gtk_frame_extents_supported(
1417    xcb_connection: &XCBConnection,
1418    atoms: &XcbAtoms,
1419    root: xproto::Window,
1420) -> bool {
1421    let supported_atoms = xcb_connection
1422        .get_property(
1423            false,
1424            root,
1425            atoms._NET_SUPPORTED,
1426            xproto::AtomEnum::ATOM,
1427            0,
1428            1024,
1429        )
1430        .unwrap()
1431        .reply()
1432        .map(|reply| {
1433            // Convert Vec<u8> to Vec<u32>
1434            reply
1435                .value
1436                .chunks_exact(4)
1437                .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
1438                .collect::<Vec<u32>>()
1439        })
1440        .unwrap_or_default();
1441
1442    supported_atoms.contains(&atoms._GTK_FRAME_EXTENTS)
1443}