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::{channel, 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, |event, _, _: &mut X11Client| {
 169                if let calloop::channel::Event::Msg(runnable) = event {
 170                    runnable.run();
 171                }
 172            })
 173            .unwrap();
 174
 175        let (xcb_connection, x_root_index) = XCBConnection::connect(None).unwrap();
 176        xcb_connection
 177            .prefetch_extension_information(xkb::X11_EXTENSION_NAME)
 178            .unwrap();
 179        xcb_connection
 180            .prefetch_extension_information(randr::X11_EXTENSION_NAME)
 181            .unwrap();
 182        xcb_connection
 183            .prefetch_extension_information(render::X11_EXTENSION_NAME)
 184            .unwrap();
 185        xcb_connection
 186            .prefetch_extension_information(xinput::X11_EXTENSION_NAME)
 187            .unwrap();
 188
 189        let xinput_version = xcb_connection
 190            .xinput_xi_query_version(2, 0)
 191            .unwrap()
 192            .reply()
 193            .unwrap();
 194        assert!(
 195            xinput_version.major_version >= 2,
 196            "XInput Extension v2 not supported."
 197        );
 198
 199        let master_device_query = xcb_connection
 200            .xinput_xi_query_device(XINPUT_MASTER_DEVICE)
 201            .unwrap()
 202            .reply()
 203            .unwrap();
 204        let scroll_class_data = master_device_query
 205            .infos
 206            .iter()
 207            .find(|info| info.type_ == xinput::DeviceType::MASTER_POINTER)
 208            .unwrap()
 209            .classes
 210            .iter()
 211            .filter_map(|class| class.data.as_scroll())
 212            .map(|class| *class)
 213            .collect::<Vec<_>>();
 214
 215        let atoms = XcbAtoms::new(&xcb_connection).unwrap();
 216        let xkb = xcb_connection
 217            .xkb_use_extension(XKB_X11_MIN_MAJOR_XKB_VERSION, XKB_X11_MIN_MINOR_XKB_VERSION)
 218            .unwrap();
 219
 220        let atoms = atoms.reply().unwrap();
 221        let xkb = xkb.reply().unwrap();
 222        let events = xkb::EventType::STATE_NOTIFY;
 223        xcb_connection
 224            .xkb_select_events(
 225                xkb::ID::USE_CORE_KBD.into(),
 226                0u8.into(),
 227                events,
 228                0u8.into(),
 229                0u8.into(),
 230                &xkb::SelectEventsAux::new(),
 231            )
 232            .unwrap();
 233        assert!(xkb.supported);
 234
 235        let xkb_context = xkbc::Context::new(xkbc::CONTEXT_NO_FLAGS);
 236        let xkb_state = {
 237            let xkb_device_id = xkbc::x11::get_core_keyboard_device_id(&xcb_connection);
 238            let xkb_keymap = xkbc::x11::keymap_new_from_device(
 239                &xkb_context,
 240                &xcb_connection,
 241                xkb_device_id,
 242                xkbc::KEYMAP_COMPILE_NO_FLAGS,
 243            );
 244            xkbc::x11::state_new_from_device(&xkb_keymap, &xcb_connection, xkb_device_id)
 245        };
 246        let compose_state = {
 247            let locale = std::env::var_os("LC_CTYPE").unwrap_or(OsString::from("C"));
 248            let table = xkbc::compose::Table::new_from_locale(
 249                &xkb_context,
 250                &locale,
 251                xkbc::compose::COMPILE_NO_FLAGS,
 252            )
 253            .log_err()
 254            .unwrap();
 255            xkbc::compose::State::new(&table, xkbc::compose::STATE_NO_FLAGS)
 256        };
 257
 258        let resource_database = x11rb::resource_manager::new_from_default(&xcb_connection).unwrap();
 259
 260        let scale_factor = resource_database
 261            .get_value("Xft.dpi", "Xft.dpi")
 262            .ok()
 263            .flatten()
 264            .map(|dpi: f32| dpi / 96.0)
 265            .unwrap_or(1.0);
 266
 267        let cursor_handle = cursor::Handle::new(&xcb_connection, x_root_index, &resource_database)
 268            .unwrap()
 269            .reply()
 270            .unwrap();
 271
 272        let clipboard = X11ClipboardContext::<Clipboard>::new().unwrap();
 273        let primary = X11ClipboardContext::<Primary>::new().unwrap();
 274
 275        let xcb_connection = Rc::new(xcb_connection);
 276
 277        let (xim_tx, xim_rx) = channel::channel::<XimCallbackEvent>();
 278
 279        let ximc = X11rbClient::init(Rc::clone(&xcb_connection), x_root_index, None).ok();
 280        let xim_handler = if ximc.is_some() {
 281            Some(XimHandler::new(xim_tx))
 282        } else {
 283            None
 284        };
 285
 286        // Safety: Safe if xcb::Connection always returns a valid fd
 287        let fd = unsafe { FdWrapper::new(Rc::clone(&xcb_connection)) };
 288
 289        handle
 290            .insert_source(
 291                Generic::new_with_error::<EventHandlerError>(
 292                    fd,
 293                    calloop::Interest::READ,
 294                    calloop::Mode::Level,
 295                ),
 296                {
 297                    let xcb_connection = xcb_connection.clone();
 298                    move |_readiness, _, client| {
 299                        while let Some(event) = xcb_connection.poll_for_event()? {
 300                            let mut state = client.0.borrow_mut();
 301                            if state.ximc.is_none() || state.xim_handler.is_none() {
 302                                drop(state);
 303                                client.handle_event(event);
 304                                continue;
 305                            }
 306                            let mut ximc = state.ximc.take().unwrap();
 307                            let mut xim_handler = state.xim_handler.take().unwrap();
 308                            let xim_connected = xim_handler.connected;
 309                            drop(state);
 310                            let xim_filtered = match ximc.filter_event(&event, &mut xim_handler) {
 311                                Ok(handled) => handled,
 312                                Err(err) => {
 313                                    log::error!("XIMClientError: {}", err);
 314                                    false
 315                                }
 316                            };
 317                            let mut state = client.0.borrow_mut();
 318                            state.ximc = Some(ximc);
 319                            state.xim_handler = Some(xim_handler);
 320                            drop(state);
 321                            if xim_filtered {
 322                                continue;
 323                            }
 324                            if xim_connected {
 325                                client.xim_handle_event(event);
 326                            } else {
 327                                client.handle_event(event);
 328                            }
 329                        }
 330                        Ok(calloop::PostAction::Continue)
 331                    }
 332                },
 333            )
 334            .expect("Failed to initialize x11 event source");
 335        handle
 336            .insert_source(xim_rx, {
 337                move |chan_event, _, client| match chan_event {
 338                    channel::Event::Msg(xim_event) => {
 339                        match xim_event {
 340                            XimCallbackEvent::XimXEvent(event) => {
 341                                client.handle_event(event);
 342                            }
 343                            XimCallbackEvent::XimCommitEvent(window, text) => {
 344                                client.xim_handle_commit(window, text);
 345                            }
 346                            XimCallbackEvent::XimPreeditEvent(window, text) => {
 347                                client.xim_handle_preedit(window, text);
 348                            }
 349                        };
 350                    }
 351                    channel::Event::Closed => {
 352                        log::error!("XIM Event Sender dropped")
 353                    }
 354                }
 355            })
 356            .expect("Failed to initialize XIM event source");
 357        handle
 358            .insert_source(XDPEventSource::new(&common.background_executor), {
 359                move |event, _, client| match event {
 360                    XDPEvent::WindowAppearance(appearance) => {
 361                        client.with_common(|common| common.appearance = appearance);
 362                        for (_, window) in &mut client.0.borrow_mut().windows {
 363                            window.window.set_appearance(appearance);
 364                        }
 365                    }
 366                }
 367            })
 368            .unwrap();
 369
 370        X11Client(Rc::new(RefCell::new(X11ClientState {
 371            modifiers: Modifiers::default(),
 372            event_loop: Some(event_loop),
 373            loop_handle: handle,
 374            common,
 375            last_click: Instant::now(),
 376            last_location: Point::new(px(0.0), px(0.0)),
 377            current_count: 0,
 378            scale_factor,
 379
 380            xcb_connection,
 381            x_root_index,
 382            _resource_database: resource_database,
 383            atoms,
 384            windows: HashMap::default(),
 385            focused_window: None,
 386            xkb: xkb_state,
 387            ximc,
 388            xim_handler,
 389
 390            compose_state: compose_state,
 391            pre_edit_text: None,
 392            composing: false,
 393
 394            cursor_handle,
 395            cursor_styles: HashMap::default(),
 396            cursor_cache: HashMap::default(),
 397
 398            scroll_class_data,
 399            scroll_x: None,
 400            scroll_y: None,
 401
 402            clipboard,
 403            primary,
 404        })))
 405    }
 406
 407    pub fn enable_ime(&self) {
 408        let mut state = self.0.borrow_mut();
 409        if state.ximc.is_none() {
 410            return;
 411        }
 412
 413        let mut ximc = state.ximc.take().unwrap();
 414        let mut xim_handler = state.xim_handler.take().unwrap();
 415        let mut ic_attributes = ximc
 416            .build_ic_attributes()
 417            .push(
 418                AttributeName::InputStyle,
 419                InputStyle::PREEDIT_CALLBACKS
 420                    | InputStyle::STATUS_NOTHING
 421                    | InputStyle::PREEDIT_NONE,
 422            )
 423            .push(AttributeName::ClientWindow, xim_handler.window)
 424            .push(AttributeName::FocusWindow, xim_handler.window);
 425
 426        let window_id = state.focused_window;
 427        drop(state);
 428        if let Some(window_id) = window_id {
 429            let window = self.get_window(window_id).unwrap();
 430            if let Some(area) = window.get_ime_area() {
 431                ic_attributes =
 432                    ic_attributes.nested_list(xim::AttributeName::PreeditAttributes, |b| {
 433                        b.push(
 434                            xim::AttributeName::SpotLocation,
 435                            xim::Point {
 436                                x: u32::from(area.origin.x + area.size.width) as i16,
 437                                y: u32::from(area.origin.y + area.size.height) as i16,
 438                            },
 439                        );
 440                    });
 441            }
 442        }
 443        ximc.create_ic(xim_handler.im_id, ic_attributes.build())
 444            .ok();
 445        state = self.0.borrow_mut();
 446        state.xim_handler = Some(xim_handler);
 447        state.ximc = Some(ximc);
 448    }
 449
 450    pub fn disable_ime(&self) {
 451        let mut state = self.0.borrow_mut();
 452        state.composing = false;
 453        if let Some(mut ximc) = state.ximc.take() {
 454            let xim_handler = state.xim_handler.as_ref().unwrap();
 455            ximc.destroy_ic(xim_handler.im_id, xim_handler.ic_id).ok();
 456            state.ximc = Some(ximc);
 457        }
 458    }
 459
 460    fn get_window(&self, win: xproto::Window) -> Option<X11WindowStatePtr> {
 461        let state = self.0.borrow();
 462        state
 463            .windows
 464            .get(&win)
 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                let modifiers = Modifiers::from_xkb(&state.xkb);
 532                let focused_window_id = state.focused_window?;
 533                state.modifiers = modifiers;
 534                drop(state);
 535
 536                let focused_window = self.get_window(focused_window_id)?;
 537                focused_window.handle_input(PlatformInput::ModifiersChanged(
 538                    ModifiersChangedEvent { modifiers },
 539                ));
 540            }
 541            Event::KeyPress(event) => {
 542                let window = self.get_window(event.event)?;
 543                let mut state = self.0.borrow_mut();
 544
 545                let modifiers = modifiers_from_state(event.state);
 546                state.modifiers = modifiers;
 547
 548                let keystroke = {
 549                    let code = event.detail.into();
 550                    let mut keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
 551                    state.xkb.update_key(code, xkbc::KeyDirection::Down);
 552                    let keysym = state.xkb.key_get_one_sym(code);
 553                    if keysym.is_modifier_key() {
 554                        return Some(());
 555                    }
 556                    state.compose_state.feed(keysym);
 557                    match state.compose_state.status() {
 558                        xkbc::Status::Composed => {
 559                            state.pre_edit_text.take();
 560                            keystroke.ime_key = state.compose_state.utf8();
 561                            keystroke.key =
 562                                xkbc::keysym_get_name(state.compose_state.keysym().unwrap());
 563                        }
 564                        xkbc::Status::Composing => {
 565                            state.pre_edit_text = state
 566                                .compose_state
 567                                .utf8()
 568                                .or(crate::Keystroke::underlying_dead_key(keysym));
 569                            let pre_edit = state.pre_edit_text.clone().unwrap_or(String::default());
 570                            drop(state);
 571                            window.handle_ime_preedit(pre_edit);
 572                            state = self.0.borrow_mut();
 573                        }
 574                        xkbc::Status::Cancelled => {
 575                            let pre_edit = state.pre_edit_text.take();
 576                            drop(state);
 577                            if let Some(pre_edit) = pre_edit {
 578                                window.handle_ime_commit(pre_edit);
 579                            }
 580                            if let Some(current_key) = Keystroke::underlying_dead_key(keysym) {
 581                                window.handle_ime_preedit(current_key);
 582                            }
 583                            state = self.0.borrow_mut();
 584                            state.compose_state.feed(keysym);
 585                        }
 586                        _ => {}
 587                    }
 588                    keystroke
 589                };
 590                drop(state);
 591                window.handle_input(PlatformInput::KeyDown(crate::KeyDownEvent {
 592                    keystroke,
 593                    is_held: false,
 594                }));
 595            }
 596            Event::KeyRelease(event) => {
 597                let window = self.get_window(event.event)?;
 598                let mut state = self.0.borrow_mut();
 599
 600                let modifiers = modifiers_from_state(event.state);
 601                state.modifiers = modifiers;
 602
 603                let keystroke = {
 604                    let code = event.detail.into();
 605                    let keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
 606                    state.xkb.update_key(code, xkbc::KeyDirection::Up);
 607                    let keysym = state.xkb.key_get_one_sym(code);
 608                    if keysym.is_modifier_key() {
 609                        return Some(());
 610                    }
 611                    keystroke
 612                };
 613                drop(state);
 614                window.handle_input(PlatformInput::KeyUp(crate::KeyUpEvent { keystroke }));
 615            }
 616            Event::XinputButtonPress(event) => {
 617                let window = self.get_window(event.event)?;
 618                let mut state = self.0.borrow_mut();
 619
 620                let modifiers = modifiers_from_xinput_info(event.mods);
 621                state.modifiers = modifiers;
 622
 623                let position = point(
 624                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
 625                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
 626                );
 627
 628                if state.composing && state.ximc.is_some() {
 629                    drop(state);
 630                    self.disable_ime();
 631                    self.enable_ime();
 632                    window.handle_ime_unmark();
 633                    state = self.0.borrow_mut();
 634                } else if let Some(text) = state.pre_edit_text.take() {
 635                    state.compose_state.reset();
 636                    drop(state);
 637                    window.handle_ime_commit(text);
 638                    state = self.0.borrow_mut();
 639                }
 640                if let Some(button) = button_of_key(event.detail.try_into().unwrap()) {
 641                    let click_elapsed = state.last_click.elapsed();
 642
 643                    if click_elapsed < DOUBLE_CLICK_INTERVAL
 644                        && is_within_click_distance(state.last_location, position)
 645                    {
 646                        state.current_count += 1;
 647                    } else {
 648                        state.current_count = 1;
 649                    }
 650
 651                    state.last_click = Instant::now();
 652                    state.last_location = position;
 653                    let current_count = state.current_count;
 654
 655                    drop(state);
 656                    window.handle_input(PlatformInput::MouseDown(crate::MouseDownEvent {
 657                        button,
 658                        position,
 659                        modifiers,
 660                        click_count: current_count,
 661                        first_mouse: false,
 662                    }));
 663                } else {
 664                    log::warn!("Unknown button press: {event:?}");
 665                }
 666            }
 667            Event::XinputButtonRelease(event) => {
 668                let window = self.get_window(event.event)?;
 669                let mut state = self.0.borrow_mut();
 670                let modifiers = modifiers_from_xinput_info(event.mods);
 671                state.modifiers = modifiers;
 672
 673                let position = point(
 674                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
 675                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
 676                );
 677                if let Some(button) = button_of_key(event.detail.try_into().unwrap()) {
 678                    let click_count = state.current_count;
 679                    drop(state);
 680                    window.handle_input(PlatformInput::MouseUp(crate::MouseUpEvent {
 681                        button,
 682                        position,
 683                        modifiers,
 684                        click_count,
 685                    }));
 686                }
 687            }
 688            Event::XinputMotion(event) => {
 689                let window = self.get_window(event.event)?;
 690                let mut state = self.0.borrow_mut();
 691                let pressed_button = pressed_button_from_mask(event.button_mask[0]);
 692                let position = point(
 693                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
 694                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
 695                );
 696                let modifiers = modifiers_from_xinput_info(event.mods);
 697                state.modifiers = modifiers;
 698                drop(state);
 699
 700                let axisvalues = event
 701                    .axisvalues
 702                    .iter()
 703                    .map(|axisvalue| fp3232_to_f32(*axisvalue))
 704                    .collect::<Vec<_>>();
 705
 706                if event.valuator_mask[0] & 3 != 0 {
 707                    window.handle_input(PlatformInput::MouseMove(crate::MouseMoveEvent {
 708                        position,
 709                        pressed_button,
 710                        modifiers,
 711                    }));
 712                }
 713
 714                let mut valuator_idx = 0;
 715                let scroll_class_data = self.0.borrow().scroll_class_data.clone();
 716                for shift in 0..32 {
 717                    if (event.valuator_mask[0] >> shift) & 1 == 0 {
 718                        continue;
 719                    }
 720
 721                    for scroll_class in &scroll_class_data {
 722                        if scroll_class.scroll_type == xinput::ScrollType::HORIZONTAL
 723                            && scroll_class.number == shift
 724                        {
 725                            let new_scroll = axisvalues[valuator_idx]
 726                                / fp3232_to_f32(scroll_class.increment)
 727                                * SCROLL_LINES as f32;
 728                            let old_scroll = self.0.borrow().scroll_x;
 729                            self.0.borrow_mut().scroll_x = Some(new_scroll);
 730
 731                            if let Some(old_scroll) = old_scroll {
 732                                let delta_scroll = old_scroll - new_scroll;
 733                                window.handle_input(PlatformInput::ScrollWheel(
 734                                    crate::ScrollWheelEvent {
 735                                        position,
 736                                        delta: ScrollDelta::Lines(Point::new(delta_scroll, 0.0)),
 737                                        modifiers,
 738                                        touch_phase: TouchPhase::default(),
 739                                    },
 740                                ));
 741                            }
 742                        } else if scroll_class.scroll_type == xinput::ScrollType::VERTICAL
 743                            && scroll_class.number == shift
 744                        {
 745                            // the `increment` is the valuator delta equivalent to one positive unit of scrolling. Here that means SCROLL_LINES lines.
 746                            let new_scroll = axisvalues[valuator_idx]
 747                                / fp3232_to_f32(scroll_class.increment)
 748                                * SCROLL_LINES as f32;
 749                            let old_scroll = self.0.borrow().scroll_y;
 750                            self.0.borrow_mut().scroll_y = Some(new_scroll);
 751
 752                            if let Some(old_scroll) = old_scroll {
 753                                let delta_scroll = old_scroll - new_scroll;
 754                                window.handle_input(PlatformInput::ScrollWheel(
 755                                    crate::ScrollWheelEvent {
 756                                        position,
 757                                        delta: ScrollDelta::Lines(Point::new(0.0, delta_scroll)),
 758                                        modifiers,
 759                                        touch_phase: TouchPhase::default(),
 760                                    },
 761                                ));
 762                            }
 763                        }
 764                    }
 765
 766                    valuator_idx += 1;
 767                }
 768            }
 769            Event::XinputLeave(event) if event.mode == xinput::NotifyMode::NORMAL => {
 770                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)
 771                self.0.borrow_mut().scroll_y = None;
 772
 773                let window = self.get_window(event.event)?;
 774                let mut state = self.0.borrow_mut();
 775                let pressed_button = pressed_button_from_mask(event.buttons[0]);
 776                let position = point(
 777                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
 778                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
 779                );
 780                let modifiers = modifiers_from_xinput_info(event.mods);
 781                state.modifiers = modifiers;
 782                drop(state);
 783
 784                window.handle_input(PlatformInput::MouseExited(crate::MouseExitEvent {
 785                    pressed_button,
 786                    position,
 787                    modifiers,
 788                }));
 789            }
 790            _ => {}
 791        };
 792
 793        Some(())
 794    }
 795
 796    fn xim_handle_event(&self, event: Event) -> Option<()> {
 797        match event {
 798            Event::KeyPress(event) | Event::KeyRelease(event) => {
 799                let mut state = self.0.borrow_mut();
 800                let mut ximc = state.ximc.take().unwrap();
 801                let mut xim_handler = state.xim_handler.take().unwrap();
 802                drop(state);
 803                xim_handler.window = event.event;
 804                ximc.forward_event(
 805                    xim_handler.im_id,
 806                    xim_handler.ic_id,
 807                    xim::ForwardEventFlag::empty(),
 808                    &event,
 809                )
 810                .unwrap();
 811                let mut state = self.0.borrow_mut();
 812                state.ximc = Some(ximc);
 813                state.xim_handler = Some(xim_handler);
 814                drop(state);
 815            }
 816            event => {
 817                self.handle_event(event);
 818            }
 819        }
 820        Some(())
 821    }
 822
 823    fn xim_handle_commit(&self, window: xproto::Window, text: String) -> Option<()> {
 824        let window = self.get_window(window).unwrap();
 825        let mut state = self.0.borrow_mut();
 826        state.composing = false;
 827        drop(state);
 828
 829        window.handle_ime_commit(text);
 830        Some(())
 831    }
 832
 833    fn xim_handle_preedit(&self, window: xproto::Window, text: String) -> Option<()> {
 834        let window = self.get_window(window).unwrap();
 835        window.handle_ime_preedit(text);
 836
 837        let mut state = self.0.borrow_mut();
 838        let mut ximc = state.ximc.take().unwrap();
 839        let mut xim_handler = state.xim_handler.take().unwrap();
 840        state.composing = true;
 841        drop(state);
 842
 843        if let Some(area) = window.get_ime_area() {
 844            let ic_attributes = ximc
 845                .build_ic_attributes()
 846                .push(
 847                    xim::AttributeName::InputStyle,
 848                    xim::InputStyle::PREEDIT_CALLBACKS
 849                        | xim::InputStyle::STATUS_NOTHING
 850                        | xim::InputStyle::PREEDIT_POSITION,
 851                )
 852                .push(xim::AttributeName::ClientWindow, xim_handler.window)
 853                .push(xim::AttributeName::FocusWindow, xim_handler.window)
 854                .nested_list(xim::AttributeName::PreeditAttributes, |b| {
 855                    b.push(
 856                        xim::AttributeName::SpotLocation,
 857                        xim::Point {
 858                            x: u32::from(area.origin.x + area.size.width) as i16,
 859                            y: u32::from(area.origin.y + area.size.height) as i16,
 860                        },
 861                    );
 862                })
 863                .build();
 864            ximc.set_ic_values(xim_handler.im_id, xim_handler.ic_id, ic_attributes)
 865                .ok();
 866        }
 867        let mut state = self.0.borrow_mut();
 868        state.ximc = Some(ximc);
 869        state.xim_handler = Some(xim_handler);
 870        drop(state);
 871        Some(())
 872    }
 873}
 874
 875impl LinuxClient for X11Client {
 876    fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
 877        f(&mut self.0.borrow_mut().common)
 878    }
 879
 880    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
 881        let state = self.0.borrow();
 882        let setup = state.xcb_connection.setup();
 883        setup
 884            .roots
 885            .iter()
 886            .enumerate()
 887            .filter_map(|(root_id, _)| {
 888                Some(Rc::new(X11Display::new(&state.xcb_connection, root_id)?)
 889                    as Rc<dyn PlatformDisplay>)
 890            })
 891            .collect()
 892    }
 893
 894    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 895        let state = self.0.borrow();
 896
 897        Some(Rc::new(
 898            X11Display::new(&state.xcb_connection, state.x_root_index)
 899                .expect("There should always be a root index"),
 900        ))
 901    }
 902
 903    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
 904        let state = self.0.borrow();
 905
 906        Some(Rc::new(X11Display::new(
 907            &state.xcb_connection,
 908            id.0 as usize,
 909        )?))
 910    }
 911
 912    fn open_window(
 913        &self,
 914        handle: AnyWindowHandle,
 915        params: WindowParams,
 916    ) -> Box<dyn PlatformWindow> {
 917        let mut state = self.0.borrow_mut();
 918        let x_window = state.xcb_connection.generate_id().unwrap();
 919
 920        let window = X11Window::new(
 921            handle,
 922            X11ClientStatePtr(Rc::downgrade(&self.0)),
 923            state.common.foreground_executor.clone(),
 924            params,
 925            &state.xcb_connection,
 926            state.x_root_index,
 927            x_window,
 928            &state.atoms,
 929            state.scale_factor,
 930            state.common.appearance,
 931        );
 932
 933        let screen_resources = state
 934            .xcb_connection
 935            .randr_get_screen_resources(x_window)
 936            .unwrap()
 937            .reply()
 938            .expect("Could not find available screens");
 939
 940        let mode = screen_resources
 941            .crtcs
 942            .iter()
 943            .find_map(|crtc| {
 944                let crtc_info = state
 945                    .xcb_connection
 946                    .randr_get_crtc_info(*crtc, x11rb::CURRENT_TIME)
 947                    .ok()?
 948                    .reply()
 949                    .ok()?;
 950
 951                screen_resources
 952                    .modes
 953                    .iter()
 954                    .find(|m| m.id == crtc_info.mode)
 955            })
 956            .expect("Unable to find screen refresh rate");
 957
 958        let refresh_event_token = state
 959            .loop_handle
 960            .insert_source(calloop::timer::Timer::immediate(), {
 961                let refresh_duration = mode_refresh_rate(mode);
 962                move |mut instant, (), client| {
 963                    let state = client.0.borrow_mut();
 964                    state
 965                        .xcb_connection
 966                        .send_event(
 967                            false,
 968                            x_window,
 969                            xproto::EventMask::EXPOSURE,
 970                            xproto::ExposeEvent {
 971                                response_type: xproto::EXPOSE_EVENT,
 972                                sequence: 0,
 973                                window: x_window,
 974                                x: 0,
 975                                y: 0,
 976                                width: 0,
 977                                height: 0,
 978                                count: 1,
 979                            },
 980                        )
 981                        .unwrap();
 982                    let _ = state.xcb_connection.flush().unwrap();
 983                    // Take into account that some frames have been skipped
 984                    let now = Instant::now();
 985                    while instant < now {
 986                        instant += refresh_duration;
 987                    }
 988                    calloop::timer::TimeoutAction::ToInstant(instant)
 989                }
 990            })
 991            .expect("Failed to initialize refresh timer");
 992
 993        let window_ref = WindowRef {
 994            window: window.0.clone(),
 995            refresh_event_token,
 996        };
 997
 998        state.windows.insert(x_window, window_ref);
 999        Box::new(window)
1000    }
1001
1002    fn set_cursor_style(&self, style: CursorStyle) {
1003        let mut state = self.0.borrow_mut();
1004        let Some(focused_window) = state.focused_window else {
1005            return;
1006        };
1007        let current_style = state
1008            .cursor_styles
1009            .get(&focused_window)
1010            .unwrap_or(&CursorStyle::Arrow);
1011        if *current_style == style {
1012            return;
1013        }
1014
1015        let cursor = match state.cursor_cache.get(&style) {
1016            Some(cursor) => *cursor,
1017            None => {
1018                let cursor = state
1019                    .cursor_handle
1020                    .load_cursor(&state.xcb_connection, &style.to_icon_name())
1021                    .expect("failed to load cursor");
1022                state.cursor_cache.insert(style, cursor);
1023                cursor
1024            }
1025        };
1026
1027        state.cursor_styles.insert(focused_window, style);
1028        state
1029            .xcb_connection
1030            .change_window_attributes(
1031                focused_window,
1032                &ChangeWindowAttributesAux {
1033                    cursor: Some(cursor),
1034                    ..Default::default()
1035                },
1036            )
1037            .expect("failed to change window cursor");
1038    }
1039
1040    fn open_uri(&self, uri: &str) {
1041        open_uri_internal(uri, None);
1042    }
1043
1044    fn write_to_primary(&self, item: crate::ClipboardItem) {
1045        self.0.borrow_mut().primary.set_contents(item.text).ok();
1046    }
1047
1048    fn write_to_clipboard(&self, item: crate::ClipboardItem) {
1049        self.0.borrow_mut().clipboard.set_contents(item.text).ok();
1050    }
1051
1052    fn read_from_primary(&self) -> Option<crate::ClipboardItem> {
1053        self.0
1054            .borrow_mut()
1055            .primary
1056            .get_contents()
1057            .ok()
1058            .map(|text| crate::ClipboardItem {
1059                text,
1060                metadata: None,
1061            })
1062    }
1063
1064    fn read_from_clipboard(&self) -> Option<crate::ClipboardItem> {
1065        self.0
1066            .borrow_mut()
1067            .clipboard
1068            .get_contents()
1069            .ok()
1070            .map(|text| crate::ClipboardItem {
1071                text,
1072                metadata: None,
1073            })
1074    }
1075
1076    fn run(&self) {
1077        let mut event_loop = self
1078            .0
1079            .borrow_mut()
1080            .event_loop
1081            .take()
1082            .expect("App is already running");
1083
1084        event_loop.run(None, &mut self.clone(), |_| {}).log_err();
1085    }
1086
1087    fn active_window(&self) -> Option<AnyWindowHandle> {
1088        let state = self.0.borrow();
1089        state.focused_window.and_then(|focused_window| {
1090            state
1091                .windows
1092                .get(&focused_window)
1093                .map(|window| window.handle())
1094        })
1095    }
1096}
1097
1098// Adatpted from:
1099// https://docs.rs/winit/0.29.11/src/winit/platform_impl/linux/x11/monitor.rs.html#103-111
1100pub fn mode_refresh_rate(mode: &randr::ModeInfo) -> Duration {
1101    let millihertz = mode.dot_clock as u64 * 1_000 / (mode.htotal as u64 * mode.vtotal as u64);
1102    let micros = 1_000_000_000 / millihertz;
1103    log::info!("Refreshing at {} micros", micros);
1104    Duration::from_micros(micros)
1105}
1106
1107fn fp3232_to_f32(value: xinput::Fp3232) -> f32 {
1108    value.integral as f32 + value.frac as f32 / u32::MAX as f32
1109}