mgui-shell-winit 0.9.0

winit 适配层:Window → WindowShell / ShellEvent,以及软件回退窗口句柄
Documentation
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

use mgui_core::{Rect, Size};
use mgui_shell::{
    ClipboardHandle, CursorIcon, FileDialogOptions, FileDragOptions, FileDragOutcome, NativeMenuController,
    Notification, ResizeDirection, ShellMetrics, SystemTheme, WindowCommand, WindowCommandBus, WindowCorners,
    WindowShell, WindowState,
};
use winit::dpi::{LogicalPosition, LogicalSize};
use winit::window::{
    CursorIcon as WinitCursorIcon, Fullscreen, ResizeDirection as WinitResizeDirection, Theme as WinitTheme, Window,
    WindowLevel as WinitWindowLevel,
};

/// 桌面窗口句柄(可克隆)。
#[derive(Clone)]
pub struct DesktopWindow {
    window: Arc<Window>,
    /// `ctx.shell.request_close()` 置位;host 在事件/帧循环里消费
    close_requested: Arc<AtomicBool>,
    /// 宿主创建托盘成功后置位;`WindowShell::tray_available()` 读它。
    tray_available: Arc<AtomicBool>,
    /// 桌面应用 id(Windows 通知 AUMID 兜底)。
    app_id: Option<String>,
    /// 系统剪贴板(文本/HTML/图片/文件列表)。
    clipboard: ClipboardHandle,
    /// 已安装原生菜单的运行期控制器(由 desktop host 注入)。
    native_menu: Option<Rc<dyn NativeMenuController>>,
    /// 多窗口宿主的跨窗命令总线;单窗口宿主为 None。
    window_commands: Option<WindowCommandBus>,
    /// 本窗口在 `MultiWindowConfig` 里的名字。
    window_name: Option<String>,
}

impl DesktopWindow {
    pub fn new(window: Arc<Window>) -> Self {
        Self {
            window,
            close_requested: Arc::new(AtomicBool::new(false)),
            tray_available: Arc::new(AtomicBool::new(false)),
            app_id: None,
            clipboard: ClipboardHandle::new(Box::new(crate::clipboard::DesktopClipboard::new())),
            native_menu: None,
            window_commands: None,
            window_name: None,
        }
    }

    /// 注入多窗口宿主的跨窗命令总线与本窗口名字;由 `run_multi_app` 在创建槽位时调用。
    pub fn with_window_identity(mut self, name: impl Into<String>, bus: WindowCommandBus) -> Self {
        self.window_name = Some(name.into());
        self.window_commands = Some(bus);
        self
    }

    /// 注入原生菜单控制器;由 desktop host 在菜单创建后调用。
    pub fn set_native_menu_controller(&mut self, controller: Option<Rc<dyn NativeMenuController>>) {
        self.native_menu = controller;
    }

    /// 设置应用 id;Windows 系统通知会把它作为 AUMID 兜底。
    pub fn with_app_id(mut self, app_id: impl Into<String>) -> Self {
        self.app_id = Some(app_id.into());
        self
    }

    /// 底层 winit 窗口——仅供 desktop host 的 GPU/AccessKit/事件循环使用。
    pub fn as_winit(&self) -> &Arc<Window> {
        &self.window
    }

    /// host 消费一次关闭请求。
    pub fn take_close_request(&self) -> bool {
        self.close_requested.swap(false, Ordering::SeqCst)
    }

    /// 宿主创建/移除托盘图标后写这个开关(窗口存活期间可变,故用 `Arc<AtomicBool>`)。
    pub fn set_tray_available(&self, available: bool) {
        self.tray_available.store(available, Ordering::SeqCst);
    }

    fn dialog(&self, options: &FileDialogOptions) -> rfd::FileDialog {
        let mut dialog = rfd::FileDialog::new().set_parent(self.window.as_ref());
        if !options.title.is_empty() {
            dialog = dialog.set_title(&options.title);
        }
        if let Some(directory) = &options.directory {
            dialog = dialog.set_directory(directory);
        }
        if let Some(file_name) = &options.file_name {
            dialog = dialog.set_file_name(file_name);
        }
        for filter in &options.filters {
            if filter.extensions.is_empty() {
                continue;
            }
            let extensions: Vec<&str> = filter.extensions.iter().map(String::as_str).collect();
            dialog = dialog.add_filter(&filter.name, &extensions);
        }
        dialog
    }
}

impl WindowShell for DesktopWindow {
    fn metrics(&self) -> ShellMetrics {
        let sf = (self.window.scale_factor() as f32).max(0.01);
        let phys = self.window.inner_size();
        ShellMetrics::from_physical(phys.width, phys.height, sf)
    }

    fn request_redraw(&self) {
        self.window.request_redraw();
    }

    fn window_name(&self) -> Option<String> {
        self.window_name.clone()
    }

