client.rs

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