client.rs

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