1#![forbid(unsafe_code)]
12
13use std::cell::Cell;
14use std::path::{Path, PathBuf};
15use std::rc::Rc;
16use std::time::Instant;
17
18use mgui_core::{KeyCode, KeyModifiers, MouseButton, Point, Rect, Size};
19
20pub use mgui_core::{ClipboardHandle, ClipboardImage, ClipboardProvider, NoopClipboard};
21
22pub mod dispatch;
23pub use dispatch::dispatch_shell_event;
24pub mod icon;
25pub use icon::{IconImage, WindowIcon};
26pub mod window_command;
27pub use window_command::{route_window_commands, WindowCommand, WindowCommandBus};
28
29#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
31pub struct ShellWindowId(pub u64);
32
33#[derive(Clone, Copy, Debug, PartialEq)]
35pub struct ShellMetrics {
36 pub logical_size: Size,
37 pub scale_factor: f32,
39}
40
41impl ShellMetrics {
42 pub fn new(logical_size: Size, scale_factor: f32) -> Self {
43 Self {
44 logical_size: Size::new(logical_size.width.max(1.0), logical_size.height.max(1.0)),
45 scale_factor: scale_factor.max(0.01),
46 }
47 }
48
49 pub fn from_physical(physical_width: u32, physical_height: u32, scale_factor: f32) -> Self {
51 let scale_factor = scale_factor.max(0.01);
52 Self::new(Size::new(physical_width as f32 / scale_factor, physical_height as f32 / scale_factor), scale_factor)
53 }
54}
55
56impl Default for ShellMetrics {
57 fn default() -> Self {
58 Self::new(Size::new(800.0, 600.0), 1.0)
59 }
60}
61
62#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
64pub enum CursorIcon {
65 #[default]
66 Default,
67 Pointer,
68 Text,
69 Crosshair,
70 Move,
71 NotAllowed,
72 Wait,
73 Progress,
74 Help,
75 Grab,
76 Grabbing,
77 ZoomIn,
78 ZoomOut,
79 ResizeHorizontal,
80 ResizeVertical,
81 ResizeNwSe,
82 ResizeNeSw,
83 ResizeAll,
84 ColumnResize,
85 RowResize,
86}
87
88#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub enum ResizeDirection {
91 East,
92 North,
93 NorthEast,
94 NorthWest,
95 South,
96 SouthEast,
97 SouthWest,
98 West,
99}
100
101impl ResizeDirection {
102 pub fn hit_test(position: Point, size: Size, margin: f32) -> Option<Self> {
106 if !(margin.is_finite() && margin > 0.0)
107 || !(size.width.is_finite() && size.height.is_finite() && size.width > 0.0 && size.height > 0.0)
108 || !(position.x.is_finite() && position.y.is_finite())
109 {
110 return None;
111 }
112 if position.x < 0.0 || position.y < 0.0 || position.x >= size.width || position.y >= size.height {
113 return None;
114 }
115 let mx = margin.min(size.width / 2.0);
116 let my = margin.min(size.height / 2.0);
117 let left = position.x < mx;
118 let right = position.x > size.width - mx;
119 let top = position.y < my;
120 let bottom = position.y > size.height - my;
121 match (top, bottom, left, right) {
122 (true, _, true, _) => Some(Self::NorthWest),
123 (true, _, _, true) => Some(Self::NorthEast),
124 (_, true, true, _) => Some(Self::SouthWest),
125 (_, true, _, true) => Some(Self::SouthEast),
126 (true, _, _, _) => Some(Self::North),
127 (_, true, _, _) => Some(Self::South),
128 (_, _, true, _) => Some(Self::West),
129 (_, _, _, true) => Some(Self::East),
130 _ => None,
131 }
132 }
133}
134
135#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
137pub enum WindowCorners {
138 #[default]
140 Default,
141 Square,
143 Rounded,
145}
146
147#[derive(Clone, Copy, Debug, PartialEq)]
149pub struct WindowState {
150 pub size: Size,
151 pub position: Option<(f32, f32)>,
153 pub maximized: bool,
154}
155
156impl WindowState {
157 pub fn new(size: Size) -> Self {
158 Self { size: Size::new(size.width.max(1.0), size.height.max(1.0)), position: None, maximized: false }
159 }
160
161 pub fn encode(&self) -> String {
162 let mut out = String::from("mgui-window-state=1\n");
163 out.push_str(&format!("width={}\nheight={}\n", self.size.width, self.size.height));
164 if let Some((x, y)) = self.position {
165 out.push_str(&format!("x={x}\ny={y}\n"));
166 }
167 out.push_str(&format!("maximized={}\n", self.maximized));
168 out
169 }
170
171 pub fn parse(text: &str) -> Option<Self> {
172 let mut version = None;
173 let mut width = None;
174 let mut height = None;
175 let mut x = None;
176 let mut y = None;
177 let mut maximized = false;
178 for line in text.lines() {
179 let Some((key, value)) = line.split_once('=') else { continue };
180 let key = key.trim();
181 let value = value.trim();
182 match key {
183 "mgui-window-state" => version = value.parse::<u32>().ok(),
184 "width" => width = value.parse::<f32>().ok(),
185 "height" => height = value.parse::<f32>().ok(),
186 "x" => x = value.parse::<f32>().ok(),
187 "y" => y = value.parse::<f32>().ok(),
188 "maximized" => maximized = matches!(value, "1" | "true"),
189 _ => {}
190 }
191 }
192 if version != Some(1) {
193 return None;
194 }
195 let width = width.filter(|v| v.is_finite() && *v >= 1.0)?;
196 let height = height.filter(|v| v.is_finite() && *v >= 1.0)?;
197 let position = match (x, y) {
198 (Some(x), Some(y)) if x.is_finite() && y.is_finite() => Some((x, y)),
199 _ => None,
200 };
201 Some(Self { size: Size::new(width, height), position, maximized })
202 }
203
204 pub fn load(path: impl AsRef<Path>) -> Option<Self> {
205 let text = std::fs::read_to_string(path).ok()?;
206 Self::parse(&text)
207 }
208
209 pub fn save(&self, path: impl AsRef<Path>) -> Result<(), String> {
210 let path = path.as_ref();
211 if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
212 std::fs::create_dir_all(parent).map_err(|e| format!("create {}: {e}", parent.display()))?;
213 }
214 std::fs::write(path, self.encode()).map_err(|e| format!("write {}: {e}", path.display()))
215 }
216}
217
218#[derive(Clone, Copy, Debug, PartialEq, Eq)]
220pub enum SystemTheme {
221 Light,
222 Dark,
223}
224
225#[derive(Clone, Debug, PartialEq, Eq)]
227pub struct FileDialogFilter {
228 pub name: String,
229 pub extensions: Vec<String>,
230}
231
232impl FileDialogFilter {
233 pub fn new<I, S>(name: impl Into<String>, extensions: I) -> Self
234 where
235 I: IntoIterator<Item = S>,
236 S: Into<String>,
237 {
238 Self { name: name.into(), extensions: extensions.into_iter().map(Into::into).collect() }
239 }
240}
241
242#[derive(Clone, Debug, Default, PartialEq, Eq)]
244pub struct FileDialogOptions {
245 pub title: String,
246 pub directory: Option<PathBuf>,
247 pub file_name: Option<String>,
248 pub filters: Vec<FileDialogFilter>,
249}
250
251impl FileDialogOptions {
252 pub fn new(title: impl Into<String>) -> Self {
253 Self { title: title.into(), ..Self::default() }
254 }
255
256 pub fn with_directory(mut self, directory: impl Into<PathBuf>) -> Self {
257 self.directory = Some(directory.into());
258 self
259 }
260
261 pub fn with_file_name(mut self, name: impl Into<String>) -> Self {
262 self.file_name = Some(name.into());
263 self
264 }
265
266 pub fn with_filter<I, S>(mut self, name: impl Into<String>, extensions: I) -> Self
267 where
268 I: IntoIterator<Item = S>,
269 S: Into<String>,
270 {
271 self.filters.push(FileDialogFilter::new(name, extensions));
272 self
273 }
274}
275
276#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
278pub enum NotificationLevel {
279 Low,
280 #[default]
281 Normal,
282 Critical,
283}
284
285#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
287pub enum NotificationTimeout {
288 #[default]
290 Default,
291 Never,
293 Milliseconds(u32),
295}
296
297#[derive(Clone, Debug, PartialEq, Eq)]
302pub struct Notification {
303 pub title: String,
304 pub body: String,
305 pub app_name: Option<String>,
306 pub app_id: Option<String>,
307 pub level: NotificationLevel,
308 pub silent: bool,
309 pub timeout: NotificationTimeout,
310 pub icon: Option<String>,
312}
313
314impl Notification {
315 pub fn new(title: impl Into<String>) -> Self {
316 Self {
317 title: title.into(),
318 body: String::new(),
319 app_name: None,
320 app_id: None,
321 level: NotificationLevel::Normal,
322 silent: false,
323 timeout: NotificationTimeout::Default,
324 icon: None,
325 }
326 }
327
328 pub fn with_body(mut self, body: impl Into<String>) -> Self {
329 self.body = body.into();
330 self
331 }
332
333 pub fn with_app_name(mut self, name: impl Into<String>) -> Self {
334 self.app_name = Some(name.into());
335 self
336 }
337
338 pub fn with_app_id(mut self, id: impl Into<String>) -> Self {
339 self.app_id = Some(id.into());
340 self
341 }
342
343 pub fn with_level(mut self, level: NotificationLevel) -> Self {
344 self.level = level;
345 self
346 }
347
348 pub fn with_silent(mut self, silent: bool) -> Self {
349 self.silent = silent;
350 self
351 }
352
353 pub fn with_timeout(mut self, timeout: NotificationTimeout) -> Self {
354 self.timeout = timeout;
355 self
356 }
357
358 pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
359 self.icon = Some(icon.into());
360 self
361 }
362}
363
364#[derive(Clone, Debug, PartialEq, Eq)]
369pub enum TrayMenuItem {
370 Item { id: u64, label: String, enabled: bool },
371 Separator,
372 Submenu { label: String, items: Vec<TrayMenuItem> },
373}
374
375impl TrayMenuItem {
376 pub fn item(id: u64, label: impl Into<String>) -> Self {
377 Self::Item { id, label: label.into(), enabled: true }
378 }
379
380 pub fn item_enabled(id: u64, label: impl Into<String>, enabled: bool) -> Self {
381 Self::Item { id, label: label.into(), enabled }
382 }
383
384 pub fn separator() -> Self {
385 Self::Separator
386 }
387
388 pub fn submenu(label: impl Into<String>, items: Vec<TrayMenuItem>) -> Self {
389 Self::Submenu { label: label.into(), items }
390 }
391}
392
393#[derive(Clone, Debug, Default, PartialEq, Eq)]
399pub struct TrayConfig {
400 pub tooltip: String,
401 pub icon: Option<IconImage>,
402 pub menu: Vec<TrayMenuItem>,
403 pub open_menu_on_left_click: bool,
404}
405
406impl TrayConfig {
407 pub fn new(tooltip: impl Into<String>) -> Self {
408 Self { tooltip: tooltip.into(), ..Self::default() }
409 }
410
411 pub fn with_icon(mut self, icon: IconImage) -> Self {
412 self.icon = Some(icon);
413 self
414 }
415
416 pub fn with_menu(mut self, items: Vec<TrayMenuItem>) -> Self {
417 self.menu = items;
418 self
419 }
420
421 pub fn with_menu_item(mut self, item: TrayMenuItem) -> Self {
422 self.menu.push(item);
423 self
424 }
425
426 pub fn with_open_menu_on_left_click(mut self, open: bool) -> Self {
427 self.open_menu_on_left_click = open;
428 self
429 }
430}
431
432#[derive(Clone, Copy, Debug, PartialEq, Eq)]
434pub enum TrayEvent {
435 Click { button: MouseButton },
437 Menu { id: u64 },
439}
440
441#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
445pub enum ShortcutKey {
446 Char(char),
447 Enter,
448 Escape,
449 Tab,
450 Space,
451 Backspace,
452 Delete,
453 Insert,
454 Left,
455 Right,
456 Up,
457 Down,
458 Home,
459 End,
460 PageUp,
461 PageDown,
462 F(u8),
464}
465
466#[derive(Clone, Copy, Debug, PartialEq, Eq)]
468pub struct Shortcut {
469 pub modifiers: KeyModifiers,
470 pub key: ShortcutKey,
471}
472
473impl Shortcut {
474 pub const fn new(modifiers: KeyModifiers, key: ShortcutKey) -> Self {
475 Self { modifiers, key }
476 }
477
478 pub fn command(key: ShortcutKey) -> Self {
480 Self::new(KeyModifiers::command_only(), key)
481 }
482
483 pub fn ctrl(key: ShortcutKey) -> Self {
484 Self::new(KeyModifiers::ctrl_only(), key)
485 }
486
487 pub fn shift(key: ShortcutKey) -> Self {
488 Self::new(KeyModifiers::shift_only(), key)
489 }
490
491 pub fn ctrl_shift(key: ShortcutKey) -> Self {
492 Self::new(KeyModifiers(KeyModifiers::CTRL | KeyModifiers::SHIFT), key)
493 }
494
495 pub fn ctrl_alt(key: ShortcutKey) -> Self {
496 Self::new(KeyModifiers(KeyModifiers::CTRL | KeyModifiers::ALT), key)
497 }
498
499 pub fn alt(key: ShortcutKey) -> Self {
500 Self::new(KeyModifiers(KeyModifiers::ALT), key)
501 }
502}
503
504#[derive(Clone, Debug, PartialEq, Eq)]
510pub struct SingleInstanceConfig {
511 pub id: String,
512 pub forward_args: bool,
514}
515
516impl SingleInstanceConfig {
517 pub fn new(id: impl Into<String>) -> Self {
518 Self { id: id.into(), forward_args: true }
519 }
520
521 pub fn with_forward_args(mut self, forward: bool) -> Self {
522 self.forward_args = forward;
523 self
524 }
525}
526
527#[derive(Clone, Debug, PartialEq, Eq)]
531pub struct GlobalShortcut {
532 pub id: u64,
533 pub shortcut: Shortcut,
534}
535
536impl GlobalShortcut {
537 pub fn new(id: u64, shortcut: Shortcut) -> Self {
538 Self { id, shortcut }
539 }
540}
541
542#[derive(Clone, Debug, PartialEq, Eq)]
544pub struct NativeMenuCommand {
545 pub id: u64,
546 pub label: String,
547 pub shortcut: Option<Shortcut>,
548 pub enabled: bool,
549 pub checked: Option<bool>,
551}
552
553impl NativeMenuCommand {
554 pub fn new(id: u64, label: impl Into<String>) -> Self {
555 Self { id, label: label.into(), shortcut: None, enabled: true, checked: None }
556 }
557
558 pub fn with_shortcut(mut self, shortcut: Shortcut) -> Self {
559 self.shortcut = Some(shortcut);
560 self
561 }
562
563 pub fn with_enabled(mut self, enabled: bool) -> Self {
564 self.enabled = enabled;
565 self
566 }
567
568 pub fn with_checked(mut self, checked: bool) -> Self {
569 self.checked = Some(checked);
570 self
571 }
572}
573
574#[derive(Clone, Debug, PartialEq, Eq)]
576pub enum NativeMenuItem {
577 Command(NativeMenuCommand),
578 Separator,
579 Submenu(NativeMenu),
580}
581
582impl NativeMenuItem {
583 pub fn separator() -> Self {
584 Self::Separator
585 }
586}
587
588impl From<NativeMenuCommand> for NativeMenuItem {
589 fn from(command: NativeMenuCommand) -> Self {
590 Self::Command(command)
591 }
592}
593
594impl From<NativeMenu> for NativeMenuItem {
595 fn from(menu: NativeMenu) -> Self {
596 Self::Submenu(menu)
597 }
598}
599
600#[derive(Clone, Debug, PartialEq, Eq)]
602pub struct NativeMenu {
603 pub title: String,
604 pub items: Vec<NativeMenuItem>,
605}
606
607impl NativeMenu {
608 pub fn new(title: impl Into<String>) -> Self {
609 Self { title: title.into(), items: Vec::new() }
610 }
611
612 pub fn with_item(mut self, item: impl Into<NativeMenuItem>) -> Self {
613 self.items.push(item.into());
614 self
615 }
616
617 pub fn with_separator(mut self) -> Self {
618 self.items.push(NativeMenuItem::Separator);
619 self
620 }
621}
622
623#[derive(Clone, Debug, Default, PartialEq, Eq)]
628pub struct NativeMenuBar {
629 pub menus: Vec<NativeMenu>,
630}
631
632impl NativeMenuBar {
633 pub fn new() -> Self {
634 Self::default()
635 }
636
637 pub fn with_menu(mut self, menu: NativeMenu) -> Self {
638 self.menus.push(menu);
639 self
640 }
641
642 pub fn command_ids(&self) -> Vec<u64> {
644 fn collect(menu: &NativeMenu, out: &mut Vec<u64>) {
645 for item in &menu.items {
646 match item {
647 NativeMenuItem::Command(command) => out.push(command.id),
648 NativeMenuItem::Submenu(submenu) => collect(submenu, out),
649 NativeMenuItem::Separator => {}
650 }
651 }
652 }
653 let mut out = Vec::new();
654 for menu in &self.menus {
655 collect(menu, &mut out);
656 }
657 out
658 }
659
660 pub fn accelerators(&self) -> Vec<(u64, Shortcut)> {
662 fn collect(menu: &NativeMenu, out: &mut Vec<(u64, Shortcut)>) {
663 for item in &menu.items {
664 match item {
665 NativeMenuItem::Command(command) => {
666 if let Some(shortcut) = command.shortcut {
667 out.push((command.id, shortcut));
668 }
669 }
670 NativeMenuItem::Submenu(submenu) => collect(submenu, out),
671 NativeMenuItem::Separator => {}
672 }
673 }
674 }
675 let mut out = Vec::new();
676 for menu in &self.menus {
677 collect(menu, &mut out);
678 }
679 out
680 }
681}
682
683#[derive(Clone, Copy, Debug, PartialEq, Eq)]
685pub enum FileDragOutcome {
686 Dropped,
687 Cancelled,
688}
689
690#[derive(Clone, Debug, PartialEq, Eq)]
692pub struct FileDragOptions {
693 pub preview: Option<PathBuf>,
695 pub copy: bool,
697}
698
699impl Default for FileDragOptions {
700 fn default() -> Self {
701 Self { preview: None, copy: true }
702 }
703}
704
705impl FileDragOptions {
706 pub fn new() -> Self {
707 Self::default()
708 }
709
710 pub fn with_preview(mut self, path: impl Into<PathBuf>) -> Self {
711 self.preview = Some(path.into());
712 self
713 }
714
715 pub fn with_copy(mut self, copy: bool) -> Self {
716 self.copy = copy;
717 self
718 }
719}
720
721pub trait NativeMenuController {
725 fn set_item_enabled(&self, id: u64, enabled: bool);
726 fn set_item_checked(&self, id: u64, checked: bool);
727 fn set_visible(&self, visible: bool);
730}
731
732pub trait WindowShell {
737 fn metrics(&self) -> ShellMetrics;
738 fn request_redraw(&self);
739 fn set_title(&self, title: &str);
740 fn set_visible(&self, visible: bool);
741 fn is_visible(&self) -> bool {
743 true
744 }
745 fn set_ime_allowed(&self, allowed: bool);
746 fn set_ime_cursor_area(&self, rect: Rect);
747
748 fn set_cursor(&self, _cursor: CursorIcon) {}
750 fn set_fullscreen(&self, _fullscreen: bool) {}
752 fn is_fullscreen(&self) -> bool {
753 false
754 }
755 fn set_minimized(&self, _minimized: bool) {}
757 fn set_maximized(&self, _maximized: bool) {}
759 fn is_maximized(&self) -> bool {
760 false
761 }
762 fn focus_window(&self) {}
764 fn set_decorations(&self, _decorations: bool) {}
766 fn toggle_maximized(&self) {
769 self.set_maximized(!self.is_maximized());
770 }
771 fn start_dragging(&self) -> Result<(), String> {
774 Err("当前 shell 不支持窗口拖拽".to_string())
775 }
776 fn start_resize(&self, _direction: ResizeDirection) -> Result<(), String> {
780 Err("当前 shell 不支持窗口边缘缩放".to_string())
781 }
782 fn set_resizable(&self, _resizable: bool) {}
784 fn set_always_on_top(&self, _on_top: bool) {}
786 fn set_size(&self, _size: Size) {}
788 fn set_position(&self, _x: f32, _y: f32) {}
790
791 fn request_close(&self) {}
794
795 fn tray_available(&self) -> bool {
802 false
803 }
804
805 fn window_name(&self) -> Option<String> {
808 None
809 }
810
811 fn send_window_command(&self, _window: &str, _command: WindowCommand) -> Result<(), String> {
817 Err("当前 shell 不支持跨窗口命令(只有 run_multi_app 宿主支持)".to_string())
818 }
819
820 fn system_theme(&self) -> Option<SystemTheme> {
822 None
823 }
824
825 fn clipboard(&self) -> ClipboardHandle {
829 ClipboardHandle::noop()
830 }
831
832 fn native_menu(&self) -> Option<Rc<dyn NativeMenuController>> {
834 None
835 }
836
837 fn set_undecorated_shadow(&self, _shadow: bool) {}
841
842 fn high_contrast(&self) -> bool {
847 false
848 }
849
850 fn set_window_corners(&self, _corners: WindowCorners) {}
855
856 fn window_state(&self) -> Option<WindowState> {
858 None
859 }
860
861 fn pick_file(&self, _options: &FileDialogOptions) -> Option<PathBuf> {
864 None
865 }
866
867 fn pick_files(&self, _options: &FileDialogOptions) -> Option<Vec<PathBuf>> {
869 None
870 }
871
872 fn pick_folder(&self, _options: &FileDialogOptions) -> Option<PathBuf> {
874 None
875 }
876
877 fn save_file(&self, _options: &FileDialogOptions) -> Option<PathBuf> {
879 None
880 }
881
882 fn start_file_drag(&self, _paths: &[PathBuf], _options: &FileDragOptions) -> Result<FileDragOutcome, String> {
887 Err("当前 shell 不支持拖出文件".to_string())
888 }
889
890 fn show_notification(&self, _notification: &Notification) -> Result<(), String> {
893 Err("当前 shell 不支持系统通知".to_string())
894 }
895}
896
897#[derive(Clone, Debug, PartialEq)]
901pub enum ShellEvent {
902 CursorMoved {
903 position: Point,
904 },
905 MouseInput {
906 position: Point,
907 button: MouseButton,
908 pressed: bool,
909 modifiers: KeyModifiers,
910 },
911 CursorLeft,
913 Wheel {
915 position: Point,
916 delta: Point,
917 modifiers: KeyModifiers,
918 },
919 ModifiersChanged(KeyModifiers),
920 Keyboard {
921 key: KeyCode,
922 pressed: bool,
923 repeat: bool,
924 modifiers: KeyModifiers,
925 },
926 Focused(bool),
927 Ime(ImeEvent),
928 FileHovered(PathBuf),
930 FileHoverCancelled,
932 FileDropped(PathBuf),
934 ThemeChanged(SystemTheme),
936}
937
938#[derive(Clone, Debug, PartialEq, Eq)]
940pub enum ImeEvent {
941 Enabled,
942 Disabled,
943 Preedit(String, Option<(usize, usize)>),
944 Commit(String),
945}
946
947pub trait Clock {
949 fn now_ms(&self) -> u64;
950}
951
952#[derive(Clone, Debug)]
954pub struct ManualClock {
955 now_ms: Cell<u64>,
956}
957
958impl ManualClock {
959 pub fn new(start_ms: u64) -> Self {
960 Self { now_ms: Cell::new(start_ms) }
961 }
962
963 pub fn set(&self, now_ms: u64) {
964 self.now_ms.set(now_ms);
965 }
966
967 pub fn advance(&self, delta_ms: u64) -> u64 {
968 let next = self.now_ms.get().saturating_add(delta_ms);
969 self.now_ms.set(next);
970 next
971 }
972}
973
974impl Default for ManualClock {
975 fn default() -> Self {
976 Self::new(0)
977 }
978}
979
980impl Clock for ManualClock {
981 fn now_ms(&self) -> u64 {
982 self.now_ms.get()
983 }
984}
985
986#[derive(Debug)]
988pub struct SystemClock {
989 start: Instant,
990}
991
992impl SystemClock {
993 pub fn new() -> Self {
994 Self { start: Instant::now() }
995 }
996}
997
998impl Default for SystemClock {
999 fn default() -> Self {
1000 Self::new()
1001 }
1002}
1003
1004impl Clock for SystemClock {
1005 fn now_ms(&self) -> u64 {
1006 self.start.elapsed().as_millis() as u64
1007 }
1008}
1009
1010#[cfg(test)]
1011mod tests {
1012 use super::*;
1013
1014 #[test]
1015 fn manual_clock_is_deterministic() {
1016 let clock = ManualClock::new(100);
1017 assert_eq!(clock.now_ms(), 100);
1018 assert_eq!(clock.advance(16), 116);
1019 clock.set(500);
1020 assert_eq!(clock.now_ms(), 500);
1021 }
1022
1023 #[test]
1024 fn metrics_clamp_invalid_values() {
1025 let m = ShellMetrics::new(Size::new(0.0, -5.0), 0.0);
1026 assert_eq!(m.logical_size, Size::new(1.0, 1.0));
1027 assert_eq!(m.scale_factor, 0.01);
1028 }
1029
1030 #[test]
1031 fn metrics_from_physical_divides_by_dpr() {
1032 let m = ShellMetrics::from_physical(1920, 1080, 2.0);
1033 assert_eq!(m.logical_size, Size::new(960.0, 540.0));
1034 assert_eq!(m.scale_factor, 2.0);
1035 }
1036
1037 #[test]
1038 fn window_state_roundtrip_and_validation() {
1039 let state = WindowState { size: Size::new(1024.0, 720.0), position: Some((120.0, 80.0)), maximized: true };
1040 let parsed = WindowState::parse(&state.encode()).expect("parse roundtrip");
1041 assert_eq!(parsed, state);
1042
1043 let compact = WindowState::parse("mgui-window-state=1\nwidth=800\nheight=600\n").expect("compact");
1045 assert_eq!(compact.position, None);
1046 assert!(!compact.maximized);
1047 assert!(WindowState::parse("mgui-window-state=2\nwidth=800\nheight=600").is_none());
1048 assert!(WindowState::parse("mgui-window-state=1\nwidth=0\nheight=600").is_none());
1049 }
1050
1051 #[test]
1052 fn window_state_file_roundtrip() {
1053 let path = std::env::temp_dir().join(format!(
1054 "mgui-window-state-{}-{}.txt",
1055 std::process::id(),
1056 std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0)
1057 ));
1058 let state = WindowState { size: Size::new(1280.0, 800.0), position: Some((10.0, 20.0)), maximized: false };
1059 state.save(&path).expect("save state");
1060 assert_eq!(WindowState::load(&path), Some(state));
1061 let _ = std::fs::remove_file(path);
1062 }
1063
1064 #[test]
1065 fn file_dialog_options_builder() {
1066 let options = FileDialogOptions::new("Open")
1067 .with_directory("/tmp")
1068 .with_file_name("notes.txt")
1069 .with_filter("Text", ["txt", "md"])
1070 .with_filter("All", ["*"]);
1071 assert_eq!(options.title, "Open");
1072 assert_eq!(options.directory.as_deref(), Some(std::path::Path::new("/tmp")));
1073 assert_eq!(options.file_name.as_deref(), Some("notes.txt"));
1074 assert_eq!(options.filters.len(), 2);
1075 assert_eq!(options.filters[0].name, "Text");
1076 assert_eq!(options.filters[0].extensions, vec!["txt", "md"]);
1077 }
1078
1079 #[test]
1080 fn notification_builder_defaults_and_overrides() {
1081 let n = Notification::new("Build finished");
1082 assert_eq!(n.title, "Build finished");
1083 assert!(n.body.is_empty());
1084 assert_eq!(n.level, NotificationLevel::Normal);
1085 assert_eq!(n.timeout, NotificationTimeout::Default);
1086 assert!(!n.silent);
1087
1088 let n = n
1089 .with_body("all green")
1090 .with_app_id("studio.qianbai.mgui")
1091 .with_level(NotificationLevel::Critical)
1092 .with_timeout(NotificationTimeout::Never)
1093 .with_silent(true)
1094 .with_icon("dialog-information");
1095 assert_eq!(n.body, "all green");
1096 assert_eq!(n.app_id.as_deref(), Some("studio.qianbai.mgui"));
1097 assert_eq!(n.level, NotificationLevel::Critical);
1098 assert_eq!(n.timeout, NotificationTimeout::Never);
1099 assert!(n.silent);
1100 assert_eq!(n.icon.as_deref(), Some("dialog-information"));
1101 }
1102
1103 #[test]
1104 fn tray_config_keeps_menu_order() {
1105 let icon = IconImage::from_rgba(2, 2, vec![255; 16]).expect("valid icon");
1106 let tray = TrayConfig::new("mgui")
1107 .with_icon(icon)
1108 .with_menu_item(TrayMenuItem::item(1, "Show"))
1109 .with_menu_item(TrayMenuItem::separator())
1110 .with_menu_item(TrayMenuItem::submenu("More", vec![TrayMenuItem::item_enabled(2, "Disabled", false)]))
1111 .with_open_menu_on_left_click(true);
1112 assert_eq!(tray.tooltip, "mgui");
1113 assert!(tray.icon.is_some());
1114 assert_eq!(tray.menu.len(), 3);
1115 assert!(matches!(tray.menu[0], TrayMenuItem::Item { id: 1, ref label, enabled: true } if label == "Show"));
1116 assert_eq!(tray.menu[1], TrayMenuItem::Separator);
1117 assert!(matches!(tray.menu[2], TrayMenuItem::Submenu { ref label, .. } if label == "More"));
1118 assert!(tray.open_menu_on_left_click);
1119 }
1120
1121 #[test]
1122 fn tray_event_is_comparable() {
1123 assert_eq!(TrayEvent::Menu { id: 7 }, TrayEvent::Menu { id: 7 });
1124 assert_ne!(TrayEvent::Click { button: MouseButton::Left }, TrayEvent::Click { button: MouseButton::Right });
1125 }
1126
1127 #[test]
1128 fn shortcut_helpers_set_expected_modifiers() {
1129 assert_eq!(Shortcut::command(ShortcutKey::Char('s')).modifiers, KeyModifiers::command_only());
1130 assert_eq!(Shortcut::ctrl(ShortcutKey::Char('s')).modifiers, KeyModifiers::ctrl_only());
1131 assert_eq!(
1132 Shortcut::ctrl_shift(ShortcutKey::F(5)).modifiers,
1133 KeyModifiers(KeyModifiers::CTRL | KeyModifiers::SHIFT)
1134 );
1135 assert_eq!(Shortcut::alt(ShortcutKey::Left).key, ShortcutKey::Left);
1136 }
1137
1138 #[test]
1139 fn native_menu_builder_collects_nested_accelerators() {
1140 let menu = NativeMenuBar::new()
1141 .with_menu(
1142 NativeMenu::new("File")
1143 .with_item(
1144 NativeMenuCommand::new(1, "New").with_shortcut(Shortcut::command(ShortcutKey::Char('n'))),
1145 )
1146 .with_item(NativeMenuItem::separator())
1147 .with_item(
1148 NativeMenuCommand::new(2, "Exit").with_shortcut(Shortcut::command(ShortcutKey::Char('q'))),
1149 )
1150 .with_item(
1151 NativeMenu::new("More").with_item(
1152 NativeMenuCommand::new(3, "Deep")
1153 .with_shortcut(Shortcut::ctrl_shift(ShortcutKey::F(7)))
1154 .with_checked(true),
1155 ),
1156 ),
1157 )
1158 .with_menu(NativeMenu::new("Help"));
1159 let accelerators = menu.accelerators();
1160 assert_eq!(accelerators.len(), 3);
1161 assert_eq!(accelerators[0].0, 1);
1162 assert_eq!(accelerators[1].0, 2);
1163 assert_eq!(accelerators[2].0, 3);
1164 assert_eq!(accelerators[2].1.key, ShortcutKey::F(7));
1165 assert_eq!(menu.menus.len(), 2);
1166 assert_eq!(menu.command_ids(), vec![1, 2, 3]);
1167 }
1168
1169 #[test]
1170 fn global_shortcut_keeps_id_and_combo() {
1171 let shortcut = Shortcut::ctrl_alt(ShortcutKey::Char('m'));
1172 let global = GlobalShortcut::new(42, shortcut);
1173 assert_eq!(global.id, 42);
1174 assert_eq!(global.shortcut, shortcut);
1175 }
1176
1177 #[test]
1178 fn single_instance_config_defaults_to_forwarding() {
1179 let config = SingleInstanceConfig::new("studio.example.app");
1180 assert_eq!(config.id, "studio.example.app");
1181 assert!(config.forward_args);
1182 assert!(!config.with_forward_args(false).forward_args);
1183 }
1184
1185 #[test]
1186 fn file_drag_options_default_to_copy() {
1187 let options = FileDragOptions::new().with_preview("/tmp/a.png").with_copy(false);
1188 assert_eq!(options.preview.as_deref(), Some(std::path::Path::new("/tmp/a.png")));
1189 assert!(!options.copy);
1190 assert!(FileDragOptions::default().copy);
1191 }
1192
1193 #[test]
1194 fn resize_direction_hit_test_prioritizes_corners() {
1195 let size = Size::new(200.0, 100.0);
1196 assert_eq!(ResizeDirection::hit_test(Point::new(2.0, 2.0), size, 6.0), Some(ResizeDirection::NorthWest));
1197 assert_eq!(ResizeDirection::hit_test(Point::new(198.0, 2.0), size, 6.0), Some(ResizeDirection::NorthEast));
1198 assert_eq!(ResizeDirection::hit_test(Point::new(2.0, 98.0), size, 6.0), Some(ResizeDirection::SouthWest));
1199 assert_eq!(ResizeDirection::hit_test(Point::new(100.0, 98.0), size, 6.0), Some(ResizeDirection::South));
1200 assert_eq!(ResizeDirection::hit_test(Point::new(2.0, 50.0), size, 6.0), Some(ResizeDirection::West));
1201 assert_eq!(ResizeDirection::hit_test(Point::new(100.0, 50.0), size, 6.0), None);
1202 assert_eq!(ResizeDirection::hit_test(Point::new(-1.0, 50.0), size, 6.0), None);
1203 assert_eq!(ResizeDirection::hit_test(Point::new(2.0, 2.0), size, 0.0), None);
1204 }
1205}