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, Copy, Debug, Default, PartialEq, Eq)]
234pub enum ThemeMode {
235 Light,
236 Dark,
237 #[default]
238 System,
239}
240
241impl ThemeMode {
242 pub fn resolve(self, system: Option<SystemTheme>) -> SystemTheme {
244 match self {
245 ThemeMode::Light => SystemTheme::Light,
246 ThemeMode::Dark => SystemTheme::Dark,
247 ThemeMode::System => system.unwrap_or(SystemTheme::Light),
248 }
249 }
250
251 pub fn follows_system(self) -> bool {
253 matches!(self, ThemeMode::System)
254 }
255}
256
257#[derive(Clone, Debug, PartialEq, Eq)]
259pub struct FileDialogFilter {
260 pub name: String,
261 pub extensions: Vec<String>,
262}
263
264impl FileDialogFilter {
265 pub fn new<I, S>(name: impl Into<String>, extensions: I) -> Self
266 where
267 I: IntoIterator<Item = S>,
268 S: Into<String>,
269 {
270 Self { name: name.into(), extensions: extensions.into_iter().map(Into::into).collect() }
271 }
272}
273
274#[derive(Clone, Debug, Default, PartialEq, Eq)]
276pub struct FileDialogOptions {
277 pub title: String,
278 pub directory: Option<PathBuf>,
279 pub file_name: Option<String>,
280 pub filters: Vec<FileDialogFilter>,
281}
282
283impl FileDialogOptions {
284 pub fn new(title: impl Into<String>) -> Self {
285 Self { title: title.into(), ..Self::default() }
286 }
287
288 pub fn with_directory(mut self, directory: impl Into<PathBuf>) -> Self {
289 self.directory = Some(directory.into());
290 self
291 }
292
293 pub fn with_file_name(mut self, name: impl Into<String>) -> Self {
294 self.file_name = Some(name.into());
295 self
296 }
297
298 pub fn with_filter<I, S>(mut self, name: impl Into<String>, extensions: I) -> Self
299 where
300 I: IntoIterator<Item = S>,
301 S: Into<String>,
302 {
303 self.filters.push(FileDialogFilter::new(name, extensions));
304 self
305 }
306}
307
308#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
310pub enum NotificationLevel {
311 Low,
312 #[default]
313 Normal,
314 Critical,
315}
316
317#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
319pub enum NotificationTimeout {
320 #[default]
322 Default,
323 Never,
325 Milliseconds(u32),
327}
328
329#[derive(Clone, Debug, PartialEq, Eq)]
334pub struct Notification {
335 pub title: String,
336 pub body: String,
337 pub app_name: Option<String>,
338 pub app_id: Option<String>,
339 pub level: NotificationLevel,
340 pub silent: bool,
341 pub timeout: NotificationTimeout,
342 pub icon: Option<String>,
344}
345
346impl Notification {
347 pub fn new(title: impl Into<String>) -> Self {
348 Self {
349 title: title.into(),
350 body: String::new(),
351 app_name: None,
352 app_id: None,
353 level: NotificationLevel::Normal,
354 silent: false,
355 timeout: NotificationTimeout::Default,
356 icon: None,
357 }
358 }
359
360 pub fn with_body(mut self, body: impl Into<String>) -> Self {
361 self.body = body.into();
362 self
363 }
364
365 pub fn with_app_name(mut self, name: impl Into<String>) -> Self {
366 self.app_name = Some(name.into());
367 self
368 }
369
370 pub fn with_app_id(mut self, id: impl Into<String>) -> Self {
371 self.app_id = Some(id.into());
372 self
373 }
374
375 pub fn with_level(mut self, level: NotificationLevel) -> Self {
376 self.level = level;
377 self
378 }
379
380 pub fn with_silent(mut self, silent: bool) -> Self {
381 self.silent = silent;
382 self
383 }
384
385 pub fn with_timeout(mut self, timeout: NotificationTimeout) -> Self {
386 self.timeout = timeout;
387 self
388 }
389
390 pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
391 self.icon = Some(icon.into());
392 self
393 }
394}
395
396#[derive(Clone, Debug, PartialEq, Eq)]
401pub enum TrayMenuItem {
402 Item { id: u64, label: String, enabled: bool },
403 Separator,
404 Submenu { label: String, items: Vec<TrayMenuItem> },
405}
406
407impl TrayMenuItem {
408 pub fn item(id: u64, label: impl Into<String>) -> Self {
409 Self::Item { id, label: label.into(), enabled: true }
410 }
411
412 pub fn item_enabled(id: u64, label: impl Into<String>, enabled: bool) -> Self {
413 Self::Item { id, label: label.into(), enabled }
414 }
415
416 pub fn separator() -> Self {
417 Self::Separator
418 }
419
420 pub fn submenu(label: impl Into<String>, items: Vec<TrayMenuItem>) -> Self {
421 Self::Submenu { label: label.into(), items }
422 }
423}
424
425#[derive(Clone, Debug, Default, PartialEq, Eq)]
431pub struct TrayConfig {
432 pub tooltip: String,
433 pub icon: Option<IconImage>,
434 pub menu: Vec<TrayMenuItem>,
435 pub open_menu_on_left_click: bool,
436}
437
438impl TrayConfig {
439 pub fn new(tooltip: impl Into<String>) -> Self {
440 Self { tooltip: tooltip.into(), ..Self::default() }
441 }
442
443 pub fn with_icon(mut self, icon: IconImage) -> Self {
444 self.icon = Some(icon);
445 self
446 }
447
448 pub fn with_menu(mut self, items: Vec<TrayMenuItem>) -> Self {
449 self.menu = items;
450 self
451 }
452
453 pub fn with_menu_item(mut self, item: TrayMenuItem) -> Self {
454 self.menu.push(item);
455 self
456 }
457
458 pub fn with_open_menu_on_left_click(mut self, open: bool) -> Self {
459 self.open_menu_on_left_click = open;
460 self
461 }
462}
463
464#[derive(Clone, Copy, Debug, PartialEq, Eq)]
466pub enum TrayEvent {
467 Click { button: MouseButton },
469 Menu { id: u64 },
471}
472
473#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
477pub enum ShortcutKey {
478 Char(char),
479 Enter,
480 Escape,
481 Tab,
482 Space,
483 Backspace,
484 Delete,
485 Insert,
486 Left,
487 Right,
488 Up,
489 Down,
490 Home,
491 End,
492 PageUp,
493 PageDown,
494 F(u8),
496}
497
498#[derive(Clone, Copy, Debug, PartialEq, Eq)]
500pub struct Shortcut {
501 pub modifiers: KeyModifiers,
502 pub key: ShortcutKey,
503}
504
505impl Shortcut {
506 pub const fn new(modifiers: KeyModifiers, key: ShortcutKey) -> Self {
507 Self { modifiers, key }
508 }
509
510 pub fn command(key: ShortcutKey) -> Self {
512 Self::new(KeyModifiers::command_only(), key)
513 }
514
515 pub fn ctrl(key: ShortcutKey) -> Self {
516 Self::new(KeyModifiers::ctrl_only(), key)
517 }
518
519 pub fn shift(key: ShortcutKey) -> Self {
520 Self::new(KeyModifiers::shift_only(), key)
521 }
522
523 pub fn ctrl_shift(key: ShortcutKey) -> Self {
524 Self::new(KeyModifiers(KeyModifiers::CTRL | KeyModifiers::SHIFT), key)
525 }
526
527 pub fn ctrl_alt(key: ShortcutKey) -> Self {
528 Self::new(KeyModifiers(KeyModifiers::CTRL | KeyModifiers::ALT), key)
529 }
530
531 pub fn alt(key: ShortcutKey) -> Self {
532 Self::new(KeyModifiers(KeyModifiers::ALT), key)
533 }
534}
535
536#[derive(Clone, Debug, PartialEq, Eq)]
542pub struct SingleInstanceConfig {
543 pub id: String,
544 pub forward_args: bool,
546}
547
548impl SingleInstanceConfig {
549 pub fn new(id: impl Into<String>) -> Self {
550 Self { id: id.into(), forward_args: true }
551 }
552
553 pub fn with_forward_args(mut self, forward: bool) -> Self {
554 self.forward_args = forward;
555 self
556 }
557}
558
559#[derive(Clone, Debug, PartialEq, Eq)]
563pub struct GlobalShortcut {
564 pub id: u64,
565 pub shortcut: Shortcut,
566}
567
568impl GlobalShortcut {
569 pub fn new(id: u64, shortcut: Shortcut) -> Self {
570 Self { id, shortcut }
571 }
572}
573
574#[derive(Clone, Debug, PartialEq, Eq)]
576pub struct NativeMenuCommand {
577 pub id: u64,
578 pub label: String,
579 pub shortcut: Option<Shortcut>,
580 pub enabled: bool,
581 pub checked: Option<bool>,
583}
584
585impl NativeMenuCommand {
586 pub fn new(id: u64, label: impl Into<String>) -> Self {
587 Self { id, label: label.into(), shortcut: None, enabled: true, checked: None }
588 }
589
590 pub fn with_shortcut(mut self, shortcut: Shortcut) -> Self {
591 self.shortcut = Some(shortcut);
592 self
593 }
594
595 pub fn with_enabled(mut self, enabled: bool) -> Self {
596 self.enabled = enabled;
597 self
598 }
599
600 pub fn with_checked(mut self, checked: bool) -> Self {
601 self.checked = Some(checked);
602 self
603 }
604}
605
606#[derive(Clone, Debug, PartialEq, Eq)]
608pub enum NativeMenuItem {
609 Command(NativeMenuCommand),
610 Separator,
611 Submenu(NativeMenu),
612}
613
614impl NativeMenuItem {
615 pub fn separator() -> Self {
616 Self::Separator
617 }
618}
619
620impl From<NativeMenuCommand> for NativeMenuItem {
621 fn from(command: NativeMenuCommand) -> Self {
622 Self::Command(command)
623 }
624}
625
626impl From<NativeMenu> for NativeMenuItem {
627 fn from(menu: NativeMenu) -> Self {
628 Self::Submenu(menu)
629 }
630}
631
632#[derive(Clone, Debug, PartialEq, Eq)]
634pub struct NativeMenu {
635 pub title: String,
636 pub items: Vec<NativeMenuItem>,
637}
638
639impl NativeMenu {
640 pub fn new(title: impl Into<String>) -> Self {
641 Self { title: title.into(), items: Vec::new() }
642 }
643
644 pub fn with_item(mut self, item: impl Into<NativeMenuItem>) -> Self {
645 self.items.push(item.into());
646 self
647 }
648
649 pub fn with_separator(mut self) -> Self {
650 self.items.push(NativeMenuItem::Separator);
651 self
652 }
653}
654
655#[derive(Clone, Debug, Default, PartialEq, Eq)]
660pub struct NativeMenuBar {
661 pub menus: Vec<NativeMenu>,
662}
663
664impl NativeMenuBar {
665 pub fn new() -> Self {
666 Self::default()
667 }
668
669 pub fn with_menu(mut self, menu: NativeMenu) -> Self {
670 self.menus.push(menu);
671 self
672 }
673
674 pub fn command_ids(&self) -> Vec<u64> {
676 fn collect(menu: &NativeMenu, out: &mut Vec<u64>) {
677 for item in &menu.items {
678 match item {
679 NativeMenuItem::Command(command) => out.push(command.id),
680 NativeMenuItem::Submenu(submenu) => collect(submenu, out),
681 NativeMenuItem::Separator => {}
682 }
683 }
684 }
685 let mut out = Vec::new();
686 for menu in &self.menus {
687 collect(menu, &mut out);
688 }
689 out
690 }
691
692 pub fn accelerators(&self) -> Vec<(u64, Shortcut)> {
694 fn collect(menu: &NativeMenu, out: &mut Vec<(u64, Shortcut)>) {
695 for item in &menu.items {
696 match item {
697 NativeMenuItem::Command(command) => {
698 if let Some(shortcut) = command.shortcut {
699 out.push((command.id, shortcut));
700 }
701 }
702 NativeMenuItem::Submenu(submenu) => collect(submenu, out),
703 NativeMenuItem::Separator => {}
704 }
705 }
706 }
707 let mut out = Vec::new();
708 for menu in &self.menus {
709 collect(menu, &mut out);
710 }
711 out
712 }
713}
714
715#[derive(Clone, Copy, Debug, PartialEq, Eq)]
717pub enum FileDragOutcome {
718 Dropped,
719 Cancelled,
720}
721
722#[derive(Clone, Debug, PartialEq, Eq)]
724pub struct FileDragOptions {
725 pub preview: Option<PathBuf>,
727 pub copy: bool,
729}
730
731impl Default for FileDragOptions {
732 fn default() -> Self {
733 Self { preview: None, copy: true }
734 }
735}
736
737impl FileDragOptions {
738 pub fn new() -> Self {
739 Self::default()
740 }
741
742 pub fn with_preview(mut self, path: impl Into<PathBuf>) -> Self {
743 self.preview = Some(path.into());
744 self
745 }
746
747 pub fn with_copy(mut self, copy: bool) -> Self {
748 self.copy = copy;
749 self
750 }
751}
752
753pub trait NativeMenuController {
757 fn set_item_enabled(&self, id: u64, enabled: bool);
758 fn set_item_checked(&self, id: u64, checked: bool);
759 fn set_visible(&self, visible: bool);
762}
763
764pub trait WindowShell {
769 fn metrics(&self) -> ShellMetrics;
770 fn request_redraw(&self);
771 fn set_title(&self, title: &str);
772 fn set_visible(&self, visible: bool);
773 fn is_visible(&self) -> bool {
775 true
776 }
777 fn set_ime_allowed(&self, allowed: bool);
778 fn set_ime_cursor_area(&self, rect: Rect);
779
780 fn set_cursor(&self, _cursor: CursorIcon) {}
782 fn set_fullscreen(&self, _fullscreen: bool) {}
784 fn is_fullscreen(&self) -> bool {
785 false
786 }
787 fn set_minimized(&self, _minimized: bool) {}
789 fn set_maximized(&self, _maximized: bool) {}
791 fn is_maximized(&self) -> bool {
792 false
793 }
794 fn focus_window(&self) {}
796 fn set_decorations(&self, _decorations: bool) {}
798 fn toggle_maximized(&self) {
801 self.set_maximized(!self.is_maximized());
802 }
803 fn start_dragging(&self) -> Result<(), String> {
806 Err("当前 shell 不支持窗口拖拽".to_string())
807 }
808 fn start_resize(&self, _direction: ResizeDirection) -> Result<(), String> {
812 Err("当前 shell 不支持窗口边缘缩放".to_string())
813 }
814 fn set_resizable(&self, _resizable: bool) {}
816 fn set_always_on_top(&self, _on_top: bool) {}
818 fn set_size(&self, _size: Size) {}
820 fn set_position(&self, _x: f32, _y: f32) {}
822
823 fn request_close(&self) {}
826
827 fn tray_available(&self) -> bool {
834 false
835 }
836
837 fn window_name(&self) -> Option<String> {
840 None
841 }
842
843 fn send_window_command(&self, _window: &str, _command: WindowCommand) -> Result<(), String> {
849 Err("当前 shell 不支持跨窗口命令(只有 run_multi_app 宿主支持)".to_string())
850 }
851
852 fn system_theme(&self) -> Option<SystemTheme> {
854 None
855 }
856
857 fn clipboard(&self) -> ClipboardHandle {
861 ClipboardHandle::noop()
862 }
863
864 fn native_menu(&self) -> Option<Rc<dyn NativeMenuController>> {
866 None
867 }
868
869 fn set_undecorated_shadow(&self, _shadow: bool) {}
873
874 fn high_contrast(&self) -> bool {
879 false
880 }
881
882 fn set_window_corners(&self, _corners: WindowCorners) {}
887
888 fn window_state(&self) -> Option<WindowState> {
890 None
891 }
892
893 fn pick_file(&self, _options: &FileDialogOptions) -> Option<PathBuf> {
896 None
897 }
898
899 fn pick_files(&self, _options: &FileDialogOptions) -> Option<Vec<PathBuf>> {
901 None
902 }
903
904 fn pick_folder(&self, _options: &FileDialogOptions) -> Option<PathBuf> {
906 None
907 }
908
909 fn save_file(&self, _options: &FileDialogOptions) -> Option<PathBuf> {
911 None
912 }
913
914 fn start_file_drag(&self, _paths: &[PathBuf], _options: &FileDragOptions) -> Result<FileDragOutcome, String> {
919 Err("当前 shell 不支持拖出文件".to_string())
920 }
921
922 fn show_notification(&self, _notification: &Notification) -> Result<(), String> {
925 Err("当前 shell 不支持系统通知".to_string())
926 }
927}
928
929#[derive(Clone, Debug, PartialEq)]
933pub enum ShellEvent {
934 CursorMoved {
935 position: Point,
936 },
937 MouseInput {
938 position: Point,
939 button: MouseButton,
940 pressed: bool,
941 modifiers: KeyModifiers,
942 },
943 CursorLeft,
945 Wheel {
947 position: Point,
948 delta: Point,
949 modifiers: KeyModifiers,
950 },
951 ModifiersChanged(KeyModifiers),
952 Keyboard {
953 key: KeyCode,
954 pressed: bool,
955 repeat: bool,
956 modifiers: KeyModifiers,
957 },
958 Focused(bool),
959 Ime(ImeEvent),
960 FileHovered(PathBuf),
962 FileHoverCancelled,
964 FileDropped(PathBuf),
966 ThemeChanged(SystemTheme),
968}
969
970#[derive(Clone, Debug, PartialEq, Eq)]
972pub enum ImeEvent {
973 Enabled,
974 Disabled,
975 Preedit(String, Option<(usize, usize)>),
976 Commit(String),
977}
978
979pub trait Clock {
981 fn now_ms(&self) -> u64;
982}
983
984#[derive(Clone, Debug)]
986pub struct ManualClock {
987 now_ms: Cell<u64>,
988}
989
990impl ManualClock {
991 pub fn new(start_ms: u64) -> Self {
992 Self { now_ms: Cell::new(start_ms) }
993 }
994
995 pub fn set(&self, now_ms: u64) {
996 self.now_ms.set(now_ms);
997 }
998
999 pub fn advance(&self, delta_ms: u64) -> u64 {
1000 let next = self.now_ms.get().saturating_add(delta_ms);
1001 self.now_ms.set(next);
1002 next
1003 }
1004}
1005
1006impl Default for ManualClock {
1007 fn default() -> Self {
1008 Self::new(0)
1009 }
1010}
1011
1012impl Clock for ManualClock {
1013 fn now_ms(&self) -> u64 {
1014 self.now_ms.get()
1015 }
1016}
1017
1018#[derive(Debug)]
1020pub struct SystemClock {
1021 start: Instant,
1022}
1023
1024impl SystemClock {
1025 pub fn new() -> Self {
1026 Self { start: Instant::now() }
1027 }
1028}
1029
1030impl Default for SystemClock {
1031 fn default() -> Self {
1032 Self::new()
1033 }
1034}
1035
1036impl Clock for SystemClock {
1037 fn now_ms(&self) -> u64 {
1038 self.start.elapsed().as_millis() as u64
1039 }
1040}
1041
1042#[cfg(test)]
1043mod tests {
1044 use super::*;
1045
1046 #[test]
1047 fn theme_mode_resolves_deterministically() {
1048 assert_eq!(ThemeMode::Light.resolve(Some(SystemTheme::Dark)), SystemTheme::Light);
1049 assert_eq!(ThemeMode::Dark.resolve(Some(SystemTheme::Light)), SystemTheme::Dark);
1050 assert_eq!(ThemeMode::System.resolve(Some(SystemTheme::Dark)), SystemTheme::Dark);
1051 assert_eq!(ThemeMode::System.resolve(None), SystemTheme::Light);
1053 assert!(ThemeMode::System.follows_system());
1054 assert!(!ThemeMode::Light.follows_system());
1055 assert_eq!(ThemeMode::default(), ThemeMode::System);
1056 }
1057
1058 #[test]
1059 fn manual_clock_is_deterministic() {
1060 let clock = ManualClock::new(100);
1061 assert_eq!(clock.now_ms(), 100);
1062 assert_eq!(clock.advance(16), 116);
1063 clock.set(500);
1064 assert_eq!(clock.now_ms(), 500);
1065 }
1066
1067 #[test]
1068 fn metrics_clamp_invalid_values() {
1069 let m = ShellMetrics::new(Size::new(0.0, -5.0), 0.0);
1070 assert_eq!(m.logical_size, Size::new(1.0, 1.0));
1071 assert_eq!(m.scale_factor, 0.01);
1072 }
1073
1074 #[test]
1075 fn metrics_from_physical_divides_by_dpr() {
1076 let m = ShellMetrics::from_physical(1920, 1080, 2.0);
1077 assert_eq!(m.logical_size, Size::new(960.0, 540.0));
1078 assert_eq!(m.scale_factor, 2.0);
1079 }
1080
1081 #[test]
1082 fn window_state_roundtrip_and_validation() {
1083 let state = WindowState { size: Size::new(1024.0, 720.0), position: Some((120.0, 80.0)), maximized: true };
1084 let parsed = WindowState::parse(&state.encode()).expect("parse roundtrip");
1085 assert_eq!(parsed, state);
1086
1087 let compact = WindowState::parse("mgui-window-state=1\nwidth=800\nheight=600\n").expect("compact");
1089 assert_eq!(compact.position, None);
1090 assert!(!compact.maximized);
1091 assert!(WindowState::parse("mgui-window-state=2\nwidth=800\nheight=600").is_none());
1092 assert!(WindowState::parse("mgui-window-state=1\nwidth=0\nheight=600").is_none());
1093 }
1094
1095 #[test]
1096 fn window_state_file_roundtrip() {
1097 let path = std::env::temp_dir().join(format!(
1098 "mgui-window-state-{}-{}.txt",
1099 std::process::id(),
1100 std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0)
1101 ));
1102 let state = WindowState { size: Size::new(1280.0, 800.0), position: Some((10.0, 20.0)), maximized: false };
1103 state.save(&path).expect("save state");
1104 assert_eq!(WindowState::load(&path), Some(state));
1105 let _ = std::fs::remove_file(path);
1106 }
1107
1108 #[test]
1109 fn file_dialog_options_builder() {
1110 let options = FileDialogOptions::new("Open")
1111 .with_directory("/tmp")
1112 .with_file_name("notes.txt")
1113 .with_filter("Text", ["txt", "md"])
1114 .with_filter("All", ["*"]);
1115 assert_eq!(options.title, "Open");
1116 assert_eq!(options.directory.as_deref(), Some(std::path::Path::new("/tmp")));
1117 assert_eq!(options.file_name.as_deref(), Some("notes.txt"));
1118 assert_eq!(options.filters.len(), 2);
1119 assert_eq!(options.filters[0].name, "Text");
1120 assert_eq!(options.filters[0].extensions, vec!["txt", "md"]);
1121 }
1122
1123 #[test]
1124 fn notification_builder_defaults_and_overrides() {
1125 let n = Notification::new("Build finished");
1126 assert_eq!(n.title, "Build finished");
1127 assert!(n.body.is_empty());
1128 assert_eq!(n.level, NotificationLevel::Normal);
1129 assert_eq!(n.timeout, NotificationTimeout::Default);
1130 assert!(!n.silent);
1131
1132 let n = n
1133 .with_body("all green")
1134 .with_app_id("studio.qianbai.mgui")
1135 .with_level(NotificationLevel::Critical)
1136 .with_timeout(NotificationTimeout::Never)
1137 .with_silent(true)
1138 .with_icon("dialog-information");
1139 assert_eq!(n.body, "all green");
1140 assert_eq!(n.app_id.as_deref(), Some("studio.qianbai.mgui"));
1141 assert_eq!(n.level, NotificationLevel::Critical);
1142 assert_eq!(n.timeout, NotificationTimeout::Never);
1143 assert!(n.silent);
1144 assert_eq!(n.icon.as_deref(), Some("dialog-information"));
1145 }
1146
1147 #[test]
1148 fn tray_config_keeps_menu_order() {
1149 let icon = IconImage::from_rgba(2, 2, vec![255; 16]).expect("valid icon");
1150 let tray = TrayConfig::new("mgui")
1151 .with_icon(icon)
1152 .with_menu_item(TrayMenuItem::item(1, "Show"))
1153 .with_menu_item(TrayMenuItem::separator())
1154 .with_menu_item(TrayMenuItem::submenu("More", vec![TrayMenuItem::item_enabled(2, "Disabled", false)]))
1155 .with_open_menu_on_left_click(true);
1156 assert_eq!(tray.tooltip, "mgui");
1157 assert!(tray.icon.is_some());
1158 assert_eq!(tray.menu.len(), 3);
1159 assert!(matches!(tray.menu[0], TrayMenuItem::Item { id: 1, ref label, enabled: true } if label == "Show"));
1160 assert_eq!(tray.menu[1], TrayMenuItem::Separator);
1161 assert!(matches!(tray.menu[2], TrayMenuItem::Submenu { ref label, .. } if label == "More"));
1162 assert!(tray.open_menu_on_left_click);
1163 }
1164
1165 #[test]
1166 fn tray_event_is_comparable() {
1167 assert_eq!(TrayEvent::Menu { id: 7 }, TrayEvent::Menu { id: 7 });
1168 assert_ne!(TrayEvent::Click { button: MouseButton::Left }, TrayEvent::Click { button: MouseButton::Right });
1169 }
1170
1171 #[test]
1172 fn shortcut_helpers_set_expected_modifiers() {
1173 assert_eq!(Shortcut::command(ShortcutKey::Char('s')).modifiers, KeyModifiers::command_only());
1174 assert_eq!(Shortcut::ctrl(ShortcutKey::Char('s')).modifiers, KeyModifiers::ctrl_only());
1175 assert_eq!(
1176 Shortcut::ctrl_shift(ShortcutKey::F(5)).modifiers,
1177 KeyModifiers(KeyModifiers::CTRL | KeyModifiers::SHIFT)
1178 );
1179 assert_eq!(Shortcut::alt(ShortcutKey::Left).key, ShortcutKey::Left);
1180 }
1181
1182 #[test]
1183 fn native_menu_builder_collects_nested_accelerators() {
1184 let menu = NativeMenuBar::new()
1185 .with_menu(
1186 NativeMenu::new("File")
1187 .with_item(
1188 NativeMenuCommand::new(1, "New").with_shortcut(Shortcut::command(ShortcutKey::Char('n'))),
1189 )
1190 .with_item(NativeMenuItem::separator())
1191 .with_item(
1192 NativeMenuCommand::new(2, "Exit").with_shortcut(Shortcut::command(ShortcutKey::Char('q'))),
1193 )
1194 .with_item(
1195 NativeMenu::new("More").with_item(
1196 NativeMenuCommand::new(3, "Deep")
1197 .with_shortcut(Shortcut::ctrl_shift(ShortcutKey::F(7)))
1198 .with_checked(true),
1199 ),
1200 ),
1201 )
1202 .with_menu(NativeMenu::new("Help"));
1203 let accelerators = menu.accelerators();
1204 assert_eq!(accelerators.len(), 3);
1205 assert_eq!(accelerators[0].0, 1);
1206 assert_eq!(accelerators[1].0, 2);
1207 assert_eq!(accelerators[2].0, 3);
1208 assert_eq!(accelerators[2].1.key, ShortcutKey::F(7));
1209 assert_eq!(menu.menus.len(), 2);
1210 assert_eq!(menu.command_ids(), vec![1, 2, 3]);
1211 }
1212
1213 #[test]
1214 fn global_shortcut_keeps_id_and_combo() {
1215 let shortcut = Shortcut::ctrl_alt(ShortcutKey::Char('m'));
1216 let global = GlobalShortcut::new(42, shortcut);
1217 assert_eq!(global.id, 42);
1218 assert_eq!(global.shortcut, shortcut);
1219 }
1220
1221 #[test]
1222 fn single_instance_config_defaults_to_forwarding() {
1223 let config = SingleInstanceConfig::new("studio.example.app");
1224 assert_eq!(config.id, "studio.example.app");
1225 assert!(config.forward_args);
1226 assert!(!config.with_forward_args(false).forward_args);
1227 }
1228
1229 #[test]
1230 fn file_drag_options_default_to_copy() {
1231 let options = FileDragOptions::new().with_preview("/tmp/a.png").with_copy(false);
1232 assert_eq!(options.preview.as_deref(), Some(std::path::Path::new("/tmp/a.png")));
1233 assert!(!options.copy);
1234 assert!(FileDragOptions::default().copy);
1235 }
1236
1237 #[test]
1238 fn resize_direction_hit_test_prioritizes_corners() {
1239 let size = Size::new(200.0, 100.0);
1240 assert_eq!(ResizeDirection::hit_test(Point::new(2.0, 2.0), size, 6.0), Some(ResizeDirection::NorthWest));
1241 assert_eq!(ResizeDirection::hit_test(Point::new(198.0, 2.0), size, 6.0), Some(ResizeDirection::NorthEast));
1242 assert_eq!(ResizeDirection::hit_test(Point::new(2.0, 98.0), size, 6.0), Some(ResizeDirection::SouthWest));
1243 assert_eq!(ResizeDirection::hit_test(Point::new(100.0, 98.0), size, 6.0), Some(ResizeDirection::South));
1244 assert_eq!(ResizeDirection::hit_test(Point::new(2.0, 50.0), size, 6.0), Some(ResizeDirection::West));
1245 assert_eq!(ResizeDirection::hit_test(Point::new(100.0, 50.0), size, 6.0), None);
1246 assert_eq!(ResizeDirection::hit_test(Point::new(-1.0, 50.0), size, 6.0), None);
1247 assert_eq!(ResizeDirection::hit_test(Point::new(2.0, 2.0), size, 0.0), None);
1248 }
1249}