mgui-shell-winit 0.2.0

winit 适配层:Window → WindowShell / ShellEvent,以及软件回退窗口句柄
Documentation
//! winit → `ShellEvent` 输入翻译器。
//!
//! 负责所有平台差异:
//! - 物理像素 → 逻辑坐标(CursorMoved / PixelDelta)
//! - LineDelta × 16 / PixelDelta ÷ DPR ÷ 2 → 统一逻辑滚轮像素
//! - winit Key / NamedKey → core `KeyCode`(含 Shift+Tab、F3)
//! - winit ModifiersState → core `KeyModifiers`
//! - winit Ime → `ImeEvent`

use mgui_core::{KeyCode, KeyModifiers, MouseButton, Point};
use mgui_shell::{ImeEvent, ShellEvent, SystemTheme};
use winit::event::{ElementState, Ime as WinitIme, MouseButton as WinitMouseButton, MouseScrollDelta, WindowEvent};
use winit::keyboard::{Key, NamedKey};
use winit::window::{Theme as WinitTheme, Window};

/// 有状态输入翻译器:跟踪最近指针位置与修饰键。
#[derive(Debug)]
pub struct WinitInput {
    cursor: Point,
    modifiers: KeyModifiers,
}

impl WinitInput {
    pub fn new() -> Self {
        Self { cursor: Point::ZERO, modifiers: KeyModifiers::none() }
    }

    /// 最近一次 `ModifiersChanged` 的修饰键状态。
    pub fn modifiers(&self) -> KeyModifiers {
        self.modifiers
    }

    /// 返回 `None` 表示该原生事件不需要传给应用(Resize/Redraw/Close 等由 Runner 处理)。
    pub fn translate(&mut self, window: &Window, event: &WindowEvent) -> Option<ShellEvent> {
        let sf = (window.scale_factor() as f32).max(0.01);
        match event {
            WindowEvent::CursorMoved { position, .. } => {
                self.cursor = Point::new(position.x as f32 / sf, position.y as f32 / sf);
                Some(ShellEvent::CursorMoved { position: self.cursor })
            }
            WindowEvent::MouseInput { state, button, .. } => Some(ShellEvent::MouseInput {
                position: self.cursor,
                button: map_button(*button),
                pressed: *state == ElementState::Pressed,
                modifiers: self.modifiers,
            }),
            WindowEvent::ModifiersChanged(mods) => {
                self.modifiers = map_modifiers(mods.state());
                Some(ShellEvent::ModifiersChanged(self.modifiers))
            }
            WindowEvent::MouseWheel { delta, .. } => Some(ShellEvent::Wheel {
                position: self.cursor,
                delta: scroll_delta(sf, delta),
                modifiers: self.modifiers,
            }),
            WindowEvent::KeyboardInput { event: key_event, .. } => {
                let key = convert_key(key_event, self.modifiers)?;
                Some(ShellEvent::Keyboard {
                    key,
                    pressed: key_event.state == ElementState::Pressed,
                    repeat: key_event.repeat,
                    modifiers: self.modifiers,
                })
            }
            WindowEvent::Focused(focused) => Some(ShellEvent::Focused(*focused)),
            WindowEvent::CursorLeft { .. } => Some(ShellEvent::CursorLeft),
            WindowEvent::HoveredFile(path) => Some(ShellEvent::FileHovered(path.clone())),
            WindowEvent::HoveredFileCancelled => Some(ShellEvent::FileHoverCancelled),
            WindowEvent::DroppedFile(path) => Some(ShellEvent::FileDropped(path.clone())),
            WindowEvent::ThemeChanged(theme) => Some(ShellEvent::ThemeChanged(map_theme(*theme))),
            WindowEvent::Ime(ime) => Some(ShellEvent::Ime(match ime {
                WinitIme::Enabled => ImeEvent::Enabled,
                WinitIme::Disabled => ImeEvent::Disabled,
                WinitIme::Preedit(text, cursor) => ImeEvent::Preedit(text.clone(), *cursor),
                WinitIme::Commit(text) => ImeEvent::Commit(text.clone()),
            })),
            _ => None,
        }
    }
}

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

fn map_theme(theme: WinitTheme) -> SystemTheme {
    match theme {
        WinitTheme::Light => SystemTheme::Light,
        WinitTheme::Dark => SystemTheme::Dark,
    }
}

fn map_button(button: WinitMouseButton) -> MouseButton {
    match button {
        WinitMouseButton::Left => MouseButton::Left,
        WinitMouseButton::Right => MouseButton::Right,
        WinitMouseButton::Middle => MouseButton::Middle,
        _ => MouseButton::Other(0),
    }
}

