From 9ea53a042baa426f79dbdb842f3e961ae215c534 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 8 Oct 2026 12:51:59 +0200 Subject: [PATCH] feat: add live plot navigation and peak overlay --- README.md | 4 ++- docs/configuration.md | 8 ++--- docs/testing.md | 2 +- docs/tiny-wb-operations.md | 12 ++++--- src/config.rs | 2 +- src/ui/mod.rs | 65 +++++++++++++++++++++++++++++++++----- src/ui/state.rs | 30 ++++++++++++++++++ src/ui/view.rs | 39 ++++++++++++++++++++--- 8 files changed, 138 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index eed42ce..489dce4 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,9 @@ cargo run --release -- --view scan.csv ``` 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 +`0` or Home to restore the full frequency range. These controls also work during +live capture. Press `m` to toggle a box showing the strongest visible sample's +level and frequency. Plot bindings are configurable under `[ui.bindings]`. After an acquired scan, `r` immediately repeats the same scan and `n` returns to the prefilled scan-parameter editor. diff --git a/docs/configuration.md b/docs/configuration.md index 70537e2..0e4d8fe 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -81,10 +81,10 @@ 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: +`[ui.bindings]` configures completed, CSV, and live plot navigation. 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] diff --git a/docs/testing.md b/docs/testing.md index 6aff5e4..eefd389 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -17,7 +17,7 @@ cargo test --locked --doc | 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, one retry after an unusable identity reply, repeated complete live snapshots, optional legacy pre-scan, progress completion, successful decoding, resume after malformed frames, and preservation of acquisition plus recovery errors. | | Live processing | Four/sixteen-sweep rolling windows, bounded history, min/max hold, one-dB decay, incompatible axes, non-finite input and mode-key mapping. | -| UI/startup | `--live` parsing, missing/stale ports, numeric overflow and clamping, typed frequency/point commit/cancel/bounds, configured baud rates, sample-resolution plot zoom, adaptive axis precision, pan/reset and clamping, new-scan navigation, view-only CSV behavior, direct CSV startup failures, one-time result transfer, every screen on small/headless terminals, and invalid config before terminal startup. | +| UI/startup | `--live` parsing, missing/stale ports, numeric overflow and clamping, typed frequency/point commit/cancel/bounds, configured baud rates, completed/live sample-resolution zoom, adaptive axis precision, pan/reset and clamping, viewport-aware peak selection and overlay, new-scan navigation, view-only CSV behavior, 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 diff --git a/docs/tiny-wb-operations.md b/docs/tiny-wb-operations.md index a184177..788b81e 100644 --- a/docs/tiny-wb-operations.md +++ b/docs/tiny-wb-operations.md @@ -140,11 +140,13 @@ 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. +The frequency axis is labeled in MHz. In completed plots and live mode, `+` 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. `m` toggles a top-right box containing the level and +frequency of the strongest sample in the visible range. After an acquired scan, `r` reconnects and repeats the exact request and settings without reopening the parameter screen; each successful repeat creates a new collision-safe CSV. `n` returns to the scan screen with the previous parameters diff --git a/src/config.rs b/src/config.rs index 36dc776..52c3915 100644 --- a/src/config.rs +++ b/src/config.rs @@ -163,7 +163,7 @@ 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. + /// Configurable keyboard shortcuts used by completed, CSV, and live plots. pub bindings: PlotBindings, } diff --git a/src/ui/mod.rs b/src/ui/mod.rs index 45c28e6..feb59ef 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -57,6 +57,7 @@ impl App { live_enabled: false, live_generation: 0, live_exit_requested: false, + show_peak_info: false, plot: None, last_scan: None, can_acquire: true, @@ -197,9 +198,13 @@ impl App { KeyCode::Char(key) => { if let Some(mode) = TraceMode::from_key(key) { self.live_state.set_mode(mode); + } else if !self.apply_plot_navigation(&code) && key == 'm' { + self.show_peak_info = !self.show_peak_info; } } - _ => {} + _ => { + self.apply_plot_navigation(&code); + } } Ok(()) } @@ -252,21 +257,32 @@ impl App { } _ => {} } + if !self.apply_plot_navigation(&code) && code == KeyCode::Char('m') { + self.show_peak_info = !self.show_peak_info; + } + Ok(()) + } + + /// Apply configured zoom, pan, or reset navigation to the current plot. + fn apply_plot_navigation(&mut self, code: &KeyCode) -> bool { let bindings = &self.config.ui.bindings; - let action = if binding_matches(&code, &bindings.zoom_in) { + let action = if binding_matches(code, &bindings.zoom_in) { Some(PlotAction::ZoomIn) - } else if binding_matches(&code, &bindings.zoom_out) { + } else if binding_matches(code, &bindings.zoom_out) { Some(PlotAction::ZoomOut) - } else if binding_matches(&code, &bindings.pan_left) { + } else if binding_matches(code, &bindings.pan_left) { Some(PlotAction::PanLeft) - } else if binding_matches(&code, &bindings.pan_right) { + } else if binding_matches(code, &bindings.pan_right) { Some(PlotAction::PanRight) - } else if binding_matches(&code, &bindings.reset_view) { + } else if binding_matches(code, &bindings.reset_view) { Some(PlotAction::Reset) } else { None }; - if let (Some(plot), Some(action)) = (self.plot.as_mut(), action) { + let Some(action) = action else { + return false; + }; + if let Some(plot) = self.plot.as_mut() { match action { PlotAction::ZoomIn => plot.viewport.zoom_in(), PlotAction::ZoomOut => plot.viewport.zoom_out(), @@ -275,7 +291,7 @@ impl App { PlotAction::Reset => plot.viewport.reset(), } } - Ok(()) + true } /// Apply vertical input to the selected field. @@ -696,7 +712,17 @@ mod tests { fn live_keys_switch_mode_and_request_a_graceful_exit() { let mut app = app(); app.flow_state = AppState::Live; + app.plot = Some(Plot::new( + "live", + vec![(100.0, -30.0), (150.0, -10.0), (200.0, -20.0)], + )); app.live_state.begin(); + app.handle_start_keys(KeyEvent::new(KeyCode::Char('+'), KeyModifiers::NONE)) + .unwrap(); + assert_eq!(app.plot.as_ref().unwrap().viewport.bounds(), [125.0, 175.0]); + app.handle_start_keys(KeyEvent::new(KeyCode::Char('m'), KeyModifiers::NONE)) + .unwrap(); + assert!(app.show_peak_info); app.handle_start_keys(KeyEvent::new(KeyCode::Char('6'), KeyModifiers::NONE)) .unwrap(); assert_eq!(app.live_state.mode(), TraceMode::MinDecay); @@ -717,6 +743,7 @@ mod tests { app.init_config().unwrap(); app.init_progress().unwrap(); app.plot = Some(Plot::new("test.csv", vec![(240.0, -64.0)])); + app.show_peak_info = true; let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); for screen in [ AppState::default(), @@ -734,4 +761,26 @@ mod tests { } } } + + #[test] + fn peak_toggle_renders_the_strongest_visible_sample() { + let mut app = App::viewer( + Config::default(), + PathBuf::from("scan.csv"), + vec![(100.0, -30.0), (150.0, -10.0), (200.0, -20.0)], + ); + app.show_peak_info = true; + let mut terminal = Terminal::new(TestBackend::new(100, 24)).unwrap(); + terminal.draw(|frame| app.draw(frame).unwrap()).unwrap(); + let rendered: String = terminal + .backend() + .buffer() + .content + .iter() + .map(|cell| cell.symbol()) + .collect(); + assert!(rendered.contains("Visible peak")); + assert!(rendered.contains("-10.00 dBm")); + assert!(rendered.contains("150.00 MHz")); + } } diff --git a/src/ui/state.rs b/src/ui/state.rs index 0e9ab1e..31019d3 100644 --- a/src/ui/state.rs +++ b/src/ui/state.rs @@ -53,6 +53,8 @@ pub(crate) struct App { pub(crate) live_generation: u64, /// Whether the UI should exit after live recovery and final export. pub(crate) live_exit_requested: bool, + /// Whether the plot overlays the strongest sample in the visible frequency range. + pub(crate) show_peak_info: bool, /// Validated settings retained when the selection is saved. pub(crate) config: Config, /// Explicit settings path selected at startup. @@ -98,6 +100,16 @@ impl Plot { self.label = label.into(); self.data = data; } + + /// Return the strongest sample inside the current horizontal viewport. + pub(crate) fn visible_peak(&self) -> Option<(f64, f64)> { + let [minimum, maximum] = self.viewport.bounds(); + self.data + .iter() + .copied() + .filter(|(frequency, _)| (minimum..=maximum).contains(frequency)) + .reduce(|peak, sample| if sample.1 > peak.1 { sample } else { peak }) + } } /// Horizontal chart bounds with zoom and pan clamped to the source data. @@ -598,6 +610,24 @@ mod tests { assert!(minimum < 240.0 && maximum > 240.0); } + #[test] + fn visible_peak_tracks_the_zoomed_and_panned_viewport() { + let mut plot = Plot::new( + "test", + vec![ + (100.0, -30.0), + (125.0, -10.0), + (150.0, -20.0), + (200.0, -5.0), + ], + ); + assert_eq!(plot.visible_peak(), Some((200.0, -5.0))); + plot.viewport.zoom_in(); + assert_eq!(plot.visible_peak(), Some((125.0, -10.0))); + plot.viewport.pan(InputDirection::Right); + assert_eq!(plot.visible_peak(), Some((150.0, -20.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 57d3a4f..4646225 100644 --- a/src/ui/view.rs +++ b/src/ui/view.rs @@ -1,14 +1,14 @@ //! Ratatui rendering; acquisition results arrive through shared scan state. use super::state::{ - App, AppState, SelectedConnection, SelectedScan, SELECTED_COLOR, UNSELECTED_COLOR, + App, AppState, Plot, SelectedConnection, SelectedScan, SELECTED_COLOR, UNSELECTED_COLOR, }; use crate::error::UiError; use ratatui::{ layout::{Constraint, Layout, Rect}, style::{Color, Style}, symbols::Marker, - widgets::{Axis, Block, Chart, Dataset, GraphType, List, Paragraph, Wrap}, + widgets::{Axis, Block, Chart, Clear, Dataset, GraphType, List, Paragraph, Wrap}, Frame, }; @@ -76,6 +76,9 @@ impl App { .bounds([self.config.ui.chart_min_dbm, self.config.ui.chart_max_dbm]), ); frame.render_widget(chart, graph_area); + if self.show_peak_info { + render_peak_info(frame, graph_area, plot); + } } else { frame.render_widget( Paragraph::new("Waiting for the first complete sweep…") @@ -86,7 +89,7 @@ impl App { } frame.render_widget( Paragraph::new( - "1 avg4 · 2 avg16 · 3 max hold · 4 max decay · 5 min hold · 6 min decay · s save · q stop+save", + "1–6 trace · zoom +/= / - · pan ←/→ · 0 reset · m peak · s save · q stop+save", ) .centered() .wrap(Wrap { trim: true }), @@ -398,6 +401,9 @@ impl App { ]), ); frame.render_widget(chart, graph_area); + if self.show_peak_info { + render_peak_info(frame, graph_area, plot); + } let keys = &self.config.ui.bindings; let restart = if self.can_acquire { "; r repeats; n edits a new scan" @@ -405,7 +411,7 @@ impl App { "" }; let footer = Paragraph::new(format!( - "zoom {} / {}; pan {} / {}; reset {}{}; q exits", + "zoom {} / {}; pan {} / {}; reset {}; m peak{}; q exits", keys.zoom_in.join("|"), keys.zoom_out.join("|"), keys.pan_left.join("|"), @@ -420,6 +426,31 @@ impl App { } } +/// Overlay the maximum visible sample without changing the chart's data bounds. +fn render_peak_info(frame: &mut Frame<'_>, graph_area: Rect, plot: &Plot) { + let Some((frequency, level)) = plot.visible_peak() else { + return; + }; + let width = graph_area.width.min(26); + let height = graph_area.height.min(4); + if width == 0 || height == 0 { + return; + } + let area = Rect::new( + graph_area.right().saturating_sub(width), + graph_area.y, + width, + height, + ); + let span = plot.viewport.bounds()[1] - plot.viewport.bounds()[0]; + let text = format!("{level:.2} dBm\n{} MHz", format_frequency(frequency, span)); + frame.render_widget(Clear, area); + frame.render_widget( + Paragraph::new(text).block(Block::bordered().title("Visible peak")), + area, + ); +} + /// 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;