    fn send_window_command(&self, window: &str, command: WindowCommand) -> Result<(), String> {
        match &self.window_commands {
            Some(bus) => {
                bus.send(window, command);
                // 本窗口的下一轮循环里消费;自己也顺带请求一次重绘,
                // 避免"应用只发命令、当前帧之后没有事件"时命令滞留队列。
                self.window.request_redraw();
                Ok(())
            }
            None => Err("单窗口宿主没有跨窗口命令总线".to_string()),
        }
    }

    fn set_title(&self, title: &str) {
        self.window.set_title(title);
    }

    fn set_visible(&self, visible: bool) {
        self.window.set_visible(visible);
    }

    fn is_visible(&self) -> bool {
        self.window.is_visible().unwrap_or(true)
    }

    fn set_ime_allowed(&self, allowed: bool) {
        self.window.set_ime_allowed(allowed);
    }

    fn set_ime_cursor_area(&self, rect: Rect) {
        self.window.set_ime_cursor_area(
            LogicalPosition::new(rect.x as f64, rect.y as f64),
            LogicalSize::new(rect.width.max(0.0) as f64, rect.height.max(0.0) as f64),
        );
    }

    fn set_cursor(&self, cursor: CursorIcon) {
        self.window.set_cursor(map_cursor(cursor));
    }

    fn set_fullscreen(&self, fullscreen: bool) {
        self.window.set_fullscreen(fullscreen.then_some(Fullscreen::Borderless(None)));
    }

    fn is_fullscreen(&self) -> bool {
        self.window.fullscreen().is_some()
    }

    fn set_minimized(&self, minimized: bool) {
        self.window.set_minimized(minimized);
    }

    fn set_maximized(&self, maximized: bool) {
        self.window.set_maximized(maximized);
    }

    fn is_maximized(&self) -> bool {
        self.window.is_maximized()
    }

    fn focus_window(&self) {
        self.window.focus_window();
    }

    fn set_decorations(&self, decorations: bool) {
        self.window.set_decorations(decorations);
    }

    fn start_dragging(&self) -> Result<(), String> {
        self.window.drag_window().map_err(|e| format!("start_dragging: {e}"))
    }

    fn start_resize(&self, direction: ResizeDirection) -> Result<(), String> {
        self.window.drag_resize_window(map_resize_direction(direction)).map_err(|e| format!("start_resize: {e}"))
    }

    fn set_resizable(&self, resizable: bool) {
        self.window.set_resizable(resizable);
    }

    fn set_always_on_top(&self, on_top: bool) {
        self.window.set_window_level(if on_top { WinitWindowLevel::AlwaysOnTop } else { WinitWindowLevel::Normal });
    }

    fn set_size(&self, size: Size) {
        let _ = self.window.request_inner_size(LogicalSize::new(size.width as f64, size.height as f64));
    }

    fn set_position(&self, x: f32, y: f32) {
        self.window.set_outer_position(LogicalPosition::new(x as f64, y as f64));
    }

    fn request_close(&self) {
        self.close_requested.store(true, Ordering::SeqCst);
        self.window.request_redraw();
    }

    fn tray_available(&self) -> bool {
        self.tray_available.load(Ordering::SeqCst)
    }

    fn system_theme(&self) -> Option<SystemTheme> {
        self.window.theme().map(|theme| match theme {
            WinitTheme::Light => SystemTheme::Light,
            WinitTheme::Dark => SystemTheme::Dark,
        })
    }

    fn high_contrast(&self) -> bool {
        crate::high_contrast::is_enabled()
    }

    fn clipboard(&self) -> ClipboardHandle {
        self.clipboard.clone()
    }

    fn native_menu(&self) -> Option<Rc<dyn NativeMenuController>> {
        self.native_menu.clone()
    }

    fn set_undecorated_shadow(&self, shadow: bool) {
        #[cfg(target_os = "windows")]
        {
            use winit::platform::windows::WindowExtWindows;
            self.window.set_undecorated_shadow(shadow);
        }
        #[cfg(not(target_os = "windows"))]
        let _ = shadow;
    }

    fn set_window_corners(&self, corners: WindowCorners) {
        #[cfg(target_os = "windows")]
        {
            use winit::platform::windows::{CornerPreference, WindowExtWindows};
            let preference = match corners {
                WindowCorners::Default => CornerPreference::Default,
                WindowCorners::Square => CornerPreference::DoNotRound,
                WindowCorners::Rounded => CornerPreference::Round,
            };
            self.window.set_corner_preference(preference);
        }
        #[cfg(not(target_os = "windows"))]
        let _ = corners;
    }

