sinomo-ui-core 0.7.0

Shared core contracts and data types for SUI.
Documentation
use std::{ops::Range, path::PathBuf};

use crate::{
    AsyncWakeToken, DragEvent, Point, SafeAreaInsets, SemanticsActionRequest, Size, TimerToken,
    Vector, WidgetId,
};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Modifiers {
    pub shift: bool,
    pub control: bool,
    pub alt: bool,
    pub meta: bool,
}

/// Requested host behavior for the system cursor.
///
/// Cursor grabbing is best effort. A platform may fall back from [`Self::Locked`]
/// to [`Self::Confined`], or leave the cursor ungrabbed when neither mode is
/// supported.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CursorGrabMode {
    /// The cursor can leave the host viewport and absolute pointer motion is
    /// available normally.
    #[default]
    None,
    /// Keep the cursor inside the host viewport while retaining an absolute
    /// cursor position.
    Confined,
    /// Decouple motion from the host's absolute cursor position and report
    /// relative movement. Visibility remains a separate host request.
    Locked,
}

/// Device-relative mouse motion in the host's raw, device-specific units.
///
/// This event is independent of [`PointerEvent::position`] and is not DPI
/// normalized. Desktop hosts deliver it to the widget that owns the active
/// cursor grab.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RawMouseMotionEvent {
    pub delta: Vector,
    pub modifiers: Modifiers,
}

impl Modifiers {
    pub const NONE: Self = Self {
        shift: false,
        control: false,
        alt: false,
        meta: false,
    };

