SimPaM/patient-monitor-simulation/src/render.rs

650 lines
28 KiB
Rust
Raw Normal View History

2026-11-12 09:36:13 +01:00
//! Size-independent Cairo drawing of the synthetic bedside monitor.
use gtk::cairo::{Context, FontSlant, FontWeight, LineCap, LineJoin};
2026-11-12 14:07:59 +01:00
use crate::model::{AlarmLimits, AlarmState, Parameters, PulseConduction, Spo2Quality, Spo2Status};
2026-11-12 09:36:13 +01:00
use crate::simulation::{Sample, Simulator};
type Color = (f64, f64, f64);
const BG: Color = (0.0, 0.0, 0.0);
const GREEN: Color = (0.26, 1.0, 0.39);
const YELLOW: Color = (1.0, 0.85, 0.17);
const RED: Color = (1.0, 0.30, 0.31);
const LIGHT_GREY: Color = (0.80, 0.84, 0.87);
const MUTED: Color = (0.42, 0.46, 0.49);
const GRID: Color = (0.10, 0.14, 0.13);
#[derive(Clone, Copy)]
enum Channel { Ecg, Pleth, Art, Capno }
fn visible_channels(p: &Parameters) -> Vec<(Channel, &'static str, Color)> {
let mut channels = Vec::with_capacity(4);
if p.show_ecg { channels.push((Channel::Ecg, "II / ECG", GREEN)); }
if p.show_spo2 { channels.push((Channel::Pleth, "SpO₂ / PLETH", YELLOW)); }
if p.show_art { channels.push((Channel::Art, "ART", RED)); }
if p.show_capno { channels.push((Channel::Capno, "CO₂", LIGHT_GREY)); }
channels
}
pub fn draw(cr: &Context, width: i32, height: i32, p: &Parameters, sim: &Simulator) {
let w = f64::from(width.max(1));
let h = f64::from(height.max(1));
set_color(cr, BG);
let _ = cr.paint();
let pad = (w.min(h) * 0.018).clamp(6.0, 20.0);
let header = (h * 0.083).clamp(32.0, 68.0);
let channels = visible_channels(p);
2026-11-12 14:07:59 +01:00
let body_height = (h - header - pad).max(20.0);
// NIBP occupies a dedicated box at the bottom of the numerical right column.
// Trace rows remain full height on the left.
let nibp_box_height = if p.show_nibp { (h * 0.24).clamp(135.0, 210.0).min(body_height * 0.55) }
else { 0.0 };
let trace_row_height = body_height / channels.len().max(1) as f64;
let vital_row_height = (body_height - nibp_box_height) / channels.len().max(1) as f64;
2026-11-12 09:36:13 +01:00
let sidebar = (w * 0.235).clamp(125.0, 370.0).min(w * 0.44);
let split_x = w - sidebar - pad;
let trace_left = pad + 6.0;
let trace_right = (split_x - pad).max(trace_left + 40.0);
let text_scale = (w.min(h * 1.7) / 850.0).clamp(0.65, 1.5);
2026-11-12 10:43:11 +01:00
let patient_title = if p.patient_name.trim().is_empty() {
"PATIENT MONITOR"
} else {
p.patient_name.trim()
};
let title_max_width = if w >= 850.0 {
split_x - pad * 2.0 - 145.0 * text_scale
} else {
split_x - pad * 2.0
};
fitted_text(cr, patient_title, pad + 5.0, header * 0.58,
18.0 * text_scale, title_max_width.max(25.0), LIGHT_GREY);
2026-11-12 09:36:13 +01:00
if w >= 850.0 {
text(cr, "SIMULATION", split_x - 128.0 * text_scale, header * 0.58,
11.0 * text_scale, MUTED, false);
}
stroke_line(cr, pad, header, w - pad, header, MUTED, 0.8);
2026-11-12 14:07:59 +01:00
stroke_line(cr, split_x, header, split_x, h - pad, MUTED, 0.9);
2026-11-12 09:36:13 +01:00
for (index, (channel, title, color)) in channels.iter().copied().enumerate() {
2026-11-12 14:07:59 +01:00
let top = header + index as f64 * trace_row_height;
let bottom = top + trace_row_height;
stroke_line(cr, pad, bottom, split_x, bottom, MUTED, 0.65);
text(cr, title, trace_left + 4.0, top + trace_row_height * 0.17,
(trace_row_height * 0.11).clamp(10.0, 17.0), color, false);
2026-11-12 09:36:13 +01:00
draw_trace(cr, channel, color, trace_left, trace_right,
2026-11-12 14:07:59 +01:00
top + trace_row_height * 0.25, bottom - trace_row_height * 0.06, p, sim);
let vital_top = header + index as f64 * vital_row_height;
stroke_line(cr, split_x, vital_top + vital_row_height,
w - pad, vital_top + vital_row_height, MUTED, 0.65);
2026-11-12 09:36:13 +01:00
draw_vitals(cr, channel, color, split_x + pad,
2026-11-12 14:07:59 +01:00
vital_top, vital_row_height, sidebar - 2.0 * pad, p, sim);
2026-11-12 09:36:13 +01:00
}
if p.show_nibp {
2026-11-12 14:07:59 +01:00
draw_nibp_box(cr, split_x + pad, h - pad - nibp_box_height,
sidebar - 2.0 * pad, nibp_box_height, p, sim);
2026-11-12 09:36:13 +01:00
}
}
2026-11-12 14:07:59 +01:00
fn draw_nibp_box(cr: &Context, x: f64, top: f64, width: f64, height: f64,
p: &Parameters, sim: &Simulator) {
let right = x + width;
let pressure = sim.nibp().cuff_pressure(sim.time());
let in_progress = sim.nibp().measuring();
let reading = sim.nibp().reading();
let value_width = (width - 35.0).max(30.0);
let small = (height * 0.095).clamp(10.0, 14.0);
let number_size = (height * 0.25).clamp(18.0, 41.0);
// Subtle red outline distinguishes the independent cuff reading box.
let _ = cr.save();
cr.set_source_rgb(0.28, 0.09, 0.10);
cr.set_line_width(1.0);
cr.rectangle(x - 7.0, top, width + 13.0, height - 1.0);
let _ = cr.stroke();
let _ = cr.restore();
text(cr, "NIBP", x, top + height * 0.13, small * 1.15, RED, true);
if in_progress {
text(cr, "MEASURING", x, top + height * 0.27, small, RED, false);
} else {
text(cr, "mmHg", x, top + height * 0.27, small, MUTED, false);
}
if sim.nibp().show_new_value(sim.time()) {
let (sys, dia) = reading.map_or(("---".to_owned(), "---".to_owned()), |r|
(r.systolic.to_string(), r.diastolic.to_string()));
draw_pressure_components(cr, &sys, &dia, x, top + height * 0.60,
number_size, value_width, RED,
alarmed(p.alarms.nibp_sys, reading.map(|r| r.systolic)),
alarmed(p.alarms.nibp_dia, reading.map(|r| r.diastolic)), alarm_flash_on(sim));
let map = reading.map_or("---".to_owned(), |r| r.mean().to_string());
draw_alarm_inline(cr, x, top + height * 0.72, small * 1.15, value_width,
RED, "MAP ", &map, " mmHg",
alarmed(p.alarms.nibp_map, reading.map(|r| r.mean())), alarm_flash_on(sim));
}
// Horizontal: elapsed fraction of the selected measurement interval.
let progress_y = top + height * 0.85;
let progress_width = (width - 9.0).max(8.0);
stroke_line(cr, x, progress_y, x + progress_width, progress_y, MUTED, 4.0);
stroke_line(cr, x, progress_y,
x + progress_width * sim.nibp().interval_progress(sim.time(), p.nibp_interval_minutes),
progress_y, RED, 4.0);
text(cr, &format!("Every {} min", p.nibp_interval_minutes),
x, top + height * 0.97, small * 0.85, MUTED, false);
// Vertical cuff-pressure gauge (0..200 mmHg), always visible when measuring.
let gauge_x = right - 15.0;
let gauge_top = top + height * 0.31;
let gauge_h = height * 0.40;
stroke_line(cr, gauge_x, gauge_top, gauge_x, gauge_top + gauge_h, MUTED, 7.0);
if in_progress {
stroke_line(cr, gauge_x, gauge_top + gauge_h,
gauge_x, gauge_top + gauge_h * (1.0 - pressure / 200.0), RED, 6.0);
}
text(cr, &format!("{:.0}", pressure), gauge_x - 12.0,
gauge_top - 3.0, small * 0.75, RED, false);
draw_alarm_annotations(cr, &[
("SYS", p.alarms.nibp_sys),
("MAP", p.alarms.nibp_map),
("DIA", p.alarms.nibp_dia),
], right, top, height * 0.65, width * 0.72);
}
2026-11-12 10:43:11 +01:00
fn pleth_trace_enabled(p: &Parameters) -> bool {
p.spo2_sensor_attached && p.spo2_quality != Spo2Quality::None
}
2026-11-12 14:07:59 +01:00
#[cfg(test)]
fn spo2_vitals(p: &Parameters, pulse_rate: Option<i32>, signal_lost: bool)
-> (String, String, String) {
2026-11-12 14:07:59 +01:00
spo2_vitals_at_quality(p, pulse_rate, signal_lost, p.spo2_quality)
}
fn spo2_vitals_at_quality(p: &Parameters, pulse_rate: Option<i32>, signal_lost: bool,
quality: Spo2Quality) -> (String, String, String) {
match p.spo2_status_at_quality(pulse_rate, signal_lost, quality) {
2026-11-12 12:08:46 +01:00
Spo2Status::NoSensor => (
"SpO₂".to_owned(), "NO SENSOR".to_owned(), "PR -- bpm".to_owned()),
Spo2Status::NoReading => (
"SpO₂".to_owned(), "NO READING".to_owned(), "PR -- bpm".to_owned()),
Spo2Status::Available => (
2026-11-12 14:07:59 +01:00
format!("SpO₂ {}", quality.stars()),
2026-11-12 12:08:46 +01:00
p.spo2.to_string(),
format!("% PR {} bpm", pulse_rate.unwrap_or_default()),
),
2026-11-12 10:43:11 +01:00
}
}
2026-11-12 11:30:50 +01:00
fn alarmed(limits: AlarmLimits, value: Option<i32>) -> bool {
limits.evaluate(value) != AlarmState::Normal
}
/// The drawing loop runs continuously; alternate the alarm rectangle every
/// 500 ms. No extra timer or state can become desynchronized with the display.
fn alarm_flash_on(sim: &Simulator) -> bool {
let time = sim.samples().back().map_or(0.0, |sample| sample.time);
(time * 2.0).floor() as i64 % 2 == 0
}
2026-11-12 09:36:13 +01:00
fn draw_vitals(cr: &Context, ch: Channel, color: Color, x: f64,
top: f64, row_h: f64, width: f64, p: &Parameters, sim: &Simulator) {
let label_size = (row_h * 0.135).clamp(11.0, 19.0);
let number_size = (row_h * 0.375).min(width * 0.26).clamp(16.0, 59.0);
2026-11-12 11:30:50 +01:00
let sub_size = (row_h * 0.16).clamp(11.0, 22.0) * 0.85;
let flash = alarm_flash_on(sim);
2026-11-12 12:08:46 +01:00
let has_capture = p.ecg_rhythm.can_generate_pulse()
2026-11-12 09:36:13 +01:00
&& p.heart_rate > 0
&& p.pulse_conduction != PulseConduction::None;
let pulse_rate = if has_capture { sim.pulse_rate() } else { None };
2026-11-12 11:30:50 +01:00
let ecg_hr = if p.ecg_rhythm.has_qrs() && p.heart_rate > 0 {
Some(p.heart_rate)
} else { None };
2026-11-12 14:07:59 +01:00
let spo2_status = p.spo2_status_at_quality(pulse_rate, sim.poor_signal_lost(), sim.spo2_quality(p));
2026-11-12 12:08:46 +01:00
let oxygen = if spo2_status == Spo2Status::Available { Some(p.spo2) } else { None };
2026-11-12 11:30:50 +01:00
let limits: Vec<(&str, AlarmLimits)> = match ch {
Channel::Ecg => vec![("HR", p.alarms.hr)],
Channel::Pleth => vec![("SpO₂", p.alarms.spo2), ("PR", p.alarms.pr)],
Channel::Art => vec![("SYS", p.alarms.art_sys),
("MAP", p.alarms.art_map), ("DIA", p.alarms.art_dia),
("PPV", p.alarms.ppv)],
Channel::Capno => vec![("EtCO₂", p.alarms.etco2), ("RR", p.alarms.rr)],
};
draw_alarm_annotations(cr, &limits, x + width, top, row_h, width);
let value_y = top + row_h * 0.64;
let info_y = top + row_h * 0.87;
match ch {
Channel::Ecg => {
text(cr, "HR", x, top + row_h * 0.24, label_size, color, false);
draw_alarm_number(cr, &ecg_hr.map_or("--".to_owned(), |v| v.to_string()),
x, value_y, number_size, width, color,
alarmed(p.alarms.hr, ecg_hr), flash);
2026-11-12 12:08:46 +01:00
// Show only the clinical alarm message, never the selected ECG rhythm.
if let Some(message) = p.ecg_rhythm.rhythm_alarm() {
draw_alarm_number(cr, message, x, info_y, sub_size * 1.1,
width, color, true, flash);
} else {
text(cr, "bpm", x, info_y, sub_size, color, false);
}
2026-11-12 11:30:50 +01:00
}
Channel::Pleth => {
2026-11-12 14:07:59 +01:00
let (label, value, info) = spo2_vitals_at_quality(p, pulse_rate,
sim.poor_signal_lost(), sim.spo2_quality(p));
2026-11-12 11:30:50 +01:00
text(cr, &label, x, top + row_h * 0.24, label_size, color, false);
2026-11-12 12:08:46 +01:00
let technical_alarm = spo2_status != Spo2Status::Available;
let value_size = if technical_alarm {
number_size.min(0.17 * width).min(26.0)
2026-11-12 11:30:50 +01:00
} else { number_size };
draw_alarm_number(cr, &value, x, value_y, value_size,
2026-11-12 12:08:46 +01:00
width, color, technical_alarm || alarmed(p.alarms.spo2, oxygen), flash);
2026-11-12 11:30:50 +01:00
if oxygen.is_some() {
draw_alarm_inline(cr, x, info_y, sub_size, width, color,
"% PR ", &pulse_rate.unwrap_or_default().to_string(), " bpm",
alarmed(p.alarms.pr, pulse_rate), flash);
} else {
text(cr, &info, x, info_y, sub_size, color, false);
}
}
Channel::Art => {
text(cr, "ART", x, top + row_h * 0.24, label_size, color, false);
2026-11-12 14:07:59 +01:00
let (sys, dia, map) = sim.displayed_art_pressures(p, pulse_rate.is_some());
let sys_text = sys.map_or("--".to_owned(), |v| v.to_string());
let dia_text = dia.map_or("--".to_owned(), |v| v.to_string());
draw_pressure_components(cr, &sys_text, &dia_text,
x, value_y, number_size * 0.78, width, color,
alarmed(p.alarms.art_sys, sys),
alarmed(p.alarms.art_dia, dia), flash);
let map_text = map.map_or("--".to_owned(), |v| v.to_string());
if p.pulse_pressure_variation > 0 || p.alarms.ppv.enabled() {
let ppv_text = p.pulse_pressure_variation.to_string();
draw_alarm_parts(cr, x, info_y, sub_size, width, color, &[
("MAP ", false),
(&map_text, alarmed(p.alarms.art_map, map)),
(" · PPV ", false),
(&ppv_text, alarmed(p.alarms.ppv, Some(p.pulse_pressure_variation))),
("%", false),
], flash);
2026-11-12 11:30:50 +01:00
} else {
2026-11-12 14:07:59 +01:00
draw_alarm_inline(cr, x, info_y, sub_size, width, color,
"MAP ", &map_text, " mmHg",
alarmed(p.alarms.art_map, map), flash);
2026-11-12 11:30:50 +01:00
}
}
Channel::Capno => {
text(cr, "EtCO₂", x, top + row_h * 0.24, label_size, color, false);
draw_alarm_number(cr, &p.etco2.to_string(), x, value_y,
number_size, width, color,
alarmed(p.alarms.etco2, Some(p.etco2)), flash);
draw_alarm_inline(cr, x, info_y, sub_size, width, color,
"mmHg RR ", &p.respiratory_rate.to_string(), " /min",
alarmed(p.alarms.rr, Some(p.respiratory_rate)), flash);
}
}
}
/// Compact lines anchored at the top-right edge of each parameter region.
/// Unset limits are explicitly rendered as '---'.
fn draw_alarm_annotations(cr: &Context, limits: &[(&str, AlarmLimits)],
right: f64, top: f64, height: f64, available_width: f64) {
let size = (height * 0.073).clamp(8.0, 11.0)
.min((available_width / 20.0).clamp(7.0, 11.0));
let step = (height * 0.105).clamp(11.0, 15.0);
let any_enabled = limits.iter().any(|(_, limits)| limits.enabled());
for (i, (name, bounds)) in limits.iter().enumerate() {
let line = if i == 0 && any_enabled {
format!("⚠ {}", bounds.display(name))
} else { bounds.display(name) };
let line_width = measure_text(cr, &line, size, false);
let x = (right - line_width).max(right - available_width);
let baseline = top + (height * 0.10).max(10.0) + i as f64 * step;
text(cr, &line, x, baseline, size, MUTED, false);
}
}
/// Paint the numeric rectangle in its own waveform color on alternating frames.
/// Only the number, not the whole channel or waveform, is inverted.
#[allow(clippy::too_many_arguments)]
fn draw_alarm_number(cr: &Context, value: &str, x: f64, baseline: f64,
nominal_size: f64, available_width: f64, color: Color,
alarm: bool, flash: bool) {
let size = fitting_size(cr, value, nominal_size, available_width, true);
let _ = cr.save();
cr.rectangle(x, baseline - size * 1.28,
available_width.max(1.0), size * 1.65);
cr.clip();
draw_segment(cr, value, x, baseline, size, color, alarm && flash, true);
let _ = cr.restore();
}
2026-11-12 14:07:59 +01:00
/// Draw SYS and DIA independently; their threshold alarms can invert separately.
#[allow(clippy::too_many_arguments)]
fn draw_pressure_components(cr: &Context, sys: &str, dia: &str,
x: f64, baseline: f64, nominal_size: f64,
available_width: f64, color: Color,
sys_alarm: bool, dia_alarm: bool, flash: bool) {
2026-11-12 11:30:50 +01:00
let full = format!("{}/{}", sys, dia);
let size = fitting_size(cr, &full, nominal_size, available_width, true);
let _ = cr.save();
cr.rectangle(x, baseline - size * 1.28, available_width.max(1.0), size * 1.65);
cr.clip();
let mut cursor = x;
cursor += draw_segment(cr, sys, cursor, baseline, size, color, sys_alarm && flash, true);
2026-11-12 11:30:50 +01:00
cursor += draw_segment(cr, "/", cursor, baseline, size, color, false, true);
draw_segment(cr, dia, cursor, baseline, size, color, dia_alarm && flash, true);
2026-11-12 11:30:50 +01:00
let _ = cr.restore();
}
/// One smaller value embedded in text (MAP, PR or RR), with independent alarm.
#[allow(clippy::too_many_arguments)]
fn draw_alarm_inline(cr: &Context, x: f64, baseline: f64, nominal_size: f64,
available_width: f64, color: Color, prefix: &str,
number: &str, suffix: &str, alarm: bool, flash: bool) {
draw_alarm_parts(cr, x, baseline, nominal_size, available_width, color,
&[(prefix, false), (number, alarm), (suffix, false)], flash);
}
#[allow(clippy::too_many_arguments)]
fn draw_alarm_parts(cr: &Context, x: f64, baseline: f64, nominal_size: f64,
available_width: f64, color: Color,
parts: &[(&str, bool)], flash: bool) {
let full: String = parts.iter().map(|(part, _)| *part).collect();
let size = fitting_size(cr, &full, nominal_size, available_width, false);
let _ = cr.save();
cr.rectangle(x, baseline - size * 1.28, available_width.max(1.0), size * 1.65);
cr.clip();
let mut cursor = x;
for (part, alarm) in parts {
cursor += draw_segment(cr, part, cursor, baseline, size, color, *alarm && flash, false);
}
let _ = cr.restore();
}
fn draw_segment(cr: &Context, value: &str, x: f64, baseline: f64,
size: f64, color: Color, inverted: bool, bold: bool) -> f64 {
let width = measure_text(cr, value, size, bold);
if inverted {
set_color(cr, color);
cr.rectangle(x - 1.0, baseline - size * 0.95, width + 2.0, size * 1.15);
let _ = cr.fill();
}
text(cr, value, x, baseline, size, if inverted { BG } else { color }, bold);
width
}
fn measure_text(cr: &Context, value: &str, size: f64, bold: bool) -> f64 {
cr.select_font_face("Sans", FontSlant::Normal,
if bold { FontWeight::Bold } else { FontWeight::Normal });
cr.set_font_size(size);
cr.text_extents(value).map(|ext| ext.x_advance()).unwrap_or(0.0)
}
fn fitting_size(cr: &Context, value: &str, size: f64,
width: f64, bold: bool) -> f64 {
let actual_width = measure_text(cr, value, size, bold);
if actual_width > width && actual_width > 0.0 {
(size * width / actual_width).max(7.0)
} else { size }
2026-11-12 09:36:13 +01:00
}
#[allow(clippy::too_many_arguments)]
fn draw_trace(cr: &Context, channel: Channel, color: Color,
left: f64, right: f64, top: f64, bottom: f64,
p: &Parameters, sim: &Simulator) {
// ART is shown on an absolute fixed-pressure axis (0..200 mmHg),
// unlike the automatically normalized ECG, pleth and CO2 traces.
let axis_width = if matches!(channel, Channel::Art) { 36.0 } else { 0.0 };
let plot_left = left + axis_width;
let trace_width = (right - plot_left).max(1.0);
let trace_height = (bottom - top).max(1.0);
const VISIBLE_SECONDS: f64 = 8.0;
let last_t = sim.samples().back().map(|s| s.time).unwrap_or(0.0);
let start_t = last_t - VISIBLE_SECONDS;
let _ = cr.save();
cr.rectangle(left, top, right - left, trace_height);
cr.clip();
// A subtle grid, one vertical division per second.
for second in (start_t.ceil() as i64)..=(last_t.floor() as i64) {
let x = right - (last_t - second as f64) / VISIBLE_SECONDS * trace_width;
stroke_line(cr, x, top, x, bottom, GRID, 0.75);
}
if matches!(channel, Channel::Art) {
for pressure in (0..=200).step_by(50) {
let y = bottom - pressure as f64 / 200.0 * trace_height;
stroke_line(cr, plot_left, y, right, y, GRID, 0.8);
// Right-align tick labels against the axis.
let label = pressure.to_string();
let label_offset = if pressure >= 100 { 23.0 } else if pressure >= 10 { 17.0 } else { 10.0 };
text(cr, &label, plot_left - label_offset, (y + 3.0).max(top + 9.0).min(bottom),
9.5, MUTED, false);
}
stroke_line(cr, plot_left, top, plot_left, bottom, MUTED, 0.75);
} else {
stroke_line(cr, left, top + trace_height * 0.5,
right, top + trace_height * 0.5, GRID, 0.7);
}
2026-11-12 10:43:11 +01:00
// Disconnected or absent pleth signal: no curve, including historical pulses.
2026-11-12 12:08:46 +01:00
if matches!(channel, Channel::Pleth)
&& (!pleth_trace_enabled(p)
2026-11-12 14:07:59 +01:00
|| p.spo2_status_at_quality(sim.pulse_rate(), sim.poor_signal_lost(),
sim.spo2_quality(p)) != Spo2Status::Available)
2026-11-12 10:43:11 +01:00
{
let _ = cr.restore();
return;
}
2026-11-12 09:36:13 +01:00
set_color(cr, color);
cr.set_line_width((trace_height * 0.016).clamp(1.2, 2.4));
cr.set_line_cap(LineCap::Round);
cr.set_line_join(LineJoin::Round);
let mut started = false;
for s in sim.samples().iter().filter(|s| s.time >= start_t) {
let x = right - (last_t - s.time) / VISIBLE_SECONDS * trace_width;
let amplitude = normalized(channel, s, p);
let y = bottom - amplitude * trace_height;
if matches!(channel, Channel::Pleth) && !s.pleth_valid {
if started { let _ = cr.stroke(); started = false; }
continue;
}
2026-11-12 09:36:13 +01:00
if started { cr.line_to(x, y); }
else { cr.move_to(x, y); started = true; }
}
if started { let _ = cr.stroke(); }
let _ = cr.restore();
}
fn normalized(channel: Channel, s: &Sample, p: &Parameters) -> f64 {
match channel {
Channel::Ecg => (0.40 + s.ecg * 0.38).clamp(0.02, 0.98),
2026-11-12 14:07:59 +01:00
Channel::Pleth => (0.10 + pleth_visual_amplitude(s.pleth, s.time, s.pleth_quality) * 0.78)
2026-11-12 10:43:11 +01:00
.clamp(0.02, 0.98),
2026-11-12 09:36:13 +01:00
Channel::Art => (s.art / 200.0).clamp(0.0, 1.0),
Channel::Capno => (0.08 + (s.co2 / f64::from(p.etco2.max(1))) * 0.80)
.clamp(0.02, 0.98),
}
}
2026-11-12 10:43:11 +01:00
/// Signal degradation is presentation-only: no quality setting can invent
/// pulses or change the ECG/ART generator. The noise is smoothly interpolated
/// and reproducible, so redrawing a sample does not make it flicker.
fn pleth_visual_amplitude(pleth: f64, time: f64, quality: Spo2Quality) -> f64 {
let scale = quality.amplitude_scale();
if scale == 0.0 || pleth <= 0.0 { return 0.0; }
let distortion = if quality == Spo2Quality::Poor {
(1.0 + 0.55 * smooth_noise(time * 7.0)
+ 0.20 * smooth_noise(time * 23.0 + 4.0)).clamp(0.15, 1.75)
} else {
1.0
};
(pleth * scale * distortion).clamp(0.0, 1.0)
}
fn smooth_noise(position: f64) -> f64 {
let index = position.floor() as i64;
let fraction = position - index as f64;
let smooth = fraction * fraction * (3.0 - 2.0 * fraction);
let a = noise_value(index);
let b = noise_value(index.wrapping_add(1));
a + (b - a) * smooth
}
fn noise_value(index: i64) -> f64 {
let mut x = (index as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
x ^= x >> 30;
x = x.wrapping_mul(0xBF58_476D_1CE4_E5B9);
x ^= x >> 27;
x = x.wrapping_mul(0x94D0_49BB_1331_11EB);
x ^= x >> 31;
(x as f64 / u64::MAX as f64) * 2.0 - 1.0
}
/// Fit a name or numeric/status reading horizontally without changing the
/// other monitor dimensions. For exceptionally long values, clip safely.
fn fitted_text(cr: &Context, value: &str, x: f64, baseline: f64,
nominal_size: f64, available_width: f64, color: Color) {
cr.select_font_face("Sans", FontSlant::Normal, FontWeight::Bold);
cr.set_font_size(nominal_size);
let actual_width = cr.text_extents(value).map(|ext| ext.x_advance()).unwrap_or(0.0);
let fitted_size = if actual_width > available_width && actual_width > 0.0 {
(nominal_size * available_width / actual_width).max(8.0)
} else {
nominal_size
};
let _ = cr.save();
cr.rectangle(x, baseline - fitted_size * 1.25,
available_width.max(1.0), fitted_size * 1.55);
cr.clip();
text(cr, value, x, baseline, fitted_size, color, true);
let _ = cr.restore();
}
2026-11-12 09:36:13 +01:00
fn set_color(cr: &Context, c: Color) {
cr.set_source_rgb(c.0, c.1, c.2);
}
fn stroke_line(cr: &Context, x1: f64, y1: f64, x2: f64, y2: f64,
color: Color, width: f64) {
set_color(cr, color);
cr.set_line_width(width);
cr.move_to(x1, y1);
cr.line_to(x2, y2);
let _ = cr.stroke();
}
fn text(cr: &Context, value: &str, x: f64, baseline: f64,
size: f64, color: Color, bold: bool) {
set_color(cr, color);
cr.select_font_face("Sans", FontSlant::Normal,
if bold { FontWeight::Bold } else { FontWeight::Normal });
cr.set_font_size(size);
cr.move_to(x, baseline);
let _ = cr.show_text(value);
}
#[cfg(test)]
mod tests {
use super::*;
2026-11-12 11:30:50 +01:00
#[test]
fn alarm_states_do_not_trigger_for_unavailable_readouts() {
let p = Parameters::default();
let limits = AlarmLimits { lower: Some(95), upper: Some(99) };
assert!(!alarmed(limits, None));
assert!(alarmed(limits, Some(94)));
assert!(alarmed(limits, Some(100)));
assert!(!alarmed(limits, Some(98)));
assert_eq!(p.alarms.spo2, AlarmLimits::default());
}
2026-11-12 09:36:13 +01:00
#[test]
fn toggled_channels_disappear_and_remaining_rows_reflow() {
let mut p = Parameters::default();
assert_eq!(visible_channels(&p).len(), 4);
p.show_ecg = false;
p.show_art = false;
assert_eq!(visible_channels(&p).len(), 2);
assert!(matches!(visible_channels(&p)[0].0, Channel::Pleth));
assert!(matches!(visible_channels(&p)[1].0, Channel::Capno));
p.show_spo2 = false;
p.show_capno = false;
assert!(visible_channels(&p).is_empty());
}
2026-11-12 10:43:11 +01:00
#[test]
fn pleth_degradation_preserves_capture_timing_and_suppresses_false_pulses() {
let pulse = 0.6;
let t = 1.234;
assert_eq!(pleth_visual_amplitude(pulse, t, Spo2Quality::None), 0.0);
assert_eq!(pleth_visual_amplitude(0.0, t, Spo2Quality::Poor), 0.0);
assert!(pleth_visual_amplitude(pulse, t, Spo2Quality::Poor)
< pleth_visual_amplitude(pulse, t, Spo2Quality::Adequate));
assert!(pleth_visual_amplitude(pulse, t, Spo2Quality::Adequate)
< pleth_visual_amplitude(pulse, t, Spo2Quality::Good));
assert_eq!(pleth_visual_amplitude(pulse, t, Spo2Quality::Good), pulse);
assert_eq!(pleth_visual_amplitude(pulse, t, Spo2Quality::Poor),
pleth_visual_amplitude(pulse, t, Spo2Quality::Poor));
assert_ne!(pleth_visual_amplitude(pulse, t, Spo2Quality::Poor),
pleth_visual_amplitude(pulse, t + 0.5, Spo2Quality::Poor));
}
#[test]
fn disconnected_or_no_quality_means_no_pleth_or_spo2_reading() {
let mut p = Parameters::default();
assert!(pleth_trace_enabled(&p));
p.spo2_sensor_attached = false;
assert!(!pleth_trace_enabled(&p));
assert_eq!(spo2_vitals(&p, Some(75), false).1, "NO SENSOR");
assert!(spo2_vitals(&p, Some(75), false).2.contains("PR --"));
2026-11-12 10:43:11 +01:00
p.spo2_sensor_attached = true;
p.spo2_quality = Spo2Quality::None;
assert!(!pleth_trace_enabled(&p));
assert_eq!(spo2_vitals(&p, Some(75), false).1, "NO READING");
assert!(spo2_vitals(&p, Some(75), false).2.contains("PR --"));
2026-11-12 10:43:11 +01:00
assert!(p.show_spo2); // no readings, but visible row and status
}
#[test]
fn poor_and_good_quality_keep_derived_pr_and_quality_indicators() {
let mut p = Parameters::default();
p.spo2_quality = Spo2Quality::Poor;
assert_eq!(spo2_vitals(&p, Some(75), false).0, "SpO₂ ★");
assert_eq!(spo2_vitals(&p, Some(75), false).1, "98");
assert!(spo2_vitals(&p, Some(75), false).2.contains("PR 75 bpm"));
2026-11-12 10:43:11 +01:00
p.spo2_quality = Spo2Quality::Good;
assert_eq!(spo2_vitals(&p, Some(75), false).0, "SpO₂ ★★★");
assert_eq!(spo2_vitals(&p, None, false).1, "NO READING");
assert!(spo2_vitals(&p, None, false).2.contains("PR --"));
2026-11-12 10:43:11 +01:00
}
2026-11-12 12:08:46 +01:00
#[test]
fn no_sensor_precedes_no_reading_and_both_are_spo2_alarms() {
let mut p = Parameters::default();
assert_eq!(spo2_vitals(&p, None, false).1, "NO READING");
2026-11-12 12:08:46 +01:00
p.ecg_rhythm = crate::model::EcgRhythm::PulselessVentricularTachycardia;
assert_eq!(spo2_vitals(&p, Some(100), false).1, "NO READING");
2026-11-12 12:08:46 +01:00
p.spo2_sensor_attached = false;
assert_eq!(spo2_vitals(&p, Some(100), false).1, "NO SENSOR");
}
#[test]
fn intermittent_poor_spo2_loss_raises_no_reading_not_no_sensor() {
let p = Parameters { spo2_quality: Spo2Quality::Poor, ..Parameters::default() };
assert_eq!(spo2_vitals(&p, Some(75), true).1, "NO READING");
assert!(spo2_vitals(&p, Some(75), true).2.contains("PR --"));
assert_eq!(spo2_vitals(&p, Some(75), false).1, "98");
2026-11-12 12:08:46 +01:00
}
2026-11-12 09:36:13 +01:00
#[test]
fn arterial_axis_is_absolute_and_fixed_to_200_mmhg() {
let p = Parameters::default();
2026-11-12 14:07:59 +01:00
let mut s = Sample { time: 0.0, ecg: 0.0, pleth: 0.0, pleth_valid: true, pleth_quality: Spo2Quality::Good, art: 100.0, co2: 0.0 };
2026-11-12 09:36:13 +01:00
assert_eq!(normalized(Channel::Art, &s, &p), 0.5);
s.art = 200.0;
assert_eq!(normalized(Channel::Art, &s, &p), 1.0);
s.art = 0.0;
assert_eq!(normalized(Channel::Art, &s, &p), 0.0);
}
}