<NME> mod.rs
<BEF> //! Implementation of input backend trait for types provided by `libinput`

mod helpers;
use helpers::{on_device_event, on_keyboard_event, on_pointer_event, on_touch_event};

use crate::backend::input::{self as backend, Axis, InputBackend};
#[cfg(feature = "backend_session")]
use crate::backend::session::{AsErrno, Session, SessionObserver};
use input as libinput;
use input::event;

#[cfg(feature = "backend_session")]
use std::path::Path;
use std::{
    io,
    os::unix::io::{AsRawFd, RawFd},
    os::unix::io::{AsRawFd, RawFd},
};

use calloop::{generic::Generic, InsertError, LoopHandle, Source};

// No idea if this is the same across unix platforms
// Lets make this linux exclusive for now, once someone tries to build it for
mod tablet;

// No idea if this is the same across unix platforms
// Lets make this linux exclusive for now, once someone tries to build it for
// any BSD-like system, they can verify if this is right and make a PR to change this.
#[cfg(all(any(target_os = "linux", target_os = "android"), feature = "backend_session"))]
const INPUT_MAJOR: u32 = 13;
/// context.
pub struct LibinputInputBackend {
    context: libinput::Libinput,
    devices: Vec<libinput::Device>,
    seats: HashMap<libinput::Seat, backend::Seat>,
    handler: Option<Box<dyn backend::InputHandler<LibinputInputBackend> + 'static>>,
    logger: ::slog::Logger,
}

    #[cfg(feature = "backend_session")]
    links: Vec<SignalToken>,
    logger: ::slog::Logger,
    token: Option<Token>,
}

impl LibinputInputBackend {
    /// Initialize a new [`LibinputInputBackend`] from a given already initialized
        info!(log, "Initializing a libinput backend");
        LibinputInputBackend {
            context,
            devices: Vec::new(),
            seats: HashMap::new(),
            handler: None,
            logger: log,
        }
    }
            context,
            #[cfg(feature = "backend_session")]
            links: Vec::new(),
            logger: log,
            token: None,
        }
    }
}

#[cfg(feature = "backend_session")]
impl Linkable<SessionSignal> for LibinputInputBackend {
    fn link(&mut self, signaler: Signaler<SessionSignal>) {
        let mut input = self.context.clone();
        let log = self.logger.clone();
        let token = signaler.register(move |s| match s {
            SessionSignal::PauseSession
            | SessionSignal::PauseDevice {
                major: INPUT_MAJOR, ..
            } => {
                input.suspend();
            }
            SessionSignal::ActivateSession | SessionSignal::ActivateDevice { .. } => {
                if input.resume().is_err() {
                    slog::error!(log, "Failed to resume libinput context");
                }
            }
            _ => {}
        });
        self.links.push(token);
    }
}

impl backend::Device for libinput::Device {
    fn id(&self) -> String {
        self.sysname().into()
    }

    fn name(&self) -> String {
        self.name().into()
    }

    fn has_capability(&self, capability: backend::DeviceCapability) -> bool {
        libinput::Device::has_capability(self, capability.into())
    }

    fn usb_id(&self) -> Option<(u32, u32)> {
        Some((
            libinput::Device::id_product(self),
            libinput::Device::id_vendor(self),
        ))
    }

    fn syspath(&self) -> Option<PathBuf> {
        #[cfg(feature = "udev")]
        return unsafe { libinput::Device::udev_device(self) }.map(|d| d.syspath().to_owned());

        #[cfg(not(feature = "udev"))]
        None
    }
}

impl From<backend::DeviceCapability> for libinput::DeviceCapability {
    fn from(other: backend::DeviceCapability) -> libinput::DeviceCapability {
        match other {
            backend::DeviceCapability::Gesture => libinput::DeviceCapability::Gesture,
            backend::DeviceCapability::Keyboard => libinput::DeviceCapability::Keyboard,
            backend::DeviceCapability::Pointer => libinput::DeviceCapability::Pointer,
            backend::DeviceCapability::Switch => libinput::DeviceCapability::Switch,
            backend::DeviceCapability::TabletPad => libinput::DeviceCapability::TabletPad,
            backend::DeviceCapability::TabletTool => libinput::DeviceCapability::TabletTool,
            backend::DeviceCapability::Touch => libinput::DeviceCapability::Touch,
        }
    }
}

