feat: improve scan workflow reliability
This commit is contained in:
parent
8a0e7bd9b1
commit
f8280b35bc
|
|
@ -48,7 +48,11 @@ a COM port. If the port cannot be opened, follow the
|
|||
[serial-permission guidance](docs/tiny-wb-operations.md#serial-permissions).
|
||||
|
||||
Use Left/Right or `h`/`l` to select a field, Up/Down or `k`/`j` to change it,
|
||||
Enter to advance, and `q` or Escape to quit. A successful scan displays a trace
|
||||
or type digits to edit a selected start/stop frequency in MHz or the point count.
|
||||
Enter applies a typed value (press it again to advance), Backspace removes a
|
||||
digit, and Escape cancels an active edit. Otherwise Enter advances and `q` or
|
||||
Escape quits.
|
||||
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.
|
||||
|
||||
|
|
@ -62,7 +66,8 @@ 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
|
||||
under `[ui.bindings]`.
|
||||
under `[ui.bindings]`. After an acquired scan, `r` immediately repeats the same
|
||||
scan and `n` returns to the prefilled scan-parameter editor.
|
||||
|
||||
## Configuration and documentation
|
||||
|
||||
|
|
|
|||
|
|
@ -68,9 +68,11 @@ the original error's message instead of a second exhaustive mapping.
|
|||
|
||||
```text
|
||||
SelectingConnection -> SelectingScan -> Scanning -> Complete -> exit
|
||||
^ | |
|
||||
+---- n -------+ +-- r --> Scanning
|
||||
| | |
|
||||
+------------------+-------------+-> Error -> exit
|
||||
CSV file -------------------------------------> Complete
|
||||
CSV file -------------------------------------> Complete -> exit
|
||||
```
|
||||
|
||||
The constructor takes configuration and enumerated ports as values, without
|
||||
|
|
@ -79,6 +81,8 @@ 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.
|
||||
An acquired result can repeat its retained request/settings or return to the
|
||||
prefilled scan editor; a standalone CSV remains view-only.
|
||||
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.
|
||||
|
|
|
|||
|
|
@ -15,8 +15,8 @@ cargo test --locked --doc
|
|||
| Configuration | Embedded defaults, legacy flat keys, partial nested overrides, unknown/malformed values, numeric and path bounds, round trips, and failed replacement preservation. |
|
||||
| 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, 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. |
|
||||
| Acquisition | Exact command ordering, one retry after an unusable identity reply, 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, 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. |
|
||||
| Export | Header/units, header and headerless parsing, malformed/unordered input, deterministic CSV values, propagated write failures and collision-safe output files. |
|
||||
|
||||
`Shell<T>` accepts `T: Read + Write`. To add a regression, provide a transcript
|
||||
|
|
|
|||
|
|
@ -102,7 +102,18 @@ configurable; Basic frequency limits remain fixed protocol rules.
|
|||
| Repeat | measurements/point | 1 | 1 | 1–1,000 |
|
||||
|
||||
Left/right or `h`/`l` changes the selected field. Up/down or `k`/`j` changes
|
||||
the selection/value. Enter advances to the next screen. `q` or Escape exits.
|
||||
the selection/value. On either frequency field or the Points field, typing a
|
||||
digit opens an inline editor: digits append, Backspace removes a digit, Enter
|
||||
applies a value within the displayed bounds, and Escape cancels the edit.
|
||||
Frequencies are entered in MHz; points are entered as a sample count. Applying
|
||||
a typed value does not advance, so press Enter again to start the scan. Outside
|
||||
the editor, Enter advances to the next screen and `q` or Escape exits.
|
||||
|
||||
Instrument identification sends the read-only `version` and `info` queries. If
|
||||
the first complete pair is empty or cannot identify a supported family, tiny-wb
|
||||
repeats that pair once before reporting the identification error. Transport
|
||||
timeouts and incomplete prompts are not replayed on a potentially unsynchronized
|
||||
stream.
|
||||
|
||||
Large point and repeat values can produce extremely long scans. Total time also
|
||||
depends on RBW and instrument mode; the progress bar is based mainly on bytes
|
||||
|
|
@ -121,8 +132,13 @@ 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.
|
||||
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
|
||||
prefilled so they can be edited before starting another scan. These restart keys
|
||||
are not available when viewing a CSV directly. Plot bindings are configurable
|
||||
under `[ui.bindings]`; on acquired results, `r` and `n` take precedence over any
|
||||
matching plot binding. `q`, Escape, or Enter exits the renderer.
|
||||
|
||||
## Files
|
||||
|
||||
|
|
|
|||
|
|
@ -114,12 +114,7 @@ pub fn acquire<T: Read + Write>(
|
|||
report(ScanEvent::Message("Identifying instrument"));
|
||||
report(ScanEvent::Progress(5));
|
||||
shell.synchronize()?;
|
||||
let version = shell.command("version", delay, settle)?;
|
||||
let info = shell.command("info", delay, settle)?;
|
||||
if version.trim().is_empty() || info.trim().is_empty() {
|
||||
return Err(AcquisitionError::MissingIdentity);
|
||||
}
|
||||
let identity = DeviceIdentity::detect(version, info)?;
|
||||
let identity = identify_with_retry(shell, delay, settle, &mut report)?;
|
||||
let expected = match scan.device_model {
|
||||
ModelSelection::Auto => None,
|
||||
ModelSelection::Basic => Some(DeviceModel::Basic),
|
||||
|
|
@ -243,6 +238,37 @@ pub fn acquire<T: Read + Write>(
|
|||
}
|
||||
}
|
||||
|
||||
/// Retry the read-only identity exchange once after a complete but unusable reply.
|
||||
///
|
||||
/// Transport failures are not retried because a timeout can leave an incomplete
|
||||
/// prompt in the buffered stream. Replaying commands in that state would risk
|
||||
/// assigning a late response to the wrong request.
|
||||
fn identify_with_retry<T: Read + Write>(
|
||||
shell: &mut Shell<T>,
|
||||
delay: Duration,
|
||||
settle: Duration,
|
||||
report: &mut impl FnMut(ScanEvent),
|
||||
) -> Result<DeviceIdentity, AcquisitionError> {
|
||||
for attempt in 0..2 {
|
||||
let version = shell.command("version", delay, settle)?;
|
||||
let info = shell.command("info", delay, settle)?;
|
||||
let identity = if version.trim().is_empty() || info.trim().is_empty() {
|
||||
Err(AcquisitionError::MissingIdentity)
|
||||
} else {
|
||||
DeviceIdentity::detect(version, info).map_err(AcquisitionError::from)
|
||||
};
|
||||
match identity {
|
||||
Ok(identity) => return Ok(identity),
|
||||
Err(error) if attempt == 0 => {
|
||||
log::warn!("instrument identification failed; retrying once: {error}");
|
||||
report(ScanEvent::Message("Retrying instrument identification"));
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
unreachable!("the bounded identity loop always returns")
|
||||
}
|
||||
|
||||
fn advertises_command(help: &str, command: &str) -> bool {
|
||||
help.split(|character: char| !(character.is_ascii_alphanumeric() || character == '_'))
|
||||
.any(|word| word.eq_ignore_ascii_case(command))
|
||||
|
|
@ -362,6 +388,49 @@ mod tests {
|
|||
assert!(!commands.contains("\rscan "));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identification_retries_once_after_an_unusable_version() {
|
||||
let mut config = Config::default();
|
||||
config.scan.legacy_pre_scan = false;
|
||||
config.serial.command_delay_ms = 0;
|
||||
config.serial.settle_delay_ms = 0;
|
||||
let request = ScanRequest {
|
||||
start_hz: 240_000_000,
|
||||
stop_hz: 960_000_000,
|
||||
points: 2,
|
||||
repeat: 1,
|
||||
};
|
||||
let mut input = b"ch>\r\nch>unknown\r\nch>tinySA_v1.4-test\r\nch>tinySA\r\nch>Commands: repeat zero pause mode sweep scanraw resume\r\nch>"
|
||||
.to_vec();
|
||||
input.extend_from_slice(b"okch>".repeat(2).as_slice());
|
||||
input.extend_from_slice(b"128dBm\r\nch>");
|
||||
input.extend_from_slice(b"okch>".repeat(5).as_slice());
|
||||
input.extend_from_slice(b"{x\0\x08x\0\x10}ch>okch>");
|
||||
let commands = Arc::new(Mutex::new(Vec::new()));
|
||||
let mut shell = Shell::new(
|
||||
Transcript {
|
||||
input: Cursor::new(input),
|
||||
commands: commands.clone(),
|
||||
},
|
||||
1024,
|
||||
);
|
||||
let mut events = Vec::new();
|
||||
|
||||
let result = acquire(
|
||||
&mut shell,
|
||||
&request,
|
||||
&config.scan,
|
||||
&config.serial,
|
||||
|event| events.push(event),
|
||||
);
|
||||
|
||||
assert!(result.is_ok(), "{result:?}");
|
||||
let written = String::from_utf8(commands.lock().unwrap().clone()).unwrap();
|
||||
assert!(written.starts_with("version\rinfo\rversion\rinfo\rhelp\r"));
|
||||
assert_eq!(written.matches("version\r").count(), 2);
|
||||
assert!(events.contains(&ScanEvent::Message("Retrying instrument identification")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_frames_still_resume_and_preserve_original_error() {
|
||||
let (result, commands, _) = exercise(b"{y\0\x08x\0\x10}", true, true);
|
||||
|
|
@ -426,7 +495,14 @@ mod tests {
|
|||
)
|
||||
.unwrap();
|
||||
let commands = Arc::new(Mutex::new(Vec::new()));
|
||||
let input = format!("ch>{version}\r\nch>{info}\r\nch>{help}\r\nch>ch>ch>{zero}\r\nch>");
|
||||
let retry_identity = if matches!(expected, "unsupported device" | "conflicting") {
|
||||
format!("{version}\r\nch>{info}\r\nch>")
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let input = format!(
|
||||
"ch>{version}\r\nch>{info}\r\nch>{retry_identity}{help}\r\nch>ch>ch>{zero}\r\nch>"
|
||||
);
|
||||
let mut shell = Shell::new(
|
||||
Transcript {
|
||||
input: Cursor::new(input.into_bytes()),
|
||||
|
|
|
|||
32
src/scan.rs
32
src/scan.rs
|
|
@ -72,6 +72,16 @@ impl ScanState {
|
|||
}
|
||||
}
|
||||
|
||||
/// Clear results and errors before launching another worker.
|
||||
pub(crate) fn begin(&self) {
|
||||
let mut progress = self.lock();
|
||||
*progress = Progress {
|
||||
status: ScanStatus::Running,
|
||||
message: "Opening connection".into(),
|
||||
..Progress::default()
|
||||
};
|
||||
}
|
||||
|
||||
/// Current completion estimate; 100 means acquisition and export succeeded.
|
||||
pub(crate) fn progress(&self) -> usize {
|
||||
self.lock().percent
|
||||
|
|
@ -121,11 +131,7 @@ pub(crate) fn run_scan(
|
|||
request: ScanRequest,
|
||||
config: Config,
|
||||
) -> Result<(), AppError> {
|
||||
{
|
||||
let mut progress = state.lock();
|
||||
progress.status = ScanStatus::Running;
|
||||
progress.message = "Opening connection".into();
|
||||
}
|
||||
state.begin();
|
||||
config.validate()?;
|
||||
request
|
||||
.validate()
|
||||
|
|
@ -175,4 +181,20 @@ mod tests {
|
|||
assert_eq!(state.take_samples().unwrap(), vec![(240.0, -64.0)]);
|
||||
assert!(state.take_samples().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn beginning_another_scan_clears_previous_results_and_errors() {
|
||||
let state = ScanState::default();
|
||||
state.complete(PathBuf::from("old.csv"), vec![(240.0, -64.0)]);
|
||||
state.fail("old failure");
|
||||
|
||||
state.begin();
|
||||
|
||||
assert_eq!(state.status(), ScanStatus::Running);
|
||||
assert_eq!(state.progress(), 0);
|
||||
assert_eq!(state.message(), "Opening connection");
|
||||
assert!(state.info().is_empty());
|
||||
assert!(state.error().is_none());
|
||||
assert!(state.take_samples().is_err());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
204
src/ui/mod.rs
204
src/ui/mod.rs
|
|
@ -54,6 +54,8 @@ impl App {
|
|||
repeat: NumericInput::new(config.repeat, 1, 1, config.scan.max_repeat),
|
||||
scan_state: ScanState::default(),
|
||||
plot: None,
|
||||
last_scan: None,
|
||||
can_acquire: true,
|
||||
config,
|
||||
config_path,
|
||||
}
|
||||
|
|
@ -64,6 +66,7 @@ impl App {
|
|||
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.can_acquire = false;
|
||||
app
|
||||
}
|
||||
|
||||
|
|
@ -150,6 +153,9 @@ impl App {
|
|||
if matches!(self.flow_state, AppState::Complete) {
|
||||
return self.handle_plot_key(key.code);
|
||||
}
|
||||
if self.handle_numeric_editor_key(key.code) {
|
||||
return Ok(());
|
||||
}
|
||||
match key.code {
|
||||
KeyCode::Char('q') | KeyCode::Esc => self.should_quit = true,
|
||||
KeyCode::Char('j') | KeyCode::Down => self.change_cursor_position(InputDirection::Down),
|
||||
|
|
@ -165,11 +171,53 @@ impl App {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Give an active direct-entry editor exclusive use of keys and start one on a digit.
|
||||
fn handle_numeric_editor_key(&mut self, code: KeyCode) -> bool {
|
||||
let input = match self.flow_state {
|
||||
AppState::SelectingScan(SelectedScan::StartFreq) => &mut self.start_frequency,
|
||||
AppState::SelectingScan(SelectedScan::FinalFreq) => &mut self.stop_frequency,
|
||||
AppState::SelectingScan(SelectedScan::Points) => &mut self.points,
|
||||
_ => return false,
|
||||
};
|
||||
if input.is_editing() {
|
||||
match code {
|
||||
KeyCode::Char(digit) if digit.is_ascii_digit() => input.push_digit(digit),
|
||||
KeyCode::Backspace => input.backspace(),
|
||||
KeyCode::Enter => {
|
||||
input.commit_edit();
|
||||
}
|
||||
KeyCode::Esc => input.cancel_edit(),
|
||||
_ => {}
|
||||
}
|
||||
true
|
||||
} else {
|
||||
match code {
|
||||
KeyCode::Char(digit) if digit.is_ascii_digit() => {
|
||||
input.push_digit(digit);
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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(());
|
||||
match code {
|
||||
KeyCode::Char('q') | KeyCode::Esc | KeyCode::Enter => {
|
||||
self.should_quit = true;
|
||||
return Ok(());
|
||||
}
|
||||
KeyCode::Char('r') if self.can_acquire => {
|
||||
self.repeat_last_scan()?;
|
||||
return Ok(());
|
||||
}
|
||||
KeyCode::Char('n') if self.can_acquire => {
|
||||
self.plot = None;
|
||||
self.flow_state = AppState::SelectingScan(SelectedScan::default());
|
||||
return Ok(());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let bindings = &self.config.ui.bindings;
|
||||
let action = if binding_matches(&code, &bindings.zoom_in) {
|
||||
|
|
@ -268,26 +316,7 @@ impl App {
|
|||
self.flow_state = AppState::SelectingScan(SelectedScan::default());
|
||||
}
|
||||
AppState::SelectingScan(_) => {
|
||||
let config = self.selected_config()?;
|
||||
let request = ScanRequest {
|
||||
start_hz: config.start_frequency as u64 * 1_000_000,
|
||||
stop_hz: config.stop_frequency as u64 * 1_000_000,
|
||||
points: config.points,
|
||||
repeat: config.repeat,
|
||||
};
|
||||
request
|
||||
.validate()
|
||||
.map_err(tiny_wb::acquisition::AcquisitionError::from)
|
||||
.map_err(AppError::from)?;
|
||||
config.save(&self.config_path).map_err(AppError::from)?;
|
||||
self.flow_state = AppState::Scanning;
|
||||
self.init_progress()?;
|
||||
let connection = self.scan_state.clone();
|
||||
thread::spawn(move || {
|
||||
if let Err(error) = scan::run_scan(connection.clone(), request, config) {
|
||||
connection.fail(error);
|
||||
}
|
||||
});
|
||||
self.start_selected_scan()?;
|
||||
}
|
||||
AppState::Complete => {
|
||||
self.should_quit = true;
|
||||
|
|
@ -299,6 +328,47 @@ impl App {
|
|||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate and persist the edited fields, then launch their scan.
|
||||
fn start_selected_scan(&mut self) -> Result<(), UiError> {
|
||||
let config = self.selected_config()?;
|
||||
let request = ScanRequest {
|
||||
start_hz: config.start_frequency as u64 * 1_000_000,
|
||||
stop_hz: config.stop_frequency as u64 * 1_000_000,
|
||||
points: config.points,
|
||||
repeat: config.repeat,
|
||||
};
|
||||
request
|
||||
.validate()
|
||||
.map_err(tiny_wb::acquisition::AcquisitionError::from)
|
||||
.map_err(AppError::from)?;
|
||||
config.save(&self.config_path).map_err(AppError::from)?;
|
||||
self.launch_scan(request, config)
|
||||
}
|
||||
|
||||
/// Relaunch the exact request and settings used by the previous scan.
|
||||
fn repeat_last_scan(&mut self) -> Result<(), UiError> {
|
||||
let Some((request, config)) = self.last_scan.clone() else {
|
||||
return Ok(());
|
||||
};
|
||||
self.launch_scan(request, config)
|
||||
}
|
||||
|
||||
/// Reset progress synchronously and start one acquisition worker.
|
||||
fn launch_scan(&mut self, request: ScanRequest, config: Config) -> Result<(), UiError> {
|
||||
self.init_progress()?;
|
||||
self.scan_state.begin();
|
||||
self.flow_state = AppState::Scanning;
|
||||
self.plot = None;
|
||||
self.last_scan = Some((request, config.clone()));
|
||||
let connection = self.scan_state.clone();
|
||||
thread::spawn(move || {
|
||||
if let Err(error) = scan::run_scan(connection.clone(), request, config) {
|
||||
connection.fail(error);
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
/// Transfer completed samples once and keep rendering free of transitions.
|
||||
fn refresh_scan(&mut self) -> Result<(), UiError> {
|
||||
if matches!(self.flow_state, AppState::Scanning) {
|
||||
|
|
@ -390,6 +460,69 @@ mod tests {
|
|||
assert!(app.should_quit);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frequency_digits_open_an_editor_before_enter_advances() {
|
||||
let mut app = app();
|
||||
app.init_config().unwrap();
|
||||
app.next_step().unwrap();
|
||||
for digit in "315".chars() {
|
||||
app.handle_start_keys(KeyEvent::new(KeyCode::Char(digit), KeyModifiers::NONE))
|
||||
.unwrap();
|
||||
}
|
||||
assert_eq!(app.start_frequency.to_string(), "315_");
|
||||
app.handle_start_keys(KeyEvent::new(KeyCode::Left, KeyModifiers::NONE))
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
app.flow_state,
|
||||
AppState::SelectingScan(SelectedScan::StartFreq)
|
||||
));
|
||||
app.handle_start_keys(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE))
|
||||
.unwrap();
|
||||
assert_eq!(app.start_frequency.value(), 315);
|
||||
assert!(matches!(
|
||||
app.flow_state,
|
||||
AppState::SelectingScan(SelectedScan::StartFreq)
|
||||
));
|
||||
app.handle_start_keys(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE))
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
app.flow_state,
|
||||
AppState::SelectingScan(SelectedScan::FinalFreq)
|
||||
));
|
||||
app.handle_start_keys(KeyEvent::new(KeyCode::Char('9'), KeyModifiers::NONE))
|
||||
.unwrap();
|
||||
app.handle_start_keys(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE))
|
||||
.unwrap();
|
||||
assert_eq!(app.stop_frequency.value(), 800);
|
||||
assert!(!app.should_quit);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_digits_use_the_same_bounded_editor() {
|
||||
let mut app = app();
|
||||
app.init_config().unwrap();
|
||||
app.next_step().unwrap();
|
||||
app.next_menu(InputDirection::Right).unwrap();
|
||||
app.next_menu(InputDirection::Right).unwrap();
|
||||
assert!(matches!(
|
||||
app.flow_state,
|
||||
AppState::SelectingScan(SelectedScan::Points)
|
||||
));
|
||||
|
||||
for digit in "2048".chars() {
|
||||
app.handle_start_keys(KeyEvent::new(KeyCode::Char(digit), KeyModifiers::NONE))
|
||||
.unwrap();
|
||||
}
|
||||
assert_eq!(app.points.to_string(), "2048_");
|
||||
app.handle_start_keys(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE))
|
||||
.unwrap();
|
||||
assert_eq!(app.points.value(), 2048);
|
||||
assert!(matches!(
|
||||
app.flow_state,
|
||||
AppState::SelectingScan(SelectedScan::Points)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_ports_and_invalid_spans_fail_before_saving_or_scanning() {
|
||||
let mut app = App::new(
|
||||
|
|
@ -450,6 +583,31 @@ mod tests {
|
|||
assert_eq!(app.plot.as_ref().unwrap().viewport.bounds(), [100.0, 200.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_scan_key_returns_to_prefilled_parameters_only_for_acquisition() {
|
||||
let mut app = app();
|
||||
app.flow_state = AppState::Complete;
|
||||
app.plot = Some(Plot::new("scan.csv", vec![(240.0, -64.0)]));
|
||||
app.handle_start_keys(KeyEvent::new(KeyCode::Char('n'), KeyModifiers::NONE))
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
app.flow_state,
|
||||
AppState::SelectingScan(SelectedScan::StartFreq)
|
||||
));
|
||||
assert_eq!(app.start_frequency.value(), 240);
|
||||
assert!(app.plot.is_none());
|
||||
|
||||
let mut viewer = App::viewer(
|
||||
Config::default(),
|
||||
PathBuf::from("scan.csv"),
|
||||
vec![(240.0, -64.0)],
|
||||
);
|
||||
viewer
|
||||
.handle_start_keys(KeyEvent::new(KeyCode::Char('n'), KeyModifiers::NONE))
|
||||
.unwrap();
|
||||
assert!(matches!(viewer.flow_state, AppState::Complete));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_screen_renders_without_a_physical_terminal() {
|
||||
for (width, height) in [(120, 40), (40, 10), (1, 1)] {
|
||||
|
|
|
|||
101
src/ui/state.rs
101
src/ui/state.rs
|
|
@ -13,7 +13,7 @@ use crate::{
|
|||
error::{AppError, UiError},
|
||||
scan::ScanState,
|
||||
};
|
||||
use tiny_wb::config::Config;
|
||||
use tiny_wb::{config::Config, protocol::ScanRequest};
|
||||
|
||||
/// Color of a selected border
|
||||
pub(crate) const SELECTED_COLOR: Color = Color::White;
|
||||
|
|
@ -49,6 +49,10 @@ pub(crate) struct App {
|
|||
pub(crate) config: Config,
|
||||
/// Explicit settings path selected at startup.
|
||||
pub(crate) config_path: PathBuf,
|
||||
/// Last launched request and settings, retained for one-key repetition.
|
||||
pub(crate) last_scan: Option<(ScanRequest, Config)>,
|
||||
/// Whether this session may acquire, as opposed to viewing a standalone CSV.
|
||||
pub(crate) can_acquire: bool,
|
||||
/// Plot currently shown by the renderer; a collection boundary for future tabs.
|
||||
pub(crate) plot: Option<Plot>,
|
||||
}
|
||||
|
|
@ -179,6 +183,10 @@ pub(crate) struct NumericInput {
|
|||
min_clamp: usize,
|
||||
/// Inclusive upper bound.
|
||||
max_clamp: usize,
|
||||
/// Digits being entered directly; `None` retains step-based behavior.
|
||||
edit_buffer: Option<String>,
|
||||
/// Whether the current buffer failed bounds or integer validation.
|
||||
invalid_edit: bool,
|
||||
}
|
||||
|
||||
impl NumericInput {
|
||||
|
|
@ -208,6 +216,8 @@ impl NumericInput {
|
|||
increment,
|
||||
max_clamp,
|
||||
min_clamp,
|
||||
edit_buffer: None,
|
||||
invalid_edit: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -215,6 +225,57 @@ impl NumericInput {
|
|||
pub(crate) fn value(&self) -> usize {
|
||||
self.value
|
||||
}
|
||||
|
||||
/// Start or extend direct decimal entry without changing the committed value.
|
||||
pub(crate) fn push_digit(&mut self, digit: char) {
|
||||
if !digit.is_ascii_digit() {
|
||||
return;
|
||||
}
|
||||
let buffer = self.edit_buffer.get_or_insert_with(String::new);
|
||||
if buffer.len() < 20 {
|
||||
buffer.push(digit);
|
||||
}
|
||||
self.invalid_edit = false;
|
||||
}
|
||||
|
||||
/// Remove the last typed digit while retaining edit mode.
|
||||
pub(crate) fn backspace(&mut self) {
|
||||
if let Some(buffer) = self.edit_buffer.as_mut() {
|
||||
buffer.pop();
|
||||
self.invalid_edit = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Commit direct entry when it is an integer inside the field's bounds.
|
||||
pub(crate) fn commit_edit(&mut self) -> bool {
|
||||
let parsed = self
|
||||
.edit_buffer
|
||||
.as_deref()
|
||||
.filter(|buffer| !buffer.is_empty())
|
||||
.and_then(|buffer| buffer.parse::<usize>().ok());
|
||||
if let Some(value) =
|
||||
parsed.filter(|value| (self.min_clamp..=self.max_clamp).contains(value))
|
||||
{
|
||||
self.value = value;
|
||||
self.edit_buffer = None;
|
||||
self.invalid_edit = false;
|
||||
true
|
||||
} else {
|
||||
self.invalid_edit = true;
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Abandon direct entry and restore the previously committed value.
|
||||
pub(crate) fn cancel_edit(&mut self) {
|
||||
self.edit_buffer = None;
|
||||
self.invalid_edit = false;
|
||||
}
|
||||
|
||||
/// Whether keystrokes currently belong to the inline editor.
|
||||
pub(crate) fn is_editing(&self) -> bool {
|
||||
self.edit_buffer.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
|
|
@ -408,7 +469,21 @@ pub(crate) enum InputDirection {
|
|||
|
||||
impl std::fmt::Display for NumericInput {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
self.value.fmt(formatter)
|
||||
if let Some(buffer) = &self.edit_buffer {
|
||||
if self.invalid_edit {
|
||||
write!(
|
||||
formatter,
|
||||
"{}_ (enter {}–{})",
|
||||
buffer, self.min_clamp, self.max_clamp
|
||||
)
|
||||
} else if buffer.is_empty() {
|
||||
formatter.write_str("_")
|
||||
} else {
|
||||
write!(formatter, "{buffer}_")
|
||||
}
|
||||
} else {
|
||||
self.value.fmt(formatter)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -432,6 +507,28 @@ mod tests {
|
|||
assert_eq!(field.value(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numeric_input_edits_commits_and_cancels_typed_values() {
|
||||
let mut field = NumericInput::new(240, 10, 0, 5_400);
|
||||
for digit in "1234".chars() {
|
||||
field.push_digit(digit);
|
||||
}
|
||||
assert!(field.is_editing());
|
||||
assert_eq!(field.to_string(), "1234_");
|
||||
assert!(field.commit_edit());
|
||||
assert_eq!(field.value(), 1234);
|
||||
|
||||
for digit in "9999".chars() {
|
||||
field.push_digit(digit);
|
||||
}
|
||||
assert!(!field.commit_edit());
|
||||
assert_eq!(field.value(), 1234);
|
||||
assert!(field.to_string().contains("enter 0–5400"));
|
||||
field.backspace();
|
||||
field.cancel_edit();
|
||||
assert_eq!(field.to_string(), "1234");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn viewport_zooms_pans_clamps_and_resets() {
|
||||
let mut viewport = FrequencyViewport::from_samples(&[
|
||||
|
|
|
|||
|
|
@ -113,13 +113,21 @@ impl App {
|
|||
}
|
||||
/// Show keyboard guidance below editable settings.
|
||||
fn render_footer(&self, frame: &mut Frame, area: Rect) {
|
||||
frame.render_widget(
|
||||
Paragraph::new(
|
||||
"Use ↓↑ to move, ←→ to change status widget and ↲ to validate configuration.",
|
||||
)
|
||||
.centered(),
|
||||
area,
|
||||
);
|
||||
let guidance = match self.flow_state {
|
||||
AppState::SelectingScan(SelectedScan::StartFreq | SelectedScan::FinalFreq)
|
||||
if self.start_frequency.is_editing() || self.stop_frequency.is_editing() =>
|
||||
{
|
||||
"Type MHz; Backspace deletes, ↲ applies, and Esc cancels."
|
||||
}
|
||||
AppState::SelectingScan(SelectedScan::Points) if self.points.is_editing() => {
|
||||
"Type the point count; Backspace deletes, ↲ applies, and Esc cancels."
|
||||
}
|
||||
AppState::SelectingScan(_) => {
|
||||
"Use ↓↑ to change, ←→ to select, digits to type MHz/points, and ↲ to continue."
|
||||
}
|
||||
_ => "Use ↓↑ to move, ←→ to select, and ↲ to continue.",
|
||||
};
|
||||
frame.render_widget(Paragraph::new(guidance).centered(), area);
|
||||
}
|
||||
|
||||
/// Render the available ports and configured baud choices.
|
||||
|
|
@ -320,13 +328,19 @@ impl App {
|
|||
);
|
||||
frame.render_widget(chart, graph_area);
|
||||
let keys = &self.config.ui.bindings;
|
||||
let restart = if self.can_acquire {
|
||||
"; r repeats; n edits a new scan"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let footer = Paragraph::new(format!(
|
||||
"zoom {} / {}; pan {} / {}; reset {}; q exits",
|
||||
"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("|"),
|
||||
restart,
|
||||
))
|
||||
.centered();
|
||||
frame.render_widget(status, title_area);
|
||||
|
|
|
|||
Loading…
Reference in New Issue