client.rs

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