fn map_modifiers(state: winit::keyboard::ModifiersState) -> KeyModifiers {
    let mut km = KeyModifiers::none();
    if state.shift_key() {
        km.0 |= KeyModifiers::SHIFT;
    }
    if state.control_key() {
        km.0 |= KeyModifiers::CTRL;
    }
    if state.alt_key() {
        km.0 |= KeyModifiers::ALT;
    }
    if state.super_key() {
        km.0 |= KeyModifiers::META;
    }
    km
}

fn scroll_delta(scale_factor: f32, delta: &MouseScrollDelta) -> Point {
    match delta {
        MouseScrollDelta::LineDelta(x, y) => Point::new(x * 16.0, y * 16.0),
        MouseScrollDelta::PixelDelta(p) => Point::new(p.x as f32 / scale_factor / 2.0, p.y as f32 / scale_factor / 2.0),
    }
}

fn convert_key(key_event: &winit::event::KeyEvent, mods: KeyModifiers) -> Option<KeyCode> {
    let code = match &key_event.logical_key {
        Key::Named(NamedKey::Enter) => KeyCode::Enter,
        Key::Named(NamedKey::Space) => KeyCode::Space,
        Key::Named(NamedKey::Escape) => KeyCode::Escape,
        Key::Named(NamedKey::Tab) => {
            if mods.shift() {
                KeyCode::BackTab
            } else {
                KeyCode::Tab
            }
        }
        Key::Named(NamedKey::ArrowLeft) => KeyCode::LeftArrow,
        Key::Named(NamedKey::ArrowRight) => KeyCode::RightArrow,
        Key::Named(NamedKey::ArrowUp) => KeyCode::UpArrow,
        Key::Named(NamedKey::ArrowDown) => KeyCode::DownArrow,
        Key::Named(NamedKey::PageUp) => KeyCode::PageUp,
        Key::Named(NamedKey::PageDown) => KeyCode::PageDown,
        Key::Named(NamedKey::Home) => KeyCode::Home,
        Key::Named(NamedKey::End) => KeyCode::End,
        Key::Named(NamedKey::Backspace) => KeyCode::Backspace,
        Key::Named(NamedKey::Delete) => KeyCode::Delete,
        Key::Named(NamedKey::F3) => KeyCode::F3,
        Key::Named(NamedKey::F11) => KeyCode::F11,
        Key::Character(s) => {
            let mut chars = s.chars();
            match (chars.next(), chars.next()) {
                (Some(c), None) if !c.is_control() => KeyCode::Char(c.to_lowercase().next().unwrap_or(c)),
                _ => KeyCode::Other,
            }
        }
        _ => KeyCode::Other,
    };
    Some(code)
}

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

    #[test]
    fn line_delta_maps_to_16px_per_line() {
        let p = scroll_delta(2.0, &MouseScrollDelta::LineDelta(1.0, -2.0));
        assert_eq!(p, Point::new(16.0, -32.0), "LineDelta 不应乘 DPR");
    }

    #[test]
    fn pixel_delta_is_logical_and_halved() {
        let p = scroll_delta(2.0, &MouseScrollDelta::PixelDelta(winit::dpi::PhysicalPosition::new(40.0, -80.0)));
        assert_eq!(p, Point::new(10.0, -20.0));
    }

    #[test]
    fn theme_maps_to_shell_enum() {
        assert_eq!(map_theme(WinitTheme::Light), SystemTheme::Light);
        assert_eq!(map_theme(WinitTheme::Dark), SystemTheme::Dark);
    }

    #[test]
    fn mouse_buttons_map_to_core_enum() {
        assert_eq!(map_button(WinitMouseButton::Left), MouseButton::Left);
        assert_eq!(map_button(WinitMouseButton::Right), MouseButton::Right);
        assert_eq!(map_button(WinitMouseButton::Middle), MouseButton::Middle);
        assert_eq!(map_button(WinitMouseButton::Back), MouseButton::Other(0));
    }

    #[test]
    fn modifiers_map_all_four_bits() {
        let state = winit::keyboard::ModifiersState::SHIFT
            | winit::keyboard::ModifiersState::CONTROL
            | winit::keyboard::ModifiersState::ALT
            | winit::keyboard::ModifiersState::SUPER;
        let km = map_modifiers(state);
        assert!(km.shift() && km.ctrl() && km.alt() && km.meta());
    }
}