    fn window_state(&self) -> Option<WindowState> {
        let sf = (self.window.scale_factor() as f32).max(0.01);
        let inner = self.window.inner_size();
        let size = Size::new(inner.width as f32 / sf, inner.height as f32 / sf);
        let position = self.window.outer_position().ok().map(|p| (p.x as f32 / sf, p.y as f32 / sf));
        Some(WindowState { size, position, maximized: self.window.is_maximized() })
    }

    fn pick_file(&self, options: &FileDialogOptions) -> Option<PathBuf> {
        self.dialog(options).pick_file()
    }

    fn pick_files(&self, options: &FileDialogOptions) -> Option<Vec<PathBuf>> {
        self.dialog(options).pick_files()
    }

    fn pick_folder(&self, options: &FileDialogOptions) -> Option<PathBuf> {
        self.dialog(options).pick_folder()
    }

    fn save_file(&self, options: &FileDialogOptions) -> Option<PathBuf> {
        self.dialog(options).save_file()
    }

    fn start_file_drag(&self, paths: &[PathBuf], options: &FileDragOptions) -> Result<FileDragOutcome, String> {
        #[cfg(any(target_os = "windows", target_os = "macos"))]
        {
            if paths.is_empty() {
                return Err("拖出文件列表为空".to_string());
            }
            let preview = options.preview.clone().or_else(|| paths.first().cloned());
            let item = drag::DragItem::Files(paths.to_vec());
            let image = drag::Image::File(preview.unwrap_or_else(|| paths[0].clone()));
            let mode = if options.copy { drag::DragMode::Copy } else { drag::DragMode::Move };
            let result = std::sync::Arc::new(std::sync::Mutex::new(None));
            let callback_result = std::sync::Arc::clone(&result);
            drag::start_drag(
                self.window.as_ref(),
                item,
                image,
                move |outcome, _| {
                    if let Ok(mut slot) = callback_result.lock() {
                        *slot = Some(outcome);
                    }
                },
                drag::Options { mode, ..Default::default() },
            )
            .map_err(|e| format!("start_file_drag: {e}"))?;
            let outcome = result.lock().ok().and_then(|mut slot| slot.take());
            Ok(match outcome {
                Some(drag::DragResult::Dropped) => FileDragOutcome::Dropped,
                Some(drag::DragResult::Cancel) | None => FileDragOutcome::Cancelled,
            })
        }
        #[cfg(not(any(target_os = "windows", target_os = "macos")))]
        {
            let _ = (paths, options);
            Err("当前平台暂不支持从窗口拖出文件".to_string())
        }
    }

    fn show_notification(&self, notification: &Notification) -> Result<(), String> {
        crate::notification::show(notification, self.app_id.as_deref())
    }
}

fn map_resize_direction(direction: ResizeDirection) -> WinitResizeDirection {
    match direction {
        ResizeDirection::East => WinitResizeDirection::East,
        ResizeDirection::North => WinitResizeDirection::North,
        ResizeDirection::NorthEast => WinitResizeDirection::NorthEast,
        ResizeDirection::NorthWest => WinitResizeDirection::NorthWest,
        ResizeDirection::South => WinitResizeDirection::South,
        ResizeDirection::SouthEast => WinitResizeDirection::SouthEast,
        ResizeDirection::SouthWest => WinitResizeDirection::SouthWest,
        ResizeDirection::West => WinitResizeDirection::West,
    }
}

fn map_cursor(cursor: CursorIcon) -> WinitCursorIcon {
    match cursor {
        CursorIcon::Default => WinitCursorIcon::Default,
        CursorIcon::Pointer => WinitCursorIcon::Pointer,
        CursorIcon::Text => WinitCursorIcon::Text,
        CursorIcon::Crosshair => WinitCursorIcon::Crosshair,
        CursorIcon::Move => WinitCursorIcon::Move,
        CursorIcon::NotAllowed => WinitCursorIcon::NotAllowed,
        CursorIcon::Wait => WinitCursorIcon::Wait,
        CursorIcon::Progress => WinitCursorIcon::Progress,
        CursorIcon::Help => WinitCursorIcon::Help,
        CursorIcon::Grab => WinitCursorIcon::Grab,
        CursorIcon::Grabbing => WinitCursorIcon::Grabbing,
        CursorIcon::ZoomIn => WinitCursorIcon::ZoomIn,
        CursorIcon::ZoomOut => WinitCursorIcon::ZoomOut,
        CursorIcon::ResizeHorizontal => WinitCursorIcon::EwResize,
        CursorIcon::ResizeVertical => WinitCursorIcon::NsResize,
        CursorIcon::ResizeNwSe => WinitCursorIcon::NwseResize,
        CursorIcon::ResizeNeSw => WinitCursorIcon::NeswResize,
        CursorIcon::ResizeAll => WinitCursorIcon::AllScroll,
        CursorIcon::ColumnResize => WinitCursorIcon::ColResize,
        CursorIcon::RowResize => WinitCursorIcon::RowResize,
    }
}