impl backend::Event<LibinputInputBackend> for event::keyboard::KeyboardKeyEvent {
    fn time(&self) -> u32 {
        event::keyboard::KeyboardEventTrait::time(self)
    }

    fn device(&self) -> libinput::Device {
        event::EventTrait::device(self)
    }
}

impl backend::KeyboardKeyEvent<LibinputInputBackend> for event::keyboard::KeyboardKeyEvent {
    fn key_code(&self) -> u32 {
        use input::event::keyboard::KeyboardEventTrait;
        self.key()
    }

    fn state(&self) -> backend::KeyState {
        use input::event::keyboard::KeyboardEventTrait;
        self.key_state().into()
    }

    fn count(&self) -> u32 {
        self.seat_key_count()
    }
}

impl backend::Event<LibinputInputBackend> for event::pointer::PointerAxisEvent {
    fn time(&self) -> u32 {
        event::pointer::PointerEventTrait::time(self)
    }

    fn device(&self) -> libinput::Device {
        event::EventTrait::device(self)
    }
}

impl backend::PointerAxisEvent<LibinputInputBackend> for event::pointer::PointerAxisEvent {
    fn amount(&self, axis: Axis) -> Option<f64> {
        let axis = axis.into();
        if self.has_axis(axis) {
            Some(self.axis_value(axis))
        } else {
            None
        }
    }

    fn amount_discrete(&self, axis: Axis) -> Option<f64> {
        let axis = axis.into();
        if self.has_axis(axis) {
            self.axis_value_discrete(axis)
        } else {
            None
        }
    }

    fn source(&self) -> backend::AxisSource {
        self.axis_source().into()
    }
}

impl backend::Event<LibinputInputBackend> for event::pointer::PointerButtonEvent {
    fn time(&self) -> u32 {
        event::pointer::PointerEventTrait::time(self)
    }

    fn device(&self) -> libinput::Device {
        event::EventTrait::device(self)
    }
}

impl backend::PointerButtonEvent<LibinputInputBackend> for event::pointer::PointerButtonEvent {
    fn button_code(&self) -> u32 {
        self.button()
    }

    fn state(&self) -> backend::ButtonState {
        self.button_state().into()
    }
}

impl backend::Event<LibinputInputBackend> for event::pointer::PointerMotionEvent {
    fn time(&self) -> u32 {
        event::pointer::PointerEventTrait::time(self)
    }

    fn device(&self) -> libinput::Device {
        event::EventTrait::device(self)
    }
}

impl backend::PointerMotionEvent<LibinputInputBackend> for event::pointer::PointerMotionEvent {
    fn delta_x(&self) -> f64 {
        self.dx()
    }
    fn delta_y(&self) -> f64 {
        self.dy()
    }
}

impl backend::Event<LibinputInputBackend> for event::pointer::PointerMotionAbsoluteEvent {
    fn time(&self) -> u32 {
        event::pointer::PointerEventTrait::time(self)
    }

    fn device(&self) -> libinput::Device {
        event::EventTrait::device(self)
    }
}

impl backend::PointerMotionAbsoluteEvent<LibinputInputBackend>
    for event::pointer::PointerMotionAbsoluteEvent
{
}


impl backend::TouchFrameEvent for event::touch::TouchFrameEvent {}

impl InputBackend for LibinputInputBackend {
    type InputConfig = [libinput::Device];
    type EventError = IoError;

    type KeyboardKeyEvent = event::keyboard::KeyboardKeyEvent;
impl backend::TouchEvent<LibinputInputBackend> for event::touch::TouchDownEvent {
    fn slot(&self) -> backend::TouchSlot {
        event::touch::TouchEventSlot::slot(self).into()
    }
}

impl backend::AbsolutePositionEvent<LibinputInputBackend> for event::touch::TouchDownEvent {
    type TouchCancelEvent = event::touch::TouchCancelEvent;
    type TouchFrameEvent = event::touch::TouchFrameEvent;

