moce patches

This commit is contained in:
GABRIEL Sebastian 2026-11-13 10:59:24 +01:00
commit 5665d68db0
37 changed files with 1472 additions and 570 deletions

View file

@ -0,0 +1,106 @@
diff --git a/Cargo.toml b/Cargo.toml
index 35b29c9..13195d0 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "patient-monitor-simulation"
-version = "0.5.5"
+version = "0.5.6"
edition = "2021"
license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"
diff --git a/README.de.md b/README.de.md
index f69dacf..4082c89 100644
--- a/README.de.md
+++ b/README.de.md
@@ -474,3 +474,8 @@ Das Messverhalten und die Alarmfunktionen bleiben unverändert.
### v0.5.5 – Korrektur der CPR-Plethysmographie
Die verzögerte Plethysmographiekurve bei Thoraxkompressionen überlappt nicht mehr mit der nächsten Kompression. Der Regressionstest gibt bei einem Fehlschlag die maximale gültige Kurvenamplitude aus. Sonstige Simulationseinstellungen bleiben unverändert.
+
+
+### v0.5.6 – Persistenz des Pleth-Filters bei Thoraxkompressionen
+
+Die eigentliche Ursache des Testfehlers aus v0.5.5 wurde behoben: Bei pulslosen Rhythmen wurde der Pleth-Tiefpassfilter bislang mit jedem 250-Hz-Abtastwert zurückgesetzt. Während qualitativ guter Thoraxkompressionen bleibt der Filterzustand nun erhalten; QRS-getriggerte mechanische Pulse werden weiterhin verworfen. Nach dem Beenden der Kompressionen bei VF/PVT verschwindet das Pleth-Signal sofort. Ein zusätzlicher Regressionstest deckt PVT ab.
diff --git a/README.md b/README.md
index 09f8506..dc19c84 100644
--- a/README.md
+++ b/README.md
@@ -495,3 +495,8 @@ No NIBP measurement logic or alarm behavior was changed.
### v0.5.5 — CPR plethysmography correction
The delayed CPR pleth waveform no longer wraps its trailing portion into the next compression. The regression test now reports the maximum valid waveform amplitude when failing. No other simulation controls were changed.
+
+
+### v0.5.6 — CPR pleth filter persistence
+
+Corrects the underlying cause of the v0.5.5 test failure: in pulseless rhythms, the simulation had reset the pleth low-pass filter at every 250 Hz sample, preventing CPR-induced signals from accumulating. The filter now persists during good-quality chest compressions while QRS-triggered mechanical pulses are still cleared. Stopping CPR in VF/PVT immediately restores no reading. Additional regression coverage includes PVT.
diff --git a/src/simulation.rs b/src/simulation.rs
index fddf191..e947f69 100644
--- a/src/simulation.rs
+++ b/src/simulation.rs
@@ -361,16 +361,25 @@ impl Simulator {
let start_quality = self.nibp_start_quality(params);
self.nibp.update(self.time, params, start_quality);
- if params.ecg_rhythm != self.previous_rhythm
- || params.pulse_conduction != self.previous_conduction
- || !params.ecg_rhythm.can_generate_pulse()
+ let capture_changed = params.ecg_rhythm != self.previous_rhythm
+ || params.pulse_conduction != self.previous_conduction;
+ let no_intrinsic_pulse = !params.ecg_rhythm.can_generate_pulse()
|| params.pulse_conduction == PulseConduction::None
- || params.heart_rate <= 0
- {
- // A rhythm/capture change terminates previously queued mechanical events.
+ || params.heart_rate <= 0;
+ if capture_changed || no_intrinsic_pulse {
+ // Cancel stale QRS-triggered pulses immediately when capture is lost.
self.conducted_qrs.clear();
self.rate_qrs.clear();
- self.filtered_pleth = 0.0;
+ // VF/PVT/asystole/PEA remain pulseless without effective CPR.
+ // During Good CPR, however, keep the filter history so the
+ // compression-driven pleth can build up over multiple 4 ms steps.
+ // Reset once on a rhythm/capture transition, never on *every*
+ // sample merely because the underlying rhythm is pulseless.
+ let cpr_produces_pleth = params.chest_compressions_active
+ && params.chest_compression_quality == ChestCompressionQuality::Good;
+ if capture_changed || !cpr_produces_pleth {
+ self.filtered_pleth = 0.0;
+ }
self.previous_rhythm = params.ecg_rhythm;
self.previous_conduction = params.pulse_conduction;
}
@@ -762,6 +771,30 @@ mod tests {
assert!(recent.iter().all(|s| s.pleth_quality == Spo2Quality::Poor));
}
+ #[test]
+ fn pleth_filter_accumulates_during_good_cpr_but_clears_when_stopped() {
+ let mut p = Parameters {
+ ecg_rhythm: EcgRhythm::PulselessVentricularTachycardia,
+ chest_compressions_active: true,
+ chest_compression_quality: ChestCompressionQuality::Good,
+ spo2_quality: Spo2Quality::None,
+ ..Parameters::default()
+ };
+ let mut sim = Simulator::new(&p);
+ for _ in 0..500 { sim.step(&p); }
+ let max_valid_pleth = sim.samples.iter().rev().take(500)
+ .filter(|s| s.pleth_valid).map(|s| s.pleth)
+ .fold(0.0_f64, f64::max);
+ assert!(max_valid_pleth > 0.05,
+ "PVT with good CPR must accumulate pleth across samples: {max_valid_pleth:.4}");
+
+ p.chest_compressions_active = false;
+ sim.step(&p);
+ let after_stop = sim.samples.back().unwrap();
+ assert!(!after_stop.pleth_valid);
+ assert_eq!(after_stop.pleth, 0.0);
+ }
+
#[test]
fn only_good_cpr_shows_pleth_and_sensor_disconnect_takes_precedence() {
for quality in [ChestCompressionQuality::Adequate,

View file

@ -0,0 +1,526 @@
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "patient-monitor-simulation"
-version = "0.3.1"
+version = "0.3.2"
edition = "2021"
license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.3.1
+# Patient Monitor Simulation (PaMSim) — v0.3.2
A two-window, Rust/GTK4 patient-monitor simulator for teaching on Fedora Linux.
@@ -20,14 +20,17 @@
## Windows
-**Admin:** Controls ECG rhythm and rate; mechanical capture; SpO₂; invasive
-arterial pressure, waveform shape and pulse-pressure variation; NIBP; and
-capnography. Numeric inputs have bidirectionally linked sliders and text fields.
+**Admin:** Controls patient name; ECG rhythm and rate; mechanical capture;
+SpO₂, signal quality and sensor connection; invasive arterial pressure,
+waveform shape and pulse-pressure variation; NIBP; and capnography. Numeric inputs have bidirectionally linked sliders and text fields.
Each of the five monitor parameters (ECG, SpO₂/pleth, ART, CO₂, NIBP) has its
own **Show on monitor** checkbox.
**Monitor:** Black background; ECG green, pleth yellow, ART red and capnogram
-light grey. Waveforms and vital signs disappear together when their respective
+light grey. The patient name entered in Admin replaces **PATIENT MONITOR** in
+the header immediately; leaving the name blank restores the generic title.
+Long names are automatically resized or clipped to fit the header.
+Waveforms and vital signs disappear together when their respective
visibility checkbox is cleared. Remaining waveform rows expand to use the space.
Hiding a display channel does **not** stop signal generation or physiological
coupling: for example, hiding ECG does not stop ART or pleth pulses. NIBP can
@@ -36,6 +39,41 @@
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.
+
+## 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
+monitor headline. It is optional; an empty or whitespace-only name displays
+**PATIENT MONITOR**. This is a local teaching label, not a patient record.
+
+Admin → **Pulse oximetry** has two additional controls:
+
+- **Sensor not attached** (checkbox): immediately removes the pleth waveform,
+ suppresses SpO₂ and pulse-rate readings, and displays **NO SENSOR** instead
+ of the numeric saturation. This takes precedence over signal quality.
+- **Signal quality** (dropdown), which changes the visible pleth waveform and
+ quality indicator, independently of the instructor-set SpO₂ percentage:
+
+| Setting | Pleth waveform | Monitor display |
+| --- | --- | --- |
+| **0 — None** | No waveform | SpO₂ `--`, PR `--`, **NO SIGNAL**; no stars |
+| **1 — Poor** | Small, irregularly amplitude-distorted pulse | 1 star (★) |
+| **2 — Adequate** | Medium, smoothly damped pulse | 2 stars (★★) |
+| **3 — Good** | Full nominal, smoothly damped pulse | 3 stars (★★★) |
+
+Default: sensor attached; signal quality **3 — Good**. At levels 1–3, the
+instructor-set SpO₂ number is shown only when mechanical pulses are detected.
+The signal quality does **not** randomly alter that number: it affects the
+pleth morphology and the quality indicator only. The simulated pulse rate
+remains derived from mechanically captured QRS complexes.
+
+The degraded waveform uses deterministic, smoothly interpolated pseudo-noise
+that scales only existing pleth pulses: it cannot manufacture pulses during
+PEA, ventricular fibrillation or asystole. Unplugging a sensor or selecting
+quality 0 hides even previously buffered pleth samples immediately. ECG and
+ART continue unaffected. The **Show on monitor** checkbox still hides the
+entire SpO₂ row; sensor/quality controls leave the row visible so the status
+can be taught.
## ECG and mechanical coupling
@@ -161,3 +199,17 @@
**Verification:** The archive is generated from these sources. Run `cargo test`
locally to verify the Rust/GTK build; Rust and GTK4 development components
were not available in the environment where this ZIP was prepared.
+
+## Changes in v0.3.2
+
+1. Added live patient-name header in Admin/Monitor with blank-name fallback.
+2. Added four levels of SpO₂ signal quality, quality stars and an irregular,
+ low-amplitude pleth waveform for Poor quality.
+3. Added **Sensor not attached** with `NO SENSOR` status and suppression of
+ saturation, pulse rate and pleth waveform.
+4. Added tests for signal-quality scaling, displayed readings and disconnected
+ sensor behavior.
+
+**Build verification:** ZIP integrity and patch application were checked.
+The GTK4 application and Rust tests were not compiled in the packaging
+environment; run `cargo test` and `cargo run --release` on Fedora.
--- a/src/model.rs
+++ b/src/model.rs
@@ -58,12 +58,45 @@
Obstructive,
}
-#[derive(Clone, Copy, Debug)]
+/// Instructor-selected plethysmography signal quality; separate from the
+/// physiological oxygen-saturation setting and mechanical pulse capture.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Spo2Quality {
+ None,
+ Poor,
+ Adequate,
+ Good,
+}
+
+impl Spo2Quality {
+ pub fn stars(self) -> &'static str {
+ match self {
+ Self::None => "",
+ Self::Poor => "★",
+ Self::Adequate => "★★",
+ Self::Good => "★★★",
+ }
+ }
+
+ pub fn amplitude_scale(self) -> f64 {
+ match self {
+ Self::None => 0.0,
+ Self::Poor => 0.25,
+ Self::Adequate => 0.56,
+ Self::Good => 1.0,
+ }
+ }
+}
+
+#[derive(Clone, Debug)]
pub struct Parameters {
+ pub patient_name: String, // displayed in the monitor header, blank = generic title
pub ecg_rhythm: EcgRhythm,
pub heart_rate: i32, // bpm, organized electrical rate; not mechanical pulse rate
pub pulse_conduction: PulseConduction,
- pub spo2: i32, // %
+ pub spo2: i32, // %; instructor-set nominal saturation
+ pub spo2_quality: Spo2Quality,
+ pub spo2_sensor_attached: bool,
pub art_systolic: i32, // mmHg, nominal pressure; display axis 0..200
pub art_diastolic: i32, // mmHg
pub arterial_shape: ArterialShape,
@@ -84,10 +117,13 @@
impl Default for Parameters {
fn default() -> Self {
Self {
+ patient_name: String::new(),
ecg_rhythm: EcgRhythm::Sinus,
heart_rate: 75,
pulse_conduction: PulseConduction::OneToOne,
spo2: 98,
+ spo2_quality: Spo2Quality::Good,
+ spo2_sensor_attached: true,
art_systolic: 120,
art_diastolic: 75,
arterial_shape: ArterialShape::Normal,
@@ -120,6 +156,17 @@
}
#[test]
+ fn spo2_quality_stars_and_amplitude_progress_monotonically() {
+ assert_eq!(Spo2Quality::None.stars(), "");
+ assert_eq!(Spo2Quality::Poor.stars(), "★");
+ assert_eq!(Spo2Quality::Adequate.stars(), "★★");
+ assert_eq!(Spo2Quality::Good.stars(), "★★★");
+ assert_eq!(Spo2Quality::None.amplitude_scale(), 0.0);
+ assert!(Spo2Quality::Poor.amplitude_scale() < Spo2Quality::Adequate.amplitude_scale());
+ assert!(Spo2Quality::Adequate.amplitude_scale() < Spo2Quality::Good.amplitude_scale());
+ }
+
+ #[test]
fn grouped_mechanical_capture_follows_requested_patterns() {
assert_eq!((1..=8).filter(|&b| PulseConduction::TwoToOne.conducts(b)).collect::<Vec<_>>(),
vec![1, 3, 5, 7]);
--- 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};
+use crate::model::{mean_arterial_pressure, EcgRhythm, Parameters, PulseConduction, Spo2Quality};
use crate::simulation::{Sample, Simulator};
type Color = (f64, f64, f64);
@@ -43,8 +43,18 @@
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);
- text(cr, "PATIENT MONITOR", pad + 5.0, header * 0.58, 18.0 * text_scale,
- LIGHT_GREY, true);
+ 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);
if w >= 850.0 {
text(cr, "SIMULATION", split_x - 128.0 * text_scale, header * 0.58,
11.0 * text_scale, MUTED, false);
@@ -84,6 +94,24 @@
}
}
+fn pleth_trace_enabled(p: &Parameters) -> bool {
+ p.spo2_sensor_attached && p.spo2_quality != Spo2Quality::None
+}
+
+fn spo2_vitals(p: &Parameters, pulse_rate: Option<i32>) -> (String, String, String) {
+ if !p.spo2_sensor_attached {
+ return ("SpO₂".to_owned(), "NO SENSOR".to_owned(), "SpO₂ -- PR -- bpm".to_owned());
+ }
+ if p.spo2_quality == Spo2Quality::None {
+ return ("SpO₂".to_owned(), "--".to_owned(), "NO SIGNAL PR -- bpm".to_owned());
+ }
+ (
+ format!("SpO₂ {}", p.spo2_quality.stars()),
+ if pulse_rate.is_some() { p.spo2.to_string() } else { "--".to_owned() },
+ format!("% PR {} bpm", pulse_rate.map_or("--".to_owned(), |pr| pr.to_string())),
+ )
+}
+
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);
@@ -95,7 +123,7 @@
let pulse_rate = if has_capture { sim.pulse_rate() } else { None };
let (label, value, info) = match ch {
Channel::Ecg => (
- "HR",
+ "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 {
@@ -106,13 +134,9 @@
EcgRhythm::Asystole => "Asystole",
}),
),
- Channel::Pleth => (
- "SpO₂",
- if pulse_rate.is_some() { p.spo2.to_string() } else { "--".to_owned() },
- format!("% PR {} bpm", pulse_rate.map_or("--".to_owned(), |pr| pr.to_string())),
- ),
+ Channel::Pleth => spo2_vitals(p, pulse_rate),
Channel::Art => (
- "ART",
+ "ART".to_owned(),
if pulse_rate.is_some() {
format!("{}/{}", p.art_systolic, p.art_diastolic)
} else { "--/--".to_owned() },
@@ -126,13 +150,20 @@
}
} else { "MAP -- mmHg".to_owned() },
),
- Channel::Capno => ("EtCO₂", p.etco2.to_string(),
+ 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 BP values so they fit within the sidebar.
- let value_size = if matches!(ch, Channel::Art) { number_size * 0.78 } else { number_size };
- text(cr, &value, x, top + row_h * 0.64, value_size, color, true);
+ 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);
}
@@ -175,6 +206,13 @@
right, top + trace_height * 0.5, GRID, 0.7);
}
+ // Disconnected or absent pleth signal: no curve, including historical pulses.
+ if matches!(channel, Channel::Pleth) && !pleth_trace_enabled(p)
+ {
+ let _ = cr.restore();
+ return;
+ }
+
set_color(cr, color);
cr.set_line_width((trace_height * 0.016).clamp(1.2, 2.4));
cr.set_line_cap(LineCap::Round);
@@ -194,11 +232,66 @@
fn normalized(channel: Channel, s: &Sample, p: &Parameters) -> f64 {
match channel {
Channel::Ecg => (0.40 + s.ecg * 0.38).clamp(0.02, 0.98),
- Channel::Pleth => (0.10 + s.pleth * 0.78).clamp(0.02, 0.98),
+ Channel::Pleth => (0.10 + pleth_visual_amplitude(s.pleth, s.time, p.spo2_quality) * 0.78)
+ .clamp(0.02, 0.98),
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),
}
+}
+
+/// 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();
}
fn set_color(cr: &Context, c: Color) {
@@ -243,6 +336,53 @@
}
#[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)).1, "NO SENSOR");
+ assert!(spo2_vitals(&p, Some(75)).2.contains("PR --"));
+ p.spo2_sensor_attached = true;
+ p.spo2_quality = Spo2Quality::None;
+ assert!(!pleth_trace_enabled(&p));
+ assert_eq!(spo2_vitals(&p, Some(75)).1, "--");
+ assert!(spo2_vitals(&p, Some(75)).2.contains("NO SIGNAL"));
+ assert!(spo2_vitals(&p, Some(75)).2.contains("PR --"));
+ 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)).0, "SpO₂ ★");
+ assert_eq!(spo2_vitals(&p, Some(75)).1, "98");
+ assert!(spo2_vitals(&p, Some(75)).2.contains("PR 75 bpm"));
+ p.spo2_quality = Spo2Quality::Good;
+ assert_eq!(spo2_vitals(&p, Some(75)).0, "SpO₂ ★★★");
+ assert_eq!(spo2_vitals(&p, None).1, "--");
+ assert!(spo2_vitals(&p, None).2.contains("PR --"));
+ }
+
+ #[test]
fn arterial_axis_is_absolute_and_fixed_to_200_mmhg() {
let p = Parameters::default();
let mut s = Sample { time: 0.0, ecg: 0.0, pleth: 0.0, art: 100.0, co2: 0.0 };
--- a/src/ui.rs
+++ b/src/ui.rs
@@ -8,7 +8,7 @@
use gtk::prelude::*;
use gtk::{Application, ApplicationWindow, Orientation};
-use crate::model::{ArterialShape, CapnoShape, EcgRhythm, Parameters, PulseConduction};
+use crate::model::{ArterialShape, CapnoShape, EcgRhythm, Parameters, PulseConduction, Spo2Quality};
use crate::render;
use crate::simulation::Simulator;
@@ -41,7 +41,7 @@
let params = params.clone();
let simulator = simulator.clone();
move |_area, cr, width, height| {
- let config = *params.borrow();
+ let config = params.borrow();
render::draw(cr, width, height, &config, &simulator.borrow());
}
});
@@ -54,7 +54,7 @@
let now = Instant::now();
let elapsed = now.saturating_duration_since(previous.get()).as_secs_f64();
previous.set(now);
- let config = *params.borrow();
+ let config = params.borrow();
simulator.borrow_mut().advance(elapsed, &config);
area.queue_draw();
glib::ControlFlow::Continue
@@ -104,6 +104,24 @@
scroller.set_vexpand(true);
scroller.set_policy(gtk::PolicyType::Never, gtk::PolicyType::Automatic);
let controls = gtk::Box::new(Orientation::Vertical, 12);
+
+ let patient = group(&controls, "Patient");
+ let patient_row = gtk::Box::new(Orientation::Horizontal, 8);
+ let patient_label = gtk::Label::new(Some("Patient name"));
+ patient_label.set_xalign(0.0);
+ patient_label.set_width_chars(17);
+ let name_entry = gtk::Entry::new();
+ name_entry.set_hexpand(true);
+ name_entry.set_max_length(80);
+ name_entry.set_placeholder_text(Some("Name displayed on monitor"));
+ name_entry.set_text(&params.borrow().patient_name);
+ name_entry.connect_changed({
+ let params = params.clone();
+ move |entry| params.borrow_mut().patient_name = entry.text().to_string()
+ });
+ patient_row.append(&patient_label);
+ patient_row.append(&name_entry);
+ patient.append(&patient_row);
let ecg = group(&controls, "ECG");
add_visibility(&ecg, params.borrow().show_ecg, params.clone(), |p, show| p.show_ecg = show);
@@ -126,6 +144,26 @@
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);
+ let sensor = gtk::CheckButton::with_label("Sensor not attached");
+ sensor.set_active(!params.borrow().spo2_sensor_attached);
+ sensor.connect_toggled({
+ let params = params.clone();
+ move |button| params.borrow_mut().spo2_sensor_attached = !button.is_active()
+ });
+ spo2.append(&sensor);
+ add_dropdown_at(&spo2, "Signal quality", &[
+ "0 — None (no reading)",
+ "1 — Poor (*)",
+ "2 — Adequate (**)",
+ "3 — Good (***)",
+ ], params.borrow().spo2_quality as u32, params.clone(), |p, selected| {
+ p.spo2_quality = match selected {
+ 1 => Spo2Quality::Poor,
+ 2 => Spo2Quality::Adequate,
+ 3 => Spo2Quality::Good,
+ _ => Spo2Quality::None,
+ };
+ });
add_dropdown(&spo2, "Mechanical capture", &[
"1:1 (every QRS)",
"2:1 (one pulse in two)",
@@ -243,11 +281,18 @@
fn add_dropdown<F>(parent: &gtk::Box, label: &str, items: &[&str],
params: SharedParams, setter: F)
where F: Fn(&mut Parameters, u32) + 'static {
+ add_dropdown_at(parent, label, items, 0, params, setter);
+}
+
+fn add_dropdown_at<F>(parent: &gtk::Box, label: &str, items: &[&str],
+ initial: u32, params: SharedParams, setter: F)
+where F: Fn(&mut Parameters, u32) + '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 combo = gtk::DropDown::from_strings(items);
+ combo.set_selected(initial);
combo.set_hexpand(true);
combo.connect_selected_notify(move |combo| {
setter(&mut params.borrow_mut(), combo.selected());

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

@ -0,0 +1,462 @@
diff --git a/Cargo.toml b/Cargo.toml
index 6c9e60a..4c97d45 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "patient-monitor-simulation"
-version = "0.4.0"
+version = "0.4.1"
edition = "2021"
license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"
diff --git a/README.md b/README.md
index 9e140e3..4c5b8f0 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.4.0
+# Patient Monitor Simulation (PaMSim) — v0.4.1
A two-window, Rust/GTK4 patient-monitor simulator for teaching on Fedora Linux.
@@ -40,11 +40,14 @@ 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)
+## Numerical alarm limits (v0.4.0; layout and presets updated in v0.4.1)
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
+upper (↑) alarm threshold** in the corresponding Admin section. The lower
+and upper entries are placed **in the same row as the corresponding slider**.
+Derived values with no separate slider (PR, ART MAP, NIBP MAP) have their own
+compact alarm rows. The Admin window opens wider to accommodate these controls.
+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
@@ -64,11 +67,40 @@ each channel, with an arrow for the corresponding direction. A disabled
boundary is displayed as `---`. For instance:
```text
-⚠ SYS ↑180 ↓80
- MAP ↑--- ↓60
- DIA ↑--- ↓---
+⚠ SYS ↓80 ↑180
+ MAP ↓60 ↑---
+ DIA ↓--- ↑---
```
+### Alert presets
+
+The **Alert presets** dropdown at the top of Admin offers **Custom** (manual)
+and **Adult**. Choosing **Adult** immediately sets all alarm limits and updates
+the lower/upper text fields alongside the sliders. It changes *only* alarm limits:
+it does not change heart rate, blood pressure, channel visibility or any other
+simulated physiological setting. Editing any alarm field after applying Adult
+switches the selector to **Custom** without changing other alarm limits. Select
+**Adult** again to reapply the complete preset.
+
+| Parameter | Lower | Upper |
+| --- | ---: | ---: |
+| HR (bpm) | 60 | 100 |
+| SpO₂ (%) | 90 | --- |
+| PR (bpm) | --- | --- |
+| ART SYS (mmHg) | 80 | 180 |
+| ART MAP (mmHg) | 60 | 100 |
+| ART DIA (mmHg) | --- | --- |
+| PPV (%) | --- | 10 |
+| NIBP SYS (mmHg) | 80 | 180 |
+| NIBP MAP (mmHg) | 60 | 100 |
+| NIBP DIA (mmHg) | --- | --- |
+| EtCO₂ (mmHg) | 30 | 50 |
+| RR (/min) | 10 | 20 |
+
+`---` denotes a disabled threshold. Adult is a **teaching convenience preset**,
+not a clinically validated set of alarm limits. Initially the selector is
+**Custom**, with all limits disabled (as in v0.4.0).
+
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
diff --git a/src/model.rs b/src/model.rs
index 81b5e2e..2ce532c 100644
--- a/src/model.rs
+++ b/src/model.rs
@@ -127,13 +127,13 @@ impl AlarmLimits {
fn bound(value: Option<i32>) -> String {
value.map_or_else(|| "---".to_owned(), |v| v.to_string())
}
- format!("{} ↑{} ↓{}", name, bound(self.upper), bound(self.lower))
+ format!("{} ↓{} ↑{}", name, bound(self.lower), bound(self.upper))
}
}
/// 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)]
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct AlarmSettings {
pub hr: AlarmLimits,
pub spo2: AlarmLimits,
@@ -149,6 +149,25 @@ pub struct AlarmSettings {
pub rr: AlarmLimits,
}
+impl AlarmSettings {
+ /// Instructor convenience preset; does not change physiological settings.
+ /// Unspecified alarm boundaries remain disabled.
+ pub fn adult() -> Self {
+ Self {
+ hr: AlarmLimits { lower: Some(60), upper: Some(100) },
+ spo2: AlarmLimits { lower: Some(90), upper: None },
+ art_sys: AlarmLimits { lower: Some(80), upper: Some(180) },
+ art_map: AlarmLimits { lower: Some(60), upper: Some(100) },
+ ppv: AlarmLimits { lower: None, upper: Some(10) },
+ nibp_sys: AlarmLimits { lower: Some(80), upper: Some(180) },
+ nibp_map: AlarmLimits { lower: Some(60), upper: Some(100) },
+ etco2: AlarmLimits { lower: Some(30), upper: Some(50) },
+ rr: AlarmLimits { lower: Some(10), upper: Some(20) },
+ ..Self::default()
+ }
+ }
+}
+
#[derive(Clone, Debug)]
pub struct Parameters {
pub patient_name: String, // displayed in the monitor header, blank = generic title
@@ -239,7 +258,7 @@ mod tests {
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");
+ 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);
@@ -248,10 +267,34 @@ mod tests {
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_eq!(both.display("SYS"), "SYS ↓80 ↑180");
assert!(!AlarmLimits { lower: Some(181), upper: Some(80) }.valid());
}
+ #[test]
+ fn adult_preset_sets_exact_requested_limits_and_leaves_others_off() {
+ let preset = AlarmSettings::adult();
+ let pair = |lo, hi| AlarmLimits { lower: lo, upper: hi };
+ assert_eq!(preset.hr, pair(Some(60), Some(100)));
+ assert_eq!(preset.spo2, pair(Some(90), None));
+ assert_eq!(preset.pr, pair(None, None));
+ assert_eq!(preset.art_sys, pair(Some(80), Some(180)));
+ assert_eq!(preset.art_map, pair(Some(60), Some(100)));
+ assert_eq!(preset.art_dia, pair(None, None));
+ assert_eq!(preset.ppv, pair(None, Some(10)));
+ assert_eq!(preset.nibp_sys, preset.art_sys);
+ assert_eq!(preset.nibp_map, preset.art_map);
+ assert_eq!(preset.nibp_dia, preset.art_dia);
+ assert_eq!(preset.etco2, pair(Some(30), Some(50)));
+ assert_eq!(preset.rr, pair(Some(10), Some(20)));
+ assert!([
+ preset.hr, preset.spo2, preset.art_sys, preset.art_map,
+ preset.ppv, preset.nibp_sys, preset.nibp_map,
+ preset.etco2, preset.rr,
+ ].iter().all(|bounds| bounds.valid()));
+ assert_eq!(AlarmSettings::default(), Parameters::default().alarms);
+ }
+
#[test]
fn all_limits_disabled_by_default() {
let p = Parameters::default();
diff --git a/src/ui.rs b/src/ui.rs
index 6d1e913..a36fec3 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::{AlarmLimits, ArterialShape, CapnoShape, EcgRhythm, Parameters, PulseConduction, Spo2Quality};
+use crate::model::{AlarmLimits, AlarmSettings, ArterialShape, CapnoShape, EcgRhythm, Parameters, PulseConduction, Spo2Quality};
use crate::render;
use crate::simulation::Simulator;
@@ -85,7 +85,7 @@ fn create_admin(app: &Application, params: SharedParams,
let window = ApplicationWindow::builder()
.application(app)
.title(concat!("Patient Monitor — Admin v", env!("CARGO_PKG_VERSION")))
- .default_width(600)
+ .default_width(920)
.default_height(790)
.build();
@@ -111,6 +111,20 @@ fn create_admin(app: &Application, params: SharedParams,
alarm_hint.set_wrap(true);
controls.append(&alarm_hint);
+ // A preset replaces alarm limits only. Selecting Custom preserves manual edits;
+ // editing any alarm field switches the selector back to Custom.
+ let preset_row = gtk::Box::new(Orientation::Horizontal, 8);
+ let preset_caption = gtk::Label::new(Some("Alert presets"));
+ preset_caption.set_xalign(0.0);
+ preset_caption.set_width_chars(17);
+ let preset_dropdown = gtk::DropDown::from_strings(&["Custom", "Adult"]);
+ preset_dropdown.set_hexpand(true);
+ preset_row.append(&preset_caption);
+ preset_row.append(&preset_dropdown);
+ controls.append(&preset_row);
+ let updating_preset = Rc::new(Cell::new(false));
+ let mut alarm_editors: Vec<(AlarmEditor, fn(&AlarmSettings) -> AlarmLimits)> = Vec::new();
+
let patient = group(&controls, "Patient");
let patient_row = gtk::Box::new(Orientation::Horizontal, 8);
let patient_label = gtk::Label::new(Some("Patient name"));
@@ -143,19 +157,22 @@ fn create_admin(app: &Application, params: SharedParams,
_ => EcgRhythm::Sinus,
};
});
- add_numeric(&ecg, "Heart rate", "bpm", 0, 240, params.borrow().heart_rate,
+ let hr_row = 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);
+ alarm_editors.push((add_alarm_limits(&hr_row, "", "", 240,
+ params.borrow().alarms.hr, params.clone(), |p, v| p.alarms.hr = v,
+ &preset_dropdown, &updating_preset), |s| s.hr));
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,
+ let spo2_row = 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);
+ alarm_editors.push((add_alarm_limits(&spo2_row, "", "", 100,
+ params.borrow().alarms.spo2, params.clone(), |p, v| p.alarms.spo2 = v,
+ &preset_dropdown, &updating_preset), |s| s.spo2));
+ alarm_editors.push((add_alarm_limits(&spo2, "PR (derived)", "bpm", 240,
+ params.borrow().alarms.pr, params.clone(), |p, v| p.alarms.pr = v,
+ &preset_dropdown, &updating_preset), |s| s.pr));
let sensor = gtk::CheckButton::with_label("Sensor not attached");
sensor.set_active(!params.borrow().spo2_sensor_attached);
sensor.connect_toggled({
@@ -201,21 +218,25 @@ ART and pleth are delayed; VF and asystole always have no pulse."
let art = group(&controls, "Invasive arterial blood pressure");
add_visibility(&art, params.borrow().show_art, params.clone(), |p, show| p.show_art = show);
- add_numeric(&art, "Systolic", "mmHg", 0, 200, params.borrow().art_systolic,
+ let art_sys_row = add_numeric(&art, "Systolic", "mmHg", 0, 200, params.borrow().art_systolic,
params.clone(), |p, v| p.art_systolic = v);
- add_numeric(&art, "Diastolic", "mmHg", 0, 200, params.borrow().art_diastolic,
+ alarm_editors.push((add_alarm_limits(&art_sys_row, "", "", 200,
+ params.borrow().alarms.art_sys, params.clone(), |p, v| p.alarms.art_sys = v,
+ &preset_dropdown, &updating_preset), |s| s.art_sys));
+ alarm_editors.push((add_alarm_limits(&art, "MAP (derived)", "mmHg", 200,
+ params.borrow().alarms.art_map, params.clone(), |p, v| p.alarms.art_map = v,
+ &preset_dropdown, &updating_preset), |s| s.art_map));
+ let art_dia_row = 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,
+ alarm_editors.push((add_alarm_limits(&art_dia_row, "", "", 200,
+ params.borrow().alarms.art_dia, params.clone(), |p, v| p.alarms.art_dia = v,
+ &preset_dropdown, &updating_preset), |s| s.art_dia));
+ let ppv_row = 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);
+ alarm_editors.push((add_alarm_limits(&ppv_row, "", "", 60,
+ params.borrow().alarms.ppv, params.clone(), |p, v| p.alarms.ppv = v,
+ &preset_dropdown, &updating_preset), |s| s.ppv));
let ppv_hint = gtk::Label::new(Some(
"Respiratory pulse-pressure swing (PPV). 0% = off; requires RR > 0."
));
@@ -234,17 +255,19 @@ ART and pleth are delayed; VF and asystole always have no pulse."
let nibp = group(&controls, "Non-invasive blood pressure (NIBP)");
add_visibility(&nibp, params.borrow().show_nibp, params.clone(), |p, show| p.show_nibp = show);
- add_numeric(&nibp, "Systolic", "mmHg", 0, 260, params.borrow().nibp_systolic,
+ let nibp_sys_row = add_numeric(&nibp, "Systolic", "mmHg", 0, 260, params.borrow().nibp_systolic,
params.clone(), |p, v| p.nibp_systolic = v);
- add_numeric(&nibp, "Diastolic", "mmHg", 0, 200, params.borrow().nibp_diastolic,
+ alarm_editors.push((add_alarm_limits(&nibp_sys_row, "", "", 260,
+ params.borrow().alarms.nibp_sys, params.clone(), |p, v| p.alarms.nibp_sys = v,
+ &preset_dropdown, &updating_preset), |s| s.nibp_sys));
+ alarm_editors.push((add_alarm_limits(&nibp, "MAP (derived)", "mmHg", 260,
+ params.borrow().alarms.nibp_map, params.clone(), |p, v| p.alarms.nibp_map = v,
+ &preset_dropdown, &updating_preset), |s| s.nibp_map));
+ let nibp_dia_row = 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);
+ alarm_editors.push((add_alarm_limits(&nibp_dia_row, "", "", 200,
+ params.borrow().alarms.nibp_dia, params.clone(), |p, v| p.alarms.nibp_dia = v,
+ &preset_dropdown, &updating_preset), |s| s.nibp_dia));
let capno = group(&controls, "Capnography");
add_visibility(&capno, params.borrow().show_capno, params.clone(), |p, show| p.show_capno = show);
@@ -253,15 +276,33 @@ ART and pleth are delayed; VF and asystole always have no pulse."
p.capno_shape = if selected == 1 { CapnoShape::Obstructive }
else { CapnoShape::Normal };
});
- add_numeric(&capno, "EtCO₂", "mmHg", 0, 100, params.borrow().etco2,
+ let etco2_row = add_numeric(&capno, "EtCO₂", "mmHg", 0, 100, params.borrow().etco2,
params.clone(), |p, v| p.etco2 = v);
- add_numeric(&capno, "Respiratory rate", "/min", 0, 60, params.borrow().respiratory_rate,
+ alarm_editors.push((add_alarm_limits(&etco2_row, "", "", 100,
+ params.borrow().alarms.etco2, params.clone(), |p, v| p.alarms.etco2 = v,
+ &preset_dropdown, &updating_preset), |s| s.etco2));
+ let rr_row = add_numeric(&capno, "Respiratory rate", "/min", 0, 60, params.borrow().respiratory_rate,
params.clone(), |p, v| p.respiratory_rate = v);
+ alarm_editors.push((add_alarm_limits(&rr_row, "", "", 60,
+ params.borrow().alarms.rr, params.clone(), |p, v| p.alarms.rr = v,
+ &preset_dropdown, &updating_preset), |s| s.rr));
- 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);
+ preset_dropdown.connect_selected_notify({
+ let params = params.clone();
+ let updating_preset = updating_preset.clone();
+ move |dropdown| {
+ if dropdown.selected() != 1 { return; }
+ let limits = AlarmSettings::adult();
+ // Suppress per-field callbacks while writing both entries in each row.
+ // Otherwise a half-updated pair could temporarily be invalid.
+ updating_preset.set(true);
+ for (editor, get_limits) in &alarm_editors {
+ editor.set_limits(get_limits(&limits));
+ }
+ updating_preset.set(false);
+ params.borrow_mut().alarms = limits;
+ }
+ });
scroller.set_child(Some(&controls));
main_box.append(&scroller);
@@ -337,7 +378,7 @@ where F: Fn(&mut Parameters, u32) + 'static {
#[allow(clippy::too_many_arguments)]
fn add_numeric<F>(parent: &gtk::Box, label: &str, unit: &str,
min: i32, max: i32, initial: i32,
- params: SharedParams, setter: F)
+ params: SharedParams, setter: F) -> gtk::Box
where F: Fn(&mut Parameters, i32) + 'static {
let row = gtk::Box::new(Orientation::Horizontal, 8);
let caption = gtk::Label::new(Some(label));
@@ -392,6 +433,7 @@ where F: Fn(&mut Parameters, i32) + 'static {
row.append(&entry);
row.append(&suffix);
parent.append(&row);
+ row
}
fn normalize_entry(entry: &gtk::Entry, slider: &gtk::Scale, min: i32, max: i32) {
@@ -402,29 +444,50 @@ fn normalize_entry(entry: &gtk::Entry, slider: &gtk::Scale, min: i32, max: i32)
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.
+/// Two entries for one alarm; retained so presets can update visible inputs.
+struct AlarmEditor {
+ lower: gtk::Entry,
+ upper: gtk::Entry,
+}
+
+impl AlarmEditor {
+ fn set_limits(&self, limits: AlarmLimits) {
+ self.lower.set_text(&limits.lower.map_or_else(String::new, |v| v.to_string()));
+ self.upper.set_text(&limits.upper.map_or_else(String::new, |v| v.to_string()));
+ self.lower.remove_css_class("error");
+ self.upper.remove_css_class("error");
+ }
+}
+
+/// Thresholds are optional text entries (no slider), because empty disables
+/// that side. An empty label places them directly beside a numeric slider;
+/// derived measurements (MAP, PR) get compact standalone rows.
+#[allow(clippy::too_many_arguments)]
fn add_alarm_limits<F>(parent: &gtk::Box, label: &str, unit: &str, max: i32,
- initial: AlarmLimits, params: SharedParams, setter: F)
+ initial: AlarmLimits, params: SharedParams, setter: F,
+ preset: &gtk::DropDown, updating_preset: &Rc<Cell<bool>>) -> AlarmEditor
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 row = gtk::Box::new(Orientation::Horizontal, 5);
+ if !label.is_empty() {
+ let caption = gtk::Label::new(Some(label));
+ caption.set_xalign(0.0);
+ caption.set_width_chars(17);
+ row.append(&caption);
+ }
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);
+ if !unit.is_empty() {
+ let suffix = gtk::Label::new(Some(unit));
+ suffix.set_xalign(0.0);
+ suffix.set_width_chars(5);
+ row.append(&suffix);
+ }
parent.append(&row);
let setter: Rc<dyn Fn(&mut Parameters, AlarmLimits)> = Rc::new(setter);
@@ -432,16 +495,25 @@ where F: Fn(&mut Parameters, AlarmLimits) + 'static {
let high_entry = high_entry.clone();
let params = params.clone();
let setter = setter.clone();
+ let preset = preset.clone();
+ let updating_preset = updating_preset.clone();
move |low_entry| {
+ if updating_preset.get() { return; }
+ preset.set_selected(0);
update_alarm_limits(low_entry, &high_entry, max, &params, &setter);
}
});
high_entry.connect_changed({
let low_entry = low_entry.clone();
+ let preset = preset.clone();
+ let updating_preset = updating_preset.clone();
move |high_entry| {
+ if updating_preset.get() { return; }
+ preset.set_selected(0);
update_alarm_limits(&low_entry, high_entry, max, &params, &setter);
}
});
+ AlarmEditor { lower: low_entry, upper: high_entry }
}
fn alarm_entry(initial: Option<i32>, placeholder: &str) -> gtk::Entry {

View file

@ -0,0 +1,509 @@
diff --git a/Cargo.toml b/Cargo.toml
index 4c97d45..02a5d17 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "patient-monitor-simulation"
-version = "0.4.1"
+version = "0.4.2"
edition = "2021"
license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"
diff --git a/README.md b/README.md
index 4c5b8f0..c693e16 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.4.1
+# Patient Monitor Simulation (PaMSim) — v0.4.2
A two-window, Rust/GTK4 patient-monitor simulator for teaching on Fedora Linux.
@@ -130,7 +130,7 @@ Admin → **Pulse oximetry** has two additional controls:
| Setting | Pleth waveform | Monitor display |
| --- | --- | --- |
-| **0 — None** | No waveform | SpO₂ `--`, PR `--`, **NO SIGNAL**; no stars |
+| **0 — None** | No waveform | Flashing **NO READING**, PR `--`; no stars |
| **1 — Poor** | Small, irregularly amplitude-distorted pulse | 1 star (★) |
| **2 — Adequate** | Medium, smoothly damped pulse | 2 stars (★★) |
| **3 — Good** | Full nominal, smoothly damped pulse | 3 stars (★★★) |
@@ -143,7 +143,7 @@ remains derived from mechanically captured QRS complexes.
The degraded waveform uses deterministic, smoothly interpolated pseudo-noise
that scales only existing pleth pulses: it cannot manufacture pulses during
-PEA, ventricular fibrillation or asystole. Unplugging a sensor or selecting
+PEA, PVT, ventricular fibrillation or asystole. Unplugging a sensor or selecting
quality 0 hides even previously buffered pleth samples immediately. ECG and
ART continue unaffected. The **Show on monitor** checkbox still hides the
entire SpO₂ row; sensor/quality controls leave the row visible so the status
@@ -151,15 +151,18 @@ can be taught.
## ECG and mechanical coupling
-- ECG rhythms: sinus, atrial fibrillation, monomorphic ventricular tachycardia,
+- ECG rhythms: sinus, atrial fibrillation, monomorphic ventricular tachycardia
+ (potentially perfusing), pulseless ventricular tachycardia (PVT),
ventricular fibrillation and asystole.
- Mechanical capture: **1:1**, **2:1**, **3:1**, **None (PEA)**, or deterministic
pseudo-random capture (~65%). PR is derived from conducted QRS events, never
controlled by a pulse-rate slider.
- A captured QRS leads to an ART upstroke after a schematic **120 ms**, and a
peripheral pleth pulse after **300 ms**. Pleth is strongly damped/filtered.
-- VF, asystole and PEA suppress mechanical pulses; old samples scroll out of
- view. NIBP is a static, separately entered cuff reading.
+- PVT, VF, asystole and PEA suppress mechanical pulses; the ART trace then
+ drifts smoothly at 0–5 mmHg rather than representing a pulsatile pressure.
+ Previous pressure samples scroll out of view. NIBP is a static,
+ separately entered cuff reading.
## Invasive arterial pressure and PPV (new in v0.3)
@@ -205,7 +208,7 @@ The five **Show on monitor** checkboxes affect the presentation only:
| Checkbox | Hidden monitor content |
| --- | --- |
-| ECG | ECG waveform, HR and rhythm label |
+| ECG | ECG waveform, HR and rhythm alarm (when present) |
| Pulse oximetry | Pleth waveform, SpO₂ and PR |
| Invasive arterial blood pressure | ART waveform, pressure values, MAP and PPV label |
| Capnography | CO₂ waveform, EtCO₂ and RR |
@@ -287,3 +290,13 @@ were not available in the environment where this ZIP was prepared.
**Build verification:** ZIP integrity and patch application were checked.
The GTK4 application and Rust tests were not compiled in the packaging
environment; run `cargo test` and `cargo run --release` on Fedora.
+
+
+## v0.4.2 — Rhythm, sensor and missing-reading alarms
+
+- **VT** remains potentially perfusing. The new **PVT** (pulseless ventricular tachycardia) rhythm retains organized broad QRS complexes but produces no arterial/pleth pulses. VF and asystole are also pulseless regardless of capture selection.
+- **ECG**: a flashing **ARRHYTHMIA** message for VT, PVT and VF; a flashing **ASYSTOLE** message for asystole. These event alarms do not depend on numerical HR limits.
+- **SpO₂**: when the probe is disconnected, a flashing **NO SENSOR** replaces the saturation reading. Quality 0, loss of mechanical capture or a pulseless rhythm results in flashing **NO READING** (no numerical SpO₂/PR). Sensor disconnection takes precedence. No pleth waveform is displayed in these conditions.
+- **ART**: without mechanical pulses (including PVT/VF/asystole/PEA), the simulated invasive pressure line has slow non-pulsatile drift between **0 and 5 mmHg**. The numerical blood-pressure reading remains unavailable (`--/--`), rather than misrepresenting this baseline as true systolic and diastolic pressures.
+- **ECG rhythm name** has been removed from the monitor; only HR and the associated alarm message, when present, are visible. The instructor continues to select the rhythm in Admin.
+- Numerical alarm thresholds and the Adult preset from v0.4.1 are unchanged. Synthetic demonstration behavior only; not suitable for clinical decisions.
diff --git a/src/model.rs b/src/model.rs
index 2ce532c..6b1f6d1 100644
--- a/src/model.rs
+++ b/src/model.rs
@@ -5,15 +5,40 @@ pub enum EcgRhythm {
Sinus,
AtrialFibrillation,
VentricularTachycardia,
+ PulselessVentricularTachycardia,
VentricularFibrillation,
Asystole,
}
impl EcgRhythm {
- /// VF and asystole have no organized QRS to trigger a mechanical pulse.
+ /// Organized electrical QRS complexes. PVT still has electrical QRS complexes.
pub fn has_qrs(self) -> bool {
!matches!(self, Self::VentricularFibrillation | Self::Asystole)
}
+
+ /// Whether a QRS can trigger a mechanical pulse, depending on capture.
+ /// Perfusing VT is distinct from PVT. VF and asystole have no QRS.
+ pub fn can_generate_pulse(self) -> bool {
+ self.has_qrs() && self != Self::PulselessVentricularTachycardia
+ }
+
+ /// Rhythm alarms are independent of instructor-defined HR thresholds.
+ pub fn rhythm_alarm(self) -> Option<&'static str> {
+ match self {
+ Self::VentricularTachycardia | Self::PulselessVentricularTachycardia
+ | Self::VentricularFibrillation => Some("ARRHYTHMIA"),
+ Self::Asystole => Some("ASYSTOLE"),
+ _ => None,
+ }
+ }
+}
+
+/// Pulse-oximeter availability and technical alarms. Sensor loss takes precedence.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Spo2Status {
+ Available,
+ NoSensor,
+ NoReading,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -195,6 +220,24 @@ pub struct Parameters {
pub show_nibp: bool,
}
+impl Parameters {
+ /// No saturation without an attached sensor, usable signal quality and
+ /// two observed mechanical pulse events. Thresholds do not control this alarm.
+ pub fn spo2_status(&self, pulse_rate: Option<i32>) -> Spo2Status {
+ if !self.spo2_sensor_attached {
+ Spo2Status::NoSensor
+ } else if self.spo2_quality == Spo2Quality::None || pulse_rate.is_none()
+ || !self.ecg_rhythm.can_generate_pulse()
+ || self.pulse_conduction == PulseConduction::None
+ || self.heart_rate <= 0
+ {
+ Spo2Status::NoReading
+ } else {
+ Spo2Status::Available
+ }
+ }
+}
+
impl Default for Parameters {
fn default() -> Self {
Self {
@@ -308,6 +351,41 @@ mod tests {
assert!(!p.alarms.pr.enabled());
}
+ #[test]
+ fn vt_stays_perfusing_and_pvt_is_electrically_organized_but_pulseless() {
+ use EcgRhythm::*;
+ assert!(VentricularTachycardia.has_qrs());
+ assert!(VentricularTachycardia.can_generate_pulse());
+ assert!(PulselessVentricularTachycardia.has_qrs());
+ assert!(!PulselessVentricularTachycardia.can_generate_pulse());
+ assert!(!VentricularFibrillation.can_generate_pulse());
+ assert!(!Asystole.can_generate_pulse());
+ for rhythm in [VentricularTachycardia, PulselessVentricularTachycardia, VentricularFibrillation] {
+ assert_eq!(rhythm.rhythm_alarm(), Some("ARRHYTHMIA"));
+ }
+ assert_eq!(Asystole.rhythm_alarm(), Some("ASYSTOLE"));
+ assert_eq!(Sinus.rhythm_alarm(), None);
+ assert_eq!(AtrialFibrillation.rhythm_alarm(), None);
+ }
+
+ #[test]
+ fn sensor_and_no_reading_alarms_override_spo2_thresholds() {
+ let mut p = Parameters::default();
+ assert_eq!(p.spo2_status(Some(80)), Spo2Status::Available);
+ assert_eq!(p.spo2_status(None), Spo2Status::NoReading);
+ p.spo2_quality = Spo2Quality::None;
+ assert_eq!(p.spo2_status(Some(80)), Spo2Status::NoReading);
+ p.spo2_sensor_attached = false;
+ assert_eq!(p.spo2_status(Some(80)), Spo2Status::NoSensor);
+ p.spo2_sensor_attached = true;
+ p.spo2_quality = Spo2Quality::Good;
+ p.ecg_rhythm = EcgRhythm::PulselessVentricularTachycardia;
+ assert_eq!(p.spo2_status(Some(80)), Spo2Status::NoReading);
+ p.ecg_rhythm = EcgRhythm::Sinus;
+ p.pulse_conduction = PulseConduction::None;
+ assert_eq!(p.spo2_status(Some(80)), Spo2Status::NoReading);
+ }
+
#[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 8391fe8..c0f8474 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, AlarmLimits, AlarmState, EcgRhythm, Parameters, PulseConduction, Spo2Quality};
+use crate::model::{mean_arterial_pressure, AlarmLimits, AlarmState, Parameters, PulseConduction, Spo2Quality, Spo2Status};
use crate::simulation::{Sample, Simulator};
type Color = (f64, f64, f64);
@@ -106,17 +106,17 @@ fn pleth_trace_enabled(p: &Parameters) -> bool {
}
fn spo2_vitals(p: &Parameters, pulse_rate: Option<i32>) -> (String, String, String) {
- if !p.spo2_sensor_attached {
- return ("SpO₂".to_owned(), "NO SENSOR".to_owned(), "SpO₂ -- PR -- bpm".to_owned());
+ match p.spo2_status(pulse_rate) {
+ 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 => (
+ format!("SpO₂ {}", p.spo2_quality.stars()),
+ p.spo2.to_string(),
+ format!("% PR {} bpm", pulse_rate.unwrap_or_default()),
+ ),
}
- if p.spo2_quality == Spo2Quality::None {
- return ("SpO₂".to_owned(), "--".to_owned(), "NO SIGNAL PR -- bpm".to_owned());
- }
- (
- format!("SpO₂ {}", p.spo2_quality.stars()),
- if pulse_rate.is_some() { p.spo2.to_string() } else { "--".to_owned() },
- format!("% PR {} bpm", pulse_rate.map_or("--".to_owned(), |pr| pr.to_string())),
- )
}
fn alarmed(limits: AlarmLimits, value: Option<i32>) -> bool {
@@ -136,16 +136,15 @@ fn draw_vitals(cr: &Context, ch: Channel, color: Color, x: f64,
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) * 0.85;
let flash = alarm_flash_on(sim);
- let has_capture = p.ecg_rhythm.has_qrs()
+ let has_capture = p.ecg_rhythm.can_generate_pulse()
&& p.heart_rate > 0
&& p.pulse_conduction != PulseConduction::None;
let pulse_rate = if has_capture { sim.pulse_rate() } else { None };
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 spo2_status = p.spo2_status(pulse_rate);
+ let oxygen = if spo2_status == Spo2Status::Available { Some(p.spo2) } else { None };
let art_map = mean_arterial_pressure(p.art_systolic, p.art_diastolic);
let limits: Vec<(&str, AlarmLimits)> = match ch {
@@ -165,23 +164,23 @@ fn draw_vitals(cr: &Context, ch: Channel, color: Color, x: f64,
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",
- };
- text(cr, &format!("bpm · {}", rhythm), x, info_y, sub_size, color, false);
+ // 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);
+ }
}
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)
+ let technical_alarm = spo2_status != Spo2Status::Available;
+ let value_size = if technical_alarm {
+ number_size.min(0.17 * 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);
+ width, color, technical_alarm || 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",
@@ -377,7 +376,9 @@ fn draw_trace(cr: &Context, channel: Channel, color: Color,
}
// Disconnected or absent pleth signal: no curve, including historical pulses.
- if matches!(channel, Channel::Pleth) && !pleth_trace_enabled(p)
+ if matches!(channel, Channel::Pleth)
+ && (!pleth_trace_enabled(p)
+ || p.spo2_status(sim.pulse_rate()) != Spo2Status::Available)
{
let _ = cr.restore();
return;
@@ -544,8 +545,7 @@ mod tests {
p.spo2_sensor_attached = true;
p.spo2_quality = Spo2Quality::None;
assert!(!pleth_trace_enabled(&p));
- assert_eq!(spo2_vitals(&p, Some(75)).1, "--");
- assert!(spo2_vitals(&p, Some(75)).2.contains("NO SIGNAL"));
+ assert_eq!(spo2_vitals(&p, Some(75)).1, "NO READING");
assert!(spo2_vitals(&p, Some(75)).2.contains("PR --"));
assert!(p.show_spo2); // no readings, but visible row and status
}
@@ -559,10 +559,20 @@ mod tests {
assert!(spo2_vitals(&p, Some(75)).2.contains("PR 75 bpm"));
p.spo2_quality = Spo2Quality::Good;
assert_eq!(spo2_vitals(&p, Some(75)).0, "SpO₂ ★★★");
- assert_eq!(spo2_vitals(&p, None).1, "--");
+ assert_eq!(spo2_vitals(&p, None).1, "NO READING");
assert!(spo2_vitals(&p, None).2.contains("PR --"));
}
+ #[test]
+ fn no_sensor_precedes_no_reading_and_both_are_spo2_alarms() {
+ let mut p = Parameters::default();
+ assert_eq!(spo2_vitals(&p, None).1, "NO READING");
+ p.ecg_rhythm = crate::model::EcgRhythm::PulselessVentricularTachycardia;
+ assert_eq!(spo2_vitals(&p, Some(100)).1, "NO READING");
+ p.spo2_sensor_attached = false;
+ assert_eq!(spo2_vitals(&p, Some(100)).1, "NO SENSOR");
+ }
+
#[test]
fn arterial_axis_is_absolute_and_fixed_to_200_mmhg() {
let p = Parameters::default();
diff --git a/src/simulation.rs b/src/simulation.rs
index f3d7b01..a9f5c7b 100644
--- a/src/simulation.rs
+++ b/src/simulation.rs
@@ -109,7 +109,7 @@ impl Simulator {
if params.ecg_rhythm != self.previous_rhythm
|| params.pulse_conduction != self.previous_conduction
- || !params.ecg_rhythm.has_qrs()
+ || !params.ecg_rhythm.can_generate_pulse()
|| params.pulse_conduction == PulseConduction::None
|| params.heart_rate <= 0
{
@@ -146,7 +146,8 @@ impl Simulator {
// Interpolate within the 4 ms sample so mechanical onsets stay aligned.
let qrs_time = self.time - SAMPLE_STEP * (next_phase - QRS_PHASE) / increment;
self.ecg_beat_number += 1;
- if params.pulse_conduction.conducts(self.ecg_beat_number) {
+ if params.ecg_rhythm.can_generate_pulse()
+ && params.pulse_conduction.conducts(self.ecg_beat_number) {
let pulse_pressure_scale = if params.respiratory_rate > 0 {
ppv_multiplier(params.pulse_pressure_variation, self.respiratory_phase)
} else {
@@ -208,7 +209,14 @@ impl Simulator {
}
}
- let art = if let Some(age) = latest_art_age {
+ let art = if !params.ecg_rhythm.can_generate_pulse()
+ || params.pulse_conduction == PulseConduction::None
+ || params.heart_rate <= 0
+ {
+ // Low-frequency baseline drift around zero, without pulsations.
+ // The smooth, deterministic noise stays within 0..5 mmHg.
+ pulseless_arterial_drift(self.time)
+ } else if let Some(age) = latest_art_age {
// Pressure decays after an unperfused interval instead of showing a
// non-existent 75 mmHg baseline during prolonged missed captures.
let baseline = diastolic * (-(age - 0.60).max(0.0) / 1.40).exp();
@@ -220,6 +228,28 @@ impl Simulator {
}
}
+/// Deterministic smooth value noise with a slow, non-cardiac frequency.
+fn smooth_random_unit(time: f64, seconds_per_step: f64, seed: i64) -> f64 {
+ fn hash(index: i64) -> f64 {
+ let mut x = (index as u64).wrapping_add(0x9E37_79B9_7F4A_7C15);
+ x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
+ x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
+ x ^= x >> 31;
+ (x as f64) / (u64::MAX as f64)
+ }
+ let position = time / seconds_per_step;
+ let index = position.floor() as i64;
+ let delta = position - index as f64;
+ let fade = delta * delta * (3.0 - 2.0 * delta);
+ hash(index.wrapping_add(seed)) * (1.0 - fade)
+ + hash(index.wrapping_add(seed).wrapping_add(1)) * fade
+}
+
+fn pulseless_arterial_drift(time: f64) -> f64 {
+ (0.4 + 3.6 * smooth_random_unit(time, 2.4, 12)
+ + 0.65 * smooth_random_unit(time, 0.95, 41)).clamp(0.0, 5.0)
+}
+
fn gaussian(x: f64, center: f64, width: f64) -> f64 {
let d = (x - center) / width;
(-0.5 * d * d).exp()
@@ -281,7 +311,7 @@ fn ecg_amplitude(phase: f64, time: f64, rhythm: EcgRhythm, heart_rate: i32) -> f
- 0.32 * lobe(0.028, 0.012)
+ 0.28 * lobe(t_after_qrs, t_width)
}
- EcgRhythm::VentricularTachycardia => {
+ EcgRhythm::VentricularTachycardia | EcgRhythm::PulselessVentricularTachycardia => {
// Broad monomorphic ventricular complexes, also in milliseconds.
1.06 * lobe(0.0, 0.045)
- 0.49 * lobe(0.068, 0.030)
@@ -389,13 +419,14 @@ mod tests {
for (rhythm, capture) in [
(EcgRhythm::Asystole, PulseConduction::OneToOne),
(EcgRhythm::VentricularFibrillation, PulseConduction::OneToOne),
+ (EcgRhythm::PulselessVentricularTachycardia, PulseConduction::OneToOne),
(EcgRhythm::Sinus, PulseConduction::None),
] {
let p = Parameters { ecg_rhythm: rhythm, pulse_conduction: capture, ..Parameters::default() };
let mut sim = Simulator::new(&p);
for _ in 0..250 { sim.step(&p); }
assert!(sim.pulse_rate().is_none());
- assert!(sim.samples.iter().all(|s| s.art == 0.0 && s.pleth == 0.0));
+ assert!(sim.samples.iter().all(|s| (0.0..=5.0).contains(&s.art) && s.pleth == 0.0));
}
}
@@ -407,10 +438,44 @@ mod tests {
p.pulse_conduction = PulseConduction::None;
sim.step(&p);
assert!(sim.pulse_rate().is_none());
- assert_eq!(sim.samples.back().unwrap().art, 0.0);
+ assert!((0.0..=5.0).contains(&sim.samples.back().unwrap().art));
assert_eq!(sim.samples.back().unwrap().pleth, 0.0);
}
+ #[test]
+ fn vt_remains_perfusing_and_pvt_has_qrs_but_no_pulse() {
+ let mut p = Parameters {
+ ecg_rhythm: EcgRhythm::VentricularTachycardia,
+ heart_rate: 160,
+ ..Parameters::default()
+ };
+ let mut sim = Simulator::new(&p);
+ assert_eq!(sim.pulse_rate(), Some(160));
+ assert!(sim.samples().iter().any(|s| s.art > 70.0 && s.pleth > 0.0));
+ p.ecg_rhythm = EcgRhythm::PulselessVentricularTachycardia;
+ sim.step(&p);
+ assert_eq!(sim.pulse_rate(), None);
+ assert!((0.0..=5.0).contains(&sim.samples().back().unwrap().art));
+ assert_eq!(sim.samples().back().unwrap().pleth, 0.0);
+ for _ in 0..500 { sim.step(&p); }
+ assert!(sim.samples().iter().rev().take(500)
+ .all(|s| (0.0..=5.0).contains(&s.art) && s.pleth == 0.0));
+ assert!(sim.samples().iter().rev().take(500)
+ .any(|s| s.ecg.abs() > 0.3));
+ }
+
+ #[test]
+ fn low_pressure_drift_is_smooth_and_never_pulsatile() {
+ let values: Vec<f64> = (0..5000)
+ .map(|n| pulseless_arterial_drift(n as f64 * SAMPLE_STEP))
+ .collect();
+ assert!(values.iter().all(|v| (0.0..=5.0).contains(v)));
+ assert!(values.windows(2).all(|w| (w[1] - w[0]).abs() < 0.10));
+ let spread = values.iter().copied().fold(f64::NEG_INFINITY, f64::max)
+ - values.iter().copied().fold(f64::INFINITY, f64::min);
+ assert!(spread > 0.25);
+ }
+
#[test]
fn pulse_rate_follows_two_to_one_capture() {
let p = Parameters { pulse_conduction: PulseConduction::TwoToOne, ..Parameters::default() };
diff --git a/src/ui.rs b/src/ui.rs
index a36fec3..669c227 100644
--- a/src/ui.rs
+++ b/src/ui.rs
@@ -146,14 +146,15 @@ fn create_admin(app: &Application, params: SharedParams,
let ecg = group(&controls, "ECG");
add_visibility(&ecg, params.borrow().show_ecg, params.clone(), |p, show| p.show_ecg = show);
add_dropdown(&ecg, "ECG rhythm", &[
- "Sinus rhythm", "Atrial fibrillation", "Ventricular tachycardia",
- "Ventricular fibrillation", "Asystole",
+ "Sinus rhythm", "Atrial fibrillation", "Ventricular tachycardia (VT)",
+ "Pulseless ventricular tachycardia (PVT)", "Ventricular fibrillation", "Asystole",
], params.clone(), |p, selected| {
p.ecg_rhythm = match selected {
1 => EcgRhythm::AtrialFibrillation,
2 => EcgRhythm::VentricularTachycardia,
- 3 => EcgRhythm::VentricularFibrillation,
- 4 => EcgRhythm::Asystole,
+ 3 => EcgRhythm::PulselessVentricularTachycardia,
+ 4 => EcgRhythm::VentricularFibrillation,
+ 5 => EcgRhythm::Asystole,
_ => EcgRhythm::Sinus,
};
});
@@ -210,7 +211,7 @@ fn create_admin(app: &Application, params: SharedParams,
});
let conduction_hint = gtk::Label::new(Some(
"Pulse rate is derived from captured QRS events.
-ART and pleth are delayed; VF and asystole always have no pulse."
+ART and pleth are delayed. VT can be perfusing; PVT, VF and asystole are pulseless."
));
conduction_hint.set_xalign(0.0);
conduction_hint.set_wrap(true);

View file

@ -0,0 +1,691 @@
diff --git a/Cargo.toml b/Cargo.toml
index 02a5d17..e273c5e 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "patient-monitor-simulation"
-version = "0.4.2"
+version = "0.4.3"
edition = "2021"
license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"
diff --git a/README.md b/README.md
index c693e16..cdc1f9b 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.4.2
+# Patient Monitor Simulation (PaMSim) — v0.4.3
A two-window, Rust/GTK4 patient-monitor simulator for teaching on Fedora Linux.
@@ -131,15 +131,21 @@ Admin → **Pulse oximetry** has two additional controls:
| Setting | Pleth waveform | Monitor display |
| --- | --- | --- |
| **0 — None** | No waveform | Flashing **NO READING**, PR `--`; no stars |
-| **1 — Poor** | Small, irregularly amplitude-distorted pulse | 1 star (★) |
+| **1 — Poor** | Small, irregularly distorted pulse, with temporary losses of signal | 1 star (★) when available; blinking **NO READING** during loss |
| **2 — Adequate** | Medium, smoothly damped pulse | 2 stars (★★) |
| **3 — Good** | Full nominal, smoothly damped pulse | 3 stars (★★★) |
Default: sensor attached; signal quality **3 — Good**. At levels 1–3, the
instructor-set SpO₂ number is shown only when mechanical pulses are detected.
-The signal quality does **not** randomly alter that number: it affects the
-pleth morphology and the quality indicator only. The simulated pulse rate
-remains derived from mechanically captured QRS complexes.
+In **Poor** quality, the signal also has intermittent complete dropouts:
+**30–180 seconds of signal** between interruptions, with each interruption
+lasting **5–20 seconds**. During an interruption the pleth trace disappears,
+SpO₂ and PR are unavailable, and **NO READING** flashes. Following recovery,
+the Poor waveform and numerical readings return automatically. These intervals
+are pseudo-random and driven by simulation time, independent of frame rate;
+they reset when Poor quality is selected again. The dropout does not affect
+the actual saturation setting, ECG, derived mechanical pulse generation, or ART.
+The simulated pulse rate remains derived from captured QRS complexes.
The degraded waveform uses deterministic, smoothly interpolated pseudo-noise
that scales only existing pleth pulses: it cannot manufacture pulses during
@@ -159,8 +165,12 @@ can be taught.
controlled by a pulse-rate slider.
- A captured QRS leads to an ART upstroke after a schematic **120 ms**, and a
peripheral pleth pulse after **300 ms**. Pleth is strongly damped/filtered.
+- VT and PVT selections start with a heart rate of **160 bpm**, and update
+ both the HR slider and numeric entry. The instructor may modify this afterward.
- PVT, VF, asystole and PEA suppress mechanical pulses; the ART trace then
drifts smoothly at 0–5 mmHg rather than representing a pulsatile pressure.
+ The ART **SYS** number shows the rounded low transducer pressure (0–5 mmHg),
+ while DIA and MAP show `--` because they cannot be reliably estimated.
Previous pressure samples scroll out of view. NIBP is a static,
separately entered cuff reading.
@@ -297,6 +307,26 @@ environment; run `cargo test` and `cargo run --release` on Fedora.
- **VT** remains potentially perfusing. The new **PVT** (pulseless ventricular tachycardia) rhythm retains organized broad QRS complexes but produces no arterial/pleth pulses. VF and asystole are also pulseless regardless of capture selection.
- **ECG**: a flashing **ARRHYTHMIA** message for VT, PVT and VF; a flashing **ASYSTOLE** message for asystole. These event alarms do not depend on numerical HR limits.
- **SpO₂**: when the probe is disconnected, a flashing **NO SENSOR** replaces the saturation reading. Quality 0, loss of mechanical capture or a pulseless rhythm results in flashing **NO READING** (no numerical SpO₂/PR). Sensor disconnection takes precedence. No pleth waveform is displayed in these conditions.
-- **ART**: without mechanical pulses (including PVT/VF/asystole/PEA), the simulated invasive pressure line has slow non-pulsatile drift between **0 and 5 mmHg**. The numerical blood-pressure reading remains unavailable (`--/--`), rather than misrepresenting this baseline as true systolic and diastolic pressures.
+- **ART**: without mechanical pulses (including PVT/VF/asystole/PEA), the simulated invasive pressure line has slow non-pulsatile drift between **0 and 5 mmHg**. In v0.4.2, the numeric display showed `--/--`; v0.4.3 changes this to a rounded measured SYS of 0–5 mmHg, with `--` for DIA and MAP.
- **ECG rhythm name** has been removed from the monitor; only HR and the associated alarm message, when present, are visible. The instructor continues to select the rhythm in Admin.
- Numerical alarm thresholds and the Adult preset from v0.4.1 are unchanged. Synthetic demonstration behavior only; not suitable for clinical decisions.
+
+
+## v0.4.3 — Low arterial pressure, VT rate preset and intermittent Poor SpO₂
+
+- Pulseless rhythms, PEA or otherwise absent mechanical capture: invasive SYS
+ reports the **current measured 0–5 mmHg** pressure, e.g. `3/--` with
+ `MAP -- mmHg`. **Only SYS** is tested against configured ART SYS limits;
+ no spurious MAP/DIA threshold alarms are generated from missing readings.
+- Selecting **VT** or **PVT** in Admin sets HR to **160 bpm** and updates the
+ associated slider and text field. Subsequent manual rate changes are allowed.
+ Perfusing VT still produces QRS-linked pulses subject to capture settings;
+ PVT remains pulseless.
+- **Poor (★)** SpO₂ signal periodically changes to **NO READING** for a
+ pseudo-random **5–20 seconds**, after a pseudo-random **30–180 seconds** of
+ usable low-quality signal. The technical alarm blinks, SpO₂/PR readings are
+ suppressed, and the pleth waveform is absent. On recovery it resumes at Poor
+ quality. The simulated signal history retains visible gaps for outages.
+ Choosing another signal quality immediately clears the intermittent outage.
+- No changes to Adult alarm presets, alarm limit ordering, or the 0–200 mmHg
+ arterial scale. All behavior is synthetic and intended for teaching only.
diff --git a/src/model.rs b/src/model.rs
index 6b1f6d1..03d7bbe 100644
--- a/src/model.rs
+++ b/src/model.rs
@@ -221,12 +221,29 @@ pub struct Parameters {
}
impl Parameters {
+ /// Selecting a ventricular tachycardia starts at the teaching default of
+ /// 160 bpm. The instructor can subsequently adjust the heart rate.
+ pub fn select_ecg_rhythm(&mut self, rhythm: EcgRhythm) {
+ self.ecg_rhythm = rhythm;
+ if matches!(rhythm, EcgRhythm::VentricularTachycardia
+ | EcgRhythm::PulselessVentricularTachycardia) {
+ self.heart_rate = 160;
+ }
+ }
+
/// No saturation without an attached sensor, usable signal quality and
/// two observed mechanical pulse events. Thresholds do not control this alarm.
pub fn spo2_status(&self, pulse_rate: Option<i32>) -> Spo2Status {
+ self.spo2_status_during(pulse_rate, false)
+ }
+
+ /// Poor-quality signal interruptions are generated by the simulator and
+ /// override the normal reading, but not a physically disconnected sensor.
+ pub fn spo2_status_during(&self, pulse_rate: Option<i32>, signal_lost: bool) -> Spo2Status {
if !self.spo2_sensor_attached {
Spo2Status::NoSensor
- } else if self.spo2_quality == Spo2Quality::None || pulse_rate.is_none()
+ } else if (signal_lost && self.spo2_quality == Spo2Quality::Poor)
+ || self.spo2_quality == Spo2Quality::None || pulse_rate.is_none()
|| !self.ecg_rhythm.can_generate_pulse()
|| self.pulse_conduction == PulseConduction::None
|| self.heart_rate <= 0
@@ -368,6 +385,34 @@ mod tests {
assert_eq!(AtrialFibrillation.rhythm_alarm(), None);
}
+ #[test]
+ fn tachycardia_selection_sets_160_bpm_but_other_rhythms_do_not() {
+ let mut p = Parameters::default();
+ p.select_ecg_rhythm(EcgRhythm::VentricularTachycardia);
+ assert_eq!(p.heart_rate, 160);
+ p.heart_rate = 185; // a subsequent instructor override remains possible
+ p.select_ecg_rhythm(EcgRhythm::Sinus);
+ assert_eq!(p.heart_rate, 185);
+ p.select_ecg_rhythm(EcgRhythm::PulselessVentricularTachycardia);
+ assert_eq!(p.heart_rate, 160);
+ assert!(!p.ecg_rhythm.can_generate_pulse());
+ }
+
+ #[test]
+ fn transient_poor_signal_loss_preserves_sensor_precedence() {
+ let mut p = Parameters::default();
+ p.spo2_quality = Spo2Quality::Poor;
+ assert_eq!(p.spo2_status_during(Some(80), false), Spo2Status::Available);
+ assert_eq!(p.spo2_status_during(Some(80), true), Spo2Status::NoReading);
+ p.spo2_sensor_attached = false;
+ assert_eq!(p.spo2_status_during(Some(80), true), Spo2Status::NoSensor);
+ p.spo2_sensor_attached = true;
+ p.spo2_quality = Spo2Quality::Good;
+ assert_eq!(p.spo2_status_during(Some(80), false), Spo2Status::Available);
+ assert_eq!(p.spo2_status_during(Some(80), true), Spo2Status::Available);
+
+ }
+
#[test]
fn sensor_and_no_reading_alarms_override_spo2_thresholds() {
let mut p = Parameters::default();
diff --git a/src/render.rs b/src/render.rs
index c0f8474..3412859 100644
--- a/src/render.rs
+++ b/src/render.rs
@@ -105,8 +105,9 @@ fn pleth_trace_enabled(p: &Parameters) -> bool {
p.spo2_sensor_attached && p.spo2_quality != Spo2Quality::None
}
-fn spo2_vitals(p: &Parameters, pulse_rate: Option<i32>) -> (String, String, String) {
- match p.spo2_status(pulse_rate) {
+fn spo2_vitals(p: &Parameters, pulse_rate: Option<i32>, signal_lost: bool)
+ -> (String, String, String) {
+ match p.spo2_status_during(pulse_rate, signal_lost) {
Spo2Status::NoSensor => (
"SpO₂".to_owned(), "NO SENSOR".to_owned(), "PR -- bpm".to_owned()),
Spo2Status::NoReading => (
@@ -143,7 +144,7 @@ fn draw_vitals(cr: &Context, ch: Channel, color: Color, x: f64,
let ecg_hr = if p.ecg_rhythm.has_qrs() && p.heart_rate > 0 {
Some(p.heart_rate)
} else { None };
- let spo2_status = p.spo2_status(pulse_rate);
+ let spo2_status = p.spo2_status_during(pulse_rate, sim.poor_signal_lost());
let oxygen = if spo2_status == Spo2Status::Available { Some(p.spo2) } else { None };
let art_map = mean_arterial_pressure(p.art_systolic, p.art_diastolic);
@@ -173,7 +174,7 @@ fn draw_vitals(cr: &Context, ch: Channel, color: Color, x: f64,
}
}
Channel::Pleth => {
- let (label, value, info) = spo2_vitals(p, pulse_rate);
+ let (label, value, info) = spo2_vitals(p, pulse_rate, sim.poor_signal_lost());
text(cr, &label, x, top + row_h * 0.24, label_size, color, false);
let technical_alarm = spo2_status != Spo2Status::Available;
let value_size = if technical_alarm {
@@ -212,8 +213,14 @@ fn draw_vitals(cr: &Context, ch: Channel, color: Color, x: f64,
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);
+ // Without mechanical activity the transducer still reads the
+ // slowly drifting 0..5 mmHg pressure. DIA/MAP are indeterminate.
+ let pulseless = !has_capture;
+ let sys = if pulseless { sim.measured_art_pressure() } else { None };
+ let displayed_sys = sys.map_or_else(|| "--".to_owned(), |v| v.to_string());
+ draw_pressure_components(cr, &displayed_sys, "--", x, value_y,
+ number_size * 0.78, width, color,
+ alarmed(p.alarms.art_sys, sys), false, flash);
text(cr, "MAP -- mmHg", x, info_y, sub_size, color, false);
}
}
@@ -270,17 +277,24 @@ 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();
+ draw_pressure_components(cr, &systolic.to_string(), &diastolic.to_string(),
+ x, baseline, nominal_size, available_width, color, sys_alarm, dia_alarm, flash);
+}
+
+#[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) {
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, 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);
+ draw_segment(cr, dia, cursor, baseline, size, color, dia_alarm && flash, true);
let _ = cr.restore();
}
@@ -378,7 +392,7 @@ fn draw_trace(cr: &Context, channel: Channel, color: Color,
// Disconnected or absent pleth signal: no curve, including historical pulses.
if matches!(channel, Channel::Pleth)
&& (!pleth_trace_enabled(p)
- || p.spo2_status(sim.pulse_rate()) != Spo2Status::Available)
+ || p.spo2_status_during(sim.pulse_rate(), sim.poor_signal_lost()) != Spo2Status::Available)
{
let _ = cr.restore();
return;
@@ -393,6 +407,10 @@ fn draw_trace(cr: &Context, channel: Channel, color: Color,
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;
+ }
if started { cr.line_to(x, y); }
else { cr.move_to(x, y); started = true; }
}
@@ -540,13 +558,13 @@ mod tests {
assert!(pleth_trace_enabled(&p));
p.spo2_sensor_attached = false;
assert!(!pleth_trace_enabled(&p));
- assert_eq!(spo2_vitals(&p, Some(75)).1, "NO SENSOR");
- assert!(spo2_vitals(&p, Some(75)).2.contains("PR --"));
+ assert_eq!(spo2_vitals(&p, Some(75), false).1, "NO SENSOR");
+ assert!(spo2_vitals(&p, Some(75), false).2.contains("PR --"));
p.spo2_sensor_attached = true;
p.spo2_quality = Spo2Quality::None;
assert!(!pleth_trace_enabled(&p));
- assert_eq!(spo2_vitals(&p, Some(75)).1, "NO READING");
- assert!(spo2_vitals(&p, Some(75)).2.contains("PR --"));
+ assert_eq!(spo2_vitals(&p, Some(75), false).1, "NO READING");
+ assert!(spo2_vitals(&p, Some(75), false).2.contains("PR --"));
assert!(p.show_spo2); // no readings, but visible row and status
}
@@ -554,29 +572,37 @@ mod tests {
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)).0, "SpO₂ ★");
- assert_eq!(spo2_vitals(&p, Some(75)).1, "98");
- assert!(spo2_vitals(&p, Some(75)).2.contains("PR 75 bpm"));
+ 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"));
p.spo2_quality = Spo2Quality::Good;
- assert_eq!(spo2_vitals(&p, Some(75)).0, "SpO₂ ★★★");
- assert_eq!(spo2_vitals(&p, None).1, "NO READING");
- assert!(spo2_vitals(&p, None).2.contains("PR --"));
+ 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 --"));
}
#[test]
fn no_sensor_precedes_no_reading_and_both_are_spo2_alarms() {
let mut p = Parameters::default();
- assert_eq!(spo2_vitals(&p, None).1, "NO READING");
+ assert_eq!(spo2_vitals(&p, None, false).1, "NO READING");
p.ecg_rhythm = crate::model::EcgRhythm::PulselessVentricularTachycardia;
- assert_eq!(spo2_vitals(&p, Some(100)).1, "NO READING");
+ assert_eq!(spo2_vitals(&p, Some(100), false).1, "NO READING");
p.spo2_sensor_attached = false;
- assert_eq!(spo2_vitals(&p, Some(100)).1, "NO SENSOR");
+ 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");
}
#[test]
fn arterial_axis_is_absolute_and_fixed_to_200_mmhg() {
let p = Parameters::default();
- let mut s = Sample { time: 0.0, ecg: 0.0, pleth: 0.0, art: 100.0, co2: 0.0 };
+ let mut s = Sample { time: 0.0, ecg: 0.0, pleth: 0.0, pleth_valid: true, art: 100.0, co2: 0.0 };
assert_eq!(normalized(Channel::Art, &s, &p), 0.5);
s.art = 200.0;
assert_eq!(normalized(Channel::Art, &s, &p), 1.0);
diff --git a/src/simulation.rs b/src/simulation.rs
index a9f5c7b..a2b7bc5 100644
--- a/src/simulation.rs
+++ b/src/simulation.rs
@@ -2,7 +2,7 @@
//! A conducted QRS schedules an arterial pulse and a delayed, smoothed pleth pulse.
use std::collections::VecDeque;
-use crate::model::{ArterialShape, CapnoShape, EcgRhythm, Parameters, PulseConduction};
+use crate::model::{ArterialShape, CapnoShape, EcgRhythm, Parameters, PulseConduction, Spo2Quality};
const SAMPLE_STEP: f64 = 0.004; // 250 Hz; adequately samples the QRS upstroke
const HISTORY_SECONDS: f64 = 10.0;
@@ -32,10 +32,59 @@ pub struct Sample {
pub time: f64,
pub ecg: f64, // arbitrary amplitude
pub pleth: f64, // attenuated, low-pass-filtered amplitude 0..1
+ pub pleth_valid: bool, // gaps during intermittent signal dropout
pub art: f64, // absolute pressure in mmHg; display clips above 200
pub co2: f64, // mmHg
}
+/// Reproducible pseudo-random outages of the pulse-oximeter in Poor quality.
+/// Each recovery is followed by 30..180 s of signal before a 5..20 s dropout.
+/// The schedule advances in simulation seconds and does not depend on FPS.
+#[derive(Debug)]
+struct PoorSignalOutages {
+ rng: u64,
+ enabled: bool,
+ active: bool,
+ next_start: f64,
+ end: f64,
+}
+
+impl PoorSignalOutages {
+ fn new() -> Self {
+ Self { rng: 0xC3A5_C85C_97CB_3127, enabled: false,
+ active: false, next_start: 0.0, end: 0.0 }
+ }
+
+ fn random_range(&mut self, lower: f64, upper: f64) -> f64 {
+ // 64-bit LCG; deterministic, not cryptographic randomness.
+ self.rng = self.rng.wrapping_mul(6_364_136_223_846_793_005)
+ .wrapping_add(1_442_695_040_888_963_407);
+ let fraction = (self.rng >> 11) as f64 / (1_u64 << 53) as f64;
+ lower + (upper - lower) * fraction
+ }
+
+ fn update(&mut self, now: f64, poor: bool) {
+ if !poor {
+ self.enabled = false;
+ self.active = false;
+ return;
+ }
+ // Deliberately do not schedule during the negative-time trace warmup.
+ if now < 0.0 { return; }
+ if !self.enabled {
+ self.enabled = true;
+ self.active = false;
+ self.next_start = now + self.random_range(30.0, 180.0);
+ } else if self.active && now >= self.end {
+ self.active = false;
+ self.next_start = now + self.random_range(30.0, 180.0);
+ } else if !self.active && now >= self.next_start {
+ self.active = true;
+ self.end = now + self.random_range(5.0, 20.0);
+ }
+ }
+}
+
pub struct Simulator {
samples: VecDeque<Sample>,
time: f64,
@@ -48,6 +97,7 @@ pub struct Simulator {
previous_rhythm: EcgRhythm,
previous_conduction: PulseConduction,
previous_heart_rate: i32,
+ poor_signal_outages: PoorSignalOutages,
pending_time: f64,
}
@@ -65,6 +115,7 @@ impl Simulator {
previous_rhythm: params.ecg_rhythm,
previous_conduction: params.pulse_conduction,
previous_heart_rate: params.heart_rate,
+ poor_signal_outages: PoorSignalOutages::new(),
pending_time: 0.0,
};
// Prepopulate the trace and pulse history, including the initial pulse rate.
@@ -83,6 +134,15 @@ impl Simulator {
}
}
+ pub fn poor_signal_lost(&self) -> bool {
+ self.poor_signal_outages.active
+ }
+
+ /// Last arterial transducer sample, in mmHg (including slow 0..5 drift).
+ pub fn measured_art_pressure(&self) -> Option<i32> {
+ self.samples.back().map(|sample| sample.art.round() as i32)
+ }
+
pub fn samples(&self) -> &VecDeque<Sample> {
&self.samples
}
@@ -106,6 +166,8 @@ impl Simulator {
fn step(&mut self, params: &Parameters) {
self.time += SAMPLE_STEP;
+ self.poor_signal_outages.update(self.time,
+ params.spo2_quality == Spo2Quality::Poor && params.spo2_sensor_attached);
if params.ecg_rhythm != self.previous_rhythm
|| params.pulse_conduction != self.previous_conduction
@@ -180,7 +242,10 @@ impl Simulator {
capno_amplitude(self.respiratory_phase, params.capno_shape)
};
- self.samples.push_back(Sample { time: self.time, ecg, pleth, art, co2 });
+ let pleth_valid = params.spo2_sensor_attached
+ && params.spo2_quality != Spo2Quality::None
+ && !self.poor_signal_outages.active;
+ self.samples.push_back(Sample { time: self.time, ecg, pleth, pleth_valid, art, co2 });
while self.samples.front().is_some_and(|first| first.time < self.time - HISTORY_SECONDS) {
self.samples.pop_front();
}
@@ -476,6 +541,68 @@ mod tests {
assert!(spread > 0.25);
}
+ #[test]
+ fn low_arterial_pressure_stays_measurable_without_pulses() {
+ for rhythm in [EcgRhythm::PulselessVentricularTachycardia,
+ EcgRhythm::VentricularFibrillation, EcgRhythm::Asystole] {
+ let p = Parameters { ecg_rhythm: rhythm, ..Parameters::default() };
+ let mut sim = Simulator::new(&p);
+ for _ in 0..500 { sim.step(&p); }
+ assert_eq!(sim.pulse_rate(), None);
+ let pressure = sim.measured_art_pressure().unwrap();
+ assert!((0..=5).contains(&pressure), "{rhythm:?}: {pressure}");
+ }
+ }
+
+ #[test]
+ fn poor_signal_outages_have_random_intervals_and_durations() {
+ let mut outage = PoorSignalOutages::new();
+ outage.update(0.0, true);
+ let mut start = 0.0;
+ let mut gaps = Vec::new();
+ let mut durations = Vec::new();
+ for _ in 0..16 {
+ let next = outage.next_start;
+ gaps.push(next - start);
+ assert!((30.0..=180.0).contains(&(next - start)));
+ outage.update(next, true);
+ assert!(outage.active);
+ let end = outage.end;
+ durations.push(end - next);
+ assert!((5.0..=20.0).contains(&(end - next)));
+ outage.update(end, true);
+ assert!(!outage.active);
+ start = end;
+ }
+ assert!(gaps.iter().any(|v| (v - gaps[0]).abs() > 1.0));
+ assert!(durations.iter().any(|v| (v - durations[0]).abs() > 1.0));
+ outage.update(start + 1.0, false);
+ assert!(!outage.active);
+ outage.update(start + 2.0, true);
+ assert!(!outage.active); // switching back to Poor reschedules
+ }
+
+ #[test]
+ fn poor_signal_dropout_does_not_change_art_or_ecg() {
+ let mut p = Parameters::default();
+ p.spo2_quality = Spo2Quality::Poor;
+ let mut sim = Simulator::new(&p);
+ // Force an outage to test signal gaps without synthesizing minutes.
+ sim.poor_signal_outages.enabled = true;
+ sim.poor_signal_outages.active = true;
+ sim.poor_signal_outages.end = sim.time + 10.0;
+ sim.step(&p);
+ assert!(!sim.samples.back().unwrap().pleth_valid);
+ assert!(sim.poor_signal_lost());
+ assert!((0.0..=200.0).contains(&sim.samples.back().unwrap().art));
+ assert_eq!(p.spo2_status_during(sim.pulse_rate(), sim.poor_signal_lost()),
+ crate::model::Spo2Status::NoReading);
+ p.spo2_quality = Spo2Quality::Good;
+ sim.step(&p);
+ assert!(!sim.poor_signal_lost());
+ assert!(sim.samples.back().unwrap().pleth_valid);
+ }
+
#[test]
fn pulse_rate_follows_two_to_one_capture() {
let p = Parameters { pulse_conduction: PulseConduction::TwoToOne, ..Parameters::default() };
diff --git a/src/ui.rs b/src/ui.rs
index 669c227..55d31cb 100644
--- a/src/ui.rs
+++ b/src/ui.rs
@@ -145,11 +145,11 @@ fn create_admin(app: &Application, params: SharedParams,
let ecg = group(&controls, "ECG");
add_visibility(&ecg, params.borrow().show_ecg, params.clone(), |p, show| p.show_ecg = show);
- add_dropdown(&ecg, "ECG rhythm", &[
+ let rhythm_dropdown = add_dropdown_at(&ecg, "ECG rhythm", &[
"Sinus rhythm", "Atrial fibrillation", "Ventricular tachycardia (VT)",
"Pulseless ventricular tachycardia (PVT)", "Ventricular fibrillation", "Asystole",
- ], params.clone(), |p, selected| {
- p.ecg_rhythm = match selected {
+ ], 0, params.clone(), |p, selected| {
+ let rhythm = match selected {
1 => EcgRhythm::AtrialFibrillation,
2 => EcgRhythm::VentricularTachycardia,
3 => EcgRhythm::PulselessVentricularTachycardia,
@@ -157,16 +157,25 @@ fn create_admin(app: &Application, params: SharedParams,
5 => EcgRhythm::Asystole,
_ => EcgRhythm::Sinus,
};
+ p.select_ecg_rhythm(rhythm);
+ });
+ let (hr_row, hr_slider, hr_entry) = add_numeric(&ecg, "Heart rate", "bpm", 0, 240,
+ params.borrow().heart_rate, params.clone(), |p, v| p.heart_rate = v);
+ // Programmatic 160 bpm VT/PVT preset must update both controls,
+ // including an HR field that currently has keyboard focus.
+ rhythm_dropdown.connect_selected_notify(move |selector| {
+ if selector.selected() == 2 || selector.selected() == 3 {
+ hr_slider.set_value(160.0);
+ hr_entry.set_text("160");
+ }
});
- let hr_row = add_numeric(&ecg, "Heart rate", "bpm", 0, 240, params.borrow().heart_rate,
- params.clone(), |p, v| p.heart_rate = v);
alarm_editors.push((add_alarm_limits(&hr_row, "", "", 240,
params.borrow().alarms.hr, params.clone(), |p, v| p.alarms.hr = v,
&preset_dropdown, &updating_preset), |s| s.hr));
let spo2 = group(&controls, "Pulse oximetry");
add_visibility(&spo2, params.borrow().show_spo2, params.clone(), |p, show| p.show_spo2 = show);
- let spo2_row = add_numeric(&spo2, "SpO₂", "%", 0, 100, params.borrow().spo2,
+ let (spo2_row, _, _) = add_numeric(&spo2, "SpO₂", "%", 0, 100, params.borrow().spo2,
params.clone(), |p, v| p.spo2 = v);
alarm_editors.push((add_alarm_limits(&spo2_row, "", "", 100,
params.borrow().alarms.spo2, params.clone(), |p, v| p.alarms.spo2 = v,
@@ -181,7 +190,7 @@ fn create_admin(app: &Application, params: SharedParams,
move |button| params.borrow_mut().spo2_sensor_attached = !button.is_active()
});
spo2.append(&sensor);
- add_dropdown_at(&spo2, "Signal quality", &[
+ let _ = add_dropdown_at(&spo2, "Signal quality", &[
"0 — None (no reading)",
"1 — Poor (*)",
"2 — Adequate (**)",
@@ -209,6 +218,18 @@ fn create_admin(app: &Application, params: SharedParams,
_ => PulseConduction::OneToOne,
};
});
+ let dropout_hint = gtk::Label::new(Some(
+ "Poor signal: randomly loses all SpO₂/PR readings for 5–20 s,"
+ ));
+ dropout_hint.set_xalign(0.0);
+ dropout_hint.set_wrap(true);
+ spo2.append(&dropout_hint);
+ let dropout_hint2 = gtk::Label::new(Some(
+ "with 30–180 s of usable poor-quality signal between interruptions."
+ ));
+ dropout_hint2.set_xalign(0.0);
+ dropout_hint2.set_wrap(true);
+ spo2.append(&dropout_hint2);
let conduction_hint = gtk::Label::new(Some(
"Pulse rate is derived from captured QRS events.
ART and pleth are delayed. VT can be perfusing; PVT, VF and asystole are pulseless."
@@ -219,7 +240,7 @@ ART and pleth are delayed. VT can be perfusing; PVT, VF and asystole are pulsele
let art = group(&controls, "Invasive arterial blood pressure");
add_visibility(&art, params.borrow().show_art, params.clone(), |p, show| p.show_art = show);
- let art_sys_row = add_numeric(&art, "Systolic", "mmHg", 0, 200, params.borrow().art_systolic,
+ let (art_sys_row, _, _) = add_numeric(&art, "Systolic", "mmHg", 0, 200, params.borrow().art_systolic,
params.clone(), |p, v| p.art_systolic = v);
alarm_editors.push((add_alarm_limits(&art_sys_row, "", "", 200,
params.borrow().alarms.art_sys, params.clone(), |p, v| p.alarms.art_sys = v,
@@ -227,12 +248,12 @@ ART and pleth are delayed. VT can be perfusing; PVT, VF and asystole are pulsele
alarm_editors.push((add_alarm_limits(&art, "MAP (derived)", "mmHg", 200,
params.borrow().alarms.art_map, params.clone(), |p, v| p.alarms.art_map = v,
&preset_dropdown, &updating_preset), |s| s.art_map));
- let art_dia_row = add_numeric(&art, "Diastolic", "mmHg", 0, 200, params.borrow().art_diastolic,
+ let (art_dia_row, _, _) = add_numeric(&art, "Diastolic", "mmHg", 0, 200, params.borrow().art_diastolic,
params.clone(), |p, v| p.art_diastolic = v);
alarm_editors.push((add_alarm_limits(&art_dia_row, "", "", 200,
params.borrow().alarms.art_dia, params.clone(), |p, v| p.alarms.art_dia = v,
&preset_dropdown, &updating_preset), |s| s.art_dia));
- let ppv_row = add_numeric(&art, "Pulse pressure variation", "%", 0, 60,
+ let (ppv_row, _, _) = add_numeric(&art, "Pulse pressure variation", "%", 0, 60,
params.borrow().pulse_pressure_variation, params.clone(),
|p, v| p.pulse_pressure_variation = v);
alarm_editors.push((add_alarm_limits(&ppv_row, "", "", 60,
@@ -256,7 +277,7 @@ ART and pleth are delayed. VT can be perfusing; PVT, VF and asystole are pulsele
let nibp = group(&controls, "Non-invasive blood pressure (NIBP)");
add_visibility(&nibp, params.borrow().show_nibp, params.clone(), |p, show| p.show_nibp = show);
- let nibp_sys_row = add_numeric(&nibp, "Systolic", "mmHg", 0, 260, params.borrow().nibp_systolic,
+ let (nibp_sys_row, _, _) = add_numeric(&nibp, "Systolic", "mmHg", 0, 260, params.borrow().nibp_systolic,
params.clone(), |p, v| p.nibp_systolic = v);
alarm_editors.push((add_alarm_limits(&nibp_sys_row, "", "", 260,
params.borrow().alarms.nibp_sys, params.clone(), |p, v| p.alarms.nibp_sys = v,
@@ -264,7 +285,7 @@ ART and pleth are delayed. VT can be perfusing; PVT, VF and asystole are pulsele
alarm_editors.push((add_alarm_limits(&nibp, "MAP (derived)", "mmHg", 260,
params.borrow().alarms.nibp_map, params.clone(), |p, v| p.alarms.nibp_map = v,
&preset_dropdown, &updating_preset), |s| s.nibp_map));
- let nibp_dia_row = add_numeric(&nibp, "Diastolic", "mmHg", 0, 200, params.borrow().nibp_diastolic,
+ let (nibp_dia_row, _, _) = add_numeric(&nibp, "Diastolic", "mmHg", 0, 200, params.borrow().nibp_diastolic,
params.clone(), |p, v| p.nibp_diastolic = v);
alarm_editors.push((add_alarm_limits(&nibp_dia_row, "", "", 200,
params.borrow().alarms.nibp_dia, params.clone(), |p, v| p.alarms.nibp_dia = v,
@@ -277,12 +298,12 @@ ART and pleth are delayed. VT can be perfusing; PVT, VF and asystole are pulsele
p.capno_shape = if selected == 1 { CapnoShape::Obstructive }
else { CapnoShape::Normal };
});
- let etco2_row = add_numeric(&capno, "EtCO₂", "mmHg", 0, 100, params.borrow().etco2,
+ let (etco2_row, _, _) = add_numeric(&capno, "EtCO₂", "mmHg", 0, 100, params.borrow().etco2,
params.clone(), |p, v| p.etco2 = v);
alarm_editors.push((add_alarm_limits(&etco2_row, "", "", 100,
params.borrow().alarms.etco2, params.clone(), |p, v| p.alarms.etco2 = v,
&preset_dropdown, &updating_preset), |s| s.etco2));
- let rr_row = add_numeric(&capno, "Respiratory rate", "/min", 0, 60, params.borrow().respiratory_rate,
+ let (rr_row, _, _) = add_numeric(&capno, "Respiratory rate", "/min", 0, 60, params.borrow().respiratory_rate,
params.clone(), |p, v| p.respiratory_rate = v);
alarm_editors.push((add_alarm_limits(&rr_row, "", "", 60,
params.borrow().alarms.rr, params.clone(), |p, v| p.alarms.rr = v,
@@ -355,11 +376,11 @@ where F: Fn(&mut Parameters, bool) + 'static {
fn add_dropdown<F>(parent: &gtk::Box, label: &str, items: &[&str],
params: SharedParams, setter: F)
where F: Fn(&mut Parameters, u32) + 'static {
- add_dropdown_at(parent, label, items, 0, params, setter);
+ let _ = add_dropdown_at(parent, label, items, 0, params, setter);
}
fn add_dropdown_at<F>(parent: &gtk::Box, label: &str, items: &[&str],
- initial: u32, params: SharedParams, setter: F)
+ initial: u32, params: SharedParams, setter: F) -> gtk::DropDown
where F: Fn(&mut Parameters, u32) + 'static {
let row = gtk::Box::new(Orientation::Horizontal, 8);
let caption = gtk::Label::new(Some(label));
@@ -374,12 +395,13 @@ where F: Fn(&mut Parameters, u32) + 'static {
row.append(&caption);
row.append(&combo);
parent.append(&row);
+ combo
}
#[allow(clippy::too_many_arguments)]
fn add_numeric<F>(parent: &gtk::Box, label: &str, unit: &str,
min: i32, max: i32, initial: i32,
- params: SharedParams, setter: F) -> gtk::Box
+ params: SharedParams, setter: F) -> (gtk::Box, gtk::Scale, gtk::Entry)
where F: Fn(&mut Parameters, i32) + 'static {
let row = gtk::Box::new(Orientation::Horizontal, 8);
let caption = gtk::Label::new(Some(label));
@@ -434,7 +456,7 @@ where F: Fn(&mut Parameters, i32) + 'static {
row.append(&entry);
row.append(&suffix);
parent.append(&row);
- row
+ (row, slider, entry)
}
fn normalize_entry(entry: &gtk::Entry, slider: &gtk::Scale, min: i32, max: i32) {

View file

@ -0,0 +1,15 @@
diff --git a/src/model.rs b/src/model.rs
index 03d7bbe..4d0bc9b 100644
--- a/src/model.rs
+++ b/src/model.rs
@@ -231,8 +231,8 @@ impl Parameters {
}
}
- /// No saturation without an attached sensor, usable signal quality and
- /// two observed mechanical pulse events. Thresholds do not control this alarm.
+ /// Test-only convenience wrapper for saturation availability without dropout.
+ #[cfg(test)]
pub fn spo2_status(&self, pulse_rate: Option<i32>) -> Spo2Status {
self.spo2_status_during(pulse_rate, false)
}

View file

@ -0,0 +1,141 @@
diff --git a/Cargo.toml b/Cargo.toml
index e273c5e..b9aa888 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "patient-monitor-simulation"
-version = "0.4.3"
+version = "0.4.4"
edition = "2021"
license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"
diff --git a/README.md b/README.md
index cdc1f9b..21e1f99 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.4.3
+# Patient Monitor Simulation (PaMSim) — v0.4.4
A two-window, Rust/GTK4 patient-monitor simulator for teaching on Fedora Linux.
@@ -20,6 +20,12 @@ session (e.g., Fedora KDE/Wayland).
## Windows
+**Admin sections** have a narrow colored stripe on their left edge to match the
+monitor: ECG **green**, SpO₂ **yellow**, invasive arterial pressure **red**,
+capnography **light grey**, NIBP **light grey**. The Patient section remains
+neutral. These accents are drawn by GTK and remain visible independently of
+light/dark themes. This is a visual-only change; control behavior is unchanged.
+
**Admin:** Controls patient name; ECG rhythm and rate; mechanical capture;
SpO₂, signal quality and sensor connection; invasive arterial pressure,
waveform shape and pulse-pressure variation; NIBP; and capnography. Numeric inputs have bidirectionally linked sliders and text fields.
diff --git a/src/ui.rs b/src/ui.rs
index 55d31cb..7000833 100644
--- a/src/ui.rs
+++ b/src/ui.rs
@@ -14,6 +14,14 @@ use crate::simulation::Simulator;
type SharedParams = Rc<RefCell<Parameters>>;
+// Match the RGB colors of the monitor traces (see render.rs).
+// NIBP uses the same light grey as the NIBP footer and capnography.
+type AccentColor = (f64, f64, f64);
+const ECG_GREEN: AccentColor = (0.26, 1.0, 0.39);
+const SPO2_YELLOW: AccentColor = (1.0, 0.85, 0.17);
+const ART_RED: AccentColor = (1.0, 0.30, 0.31);
+const MONITOR_GREY: AccentColor = (0.80, 0.84, 0.87);
+
pub fn create_windows(app: &Application) {
let parameters = Rc::new(RefCell::new(Parameters::default()));
let simulator = Rc::new(RefCell::new(Simulator::new(&parameters.borrow())));
@@ -125,7 +133,7 @@ fn create_admin(app: &Application, params: SharedParams,
let updating_preset = Rc::new(Cell::new(false));
let mut alarm_editors: Vec<(AlarmEditor, fn(&AlarmSettings) -> AlarmLimits)> = Vec::new();
- let patient = group(&controls, "Patient");
+ let patient = group(&controls, "Patient", None);
let patient_row = gtk::Box::new(Orientation::Horizontal, 8);
let patient_label = gtk::Label::new(Some("Patient name"));
patient_label.set_xalign(0.0);
@@ -143,7 +151,7 @@ fn create_admin(app: &Application, params: SharedParams,
patient_row.append(&name_entry);
patient.append(&patient_row);
- let ecg = group(&controls, "ECG");
+ let ecg = group(&controls, "ECG", Some(ECG_GREEN));
add_visibility(&ecg, params.borrow().show_ecg, params.clone(), |p, show| p.show_ecg = show);
let rhythm_dropdown = add_dropdown_at(&ecg, "ECG rhythm", &[
"Sinus rhythm", "Atrial fibrillation", "Ventricular tachycardia (VT)",
@@ -173,7 +181,7 @@ fn create_admin(app: &Application, params: SharedParams,
params.borrow().alarms.hr, params.clone(), |p, v| p.alarms.hr = v,
&preset_dropdown, &updating_preset), |s| s.hr));
- let spo2 = group(&controls, "Pulse oximetry");
+ let spo2 = group(&controls, "Pulse oximetry", Some(SPO2_YELLOW));
add_visibility(&spo2, params.borrow().show_spo2, params.clone(), |p, show| p.show_spo2 = show);
let (spo2_row, _, _) = add_numeric(&spo2, "SpO₂", "%", 0, 100, params.borrow().spo2,
params.clone(), |p, v| p.spo2 = v);
@@ -238,7 +246,7 @@ ART and pleth are delayed. VT can be perfusing; PVT, VF and asystole are pulsele
conduction_hint.set_wrap(true);
spo2.append(&conduction_hint);
- let art = group(&controls, "Invasive arterial blood pressure");
+ let art = group(&controls, "Invasive arterial blood pressure", Some(ART_RED));
add_visibility(&art, params.borrow().show_art, params.clone(), |p, show| p.show_art = show);
let (art_sys_row, _, _) = add_numeric(&art, "Systolic", "mmHg", 0, 200, params.borrow().art_systolic,
params.clone(), |p, v| p.art_systolic = v);
@@ -275,7 +283,7 @@ ART and pleth are delayed. VT can be perfusing; PVT, VF and asystole are pulsele
};
});
- let nibp = group(&controls, "Non-invasive blood pressure (NIBP)");
+ let nibp = group(&controls, "Non-invasive blood pressure (NIBP)", Some(MONITOR_GREY));
add_visibility(&nibp, params.borrow().show_nibp, params.clone(), |p, show| p.show_nibp = show);
let (nibp_sys_row, _, _) = add_numeric(&nibp, "Systolic", "mmHg", 0, 260, params.borrow().nibp_systolic,
params.clone(), |p, v| p.nibp_systolic = v);
@@ -291,7 +299,7 @@ ART and pleth are delayed. VT can be perfusing; PVT, VF and asystole are pulsele
params.borrow().alarms.nibp_dia, params.clone(), |p, v| p.alarms.nibp_dia = v,
&preset_dropdown, &updating_preset), |s| s.nibp_dia));
- let capno = group(&controls, "Capnography");
+ let capno = group(&controls, "Capnography", Some(MONITOR_GREY));
add_visibility(&capno, params.borrow().show_capno, params.clone(), |p, show| p.show_capno = show);
add_dropdown(&capno, "Capnogram", &["Normal", "Obstructive / shark fin"],
params.clone(), |p, selected| {
@@ -352,14 +360,30 @@ ART and pleth are delayed. VT can be perfusing; PVT, VF and asystole are pulsele
window
}
-fn group(parent: &gtk::Box, title: &str) -> gtk::Box {
+/// Frame a parameter section with an optional monitor-colored left sidebar.
+/// A DrawingArea keeps the color independent of the user's GTK theme/CSS.
+fn group(parent: &gtk::Box, title: &str, accent: Option<AccentColor>) -> gtk::Box {
let frame = gtk::Frame::new(Some(title));
+ let body = gtk::Box::new(Orientation::Horizontal, 0);
+ if let Some((red, green, blue)) = accent {
+ let stripe = gtk::DrawingArea::new();
+ stripe.set_content_width(7);
+ stripe.set_vexpand(true);
+ stripe.set_draw_func(move |_area, cr, width, height| {
+ cr.set_source_rgb(red, green, blue);
+ cr.rectangle(0.0, 0.0, f64::from(width), f64::from(height));
+ let _ = cr.fill();
+ });
+ body.append(&stripe);
+ }
let content = gtk::Box::new(Orientation::Vertical, 8);
+ content.set_hexpand(true);
content.set_margin_top(10);
content.set_margin_bottom(10);
content.set_margin_start(10);
content.set_margin_end(10);
- frame.set_child(Some(&content));
+ body.append(&content);
+ frame.set_child(Some(&body));
parent.append(&frame);
content
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,203 @@
diff --git a/Cargo.toml b/Cargo.toml
index 6ee2389..2302d65 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "patient-monitor-simulation"
-version = "0.5.0"
+version = "0.5.1"
edition = "2021"
license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"
diff --git a/README.de.md b/README.de.md
index 3c43a45..bcd4209 100644
--- a/README.de.md
+++ b/README.de.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.5.0
+# Patient Monitor Simulation (PaMSim) — v0.5.1
Ein mit Rust und GTK4 entwickelter Patient*innenmonitor-Simulator mit zwei Fenstern für die Lehre unter Fedora Linux.
@@ -36,7 +36,11 @@ Lange Namen werden an die verfügbare Breite angepasst oder abgeschnitten.
Wird die Sichtbarkeit eines Parameters deaktiviert, verschwinden sowohl seine Kurve als auch die zugehörigen Messwerte.
Die verbleibenden Kurvenbereiche vergrößern sich entsprechend.
Das Ausblenden eines Monitorbereichs unterbricht **nicht** die Signalerzeugung oder physiologische Kopplung: Wird beispielsweise das EKG ausgeblendet, können arterielle und plethysmographische Pulse weiterhin auftreten.
-NIBP kann unabhängig ausgeblendet werden; dabei verschwindet auch das separate rote Wertefeld in der rechten Monitorspalte.
+Für NIBP wird in der linken Kurvenspalte eine **leere Zelle** freigehalten.
+Damit sind die Kurvenbereiche und die numerischen Wertefelder in der rechten Spalte
+in allen Zeilen exakt aufeinander ausgerichtet.
+NIBP kann unabhängig ausgeblendet werden; dabei verschwindet die gesamte NIBP-Zeile
+und die übrigen Zeilen nutzen den frei werdenden Platz.
Das Monitorfenster lässt sich in der Größe verändern.
Mit **F11** wird der Vollbildmodus aktiviert bzw. umgeschaltet, mit **Esc** wird er verlassen.
@@ -367,3 +371,11 @@ Beide Manschetten-Interferenzoptionen sind standardmäßig deaktiviert.
**Die NIBP-Simulation ist ausschließlich ein didaktisches Modell und keine
klinisch validierte oszillometrische Messung.**
+
+## v0.5.1 — Ausrichtung der Monitorspalten
+
+Die linke Kurvenspalte und die rechte numerische Spalte verwenden nun dieselbe
+Zeilenaufteilung. Neben dem NIBP-Wertefeld bleibt links eine leere Zelle, statt
+die anderen Wertefelder vertikal zusammenzudrängen. Beim Ausblenden einzelner
+Monitorbereiche werden beide Spalten gemeinsam neu aufgeteilt.
+Das Messverhalten und die Alarmfunktionen bleiben unverändert.
diff --git a/README.md b/README.md
index 66c1469..d1f48c0 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.5.0
+# Patient Monitor Simulation (PaMSim) — v0.5.1
A two-window, Rust/GTK4 patient-monitor simulator for teaching on Fedora Linux.
@@ -39,8 +39,10 @@ Long names are automatically resized or clipped to fit the header.
Waveforms and vital signs disappear together when their respective
visibility checkbox is cleared. Remaining waveform rows expand to use the space.
Hiding a display channel does **not** stop signal generation or physiological
-coupling: for example, hiding ECG does not stop ART or pleth pulses. NIBP can
-be hidden independently; this also removes its value box from the right column.
+coupling: for example, hiding ECG does not stop ART or pleth pulses. NIBP occupies a dedicated right-column row with an **empty waveform cell** on the
+left. All waveform rows and their corresponding numeric boxes share the same
+height and horizontal boundaries. NIBP can be hidden independently; its entire
+row is then removed and the remaining rows expand evenly.
The monitor can be resized and toggled fullscreen with **F11**; **Esc** exits
fullscreen. On Wayland, move the monitor to the presentation screen before
@@ -164,7 +166,9 @@ can be taught.
## NIBP measurement cycle (v0.5.0)
NIBP is **red**, with a dedicated value box in the **right-hand numeric column**.
-The previous static NIBP footer has been removed. In Admin, choose an interval
+An **empty left-hand waveform cell** occupies the same row, keeping every numeric
+value box horizontally aligned with its waveform region. The previous static
+NIBP footer has been removed. In Admin, choose an interval
of **1, 3, 5, 10, 20, 30, or 60 minutes** (default 5). The initial cuff cycle
begins when the simulation starts; subsequent intervals run **from the end of
the last measurement**, not from its beginning. **Measure now** starts an
@@ -292,8 +296,9 @@ The five **Show on monitor** checkboxes affect the presentation only:
| Capnography | CO₂ waveform, EtCO₂ and RR |
| NIBP | Timed cuff-measurement values and red right-column value box |
-Remaining visible waveforms keep their relative order and receive an equal
-share of the available area; zero waveform channels is supported.
+Remaining visible waveform rows and the NIBP-only row share an equal
+portion of the available height and remain aligned across both columns; zero
+waveform channels is supported.
## ECG morphology correction (v0.3.1)
@@ -399,3 +404,10 @@ environment; run `cargo test` and `cargo run --release` on Fedora.
Choosing another signal quality immediately clears the intermittent outage.
- No changes to Adult alarm presets, alarm limit ordering, or the 0–200 mmHg
arterial scale. All behavior is synthetic and intended for teaching only.
+
+## v0.5.1 — Aligned monitor columns
+
+The left waveform column and right numeric column now share the same row grid.
+NIBP reserves an empty cell in the left waveform column instead of shortening
+the other numeric rows. Hiding any channel reflows both columns together.
+No NIBP measurement logic or alarm behavior was changed.
diff --git a/src/render.rs b/src/render.rs
index def9706..b3dc04d 100644
--- a/src/render.rs
+++ b/src/render.rs
@@ -35,12 +35,9 @@ pub fn draw(cr: &Context, width: i32, height: i32, p: &Parameters, sim: &Simulat
let header = (h * 0.083).clamp(32.0, 68.0);
let channels = visible_channels(p);
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;
+ // A single grid governs both columns. NIBP has an empty waveform cell
+ // on the left, so all numeric boxes line up with their waveform rows.
+ let (row_height, nibp_top) = monitor_rows(header, body_height, channels.len(), p.show_nibp);
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;
@@ -67,26 +64,35 @@ pub fn draw(cr: &Context, width: i32, height: i32, p: &Parameters, sim: &Simulat
stroke_line(cr, split_x, header, split_x, h - pad, MUTED, 0.9);
for (index, (channel, title, color)) in channels.iter().copied().enumerate() {
- 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);
+ let top = header + index as f64 * row_height;
+ let bottom = top + row_height;
+ stroke_line(cr, pad, bottom, w - pad, bottom, MUTED, 0.65);
+ text(cr, title, trace_left + 4.0, top + row_height * 0.17,
+ (row_height * 0.11).clamp(10.0, 17.0), color, false);
draw_trace(cr, channel, color, trace_left, trace_right,
- 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);
+ top + row_height * 0.25, bottom - row_height * 0.06, p, sim);
draw_vitals(cr, channel, color, split_x + pad,
- vital_top, vital_row_height, sidebar - 2.0 * pad, p, sim);
+ top, row_height, sidebar - 2.0 * pad, p, sim);
}
- if p.show_nibp {
- draw_nibp_box(cr, split_x + pad, h - pad - nibp_box_height,
- sidebar - 2.0 * pad, nibp_box_height, p, sim);
+ if let Some(top) = nibp_top {
+ // Intentionally blank waveform cell to the left of the NIBP box.
+ stroke_line(cr, pad, top + row_height, w - pad, top + row_height, MUTED, 0.65);
+ draw_nibp_box(cr, split_x + pad, top,
+ sidebar - 2.0 * pad, row_height, p, sim);
}
}
+/// Compute the same row boundaries for the waveform and numeric columns.
+/// NIBP, when visible, occupies the final row and leaves its left cell empty.
+fn monitor_rows(header: f64, body_height: f64, trace_count: usize, show_nibp: bool)
+ -> (f64, Option<f64>) {
+ let row_count = trace_count + usize::from(show_nibp);
+ let row_height = body_height / row_count.max(1) as f64;
+ let nibp_top = show_nibp.then_some(header + trace_count as f64 * row_height);
+ (row_height, nibp_top)
+}
+
fn draw_nibp_box(cr: &Context, x: f64, top: f64, width: f64, height: f64,
p: &Parameters, sim: &Simulator) {
let right = x + width;
@@ -548,6 +554,29 @@ fn text(cr: &Context, value: &str, x: f64, baseline: f64,
mod tests {
use super::*;
+ #[test]
+ fn monitor_rows_align_waveforms_and_numbers_with_blank_nibp_left_cell() {
+ let header = 60.0;
+ let body_height = 700.0;
+ let (height, nibp_top) = monitor_rows(header, body_height, 4, true);
+ assert_eq!(height, 140.0);
+ assert_eq!(nibp_top, Some(620.0));
+ // Every waveform row and its corresponding numeric row share boundaries.
+ for index in 0..4 {
+ let top = header + index as f64 * height;
+ let bottom = top + height;
+ assert_eq!(bottom, header + (index + 1) as f64 * height);
+ }
+ assert_eq!(nibp_top.unwrap() + height, header + body_height);
+ }
+
+ #[test]
+ fn monitor_rows_reflow_when_nibp_or_waveforms_are_hidden() {
+ assert_eq!(monitor_rows(60.0, 700.0, 4, false), (175.0, None));
+ assert_eq!(monitor_rows(60.0, 700.0, 0, true), (700.0, Some(60.0)));
+ assert_eq!(monitor_rows(60.0, 700.0, 0, false), (700.0, None));
+ }
+
#[test]
fn alarm_states_do_not_trigger_for_unavailable_readouts() {
let p = Parameters::default();

View file

@ -0,0 +1,46 @@
diff -ruN a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml 2026-11-12 13:05:10.000000000 +0000
+++ b/Cargo.toml 2026-11-12 13:10:05.130839688 +0000
@@ -1,6 +1,6 @@
[package]
name = "patient-monitor-simulation"
-version = "0.5.1"
+version = "0.5.2"
edition = "2021"
license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"
diff -ruN a/README.de.md b/README.de.md
--- a/README.de.md 2026-11-12 13:05:10.000000000 +0000
+++ b/README.de.md 2026-11-12 13:10:05.131166243 +0000
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.5.1
+# Patient Monitor Simulation (PaMSim) — v0.5.2
Ein mit Rust und GTK4 entwickelter Patient*innenmonitor-Simulator mit zwei Fenstern für die Lehre unter Fedora Linux.
diff -ruN a/README.md b/README.md
--- a/README.md 2026-11-12 13:05:10.000000000 +0000
+++ b/README.md 2026-11-12 13:10:05.130976637 +0000
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.5.1
+# Patient Monitor Simulation (PaMSim) — v0.5.2
A two-window, Rust/GTK4 patient-monitor simulator for teaching on Fedora Linux.
diff -ruN a/src/render.rs b/src/render.rs
--- a/src/render.rs 2026-11-12 13:05:10.000000000 +0000
+++ b/src/render.rs 2026-11-12 13:10:05.128193199 +0000
@@ -102,13 +102,6 @@
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);

View file

@ -0,0 +1,623 @@
diff -ruN a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml 2026-11-12 13:10:05.130839688 +0000
+++ b/Cargo.toml 2026-11-12 13:27:14.340210857 +0000
@@ -1,6 +1,6 @@
[package]
name = "patient-monitor-simulation"
-version = "0.5.2"
+version = "0.5.3"
edition = "2021"
license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"
diff -ruN a/README.de.md b/README.de.md
--- a/README.de.md 2026-11-12 13:10:05.131166243 +0000
+++ b/README.de.md 2026-11-12 13:28:21.812109359 +0000
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.5.2
+# Patient Monitor Simulation (PaMSim) — v0.5.3
Ein mit Rust und GTK4 entwickelter Patient*innenmonitor-Simulator mit zwei Fenstern für die Lehre unter Fedora Linux.
@@ -9,7 +9,7 @@
## Installation, Kompilierung und Start unter Fedora
```bash
-sudo dnf install rust cargo gcc pkgconf-pkg-config gtk4-devel
+sudo dnf install rust cargo gcc pkgconf-pkg-config gtk4-devel pipewire-utils
cargo test
cargo run --release
```
@@ -47,6 +47,39 @@
Unter Wayland sollte das Fenster vor dem Wechsel in den Vollbildmodus auf den gewünschten Präsentationsbildschirm verschoben werden.
Der Vollbildmodus sperrt den Computer nicht gegen andere Eingaben.
+## Akustische Alarme (v0.5.3)
+
+Die akustische Alarmierung ist **standardmäßig eingeschaltet**. Im
+Admin-Fenster lässt sie sich mit **Audible alarms** aktivieren bzw. stummschalten.
+Mit **Test tone** kann die Tonausgabe unabhängig von der Stummschaltung geprüft
+werden. Die optischen Alarme blinken bei stummgeschalteter Tonausgabe weiterhin.
+
+- **Kritische Rhythmusalarme:** VT, PVT, Kammerflimmern und Asystolie lösen
+ einen Doppelton aus (zweimal kurz 880 Hz), der ungefähr alle 1,5 Sekunden
+ wiederholt wird.
+- **Numerische und technische Alarme:** Grenzwertüberschreitungen sowie
+ **NO SENSOR** und **NO READING** lösen einen kurzen Ton mit 700 Hz aus,
+ der ungefähr alle 2,5 Sekunden wiederholt wird.
+- Kritische Alarme haben Vorrang. Auch bei mehreren gleichzeitig aktiven
+ Alarmen wird nur eine Tonfolge ausgegeben. Bei behobenem Alarm oder
+ Stummschaltung verstummt die Ausgabe. Ausgeblendete Monitorbereiche
+ lösen keine akustischen Alarme aus.
+- Nicht verfügbare Messwerte, etwa NIBP vor der ersten abgeschlossenen Messung,
+ lösen keinen numerischen Grenzwertalarm aus. Eine laufende NIBP-Messung
+ selbst ist kein Alarm. Die Audioausgabe wird unabhängig von der Darstellung
+ der Kurven verarbeitet.
+
+Unter Fedora wird **`pw-play`** aus dem Paket `pipewire-utils` verwendet,
+alternativ **`paplay`**. Es sind weder zusätzliche Rust-Bibliotheken noch
+mitzuliefernde Audiodateien notwendig: Das Programm erzeugt seine WAV-Töne
+zur Laufzeit. Falls kein Wiedergabeprogramm verfügbar ist, erscheint im
+Admin-Fenster ein entsprechender Hinweis; der Monitor bleibt funktionstüchtig.
+Wiedergabegerät und Lautstärke werden über die Systemeinstellungen verwaltet.
+
+**Wichtig:** Diese didaktischen Tonsignale entsprechen nicht den Anforderungen
+an Medizinproduktealarme (insbesondere IEC 60601-1-8) und dürfen nicht zur
+klinischen Überwachung verwendet werden.
+
## Numerische Alarmgrenzen (seit v0.4.0; Anordnung und Voreinstellungen seit v0.4.1)
Für jeden angezeigten numerischen Messwert können im zugehörigen Admin-Bereich **unabhängige optionale untere (↓) und obere (↑) Alarmgrenzen** festgelegt werden.
@@ -379,3 +412,13 @@
die anderen Wertefelder vertikal zusammenzudrängen. Beim Ausblenden einzelner
Monitorbereiche werden beide Spalten gemeinsam neu aufgeteilt.
Das Messverhalten und die Alarmfunktionen bleiben unverändert.
+
+## v0.5.3 — Akustische Alarmierung
+
+- Alarmausgabe mit `pw-play` (PipeWire) bzw. `paplay` (Fallback), ohne neue
+ Rust-Bibliotheken.
+- Admin-Bedienelemente zum Stummschalten und für einen Testton.
+- Unterschiedliche Töne für kritische Rhythmusalarme und Standard- bzw.
+ technische Alarme; kritische Alarme haben Vorrang.
+- Die Audioausgabe ist von der Kurvendarstellung entkoppelt.
+- Bisherige optische Alarme und Simulationsfunktionen bleiben unverändert.
diff -ruN a/README.md b/README.md
--- a/README.md 2026-11-12 13:10:05.130976637 +0000
+++ b/README.md 2026-11-12 13:28:21.810121988 +0000
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.5.2
+# Patient Monitor Simulation (PaMSim) — v0.5.3
A two-window, Rust/GTK4 patient-monitor simulator for teaching on Fedora Linux.
@@ -9,7 +9,7 @@
## Build and run on Fedora
```bash
-sudo dnf install rust cargo gcc pkgconf-pkg-config gtk4-devel
+sudo dnf install rust cargo gcc pkgconf-pkg-config gtk4-devel pipewire-utils
cargo test
cargo run --release
```
@@ -48,6 +48,35 @@
fullscreen. On Wayland, move the monitor to the presentation screen before
activating fullscreen. Fullscreen does not lock down the computer.
+## Audible alarms (v0.5.3)
+
+Sound is **enabled by default**. The Admin window has an **Audible alarms**
+checkbox for muting and a **Test tone** button (works even while muted).
+Visual alarms keep blinking normally when sound is off.
+
+- **Critical rhythm alarm:** VT, PVT, VF and asystole produce a double beep
+ (two short 880 Hz tones), repeated approximately every 1.5 seconds.
+- **Numerical and SpO₂ technical alarms:** out-of-range values, **NO SENSOR**
+ and **NO READING** produce a single 700 Hz beep, repeated approximately
+ every 2.5 seconds.
+- Critical alarms have priority: only one tone pattern is played even if
+ multiple alarms are active. The sound stops when all alarms clear or when
+ the checkbox is unchecked. Alarms on hidden monitor channels are excluded.
+- Values not yet available (e.g. NIBP before a completed measurement) do not
+ trigger numerical limit alarms. The cuff measurement cycle by itself is not
+ an alarm. Audio playback is separate from waveform rendering and simulation.
+
+On Fedora, sound is played through **`pw-play`** from `pipewire-utils`, with
+**`paplay`** as a fallback. No additional Rust crates or sound files are needed:
+the application creates its own short WAV tones at runtime. If neither player
+is installed, Admin reports that audio is unavailable; the monitor continues
+to work normally. `Test tone` helps verify the desktop audio output. The
+application uses the system output device and mixer volume.
+
+**Important:** These simple teaching tones do not comply with medical-device
+alarm standards (including IEC 60601-1-8) and must never be relied on for
+clinical monitoring.
+
## Numerical alarm limits (v0.4.0; layout and presets updated in v0.4.1)
Each displayed numeric measurement has an **independent optional lower (↓) and
@@ -411,3 +440,12 @@
NIBP reserves an empty cell in the left waveform column instead of shortening
the other numeric rows. Hiding any channel reflows both columns together.
No NIBP measurement logic or alarm behavior was changed.
+
+## v0.5.3 — Audible alarm output
+
+- Alarm-tone playback through Fedora PipeWire (`pw-play`) or PulseAudio
+ compatibility (`paplay`), without any new Rust library dependencies.
+- Admin controls to mute/unmute alarms or play a test tone.
+- Distinct critical-rhythm and standard/technical patterns; critical priority.
+- Audio keeps running independently of the monitor's drawing callback.
+- Visual alarms and existing physiological simulation remain unchanged.
diff -ruN a/src/alarm.rs b/src/alarm.rs
--- a/src/alarm.rs 1970-01-01 00:00:00.000000000 +0000
+++ b/src/alarm.rs 2026-11-12 13:27:13.323621333 +0000
@@ -0,0 +1,364 @@
+//! Audible teaching alarms. This is not a clinical alarm system.
+//!
+//! The decision uses the same available readings, visibility settings and limits
+//! as the monitor. Sound is played using Fedora's PipeWire command-line player
+//! (or paplay) without adding a native audio-library dependency to Cargo.
+
+use std::env;
+use std::fs::{self, OpenOptions};
+use std::io::{self, Write};
+use std::path::{Path, PathBuf};
+use std::process::{Child, Command, Stdio};
+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
+
+use crate::model::{AlarmLimits, AlarmState, Parameters, PulseConduction, Spo2Status};
+use crate::simulation::Simulator;
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
+pub enum AlarmLevel {
+ #[default]
+ None,
+ Standard,
+ Critical,
+}
+
+fn outside(limits: AlarmLimits, value: Option<i32>) -> bool {
+ limits.evaluate(value) != AlarmState::Normal
+}
+
+/// Only parameters actually shown on the monitor contribute audible alarms.
+/// Missing numeric values do not trigger threshold alarms, but missing SpO2
+/// readings and disconnected sensors are explicit technical alarms.
+pub fn level(p: &Parameters, sim: &Simulator) -> AlarmLevel {
+ let mut result = AlarmLevel::None;
+ let hr = (p.ecg_rhythm.has_qrs() && p.heart_rate > 0).then_some(p.heart_rate);
+ let captured = p.ecg_rhythm.can_generate_pulse()
+ && p.heart_rate > 0
+ && p.pulse_conduction != PulseConduction::None;
+ let pr = if captured { sim.pulse_rate() } else { None };
+
+ if p.show_ecg {
+ if p.ecg_rhythm.rhythm_alarm().is_some() {
+ return AlarmLevel::Critical;
+ }
+ if outside(p.alarms.hr, hr) {
+ result = AlarmLevel::Standard;
+ }
+ }
+
+ if p.show_spo2 {
+ let status = p.spo2_status_at_quality(pr, sim.poor_signal_lost(), sim.spo2_quality(p));
+ if status != Spo2Status::Available
+ || outside(p.alarms.spo2, Some(p.spo2))
+ || outside(p.alarms.pr, pr)
+ {
+ result = AlarmLevel::Standard;
+ }
+ }
+
+ if p.show_art {
+ let (sys, dia, map) = sim.displayed_art_pressures(p, captured);
+ if outside(p.alarms.art_sys, sys)
+ || outside(p.alarms.art_dia, dia)
+ || outside(p.alarms.art_map, map)
+ || outside(p.alarms.ppv, Some(p.pulse_pressure_variation))
+ {
+ result = AlarmLevel::Standard;
+ }
+ }
+
+ if p.show_capno && (outside(p.alarms.etco2, Some(p.etco2))
+ || outside(p.alarms.rr, Some(p.respiratory_rate)))
+ {
+ result = AlarmLevel::Standard;
+ }
+
+ if p.show_nibp {
+ let reading = sim.nibp().reading();
+ if outside(p.alarms.nibp_sys, reading.map(|r| r.systolic))
+ || outside(p.alarms.nibp_dia, reading.map(|r| r.diastolic))
+ || outside(p.alarms.nibp_map, reading.map(|r| r.mean()))
+ {
+ result = AlarmLevel::Standard;
+ }
+ }
+ result
+}
+
+/// Very short, original synthesized sine beeps; mono PCM16 WAV.
+fn wav(critical: bool) -> Vec<u8> {
+ const SAMPLE_RATE: u32 = 44_100;
+ let segments: &[(f64, f64)] = if critical {
+ &[(880.0, 0.16), (0.0, 0.09), (880.0, 0.16)]
+ } else {
+ &[(700.0, 0.18)]
+ };
+ let samples: usize = segments.iter()
+ .map(|(_, seconds)| (seconds * f64::from(SAMPLE_RATE)).round() as usize)
+ .sum();
+ let size = (samples * 2) as u32;
+ let mut bytes = Vec::with_capacity(44 + size as usize);
+ bytes.extend_from_slice(b"RIFF");
+ bytes.extend_from_slice(&(size + 36).to_le_bytes());
+ bytes.extend_from_slice(b"WAVEfmt ");
+ bytes.extend_from_slice(&16_u32.to_le_bytes()); // PCM format chunk
+ bytes.extend_from_slice(&1_u16.to_le_bytes()); // PCM
+ bytes.extend_from_slice(&1_u16.to_le_bytes()); // mono
+ bytes.extend_from_slice(&SAMPLE_RATE.to_le_bytes());
+ bytes.extend_from_slice(&(SAMPLE_RATE * 2).to_le_bytes()); // byte rate
+ bytes.extend_from_slice(&2_u16.to_le_bytes()); // block align
+ bytes.extend_from_slice(&16_u16.to_le_bytes()); // bits per sample
+ bytes.extend_from_slice(b"data");
+ bytes.extend_from_slice(&size.to_le_bytes());
+
+ for &(frequency, seconds) in segments {
+ let count = (seconds * f64::from(SAMPLE_RATE)).round() as usize;
+ for i in 0..count {
+ let t = i as f64 / f64::from(SAMPLE_RATE);
+ let remaining = (count - i) as f64 / f64::from(SAMPLE_RATE);
+ let envelope = (t / 0.012).min(1.0).min(remaining / 0.012).max(0.0);
+ let value = if frequency > 0.0 {
+ (2.0 * std::f64::consts::PI * frequency * t).sin() * envelope * 0.17
+ } else { 0.0 };
+ let sample = (value * f64::from(i16::MAX)).round() as i16;
+ bytes.extend_from_slice(&sample.to_le_bytes());
+ }
+ }
+ bytes
+}
+
+struct SoundFiles {
+ standard: PathBuf,
+ critical: PathBuf,
+}
+
+impl Drop for SoundFiles {
+ fn drop(&mut self) {
+ let _ = fs::remove_file(&self.standard);
+ let _ = fs::remove_file(&self.critical);
+ }
+}
+
+fn write_new(path: &Path, content: &[u8]) -> io::Result<()> {
+ let mut out = OpenOptions::new().write(true).create_new(true).open(path)?;
+ out.write_all(content)
+}
+
+impl SoundFiles {
+ fn create_in(directory: &Path) -> io::Result<Self> {
+ let nonce = SystemTime::now().duration_since(UNIX_EPOCH)
+ .unwrap_or_default().as_nanos();
+ let prefix = format!("pamsim-{}-{nonce}", std::process::id());
+ let standard = directory.join(format!("{prefix}-alarm.wav"));
+ let critical = directory.join(format!("{prefix}-critical.wav"));
+ write_new(&standard, &wav(false))?;
+ if let Err(err) = write_new(&critical, &wav(true)) {
+ let _ = fs::remove_file(&standard);
+ return Err(err);
+ }
+ Ok(Self { standard, critical })
+ }
+
+ fn create() -> io::Result<Self> {
+ if let Some(runtime) = env::var_os("XDG_RUNTIME_DIR") {
+ if let Ok(files) = Self::create_in(Path::new(&runtime)) {
+ return Ok(files);
+ }
+ }
+ Self::create_in(&env::temp_dir())
+ }
+}
+
+fn command_on_path(name: &str) -> bool {
+ env::var_os("PATH").is_some_and(|paths| {
+ env::split_paths(&paths).any(|dir| {
+ let candidate = dir.join(name);
+ if !candidate.is_file() { return false; }
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ fs::metadata(&candidate).is_ok_and(|meta| meta.permissions().mode() & 0o111 != 0)
+ }
+ #[cfg(not(unix))]
+ { true }
+ })
+ })
+}
+
+/// Sound playback runs outside the GTK drawing callback. At most one short
+/// player process exists at a time; stopping or muting kills an active tone.
+pub struct AlarmAudio {
+ player: Option<&'static str>,
+ files: Option<SoundFiles>,
+ child: Option<Child>,
+ previous: AlarmLevel,
+ next_at: Instant,
+ error_reported: bool,
+}
+
+impl AlarmAudio {
+ pub fn new() -> Self {
+ let player = ["pw-play", "paplay"].into_iter().find(|name| command_on_path(name));
+ let files = if player.is_some() {
+ match SoundFiles::create() {
+ Ok(files) => Some(files),
+ Err(error) => {
+ eprintln!("PaMSim: cannot prepare alarm tones: {error}");
+ None
+ }
+ }
+ } else { None };
+ if player.is_none() {
+ eprintln!("PaMSim: alarm audio unavailable; install pipewire-utils (pw-play) on Fedora.");
+ }
+ Self {
+ player, files, child: None, previous: AlarmLevel::None,
+ next_at: Instant::now(), error_reported: false,
+ }
+ }
+
+ pub fn available(&self) -> bool {
+ self.player.is_some() && self.files.is_some()
+ }
+
+ fn stop_child(&mut self) {
+ if let Some(mut child) = self.child.take() {
+ let _ = child.kill();
+ let _ = child.wait();
+ }
+ }
+
+ fn reap(&mut self) {
+ if let Some(child) = self.child.as_mut() {
+ match child.try_wait() {
+ Ok(Some(status)) => {
+ self.child = None;
+ if !status.success() && !self.error_reported {
+ eprintln!("PaMSim: alarm sound player exited with {status}; check PipeWire and the output device.");
+ self.error_reported = true;
+ }
+ }
+ Err(error) => {
+ self.child = None;
+ if !self.error_reported {
+ eprintln!("PaMSim: could not check alarm playback: {error}");
+ self.error_reported = true;
+ }
+ }
+ Ok(None) => {}
+ }
+ }
+ }
+
+ fn play(&mut self, level: AlarmLevel) {
+ self.reap();
+ if self.child.is_some() { return; }
+ let (Some(player), Some(files)) = (self.player, self.files.as_ref()) else { return; };
+ let filename = if level == AlarmLevel::Critical { &files.critical } else { &files.standard };
+ match Command::new(player).arg(filename)
+ .stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).spawn()
+ {
+ Ok(child) => self.child = Some(child),
+ Err(error) if !self.error_reported => {
+ eprintln!("PaMSim: alarm sound playback failed: {error}");
+ self.error_reported = true;
+ }
+ Err(_) => {}
+ }
+ }
+
+ /// Called from a 100-ms GLib timer, not the 250-Hz waveform simulator.
+ /// Critical rhythms: double tone every 1.5 s; other alarms: single tone
+ /// every 2.5 s. Stop promptly when muted or all alarm states clear.
+ pub fn update(&mut self, level: AlarmLevel, enabled: bool) {
+ self.reap();
+ if !enabled || level == AlarmLevel::None {
+ self.stop_child();
+ self.previous = AlarmLevel::None;
+ return;
+ }
+ let now = Instant::now();
+ if level != self.previous {
+ self.stop_child();
+ self.previous = level;
+ self.next_at = now;
+ }
+ if now >= self.next_at {
+ self.play(level);
+ self.next_at = now + if level == AlarmLevel::Critical {
+ Duration::from_millis(1500)
+ } else { Duration::from_millis(2500) };
+ }
+ }
+
+ /// Manual test is independent of the audible-alarm enable checkbox.
+ pub fn test(&mut self) {
+ self.stop_child();
+ self.play(AlarmLevel::Standard);
+ self.next_at = Instant::now() + Duration::from_millis(2500);
+ }
+}
+
+impl Drop for AlarmAudio {
+ fn drop(&mut self) {
+ self.stop_child();
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::model::{AlarmSettings, EcgRhythm};
+
+ #[test]
+ fn valid_wav_files_and_distinct_tone_patterns() {
+ for critical in [false, true] {
+ let bytes = wav(critical);
+ assert_eq!(&bytes[..4], b"RIFF");
+ assert_eq!(&bytes[8..12], b"WAVE");
+ assert_eq!(&bytes[36..40], b"data");
+ assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()) as usize + 8, bytes.len());
+ assert_eq!(u32::from_le_bytes(bytes[40..44].try_into().unwrap()) as usize + 44, bytes.len());
+ }
+ assert!(wav(true).len() > wav(false).len());
+ }
+
+ #[test]
+ fn normal_signals_are_silent_and_numeric_limit_alarms_beep() {
+ let mut p = Parameters::default();
+ let sim = Simulator::new(&p);
+ assert_eq!(level(&p, &sim), AlarmLevel::None);
+ p.alarms = AlarmSettings::adult();
+ assert_eq!(level(&p, &sim), AlarmLevel::None);
+ p.heart_rate = 110;
+ assert_eq!(level(&p, &sim), AlarmLevel::Standard);
+ p.show_ecg = false;
+ assert_eq!(level(&p, &sim), AlarmLevel::None);
+ }
+
+ #[test]
+ fn rhythms_are_critical_and_sensor_issues_are_standard() {
+ let mut p = Parameters::default();
+ p.spo2_sensor_attached = false;
+ let sim = Simulator::new(&p);
+ assert_eq!(level(&p, &sim), AlarmLevel::Standard);
+ p.spo2_sensor_attached = true;
+ p.ecg_rhythm = EcgRhythm::VentricularFibrillation;
+ assert_eq!(level(&p, &sim), AlarmLevel::Critical);
+ p.ecg_rhythm = EcgRhythm::Asystole;
+ assert_eq!(level(&p, &sim), AlarmLevel::Critical);
+ p.show_ecg = false;
+ assert_eq!(level(&p, &sim), AlarmLevel::Standard); // no SpO2 reading
+ p.show_spo2 = false;
+ assert_eq!(level(&p, &sim), AlarmLevel::None);
+ }
+
+ #[test]
+ fn no_nibp_measurement_does_not_trigger_numeric_alarm() {
+ let mut p = Parameters::default();
+ p.alarms.nibp_sys.lower = Some(120);
+ let sim = Simulator::new(&p);
+ assert!(sim.nibp().reading().is_none());
+ assert_eq!(level(&p, &sim), AlarmLevel::None);
+ }
+}
diff -ruN a/src/main.rs b/src/main.rs
--- a/src/main.rs 2026-11-12 12:48:16.000000000 +0000
+++ b/src/main.rs 2026-11-12 13:27:14.335943186 +0000
@@ -1,3 +1,4 @@
+mod alarm;
mod model;
mod nibp;
mod render;
diff -ruN a/src/model.rs b/src/model.rs
--- a/src/model.rs 2026-11-12 12:58:26.000000000 +0000
+++ b/src/model.rs 2026-11-12 13:27:14.337421392 +0000
@@ -201,6 +201,7 @@
pub struct Parameters {
pub patient_name: String, // displayed in the monitor header, blank = generic title
pub alarms: AlarmSettings,
+ pub audible_alarms: bool, // mute only the sound, never the visual alarms
pub ecg_rhythm: EcgRhythm,
pub heart_rate: i32, // bpm, organized electrical rate; not mechanical pulse rate
pub pulse_conduction: PulseConduction,
@@ -275,6 +276,7 @@
Self {
patient_name: String::new(),
alarms: AlarmSettings::default(),
+ audible_alarms: true,
ecg_rhythm: EcgRhythm::Sinus,
heart_rate: 75,
pulse_conduction: PulseConduction::OneToOne,
diff -ruN a/src/ui.rs b/src/ui.rs
--- a/src/ui.rs 2026-11-12 12:59:46.000000000 +0000
+++ b/src/ui.rs 2026-11-12 13:27:14.339539904 +0000
@@ -1,13 +1,14 @@
//! GTK4 Admin and Monitor windows; all callbacks run on the GTK main thread.
use std::cell::{Cell, RefCell};
use std::rc::Rc;
-use std::time::Instant;
+use std::time::{Duration, Instant};
use gtk::gdk;
use gtk::glib;
use gtk::prelude::*;
use gtk::{Application, ApplicationWindow, Orientation};
+use crate::alarm::{self, AlarmAudio};
use crate::model::{AlarmLimits, AlarmSettings, ArterialShape, CapnoShape, EcgRhythm, Parameters, PulseConduction, Spo2Quality};
use crate::render;
use crate::simulation::Simulator;
@@ -25,8 +26,18 @@
pub fn create_windows(app: &Application) {
let parameters = Rc::new(RefCell::new(Parameters::default()));
let simulator = Rc::new(RefCell::new(Simulator::new(&parameters.borrow())));
+ let audio = Rc::new(RefCell::new(AlarmAudio::new()));
let monitor = create_monitor(app, parameters.clone(), simulator.clone());
- let admin = create_admin(app, parameters, simulator, &monitor);
+ let admin = create_admin(app, parameters.clone(), simulator.clone(), &monitor, audio.clone());
+
+ // Alarm evaluation has its own 100-ms timer; waveform drawing never blocks
+ // on sound playback. Audio also continues if the monitor is not mapped.
+ glib::timeout_add_local(Duration::from_millis(100), move || {
+ let config = parameters.borrow();
+ let current = alarm::level(&config, &simulator.borrow());
+ audio.borrow_mut().update(current, config.audible_alarms);
+ glib::ControlFlow::Continue
+ });
// Present monitor first, then leave controls in the foreground.
monitor.present();
@@ -90,7 +101,8 @@
fn create_admin(app: &Application, params: SharedParams,
simulator: Rc<RefCell<Simulator>>,
- monitor: &ApplicationWindow) -> ApplicationWindow {
+ monitor: &ApplicationWindow,
+ audio: Rc<RefCell<AlarmAudio>>) -> ApplicationWindow {
let window = ApplicationWindow::builder()
.application(app)
.title(concat!("Patient Monitor — Admin v", env!("CARGO_PKG_VERSION")))
@@ -131,6 +143,28 @@
preset_row.append(&preset_caption);
preset_row.append(&preset_dropdown);
controls.append(&preset_row);
+
+ // Sound control is independent of visual alarm limits and of the rhythm.
+ let sound_row = gtk::Box::new(Orientation::Horizontal, 12);
+ let audible = gtk::CheckButton::with_label("Audible alarms");
+ audible.set_active(params.borrow().audible_alarms);
+ audible.connect_toggled({
+ let params = params.clone();
+ move |button| params.borrow_mut().audible_alarms = button.is_active()
+ });
+ sound_row.append(&audible);
+ let test_sound = gtk::Button::with_label("Test tone");
+ test_sound.connect_clicked({
+ let audio = audio.clone();
+ move |_| audio.borrow_mut().test()
+ });
+ sound_row.append(&test_sound);
+ if !audio.borrow().available() {
+ let missing = gtk::Label::new(Some("Audio unavailable — install pipewire-utils"));
+ missing.set_xalign(0.0);
+ sound_row.append(&missing);
+ }
+ controls.append(&sound_row);
let updating_preset = Rc::new(Cell::new(false));
let mut alarm_editors: Vec<(AlarmEditor, fn(&AlarmSettings) -> AlarmLimits)> = Vec::new();

View file

@ -0,0 +1,764 @@
diff --git a/Cargo.toml b/Cargo.toml
index debf638..d2a7098 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "patient-monitor-simulation"
-version = "0.5.3"
+version = "0.5.4"
edition = "2021"
license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"
diff --git a/README.de.md b/README.de.md
index 374281f..f7c5ba2 100644
--- a/README.de.md
+++ b/README.de.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.5.3
+# Patient Monitor Simulation (PaMSim) — v0.5.4
Ein mit Rust und GTK4 entwickelter Patient*innenmonitor-Simulator mit zwei Fenstern für die Lehre unter Fedora Linux.
@@ -6,6 +6,53 @@ Ein mit Rust und GTK4 entwickelter Patient*innenmonitor-Simulator mit zwei Fenst
> EKG, invasive arterielle Druckkurve, Plethysmogramm und Kapnogramm sind schematische mathematische Annäherungen.
> Die Simulation wurde nicht klinisch validiert und ist kein Medizinprodukt.
+## Thoraxkompressionen (v0.5.4)
+
+Im Admin-Bereich **Chest compressions** startet die grüne Schaltfläche
+**Start Chest Compressions** die Simulation. Während aktiver Kompressionen
+wechselt sie zu **Stop Chest Compressions** mit rotem Hintergrund.
+Die **Compression quality** kann jederzeit auf **Good**, **Adequate**
+(Standard), **Poor** oder **Bad** gestellt werden.
+
+- Die Kompressionsfrequenz schwankt zufällig im Bereich **90–110/min**;
+ für jeden Druckstoß werden Frequenz und Druckhöhe neu festgelegt.
+ Der eingestellte EKG-Rhythmus und die elektrische Herzfrequenz bleiben
+ unverändert.
+- Das EKG wird durch kompressionssynchrone Bewegungsartefakte überlagert.
+ Besteht ein **eigener arterieller Kreislauf**, bleibt die ursprüngliche
+ Druckkurve bestehen, wird jedoch durch Kompressionen verzerrt.
+- **Ohne eigenständige arterielle Pulsation** (beispielsweise bei KF, PVT,
+ Asystolie oder PEA) erzeugen wirksame Kompressionen breite, stumpfe
+ arterielle Druckwellen:
+
+ | Kompressionsqualität | Systolischer ART-Spitzendruck |
+ | --- | --- |
+ | Good | 90 mmHg ±10 % (81–99 mmHg) |
+ | Adequate (Standard) | 70 mmHg ±10 % (63–77 mmHg) |
+ | Poor | 50 mmHg, +10 % / −50 % (25–55 mmHg) |
+ | Bad | Kein durch Kompressionen erzeugter Druck; Grundschwankung von 0–5 mmHg |
+
+ Bei fehlender Eigenpulsation zeigt **ART SYS** den Spitzendruck der
+ aktuellen Kompression; **DIA/MAP** bleiben `--`, da sie aus der synthetischen
+ Kurve nicht verlässlich bestimmt werden.
+- Ein SpO₂-Messwert und ein Plethysmogramm werden während laufender
+ Kompressionen **nur bei Qualität Good** angezeigt, vorausgesetzt, der Sensor
+ ist angeschlossen und nicht durch eine NIBP-Manschette okkludiert.
+ Die angezeigte Signalqualität beträgt unabhängig von der Grundeinstellung
+ **Poor (★)**. Die angezeigte **PR folgt der Kompressionsfrequenz (90–110/min)**,
+ nicht der EKG-Frequenz. Bei Adequate, Poor oder Bad erscheint **NO READING**,
+ bei abgezogenem Sensor **NO SENSOR**. Die durch Kompressionen erzwungene
+ Signalqualität Poor führt nicht zu den sonst üblichen periodischen
+ Aussetzern; bei regulärer Grundeinstellung Poor gelten diese nach Ende
+ der Kompressionen wieder.
+- Die bestehenden Rhythmus- und Grenzwertalarme bleiben aktiv. ART-SYS-Grenzen
+ beziehen sich dabei auf die Kompressionsspitzen. Die NIBP-Messintervalle bleiben unverändert; die Dauer eines Messzyklus
+ richtet sich weiterhin nach der wirksamen SpO₂-Signalqualität beim Start.
+
+**Hinweis:** Druckwerte und Signalformen sind didaktisch gewählt und nicht
+klinisch validiert. Aus dieser Simulation darf keine reale Wirksamkeit von
+Reanimationsmaßnahmen abgeleitet werden.
+
## Installation, Kompilierung und Start unter Fedora
```bash
diff --git a/README.md b/README.md
index 20d5943..30ec481 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.5.3
+# Patient Monitor Simulation (PaMSim) — v0.5.4
A two-window, Rust/GTK4 patient-monitor simulator for teaching on Fedora Linux.
@@ -6,6 +6,47 @@ A two-window, Rust/GTK4 patient-monitor simulator for teaching on Fedora Linux.
> plethysmography and capnography are schematic mathematical approximations. The
> simulation has no clinical validation and is not a medical device.
+## Chest compressions (v0.5.4)
+
+The **Chest compressions** Admin group provides a large **Start Chest Compressions**
+button (green background). While active it changes to **Stop Chest Compressions**
+(red background). **Compression quality** can be changed at any time:
+**Good**, **Adequate** (default), **Poor**, or **Bad**.
+
+- Compressions are generated independently of the ECG at **90–110/min**, with
+ a new reproducible pseudo-random compression rate and pressure each stroke.
+ **The ECG rhythm and electrical HR setting are not changed.**
+- Every compression adds movement artifact to the ECG. In a patient with
+ **existing intrinsic arterial perfusion**, the native arterial waveform is
+ preserved but distorted by compression-synchronous pressure artifact.
+- With **no intrinsic arterial pulse** (e.g., VF, PVT, asystole or PEA),
+ each effective compression generates a broad, blunt arterial pressure wave:
+
+ | Compression quality | Compression-generated ART systolic peak |
+ | --- | --- |
+ | Good | 90 mmHg ±10% (81–99 mmHg) |
+ | Adequate (default) | 70 mmHg ±10% (63–77 mmHg) |
+ | Poor | 50 mmHg, +10% / −50% (25–55 mmHg) |
+ | Bad | No compression-generated arterial pressure; 0–5 mmHg baseline drift |
+
+ During pulseless CPR, **ART SYS** shows the current compression peak,
+ while **DIA/MAP** remain `--` (not estimable from this synthetic pressure).
+- SpO₂ numeric saturation and the pleth waveform remain visible **only when
+ compression quality is Good**, provided the sensor is connected and not
+ occluded by an NIBP cuff. Their effective signal quality is forced to
+ **Poor (★)**, irrespective of the normal Admin quality setting. The displayed
+ pleth-derived **PR follows the compression rate (90–110/min)**, not the ECG.
+ Adequate, Poor and Bad CPR display **NO READING**; detached sensors display
+ **NO SENSOR**. Compression-induced Poor quality does not schedule the usual
+ intermittent dropout; that resumes when ordinary Poor signal mode returns.
+- Existing numerical alarms and rhythm alarms remain active. ART SYS limits
+ apply to compression-generated systolic peaks; NIBP scheduling remains unchanged; its cycle duration still depends on
+ effective SpO₂ quality at the start of a measurement.
+
+These pressure targets are **didactic assumptions**, not validated CPR
+hemodynamic criteria. The exercise must not be used to judge real compression
+quality or clinical perfusion.
+
## Build and run on Fedora
```bash
diff --git a/src/alarm.rs b/src/alarm.rs
index d368f20..116b7f4 100644
--- a/src/alarm.rs
+++ b/src/alarm.rs
@@ -35,7 +35,6 @@ pub fn level(p: &Parameters, sim: &Simulator) -> AlarmLevel {
let captured = p.ecg_rhythm.can_generate_pulse()
&& p.heart_rate > 0
&& p.pulse_conduction != PulseConduction::None;
- let pr = if captured { sim.pulse_rate() } else { None };
if p.show_ecg {
if p.ecg_rhythm.rhythm_alarm().is_some() {
@@ -47,10 +46,10 @@ pub fn level(p: &Parameters, sim: &Simulator) -> AlarmLevel {
}
if p.show_spo2 {
- let status = p.spo2_status_at_quality(pr, sim.poor_signal_lost(), sim.spo2_quality(p));
+ let status = sim.spo2_status(p);
if status != Spo2Status::Available
|| outside(p.alarms.spo2, Some(p.spo2))
- || outside(p.alarms.pr, pr)
+ || outside(p.alarms.pr, sim.spo2_pulse_rate(p))
{
result = AlarmLevel::Standard;
}
diff --git a/src/model.rs b/src/model.rs
index 996d6ba..009b231 100644
--- a/src/model.rs
+++ b/src/model.rs
@@ -83,6 +83,29 @@ pub enum CapnoShape {
Obstructive,
}
+/// Instructor-selected efficacy of manual chest compressions.
+/// This affects synthetic pressure and pleth signals, not ECG rhythm or HR.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum ChestCompressionQuality {
+ Good,
+ Adequate,
+ Poor,
+ Bad,
+}
+
+impl ChestCompressionQuality {
+ /// Approximate compression-generated systolic peak pressure (mmHg).
+ /// None means that compressions generate no measurable arterial pressure.
+ pub fn peak_range(self) -> Option<(f64, f64)> {
+ match self {
+ Self::Good => Some((81.0, 99.0)), // 90 +/- 10%
+ Self::Adequate => Some((63.0, 77.0)), // 70 +/- 10%
+ Self::Poor => Some((25.0, 55.0)), // 50 -50% / +10%
+ Self::Bad => None,
+ }
+ }
+}
+
/// Instructor-selected plethysmography signal quality; separate from the
/// physiological oxygen-saturation setting and mechanical pulse capture.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -202,6 +225,8 @@ pub struct Parameters {
pub patient_name: String, // displayed in the monitor header, blank = generic title
pub alarms: AlarmSettings,
pub audible_alarms: bool, // mute only the sound, never the visual alarms
+ pub chest_compressions_active: bool,
+ pub chest_compression_quality: ChestCompressionQuality,
pub ecg_rhythm: EcgRhythm,
pub heart_rate: i32, // bpm, organized electrical rate; not mechanical pulse rate
pub pulse_conduction: PulseConduction,
@@ -277,6 +302,8 @@ impl Default for Parameters {
patient_name: String::new(),
alarms: AlarmSettings::default(),
audible_alarms: true,
+ chest_compressions_active: false,
+ chest_compression_quality: ChestCompressionQuality::Adequate,
ecg_rhythm: EcgRhythm::Sinus,
heart_rate: 75,
pulse_conduction: PulseConduction::OneToOne,
@@ -313,6 +340,17 @@ pub fn mean_arterial_pressure(systolic: i32, diastolic: i32) -> i32 {
mod tests {
use super::*;
+ #[test]
+ fn compression_quality_defaults_to_adequate_and_has_requested_pressure_ranges() {
+ let p = Parameters::default();
+ assert!(!p.chest_compressions_active);
+ assert_eq!(p.chest_compression_quality, ChestCompressionQuality::Adequate);
+ assert_eq!(ChestCompressionQuality::Good.peak_range(), Some((81.0, 99.0)));
+ assert_eq!(ChestCompressionQuality::Adequate.peak_range(), Some((63.0, 77.0)));
+ assert_eq!(ChestCompressionQuality::Poor.peak_range(), Some((25.0, 55.0)));
+ assert_eq!(ChestCompressionQuality::Bad.peak_range(), None);
+ }
+
#[test]
fn mean_pressure_uses_one_third_pulse_pressure() {
assert_eq!(mean_arterial_pressure(120, 75), 90);
diff --git a/src/render.rs b/src/render.rs
index 8cce43d..4053fe1 100644
--- a/src/render.rs
+++ b/src/render.rs
@@ -150,6 +150,7 @@ fn draw_nibp_box(cr: &Context, x: f64, top: f64, width: f64, height: f64,
], right, top, height * 0.65, width * 0.72);
}
+#[cfg(test)]
fn pleth_trace_enabled(p: &Parameters) -> bool {
p.spo2_sensor_attached && p.spo2_quality != Spo2Quality::None
}
@@ -160,9 +161,16 @@ fn spo2_vitals(p: &Parameters, pulse_rate: Option<i32>, signal_lost: bool)
spo2_vitals_at_quality(p, pulse_rate, signal_lost, p.spo2_quality)
}
+#[cfg(test)]
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) {
+ spo2_vitals_for_status(p, pulse_rate, quality,
+ p.spo2_status_at_quality(pulse_rate, signal_lost, quality))
+}
+
+fn spo2_vitals_for_status(p: &Parameters, pulse_rate: Option<i32>, quality: Spo2Quality,
+ status: Spo2Status) -> (String, String, String) {
+ match status {
Spo2Status::NoSensor => (
"SpO₂".to_owned(), "NO SENSOR".to_owned(), "PR -- bpm".to_owned()),
Spo2Status::NoReading => (
@@ -196,10 +204,11 @@ fn draw_vitals(cr: &Context, ch: Channel, color: Color, x: f64,
&& p.heart_rate > 0
&& p.pulse_conduction != PulseConduction::None;
let pulse_rate = if has_capture { sim.pulse_rate() } else { None };
+ let spo2_rate = sim.spo2_pulse_rate(p);
let ecg_hr = if p.ecg_rhythm.has_qrs() && p.heart_rate > 0 {
Some(p.heart_rate)
} else { None };
- let spo2_status = p.spo2_status_at_quality(pulse_rate, sim.poor_signal_lost(), sim.spo2_quality(p));
+ let spo2_status = sim.spo2_status(p);
let oxygen = if spo2_status == Spo2Status::Available { Some(p.spo2) } else { None };
let limits: Vec<(&str, AlarmLimits)> = match ch {
@@ -228,8 +237,8 @@ fn draw_vitals(cr: &Context, ch: Channel, color: Color, x: f64,
}
}
Channel::Pleth => {
- let (label, value, info) = spo2_vitals_at_quality(p, pulse_rate,
- sim.poor_signal_lost(), sim.spo2_quality(p));
+ let (label, value, info) = spo2_vitals_for_status(p, spo2_rate,
+ sim.spo2_quality(p), spo2_status);
text(cr, &label, x, top + row_h * 0.24, label_size, color, false);
let technical_alarm = spo2_status != Spo2Status::Available;
let value_size = if technical_alarm {
@@ -239,8 +248,8 @@ fn draw_vitals(cr: &Context, ch: Channel, color: Color, x: f64,
width, color, technical_alarm || 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);
+ "% PR ", &spo2_rate.unwrap_or_default().to_string(), " bpm",
+ alarmed(p.alarms.pr, spo2_rate), flash);
} else {
text(cr, &info, x, info_y, sub_size, color, false);
}
@@ -427,9 +436,7 @@ fn draw_trace(cr: &Context, channel: Channel, color: Color,
// Disconnected or absent pleth signal: no curve, including historical pulses.
if matches!(channel, Channel::Pleth)
- && (!pleth_trace_enabled(p)
- || p.spo2_status_at_quality(sim.pulse_rate(), sim.poor_signal_lost(),
- sim.spo2_quality(p)) != Spo2Status::Available)
+ && sim.spo2_status(p) != Spo2Status::Available
{
let _ = cr.restore();
return;
diff --git a/src/simulation.rs b/src/simulation.rs
index c148a30..06fd000 100644
--- a/src/simulation.rs
+++ b/src/simulation.rs
@@ -2,7 +2,8 @@
//! A conducted QRS schedules an arterial pulse and a delayed, smoothed pleth pulse.
use std::collections::VecDeque;
-use crate::model::{ArterialShape, CapnoShape, EcgRhythm, Parameters, PulseConduction, Spo2Quality};
+use crate::model::{ArterialShape, CapnoShape, ChestCompressionQuality, EcgRhythm,
+ Parameters, PulseConduction, Spo2Quality, Spo2Status};
use crate::nibp::{CuffZone, NibpMachine, NibpReading};
const SAMPLE_STEP: f64 = 0.004; // 250 Hz; adequately samples the QRS upstroke
@@ -87,6 +88,91 @@ impl PoorSignalOutages {
}
}
+/// CPR is a separate mechanical clock, independent of intrinsic cardiac rate.
+/// Randomness is sampled once per compression, so peaks and intervals remain
+/// stable during drawing and are reproducible in tests.
+#[derive(Debug)]
+struct ChestCompressions {
+ active: bool,
+ phase: f64,
+ rate_bpm: f64,
+ peak_pressure: f64,
+ quality: ChestCompressionQuality,
+ rng: u64,
+}
+
+impl ChestCompressions {
+ fn new() -> Self {
+ Self { active: false, phase: 0.0, rate_bpm: 100.0,
+ peak_pressure: 0.0, quality: ChestCompressionQuality::Adequate,
+ rng: 0xC0FF_EE12_3456_789A }
+ }
+
+ fn random_unit(&mut self) -> f64 {
+ self.rng = self.rng.wrapping_mul(6_364_136_223_846_793_005)
+ .wrapping_add(1_442_695_040_888_963_407);
+ (self.rng >> 11) as f64 / (1_u64 << 53) as f64
+ }
+
+ fn choose_peak(&mut self) {
+ self.peak_pressure = match self.quality.peak_range() {
+ Some((low, high)) => low + (high - low) * self.random_unit(),
+ None => 0.0,
+ };
+ }
+
+ fn update(&mut self, enabled: bool, quality: ChestCompressionQuality) {
+ if !enabled {
+ self.active = false;
+ self.phase = 0.0;
+ self.peak_pressure = 0.0;
+ return;
+ }
+ if !self.active {
+ self.active = true;
+ self.phase = 0.0;
+ self.rate_bpm = 90.0 + self.random_unit() * 20.0;
+ self.quality = quality;
+ self.choose_peak();
+ } else if self.quality != quality {
+ self.quality = quality;
+ self.choose_peak();
+ }
+ self.phase += SAMPLE_STEP * self.rate_bpm / 60.0;
+ if self.phase >= 1.0 {
+ self.phase = self.phase.fract();
+ self.rate_bpm = 90.0 + self.random_unit() * 20.0;
+ self.choose_peak();
+ }
+ }
+
+ fn pressure_wave(&self) -> f64 {
+ // Rounded, broad compression crest (no narrow physiological upstroke).
+ let rise = smooth_step(self.phase / 0.22);
+ let fall = 1.0 - smooth_step((self.phase - 0.36) / 0.43);
+ (rise * fall).clamp(0.0, 1.0)
+ }
+
+ fn pleth_wave(&self) -> f64 {
+ // A delayed, deliberately weak mechanical pleth pulse.
+ let phase = (self.phase - 0.26).rem_euclid(1.0);
+ smooth_step(phase / 0.27) * (1.0 - smooth_step((phase - 0.27) / 0.62))
+ }
+
+ fn ecg_artifact(&self, time: f64) -> f64 {
+ // Compression-synchronous baseline motion and jagged contact artifact.
+ let wave = self.pressure_wave();
+ 0.56 * (wave - 0.30)
+ + 0.12 * (time * 71.0).sin() * wave
+ + 0.08 * (time * 113.0).sin() * wave
+ }
+}
+
+fn smooth_step(value: f64) -> f64 {
+ let t = value.clamp(0.0, 1.0);
+ t * t * (3.0 - 2.0 * t)
+}
+
pub struct Simulator {
samples: VecDeque<Sample>,
time: f64,
@@ -100,6 +186,7 @@ pub struct Simulator {
previous_conduction: PulseConduction,
previous_heart_rate: i32,
poor_signal_outages: PoorSignalOutages,
+ compressions: ChestCompressions,
nibp: NibpMachine,
art_hold_pressure: Option<f64>,
pending_time: f64,
@@ -120,6 +207,7 @@ impl Simulator {
previous_conduction: params.pulse_conduction,
previous_heart_rate: params.heart_rate,
poor_signal_outages: PoorSignalOutages::new(),
+ compressions: ChestCompressions::new(),
nibp: NibpMachine::new(),
art_hold_pressure: None,
pending_time: 0.0,
@@ -149,7 +237,43 @@ impl Simulator {
pub fn time(&self) -> f64 { self.time }
pub fn spo2_quality(&self, p: &Parameters) -> Spo2Quality {
- self.nibp.effective_spo2_quality(self.time, p)
+ if !p.chest_compressions_active {
+ return self.nibp.effective_spo2_quality(self.time, p);
+ }
+ if p.chest_compression_quality != ChestCompressionQuality::Good {
+ return Spo2Quality::None;
+ }
+ // During effective CPR the pleth signal is Poor regardless of Admin's
+ // baseline quality; an occlusive NIBP cuff can still suppress it.
+ if p.nibp_cuff_on_spo2 {
+ match self.nibp.cuff_zone(self.time, p) {
+ CuffZone::Occluded => return Spo2Quality::None,
+ CuffZone::Partial | CuffZone::Free => {}
+ }
+ }
+ Spo2Quality::Poor
+ }
+
+ /// Display-only pulse rate: under effective CPR the peripheral signal
+ /// follows compressions rather than non-perfusing electrical QRS events.
+ pub fn spo2_pulse_rate(&self, p: &Parameters) -> Option<i32> {
+ if p.chest_compressions_active {
+ (p.chest_compression_quality == ChestCompressionQuality::Good)
+ .then_some(self.compressions.rate_bpm.round() as i32)
+ } else {
+ self.pulse_rate()
+ }
+ }
+
+ pub fn spo2_status(&self, p: &Parameters) -> Spo2Status {
+ if !p.spo2_sensor_attached { return Spo2Status::NoSensor; }
+ if p.chest_compressions_active {
+ return if p.chest_compression_quality == ChestCompressionQuality::Good
+ && self.spo2_quality(p) != Spo2Quality::None
+ { Spo2Status::Available } else { Spo2Status::NoReading };
+ }
+ p.spo2_status_at_quality(self.pulse_rate(), self.poor_signal_lost(),
+ self.spo2_quality(p))
}
pub fn start_nibp_now(&mut self, p: &Parameters) {
@@ -161,7 +285,7 @@ impl Simulator {
if !p.spo2_sensor_attached || self.poor_signal_outages.active {
Spo2Quality::None
} else {
- p.spo2_quality
+ self.spo2_quality(p)
}
}
@@ -169,6 +293,11 @@ impl Simulator {
pub fn displayed_art_pressures(&self, p: &Parameters, has_capture: bool)
-> (Option<i32>, Option<i32>, Option<i32>) {
if !has_capture {
+ // During pulseless CPR the upper ART number reflects the peak
+ // compression pressure; DIA/MAP remain intentionally unassessed.
+ if self.compressions.active && p.chest_compression_quality != ChestCompressionQuality::Bad {
+ return (Some(self.compressions.peak_pressure.round() as i32), None, None);
+ }
return (self.measured_art_pressure(), None, None);
}
if p.nibp_cuff_on_art {
@@ -219,8 +348,11 @@ impl Simulator {
fn step(&mut self, params: &Parameters) {
self.time += SAMPLE_STEP;
+ self.compressions.update(params.chest_compressions_active,
+ params.chest_compression_quality);
self.poor_signal_outages.update(self.time,
- params.spo2_quality == Spo2Quality::Poor && params.spo2_sensor_attached);
+ !params.chest_compressions_active && params.spo2_quality == Spo2Quality::Poor
+ && params.spo2_sensor_attached);
// Snapshot the unoccluded sensor quality at the start of a cuff cycle.
// Cuff-induced signal loss during that cycle must not change its duration.
let start_quality = self.nibp_start_quality(params);
@@ -289,8 +421,25 @@ impl Simulator {
self.rate_qrs.pop_front();
}
- let ecg = ecg_amplitude(self.ecg_phase, self.time, params.ecg_rhythm, params.heart_rate);
- let (normal_art, pleth_target) = self.mechanical_signals(params);
+ let mut ecg = ecg_amplitude(self.ecg_phase, self.time, params.ecg_rhythm, params.heart_rate);
+ let (mut normal_art, mut pleth_target) = self.mechanical_signals(params);
+ if self.compressions.active {
+ ecg += self.compressions.ecg_artifact(self.time);
+ let perfusing = params.ecg_rhythm.can_generate_pulse()
+ && params.pulse_conduction != PulseConduction::None && params.heart_rate > 0;
+ let wave = self.compressions.pressure_wave();
+ if perfusing {
+ // Preserve the patient's intrinsic pressure, with superimposed
+ // compression-synchronous artifact even during bad CPR.
+ normal_art = (normal_art + 22.0 * (wave - 0.32)).clamp(0.0, 250.0);
+ } else if self.compressions.peak_pressure > 0.0 {
+ let baseline = pulseless_arterial_drift(self.time);
+ normal_art = baseline + (self.compressions.peak_pressure - baseline) * wave;
+ }
+ pleth_target = if params.chest_compression_quality == ChestCompressionQuality::Good {
+ 0.85 * self.compressions.pleth_wave()
+ } else { 0.0 };
+ }
let art = self.art_with_cuff(normal_art, params);
let smoothing = 1.0 - (-SAMPLE_STEP / PLETH_FILTER_TAU).exp();
self.filtered_pleth += smoothing * (pleth_target - self.filtered_pleth);
@@ -301,9 +450,7 @@ impl Simulator {
};
let pleth_quality = self.spo2_quality(params);
- let pleth_valid = params.spo2_sensor_attached
- && pleth_quality != Spo2Quality::None
- && !self.poor_signal_outages.active;
+ let pleth_valid = self.spo2_status(params) == Spo2Status::Available;
self.samples.push_back(Sample {
time: self.time, ecg, pleth, pleth_valid, pleth_quality, art, co2,
});
@@ -313,9 +460,10 @@ impl Simulator {
}
fn art_with_cuff(&mut self, normal_art: f64, params: &Parameters) -> f64 {
- if !params.nibp_cuff_on_art || !params.ecg_rhythm.can_generate_pulse()
- || params.pulse_conduction == PulseConduction::None || params.heart_rate <= 0
- {
+ let native_pulse = params.ecg_rhythm.can_generate_pulse()
+ && params.pulse_conduction != PulseConduction::None && params.heart_rate > 0;
+ let compression_pulse = self.compressions.active && self.compressions.peak_pressure > 0.0;
+ if !params.nibp_cuff_on_art || !(native_pulse || compression_pulse) {
self.art_hold_pressure = None;
return normal_art;
}
@@ -545,6 +693,129 @@ mod tests {
sim
}
+ #[test]
+ fn compression_rate_varies_only_between_90_and_110_bpm() {
+ let mut cpr = ChestCompressions::new();
+ let mut observed = Vec::new();
+ for _ in 0..(25.0 / SAMPLE_STEP) as usize {
+ let previous = cpr.phase;
+ cpr.update(true, ChestCompressionQuality::Good);
+ assert!((90.0..=110.0).contains(&cpr.rate_bpm));
+ if cpr.phase < previous { observed.push(cpr.rate_bpm); }
+ }
+ assert!(observed.len() >= 30);
+ assert!(observed.iter().any(|rate| (rate - observed[0]).abs() > 1.0));
+ cpr.update(false, ChestCompressionQuality::Good);
+ assert!(!cpr.active);
+ assert_eq!(cpr.peak_pressure, 0.0);
+ }
+
+ #[test]
+ fn compressions_generate_requested_pulseless_arterial_pressure_by_quality() {
+ for (quality, limits) in [
+ (ChestCompressionQuality::Good, Some((81.0, 99.0))),
+ (ChestCompressionQuality::Adequate, Some((63.0, 77.0))),
+ (ChestCompressionQuality::Poor, Some((25.0, 55.0))),
+ (ChestCompressionQuality::Bad, None),
+ ] {
+ let p = Parameters { ecg_rhythm: EcgRhythm::VentricularFibrillation,
+ chest_compressions_active: true, chest_compression_quality: quality,
+ ..Parameters::default() };
+ let mut sim = Simulator::new(&p);
+ for _ in 0..(2.0 / SAMPLE_STEP) as usize { sim.step(&p); }
+ assert_eq!(sim.pulse_rate(), None, "no intrinsic QRS pulse in VF");
+ let recent: Vec<_> = sim.samples.iter().rev().take(500).collect();
+ let peak = recent.iter().map(|s| s.art).fold(f64::NEG_INFINITY, f64::max);
+ let (sys, dia, map) = sim.displayed_art_pressures(&p, false);
+ assert_eq!((dia, map), (None, None));
+ if let Some((low, high)) = limits {
+ assert!(peak >= low - 1.0 && peak <= high + 1.0,
+ "{quality:?}: waveform peak {peak}");
+ assert!(sys.is_some_and(|v| (low - 1.0..=high + 1.0).contains(&f64::from(v))));
+ } else {
+ assert!(peak <= 5.0, "bad CPR must not create a pulse");
+ assert!(sys.is_some_and(|v| (0..=5).contains(&v)));
+ }
+ }
+ }
+
+ #[test]
+ fn good_cpr_can_create_poor_pleth_in_vf_despite_admin_no_quality() {
+ let p = Parameters { ecg_rhythm: EcgRhythm::VentricularFibrillation,
+ spo2_quality: Spo2Quality::None,
+ chest_compressions_active: true,
+ chest_compression_quality: ChestCompressionQuality::Good,
+ ..Parameters::default() };
+ let mut sim = Simulator::new(&p);
+ for _ in 0..400 { sim.step(&p); }
+ assert_eq!(sim.spo2_quality(&p), Spo2Quality::Poor);
+ assert_eq!(sim.spo2_status(&p), Spo2Status::Available);
+ assert!(sim.spo2_pulse_rate(&p).is_some_and(|v| (90..=110).contains(&v)));
+ assert!(sim.samples.iter().rev().take(400).any(|s| s.pleth > 0.05 && s.pleth_valid));
+ assert!(sim.samples.iter().rev().take(400).all(|s| s.pleth_quality == Spo2Quality::Poor));
+ }
+
+ #[test]
+ fn only_good_cpr_shows_pleth_and_sensor_disconnect_takes_precedence() {
+ for quality in [ChestCompressionQuality::Adequate,
+ ChestCompressionQuality::Poor, ChestCompressionQuality::Bad] {
+ let p = Parameters { chest_compressions_active: true,
+ chest_compression_quality: quality, ..Parameters::default() };
+ let mut sim = Simulator::new(&p);
+ sim.step(&p);
+ assert_eq!(sim.spo2_status(&p), Spo2Status::NoReading);
+ assert_eq!(sim.spo2_pulse_rate(&p), None);
+ assert!(!sim.samples.back().unwrap().pleth_valid);
+ }
+ let mut p = Parameters { chest_compressions_active: true,
+ chest_compression_quality: ChestCompressionQuality::Good, ..Parameters::default() };
+ let mut sim = Simulator::new(&p);
+ p.spo2_sensor_attached = false;
+ sim.step(&p);
+ assert_eq!(sim.spo2_status(&p), Spo2Status::NoSensor);
+ assert!(!sim.samples.back().unwrap().pleth_valid);
+ }
+
+ #[test]
+ fn compressions_distort_ecg_and_preserve_intrinsic_pulses_in_sinus() {
+ let normal = Parameters::default();
+ let with_cpr = Parameters { chest_compressions_active: true,
+ chest_compression_quality: ChestCompressionQuality::Adequate,
+ ..Parameters::default() };
+ let mut base = Simulator::new(&normal);
+ let mut cpr = Simulator::new(&with_cpr);
+ let mut ecg_distortion = false;
+ let mut art_distortion = false;
+ for _ in 0..500 {
+ base.step(&normal);
+ cpr.step(&with_cpr);
+ let native = base.samples.back().unwrap();
+ let compressed = cpr.samples.back().unwrap();
+ ecg_distortion |= (compressed.ecg - native.ecg).abs() > 0.1;
+ art_distortion |= (compressed.art - native.art).abs() > 5.0;
+ }
+ assert!(ecg_distortion);
+ assert!(art_distortion);
+ assert!(cpr.samples.iter().rev().take(500).any(|s| s.art > 60.0));
+ assert_eq!(cpr.pulse_rate(), Some(75), "CPR must not change underlying HR/PR capture");
+ }
+
+ #[test]
+ fn stopping_compressions_restores_pulseless_drift_and_normal_pleth_rules() {
+ let mut p = Parameters { ecg_rhythm: EcgRhythm::Asystole,
+ chest_compressions_active: true,
+ chest_compression_quality: ChestCompressionQuality::Good,
+ ..Parameters::default() };
+ let mut sim = Simulator::new(&p);
+ assert_eq!(sim.spo2_status(&p), Spo2Status::Available);
+ p.chest_compressions_active = false;
+ sim.step(&p);
+ assert!((0.0..=5.0).contains(&sim.samples.back().unwrap().art));
+ assert_eq!(sim.spo2_status(&p), Spo2Status::NoReading);
+ assert!(!sim.samples.back().unwrap().pleth_valid);
+ assert_eq!(sim.spo2_pulse_rate(&p), None);
+ }
+
#[test]
fn signals_remain_in_expected_ranges() {
let p = Parameters::default();
diff --git a/src/ui.rs b/src/ui.rs
index 7e6fd0a..ffb8579 100644
--- a/src/ui.rs
+++ b/src/ui.rs
@@ -9,7 +9,8 @@ use gtk::prelude::*;
use gtk::{Application, ApplicationWindow, Orientation};
use crate::alarm::{self, AlarmAudio};
-use crate::model::{AlarmLimits, AlarmSettings, ArterialShape, CapnoShape, EcgRhythm, Parameters, PulseConduction, Spo2Quality};
+use crate::model::{AlarmLimits, AlarmSettings, ArterialShape, CapnoShape,
+ ChestCompressionQuality, EcgRhythm, Parameters, PulseConduction, Spo2Quality};
use crate::render;
use crate::simulation::Simulator;
@@ -186,6 +187,60 @@ fn create_admin(app: &Application, params: SharedParams,
patient_row.append(&name_entry);
patient.append(&patient_row);
+ // Resuscitation controls are deliberately near the top of the Admin panel.
+ // CSS sets the *button background*, not just its text color.
+ if let Some(display) = gdk::Display::default() {
+ let provider = gtk::CssProvider::new();
+ provider.load_from_data(
+ "button.cpr-start { background-image: none; background-color: #158742; color: #ffffff; font-weight: bold; }
+ button.cpr-stop { background-image: none; background-color: #c53035; color: #ffffff; font-weight: bold; }"
+ );
+ gtk::style_context_add_provider_for_display(
+ &display, &provider, gtk::STYLE_PROVIDER_PRIORITY_APPLICATION);
+ }
+ let cpr = group(&controls, "Chest compressions", None);
+ let compression_button = gtk::Button::with_label("Start Chest Compressions");
+ compression_button.set_hexpand(true);
+ compression_button.add_css_class("cpr-start");
+ compression_button.connect_clicked({
+ let params = params.clone();
+ move |button| {
+ let mut p = params.borrow_mut();
+ p.chest_compressions_active = !p.chest_compressions_active;
+ if p.chest_compressions_active {
+ button.set_label("Stop Chest Compressions");
+ button.remove_css_class("cpr-start");
+ button.add_css_class("cpr-stop");
+ } else {
+ button.set_label("Start Chest Compressions");
+ button.remove_css_class("cpr-stop");
+ button.add_css_class("cpr-start");
+ }
+ }
+ });
+ cpr.append(&compression_button);
+ let _quality = add_dropdown_at(&cpr, "Compression quality",
+ &["Good", "Adequate", "Poor", "Bad"], 1, params.clone(), |p, selected| {
+ p.chest_compression_quality = match selected {
+ 0 => ChestCompressionQuality::Good,
+ 2 => ChestCompressionQuality::Poor,
+ 3 => ChestCompressionQuality::Bad,
+ _ => ChestCompressionQuality::Adequate,
+ };
+ });
+ let cpr_hint = gtk::Label::new(Some(
+ "CPR: 90–110 compressions/min. ECG is distorted; ART receives compression waves. "
+ ));
+ cpr_hint.set_xalign(0.0);
+ cpr_hint.set_wrap(true);
+ cpr.append(&cpr_hint);
+ let cpr_hint2 = gtk::Label::new(Some(
+ "Only Good compressions generate a Poor-quality SpO₂/pleth signal (if the sensor is attached)."
+ ));
+ cpr_hint2.set_xalign(0.0);
+ cpr_hint2.set_wrap(true);
+ cpr.append(&cpr_hint2);
+
let ecg = group(&controls, "ECG", Some(ECG_GREEN));
add_visibility(&ecg, params.borrow().show_ecg, params.clone(), |p, show| p.show_ecg = show);
let rhythm_dropdown = add_dropdown_at(&ecg, "ECG rhythm", &[

View file

@ -0,0 +1,65 @@
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "patient-monitor-simulation"
-version = "0.5.4"
+version = "0.5.5"
edition = "2021"
license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"
--- a/README.md
+++ b/README.md
@@ -490,3 +490,8 @@
- Distinct critical-rhythm and standard/technical patterns; critical priority.
- Audio keeps running independently of the monitor's drawing callback.
- Visual alarms and existing physiological simulation remain unchanged.
+
+
+### v0.5.5 — CPR plethysmography correction
+
+The delayed CPR pleth waveform no longer wraps its trailing portion into the next compression. The regression test now reports the maximum valid waveform amplitude when failing. No other simulation controls were changed.
--- a/README.de.md
+++ b/README.de.md
@@ -469,3 +469,8 @@
technische Alarme; kritische Alarme haben Vorrang.
- Die Audioausgabe ist von der Kurvendarstellung entkoppelt.
- Bisherige optische Alarme und Simulationsfunktionen bleiben unverändert.
+
+
+### v0.5.5 – Korrektur der CPR-Plethysmographie
+
+Die verzögerte Plethysmographiekurve bei Thoraxkompressionen überlappt nicht mehr mit der nächsten Kompression. Der Regressionstest gibt bei einem Fehlschlag die maximale gültige Kurvenamplitude aus. Sonstige Simulationseinstellungen bleiben unverändert.
--- a/src/simulation.rs
+++ b/src/simulation.rs
@@ -154,9 +154,12 @@
}
fn pleth_wave(&self) -> f64 {
- // A delayed, deliberately weak mechanical pleth pulse.
- let phase = (self.phase - 0.26).rem_euclid(1.0);
- smooth_step(phase / 0.27) * (1.0 - smooth_step((phase - 0.27) / 0.62))
+ // A delayed, low-amplitude pulse for effective CPR. Using a bounded
+ // within-compression phase instead of wrapping the delay prevents
+ // a pulse's trailing portion leaking into the *next* compression.
+ let phase = self.phase - 0.25;
+ if phase <= 0.0 { return 0.0; }
+ smooth_step(phase / 0.22) * (1.0 - smooth_step((phase - 0.35) / 0.35))
}
fn ecg_artifact(&self, time: f64) -> f64 {
@@ -751,8 +754,12 @@
assert_eq!(sim.spo2_quality(&p), Spo2Quality::Poor);
assert_eq!(sim.spo2_status(&p), Spo2Status::Available);
assert!(sim.spo2_pulse_rate(&p).is_some_and(|v| (90..=110).contains(&v)));
- assert!(sim.samples.iter().rev().take(400).any(|s| s.pleth > 0.05 && s.pleth_valid));
- assert!(sim.samples.iter().rev().take(400).all(|s| s.pleth_quality == Spo2Quality::Poor));
+ let recent: Vec<_> = sim.samples.iter().rev().take(400).collect();
+ let max_valid_pleth = recent.iter().filter(|s| s.pleth_valid)
+ .map(|s| s.pleth).fold(0.0_f64, f64::max);
+ assert!(max_valid_pleth > 0.05,
+ "good CPR in VF must generate valid pleth pulses; max valid amplitude={max_valid_pleth:.4}");
+ assert!(recent.iter().all(|s| s.pleth_quality == Spo2Quality::Poor));
}
#[test]

View file

@ -0,0 +1,311 @@
diff --git a/Cargo.toml b/Cargo.toml
index 13195d0..77b0b47 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "patient-monitor-simulation"
-version = "0.5.6"
+version = "0.5.7"
edition = "2021"
license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"
diff --git a/README.de.md b/README.de.md
index 4082c89..0fdf2d0 100644
--- a/README.de.md
+++ b/README.de.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.5.4
+# Patient Monitor Simulation (PaMSim) — v0.5.7
Ein mit Rust und GTK4 entwickelter Patient*innenmonitor-Simulator mit zwei Fenstern für die Lehre unter Fedora Linux.
@@ -6,6 +6,26 @@ Ein mit Rust und GTK4 entwickelter Patient*innenmonitor-Simulator mit zwei Fenst
> EKG, invasive arterielle Druckkurve, Plethysmogramm und Kapnogramm sind schematische mathematische Annäherungen.
> Die Simulation wurde nicht klinisch validiert und ist kein Medizinprodukt.
+## Monitoraufteilung (v0.5.7)
+
+Der nutzbare Monitorbereich wird in einem festen Verhältnis von **75 % für die
+Kurvenspalte** und **25 % für die numerische Spalte** aufgeteilt. Dies gilt auch
+bei Änderung der Fenstergröße. Die letzte Zeile besteht aus vier gleich breiten
+Wertefeldern:
+
+| Feld 1 (25 %) | Feld 2 (25 %) | Feld 3 (25 %) | Feld 4 (25 %) |
+| --- | --- | --- | --- |
+| CO / CI | SVRI · GEDI · ELWI | *(leer)* | NIBP |
+
+In den ersten beiden Feldern sind ausschließlich die Beschriftungen sichtbar;
+Messwerte und Berechnungen werden erst in einer späteren Version implementiert.
+Das dritte Feld bleibt vollständig leer. Im vierten Feld bleiben die bestehenden
+NIBP-Messwerte, der Manschettendruckbalken, die Fortschrittsanzeige und die
+Alarme erhalten. Wenn NIBP ausgeblendet wird, verschwindet nur der Inhalt des
+vierten Feldes; die gesamte untere Wertezeile bleibt bestehen.
+Beim Ausblenden anderer Parameter werden die verbleibenden Kurvenzeilen wie
+bisher dynamisch verteilt.
+
## Thoraxkompressionen (v0.5.4)
Im Admin-Bereich **Chest compressions** startet die grüne Schaltfläche
@@ -83,11 +103,10 @@ Lange Namen werden an die verfügbare Breite angepasst oder abgeschnitten.
Wird die Sichtbarkeit eines Parameters deaktiviert, verschwinden sowohl seine Kurve als auch die zugehörigen Messwerte.
Die verbleibenden Kurvenbereiche vergrößern sich entsprechend.
Das Ausblenden eines Monitorbereichs unterbricht **nicht** die Signalerzeugung oder physiologische Kopplung: Wird beispielsweise das EKG ausgeblendet, können arterielle und plethysmographische Pulse weiterhin auftreten.
-Für NIBP wird in der linken Kurvenspalte eine **leere Zelle** freigehalten.
-Damit sind die Kurvenbereiche und die numerischen Wertefelder in der rechten Spalte
-in allen Zeilen exakt aufeinander ausgerichtet.
-NIBP kann unabhängig ausgeblendet werden; dabei verschwindet die gesamte NIBP-Zeile
-und die übrigen Zeilen nutzen den frei werdenden Platz.
+Die unterste Zeile enthält vier gleich breite numerische Wertefelder. Das
+vierte Feld für NIBP ist an der rechten Monitorspalte ausgerichtet.
+NIBP kann unabhängig ausgeblendet werden; dabei bleibt die untere Zeile mit
+den drei noch nicht implementierten Messgruppen bestehen.
Das Monitorfenster lässt sich in der Größe verändern.
Mit **F11** wird der Vollbildmodus aktiviert bzw. umgeschaltet, mit **Esc** wird er verlassen.
@@ -479,3 +498,11 @@ Die verzögerte Plethysmographiekurve bei Thoraxkompressionen überlappt nicht m
### v0.5.6 – Persistenz des Pleth-Filters bei Thoraxkompressionen
Die eigentliche Ursache des Testfehlers aus v0.5.5 wurde behoben: Bei pulslosen Rhythmen wurde der Pleth-Tiefpassfilter bislang mit jedem 250-Hz-Abtastwert zurückgesetzt. Während qualitativ guter Thoraxkompressionen bleibt der Filterzustand nun erhalten; QRS-getriggerte mechanische Pulse werden weiterhin verworfen. Nach dem Beenden der Kompressionen bei VF/PVT verschwindet das Pleth-Signal sofort. Ein zusätzlicher Regressionstest deckt PVT ab.
+
+### v0.5.7 – Vier numerische Messgruppen in der unteren Zeile
+
+Feste Aufteilung von 75 % Kurvenspalte und 25 % numerischer Spalte. In der
+untersten Zeile stehen vier gleich breite Bereiche: CO/CI, SVRI/GEDI/ELWI,
+ein vollständig leerer Platzhalter und NIBP. Die ersten beiden Bereiche
+zeigen derzeit nur ihre Bezeichnungen. Wird NIBP ausgeblendet, bleibt die
+untere Zeile bestehen. Das Simulationsverhalten ist unverändert.
diff --git a/README.md b/README.md
index dc19c84..fe6cac3 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.5.4
+# Patient Monitor Simulation (PaMSim) — v0.5.7
A two-window, Rust/GTK4 patient-monitor simulator for teaching on Fedora Linux.
@@ -6,6 +6,23 @@ A two-window, Rust/GTK4 patient-monitor simulator for teaching on Fedora Linux.
> plethysmography and capnography are schematic mathematical approximations. The
> simulation has no clinical validation and is not a medical device.
+## Monitor layout (v0.5.7)
+
+The monitor uses a fixed **3:1 column ratio** over the drawable area:
+**75% waveform column / 25% numeric column**, regardless of window size.
+The last row is reserved for four equal-width numerical measurement groups:
+
+| Group 1 (25%) | Group 2 (25%) | Group 3 (25%) | Group 4 (25%) |
+| --- | --- | --- | --- |
+| CO / CI | SVRI · GEDI · ELWI | *(empty)* | NIBP |
+
+The first two groups currently display only their headings, with no numerical
+values or simulation logic. The third group is completely empty. The fourth
+retains the existing red NIBP readings, cuff gauge, progress bar and alarms.
+The NIBP visibility toggle hides **only the fourth group's content**; the
+bottom measurement row and other three groups remain present. Disabling one
+of the four waveform channels still reflows the remaining rows above it.
+
## Chest compressions (v0.5.4)
The **Chest compressions** Admin group provides a large **Start Chest Compressions**
@@ -80,10 +97,11 @@ Long names are automatically resized or clipped to fit the header.
Waveforms and vital signs disappear together when their respective
visibility checkbox is cleared. Remaining waveform rows expand to use the space.
Hiding a display channel does **not** stop signal generation or physiological
-coupling: for example, hiding ECG does not stop ART or pleth pulses. NIBP occupies a dedicated right-column row with an **empty waveform cell** on the
-left. All waveform rows and their corresponding numeric boxes share the same
-height and horizontal boundaries. NIBP can be hidden independently; its entire
-row is then removed and the remaining rows expand evenly.
+coupling: for example, hiding ECG does not stop ART or pleth pulses.
+The final row is split into four equal-width measurement groups, with **NIBP in
+the fourth group**, aligned beneath the regular numeric column. The first
+three groups are reserved for future measurements. Hiding NIBP only clears
+its own fourth group, without removing the final row.
The monitor can be resized and toggled fullscreen with **F11**; **Esc** exits
fullscreen. On Wayland, move the monitor to the presentation screen before
@@ -236,8 +254,8 @@ can be taught.
## NIBP measurement cycle (v0.5.0)
NIBP is **red**, with a dedicated value box in the **right-hand numeric column**.
-An **empty left-hand waveform cell** occupies the same row, keeping every numeric
-value box horizontally aligned with its waveform region. The previous static
+The bottom measurement row has three placeholder groups to its left, keeping
+NIBP aligned with the standard right-hand numeric column. The previous static
NIBP footer has been removed. In Admin, choose an interval
of **1, 3, 5, 10, 20, 30, or 60 minutes** (default 5). The initial cuff cycle
begins when the simulation starts; subsequent intervals run **from the end of
@@ -366,9 +384,10 @@ The five **Show on monitor** checkboxes affect the presentation only:
| Capnography | CO₂ waveform, EtCO₂ and RR |
| NIBP | Timed cuff-measurement values and red right-column value box |
-Remaining visible waveform rows and the NIBP-only row share an equal
+Remaining visible waveform rows and the bottom measurements row share an equal
portion of the available height and remain aligned across both columns; zero
-waveform channels is supported.
+waveform channels is supported. Hiding NIBP leaves the three future measurement
+placeholders visible.
## ECG morphology correction (v0.3.1)
@@ -500,3 +519,11 @@ The delayed CPR pleth waveform no longer wraps its trailing portion into the nex
### v0.5.6 — CPR pleth filter persistence
Corrects the underlying cause of the v0.5.5 test failure: in pulseless rhythms, the simulation had reset the pleth low-pass filter at every 250 Hz sample, preventing CPR-induced signals from accumulating. The filter now persists during good-quality chest compressions while QRS-triggered mechanical pulses are still cleared. Stopping CPR in VF/PVT immediately restores no reading. Additional regression coverage includes PVT.
+
+### v0.5.7 — Four-group numerical measurement row
+
+The monitor now uses a 75%/25% waveform/numeric column split. The final
+row has four equally sized measurement groups: CO/CI; SVRI/GEDI/ELWI;
+reserved empty; and the unchanged NIBP readout. Only headings are rendered
+in the first two groups; the third has no content. NIBP can be hidden without
+removing the final row. No physiological simulation behavior was modified.
diff --git a/src/render.rs b/src/render.rs
index 4053fe1..cb62a42 100644
--- a/src/render.rs
+++ b/src/render.rs
@@ -35,13 +35,13 @@ pub fn draw(cr: &Context, width: i32, height: i32, p: &Parameters, sim: &Simulat
let header = (h * 0.083).clamp(32.0, 68.0);
let channels = visible_channels(p);
let body_height = (h - header - pad).max(20.0);
- // A single grid governs both columns. NIBP has an empty waveform cell
- // on the left, so all numeric boxes line up with their waveform rows.
- let (row_height, nibp_top) = monitor_rows(header, body_height, channels.len(), p.show_nibp);
- let sidebar = (w * 0.235).clamp(125.0, 370.0).min(w * 0.44);
- let split_x = w - sidebar - pad;
+ // Waveforms occupy three quarters of the drawable width and numeric
+ // values one quarter. The final row is four equal-sized numeric cells.
+ let (row_height, measurements_top) = monitor_rows(header, body_height, channels.len());
+ let (split_x, quarter_width) = monitor_columns(w, pad);
+ let numeric_width = (quarter_width - 2.0 * pad).max(1.0);
let trace_left = pad + 6.0;
- let trace_right = (split_x - pad).max(trace_left + 40.0);
+ let trace_right = (split_x - pad).max(trace_left + 1.0);
let text_scale = (w.min(h * 1.7) / 850.0).clamp(0.65, 1.5);
let patient_title = if p.patient_name.trim().is_empty() {
@@ -72,25 +72,58 @@ pub fn draw(cr: &Context, width: i32, height: i32, p: &Parameters, sim: &Simulat
draw_trace(cr, channel, color, trace_left, trace_right,
top + row_height * 0.25, bottom - row_height * 0.06, p, sim);
draw_vitals(cr, channel, color, split_x + pad,
- top, row_height, sidebar - 2.0 * pad, p, sim);
+ top, row_height, numeric_width, p, sim);
}
- if let Some(top) = nibp_top {
- // Intentionally blank waveform cell to the left of the NIBP box.
- stroke_line(cr, pad, top + row_height, w - pad, top + row_height, MUTED, 0.65);
- draw_nibp_box(cr, split_x + pad, top,
- sidebar - 2.0 * pad, row_height, p, sim);
- }
+ // The last row contains four adjacent measurement groups, each spanning
+ // exactly one quarter of the drawable width. The fourth is the normal
+ // right-hand NIBP numeric column. The other groups are future placeholders.
+ draw_measurements_row(cr, pad, measurements_top, row_height, quarter_width,
+ numeric_width, p, sim);
+}
+
+/// Left/right split and the width of each bottom-row group. Outer margins
+/// are excluded, so 75% / 25% holds at all window sizes (no width clamping).
+fn monitor_columns(window_width: f64, pad: f64) -> (f64, f64) {
+ let quarter_width = (window_width - 2.0 * pad).max(1.0) / 4.0;
+ (pad + 3.0 * quarter_width, quarter_width)
}
-/// Compute the same row boundaries for the waveform and numeric columns.
-/// NIBP, when visible, occupies the final row and leaves its left cell empty.
-fn monitor_rows(header: f64, body_height: f64, trace_count: usize, show_nibp: bool)
- -> (f64, Option<f64>) {
- let row_count = trace_count + usize::from(show_nibp);
- let row_height = body_height / row_count.max(1) as f64;
- let nibp_top = show_nibp.then_some(header + trace_count as f64 * row_height);
- (row_height, nibp_top)
+/// The bottom measurement row always exists, even when NIBP is hidden: the
+/// remaining three groups are reserved for future parameters. Waveform rows
+/// above it still reflow when individual channels are hidden.
+fn monitor_rows(header: f64, body_height: f64, trace_count: usize) -> (f64, f64) {
+ let row_height = body_height / (trace_count + 1) as f64;
+ let measurements_top = header + trace_count as f64 * row_height;
+ (row_height, measurements_top)
+}
+
+const FUTURE_MEASUREMENT_LABELS: [&str; 3] = ["CO / CI", "SVRI · GEDI · ELWI", ""];
+
+#[allow(clippy::too_many_arguments)]
+fn draw_measurements_row(cr: &Context, left: f64, top: f64, height: f64,
+ quarter_width: f64, numeric_width: f64,
+ p: &Parameters, sim: &Simulator) {
+ let bottom = top + height;
+ stroke_line(cr, left, bottom, left + 4.0 * quarter_width, bottom, MUTED, 0.65);
+ let label_size = (height * 0.135).clamp(11.0, 19.0);
+ for (index, label) in FUTURE_MEASUREMENT_LABELS.iter().enumerate() {
+ let cell_left = left + index as f64 * quarter_width;
+ if index > 0 {
+ stroke_line(cr, cell_left, top, cell_left, bottom, MUTED, 0.65);
+ }
+ if !label.is_empty() {
+ // Placeholder labels only: no numerical values or simulated data.
+ fitted_text(cr, label, cell_left + quarter_width * 0.06,
+ top + height * 0.24, label_size,
+ quarter_width * 0.88, LIGHT_GREY);
+ }
+ }
+ // The existing global column separator supplies the fourth divider.
+ if p.show_nibp {
+ draw_nibp_box(cr, left + 3.0 * quarter_width + (quarter_width - numeric_width) * 0.5, top,
+ numeric_width, height, p, sim);
+ }
}
fn draw_nibp_box(cr: &Context, x: f64, top: f64, width: f64, height: f64,
@@ -555,26 +588,41 @@ mod tests {
use super::*;
#[test]
- fn monitor_rows_align_waveforms_and_numbers_with_blank_nibp_left_cell() {
+ fn monitor_rows_align_waveforms_and_bottom_measurements() {
let header = 60.0;
let body_height = 700.0;
- let (height, nibp_top) = monitor_rows(header, body_height, 4, true);
+ let (height, measurements_top) = monitor_rows(header, body_height, 4);
assert_eq!(height, 140.0);
- assert_eq!(nibp_top, Some(620.0));
+ assert_eq!(measurements_top, 620.0);
// Every waveform row and its corresponding numeric row share boundaries.
for index in 0..4 {
let top = header + index as f64 * height;
let bottom = top + height;
assert_eq!(bottom, header + (index + 1) as f64 * height);
}
- assert_eq!(nibp_top.unwrap() + height, header + body_height);
+ assert_eq!(measurements_top + height, header + body_height);
}
#[test]
- fn monitor_rows_reflow_when_nibp_or_waveforms_are_hidden() {
- assert_eq!(monitor_rows(60.0, 700.0, 4, false), (175.0, None));
- assert_eq!(monitor_rows(60.0, 700.0, 0, true), (700.0, Some(60.0)));
- assert_eq!(monitor_rows(60.0, 700.0, 0, false), (700.0, None));
+ fn bottom_measurements_remain_when_nibp_or_waveforms_are_hidden() {
+ // Hiding NIBP only clears the fourth cell; the placeholders stay.
+ assert_eq!(monitor_rows(60.0, 700.0, 4), (140.0, 620.0));
+ assert_eq!(monitor_rows(60.0, 700.0, 2), (700.0 / 3.0, 60.0 + 2.0 * (700.0 / 3.0)));
+ assert_eq!(monitor_rows(60.0, 700.0, 0), (700.0, 60.0));
+ }
+
+ #[test]
+ fn waveform_split_is_three_quarters_and_bottom_groups_are_equal() {
+ for (width, pad) in [(800.0, 10.0), (1280.0, 20.0), (2560.0, 20.0)] {
+ let (split, group) = monitor_columns(width, pad);
+ let usable = width - 2.0 * pad;
+ assert!((split - (pad + 0.75 * usable)).abs() < 1e-9);
+ assert!((group - 0.25 * usable).abs() < 1e-9);
+ assert!((split - (pad + 3.0 * group)).abs() < 1e-9);
+ assert!((pad + 4.0 * group - (width - pad)).abs() < 1e-9);
+ }
+ assert_eq!(FUTURE_MEASUREMENT_LABELS,
+ ["CO / CI", "SVRI · GEDI · ELWI", ""]);
}
#[test]

View file

@ -0,0 +1,604 @@
diff --git a/Cargo.toml b/Cargo.toml
index 77b0b47..fa0ab8d 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "patient-monitor-simulation"
-version = "0.5.7"
+version = "0.5.8"
edition = "2021"
license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"
diff --git a/README.de.md b/README.de.md
index 0fdf2d0..7e03cee 100644
--- a/README.de.md
+++ b/README.de.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.5.7
+# Patient Monitor Simulation (PaMSim) — v0.5.8
Ein mit Rust und GTK4 entwickelter Patient*innenmonitor-Simulator mit zwei Fenstern für die Lehre unter Fedora Linux.
@@ -26,6 +26,33 @@ vierten Feldes; die gesamte untere Wertezeile bleibt bestehen.
Beim Ausblenden anderer Parameter werden die verbleibenden Kurvenzeilen wie
bisher dynamisch verteilt.
+## EKG-Bedienung direkt am Monitor (v0.5.8)
+
+Durch Berühren oder Anklicken der **EKG-Zeile** öffnet sich ein eigenes
+Einstellfenster mit **grüner Schrift auf schwarzem Hintergrund**. Die gesamte
+EKG-Zeile ist aktiv, sowohl die Kurve links (75 %) als auch das numerische
+Herzfrequenzfeld rechts (25 %). Die Bedienung ist auch im Vollbildmodus möglich.
+Bei ausgeblendetem EKG ist die Interaktionsfläche deaktiviert.
+
+Im Einstellfenster stehen folgende Optionen zur Verfügung:
+
+- **ECG lead:** I, II (Voreinstellung), III, aVR, aVL, aVF und V1–V6. Nach
+ **Apply** ändert sich die Ableitungsbezeichnung im Monitor sowie die
+ schematische Polarität/Amplitude der Kurve. Es handelt sich **nicht** um
+ eine klinisch validierte 12-Kanal-EKG-Ableitung. Frequenz, QRS-Zeitpunkte
+ und mechanische Pulskopplung bleiben unverändert.
+- **HR alarm limits:** unabhängig einstellbare untere (↓) und obere (↑)
+ Herzfrequenzgrenze in /min. Ein leeres Eingabefeld (**OFF**) deaktiviert
+ die jeweilige Grenze. Zulässig sind 0–240; die untere Grenze darf die obere
+ nicht überschreiten.
+- **Apply** übernimmt beide Alarmgrenzen und die Ableitung gemeinsam;
+ **Cancel** oder **Esc** verwirft die noch nicht übernommenen Eingaben.
+
+Die Einstellungen werden mit der Admin-Oberfläche synchronisiert. Eine am
+Monitor geänderte Alarmgrenze schaltet die Alarmvoreinstellung auf **Custom**.
+Auch in der Admin-Oberfläche ist die EKG-Ableitung auswählbar. Andere
+Monitorparameter besitzen vorerst noch keine berührungsempfindlichen Menüs.
+
## Thoraxkompressionen (v0.5.4)
Im Admin-Bereich **Chest compressions** startet die grüne Schaltfläche
@@ -506,3 +533,12 @@ untersten Zeile stehen vier gleich breite Bereiche: CO/CI, SVRI/GEDI/ELWI,
ein vollständig leerer Platzhalter und NIBP. Die ersten beiden Bereiche
zeigen derzeit nur ihre Bezeichnungen. Wird NIBP ausgeblendet, bleibt die
untere Zeile bestehen. Das Simulationsverhalten ist unverändert.
+
+### v0.5.8 – EKG-Bedienung am Monitor
+
+Mit einem Fingertipp oder Mausklick auf die EKG-Kurve oder das numerische
+HF-Feld öffnet sich ein monitorähnliches Einstellfenster. Darin können
+EKG-Ableitung und untere/obere HF-Alarmgrenze verändert werden. Eingaben
+werden geprüft und mit dem Admin-Fenster synchronisiert. Die geänderte
+Kurvenpolarität ist eine schematische Darstellung ohne diagnostischen
+Anspruch; die zugrunde liegende Rhythmus- und Pulssimulation bleibt gleich.
diff --git a/README.md b/README.md
index fe6cac3..05cd987 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
-# Patient Monitor Simulation (PaMSim) — v0.5.7
+# Patient Monitor Simulation (PaMSim) — v0.5.8
-A two-window, Rust/GTK4 patient-monitor simulator for teaching on Fedora Linux.
+A Rust/GTK4 patient-monitor simulator with two main windows for teaching on Fedora Linux.
> **Synthetic training signals only — not for clinical use.** ECG, arterial pressure,
> plethysmography and capnography are schematic mathematical approximations. The
@@ -23,6 +23,32 @@ The NIBP visibility toggle hides **only the fourth group's content**; the
bottom measurement row and other three groups remain present. Disabling one
of the four waveform channels still reflows the remaining rows above it.
+## ECG touchscreen settings (v0.5.8)
+
+Tap or click **anywhere in the ECG row**, on either the **trace (left 75%)** or
+**heart-rate readout (right 25%)**, to open a modal green-on-black ECG settings
+window above the monitor. The same interaction works when the monitor is in
+fullscreen mode. Touch/click input outside the ECG row opens no menu. Hiding
+the ECG channel also disables its touch target.
+
+The menu offers:
+
+- **ECG lead:** I, II (default), III, aVR, aVL, aVF, and V1–V6. The monitor
+ trace label changes immediately after **Apply**, and the waveform undergoes
+ an *illustrative lead-dependent gain/polarity transformation*. This is **not**
+ a diagnostic 12-lead ECG derivation; cardiac timing, HR and mechanical
+ capture do not change when the lead changes.
+- **HR alarm limits:** optional **↓ Lower** and **↑ Upper**, in bpm. Leave
+ either box empty (OFF) to disable that alarm boundary. A limit must be in
+ the range 0–240 and the lower limit must not exceed the upper limit.
+- **Apply** commits lead and limits together; **Cancel** or **Esc** discards
+ unsaved changes. Both Admin and monitor displays reflect committed changes.
+ Changing limits in the monitor marks the Admin alarm preset as **Custom**.
+
+The Admin ECG section also includes an ECG-lead selector, synchronized with
+changes made from the monitor. No settings menu is yet provided for other
+channels.
+
## Chest compressions (v0.5.4)
The **Chest compressions** Admin group provides a large **Start Chest Compressions**
@@ -527,3 +553,11 @@ row has four equally sized measurement groups: CO/CI; SVRI/GEDI/ELWI;
reserved empty; and the unchanged NIBP readout. Only headings are rendered
in the first two groups; the third has no content. NIBP can be hidden without
removing the final row. No physiological simulation behavior was modified.
+
+### v0.5.8 — ECG touchscreen controls
+
+Added a monitor-styled ECG settings window, opened by touching either the ECG
+waveform or numeric HR cell. Edits HR lower/upper alarms and displayed lead
+(I, II, III, aVR, aVL, aVF, V1–V6), with input validation and Admin sync.
+Lead changes are schematic display projections only; arrhythmia and pulse
+simulation remain unchanged.
diff --git a/src/model.rs b/src/model.rs
index 009b231..8f0e7d4 100644
--- a/src/model.rs
+++ b/src/model.rs
@@ -33,6 +33,48 @@ impl EcgRhythm {
}
}
+/// Displayed single-channel ECG lead. Synthetic morphology is lead-II-like;
+/// projection below provides illustrative polarity/gain, not a 12-lead model.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum EcgLead {
+ I, II, III, AVR, AVL, AVF, V1, V2, V3, V4, V5, V6,
+}
+
+impl EcgLead {
+ pub const LABELS: &'static [&'static str] = &[
+ "I", "II", "III", "aVR", "aVL", "aVF", "V1", "V2", "V3", "V4", "V5", "V6",
+ ];
+
+ pub fn from_index(index: u32) -> Self {
+ match index {
+ 0 => Self::I, 2 => Self::III, 3 => Self::AVR, 4 => Self::AVL,
+ 5 => Self::AVF, 6 => Self::V1, 7 => Self::V2, 8 => Self::V3,
+ 9 => Self::V4, 10 => Self::V5, 11 => Self::V6, _ => Self::II,
+ }
+ }
+
+ pub fn index(self) -> u32 {
+ match self {
+ Self::I => 0, Self::II => 1, Self::III => 2, Self::AVR => 3,
+ Self::AVL => 4, Self::AVF => 5, Self::V1 => 6, Self::V2 => 7,
+ Self::V3 => 8, Self::V4 => 9, Self::V5 => 10, Self::V6 => 11,
+ }
+ }
+
+ pub fn label(self) -> &'static str { Self::LABELS[self.index() as usize] }
+
+ /// Illustrative polarity and voltage gain relative to lead II. This changes
+ /// only the trace, never ECG event timing or mechanical capture.
+ pub fn display_gain(self) -> f64 {
+ match self {
+ Self::I => 0.82, Self::II => 1.0, Self::III => 0.67,
+ Self::AVR => -0.85, Self::AVL => 0.52, Self::AVF => 0.75,
+ Self::V1 => -0.75, Self::V2 => -0.38, Self::V3 => 0.52,
+ Self::V4 => 1.08, Self::V5 => 1.0, Self::V6 => 0.83,
+ }
+ }
+}
+
/// Pulse-oximeter availability and technical alarms. Sensor loss takes precedence.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Spo2Status {
@@ -228,6 +270,7 @@ pub struct Parameters {
pub chest_compressions_active: bool,
pub chest_compression_quality: ChestCompressionQuality,
pub ecg_rhythm: EcgRhythm,
+ pub ecg_lead: EcgLead, // ECG trace label and illustrative lead projection
pub heart_rate: i32, // bpm, organized electrical rate; not mechanical pulse rate
pub pulse_conduction: PulseConduction,
pub spo2: i32, // %; instructor-set nominal saturation
@@ -305,6 +348,7 @@ impl Default for Parameters {
chest_compressions_active: false,
chest_compression_quality: ChestCompressionQuality::Adequate,
ecg_rhythm: EcgRhythm::Sinus,
+ ecg_lead: EcgLead::II,
heart_rate: 75,
pulse_conduction: PulseConduction::OneToOne,
spo2: 98,
@@ -351,6 +395,21 @@ mod tests {
assert_eq!(ChestCompressionQuality::Bad.peak_range(), None);
}
+ #[test]
+ fn ecg_lead_defaults_to_ii_and_selection_is_bijective() {
+ let p = Parameters::default();
+ assert_eq!(p.ecg_lead, EcgLead::II);
+ assert_eq!(p.ecg_lead.label(), "II");
+ for index in 0..EcgLead::LABELS.len() as u32 {
+ let lead = EcgLead::from_index(index);
+ assert_eq!(lead.index(), index);
+ assert_eq!(lead.label(), EcgLead::LABELS[index as usize]);
+ }
+ assert_eq!(EcgLead::from_index(999), EcgLead::II);
+ assert!(EcgLead::AVR.display_gain() < 0.0);
+ assert_eq!(EcgLead::II.display_gain(), 1.0);
+ }
+
#[test]
fn mean_pressure_uses_one_third_pulse_pressure() {
assert_eq!(mean_arterial_pressure(120, 75), 90);
diff --git a/src/render.rs b/src/render.rs
index cb62a42..efb8cf2 100644
--- a/src/render.rs
+++ b/src/render.rs
@@ -67,7 +67,10 @@ pub fn draw(cr: &Context, width: i32, height: i32, p: &Parameters, sim: &Simulat
let top = header + index as f64 * row_height;
let bottom = top + row_height;
stroke_line(cr, pad, bottom, w - pad, bottom, MUTED, 0.65);
- text(cr, title, trace_left + 4.0, top + row_height * 0.17,
+ let displayed_title = if matches!(channel, Channel::Ecg) {
+ format!("{} / ECG", p.ecg_lead.label())
+ } else { title.to_owned() };
+ text(cr, &displayed_title, trace_left + 4.0, top + row_height * 0.17,
(row_height * 0.11).clamp(10.0, 17.0), color, false);
draw_trace(cr, channel, color, trace_left, trace_right,
top + row_height * 0.25, bottom - row_height * 0.06, p, sim);
@@ -82,6 +85,20 @@ pub fn draw(cr: &Context, width: i32, height: i32, p: &Parameters, sim: &Simulat
numeric_width, p, sim);
}
+/// Same geometry as the Cairo renderer: the full first ECG row (waveform
+/// and numeric region) is one target for touch, pen, or mouse interaction.
+/// Hidden ECG is never interactive; other rows and the header are excluded.
+pub fn ecg_hit_test(x: f64, y: f64, width: i32, height: i32, p: &Parameters) -> bool {
+ if !p.show_ecg { return false; }
+ let w = f64::from(width.max(1));
+ let h = f64::from(height.max(1));
+ let pad = (w.min(h) * 0.018).clamp(6.0, 20.0);
+ let header = (h * 0.083).clamp(32.0, 68.0);
+ let body_height = (h - header - pad).max(20.0);
+ let (row_height, _) = monitor_rows(header, body_height, visible_channels(p).len());
+ x >= pad && x <= w - pad && y >= header && y < header + row_height
+}
+
/// Left/right split and the width of each bottom-row group. Outer margins
/// are excluded, so 75% / 25% holds at all window sizes (no width clamping).
fn monitor_columns(window_width: f64, pad: f64) -> (f64, f64) {
@@ -497,7 +514,7 @@ fn draw_trace(cr: &Context, channel: Channel, color: Color,
fn normalized(channel: Channel, s: &Sample, p: &Parameters) -> f64 {
match channel {
- Channel::Ecg => (0.40 + s.ecg * 0.38).clamp(0.02, 0.98),
+ Channel::Ecg => (0.40 + s.ecg * p.ecg_lead.display_gain() * 0.38).clamp(0.02, 0.98),
Channel::Pleth => (0.10 + pleth_visual_amplitude(s.pleth, s.time, s.pleth_quality) * 0.78)
.clamp(0.02, 0.98),
Channel::Art => (s.art / 200.0).clamp(0.0, 1.0),
@@ -636,6 +653,36 @@ mod tests {
assert_eq!(p.alarms.spo2, AlarmLimits::default());
}
+ #[test]
+ fn ecg_touch_target_covers_curve_and_hr_and_reflows() {
+ let mut p = Parameters::default();
+ assert!(!ecg_hit_test(100.0, 20.0, 1200, 760, &p)); // header
+ assert!(ecg_hit_test(140.0, 110.0, 1200, 760, &p)); // curve
+ assert!(ecg_hit_test(1080.0, 110.0, 1200, 760, &p)); // HR numbers
+ assert!(!ecg_hit_test(140.0, 300.0, 1200, 760, &p)); // next channel
+ assert!(!ecg_hit_test(1.0, 110.0, 1200, 760, &p)); // outside padding
+ p.show_spo2 = false;
+ p.show_art = false;
+ p.show_capno = false;
+ assert!(ecg_hit_test(900.0, 300.0, 1200, 760, &p));
+ p.show_ecg = false;
+ assert!(!ecg_hit_test(900.0, 110.0, 1200, 760, &p));
+ }
+
+ #[test]
+ fn displayed_ecg_lead_changes_polarity_without_touching_sample() {
+ let mut p = Parameters::default();
+ let s = Sample { time: 0.0, ecg: 1.0, pleth: 0.0,
+ pleth_valid: true, pleth_quality: Spo2Quality::Good,
+ art: 0.0, co2: 0.0 };
+ let lead_ii = normalized(Channel::Ecg, &s, &p);
+ p.ecg_lead = crate::model::EcgLead::AVR;
+ let lead_avr = normalized(Channel::Ecg, &s, &p);
+ assert!(lead_ii > 0.40);
+ assert!(lead_avr < 0.40);
+ assert_eq!(s.ecg, 1.0);
+ }
+
#[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 ffb8579..724bc80 100644
--- a/src/ui.rs
+++ b/src/ui.rs
@@ -10,11 +10,14 @@ use gtk::{Application, ApplicationWindow, Orientation};
use crate::alarm::{self, AlarmAudio};
use crate::model::{AlarmLimits, AlarmSettings, ArterialShape, CapnoShape,
- ChestCompressionQuality, EcgRhythm, Parameters, PulseConduction, Spo2Quality};
+ ChestCompressionQuality, EcgLead, EcgRhythm, Parameters, PulseConduction, Spo2Quality};
use crate::render;
use crate::simulation::Simulator;
type SharedParams = Rc<RefCell<Parameters>>;
+/// Refresh the Admin alarm widgets when a limit is changed on the monitor.
+type EcgAlarmChanged = Rc<RefCell<Option<Box<dyn Fn(AlarmLimits, EcgLead, bool)>>>>;
+type EcgMenuHandle = Rc<RefCell<Option<glib::WeakRef<gtk::Window>>>>;
// Match the RGB colors of the monitor traces (see render.rs).
// NIBP shares the arterial-pressure red; capnography is light grey.
@@ -28,8 +31,12 @@ pub fn create_windows(app: &Application) {
let parameters = Rc::new(RefCell::new(Parameters::default()));
let simulator = Rc::new(RefCell::new(Simulator::new(&parameters.borrow())));
let audio = Rc::new(RefCell::new(AlarmAudio::new()));
- let monitor = create_monitor(app, parameters.clone(), simulator.clone());
- let admin = create_admin(app, parameters.clone(), simulator.clone(), &monitor, audio.clone());
+ install_ecg_menu_style();
+ let ecg_alarm_changed: EcgAlarmChanged = Rc::new(RefCell::new(None));
+ let monitor = create_monitor(app, parameters.clone(), simulator.clone(),
+ ecg_alarm_changed.clone());
+ let admin = create_admin(app, parameters.clone(), simulator.clone(), &monitor,
+ audio.clone(), ecg_alarm_changed);
// Alarm evaluation has its own 100-ms timer; waveform drawing never blocks
// on sound playback. Audio also continues if the monitor is not mapped.
@@ -46,7 +53,8 @@ pub fn create_windows(app: &Application) {
}
fn create_monitor(app: &Application, params: SharedParams,
- simulator: Rc<RefCell<Simulator>>) -> ApplicationWindow {
+ simulator: Rc<RefCell<Simulator>>,
+ ecg_alarm_changed: EcgAlarmChanged) -> ApplicationWindow {
let window = ApplicationWindow::builder()
.application(app)
.title(concat!("Patient Monitor — Simulation v", env!("CARGO_PKG_VERSION")))
@@ -96,6 +104,28 @@ fn create_monitor(app: &Application, params: SharedParams,
}
});
window.add_controller(keys);
+
+ // A single touch/mouse target covers the entire ECG row (trace and HR).
+ // GTK's gesture handles Wayland touch and pointer events alike.
+ let ecg_menu: EcgMenuHandle = Rc::new(RefCell::new(None));
+ let click = gtk::GestureClick::new();
+ click.connect_released({
+ let app = app.clone();
+ let window = window.clone();
+ let canvas = canvas.clone();
+ let params = params.clone();
+ move |_gesture, _press_count, x, y| {
+ let ecg_touched = {
+ let p = params.borrow();
+ render::ecg_hit_test(x, y, canvas.width(), canvas.height(), &p)
+ };
+ if ecg_touched {
+ open_ecg_menu(&app, &window, params.clone(),
+ ecg_alarm_changed.clone(), ecg_menu.clone());
+ }
+ }
+ });
+ canvas.add_controller(click);
window.set_child(Some(&canvas));
window
}
@@ -103,7 +133,8 @@ fn create_monitor(app: &Application, params: SharedParams,
fn create_admin(app: &Application, params: SharedParams,
simulator: Rc<RefCell<Simulator>>,
monitor: &ApplicationWindow,
- audio: Rc<RefCell<AlarmAudio>>) -> ApplicationWindow {
+ audio: Rc<RefCell<AlarmAudio>>,
+ ecg_alarm_changed: EcgAlarmChanged) -> ApplicationWindow {
let window = ApplicationWindow::builder()
.application(app)
.title(concat!("Patient Monitor — Admin v", env!("CARGO_PKG_VERSION")))
@@ -243,6 +274,10 @@ fn create_admin(app: &Application, params: SharedParams,
let ecg = group(&controls, "ECG", Some(ECG_GREEN));
add_visibility(&ecg, params.borrow().show_ecg, params.clone(), |p, show| p.show_ecg = show);
+ let lead_dropdown = add_dropdown_at(&ecg, "ECG lead", EcgLead::LABELS,
+ params.borrow().ecg_lead.index(), params.clone(), |p, selected| {
+ p.ecg_lead = EcgLead::from_index(selected);
+ });
let rhythm_dropdown = add_dropdown_at(&ecg, "ECG rhythm", &[
"Sinus rhythm", "Atrial fibrillation", "Ventricular tachycardia (VT)",
"Pulseless ventricular tachycardia (PVT)", "Ventricular fibrillation", "Asystole",
@@ -267,9 +302,10 @@ fn create_admin(app: &Application, params: SharedParams,
hr_entry.set_text("160");
}
});
- alarm_editors.push((add_alarm_limits(&hr_row, "", "", 240,
+ let hr_alarm_editor = add_alarm_limits(&hr_row, "", "", 240,
params.borrow().alarms.hr, params.clone(), |p, v| p.alarms.hr = v,
- &preset_dropdown, &updating_preset), |s| s.hr));
+ &preset_dropdown, &updating_preset);
+ alarm_editors.push((hr_alarm_editor.clone(), |s| s.hr));
let spo2 = group(&controls, "Pulse oximetry", Some(SPO2_YELLOW));
add_visibility(&spo2, params.borrow().show_spo2, params.clone(), |p, show| p.show_spo2 = show);
@@ -461,6 +497,22 @@ ART and pleth are delayed. VT can be perfusing; PVT, VF and asystole are pulsele
}
});
+ // Monitor settings are shared with Admin. Updating the HR alarm from the
+ // ECG menu refreshes the visible alarm boxes and marks the preset Custom.
+ *ecg_alarm_changed.borrow_mut() = Some(Box::new({
+ let preset_dropdown = preset_dropdown.clone();
+ let updating_preset = updating_preset.clone();
+ move |limits: AlarmLimits, lead: EcgLead, alarm_changed: bool| {
+ if alarm_changed {
+ updating_preset.set(true);
+ hr_alarm_editor.set_limits(limits);
+ updating_preset.set(false);
+ preset_dropdown.set_selected(0);
+ }
+ lead_dropdown.set_selected(lead.index());
+ }
+ }));
+
scroller.set_child(Some(&controls));
main_box.append(&scroller);
@@ -487,6 +539,163 @@ ART and pleth are delayed. VT can be perfusing; PVT, VF and asystole are pulsele
window
}
+/// Dark ECG control panel matching the green-on-black bedside monitor.
+/// Installed only once, with a CSS class scoped to this popup.
+fn install_ecg_menu_style() {
+ if let Some(display) = gdk::Display::default() {
+ let provider = gtk::CssProvider::new();
+ provider.load_from_data(
+ "window.ecg-settings { background-color: #000000; }
+ window.ecg-settings box { background-color: #000000; }
+ window.ecg-settings label { color: #42ff63; }
+ window.ecg-settings label.menu-error { color: #ff4d50; }
+ window.ecg-settings entry { color: #42ff63; background-color: #101b13;
+ border: 1px solid #377547; min-height: 42px; }
+ window.ecg-settings dropdown { color: #42ff63; background-color: #101b13;
+ min-height: 44px; }
+ window.ecg-settings button { min-height: 44px; }
+ window.ecg-settings button.ecg-apply { color: #000000;
+ background-image: none; background-color: #42ff63; font-weight: bold; }
+ window.ecg-settings button.ecg-close { color: #42ff63;
+ background-image: none; background-color: #152219; }"
+ );
+ gtk::style_context_add_provider_for_display(
+ &display, &provider, gtk::STYLE_PROVIDER_PRIORITY_APPLICATION);
+ }
+}
+
+/// Displayed only for touches in the ECG row. The monitor window can remain
+/// fullscreen. The dialog is modal to that monitor, including on Wayland.
+fn open_ecg_menu(app: &Application, monitor: &ApplicationWindow,
+ params: SharedParams, on_change: EcgAlarmChanged,
+ open_menu: EcgMenuHandle) {
+ if let Some(existing) = open_menu.borrow().as_ref().and_then(|weak| weak.upgrade()) {
+ existing.present();
+ return;
+ }
+ let (limits, lead) = {
+ let p = params.borrow();
+ (p.alarms.hr, p.ecg_lead)
+ };
+ let dialog = gtk::Window::builder()
+ .application(app)
+ .title("ECG settings")
+ .transient_for(monitor)
+ .modal(true)
+ .resizable(false)
+ .default_width(450)
+ .default_height(340)
+ .build();
+ dialog.add_css_class("ecg-settings");
+ dialog.set_decorated(false);
+ *open_menu.borrow_mut() = Some(dialog.downgrade());
+
+ let content = gtk::Box::new(Orientation::Vertical, 15);
+ content.set_margin_top(22);
+ content.set_margin_bottom(22);
+ content.set_margin_start(22);
+ content.set_margin_end(22);
+ let title = gtk::Label::new(Some("ECG / SETTINGS"));
+ title.set_xalign(0.0);
+ title.add_css_class("title-2");
+ content.append(&title);
+ content.append(&gtk::Separator::new(Orientation::Horizontal));
+
+ let lead_row = gtk::Box::new(Orientation::Horizontal, 12);
+ let lead_label = gtk::Label::new(Some("ECG lead"));
+ lead_label.set_xalign(0.0);
+ lead_label.set_width_chars(13);
+ let lead_selector = gtk::DropDown::from_strings(EcgLead::LABELS);
+ lead_selector.set_selected(lead.index());
+ lead_selector.set_hexpand(true);
+ lead_row.append(&lead_label);
+ lead_row.append(&lead_selector);
+ content.append(&lead_row);
+
+ let limits_header = gtk::Label::new(Some("HR alarm limits · bpm"));
+ limits_header.set_xalign(0.0);
+ content.append(&limits_header);
+ let limits_row = gtk::Box::new(Orientation::Horizontal, 10);
+ let lower = alarm_entry(limits.lower, "OFF");
+ let upper = alarm_entry(limits.upper, "OFF");
+ lower.set_hexpand(true);
+ upper.set_hexpand(true);
+ limits_row.append(&gtk::Label::new(Some("↓ Lower")));
+ limits_row.append(&lower);
+ limits_row.append(&gtk::Label::new(Some("↑ Upper")));
+ limits_row.append(&upper);
+ content.append(&limits_row);
+
+ let hint = gtk::Label::new(Some(
+ "Leave either limit empty to disable that alarm boundary."
+ ));
+ hint.set_wrap(true);
+ hint.set_xalign(0.0);
+ content.append(&hint);
+
+ let error = gtk::Label::new(None);
+ error.add_css_class("menu-error");
+ error.set_xalign(0.0);
+ error.set_wrap(true);
+ content.append(&error);
+
+ let buttons = gtk::Box::new(Orientation::Horizontal, 12);
+ buttons.set_halign(gtk::Align::End);
+ let cancel = gtk::Button::with_label("Cancel");
+ cancel.add_css_class("ecg-close");
+ cancel.connect_clicked({
+ let weak = dialog.downgrade();
+ move |_| { if let Some(window) = weak.upgrade() { window.close(); } }
+ });
+ let apply = gtk::Button::with_label("Apply");
+ apply.add_css_class("ecg-apply");
+ apply.connect_clicked({
+ let weak = dialog.downgrade();
+ move |_| {
+ let (Ok(lo), Ok(hi)) = (
+ parse_alarm_bound(&lower, 240), parse_alarm_bound(&upper, 240)
+ ) else {
+ error.set_text("Alarm limits must be 0–240 bpm, or blank (OFF).");
+ return;
+ };
+ let new_limits = AlarmLimits { lower: lo, upper: hi };
+ if !new_limits.valid() {
+ error.set_text("The lower limit must not exceed the upper limit.");
+ return;
+ }
+ let new_lead = EcgLead::from_index(lead_selector.selected());
+ let alarm_changed = {
+ let mut p = params.borrow_mut();
+ let changed = p.alarms.hr != new_limits;
+ p.ecg_lead = new_lead;
+ p.alarms.hr = new_limits;
+ changed
+ };
+ if let Some(callback) = on_change.borrow().as_ref() {
+ callback(new_limits, new_lead, alarm_changed);
+ }
+ if let Some(window) = weak.upgrade() { window.close(); }
+ }
+ });
+ buttons.append(&cancel);
+ buttons.append(&apply);
+ content.append(&buttons);
+ dialog.set_child(Some(&content));
+
+ let escape = gtk::EventControllerKey::new();
+ escape.connect_key_pressed({
+ let weak = dialog.downgrade();
+ move |_, key, _, _| {
+ if key == gdk::Key::Escape {
+ if let Some(window) = weak.upgrade() { window.close(); }
+ glib::Propagation::Stop
+ } else { glib::Propagation::Proceed }
+ }
+ });
+ dialog.add_controller(escape);
+ dialog.present();
+}
+
/// Frame a parameter section with an optional monitor-colored left sidebar.
/// A DrawingArea keeps the color independent of the user's GTK theme/CSS.
fn group(parent: &gtk::Box, title: &str, accent: Option<AccentColor>) -> gtk::Box {
@@ -619,6 +828,7 @@ fn normalize_entry(entry: &gtk::Entry, slider: &gtk::Scale, min: i32, max: i32)
}
/// Two entries for one alarm; retained so presets can update visible inputs.
+#[derive(Clone)]
struct AlarmEditor {
lower: gtk::Entry,
upper: gtk::Entry,

View file

@ -0,0 +1,420 @@
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "patient-monitor-simulation"
-version = "0.5.8"
+version = "0.5.9"
edition = "2021"
license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"
--- a/README.de.md
+++ b/README.de.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.5.8
+# Patient Monitor Simulation (PaMSim) — v0.5.9
Ein mit Rust und GTK4 entwickelter Patient*innenmonitor-Simulator mit zwei Fenstern für die Lehre unter Fedora Linux.
@@ -26,10 +26,10 @@
Beim Ausblenden anderer Parameter werden die verbleibenden Kurvenzeilen wie
bisher dynamisch verteilt.
-## EKG-Bedienung direkt am Monitor (v0.5.8)
+## EKG-Bedienung direkt am Monitor (v0.5.9)
Durch Berühren oder Anklicken der **EKG-Zeile** öffnet sich ein eigenes
-Einstellfenster mit **grüner Schrift auf schwarzem Hintergrund**. Die gesamte
+Einstellfenster mit **hellgrauer Schrift auf schwarzem Hintergrund**. Die gesamte
EKG-Zeile ist aktiv, sowohl die Kurve links (75 %) als auch das numerische
Herzfrequenzfeld rechts (25 %). Die Bedienung ist auch im Vollbildmodus möglich.
Bei ausgeblendetem EKG ist die Interaktionsfläche deaktiviert.
@@ -42,11 +42,17 @@
eine klinisch validierte 12-Kanal-EKG-Ableitung. Frequenz, QRS-Zeitpunkte
und mechanische Pulskopplung bleiben unverändert.
- **HR alarm limits:** unabhängig einstellbare untere (↓) und obere (↑)
- Herzfrequenzgrenze in /min. Ein leeres Eingabefeld (**OFF**) deaktiviert
- die jeweilige Grenze. Zulässig sind 0–240; die untere Grenze darf die obere
- nicht überschreiten.
+ Herzfrequenzgrenze in /min. Große Tasten **− / +** ändern den jeweiligen
+ Grenzwert in **5er-Schritten** zwischen 0 und 240. Mit **OFF** lässt sich
+ jede Grenze einzeln deaktivieren; **ON** aktiviert den vorherigen Wert
+ erneut (bei anfänglich nicht gesetzten Werten 60 bzw. 100 /min).
+ Die untere Grenze darf die obere nicht überschreiten.
- **Apply** übernimmt beide Alarmgrenzen und die Ableitung gemeinsam;
**Cancel** oder **Esc** verwirft die noch nicht übernommenen Eingaben.
+
+Die Bedienelemente sind ohne Tastatur verwendbar. Schmale hellgraue
+Begrenzungslinien und Trennlinien orientieren sich an der Gestaltung des
+Monitors; die EKG-spezifische grüne Textfarbe wird hier nicht verwendet.
Die Einstellungen werden mit der Admin-Oberfläche synchronisiert. Eine am
Monitor geänderte Alarmgrenze schaltet die Alarmvoreinstellung auf **Custom**.
@@ -542,3 +548,13 @@
werden geprüft und mit dem Admin-Fenster synchronisiert. Die geänderte
Kurvenpolarität ist eine schematische Darstellung ohne diagnostischen
Anspruch; die zugrunde liegende Rhythmus- und Pulssimulation bleibt gleich.
+
+### v0.5.9 – Berührungsoptimiertes EKG-Einstellfenster
+
+Hellgraue Bedienelemente auf schwarzem Hintergrund, eine dezente umlaufende
+Rahmenlinie und 0,8 Pixel breite Trennlinien im Stil des Hauptmonitors.
+Die unteren und oberen HF-Alarmgrenzen werden am Monitor ohne Tastatur über
+große **−/+**-Tasten in 5er-Schritten und über **ON/OFF** eingestellt.
+Die Ableitung wird weiterhin über das Auswahlmenü gewählt. Änderungen
+werden erst mit **Apply** übernommen; **Cancel** verwirft sie.
+Keine Änderungen an den simulierten Vitalparametern.
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.5.8
+# Patient Monitor Simulation (PaMSim) — v0.5.9
A Rust/GTK4 patient-monitor simulator with two main windows for teaching on Fedora Linux.
@@ -23,10 +23,10 @@
bottom measurement row and other three groups remain present. Disabling one
of the four waveform channels still reflows the remaining rows above it.
-## ECG touchscreen settings (v0.5.8)
+## ECG touchscreen settings (v0.5.9)
Tap or click **anywhere in the ECG row**, on either the **trace (left 75%)** or
-**heart-rate readout (right 25%)**, to open a modal green-on-black ECG settings
+**heart-rate readout (right 25%)**, to open a modal **black-and-light-grey ECG settings**
window above the monitor. The same interaction works when the monitor is in
fullscreen mode. Touch/click input outside the ECG row opens no menu. Hiding
the ECG channel also disables its touch target.
@@ -38,12 +38,19 @@
an *illustrative lead-dependent gain/polarity transformation*. This is **not**
a diagnostic 12-lead ECG derivation; cardiac timing, HR and mechanical
capture do not change when the lead changes.
-- **HR alarm limits:** optional **↓ Lower** and **↑ Upper**, in bpm. Leave
- either box empty (OFF) to disable that alarm boundary. A limit must be in
- the range 0–240 and the lower limit must not exceed the upper limit.
+- **HR alarm limits:** optional **↓ Lower** and **↑ Upper**, in bpm.
+ Each limit has large **− / +** touch buttons that adjust the value in
+ **5 bpm steps** (range 0–240), plus an **OFF** button to disable it.
+ When disabled, an **ON** button restores its previous value (or 60 bpm
+ for an unset lower limit and 100 bpm for an unset upper limit).
+ The lower limit must not exceed the upper limit.
- **Apply** commits lead and limits together; **Cancel** or **Esc** discards
unsaved changes. Both Admin and monitor displays reflect committed changes.
Changing limits in the monitor marks the Admin alarm preset as **Custom**.
+
+The menu uses light-grey text instead of the ECG waveform color and
+subtle separators matching the main monitor divider thickness. No keyboard
+is required for the ECG menu; the Admin window retains numeric text inputs.
The Admin ECG section also includes an ECG-lead selector, synchronized with
changes made from the monitor. No settings menu is yet provided for other
@@ -561,3 +568,12 @@
(I, II, III, aVR, aVL, aVF, V1–V6), with input validation and Admin sync.
Lead changes are schematic display projections only; arrhythmia and pulse
simulation remain unchanged.
+
+### v0.5.9 — Touch-optimized ECG settings
+
+Restyled the ECG settings window with light-grey text/controls, a neutral
+0.8-pixel outer border and thin 0.8-pixel Cairo separators matching the
+monitor. Replaced the on-monitor HR limit text entries with large 5-bpm
+**−/+** buttons and independent **ON/OFF** controls; the ECG lead remains a
+touch-selectable dropdown. Pending changes still require Apply, and Cancel
+leaves the shared parameters unchanged. No signal generation was altered.
--- a/src/ui.rs
+++ b/src/ui.rs
@@ -539,29 +539,144 @@
window
}
-/// Dark ECG control panel matching the green-on-black bedside monitor.
-/// Installed only once, with a CSS class scoped to this popup.
+/// Neutral black-and-light-grey ECG control panel. Match the monitor's
+/// MUTED divider color, with 0.8-pixel outer borders and 0.8-pixel Cairo
+/// dividers (the same thickness as the main monitor header divider).
fn install_ecg_menu_style() {
if let Some(display) = gdk::Display::default() {
let provider = gtk::CssProvider::new();
provider.load_from_data(
"window.ecg-settings { background-color: #000000; }
- window.ecg-settings box { background-color: #000000; }
- window.ecg-settings label { color: #42ff63; }
- window.ecg-settings label.menu-error { color: #ff4d50; }
- window.ecg-settings entry { color: #42ff63; background-color: #101b13;
- border: 1px solid #377547; min-height: 42px; }
- window.ecg-settings dropdown { color: #42ff63; background-color: #101b13;
- min-height: 44px; }
- window.ecg-settings button { min-height: 44px; }
- window.ecg-settings button.ecg-apply { color: #000000;
- background-image: none; background-color: #42ff63; font-weight: bold; }
- window.ecg-settings button.ecg-close { color: #42ff63;
- background-image: none; background-color: #152219; }"
+ window.ecg-settings box.ecg-panel {
+ background-color: #000000; border: 0.8px solid #6b757d;
+ }
+ window.ecg-settings label { color: #e5e9eb; }
+ window.ecg-settings label.menu-error { color: #ff8080; }
+ window.ecg-settings label.ecg-limit-value {
+ color: #e5e9eb; font-weight: bold; font-size: 19px;
+ }
+ window.ecg-settings dropdown {
+ color: #e5e9eb; background-color: #141414;
+ border: 1px solid #6b757d; min-height: 48px;
+ }
+ window.ecg-settings dropdown button {
+ color: #e5e9eb; background-color: #141414;
+ }
+ window.ecg-settings button {
+ color: #e5e9eb; background-image: none;
+ background-color: #171717; border: 1px solid #6b757d;
+ min-height: 48px; min-width: 52px;
+ }
+ window.ecg-settings button:hover { background-color: #303437; }
+ window.ecg-settings button.ecg-apply {
+ color: #000000; background-color: #e5e9eb; font-weight: bold;
+ }
+ window.ecg-settings button.ecg-close { background-color: #171717; }"
);
gtk::style_context_add_provider_for_display(
&display, &provider, gtk::STYLE_PROVIDER_PRIORITY_APPLICATION);
}
+}
+
+/// Cairo divider with the same line thickness and color as the bedside
+/// monitor's header separator (render.rs: MUTED, 0.8 logical pixels).
+fn ecg_menu_divider() -> gtk::DrawingArea {
+ let separator = gtk::DrawingArea::new();
+ separator.set_hexpand(true);
+ separator.set_content_height(2);
+ separator.set_draw_func(|_area, cr, width, height| {
+ cr.set_source_rgb(0.42, 0.46, 0.49);
+ cr.set_line_width(0.8);
+ let y = f64::from(height) / 2.0;
+ cr.move_to(0.0, y);
+ cr.line_to(f64::from(width), y);
+ let _ = cr.stroke();
+ });
+ separator
+}
+
+const TOUCH_HR_STEP: i32 = 5;
+const MAX_HR_ALARM: i32 = 240;
+
+/// When a limit is OFF, either +/- first restores its previous value (or
+/// a sensible initial value). Subsequent presses adjust it by 5 bpm.
+fn stepped_hr_limit(current: Option<i32>, last_enabled: i32, direction: i32) -> i32 {
+ current.map_or(last_enabled, |value| {
+ (value + TOUCH_HR_STEP * direction).clamp(0, MAX_HR_ALARM)
+ })
+}
+
+fn show_touch_hr_limit(value: Option<i32>, number: &gtk::Label,
+ toggle: &gtk::Button) {
+ number.set_text(&value.map_or("OFF".to_owned(), |v| v.to_string()));
+ toggle.set_label(if value.is_some() { "OFF" } else { "ON" });
+}
+
+/// Large, keyboard-free +/- and ON/OFF controls. Returning a Cell permits
+/// Apply to read the draft value without changing the shared configuration.
+fn ecg_touch_limit(parent: &gtk::Box, caption: &str,
+ initial: Option<i32>, default: i32) -> Rc<Cell<Option<i32>>> {
+ let state = Rc::new(Cell::new(initial));
+ let previous = Rc::new(Cell::new(initial.unwrap_or(default)));
+ let row = gtk::Box::new(Orientation::Horizontal, 10);
+
+ let heading = gtk::Label::new(Some(caption));
+ heading.set_xalign(0.0);
+ heading.set_width_chars(10);
+ row.append(&heading);
+
+ let minus = gtk::Button::with_label("−");
+ minus.set_tooltip_text(Some("Decrease alarm limit by 5 bpm"));
+ minus.set_size_request(54, 50);
+ row.append(&minus);
+
+ let display = gtk::Label::new(None);
+ display.add_css_class("ecg-limit-value");
+ display.set_width_chars(5);
+ display.set_xalign(0.5);
+ row.append(&display);
+
+ let plus = gtk::Button::with_label("+");
+ plus.set_tooltip_text(Some("Increase alarm limit by 5 bpm"));
+ plus.set_size_request(54, 50);
+ row.append(&plus);
+
+ let enable_toggle = gtk::Button::new();
+ enable_toggle.set_tooltip_text(Some("Enable or disable this alarm limit"));
+ enable_toggle.set_size_request(78, 50);
+ row.append(&enable_toggle);
+ show_touch_hr_limit(initial, &display, &enable_toggle);
+
+ for (button, direction) in [(minus, -1), (plus, 1)] {
+ let state = state.clone();
+ let previous = previous.clone();
+ let display = display.clone();
+ let enable_toggle = enable_toggle.clone();
+ button.connect_clicked(move |_| {
+ let next = stepped_hr_limit(state.get(), previous.get(), direction);
+ state.set(Some(next));
+ previous.set(next);
+ show_touch_hr_limit(Some(next), &display, &enable_toggle);
+ });
+ }
+ enable_toggle.connect_clicked({
+ let state = state.clone();
+ let previous = previous.clone();
+ let display = display.clone();
+ move |button| {
+ let new_value = match state.get() {
+ Some(value) => {
+ previous.set(value);
+ None
+ }
+ None => Some(previous.get()),
+ };
+ state.set(new_value);
+ show_touch_hr_limit(new_value, &display, button);
+ }
+ });
+ parent.append(&row);
+ state
}
/// Displayed only for touches in the ECG row. The monitor window can remain
@@ -583,23 +698,32 @@
.transient_for(monitor)
.modal(true)
.resizable(false)
- .default_width(450)
- .default_height(340)
+ .default_width(550)
+ .default_height(410)
.build();
dialog.add_css_class("ecg-settings");
dialog.set_decorated(false);
*open_menu.borrow_mut() = Some(dialog.downgrade());
- let content = gtk::Box::new(Orientation::Vertical, 15);
- content.set_margin_top(22);
- content.set_margin_bottom(22);
- content.set_margin_start(22);
- content.set_margin_end(22);
+ let content = gtk::Box::new(Orientation::Vertical, 12);
+ content.add_css_class("ecg-panel");
+ content.set_margin_top(1);
+ content.set_margin_bottom(1);
+ content.set_margin_start(1);
+ content.set_margin_end(1);
+ // Inner padding keeps controls away from the thin panel border.
+ let inner = gtk::Box::new(Orientation::Vertical, 12);
+ inner.set_margin_top(20);
+ inner.set_margin_bottom(20);
+ inner.set_margin_start(20);
+ inner.set_margin_end(20);
+ content.append(&inner);
+
let title = gtk::Label::new(Some("ECG / SETTINGS"));
title.set_xalign(0.0);
title.add_css_class("title-2");
- content.append(&title);
- content.append(&gtk::Separator::new(Orientation::Horizontal));
+ inner.append(&title);
+ inner.append(&ecg_menu_divider());
let lead_row = gtk::Box::new(Orientation::Horizontal, 12);
let lead_label = gtk::Label::new(Some("ECG lead"));
@@ -610,34 +734,27 @@
lead_selector.set_hexpand(true);
lead_row.append(&lead_label);
lead_row.append(&lead_selector);
- content.append(&lead_row);
+ inner.append(&lead_row);
+ inner.append(&ecg_menu_divider());
let limits_header = gtk::Label::new(Some("HR alarm limits · bpm"));
limits_header.set_xalign(0.0);
- content.append(&limits_header);
- let limits_row = gtk::Box::new(Orientation::Horizontal, 10);
- let lower = alarm_entry(limits.lower, "OFF");
- let upper = alarm_entry(limits.upper, "OFF");
- lower.set_hexpand(true);
- upper.set_hexpand(true);
- limits_row.append(&gtk::Label::new(Some("↓ Lower")));
- limits_row.append(&lower);
- limits_row.append(&gtk::Label::new(Some("↑ Upper")));
- limits_row.append(&upper);
- content.append(&limits_row);
-
+ inner.append(&limits_header);
+ let lower = ecg_touch_limit(&inner, "↓ Lower", limits.lower, 60);
+ let upper = ecg_touch_limit(&inner, "↑ Upper", limits.upper, 100);
let hint = gtk::Label::new(Some(
- "Leave either limit empty to disable that alarm boundary."
+ "+/− adjusts by 5 bpm. OFF disables the limit; ON restores it."
));
hint.set_wrap(true);
hint.set_xalign(0.0);
- content.append(&hint);
+ inner.append(&hint);
+ inner.append(&ecg_menu_divider());
let error = gtk::Label::new(None);
error.add_css_class("menu-error");
error.set_xalign(0.0);
error.set_wrap(true);
- content.append(&error);
+ inner.append(&error);
let buttons = gtk::Box::new(Orientation::Horizontal, 12);
buttons.set_halign(gtk::Align::End);
@@ -652,13 +769,7 @@
apply.connect_clicked({
let weak = dialog.downgrade();
move |_| {
- let (Ok(lo), Ok(hi)) = (
- parse_alarm_bound(&lower, 240), parse_alarm_bound(&upper, 240)
- ) else {
- error.set_text("Alarm limits must be 0–240 bpm, or blank (OFF).");
- return;
- };
- let new_limits = AlarmLimits { lower: lo, upper: hi };
+ let new_limits = AlarmLimits { lower: lower.get(), upper: upper.get() };
if !new_limits.valid() {
error.set_text("The lower limit must not exceed the upper limit.");
return;
@@ -679,7 +790,7 @@
});
buttons.append(&cancel);
buttons.append(&apply);
- content.append(&buttons);
+ inner.append(&buttons);
dialog.set_child(Some(&content));
let escape = gtk::EventControllerKey::new();
@@ -694,6 +805,25 @@
});
dialog.add_controller(escape);
dialog.present();
+}
+
+#[cfg(test)]
+mod ecg_touch_menu_tests {
+ use super::*;
+
+ #[test]
+ fn touch_step_uses_five_bpm_and_respects_bounds() {
+ assert_eq!(stepped_hr_limit(Some(60), 60, 1), 65);
+ assert_eq!(stepped_hr_limit(Some(60), 60, -1), 55);
+ assert_eq!(stepped_hr_limit(Some(240), 240, 1), 240);
+ assert_eq!(stepped_hr_limit(Some(0), 0, -1), 0);
+ }
+
+ #[test]
+ fn disabled_alarm_reenables_at_last_saved_value() {
+ assert_eq!(stepped_hr_limit(None, 60, 1), 60);
+ assert_eq!(stepped_hr_limit(None, 100, -1), 100);
+ }
}
/// Frame a parameter section with an optional monitor-colored left sidebar.

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,10 @@
--- a/src/ui.rs
+++ b/src/ui.rs
@@ -80,6 +80,7 @@
let previous = Rc::new(Cell::new(Instant::now()));
canvas.add_tick_callback({
let params = params.clone();
+ let simulator = simulator.clone();
move |area, _frame_clock| {
let now = Instant::now();
let elapsed = now.saturating_duration_since(previous.get()).as_secs_f64();

View file

@ -0,0 +1,635 @@
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "patient-monitor-simulation"
-version = "0.6.0"
+version = "0.6.1"
edition = "2021"
license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"
--- a/README.de.md
+++ b/README.de.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.6.0
+# Patient Monitor Simulation (PaMSim) — v0.6.1
Ein mit Rust und GTK4 entwickelter Patient*innenmonitor-Simulator mit zwei Fenstern für die Lehre unter Fedora Linux.
@@ -26,80 +26,52 @@
Beim Ausblenden anderer Parameter werden die verbleibenden Kurvenzeilen wie
bisher dynamisch verteilt.
-## EKG-Bedienung direkt am Monitor (v0.5.9)
-
-Durch Berühren oder Anklicken der **EKG-Zeile** öffnet sich ein eigenes
-Einstellfenster mit **hellgrauer Schrift auf schwarzem Hintergrund**. Die gesamte
-EKG-Zeile ist aktiv, sowohl die Kurve links (75 %) als auch das numerische
-Herzfrequenzfeld rechts (25 %). Die Bedienung ist auch im Vollbildmodus möglich.
-Bei ausgeblendetem EKG ist die Interaktionsfläche deaktiviert.
-
-Im Einstellfenster stehen folgende Optionen zur Verfügung:
-
-- **ECG lead:** I, II (Voreinstellung), III, aVR, aVL, aVF und V1–V6. Nach
- **Apply** ändert sich die Ableitungsbezeichnung im Monitor sowie die
- schematische Polarität/Amplitude der Kurve. Es handelt sich **nicht** um
- eine klinisch validierte 12-Kanal-EKG-Ableitung. Frequenz, QRS-Zeitpunkte
- und mechanische Pulskopplung bleiben unverändert.
-- **HR alarm limits:** unabhängig einstellbare untere (↓) und obere (↑)
- Herzfrequenzgrenze in /min. Große Tasten **− / +** ändern den jeweiligen
- Grenzwert in **5er-Schritten** zwischen 0 und 240. Mit **OFF** lässt sich
- jede Grenze einzeln deaktivieren; **ON** aktiviert den vorherigen Wert
- erneut (bei anfänglich nicht gesetzten Werten 60 bzw. 100 /min).
- Die untere Grenze darf die obere nicht überschreiten.
-- **Apply** übernimmt beide Alarmgrenzen und die Ableitung gemeinsam;
- **Cancel** oder **Esc** verwirft die noch nicht übernommenen Eingaben.
-
-Die Bedienelemente sind ohne Tastatur verwendbar. Schmale hellgraue
-Begrenzungslinien und Trennlinien orientieren sich an der Gestaltung des
-Monitors; die EKG-spezifische grüne Textfarbe wird hier nicht verwendet.
-
-Die Einstellungen werden mit der Admin-Oberfläche synchronisiert. Eine am
-Monitor geänderte Alarmgrenze schaltet die Alarmvoreinstellung auf **Custom**.
-Auch in der Admin-Oberfläche ist die EKG-Ableitung auswählbar. Die anderen
-Monitorparameter besitzen ab v0.6.0 ebenfalls berührungsempfindliche Menüs.
-
-## Weitere Touch-Menüs am Monitor (v0.6.0)
-
-Ein Tipp auf die **Kurve oder die numerischen Werte** von SpO₂, ART oder CO₂
-öffnet das zugehörige Einstellfenster. Für NIBP ist das **rechte Viertel der
-untersten Messwertzeile** aktiv. Die Felder CO/CI, SVRI/GEDI/ELWI und das
-unbelegte dritte Feld erhalten noch keine Touch-Bedienung. Alle Menüs
-verwenden das Design des EKG-Menüs: **schwarzer Hintergrund, hellgraue Schrift
-und 0,8 Pixel breite Trennlinien**. Eine Bildschirmtastatur ist nicht nötig.
-
-| Bereich | Alarmgrenzen | Weitere Einstellungen |
+## Touch-Bedienung am Monitor: ausschließlich Alarmgrenzen (v0.6.1)
+
+Durch Berühren oder Anklicken der **Kurve oder des numerischen Wertefeldes**
+von EKG, SpO₂, ART oder CO₂ öffnet sich das entsprechende Alarmmenü. Bei
+NIBP ist das **rechte Viertel der untersten Wertezeile** aktiv. Die übrigen
+drei Wertefelder der untersten Zeile bleiben vorerst ohne Touch-Funktion.
+Die Menüs funktionieren auch im Vollbildmodus und verwenden **schwarzen
+Hintergrund, sehr hellgraue Schrift sowie 0,8 Pixel breite Begrenzungs-
+und Trennlinien** wie der Hauptmonitor.
+
+**Am Monitor können ausschließlich Alarmgrenzen eingestellt werden.**
+Für jede untere und obere Alarmgrenze stehen große **−/+**-Tasten sowie
+separate **ON/OFF**-Tasten zur Verfügung. Nicht gesetzte Grenzwerte sind
+deaktiviert. Ein unterer Grenzwert darf den oberen nicht überschreiten.
+Eine Bildschirmtastatur ist nicht erforderlich.
+
+| Monitorbereich | Einstellbare Alarmgrenzen | Schrittweite |
| --- | --- | --- |
-| SpO₂ | SpO₂, Pulsfrequenz (PR) | Signalqualität, Sensor angeschlossen/nicht angeschlossen |
-| ART | SYS, MAP, DIA, PPV | Form der arteriellen Druckkurve |
-| CO₂ | EtCO₂, Atemfrequenz (RR) | Normales oder obstruktives Kapnogramm |
-| NIBP | SYS, MAP, DIA | Intervall 1/3/5/10/20/30/60 min, Auto ON/OFF, Messausfall, Manschettenlokalisation und **Measure now** |
-
-Die einzelnen unteren und oberen Alarmgrenzen werden mit großen **−/+**-
-und **ON/OFF**-Tasten verändert. Die Schrittweiten betragen 5 /min bei PR,
-1 % bei SpO₂ und PPV, 5 mmHg bei ART/NIBP, 1 mmHg bei EtCO₂ und
-1 /min bei der Atemfrequenz. Eine untere Grenze darf nicht höher liegen
-als die obere.
-
-Mit **Apply** werden die Änderungen übernommen und zugleich die Admin-
-Oberfläche aktualisiert; eine geänderte Alarmgrenze setzt das Preset auf
-**Custom**. **Cancel** verwirft die Eingaben, **Esc** schließt das Fenster.
-Die Schaltfläche **Measure now** führt dagegen eine sofortige NIBP-Messung
-mit den *bereits übernommenen* Einstellungen aus. Änderungen für diese
-Messung müssen daher zuerst mit **Apply** bestätigt werden.
+| EKG | Herzfrequenz (HR) | 5/min |
+| SpO₂ | SpO₂; Pulsfrequenz (PR) | 1 % SpO₂; 5/min PR |
+| ART | SYS; MAP; DIA; PPV | 5 mmHg Druck; 1 % PPV |
+| CO₂ | EtCO₂; Atemfrequenz (RR) | 1 mmHg EtCO₂; 1/min RR |
+| NIBP | SYS; MAP; DIA | 5 mmHg |
+
+**Apply** übernimmt die Alarmgrenzen und synchronisiert das Admin-Fenster.
+Bei manueller Änderung wechselt das Alarm-Preset zu **Custom**. Mit
+**Cancel** oder **Esc** werden nicht übernommene Änderungen verworfen.
+
+Die Auswahl der EKG-Ableitung, SpO₂-Signalqualität und Sensorverbindung,
+der arteriellen Kurvenform, der Kapnogrammform sowie **sämtliche NIBP-
+Messfunktionen** sind ausschließlich im **Admin-Fenster** verfügbar. Dazu
+zählen Messintervall, automatische Messung, **Measure now**, simulierter
+Messausfall und Manschettenlokalisation. Diese Parameter können über die
+Alarmmenüs am Monitor nicht verändert werden.
### NIBP beim Programmstart
Die **automatische NIBP-Messung ist beim Start ausgeschaltet**. Anfangs
-zeigt der Monitor `---/---` (MAP `---`); es wird keine Messung durchgeführt.
-Erst **Measure now** oder das Aktivieren von **Automatic measurement**
-im NIBP-Touch-Menü (alternativ im Admin-Fenster) startet eine erste Messung.
-Wird Auto eingeschaltet, beginnt der erste Zyklus sofort; danach wird das
-eingestellte Intervall jeweils ab Ende der letzten Messung gezählt.
-Das Ausschalten von Auto verhindert neue automatische Messungen, bricht
-einen bereits begonnenen Zyklus jedoch nicht ab. **Measure now** bleibt
-bei ausgeschalteter Automatik nutzbar, solange keine Messung läuft.
-Bei Auto OFF ist der Intervallbalken leer und `AUTO OFF` wird angezeigt.
+zeigt der Monitor `---/---` (MAP `---`); es findet keine Messung statt.
+Die erste Messung wird über **Measure now** im Admin-Fenster oder durch
+Aktivieren von **Automatic NIBP measurement** ausgelöst. Beim Einschalten
+von Auto beginnt sofort ein Messzyklus; das Intervall zählt anschließend
+jeweils ab Ende der vorherigen Messung. Beim Ausschalten von Auto wird
+eine bereits laufende Messung nicht abgebrochen. **Measure now** funktioniert
+auch bei ausgeschalteter Automatik. Dann bleibt die Intervallanzeige leer
+und der Monitor zeigt `AUTO OFF`.
## Thoraxkompressionen (v0.5.4)
@@ -614,3 +586,11 @@
kein NIBP-Messwert vorhanden; der erste Zyklus muss manuell oder durch
Aktivieren der Automatik gestartet werden. Die bisherige NIBP-Messlogik
wird ansonsten unverändert weiterverwendet.
+
+### v0.6.1 – Touch-Menüs ausschließlich für Alarmgrenzen
+
+Alle Touch-Menüs für EKG, SpO₂, ART, CO₂ und NIBP enthalten jetzt nur noch
+untere und obere Alarmgrenzen. EKG-Ableitung, Signal- und Sensoreinstellungen,
+Kurvenformen sowie NIBP-Messfunktionen wurden aus den Monitor-Menüs entfernt
+und bleiben im Admin-Fenster verfügbar. Die Simulationslogik, Alarmprüfung
+und das NIBP-Startverhalten wurden nicht verändert.
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.6.0
+# Patient Monitor Simulation (PaMSim) — v0.6.1
A Rust/GTK4 patient-monitor simulator with two main windows for teaching on Fedora Linux.
@@ -23,79 +23,49 @@
bottom measurement row and other three groups remain present. Disabling one
of the four waveform channels still reflows the remaining rows above it.
-## ECG touchscreen settings (v0.5.9)
-
-Tap or click **anywhere in the ECG row**, on either the **trace (left 75%)** or
-**heart-rate readout (right 25%)**, to open a modal **black-and-light-grey ECG settings**
-window above the monitor. The same interaction works when the monitor is in
-fullscreen mode. The same interaction now applies to the other channels.
-Hiding
-the ECG channel also disables its touch target.
-
-The menu offers:
-
-- **ECG lead:** I, II (default), III, aVR, aVL, aVF, and V1–V6. The monitor
- trace label changes immediately after **Apply**, and the waveform undergoes
- an *illustrative lead-dependent gain/polarity transformation*. This is **not**
- a diagnostic 12-lead ECG derivation; cardiac timing, HR and mechanical
- capture do not change when the lead changes.
-- **HR alarm limits:** optional **↓ Lower** and **↑ Upper**, in bpm.
- Each limit has large **− / +** touch buttons that adjust the value in
- **5 bpm steps** (range 0–240), plus an **OFF** button to disable it.
- When disabled, an **ON** button restores its previous value (or 60 bpm
- for an unset lower limit and 100 bpm for an unset upper limit).
- The lower limit must not exceed the upper limit.
-- **Apply** commits lead and limits together; **Cancel** or **Esc** discards
- unsaved changes. Both Admin and monitor displays reflect committed changes.
- Changing limits in the monitor marks the Admin alarm preset as **Custom**.
-
-The menu uses light-grey text instead of the ECG waveform color and
-subtle separators matching the main monitor divider thickness. No keyboard
-is required for the ECG menu; the Admin window retains numeric text inputs.
-
-The Admin ECG section also includes an ECG-lead selector, synchronized with
-changes made from the monitor. SpO₂, ART, CO₂ and NIBP now also have
-neutral, touch-operated settings panels (details below).
-
-## Additional monitor touchscreen menus (v0.6.0)
-
-Tap or click the **waveform or numeric readout** of SpO₂, ART or CO₂ to open
-that channel's settings panel. For NIBP, tap the **rightmost quarter of the
-bottom measurement row**. The CO/CI, SVRI/GEDI/ELWI and unused third cells
-remain non-interactive. All menus share the ECG menu's **black background,
-light-grey text and thin 0.8 px dividers**. No on-monitor keyboard is needed.
-
-| Touched channel | Alarm thresholds | Other touch settings |
+## Monitor touchscreen: alarm limits only (v0.6.1)
+
+Tap or click the **waveform or numerical readout** of ECG, SpO₂, ART or CO₂
+to open that channel's alarm-limit panel. For NIBP, tap the **rightmost
+quarter of the bottom measurement row**. The other three bottom-row groups
+are reserved for future measurements and remain non-interactive. The panels
+are available in fullscreen and retain a **black background, very light-grey
+text, and 0.8-pixel borders and dividers**, in the style of the main monitor.
+
+**Only alarm thresholds can be modified from the monitor-side menus.**
+No keyboard is required: every lower/upper limit has large **− / +** controls
+with a parameter-specific increment and an independent **ON/OFF** control.
+Unset limits remain disabled. The lower limit cannot exceed the upper limit.
+
+| Touch area | Available alarm limits | Increment |
| --- | --- | --- |
-| SpO₂ | SpO₂, PR | Signal quality; sensor attached/detached |
-| ART | SYS, MAP, DIA, PPV | Arterial waveform shape |
-| CO₂ | EtCO₂, RR | Normal or obstructive capnogram |
-| NIBP | SYS, MAP, DIA | 1/3/5/10/20/30/60-minute interval, Auto ON/OFF, simulated failed reading, cuff extremity, **Measure now** |
-
-Each independent alarm bound is changed via large **−/+** buttons and
-**ON/OFF**. Touch increments are appropriate for the measurement: 5 bpm for
-PR; 1% for SpO₂ and PPV; 5 mmHg for ART and NIBP; 1 mmHg for EtCO₂; and
-1 breath/min for RR. Lower bounds must not exceed upper bounds.
-
-**Apply** commits the settings and updates the Admin controls and selected
-alarm preset (**Custom** if limits were changed). **Cancel** discards edits;
-**Esc** closes the panel. **Measure now** is an immediate action and starts
-an NIBP cuff cycle independently of Apply, using the currently active
-simulation settings. Apply other changed settings first if they should affect
-the next manual measurement.
+| ECG | HR | 5 bpm |
+| SpO₂ | SpO₂; pulse rate (PR) | 1% SpO₂; 5 bpm PR |
+| ART | SYS; MAP; DIA; PPV | 5 mmHg pressure; 1% PPV |
+| CO₂ | EtCO₂; respiratory rate (RR) | 1 mmHg EtCO₂; 1 breath/min RR |
+| NIBP | SYS; MAP; DIA | 5 mmHg |
+
+**Apply** commits the threshold changes and synchronizes the Admin window.
+Changing a threshold sets the alarm preset to **Custom**. **Cancel** or
+**Esc** discards the draft changes.
+
+ECG lead selection, SpO₂ signal quality and sensor status, ART waveform shape,
+capnogram shape, and all NIBP measurement controls are **Admin-only**. This
+includes NIBP measurement interval, Auto ON/OFF, **Measure now**, simulated
+failed reading, and cuff placement. None of these physiological or technical
+parameters is changed by the monitor-side alarm menus.
### NIBP startup and automatic measurements
-**Auto measurement is OFF by default.** The monitor displays `---/---`
-(MAP `---`) on startup, and there is **no automatic first measurement**.
-A first result appears only after selecting **Measure now**, or after
-activating **Automatic measurement** from the NIBP touch menu (also available
-in Admin). When Auto is first enabled, a measurement starts immediately;
-thereafter the selected interval counts from completion of the previous cycle.
-Switching Auto off prevents future scheduled cycles but **does not interrupt
-a cycle already under way**. Manual measurements can always be initiated
-when no cycle is running, even with Auto OFF. While Auto is OFF, the NIBP
-interval bar is empty and the display says `AUTO OFF`.
+**Auto measurement is OFF by default.** On startup the monitor shows
+`---/---` (MAP `---`) and no measurement is initiated. To obtain a reading,
+select **Measure now** in Admin, or enable **Automatic NIBP measurement**
+there. The first automatic cycle begins immediately after enabling Auto;
+subsequent measurement intervals count from completion of the prior cycle.
+Disabling Auto stops further scheduled measurements without interrupting a
+cycle already in progress. Manual measurement remains possible while Auto
+is off. The interval bar is empty and the monitor displays `AUTO OFF`
+whenever automatic measurements are disabled.
## Chest compressions (v0.5.4)
@@ -630,3 +600,11 @@
manual **Measure now**, Auto ON/OFF and cuff options. Startup no longer
initiates a cuff cycle or shows any NIBP reading; Auto is OFF by default.
Existing NIBP cycle physics and signal quality behavior are unchanged.
+
+### v0.6.1 — Alarm-only monitor touch menus
+
+The ECG, SpO₂, ART, CO₂ and NIBP touch menus now edit only lower/upper
+alarm limits. Removed ECG lead, signal/sensor, waveform and all NIBP
+measurement controls from monitor-side menus. These remain available in
+Admin, including manual NIBP measurement and Auto ON/OFF. No physiological
+model, alarm evaluation or NIBP startup behavior was changed.
--- a/src/ui.rs
+++ b/src/ui.rs
@@ -108,9 +108,8 @@
});
window.add_controller(keys);
- // One gesture covers each visible waveform/numeric row and the NIBP
- // quarter of the bottom row. Hit regions are computed by the renderer,
- // so mouse and Wayland touch share the same dynamic geometry.
+ // One gesture opens alarm-only panels for visible waveform/numeric rows
+ // and NIBP's bottom-right cell. Mouse and Wayland touch share geometry.
let monitor_menu: MonitorMenuHandle = Rc::new(RefCell::new(None));
let click = gtk::GestureClick::new();
click.connect_released({
@@ -127,7 +126,7 @@
Some(render::TouchChannel::Ecg) => open_ecg_menu(&app, &window,
params.clone(), admin_changed.clone(), monitor_menu.clone()),
Some(channel) => open_module_menu(&app, &window, params.clone(),
- simulator.clone(), admin_changed.clone(), monitor_menu.clone(), channel),
+ admin_changed.clone(), monitor_menu.clone(), channel),
None => (),
}
}
@@ -593,13 +592,6 @@
window.ecg-settings label.ecg-limit-value {
color: #e5e9eb; font-weight: bold; font-size: 19px;
}
- window.ecg-settings dropdown {
- color: #e5e9eb; background-color: #141414;
- border: 1px solid #6b757d; min-height: 48px;
- }
- window.ecg-settings dropdown button {
- color: #e5e9eb; background-color: #141414;
- }
window.ecg-settings button {
color: #e5e9eb; background-image: none;
background-color: #171717; border: 1px solid #6b757d;
@@ -726,10 +718,7 @@
existing.present();
return;
}
- let (limits, lead) = {
- let p = params.borrow();
- (p.alarms.hr, p.ecg_lead)
- };
+ let limits = params.borrow().alarms.hr;
let dialog = gtk::Window::builder()
.application(app)
.title("ECG settings")
@@ -737,7 +726,7 @@
.modal(true)
.resizable(false)
.default_width(550)
- .default_height(410)
+ .default_height(345)
.build();
dialog.add_css_class("ecg-settings");
dialog.set_decorated(false);
@@ -763,18 +752,6 @@
inner.append(&title);
inner.append(&ecg_menu_divider());
- let lead_row = gtk::Box::new(Orientation::Horizontal, 12);
- let lead_label = gtk::Label::new(Some("ECG lead"));
- lead_label.set_xalign(0.0);
- lead_label.set_width_chars(13);
- let lead_selector = gtk::DropDown::from_strings(EcgLead::LABELS);
- lead_selector.set_selected(lead.index());
- lead_selector.set_hexpand(true);
- lead_row.append(&lead_label);
- lead_row.append(&lead_selector);
- inner.append(&lead_row);
- inner.append(&ecg_menu_divider());
-
let limits_header = gtk::Label::new(Some("HR alarm limits · bpm"));
limits_header.set_xalign(0.0);
inner.append(&limits_header);
@@ -812,11 +789,9 @@
error.set_text("The lower limit must not exceed the upper limit.");
return;
}
- let new_lead = EcgLead::from_index(lead_selector.selected());
let alarm_changed = {
let mut p = params.borrow_mut();
let changed = p.alarms.hr != new_limits;
- p.ecg_lead = new_lead;
p.alarms.hr = new_limits;
changed
};
@@ -862,15 +837,6 @@
assert_eq!(stepped_hr_limit(None, 60, 1), 60);
assert_eq!(stepped_hr_limit(None, 100, -1), 100);
}
-}
-
-const NIBP_INTERVALS: [i32; 7] = [1, 3, 5, 10, 20, 30, 60];
-const NIBP_INTERVAL_LABELS: [&str; 7] = [
- "1 min", "3 min", "5 min", "10 min", "20 min", "30 min", "60 min"
-];
-
-fn nibp_interval_index(minutes: i32) -> u32 {
- NIBP_INTERVALS.iter().position(|&value| value == minutes).unwrap_or(2) as u32
}
/// Touchscreen alarm controls for a numerical value. The two bounds are
@@ -988,35 +954,25 @@
state
}
-fn module_touch_selector(parent: &gtk::Box, label: &str, items: &[&str],
- selected: u32) -> gtk::DropDown {
- let row = gtk::Box::new(Orientation::Horizontal, 12);
- let heading = gtk::Label::new(Some(label));
- heading.set_xalign(0.0);
- heading.set_width_chars(17);
- let dropdown = gtk::DropDown::from_strings(items);
- dropdown.set_selected(selected);
- dropdown.set_hexpand(true);
- row.append(&heading);
- row.append(&dropdown);
- parent.append(&row);
- dropdown
-}
-
-fn module_touch_checkbox(parent: &gtk::Box, text: &str, selected: bool) -> gtk::CheckButton {
- let control = gtk::CheckButton::with_label(text);
- control.set_active(selected);
- parent.append(&control);
- control
-}
-
-/// Open a modal settings panel using the same black, grey, 0.8 px divider and
-/// border design as the ECG panel. All settings except Measure now are drafts.
+/// A monitor-side menu may change only alarm limits. All patient and
+/// measurement configuration (including NIBP scheduling) stays Admin-only.
+fn apply_module_alarm_changes(
+ p: &mut Parameters,
+ limits: &[(fn(&mut AlarmSettings, AlarmLimits), AlarmLimits)],
+) -> bool {
+ let previous = p.alarms.clone();
+ for (setter, limit) in limits {
+ setter(&mut p.alarms, *limit);
+ }
+ p.alarms != previous
+}
+
+/// Open a modal alarm-limit panel with the same black, grey, 0.8 px divider
+/// and border design as the ECG panel. Other parameters are Admin-only.
#[allow(clippy::too_many_arguments)]
fn open_module_menu(app: &Application, monitor: &ApplicationWindow,
- params: SharedParams, simulator: Rc<RefCell<Simulator>>,
- on_change: AdminChanged, open_menu: MonitorMenuHandle,
- channel: render::TouchChannel) {
+ params: SharedParams, on_change: AdminChanged,
+ open_menu: MonitorMenuHandle, channel: render::TouchChannel) {
if let Some(existing) = open_menu.borrow().as_ref().and_then(|weak| weak.upgrade()) {
existing.present();
return;
@@ -1082,74 +1038,6 @@
inner.append(&ecg_menu_divider());
}
- // Dedicated sensor/measurement options relevant to each module.
- let mut mode_selector = None;
- let mut sensor_toggle = None;
- let mut nibp_auto = None;
- let mut nibp_force_failure = None;
- let mut cuff_on_spo2 = None;
- let mut cuff_on_art = None;
- match channel {
- render::TouchChannel::Spo2 => {
- mode_selector = Some(module_touch_selector(&inner, "Signal quality", &[
- "0 — None", "1 — Poor", "2 — Adequate", "3 — Good",
- ], current.spo2_quality as u32));
- sensor_toggle = Some(module_touch_checkbox(&inner,
- "Sensor not attached", !current.spo2_sensor_attached));
- }
- render::TouchChannel::Art => {
- mode_selector = Some(module_touch_selector(&inner, "Arterial waveform", &[
- "Normal", "Damped", "Hyperdynamic",
- ], match current.arterial_shape {
- ArterialShape::Normal => 0, ArterialShape::Damped => 1,
- ArterialShape::Hyperdynamic => 2,
- }));
- }
- render::TouchChannel::Capno => {
- mode_selector = Some(module_touch_selector(&inner, "Capnogram", &[
- "Normal", "Obstructive / shark fin",
- ], match current.capno_shape {
- CapnoShape::Normal => 0, CapnoShape::Obstructive => 1,
- }));
- }
- render::TouchChannel::Nibp => {
- mode_selector = Some(module_touch_selector(&inner, "Interval", &NIBP_INTERVAL_LABELS,
- nibp_interval_index(current.nibp_interval_minutes)));
- nibp_auto = Some(module_touch_checkbox(&inner, "Automatic measurement",
- current.nibp_auto_measurement));
- nibp_force_failure = Some(module_touch_checkbox(&inner, "No reading (simulate failure)",
- current.nibp_no_reading));
- cuff_on_spo2 = Some(module_touch_checkbox(&inner, "Cuff on SpO₂ extremity",
- current.nibp_cuff_on_spo2));
- cuff_on_art = Some(module_touch_checkbox(&inner, "Cuff on ART extremity",
- current.nibp_cuff_on_art));
- inner.append(&ecg_menu_divider());
- let measure = gtk::Button::with_label("Measure now");
- measure.set_size_request(-1, 54);
- inner.append(&measure);
- let status = gtk::Label::new(Some(
- "Manual measurement works even when Auto is OFF."
- ));
- status.set_xalign(0.0);
- status.set_wrap(true);
- inner.append(&status);
- measure.connect_clicked({
- let simulator = simulator.clone();
- let params = params.clone();
- move |_| {
- let in_progress = simulator.borrow().nibp().measuring();
- if in_progress {
- status.set_text("Measurement already in progress.");
- } else {
- simulator.borrow_mut().start_nibp_now(&params.borrow());
- status.set_text("Cuff measurement started.");
- }
- }
- });
- }
- render::TouchChannel::Ecg => (),
- }
- inner.append(&ecg_menu_divider());
let error = gtk::Label::new(None);
error.set_xalign(0.0);
error.add_css_class("menu-error");
@@ -1182,66 +1070,10 @@
}
selected_limits.push((field.apply, limits));
}
- let changed_alarms;
- {
+ let changed_alarms = {
let mut p = params.borrow_mut();
- let mut revised = p.alarms.clone();
- for (setter, limits) in selected_limits {
- setter(&mut revised, limits);
- }
- changed_alarms = revised != p.alarms;
- p.alarms = revised;
- match channel {
- render::TouchChannel::Spo2 => {
- if let Some(selector) = &mode_selector {
- p.spo2_quality = match selector.selected() {
- 1 => Spo2Quality::Poor,
- 2 => Spo2Quality::Adequate,
- 3 => Spo2Quality::Good,
- _ => Spo2Quality::None,
- };
- }
- if let Some(check) = &sensor_toggle {
- p.spo2_sensor_attached = !check.is_active();
- }
- }
- render::TouchChannel::Art => {
- if let Some(selector) = &mode_selector {
- p.arterial_shape = match selector.selected() {
- 1 => ArterialShape::Damped,
- 2 => ArterialShape::Hyperdynamic,
- _ => ArterialShape::Normal,
- };
- }
- }
- render::TouchChannel::Capno => {
- if let Some(selector) = &mode_selector {
- p.capno_shape = if selector.selected() == 1 {
- CapnoShape::Obstructive
- } else { CapnoShape::Normal };
- }
- }
- render::TouchChannel::Nibp => {
- if let Some(selector) = &mode_selector {
- p.nibp_interval_minutes = NIBP_INTERVALS
- .get(selector.selected() as usize).copied().unwrap_or(5);
- }
- if let Some(check) = &nibp_auto {
- p.nibp_auto_measurement = check.is_active();
- }
- if let Some(check) = &nibp_force_failure {
- p.nibp_no_reading = check.is_active();
- }
- if let Some(check) = &cuff_on_spo2 {
- p.nibp_cuff_on_spo2 = check.is_active();
- }
- if let Some(check) = &cuff_on_art {
- p.nibp_cuff_on_art = check.is_active();
- }
- }
- render::TouchChannel::Ecg => (),
- }
- }
+ apply_module_alarm_changes(&mut p, &selected_limits)
+ };
if let Some(callback) = on_change.borrow().as_ref() {
callback(changed_alarms);
}
@@ -1287,11 +1119,35 @@
}
#[test]
- fn interval_menu_maps_exactly_to_simulator_minutes() {
- for (index, minutes) in NIBP_INTERVALS.iter().copied().enumerate() {
- assert_eq!(nibp_interval_index(minutes), index as u32);
- }
- }
+ fn touchscreen_applies_only_alarm_limits_and_preserves_other_controls() {
+ let mut p = Parameters::default();
+ p.ecg_lead = EcgLead::V1;
+ p.spo2_quality = Spo2Quality::Poor;
+ p.spo2_sensor_attached = false;
+ p.arterial_shape = ArterialShape::Damped;
+ p.capno_shape = CapnoShape::Obstructive;
+ p.nibp_interval_minutes = 30;
+ p.nibp_auto_measurement = true;
+ p.nibp_no_reading = true;
+ p.nibp_cuff_on_spo2 = true;
+ p.nibp_cuff_on_art = true;
+ let limits = AlarmLimits { lower: Some(70), upper: Some(140) };
+ let spec = module_alarm_specs(render::TouchChannel::Nibp, &p).remove(0);
+ assert!(apply_module_alarm_changes(&mut p, &[(spec.apply, limits)]));
+ assert_eq!(p.alarms.nibp_sys, limits);
+ assert!(!apply_module_alarm_changes(&mut p, &[(spec.apply, limits)]));
+ assert_eq!(p.ecg_lead, EcgLead::V1);
+ assert_eq!(p.spo2_quality, Spo2Quality::Poor);
+ assert!(!p.spo2_sensor_attached);
+ assert_eq!(p.arterial_shape, ArterialShape::Damped);
+ assert_eq!(p.capno_shape, CapnoShape::Obstructive);
+ assert_eq!(p.nibp_interval_minutes, 30);
+ assert!(p.nibp_auto_measurement);
+ assert!(p.nibp_no_reading);
+ assert!(p.nibp_cuff_on_spo2);
+ assert!(p.nibp_cuff_on_art);
+ }
+
}
/// Frame a parameter section with an optional monitor-colored left sidebar.

View file

@ -0,0 +1,31 @@
--- a/src/ui.rs
+++ b/src/ui.rs
@@ -136,6 +136,13 @@
window
}
+/// Map an Admin NIBP measurement interval to its dropdown selection.
+/// The touchscreen alarm menus do not expose scheduling controls.
+fn nibp_interval_index(minutes: i32) -> u32 {
+ const INTERVALS: [i32; 7] = [1, 3, 5, 10, 20, 30, 60];
+ INTERVALS.iter().position(|&value| value == minutes).unwrap_or(2) as u32
+}
+
fn create_admin(app: &Application, params: SharedParams,
simulator: Rc<RefCell<Simulator>>,
monitor: &ApplicationWindow,
@@ -837,6 +844,14 @@
assert_eq!(stepped_hr_limit(None, 60, 1), 60);
assert_eq!(stepped_hr_limit(None, 100, -1), 100);
}
+
+ #[test]
+ fn nibp_interval_dropdown_supports_every_admin_interval() {
+ for (index, minutes) in [1, 3, 5, 10, 20, 30, 60].into_iter().enumerate() {
+ assert_eq!(nibp_interval_index(minutes), index as u32);
+ }
+ assert_eq!(nibp_interval_index(999), 2); // 5-minute fallback
+ }
}
/// Touchscreen alarm controls for a numerical value. The two bounds are

View file

@ -0,0 +1,323 @@
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "patient-monitor-simulation"
-version = "0.6.1"
+version = "0.6.2"
edition = "2021"
license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"
--- a/README.de.md
+++ b/README.de.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.6.1
+# Patient Monitor Simulation (PaMSim) — v0.6.2
Ein mit Rust und GTK4 entwickelter Patient*innenmonitor-Simulator mit zwei Fenstern für die Lehre unter Fedora Linux.
@@ -72,6 +72,17 @@
eine bereits laufende Messung nicht abgebrochen. **Measure now** funktioniert
auch bei ausgeschalteter Automatik. Dann bleibt die Intervallanzeige leer
und der Monitor zeigt `AUTO OFF`.
+
+### Anordnung der ART-Alarmgrenzen (v0.6.2)
+
+Das Touchmenü für die invasive arterielle Druckmessung ordnet **SYS, MAP und
+DIA** in drei Spalten an. Die obere Bedienzeile enthält die **oberen (↑)**
+Alarmgrenzen, die zweite die **unteren (↓)** Alarmgrenzen. **PPV** folgt unter
+SYS mit eigenen oberen und unteren Grenzwerten. Die bisherigen großen
+**+ / Wert / − / EIN-AUS**-Schaltflächen und ihre Bedienlogik bleiben erhalten.
+Die Gestaltung verwendet weiterhin Schwarz, Hellgrau und schmale Rahmenlinien.
+Alle anderen Parametermenüs bleiben unverändert. Alarmverarbeitung und
+Voreinstellungen sind von dieser Layoutänderung nicht betroffen.
## Thoraxkompressionen (v0.5.4)
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.6.1
+# Patient Monitor Simulation (PaMSim) — v0.6.2
A Rust/GTK4 patient-monitor simulator with two main windows for teaching on Fedora Linux.
@@ -66,6 +66,17 @@
cycle already in progress. Manual measurement remains possible while Auto
is off. The interval bar is empty and the monitor displays `AUTO OFF`
whenever automatic measurements are disabled.
+
+### ART alarm-limit arrangement (v0.6.2)
+
+The ART touchscreen alarm panel groups **SYS, MAP and DIA** in three
+side-by-side columns. The first control row adjusts their **upper (↑)** limits;
+the second adjusts their **lower (↓)** limits. **PPV** appears below SYS, with
+its own upper and lower controls. Each bound retains the existing large
+**+ / value / − / ON-OFF** buttons, including previous-value restoration.
+The groups share the monitor's neutral black/grey palette and thin borders.
+All other module menus retain their previous arrangement. This is a layout
+change only; thresholds, presets and alarm evaluation are unchanged.
## Chest compressions (v0.5.4)
--- a/src/ui.rs
+++ b/src/ui.rs
@@ -608,7 +608,16 @@
window.ecg-settings button.ecg-apply {
color: #000000; background-color: #e5e9eb; font-weight: bold;
}
- window.ecg-settings button.ecg-close { background-color: #171717; }"
+ window.ecg-settings button.ecg-close { background-color: #171717; }
+ window.ecg-settings box.art-limit-frame {
+ border: 0.8px solid #6b757d; padding: 12px;
+ }
+ window.ecg-settings label.art-limit-heading {
+ font-weight: bold; font-size: 17px;
+ }
+ window.ecg-settings label.art-limit-arrow {
+ font-size: 21px;
+ }"
);
gtk::style_context_add_provider_for_display(
&display, &provider, gtk::STYLE_PROVIDER_PRIORITY_APPLICATION);
@@ -969,6 +978,127 @@
state
}
+/// ART-only keyboard-free limit editor: the existing button appearance and
+/// callback semantics are retained, but its widgets are stacked vertically
+/// for the SYS/MAP/DIA columns and the PPV controls below them.
+#[allow(clippy::too_many_arguments)]
+fn art_touch_limit(grid: &gtk::Grid, column: i32, row: i32,
+ initial: Option<i32>, fallback: i32,
+ step: i32, maximum: i32) -> Rc<Cell<Option<i32>>> {
+ let state = Rc::new(Cell::new(initial));
+ let previous = Rc::new(Cell::new(initial.unwrap_or(fallback)));
+ let controls = gtk::Box::new(Orientation::Vertical, 7);
+ controls.set_halign(gtk::Align::Center);
+ controls.set_hexpand(true);
+
+ let plus = gtk::Button::with_label("+");
+ plus.set_size_request(54, 50);
+ plus.set_halign(gtk::Align::Center);
+ controls.append(&plus);
+
+ let display = gtk::Label::new(None);
+ display.add_css_class("ecg-limit-value");
+ display.set_width_chars(5);
+ display.set_xalign(0.5);
+ controls.append(&display);
+
+ let minus = gtk::Button::with_label("−");
+ minus.set_size_request(54, 50);
+ minus.set_halign(gtk::Align::Center);
+ controls.append(&minus);
+
+ let toggle = gtk::Button::new();
+ toggle.set_size_request(78, 50);
+ toggle.set_halign(gtk::Align::Center);
+ show_touch_hr_limit(initial, &display, &toggle);
+ controls.append(&toggle);
+
+ for (button, direction) in [(plus, 1), (minus, -1)] {
+ let state = state.clone();
+ let previous = previous.clone();
+ let display = display.clone();
+ let toggle = toggle.clone();
+ button.connect_clicked(move |_| {
+ let new_value = state.get().map_or(previous.get(), |current| {
+ (current + direction * step).clamp(0, maximum)
+ });
+ state.set(Some(new_value));
+ previous.set(new_value);
+ show_touch_hr_limit(Some(new_value), &display, &toggle);
+ });
+ }
+ toggle.connect_clicked({
+ let state = state.clone();
+ let previous = previous.clone();
+ let display = display.clone();
+ move |button| {
+ let new_value = match state.get() {
+ Some(value) => { previous.set(value); None }
+ None => Some(previous.get()),
+ };
+ state.set(new_value);
+ show_touch_hr_limit(new_value, &display, button);
+ }
+ });
+ grid.attach(&controls, column, row, 1, 1);
+ state
+}
+
+/// Map the four ART parameters to the three-column alarm grid. Row 1 is
+/// upper thresholds, row 2 lower; PPV occupies column SYS in rows 4 and 5.
+fn art_alarm_position(index: usize) -> (i32, i32, i32, i32, &'static str) {
+ match index {
+ 0 => (1, 0, 1, 2, "SYS"),
+ 1 => (2, 0, 1, 2, "MAP"),
+ 2 => (3, 0, 1, 2, "DIA"),
+ 3 => (1, 3, 4, 5, "PPV"),
+ _ => unreachable!("ART has exactly four alarm parameters"),
+ }
+}
+
+/// The ART alarm menu groups SYS/MAP/DIA into columns with upper limits in
+/// the first row and lower limits in the second; PPV occupies the first
+/// parameter column beneath them. It reuses the same alarm draft/Apply path.
+fn art_alarm_grid(specs: Vec<TouchAlarmSpec>, drafts: &mut Vec<TouchAlarmDraft>) -> gtk::Box {
+ let frame = gtk::Box::new(Orientation::Vertical, 16);
+ frame.add_css_class("art-limit-frame");
+ frame.set_hexpand(true);
+
+ let heading = gtk::Label::new(Some("Alarm Limits"));
+ heading.add_css_class("art-limit-heading");
+ heading.set_xalign(0.0);
+ frame.append(&heading);
+
+ let grid = gtk::Grid::new();
+ grid.set_hexpand(true);
+ grid.set_column_spacing(12);
+ grid.set_row_spacing(23);
+
+ for (row, arrow) in [(1, "↑"), (2, "↓"), (4, "↑"), (5, "↓")] {
+ let label = gtk::Label::new(Some(arrow));
+ label.add_css_class("art-limit-arrow");
+ label.set_width_chars(2);
+ grid.attach(&label, 0, row, 1, 1);
+ }
+ for (i, spec) in specs.into_iter().enumerate() {
+ let (column, title_row, upper_row, lower_row, title) = art_alarm_position(i);
+ let label = gtk::Label::new(Some(title));
+ label.add_css_class("art-limit-heading");
+ label.set_hexpand(true);
+ grid.attach(&label, column, title_row, 1, 1);
+
+ let upper = art_touch_limit(&grid, column, upper_row, spec.limits.upper,
+ spec.restore_upper, spec.step, spec.maximum);
+ let lower = art_touch_limit(&grid, column, lower_row, spec.limits.lower,
+ spec.restore_lower, spec.step, spec.maximum);
+ drafts.push(TouchAlarmDraft {
+ name: spec.name, lower, upper, apply: spec.apply,
+ });
+ }
+ frame.append(&grid);
+ frame
+}
+
/// A monitor-side menu may change only alarm limits. All patient and
/// measurement configuration (including NIBP scheduling) stays Admin-only.
fn apply_module_alarm_changes(
@@ -1006,8 +1136,8 @@
.transient_for(monitor)
.modal(true)
.resizable(true)
- .default_width(560)
- .default_height(if channel == render::TouchChannel::Art { 720 } else { 610 })
+ .default_width(if channel == render::TouchChannel::Art { 720 } else { 560 })
+ .default_height(if channel == render::TouchChannel::Art { 790 } else { 610 })
.build();
dialog.add_css_class("ecg-settings");
dialog.set_decorated(false);
@@ -1039,25 +1169,42 @@
// Every numeric alarm has two optional bounds, editable without a keyboard.
let specs = module_alarm_specs(channel, &current);
let mut alarm_drafts = Vec::new();
- for spec in specs {
- let label = gtk::Label::new(Some(&format!("{} alarm limits · {}", spec.name, spec.unit)));
- label.set_xalign(0.0);
- inner.append(&label);
- let lower = module_touch_limit(&inner, "↓ Lower", spec.limits.lower,
- spec.restore_lower, spec.step, spec.maximum);
- let upper = module_touch_limit(&inner, "↑ Upper", spec.limits.upper,
- spec.restore_upper, spec.step, spec.maximum);
- alarm_drafts.push(TouchAlarmDraft {
- name: spec.name, lower, upper, apply: spec.apply,
- });
- inner.append(&ecg_menu_divider());
+ if channel == render::TouchChannel::Art {
+ // The ART panel uses the requested column/row arrangement. Other
+ // channels retain their current one-parameter-at-a-time layout.
+ inner.append(&art_alarm_grid(specs, &mut alarm_drafts));
+ } else {
+ for spec in specs {
+ let label = gtk::Label::new(Some(&format!("{} alarm limits · {}", spec.name, spec.unit)));
+ label.set_xalign(0.0);
+ inner.append(&label);
+ let lower = module_touch_limit(&inner, "↓ Lower", spec.limits.lower,
+ spec.restore_lower, spec.step, spec.maximum);
+ let upper = module_touch_limit(&inner, "↑ Upper", spec.limits.upper,
+ spec.restore_upper, spec.step, spec.maximum);
+ alarm_drafts.push(TouchAlarmDraft {
+ name: spec.name, lower, upper, apply: spec.apply,
+ });
+ inner.append(&ecg_menu_divider());
+ }
}
let error = gtk::Label::new(None);
error.set_xalign(0.0);
error.add_css_class("menu-error");
error.set_wrap(true);
- inner.append(&error);
+ // The ART layout is taller; keep validation and buttons visible while
+ // the alarm-limit controls scroll on smaller monitor touchscreens.
+ let footer = gtk::Box::new(Orientation::Vertical, 8);
+ if channel == render::TouchChannel::Art {
+ footer.set_margin_start(20);
+ footer.set_margin_end(20);
+ footer.set_margin_top(8);
+ footer.set_margin_bottom(12);
+ footer.append(&error);
+ } else {
+ inner.append(&error);
+ }
let buttons = gtk::Box::new(Orientation::Horizontal, 12);
buttons.set_halign(gtk::Align::End);
let cancel = gtk::Button::with_label("Cancel");
@@ -1097,7 +1244,12 @@
});
buttons.append(&cancel);
buttons.append(&apply);
- inner.append(&buttons);
+ if channel == render::TouchChannel::Art {
+ footer.append(&buttons);
+ content.append(&footer);
+ } else {
+ inner.append(&buttons);
+ }
dialog.set_child(Some(&content));
let escape = gtk::EventControllerKey::new();
@@ -1131,6 +1283,31 @@
assert_eq!(specs.len(), expected);
assert!(specs.iter().all(|spec| spec.maximum > 0 && spec.step > 0));
}
+ }
+
+ #[test]
+ fn art_menu_columns_follow_sys_map_dia_and_ppv_order() {
+ assert_eq!(art_alarm_position(0), (1, 0, 1, 2, "SYS"));
+ assert_eq!(art_alarm_position(1), (2, 0, 1, 2, "MAP"));
+ assert_eq!(art_alarm_position(2), (3, 0, 1, 2, "DIA"));
+ assert_eq!(art_alarm_position(3), (1, 3, 4, 5, "PPV"));
+ let specs = module_alarm_specs(render::TouchChannel::Art, &Parameters::default());
+ assert_eq!(specs.iter().map(|spec| spec.name).collect::<Vec<_>>(),
+ ["ART systolic", "ART MAP", "ART diastolic", "PPV"]);
+ let mut alarms = AlarmSettings::default();
+ let limits = [
+ AlarmLimits { lower: Some(80), upper: Some(180) },
+ AlarmLimits { lower: Some(60), upper: Some(100) },
+ AlarmLimits { lower: None, upper: None },
+ AlarmLimits { lower: None, upper: Some(10) },
+ ];
+ for (spec, value) in specs.into_iter().zip(limits.iter().copied()) {
+ (spec.apply)(&mut alarms, value);
+ }
+ assert_eq!(alarms.art_sys, limits[0]);
+ assert_eq!(alarms.art_map, limits[1]);
+ assert_eq!(alarms.art_dia, limits[2]);
+ assert_eq!(alarms.ppv, limits[3]);
}
#[test]

View file

@ -0,0 +1,752 @@
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "patient-monitor-simulation"
-version = "0.6.2"
+version = "0.6.3"
edition = "2021"
license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"
--- a/README.de.md
+++ b/README.de.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.6.2
+# Patient Monitor Simulation (PaMSim) — v0.6.3
Ein mit Rust und GTK4 entwickelter Patient*innenmonitor-Simulator mit zwei Fenstern für die Lehre unter Fedora Linux.
@@ -73,16 +73,18 @@
auch bei ausgeschalteter Automatik. Dann bleibt die Intervallanzeige leer
und der Monitor zeigt `AUTO OFF`.
-### Anordnung der ART-Alarmgrenzen (v0.6.2)
-
-Das Touchmenü für die invasive arterielle Druckmessung ordnet **SYS, MAP und
-DIA** in drei Spalten an. Die obere Bedienzeile enthält die **oberen (↑)**
-Alarmgrenzen, die zweite die **unteren (↓)** Alarmgrenzen. **PPV** folgt unter
-SYS mit eigenen oberen und unteren Grenzwerten. Die bisherigen großen
-**+ / Wert / − / EIN-AUS**-Schaltflächen und ihre Bedienlogik bleiben erhalten.
-Die Gestaltung verwendet weiterhin Schwarz, Hellgrau und schmale Rahmenlinien.
-Alle anderen Parametermenüs bleiben unverändert. Alarmverarbeitung und
-Voreinstellungen sind von dieser Layoutänderung nicht betroffen.
+### Horizontale Matrix für Alarmgrenzen (v0.6.3)
+
+Alle fünf Touchmenüs des Monitors verwenden dieselbe kompakte Matrix.
+Jeder Parameter belegt eine Zeile (bei ART: **SYS**, **MAP**, **DIA**,
+**PPV**); die **untere (↓)** und **obere (↑)** Alarmgrenze stehen
+nebeneinander. Die Schaltflächen jedes Grenzwerts sind von links nach
+rechts **+ · Wert · − · OFF/ON** angeordnet. Die Schaltfläche zum
+Deaktivieren liegt unmittelbar rechts von Minus. Größe, Gestaltung,
+Schrittweite, Wiederherstellung des letzten Werts sowie Apply/Cancel
+bleiben erhalten. Bei Platzmangel lässt sich die Matrix scrollen, während
+Apply und Cancel zugänglich bleiben. Andere Einstellungen bleiben dem
+Admin-Fenster vorbehalten.
## Thoraxkompressionen (v0.5.4)
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.6.2
+# Patient Monitor Simulation (PaMSim) — v0.6.3
A Rust/GTK4 patient-monitor simulator with two main windows for teaching on Fedora Linux.
@@ -67,16 +67,17 @@
is off. The interval bar is empty and the monitor displays `AUTO OFF`
whenever automatic measurements are disabled.
-### ART alarm-limit arrangement (v0.6.2)
-
-The ART touchscreen alarm panel groups **SYS, MAP and DIA** in three
-side-by-side columns. The first control row adjusts their **upper (↑)** limits;
-the second adjusts their **lower (↓)** limits. **PPV** appears below SYS, with
-its own upper and lower controls. Each bound retains the existing large
-**+ / value / − / ON-OFF** buttons, including previous-value restoration.
-The groups share the monitor's neutral black/grey palette and thin borders.
-All other module menus retain their previous arrangement. This is a layout
-change only; thresholds, presets and alarm evaluation are unchanged.
+### Horizontal touchscreen alarm matrix (v0.6.3)
+
+All five monitor touch menus now share a compact horizontal alarm-limit matrix.
+Each parameter occupies its own row (for ART: **SYS**, **MAP**, **DIA**,
+**PPV**), with **↓ Lower** and **↑ Upper** displayed in adjacent columns.
+Within each limit cell, the touch controls are ordered **+ · value · − ·
+OFF/ON** (the OFF/ON button is immediately right of minus). The original
+large button styling, per-parameter increments, last-value restoration,
+optional bounds and Apply/Cancel semantics are unchanged. The matrix scrolls
+if necessary while Apply and Cancel remain accessible below it. Other
+physiological and NIBP controls remain Admin-only.
## Chest compressions (v0.5.4)
--- a/src/ui.rs
+++ b/src/ui.rs
@@ -122,12 +122,9 @@
let p = params.borrow();
render::monitor_hit_test(x, y, canvas.width(), canvas.height(), &p)
};
- match touched {
- Some(render::TouchChannel::Ecg) => open_ecg_menu(&app, &window,
- params.clone(), admin_changed.clone(), monitor_menu.clone()),
- Some(channel) => open_module_menu(&app, &window, params.clone(),
- admin_changed.clone(), monitor_menu.clone(), channel),
- None => (),
+ if let Some(channel) = touched {
+ open_module_menu(&app, &window, params.clone(),
+ admin_changed.clone(), monitor_menu.clone(), channel);
}
}
});
@@ -609,14 +606,14 @@
color: #000000; background-color: #e5e9eb; font-weight: bold;
}
window.ecg-settings button.ecg-close { background-color: #171717; }
- window.ecg-settings box.art-limit-frame {
+ window.ecg-settings box.alarm-limit-frame {
border: 0.8px solid #6b757d; padding: 12px;
}
- window.ecg-settings label.art-limit-heading {
+ window.ecg-settings label.alarm-limit-heading {
font-weight: bold; font-size: 17px;
}
- window.ecg-settings label.art-limit-arrow {
- font-size: 21px;
+ window.ecg-settings label.alarm-limit-column-heading {
+ font-size: 15px; font-weight: bold;
}"
);
gtk::style_context_add_provider_for_display(
@@ -641,14 +638,12 @@
separator
}
-const TOUCH_HR_STEP: i32 = 5;
-const MAX_HR_ALARM: i32 = 240;
-
-/// When a limit is OFF, either +/- first restores its previous value (or
-/// a sensible initial value). Subsequent presses adjust it by 5 bpm.
-fn stepped_hr_limit(current: Option<i32>, last_enabled: i32, direction: i32) -> i32 {
- current.map_or(last_enabled, |value| {
- (value + TOUCH_HR_STEP * direction).clamp(0, MAX_HR_ALARM)
+/// Apply a touchscreen step to an alarm value. When the alarm is disabled,
+/// either +/- first restores its last enabled value (unchanged behavior).
+fn stepped_alarm_limit(current: Option<i32>, previous: i32,
+ direction: i32, step: i32, maximum: i32) -> i32 {
+ current.map_or(previous, |value| {
+ (value + step * direction).clamp(0, maximum)
})
}
@@ -658,200 +653,23 @@
toggle.set_label(if value.is_some() { "OFF" } else { "ON" });
}
-/// Large, keyboard-free +/- and ON/OFF controls. Returning a Cell permits
-/// Apply to read the draft value without changing the shared configuration.
-fn ecg_touch_limit(parent: &gtk::Box, caption: &str,
- initial: Option<i32>, default: i32) -> Rc<Cell<Option<i32>>> {
- let state = Rc::new(Cell::new(initial));
- let previous = Rc::new(Cell::new(initial.unwrap_or(default)));
- let row = gtk::Box::new(Orientation::Horizontal, 10);
-
- let heading = gtk::Label::new(Some(caption));
- heading.set_xalign(0.0);
- heading.set_width_chars(10);
- row.append(&heading);
-
- let minus = gtk::Button::with_label("−");
- minus.set_tooltip_text(Some("Decrease alarm limit by 5 bpm"));
- minus.set_size_request(54, 50);
- row.append(&minus);
-
- let display = gtk::Label::new(None);
- display.add_css_class("ecg-limit-value");
- display.set_width_chars(5);
- display.set_xalign(0.5);
- row.append(&display);
-
- let plus = gtk::Button::with_label("+");
- plus.set_tooltip_text(Some("Increase alarm limit by 5 bpm"));
- plus.set_size_request(54, 50);
- row.append(&plus);
-
- let enable_toggle = gtk::Button::new();
- enable_toggle.set_tooltip_text(Some("Enable or disable this alarm limit"));
- enable_toggle.set_size_request(78, 50);
- row.append(&enable_toggle);
- show_touch_hr_limit(initial, &display, &enable_toggle);
-
- for (button, direction) in [(minus, -1), (plus, 1)] {
- let state = state.clone();
- let previous = previous.clone();
- let display = display.clone();
- let enable_toggle = enable_toggle.clone();
- button.connect_clicked(move |_| {
- let next = stepped_hr_limit(state.get(), previous.get(), direction);
- state.set(Some(next));
- previous.set(next);
- show_touch_hr_limit(Some(next), &display, &enable_toggle);
- });
- }
- enable_toggle.connect_clicked({
- let state = state.clone();
- let previous = previous.clone();
- let display = display.clone();
- move |button| {
- let new_value = match state.get() {
- Some(value) => {
- previous.set(value);
- None
- }
- None => Some(previous.get()),
- };
- state.set(new_value);
- show_touch_hr_limit(new_value, &display, button);
- }
- });
- parent.append(&row);
- state
-}
-
-/// Displayed only for touches in the ECG row. The monitor window can remain
-/// fullscreen. The dialog is modal to that monitor, including on Wayland.
-fn open_ecg_menu(app: &Application, monitor: &ApplicationWindow,
- params: SharedParams, on_change: AdminChanged,
- open_menu: MonitorMenuHandle) {
- if let Some(existing) = open_menu.borrow().as_ref().and_then(|weak| weak.upgrade()) {
- existing.present();
- return;
- }
- let limits = params.borrow().alarms.hr;
- let dialog = gtk::Window::builder()
- .application(app)
- .title("ECG settings")
- .transient_for(monitor)
- .modal(true)
- .resizable(false)
- .default_width(550)
- .default_height(345)
- .build();
- dialog.add_css_class("ecg-settings");
- dialog.set_decorated(false);
- *open_menu.borrow_mut() = Some(dialog.downgrade());
-
- let content = gtk::Box::new(Orientation::Vertical, 12);
- content.add_css_class("ecg-panel");
- content.set_margin_top(1);
- content.set_margin_bottom(1);
- content.set_margin_start(1);
- content.set_margin_end(1);
- // Inner padding keeps controls away from the thin panel border.
- let inner = gtk::Box::new(Orientation::Vertical, 12);
- inner.set_margin_top(20);
- inner.set_margin_bottom(20);
- inner.set_margin_start(20);
- inner.set_margin_end(20);
- content.append(&inner);
-
- let title = gtk::Label::new(Some("ECG / SETTINGS"));
- title.set_xalign(0.0);
- title.add_css_class("title-2");
- inner.append(&title);
- inner.append(&ecg_menu_divider());
-
- let limits_header = gtk::Label::new(Some("HR alarm limits · bpm"));
- limits_header.set_xalign(0.0);
- inner.append(&limits_header);
- let lower = ecg_touch_limit(&inner, "↓ Lower", limits.lower, 60);
- let upper = ecg_touch_limit(&inner, "↑ Upper", limits.upper, 100);
- let hint = gtk::Label::new(Some(
- "+/− adjusts by 5 bpm. OFF disables the limit; ON restores it."
- ));
- hint.set_wrap(true);
- hint.set_xalign(0.0);
- inner.append(&hint);
- inner.append(&ecg_menu_divider());
-
- let error = gtk::Label::new(None);
- error.add_css_class("menu-error");
- error.set_xalign(0.0);
- error.set_wrap(true);
- inner.append(&error);
-
- let buttons = gtk::Box::new(Orientation::Horizontal, 12);
- buttons.set_halign(gtk::Align::End);
- let cancel = gtk::Button::with_label("Cancel");
- cancel.add_css_class("ecg-close");
- cancel.connect_clicked({
- let weak = dialog.downgrade();
- move |_| { if let Some(window) = weak.upgrade() { window.close(); } }
- });
- let apply = gtk::Button::with_label("Apply");
- apply.add_css_class("ecg-apply");
- apply.connect_clicked({
- let weak = dialog.downgrade();
- move |_| {
- let new_limits = AlarmLimits { lower: lower.get(), upper: upper.get() };
- if !new_limits.valid() {
- error.set_text("The lower limit must not exceed the upper limit.");
- return;
- }
- let alarm_changed = {
- let mut p = params.borrow_mut();
- let changed = p.alarms.hr != new_limits;
- p.alarms.hr = new_limits;
- changed
- };
- if let Some(callback) = on_change.borrow().as_ref() {
- callback(alarm_changed);
- }
- if let Some(window) = weak.upgrade() { window.close(); }
- }
- });
- buttons.append(&cancel);
- buttons.append(&apply);
- inner.append(&buttons);
- dialog.set_child(Some(&content));
-
- let escape = gtk::EventControllerKey::new();
- escape.connect_key_pressed({
- let weak = dialog.downgrade();
- move |_, key, _, _| {
- if key == gdk::Key::Escape {
- if let Some(window) = weak.upgrade() { window.close(); }
- glib::Propagation::Stop
- } else { glib::Propagation::Proceed }
- }
- });
- dialog.add_controller(escape);
- dialog.present();
-}
-
#[cfg(test)]
mod ecg_touch_menu_tests {
use super::*;
#[test]
- fn touch_step_uses_five_bpm_and_respects_bounds() {
- assert_eq!(stepped_hr_limit(Some(60), 60, 1), 65);
- assert_eq!(stepped_hr_limit(Some(60), 60, -1), 55);
- assert_eq!(stepped_hr_limit(Some(240), 240, 1), 240);
- assert_eq!(stepped_hr_limit(Some(0), 0, -1), 0);
+ fn touch_step_preserves_per_parameter_increment_and_bounds() {
+ assert_eq!(stepped_alarm_limit(Some(60), 60, 1, 5, 240), 65);
+ assert_eq!(stepped_alarm_limit(Some(60), 60, -1, 5, 240), 55);
+ assert_eq!(stepped_alarm_limit(Some(240), 240, 1, 5, 240), 240);
+ assert_eq!(stepped_alarm_limit(Some(0), 0, -1, 5, 240), 0);
+ assert_eq!(stepped_alarm_limit(Some(90), 90, 1, 1, 100), 91);
}
#[test]
fn disabled_alarm_reenables_at_last_saved_value() {
- assert_eq!(stepped_hr_limit(None, 60, 1), 60);
- assert_eq!(stepped_hr_limit(None, 100, -1), 100);
+ assert_eq!(stepped_alarm_limit(None, 60, 1, 5, 240), 60);
+ assert_eq!(stepped_alarm_limit(None, 100, -1, 5, 240), 100);
}
#[test]
@@ -896,6 +714,9 @@
};
}
match channel {
+ render::TouchChannel::Ecg => {
+ limits!("HR", "bpm", hr, 240, 5, 60, 100);
+ }
render::TouchChannel::Spo2 => {
limits!("SpO₂", "%", spo2, 100, 1, 90, 100);
limits!("Pulse rate", "bpm", pr, 240, 5, 50, 120);
@@ -915,102 +736,40 @@
limits!("NIBP MAP", "mmHg", nibp_map, 260, 5, 60, 100);
limits!("NIBP diastolic", "mmHg", nibp_dia, 260, 5, 40, 100);
}
- render::TouchChannel::Ecg => {}
}
specs
}
-/// Generic unit-aware limit control with large +/- and ON/OFF touch buttons.
-/// Unlike the ECG-only helper, the increment and permitted range are per value.
+/// A compact alarm-limit cell: [+] value [−] [OFF/ON]. Its buttons retain
+/// the old size/style, step size, last-value restoration and draft semantics.
#[allow(clippy::too_many_arguments)]
-fn module_touch_limit(parent: &gtk::Box, caption: &str, initial: Option<i32>,
- fallback: i32, step: i32, maximum: i32) -> Rc<Cell<Option<i32>>> {
+fn alarm_matrix_cell(initial: Option<i32>, fallback: i32, step: i32,
+ maximum: i32) -> (gtk::Box, Rc<Cell<Option<i32>>>) {
let state = Rc::new(Cell::new(initial));
let previous = Rc::new(Cell::new(initial.unwrap_or(fallback)));
- let row = gtk::Box::new(Orientation::Horizontal, 10);
- let caption_label = gtk::Label::new(Some(caption));
- caption_label.set_width_chars(10);
- caption_label.set_xalign(0.0);
- row.append(&caption_label);
- let minus = gtk::Button::with_label("−");
- minus.set_size_request(54, 50);
- let display = gtk::Label::new(None);
- display.add_css_class("ecg-limit-value");
- display.set_xalign(0.5);
- display.set_width_chars(5);
+ let controls = gtk::Box::new(Orientation::Horizontal, 5);
+ controls.set_hexpand(true);
+ controls.set_halign(gtk::Align::Center);
+
let plus = gtk::Button::with_label("+");
plus.set_size_request(54, 50);
- let toggle = gtk::Button::new();
- toggle.set_size_request(78, 50);
- show_touch_hr_limit(initial, &display, &toggle);
- row.append(&minus);
- row.append(&display);
- row.append(&plus);
- row.append(&toggle);
- for (button, direction) in [(minus, -1), (plus, 1)] {
- let state = state.clone();
- let previous = previous.clone();
- let display = display.clone();
- let toggle = toggle.clone();
- button.connect_clicked(move |_| {
- let new_value = state.get().map_or(previous.get(), |current| {
- (current + direction * step).clamp(0, maximum)
- });
- state.set(Some(new_value));
- previous.set(new_value);
- show_touch_hr_limit(Some(new_value), &display, &toggle);
- });
- }
- toggle.connect_clicked({
- let state = state.clone();
- let previous = previous.clone();
- let display = display.clone();
- move |button| {
- let new_value = match state.get() {
- Some(value) => { previous.set(value); None }
- None => Some(previous.get()),
- };
- state.set(new_value);
- show_touch_hr_limit(new_value, &display, button);
- }
- });
- parent.append(&row);
- state
-}
-
-/// ART-only keyboard-free limit editor: the existing button appearance and
-/// callback semantics are retained, but its widgets are stacked vertically
-/// for the SYS/MAP/DIA columns and the PPV controls below them.
-#[allow(clippy::too_many_arguments)]
-fn art_touch_limit(grid: &gtk::Grid, column: i32, row: i32,
- initial: Option<i32>, fallback: i32,
- step: i32, maximum: i32) -> Rc<Cell<Option<i32>>> {
- let state = Rc::new(Cell::new(initial));
- let previous = Rc::new(Cell::new(initial.unwrap_or(fallback)));
- let controls = gtk::Box::new(Orientation::Vertical, 7);
- controls.set_halign(gtk::Align::Center);
- controls.set_hexpand(true);
-
- let plus = gtk::Button::with_label("+");
- plus.set_size_request(54, 50);
- plus.set_halign(gtk::Align::Center);
- controls.append(&plus);
-
+ plus.set_tooltip_text(Some("Increase alarm limit"));
let display = gtk::Label::new(None);
display.add_css_class("ecg-limit-value");
display.set_width_chars(5);
display.set_xalign(0.5);
- controls.append(&display);
-
let minus = gtk::Button::with_label("−");
minus.set_size_request(54, 50);
- minus.set_halign(gtk::Align::Center);
- controls.append(&minus);
-
+ minus.set_tooltip_text(Some("Decrease alarm limit"));
let toggle = gtk::Button::new();
toggle.set_size_request(78, 50);
- toggle.set_halign(gtk::Align::Center);
+ toggle.set_tooltip_text(Some("Enable or disable this alarm limit"));
show_touch_hr_limit(initial, &display, &toggle);
+
+ // Requested left-to-right order: plus, value, minus, OFF.
+ controls.append(&plus);
+ controls.append(&display);
+ controls.append(&minus);
controls.append(&toggle);
for (button, direction) in [(plus, 1), (minus, -1)] {
@@ -1019,12 +778,11 @@
let display = display.clone();
let toggle = toggle.clone();
button.connect_clicked(move |_| {
- let new_value = state.get().map_or(previous.get(), |current| {
- (current + direction * step).clamp(0, maximum)
- });
- state.set(Some(new_value));
- previous.set(new_value);
- show_touch_hr_limit(Some(new_value), &display, &toggle);
+ let next = stepped_alarm_limit(state.get(), previous.get(),
+ direction, step, maximum);
+ state.set(Some(next));
+ previous.set(next);
+ show_touch_hr_limit(Some(next), &display, &toggle);
});
}
toggle.connect_clicked({
@@ -1032,65 +790,74 @@
let previous = previous.clone();
let display = display.clone();
move |button| {
- let new_value = match state.get() {
+ let next = match state.get() {
Some(value) => { previous.set(value); None }
None => Some(previous.get()),
};
- state.set(new_value);
- show_touch_hr_limit(new_value, &display, button);
- }
- });
- grid.attach(&controls, column, row, 1, 1);
- state
-}
-
-/// Map the four ART parameters to the three-column alarm grid. Row 1 is
-/// upper thresholds, row 2 lower; PPV occupies column SYS in rows 4 and 5.
-fn art_alarm_position(index: usize) -> (i32, i32, i32, i32, &'static str) {
- match index {
- 0 => (1, 0, 1, 2, "SYS"),
- 1 => (2, 0, 1, 2, "MAP"),
- 2 => (3, 0, 1, 2, "DIA"),
- 3 => (1, 3, 4, 5, "PPV"),
- _ => unreachable!("ART has exactly four alarm parameters"),
- }
-}
-
-/// The ART alarm menu groups SYS/MAP/DIA into columns with upper limits in
-/// the first row and lower limits in the second; PPV occupies the first
-/// parameter column beneath them. It reuses the same alarm draft/Apply path.
-fn art_alarm_grid(specs: Vec<TouchAlarmSpec>, drafts: &mut Vec<TouchAlarmDraft>) -> gtk::Box {
- let frame = gtk::Box::new(Orientation::Vertical, 16);
- frame.add_css_class("art-limit-frame");
+ state.set(next);
+ show_touch_hr_limit(next, &display, button);
+ }
+ });
+ (controls, state)
+}
+
+/// Short names in the alarm matrix; full labels remain available as tooltips.
+fn alarm_matrix_label(name: &str) -> &str {
+ match name {
+ "ART systolic" | "NIBP systolic" => "SYS",
+ "ART MAP" | "NIBP MAP" => "MAP",
+ "ART diastolic" | "NIBP diastolic" => "DIA",
+ "Pulse rate" => "PR",
+ "Respiratory rate" => "RR",
+ other => other,
+ }
+}
+
+/// Common touchscreen matrix for ECG, SpO2, ART, CO2 and NIBP.
+/// Each parameter occupies one horizontal row; lower and upper limits have
+/// identical columns and the action order [+] value [−] [OFF/ON].
+fn alarm_limit_matrix(specs: Vec<TouchAlarmSpec>,
+ drafts: &mut Vec<TouchAlarmDraft>) -> gtk::Box {
+ let frame = gtk::Box::new(Orientation::Vertical, 8);
+ frame.add_css_class("alarm-limit-frame");
frame.set_hexpand(true);
let heading = gtk::Label::new(Some("Alarm Limits"));
- heading.add_css_class("art-limit-heading");
+ heading.add_css_class("alarm-limit-heading");
heading.set_xalign(0.0);
frame.append(&heading);
let grid = gtk::Grid::new();
grid.set_hexpand(true);
- grid.set_column_spacing(12);
- grid.set_row_spacing(23);
-
- for (row, arrow) in [(1, "↑"), (2, "↓"), (4, "↑"), (5, "↓")] {
- let label = gtk::Label::new(Some(arrow));
- label.add_css_class("art-limit-arrow");
- label.set_width_chars(2);
- grid.attach(&label, 0, row, 1, 1);
- }
- for (i, spec) in specs.into_iter().enumerate() {
- let (column, title_row, upper_row, lower_row, title) = art_alarm_position(i);
- let label = gtk::Label::new(Some(title));
- label.add_css_class("art-limit-heading");
- label.set_hexpand(true);
- grid.attach(&label, column, title_row, 1, 1);
-
- let upper = art_touch_limit(&grid, column, upper_row, spec.limits.upper,
+ grid.set_column_spacing(8);
+ grid.set_row_spacing(8);
+
+ for (column, text) in [(1, "↓ Lower"), (2, "↑ Upper")] {
+ let label = gtk::Label::new(Some(text));
+ label.add_css_class("alarm-limit-column-heading");
+ label.set_halign(gtk::Align::Center);
+ grid.attach(&label, column, 0, 1, 1);
+ }
+
+ for (index, spec) in specs.into_iter().enumerate() {
+ // An empty narrow divider row keeps each parameter visually distinct.
+ let base = 1 + (index as i32) * 2;
+ if index > 0 {
+ grid.attach(&ecg_menu_divider(), 0, base - 1, 3, 1);
+ }
+ let label = gtk::Label::new(Some(alarm_matrix_label(spec.name)));
+ label.set_xalign(0.0);
+ label.set_tooltip_text(Some(&format!("{} ({})", spec.name, spec.unit)));
+ label.add_css_class("alarm-limit-heading");
+ label.set_width_chars(5);
+ grid.attach(&label, 0, base, 1, 1);
+
+ let (lower_controls, lower) = alarm_matrix_cell(spec.limits.lower,
+ spec.restore_lower, spec.step, spec.maximum);
+ let (upper_controls, upper) = alarm_matrix_cell(spec.limits.upper,
spec.restore_upper, spec.step, spec.maximum);
- let lower = art_touch_limit(&grid, column, lower_row, spec.limits.lower,
- spec.restore_lower, spec.step, spec.maximum);
+ grid.attach(&lower_controls, 1, base, 1, 1);
+ grid.attach(&upper_controls, 2, base, 1, 1);
drafts.push(TouchAlarmDraft {
name: spec.name, lower, upper, apply: spec.apply,
});
@@ -1128,7 +895,7 @@
render::TouchChannel::Art => "ART / SETTINGS",
render::TouchChannel::Capno => "CO₂ / SETTINGS",
render::TouchChannel::Nibp => "NIBP / SETTINGS",
- render::TouchChannel::Ecg => return,
+ render::TouchChannel::Ecg => "ECG / SETTINGS",
};
let dialog = gtk::Window::builder()
.application(app)
@@ -1136,8 +903,13 @@
.transient_for(monitor)
.modal(true)
.resizable(true)
- .default_width(if channel == render::TouchChannel::Art { 720 } else { 560 })
- .default_height(if channel == render::TouchChannel::Art { 790 } else { 610 })
+ .default_width(800)
+ .default_height(match channel {
+ render::TouchChannel::Art => 560,
+ render::TouchChannel::Nibp => 490,
+ render::TouchChannel::Ecg => 310,
+ _ => 420,
+ })
.build();
dialog.add_css_class("ecg-settings");
dialog.set_decorated(false);
@@ -1166,45 +938,22 @@
inner.append(&heading);
inner.append(&ecg_menu_divider());
- // Every numeric alarm has two optional bounds, editable without a keyboard.
+ // A shared horizontal matrix is used in every monitor-side touch menu.
let specs = module_alarm_specs(channel, &current);
let mut alarm_drafts = Vec::new();
- if channel == render::TouchChannel::Art {
- // The ART panel uses the requested column/row arrangement. Other
- // channels retain their current one-parameter-at-a-time layout.
- inner.append(&art_alarm_grid(specs, &mut alarm_drafts));
- } else {
- for spec in specs {
- let label = gtk::Label::new(Some(&format!("{} alarm limits · {}", spec.name, spec.unit)));
- label.set_xalign(0.0);
- inner.append(&label);
- let lower = module_touch_limit(&inner, "↓ Lower", spec.limits.lower,
- spec.restore_lower, spec.step, spec.maximum);
- let upper = module_touch_limit(&inner, "↑ Upper", spec.limits.upper,
- spec.restore_upper, spec.step, spec.maximum);
- alarm_drafts.push(TouchAlarmDraft {
- name: spec.name, lower, upper, apply: spec.apply,
- });
- inner.append(&ecg_menu_divider());
- }
- }
+ inner.append(&alarm_limit_matrix(specs, &mut alarm_drafts));
let error = gtk::Label::new(None);
error.set_xalign(0.0);
error.add_css_class("menu-error");
error.set_wrap(true);
- // The ART layout is taller; keep validation and buttons visible while
- // the alarm-limit controls scroll on smaller monitor touchscreens.
+ // Validation and Apply/Cancel stay fixed when the matrix scrolls.
let footer = gtk::Box::new(Orientation::Vertical, 8);
- if channel == render::TouchChannel::Art {
- footer.set_margin_start(20);
- footer.set_margin_end(20);
- footer.set_margin_top(8);
- footer.set_margin_bottom(12);
- footer.append(&error);
- } else {
- inner.append(&error);
- }
+ footer.set_margin_start(20);
+ footer.set_margin_end(20);
+ footer.set_margin_top(8);
+ footer.set_margin_bottom(12);
+ footer.append(&error);
let buttons = gtk::Box::new(Orientation::Horizontal, 12);
buttons.set_halign(gtk::Align::End);
let cancel = gtk::Button::with_label("Cancel");
@@ -1244,12 +993,8 @@
});
buttons.append(&cancel);
buttons.append(&apply);
- if channel == render::TouchChannel::Art {
- footer.append(&buttons);
- content.append(&footer);
- } else {
- inner.append(&buttons);
- }
+ footer.append(&buttons);
+ content.append(&footer);
dialog.set_child(Some(&content));
let escape = gtk::EventControllerKey::new();
@@ -1286,21 +1031,29 @@
}
#[test]
- fn art_menu_columns_follow_sys_map_dia_and_ppv_order() {
- assert_eq!(art_alarm_position(0), (1, 0, 1, 2, "SYS"));
- assert_eq!(art_alarm_position(1), (2, 0, 1, 2, "MAP"));
- assert_eq!(art_alarm_position(2), (3, 0, 1, 2, "DIA"));
- assert_eq!(art_alarm_position(3), (1, 3, 4, 5, "PPV"));
- let specs = module_alarm_specs(render::TouchChannel::Art, &Parameters::default());
- assert_eq!(specs.iter().map(|spec| spec.name).collect::<Vec<_>>(),
- ["ART systolic", "ART MAP", "ART diastolic", "PPV"]);
- let mut alarms = AlarmSettings::default();
+ fn alarm_matrix_order_and_labels() {
+ let p = Parameters::default();
+ for (channel, names) in [
+ (render::TouchChannel::Ecg, vec!["HR"]),
+ (render::TouchChannel::Spo2, vec!["SpO₂", "PR"]),
+ (render::TouchChannel::Art, vec!["SYS", "MAP", "DIA", "PPV"]),
+ (render::TouchChannel::Capno, vec!["EtCO₂", "RR"]),
+ (render::TouchChannel::Nibp, vec!["SYS", "MAP", "DIA"]),
+ ] {
+ let specs = module_alarm_specs(channel, &p);
+ let actual: Vec<_> = specs.iter()
+ .map(|spec| alarm_matrix_label(spec.name)).collect();
+ assert_eq!(actual, names);
+ }
+ // Same underlying ART alarm setters are retained after rearrangement.
+ let specs = module_alarm_specs(render::TouchChannel::Art, &p);
let limits = [
AlarmLimits { lower: Some(80), upper: Some(180) },
AlarmLimits { lower: Some(60), upper: Some(100) },
AlarmLimits { lower: None, upper: None },
AlarmLimits { lower: None, upper: Some(10) },
];
+ let mut alarms = AlarmSettings::default();
for (spec, value) in specs.into_iter().zip(limits.iter().copied()) {
(spec.apply)(&mut alarms, value);
}

View file

@ -0,0 +1,463 @@
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "patient-monitor-simulation"
-version = "0.6.3"
+version = "0.6.4"
edition = "2021"
license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"
--- a/README.de.md
+++ b/README.de.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.6.3
+# Patient Monitor Simulation (PaMSim) — v0.6.4
Ein mit Rust und GTK4 entwickelter Patient*innenmonitor-Simulator mit zwei Fenstern für die Lehre unter Fedora Linux.
@@ -26,7 +26,7 @@
Beim Ausblenden anderer Parameter werden die verbleibenden Kurvenzeilen wie
bisher dynamisch verteilt.
-## Touch-Bedienung am Monitor: ausschließlich Alarmgrenzen (v0.6.1)
+## Touch-Bedienung am Monitor: Alarmgrenzen und NIBP-Funktionen (v0.6.4)
Durch Berühren oder Anklicken der **Kurve oder des numerischen Wertefeldes**
von EKG, SpO₂, ART oder CO₂ öffnet sich das entsprechende Alarmmenü. Bei
@@ -36,7 +36,7 @@
Hintergrund, sehr hellgraue Schrift sowie 0,8 Pixel breite Begrenzungs-
und Trennlinien** wie der Hauptmonitor.
-**Am Monitor können ausschließlich Alarmgrenzen eingestellt werden.**
+**In allen Monitor-Menüs können die Alarmgrenzen eingestellt werden.**
Für jede untere und obere Alarmgrenze stehen große **−/+**-Tasten sowie
separate **ON/OFF**-Tasten zur Verfügung. Nicht gesetzte Grenzwerte sind
deaktiviert. Ein unterer Grenzwert darf den oberen nicht überschreiten.
@@ -55,18 +55,20 @@
**Cancel** oder **Esc** werden nicht übernommene Änderungen verworfen.
Die Auswahl der EKG-Ableitung, SpO₂-Signalqualität und Sensorverbindung,
-der arteriellen Kurvenform, der Kapnogrammform sowie **sämtliche NIBP-
-Messfunktionen** sind ausschließlich im **Admin-Fenster** verfügbar. Dazu
-zählen Messintervall, automatische Messung, **Measure now**, simulierter
-Messausfall und Manschettenlokalisation. Diese Parameter können über die
-Alarmmenüs am Monitor nicht verändert werden.
+der arteriellen Kurvenform und der Kapnogrammform bleiben ausschließlich im
+**Admin-Fenster**. Das **NIBP-Touchmenü** bietet zusätzlich **Measure now**,
+**Automatic measurement ON/OFF** und **Measurement interval** (1, 3, 5, 10,
+20, 30 oder 60 Minuten). Intervall und Automatik werden erst mit **Apply**
+übernommen; **Measure now** startet dagegen sofort, auch bei deaktivierter
+Automatik. Eine bereits laufende Messung wird nicht erneut gestartet.
+Simulierter Messausfall und Manschettenlokalisation bleiben Admin-only.
### NIBP beim Programmstart
Die **automatische NIBP-Messung ist beim Start ausgeschaltet**. Anfangs
zeigt der Monitor `---/---` (MAP `---`); es findet keine Messung statt.
-Die erste Messung wird über **Measure now** im Admin-Fenster oder durch
-Aktivieren von **Automatic NIBP measurement** ausgelöst. Beim Einschalten
+Die erste Messung wird über **Measure now** im NIBP-Touchmenü oder Admin-Fenster
+oder durch Aktivieren von **Automatic NIBP measurement** ausgelöst. Beim Einschalten
von Auto beginnt sofort ein Messzyklus; das Intervall zählt anschließend
jeweils ab Ende der vorherigen Messung. Beim Ausschalten von Auto wird
eine bereits laufende Messung nicht abgebrochen. **Measure now** funktioniert
@@ -83,8 +85,8 @@
Deaktivieren liegt unmittelbar rechts von Minus. Größe, Gestaltung,
Schrittweite, Wiederherstellung des letzten Werts sowie Apply/Cancel
bleiben erhalten. Bei Platzmangel lässt sich die Matrix scrollen, während
-Apply und Cancel zugänglich bleiben. Andere Einstellungen bleiben dem
-Admin-Fenster vorbehalten.
+Apply und Cancel zugänglich bleiben. Andere Einstellungen bleiben dem Admin-Fenster vorbehalten, mit Ausnahme der
+expliziten NIBP-Messfunktionen im Touchmenü.
## Thoraxkompressionen (v0.5.4)
@@ -607,3 +609,13 @@
Kurvenformen sowie NIBP-Messfunktionen wurden aus den Monitor-Menüs entfernt
und bleiben im Admin-Fenster verfügbar. Die Simulationslogik, Alarmprüfung
und das NIBP-Startverhalten wurden nicht verändert.
+
+### v0.6.4 – NIBP-Touchbedienung wiederhergestellt
+
+Das NIBP-Menü enthält wieder **Measure now**, **Automatic measurement ON/OFF**
+und das **Messintervall** (1, 3, 5, 10, 20, 30 oder 60 Minuten) oberhalb der
+SYS/MAP/DIA-Alarmmatrix. Die Einstellungen für Intervall und Automatik werden
+mit **Apply** gespeichert; **Measure now** startet unmittelbar einen Messzyklus,
+auch wenn die Automatik ausgeschaltet ist. Die Admin-Oberfläche wird
+synchronisiert. Die anderen Parametermenüs bleiben auf Alarmgrenzen beschränkt.
+Manschettenzuordnung und simulierter Messausfall verbleiben im Admin-Fenster.
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.6.3
+# Patient Monitor Simulation (PaMSim) — v0.6.4
A Rust/GTK4 patient-monitor simulator with two main windows for teaching on Fedora Linux.
@@ -23,7 +23,7 @@
bottom measurement row and other three groups remain present. Disabling one
of the four waveform channels still reflows the remaining rows above it.
-## Monitor touchscreen: alarm limits only (v0.6.1)
+## Monitor touchscreen: alarm limits and NIBP controls (v0.6.4)
Tap or click the **waveform or numerical readout** of ECG, SpO₂, ART or CO₂
to open that channel's alarm-limit panel. For NIBP, tap the **rightmost
@@ -32,7 +32,7 @@
are available in fullscreen and retain a **black background, very light-grey
text, and 0.8-pixel borders and dividers**, in the style of the main monitor.
-**Only alarm thresholds can be modified from the monitor-side menus.**
+**Alarm thresholds can be modified from every monitor-side menu.**
No keyboard is required: every lower/upper limit has large **− / +** controls
with a parameter-specific increment and an independent **ON/OFF** control.
Unset limits remain disabled. The lower limit cannot exceed the upper limit.
@@ -49,18 +49,20 @@
Changing a threshold sets the alarm preset to **Custom**. **Cancel** or
**Esc** discards the draft changes.
-ECG lead selection, SpO₂ signal quality and sensor status, ART waveform shape,
-capnogram shape, and all NIBP measurement controls are **Admin-only**. This
-includes NIBP measurement interval, Auto ON/OFF, **Measure now**, simulated
-failed reading, and cuff placement. None of these physiological or technical
-parameters is changed by the monitor-side alarm menus.
+**NIBP is the exception:** its monitor-side menu additionally provides **Measure now**,
+**Automatic measurement ON/OFF**, and the **1/3/5/10/20/30/60-minute interval**.
+Interval and Auto changes take effect with **Apply** (or are discarded with
+Cancel/Esc); **Measure now starts immediately**, even with Auto OFF and before
+Apply. The touch controls synchronize with Admin. A measurement already in
+progress is not restarted. The simulated failure option and cuff placement
+remain Admin-only, as do ECG lead, SpO₂ sensor/quality and waveform choices.
### NIBP startup and automatic measurements
**Auto measurement is OFF by default.** On startup the monitor shows
`---/---` (MAP `---`) and no measurement is initiated. To obtain a reading,
-select **Measure now** in Admin, or enable **Automatic NIBP measurement**
-there. The first automatic cycle begins immediately after enabling Auto;
+select **Measure now** in the NIBP monitor menu (or in Admin), or enable
+**Automatic NIBP measurement** via the menu (or Admin). The first automatic cycle begins immediately after enabling Auto;
subsequent measurement intervals count from completion of the prior cycle.
Disabling Auto stops further scheduled measurements without interrupting a
cycle already in progress. Manual measurement remains possible while Auto
@@ -77,7 +79,8 @@
large button styling, per-parameter increments, last-value restoration,
optional bounds and Apply/Cancel semantics are unchanged. The matrix scrolls
if necessary while Apply and Cancel remain accessible below it. Other
-physiological and NIBP controls remain Admin-only.
+physiological controls remain Admin-only, except for the three explicitly
+requested NIBP measurement controls.
## Chest compressions (v0.5.4)
@@ -620,3 +623,14 @@
measurement controls from monitor-side menus. These remain available in
Admin, including manual NIBP measurement and Auto ON/OFF. No physiological
model, alarm evaluation or NIBP startup behavior was changed.
+
+### v0.6.4 — NIBP touch controls restored
+
+The monitor-side NIBP settings menu again contains **Measure now**,
+**Automatic measurement ON/OFF** and the **measurement interval** (1, 3, 5,
+10, 20, 30, 60 minutes). These controls are above the horizontal SYS/MAP/DIA
+alarm matrix and share its monochrome touchscreen styling. Auto and interval
+are saved with Apply; Measure now starts a cuff cycle immediately regardless
+of Auto. Both monitor and Admin display the selected settings. Other monitor
+menus remain limited to alarm thresholds; NIBP cuff placement, the simulated
+failed-reading option and non-NIBP signal settings remain Admin-only.
--- a/src/simulation.rs
+++ b/src/simulation.rs
@@ -277,6 +277,10 @@
}
p.spo2_status_at_quality(self.pulse_rate(), self.poor_signal_lost(),
self.spo2_quality(p))
+ }
+
+ pub fn nibp_measuring(&self) -> bool {
+ self.nibp.measuring()
}
pub fn start_nibp_now(&mut self, p: &Parameters) {
--- a/src/ui.rs
+++ b/src/ui.rs
@@ -108,8 +108,8 @@
});
window.add_controller(keys);
- // One gesture opens alarm-only panels for visible waveform/numeric rows
- // and NIBP's bottom-right cell. Mouse and Wayland touch share geometry.
+ // Mouse and Wayland touch open the visible module's settings panel.
+ // NIBP alone also includes its explicitly requested measurement controls.
let monitor_menu: MonitorMenuHandle = Rc::new(RefCell::new(None));
let click = gtk::GestureClick::new();
click.connect_released({
@@ -117,13 +117,14 @@
let window = window.clone();
let canvas = canvas.clone();
let params = params.clone();
+ let simulator = simulator.clone();
move |_gesture, _press_count, x, y| {
let touched = {
let p = params.borrow();
render::monitor_hit_test(x, y, canvas.width(), canvas.height(), &p)
};
if let Some(channel) = touched {
- open_module_menu(&app, &window, params.clone(),
+ open_module_menu(&app, &window, params.clone(), simulator.clone(),
admin_changed.clone(), monitor_menu.clone(), channel);
}
}
@@ -133,11 +134,25 @@
window
}
-/// Map an Admin NIBP measurement interval to its dropdown selection.
-/// The touchscreen alarm menus do not expose scheduling controls.
+/// Both Admin and the monitor NIBP menu use the same interval options.
+const NIBP_INTERVALS: [i32; 7] = [1, 3, 5, 10, 20, 30, 60];
+
fn nibp_interval_index(minutes: i32) -> u32 {
- const INTERVALS: [i32; 7] = [1, 3, 5, 10, 20, 30, 60];
- INTERVALS.iter().position(|&value| value == minutes).unwrap_or(2) as u32
+ NIBP_INTERVALS.iter().position(|&value| value == minutes).unwrap_or(2) as u32
+}
+
+fn nibp_interval_minutes(selected: u32) -> i32 {
+ NIBP_INTERVALS.get(selected as usize).copied().unwrap_or(5)
+}
+
+/// Apply only the explicitly requested monitor-side NIBP measurement settings.
+/// Neither cuff settings nor any other module's configuration is changed.
+fn apply_nibp_measurement_settings(p: &mut Parameters, selected: u32, auto: bool) -> bool {
+ let minutes = nibp_interval_minutes(selected);
+ let changed = p.nibp_interval_minutes != minutes || p.nibp_auto_measurement != auto;
+ p.nibp_interval_minutes = minutes;
+ p.nibp_auto_measurement = auto;
+ changed
}
fn create_admin(app: &Application, params: SharedParams,
@@ -437,10 +452,9 @@
let nibp_interval_dropdown = add_dropdown_at(&nibp, "Measurement interval",
&["1 min", "3 min", "5 min", "10 min", "20 min", "30 min", "60 min"],
- 2, params.clone(), |p, selected| {
- p.nibp_interval_minutes = match selected {
- 0 => 1, 1 => 3, 2 => 5, 3 => 10, 4 => 20, 5 => 30, _ => 60,
- };
+ nibp_interval_index(params.borrow().nibp_interval_minutes),
+ params.clone(), |p, selected| {
+ p.nibp_interval_minutes = nibp_interval_minutes(selected);
});
let nibp_auto = gtk::CheckButton::with_label("Automatic NIBP measurement");
nibp_auto.set_active(params.borrow().nibp_auto_measurement);
@@ -602,6 +616,10 @@
min-height: 48px; min-width: 52px;
}
window.ecg-settings button:hover { background-color: #303437; }
+ window.ecg-settings dropdown {
+ color: #e5e9eb; background-color: #171717;
+ border: 1px solid #6b757d; min-height: 48px;
+ }
window.ecg-settings button.ecg-apply {
color: #000000; background-color: #e5e9eb; font-weight: bold;
}
@@ -866,8 +884,85 @@
frame
}
-/// A monitor-side menu may change only alarm limits. All patient and
-/// measurement configuration (including NIBP scheduling) stays Admin-only.
+/// Add the three explicitly requested NIBP actions to the monitor menu.
+/// Alarm limits, interval and Auto are staged until Apply. "Measure now" is
+/// an immediate command, independent of Auto and of the staged settings.
+fn nibp_touch_measurement_controls(
+ current: &Parameters,
+ params: SharedParams,
+ simulator: Rc<RefCell<Simulator>>,
+) -> (gtk::Box, gtk::DropDown, gtk::ToggleButton) {
+ let section = gtk::Box::new(Orientation::Vertical, 12);
+ section.add_css_class("alarm-limit-frame");
+ section.set_hexpand(true);
+
+ let heading = gtk::Label::new(Some("NIBP measurement"));
+ heading.add_css_class("alarm-limit-heading");
+ heading.set_xalign(0.0);
+ section.append(&heading);
+
+ let row = gtk::Box::new(Orientation::Horizontal, 12);
+ let label = gtk::Label::new(Some("Measurement interval"));
+ label.set_hexpand(true);
+ label.set_xalign(0.0);
+ let interval = gtk::DropDown::from_strings(&[
+ "1 min", "3 min", "5 min", "10 min", "20 min", "30 min", "60 min",
+ ]);
+ interval.set_selected(nibp_interval_index(current.nibp_interval_minutes));
+ interval.set_size_request(160, 52);
+ row.append(&label);
+ row.append(&interval);
+ section.append(&row);
+
+ let action_row = gtk::Box::new(Orientation::Horizontal, 12);
+ action_row.set_homogeneous(true);
+ let auto = gtk::ToggleButton::new();
+ auto.set_active(current.nibp_auto_measurement);
+ auto.set_label(if auto.is_active() {
+ "Automatic measurement: ON"
+ } else {
+ "Automatic measurement: OFF"
+ });
+ auto.connect_toggled(|button| {
+ button.set_label(if button.is_active() {
+ "Automatic measurement: ON"
+ } else {
+ "Automatic measurement: OFF"
+ });
+ });
+ action_row.append(&auto);
+
+ let measure_now = gtk::Button::with_label("Measure now");
+ measure_now.set_tooltip_text(Some("Start an NIBP cuff measurement immediately"));
+ action_row.append(&measure_now);
+ section.append(&action_row);
+
+ let feedback = gtk::Label::new(Some(
+ "Measure now acts immediately. Interval and Auto are saved with Apply."
+ ));
+ feedback.set_xalign(0.0);
+ feedback.set_wrap(true);
+ measure_now.connect_clicked({
+ let feedback = feedback.clone();
+ move |_| {
+ // Drop the immutable Ref before borrowing the simulator mutably.
+ let measuring = { simulator.borrow().nibp_measuring() };
+ if measuring {
+ feedback.set_text("NIBP measurement already in progress.");
+ } else {
+ simulator.borrow_mut().start_nibp_now(&params.borrow());
+ feedback.set_text("NIBP measurement started.");
+ }
+ }
+ });
+ // Keep the explanatory label visible while the button changes its status.
+ // It is owned by the section, not by the button callback.
+ section.append(&feedback);
+ (section, interval, auto)
+}
+
+/// All monitor modules can edit alarm limits. Only NIBP additionally offers
+/// the explicitly requested interval, Auto and immediate measurement controls.
fn apply_module_alarm_changes(
p: &mut Parameters,
limits: &[(fn(&mut AlarmSettings, AlarmLimits), AlarmLimits)],
@@ -879,12 +974,13 @@
p.alarms != previous
}
-/// Open a modal alarm-limit panel with the same black, grey, 0.8 px divider
-/// and border design as the ECG panel. Other parameters are Admin-only.
+/// Open a modal monitor settings panel in neutral black/grey styling.
+/// All modules edit alarm limits; NIBP also retains its explicit controls.
#[allow(clippy::too_many_arguments)]
fn open_module_menu(app: &Application, monitor: &ApplicationWindow,
- params: SharedParams, on_change: AdminChanged,
- open_menu: MonitorMenuHandle, channel: render::TouchChannel) {
+ params: SharedParams, simulator: Rc<RefCell<Simulator>>,
+ on_change: AdminChanged, open_menu: MonitorMenuHandle,
+ channel: render::TouchChannel) {
if let Some(existing) = open_menu.borrow().as_ref().and_then(|weak| weak.upgrade()) {
existing.present();
return;
@@ -906,7 +1002,7 @@
.default_width(800)
.default_height(match channel {
render::TouchChannel::Art => 560,
- render::TouchChannel::Nibp => 490,
+ render::TouchChannel::Nibp => 640,
render::TouchChannel::Ecg => 310,
_ => 420,
})
@@ -937,6 +1033,18 @@
heading.add_css_class("title-2");
inner.append(&heading);
inner.append(&ecg_menu_divider());
+
+ // NIBP is the explicit exception to the alarm-only monitor menu policy.
+ // Put the manual measurement action above the limit matrix for easy access.
+ let nibp_controls = if channel == render::TouchChannel::Nibp {
+ let (section, interval, auto) = nibp_touch_measurement_controls(
+ &current, params.clone(), simulator);
+ inner.append(&section);
+ inner.append(&ecg_menu_divider());
+ Some((interval, auto))
+ } else {
+ None
+ };
// A shared horizontal matrix is used in every monitor-side touch menu.
let specs = module_alarm_specs(channel, &current);
@@ -983,7 +1091,12 @@
}
let changed_alarms = {
let mut p = params.borrow_mut();
- apply_module_alarm_changes(&mut p, &selected_limits)
+ let changed = apply_module_alarm_changes(&mut p, &selected_limits);
+ if let Some((interval, auto)) = &nibp_controls {
+ apply_nibp_measurement_settings(&mut p,
+ interval.selected(), auto.is_active());
+ }
+ changed
};
if let Some(callback) = on_change.borrow().as_ref() {
callback(changed_alarms);
@@ -1064,7 +1177,7 @@
}
#[test]
- fn touchscreen_applies_only_alarm_limits_and_preserves_other_controls() {
+ fn monitor_alarm_edits_preserve_other_controls() {
let mut p = Parameters::default();
p.ecg_lead = EcgLead::V1;
p.spo2_quality = Spo2Quality::Poor;
@@ -1093,6 +1206,40 @@
assert!(p.nibp_cuff_on_art);
}
+ #[test]
+ fn nibp_touch_interval_roundtrip_and_startup_off() {
+ let p = Parameters::default();
+ assert!(!p.nibp_auto_measurement);
+ assert_eq!(p.nibp_interval_minutes, 5);
+ for (index, minutes) in NIBP_INTERVALS.into_iter().enumerate() {
+ assert_eq!(nibp_interval_index(minutes), index as u32);
+ assert_eq!(nibp_interval_minutes(index as u32), minutes);
+ }
+ assert_eq!(nibp_interval_minutes(99), 5);
+ }
+
+ #[test]
+ fn nibp_touch_apply_changes_only_interval_and_auto() {
+ let mut p = Parameters::default();
+ p.nibp_no_reading = true;
+ p.nibp_cuff_on_spo2 = true;
+ p.nibp_cuff_on_art = true;
+ p.show_nibp = false;
+ p.alarms.nibp_sys.lower = Some(80);
+ assert!(apply_nibp_measurement_settings(&mut p, 5, true));
+ assert_eq!(p.nibp_interval_minutes, 30);
+ assert!(p.nibp_auto_measurement);
+ assert!(!apply_nibp_measurement_settings(&mut p, 5, true));
+ assert!(apply_nibp_measurement_settings(&mut p, 0, false));
+ assert_eq!(p.nibp_interval_minutes, 1);
+ assert!(!p.nibp_auto_measurement);
+ assert!(p.nibp_no_reading);
+ assert!(p.nibp_cuff_on_spo2);
+ assert!(p.nibp_cuff_on_art);
+ assert!(!p.show_nibp);
+ assert_eq!(p.alarms.nibp_sys.lower, Some(80));
+ }
+
}
/// Frame a parameter section with an optional monitor-colored left sidebar.

View file

@ -0,0 +1,180 @@
diff --git a/Cargo.toml b/Cargo.toml
index 46b979b..8087e1c 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "patient-monitor-simulation"
-version = "0.6.4"
+version = "0.6.5"
edition = "2021"
license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"
diff --git a/README.de.md b/README.de.md
index d9f1101..3a42b91 100644
--- a/README.de.md
+++ b/README.de.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.6.4
+# Patient Monitor Simulation (PaMSim) — v0.6.5
Ein mit Rust und GTK4 entwickelter Patient*innenmonitor-Simulator mit zwei Fenstern für die Lehre unter Fedora Linux.
@@ -175,7 +175,7 @@ Mit **F11** wird der Vollbildmodus aktiviert bzw. umgeschaltet, mit **Esc** wird
Unter Wayland sollte das Fenster vor dem Wechsel in den Vollbildmodus auf den gewünschten Präsentationsbildschirm verschoben werden.
Der Vollbildmodus sperrt den Computer nicht gegen andere Eingaben.
-## Akustische Alarme (v0.5.3)
+## Akustische Alarme (aktualisiert v0.6.5)
Die akustische Alarmierung ist **standardmäßig eingeschaltet**. Im
Admin-Fenster lässt sie sich mit **Audible alarms** aktivieren bzw. stummschalten.
@@ -183,11 +183,14 @@ Mit **Test tone** kann die Tonausgabe unabhängig von der Stummschaltung geprüf
werden. Die optischen Alarme blinken bei stummgeschalteter Tonausgabe weiterhin.
- **Kritische Rhythmusalarme:** VT, PVT, Kammerflimmern und Asystolie lösen
- einen Doppelton aus (zweimal kurz 880 Hz), der ungefähr alle 1,5 Sekunden
- wiederholt wird.
+ einen **Zweiklang aus aufeinanderfolgenden, unterschiedlichen Tönen** aus
+ (880 Hz gefolgt von 1160 Hz), der ungefähr alle 1,5 Sekunden wiederholt wird.
- **Numerische und technische Alarme:** Grenzwertüberschreitungen sowie
- **NO SENSOR** und **NO READING** lösen einen kurzen Ton mit 700 Hz aus,
- der ungefähr alle 2,5 Sekunden wiederholt wird.
+ **NO SENSOR** und **NO READING** lösen ebenfalls einen **Zweitonalarm** aus
+ (700 Hz gefolgt von 950 Hz), der ungefähr alle 2,5 Sekunden wiederholt wird.
+- Zwischen beiden Tönen liegt jeweils eine kurze Pause. Ein einzelner
+ **QRS-Piepton** ist für eine spätere Version vorgesehen und wird derzeit
+ noch nicht ausgegeben.
- Kritische Alarme haben Vorrang. Auch bei mehreren gleichzeitig aktiven
Alarmen wird nur eine Tonfolge ausgegeben. Bei behobenem Alarm oder
Stummschaltung verstummt die Ausgabe. Ausgeblendete Monitorbereiche
@@ -619,3 +622,13 @@ mit **Apply** gespeichert; **Measure now** startet unmittelbar einen Messzyklus,
auch wenn die Automatik ausgeschaltet ist. Die Admin-Oberfläche wird
synchronisiert. Die anderen Parametermenüs bleiben auf Alarmgrenzen beschränkt.
Manschettenzuordnung und simulierter Messausfall verbleiben im Admin-Fenster.
+
+
+### v0.6.5 – Zweitonige akustische Alarme
+
+Sowohl Standard- und technische Alarme als auch kritische Rhythmusalarme
+bestehen nun aus zwei aufeinanderfolgenden Tönen unterschiedlicher Frequenz.
+Die Priorisierung und die Wiederholungsintervalle bleiben unverändert.
+**Test tone** spielt den Standard-Zweitonalarm. Ein einzelner QRS-Piepton
+ist für eine spätere Erweiterung reserviert. Optische Alarme und
+Simulationsverhalten wurden nicht verändert.
diff --git a/README.md b/README.md
index faab37e..f413723 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.6.4
+# Patient Monitor Simulation (PaMSim) — v0.6.5
A Rust/GTK4 patient-monitor simulator with two main windows for teaching on Fedora Linux.
@@ -166,17 +166,21 @@ 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.
-## Audible alarms (v0.5.3)
+## Audible alarms (updated v0.6.5)
Sound is **enabled by default**. The Admin window has an **Audible alarms**
checkbox for muting and a **Test tone** button (works even while muted).
Visual alarms keep blinking normally when sound is off.
-- **Critical rhythm alarm:** VT, PVT, VF and asystole produce a double beep
- (two short 880 Hz tones), repeated approximately every 1.5 seconds.
+- **Critical rhythm alarm:** VT, PVT, VF and asystole produce a higher-pitched
+ **two-tone** alert (880 Hz followed by 1160 Hz), repeated approximately
+ every 1.5 seconds.
- **Numerical and SpO₂ technical alarms:** out-of-range values, **NO SENSOR**
- and **NO READING** produce a single 700 Hz beep, repeated approximately
- every 2.5 seconds.
+ and **NO READING** produce a lower-pitched **two-tone** alert
+ (700 Hz followed by 950 Hz), repeated approximately every 2.5 seconds.
+- Both alarm signals use two **different successive pitches**, separated by
+ a brief silence. A distinct **single QRS beep is reserved for future work**;
+ QRS-related audio is not yet implemented.
- Critical alarms have priority: only one tone pattern is played even if
multiple alarms are active. The sound stops when all alarms clear or when
the checkbox is unchecked. Alarms on hidden monitor channels are excluded.
@@ -634,3 +638,12 @@ are saved with Apply; Measure now starts a cuff cycle immediately regardless
of Auto. Both monitor and Admin display the selected settings. Other monitor
menus remain limited to alarm thresholds; NIBP cuff placement, the simulated
failed-reading option and non-NIBP signal settings remain Admin-only.
+
+
+### v0.6.5 — Two-tone audible alarms
+
+Both standard/technical and critical alarm sounds now consist of two distinct
+successive pitches. Critical alarms retain their priority and faster repeat
+interval; standard alarms retain their slower cadence. The Admin test button
+plays the standard two-tone alert. A single QRS beep is reserved for a later
+release and is not generated yet. No visual alarm or simulation logic changed.
diff --git a/src/alarm.rs b/src/alarm.rs
index 116b7f4..6e0b1af 100644
--- a/src/alarm.rs
+++ b/src/alarm.rs
@@ -84,14 +84,21 @@ pub fn level(p: &Parameters, sim: &Simulator) -> AlarmLevel {
result
}
-/// Very short, original synthesized sine beeps; mono PCM16 WAV.
+/// Both alarm priorities sound as two successive, different pitches.
+/// A future QRS beep will be a separate, single-tone signal.
+/// Zero-frequency segments are short silences between the notes.
+fn tone_segments(critical: bool) -> &'static [(f64, f64)] {
+ if critical {
+ &[(880.0, 0.16), (0.0, 0.08), (1160.0, 0.16)]
+ } else {
+ &[(700.0, 0.14), (0.0, 0.06), (950.0, 0.14)]
+ }
+}
+
+/// Very short, original synthesized two-tone alerts; mono PCM16 WAV.
fn wav(critical: bool) -> Vec<u8> {
const SAMPLE_RATE: u32 = 44_100;
- let segments: &[(f64, f64)] = if critical {
- &[(880.0, 0.16), (0.0, 0.09), (880.0, 0.16)]
- } else {
- &[(700.0, 0.18)]
- };
+ let segments = tone_segments(critical);
let samples: usize = segments.iter()
.map(|(_, seconds)| (seconds * f64::from(SAMPLE_RATE)).round() as usize)
.sum();
@@ -267,8 +274,9 @@ impl AlarmAudio {
}
/// Called from a 100-ms GLib timer, not the 250-Hz waveform simulator.
- /// Critical rhythms: double tone every 1.5 s; other alarms: single tone
- /// every 2.5 s. Stop promptly when muted or all alarm states clear.
+ /// Critical rhythms: higher-pitched two-tone alert every 1.5 s;
+ /// other alarms: lower-pitched two-tone alert every 2.5 s.
+ /// Stop promptly when muted or all alarm states clear.
pub fn update(&mut self, level: AlarmLevel, enabled: bool) {
self.reap();
if !enabled || level == AlarmLevel::None {
@@ -322,6 +330,21 @@ mod tests {
assert!(wav(true).len() > wav(false).len());
}
+ #[test]
+ fn both_alarm_priorities_have_two_distinct_audible_pitches() {
+ for critical in [false, true] {
+ let segments = tone_segments(critical);
+ let notes: Vec<f64> = segments.iter()
+ .filter_map(|(hz, _seconds)| (*hz > 0.0).then_some(*hz))
+ .collect();
+ assert_eq!(notes.len(), 2, "each alarm pattern must contain two notes");
+ assert_ne!(notes[0], notes[1], "a two-tone alert needs distinct pitches");
+ assert!(segments.iter().any(|(hz, _)| *hz == 0.0), "notes must be separated");
+ assert!(segments.iter().all(|(_, seconds)| *seconds > 0.0));
+ }
+ assert_ne!(wav(false), wav(true));
+ }
+
#[test]
fn normal_signals_are_silent_and_numeric_limit_alarms_beep() {
let mut p = Parameters::default();

View file

@ -0,0 +1,749 @@
diff --git a/Cargo.toml b/Cargo.toml
index 8087e1c..f3abff3 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "patient-monitor-simulation"
-version = "0.6.5"
+version = "0.6.6"
edition = "2021"
license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"
diff --git a/README.de.md b/README.de.md
index 3a42b91..605a34f 100644
--- a/README.de.md
+++ b/README.de.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.6.5
+# Patient Monitor Simulation (PaMSim) — v0.6.6
Ein mit Rust und GTK4 entwickelter Patient*innenmonitor-Simulator mit zwei Fenstern für die Lehre unter Fedora Linux.
@@ -175,7 +175,7 @@ Mit **F11** wird der Vollbildmodus aktiviert bzw. umgeschaltet, mit **Esc** wird
Unter Wayland sollte das Fenster vor dem Wechsel in den Vollbildmodus auf den gewünschten Präsentationsbildschirm verschoben werden.
Der Vollbildmodus sperrt den Computer nicht gegen andere Eingaben.
-## Akustische Alarme (aktualisiert v0.6.5)
+## Akustische Alarme und QRS-Ton (aktualisiert v0.6.6)
Die akustische Alarmierung ist **standardmäßig eingeschaltet**. Im
Admin-Fenster lässt sie sich mit **Audible alarms** aktivieren bzw. stummschalten.
@@ -188,9 +188,10 @@ werden. Die optischen Alarme blinken bei stummgeschalteter Tonausgabe weiterhin.
- **Numerische und technische Alarme:** Grenzwertüberschreitungen sowie
**NO SENSOR** und **NO READING** lösen ebenfalls einen **Zweitonalarm** aus
(700 Hz gefolgt von 950 Hz), der ungefähr alle 2,5 Sekunden wiederholt wird.
-- Zwischen beiden Tönen liegt jeweils eine kurze Pause. Ein einzelner
- **QRS-Piepton** ist für eine spätere Version vorgesehen und wird derzeit
- noch nicht ausgegeben.
+- Zwischen beiden Tönen liegt jeweils eine kurze Pause. Zusätzlich gibt es
+ einen separaten, kurzen **QRS-/Pulston**, der im Admin-Fenster über
+ **QRS tone** unabhängig von **Audible alarms** ein- und ausgeschaltet wird
+ (standardmäßig eingeschaltet).
- Kritische Alarme haben Vorrang. Auch bei mehreren gleichzeitig aktiven
Alarmen wird nur eine Tonfolge ausgegeben. Bei behobenem Alarm oder
Stummschaltung verstummt die Ausgabe. Ausgeblendete Monitorbereiche
@@ -200,6 +201,42 @@ werden. Die optischen Alarme blinken bei stummgeschalteter Tonausgabe weiterhin.
selbst ist kein Alarm. Die Audioausgabe wird unabhängig von der Darstellung
der Kurven verarbeitet.
+### Synchroner QRS-/Pulston
+
+**QRS tone** ist unabhängig von **Audible alarms** schaltbar. Jeder kurze
+Piepton (85 ms) wird durch ein tatsächliches simuliertes elektrisches oder
+mechanisches Ereignis ausgelöst, nicht durch einen eigenen Taktgeber:
+
+- **SpO₂-Messwert vorhanden:** Auslösung beim verzögerten Pleth-Puls.
+ Die Frequenz richtet sich nach der angezeigten Sauerstoffsättigung.
+ Nicht übergeleitete mechanische Pulse erzeugen keinen Pleth-Piepton.
+- **Kein SpO₂-Messwert:** fester Ton mit **500 Hz** bei einem sichtbaren,
+ organisierten EKG-QRS; andernfalls bei einem dargestellten arteriellen
+ Pulsschlag. Bei gleichzeitig sichtbarem EKG und ART wird ein Herzschlag
+ nicht doppelt vertont.
+- **Kammerflimmern/Asystolie ohne wirksame Herzdruckmassage:** kein
+ Pulston. Bei Herzdruckmassage können ART-Pulse einen 500-Hz-Ton auslösen;
+ bei guter Kompressionsqualität und gültigem SpO₂-Messwert wird die
+ sättigungsabhängige Tonhöhe verwendet.
+
+| SpO₂ (%) | Frequenz (Hz) |
+| --- | ---: |
+| 97–100 | 740 |
+| 94–96 | 675 |
+| 90–93 | 609 |
+| 80–89 | 544 |
+| 70–79 | 479 |
+| 60–69 | 413 |
+| 50–59 | 348 |
+| 40–49 | 283 |
+| 30–39 | 218 |
+| 20–29 | 152 |
+| 0–19 | 87 |
+
+Die Frequenzen sind ausschließlich didaktische Simulationen, keine
+kalibrierten Töne eines klinischen Pulsoxymeters. QRS-/Pulston und
+Zweitonalarm können unabhängig voneinander erklingen.
+
Unter Fedora wird **`pw-play`** aus dem Paket `pipewire-utils` verwendet,
alternativ **`paplay`**. Es sind weder zusätzliche Rust-Bibliotheken noch
mitzuliefernde Audiodateien notwendig: Das Programm erzeugt seine WAV-Töne
@@ -632,3 +669,14 @@ Die Priorisierung und die Wiederholungsintervalle bleiben unverändert.
**Test tone** spielt den Standard-Zweitonalarm. Ein einzelner QRS-Piepton
ist für eine spätere Erweiterung reserviert. Optische Alarme und
Simulationsverhalten wurden nicht verändert.
+
+
+### v0.6.6 – Schaltbarer QRS-/Pulston
+
+Ein neuer Admin-Schalter **QRS tone** aktiviert oder deaktiviert den
+kurzen, beat-synchronen Einzelton unabhängig von den Zweitonalarmen.
+Bei vorhandenem SpO₂-Messwert richtet sich die Tonhöhe in elf Stufen
+zwischen 740 und 87 Hz nach der Sauerstoffsättigung; ohne SpO₂-Messwert
+erfolgt bei EKG-QRS oder arteriellem Puls ein 500-Hz-Ton. Die bisherigen
+Zweitonalarme bleiben unverändert. Zusätzliche Tests prüfen die
+Frequenzbereiche, Ereigniszuordnung und WAV-Ausgabe.
diff --git a/README.md b/README.md
index f413723..250b938 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.6.5
+# Patient Monitor Simulation (PaMSim) — v0.6.6
A Rust/GTK4 patient-monitor simulator with two main windows for teaching on Fedora Linux.
@@ -166,7 +166,7 @@ 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.
-## Audible alarms (updated v0.6.5)
+## Audible alarms and QRS tone (updated v0.6.6)
Sound is **enabled by default**. The Admin window has an **Audible alarms**
checkbox for muting and a **Test tone** button (works even while muted).
@@ -179,8 +179,8 @@ Visual alarms keep blinking normally when sound is off.
and **NO READING** produce a lower-pitched **two-tone** alert
(700 Hz followed by 950 Hz), repeated approximately every 2.5 seconds.
- Both alarm signals use two **different successive pitches**, separated by
- a brief silence. A distinct **single QRS beep is reserved for future work**;
- QRS-related audio is not yet implemented.
+ a brief silence. The single QRS/pulse beep is independent and configurable
+ using the new **QRS tone** checkbox in Admin (ON by default).
- Critical alarms have priority: only one tone pattern is played even if
multiple alarms are active. The sound stops when all alarms clear or when
the checkbox is unchecked. Alarms on hidden monitor channels are excluded.
@@ -188,6 +188,41 @@ Visual alarms keep blinking normally when sound is off.
trigger numerical limit alarms. The cuff measurement cycle by itself is not
an alarm. Audio playback is separate from waveform rendering and simulation.
+### Beat-synchronous QRS/pulse tone
+
+The **QRS tone** checkbox is independent of **Audible alarms**; turning off
+one does not mute the other. Each brief (85 ms), **single-frequency** beep
+follows an actual simulated beat event, not a separate rate timer:
+
+- **SpO₂ reading available:** beep on the delayed peripheral pleth pulse;
+ the pitch follows the *displayed* saturation (including during effective
+ good-quality chest compressions). Missed mechanical captures produce no
+ peripheral beep.
+- **SpO₂ reading unavailable:** a fixed **500 Hz** beep follows an organized
+ ECG QRS if ECG is displayed; otherwise it follows an arterial pulse if
+ ART is displayed. ECG and ART together do not cause duplicate beeps.
+- **VF/asystole without effective CPR:** no beat beep is generated. ART pulses
+ created by CPR can generate the fallback tone, while good CPR with a valid
+ SpO₂ reading uses the saturation-dependent tone.
+
+| SpO₂ (%) | Tone (Hz) |
+| --- | ---: |
+| 97–100 | 740 |
+| 94–96 | 675 |
+| 90–93 | 609 |
+| 80–89 | 544 |
+| 70–79 | 479 |
+| 60–69 | 413 |
+| 50–59 | 348 |
+| 40–49 | 283 |
+| 30–39 | 218 |
+| 20–29 | 152 |
+| 0–19 | 87 |
+
+Saturation tone pitches are deliberately simplified teaching tones, not
+calibrated clinical pulse-oximeter sounds. The QRS beep and two-tone alarm can
+sound independently; no alarm priority or visual alarm logic was changed.
+
On Fedora, sound is played through **`pw-play`** from `pipewire-utils`, with
**`paplay`** as a fallback. No additional Rust crates or sound files are needed:
the application creates its own short WAV tones at runtime. If neither player
@@ -647,3 +682,14 @@ successive pitches. Critical alarms retain their priority and faster repeat
interval; standard alarms retain their slower cadence. The Admin test button
plays the standard two-tone alert. A single QRS beep is reserved for a later
release and is not generated yet. No visual alarm or simulation logic changed.
+
+
+### v0.6.6 — Optional QRS/pulse beep
+
+Added a separate **QRS tone** checkbox (enabled by default). An 85 ms
+single-note beep follows actual ECG or mechanical beat events. With a valid
+SpO₂ reading, the delayed pleth pulse determines the timing and the oxygen
+saturation determines the pitch in eleven steps from 740 to 87 Hz; otherwise
+ECG QRS or ART pulses trigger a fixed 500 Hz tone. The two-tone alarm sounds
+remain unchanged. Added regression tests for band boundaries, event selection
+and single-tone WAV output.
diff --git a/src/alarm.rs b/src/alarm.rs
index 6e0b1af..89814d6 100644
--- a/src/alarm.rs
+++ b/src/alarm.rs
@@ -12,7 +12,7 @@ use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use crate::model::{AlarmLimits, AlarmState, Parameters, PulseConduction, Spo2Status};
-use crate::simulation::Simulator;
+use crate::simulation::{BeatEvent, BeatSource, Simulator};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub enum AlarmLevel {
@@ -84,6 +84,88 @@ pub fn level(p: &Parameters, sim: &Simulator) -> AlarmLevel {
result
}
+/// Single-note QRS/pulse beep. The oximeter is the source when it has a
+/// reading; otherwise use an ECG QRS or an available arterial pulse.
+/// Mid is the fixed pitch used when no SpO2 reading is present.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum QrsTone { Mid, Saturation(usize) }
+
+const QRS_MID_HZ: f64 = 500.0;
+const QRS_SPO2_HZ: [f64; 11] = [
+ 740.0, 675.0, 609.0, 544.0, 479.0, 413.0,
+ 348.0, 283.0, 218.0, 152.0, 87.0,
+];
+
+/// Stepwise saturation-to-pitch mapping: 100–97, 96–94, 93–90,
+/// then 89–80, 79–70, ..., 19–10%. 10% or less always gives 87 Hz.
+fn spo2_tone_index(saturation: i32) -> usize {
+ match saturation.clamp(0, 100) {
+ 97..=100 => 0,
+ 94..=96 => 1,
+ 90..=93 => 2,
+ 80..=89 => 3,
+ 70..=79 => 4,
+ 60..=69 => 5,
+ 50..=59 => 6,
+ 40..=49 => 7,
+ 30..=39 => 8,
+ 20..=29 => 9,
+ _ => 10,
+ }
+}
+
+pub fn qrs_tone(p: &Parameters, sim: &Simulator, events: &[BeatEvent]) -> Option<QrsTone> {
+ if p.show_spo2 && sim.spo2_status(p) == Spo2Status::Available {
+ // Actual peripheral pulses, not an independent HR metronome. This
+ // respects mechanical capture ratios and good-quality CPR.
+ return events.iter().any(|event| event.source == BeatSource::Pleth
+ && sim.time() - event.time <= 0.25)
+ .then_some(QrsTone::Saturation(spo2_tone_index(p.spo2)));
+ }
+ // ECG takes precedence over the delayed arterial signal: never beep twice
+ // for the same QRS when both monitor channels are visible.
+ if p.show_ecg && p.ecg_rhythm.has_qrs() && p.heart_rate > 0 {
+ return events.iter().any(|event| event.source == BeatSource::Ecg
+ && sim.time() - event.time <= 0.25)
+ .then_some(QrsTone::Mid);
+ }
+ if p.show_art {
+ return events.iter().any(|event| event.source == BeatSource::Art
+ && sim.time() - event.time <= 0.25)
+ .then_some(QrsTone::Mid);
+ }
+ None
+}
+
+/// Original, brief PCM16 sine wave with smooth fades to avoid clicks.
+fn single_beep_wav(frequency: f64) -> Vec<u8> {
+ const SAMPLE_RATE: u32 = 44_100;
+ const DURATION: f64 = 0.085;
+ let samples = (DURATION * f64::from(SAMPLE_RATE)).round() as usize;
+ let size = (samples * 2) as u32;
+ let mut bytes = Vec::with_capacity(44 + size as usize);
+ bytes.extend_from_slice(b"RIFF");
+ bytes.extend_from_slice(&(size + 36).to_le_bytes());
+ bytes.extend_from_slice(b"WAVEfmt ");
+ bytes.extend_from_slice(&16_u32.to_le_bytes());
+ bytes.extend_from_slice(&1_u16.to_le_bytes());
+ bytes.extend_from_slice(&1_u16.to_le_bytes());
+ bytes.extend_from_slice(&SAMPLE_RATE.to_le_bytes());
+ bytes.extend_from_slice(&(SAMPLE_RATE * 2).to_le_bytes());
+ bytes.extend_from_slice(&2_u16.to_le_bytes());
+ bytes.extend_from_slice(&16_u16.to_le_bytes());
+ bytes.extend_from_slice(b"data");
+ bytes.extend_from_slice(&size.to_le_bytes());
+ for i in 0..samples {
+ let t = i as f64 / f64::from(SAMPLE_RATE);
+ let remaining = (samples - i) as f64 / f64::from(SAMPLE_RATE);
+ let envelope = (t / 0.010).min(1.0).min(remaining / 0.016).max(0.0);
+ let value = (std::f64::consts::TAU * frequency * t).sin() * envelope * 0.13;
+ bytes.extend_from_slice(&((value * f64::from(i16::MAX)).round() as i16).to_le_bytes());
+ }
+ bytes
+}
+
/// Both alarm priorities sound as two successive, different pitches.
/// A future QRS beep will be a separate, single-tone signal.
/// Zero-frequency segments are short silences between the notes.
@@ -175,6 +257,115 @@ impl SoundFiles {
}
}
+/// Prepared once on startup. Reuse the same playback utility as the alarms,
+/// but use an independent child so the two-tone alarm is never interrupted by
+/// single QRS/pulse beeps.
+struct QrsSoundFiles {
+ mid: PathBuf,
+ saturations: Vec<PathBuf>,
+}
+
+impl Drop for QrsSoundFiles {
+ fn drop(&mut self) {
+ let _ = fs::remove_file(&self.mid);
+ for file in &self.saturations { let _ = fs::remove_file(file); }
+ }
+}
+
+impl QrsSoundFiles {
+ fn create_in(directory: &Path) -> io::Result<Self> {
+ let nonce = SystemTime::now().duration_since(UNIX_EPOCH)
+ .unwrap_or_default().as_nanos();
+ let prefix = format!("pamsim-qrs-{}-{nonce}", std::process::id());
+ let mid = directory.join(format!("{prefix}-mid.wav"));
+ write_new(&mid, &single_beep_wav(QRS_MID_HZ))?;
+ let mut files = Self { mid, saturations: Vec::new() };
+ for (i, &frequency) in QRS_SPO2_HZ.iter().enumerate() {
+ let path = directory.join(format!("{prefix}-spo2-{i}.wav"));
+ write_new(&path, &single_beep_wav(frequency))?;
+ files.saturations.push(path);
+ }
+ Ok(files)
+ }
+
+ fn create() -> io::Result<Self> {
+ if let Some(runtime) = env::var_os("XDG_RUNTIME_DIR") {
+ if let Ok(files) = Self::create_in(Path::new(&runtime)) {
+ return Ok(files);
+ }
+ }
+ Self::create_in(&env::temp_dir())
+ }
+
+ fn path(&self, tone: QrsTone) -> &Path {
+ match tone {
+ QrsTone::Mid => &self.mid,
+ QrsTone::Saturation(index) => &self.saturations[index.min(self.saturations.len() - 1)],
+ }
+ }
+}
+
+pub struct QrsAudio {
+ player: Option<&'static str>,
+ files: Option<QrsSoundFiles>,
+ child: Option<Child>,
+ error_reported: bool,
+}
+
+impl QrsAudio {
+ pub fn new() -> Self {
+ let player = ["pw-play", "paplay"].into_iter().find(|name| command_on_path(name));
+ let files = if player.is_some() {
+ match QrsSoundFiles::create() {
+ Ok(files) => Some(files),
+ Err(error) => {
+ eprintln!("PaMSim: cannot prepare QRS beeps: {error}");
+ None
+ }
+ }
+ } else { None };
+ Self { player, files, child: None, error_reported: false }
+ }
+
+ fn stop_child(&mut self) {
+ if let Some(mut child) = self.child.take() {
+ let _ = child.kill();
+ let _ = child.wait();
+ }
+ }
+
+ /// The audio timer delivers at most one beat in a 100-ms tick. Do not
+ /// replay events after disabling sound; do not restart an active beep.
+ pub fn update(&mut self, tone: Option<QrsTone>, enabled: bool) {
+ if !enabled {
+ self.stop_child();
+ return;
+ }
+ if let Some(child) = self.child.as_mut() {
+ match child.try_wait() {
+ Ok(Some(_)) | Err(_) => self.child = None,
+ Ok(None) => return,
+ }
+ }
+ let (Some(tone), Some(player), Some(files)) = (tone, self.player, self.files.as_ref())
+ else { return; };
+ match Command::new(player).arg(files.path(tone))
+ .stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).spawn()
+ {
+ Ok(child) => self.child = Some(child),
+ Err(error) if !self.error_reported => {
+ eprintln!("PaMSim: QRS sound playback failed: {error}");
+ self.error_reported = true;
+ }
+ Err(_) => {}
+ }
+ }
+}
+
+impl Drop for QrsAudio {
+ fn drop(&mut self) { self.stop_child(); }
+}
+
fn command_on_path(name: &str) -> bool {
env::var_os("PATH").is_some_and(|paths| {
env::split_paths(&paths).any(|dir| {
@@ -317,6 +508,59 @@ mod tests {
use super::*;
use crate::model::{AlarmSettings, EcgRhythm};
+ #[test]
+ fn saturation_pitches_follow_exact_bands_and_decrease_to_87_hz() {
+ assert_eq!(QRS_SPO2_HZ.first(), Some(&740.0));
+ assert_eq!(QRS_SPO2_HZ.last(), Some(&87.0));
+ for (saturation, expected) in [
+ (100, 0), (97, 0), (96, 1), (94, 1), (93, 2), (90, 2),
+ (89, 3), (80, 3), (79, 4), (70, 4), (69, 5), (60, 5),
+ (59, 6), (50, 6), (49, 7), (40, 7), (39, 8), (30, 8),
+ (29, 9), (20, 9), (19, 10), (10, 10), (0, 10),
+ ] {
+ assert_eq!(spo2_tone_index(saturation), expected, "SpO2 {saturation}%");
+ }
+ assert!(QRS_SPO2_HZ.windows(2).all(|hz| hz[0] > hz[1]));
+ assert_eq!(QRS_MID_HZ, 500.0);
+ }
+
+ #[test]
+ fn qrs_audio_uses_pleth_when_available_and_electrical_fallback_without_reading() {
+ let mut p = Parameters::default();
+ let mut sim = Simulator::new(&p);
+ let mut events = Vec::new();
+ for _ in 0..40 {
+ sim.advance(0.05, &p);
+ let current = sim.take_audio_events();
+ if current.iter().any(|e| e.source == BeatSource::Pleth
+ && sim.time() - e.time <= 0.25) {
+ events = current;
+ break;
+ }
+ }
+ assert!(events.iter().any(|e| e.source == BeatSource::Pleth));
+ assert_eq!(qrs_tone(&p, &sim, &events), Some(QrsTone::Saturation(0)));
+ p.spo2_sensor_attached = false;
+ let fallback = [BeatEvent { source: BeatSource::Ecg, time: sim.time() },
+ BeatEvent { source: BeatSource::Art, time: sim.time() }];
+ assert_eq!(qrs_tone(&p, &sim, &fallback), Some(QrsTone::Mid));
+ p.show_ecg = false;
+ assert_eq!(qrs_tone(&p, &sim, &fallback), Some(QrsTone::Mid));
+ p.show_art = false;
+ assert_eq!(qrs_tone(&p, &sim, &fallback), None);
+ }
+
+ #[test]
+ fn single_beep_is_valid_wav_independent_of_two_tone_alarm() {
+ for hz in QRS_SPO2_HZ.iter().copied().chain([QRS_MID_HZ]) {
+ let bytes = single_beep_wav(hz);
+ assert_eq!(&bytes[..4], b"RIFF");
+ assert_eq!(&bytes[8..12], b"WAVE");
+ assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()) as usize + 8, bytes.len());
+ }
+ assert_ne!(single_beep_wav(740.0), single_beep_wav(87.0));
+ }
+
#[test]
fn valid_wav_files_and_distinct_tone_patterns() {
for critical in [false, true] {
diff --git a/src/model.rs b/src/model.rs
index b01a854..dcd82bb 100644
--- a/src/model.rs
+++ b/src/model.rs
@@ -267,6 +267,7 @@ pub struct Parameters {
pub patient_name: String, // displayed in the monitor header, blank = generic title
pub alarms: AlarmSettings,
pub audible_alarms: bool, // mute only the sound, never the visual alarms
+ pub qrs_tone_enabled: bool, // beat-synchronous single beep; separate from two-tone alarms
pub chest_compressions_active: bool,
pub chest_compression_quality: ChestCompressionQuality,
pub ecg_rhythm: EcgRhythm,
@@ -346,6 +347,7 @@ impl Default for Parameters {
patient_name: String::new(),
alarms: AlarmSettings::default(),
audible_alarms: true,
+ qrs_tone_enabled: true,
chest_compressions_active: false,
chest_compression_quality: ChestCompressionQuality::Adequate,
ecg_rhythm: EcgRhythm::Sinus,
diff --git a/src/simulation.rs b/src/simulation.rs
index 61ca53e..ec88a5a 100644
--- a/src/simulation.rs
+++ b/src/simulation.rs
@@ -29,6 +29,18 @@ fn ppv_multiplier(ppv_percent: i32, respiratory_phase: f64) -> f64 {
* (std::f64::consts::TAU * respiratory_phase).sin()
}
+/// One distinct electrical or mechanical beat event for the optional beep.
+/// Electrical QRS, arterial and peripheral pulses are generated at their
+/// respective physiological simulation times, not at the audio-timer rate.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum BeatSource { Ecg, Art, Pleth }
+
+#[derive(Clone, Copy, Debug)]
+pub struct BeatEvent {
+ pub time: f64,
+ pub source: BeatSource,
+}
+
#[derive(Clone, Copy, Debug)]
pub struct Sample {
pub time: f64,
@@ -121,12 +133,12 @@ impl ChestCompressions {
};
}
- fn update(&mut self, enabled: bool, quality: ChestCompressionQuality) {
+ fn update(&mut self, enabled: bool, quality: ChestCompressionQuality) -> bool {
if !enabled {
self.active = false;
self.phase = 0.0;
self.peak_pressure = 0.0;
- return;
+ return false;
}
if !self.active {
self.active = true;
@@ -143,7 +155,9 @@ impl ChestCompressions {
self.phase = self.phase.fract();
self.rate_bpm = 90.0 + self.random_unit() * 20.0;
self.choose_peak();
+ return true;
}
+ false
}
fn pressure_wave(&self) -> f64 {
@@ -184,6 +198,7 @@ pub struct Simulator {
ecg_beat_number: u64,
conducted_qrs: VecDeque<ConductedBeat>, // captured QRS with respiratory beat amplitude
rate_qrs: VecDeque<f64>, // captured beats for measured PR; reset after rate changes
+ audio_events: VecDeque<BeatEvent>, // consumed by the 100-ms UI audio timer
filtered_pleth: f64,
previous_rhythm: EcgRhythm,
previous_conduction: PulseConduction,
@@ -205,6 +220,7 @@ impl Simulator {
ecg_beat_number: 0,
conducted_qrs: VecDeque::new(),
rate_qrs: VecDeque::new(),
+ audio_events: VecDeque::new(),
filtered_pleth: 0.0,
previous_rhythm: params.ecg_rhythm,
previous_conduction: params.pulse_conduction,
@@ -219,6 +235,8 @@ impl Simulator {
for _ in 0..(8.0 / SAMPLE_STEP) as usize {
sim.step(params);
}
+ // Initial history is visual-only; never replay warmup beats as sound.
+ sim.audio_events.clear();
sim
}
@@ -336,6 +354,18 @@ impl Simulator {
&self.samples
}
+ /// Drain beat events since the previous sound callback. Kept bounded so
+ /// a suspended window cannot replay a long backlog of old beats.
+ pub fn take_audio_events(&mut self) -> Vec<BeatEvent> {
+ self.audio_events.drain(..).collect()
+ }
+
+ fn emit_beat(&mut self, source: BeatSource, time: f64) {
+ if time < 0.0 { return; } // no audio events from history warmup
+ if self.audio_events.len() >= 32 { self.audio_events.pop_front(); }
+ self.audio_events.push_back(BeatEvent { source, time });
+ }
+
/// Average of recent *mechanically captured* beat intervals, not an independent setting.
pub fn pulse_rate(&self) -> Option<i32> {
if self.rate_qrs.len() < 2 {
@@ -355,8 +385,18 @@ impl Simulator {
fn step(&mut self, params: &Parameters) {
self.time += SAMPLE_STEP;
- self.compressions.update(params.chest_compressions_active,
+ let compression_event = self.compressions.update(params.chest_compressions_active,
params.chest_compression_quality);
+ if compression_event {
+ // Good CPR generates a pleth beat. Any effective CPR generates
+ // an arterial beat, even without underlying organized ECG.
+ if self.compressions.peak_pressure > 0.0 {
+ self.emit_beat(BeatSource::Art, self.time);
+ }
+ if params.chest_compression_quality == ChestCompressionQuality::Good {
+ self.emit_beat(BeatSource::Pleth, self.time);
+ }
+ }
self.poor_signal_outages.update(self.time,
!params.chest_compressions_active && params.spo2_quality == Spo2Quality::Poor
&& params.spo2_sensor_attached);
@@ -413,6 +453,7 @@ impl Simulator {
// Interpolate within the 4 ms sample so mechanical onsets stay aligned.
let qrs_time = self.time - SAMPLE_STEP * (next_phase - QRS_PHASE) / increment;
self.ecg_beat_number += 1;
+ self.emit_beat(BeatSource::Ecg, qrs_time);
if params.ecg_rhythm.can_generate_pulse()
&& params.pulse_conduction.conducts(self.ecg_beat_number) {
let pulse_pressure_scale = if params.respiratory_rate > 0 {
@@ -429,6 +470,29 @@ impl Simulator {
self.ecg_phase = 0.0;
}
+ // Schedule single beeps at the delayed mechanical onsets. During CPR,
+ // the compression clock replaces the intrinsic ART/pleth sound source
+ // except for a perfusing native arterial pulse under ineffective CPR.
+ let mut mechanical_events = Vec::new();
+ for beat in &self.conducted_qrs {
+ let art_time = beat.qrs_time + ART_DELAY;
+ let pleth_time = beat.qrs_time + PLETH_DELAY;
+ if art_time > self.time - SAMPLE_STEP && art_time <= self.time
+ && (!params.chest_compressions_active
+ || params.chest_compression_quality == ChestCompressionQuality::Bad)
+ {
+ mechanical_events.push((BeatSource::Art, art_time));
+ }
+ if pleth_time > self.time - SAMPLE_STEP && pleth_time <= self.time
+ && !params.chest_compressions_active
+ {
+ mechanical_events.push((BeatSource::Pleth, pleth_time));
+ }
+ }
+ for (source, time) in mechanical_events {
+ self.emit_beat(source, time);
+ }
+
// Preserve up to 30s of delivered events for stable derived PR calculations.
while self.conducted_qrs.front().is_some_and(|beat| beat.qrs_time < self.time - 30.0) {
self.conducted_qrs.pop_front();
@@ -709,6 +773,60 @@ mod tests {
sim
}
+ #[test]
+ fn audio_events_follow_actual_qrs_and_delayed_mechanical_pulses() {
+ let p = Parameters::default();
+ let mut sim = Simulator::new(&p);
+ for _ in 0..30 { sim.advance(0.1, &p); }
+ let events = sim.take_audio_events();
+ let qrs = events.iter().find(|e| e.source == BeatSource::Ecg).unwrap().time;
+ assert!(events.iter().any(|e| e.source == BeatSource::Art
+ && ((e.time - qrs) - ART_DELAY).abs() <= SAMPLE_STEP));
+ assert!(events.iter().any(|e| e.source == BeatSource::Pleth
+ && ((e.time - qrs) - PLETH_DELAY).abs() <= SAMPLE_STEP));
+ assert!(sim.take_audio_events().is_empty(), "events must be consumed once");
+ }
+
+ #[test]
+ fn two_to_one_capture_has_half_as_many_peripheral_audio_beats() {
+ let p = Parameters { pulse_conduction: PulseConduction::TwoToOne,
+ ..Parameters::default() };
+ let mut sim = Simulator::new(&p);
+ let mut qrs = 0;
+ let mut pleth = 0;
+ for _ in 0..100 {
+ sim.advance(0.1, &p);
+ for event in sim.take_audio_events() {
+ match event.source {
+ BeatSource::Ecg => qrs += 1,
+ BeatSource::Pleth => pleth += 1,
+ BeatSource::Art => {}
+ }
+ }
+ }
+ assert!(qrs >= 10);
+ assert!((2 * pleth as i32 - qrs as i32).abs() <= 2,
+ "2:1 capture: {qrs} QRS events, {pleth} peripheral events");
+ }
+
+ #[test]
+ fn vf_generates_no_beats_without_cpr_but_compressions_generate_art_events() {
+ let mut p = Parameters { ecg_rhythm: EcgRhythm::VentricularFibrillation,
+ ..Parameters::default() };
+ let mut sim = Simulator::new(&p);
+ for _ in 0..20 { sim.advance(0.1, &p); }
+ assert!(sim.take_audio_events().is_empty());
+ p.chest_compressions_active = true;
+ p.chest_compression_quality = ChestCompressionQuality::Adequate;
+ for _ in 0..20 { sim.advance(0.1, &p); }
+ let events = sim.take_audio_events();
+ assert!(events.iter().any(|e| e.source == BeatSource::Art));
+ assert!(!events.iter().any(|e| e.source == BeatSource::Pleth));
+ p.chest_compression_quality = ChestCompressionQuality::Good;
+ for _ in 0..20 { sim.advance(0.1, &p); }
+ assert!(sim.take_audio_events().iter().any(|e| e.source == BeatSource::Pleth));
+ }
+
#[test]
fn compression_rate_varies_only_between_90_and_110_bpm() {
let mut cpr = ChestCompressions::new();
diff --git a/src/ui.rs b/src/ui.rs
index 98e35c2..0c02b36 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::alarm::{self, AlarmAudio};
+use crate::alarm::{self, AlarmAudio, QrsAudio};
use crate::model::{AlarmLimits, AlarmSettings, ArterialShape, CapnoShape,
ChestCompressionQuality, EcgLead, EcgRhythm, Parameters, PulseConduction, Spo2Quality};
use crate::render;
@@ -33,6 +33,7 @@ pub fn create_windows(app: &Application) {
let parameters = Rc::new(RefCell::new(Parameters::default()));
let simulator = Rc::new(RefCell::new(Simulator::new(&parameters.borrow())));
let audio = Rc::new(RefCell::new(AlarmAudio::new()));
+ let qrs_audio = Rc::new(RefCell::new(QrsAudio::new()));
install_ecg_menu_style(); // neutral style shared by all parameter panels
let admin_changed: AdminChanged = Rc::new(RefCell::new(None));
let monitor = create_monitor(app, parameters.clone(), simulator.clone(),
@@ -44,8 +45,13 @@ pub fn create_windows(app: &Application) {
// on sound playback. Audio also continues if the monitor is not mapped.
glib::timeout_add_local(Duration::from_millis(100), move || {
let config = parameters.borrow();
- let current = alarm::level(&config, &simulator.borrow());
+ let mut sim = simulator.borrow_mut();
+ let events = sim.take_audio_events();
+ let current = alarm::level(&config, &sim);
+ let beat_tone = alarm::qrs_tone(&config, &sim, &events);
+ drop(sim);
audio.borrow_mut().update(current, config.audible_alarms);
+ qrs_audio.borrow_mut().update(beat_tone, config.qrs_tone_enabled);
glib::ControlFlow::Continue
});
@@ -210,6 +216,13 @@ fn create_admin(app: &Application, params: SharedParams,
move |button| params.borrow_mut().audible_alarms = button.is_active()
});
sound_row.append(&audible);
+ let qrs_enabled = gtk::CheckButton::with_label("QRS tone");
+ qrs_enabled.set_active(params.borrow().qrs_tone_enabled);
+ qrs_enabled.connect_toggled({
+ let params = params.clone();
+ move |button| params.borrow_mut().qrs_tone_enabled = button.is_active()
+ });
+ sound_row.append(&qrs_enabled);
let test_sound = gtk::Button::with_label("Test tone");
test_sound.connect_clicked({
let audio = audio.clone();

View file

@ -0,0 +1,189 @@
diff --git a/Cargo.toml b/Cargo.toml
index f3abff3..eda3ddf 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "patient-monitor-simulation"
-version = "0.6.6"
+version = "0.6.7"
edition = "2021"
license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"
diff --git a/README.de.md b/README.de.md
index 605a34f..17890f5 100644
--- a/README.de.md
+++ b/README.de.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.6.6
+# Patient Monitor Simulation (PaMSim) — v0.6.7
Ein mit Rust und GTK4 entwickelter Patient*innenmonitor-Simulator mit zwei Fenstern für die Lehre unter Fedora Linux.
@@ -6,6 +6,17 @@ Ein mit Rust und GTK4 entwickelter Patient*innenmonitor-Simulator mit zwei Fenst
> EKG, invasive arterielle Druckkurve, Plethysmogramm und Kapnogramm sind schematische mathematische Annäherungen.
> Die Simulation wurde nicht klinisch validiert und ist kein Medizinprodukt.
+## Stufenlose Herzfrequenzänderung (v0.6.7)
+
+Bei Änderungen der Herzfrequenz bleibt die Historie der zuletzt *mechanisch
+wirksamen* Herzschläge erhalten. Die angezeigte Pulsfrequenz passt sich über
+den gleitenden Mittelwert der letzten drei Pulsintervalle an, ohne
+zwischenzeitlich zu verschwinden. SpO₂-Wert, Plethysmogramm und
+sättigungsabhängiger Pulston bleiben bei gewöhnlichen Änderungen der
+Herzfrequenz erhalten. Ein tatsächlicher Verlust der mechanischen
+Pulsüberleitung, ein abgesteckter Sensor und wirkliche Signalausfälle lösen
+weiterhin unmittelbar die vorgesehenen Alarme aus.
+
## Monitoraufteilung (v0.5.7)
Der nutzbare Monitorbereich wird in einem festen Verhältnis von **75 % für die
@@ -175,7 +186,7 @@ Mit **F11** wird der Vollbildmodus aktiviert bzw. umgeschaltet, mit **Esc** wird
Unter Wayland sollte das Fenster vor dem Wechsel in den Vollbildmodus auf den gewünschten Präsentationsbildschirm verschoben werden.
Der Vollbildmodus sperrt den Computer nicht gegen andere Eingaben.
-## Akustische Alarme und QRS-Ton (aktualisiert v0.6.6)
+## Akustische Alarme und QRS-Ton (aktualisiert v0.6.7)
Die akustische Alarmierung ist **standardmäßig eingeschaltet**. Im
Admin-Fenster lässt sie sich mit **Audible alarms** aktivieren bzw. stummschalten.
diff --git a/README.md b/README.md
index 250b938..793a3d4 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.6.6
+# Patient Monitor Simulation (PaMSim) — v0.6.7
A Rust/GTK4 patient-monitor simulator with two main windows for teaching on Fedora Linux.
@@ -6,6 +6,16 @@ A Rust/GTK4 patient-monitor simulator with two main windows for teaching on Fedo
> plethysmography and capnography are schematic mathematical approximations. The
> simulation has no clinical validation and is not a medical device.
+## Smooth HR transitions (v0.6.7)
+
+Changing the HR slider now preserves the recent history of *mechanically
+captured* beats. PR converges to the new rate using the existing rolling
+three-interval average instead of temporarily disappearing. The SpO₂ value,
+plethysmography and saturation-dependent QRS tone remain available during
+ordinary HR adjustments. Actual loss of mechanical capture, disconnected
+sensors, deliberate signal dropout and low-quality/absent signals still
+produce their intended alarms immediately.
+
## Monitor layout (v0.5.7)
The monitor uses a fixed **3:1 column ratio** over the drawable area:
@@ -166,7 +176,7 @@ 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.
-## Audible alarms and QRS tone (updated v0.6.6)
+## Audible alarms and QRS tone (updated v0.6.7)
Sound is **enabled by default**. The Admin window has an **Audible alarms**
checkbox for muting and a **Test tone** button (works even while muted).
diff --git a/src/simulation.rs b/src/simulation.rs
index ec88a5a..800293f 100644
--- a/src/simulation.rs
+++ b/src/simulation.rs
@@ -197,12 +197,11 @@ pub struct Simulator {
respiratory_phase: f64,
ecg_beat_number: u64,
conducted_qrs: VecDeque<ConductedBeat>, // captured QRS with respiratory beat amplitude
- rate_qrs: VecDeque<f64>, // captured beats for measured PR; reset after rate changes
+ rate_qrs: VecDeque<f64>, // captured beats for measured PR; rolling history smooths HR changes
audio_events: VecDeque<BeatEvent>, // consumed by the 100-ms UI audio timer
filtered_pleth: f64,
previous_rhythm: EcgRhythm,
previous_conduction: PulseConduction,
- previous_heart_rate: i32,
poor_signal_outages: PoorSignalOutages,
compressions: ChestCompressions,
nibp: NibpMachine,
@@ -224,7 +223,6 @@ impl Simulator {
filtered_pleth: 0.0,
previous_rhythm: params.ecg_rhythm,
previous_conduction: params.pulse_conduction,
- previous_heart_rate: params.heart_rate,
poor_signal_outages: PoorSignalOutages::new(),
compressions: ChestCompressions::new(),
nibp: NibpMachine::new(),
@@ -427,12 +425,12 @@ impl Simulator {
self.previous_rhythm = params.ecg_rhythm;
self.previous_conduction = params.pulse_conduction;
}
- if params.heart_rate != self.previous_heart_rate {
- // Old captured events remain in the *waveforms* until they pass.
- // They must not bias the pulse rate after an HR slider change.
- self.rate_qrs.clear();
- self.previous_heart_rate = params.heart_rate;
- }
+ // Keep recent mechanically captured beats when only HR changes.
+ // The rolling three-interval PR calculation then converges naturally
+ // to the new rate as new pulses arrive. Clearing this history on every
+ // slider update would briefly make PR unavailable and falsely trigger
+ // SpO2 NO READING, even though perfusion and the sensor are intact.
+ // Actual loss of capture is still handled above, immediately.
// Respiratory phase drives both the capnogram and arterial PPV.
let respiratory_rate = params.respiratory_rate.max(0) as f64 / 60.0;
@@ -1181,12 +1179,55 @@ mod tests {
assert_eq!(sim.pulse_rate(), Some(75));
p.heart_rate = 189;
sim.step(&p);
- // No old 75 bpm PR is displayed while the new beat interval is measured.
- assert_eq!(sim.pulse_rate(), None);
- for _ in 0..200 { sim.step(&p); }
+ // A new HR must not invalidate existing mechanical pulse history.
+ // The displayed PR is smoothed from actual conducted QRS intervals.
+ assert_eq!(sim.pulse_rate(), Some(75));
+ assert_eq!(sim.spo2_status(&p), Spo2Status::Available);
+ for _ in 0..800 {
+ sim.step(&p);
+ assert!(sim.pulse_rate().is_some(), "PR must remain available");
+ assert_eq!(sim.spo2_status(&p), Spo2Status::Available);
+ assert!(sim.samples.back().unwrap().pleth_valid,
+ "no artificial gap in the pleth trace during HR adjustment");
+ }
assert_eq!(sim.pulse_rate(), Some(189));
}
+ #[test]
+ fn repeated_heart_rate_slider_moves_do_not_trigger_spo2_no_reading() {
+ let mut p = Parameters::default();
+ let mut sim = Simulator::new(&p);
+ for rate in [90, 105, 120, 140, 110, 80, 75] {
+ p.heart_rate = rate;
+ for _ in 0..40 { // only 160 ms between successive slider updates
+ sim.step(&p);
+ assert!(sim.pulse_rate().is_some());
+ assert_eq!(sim.spo2_status(&p), Spo2Status::Available);
+ assert!(sim.samples.back().unwrap().pleth_valid);
+ }
+ }
+ }
+
+ #[test]
+ fn conducted_two_to_one_pulses_remain_available_during_hr_change() {
+ let mut p = Parameters { pulse_conduction: PulseConduction::TwoToOne,
+ ..Parameters::default() };
+ let mut sim = Simulator::new(&p);
+ assert_eq!(sim.pulse_rate(), Some(38));
+ p.heart_rate = 150;
+ for _ in 0..1200 {
+ sim.step(&p);
+ assert!(sim.pulse_rate().is_some());
+ assert_eq!(sim.spo2_status(&p), Spo2Status::Available);
+ }
+ assert_eq!(sim.pulse_rate(), Some(75));
+ // Genuine mechanical capture loss still produces NO READING immediately.
+ p.pulse_conduction = PulseConduction::None;
+ sim.step(&p);
+ assert_eq!(sim.pulse_rate(), None);
+ assert_eq!(sim.spo2_status(&p), Spo2Status::NoReading);
+ }
+
#[test]
fn new_rate_respects_two_to_one_mechanical_capture() {
let mut p = Parameters::default();

View file

@ -0,0 +1,769 @@
diff --git a/Cargo.toml b/Cargo.toml
index eda3ddf..54bac15 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "patient-monitor-simulation"
-version = "0.6.7"
+version = "0.6.8"
edition = "2021"
license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"
diff --git a/README.de.md b/README.de.md
index 17890f5..64f4476 100644
--- a/README.de.md
+++ b/README.de.md
@@ -1,4 +1,30 @@
-# Patient Monitor Simulation (PaMSim) — v0.6.7
+# Patient Monitor Simulation (PaMSim) — v0.6.8
+
+## Kopfzeile: selektive Alarmpause und Einstellungen (v0.6.8)
+
+Rechts in der Kopfzeile befinden sich zwei per Touch oder Maus bedienbare
+Symbole:
+
+- **Gelbe Glocke (ganz rechts):** Schaltet ausschließlich jene akustischen
+ Alarmbedingungen für **120 Sekunden** stumm, die beim Drücken gerade
+ anstehen. Darunter zeigt `paused for x s` die verbleibende Zeit. Erneutes
+ Drücken erfasst die aktuell aktiven Bedingungen neu und startet die Frist
+ erneut. Neu hinzukommende Alarmbedingungen sind sofort hörbar, auch bei
+ gleicher Alarmpriorität. Ein abgeklungener Alarm ist bei einem späteren
+ erneuten Auftreten wieder hörbar. Optische Alarme und der unabhängige
+ QRS-/Pulston bleiben unverändert. Ohne aktiven Alarm wird keine Pause
+ gestartet.
+- **Zahnrad (links daneben):** Öffnet ein schwarz/hellgraues Einstellfenster
+ mit **QRS beep**, **Audible alarms**, **Alert presets** (`Custom`, `Adult`),
+ dem Eingabefeld **Patient name** und dem Text
+ `PaMSim by Critical Care Club Austria, (c) 2026`. Eine Bildschirmtastatur
+ wird nicht zusätzlich bereitgestellt. **Apply** übernimmt die Einstellungen
+ und gleicht sie mit dem Admin-Fenster ab, **Cancel/Esc** verwirft sie.
+ Die Vorgabe Adult verändert nur die Alarmgrenzen.
+
+Die bisherigen Touch-Menüs bleiben erhalten. Das NIBP-Menü enthält weiterhin
+manuelle Messung, Messautomatik und Messintervall.
+
Ein mit Rust und GTK4 entwickelter Patient*innenmonitor-Simulator mit zwei Fenstern für die Lehre unter Fedora Linux.
@@ -691,3 +717,14 @@ zwischen 740 und 87 Hz nach der Sauerstoffsättigung; ohne SpO₂-Messwert
erfolgt bei EKG-QRS oder arteriellem Puls ein 500-Hz-Ton. Die bisherigen
Zweitonalarme bleiben unverändert. Zusätzliche Tests prüfen die
Frequenzbereiche, Ereigniszuordnung und WAV-Ausgabe.
+
+
+### v0.6.8 – Kopfzeilenmenü und selektive Alarmpause
+
+Zwei Touch-Schaltflächen in der Kopfzeile: gelbe Glocke für 120 Sekunden
+selektive Unterdrückung bereits aktiver akustischer Alarme mit Countdown und
+Zahnrad für globale Einstellungen. Neu auftretende oder nach zwischenzeitlichem
+Abklingen wiederkehrende Alarmbedingungen bleiben hörbar; optische Alarme und
+QRS-Töne laufen unverändert. Das Menü ermöglicht QRS-/Alarnton, Alarmvorgabe
+und Patientennamen und enthält den Copyright-Hinweis. Die Admin-Oberfläche wird
+synchronisiert.
diff --git a/README.md b/README.md
index 793a3d4..105c082 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.6.7
+# Patient Monitor Simulation (PaMSim) — v0.6.8
A Rust/GTK4 patient-monitor simulator with two main windows for teaching on Fedora Linux.
@@ -6,6 +6,29 @@ A Rust/GTK4 patient-monitor simulator with two main windows for teaching on Fedo
> plethysmography and capnography are schematic mathematical approximations. The
> simulation has no clinical validation and is not a medical device.
+## Header controls: selective alarm pause and settings (v0.6.8)
+
+Two touch/mouse controls are drawn at the far right of the monitor header:
+
+- **Yellow bell (rightmost):** pauses only the *currently active* audible
+ alarm conditions for **120 seconds**. The caption `paused for x s` counts
+ down the remaining seconds. Pressing the bell again replaces the suppressed
+ set with the conditions active at that moment and restarts the 120-second
+ timer. A newly triggered alarm condition sounds normally, even if another
+ alarm of the same priority is paused. When a condition clears, it loses its
+ paused status so a later recurrence can sound. Pauses never change visual
+ alarms or the separate beat-synchronous QRS sound. Pressing the bell when
+ no alarms are active does not start a countdown.
+- **Gear (left of bell):** opens a black/light-grey monitor-side settings panel
+ with **QRS beep**, **Audible alarms**, **Alert presets** (`Custom`, `Adult`),
+ an editable **Patient name** field and the attribution
+ `PaMSim by Critical Care Club Austria, (c) 2026`. It does **not** create
+ an on-screen keyboard. **Apply** synchronizes settings with Admin;
+ **Cancel/Esc** discards changes. The Adult preset affects alarm limits only.
+
+Other channel touch menus are unchanged. NIBP retains its explicitly requested
+manual measurement, automatic measurement and interval controls.
+
## Smooth HR transitions (v0.6.7)
Changing the HR slider now preserves the recent history of *mechanically
@@ -703,3 +726,13 @@ saturation determines the pitch in eleven steps from 740 to 87 Hz; otherwise
ECG QRS or ART pulses trigger a fixed 500 Hz tone. The two-tone alarm sounds
remain unchanged. Added regression tests for band boundaries, event selection
and single-tone WAV output.
+
+
+### v0.6.8 — Monitor header controls and selective audible-alarm pause
+
+Added a yellow bell button with a 120-second pause countdown and a grey settings
+gear to the monitor header. The pause suppresses only alarm conditions active
+when pressed, with automatic un-silencing of new/recurrent conditions; visual
+alarms and QRS tones continue. The global monitor settings window contains
+QRS and audible-alarm switches, alert preset selection, patient name and
+attribution, and synchronizes its changes with Admin.
diff --git a/src/alarm.rs b/src/alarm.rs
index 89814d6..f992589 100644
--- a/src/alarm.rs
+++ b/src/alarm.rs
@@ -4,6 +4,7 @@
//! as the monitor. Sound is played using Fedora's PipeWire command-line player
//! (or paplay) without adding a native audio-library dependency to Cargo.
+use std::collections::{BTreeMap, BTreeSet};
use std::env;
use std::fs::{self, OpenOptions};
use std::io::{self, Write};
@@ -11,7 +12,7 @@ use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
-use crate::model::{AlarmLimits, AlarmState, Parameters, PulseConduction, Spo2Status};
+use crate::model::{AlarmLimits, AlarmState, EcgRhythm, Parameters, PulseConduction, Spo2Status};
use crate::simulation::{BeatEvent, BeatSource, Simulator};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
@@ -22,66 +23,126 @@ pub enum AlarmLevel {
Critical,
}
-fn outside(limits: AlarmLimits, value: Option<i32>) -> bool {
- limits.evaluate(value) != AlarmState::Normal
+/// One identifiable alarm condition. Upper and lower alarms of a parameter
+/// have different identities, as do individual arrhythmias and technical errors.
+/// A pause must silence identities, never a whole priority class.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
+pub enum AlarmKey {
+ Low(&'static str),
+ High(&'static str),
+ NoSensor,
+ NoReading,
+ Rhythm(&'static str),
}
-/// Only parameters actually shown on the monitor contribute audible alarms.
-/// Missing numeric values do not trigger threshold alarms, but missing SpO2
-/// readings and disconnected sensors are explicit technical alarms.
-pub fn level(p: &Parameters, sim: &Simulator) -> AlarmLevel {
- let mut result = AlarmLevel::None;
+pub type ActiveAlarms = BTreeMap<AlarmKey, AlarmLevel>;
+
+fn add_limit(alarms: &mut ActiveAlarms, name: &'static str,
+ limits: AlarmLimits, value: Option<i32>) {
+ let key = match limits.evaluate(value) {
+ AlarmState::Low => Some(AlarmKey::Low(name)),
+ AlarmState::High => Some(AlarmKey::High(name)),
+ AlarmState::Normal => None,
+ };
+ if let Some(key) = key { alarms.insert(key, AlarmLevel::Standard); }
+}
+
+/// Evaluate every independent audible alarm from the same data used by the
+/// visual display. Hidden channels do not generate audible alarms.
+pub fn active_conditions(p: &Parameters, sim: &Simulator) -> ActiveAlarms {
+ let mut alarms = ActiveAlarms::new();
let hr = (p.ecg_rhythm.has_qrs() && p.heart_rate > 0).then_some(p.heart_rate);
let captured = p.ecg_rhythm.can_generate_pulse()
&& p.heart_rate > 0
&& p.pulse_conduction != PulseConduction::None;
if p.show_ecg {
- if p.ecg_rhythm.rhythm_alarm().is_some() {
- return AlarmLevel::Critical;
- }
- if outside(p.alarms.hr, hr) {
- result = AlarmLevel::Standard;
+ let rhythm = match p.ecg_rhythm {
+ EcgRhythm::VentricularTachycardia => Some("VT"),
+ EcgRhythm::PulselessVentricularTachycardia => Some("PVT"),
+ EcgRhythm::VentricularFibrillation => Some("VF"),
+ EcgRhythm::Asystole => Some("ASYSTOLE"),
+ _ => None,
+ };
+ if let Some(name) = rhythm {
+ alarms.insert(AlarmKey::Rhythm(name), AlarmLevel::Critical);
}
+ add_limit(&mut alarms, "HR", p.alarms.hr, hr);
}
if p.show_spo2 {
- let status = sim.spo2_status(p);
- if status != Spo2Status::Available
- || outside(p.alarms.spo2, Some(p.spo2))
- || outside(p.alarms.pr, sim.spo2_pulse_rate(p))
- {
- result = AlarmLevel::Standard;
+ match sim.spo2_status(p) {
+ Spo2Status::NoSensor => {
+ alarms.insert(AlarmKey::NoSensor, AlarmLevel::Standard);
+ }
+ Spo2Status::NoReading => {
+ alarms.insert(AlarmKey::NoReading, AlarmLevel::Standard);
+ }
+ Spo2Status::Available => {
+ add_limit(&mut alarms, "SpO2", p.alarms.spo2, Some(p.spo2));
+ add_limit(&mut alarms, "PR", p.alarms.pr, sim.spo2_pulse_rate(p));
+ }
}
}
if p.show_art {
let (sys, dia, map) = sim.displayed_art_pressures(p, captured);
- if outside(p.alarms.art_sys, sys)
- || outside(p.alarms.art_dia, dia)
- || outside(p.alarms.art_map, map)
- || outside(p.alarms.ppv, Some(p.pulse_pressure_variation))
- {
- result = AlarmLevel::Standard;
- }
+ add_limit(&mut alarms, "ART SYS", p.alarms.art_sys, sys);
+ add_limit(&mut alarms, "ART DIA", p.alarms.art_dia, dia);
+ add_limit(&mut alarms, "ART MAP", p.alarms.art_map, map);
+ add_limit(&mut alarms, "PPV", p.alarms.ppv, Some(p.pulse_pressure_variation));
}
-
- if p.show_capno && (outside(p.alarms.etco2, Some(p.etco2))
- || outside(p.alarms.rr, Some(p.respiratory_rate)))
- {
- result = AlarmLevel::Standard;
+ if p.show_capno {
+ add_limit(&mut alarms, "EtCO2", p.alarms.etco2, Some(p.etco2));
+ add_limit(&mut alarms, "RR", p.alarms.rr, Some(p.respiratory_rate));
}
-
if p.show_nibp {
let reading = sim.nibp().reading();
- if outside(p.alarms.nibp_sys, reading.map(|r| r.systolic))
- || outside(p.alarms.nibp_dia, reading.map(|r| r.diastolic))
- || outside(p.alarms.nibp_map, reading.map(|r| r.mean()))
- {
- result = AlarmLevel::Standard;
+ add_limit(&mut alarms, "NIBP SYS", p.alarms.nibp_sys, reading.map(|r| r.systolic));
+ add_limit(&mut alarms, "NIBP DIA", p.alarms.nibp_dia, reading.map(|r| r.diastolic));
+ add_limit(&mut alarms, "NIBP MAP", p.alarms.nibp_map, reading.map(|r| r.mean()));
+ }
+ alarms
+}
+
+/// Preserve the legacy priority interface for tests and audio playback.
+#[cfg(test)]
+pub fn level(p: &Parameters, sim: &Simulator) -> AlarmLevel {
+ active_conditions(p, sim).values().copied().max().unwrap_or_default()
+}
+
+/// A two-minute pause captures *only* the alarm conditions that are active
+/// at button press. A new condition bypasses it; a condition that clears is
+/// removed from the snapshot so that a later recurrence sounds normally.
+#[derive(Default)]
+pub struct AlarmPause {
+ until: Option<Instant>,
+ muted: BTreeSet<AlarmKey>,
+}
+
+impl AlarmPause {
+ pub fn pause_current(&mut self, now: Instant, active: &ActiveAlarms) {
+ self.muted = active.keys().copied().collect();
+ self.until = (!self.muted.is_empty()).then_some(now + Duration::from_secs(120));
+ }
+
+ pub fn effective_level(&mut self, now: Instant, active: &ActiveAlarms) -> AlarmLevel {
+ if self.until.is_some_and(|deadline| now >= deadline) {
+ self.until = None;
+ self.muted.clear();
}
+ self.muted.retain(|key| active.contains_key(key));
+ active.iter().filter(|(key, _)| !self.muted.contains(key))
+ .map(|(_, priority)| *priority).max().unwrap_or_default()
+ }
+
+ pub fn remaining_seconds(&self, now: Instant) -> Option<u64> {
+ self.until.and_then(|deadline| {
+ let remaining = deadline.saturating_duration_since(now);
+ (!remaining.is_zero()).then_some(remaining.as_secs().saturating_add(
+ u64::from(remaining.subsec_nanos() > 0)))
+ })
}
- result
}
/// Single-note QRS/pulse beep. The oximeter is the source when it has a
@@ -508,6 +569,71 @@ mod tests {
use super::*;
use crate::model::{AlarmSettings, EcgRhythm};
+ #[test]
+ fn pause_silences_only_current_alarm_conditions() {
+ let t0 = Instant::now();
+ let mut pause = AlarmPause::default();
+ let mut alarms = ActiveAlarms::new();
+ alarms.insert(AlarmKey::High("HR"), AlarmLevel::Standard);
+ assert_eq!(pause.effective_level(t0, &alarms), AlarmLevel::Standard);
+ pause.pause_current(t0, &alarms);
+ assert_eq!(pause.remaining_seconds(t0), Some(120));
+ assert_eq!(pause.effective_level(t0, &alarms), AlarmLevel::None);
+ // New lower-limit or technical alarms sound even during the pause.
+ alarms.insert(AlarmKey::NoSensor, AlarmLevel::Standard);
+ assert_eq!(pause.effective_level(t0, &alarms), AlarmLevel::Standard);
+ // Pressing again captures both current alarms and restarts the clock.
+ pause.pause_current(t0 + Duration::from_secs(5), &alarms);
+ assert_eq!(pause.remaining_seconds(t0 + Duration::from_secs(5)), Some(120));
+ assert_eq!(pause.effective_level(t0 + Duration::from_secs(5), &alarms), AlarmLevel::None);
+ alarms.insert(AlarmKey::Rhythm("VF"), AlarmLevel::Critical);
+ assert_eq!(pause.effective_level(t0 + Duration::from_secs(6), &alarms), AlarmLevel::Critical);
+ assert_eq!(pause.effective_level(t0 + Duration::from_secs(126), &alarms), AlarmLevel::Critical);
+ }
+
+ #[test]
+ fn alarm_recurrence_and_expiration_are_not_muted() {
+ let t0 = Instant::now();
+ let mut pause = AlarmPause::default();
+ let mut active = ActiveAlarms::new();
+ active.insert(AlarmKey::Low("SpO2"), AlarmLevel::Standard);
+ pause.pause_current(t0, &active);
+ assert_eq!(pause.effective_level(t0, &active), AlarmLevel::None);
+ // The condition clears; a recurrence is a fresh alarm.
+ active.clear();
+ assert_eq!(pause.effective_level(t0 + Duration::from_secs(2), &active), AlarmLevel::None);
+ active.insert(AlarmKey::Low("SpO2"), AlarmLevel::Standard);
+ assert_eq!(pause.effective_level(t0 + Duration::from_secs(3), &active), AlarmLevel::Standard);
+ pause.pause_current(t0 + Duration::from_secs(4), &active);
+ assert_eq!(pause.effective_level(t0 + Duration::from_secs(123), &active), AlarmLevel::None);
+ assert_eq!(pause.effective_level(t0 + Duration::from_secs(124), &active), AlarmLevel::Standard);
+ assert_eq!(pause.remaining_seconds(t0 + Duration::from_secs(124)), None);
+ }
+
+ #[test]
+ fn pause_does_not_start_without_an_active_alarm() {
+ let mut pause = AlarmPause::default();
+ let now = Instant::now();
+ pause.pause_current(now, &ActiveAlarms::new());
+ assert_eq!(pause.remaining_seconds(now), None);
+ }
+
+ #[test]
+ fn separate_lower_upper_and_rhythm_alarm_identities() {
+ let mut p = Parameters::default();
+ let sim = Simulator::new(&p);
+ p.alarms.hr = AlarmLimits { lower: Some(60), upper: Some(100) };
+ p.heart_rate = 110;
+ assert!(active_conditions(&p, &sim).contains_key(&AlarmKey::High("HR")));
+ p.heart_rate = 50;
+ let conditions = active_conditions(&p, &sim);
+ assert!(conditions.contains_key(&AlarmKey::Low("HR")));
+ assert!(!conditions.contains_key(&AlarmKey::High("HR")));
+ p.ecg_rhythm = EcgRhythm::VentricularFibrillation;
+ assert_eq!(active_conditions(&p, &sim).get(&AlarmKey::Rhythm("VF")),
+ Some(&AlarmLevel::Critical));
+ }
+
#[test]
fn saturation_pitches_follow_exact_bands_and_decrease_to_87_hz() {
assert_eq!(QRS_SPO2_HZ.first(), Some(&740.0));
diff --git a/src/render.rs b/src/render.rs
index 9b9b711..de8a9c3 100644
--- a/src/render.rs
+++ b/src/render.rs
@@ -25,7 +25,8 @@ fn visible_channels(p: &Parameters) -> Vec<(Channel, &'static str, Color)> {
channels
}
-pub fn draw(cr: &Context, width: i32, height: i32, p: &Parameters, sim: &Simulator) {
+pub fn draw(cr: &Context, width: i32, height: i32, p: &Parameters,
+ sim: &Simulator, alarm_pause_seconds: Option<u64>) {
let w = f64::from(width.max(1));
let h = f64::from(height.max(1));
set_color(cr, BG);
@@ -60,6 +61,7 @@ pub fn draw(cr: &Context, width: i32, height: i32, p: &Parameters, sim: &Simulat
text(cr, "SIMULATION", split_x - 128.0 * text_scale, header * 0.58,
11.0 * text_scale, MUTED, false);
}
+ draw_header_controls(cr, w, h, alarm_pause_seconds);
stroke_line(cr, pad, header, w - pad, header, MUTED, 0.8);
stroke_line(cr, split_x, header, split_x, h - pad, MUTED, 0.9);
@@ -85,6 +87,95 @@ pub fn draw(cr: &Context, width: i32, height: i32, p: &Parameters, sim: &Simulat
numeric_width, p, sim);
}
+/// Header controls use the same Cairo canvas as the waveform. Their hit
+/// rectangles are shared by mouse and Wayland touch; no OSK is necessary.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum HeaderControl { Settings, PauseAlarms }
+
+fn header_buttons(width: f64, height: f64) -> [(HeaderControl, f64, f64, f64); 2] {
+ let pad = (width.min(height) * 0.018).clamp(6.0, 20.0);
+ let header = (height * 0.083).clamp(32.0, 68.0);
+ let side = (header * 0.54).clamp(22.0, 34.0);
+ let top = ((header - side - 14.0) * 0.5).max(2.0);
+ let pause_x = width - pad - side;
+ [
+ (HeaderControl::Settings, pause_x - side - 9.0, top, side),
+ (HeaderControl::PauseAlarms, pause_x, top, side),
+ ]
+}
+
+pub fn header_control_hit_test(x: f64, y: f64, width: i32, height: i32)
+ -> Option<HeaderControl> {
+ header_buttons(f64::from(width.max(1)), f64::from(height.max(1)))
+ .into_iter().find_map(|(control, left, top, side)| {
+ (x >= left && x <= left + side && y >= top && y <= top + side)
+ .then_some(control)
+ })
+}
+
+fn draw_header_controls(cr: &Context, w: f64, h: f64, paused: Option<u64>) {
+ use std::f64::consts::TAU;
+ let buttons = header_buttons(w, h);
+ for (control, x, y, side) in buttons {
+ let is_bell = control == HeaderControl::PauseAlarms;
+ set_color(cr, if is_bell { YELLOW } else { (0.11, 0.12, 0.13) });
+ cr.rectangle(x, y, side, side);
+ let _ = cr.fill();
+ set_color(cr, if is_bell { (0.0, 0.0, 0.0) } else { LIGHT_GREY });
+ cr.set_line_width((side * 0.065).max(1.3));
+ let cx = x + side * 0.5;
+ let cy = y + side * 0.49;
+ if is_bell {
+ // Bell dome, lower lip and clapper in the monitor's own palette.
+ let r = side * 0.23;
+ cr.move_to(cx - r, cy + r * 0.54);
+ cr.line_to(cx - r * 0.83, cy - r * 0.25);
+ cr.curve_to(cx - r * 0.85, cy - r * 1.65, cx + r * 0.85, cy - r * 1.65,
+ cx + r * 0.83, cy - r * 0.25);
+ cr.line_to(cx + r, cy + r * 0.54);
+ cr.close_path();
+ let _ = cr.stroke();
+ cr.move_to(cx - r * 1.12, cy + r * 0.66);
+ cr.line_to(cx + r * 1.12, cy + r * 0.66);
+ let _ = cr.stroke();
+ cr.arc(cx, cy + r * 0.83, r * 0.17, 0.0, TAU);
+ let _ = cr.fill();
+ } else {
+ let r = side * 0.22;
+ cr.arc(cx, cy, r, 0.0, TAU);
+ let _ = cr.stroke();
+ cr.arc(cx, cy, side * 0.065, 0.0, TAU);
+ let _ = cr.fill();
+ for i in 0..8 {
+ let angle = i as f64 * TAU / 8.0;
+ cr.move_to(cx + (r + side * 0.02) * angle.cos(),
+ cy + (r + side * 0.02) * angle.sin());
+ cr.line_to(cx + (r + side * 0.12) * angle.cos(),
+ cy + (r + side * 0.12) * angle.sin());
+ }
+ let _ = cr.stroke();
+ }
+ }
+ if let Some(seconds) = paused {
+ let (_, x, top, side) = buttons[1];
+ let message = format!("paused for {seconds} s");
+ let size = (side * 0.28).clamp(8.0, 10.0);
+ // Right-align below the bell, safely above the header divider.
+ let _ = cr.save();
+ cr.select_font_face("Sans", FontSlant::Normal, FontWeight::Normal);
+ cr.set_font_size(size);
+ if let Ok(extents) = cr.text_extents(&message) {
+ let text_x = (x + side - extents.width()).max(0.0);
+ let baseline = (top + side + size + 2.0)
+ .min((h * 0.083).clamp(32.0, 68.0) - 1.0);
+ set_color(cr, YELLOW);
+ cr.move_to(text_x, baseline);
+ let _ = cr.show_text(&message);
+ }
+ let _ = cr.restore();
+ }
+}
+
/// Touch regions track the actual layout, including hidden and reordered rows.
/// The last row uses four equal cells: only the NIBP cell is interactive.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -813,3 +904,22 @@ mod tests {
}
}
+
+#[cfg(test)]
+mod header_control_tests {
+ use super::*;
+
+ #[test]
+ fn header_buttons_are_distinct_touch_targets_outside_parameter_rows() {
+ for (w, h) in [(1200, 760), (700, 440), (1920, 1080)] {
+ let buttons = header_buttons(w as f64, h as f64);
+ for (kind, x, y, size) in buttons {
+ assert_eq!(header_control_hit_test(x + size / 2.0,
+ y + size / 2.0, w, h), Some(kind));
+ assert_eq!(monitor_hit_test(x + size / 2.0,
+ y + size / 2.0, w, h, &Parameters::default()), None);
+ }
+ assert_eq!(header_control_hit_test(10.0, h as f64 * 0.5, w, h), None);
+ }
+ }
+}
diff --git a/src/ui.rs b/src/ui.rs
index 0c02b36..210e862 100644
--- a/src/ui.rs
+++ b/src/ui.rs
@@ -34,10 +34,11 @@ pub fn create_windows(app: &Application) {
let simulator = Rc::new(RefCell::new(Simulator::new(&parameters.borrow())));
let audio = Rc::new(RefCell::new(AlarmAudio::new()));
let qrs_audio = Rc::new(RefCell::new(QrsAudio::new()));
+ let alarm_pause = Rc::new(RefCell::new(alarm::AlarmPause::default()));
install_ecg_menu_style(); // neutral style shared by all parameter panels
let admin_changed: AdminChanged = Rc::new(RefCell::new(None));
let monitor = create_monitor(app, parameters.clone(), simulator.clone(),
- admin_changed.clone());
+ admin_changed.clone(), alarm_pause.clone());
let admin = create_admin(app, parameters.clone(), simulator.clone(), &monitor,
audio.clone(), admin_changed);
@@ -47,7 +48,8 @@ pub fn create_windows(app: &Application) {
let config = parameters.borrow();
let mut sim = simulator.borrow_mut();
let events = sim.take_audio_events();
- let current = alarm::level(&config, &sim);
+ let active = alarm::active_conditions(&config, &sim);
+ let current = alarm_pause.borrow_mut().effective_level(Instant::now(), &active);
let beat_tone = alarm::qrs_tone(&config, &sim, &events);
drop(sim);
audio.borrow_mut().update(current, config.audible_alarms);
@@ -62,7 +64,8 @@ pub fn create_windows(app: &Application) {
fn create_monitor(app: &Application, params: SharedParams,
simulator: Rc<RefCell<Simulator>>,
- admin_changed: AdminChanged) -> ApplicationWindow {
+ admin_changed: AdminChanged,
+ alarm_pause: Rc<RefCell<alarm::AlarmPause>>) -> ApplicationWindow {
let window = ApplicationWindow::builder()
.application(app)
.title(concat!("Patient Monitor — Simulation v", env!("CARGO_PKG_VERSION")))
@@ -76,9 +79,11 @@ fn create_monitor(app: &Application, params: SharedParams,
canvas.set_draw_func({
let params = params.clone();
let simulator = simulator.clone();
+ let alarm_pause = alarm_pause.clone();
move |_area, cr, width, height| {
let config = params.borrow();
- render::draw(cr, width, height, &config, &simulator.borrow());
+ let remaining = alarm_pause.borrow().remaining_seconds(Instant::now());
+ render::draw(cr, width, height, &config, &simulator.borrow(), remaining);
}
});
@@ -124,7 +129,27 @@ fn create_monitor(app: &Application, params: SharedParams,
let canvas = canvas.clone();
let params = params.clone();
let simulator = simulator.clone();
+ let alarm_pause = alarm_pause.clone();
+ let admin_changed = admin_changed.clone();
+ let monitor_menu = monitor_menu.clone();
move |_gesture, _press_count, x, y| {
+ // Header actions do not activate parameter touch menus.
+ if let Some(control) = render::header_control_hit_test(
+ x, y, canvas.width(), canvas.height()) {
+ match control {
+ render::HeaderControl::PauseAlarms => {
+ let current = alarm::active_conditions(
+ &params.borrow(), &simulator.borrow());
+ alarm_pause.borrow_mut().pause_current(Instant::now(), &current);
+ canvas.queue_draw();
+ }
+ render::HeaderControl::Settings => {
+ open_monitor_settings(&app, &window, params.clone(),
+ admin_changed.clone(), monitor_menu.clone());
+ }
+ }
+ return;
+ }
let touched = {
let p = params.borrow();
render::monitor_hit_test(x, y, canvas.width(), canvas.height(), &p)
@@ -535,7 +560,7 @@ ART and pleth are delayed. VT can be perfusing; PVT, VF and asystole are pulsele
let params = params.clone();
let updating_preset = updating_preset.clone();
move |dropdown| {
- if dropdown.selected() != 1 { return; }
+ if updating_preset.get() || dropdown.selected() != 1 { return; }
let limits = AlarmSettings::adult();
// Suppress per-field callbacks while writing both entries in each row.
// Otherwise a half-updated pair could temporarily be invalid.
@@ -562,7 +587,17 @@ ART and pleth are delayed. VT can be perfusing; PVT, VF and asystole are pulsele
editor.set_limits(get_limits(&snapshot.alarms));
}
updating_preset.set(false);
- if alarm_changed { preset_dropdown.set_selected(0); }
+ // Keep Adult preset and the monitor settings synchronized. A
+ // manually edited matrix selects Custom unless it equals Adult.
+ let _ = alarm_changed;
+ updating_preset.set(true);
+ preset_dropdown.set_selected(if snapshot.alarms == AlarmSettings::adult() { 1 } else { 0 });
+ updating_preset.set(false);
+ audible.set_active(snapshot.audible_alarms);
+ qrs_enabled.set_active(snapshot.qrs_tone_enabled);
+ if name_entry.text().as_str() != snapshot.patient_name {
+ name_entry.set_text(&snapshot.patient_name);
+ }
lead_dropdown.set_selected(snapshot.ecg_lead.index());
spo2_quality_dropdown.set_selected(snapshot.spo2_quality as u32);
sensor.set_active(!snapshot.spo2_sensor_attached);
@@ -629,6 +664,11 @@ fn install_ecg_menu_style() {
min-height: 48px; min-width: 52px;
}
window.ecg-settings button:hover { background-color: #303437; }
+ window.ecg-settings entry {
+ color: #e5e9eb; background-color: #171717;
+ border: 1px solid #6b757d; min-height: 42px;
+ }
+ window.ecg-settings checkbutton { color: #e5e9eb; }
window.ecg-settings dropdown {
color: #e5e9eb; background-color: #171717;
border: 1px solid #6b757d; min-height: 48px;
@@ -987,6 +1027,135 @@ fn apply_module_alarm_changes(
p.alarms != previous
}
+/// Global controls requested for the monitor header. The settings window
+/// follows the existing black/light-grey touch-menu style. Only the patient
+/// name uses text input; no on-screen keyboard is constructed.
+fn open_monitor_settings(app: &Application, monitor: &ApplicationWindow,
+ params: SharedParams, on_change: AdminChanged,
+ open_menu: MonitorMenuHandle) {
+ if let Some(existing) = open_menu.borrow().as_ref().and_then(|weak| weak.upgrade()) {
+ existing.present();
+ return;
+ }
+ let current = params.borrow().clone();
+ let dialog = gtk::Window::builder()
+ .application(app)
+ .title("MONITOR / SETTINGS")
+ .transient_for(monitor)
+ .modal(true)
+ .resizable(true)
+ .default_width(570)
+ .default_height(480)
+ .build();
+ dialog.add_css_class("ecg-settings");
+ dialog.set_decorated(false);
+ *open_menu.borrow_mut() = Some(dialog.downgrade());
+
+ let content = gtk::Box::new(Orientation::Vertical, 12);
+ content.add_css_class("ecg-panel");
+ content.set_margin_top(1);
+ content.set_margin_bottom(1);
+ content.set_margin_start(1);
+ content.set_margin_end(1);
+ let inner = gtk::Box::new(Orientation::Vertical, 14);
+ inner.set_margin_top(20);
+ inner.set_margin_bottom(20);
+ inner.set_margin_start(20);
+ inner.set_margin_end(20);
+ let scroller = gtk::ScrolledWindow::new();
+ scroller.set_vexpand(true);
+ scroller.set_policy(gtk::PolicyType::Never, gtk::PolicyType::Automatic);
+ scroller.set_child(Some(&inner));
+ content.append(&scroller);
+ let heading = gtk::Label::new(Some("MONITOR / SETTINGS"));
+ heading.set_xalign(0.0);
+ heading.add_css_class("title-2");
+ inner.append(&heading);
+ inner.append(&ecg_menu_divider());
+
+ let qrs = gtk::CheckButton::with_label("QRS beep");
+ qrs.set_active(current.qrs_tone_enabled);
+ inner.append(&qrs);
+ let audible = gtk::CheckButton::with_label("Audible alarms");
+ audible.set_active(current.audible_alarms);
+ inner.append(&audible);
+ inner.append(&ecg_menu_divider());
+
+ let preset_row = gtk::Box::new(Orientation::Horizontal, 12);
+ let preset_label = gtk::Label::new(Some("Alert presets"));
+ preset_label.set_xalign(0.0);
+ preset_label.set_hexpand(true);
+ let preset = gtk::DropDown::from_strings(&["Custom", "Adult"]);
+ preset.set_selected(if current.alarms == AlarmSettings::adult() { 1 } else { 0 });
+ preset_row.append(&preset_label);
+ preset_row.append(&preset);
+ inner.append(&preset_row);
+
+ let patient_label = gtk::Label::new(Some("Patient name"));
+ patient_label.set_xalign(0.0);
+ inner.append(&patient_label);
+ let patient = gtk::Entry::new();
+ patient.set_max_length(80);
+ patient.set_text(&current.patient_name);
+ patient.set_placeholder_text(Some("Enter name with a physical keyboard"));
+ inner.append(&patient);
+ inner.append(&ecg_menu_divider());
+ let attribution = gtk::Label::new(Some(
+ "PaMSim by Critical Care Club Austria, (c) 2026"));
+ attribution.set_xalign(0.0);
+ attribution.set_wrap(true);
+ inner.append(&attribution);
+
+ let footer = gtk::Box::new(Orientation::Horizontal, 12);
+ footer.set_halign(gtk::Align::End);
+ footer.set_margin_start(20);
+ footer.set_margin_end(20);
+ footer.set_margin_bottom(14);
+ let cancel = gtk::Button::with_label("Cancel");
+ cancel.add_css_class("ecg-close");
+ cancel.connect_clicked({
+ let weak = dialog.downgrade();
+ move |_| { if let Some(window) = weak.upgrade() { window.close(); } }
+ });
+ let apply = gtk::Button::with_label("Apply");
+ apply.add_css_class("ecg-apply");
+ apply.connect_clicked({
+ let weak = dialog.downgrade();
+ move |_| {
+ let changed_alarms = {
+ let mut config = params.borrow_mut();
+ config.qrs_tone_enabled = qrs.is_active();
+ config.audible_alarms = audible.is_active();
+ config.patient_name = patient.text().to_string();
+ if preset.selected() == 1 && config.alarms != AlarmSettings::adult() {
+ config.alarms = AlarmSettings::adult();
+ true
+ } else { false }
+ };
+ if let Some(callback) = on_change.borrow().as_ref() {
+ callback(changed_alarms);
+ }
+ if let Some(window) = weak.upgrade() { window.close(); }
+ }
+ });
+ footer.append(&cancel);
+ footer.append(&apply);
+ content.append(&footer);
+ dialog.set_child(Some(&content));
+ let keys = gtk::EventControllerKey::new();
+ keys.connect_key_pressed({
+ let weak = dialog.downgrade();
+ move |_, key, _, _| {
+ if key == gdk::Key::Escape {
+ if let Some(window) = weak.upgrade() { window.close(); }
+ glib::Propagation::Stop
+ } else { glib::Propagation::Proceed }
+ }
+ });
+ dialog.add_controller(keys);
+ dialog.present();
+}
+
/// Open a modal monitor settings panel in neutral black/grey styling.
/// All modules edit alarm limits; NIBP also retains its explicit controls.
#[allow(clippy::too_many_arguments)]