Skip to main content

mgui_shell_winit/
window.rs

1use std::path::PathBuf;
2use std::rc::Rc;
3use std::sync::atomic::{AtomicBool, Ordering};
4use std::sync::Arc;
5
6use mgui_core::{Rect, Size};
7use mgui_shell::{
8    ClipboardHandle, CursorIcon, FileDialogOptions, FileDragOptions, FileDragOutcome, NativeMenuController,
9    Notification, ResizeDirection, ShellMetrics, SystemTheme, WindowCommand, WindowCommandBus, WindowCorners,
10    WindowShell, WindowState,
11};
12use winit::dpi::{LogicalPosition, LogicalSize};
13use winit::window::{
14    CursorIcon as WinitCursorIcon, Fullscreen, ResizeDirection as WinitResizeDirection, Theme as WinitTheme, Window,
15    WindowLevel as WinitWindowLevel,
16};
17
18/// 桌面窗口句柄(可克隆)。
19#[derive(Clone)]
20pub struct DesktopWindow {
21    window: Arc<Window>,
22    /// `ctx.shell.request_close()` 置位;host 在事件/帧循环里消费
23    close_requested: Arc<AtomicBool>,
24    /// 宿主创建托盘成功后置位;`WindowShell::tray_available()` 读它。
25    tray_available: Arc<AtomicBool>,
26    /// 桌面应用 id(Windows 通知 AUMID 兜底)。
27    app_id: Option<String>,
28    /// 系统剪贴板(文本/HTML/图片/文件列表)。
29    clipboard: ClipboardHandle,
30    /// 已安装原生菜单的运行期控制器(由 desktop host 注入)。
31    native_menu: Option<Rc<dyn NativeMenuController>>,
32    /// 多窗口宿主的跨窗命令总线;单窗口宿主为 None。
33    window_commands: Option<WindowCommandBus>,
34    /// 本窗口在 `MultiWindowConfig` 里的名字。
35    window_name: Option<String>,
36}
37
38impl DesktopWindow {
39    pub fn new(window: Arc<Window>) -> Self {
40        Self {
41            window,
42            close_requested: Arc::new(AtomicBool::new(false)),
43            tray_available: Arc::new(AtomicBool::new(false)),
44            app_id: None,
45            clipboard: ClipboardHandle::new(Box::new(crate::clipboard::DesktopClipboard::new())),
46            native_menu: None,
47            window_commands: None,
48            window_name: None,
49        }
50    }
51
52    /// 注入多窗口宿主的跨窗命令总线与本窗口名字;由 `run_multi_app` 在创建槽位时调用。
53    pub fn with_window_identity(mut self, name: impl Into<String>, bus: WindowCommandBus) -> Self {
54        self.window_name = Some(name.into());
55        self.window_commands = Some(bus);
56        self
57    }
58
59    /// 注入原生菜单控制器;由 desktop host 在菜单创建后调用。
60    pub fn set_native_menu_controller(&mut self, controller: Option<Rc<dyn NativeMenuController>>) {
61        self.native_menu = controller;
62    }
63
64    /// 设置应用 id;Windows 系统通知会把它作为 AUMID 兜底。
65    pub fn with_app_id(mut self, app_id: impl Into<String>) -> Self {
66        self.app_id = Some(app_id.into());
67        self
68    }
69
70    /// 底层 winit 窗口——仅供 desktop host 的 GPU/AccessKit/事件循环使用。
71    pub fn as_winit(&self) -> &Arc<Window> {
72        &self.window
73    }
74
75    /// host 消费一次关闭请求。
76    pub fn take_close_request(&self) -> bool {
77        self.close_requested.swap(false, Ordering::SeqCst)
78    }
79
80    /// 宿主创建/移除托盘图标后写这个开关(窗口存活期间可变,故用 `Arc<AtomicBool>`)。
81    pub fn set_tray_available(&self, available: bool) {
82        self.tray_available.store(available, Ordering::SeqCst);
83    }
84
85    fn dialog(&self, options: &FileDialogOptions) -> rfd::FileDialog {
86        let mut dialog = rfd::FileDialog::new().set_parent(self.window.as_ref());
87        if !options.title.is_empty() {
88            dialog = dialog.set_title(&options.title);
89        }
90        if let Some(directory) = &options.directory {
91            dialog = dialog.set_directory(directory);
92        }
93        if let Some(file_name) = &options.file_name {
94            dialog = dialog.set_file_name(file_name);
95        }
96        for filter in &options.filters {
97            if filter.extensions.is_empty() {
98                continue;
99            }
100            let extensions: Vec<&str> = filter.extensions.iter().map(String::as_str).collect();
101            dialog = dialog.add_filter(&filter.name, &extensions);
102        }
103        dialog
104    }
105}
106
107impl WindowShell for DesktopWindow {
108    fn metrics(&self) -> ShellMetrics {
109        let sf = (self.window.scale_factor() as f32).max(0.01);
110        let phys = self.window.inner_size();
111        ShellMetrics::from_physical(phys.width, phys.height, sf)
112    }
113
114    fn request_redraw(&self) {
115        self.window.request_redraw();
116    }
117
118    fn window_name(&self) -> Option<String> {
119        self.window_name.clone()
120    }
121
122    fn send_window_command(&self, window: &str, command: WindowCommand) -> Result<(), String> {
123        match &self.window_commands {
124            Some(bus) => {
125                bus.send(window, command);
126                // 本窗口的下一轮循环里消费;自己也顺带请求一次重绘,
127                // 避免"应用只发命令、当前帧之后没有事件"时命令滞留队列。
128                self.window.request_redraw();
129                Ok(())
130            }
131            None => Err("单窗口宿主没有跨窗口命令总线".to_string()),
132        }
133    }
134
135    fn set_title(&self, title: &str) {
136        self.window.set_title(title);
137    }
138
139    fn set_visible(&self, visible: bool) {
140        self.window.set_visible(visible);
141    }
142
143    fn is_visible(&self) -> bool {
144        self.window.is_visible().unwrap_or(true)
145    }
146
147    fn set_ime_allowed(&self, allowed: bool) {
148        self.window.set_ime_allowed(allowed);
149    }
150
151    fn set_ime_cursor_area(&self, rect: Rect) {
152        self.window.set_ime_cursor_area(
153            LogicalPosition::new(rect.x as f64, rect.y as f64),
154            LogicalSize::new(rect.width.max(0.0) as f64, rect.height.max(0.0) as f64),
155        );
156    }
157
158    fn set_cursor(&self, cursor: CursorIcon) {
159        self.window.set_cursor(map_cursor(cursor));
160    }
161
162    fn set_fullscreen(&self, fullscreen: bool) {
163        self.window.set_fullscreen(fullscreen.then_some(Fullscreen::Borderless(None)));
164    }
165
166    fn is_fullscreen(&self) -> bool {
167        self.window.fullscreen().is_some()
168    }
169
170    fn set_minimized(&self, minimized: bool) {
171        self.window.set_minimized(minimized);
172    }
173
174    fn set_maximized(&self, maximized: bool) {
175        self.window.set_maximized(maximized);
176    }
177
178    fn is_maximized(&self) -> bool {
179        self.window.is_maximized()
180    }
181
182    fn focus_window(&self) {
183        self.window.focus_window();
184    }
185
186    fn set_decorations(&self, decorations: bool) {
187        self.window.set_decorations(decorations);
188    }
189
190    fn start_dragging(&self) -> Result<(), String> {
191        self.window.drag_window().map_err(|e| format!("start_dragging: {e}"))
192    }
193
194    fn start_resize(&self, direction: ResizeDirection) -> Result<(), String> {
195        self.window.drag_resize_window(map_resize_direction(direction)).map_err(|e| format!("start_resize: {e}"))
196    }
197
198    fn set_resizable(&self, resizable: bool) {
199        self.window.set_resizable(resizable);
200    }
201
202    fn set_always_on_top(&self, on_top: bool) {
203        self.window.set_window_level(if on_top { WinitWindowLevel::AlwaysOnTop } else { WinitWindowLevel::Normal });
204    }
205
206    fn set_size(&self, size: Size) {
207        let _ = self.window.request_inner_size(LogicalSize::new(size.width as f64, size.height as f64));
208    }
209
210    fn set_position(&self, x: f32, y: f32) {
211        self.window.set_outer_position(LogicalPosition::new(x as f64, y as f64));
212    }
213
214    fn request_close(&self) {
215        self.close_requested.store(true, Ordering::SeqCst);
216        self.window.request_redraw();
217    }
218
219    fn tray_available(&self) -> bool {
220        self.tray_available.load(Ordering::SeqCst)
221    }
222
223    fn system_theme(&self) -> Option<SystemTheme> {
224        self.window.theme().map(|theme| match theme {
225            WinitTheme::Light => SystemTheme::Light,
226            WinitTheme::Dark => SystemTheme::Dark,
227        })
228    }
229
230    fn high_contrast(&self) -> bool {
231        crate::high_contrast::is_enabled()
232    }
233
234    fn clipboard(&self) -> ClipboardHandle {
235        self.clipboard.clone()
236    }
237
238    fn native_menu(&self) -> Option<Rc<dyn NativeMenuController>> {
239        self.native_menu.clone()
240    }
241
242    fn set_undecorated_shadow(&self, shadow: bool) {
243        #[cfg(target_os = "windows")]
244        {
245            use winit::platform::windows::WindowExtWindows;
246            self.window.set_undecorated_shadow(shadow);
247        }
248        #[cfg(not(target_os = "windows"))]
249        let _ = shadow;
250    }
251
252    fn set_window_corners(&self, corners: WindowCorners) {
253        #[cfg(target_os = "windows")]
254        {
255            use winit::platform::windows::{CornerPreference, WindowExtWindows};
256            let preference = match corners {
257                WindowCorners::Default => CornerPreference::Default,
258                WindowCorners::Square => CornerPreference::DoNotRound,
259                WindowCorners::Rounded => CornerPreference::Round,
260            };
261            self.window.set_corner_preference(preference);
262        }
263        #[cfg(not(target_os = "windows"))]
264        let _ = corners;
265    }
266
267    fn window_state(&self) -> Option<WindowState> {
268        let sf = (self.window.scale_factor() as f32).max(0.01);
269        let inner = self.window.inner_size();
270        let size = Size::new(inner.width as f32 / sf, inner.height as f32 / sf);
271        let position = self.window.outer_position().ok().map(|p| (p.x as f32 / sf, p.y as f32 / sf));
272        Some(WindowState { size, position, maximized: self.window.is_maximized() })
273    }
274
275    fn pick_file(&self, options: &FileDialogOptions) -> Option<PathBuf> {
276        self.dialog(options).pick_file()
277    }
278
279    fn pick_files(&self, options: &FileDialogOptions) -> Option<Vec<PathBuf>> {
280        self.dialog(options).pick_files()
281    }
282
283    fn pick_folder(&self, options: &FileDialogOptions) -> Option<PathBuf> {
284        self.dialog(options).pick_folder()
285    }
286
287    fn save_file(&self, options: &FileDialogOptions) -> Option<PathBuf> {
288        self.dialog(options).save_file()
289    }
290
291    fn start_file_drag(&self, paths: &[PathBuf], options: &FileDragOptions) -> Result<FileDragOutcome, String> {
292        #[cfg(any(target_os = "windows", target_os = "macos"))]
293        {
294            if paths.is_empty() {
295                return Err("拖出文件列表为空".to_string());
296            }
297            let preview = options.preview.clone().or_else(|| paths.first().cloned());
298            let item = drag::DragItem::Files(paths.to_vec());
299            let image = drag::Image::File(preview.unwrap_or_else(|| paths[0].clone()));
300            let mode = if options.copy { drag::DragMode::Copy } else { drag::DragMode::Move };
301            let result = std::sync::Arc::new(std::sync::Mutex::new(None));
302            let callback_result = std::sync::Arc::clone(&result);
303            drag::start_drag(
304                self.window.as_ref(),
305                item,
306                image,
307                move |outcome, _| {
308                    if let Ok(mut slot) = callback_result.lock() {
309                        *slot = Some(outcome);
310                    }
311                },
312                drag::Options { mode, ..Default::default() },
313            )
314            .map_err(|e| format!("start_file_drag: {e}"))?;
315            let outcome = result.lock().ok().and_then(|mut slot| slot.take());
316            Ok(match outcome {
317                Some(drag::DragResult::Dropped) => FileDragOutcome::Dropped,
318                Some(drag::DragResult::Cancel) | None => FileDragOutcome::Cancelled,
319            })
320        }
321        #[cfg(not(any(target_os = "windows", target_os = "macos")))]
322        {
323            let _ = (paths, options);
324            Err("当前平台暂不支持从窗口拖出文件".to_string())
325        }
326    }
327
328    fn show_notification(&self, notification: &Notification) -> Result<(), String> {
329        crate::notification::show(notification, self.app_id.as_deref())
330    }
331}
332
333fn map_resize_direction(direction: ResizeDirection) -> WinitResizeDirection {
334    match direction {
335        ResizeDirection::East => WinitResizeDirection::East,
336        ResizeDirection::North => WinitResizeDirection::North,
337        ResizeDirection::NorthEast => WinitResizeDirection::NorthEast,
338        ResizeDirection::NorthWest => WinitResizeDirection::NorthWest,
339        ResizeDirection::South => WinitResizeDirection::South,
340        ResizeDirection::SouthEast => WinitResizeDirection::SouthEast,
341        ResizeDirection::SouthWest => WinitResizeDirection::SouthWest,
342        ResizeDirection::West => WinitResizeDirection::West,
343    }
344}
345
346fn map_cursor(cursor: CursorIcon) -> WinitCursorIcon {
347    match cursor {
348        CursorIcon::Default => WinitCursorIcon::Default,
349        CursorIcon::Pointer => WinitCursorIcon::Pointer,
350        CursorIcon::Text => WinitCursorIcon::Text,
351        CursorIcon::Crosshair => WinitCursorIcon::Crosshair,
352        CursorIcon::Move => WinitCursorIcon::Move,
353        CursorIcon::NotAllowed => WinitCursorIcon::NotAllowed,
354        CursorIcon::Wait => WinitCursorIcon::Wait,
355        CursorIcon::Progress => WinitCursorIcon::Progress,
356        CursorIcon::Help => WinitCursorIcon::Help,
357        CursorIcon::Grab => WinitCursorIcon::Grab,
358        CursorIcon::Grabbing => WinitCursorIcon::Grabbing,
359        CursorIcon::ZoomIn => WinitCursorIcon::ZoomIn,
360        CursorIcon::ZoomOut => WinitCursorIcon::ZoomOut,
361        CursorIcon::ResizeHorizontal => WinitCursorIcon::EwResize,
362        CursorIcon::ResizeVertical => WinitCursorIcon::NsResize,
363        CursorIcon::ResizeNwSe => WinitCursorIcon::NwseResize,
364        CursorIcon::ResizeNeSw => WinitCursorIcon::NeswResize,
365        CursorIcon::ResizeAll => WinitCursorIcon::AllScroll,
366        CursorIcon::ColumnResize => WinitCursorIcon::ColResize,
367        CursorIcon::RowResize => WinitCursorIcon::RowResize,
368    }
369}