    fn set_handler<H: backend::InputHandler<Self> + 'static>(&mut self, mut handler: H) {
        if self.handler.is_some() {
            self.clear_handler();
        }
        info!(self.logger, "New input handler set");
        for seat in self.seats.values() {
            trace!(self.logger, "Calling on_seat_created with {:?}", seat);
            handler.on_seat_created(seat);
        }
        self.handler = Some(Box::new(handler));
    }

    fn get_handler(&mut self) -> Option<&mut dyn backend::InputHandler<Self>> {
        self.handler
            .as_mut()
            .map(|handler| handler as &mut dyn backend::InputHandler<Self>)
    }

    fn clear_handler(&mut self) {
        if let Some(mut handler) = self.handler.take() {
            for seat in self.seats.values() {
                trace!(self.logger, "Calling on_seat_destroyed with {:?}", seat);
                handler.on_seat_destroyed(seat);
            }
            info!(self.logger, "Removing input handler");
        }
    }

    fn input_config(&mut self) -> &mut Self::InputConfig {
        &mut self.devices
    }

    fn dispatch_new_events(&mut self) -> Result<(), IoError> {
        self.context.dispatch()?;

        for event in &mut self.context {
            match event {
                libinput::Event::Device(device_event) => {
                    on_device_event(
                        &mut self.handler,
                        &mut self.seats,
                        &mut self.devices,
                        device_event,
                        &self.logger,
                    );
                }
                libinput::Event::Touch(touch_event) => {
                    on_touch_event(&mut self.handler, &self.seats, touch_event, &self.logger);
                }
                libinput::Event::Keyboard(keyboard_event) => {
                    on_keyboard_event(&mut self.handler, &self.seats, keyboard_event, &self.logger);
                }
                libinput::Event::Pointer(pointer_event) => {
                    on_pointer_event(&mut self.handler, &self.seats, pointer_event, &self.logger);
                }
                _ => {} //FIXME: What to do with the rest.
            }
    }
}

impl backend::TouchUpEvent<LibinputInputBackend> for event::touch::TouchUpEvent {}

impl backend::TouchEvent<LibinputInputBackend> for event::touch::TouchUpEvent {
    fn slot(&self) -> backend::TouchSlot {
        event::touch::TouchEventSlot::slot(self).into()
    }
}

impl backend::Event<LibinputInputBackend> for event::touch::TouchCancelEvent {
    fn time(&self) -> u32 {
        event::touch::TouchEventTrait::time(self)
    }

    fn device(&self) -> libinput::Device {
        event::EventTrait::device(self)
    }
}

impl backend::TouchCancelEvent<LibinputInputBackend> for event::touch::TouchCancelEvent {}

impl backend::TouchEvent<LibinputInputBackend> for event::touch::TouchCancelEvent {
    fn slot(&self) -> backend::TouchSlot {
        event::touch::TouchEventSlot::slot(self).into()
    }
}

impl backend::Event<LibinputInputBackend> for event::touch::TouchFrameEvent {
    fn time(&self) -> u32 {
        event::touch::TouchEventTrait::time(self)
    }

    fn device(&self) -> libinput::Device {
        event::EventTrait::device(self)
    }
}

impl backend::TouchFrameEvent<LibinputInputBackend> for event::touch::TouchFrameEvent {}

impl InputBackend for LibinputInputBackend {
    type Device = libinput::Device;
    type KeyboardKeyEvent = event::keyboard::KeyboardKeyEvent;
    type PointerAxisEvent = event::pointer::PointerAxisEvent;
    type PointerButtonEvent = event::pointer::PointerButtonEvent;
    type PointerMotionEvent = event::pointer::PointerMotionEvent;
    type PointerMotionAbsoluteEvent = event::pointer::PointerMotionAbsoluteEvent;
    type TouchDownEvent = event::touch::TouchDownEvent;
    type TouchUpEvent = event::touch::TouchUpEvent;
    type TouchMotionEvent = event::touch::TouchMotionEvent;
    type TouchCancelEvent = event::touch::TouchCancelEvent;
    type TouchFrameEvent = event::touch::TouchFrameEvent;
    type TabletToolAxisEvent = event::tablet_tool::TabletToolAxisEvent;
    type TabletToolProximityEvent = event::tablet_tool::TabletToolProximityEvent;
    type TabletToolTipEvent = event::tablet_tool::TabletToolTipEvent;
    type TabletToolButtonEvent = event::tablet_tool::TabletToolButtonEvent;

