Skip to main content

mgui_shell/
lib.rs

1//! mgui-shell — 平台无关的 Shell 抽象。
2//!
3//! 这里是 desktop / headless 共享的最小契约:
4//! - [`Clock`]:帧循环、动画与 IME 闪烁的时间来源
5//! - [`ShellMetrics`]:逻辑尺寸 + DPR
6//! - [`ClipboardProvider`]:复用 core 的剪贴板契约
7//!
8//! 窗口创建、原生输入、present 等 desktop 专属能力后续在其上继续分层;
9//! 无窗口环境请使用 `mgui-shell-headless`。
10
11#![forbid(unsafe_code)]
12
13use std::cell::Cell;
14use std::time::Instant;
15
16use mgui_core::{KeyCode, KeyModifiers, MouseButton, Point, Rect, Size};
17
18pub use mgui_core::{ClipboardProvider, NoopClipboard};
19
20/// 平台无关窗口 ID。
21#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
22pub struct ShellWindowId(pub u64);
23
24/// Shell 的尺寸与 DPI。
25#[derive(Clone, Copy, Debug, PartialEq)]
26pub struct ShellMetrics {
27    pub logical_size: Size,
28    /// 物理像素 / 逻辑像素
29    pub scale_factor: f32,
30}
31
32impl ShellMetrics {
33    pub fn new(logical_size: Size, scale_factor: f32) -> Self {
34        Self {
35            logical_size: Size::new(logical_size.width.max(1.0), logical_size.height.max(1.0)),
36            scale_factor: scale_factor.max(0.01),
37        }
38    }
39
40    /// 从物理像素尺寸与 DPR 推导逻辑尺寸。
41    pub fn from_physical(physical_width: u32, physical_height: u32, scale_factor: f32) -> Self {
42        let scale_factor = scale_factor.max(0.01);
43        Self::new(Size::new(physical_width as f32 / scale_factor, physical_height as f32 / scale_factor), scale_factor)
44    }
45}
46
47impl Default for ShellMetrics {
48    fn default() -> Self {
49        Self::new(Size::new(800.0, 600.0), 1.0)
50    }
51}
52
53/// 窗口/DPI/IME 能力——应用只依赖此接口,不直接依赖 winit。
54///
55/// 逻辑坐标约定:`set_ime_cursor_area` 接收 root layer 逻辑坐标(与布局一致),
56/// 由具体 shell 负责换算成平台需要的物理/逻辑单位。
57pub trait WindowShell {
58    fn metrics(&self) -> ShellMetrics;
59    fn request_redraw(&self);
60    fn set_title(&self, title: &str);
61    fn set_visible(&self, visible: bool);
62    fn set_ime_allowed(&self, allowed: bool);
63    fn set_ime_cursor_area(&self, rect: Rect);
64}
65
66/// 平台无关输入事件 —— 桌面 shell 把原生事件翻译成此类型后再交给应用。
67///
68/// 坐标语义:全部为 **root layer 逻辑坐标**(已按 DPR 换算)。
69#[derive(Clone, Debug, PartialEq)]
70pub enum ShellEvent {
71    CursorMoved {
72        position: Point,
73    },
74    MouseInput {
75        position: Point,
76        button: MouseButton,
77        pressed: bool,
78        modifiers: KeyModifiers,
79    },
80    /// 滚轮/触控板:delta 已归一化为逻辑像素(约 16px/行)。
81    Wheel {
82        position: Point,
83        delta: Point,
84        modifiers: KeyModifiers,
85    },
86    ModifiersChanged(KeyModifiers),
87    Keyboard {
88        key: KeyCode,
89        pressed: bool,
90        repeat: bool,
91        modifiers: KeyModifiers,
92    },
93    Focused(bool),
94    Ime(ImeEvent),
95}
96
97/// 平台无关 IME 事件。
98#[derive(Clone, Debug, PartialEq, Eq)]
99pub enum ImeEvent {
100    Enabled,
101    Disabled,
102    Preedit(String, Option<(usize, usize)>),
103    Commit(String),
104}
105
106/// 帧循环 / 动画使用的单调毫秒时钟。
107pub trait Clock {
108    fn now_ms(&self) -> u64;
109}
110
111/// 手动推进的确定性时钟 —— headless 测试 / 回放用。
112#[derive(Clone, Debug)]
113pub struct ManualClock {
114    now_ms: Cell<u64>,
115}
116
117impl ManualClock {
118    pub fn new(start_ms: u64) -> Self {
119        Self { now_ms: Cell::new(start_ms) }
120    }
121
122    pub fn set(&self, now_ms: u64) {
123        self.now_ms.set(now_ms);
124    }
125
126    pub fn advance(&self, delta_ms: u64) -> u64 {
127        let next = self.now_ms.get().saturating_add(delta_ms);
128        self.now_ms.set(next);
129        next
130    }
131}
132
133impl Default for ManualClock {
134    fn default() -> Self {
135        Self::new(0)
136    }
137}
138
139impl Clock for ManualClock {
140    fn now_ms(&self) -> u64 {
141        self.now_ms.get()
142    }
143}
144
145/// 真实系统时钟(桌面 / 集成环境用)。
146#[derive(Debug)]
147pub struct SystemClock {
148    start: Instant,
149}
150
151impl SystemClock {
152    pub fn new() -> Self {
153        Self { start: Instant::now() }
154    }
155}
156
157impl Default for SystemClock {
158    fn default() -> Self {
159        Self::new()
160    }
161}
162
163impl Clock for SystemClock {
164    fn now_ms(&self) -> u64 {
165        self.start.elapsed().as_millis() as u64
166    }
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172
173    #[test]
174    fn manual_clock_is_deterministic() {
175        let clock = ManualClock::new(100);
176        assert_eq!(clock.now_ms(), 100);
177        assert_eq!(clock.advance(16), 116);
178        clock.set(500);
179        assert_eq!(clock.now_ms(), 500);
180    }
181
182    #[test]
183    fn metrics_clamp_invalid_values() {
184        let m = ShellMetrics::new(Size::new(0.0, -5.0), 0.0);
185        assert_eq!(m.logical_size, Size::new(1.0, 1.0));
186        assert_eq!(m.scale_factor, 0.01);
187    }
188
189    #[test]
190    fn metrics_from_physical_divides_by_dpr() {
191        let m = ShellMetrics::from_physical(1920, 1080, 2.0);
192        assert_eq!(m.logical_size, Size::new(960.0, 540.0));
193        assert_eq!(m.scale_factor, 2.0);
194    }
195}