mgui-shell 0.1.0

平台无关 Shell 抽象:Clock / ShellMetrics / Clipboard 能力契约
Documentation
//! mgui-shell — 平台无关的 Shell 抽象。
//!
//! 这里是 desktop / headless 共享的最小契约:
//! - [`Clock`]:帧循环、动画与 IME 闪烁的时间来源
//! - [`ShellMetrics`]:逻辑尺寸 + DPR
//! - [`ClipboardProvider`]:复用 core 的剪贴板契约
//!
//! 窗口创建、原生输入、present 等 desktop 专属能力后续在其上继续分层;
//! 无窗口环境请使用 `mgui-shell-headless`。

#![forbid(unsafe_code)]

use std::cell::Cell;
use std::time::Instant;

use mgui_core::{KeyCode, KeyModifiers, MouseButton, Point, Rect, Size};

pub use mgui_core::{ClipboardProvider, NoopClipboard};

/// 平台无关窗口 ID。
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ShellWindowId(pub u64);

/// Shell 的尺寸与 DPI。
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ShellMetrics {
    pub logical_size: Size,
    /// 物理像素 / 逻辑像素
    pub scale_factor: f32,
}

impl ShellMetrics {
    pub fn new(logical_size: Size, scale_factor: f32) -> Self {
        Self {
            logical_size: Size::new(logical_size.width.max(1.0), logical_size.height.max(1.0)),
            scale_factor: scale_factor.max(0.01),
        }
    }

    /// 从物理像素尺寸与 DPR 推导逻辑尺寸。
    pub fn from_physical(physical_width: u32, physical_height: u32, scale_factor: f32) -> Self {
        let scale_factor = scale_factor.max(0.01);
        Self::new(Size::new(physical_width as f32 / scale_factor, physical_height as f32 / scale_factor), scale_factor)
    }
}

impl Default for ShellMetrics {
    fn default() -> Self {
        Self::new(Size::new(800.0, 600.0), 1.0)
    }
}

/// 窗口/DPI/IME 能力——应用只依赖此接口,不直接依赖 winit。
///
/// 逻辑坐标约定:`set_ime_cursor_area` 接收 root layer 逻辑坐标(与布局一致),
/// 由具体 shell 负责换算成平台需要的物理/逻辑单位。
pub trait WindowShell {
    fn metrics(&self) -> ShellMetrics;
    fn request_redraw(&self);
    fn set_title(&self, title: &str);
    fn set_visible(&self, visible: bool);
    fn set_ime_allowed(&self, allowed: bool);
    fn set_ime_cursor_area(&self, rect: Rect);
}

/// 平台无关输入事件 —— 桌面 shell 把原生事件翻译成此类型后再交给应用。
///
/// 坐标语义:全部为 **root layer 逻辑坐标**(已按 DPR 换算)。
#[derive(Clone, Debug, PartialEq)]
pub enum ShellEvent {
    CursorMoved {
        position: Point,
    },
    MouseInput {
        position: Point,
        button: MouseButton,
        pressed: bool,
        modifiers: KeyModifiers,
    },
    /// 滚轮/触控板:delta 已归一化为逻辑像素(约 16px/行)。
    Wheel {
        position: Point,
        delta: Point,
        modifiers: KeyModifiers,
    },
    ModifiersChanged(KeyModifiers),
    Keyboard {
        key: KeyCode,
        pressed: bool,
        repeat: bool,
        modifiers: KeyModifiers,
    },
    Focused(bool),
    Ime(ImeEvent),
}

/// 平台无关 IME 事件。
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ImeEvent {
    Enabled,
    Disabled,
    Preedit(String, Option<(usize, usize)>),
    Commit(String),
}

/// 帧循环 / 动画使用的单调毫秒时钟。
pub trait Clock {
    fn now_ms(&self) -> u64;
}

/// 手动推进的确定性时钟 —— headless 测试 / 回放用。
#[derive(Clone, Debug)]
pub struct ManualClock {
    now_ms: Cell<u64>,
}

impl ManualClock {
    pub fn new(start_ms: u64) -> Self {
        Self { now_ms: Cell::new(start_ms) }
    }

    pub fn set(&self, now_ms: u64) {
        self.now_ms.set(now_ms);
    }

    pub fn advance(&self, delta_ms: u64) -> u64 {
        let next = self.now_ms.get().saturating_add(delta_ms);
        self.now_ms.set(next);
        next
    }
}

impl Default for ManualClock {
    fn default() -> Self {
        Self::new(0)
    }
}

impl Clock for ManualClock {
    fn now_ms(&self) -> u64 {
        self.now_ms.get()
    }
}

/// 真实系统时钟(桌面 / 集成环境用)。
#[derive(Debug)]
pub struct SystemClock {
    start: Instant,
}

impl SystemClock {
    pub fn new() -> Self {
        Self { start: Instant::now() }
    }
}

impl Default for SystemClock {
    fn default() -> Self {
        Self::new()
    }
}

impl Clock for SystemClock {
    fn now_ms(&self) -> u64 {
        self.start.elapsed().as_millis() as u64
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn manual_clock_is_deterministic() {
        let clock = ManualClock::new(100);
        assert_eq!(clock.now_ms(), 100);
        assert_eq!(clock.advance(16), 116);
        clock.set(500);
        assert_eq!(clock.now_ms(), 500);
    }

    #[test]
    fn metrics_clamp_invalid_values() {
        let m = ShellMetrics::new(Size::new(0.0, -5.0), 0.0);
        assert_eq!(m.logical_size, Size::new(1.0, 1.0));
        assert_eq!(m.scale_factor, 0.01);
    }

    #[test]
    fn metrics_from_physical_divides_by_dpr() {
        let m = ShellMetrics::from_physical(1920, 1080, 2.0);
        assert_eq!(m.logical_size, Size::new(960.0, 540.0));
        assert_eq!(m.scale_factor, 2.0);
    }
}