    type SpecialEvent = backend::UnusedEvent;
}

impl From<event::keyboard::KeyState> for backend::KeyState {
    fn from(libinput: event::keyboard::KeyState) -> Self {
        match libinput {
            event::keyboard::KeyState::Pressed => backend::KeyState::Pressed,
            event::keyboard::KeyState::Released => backend::KeyState::Released,
        }
    }
}

impl From<event::pointer::Axis> for backend::Axis {
    fn from(libinput: event::pointer::Axis) -> Self {
        match libinput {
            event::pointer::Axis::Vertical => backend::Axis::Vertical,
            event::pointer::Axis::Horizontal => backend::Axis::Horizontal,
        }
    }
}

impl From<backend::Axis> for event::pointer::Axis {
    fn from(axis: backend::Axis) -> Self {
        match axis {
            backend::Axis::Vertical => event::pointer::Axis::Vertical,
            backend::Axis::Horizontal => event::pointer::Axis::Horizontal,
        }
    }
}

impl From<event::pointer::AxisSource> for backend::AxisSource {
    fn from(libinput: event::pointer::AxisSource) -> Self {
        match libinput {
            event::pointer::AxisSource::Finger => backend::AxisSource::Finger,
            event::pointer::AxisSource::Continuous => backend::AxisSource::Continuous,
            event::pointer::AxisSource::Wheel => backend::AxisSource::Wheel,
            event::pointer::AxisSource::WheelTilt => backend::AxisSource::WheelTilt,
        }
    }
}

impl From<event::pointer::ButtonState> for backend::ButtonState {
    }
}

/// calloop source associated with the libinput backend
pub type LibinputSource = Generic<LibinputInputBackend>;

/// Binds a [`LibinputInputBackend`] to a given [`LoopHandle`].
///
/// Automatically feeds the backend with incoming events without any manual calls to
/// [`dispatch_new_events`](InputBackend::dispatch_new_events). Should be used to achieve the smallest possible latency.
pub fn libinput_bind<Data: 'static>(
    backend: LibinputInputBackend,
    handle: LoopHandle<Data>,
) -> Result<Source<LibinputSource>, InsertError<LibinputSource>> {
    let source = Generic::new(backend, calloop::Interest::Readable, calloop::Mode::Level);

    handle.insert_source(source, move |_, backend, _| {
        if let Err(error) = backend.dispatch_new_events() {
            warn!(backend.logger, "Libinput errored: {}", error);
            return Err(std::io::Error::new(std::io::ErrorKind::Other, Box::new(error)));
        }
        Ok(())
    })
}
            .map_err(|err| err.as_errno().unwrap_or(1 /*Use EPERM by default*/))
    }

    fn close_restricted(&mut self, fd: RawFd) {
        let _ = self.0.close(fd);
    }
}

impl AsRawFd for LibinputInputBackend {
    fn as_raw_fd(&self) -> RawFd {
        self.context.as_raw_fd()
    }
}

impl EventSource for LibinputInputBackend {
    type Event = InputEvent<LibinputInputBackend>;
    type Metadata = ();
    type Ret = ();
    type Error = io::Error;

