#![forbid(unsafe_code)]
use std::cell::Cell;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::time::Instant;
use mgui_core::{KeyCode, KeyModifiers, MouseButton, Point, Rect, Size};
pub use mgui_core::{ClipboardHandle, ClipboardImage, ClipboardProvider, NoopClipboard};
pub mod icon;
pub use icon::{IconImage, WindowIcon};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ShellWindowId(pub u64);
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ShellMetrics {
pub logical_size: Size,
pub scale_factor: f32,
}
impl ShellMetrics {
pub fn new(logical_size: Size, scale_factor: f32) -> Self {
Self {
logical_size: Size::new(logical_size.width.max(1.0), logical_size.height.max(1.0)),
scale_factor: scale_factor.max(0.01),
}
}
pub fn from_physical(physical_width: u32, physical_height: u32, scale_factor: f32) -> Self {
let scale_factor = scale_factor.max(0.01);
Self::new(Size::new(physical_width as f32 / scale_factor, physical_height as f32 / scale_factor), scale_factor)
}
}
impl Default for ShellMetrics {
fn default() -> Self {
Self::new(Size::new(800.0, 600.0), 1.0)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum CursorIcon {
#[default]
Default,
Pointer,
Text,
Crosshair,
Move,
NotAllowed,
Wait,
Progress,
Help,
Grab,
Grabbing,
ZoomIn,
ZoomOut,
ResizeHorizontal,
ResizeVertical,
ResizeNwSe,
ResizeNeSw,
ResizeAll,
ColumnResize,
RowResize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ResizeDirection {
East,
North,
NorthEast,
NorthWest,
South,
SouthEast,
SouthWest,
West,
}
impl ResizeDirection {
pub fn hit_test(position: Point, size: Size, margin: f32) -> Option<Self> {
if !(margin.is_finite() && margin > 0.0)
|| !(size.width.is_finite() && size.height.is_finite() && size.width > 0.0 && size.height > 0.0)
|| !(position.x.is_finite() && position.y.is_finite())
{
return None;
}
if position.x < 0.0 || position.y < 0.0 || position.x >= size.width || position.y >= size.height {
return None;
}
let mx = margin.min(size.width / 2.0);
let my = margin.min(size.height / 2.0);
let left = position.x < mx;
let right = position.x > size.width - mx;
let top = position.y < my;
let bottom = position.y > size.height - my;
match (top, bottom, left, right) {
(true, _, true, _) => Some(Self::NorthWest),
(true, _, _, true) => Some(Self::NorthEast),
(_, true, true, _) => Some(Self::SouthWest),
(_, true, _, true) => Some(Self::SouthEast),
(true, _, _, _) => Some(Self::North),
(_, true, _, _) => Some(Self::South),
(_, _, true, _) => Some(Self::West),
(_, _, _, true) => Some(Self::East),
_ => None,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum WindowCorners {
#[default]
Default,
Square,
Rounded,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WindowState {
pub size: Size,
pub position: Option<(f32, f32)>,
pub maximized: bool,
}
impl WindowState {
pub fn new(size: Size) -> Self {
Self { size: Size::new(size.width.max(1.0), size.height.max(1.0)), position: None, maximized: false }
}
pub fn encode(&self) -> String {
let mut out = String::from("mgui-window-state=1\n");
out.push_str(&format!("width={}\nheight={}\n", self.size.width, self.size.height));
if let Some((x, y)) = self.position {
out.push_str(&format!("x={x}\ny={y}\n"));
}
out.push_str(&format!("maximized={}\n", self.maximized));
out
}
pub fn parse(text: &str) -> Option<Self> {
let mut version = None;
let mut width = None;
let mut height = None;
let mut x = None;
let mut y = None;
let mut maximized = false;
for line in text.lines() {
let Some((key, value)) = line.split_once('=') else { continue };
let key = key.trim();
let value = value.trim();
match key {
"mgui-window-state" => version = value.parse::<u32>().ok(),
"width" => width = value.parse::<f32>().ok(),
"height" => height = value.parse::<f32>().ok(),
"x" => x = value.parse::<f32>().ok(),
"y" => y = value.parse::<f32>().ok(),
"maximized" => maximized = matches!(value, "1" | "true"),
_ => {}
}
}
if version != Some(1) {
return None;
}
let width = width.filter(|v| v.is_finite() && *v >= 1.0)?;
let height = height.filter(|v| v.is_finite() && *v >= 1.0)?;
let position = match (x, y) {
(Some(x), Some(y)) if x.is_finite() && y.is_finite() => Some((x, y)),
_ => None,
};
Some(Self { size: Size::new(width, height), position, maximized })
}
pub fn load(path: impl AsRef<Path>) -> Option<Self> {
let text = std::fs::read_to_string(path).ok()?;
Self::parse(&text)
}
pub fn save(&self, path: impl AsRef<Path>) -> Result<(), String> {
let path = path.as_ref();
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
std::fs::create_dir_all(parent).map_err(|e| format!("create {}: {e}", parent.display()))?;
}
std::fs::write(path, self.encode()).map_err(|e| format!("write {}: {e}", path.display()))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SystemTheme {
Light,
Dark,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FileDialogFilter {
pub name: String,
pub extensions: Vec<String>,
}
impl FileDialogFilter {
pub fn new<I, S>(name: impl Into<String>, extensions: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
Self { name: name.into(), extensions: extensions.into_iter().map(Into::into).collect() }
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FileDialogOptions {
pub title: String,
pub directory: Option<PathBuf>,
pub file_name: Option<String>,
pub filters: Vec<FileDialogFilter>,
}
impl FileDialogOptions {
pub fn new(title: impl Into<String>) -> Self {
Self { title: title.into(), ..Self::default() }
}
pub fn with_directory(mut self, directory: impl Into<PathBuf>) -> Self {
self.directory = Some(directory.into());
self
}
pub fn with_file_name(mut self, name: impl Into<String>) -> Self {
self.file_name = Some(name.into());
self
}
pub fn with_filter<I, S>(mut self, name: impl Into<String>, extensions: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.filters.push(FileDialogFilter::new(name, extensions));
self
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum NotificationLevel {
Low,
#[default]
Normal,
Critical,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum NotificationTimeout {
#[default]
Default,
Never,
Milliseconds(u32),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Notification {
pub title: String,
pub body: String,
pub app_name: Option<String>,
pub app_id: Option<String>,
pub level: NotificationLevel,
pub silent: bool,
pub timeout: NotificationTimeout,
pub icon: Option<String>,
}
impl Notification {
pub fn new(title: impl Into<String>) -> Self {
Self {
title: title.into(),
body: String::new(),
app_name: None,
app_id: None,
level: NotificationLevel::Normal,
silent: false,
timeout: NotificationTimeout::Default,
icon: None,
}
}
pub fn with_body(mut self, body: impl Into<String>) -> Self {
self.body = body.into();
self
}
pub fn with_app_name(mut self, name: impl Into<String>) -> Self {
self.app_name = Some(name.into());
self
}
pub fn with_app_id(mut self, id: impl Into<String>) -> Self {
self.app_id = Some(id.into());
self
}
pub fn with_level(mut self, level: NotificationLevel) -> Self {
self.level = level;
self
}
pub fn with_silent(mut self, silent: bool) -> Self {
self.silent = silent;
self
}
pub fn with_timeout(mut self, timeout: NotificationTimeout) -> Self {
self.timeout = timeout;
self
}
pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
self.icon = Some(icon.into());
self
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TrayMenuItem {
Item { id: u64, label: String, enabled: bool },
Separator,
Submenu { label: String, items: Vec<TrayMenuItem> },
}
impl TrayMenuItem {
pub fn item(id: u64, label: impl Into<String>) -> Self {
Self::Item { id, label: label.into(), enabled: true }
}
pub fn item_enabled(id: u64, label: impl Into<String>, enabled: bool) -> Self {
Self::Item { id, label: label.into(), enabled }
}
pub fn separator() -> Self {
Self::Separator
}
pub fn submenu(label: impl Into<String>, items: Vec<TrayMenuItem>) -> Self {
Self::Submenu { label: label.into(), items }
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TrayConfig {
pub tooltip: String,
pub icon: Option<IconImage>,
pub menu: Vec<TrayMenuItem>,
pub open_menu_on_left_click: bool,
}
impl TrayConfig {
pub fn new(tooltip: impl Into<String>) -> Self {
Self { tooltip: tooltip.into(), ..Self::default() }
}
pub fn with_icon(mut self, icon: IconImage) -> Self {
self.icon = Some(icon);
self
}
pub fn with_menu(mut self, items: Vec<TrayMenuItem>) -> Self {
self.menu = items;
self
}
pub fn with_menu_item(mut self, item: TrayMenuItem) -> Self {
self.menu.push(item);
self
}
pub fn with_open_menu_on_left_click(mut self, open: bool) -> Self {
self.open_menu_on_left_click = open;
self
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TrayEvent {
Click { button: MouseButton },
Menu { id: u64 },
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ShortcutKey {
Char(char),
Enter,
Escape,
Tab,
Space,
Backspace,
Delete,
Insert,
Left,
Right,
Up,
Down,
Home,
End,
PageUp,
PageDown,
F(u8),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Shortcut {
pub modifiers: KeyModifiers,
pub key: ShortcutKey,
}
impl Shortcut {
pub const fn new(modifiers: KeyModifiers, key: ShortcutKey) -> Self {
Self { modifiers, key }
}
pub fn command(key: ShortcutKey) -> Self {
Self::new(KeyModifiers::command_only(), key)
}
pub fn ctrl(key: ShortcutKey) -> Self {
Self::new(KeyModifiers::ctrl_only(), key)
}
pub fn shift(key: ShortcutKey) -> Self {
Self::new(KeyModifiers::shift_only(), key)
}
pub fn ctrl_shift(key: ShortcutKey) -> Self {
Self::new(KeyModifiers(KeyModifiers::CTRL | KeyModifiers::SHIFT), key)
}
pub fn ctrl_alt(key: ShortcutKey) -> Self {
Self::new(KeyModifiers(KeyModifiers::CTRL | KeyModifiers::ALT), key)
}
pub fn alt(key: ShortcutKey) -> Self {
Self::new(KeyModifiers(KeyModifiers::ALT), key)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SingleInstanceConfig {
pub id: String,
pub forward_args: bool,
}
impl SingleInstanceConfig {
pub fn new(id: impl Into<String>) -> Self {
Self { id: id.into(), forward_args: true }
}
pub fn with_forward_args(mut self, forward: bool) -> Self {
self.forward_args = forward;
self
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GlobalShortcut {
pub id: u64,
pub shortcut: Shortcut,
}
impl GlobalShortcut {
pub fn new(id: u64, shortcut: Shortcut) -> Self {
Self { id, shortcut }
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NativeMenuCommand {
pub id: u64,
pub label: String,
pub shortcut: Option<Shortcut>,
pub enabled: bool,
pub checked: Option<bool>,
}
impl NativeMenuCommand {
pub fn new(id: u64, label: impl Into<String>) -> Self {
Self { id, label: label.into(), shortcut: None, enabled: true, checked: None }
}
pub fn with_shortcut(mut self, shortcut: Shortcut) -> Self {
self.shortcut = Some(shortcut);
self
}
pub fn with_enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}
pub fn with_checked(mut self, checked: bool) -> Self {
self.checked = Some(checked);
self
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum NativeMenuItem {
Command(NativeMenuCommand),
Separator,
Submenu(NativeMenu),
}
impl NativeMenuItem {
pub fn separator() -> Self {
Self::Separator
}
}
impl From<NativeMenuCommand> for NativeMenuItem {
fn from(command: NativeMenuCommand) -> Self {
Self::Command(command)
}
}
impl From<NativeMenu> for NativeMenuItem {
fn from(menu: NativeMenu) -> Self {
Self::Submenu(menu)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NativeMenu {
pub title: String,
pub items: Vec<NativeMenuItem>,
}
impl NativeMenu {
pub fn new(title: impl Into<String>) -> Self {
Self { title: title.into(), items: Vec::new() }
}
pub fn with_item(mut self, item: impl Into<NativeMenuItem>) -> Self {
self.items.push(item.into());
self
}
pub fn with_separator(mut self) -> Self {
self.items.push(NativeMenuItem::Separator);
self
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct NativeMenuBar {
pub menus: Vec<NativeMenu>,
}
impl NativeMenuBar {
pub fn new() -> Self {
Self::default()
}
pub fn with_menu(mut self, menu: NativeMenu) -> Self {
self.menus.push(menu);
self
}
pub fn command_ids(&self) -> Vec<u64> {
fn collect(menu: &NativeMenu, out: &mut Vec<u64>) {
for item in &menu.items {
match item {
NativeMenuItem::Command(command) => out.push(command.id),
NativeMenuItem::Submenu(submenu) => collect(submenu, out),
NativeMenuItem::Separator => {}
}
}
}
let mut out = Vec::new();
for menu in &self.menus {
collect(menu, &mut out);
}
out
}
pub fn accelerators(&self) -> Vec<(u64, Shortcut)> {
fn collect(menu: &NativeMenu, out: &mut Vec<(u64, Shortcut)>) {
for item in &menu.items {
match item {
NativeMenuItem::Command(command) => {
if let Some(shortcut) = command.shortcut {
out.push((command.id, shortcut));
}
}
NativeMenuItem::Submenu(submenu) => collect(submenu, out),
NativeMenuItem::Separator => {}
}
}
}
let mut out = Vec::new();
for menu in &self.menus {
collect(menu, &mut out);
}
out
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FileDragOutcome {
Dropped,
Cancelled,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FileDragOptions {
pub preview: Option<PathBuf>,
pub copy: bool,
}
impl Default for FileDragOptions {
fn default() -> Self {
Self { preview: None, copy: true }
}
}
impl FileDragOptions {
pub fn new() -> Self {
Self::default()
}
pub fn with_preview(mut self, path: impl Into<PathBuf>) -> Self {
self.preview = Some(path.into());
self
}
pub fn with_copy(mut self, copy: bool) -> Self {
self.copy = copy;
self
}
}
pub trait NativeMenuController {
fn set_item_enabled(&self, id: u64, enabled: bool);
fn set_item_checked(&self, id: u64, checked: bool);
fn set_visible(&self, visible: bool);
}
pub trait WindowShell {
fn metrics(&self) -> ShellMetrics;
fn request_redraw(&self);
fn set_title(&self, title: &str);
fn set_visible(&self, visible: bool);
fn is_visible(&self) -> bool {
true
}
fn set_ime_allowed(&self, allowed: bool);
fn set_ime_cursor_area(&self, rect: Rect);
fn set_cursor(&self, _cursor: CursorIcon) {}
fn set_fullscreen(&self, _fullscreen: bool) {}
fn is_fullscreen(&self) -> bool {
false
}
fn set_minimized(&self, _minimized: bool) {}
fn set_maximized(&self, _maximized: bool) {}
fn is_maximized(&self) -> bool {
false
}
fn focus_window(&self) {}
fn set_decorations(&self, _decorations: bool) {}
fn toggle_maximized(&self) {
self.set_maximized(!self.is_maximized());
}
fn start_dragging(&self) -> Result<(), String> {
Err("当前 shell 不支持窗口拖拽".to_string())
}
fn start_resize(&self, _direction: ResizeDirection) -> Result<(), String> {
Err("当前 shell 不支持窗口边缘缩放".to_string())
}
fn set_resizable(&self, _resizable: bool) {}
fn set_always_on_top(&self, _on_top: bool) {}
fn set_size(&self, _size: Size) {}
fn set_position(&self, _x: f32, _y: f32) {}
fn request_close(&self) {}
fn system_theme(&self) -> Option<SystemTheme> {
None
}
fn clipboard(&self) -> ClipboardHandle {
ClipboardHandle::noop()
}
fn native_menu(&self) -> Option<Rc<dyn NativeMenuController>> {
None
}
fn set_undecorated_shadow(&self, _shadow: bool) {}
fn high_contrast(&self) -> bool {
false
}
fn set_window_corners(&self, _corners: WindowCorners) {}
fn window_state(&self) -> Option<WindowState> {
None
}
fn pick_file(&self, _options: &FileDialogOptions) -> Option<PathBuf> {
None
}
fn pick_files(&self, _options: &FileDialogOptions) -> Option<Vec<PathBuf>> {
None
}
fn pick_folder(&self, _options: &FileDialogOptions) -> Option<PathBuf> {
None
}
fn save_file(&self, _options: &FileDialogOptions) -> Option<PathBuf> {
None
}
fn start_file_drag(&self, _paths: &[PathBuf], _options: &FileDragOptions) -> Result<FileDragOutcome, String> {
Err("当前 shell 不支持拖出文件".to_string())
}
fn show_notification(&self, _notification: &Notification) -> Result<(), String> {
Err("当前 shell 不支持系统通知".to_string())
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum ShellEvent {
CursorMoved {
position: Point,
},
MouseInput {
position: Point,
button: MouseButton,
pressed: bool,
modifiers: KeyModifiers,
},
CursorLeft,
Wheel {
position: Point,
delta: Point,
modifiers: KeyModifiers,
},
ModifiersChanged(KeyModifiers),
Keyboard {
key: KeyCode,
pressed: bool,
repeat: bool,
modifiers: KeyModifiers,
},
Focused(bool),
Ime(ImeEvent),
FileHovered(PathBuf),
FileHoverCancelled,
FileDropped(PathBuf),
ThemeChanged(SystemTheme),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ImeEvent {
Enabled,
Disabled,
Preedit(String, Option<(usize, usize)>),
Commit(String),
}
pub trait Clock {
fn now_ms(&self) -> u64;
}
#[derive(Clone, Debug)]
pub struct ManualClock {
now_ms: Cell<u64>,
}
impl ManualClock {
pub fn new(start_ms: u64) -> Self {
Self { now_ms: Cell::new(start_ms) }
}
pub fn set(&self, now_ms: u64) {
self.now_ms.set(now_ms);
}
pub fn advance(&self, delta_ms: u64) -> u64 {
let next = self.now_ms.get().saturating_add(delta_ms);
self.now_ms.set(next);
next
}
}
impl Default for ManualClock {
fn default() -> Self {
Self::new(0)
}
}
impl Clock for ManualClock {
fn now_ms(&self) -> u64 {
self.now_ms.get()
}
}
#[derive(Debug)]
pub struct SystemClock {
start: Instant,
}
impl SystemClock {
pub fn new() -> Self {
Self { start: Instant::now() }
}
}
impl Default for SystemClock {
fn default() -> Self {
Self::new()
}
}
impl Clock for SystemClock {
fn now_ms(&self) -> u64 {
self.start.elapsed().as_millis() as u64
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn manual_clock_is_deterministic() {
let clock = ManualClock::new(100);
assert_eq!(clock.now_ms(), 100);
assert_eq!(clock.advance(16), 116);
clock.set(500);
assert_eq!(clock.now_ms(), 500);
}
#[test]
fn metrics_clamp_invalid_values() {
let m = ShellMetrics::new(Size::new(0.0, -5.0), 0.0);
assert_eq!(m.logical_size, Size::new(1.0, 1.0));
assert_eq!(m.scale_factor, 0.01);
}
#[test]
fn metrics_from_physical_divides_by_dpr() {
let m = ShellMetrics::from_physical(1920, 1080, 2.0);
assert_eq!(m.logical_size, Size::new(960.0, 540.0));
assert_eq!(m.scale_factor, 2.0);
}
#[test]
fn window_state_roundtrip_and_validation() {
let state = WindowState { size: Size::new(1024.0, 720.0), position: Some((120.0, 80.0)), maximized: true };
let parsed = WindowState::parse(&state.encode()).expect("parse roundtrip");
assert_eq!(parsed, state);
let compact = WindowState::parse("mgui-window-state=1\nwidth=800\nheight=600\n").expect("compact");
assert_eq!(compact.position, None);
assert!(!compact.maximized);
assert!(WindowState::parse("mgui-window-state=2\nwidth=800\nheight=600").is_none());
assert!(WindowState::parse("mgui-window-state=1\nwidth=0\nheight=600").is_none());
}
#[test]
fn window_state_file_roundtrip() {
let path = std::env::temp_dir().join(format!(
"mgui-window-state-{}-{}.txt",
std::process::id(),
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0)
));
let state = WindowState { size: Size::new(1280.0, 800.0), position: Some((10.0, 20.0)), maximized: false };
state.save(&path).expect("save state");
assert_eq!(WindowState::load(&path), Some(state));
let _ = std::fs::remove_file(path);
}
#[test]
fn file_dialog_options_builder() {
let options = FileDialogOptions::new("Open")
.with_directory("/tmp")
.with_file_name("notes.txt")
.with_filter("Text", ["txt", "md"])
.with_filter("All", ["*"]);
assert_eq!(options.title, "Open");
assert_eq!(options.directory.as_deref(), Some(std::path::Path::new("/tmp")));
assert_eq!(options.file_name.as_deref(), Some("notes.txt"));
assert_eq!(options.filters.len(), 2);
assert_eq!(options.filters[0].name, "Text");
assert_eq!(options.filters[0].extensions, vec!["txt", "md"]);
}
#[test]
fn notification_builder_defaults_and_overrides() {
let n = Notification::new("Build finished");
assert_eq!(n.title, "Build finished");
assert!(n.body.is_empty());
assert_eq!(n.level, NotificationLevel::Normal);
assert_eq!(n.timeout, NotificationTimeout::Default);
assert!(!n.silent);
let n = n
.with_body("all green")
.with_app_id("studio.qianbai.mgui")
.with_level(NotificationLevel::Critical)
.with_timeout(NotificationTimeout::Never)
.with_silent(true)
.with_icon("dialog-information");
assert_eq!(n.body, "all green");
assert_eq!(n.app_id.as_deref(), Some("studio.qianbai.mgui"));
assert_eq!(n.level, NotificationLevel::Critical);
assert_eq!(n.timeout, NotificationTimeout::Never);
assert!(n.silent);
assert_eq!(n.icon.as_deref(), Some("dialog-information"));
}
#[test]
fn tray_config_keeps_menu_order() {
let icon = IconImage::from_rgba(2, 2, vec![255; 16]).expect("valid icon");
let tray = TrayConfig::new("mgui")
.with_icon(icon)
.with_menu_item(TrayMenuItem::item(1, "Show"))
.with_menu_item(TrayMenuItem::separator())
.with_menu_item(TrayMenuItem::submenu("More", vec![TrayMenuItem::item_enabled(2, "Disabled", false)]))
.with_open_menu_on_left_click(true);
assert_eq!(tray.tooltip, "mgui");
assert!(tray.icon.is_some());
assert_eq!(tray.menu.len(), 3);
assert!(matches!(tray.menu[0], TrayMenuItem::Item { id: 1, ref label, enabled: true } if label == "Show"));
assert_eq!(tray.menu[1], TrayMenuItem::Separator);
assert!(matches!(tray.menu[2], TrayMenuItem::Submenu { ref label, .. } if label == "More"));
assert!(tray.open_menu_on_left_click);
}
#[test]
fn tray_event_is_comparable() {
assert_eq!(TrayEvent::Menu { id: 7 }, TrayEvent::Menu { id: 7 });
assert_ne!(TrayEvent::Click { button: MouseButton::Left }, TrayEvent::Click { button: MouseButton::Right });
}
#[test]
fn shortcut_helpers_set_expected_modifiers() {
assert_eq!(Shortcut::command(ShortcutKey::Char('s')).modifiers, KeyModifiers::command_only());
assert_eq!(Shortcut::ctrl(ShortcutKey::Char('s')).modifiers, KeyModifiers::ctrl_only());
assert_eq!(
Shortcut::ctrl_shift(ShortcutKey::F(5)).modifiers,
KeyModifiers(KeyModifiers::CTRL | KeyModifiers::SHIFT)
);
assert_eq!(Shortcut::alt(ShortcutKey::Left).key, ShortcutKey::Left);
}
#[test]
fn native_menu_builder_collects_nested_accelerators() {
let menu = NativeMenuBar::new()
.with_menu(
NativeMenu::new("File")
.with_item(
NativeMenuCommand::new(1, "New").with_shortcut(Shortcut::command(ShortcutKey::Char('n'))),
)
.with_item(NativeMenuItem::separator())
.with_item(
NativeMenuCommand::new(2, "Exit").with_shortcut(Shortcut::command(ShortcutKey::Char('q'))),
)
.with_item(
NativeMenu::new("More").with_item(
NativeMenuCommand::new(3, "Deep")
.with_shortcut(Shortcut::ctrl_shift(ShortcutKey::F(7)))
.with_checked(true),
),
),
)
.with_menu(NativeMenu::new("Help"));
let accelerators = menu.accelerators();
assert_eq!(accelerators.len(), 3);
assert_eq!(accelerators[0].0, 1);
assert_eq!(accelerators[1].0, 2);
assert_eq!(accelerators[2].0, 3);
assert_eq!(accelerators[2].1.key, ShortcutKey::F(7));
assert_eq!(menu.menus.len(), 2);
assert_eq!(menu.command_ids(), vec![1, 2, 3]);
}
#[test]
fn global_shortcut_keeps_id_and_combo() {
let shortcut = Shortcut::ctrl_alt(ShortcutKey::Char('m'));
let global = GlobalShortcut::new(42, shortcut);
assert_eq!(global.id, 42);
assert_eq!(global.shortcut, shortcut);
}
#[test]
fn single_instance_config_defaults_to_forwarding() {
let config = SingleInstanceConfig::new("studio.example.app");
assert_eq!(config.id, "studio.example.app");
assert!(config.forward_args);
assert!(!config.with_forward_args(false).forward_args);
}
#[test]
fn file_drag_options_default_to_copy() {
let options = FileDragOptions::new().with_preview("/tmp/a.png").with_copy(false);
assert_eq!(options.preview.as_deref(), Some(std::path::Path::new("/tmp/a.png")));
assert!(!options.copy);
assert!(FileDragOptions::default().copy);
}
#[test]
fn resize_direction_hit_test_prioritizes_corners() {
let size = Size::new(200.0, 100.0);
assert_eq!(ResizeDirection::hit_test(Point::new(2.0, 2.0), size, 6.0), Some(ResizeDirection::NorthWest));
assert_eq!(ResizeDirection::hit_test(Point::new(198.0, 2.0), size, 6.0), Some(ResizeDirection::NorthEast));
assert_eq!(ResizeDirection::hit_test(Point::new(2.0, 98.0), size, 6.0), Some(ResizeDirection::SouthWest));
assert_eq!(ResizeDirection::hit_test(Point::new(100.0, 98.0), size, 6.0), Some(ResizeDirection::South));
assert_eq!(ResizeDirection::hit_test(Point::new(2.0, 50.0), size, 6.0), Some(ResizeDirection::West));
assert_eq!(ResizeDirection::hit_test(Point::new(100.0, 50.0), size, 6.0), None);
assert_eq!(ResizeDirection::hit_test(Point::new(-1.0, 50.0), size, 6.0), None);
assert_eq!(ResizeDirection::hit_test(Point::new(2.0, 2.0), size, 0.0), None);
}
}