//! GUI-independent commands applied to the city simulator. use std::{io, path::Path}; use icenet_core::{LinkKind, NodeId, TrafficClass}; use icenet_sim::{City, DeviceRole, metrics}; const CSV_FILE: &str = "icenet-metrics.csv"; const JSON_FILE: &str = "icenet-scenario.json"; /// Grab state for stable pointer dragging of one node. #[derive(Clone, Copy, Debug)] pub struct Drag { id: NodeId, node_x: f32, node_y: f32, pointer_x: f32, pointer_y: f32, } /// Mutable state of the standalone city editor. #[derive(Debug)] pub struct UiState { /// Deterministic offline city graph. pub city: City, /// Current sender in the sample graph. pub from: NodeId, /// Current recipient in the sample graph. pub to: NodeId, /// New node role selected in the editor. pub role: DeviceRole, /// New link technology selected in the editor. pub link_kind: LinkKind, /// Human-readable result of the last export action. pub last_export: String, drag: Option, } impl Default for UiState { fn default() -> Self { Self { city: City::demo(), from: NodeId(1), to: NodeId(3), role: DeviceRole::Client, link_kind: LinkKind::FastWireless, last_export: String::new(), drag: None, } } } impl UiState { /// Cycles through available sender or recipient IDs. pub fn cycle_endpoint(&mut self, sender: bool) { let current = if sender { self.from } else { self.to }; let ids: Vec = self.city.devices.iter().map(|d| d.id).collect(); if ids.is_empty() { return; } let index = ids.iter().position(|id| *id == current).unwrap_or(0); let next = ids[(index + 1) % ids.len()]; if sender { self.from = next; } else { self.to = next; } } /// Cycles among client, relay and backbone device roles. pub fn cycle_role(&mut self) { self.role = match self.role { DeviceRole::Client => DeviceRole::Relay, DeviceRole::Relay => DeviceRole::Backbone, DeviceRole::Backbone => DeviceRole::Client, }; } /// Cycles among simulated radio, Wi-Fi, cable and internet links. pub fn cycle_link_kind(&mut self) { self.link_kind = match self.link_kind { LinkKind::SlowRadio => LinkKind::FastWireless, LinkKind::FastWireless => LinkKind::Wired, LinkKind::Wired => LinkKind::Internet, LinkKind::Internet => LinkKind::SlowRadio, }; } /// Adds a new device and selects it as recipient. pub fn add_node(&mut self) { let label = format!("New {:?} {}", self.role, self.city.devices.len() + 1); self.to = self.city.add_device(label, self.role); } /// Adds a link between the selected endpoints, if valid. pub fn connect(&mut self) { self.city.add_link(self.from, self.to, self.link_kind); } /// Toggles a device's online state. pub fn toggle_node(&mut self, id: i32) { let update = self .city .devices .iter() .find(|d| d.id.0 == id as u64) .map(|device| (device.id, !device.online)); if let Some((id, online)) = update { self.city.set_device_online(id, online); } } /// Toggles a link by its visible index. pub fn toggle_link(&mut self, index: i32) { if let Ok(index) = usize::try_from(index) && let Some(enabled) = self.city.links.get(index).map(|link| !link.enabled) { self.city.set_link_enabled(index, enabled); } } /// Remembers the node and pointer position when a drag begins. pub fn start_drag(&mut self, id: i32, pointer_x: f32, pointer_y: f32) { let id = NodeId(id as u64); if let Some(device) = self.city.devices.iter().find(|device| device.id == id) { self.drag = Some(Drag { id, node_x: device.x, node_y: device.y, pointer_x, pointer_y, }); } } /// Moves the grabbed node by the pointer delta from the drag start. pub fn drag_to(&mut self, pointer_x: f32, pointer_y: f32) { if let Some(drag) = self.drag { self.city.move_device( drag.id, (drag.node_x + pointer_x - drag.pointer_x).clamp(20.0, 520.0), (drag.node_y + pointer_y - drag.pointer_y).clamp(20.0, 310.0), ); } } /// Releases the current drag, if any. pub fn end_drag(&mut self) { self.drag = None; } /// Sends synthetic text or bulk data; no real bytes leave this process. pub fn send(&mut self, bulk: bool) { let (kind, size) = if bulk { (TrafficClass::Bulk, 5 * 1024 * 1024) } else { (TrafficClass::Text, 128) }; self.city.send(self.from, self.to, kind, size); } /// Writes deterministic message metrics to `path`. /// /// # Errors /// Returns the underlying I/O error when the file cannot be written. pub fn export_csv(&mut self, path: &Path) -> io::Result<()> { std::fs::write(path, metrics::messages_csv(&self.city))?; self.last_export = format!("Exported {}", path.display()); Ok(()) } /// Writes the full scenario to `path` as deterministic JSON. /// /// # Errors /// Returns the underlying I/O error when the file cannot be written. pub fn export_json(&mut self, path: &Path) -> io::Result<()> { std::fs::write(path, metrics::scenario_json(&self.city))?; self.last_export = format!("Exported {}", path.display()); Ok(()) } /// Writes `icenet-metrics.csv` in the process working directory. pub fn export_default_csv(&mut self) { if let Err(error) = self.export_csv(Path::new(CSV_FILE)) { self.last_export = format!("Export failed: {error}"); } } /// Writes `icenet-scenario.json` in the process working directory. pub fn export_default_json(&mut self) { if let Err(error) = self.export_json(Path::new(JSON_FILE)) { self.last_export = format!("Export failed: {error}"); } } }