    fn process_events<F>(&mut self, _: Readiness, token: Token, mut callback: F) -> io::Result<PostAction>
    where
        F: FnMut(Self::Event, &mut ()) -> Self::Ret,
    {
        if Some(token) == self.token {
            self.context.dispatch()?;

            for event in &mut self.context {
                match event {
                    libinput::Event::Device(device_event) => match device_event {
                        event::DeviceEvent::Added(device_added_event) => {
                            let added = event::EventTrait::device(&device_added_event);

                            info!(self.logger, "New device {:?}", added.sysname(),);

                            callback(InputEvent::DeviceAdded { device: added }, &mut ());
                        }
                        event::DeviceEvent::Removed(device_removed_event) => {
                            let removed = event::EventTrait::device(&device_removed_event);

                            info!(self.logger, "Removed device {:?}", removed.sysname(),);

                            callback(InputEvent::DeviceRemoved { device: removed }, &mut ());
                        }
                        _ => {
                            trace!(self.logger, "Unknown libinput device event");
                        }
                    },
                    libinput::Event::Touch(touch_event) => match touch_event {
                        event::TouchEvent::Down(down_event) => {
                            callback(InputEvent::TouchDown { event: down_event }, &mut ());
                        }
                        event::TouchEvent::Motion(motion_event) => {
                            callback(InputEvent::TouchMotion { event: motion_event }, &mut ());
                        }
                        event::TouchEvent::Up(up_event) => {
                            callback(InputEvent::TouchUp { event: up_event }, &mut ());
                        }
                        event::TouchEvent::Cancel(cancel_event) => {
                            callback(InputEvent::TouchCancel { event: cancel_event }, &mut ());
                        }
                        event::TouchEvent::Frame(frame_event) => {
                            callback(InputEvent::TouchFrame { event: frame_event }, &mut ());
                        }
                        _ => {
                            trace!(self.logger, "Unknown libinput touch event");
                        }
                    },
                    libinput::Event::Keyboard(keyboard_event) => match keyboard_event {
                        event::KeyboardEvent::Key(key_event) => {
                            callback(InputEvent::Keyboard { event: key_event }, &mut ());
                        }
                        _ => {
                            trace!(self.logger, "Unknown libinput keyboard event");
                        }
                    },
                    libinput::Event::Pointer(pointer_event) => match pointer_event {
                        event::PointerEvent::Motion(motion_event) => {
                            callback(InputEvent::PointerMotion { event: motion_event }, &mut ());
                        }
                        event::PointerEvent::MotionAbsolute(motion_abs_event) => {
                            callback(
                                InputEvent::PointerMotionAbsolute {
                                    event: motion_abs_event,
                                },
                                &mut (),
                            );
                        }
                        event::PointerEvent::Axis(axis_event) => {
                            callback(InputEvent::PointerAxis { event: axis_event }, &mut ());
                        }
                        event::PointerEvent::Button(button_event) => {
                            callback(InputEvent::PointerButton { event: button_event }, &mut ());
                        }
                        _ => {
                            trace!(self.logger, "Unknown libinput pointer event");
                        }
                    },
                    libinput::Event::Tablet(tablet_event) => match tablet_event {
                        event::TabletToolEvent::Axis(event) => {
                            callback(InputEvent::TabletToolAxis { event }, &mut ());
                        }
                        event::TabletToolEvent::Proximity(event) => {
                            callback(InputEvent::TabletToolProximity { event }, &mut ());
                        }
                        event::TabletToolEvent::Tip(event) => {
                            callback(InputEvent::TabletToolTip { event }, &mut ());
                        }
                        event::TabletToolEvent::Button(event) => {
                            callback(InputEvent::TabletToolButton { event }, &mut ());
                        }
                        _ => {
                            trace!(self.logger, "Unknown libinput tablet event");
                        }
                    },
                    _ => {} //FIXME: What to do with the rest.
                }
            }
        }

        Ok(PostAction::Continue)
    }

    fn register(&mut self, poll: &mut Poll, factory: &mut TokenFactory) -> calloop::Result<()> {
        self.token = Some(factory.token());
        poll.register(self.as_raw_fd(), Interest::READ, Mode::Level, self.token.unwrap())
    }

    fn reregister(&mut self, poll: &mut Poll, factory: &mut TokenFactory) -> calloop::Result<()> {
        self.token = Some(factory.token());
        poll.reregister(self.as_raw_fd(), Interest::READ, Mode::Level, self.token.unwrap())
    }

    fn unregister(&mut self, poll: &mut Poll) -> calloop::Result<()> {
        self.token = None;
        poll.unregister(self.as_raw_fd())
    }
}

