v0.4.0: add alarms

This commit is contained in:
GABRIEL Sebastian 2026-11-12 11:30:50 +01:00
commit 49c25bf5bb
7 changed files with 1188 additions and 52 deletions

View file

@ -0,0 +1,701 @@
diff --git a/Cargo.toml b/Cargo.toml
index 01db11b..6c9e60a 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "patient-monitor-simulation"
-version = "0.3.2"
+version = "0.4.0"
edition = "2021"
license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"
diff --git a/README.md b/README.md
index a4be1bc..9e140e3 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.3.2
+# Patient Monitor Simulation (PaMSim) — v0.4.0
A two-window, Rust/GTK4 patient-monitor simulator for teaching on Fedora Linux.
@@ -40,6 +40,48 @@ The monitor can be resized and toggled fullscreen with **F11**; **Esc** exits
fullscreen. On Wayland, move the monitor to the presentation screen before
activating fullscreen. Fullscreen does not lock down the computer.
+## Numerical alarm limits (new in v0.4.0)
+
+Each displayed numeric measurement has an **independent optional lower (↓) and
+upper (↑) alarm threshold** in the corresponding Admin section. Alarm fields
+are text inputs; leave a field **blank** (displayed as `off`) to disable just
+that threshold. With both fields blank, the whole numeric alarm is disabled.
+The value may equal either limit without triggering an alarm; only readings
+strictly below/above the respective threshold are out of range. If both limits
+are present, the lower limit must not exceed the upper limit. Invalid input is
+highlighted and the last valid configuration stays active.
+
+| Monitor section | Independently configurable alarms |
+| --- | --- |
+| ECG | HR |
+| SpO₂ | Oxygen saturation (SpO₂), derived pulse rate (PR) |
+| Invasive arterial pressure (ART) | Systolic (SYS), mean (MAP), diastolic (DIA), PPV |
+| NIBP | Systolic (SYS), mean (MAP), diastolic (DIA) |
+| Capnography | End-tidal CO₂ (EtCO₂), respiratory rate (RR) |
+
+The current limits are displayed in small type at the **upper-right corner** of
+each channel, with an arrow for the corresponding direction. A disabled
+boundary is displayed as `---`. For instance:
+
+```text
+⚠ SYS ↑180 ↓80
+ MAP ↑--- ↓60
+ DIA ↑--- ↓---
+```
+
+When a number violates a configured limit, **that number flashes by inverting
+its foreground and background colors** (500 ms inverted / 500 ms normal).
+Each pressure component (SYS, DIA, MAP) and the PPV reading flash independently. The waveform
+itself remains unchanged. All alarms are **disabled by default** so old
+scenarios do not unexpectedly flash.
+
+Numerical threshold alarms only evaluate actual displayed measurements:
+`--`, `NO SENSOR`, and other unavailable readings do not trigger low-value
+alarms. ECG-derived PR and signal visibility continue to work as in v0.3.2.
+Alarms are presentation-only: there is **no audible alarm, alarm latching,
+priority classification or clinical alarm validation**. Instructor settings
+are held in memory and reset on restart.
+
## Patient name and pulse oximeter signal state (new in v0.3.2)
The new **Patient name** text field at the top of Admin immediately replaces the
diff --git a/src/model.rs b/src/model.rs
index 49f373f..81b5e2e 100644
--- a/src/model.rs
+++ b/src/model.rs
@@ -88,9 +88,71 @@ impl Spo2Quality {
}
}
+/// Optional lower and upper bounds for one displayed numeric measurement.
+/// Equal-to-limit values are inside the permitted range.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct AlarmLimits {
+ pub lower: Option<i32>,
+ pub upper: Option<i32>,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum AlarmState {
+ Normal,
+ Low,
+ High,
+}
+
+impl AlarmLimits {
+ pub fn enabled(self) -> bool {
+ self.lower.is_some() || self.upper.is_some()
+ }
+
+ pub fn valid(self) -> bool {
+ match (self.lower, self.upper) {
+ (Some(lo), Some(hi)) => lo <= hi,
+ _ => true,
+ }
+ }
+
+ /// Missing measurements cannot cause threshold-based alarms.
+ pub fn evaluate(self, value: Option<i32>) -> AlarmState {
+ let Some(value) = value else { return AlarmState::Normal; };
+ if self.lower.is_some_and(|lo| value < lo) { return AlarmState::Low; }
+ if self.upper.is_some_and(|hi| value > hi) { return AlarmState::High; }
+ AlarmState::Normal
+ }
+
+ pub fn display(self, name: &str) -> String {
+ fn bound(value: Option<i32>) -> String {
+ value.map_or_else(|| "---".to_owned(), |v| v.to_string())
+ }
+ format!("{} ↑{} ↓{}", name, bound(self.upper), bound(self.lower))
+ }
+}
+
+/// Separate limits for every numeric readout, including derived MAP and PR.
+/// Defaults to all disabled, so adding alarms does not alter old scenarios.
+#[derive(Clone, Debug, Default)]
+pub struct AlarmSettings {
+ pub hr: AlarmLimits,
+ pub spo2: AlarmLimits,
+ pub pr: AlarmLimits,
+ pub art_sys: AlarmLimits,
+ pub art_map: AlarmLimits,
+ pub art_dia: AlarmLimits,
+ pub ppv: AlarmLimits,
+ pub nibp_sys: AlarmLimits,
+ pub nibp_map: AlarmLimits,
+ pub nibp_dia: AlarmLimits,
+ pub etco2: AlarmLimits,
+ pub rr: AlarmLimits,
+}
+
#[derive(Clone, Debug)]
pub struct Parameters {
pub patient_name: String, // displayed in the monitor header, blank = generic title
+ pub alarms: AlarmSettings,
pub ecg_rhythm: EcgRhythm,
pub heart_rate: i32, // bpm, organized electrical rate; not mechanical pulse rate
pub pulse_conduction: PulseConduction,
@@ -118,6 +180,7 @@ impl Default for Parameters {
fn default() -> Self {
Self {
patient_name: String::new(),
+ alarms: AlarmSettings::default(),
ecg_rhythm: EcgRhythm::Sinus,
heart_rate: 75,
pulse_conduction: PulseConduction::OneToOne,
@@ -166,6 +229,42 @@ mod tests {
assert!(Spo2Quality::Adequate.amplitude_scale() < Spo2Quality::Good.amplitude_scale());
}
+ #[test]
+ fn independent_optional_alarm_limits_and_inclusive_boundaries() {
+ let off = AlarmLimits::default();
+ assert!(!off.enabled());
+ assert_eq!(off.evaluate(Some(20)), AlarmState::Normal);
+ let low_only = AlarmLimits { lower: Some(60), upper: None };
+ assert!(low_only.enabled());
+ assert_eq!(low_only.evaluate(Some(59)), AlarmState::Low);
+ assert_eq!(low_only.evaluate(Some(60)), AlarmState::Normal);
+ assert_eq!(low_only.evaluate(None), AlarmState::Normal);
+ assert_eq!(low_only.display("MAP"), "MAP ↑--- ↓60");
+ let high_only = AlarmLimits { lower: None, upper: Some(180) };
+ assert_eq!(high_only.evaluate(Some(181)), AlarmState::High);
+ assert_eq!(high_only.evaluate(Some(180)), AlarmState::Normal);
+ let both = AlarmLimits { lower: Some(80), upper: Some(180) };
+ assert!(both.valid());
+ assert_eq!(both.evaluate(Some(79)), AlarmState::Low);
+ assert_eq!(both.evaluate(Some(181)), AlarmState::High);
+ assert_eq!(both.evaluate(Some(120)), AlarmState::Normal);
+ assert_eq!(both.display("SYS"), "SYS ↑180 ↓80");
+ assert!(!AlarmLimits { lower: Some(181), upper: Some(80) }.valid());
+ }
+
+ #[test]
+ fn all_limits_disabled_by_default() {
+ let p = Parameters::default();
+ assert!(!p.alarms.hr.enabled());
+ assert!(!p.alarms.art_sys.enabled());
+ assert!(!p.alarms.art_map.enabled());
+ assert!(!p.alarms.art_dia.enabled());
+ assert!(!p.alarms.ppv.enabled());
+ assert!(!p.alarms.nibp_sys.enabled());
+ assert!(!p.alarms.spo2.enabled());
+ assert!(!p.alarms.pr.enabled());
+ }
+
#[test]
fn grouped_mechanical_capture_follows_requested_patterns() {
assert_eq!((1..=8).filter(|&b| PulseConduction::TwoToOne.conducts(b)).collect::<Vec<_>>(),
diff --git a/src/render.rs b/src/render.rs
index 70e340e..8391fe8 100644
--- a/src/render.rs
+++ b/src/render.rs
@@ -1,7 +1,7 @@
//! Size-independent Cairo drawing of the synthetic bedside monitor.
use gtk::cairo::{Context, FontSlant, FontWeight, LineCap, LineJoin};
-use crate::model::{mean_arterial_pressure, EcgRhythm, Parameters, PulseConduction, Spo2Quality};
+use crate::model::{mean_arterial_pressure, AlarmLimits, AlarmState, EcgRhythm, Parameters, PulseConduction, Spo2Quality};
use crate::simulation::{Sample, Simulator};
type Color = (f64, f64, f64);
@@ -76,21 +76,28 @@ pub fn draw(cr: &Context, width: i32, height: i32, p: &Parameters, sim: &Simulat
if p.show_nibp {
let footer_top = h - footer;
+ let flash = alarm_flash_on(sim);
+ let mean = mean_arterial_pressure(p.nibp_systolic, p.nibp_diastolic);
text(cr, "NIBP", pad + 6.0, footer_top + footer * 0.32,
(footer * 0.21).clamp(12.0, 20.0), LIGHT_GREY, false);
- text(cr, &format!("{} / {}", p.nibp_systolic, p.nibp_diastolic),
+ draw_pressure_value(cr, p.nibp_systolic, p.nibp_diastolic,
pad + 6.0, footer_top + footer * 0.77,
- (footer * 0.42).clamp(20.0, 44.0), LIGHT_GREY, true);
+ (footer * 0.42).clamp(20.0, 44.0),
+ (w * 0.28).min(255.0).max(70.0), LIGHT_GREY,
+ alarmed(p.alarms.nibp_sys, Some(p.nibp_systolic)),
+ alarmed(p.alarms.nibp_dia, Some(p.nibp_diastolic)), flash);
if w >= 510.0 {
- text(cr, &format!("({}) mmHg", mean_arterial_pressure(p.nibp_systolic, p.nibp_diastolic)),
- pad + (w * 0.28).min(260.0), footer_top + footer * 0.73,
- (footer * 0.24).clamp(12.0, 23.0), LIGHT_GREY, false);
- }
- if w >= 1020.0 {
- text(cr, "SYNTHETIC SIGNALS · NOT FOR CLINICAL USE",
- w * 0.56, footer_top + footer * 0.68,
- 10.0 * text_scale, MUTED, false);
+ draw_alarm_inline(cr, pad + (w * 0.28).min(260.0),
+ footer_top + footer * 0.73, (footer * 0.24).clamp(12.0, 23.0),
+ (w * 0.25).max(90.0), LIGHT_GREY,
+ "MAP ", &mean.to_string(), " mmHg",
+ alarmed(p.alarms.nibp_map, Some(mean)), flash);
}
+ draw_alarm_annotations(cr, &[
+ ("SYS", p.alarms.nibp_sys),
+ ("MAP", p.alarms.nibp_map),
+ ("DIA", p.alarms.nibp_dia),
+ ], w - pad - 8.0, footer_top, footer, (w * 0.24).max(115.0));
}
}
@@ -112,59 +119,222 @@ fn spo2_vitals(p: &Parameters, pulse_rate: Option<i32>) -> (String, String, Stri
)
}
+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
+}
+
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);
- let sub_size = (row_h * 0.16).clamp(11.0, 22.0);
+ let sub_size = (row_h * 0.16).clamp(11.0, 22.0) * 0.85;
+ let flash = alarm_flash_on(sim);
let has_capture = p.ecg_rhythm.has_qrs()
&& p.heart_rate > 0
&& p.pulse_conduction != PulseConduction::None;
let pulse_rate = if has_capture { sim.pulse_rate() } else { None };
- let (label, value, info) = match ch {
- Channel::Ecg => (
- "HR".to_owned(),
- if !p.ecg_rhythm.has_qrs() || p.heart_rate <= 0 { "--".to_owned() }
- else { p.heart_rate.to_string() },
- format!("bpm · {}", match p.ecg_rhythm {
+ let ecg_hr = if p.ecg_rhythm.has_qrs() && p.heart_rate > 0 {
+ Some(p.heart_rate)
+ } else { None };
+ let oxygen = if pleth_trace_enabled(p) && pulse_rate.is_some() {
+ Some(p.spo2)
+ } else { None };
+ let art_map = mean_arterial_pressure(p.art_systolic, p.art_diastolic);
+
+ 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);
+ let rhythm = match p.ecg_rhythm {
EcgRhythm::Sinus => "Sinus",
EcgRhythm::AtrialFibrillation => "AF",
EcgRhythm::VentricularTachycardia => "VT",
EcgRhythm::VentricularFibrillation => "VF",
EcgRhythm::Asystole => "Asystole",
- }),
- ),
- Channel::Pleth => spo2_vitals(p, pulse_rate),
- Channel::Art => (
- "ART".to_owned(),
- if pulse_rate.is_some() {
- format!("{}/{}", p.art_systolic, p.art_diastolic)
- } else { "--/--".to_owned() },
+ };
+ text(cr, &format!("bpm · {}", rhythm), x, info_y, sub_size, color, false);
+ }
+ Channel::Pleth => {
+ let (label, value, info) = spo2_vitals(p, pulse_rate);
+ text(cr, &label, x, top + row_h * 0.24, label_size, color, false);
+ let value_size = if value == "NO SENSOR" {
+ number_size.min(0.19 * width).min(26.0)
+ } else { number_size };
+ draw_alarm_number(cr, &value, x, value_y, value_size,
+ width, color, alarmed(p.alarms.spo2, oxygen), flash);
+ 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);
if pulse_rate.is_some() {
- if p.pulse_pressure_variation > 0 {
- format!("MAP {} · PPV {}%",
- mean_arterial_pressure(p.art_systolic, p.art_diastolic),
- p.pulse_pressure_variation)
+ draw_pressure_value(cr, p.art_systolic, p.art_diastolic,
+ x, value_y, number_size * 0.78, width, color,
+ alarmed(p.alarms.art_sys, Some(p.art_systolic)),
+ alarmed(p.alarms.art_dia, Some(p.art_diastolic)), flash);
+ if p.pulse_pressure_variation > 0 || p.alarms.ppv.enabled() {
+ let map_text = art_map.to_string();
+ 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, Some(art_map))),
+ (" · PPV ", false),
+ (&ppv_text, alarmed(p.alarms.ppv, Some(p.pulse_pressure_variation))),
+ ("%", false),
+ ], flash);
} else {
- format!("MAP {} mmHg", mean_arterial_pressure(p.art_systolic, p.art_diastolic))
+ draw_alarm_inline(cr, x, info_y, sub_size, width, color,
+ "MAP ", &art_map.to_string(), " mmHg",
+ alarmed(p.alarms.art_map, Some(art_map)), flash);
}
- } else { "MAP -- mmHg".to_owned() },
- ),
- Channel::Capno => ("EtCO₂".to_owned(), p.etco2.to_string(),
- format!("mmHg RR {} /min", p.respiratory_rate)),
- };
- text(cr, &label, x, top + row_h * 0.24, label_size, color, false);
- // Reduce wide readings so they fit within the sidebar.
- let value_size = if value == "NO SENSOR" {
- number_size.min(0.19 * width).min(26.0)
- } else if matches!(ch, Channel::Art) {
- number_size * 0.78
- } else {
- number_size
- };
- fitted_text(cr, &value, x, top + row_h * 0.64, value_size,
- width.max(20.0), color);
- text(cr, &info, x, top + row_h * 0.87, sub_size * 0.85, color, false);
+ } else {
+ draw_alarm_number(cr, "--/--", x, value_y, number_size * 0.78,
+ width, color, false, flash);
+ text(cr, "MAP -- mmHg", x, info_y, sub_size, color, false);
+ }
+ }
+ 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();
+}
+
+/// Draw pressure components independently: only SYS or DIA flashes when it
+/// breaches its respective limit. The separator remains the normal color.
+#[allow(clippy::too_many_arguments)]
+fn draw_pressure_value(cr: &Context, systolic: i32, diastolic: i32,
+ x: f64, baseline: f64, nominal_size: f64,
+ available_width: f64, color: Color,
+ sys_alarm: bool, dia_alarm: bool, flash: bool) {
+ let sys = systolic.to_string();
+ let dia = diastolic.to_string();
+ 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);
+ cursor += draw_segment(cr, "/", cursor, baseline, size, color, false, true);
+ draw_segment(cr, &dia, cursor, baseline, size, color, dia_alarm && flash, true);
+ 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 }
}
#[allow(clippy::too_many_arguments)]
@@ -321,6 +491,17 @@ fn text(cr: &Context, value: &str, x: f64, baseline: f64,
mod tests {
use super::*;
+ #[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());
+ }
+
#[test]
fn toggled_channels_disappear_and_remaining_rows_reflow() {
let mut p = Parameters::default();
diff --git a/src/ui.rs b/src/ui.rs
index a68fcc3..6d1e913 100644
--- a/src/ui.rs
+++ b/src/ui.rs
@@ -8,7 +8,7 @@ use gtk::glib;
use gtk::prelude::*;
use gtk::{Application, ApplicationWindow, Orientation};
-use crate::model::{ArterialShape, CapnoShape, EcgRhythm, Parameters, PulseConduction, Spo2Quality};
+use crate::model::{AlarmLimits, ArterialShape, CapnoShape, EcgRhythm, Parameters, PulseConduction, Spo2Quality};
use crate::render;
use crate::simulation::Simulator;
@@ -104,6 +104,12 @@ fn create_admin(app: &Application, params: SharedParams,
scroller.set_vexpand(true);
scroller.set_policy(gtk::PolicyType::Never, gtk::PolicyType::Automatic);
let controls = gtk::Box::new(Orientation::Vertical, 12);
+ let alarm_hint = gtk::Label::new(Some(
+ "Alarm limits: ↓ lower, ↑ upper; leave a field empty to disable that limit."
+ ));
+ alarm_hint.set_xalign(0.0);
+ alarm_hint.set_wrap(true);
+ controls.append(&alarm_hint);
let patient = group(&controls, "Patient");
let patient_row = gtk::Box::new(Orientation::Horizontal, 8);
@@ -139,11 +145,17 @@ fn create_admin(app: &Application, params: SharedParams,
});
add_numeric(&ecg, "Heart rate", "bpm", 0, 240, params.borrow().heart_rate,
params.clone(), |p, v| p.heart_rate = v);
+ add_alarm_limits(&ecg, "HR alarm limits", "bpm", 240,
+ params.borrow().alarms.hr, params.clone(), |p, v| p.alarms.hr = v);
let spo2 = group(&controls, "Pulse oximetry");
add_visibility(&spo2, params.borrow().show_spo2, params.clone(), |p, show| p.show_spo2 = show);
add_numeric(&spo2, "SpO₂", "%", 0, 100, params.borrow().spo2,
params.clone(), |p, v| p.spo2 = v);
+ add_alarm_limits(&spo2, "SpO₂ alarm limits", "%", 100,
+ params.borrow().alarms.spo2, params.clone(), |p, v| p.alarms.spo2 = v);
+ add_alarm_limits(&spo2, "PR alarm limits", "bpm", 240,
+ params.borrow().alarms.pr, params.clone(), |p, v| p.alarms.pr = v);
let sensor = gtk::CheckButton::with_label("Sensor not attached");
sensor.set_active(!params.borrow().spo2_sensor_attached);
sensor.connect_toggled({
@@ -193,9 +205,17 @@ ART and pleth are delayed; VF and asystole always have no pulse."
params.clone(), |p, v| p.art_systolic = v);
add_numeric(&art, "Diastolic", "mmHg", 0, 200, params.borrow().art_diastolic,
params.clone(), |p, v| p.art_diastolic = v);
+ add_alarm_limits(&art, "SYS alarm limits", "mmHg", 200,
+ params.borrow().alarms.art_sys, params.clone(), |p, v| p.alarms.art_sys = v);
+ add_alarm_limits(&art, "MAP alarm limits", "mmHg", 200,
+ params.borrow().alarms.art_map, params.clone(), |p, v| p.alarms.art_map = v);
+ add_alarm_limits(&art, "DIA alarm limits", "mmHg", 200,
+ params.borrow().alarms.art_dia, params.clone(), |p, v| p.alarms.art_dia = v);
add_numeric(&art, "Pulse pressure variation", "%", 0, 60,
params.borrow().pulse_pressure_variation, params.clone(),
|p, v| p.pulse_pressure_variation = v);
+ add_alarm_limits(&art, "PPV alarm limits", "%", 60,
+ params.borrow().alarms.ppv, params.clone(), |p, v| p.alarms.ppv = v);
let ppv_hint = gtk::Label::new(Some(
"Respiratory pulse-pressure swing (PPV). 0% = off; requires RR > 0."
));
@@ -219,6 +239,13 @@ ART and pleth are delayed; VF and asystole always have no pulse."
add_numeric(&nibp, "Diastolic", "mmHg", 0, 200, params.borrow().nibp_diastolic,
params.clone(), |p, v| p.nibp_diastolic = v);
+ add_alarm_limits(&nibp, "SYS alarm limits", "mmHg", 260,
+ params.borrow().alarms.nibp_sys, params.clone(), |p, v| p.alarms.nibp_sys = v);
+ add_alarm_limits(&nibp, "MAP alarm limits", "mmHg", 260,
+ params.borrow().alarms.nibp_map, params.clone(), |p, v| p.alarms.nibp_map = v);
+ add_alarm_limits(&nibp, "DIA alarm limits", "mmHg", 200,
+ params.borrow().alarms.nibp_dia, params.clone(), |p, v| p.alarms.nibp_dia = v);
+
let capno = group(&controls, "Capnography");
add_visibility(&capno, params.borrow().show_capno, params.clone(), |p, show| p.show_capno = show);
add_dropdown(&capno, "Capnogram", &["Normal", "Obstructive / shark fin"],
@@ -231,6 +258,11 @@ ART and pleth are delayed; VF and asystole always have no pulse."
add_numeric(&capno, "Respiratory rate", "/min", 0, 60, params.borrow().respiratory_rate,
params.clone(), |p, v| p.respiratory_rate = v);
+ add_alarm_limits(&capno, "EtCO₂ alarm limits", "mmHg", 100,
+ params.borrow().alarms.etco2, params.clone(), |p, v| p.alarms.etco2 = v);
+ add_alarm_limits(&capno, "RR alarm limits", "/min", 60,
+ params.borrow().alarms.rr, params.clone(), |p, v| p.alarms.rr = v);
+
scroller.set_child(Some(&controls));
main_box.append(&scroller);
@@ -369,3 +401,84 @@ fn normalize_entry(entry: &gtk::Entry, slider: &gtk::Scale, min: i32, max: i32)
slider.set_value(f64::from(value));
entry.set_text(&value.to_string());
}
+
+/// Thresholds deliberately use *optional* text entries, not sliders: an empty
+/// field disables that side of the alarm. Non-numeric or reversed limits are
+/// highlighted and do not replace the last valid alarm configuration.
+fn add_alarm_limits<F>(parent: &gtk::Box, label: &str, unit: &str, max: i32,
+ initial: AlarmLimits, params: SharedParams, setter: F)
+where F: Fn(&mut Parameters, AlarmLimits) + 'static {
+ let row = gtk::Box::new(Orientation::Horizontal, 8);
+ let caption = gtk::Label::new(Some(label));
+ caption.set_xalign(0.0);
+ caption.set_width_chars(17);
+ let low_label = gtk::Label::new(Some("↓"));
+ let high_label = gtk::Label::new(Some("↑"));
+ let low_entry = alarm_entry(initial.lower, "off");
+ let high_entry = alarm_entry(initial.upper, "off");
+ let suffix = gtk::Label::new(Some(unit));
+ suffix.set_xalign(0.0);
+ suffix.set_width_chars(5);
+ row.append(&caption);
+ row.append(&low_label);
+ row.append(&low_entry);
+ row.append(&high_label);
+ row.append(&high_entry);
+ row.append(&suffix);
+ parent.append(&row);
+
+ let setter: Rc<dyn Fn(&mut Parameters, AlarmLimits)> = Rc::new(setter);
+ low_entry.connect_changed({
+ let high_entry = high_entry.clone();
+ let params = params.clone();
+ let setter = setter.clone();
+ move |low_entry| {
+ update_alarm_limits(low_entry, &high_entry, max, &params, &setter);
+ }
+ });
+ high_entry.connect_changed({
+ let low_entry = low_entry.clone();
+ move |high_entry| {
+ update_alarm_limits(&low_entry, high_entry, max, &params, &setter);
+ }
+ });
+}
+
+fn alarm_entry(initial: Option<i32>, placeholder: &str) -> gtk::Entry {
+ let entry = gtk::Entry::new();
+ entry.set_width_chars(4);
+ entry.set_max_width_chars(5);
+ entry.set_input_purpose(gtk::InputPurpose::Digits);
+ entry.set_placeholder_text(Some(placeholder));
+ if let Some(value) = initial { entry.set_text(&value.to_string()); }
+ entry
+}
+
+fn parse_alarm_bound(entry: &gtk::Entry, max: i32) -> Result<Option<i32>, ()> {
+ let raw = entry.text();
+ let trimmed = raw.trim();
+ if trimmed.is_empty() { return Ok(None); }
+ match trimmed.parse::<i32>() {
+ Ok(value) if (0..=max).contains(&value) => Ok(Some(value)),
+ _ => Err(()),
+ }
+}
+
+fn update_alarm_limits(low_entry: &gtk::Entry, high_entry: &gtk::Entry, max: i32,
+ params: &SharedParams,
+ setter: &Rc<dyn Fn(&mut Parameters, AlarmLimits)>) {
+ let lower = parse_alarm_bound(low_entry, max);
+ let upper = parse_alarm_bound(high_entry, max);
+ let order_valid = match (&lower, &upper) {
+ (Ok(lo), Ok(hi)) => AlarmLimits { lower: *lo, upper: *hi }.valid(),
+ _ => true,
+ };
+ if lower.is_err() || !order_valid { low_entry.add_css_class("error"); }
+ else { low_entry.remove_css_class("error"); }
+ if upper.is_err() || !order_valid { high_entry.add_css_class("error"); }
+ else { high_entry.remove_css_class("error"); }
+ if let (Ok(lower), Ok(upper)) = (lower, upper) {
+ let limits = AlarmLimits { lower, upper };
+ if limits.valid() { setter(&mut params.borrow_mut(), limits); }
+ }
+}

View file

@ -438,7 +438,7 @@ dependencies = [
[[package]] [[package]]
name = "patient-monitor-simulation" name = "patient-monitor-simulation"
version = "0.3.2" version = "0.4.0"
dependencies = [ dependencies = [
"gtk4", "gtk4",
] ]

View file

@ -1,6 +1,6 @@
[package] [package]
name = "patient-monitor-simulation" name = "patient-monitor-simulation"
version = "0.3.2" version = "0.4.0"
edition = "2021" edition = "2021"
license = "MIT" license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)" description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"

View file

@ -1,4 +1,4 @@
# Patient Monitor Simulation (PaMSim) — v0.3.2 # Patient Monitor Simulation (PaMSim) — v0.4.0
A two-window, Rust/GTK4 patient-monitor simulator for teaching on Fedora Linux. A two-window, Rust/GTK4 patient-monitor simulator for teaching on Fedora Linux.
@ -40,6 +40,48 @@ The monitor can be resized and toggled fullscreen with **F11**; **Esc** exits
fullscreen. On Wayland, move the monitor to the presentation screen before fullscreen. On Wayland, move the monitor to the presentation screen before
activating fullscreen. Fullscreen does not lock down the computer. activating fullscreen. Fullscreen does not lock down the computer.
## Numerical alarm limits (new in v0.4.0)
Each displayed numeric measurement has an **independent optional lower (↓) and
upper (↑) alarm threshold** in the corresponding Admin section. Alarm fields
are text inputs; leave a field **blank** (displayed as `off`) to disable just
that threshold. With both fields blank, the whole numeric alarm is disabled.
The value may equal either limit without triggering an alarm; only readings
strictly below/above the respective threshold are out of range. If both limits
are present, the lower limit must not exceed the upper limit. Invalid input is
highlighted and the last valid configuration stays active.
| Monitor section | Independently configurable alarms |
| --- | --- |
| ECG | HR |
| SpO₂ | Oxygen saturation (SpO₂), derived pulse rate (PR) |
| Invasive arterial pressure (ART) | Systolic (SYS), mean (MAP), diastolic (DIA), PPV |
| NIBP | Systolic (SYS), mean (MAP), diastolic (DIA) |
| Capnography | End-tidal CO₂ (EtCO₂), respiratory rate (RR) |
The current limits are displayed in small type at the **upper-right corner** of
each channel, with an arrow for the corresponding direction. A disabled
boundary is displayed as `---`. For instance:
```text
⚠ SYS ↑180 ↓80
MAP ↑--- ↓60
DIA ↑--- ↓---
```
When a number violates a configured limit, **that number flashes by inverting
its foreground and background colors** (500 ms inverted / 500 ms normal).
Each pressure component (SYS, DIA, MAP) and the PPV reading flash independently. The waveform
itself remains unchanged. All alarms are **disabled by default** so old
scenarios do not unexpectedly flash.
Numerical threshold alarms only evaluate actual displayed measurements:
`--`, `NO SENSOR`, and other unavailable readings do not trigger low-value
alarms. ECG-derived PR and signal visibility continue to work as in v0.3.2.
Alarms are presentation-only: there is **no audible alarm, alarm latching,
priority classification or clinical alarm validation**. Instructor settings
are held in memory and reset on restart.
## Patient name and pulse oximeter signal state (new in v0.3.2) ## Patient name and pulse oximeter signal state (new in v0.3.2)
The new **Patient name** text field at the top of Admin immediately replaces the The new **Patient name** text field at the top of Admin immediately replaces the

View file

@ -88,9 +88,71 @@ impl Spo2Quality {
} }
} }
/// Optional lower and upper bounds for one displayed numeric measurement.
/// Equal-to-limit values are inside the permitted range.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct AlarmLimits {
pub lower: Option<i32>,
pub upper: Option<i32>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AlarmState {
Normal,
Low,
High,
}
impl AlarmLimits {
pub fn enabled(self) -> bool {
self.lower.is_some() || self.upper.is_some()
}
pub fn valid(self) -> bool {
match (self.lower, self.upper) {
(Some(lo), Some(hi)) => lo <= hi,
_ => true,
}
}
/// Missing measurements cannot cause threshold-based alarms.
pub fn evaluate(self, value: Option<i32>) -> AlarmState {
let Some(value) = value else { return AlarmState::Normal; };
if self.lower.is_some_and(|lo| value < lo) { return AlarmState::Low; }
if self.upper.is_some_and(|hi| value > hi) { return AlarmState::High; }
AlarmState::Normal
}
pub fn display(self, name: &str) -> String {
fn bound(value: Option<i32>) -> String {
value.map_or_else(|| "---".to_owned(), |v| v.to_string())
}
format!("{} ↑{} ↓{}", name, bound(self.upper), bound(self.lower))
}
}
/// Separate limits for every numeric readout, including derived MAP and PR.
/// Defaults to all disabled, so adding alarms does not alter old scenarios.
#[derive(Clone, Debug, Default)]
pub struct AlarmSettings {
pub hr: AlarmLimits,
pub spo2: AlarmLimits,
pub pr: AlarmLimits,
pub art_sys: AlarmLimits,
pub art_map: AlarmLimits,
pub art_dia: AlarmLimits,
pub ppv: AlarmLimits,
pub nibp_sys: AlarmLimits,
pub nibp_map: AlarmLimits,
pub nibp_dia: AlarmLimits,
pub etco2: AlarmLimits,
pub rr: AlarmLimits,
}
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct Parameters { pub struct Parameters {
pub patient_name: String, // displayed in the monitor header, blank = generic title pub patient_name: String, // displayed in the monitor header, blank = generic title
pub alarms: AlarmSettings,
pub ecg_rhythm: EcgRhythm, pub ecg_rhythm: EcgRhythm,
pub heart_rate: i32, // bpm, organized electrical rate; not mechanical pulse rate pub heart_rate: i32, // bpm, organized electrical rate; not mechanical pulse rate
pub pulse_conduction: PulseConduction, pub pulse_conduction: PulseConduction,
@ -118,6 +180,7 @@ impl Default for Parameters {
fn default() -> Self { fn default() -> Self {
Self { Self {
patient_name: String::new(), patient_name: String::new(),
alarms: AlarmSettings::default(),
ecg_rhythm: EcgRhythm::Sinus, ecg_rhythm: EcgRhythm::Sinus,
heart_rate: 75, heart_rate: 75,
pulse_conduction: PulseConduction::OneToOne, pulse_conduction: PulseConduction::OneToOne,
@ -166,6 +229,42 @@ mod tests {
assert!(Spo2Quality::Adequate.amplitude_scale() < Spo2Quality::Good.amplitude_scale()); assert!(Spo2Quality::Adequate.amplitude_scale() < Spo2Quality::Good.amplitude_scale());
} }
#[test]
fn independent_optional_alarm_limits_and_inclusive_boundaries() {
let off = AlarmLimits::default();
assert!(!off.enabled());
assert_eq!(off.evaluate(Some(20)), AlarmState::Normal);
let low_only = AlarmLimits { lower: Some(60), upper: None };
assert!(low_only.enabled());
assert_eq!(low_only.evaluate(Some(59)), AlarmState::Low);
assert_eq!(low_only.evaluate(Some(60)), AlarmState::Normal);
assert_eq!(low_only.evaluate(None), AlarmState::Normal);
assert_eq!(low_only.display("MAP"), "MAP ↑--- ↓60");
let high_only = AlarmLimits { lower: None, upper: Some(180) };
assert_eq!(high_only.evaluate(Some(181)), AlarmState::High);
assert_eq!(high_only.evaluate(Some(180)), AlarmState::Normal);
let both = AlarmLimits { lower: Some(80), upper: Some(180) };
assert!(both.valid());
assert_eq!(both.evaluate(Some(79)), AlarmState::Low);
assert_eq!(both.evaluate(Some(181)), AlarmState::High);
assert_eq!(both.evaluate(Some(120)), AlarmState::Normal);
assert_eq!(both.display("SYS"), "SYS ↑180 ↓80");
assert!(!AlarmLimits { lower: Some(181), upper: Some(80) }.valid());
}
#[test]
fn all_limits_disabled_by_default() {
let p = Parameters::default();
assert!(!p.alarms.hr.enabled());
assert!(!p.alarms.art_sys.enabled());
assert!(!p.alarms.art_map.enabled());
assert!(!p.alarms.art_dia.enabled());
assert!(!p.alarms.ppv.enabled());
assert!(!p.alarms.nibp_sys.enabled());
assert!(!p.alarms.spo2.enabled());
assert!(!p.alarms.pr.enabled());
}
#[test] #[test]
fn grouped_mechanical_capture_follows_requested_patterns() { fn grouped_mechanical_capture_follows_requested_patterns() {
assert_eq!((1..=8).filter(|&b| PulseConduction::TwoToOne.conducts(b)).collect::<Vec<_>>(), assert_eq!((1..=8).filter(|&b| PulseConduction::TwoToOne.conducts(b)).collect::<Vec<_>>(),

View file

@ -1,7 +1,7 @@
//! Size-independent Cairo drawing of the synthetic bedside monitor. //! Size-independent Cairo drawing of the synthetic bedside monitor.
use gtk::cairo::{Context, FontSlant, FontWeight, LineCap, LineJoin}; use gtk::cairo::{Context, FontSlant, FontWeight, LineCap, LineJoin};
use crate::model::{mean_arterial_pressure, EcgRhythm, Parameters, PulseConduction, Spo2Quality}; use crate::model::{mean_arterial_pressure, AlarmLimits, AlarmState, EcgRhythm, Parameters, PulseConduction, Spo2Quality};
use crate::simulation::{Sample, Simulator}; use crate::simulation::{Sample, Simulator};
type Color = (f64, f64, f64); type Color = (f64, f64, f64);
@ -76,21 +76,28 @@ pub fn draw(cr: &Context, width: i32, height: i32, p: &Parameters, sim: &Simulat
if p.show_nibp { if p.show_nibp {
let footer_top = h - footer; let footer_top = h - footer;
let flash = alarm_flash_on(sim);
let mean = mean_arterial_pressure(p.nibp_systolic, p.nibp_diastolic);
text(cr, "NIBP", pad + 6.0, footer_top + footer * 0.32, text(cr, "NIBP", pad + 6.0, footer_top + footer * 0.32,
(footer * 0.21).clamp(12.0, 20.0), LIGHT_GREY, false); (footer * 0.21).clamp(12.0, 20.0), LIGHT_GREY, false);
text(cr, &format!("{} / {}", p.nibp_systolic, p.nibp_diastolic), draw_pressure_value(cr, p.nibp_systolic, p.nibp_diastolic,
pad + 6.0, footer_top + footer * 0.77, pad + 6.0, footer_top + footer * 0.77,
(footer * 0.42).clamp(20.0, 44.0), LIGHT_GREY, true); (footer * 0.42).clamp(20.0, 44.0),
(w * 0.28).min(255.0).max(70.0), LIGHT_GREY,
alarmed(p.alarms.nibp_sys, Some(p.nibp_systolic)),
alarmed(p.alarms.nibp_dia, Some(p.nibp_diastolic)), flash);
if w >= 510.0 { if w >= 510.0 {
text(cr, &format!("({}) mmHg", mean_arterial_pressure(p.nibp_systolic, p.nibp_diastolic)), draw_alarm_inline(cr, pad + (w * 0.28).min(260.0),
pad + (w * 0.28).min(260.0), footer_top + footer * 0.73, footer_top + footer * 0.73, (footer * 0.24).clamp(12.0, 23.0),
(footer * 0.24).clamp(12.0, 23.0), LIGHT_GREY, false); (w * 0.25).max(90.0), LIGHT_GREY,
} "MAP ", &mean.to_string(), " mmHg",
if w >= 1020.0 { alarmed(p.alarms.nibp_map, Some(mean)), flash);
text(cr, "SYNTHETIC SIGNALS · NOT FOR CLINICAL USE",
w * 0.56, footer_top + footer * 0.68,
10.0 * text_scale, MUTED, false);
} }
draw_alarm_annotations(cr, &[
("SYS", p.alarms.nibp_sys),
("MAP", p.alarms.nibp_map),
("DIA", p.alarms.nibp_dia),
], w - pad - 8.0, footer_top, footer, (w * 0.24).max(115.0));
} }
} }
@ -112,59 +119,222 @@ fn spo2_vitals(p: &Parameters, pulse_rate: Option<i32>) -> (String, String, Stri
) )
} }
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
}
fn draw_vitals(cr: &Context, ch: Channel, color: Color, x: f64, fn draw_vitals(cr: &Context, ch: Channel, color: Color, x: f64,
top: f64, row_h: f64, width: f64, p: &Parameters, sim: &Simulator) { top: f64, row_h: f64, width: f64, p: &Parameters, sim: &Simulator) {
let label_size = (row_h * 0.135).clamp(11.0, 19.0); 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); let number_size = (row_h * 0.375).min(width * 0.26).clamp(16.0, 59.0);
let sub_size = (row_h * 0.16).clamp(11.0, 22.0); let sub_size = (row_h * 0.16).clamp(11.0, 22.0) * 0.85;
let flash = alarm_flash_on(sim);
let has_capture = p.ecg_rhythm.has_qrs() let has_capture = p.ecg_rhythm.has_qrs()
&& p.heart_rate > 0 && p.heart_rate > 0
&& p.pulse_conduction != PulseConduction::None; && p.pulse_conduction != PulseConduction::None;
let pulse_rate = if has_capture { sim.pulse_rate() } else { None }; let pulse_rate = if has_capture { sim.pulse_rate() } else { None };
let (label, value, info) = match ch { let ecg_hr = if p.ecg_rhythm.has_qrs() && p.heart_rate > 0 {
Channel::Ecg => ( Some(p.heart_rate)
"HR".to_owned(), } else { None };
if !p.ecg_rhythm.has_qrs() || p.heart_rate <= 0 { "--".to_owned() } let oxygen = if pleth_trace_enabled(p) && pulse_rate.is_some() {
else { p.heart_rate.to_string() }, Some(p.spo2)
format!("bpm · {}", match p.ecg_rhythm { } else { None };
let art_map = mean_arterial_pressure(p.art_systolic, p.art_diastolic);
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);
let rhythm = match p.ecg_rhythm {
EcgRhythm::Sinus => "Sinus", EcgRhythm::Sinus => "Sinus",
EcgRhythm::AtrialFibrillation => "AF", EcgRhythm::AtrialFibrillation => "AF",
EcgRhythm::VentricularTachycardia => "VT", EcgRhythm::VentricularTachycardia => "VT",
EcgRhythm::VentricularFibrillation => "VF", EcgRhythm::VentricularFibrillation => "VF",
EcgRhythm::Asystole => "Asystole", EcgRhythm::Asystole => "Asystole",
}),
),
Channel::Pleth => spo2_vitals(p, pulse_rate),
Channel::Art => (
"ART".to_owned(),
if pulse_rate.is_some() {
format!("{}/{}", p.art_systolic, p.art_diastolic)
} else { "--/--".to_owned() },
if pulse_rate.is_some() {
if p.pulse_pressure_variation > 0 {
format!("MAP {} · PPV {}%",
mean_arterial_pressure(p.art_systolic, p.art_diastolic),
p.pulse_pressure_variation)
} else {
format!("MAP {} mmHg", mean_arterial_pressure(p.art_systolic, p.art_diastolic))
}
} else { "MAP -- mmHg".to_owned() },
),
Channel::Capno => ("EtCO₂".to_owned(), p.etco2.to_string(),
format!("mmHg RR {} /min", p.respiratory_rate)),
}; };
text(cr, &format!("bpm · {}", rhythm), x, info_y, sub_size, color, false);
}
Channel::Pleth => {
let (label, value, info) = spo2_vitals(p, pulse_rate);
text(cr, &label, x, top + row_h * 0.24, label_size, color, false); text(cr, &label, x, top + row_h * 0.24, label_size, color, false);
// Reduce wide readings so they fit within the sidebar.
let value_size = if value == "NO SENSOR" { let value_size = if value == "NO SENSOR" {
number_size.min(0.19 * width).min(26.0) number_size.min(0.19 * width).min(26.0)
} else if matches!(ch, Channel::Art) { } else { number_size };
number_size * 0.78 draw_alarm_number(cr, &value, x, value_y, value_size,
width, color, alarmed(p.alarms.spo2, oxygen), flash);
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 { } else {
number_size text(cr, &info, x, info_y, sub_size, color, false);
}; }
fitted_text(cr, &value, x, top + row_h * 0.64, value_size, }
width.max(20.0), color); Channel::Art => {
text(cr, &info, x, top + row_h * 0.87, sub_size * 0.85, color, false); text(cr, "ART", x, top + row_h * 0.24, label_size, color, false);
if pulse_rate.is_some() {
draw_pressure_value(cr, p.art_systolic, p.art_diastolic,
x, value_y, number_size * 0.78, width, color,
alarmed(p.alarms.art_sys, Some(p.art_systolic)),
alarmed(p.alarms.art_dia, Some(p.art_diastolic)), flash);
if p.pulse_pressure_variation > 0 || p.alarms.ppv.enabled() {
let map_text = art_map.to_string();
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, Some(art_map))),
(" · PPV ", false),
(&ppv_text, alarmed(p.alarms.ppv, Some(p.pulse_pressure_variation))),
("%", false),
], flash);
} else {
draw_alarm_inline(cr, x, info_y, sub_size, width, color,
"MAP ", &art_map.to_string(), " mmHg",
alarmed(p.alarms.art_map, Some(art_map)), flash);
}
} else {
draw_alarm_number(cr, "--/--", x, value_y, number_size * 0.78,
width, color, false, flash);
text(cr, "MAP -- mmHg", x, info_y, sub_size, color, false);
}
}
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();
}
/// Draw pressure components independently: only SYS or DIA flashes when it
/// breaches its respective limit. The separator remains the normal color.
#[allow(clippy::too_many_arguments)]
fn draw_pressure_value(cr: &Context, systolic: i32, diastolic: i32,
x: f64, baseline: f64, nominal_size: f64,
available_width: f64, color: Color,
sys_alarm: bool, dia_alarm: bool, flash: bool) {
let sys = systolic.to_string();
let dia = diastolic.to_string();
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);
cursor += draw_segment(cr, "/", cursor, baseline, size, color, false, true);
draw_segment(cr, &dia, cursor, baseline, size, color, dia_alarm && flash, true);
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 }
} }
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
@ -321,6 +491,17 @@ fn text(cr: &Context, value: &str, x: f64, baseline: f64,
mod tests { mod tests {
use super::*; use super::*;
#[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());
}
#[test] #[test]
fn toggled_channels_disappear_and_remaining_rows_reflow() { fn toggled_channels_disappear_and_remaining_rows_reflow() {
let mut p = Parameters::default(); let mut p = Parameters::default();

View file

@ -8,7 +8,7 @@ use gtk::glib;
use gtk::prelude::*; use gtk::prelude::*;
use gtk::{Application, ApplicationWindow, Orientation}; use gtk::{Application, ApplicationWindow, Orientation};
use crate::model::{ArterialShape, CapnoShape, EcgRhythm, Parameters, PulseConduction, Spo2Quality}; use crate::model::{AlarmLimits, ArterialShape, CapnoShape, EcgRhythm, Parameters, PulseConduction, Spo2Quality};
use crate::render; use crate::render;
use crate::simulation::Simulator; use crate::simulation::Simulator;
@ -104,6 +104,12 @@ fn create_admin(app: &Application, params: SharedParams,
scroller.set_vexpand(true); scroller.set_vexpand(true);
scroller.set_policy(gtk::PolicyType::Never, gtk::PolicyType::Automatic); scroller.set_policy(gtk::PolicyType::Never, gtk::PolicyType::Automatic);
let controls = gtk::Box::new(Orientation::Vertical, 12); let controls = gtk::Box::new(Orientation::Vertical, 12);
let alarm_hint = gtk::Label::new(Some(
"Alarm limits: ↓ lower, ↑ upper; leave a field empty to disable that limit."
));
alarm_hint.set_xalign(0.0);
alarm_hint.set_wrap(true);
controls.append(&alarm_hint);
let patient = group(&controls, "Patient"); let patient = group(&controls, "Patient");
let patient_row = gtk::Box::new(Orientation::Horizontal, 8); let patient_row = gtk::Box::new(Orientation::Horizontal, 8);
@ -139,11 +145,17 @@ fn create_admin(app: &Application, params: SharedParams,
}); });
add_numeric(&ecg, "Heart rate", "bpm", 0, 240, params.borrow().heart_rate, add_numeric(&ecg, "Heart rate", "bpm", 0, 240, params.borrow().heart_rate,
params.clone(), |p, v| p.heart_rate = v); params.clone(), |p, v| p.heart_rate = v);
add_alarm_limits(&ecg, "HR alarm limits", "bpm", 240,
params.borrow().alarms.hr, params.clone(), |p, v| p.alarms.hr = v);
let spo2 = group(&controls, "Pulse oximetry"); let spo2 = group(&controls, "Pulse oximetry");
add_visibility(&spo2, params.borrow().show_spo2, params.clone(), |p, show| p.show_spo2 = show); add_visibility(&spo2, params.borrow().show_spo2, params.clone(), |p, show| p.show_spo2 = show);
add_numeric(&spo2, "SpO₂", "%", 0, 100, params.borrow().spo2, add_numeric(&spo2, "SpO₂", "%", 0, 100, params.borrow().spo2,
params.clone(), |p, v| p.spo2 = v); params.clone(), |p, v| p.spo2 = v);
add_alarm_limits(&spo2, "SpO₂ alarm limits", "%", 100,
params.borrow().alarms.spo2, params.clone(), |p, v| p.alarms.spo2 = v);
add_alarm_limits(&spo2, "PR alarm limits", "bpm", 240,
params.borrow().alarms.pr, params.clone(), |p, v| p.alarms.pr = v);
let sensor = gtk::CheckButton::with_label("Sensor not attached"); let sensor = gtk::CheckButton::with_label("Sensor not attached");
sensor.set_active(!params.borrow().spo2_sensor_attached); sensor.set_active(!params.borrow().spo2_sensor_attached);
sensor.connect_toggled({ sensor.connect_toggled({
@ -193,9 +205,17 @@ ART and pleth are delayed; VF and asystole always have no pulse."
params.clone(), |p, v| p.art_systolic = v); params.clone(), |p, v| p.art_systolic = v);
add_numeric(&art, "Diastolic", "mmHg", 0, 200, params.borrow().art_diastolic, add_numeric(&art, "Diastolic", "mmHg", 0, 200, params.borrow().art_diastolic,
params.clone(), |p, v| p.art_diastolic = v); params.clone(), |p, v| p.art_diastolic = v);
add_alarm_limits(&art, "SYS alarm limits", "mmHg", 200,
params.borrow().alarms.art_sys, params.clone(), |p, v| p.alarms.art_sys = v);
add_alarm_limits(&art, "MAP alarm limits", "mmHg", 200,
params.borrow().alarms.art_map, params.clone(), |p, v| p.alarms.art_map = v);
add_alarm_limits(&art, "DIA alarm limits", "mmHg", 200,
params.borrow().alarms.art_dia, params.clone(), |p, v| p.alarms.art_dia = v);
add_numeric(&art, "Pulse pressure variation", "%", 0, 60, add_numeric(&art, "Pulse pressure variation", "%", 0, 60,
params.borrow().pulse_pressure_variation, params.clone(), params.borrow().pulse_pressure_variation, params.clone(),
|p, v| p.pulse_pressure_variation = v); |p, v| p.pulse_pressure_variation = v);
add_alarm_limits(&art, "PPV alarm limits", "%", 60,
params.borrow().alarms.ppv, params.clone(), |p, v| p.alarms.ppv = v);
let ppv_hint = gtk::Label::new(Some( let ppv_hint = gtk::Label::new(Some(
"Respiratory pulse-pressure swing (PPV). 0% = off; requires RR > 0." "Respiratory pulse-pressure swing (PPV). 0% = off; requires RR > 0."
)); ));
@ -219,6 +239,13 @@ ART and pleth are delayed; VF and asystole always have no pulse."
add_numeric(&nibp, "Diastolic", "mmHg", 0, 200, params.borrow().nibp_diastolic, add_numeric(&nibp, "Diastolic", "mmHg", 0, 200, params.borrow().nibp_diastolic,
params.clone(), |p, v| p.nibp_diastolic = v); params.clone(), |p, v| p.nibp_diastolic = v);
add_alarm_limits(&nibp, "SYS alarm limits", "mmHg", 260,
params.borrow().alarms.nibp_sys, params.clone(), |p, v| p.alarms.nibp_sys = v);
add_alarm_limits(&nibp, "MAP alarm limits", "mmHg", 260,
params.borrow().alarms.nibp_map, params.clone(), |p, v| p.alarms.nibp_map = v);
add_alarm_limits(&nibp, "DIA alarm limits", "mmHg", 200,
params.borrow().alarms.nibp_dia, params.clone(), |p, v| p.alarms.nibp_dia = v);
let capno = group(&controls, "Capnography"); let capno = group(&controls, "Capnography");
add_visibility(&capno, params.borrow().show_capno, params.clone(), |p, show| p.show_capno = show); add_visibility(&capno, params.borrow().show_capno, params.clone(), |p, show| p.show_capno = show);
add_dropdown(&capno, "Capnogram", &["Normal", "Obstructive / shark fin"], add_dropdown(&capno, "Capnogram", &["Normal", "Obstructive / shark fin"],
@ -231,6 +258,11 @@ ART and pleth are delayed; VF and asystole always have no pulse."
add_numeric(&capno, "Respiratory rate", "/min", 0, 60, params.borrow().respiratory_rate, add_numeric(&capno, "Respiratory rate", "/min", 0, 60, params.borrow().respiratory_rate,
params.clone(), |p, v| p.respiratory_rate = v); params.clone(), |p, v| p.respiratory_rate = v);
add_alarm_limits(&capno, "EtCO₂ alarm limits", "mmHg", 100,
params.borrow().alarms.etco2, params.clone(), |p, v| p.alarms.etco2 = v);
add_alarm_limits(&capno, "RR alarm limits", "/min", 60,
params.borrow().alarms.rr, params.clone(), |p, v| p.alarms.rr = v);
scroller.set_child(Some(&controls)); scroller.set_child(Some(&controls));
main_box.append(&scroller); main_box.append(&scroller);
@ -369,3 +401,84 @@ fn normalize_entry(entry: &gtk::Entry, slider: &gtk::Scale, min: i32, max: i32)
slider.set_value(f64::from(value)); slider.set_value(f64::from(value));
entry.set_text(&value.to_string()); entry.set_text(&value.to_string());
} }
/// Thresholds deliberately use *optional* text entries, not sliders: an empty
/// field disables that side of the alarm. Non-numeric or reversed limits are
/// highlighted and do not replace the last valid alarm configuration.
fn add_alarm_limits<F>(parent: &gtk::Box, label: &str, unit: &str, max: i32,
initial: AlarmLimits, params: SharedParams, setter: F)
where F: Fn(&mut Parameters, AlarmLimits) + 'static {
let row = gtk::Box::new(Orientation::Horizontal, 8);
let caption = gtk::Label::new(Some(label));
caption.set_xalign(0.0);
caption.set_width_chars(17);
let low_label = gtk::Label::new(Some("↓"));
let high_label = gtk::Label::new(Some("↑"));
let low_entry = alarm_entry(initial.lower, "off");
let high_entry = alarm_entry(initial.upper, "off");
let suffix = gtk::Label::new(Some(unit));
suffix.set_xalign(0.0);
suffix.set_width_chars(5);
row.append(&caption);
row.append(&low_label);
row.append(&low_entry);
row.append(&high_label);
row.append(&high_entry);
row.append(&suffix);
parent.append(&row);
let setter: Rc<dyn Fn(&mut Parameters, AlarmLimits)> = Rc::new(setter);
low_entry.connect_changed({
let high_entry = high_entry.clone();
let params = params.clone();
let setter = setter.clone();
move |low_entry| {
update_alarm_limits(low_entry, &high_entry, max, &params, &setter);
}
});
high_entry.connect_changed({
let low_entry = low_entry.clone();
move |high_entry| {
update_alarm_limits(&low_entry, high_entry, max, &params, &setter);
}
});
}
fn alarm_entry(initial: Option<i32>, placeholder: &str) -> gtk::Entry {
let entry = gtk::Entry::new();
entry.set_width_chars(4);
entry.set_max_width_chars(5);
entry.set_input_purpose(gtk::InputPurpose::Digits);
entry.set_placeholder_text(Some(placeholder));
if let Some(value) = initial { entry.set_text(&value.to_string()); }
entry
}
fn parse_alarm_bound(entry: &gtk::Entry, max: i32) -> Result<Option<i32>, ()> {
let raw = entry.text();
let trimmed = raw.trim();
if trimmed.is_empty() { return Ok(None); }
match trimmed.parse::<i32>() {
Ok(value) if (0..=max).contains(&value) => Ok(Some(value)),
_ => Err(()),
}
}
fn update_alarm_limits(low_entry: &gtk::Entry, high_entry: &gtk::Entry, max: i32,
params: &SharedParams,
setter: &Rc<dyn Fn(&mut Parameters, AlarmLimits)>) {
let lower = parse_alarm_bound(low_entry, max);
let upper = parse_alarm_bound(high_entry, max);
let order_valid = match (&lower, &upper) {
(Ok(lo), Ok(hi)) => AlarmLimits { lower: *lo, upper: *hi }.valid(),
_ => true,
};
if lower.is_err() || !order_valid { low_entry.add_css_class("error"); }
else { low_entry.remove_css_class("error"); }
if upper.is_err() || !order_valid { high_entry.add_css_class("error"); }
else { high_entry.remove_css_class("error"); }
if let (Ok(lower), Ok(upper)) = (lower, upper) {
let limits = AlarmLimits { lower, upper };
if limits.valid() { setter(&mut params.borrow_mut(), limits); }
}
}