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