client.rs

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