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                }
 363            })
 364            .unwrap();
 365
 366        X11Client(Rc::new(RefCell::new(X11ClientState {
 367            modifiers: Modifiers::default(),
 368            event_loop: Some(event_loop),
 369            loop_handle: handle,
 370            common,
 371            last_click: Instant::now(),
 372            last_location: Point::new(px(0.0), px(0.0)),
 373            current_count: 0,
 374            scale_factor,
 375
 376            xcb_connection,
 377            x_root_index,
 378            _resource_database: resource_database,
 379            atoms,
 380            windows: HashMap::default(),
 381            focused_window: None,
 382            xkb: xkb_state,
 383            ximc,
 384            xim_handler,
 385
 386            compose_state: compose_state,
 387            pre_edit_text: None,
 388            composing: false,
 389
 390            cursor_handle,
 391            cursor_styles: HashMap::default(),
 392            cursor_cache: HashMap::default(),
 393
 394            scroll_class_data,
 395            scroll_x: None,
 396            scroll_y: None,
 397
 398            clipboard,
 399            primary,
 400        })))
 401    }
 402
 403    pub fn enable_ime(&self) {
 404        let mut state = self.0.borrow_mut();
 405        if state.ximc.is_none() {
 406            return;
 407        }
 408
 409        let mut ximc = state.ximc.take().unwrap();
 410        let mut xim_handler = state.xim_handler.take().unwrap();
 411        let mut ic_attributes = ximc
 412            .build_ic_attributes()
 413            .push(
 414                AttributeName::InputStyle,
 415                InputStyle::PREEDIT_CALLBACKS
 416                    | InputStyle::STATUS_NOTHING
 417                    | InputStyle::PREEDIT_NONE,
 418            )
 419            .push(AttributeName::ClientWindow, xim_handler.window)
 420            .push(AttributeName::FocusWindow, xim_handler.window);
 421
 422        let window_id = state.focused_window;
 423        drop(state);
 424        if let Some(window_id) = window_id {
 425            let window = self.get_window(window_id).unwrap();
 426            if let Some(area) = window.get_ime_area() {
 427                ic_attributes =
 428                    ic_attributes.nested_list(xim::AttributeName::PreeditAttributes, |b| {
 429                        b.push(
 430                            xim::AttributeName::SpotLocation,
 431                            xim::Point {
 432                                x: u32::from(area.origin.x + area.size.width) as i16,
 433                                y: u32::from(area.origin.y + area.size.height) as i16,
 434                            },
 435                        );
 436                    });
 437            }
 438        }
 439        ximc.create_ic(xim_handler.im_id, ic_attributes.build())
 440            .ok();
 441        state = self.0.borrow_mut();
 442        state.xim_handler = Some(xim_handler);
 443        state.ximc = Some(ximc);
 444    }
 445
 446    pub fn disable_ime(&self) {
 447        let mut state = self.0.borrow_mut();
 448        state.composing = false;
 449        if let Some(mut ximc) = state.ximc.take() {
 450            let xim_handler = state.xim_handler.as_ref().unwrap();
 451            ximc.destroy_ic(xim_handler.im_id, xim_handler.ic_id).ok();
 452            state.ximc = Some(ximc);
 453        }
 454    }
 455
 456    fn get_window(&self, win: xproto::Window) -> Option<X11WindowStatePtr> {
 457        let state = self.0.borrow();
 458        state
 459            .windows
 460            .get(&win)
 461            .map(|window_reference| window_reference.window.clone())
 462    }
 463
 464    fn handle_event(&self, event: Event) -> Option<()> {
 465        match event {
 466            Event::ClientMessage(event) => {
 467                let window = self.get_window(event.window)?;
 468                let [atom, ..] = event.data.as_data32();
 469                let mut state = self.0.borrow_mut();
 470
 471                if atom == state.atoms.WM_DELETE_WINDOW {
 472                    // window "x" button clicked by user
 473                    if window.should_close() {
 474                        let window_ref = state.windows.remove(&event.window)?;
 475                        state.loop_handle.remove(window_ref.refresh_event_token);
 476                        // Rest of the close logic is handled in drop_window()
 477                    }
 478                }
 479            }
 480            Event::ConfigureNotify(event) => {
 481                let bounds = Bounds {
 482                    origin: Point {
 483                        x: event.x.into(),
 484                        y: event.y.into(),
 485                    },
 486                    size: Size {
 487                        width: event.width.into(),
 488                        height: event.height.into(),
 489                    },
 490                };
 491                let window = self.get_window(event.window)?;
 492                window.configure(bounds);
 493            }
 494            Event::Expose(event) => {
 495                let window = self.get_window(event.window)?;
 496                window.refresh();
 497            }
 498            Event::FocusIn(event) => {
 499                let window = self.get_window(event.event)?;
 500                window.set_focused(true);
 501                let mut state = self.0.borrow_mut();
 502                state.focused_window = Some(event.event);
 503                drop(state);
 504                self.enable_ime();
 505            }
 506            Event::FocusOut(event) => {
 507                let window = self.get_window(event.event)?;
 508                window.set_focused(false);
 509                let mut state = self.0.borrow_mut();
 510                state.focused_window = None;
 511                state.compose_state.reset();
 512                state.pre_edit_text.take();
 513                drop(state);
 514                self.disable_ime();
 515                window.handle_ime_delete();
 516            }
 517            Event::XkbStateNotify(event) => {
 518                let mut state = self.0.borrow_mut();
 519                state.xkb.update_mask(
 520                    event.base_mods.into(),
 521                    event.latched_mods.into(),
 522                    event.locked_mods.into(),
 523                    0,
 524                    0,
 525                    event.locked_group.into(),
 526                );
 527
 528                let modifiers = Modifiers::from_xkb(&state.xkb);
 529                if state.modifiers == modifiers {
 530                    drop(state);
 531                } else {
 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            }
 542            Event::KeyPress(event) => {
 543                let window = self.get_window(event.event)?;
 544                let mut state = self.0.borrow_mut();
 545
 546                let modifiers = modifiers_from_state(event.state);
 547                state.modifiers = modifiers;
 548
 549                let keystroke = {
 550                    let code = event.detail.into();
 551                    let mut keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
 552                    state.xkb.update_key(code, xkbc::KeyDirection::Down);
 553                    let keysym = state.xkb.key_get_one_sym(code);
 554                    if keysym.is_modifier_key() {
 555                        return Some(());
 556                    }
 557                    state.compose_state.feed(keysym);
 558                    match state.compose_state.status() {
 559                        xkbc::Status::Composed => {
 560                            state.pre_edit_text.take();
 561                            keystroke.ime_key = state.compose_state.utf8();
 562                            keystroke.key =
 563                                xkbc::keysym_get_name(state.compose_state.keysym().unwrap());
 564                        }
 565                        xkbc::Status::Composing => {
 566                            state.pre_edit_text = state
 567                                .compose_state
 568                                .utf8()
 569                                .or(crate::Keystroke::underlying_dead_key(keysym));
 570                            let pre_edit = state.pre_edit_text.clone().unwrap_or(String::default());
 571                            drop(state);
 572                            window.handle_ime_preedit(pre_edit);
 573                            state = self.0.borrow_mut();
 574                        }
 575                        xkbc::Status::Cancelled => {
 576                            let pre_edit = state.pre_edit_text.take();
 577                            drop(state);
 578                            if let Some(pre_edit) = pre_edit {
 579                                window.handle_ime_commit(pre_edit);
 580                            }
 581                            if let Some(current_key) = Keystroke::underlying_dead_key(keysym) {
 582                                window.handle_ime_preedit(current_key);
 583                            }
 584                            state = self.0.borrow_mut();
 585                            state.compose_state.feed(keysym);
 586                        }
 587                        _ => {}
 588                    }
 589                    keystroke
 590                };
 591                drop(state);
 592                window.handle_input(PlatformInput::KeyDown(crate::KeyDownEvent {
 593                    keystroke,
 594                    is_held: false,
 595                }));
 596            }
 597            Event::KeyRelease(event) => {
 598                let window = self.get_window(event.event)?;
 599                let mut state = self.0.borrow_mut();
 600
 601                let modifiers = modifiers_from_state(event.state);
 602                state.modifiers = modifiers;
 603
 604                let keystroke = {
 605                    let code = event.detail.into();
 606                    let keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
 607                    state.xkb.update_key(code, xkbc::KeyDirection::Up);
 608                    let keysym = state.xkb.key_get_one_sym(code);
 609                    if keysym.is_modifier_key() {
 610                        return Some(());
 611                    }
 612                    keystroke
 613                };
 614                drop(state);
 615                window.handle_input(PlatformInput::KeyUp(crate::KeyUpEvent { keystroke }));
 616            }
 617            Event::XinputButtonPress(event) => {
 618                let window = self.get_window(event.event)?;
 619                let mut state = self.0.borrow_mut();
 620
 621                let modifiers = modifiers_from_xinput_info(event.mods);
 622                state.modifiers = modifiers;
 623
 624                let position = point(
 625                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
 626                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
 627                );
 628
 629                if state.composing && state.ximc.is_some() {
 630                    drop(state);
 631                    self.disable_ime();
 632                    self.enable_ime();
 633                    window.handle_ime_unmark();
 634                    state = self.0.borrow_mut();
 635                } else if let Some(text) = state.pre_edit_text.take() {
 636                    state.compose_state.reset();
 637                    drop(state);
 638                    window.handle_ime_commit(text);
 639                    state = self.0.borrow_mut();
 640                }
 641                if let Some(button) = button_of_key(event.detail.try_into().unwrap()) {
 642                    let click_elapsed = state.last_click.elapsed();
 643
 644                    if click_elapsed < DOUBLE_CLICK_INTERVAL
 645                        && is_within_click_distance(state.last_location, position)
 646                    {
 647                        state.current_count += 1;
 648                    } else {
 649                        state.current_count = 1;
 650                    }
 651
 652                    state.last_click = Instant::now();
 653                    state.last_location = position;
 654                    let current_count = state.current_count;
 655
 656                    drop(state);
 657                    window.handle_input(PlatformInput::MouseDown(crate::MouseDownEvent {
 658                        button,
 659                        position,
 660                        modifiers,
 661                        click_count: current_count,
 662                        first_mouse: false,
 663                    }));
 664                } else {
 665                    log::warn!("Unknown button press: {event:?}");
 666                }
 667            }
 668            Event::XinputButtonRelease(event) => {
 669                let window = self.get_window(event.event)?;
 670                let mut state = self.0.borrow_mut();
 671                let modifiers = modifiers_from_xinput_info(event.mods);
 672                state.modifiers = modifiers;
 673
 674                let position = point(
 675                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
 676                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
 677                );
 678                if let Some(button) = button_of_key(event.detail.try_into().unwrap()) {
 679                    let click_count = state.current_count;
 680                    drop(state);
 681                    window.handle_input(PlatformInput::MouseUp(crate::MouseUpEvent {
 682                        button,
 683                        position,
 684                        modifiers,
 685                        click_count,
 686                    }));
 687                }
 688            }
 689            Event::XinputMotion(event) => {
 690                let window = self.get_window(event.event)?;
 691                let mut state = self.0.borrow_mut();
 692                let pressed_button = pressed_button_from_mask(event.button_mask[0]);
 693                let position = point(
 694                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
 695                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
 696                );
 697                let modifiers = modifiers_from_xinput_info(event.mods);
 698                state.modifiers = modifiers;
 699                drop(state);
 700
 701                let axisvalues = event
 702                    .axisvalues
 703                    .iter()
 704                    .map(|axisvalue| fp3232_to_f32(*axisvalue))
 705                    .collect::<Vec<_>>();
 706
 707                if event.valuator_mask[0] & 3 != 0 {
 708                    window.handle_input(PlatformInput::MouseMove(crate::MouseMoveEvent {
 709                        position,
 710                        pressed_button,
 711                        modifiers,
 712                    }));
 713                }
 714
 715                let mut valuator_idx = 0;
 716                let scroll_class_data = self.0.borrow().scroll_class_data.clone();
 717                for shift in 0..32 {
 718                    if (event.valuator_mask[0] >> shift) & 1 == 0 {
 719                        continue;
 720                    }
 721
 722                    for scroll_class in &scroll_class_data {
 723                        if scroll_class.scroll_type == xinput::ScrollType::HORIZONTAL
 724                            && scroll_class.number == shift
 725                        {
 726                            let new_scroll = axisvalues[valuator_idx]
 727                                / fp3232_to_f32(scroll_class.increment)
 728                                * SCROLL_LINES as f32;
 729                            let old_scroll = self.0.borrow().scroll_x;
 730                            self.0.borrow_mut().scroll_x = Some(new_scroll);
 731
 732                            if let Some(old_scroll) = old_scroll {
 733                                let delta_scroll = old_scroll - new_scroll;
 734                                window.handle_input(PlatformInput::ScrollWheel(
 735                                    crate::ScrollWheelEvent {
 736                                        position,
 737                                        delta: ScrollDelta::Lines(Point::new(delta_scroll, 0.0)),
 738                                        modifiers,
 739                                        touch_phase: TouchPhase::default(),
 740                                    },
 741                                ));
 742                            }
 743                        } else if scroll_class.scroll_type == xinput::ScrollType::VERTICAL
 744                            && scroll_class.number == shift
 745                        {
 746                            // the `increment` is the valuator delta equivalent to one positive unit of scrolling. Here that means SCROLL_LINES lines.
 747                            let new_scroll = axisvalues[valuator_idx]
 748                                / fp3232_to_f32(scroll_class.increment)
 749                                * SCROLL_LINES as f32;
 750                            let old_scroll = self.0.borrow().scroll_y;
 751                            self.0.borrow_mut().scroll_y = Some(new_scroll);
 752
 753                            if let Some(old_scroll) = old_scroll {
 754                                let delta_scroll = old_scroll - new_scroll;
 755                                window.handle_input(PlatformInput::ScrollWheel(
 756                                    crate::ScrollWheelEvent {
 757                                        position,
 758                                        delta: ScrollDelta::Lines(Point::new(0.0, delta_scroll)),
 759                                        modifiers,
 760                                        touch_phase: TouchPhase::default(),
 761                                    },
 762                                ));
 763                            }
 764                        }
 765                    }
 766
 767                    valuator_idx += 1;
 768                }
 769            }
 770            Event::XinputLeave(event) if event.mode == xinput::NotifyMode::NORMAL => {
 771                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)
 772                self.0.borrow_mut().scroll_y = None;
 773
 774                let window = self.get_window(event.event)?;
 775                let mut state = self.0.borrow_mut();
 776                let pressed_button = pressed_button_from_mask(event.buttons[0]);
 777                let position = point(
 778                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
 779                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
 780                );
 781                let modifiers = modifiers_from_xinput_info(event.mods);
 782                state.modifiers = modifiers;
 783                drop(state);
 784
 785                window.handle_input(PlatformInput::MouseExited(crate::MouseExitEvent {
 786                    pressed_button,
 787                    position,
 788                    modifiers,
 789                }));
 790            }
 791            _ => {}
 792        };
 793
 794        Some(())
 795    }
 796
 797    fn handle_xim_callback_event(&self, event: XimCallbackEvent) {
 798        match event {
 799            XimCallbackEvent::XimXEvent(event) => {
 800                self.handle_event(event);
 801            }
 802            XimCallbackEvent::XimCommitEvent(window, text) => {
 803                self.xim_handle_commit(window, text);
 804            }
 805            XimCallbackEvent::XimPreeditEvent(window, text) => {
 806                self.xim_handle_preedit(window, text);
 807            }
 808        };
 809    }
 810
 811    fn xim_handle_event(&self, event: Event) -> Option<()> {
 812        match event {
 813            Event::KeyPress(event) | Event::KeyRelease(event) => {
 814                let mut state = self.0.borrow_mut();
 815                let mut ximc = state.ximc.take().unwrap();
 816                let mut xim_handler = state.xim_handler.take().unwrap();
 817                drop(state);
 818                xim_handler.window = event.event;
 819                ximc.forward_event(
 820                    xim_handler.im_id,
 821                    xim_handler.ic_id,
 822                    xim::ForwardEventFlag::empty(),
 823                    &event,
 824                )
 825                .unwrap();
 826                let mut state = self.0.borrow_mut();
 827                state.ximc = Some(ximc);
 828                state.xim_handler = Some(xim_handler);
 829                drop(state);
 830            }
 831            event => {
 832                self.handle_event(event);
 833            }
 834        }
 835        Some(())
 836    }
 837
 838    fn xim_handle_commit(&self, window: xproto::Window, text: String) -> Option<()> {
 839        let window = self.get_window(window).unwrap();
 840        let mut state = self.0.borrow_mut();
 841        state.composing = false;
 842        drop(state);
 843
 844        window.handle_ime_commit(text);
 845        Some(())
 846    }
 847
 848    fn xim_handle_preedit(&self, window: xproto::Window, text: String) -> Option<()> {
 849        let window = self.get_window(window).unwrap();
 850        window.handle_ime_preedit(text);
 851
 852        let mut state = self.0.borrow_mut();
 853        let mut ximc = state.ximc.take().unwrap();
 854        let mut xim_handler = state.xim_handler.take().unwrap();
 855        state.composing = true;
 856        drop(state);
 857
 858        if let Some(area) = window.get_ime_area() {
 859            let ic_attributes = ximc
 860                .build_ic_attributes()
 861                .push(
 862                    xim::AttributeName::InputStyle,
 863                    xim::InputStyle::PREEDIT_CALLBACKS
 864                        | xim::InputStyle::STATUS_NOTHING
 865                        | xim::InputStyle::PREEDIT_POSITION,
 866                )
 867                .push(xim::AttributeName::ClientWindow, xim_handler.window)
 868                .push(xim::AttributeName::FocusWindow, xim_handler.window)
 869                .nested_list(xim::AttributeName::PreeditAttributes, |b| {
 870                    b.push(
 871                        xim::AttributeName::SpotLocation,
 872                        xim::Point {
 873                            x: u32::from(area.origin.x + area.size.width) as i16,
 874                            y: u32::from(area.origin.y + area.size.height) as i16,
 875                        },
 876                    );
 877                })
 878                .build();
 879            ximc.set_ic_values(xim_handler.im_id, xim_handler.ic_id, ic_attributes)
 880                .ok();
 881        }
 882        let mut state = self.0.borrow_mut();
 883        state.ximc = Some(ximc);
 884        state.xim_handler = Some(xim_handler);
 885        drop(state);
 886        Some(())
 887    }
 888}
 889
 890impl LinuxClient for X11Client {
 891    fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
 892        f(&mut self.0.borrow_mut().common)
 893    }
 894
 895    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
 896        let state = self.0.borrow();
 897        let setup = state.xcb_connection.setup();
 898        setup
 899            .roots
 900            .iter()
 901            .enumerate()
 902            .filter_map(|(root_id, _)| {
 903                Some(Rc::new(X11Display::new(&state.xcb_connection, root_id)?)
 904                    as Rc<dyn PlatformDisplay>)
 905            })
 906            .collect()
 907    }
 908
 909    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 910        let state = self.0.borrow();
 911
 912        Some(Rc::new(
 913            X11Display::new(&state.xcb_connection, state.x_root_index)
 914                .expect("There should always be a root index"),
 915        ))
 916    }
 917
 918    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
 919        let state = self.0.borrow();
 920
 921        Some(Rc::new(X11Display::new(
 922            &state.xcb_connection,
 923            id.0 as usize,
 924        )?))
 925    }
 926
 927    fn open_window(
 928        &self,
 929        handle: AnyWindowHandle,
 930        params: WindowParams,
 931    ) -> Box<dyn PlatformWindow> {
 932        let mut state = self.0.borrow_mut();
 933        let x_window = state.xcb_connection.generate_id().unwrap();
 934
 935        let window = X11Window::new(
 936            handle,
 937            X11ClientStatePtr(Rc::downgrade(&self.0)),
 938            state.common.foreground_executor.clone(),
 939            params,
 940            &state.xcb_connection,
 941            state.x_root_index,
 942            x_window,
 943            &state.atoms,
 944            state.scale_factor,
 945            state.common.appearance,
 946        );
 947
 948        let screen_resources = state
 949            .xcb_connection
 950            .randr_get_screen_resources(x_window)
 951            .unwrap()
 952            .reply()
 953            .expect("Could not find available screens");
 954
 955        let mode = screen_resources
 956            .crtcs
 957            .iter()
 958            .find_map(|crtc| {
 959                let crtc_info = state
 960                    .xcb_connection
 961                    .randr_get_crtc_info(*crtc, x11rb::CURRENT_TIME)
 962                    .ok()?
 963                    .reply()
 964                    .ok()?;
 965
 966                screen_resources
 967                    .modes
 968                    .iter()
 969                    .find(|m| m.id == crtc_info.mode)
 970            })
 971            .expect("Unable to find screen refresh rate");
 972
 973        let refresh_event_token = state
 974            .loop_handle
 975            .insert_source(calloop::timer::Timer::immediate(), {
 976                let refresh_duration = mode_refresh_rate(mode);
 977                move |mut instant, (), client| {
 978                    let state = client.0.borrow_mut();
 979                    state
 980                        .xcb_connection
 981                        .send_event(
 982                            false,
 983                            x_window,
 984                            xproto::EventMask::EXPOSURE,
 985                            xproto::ExposeEvent {
 986                                response_type: xproto::EXPOSE_EVENT,
 987                                sequence: 0,
 988                                window: x_window,
 989                                x: 0,
 990                                y: 0,
 991                                width: 0,
 992                                height: 0,
 993                                count: 1,
 994                            },
 995                        )
 996                        .unwrap();
 997                    let _ = state.xcb_connection.flush().unwrap();
 998                    // Take into account that some frames have been skipped
 999                    let now = Instant::now();
1000                    while instant < now {
1001                        instant += refresh_duration;
1002                    }
1003                    calloop::timer::TimeoutAction::ToInstant(instant)
1004                }
1005            })
1006            .expect("Failed to initialize refresh timer");
1007
1008        let window_ref = WindowRef {
1009            window: window.0.clone(),
1010            refresh_event_token,
1011        };
1012
1013        state.windows.insert(x_window, window_ref);
1014        Box::new(window)
1015    }
1016
1017    fn set_cursor_style(&self, style: CursorStyle) {
1018        let mut state = self.0.borrow_mut();
1019        let Some(focused_window) = state.focused_window else {
1020            return;
1021        };
1022        let current_style = state
1023            .cursor_styles
1024            .get(&focused_window)
1025            .unwrap_or(&CursorStyle::Arrow);
1026        if *current_style == style {
1027            return;
1028        }
1029
1030        let cursor = match state.cursor_cache.get(&style) {
1031            Some(cursor) => *cursor,
1032            None => {
1033                let cursor = state
1034                    .cursor_handle
1035                    .load_cursor(&state.xcb_connection, &style.to_icon_name())
1036                    .expect("failed to load cursor");
1037                state.cursor_cache.insert(style, cursor);
1038                cursor
1039            }
1040        };
1041
1042        state.cursor_styles.insert(focused_window, style);
1043        state
1044            .xcb_connection
1045            .change_window_attributes(
1046                focused_window,
1047                &ChangeWindowAttributesAux {
1048                    cursor: Some(cursor),
1049                    ..Default::default()
1050                },
1051            )
1052            .expect("failed to change window cursor");
1053    }
1054
1055    fn open_uri(&self, uri: &str) {
1056        open_uri_internal(uri, None);
1057    }
1058
1059    fn write_to_primary(&self, item: crate::ClipboardItem) {
1060        self.0.borrow_mut().primary.set_contents(item.text).ok();
1061    }
1062
1063    fn write_to_clipboard(&self, item: crate::ClipboardItem) {
1064        self.0.borrow_mut().clipboard.set_contents(item.text).ok();
1065    }
1066
1067    fn read_from_primary(&self) -> Option<crate::ClipboardItem> {
1068        self.0
1069            .borrow_mut()
1070            .primary
1071            .get_contents()
1072            .ok()
1073            .map(|text| crate::ClipboardItem {
1074                text,
1075                metadata: None,
1076            })
1077    }
1078
1079    fn read_from_clipboard(&self) -> Option<crate::ClipboardItem> {
1080        self.0
1081            .borrow_mut()
1082            .clipboard
1083            .get_contents()
1084            .ok()
1085            .map(|text| crate::ClipboardItem {
1086                text,
1087                metadata: None,
1088            })
1089    }
1090
1091    fn run(&self) {
1092        let mut event_loop = self
1093            .0
1094            .borrow_mut()
1095            .event_loop
1096            .take()
1097            .expect("App is already running");
1098
1099        event_loop.run(None, &mut self.clone(), |_| {}).log_err();
1100    }
1101
1102    fn active_window(&self) -> Option<AnyWindowHandle> {
1103        let state = self.0.borrow();
1104        state.focused_window.and_then(|focused_window| {
1105            state
1106                .windows
1107                .get(&focused_window)
1108                .map(|window| window.handle())
1109        })
1110    }
1111}
1112
1113// Adatpted from:
1114// https://docs.rs/winit/0.29.11/src/winit/platform_impl/linux/x11/monitor.rs.html#103-111
1115pub fn mode_refresh_rate(mode: &randr::ModeInfo) -> Duration {
1116    let millihertz = mode.dot_clock as u64 * 1_000 / (mode.htotal as u64 * mode.vtotal as u64);
1117    let micros = 1_000_000_000 / millihertz;
1118    log::info!("Refreshing at {} micros", micros);
1119    Duration::from_micros(micros)
1120}
1121
1122fn fp3232_to_f32(value: xinput::Fp3232) -> f32 {
1123    value.integral as f32 + value.frac as f32 / u32::MAX as f32
1124}