<MSG> backend.input: rework libinput as a calloop source

<DFF> @@ -3,7 +3,7 @@
 mod helpers;
 use helpers::{on_device_event, on_keyboard_event, on_pointer_event, on_touch_event};
 
-use crate::backend::input::{self as backend, Axis, InputBackend};
+use crate::backend::input::{self as backend, Axis, InputBackend, InputEvent};
 #[cfg(feature = "backend_session")]
 use crate::backend::session::{AsErrno, Session, SessionObserver};
 use input as libinput;
@@ -17,7 +17,7 @@ use std::{
     os::unix::io::{AsRawFd, RawFd},
 };
 
-use calloop::{generic::Generic, InsertError, LoopHandle, Source};
+use calloop::{EventSource, Interest, Mode, Poll, Readiness, Token};
 
 // No idea if this is the same across unix platforms
 // Lets make this linux exclusive for now, once someone tries to build it for
@@ -31,9 +31,8 @@ const INPUT_MAJOR: u32 = 13;
 /// context.
 pub struct LibinputInputBackend {
     context: libinput::Libinput,
-    devices: Vec<libinput::Device>,
+    config: LibinputConfig,
     seats: HashMap<libinput::Seat, backend::Seat>,
-    handler: Option<Box<dyn backend::InputHandler<LibinputInputBackend> + 'static>>,
     logger: ::slog::Logger,
 }
 
@@ -48,9 +47,8 @@ impl LibinputInputBackend {
         info!(log, "Initializing a libinput backend");
         LibinputInputBackend {
             context,
-            devices: Vec::new(),
+            config: LibinputConfig { devices: Vec::new() },
             seats: HashMap::new(),
-            handler: None,
             logger: log,
         }
     }