    pub const fn any(self) -> bool {
        self.shift || self.control || self.alt || self.meta
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PointerButton {
    Primary,
    Secondary,
    Middle,
    Back,
    Forward,
    Other(u16),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct PointerButtons(u8);

impl PointerButtons {
    const PRIMARY: u8 = 1 << 0;
    const SECONDARY: u8 = 1 << 1;
    const MIDDLE: u8 = 1 << 2;
    const BACK: u8 = 1 << 3;
    const FORWARD: u8 = 1 << 4;

    pub const NONE: Self = Self(0);

    pub const fn new(bits: u8) -> Self {
        Self(bits)
    }

    pub const fn bits(self) -> u8 {
        self.0
    }

    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }

    pub const fn contains(self, button: PointerButton) -> bool {
        match Self::mask(button) {
            Some(mask) => self.0 & mask != 0,
            None => false,
        }
    }

    pub fn insert(&mut self, button: PointerButton) {
        if let Some(mask) = Self::mask(button) {
            self.0 |= mask;
        }
    }

    const fn mask(button: PointerButton) -> Option<u8> {
        match button {
            PointerButton::Primary => Some(Self::PRIMARY),
            PointerButton::Secondary => Some(Self::SECONDARY),
            PointerButton::Middle => Some(Self::MIDDLE),
            PointerButton::Back => Some(Self::BACK),
            PointerButton::Forward => Some(Self::FORWARD),
            PointerButton::Other(_) => None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PointerKind {
    #[default]
    Mouse,
    Touch,
    Pen,
    Unknown,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PointerEventKind {
    Down,
    Up,
    Move,
    Scroll,
    Enter,
    Leave,
    Cancel,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ScrollDelta {
    Lines(Vector),
    Pixels(Vector),
}

#[derive(Debug, Clone, PartialEq)]
pub struct PointerEvent {
    pub pointer_id: u64,
    pub kind: PointerEventKind,
    pub position: Point,
    pub delta: Vector,
    pub scroll_delta: Option<ScrollDelta>,
    pub button: Option<PointerButton>,
    pub buttons: PointerButtons,
    pub modifiers: Modifiers,
    pub pointer_kind: PointerKind,
    pub is_primary: bool,
}

impl PointerEvent {
    pub fn new(kind: PointerEventKind, position: Point) -> Self {
        Self {
            pointer_id: 0,
            kind,
            position,
            delta: Vector::ZERO,
            scroll_delta: None,
            button: None,
            buttons: PointerButtons::NONE,
            modifiers: Modifiers::NONE,
            pointer_kind: PointerKind::Mouse,
            is_primary: true,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum WakeEvent {
    Timer {
        token: TimerToken,
        time: f64,
        deadline: f64,
    },
    Async {
        token: AsyncWakeToken,
        time: f64,
    },
    AnimationFrame {
        time: f64,
        delta: f64,
        frame_index: u64,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyState {
    Pressed,
    Released,
}

#[derive(Debug, Clone, PartialEq)]
pub struct KeyboardEvent {
    pub key: String,
    pub code: String,
    pub text: Option<String>,
    pub state: KeyState,
    pub modifiers: Modifiers,
    pub repeat: bool,
    pub is_composing: bool,
}

impl KeyboardEvent {
    pub fn new(key: impl Into<String>, state: KeyState) -> Self {
        let key = key.into();

        Self {
            code: key.clone(),
            text: keyboard_text_for_key(&key, state),
            key,
            state,
            modifiers: Modifiers::NONE,
            repeat: false,
            is_composing: false,
        }
    }
}

fn keyboard_text_for_key(key: &str, state: KeyState) -> Option<String> {
    if state != KeyState::Pressed {
        return None;
    }

    if key.is_empty() || key.chars().any(char::is_control) {
        return None;
    }

    if key.chars().count() == 1 {
        Some(key.to_string())
    } else {
        None
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum ImeEvent {
    CompositionStart,
    CompositionUpdate {
        text: String,
        cursor_range: Option<Range<usize>>,
    },
    CompositionCommit {
        text: String,
    },
    CompositionEnd,
}

#[derive(Debug, Clone, PartialEq)]
pub enum WindowEvent {
    /// The host target should close. The target is identified by the
    /// `WindowId` attached to the delivery path rather than by this event.
    CloseRequested,
    /// The host target's viewport changed size. The target may be a native
    /// window or an embedded viewport/region.
    Resized(Size),
    /// The native desktop window moved to a new physical desktop position.
    /// Embedded and web hosts may never emit this event.
    Moved(Point),
    ScaleFactorChanged {
        scale_factor: f64,
        raw_dpi: Option<f32>,
        suggested_size: Option<Size>,
    },
    /// The unobscured inset from each viewport edge changed, usually after a
    /// mobile rotation, browser viewport update, or host embedding change.
    SafeAreaChanged(SafeAreaInsets),
    Focused(bool),
    Occluded(bool),
    /// A file from outside the application is being hovered over the host
    /// window. Platforms emit one event per file when several files are
    /// dragged together.
    ExternalFileHovered(PathBuf),
    /// Files from outside the application left the host window without being
    /// dropped.
    ExternalFileHoverCancelled,
    /// A file from outside the application was dropped on the host window.
    /// Platforms emit one event per file when several files are dropped
    /// together.
    ExternalFileDropped(PathBuf),
    RedrawRequested,
}

#[derive(Debug, Clone, PartialEq)]
pub struct CustomEvent {
    pub kind: String,
    pub payload: Option<String>,
}

/// An assistive-technology action directed at a semantic node.
///
/// The runtime routes this event to the retained widget that owns `target` (or
/// the nearest graph-backed semantic ancestor for a virtual node). The semantic
/// target remains in the event so widgets with virtual or generated children
/// can update their own local state.
#[derive(Debug, Clone, PartialEq)]
pub struct SemanticsEvent {
    pub target: WidgetId,
    pub action: SemanticsActionRequest,
}

impl SemanticsEvent {
    pub fn new(target: WidgetId, action: SemanticsActionRequest) -> Self {
        Self { target, action }
    }
}

impl CustomEvent {
    pub fn new(kind: impl Into<String>) -> Self {
        Self {
            kind: kind.into(),
            payload: None,
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum Event {
    Pointer(PointerEvent),
    RawMouseMotion(RawMouseMotionEvent),
    Drag(DragEvent),
    Keyboard(KeyboardEvent),
    Ime(ImeEvent),
    Semantics(SemanticsEvent),
    Wake(WakeEvent),
    /// Window or embedded-viewport lifecycle event. The receiving `WindowId`
    /// is carried by the platform/runtime call that delivers the event.
    Window(WindowEvent),
    Custom(CustomEvent),
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use super::{WakeEvent, WindowEvent};

    #[test]
    fn wake_event_animation_frame_carries_time_and_delta() {
        let event = WakeEvent::AnimationFrame {
            time: 42.5,
            delta: 1.0 / 120.0,
            frame_index: 7,
        };

        assert!(matches!(
            event,
            WakeEvent::AnimationFrame {
                time,
                delta,
                frame_index
            } if time == 42.5 && delta == 1.0 / 120.0 && frame_index == 7
        ));
    }

    #[test]
    fn external_file_window_events_preserve_paths_and_cancellation() {
        let path = PathBuf::from(r"C:\workspace\candidate.json");

        let hovered = WindowEvent::ExternalFileHovered(path.clone());
        let dropped = WindowEvent::ExternalFileDropped(path.clone());

        assert!(matches!(
            hovered,
            WindowEvent::ExternalFileHovered(event_path) if event_path == path
        ));
        assert!(matches!(
            dropped,
            WindowEvent::ExternalFileDropped(event_path) if event_path == path
        ));
        assert!(matches!(
            WindowEvent::ExternalFileHoverCancelled,
            WindowEvent::ExternalFileHoverCancelled
        ));
    }
}