use std::sync::{Arc, Mutex};
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum WindowCommand {
Show,
Hide,
Redraw,
Focus,
SetTitle(String),
}
#[derive(Clone, Default)]
pub struct WindowCommandBus {
pending: Arc<Mutex<Vec<(String, WindowCommand)>>>,
}
impl WindowCommandBus {
pub fn new() -> Self {
Self::default()
}
pub fn send(&self, window: impl Into<String>, command: WindowCommand) {
if let Ok(mut pending) = self.pending.lock() {
pending.push((window.into(), command));
}
}
pub fn drain(&self) -> Vec<(String, WindowCommand)> {
match self.pending.lock() {
Ok(mut pending) => std::mem::take(&mut *pending),
Err(_) => Vec::new(),
}
}
pub fn is_empty(&self) -> bool {
self.pending.lock().map(|p| p.is_empty()).unwrap_or(true)
}
pub fn len(&self) -> usize {
self.pending.lock().map(|p| p.len()).unwrap_or(0)
}
}
pub fn route_window_commands(known: &[String], commands: Vec<(String, WindowCommand)>) -> Vec<(usize, WindowCommand)> {
let mut routed = Vec::with_capacity(commands.len());
for (name, command) in commands {
if name.is_empty() {
continue; }
if let Some(index) = known.iter().position(|slot| !slot.is_empty() && slot == &name) {
routed.push((index, command));
}
}
routed
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bus_keeps_order_and_drains_once() {
let bus = WindowCommandBus::new();
assert!(bus.is_empty());
bus.send("detail", WindowCommand::Redraw);
bus.send("inspector", WindowCommand::Hide);
assert_eq!(bus.len(), 2);
let drained = bus.drain();
assert_eq!(drained.len(), 2);
assert_eq!(drained[0].0, "detail");
assert_eq!(drained[1].1, WindowCommand::Hide);
assert!(bus.is_empty(), "drain 后队列必须为空");
assert!(bus.drain().is_empty());
}
#[test]
fn route_targets_only_known_window_names() {
let known = vec!["main".to_string(), "detail".to_string()];
let routed = route_window_commands(
&known,
vec![
("detail".to_string(), WindowCommand::Redraw),
("ghost".to_string(), WindowCommand::Hide),
("main".to_string(), WindowCommand::Focus),
],
);
assert_eq!(routed.len(), 2, "未知窗口名的命令应被丢弃");
assert_eq!(routed[0], (1, WindowCommand::Redraw), "detail → 槽位 1");
assert_eq!(routed[1], (0, WindowCommand::Focus), "main → 槽位 0");
}
#[test]
fn unnamed_slots_cannot_be_addressed() {
let known = vec![String::new(), "detail".to_string()];
let routed = route_window_commands(&known, vec![("".to_string(), WindowCommand::Redraw)]);
assert!(routed.is_empty(), "空名字不参与匹配(宿主侧也会跳过空名槽位)");
}
}