@@ -246,8 +244,30 @@ impl backend::Event for event::touch::TouchFrameEvent {
 
 impl backend::TouchFrameEvent for event::touch::TouchFrameEvent {}
 
+/// Special events generated by Libinput
+pub enum LibinputEvent {
+    /// A new device was plugged in
+    NewDevice(libinput::Device),
+    /// A device was plugged out
+    RemovedDevice(libinput::Device),
+}
+
+/// Configuration handle for libinput
+///
+/// This type allows you to access the list of know devices to configure them
+/// if relevant
+pub struct LibinputConfig {
+    devices: Vec<libinput::Device>,
+}
+
+impl LibinputConfig {
+    /// Access the list of current devices
+    pub fn devices(&mut self) -> &mut [libinput::Device] {
+        &mut self.devices
+    }
+}
+
 impl InputBackend for LibinputInputBackend {
-    type InputConfig = [libinput::Device];
     type EventError = IoError;
 
     type KeyboardKeyEvent = event::keyboard::KeyboardKeyEvent;
@@ -261,60 +281,60 @@ impl InputBackend for LibinputInputBackend {
     type TouchCancelEvent = event::touch::TouchCancelEvent;
     type TouchFrameEvent = event::touch::TouchFrameEvent;
 
-    fn set_handler<H: backend::InputHandler<Self> + 'static>(&mut self, mut handler: H) {
-        if self.handler.is_some() {
-            self.clear_handler();
-        }
-        info!(self.logger, "New input handler set");
-        for seat in self.seats.values() {
-            trace!(self.logger, "Calling on_seat_created with {:?}", seat);
-            handler.on_seat_created(seat);
-        }
-        self.handler = Some(Box::new(handler));
-    }
-
-    fn get_handler(&mut self) -> Option<&mut dyn backend::InputHandler<Self>> {
-        self.handler
-            .as_mut()
-            .map(|handler| handler as &mut dyn backend::InputHandler<Self>)
-    }
+    type SpecialEvent = LibinputEvent;
+    type InputConfig = LibinputConfig;
 
-    fn clear_handler(&mut self) {
-        if let Some(mut handler) = self.handler.take() {
-            for seat in self.seats.values() {
-                trace!(self.logger, "Calling on_seat_destroyed with {:?}", seat);
-                handler.on_seat_destroyed(seat);
-            }
-            info!(self.logger, "Removing input handler");
-        }
+    fn seats(&self) -> Vec<backend::Seat> {
+        self.seats.values().cloned().collect()
     }
 
     fn input_config(&mut self) -> &mut Self::InputConfig {
-        &mut self.devices
+        &mut self.config
     }
 
-    fn dispatch_new_events(&mut self) -> Result<(), IoError> {
+    fn dispatch_new_events<F>(&mut self, mut callback: F) -> Result<(), IoError>
+    where
+        F: FnMut(InputEvent<Self>, &mut LibinputConfig),
+    {
         self.context.dispatch()?;
 
         for event in &mut self.context {
             match event {
                 libinput::Event::Device(device_event) => {
                     on_device_event(
-                        &mut self.handler,
+                        &mut callback,
                         &mut self.seats,
-                        &mut self.devices,
+                        &mut self.config,
                         device_event,
                         &self.logger,
                     );
                 }
                 libinput::Event::Touch(touch_event) => {
-                    on_touch_event(&mut self.handler, &self.seats, touch_event, &self.logger);
+                    on_touch_event(
+                        &mut callback,
+                        &self.seats,
+                        &mut self.config,
+                        touch_event,
+                        &self.logger,
+                    );
                 }
                 libinput::Event::Keyboard(keyboard_event) => {
-                    on_keyboard_event(&mut self.handler, &self.seats, keyboard_event, &self.logger);
+                    on_keyboard_event(
+                        &mut callback,
+                        &self.seats,
+                        &mut self.config,
+                        keyboard_event,
+                        &self.logger,
+                    );
                 }
                 libinput::Event::Pointer(pointer_event) => {
-                    on_pointer_event(&mut self.handler, &self.seats, pointer_event, &self.logger);
+                    on_pointer_event(
+                        &mut callback,
+                        &self.seats,
+                        &mut self.config,
+                        pointer_event,
+                        &self.logger,
+                    );
                 }
                 _ => {} //FIXME: What to do with the rest.
             }
@@ -421,24 +441,27 @@ impl AsRawFd for LibinputInputBackend {
     }
 }
 
-/// calloop source associated with the libinput backend
-pub type LibinputSource = Generic<LibinputInputBackend>;
+impl EventSource for LibinputInputBackend {
+    type Event = InputEvent<LibinputInputBackend>;
+    type Metadata = LibinputConfig;
+    type Ret = ();
 
-/// Binds a [`LibinputInputBackend`] to a given [`LoopHandle`].
-///
-/// Automatically feeds the backend with incoming events without any manual calls to
-/// [`dispatch_new_events`](InputBackend::dispatch_new_events). Should be used to achieve the smallest possible latency.
-pub fn libinput_bind<Data: 'static>(
-    backend: LibinputInputBackend,
-    handle: LoopHandle<Data>,
-) -> Result<Source<LibinputSource>, InsertError<LibinputSource>> {
-    let source = Generic::new(backend, calloop::Interest::Readable, calloop::Mode::Level);
-
-    handle.insert_source(source, move |_, backend, _| {
-        if let Err(error) = backend.dispatch_new_events() {
-            warn!(backend.logger, "Libinput errored: {}", error);
-            return Err(std::io::Error::new(std::io::ErrorKind::Other, Box::new(error)));
-        }
-        Ok(())
-    })
+    fn process_events<F>(&mut self, _: Readiness, _: Token, callback: F) -> std::io::Result<()>
+    where
+        F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
+    {
+        self.dispatch_new_events(callback)
+    }
+
+    fn register(&mut self, poll: &mut Poll, token: Token) -> std::io::Result<()> {
+        poll.register(self.as_raw_fd(), Interest::Readable, Mode::Level, token)
+    }
+
+    fn reregister(&mut self, poll: &mut Poll, token: Token) -> std::io::Result<()> {
+        poll.reregister(self.as_raw_fd(), Interest::Readable, Mode::Level, token)
+    }
+
+    fn unregister(&mut self, poll: &mut Poll) -> std::io::Result<()> {
+        poll.unregister(self.as_raw_fd())
+    }
 }

backend.input: rework libinput as a calloop source