Skip to main content

velox_engine/platform/
os_integration.rs

1//! 桌面操作系统深度集成原语(`os_integration`):
2//! 统一封装原生顶部菜单栏(`NativeMenuBar`)、系统托盘(`SystemTraySpec`)、
3//! 原生文件对话框协议(`FileDialogRequest`)与跨应用拖放幽灵预览(`DragPreviewGhost`)。
4
5use std::boxed::Box;
6use std::path::PathBuf;
7use std::string::String;
8use std::sync::{Mutex, OnceLock};
9use std::vec::Vec;
10
11use crate::solver::Region;
12
13/// 原生菜单项定义(对应 macOS NSMenu / Windows HMENU / Linux DBusMenu)。
14#[derive(Clone, PartialEq, Eq, Debug)]
15pub enum NativeMenuItem {
16    Action {
17        id: u32,
18        label: String,
19        accelerator: Option<String>,
20        enabled: bool,
21        checked: Option<bool>,
22    },
23    Separator,
24    Submenu {
25        label: String,
26        items: Vec<NativeMenuItem>,
27    },
28}
29
30impl NativeMenuItem {
31    pub fn action(id: u32, label: impl Into<String>, accelerator: Option<&str>) -> Self {
32        Self::Action {
33            id,
34            label: label.into(),
35            accelerator: accelerator.map(String::from),
36            enabled: true,
37            checked: None,
38        }
39    }
40
41    pub fn checkbox(id: u32, label: impl Into<String>, checked: bool) -> Self {
42        Self::Action {
43            id,
44            label: label.into(),
45            accelerator: None,
46            enabled: true,
47            checked: Some(checked),
48        }
49    }
50}
51
52/// 顶层原生菜单栏分组(如 `File` / `Edit` / `View` / `Window`)。
53#[derive(Clone, PartialEq, Eq, Debug)]
54pub struct NativeMenuSection {
55    pub title: String,
56    pub items: Vec<NativeMenuItem>,
57}
58
59/// 跨平台声明式原生菜单栏模型。
60#[derive(Clone, PartialEq, Eq, Debug, Default)]
61pub struct NativeMenuBar {
62    pub sections: Vec<NativeMenuSection>,
63}
64
65impl NativeMenuBar {
66    pub fn new() -> Self {
67        Self {
68            sections: Vec::new(),
69        }
70    }
71
72    pub fn add_section(mut self, title: impl Into<String>, items: Vec<NativeMenuItem>) -> Self {
73        self.sections.push(NativeMenuSection {
74            title: title.into(),
75            items,
76        });
77        self
78    }
79
80    /// 按动作 ID 检索菜单项名称(用于快捷键回显与自动化校验)。
81    pub fn find_action_label(&self, target_id: u32) -> Option<&str> {
82        fn search(items: &[NativeMenuItem], id: u32) -> Option<&str> {
83            for item in items {
84                match item {
85                    NativeMenuItem::Action {
86                        id: item_id, label, ..
87                    } if *item_id == id => return Some(label.as_str()),
88                    NativeMenuItem::Submenu { items: sub, .. } => {
89                        if let Some(found) = search(sub, id) {
90                            return Some(found);
91                        }
92                    }
93                    _ => {}
94                }
95            }
96            None
97        }
98        for sec in &self.sections {
99            if let Some(found) = search(&sec.items, target_id) {
100                return Some(found);
101            }
102        }
103        None
104    }
105}
106
107/// 系统托盘图标与菜单描述(Windows NotifyIcon / macOS NSStatusItem / Linux StatusNotifierItem)。
108#[derive(Clone, PartialEq, Eq, Debug)]
109pub struct SystemTraySpec {
110    pub id: String,
111    pub tooltip: String,
112    pub badge_count: u32,
113    pub menu: Vec<NativeMenuItem>,
114}
115
116impl SystemTraySpec {
117    pub fn new(id: impl Into<String>, tooltip: impl Into<String>) -> Self {
118        Self {
119            id: id.into(),
120            tooltip: tooltip.into(),
121            badge_count: 0,
122            menu: Vec::new(),
123        }
124    }
125
126    pub fn with_menu(mut self, items: Vec<NativeMenuItem>) -> Self {
127        self.menu = items;
128        self
129    }
130}
131
132/// 系统文件对话框模式。
133#[derive(Copy, Clone, PartialEq, Eq, Debug)]
134pub enum FileDialogMode {
135    OpenFile,
136    OpenMultiple,
137    SaveFile,
138    PickFolder,
139}
140
141/// 文件扩展名过滤器。
142#[derive(Clone, PartialEq, Eq, Debug)]
143pub struct FileFilter {
144    pub name: String,
145    pub extensions: Vec<String>,
146}
147
148/// 跨平台原生文件对话框请求。
149#[derive(Clone, PartialEq, Eq, Debug)]
150pub struct FileDialogRequest {
151    pub mode: FileDialogMode,
152    pub title: String,
153    pub default_name: Option<String>,
154    pub filters: Vec<FileFilter>,
155}
156
157impl FileDialogRequest {
158    pub fn open_file(title: impl Into<String>) -> Self {
159        Self {
160            mode: FileDialogMode::OpenFile,
161            title: title.into(),
162            default_name: None,
163            filters: Vec::new(),
164        }
165    }
166
167    pub fn save_file(title: impl Into<String>, default_name: impl Into<String>) -> Self {
168        Self {
169            mode: FileDialogMode::SaveFile,
170            title: title.into(),
171            default_name: Some(default_name.into()),
172            filters: Vec::new(),
173        }
174    }
175
176    pub fn add_filter(mut self, name: impl Into<String>, exts: &[&str]) -> Self {
177        self.filters.push(FileFilter {
178            name: name.into(),
179            extensions: exts.iter().map(|s| String::from(*s)).collect(),
180        });
181        self
182    }
183}
184
185/// 文件对话框执行结果。
186#[derive(Clone, PartialEq, Eq, Debug)]
187pub enum FileDialogResult {
188    Selected(Vec<PathBuf>),
189    Cancelled,
190}
191
192type MockDialogFn = Box<dyn Fn(&FileDialogRequest) -> FileDialogResult + Send + Sync>;
193
194static MOCK_FILE_DIALOG: OnceLock<Mutex<Option<MockDialogFn>>> = OnceLock::new();
195
196/// 注册确定性文件对话框拦截器(供无头 CI 自动化测试或自定义沙箱文件系统宿主使用)。
197pub fn set_mock_file_dialog_handler<F>(handler: Option<F>)
198where
199    F: Fn(&FileDialogRequest) -> FileDialogResult + Send + Sync + 'static,
200{
201    let lock = MOCK_FILE_DIALOG.get_or_init(|| Mutex::new(None));
202    if let Ok(mut g) = lock.lock() {
203        *g = handler.map(|f| Box::new(f) as MockDialogFn);
204    }
205}
206
207/// 触发文件对话框请求(优先命中已注册测试/宿主处理器;否则返回 `Cancelled` 避免无头阻塞)。
208pub fn run_file_dialog(req: &FileDialogRequest) -> FileDialogResult {
209    let lock = MOCK_FILE_DIALOG.get_or_init(|| Mutex::new(None));
210    if let Ok(g) = lock.lock() {
211        if let Some(ref f) = *g {
212            return f(req);
213        }
214    }
215    FileDialogResult::Cancelled
216}
217
218/// 跨应用拖拽跟随幽灵预览浮层(`DragPreviewGhost`)。
219#[derive(Clone, PartialEq, Eq, Debug)]
220pub struct DragPreviewGhost {
221    pub title: String,
222    pub subtitle: String,
223    pub badge_count: u32,
224    pub pointer_x: i16,
225    pub pointer_y: i16,
226    pub width: i16,
227    pub height: i16,
228}
229
230impl DragPreviewGhost {
231    pub fn new(title: impl Into<String>, subtitle: impl Into<String>, px: i16, py: i16) -> Self {
232        Self {
233            title: title.into(),
234            subtitle: subtitle.into(),
235            badge_count: 1,
236            pointer_x: px,
237            pointer_y: py,
238            width: 196,
239            height: 44,
240        }
241    }
242
243    /// 计算不越出主视口边界的跟随屏幕矩形。
244    #[inline]
245    pub fn clamped_bounds(&self, viewport: Region) -> Region {
246        let x = (self.pointer_x + 14).clamp(
247            viewport.x,
248            (viewport.right() - self.width).max(viewport.x),
249        );
250        let y = (self.pointer_y + 14).clamp(
251            viewport.y,
252            (viewport.bottom() - self.height).max(viewport.y),
253        );
254        Region::new(x, y, self.width, self.height)
255    }
256}