diff --git a/README.md b/README.md index 3910535..be9538a 100644 --- a/README.md +++ b/README.md @@ -26,8 +26,9 @@ model, range, or mode. ## Requirements - Rust 1.88.0 or newer -- A powered tinySA Basic, Ultra, or Ultra+ and a data-capable USB cable -- Permission to open the instrument's serial port +- For acquisition, a powered tinySA Basic, Ultra, or Ultra+ and a data-capable + USB cable +- For acquisition, permission to open the instrument's serial port Do not connect an unknown RF source directly to a tinySA. Use suitable external attenuation for transmitters and a DC block where a DC component may be present. @@ -51,6 +52,18 @@ Enter to advance, and `q` or Escape to quit. A successful scan displays a trace and writes a collision-safe `scan_*.csv` file in the current directory. CSV frequencies are in MHz and levels are in dBm. +Open an existing tiny-wb CSV directly in the interactive renderer without +enumerating or connecting to a device: + +```console +cargo run --release -- --view scan.csv +# The shorter `cargo run --release -- scan.csv` is equivalent. +``` + +On a plot, use `+`/`=` and `-` to zoom, Left/Right or `h`/`l` to pan, and +`0` or Home to restore the full frequency range. Plot bindings are configurable +under `[ui.bindings]`. + ## Configuration and documentation The selected settings are saved to `config.toml`, or to the path in diff --git a/config/default.toml b/config/default.toml index bc629dd..62ae1f9 100644 --- a/config/default.toml +++ b/config/default.toml @@ -52,6 +52,14 @@ poll_interval_ms = 16 chart_min_dbm = -128.0 chart_max_dbm = 0.0 +[ui.bindings] +# Plot navigation. Values are single characters or left/right/home. +zoom_in = ["+", "="] +zoom_out = ["-"] +pan_left = ["left", "h"] +pan_right = ["right", "l"] +reset_view = ["0", "home"] + [output] directory = "." filename_prefix = "scan" diff --git a/docs/architecture.md b/docs/architecture.md index fe710f4..0ff7862 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -19,8 +19,8 @@ widgets, port discovery, worker threads, or the application's working directory. | `src/mock/` | Opt-in bounded device simulation and stream server. | | `examples/mock-tinysa-server.rs` | Portable TCP listener for the mock, outside release binaries. | | `src/acquisition.rs` | Command ordering, progress events, frame decoding and resume attempts. | -| `src/export.rs` | CSV serialization to a writer and collision-safe file export. | -| `src/main.rs` | Load configuration, start diagnostics, enumerate ports and manage terminal lifetime. | +| `src/export.rs` | CSV parsing/serialization over I/O traits and collision-safe file export. | +| `src/main.rs` | Select acquisition/direct-view mode, load configuration, start diagnostics, enumerate ports when needed and manage terminal lifetime. | | `src/error.rs` | Application/UI boundary errors with original context. | | `src/scan.rs` | Open the configured connection, adapt core events to shared progress, and export successful acquisitions. | | `src/ui/mod.rs` | Screen transitions, keyboard handling, worker startup and progress reconciliation. | @@ -70,6 +70,7 @@ the original error's message instead of a second exhaustive mapping. SelectingConnection -> SelectingScan -> Scanning -> Complete -> exit | | | +------------------+-------------+-> Error -> exit +CSV file -------------------------------------> Complete ``` The constructor takes configuration and enumerated ports as values, without @@ -77,6 +78,10 @@ reading files. Selection is clamped before rendering, including empty lists. Before a scan starts, the controller validates the complete selected settings and request, atomically saves settings, then starts a worker. The controller reconciles worker status before drawing; rendering does not consume samples. +The complete screen owns one named plot with an independent frequency viewport. +Zooming and panning mutate only that viewport, not sample data. This plot +boundary can grow into a tabbed collection without coupling CSV parsing or +acquisition to Ratatui. The terminal guard restores terminal modes on ordinary returns and unwinding. Configuration, logging and enumeration errors occur before terminal takeover. diff --git a/docs/configuration.md b/docs/configuration.md index 4cc81f5..70537e2 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -41,7 +41,7 @@ rate must be in `serial.baudrates`; points and repeat must fit the configured bo | --- | --- | | `serial` | Read timeout and command/settling/pre-scan delays in milliseconds; bounded text response size in bytes; baud-rate choices and preferred ports. | | `scan` | Raw zero offset in dB, explicit ZS406 Ultra-mode opt-in, frequency/sample keyboard steps, sample/repeat limits, frequency-axis convention, and legacy pre-scan toggle. | -| `ui` | Event polling interval in milliseconds and finite increasing chart bounds in dBm. | +| `ui` | Event polling interval in milliseconds, finite increasing chart bounds in dBm, and plot navigation bindings. | | `output` | CSV directory, filename prefix, and optional column header. | | `logging` | Logger filter expression and destination directory. | @@ -81,6 +81,20 @@ files that explicitly contain `frequency_axis = "inclusive"` keep their old labels; partial configurations that omit the key adopt the corrected default. See [frequency assignment](usb-protocol.md#frequency-assignment). +`[ui.bindings]` configures the result/CSV renderer. Each action is a nonempty +array of unique bindings. A binding is one printable character or `left`, +`right`, or `home`; bindings cannot overlap between actions and `q` remains +reserved for exit. The defaults are: + +```toml +[ui.bindings] +zoom_in = ["+", "="] +zoom_out = ["-"] +pan_left = ["left", "h"] +pan_right = ["right", "l"] +reset_view = ["0", "home"] +``` + The preparatory `scan START STOP 290 101` remains enabled by default with `scan.legacy_pre_scan = true` for compatibility. Its undocumented output mask is not a tunable protocol contract. Disable the step only after checking the diff --git a/docs/library.md b/docs/library.md index 216d448..20e28fb 100644 --- a/docs/library.md +++ b/docs/library.md @@ -29,7 +29,10 @@ or inject your own adapter. Transport deadlines belong to the adapter; an arbitrary blocking `Read` implementation cannot be interrupted by the shell. `acquisition::acquire` accepts a validated Basic `ScanRequest`, scan/timing settings and a progress callback, and returns samples without opening files. -`export::write_csv` writes those samples to any writer. +`export::write_csv` writes those samples to any writer. `export::read_csv` +loads the same two-column, optionally headed format from any `BufRead` source; +it validates finite values and nondecreasing MHz frequencies without depending +on the terminal renderer. ```rust use tiny_wb::{config::Config, connection::open_connection, diff --git a/docs/testing.md b/docs/testing.md index 099d81c..fe755a3 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -16,8 +16,8 @@ cargo test --locked --doc | Protocol | Basic mode boundaries, point/repeat validation, truncated/extra records, alignment, closing brace, binary delimiter bytes, little-endian levels, Basic/Ultra raw offsets, both frequency-axis conventions, and firmware integer/single-precision frequency rounding. | | Transport | One-byte/fragmented reads, multiple responses in one read, retained bytes after prompts, partial writes, invalid command lines, EOF, timeout, response size limits and raw-body framing. | | Acquisition | Exact command ordering, optional legacy pre-scan, progress completion, successful decoding, resume after malformed frames, and preservation of acquisition plus recovery errors. | -| UI/startup | Missing/stale ports, numeric overflow and clamping, configured baud rates, navigation, one-time result transfer, every screen on small/headless terminals, and invalid config before terminal startup. | -| Export | Header/units, deterministic CSV values, propagated write failures and collision-safe output files. | +| UI/startup | Missing/stale ports, numeric overflow and clamping, configured baud rates, sample-resolution plot zoom, adaptive axis precision, pan/reset and clamping, navigation, direct CSV startup failures, one-time result transfer, every screen on small/headless terminals, and invalid config before terminal startup. | +| Export | Header/units, header and headerless parsing, malformed/unordered input, deterministic CSV values, propagated write failures and collision-safe output files. | `Shell` accepts `T: Read + Write`. To add a regression, provide a transcript reader and capture its writes; vary read chunk size so a token may cross any diff --git a/docs/tiny-wb-operations.md b/docs/tiny-wb-operations.md index 312781e..9e6b9a6 100644 --- a/docs/tiny-wb-operations.md +++ b/docs/tiny-wb-operations.md @@ -47,8 +47,16 @@ cargo build --release ./target/release/tiny-wb ``` -The program does not currently expose meaningful command-line options; it -starts the interactive terminal immediately. Run it from the working directory for your settings and output, or set +With no arguments the program starts the acquisition workflow. To inspect a +previous export without enumerating a serial device or starting acquisition, +open its renderer directly: + +```console +./target/release/tiny-wb --view scan.csv +# A positional path is equivalent: ./target/release/tiny-wb scan.csv +``` + +Run it from the working directory for your settings and output, or set `TINY_WB_CONFIG` to another configuration path. See [configuration](configuration.md). ### Serial permissions @@ -108,6 +116,14 @@ scatter trace. Its Y axis defaults to −128–0 dBm and uses the configured `ui and `ui.chart_max_dbm` bounds. Values outside those bounds are clipped visually even though CSV data may contain them. +The frequency axis is labeled in MHz. `+` or `=` zooms in, `-` zooms out, +Left/Right or `h`/`l` pans by a quarter of the visible span, and `0` or Home +restores the full range. Zoom and pan stay within the frequencies present in +the plot. Maximum zoom follows the finest positive sample spacing in the loaded +data, and frequency labels add decimal places as the visible range narrows. +These bindings are configurable under `[ui.bindings]`; `q`, Escape, or Enter +exits the renderer. + ## Files ### `config.toml` @@ -144,6 +160,9 @@ resume response. Failed writes are reported and incomplete files are removed when possible. Enable `output.include_header` for named columns. Choose the frequency-label convention explicitly after reviewing the [frequency assignment notes](usb-protocol.md#frequency-assignment). +The direct renderer accepts this header or headerless files, ignores blank +lines, and reports malformed, non-finite, empty, or decreasing-frequency data +with its CSV line number before taking over the terminal. ### Logs diff --git a/src/config.rs b/src/config.rs index 6fce58c..36dc776 100644 --- a/src/config.rs +++ b/src/config.rs @@ -163,6 +163,27 @@ pub struct UiConfig { pub chart_min_dbm: f64, /// Chart upper bound, in dBm. pub chart_max_dbm: f64, + /// Configurable keyboard shortcuts used by the completed-scan renderer. + pub bindings: PlotBindings, +} + +/// Keyboard bindings for navigating a rendered frequency plot. +/// +/// Each entry is either one Unicode character or one of `left`, `right`, and +/// `home`. Bindings are case-sensitive for characters and must not overlap. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct PlotBindings { + /// Keys that halve the visible frequency span. + pub zoom_in: Vec, + /// Keys that double the visible frequency span. + pub zoom_out: Vec, + /// Keys that move the viewport toward lower frequencies. + pub pan_left: Vec, + /// Keys that move the viewport toward higher frequencies. + pub pan_right: Vec, + /// Keys that restore the complete frequency range. + pub reset_view: Vec, } /// CSV settings; paths are relative to the working directory unless absolute. @@ -318,6 +339,31 @@ impl Config { && self.ui.chart_min_dbm < self.ui.chart_max_dbm, "UI chart bounds must be finite and increasing", )?; + let binding_groups = [ + &self.ui.bindings.zoom_in, + &self.ui.bindings.zoom_out, + &self.ui.bindings.pan_left, + &self.ui.bindings.pan_right, + &self.ui.bindings.reset_view, + ]; + require( + binding_groups.iter().all(|group| !group.is_empty()), + "each UI plot action must have at least one binding", + )?; + let mut bindings: Vec<&str> = Vec::new(); + for binding in binding_groups.into_iter().flatten() { + let valid = matches!(binding.as_str(), "left" | "right" | "home") + || (binding.chars().count() == 1 && !binding.chars().any(char::is_control)); + require( + valid && binding != "q", + "UI plot bindings must be one printable character or left/right/home; q is reserved", + )?; + require( + !bindings.contains(&binding.as_str()), + "UI plot bindings must not overlap", + )?; + bindings.push(binding); + } require(!self.output.filename_prefix.is_empty() && self.output.filename_prefix.len() <= 64 && self.output.filename_prefix.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_' || c == b'-'), "output.filename_prefix must contain 1–64 ASCII letters, digits, underscores or hyphens")?; require( !self.output.directory.as_os_str().is_empty() @@ -412,6 +458,9 @@ mod tests { "[scan]\nfrequency_axis = 'unknown'", "[ui]\nchart_min_dbm = nan", "[ui]\nchart_min_dbm = 1.0", + "[ui.bindings]\nzoom_in = []", + "[ui.bindings]\nzoom_in = ['q']", + "[ui.bindings]\nzoom_in = ['left']", "[output]\nfilename_prefix = '../scan'", "[logging]\nfilter = ''", "[serial]\ntimeuot_ms = 5", diff --git a/src/error.rs b/src/error.rs index 8e351ed..7ef4d41 100644 --- a/src/error.rs +++ b/src/error.rs @@ -3,6 +3,9 @@ /// Errors surfaced during startup or acquisition. #[derive(Debug, thiserror::Error)] pub(crate) enum AppError { + /// Command-line arguments do not select a supported startup mode. + #[error("{0}")] + Usage(String), /// Configuration read, validation or persistence failed. #[error(transparent)] Config(#[from] tiny_wb::config::ConfigError), @@ -15,6 +18,14 @@ pub(crate) enum AppError { /// Filesystem or terminal I/O failed. #[error("I/O: {0}")] Io(#[from] std::io::Error), + /// A requested scan CSV could not be opened or decoded. + #[error("cannot load CSV {}: {source}", path.display())] + Csv { + /// Requested input path. + path: std::path::PathBuf, + /// File or data error. + source: std::io::Error, + }, /// Acquisition failed, potentially including a failed resume attempt. #[error(transparent)] Acquisition(#[from] tiny_wb::acquisition::AcquisitionError), diff --git a/src/export.rs b/src/export.rs index cf50b1e..eb38181 100644 --- a/src/export.rs +++ b/src/export.rs @@ -4,10 +4,85 @@ use crate::{config::OutputConfig, protocol::Sample}; use chrono::Local; use std::{ fs::{self, OpenOptions}, - io::{self, BufWriter, Write}, + io::{self, BufRead, BufWriter, Write}, path::PathBuf, }; +/// Read samples from tiny-wb's two-column CSV representation. +/// +/// Both headerless exports and files beginning with +/// `frequency_MHz,level_dBm` are accepted. Blank lines are ignored. Every data +/// row must contain exactly two finite numbers and frequencies must be in +/// nondecreasing order. An empty file is rejected. +/// +/// # Errors +/// Returns [`io::ErrorKind::InvalidData`] with a line number for malformed CSV. +pub fn read_csv(reader: impl BufRead) -> io::Result> { + let mut samples = Vec::new(); + let mut saw_header = false; + for (index, line) in reader.lines().enumerate() { + let line_number = index + 1; + let line = line?; + let line = line.trim(); + if line.is_empty() { + continue; + } + if samples.is_empty() && !saw_header && line == "frequency_MHz,level_dBm" { + saw_header = true; + continue; + } + let mut columns = line.split(','); + let frequency = columns.next(); + let level = columns.next(); + if frequency.is_none() || level.is_none() || columns.next().is_some() { + return Err(invalid_csv(line_number, "expected exactly two columns")); + } + let parse = |value: &str, name: &str| { + value.trim().parse::().map_err(|_| { + invalid_csv( + line_number, + &format!("invalid {name} number `{}`", value.trim()), + ) + }) + }; + let frequency_mhz = parse(frequency.unwrap_or_default(), "frequency")?; + let level_dbm = parse(level.unwrap_or_default(), "level")?; + if !frequency_mhz.is_finite() || !level_dbm.is_finite() { + return Err(invalid_csv(line_number, "values must be finite")); + } + if samples + .last() + .is_some_and(|sample: &Sample| sample.frequency_mhz > frequency_mhz) + { + return Err(invalid_csv( + line_number, + "frequencies must be in nondecreasing order", + )); + } + samples.push(Sample { + frequency_mhz, + level_dbm, + }); + } + if samples.is_empty() { + return Err(invalid_csv(0, "file contains no samples")); + } + Ok(samples) +} + +/// Build a bounded, contextual malformed-CSV error. +fn invalid_csv(line: usize, message: &str) -> io::Error { + let location = if line == 0 { + String::new() + } else { + format!(" at line {line}") + }; + io::Error::new( + io::ErrorKind::InvalidData, + format!("invalid scan CSV{location}: {message}"), + ) +} + /// Write sample values to any writer, optionally with an explicit units header. /// /// The caller decides when/how to open and flush a file. Every write error is @@ -95,6 +170,34 @@ mod tests { ); } + #[test] + fn csv_reader_accepts_header_and_headerless_data() { + let expected = vec![Sample { + frequency_mhz: 240.5, + level_dbm: -64.25, + }]; + assert_eq!( + read_csv(&b"frequency_MHz,level_dBm\n240.5,-64.25\n"[..]).unwrap(), + expected + ); + assert_eq!(read_csv(&b"\n240.5, -64.25\n"[..]).unwrap(), expected); + } + + #[test] + fn csv_reader_rejects_empty_malformed_and_unordered_data() { + for input in [ + "", + "frequency_MHz,level_dBm\n", + "240\n", + "MHz,dBm\n", + "240,NaN\n", + "241,-1\n240,-2\n", + ] { + let error = read_csv(input.as_bytes()).unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::InvalidData, "{input:?}"); + } + } + #[test] fn scans_do_not_overwrite_each_other() { let directory = std::env::temp_dir().join(format!("tiny-wb-export-{}", std::process::id())); diff --git a/src/main.rs b/src/main.rs index e2a416c..785c9c2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,9 +7,34 @@ mod ui; use error::AppError; use flexi_logger::{FileSpec, Logger, WriteMode}; -use std::path::PathBuf; +use std::{ffi::OsString, fs::File, io::BufReader, path::PathBuf}; use tiny_wb::config::{Backend, Config}; +/// Startup route selected by the small command-line surface. +#[derive(Debug, PartialEq, Eq)] +enum StartMode { + /// Configure and acquire a new scan. + Acquire, + /// Open an existing CSV directly in the renderer. + View(PathBuf), + /// Print command help without loading configuration. + Help, +} + +/// Interpret zero arguments as acquisition and one CSV path as direct viewing. +fn parse_start_mode(args: impl IntoIterator) -> Result { + let args: Vec = args.into_iter().collect(); + match args.as_slice() { + [] => Ok(StartMode::Acquire), + [flag] if flag == "-h" || flag == "--help" => Ok(StartMode::Help), + [flag, path] if flag == "--view" => Ok(StartMode::View(PathBuf::from(path))), + [path] if !path.to_string_lossy().starts_with('-') => { + Ok(StartMode::View(PathBuf::from(path))) + } + _ => Err(AppError::Usage("usage: tiny-wb [--view] [SCAN.csv]".into())), + } +} + /// Restore the terminal on ordinary errors and unwinding after initialization. struct TerminalSession; @@ -22,6 +47,11 @@ impl Drop for TerminalSession { /// Load and validate settings before taking ownership of the user's terminal. fn main() -> Result<(), AppError> { color_eyre::install()?; + let mode = parse_start_mode(std::env::args_os().skip(1))?; + if mode == StartMode::Help { + println!("tiny-wb [--view] [SCAN.csv]\n\nWith no CSV, acquire a scan. With a CSV path, open the plot renderer directly."); + return Ok(()); + } let config_path = std::env::var_os("TINY_WB_CONFIG") .map(PathBuf::from) .unwrap_or_else(|| PathBuf::from("config.toml")); @@ -33,15 +63,64 @@ fn main() -> Result<(), AppError> { .log_to_file(FileSpec::default().directory(&config.logging.directory)) .write_mode(WriteMode::BufferAndFlush) .start()?; - let ports = match config.connection.backend { - Backend::Serial => serialport::available_ports()?, - Backend::Tcp => vec![serialport::SerialPortInfo { - port_name: format!("tcp://{}", config.connection.tcp_address), - port_type: serialport::SerialPortType::Unknown, - }], + let mut app = match mode { + StartMode::Acquire => { + let ports = match config.connection.backend { + Backend::Serial => serialport::available_ports()?, + Backend::Tcp => vec![serialport::SerialPortInfo { + port_name: format!("tcp://{}", config.connection.tcp_address), + port_type: serialport::SerialPortType::Unknown, + }], + }; + ui::App::new(ports, config, config_path) + } + StartMode::View(path) => { + let file = File::open(&path).map_err(|source| AppError::Csv { + path: path.clone(), + source, + })?; + let samples = tiny_wb::export::read_csv(BufReader::new(file)).map_err(|source| { + AppError::Csv { + path: path.clone(), + source, + } + })?; + ui::App::viewer( + config, + path, + samples + .into_iter() + .map(|sample| (sample.frequency_mhz, sample.level_dbm)) + .collect(), + ) + } + StartMode::Help => unreachable!("help returned before configuration loading"), }; let _session = TerminalSession; let terminal = ratatui::try_init()?; - ui::App::new(ports, config, config_path).run(terminal)?; + app.run(terminal)?; Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn command_line_selects_acquisition_help_and_csv_viewer() { + assert_eq!(parse_start_mode([]).unwrap(), StartMode::Acquire); + assert_eq!( + parse_start_mode([OsString::from("--help")]).unwrap(), + StartMode::Help + ); + assert_eq!( + parse_start_mode([OsString::from("scan.csv")]).unwrap(), + StartMode::View(PathBuf::from("scan.csv")) + ); + assert_eq!( + parse_start_mode([OsString::from("--view"), OsString::from("scan.csv")]).unwrap(), + StartMode::View(PathBuf::from("scan.csv")) + ); + assert!(parse_start_mode([OsString::from("--unknown")]).is_err()); + } +} diff --git a/src/ui/mod.rs b/src/ui/mod.rs index d0103dd..20fa221 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -16,8 +16,8 @@ use ratatui::{ use serialport::SerialPortInfo; pub(crate) use state::App; use state::{ - AppState, BaudRateList, InputDirection, MenuItems, NumericInput, PortList, SelectedConnection, - SelectedScan, + AppState, BaudRateList, InputDirection, MenuItems, NumericInput, Plot, PortList, + SelectedConnection, SelectedScan, }; use std::{path::PathBuf, thread, time::Duration}; use strum::EnumCount; @@ -53,12 +53,20 @@ impl App { ), repeat: NumericInput::new(config.repeat, 1, 1, config.scan.max_repeat), scan_state: ScanState::default(), - return_data: Vec::new(), + plot: None, config, config_path, } } + /// Construct the renderer directly from an already parsed CSV plot. + pub(crate) fn viewer(config: Config, source: PathBuf, data: Vec<(f64, f64)>) -> Self { + let mut app = Self::new(Vec::new(), config, PathBuf::new()); + app.flow_state = AppState::Complete; + app.plot = Some(Plot::new(source.display().to_string(), data)); + app + } + /// Drive events and rendering; worker state is reconciled before each frame. pub(crate) fn run( &mut self, @@ -139,6 +147,9 @@ impl App { if key.kind != KeyEventKind::Press { return Ok(()); } + if matches!(self.flow_state, AppState::Complete) { + return self.handle_plot_key(key.code); + } match key.code { KeyCode::Char('q') | KeyCode::Esc => self.should_quit = true, KeyCode::Char('j') | KeyCode::Down => self.change_cursor_position(InputDirection::Down), @@ -154,6 +165,38 @@ impl App { Ok(()) } + /// Apply configured navigation keys on the plot screen. + fn handle_plot_key(&mut self, code: KeyCode) -> Result<(), UiError> { + if matches!(code, KeyCode::Char('q') | KeyCode::Esc | KeyCode::Enter) { + self.should_quit = true; + return Ok(()); + } + let bindings = &self.config.ui.bindings; + let action = if binding_matches(&code, &bindings.zoom_in) { + Some(PlotAction::ZoomIn) + } else if binding_matches(&code, &bindings.zoom_out) { + Some(PlotAction::ZoomOut) + } else if binding_matches(&code, &bindings.pan_left) { + Some(PlotAction::PanLeft) + } else if binding_matches(&code, &bindings.pan_right) { + Some(PlotAction::PanRight) + } else if binding_matches(&code, &bindings.reset_view) { + Some(PlotAction::Reset) + } else { + None + }; + if let (Some(plot), Some(action)) = (self.plot.as_mut(), action) { + match action { + PlotAction::ZoomIn => plot.viewport.zoom_in(), + PlotAction::ZoomOut => plot.viewport.zoom_out(), + PlotAction::PanLeft => plot.viewport.pan(InputDirection::Left), + PlotAction::PanRight => plot.viewport.pan(InputDirection::Right), + PlotAction::Reset => plot.viewport.reset(), + } + } + Ok(()) + } + /// Apply vertical input to the selected field. fn change_cursor_position(&mut self, direction: InputDirection) { match self.flow_state { @@ -261,7 +304,8 @@ impl App { if matches!(self.flow_state, AppState::Scanning) { match self.scan_state.status() { ScanStatus::Complete => { - self.return_data = self.scan_state.take_samples()?; + let data = self.scan_state.take_samples()?; + self.plot = Some(Plot::new(self.scan_state.message(), data)); self.flow_state = AppState::Complete; } ScanStatus::Failed => self.flow_state = AppState::Error, @@ -272,6 +316,35 @@ impl App { } } +/// Renderer action resolved from configured key names. +#[derive(Clone, Copy)] +enum PlotAction { + /// Decrease the visible span. + ZoomIn, + /// Increase the visible span. + ZoomOut, + /// Shift toward lower frequencies. + PanLeft, + /// Shift toward higher frequencies. + PanRight, + /// Restore the full span. + Reset, +} + +/// Match a terminal key against validated character/special-key names. +fn binding_matches(code: &KeyCode, bindings: &[String]) -> bool { + bindings + .iter() + .any(|binding| match (binding.as_str(), code) { + ("left", KeyCode::Left) | ("right", KeyCode::Right) | ("home", KeyCode::Home) => true, + (value, KeyCode::Char(character)) => { + let mut chars = value.chars(); + chars.next() == Some(*character) && chars.next().is_none() + } + _ => false, + }) +} + #[cfg(test)] mod tests { use super::*; @@ -340,7 +413,7 @@ mod tests { .complete(PathBuf::from("scan.csv"), vec![(240.0, -64.0)]); app.refresh_scan().unwrap(); assert!(matches!(app.flow_state, AppState::Complete)); - assert_eq!(app.return_data, vec![(240.0, -64.0)]); + assert_eq!(app.plot.as_ref().unwrap().data, vec![(240.0, -64.0)]); app.refresh_scan().unwrap(); app.flow_state = AppState::Scanning; app.scan_state.fail("disconnected"); @@ -348,12 +421,42 @@ mod tests { assert!(matches!(app.flow_state, AppState::Error)); } + #[test] + fn configured_plot_keys_zoom_pan_and_reset() { + let mut config = Config::default(); + config.ui.bindings.zoom_in = vec!["z".into()]; + let mut app = App::viewer( + config, + PathBuf::from("scan.csv"), + vec![ + (100.0, -1.0), + (125.0, -1.5), + (150.0, -2.0), + (175.0, -1.5), + (200.0, -1.0), + ], + ); + app.handle_start_keys(KeyEvent::new(KeyCode::Char('+'), KeyModifiers::NONE)) + .unwrap(); + assert_eq!(app.plot.as_ref().unwrap().viewport.bounds(), [100.0, 200.0]); + app.handle_start_keys(KeyEvent::new(KeyCode::Char('z'), KeyModifiers::NONE)) + .unwrap(); + assert_eq!(app.plot.as_ref().unwrap().viewport.bounds(), [125.0, 175.0]); + app.handle_start_keys(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE)) + .unwrap(); + assert_eq!(app.plot.as_ref().unwrap().viewport.bounds(), [137.5, 187.5]); + app.handle_start_keys(KeyEvent::new(KeyCode::Home, KeyModifiers::NONE)) + .unwrap(); + assert_eq!(app.plot.as_ref().unwrap().viewport.bounds(), [100.0, 200.0]); + } + #[test] fn every_screen_renders_without_a_physical_terminal() { for (width, height) in [(120, 40), (40, 10), (1, 1)] { let mut app = app(); app.init_config().unwrap(); app.init_progress().unwrap(); + app.plot = Some(Plot::new("test.csv", vec![(240.0, -64.0)])); let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); for screen in [ AppState::default(), diff --git a/src/ui/state.rs b/src/ui/state.rs index 4c5b087..03a7196 100644 --- a/src/ui/state.rs +++ b/src/ui/state.rs @@ -49,8 +49,123 @@ pub(crate) struct App { pub(crate) config: Config, /// Explicit settings path selected at startup. pub(crate) config_path: PathBuf, - /// Completed samples owned by the UI, in MHz and dBm. - pub(crate) return_data: Vec<(f64, f64)>, + /// Plot currently shown by the renderer; a collection boundary for future tabs. + pub(crate) plot: Option, +} + +/// One named plot and its independently navigable frequency viewport. +#[derive(Debug)] +pub(crate) struct Plot { + /// User-facing source name. + pub(crate) label: String, + /// Samples in MHz and dBm, ordered by frequency. + pub(crate) data: Vec<(f64, f64)>, + /// Current and complete horizontal bounds. + pub(crate) viewport: FrequencyViewport, +} + +impl Plot { + /// Construct a plot whose initial viewport contains all samples. + pub(crate) fn new(label: impl Into, data: Vec<(f64, f64)>) -> Self { + let viewport = FrequencyViewport::from_samples(&data); + Self { + label: label.into(), + data, + viewport, + } + } +} + +/// Horizontal chart bounds with zoom and pan clamped to the source data. +#[derive(Debug, Clone, Copy, PartialEq)] +pub(crate) struct FrequencyViewport { + /// Complete lower bound, in MHz. + full_min: f64, + /// Complete upper bound, in MHz. + full_max: f64, + /// Visible lower bound, in MHz. + visible_min: f64, + /// Visible upper bound, in MHz. + visible_max: f64, + /// Smallest permitted visible span. + min_span: f64, +} + +impl FrequencyViewport { + /// Derive safe increasing chart bounds from an ordered sample set. + fn from_samples(samples: &[(f64, f64)]) -> Self { + let first = samples.first().map_or(0.0, |sample| sample.0); + let last = samples.last().map_or(first, |sample| sample.0); + let (full_min, full_max) = if first < last { + (first, last) + } else { + let padding = (first.abs() * 1e-6).max(0.001); + (first - padding, first + padding) + }; + let span = full_max - full_min; + let sample_spacing = samples + .windows(2) + .filter_map(|pair| { + let spacing = pair[1].0 - pair[0].0; + (spacing > 0.0).then_some(spacing) + }) + .min_by(f64::total_cmp); + Self { + full_min, + full_max, + visible_min: full_min, + visible_max: full_max, + min_span: sample_spacing.unwrap_or(span).min(span).max(f64::EPSILON), + } + } + + /// Current `[minimum, maximum]` bounds in MHz. + pub(crate) fn bounds(self) -> [f64; 2] { + [self.visible_min, self.visible_max] + } + + /// Halve the visible span around its center, down to the resolution floor. + pub(crate) fn zoom_in(&mut self) { + self.set_span(((self.visible_max - self.visible_min) / 2.0).max(self.min_span)); + } + + /// Double the visible span around its center, up to the complete range. + pub(crate) fn zoom_out(&mut self) { + self.set_span(((self.visible_max - self.visible_min) * 2.0).min(self.full_span())); + } + + /// Move by one quarter of the visible span and clamp at the data edge. + pub(crate) fn pan(&mut self, direction: InputDirection) { + let span = self.visible_max - self.visible_min; + let shift = match direction { + InputDirection::Left => -span / 4.0, + InputDirection::Right => span / 4.0, + _ => return, + }; + let new_min = (self.visible_min + shift).clamp(self.full_min, self.full_max - span); + self.visible_min = new_min; + self.visible_max = new_min + span; + } + + /// Restore the complete source range. + pub(crate) fn reset(&mut self) { + self.visible_min = self.full_min; + self.visible_max = self.full_max; + } + + /// Update the visible span while retaining the current center when possible. + fn set_span(&mut self, span: f64) { + let span = span.clamp(self.min_span, self.full_span()); + let center = (self.visible_min + self.visible_max) / 2.0; + let new_min = (center - span / 2.0).clamp(self.full_min, self.full_max - span); + self.visible_min = new_min; + self.visible_max = new_min + span; + } + + /// Width of the complete frequency range. + fn full_span(self) -> f64 { + self.full_max - self.full_min + } } #[derive(Debug)] @@ -317,6 +432,53 @@ mod tests { assert_eq!(field.value(), 0); } + #[test] + fn viewport_zooms_pans_clamps_and_resets() { + let mut viewport = FrequencyViewport::from_samples(&[ + (100.0, -1.0), + (125.0, -1.5), + (150.0, -2.0), + (175.0, -1.5), + (200.0, -1.0), + ]); + assert_eq!(viewport.bounds(), [100.0, 200.0]); + viewport.zoom_in(); + assert_eq!(viewport.bounds(), [125.0, 175.0]); + viewport.pan(InputDirection::Right); + assert_eq!(viewport.bounds(), [137.5, 187.5]); + for _ in 0..20 { + viewport.pan(InputDirection::Right); + } + assert_eq!(viewport.bounds(), [150.0, 200.0]); + viewport.zoom_out(); + assert_eq!(viewport.bounds(), [100.0, 200.0]); + viewport.reset(); + assert_eq!(viewport.bounds(), [100.0, 200.0]); + } + + #[test] + fn maximum_zoom_uses_the_finest_positive_sample_spacing() { + let mut viewport = FrequencyViewport::from_samples(&[ + (100.0, -1.0), + (100.0, -2.0), + (100.01, -3.0), + (100.02, -4.0), + (200.0, -5.0), + ]); + for _ in 0..32 { + viewport.zoom_in(); + } + let [minimum, maximum] = viewport.bounds(); + assert!(((maximum - minimum) - 0.01).abs() < 1e-12); + } + + #[test] + fn viewport_for_one_sample_still_has_increasing_bounds() { + let viewport = FrequencyViewport::from_samples(&[(240.0, -64.0)]); + let [minimum, maximum] = viewport.bounds(); + assert!(minimum < 240.0 && maximum > 240.0); + } + #[test] fn empty_and_stale_port_selections_return_errors() { let mut list = PortList::from_serial(Vec::new(), &Config::default()); diff --git a/src/ui/view.rs b/src/ui/view.rs index e850dcd..ef467dc 100644 --- a/src/ui/view.rs +++ b/src/ui/view.rs @@ -272,11 +272,15 @@ impl App { ]) .areas(main_s); + let plot = self.plot.as_ref().ok_or(UiError::NoReturnData)?; + let bounds = plot.viewport.bounds(); + let span = bounds[1] - bounds[0]; let status = Paragraph::new(format!( - "The scan of {} points in the range ({}MHz - {}MHz) finished successfully", - self.points.value(), - self.start_frequency.value(), - self.stop_frequency.value(), + "{} — {} points — visible {} to {} MHz", + plot.label, + plot.data.len(), + format_frequency(bounds[0], span), + format_frequency(bounds[1], span), )) .block(Block::bordered().title("Status")) .style(SELECTED_COLOR); @@ -285,28 +289,20 @@ impl App { .marker(Marker::Dot) .graph_type(GraphType::Scatter) .style(Style::new().yellow()) - .data(&self.return_data)]; + .data(&plot.data)]; + + let midpoint = (bounds[0] + bounds[1]) / 2.0; let chart = Chart::new(datasets) .x_axis( Axis::default() - .bounds([ - self.start_frequency.value() as f64, - self.stop_frequency.value() as f64, - ]) + .title("Frequency (MHz)") + .bounds(bounds) .style(Style::default().fg(Color::Gray)) .labels([ - format!("{}MHz", self.start_frequency), - format!( - "{}MHz", - self.start_frequency.value() - + (self - .stop_frequency - .value() - .saturating_sub(self.start_frequency.value())) - / 2 - ), - format!("{}MHz", self.stop_frequency), + format_frequency(bounds[0], span), + format_frequency(midpoint, span), + format_frequency(bounds[1], span), ]), ) .y_axis( @@ -323,9 +319,14 @@ impl App { ]), ); frame.render_widget(chart, graph_area); + let keys = &self.config.ui.bindings; let footer = Paragraph::new(format!( - "{}, press ↲ or q to exit", - self.scan_state.message(), + "zoom {} / {}; pan {} / {}; reset {}; q exits", + keys.zoom_in.join("|"), + keys.zoom_out.join("|"), + keys.pan_left.join("|"), + keys.pan_right.join("|"), + keys.reset_view.join("|"), )) .centered(); frame.render_widget(status, title_area); @@ -334,6 +335,17 @@ impl App { } } +/// Keep axis labels compact while retaining useful precision after zooming. +fn format_frequency(value: f64, visible_span: f64) -> String { + let tick_spacing = visible_span / 2.0; + let precision = if tick_spacing >= 1.0 { + 2 + } else { + ((-tick_spacing.log10()).ceil() as usize).clamp(2, 6) + }; + format!("{value:.precision$}") +} + impl App { /// Apply the active/inactive style to a cached list widget. pub(crate) fn change_color( @@ -348,6 +360,7 @@ impl App { ) } } + impl App { /// Update connection selection styling after navigation. pub(crate) fn update_color(&mut self) -> Result<(), UiError> { @@ -384,3 +397,15 @@ impl App { Ok(()) } } + +#[cfg(test)] +mod tests { + use super::format_frequency; + + #[test] + fn frequency_labels_gain_precision_as_the_view_narrows() { + assert_eq!(format_frequency(240.123_456, 100.0), "240.12"); + assert_eq!(format_frequency(240.123_456, 0.001), "240.1235"); + assert_eq!(format_frequency(240.123_456, 0.000_001), "240.123456"); + } +} diff --git a/tests/startup.rs b/tests/startup.rs index 70ab613..8b0f20c 100644 --- a/tests/startup.rs +++ b/tests/startup.rs @@ -21,3 +21,24 @@ fn invalid_override_exits_without_entering_the_terminal() { assert_eq!(fs::read_dir(&directory).unwrap().count(), 1); fs::remove_dir_all(directory).unwrap(); } + +#[test] +fn malformed_csv_exits_without_entering_the_terminal_or_enumerating_ports() { + let directory = + std::env::temp_dir().join(format!("tiny-wb-csv-startup-{}", std::process::id())); + fs::create_dir_all(&directory).unwrap(); + let path = directory.join("broken.csv"); + fs::write(&path, "frequency_MHz,level_dBm\n240,not-a-level\n").unwrap(); + let result = Command::new(env!("CARGO_BIN_EXE_tiny-wb")) + .current_dir(&directory) + .arg("--view") + .arg(&path) + .output() + .unwrap(); + assert!(!result.status.success()); + let error = String::from_utf8_lossy(&result.stderr); + assert!(error.contains("broken.csv")); + assert!(error.contains("line 2")); + assert!(!result.stdout.windows(2).any(|bytes| bytes == b"\x1b[")); + fs::remove_dir_all(directory).unwrap(); +}