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