v0.6.9: Actions & Occurrences

This commit is contained in:
GABRIEL Sebastian 2026-11-13 11:56:44 +01:00
commit c366c4f1d7
10 changed files with 2083 additions and 18 deletions

View file

@ -0,0 +1,466 @@
//! Instructor-scripted Actions & Occurrences, separate from Direct Mode.
//! The runner interpolates selected values only. Manual Direct Mode edits
//! release ownership of that parameter, and stopping preserves current values.
//! Times are elapsed simulation seconds, not frame counts.
use crate::model::{mean_arterial_pressure, ChestCompressionQuality, EcgRhythm, Parameters, Spo2Quality};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
Defibrillation,
DefibrillationRhythm,
Hypoxia,
Shock,
ChestCompressions,
Norepinephrine,
ExcessivePropofol,
LethalPropofol,
}
impl Kind {
pub const ALL: [Kind; 8] = [
Self::Defibrillation, Self::DefibrillationRhythm, Self::Hypoxia,
Self::Shock, Self::ChestCompressions, Self::Norepinephrine,
Self::ExcessivePropofol, Self::LethalPropofol,
];
pub fn label(self) -> &'static str {
match self {
Self::Defibrillation => "Defibrillation (ECG artifact)",
Self::DefibrillationRhythm => "Defibrillation + rhythm change",
Self::Hypoxia => "Deterioration: Hypoxia",
Self::Shock => "Deterioration: Shock",
Self::ChestCompressions => "Chest compressions",
Self::Norepinephrine => "Norepinephrine bolus",
Self::ExcessivePropofol => "Too much propofol",
Self::LethalPropofol => "Lethal propofol",
}
}
fn duration(self) -> f64 {
match self {
Self::Hypoxia => 300.0, Self::Shock => 600.0,
Self::Norepinephrine => 360.0,
Self::ExcessivePropofol | Self::LethalPropofol | Self::DefibrillationRhythm => 60.0,
_ => 0.0,
}
}
fn mask(self) -> u16 {
match self {
Self::DefibrillationRhythm => SYS | DIA | ETCO2,
Self::Hypoxia => SPO2 | HR,
Self::Shock => SYS | DIA | HR | RHYTHM | QUALITY,
Self::Norepinephrine => SYS | HR,
Self::ExcessivePropofol => SYS | DIA | HR,
Self::LethalPropofol => SYS | DIA | HR | RHYTHM,
_ => 0,
}
}
}
const HR: u16 = 1 << 0;
const RHYTHM: u16 = 1 << 1;
const SPO2: u16 = 1 << 2;
const QUALITY: u16 = 1 << 3;
const SYS: u16 = 1 << 4;
const DIA: u16 = 1 << 5;
const ETCO2: u16 = 1 << 6;
const BITS: [u16; 7] = [HR, RHYTHM, SPO2, QUALITY, SYS, DIA, ETCO2];
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Value {
Number(i32), Rhythm(EcgRhythm), Quality(Spo2Quality),
}
fn read(p: &Parameters, bit: u16) -> Value {
match bit {
HR => Value::Number(p.heart_rate),
RHYTHM => Value::Rhythm(p.ecg_rhythm),
SPO2 => Value::Number(p.spo2),
QUALITY => Value::Quality(p.spo2_quality),
SYS => Value::Number(p.art_systolic),
DIA => Value::Number(p.art_diastolic),
ETCO2 => Value::Number(p.etco2),
_ => unreachable!(),
}
}
fn write(p: &mut Parameters, bit: u16, value: Value) {
match (bit, value) {
(HR, Value::Number(v)) => p.heart_rate = v,
(RHYTHM, Value::Rhythm(v)) => p.ecg_rhythm = v,
(SPO2, Value::Number(v)) => p.spo2 = v,
(QUALITY, Value::Quality(v)) => p.spo2_quality = v,
(SYS, Value::Number(v)) => p.art_systolic = v,
(DIA, Value::Number(v)) => p.art_diastolic = v,
(ETCO2, Value::Number(v)) => p.etco2 = v,
_ => unreachable!(),
}
}
#[derive(Clone, Copy, Debug)]
struct Vitals {
hr: i32, rhythm: EcgRhythm, spo2: i32, quality: Spo2Quality,
sys: i32, dia: i32, etco2: i32, cpr: bool, cpr_quality: ChestCompressionQuality,
}
impl Vitals {
fn capture(p: &Parameters) -> Self {
Self { hr: p.heart_rate, rhythm: p.ecg_rhythm, spo2: p.spo2,
quality: p.spo2_quality, sys: p.art_systolic, dia: p.art_diastolic,
etco2: p.etco2, cpr: p.chest_compressions_active,
cpr_quality: p.chest_compression_quality }
}
fn restore(self, p: &mut Parameters) {
p.heart_rate = self.hr;
p.ecg_rhythm = self.rhythm;
p.spo2 = self.spo2;
p.spo2_quality = self.quality;
p.art_systolic = self.sys;
p.art_diastolic = self.dia;
p.etco2 = self.etco2;
p.chest_compressions_active = self.cpr;
p.chest_compression_quality = self.cpr_quality;
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Status { Running, Paused, Completed, Stopped }
impl Status {
pub fn label(self) -> &'static str {
match self {
Self::Running => "Running", Self::Paused => "Paused",
Self::Completed => "Completed", Self::Stopped => "Stopped",
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct DefibTargets {
pub rhythm: EcgRhythm,
pub systolic: i32,
pub diastolic: i32,
pub etco2: i32,
}
#[derive(Clone, Debug)]
pub struct Action {
pub id: u64,
pub kind: Kind,
pub elapsed: f64,
pub status: Status,
mask: u16,
start: Vitals,
hypoxia_target: i32,
shock_hr_140: i32,
shock_hr_160: i32,
propofol_hr: i32,
defib: Option<DefibTargets>,
etco2_perfusion: bool,
}
impl Action {
pub fn fraction(&self) -> f64 {
if self.kind.duration() <= 0.0 { 1.0 }
else { (self.elapsed / self.kind.duration()).clamp(0.0, 1.0) }
}
fn values(&self) -> Vec<(u16, Value)> {
let s = self.start;
let t = self.elapsed;
let num = |bit: u16, v: i32| (bit, Value::Number(v));
match self.kind {
Kind::Hypoxia => {
let sat = lerp(s.spo2, self.hypoxia_target, (t / 300.0).min(1.0));
let hr = if sat >= 60 { s.hr } else {
// Begin slowing at 60%, reaching <= 50/min by the endpoint.
let fraction = ((60 - sat) as f64 / (60 - self.hypoxia_target).max(1) as f64)
.clamp(0.0, 1.0);
lerp(s.hr, s.hr.min(50), fraction)
};
vec![num(SPO2, sat), num(HR, hr)]
}
Kind::Shock => {
let start_map = f64::from(mean_arterial_pressure(s.sys, s.dia).max(1));
let target_map = start_map.min(45.0);
let map = start_map + (target_map - start_map) * (t / 600.0).clamp(0.0, 1.0);
let scale = map / start_map;
let sys = (f64::from(s.sys) * scale).round().max(0.0) as i32;
let dia = (f64::from(s.dia) * scale).round().clamp(0.0, sys as f64) as i32;
let hr = if t < 300.0 {
lerp(s.hr, self.shock_hr_140, (t / 300.0).min(1.0))
} else {
lerp(self.shock_hr_140, self.shock_hr_160, ((t - 300.0) / 300.0).min(1.0))
};
let quality = if map <= 50.0 { Spo2Quality::None }
else if map <= 59.0 { s.quality.min(Spo2Quality::Poor) }
else { s.quality };
vec![num(HR, hr), (RHYTHM, Value::Rhythm(if t >= 300.0 {
EcgRhythm::AtrialFibrillation
} else { s.rhythm })), num(SYS, sys), num(DIA, dia),
(QUALITY, Value::Quality(quality))]
}
Kind::Norepinephrine => {
let (sys, hr) = if t <= 30.0 {
(lerp(s.sys, 200, t / 30.0), lerp(s.hr, 160, t / 30.0))
} else if t <= 60.0 {
(lerp(200, 260, (t - 30.0) / 30.0), lerp(160, 180, (t - 30.0) / 30.0))
} else {
(lerp(260, s.sys, (t - 60.0) / 300.0),
lerp(180, s.hr, (t - 60.0) / 300.0))
};
vec![num(SYS, sys), num(HR, hr)]
}
Kind::ExcessivePropofol => {
let a = (t / 60.0).min(1.0);
vec![num(SYS, lerp(s.sys, 60, a)), num(DIA, lerp(s.dia, 45, a)),
num(HR, lerp(s.hr, self.propofol_hr, a))]
}
Kind::LethalPropofol => {
let a = (t / 60.0).min(1.0);
vec![num(SYS, lerp(s.sys, 40, a)), num(DIA, lerp(s.dia, 20, a)),
num(HR, lerp(s.hr, self.propofol_hr, a)),
(RHYTHM, Value::Rhythm(if t >= 60.0 {
EcgRhythm::VentricularFibrillation
} else { s.rhythm }))]
}
Kind::DefibrillationRhythm => {
let d = self.defib.expect("defibrillation targets");
let a = (t / 60.0).min(1.0);
let mut values = vec![num(SYS, lerp(s.sys, d.systolic, a)),
num(DIA, lerp(s.dia, d.diastolic, a))];
if self.etco2_perfusion {
values.push(num(ETCO2, lerp(s.etco2, d.etco2, (t / 30.0).min(1.0))));
}
values
}
Kind::Defibrillation | Kind::ChestCompressions => Vec::new(),
}
}
}
fn lerp(a: i32, b: i32, f: f64) -> i32 {
(f64::from(a) + f64::from(b - a) * f.clamp(0.0, 1.0)).round() as i32
}
#[derive(Default)]
pub struct ActionRunner {
pub actions: Vec<Action>,
next_id: u64,
rng: u64,
baseline: Option<Vitals>,
last_written: [Option<Value>; 7],
}
impl ActionRunner {
fn random(&mut self, low: i32, high: i32) -> i32 {
self.rng = self.rng.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
if self.rng == 0 { self.rng = 0xDEAD_BEEF; }
low + ((self.rng >> 32) % ((high - low + 1) as u64)) as i32
}
fn detect_manual_changes(&mut self, p: &Parameters) {
for (index, bit) in BITS.iter().enumerate() {
if self.last_written[index].is_some_and(|v| v != read(p, *bit)) {
for action in &mut self.actions { action.mask &= !*bit; }
self.last_written[index] = None;
}
}
}
pub fn remember_baseline(&mut self, p: &Parameters) {
if self.baseline.is_none() { self.baseline = Some(Vitals::capture(p)); }
}
pub fn trigger(&mut self, kind: Kind, p: &mut Parameters,
defib: Option<DefibTargets>) -> Option<u64> {
self.detect_manual_changes(p);
if self.baseline.is_none() { self.baseline = Some(Vitals::capture(p)); }
if kind == Kind::Defibrillation || kind == Kind::ChestCompressions {
return None; // caller handles instantaneous simulator artifact / CPR toggle
}
let start = Vitals::capture(p);
let target_spo2 = self.random(40, 50);
let hr_140 = self.random(133, 147);
let hr_160 = self.random(152, 168);
let propofol_hr = match kind {
Kind::ExcessivePropofol => self.random(124, 137),
Kind::LethalPropofol => self.random(143, 158),
_ => start.hr,
};
let defib = if kind == Kind::DefibrillationRhythm {
Some(defib.expect("rhythm + targets required"))
} else { None };
let mut mask = kind.mask();
let perfusing = defib.is_some_and(|d| d.rhythm.can_generate_pulse()
&& p.pulse_conduction != crate::model::PulseConduction::None && p.heart_rate > 0)
|| p.chest_compressions_active
&& p.chest_compression_quality != ChestCompressionQuality::Bad;
if !perfusing && kind == Kind::DefibrillationRhythm { mask &= !ETCO2; }
for action in &mut self.actions { action.mask &= !mask; }
self.next_id += 1;
let id = self.next_id;
self.actions.push(Action { id, kind, elapsed: 0.0, status: Status::Running,
mask, start, hypoxia_target: target_spo2, shock_hr_140: hr_140,
shock_hr_160: hr_160, propofol_hr, defib, etco2_perfusion: perfusing });
if let Some(d) = defib {
// Explicit instructor rhythm conversion preempts any older delayed
// rhythm changes (e.g. lethal propofol's pending VF transition).
for action in &mut self.actions {
if action.id != id { action.mask &= !RHYTHM; }
}
// Rhythm is switched on shock delivery, not at the end of the BP ramp.
p.select_ecg_rhythm(d.rhythm);
// A rhythm change that selected VT/PVT also updates the physiological HR.
// The action does not claim the HR parameter afterwards.
}
Some(id)
}
pub fn advance(&mut self, dt: f64, p: &mut Parameters) {
self.detect_manual_changes(p);
let mut controlled = 0;
for a in &mut self.actions {
if a.status == Status::Running {
a.elapsed = (a.elapsed + dt.max(0.0)).min(a.kind.duration());
for (bit, val) in a.values() {
if a.mask & bit != 0 { write(p, bit, val); controlled |= bit; }
}
if a.elapsed >= a.kind.duration() { a.status = Status::Completed; a.mask = 0; }
} else if a.status == Status::Paused {
controlled |= a.mask;
}
}
// Only an ongoing script should retain ownership in the next frame.
controlled = self.actions.iter().filter(|a| {
a.status == Status::Running || a.status == Status::Paused
}).fold(0, |mask, a| mask | a.mask) & controlled;
for (i, bit) in BITS.iter().enumerate() {
self.last_written[i] = if controlled & bit != 0 { Some(read(p, *bit)) } else { None };
}
}
pub fn pause_or_resume(&mut self, id: u64) {
if let Some(a) = self.actions.iter_mut().find(|a| a.id == id) {
a.status = match a.status {
Status::Running => Status::Paused, Status::Paused => Status::Running,
other => other,
};
}
}
pub fn stop(&mut self, id: u64) {
if let Some(a) = self.actions.iter_mut().find(|a| a.id == id) {
if matches!(a.status, Status::Running | Status::Paused) {
a.status = Status::Stopped;
a.mask = 0;
}
}
// Preserve all currently displayed values, without resurrecting old actions.
}
pub fn restore_baseline(&mut self, p: &mut Parameters) {
for a in &mut self.actions {
if matches!(a.status, Status::Running | Status::Paused) { a.status = Status::Stopped; }
a.mask = 0;
}
if let Some(b) = self.baseline.take() { b.restore(p); }
self.last_written = [None; 7];
}
pub fn status(&self, id: u64) -> Option<(Status, f64)> {
self.actions.iter().find(|a| a.id == id).map(|a| (a.status, a.fraction()))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hypoxia_runs_five_minutes_then_remains_and_can_be_stopped() {
let mut p = Parameters::default(); let mut r = ActionRunner::default();
let id = r.trigger(Kind::Hypoxia, &mut p, None).unwrap();
r.advance(240.0, &mut p);
assert!(p.spo2 > 45 && p.spo2 < 65);
r.pause_or_resume(id);
let paused = p.spo2;
r.advance(30.0, &mut p);
assert_eq!(p.spo2, paused);
r.pause_or_resume(id); r.advance(60.0, &mut p);
assert!((40..=50).contains(&p.spo2));
assert!(p.heart_rate <= 50);
assert_eq!(r.status(id).unwrap().0, Status::Completed);
}
#[test]
fn shock_stop_holds_level_and_nibp_configuration_is_untouched() {
let mut p = Parameters::default(); let mut r = ActionRunner::default();
let id = r.trigger(Kind::Shock, &mut p, None).unwrap();
r.advance(550.0, &mut p);
assert_eq!(p.ecg_rhythm, EcgRhythm::AtrialFibrillation);
assert_eq!(p.spo2_quality, Spo2Quality::None);
let values = (p.art_systolic, p.art_diastolic, p.heart_rate);
r.stop(id); r.advance(60.0, &mut p);
assert_eq!((p.art_systolic, p.art_diastolic, p.heart_rate), values);
assert!(!p.nibp_auto_measurement);
}
#[test]
fn norepinephrine_peaks_then_recovers_original_hr_and_sys() {
let mut p = Parameters::default(); let mut r = ActionRunner::default();
r.trigger(Kind::Norepinephrine, &mut p, None);
r.advance(30.0, &mut p); assert_eq!((p.art_systolic, p.heart_rate), (200,160));
r.advance(30.0, &mut p); assert_eq!((p.art_systolic, p.heart_rate), (260,180));
r.advance(300.0, &mut p); assert_eq!((p.art_systolic, p.heart_rate), (120,75));
}
#[test]
fn lethal_propofol_progresses_to_vf_but_stopping_prevents_switch() {
let mut p = Parameters::default(); let mut r = ActionRunner::default();
let id = r.trigger(Kind::LethalPropofol, &mut p, None).unwrap();
r.advance(45.0, &mut p); r.stop(id); r.advance(45.0, &mut p);
assert_eq!(p.ecg_rhythm, EcgRhythm::Sinus);
let id = r.trigger(Kind::LethalPropofol, &mut p, None).unwrap();
r.advance(60.0, &mut p);
assert_eq!(r.status(id).unwrap().0, Status::Completed);
assert_eq!(p.ecg_rhythm, EcgRhythm::VentricularFibrillation);
assert_eq!((p.art_systolic,p.art_diastolic), (40,20));
}
#[test]
fn manual_direct_change_takes_over_just_that_parameter() {
let mut p = Parameters::default(); let mut r = ActionRunner::default();
r.trigger(Kind::Hypoxia, &mut p, None); r.advance(100.0, &mut p);
p.spo2 = 98;
r.advance(100.0, &mut p);
assert_eq!(p.spo2, 98);
assert!(p.heart_rate <= 75);
}
#[test]
fn defibrillation_targets_only_when_perfusing_and_preserves_nibp() {
let mut p = Parameters::default(); let mut r = ActionRunner::default();
let d = DefibTargets { rhythm: EcgRhythm::Sinus, systolic: 130, diastolic: 85, etco2: 42 };
r.trigger(Kind::DefibrillationRhythm, &mut p, Some(d));
r.advance(30.0, &mut p); assert_eq!(p.etco2, 42);
r.advance(30.0, &mut p);
assert_eq!((p.art_systolic, p.art_diastolic), (130,85));
assert_eq!(p.nibp_systolic, 118);
}
#[test]
fn shock_reaches_target_map_and_signal_thresholds() {
let mut p = Parameters::default(); let mut r = ActionRunner::default();
r.trigger(Kind::Shock, &mut p, None);
r.advance(600.0, &mut p);
assert!((43..=47).contains(&mean_arterial_pressure(p.art_systolic, p.art_diastolic)));
assert_eq!(p.spo2_quality, Spo2Quality::None);
assert_eq!(p.ecg_rhythm, EcgRhythm::AtrialFibrillation);
assert!((152..=168).contains(&p.heart_rate));
}
#[test]
fn baseline_restoration_is_explicit_and_recovers_original_values() {
let mut p = Parameters::default(); let mut r = ActionRunner::default();
r.trigger(Kind::Shock, &mut p, None);
r.advance(400.0, &mut p);
r.restore_baseline(&mut p);
assert_eq!((p.heart_rate, p.art_systolic, p.spo2_quality),
(75, 120, Spo2Quality::Good));
assert_eq!(p.ecg_rhythm, EcgRhythm::Sinus);
}
#[test]
fn defibrillation_into_pvt_does_not_increase_etco2() {
let mut p = Parameters::default(); let mut r = ActionRunner::default();
let d = DefibTargets { rhythm: EcgRhythm::PulselessVentricularTachycardia,
systolic: 120, diastolic: 80, etco2: 70 };
r.trigger(Kind::DefibrillationRhythm, &mut p, Some(d));
r.advance(60.0, &mut p);
assert_eq!(p.etco2, 38);
assert_eq!(p.ecg_rhythm, EcgRhythm::PulselessVentricularTachycardia);
}
#[test]
fn newer_overlapping_action_has_precedence() {
let mut p = Parameters::default(); let mut r = ActionRunner::default();
r.trigger(Kind::Hypoxia, &mut p, None);
r.advance(10.0, &mut p);
r.trigger(Kind::Shock, &mut p, None);
r.advance(100.0, &mut p);
assert_ne!(p.heart_rate, 75);
assert!(p.spo2 < 98);
}
}

View file

@ -1,3 +1,4 @@
mod actions;
mod alarm;
mod model;
mod nibp;

View file

@ -206,6 +206,7 @@ pub struct Simulator {
compressions: ChestCompressions,
nibp: NibpMachine,
art_hold_pressure: Option<f64>,
defibrillation_at: Option<f64>,
pending_time: f64,
}
@ -227,6 +228,7 @@ impl Simulator {
compressions: ChestCompressions::new(),
nibp: NibpMachine::new(),
art_hold_pressure: None,
defibrillation_at: None,
pending_time: 0.0,
};
// Prepopulate the trace and pulse history, including the initial pulse rate.
@ -238,6 +240,10 @@ impl Simulator {
sim
}
/// Produce a brief electrical defibrillation artifact without changing
/// rhythm or mechanical output; the Actions runner handles optional conversion.
pub fn defibrillate(&mut self) { self.defibrillation_at = Some(self.time); }
pub fn advance(&mut self, elapsed_seconds: f64, params: &Parameters) {
// Cap huge steps after a suspended/minimized window.
self.pending_time += elapsed_seconds.clamp(0.0, 0.1);
@ -500,6 +506,16 @@ impl Simulator {
}
let mut ecg = ecg_amplitude(self.ecg_phase, self.time, params.ecg_rhythm, params.heart_rate);
if let Some(start) = self.defibrillation_at {
let age = self.time - start;
if age < 0.09 { ecg += 5.5 * (age / 0.09).clamp(0.0, 1.0); }
else if age < 0.20 { ecg -= 5.5 * ((0.20 - age) / 0.11); }
else if age < 1.25 {
let remaining = (1.25 - age) / 1.05;
ecg += remaining * (0.22 * (self.time * 43.0).sin()
+ 0.12 * (self.time * 87.0).sin());
} else { self.defibrillation_at = None; }
}
let (mut normal_art, mut pleth_target) = self.mechanical_signals(params);
if self.compressions.active {
ecg += self.compressions.ecg_artifact(self.time);
@ -573,8 +589,8 @@ impl Simulator {
}
fn mechanical_signals(&self, params: &Parameters) -> (f64, f64) {
let systolic = params.art_systolic.clamp(0, 200) as f64;
let diastolic = params.art_diastolic.clamp(0, 200).min(params.art_systolic.clamp(0, 200)) as f64;
let systolic = params.art_systolic.clamp(0, 300) as f64;
let diastolic = params.art_diastolic.clamp(0, 300).min(params.art_systolic.clamp(0, 300)) as f64;
let pulse_pressure = (systolic - diastolic).max(0.0);
let mut latest_art_age: Option<f64> = None;
@ -606,7 +622,7 @@ impl Simulator {
// 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();
(baseline + pulse_pressure * art_peak).clamp(0.0, 250.0)
(baseline + pulse_pressure * art_peak).clamp(0.0, 300.0)
} else {
0.0
};
@ -1340,3 +1356,19 @@ mod tests {
assert!((capno_amplitude(0.76, CapnoShape::Normal) - 1.0).abs() < 1e-8);
}
}
#[cfg(test)]
mod action_artifact_tests {
use super::*;
#[test]
fn defibrillation_artifact_is_transient_without_changing_rhythm() {
let p = Parameters::default();
let mut s = Simulator::new(&p);
s.defibrillate();
s.advance(0.1, &p);
assert!(s.samples.iter().rev().take(25).any(|v| v.ecg.abs() > 2.0));
for _ in 0..25 { s.advance(0.1, &p); }
assert!(s.defibrillation_at.is_none());
assert_eq!(p.ecg_rhythm, EcgRhythm::Sinus);
}
}

View file

@ -9,12 +9,14 @@ use gtk::prelude::*;
use gtk::{Application, ApplicationWindow, Orientation};
use crate::alarm::{self, AlarmAudio, QrsAudio};
use crate::actions::{ActionRunner, DefibTargets, Kind, Status};
use crate::model::{AlarmLimits, AlarmSettings, ArterialShape, CapnoShape,
ChestCompressionQuality, EcgLead, EcgRhythm, Parameters, PulseConduction, Spo2Quality};
use crate::render;
use crate::simulation::Simulator;
type SharedParams = Rc<RefCell<Parameters>>;
type SharedActions = Rc<RefCell<ActionRunner>>;
/// Refresh all Admin widgets whenever a monitor touch-menu commits changes.
/// The bool indicates whether alarm limits changed (mark preset as Custom).
type AdminChanged = Rc<RefCell<Option<Box<dyn Fn(bool)>>>>;
@ -31,6 +33,7 @@ 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 actions = Rc::new(RefCell::new(ActionRunner::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()));
@ -38,9 +41,9 @@ pub fn create_windows(app: &Application) {
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(), alarm_pause.clone());
let admin = create_admin(app, parameters.clone(), simulator.clone(), &monitor,
audio.clone(), admin_changed);
actions.clone(), admin_changed.clone(), alarm_pause.clone());
let admin = create_admin(app, parameters.clone(), simulator.clone(), actions.clone(),
&monitor, audio.clone(), admin_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.
@ -64,6 +67,7 @@ pub fn create_windows(app: &Application) {
fn create_monitor(app: &Application, params: SharedParams,
simulator: Rc<RefCell<Simulator>>,
actions: SharedActions,
admin_changed: AdminChanged,
alarm_pause: Rc<RefCell<alarm::AlarmPause>>) -> ApplicationWindow {
let window = ApplicationWindow::builder()
@ -92,11 +96,13 @@ fn create_monitor(app: &Application, params: SharedParams,
canvas.add_tick_callback({
let params = params.clone();
let simulator = simulator.clone();
let actions = actions.clone();
move |area, _frame_clock| {
let now = Instant::now();
let elapsed = now.saturating_duration_since(previous.get()).as_secs_f64();
previous.set(now);
let config = params.borrow();
let mut config = params.borrow_mut();
actions.borrow_mut().advance(elapsed.clamp(0.0, 0.1), &mut config);
simulator.borrow_mut().advance(elapsed, &config);
area.queue_draw();
glib::ControlFlow::Continue
@ -187,7 +193,7 @@ fn apply_nibp_measurement_settings(p: &mut Parameters, selected: u32, auto: bool
}
fn create_admin(app: &Application, params: SharedParams,
simulator: Rc<RefCell<Simulator>>,
simulator: Rc<RefCell<Simulator>>, actions: SharedActions,
monitor: &ApplicationWindow,
audio: Rc<RefCell<AlarmAudio>>,
admin_changed: AdminChanged) -> ApplicationWindow {
@ -313,7 +319,7 @@ fn create_admin(app: &Application, params: SharedParams,
}
});
cpr.append(&compression_button);
let _quality = add_dropdown_at(&cpr, "Compression quality",
let compression_quality_dropdown = add_dropdown_at(&cpr, "Compression quality",
&["Good", "Adequate", "Poor", "Bad"], 1, params.clone(), |p, selected| {
p.chest_compression_quality = match selected {
0 => ChestCompressionQuality::Good,
@ -359,6 +365,8 @@ fn create_admin(app: &Application, params: SharedParams,
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.
let hr_slider_for_direct = hr_slider.clone();
let hr_entry_for_direct = hr_entry.clone();
rhythm_dropdown.connect_selected_notify(move |selector| {
if selector.selected() == 2 || selector.selected() == 3 {
hr_slider.set_value(160.0);
@ -372,7 +380,7 @@ fn create_admin(app: &Application, params: SharedParams,
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,
let (spo2_row, spo2_slider, spo2_entry) = 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,
@ -437,7 +445,7 @@ ART and pleth are delayed. VT can be perfusing; PVT, VF and asystole are pulsele
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,
let (art_sys_row, art_sys_slider, art_sys_entry) = add_numeric(&art, "Systolic", "mmHg", 0, 300, 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,
@ -445,7 +453,7 @@ 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, art_dia_slider, art_dia_entry) = add_numeric(&art, "Diastolic", "mmHg", 0, 300, 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,
@ -543,7 +551,7 @@ 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, etco2_slider, etco2_entry) = 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,
@ -580,6 +588,7 @@ ART and pleth are delayed. VT can be perfusing; PVT, VF and asystole are pulsele
let params = params.clone();
let preset_dropdown = preset_dropdown.clone();
let updating_preset = updating_preset.clone();
let spo2_quality_dropdown = spo2_quality_dropdown.clone();
move |alarm_changed: bool| {
let snapshot = params.borrow().clone();
updating_preset.set(true);
@ -617,7 +626,72 @@ ART and pleth are delayed. VT can be perfusing; PVT, VF and asystole are pulsele
}));
scroller.set_child(Some(&controls));
main_box.append(&scroller);
// Direct Mode stays intact. Scripted events live in their own Admin tab.
let tabs = gtk::Notebook::new();
tabs.set_hexpand(true);
tabs.set_vexpand(true);
tabs.append_page(&scroller, Some(&gtk::Label::new(Some("Direct Mode"))));
let scripted = actions_page(params.clone(), simulator.clone(), actions.clone(),
compression_button.clone(), compression_quality_dropdown.clone());
tabs.append_page(&scripted, Some(&gtk::Label::new(Some("Actions & Occurrences"))));
main_box.append(&tabs);
// Keep sliders and text fields in Direct Mode consistent with scripted values.
// Programmatic updates write the identical value; instructor edits in that
// interval release just the corresponding scripted parameter.
let synced_numbers: Vec<(gtk::Scale, gtk::Entry, fn(&Parameters) -> i32)> = vec![
(hr_slider_for_direct, hr_entry_for_direct, |p| p.heart_rate),
(spo2_slider, spo2_entry, |p| p.spo2),
(art_sys_slider, art_sys_entry, |p| p.art_systolic),
(art_dia_slider, art_dia_entry, |p| p.art_diastolic),
(etco2_slider, etco2_entry, |p| p.etco2),
];
glib::timeout_add_local(Duration::from_millis(250), {
let params = params.clone();
let rhythm_dropdown = rhythm_dropdown.clone();
let spo2_quality_dropdown = spo2_quality_dropdown.clone();
let compression_button = compression_button.clone();
let compression_quality_dropdown = compression_quality_dropdown.clone();
move || {
let snapshot = params.borrow().clone();
for (scale, entry, read_value) in &synced_numbers {
let target = read_value(&snapshot);
if !entry.has_focus() {
if scale.value().round() as i32 != target {
scale.set_value(f64::from(target));
}
if entry.text().as_str() != target.to_string() {
entry.set_text(&target.to_string());
}
}
}
let rhythm = match snapshot.ecg_rhythm {
EcgRhythm::Sinus => 0, EcgRhythm::AtrialFibrillation => 1,
EcgRhythm::VentricularTachycardia => 2,
EcgRhythm::PulselessVentricularTachycardia => 3,
EcgRhythm::VentricularFibrillation => 4, EcgRhythm::Asystole => 5,
};
if rhythm_dropdown.selected() != rhythm { rhythm_dropdown.set_selected(rhythm); }
if spo2_quality_dropdown.selected() != snapshot.spo2_quality as u32 {
spo2_quality_dropdown.set_selected(snapshot.spo2_quality as u32);
}
let active = snapshot.chest_compressions_active;
compression_button.set_label(if active { "Stop Chest Compressions" }
else { "Start Chest Compressions" });
compression_button.remove_css_class(if active { "cpr-start" } else { "cpr-stop" });
compression_button.add_css_class(if active { "cpr-stop" } else { "cpr-start" });
let qindex = match snapshot.chest_compression_quality {
ChestCompressionQuality::Good => 0,
ChestCompressionQuality::Adequate => 1,
ChestCompressionQuality::Poor => 2,
ChestCompressionQuality::Bad => 3,
};
if compression_quality_dropdown.selected() != qindex {
compression_quality_dropdown.set_selected(qindex);
}
glib::ControlFlow::Continue
}
});
let fullscreen = gtk::CheckButton::with_label("Monitor fullscreen (F11 / Esc)");
fullscreen.connect_toggled({
@ -1666,3 +1740,256 @@ fn update_alarm_limits(low_entry: &gtk::Entry, high_entry: &gtk::Entry, max: i32
if limits.valid() { setter(&mut params.borrow_mut(), limits); }
}
}
/// Scripted instructor actions are additive to Direct Mode, never a replacement
/// for its sliders, ECG rhythms, alarm limits or NIBP scheduling controls.
fn actions_page(params: SharedParams, simulator: Rc<RefCell<Simulator>>,
actions: SharedActions, direct_cpr_button: gtk::Button,
direct_cpr_quality: gtk::DropDown) -> gtk::ScrolledWindow {
let scroller = gtk::ScrolledWindow::new();
scroller.set_policy(gtk::PolicyType::Never, gtk::PolicyType::Automatic);
let panel = gtk::Box::new(Orientation::Vertical, 14);
panel.set_margin_top(12);
panel.set_margin_bottom(12);
panel.set_margin_start(12);
panel.set_margin_end(12);
let heading = gtk::Label::new(Some("Actions & Occurrences — scripted teaching events"));
heading.set_xalign(0.0);
panel.append(&heading);
let note = gtk::Label::new(Some(concat!(
"Events act on current Direct Mode parameters. Multiple events may overlap; the newest ",
"event owns shared parameters. Direct Mode edits release that parameter. ",
"Pause freezes a timeline; Stop retains the present state. NIBP keeps its cuff cycle."
)));
note.set_xalign(0.0);
note.set_wrap(true);
panel.append(&note);
let selection = gtk::DropDown::from_strings(&[
"Defibrillation (ECG artifact)", "Defibrillation + rhythm change",
"Deterioration: Hypoxia", "Deterioration: Shock",
"Chest compressions", "Norepinephrine bolus",
"Too much propofol", "Lethal propofol",
]);
selection.set_hexpand(true);
panel.append(&selection);
// Instructor targets for a rhythm-converting defibrillation event. These
// targets are explicitly instructor-defined; none are inferred from NIBP.
let defib_config = gtk::Box::new(Orientation::Vertical, 8);
let defib_hint = gtk::Label::new(Some(concat!(
"Select the rhythm immediately after the shock. ART moves to the specified ",
"SYS/DIA over 60 s; EtCO₂ reaches its target over 30 s only with output."
)));
defib_hint.set_wrap(true);
defib_hint.set_xalign(0.0);
defib_config.append(&defib_hint);
let defib_rhythm = gtk::DropDown::from_strings(&[
"Sinus rhythm", "Atrial fibrillation", "VT", "PVT", "VF", "Asystole",
]);
defib_config.append(&defib_rhythm);
let targets = gtk::Box::new(Orientation::Horizontal, 10);
fn target_spin(parent: &gtk::Box, label: &str, initial: f64, max: f64) -> gtk::SpinButton {
let item = gtk::Box::new(Orientation::Vertical, 4);
let text = gtk::Label::new(Some(label));
text.set_xalign(0.0);
item.append(&text);
let spin = gtk::SpinButton::with_range(0.0, max, 1.0);
spin.set_value(initial);
item.append(&spin);
parent.append(&item);
spin
}
let target_sys = target_spin(&targets, "ART SYS", 120.0, 300.0);
let target_dia = target_spin(&targets, "ART DIA", 75.0, 300.0);
let target_etco2 = target_spin(&targets, "EtCO₂", 38.0, 100.0);
defib_config.append(&targets);
defib_config.set_visible(false);
panel.append(&defib_config);
let cpr_config = gtk::Box::new(Orientation::Vertical, 8);
let cpr_quality = gtk::DropDown::from_strings(&["Good", "Adequate", "Poor", "Bad"]);
cpr_quality.set_selected(1);
let quality_caption = gtk::Label::new(Some("Chest-compression quality"));
quality_caption.set_xalign(0.0);
cpr_config.append(&quality_caption);
cpr_config.append(&cpr_quality);
let cpr_button = gtk::Button::with_label("Start Chest Compressions");
cpr_button.set_hexpand(true);
cpr_button.add_css_class("cpr-start");
cpr_config.append(&cpr_button);
cpr_config.set_visible(false);
panel.append(&cpr_config);
cpr_quality.connect_selected_notify({
let params = params.clone();
move |widget| {
params.borrow_mut().chest_compression_quality = match widget.selected() {
0 => ChestCompressionQuality::Good,
2 => ChestCompressionQuality::Poor,
3 => ChestCompressionQuality::Bad,
_ => ChestCompressionQuality::Adequate,
};
}
});
cpr_button.connect_clicked({
let params = params.clone();
let actions = actions.clone();
move |_| {
let mut p = params.borrow_mut();
actions.borrow_mut().remember_baseline(&p);
p.chest_compressions_active = !p.chest_compressions_active;
}
});
// Update CPR actions when the instructor also uses Direct Mode.
glib::timeout_add_local(Duration::from_millis(250), {
let params = params.clone();
let cpr_button = cpr_button.clone();
let cpr_quality = cpr_quality.clone();
let direct_cpr_button = direct_cpr_button.clone();
let direct_cpr_quality = direct_cpr_quality.clone();
move || {
let p = params.borrow().clone();
let active = p.chest_compressions_active;
cpr_button.set_label(if active { "Stop Chest Compressions" }
else { "Start Chest Compressions" });
cpr_button.remove_css_class(if active { "cpr-start" } else { "cpr-stop" });
cpr_button.add_css_class(if active { "cpr-stop" } else { "cpr-start" });
// Keep the existing Direct Mode controls as the authoritative UI.
let _ = (&direct_cpr_button, &direct_cpr_quality);
let quality_index = match p.chest_compression_quality {
ChestCompressionQuality::Good => 0,
ChestCompressionQuality::Adequate => 1,
ChestCompressionQuality::Poor => 2,
ChestCompressionQuality::Bad => 3,
};
if cpr_quality.selected() != quality_index { cpr_quality.set_selected(quality_index); }
glib::ControlFlow::Continue
}
});
let info = gtk::Label::new(Some("Instant artifact; does not automatically alter rhythm."));
info.set_wrap(true);
info.set_xalign(0.0);
panel.append(&info);
let trigger = gtk::Button::with_label("Trigger action");
panel.append(&trigger);
selection.connect_selected_notify({
let defib_config = defib_config.clone();
let cpr_config = cpr_config.clone();
let trigger = trigger.clone();
let info = info.clone();
move |dropdown| {
let kind = Kind::ALL.get(dropdown.selected() as usize)
.copied().unwrap_or(Kind::Defibrillation);
defib_config.set_visible(kind == Kind::DefibrillationRhythm);
cpr_config.set_visible(kind == Kind::ChestCompressions);
trigger.set_visible(kind != Kind::ChestCompressions);
info.set_text(match kind {
Kind::Defibrillation => "Brief ECG shock artifact without automatic conversion.",
Kind::DefibrillationRhythm => "Instant rhythm change, ART target after 60 s, EtCO₂ after 30 s if cardiac output exists.",
Kind::Hypoxia => "SpO₂ to 45% ±5 over 5 minutes; HR slows once saturation falls below 60%.",
Kind::Shock => "10-minute deterioration: HR about 140, then AF about 160; ART MAP to 45. SpO₂ signal degrades at MAP 59/50.",
Kind::ChestCompressions => "Manual Start/Stop and quality; mirrors Direct Mode CPR controls.",
Kind::Norepinephrine => "ART SYS/HR to 200/160 after 30 s, 260/180 after 60 s; recovery over 5 minutes.",
Kind::ExcessivePropofol => "After 60 s: ART 60/45 mmHg and HR about 130.",
Kind::LethalPropofol => "After 60 s: ART 40/20 mmHg and HR about 150, then VF.",
});
}
});
let active_title = gtk::Label::new(Some("Action history / control"));
active_title.set_xalign(0.0);
panel.append(&active_title);
let action_rows = gtk::Box::new(Orientation::Vertical, 8);
panel.append(&action_rows);
trigger.connect_clicked({
let params = params.clone();
let simulator = simulator.clone();
let actions = actions.clone();
let selection = selection.clone();
let defib_rhythm = defib_rhythm.clone();
let target_sys = target_sys.clone();
let target_dia = target_dia.clone();
let target_etco2 = target_etco2.clone();
let action_rows = action_rows.clone();
let info = info.clone();
move |_| {
let kind = Kind::ALL.get(selection.selected() as usize)
.copied().unwrap_or(Kind::Defibrillation);
if kind == Kind::ChestCompressions { return; }
let defib = if kind == Kind::DefibrillationRhythm {
let rhythm = match defib_rhythm.selected() {
1 => EcgRhythm::AtrialFibrillation,
2 => EcgRhythm::VentricularTachycardia,
3 => EcgRhythm::PulselessVentricularTachycardia,
4 => EcgRhythm::VentricularFibrillation,
5 => EcgRhythm::Asystole,
_ => EcgRhythm::Sinus,
};
let sys = target_sys.value_as_int();
let dia = target_dia.value_as_int();
if dia > sys { info.set_text("ART DIA must not exceed SYS."); return; }
Some(DefibTargets { rhythm, systolic: sys, diastolic: dia,
etco2: target_etco2.value_as_int() })
} else { None };
if matches!(kind, Kind::Defibrillation | Kind::DefibrillationRhythm) {
simulator.borrow_mut().defibrillate();
}
let id = actions.borrow_mut().trigger(kind, &mut params.borrow_mut(), defib);
let Some(id) = id else {
info.set_text("Defibrillation artifact delivered.");
return;
};
let row = gtk::Box::new(Orientation::Horizontal, 8);
let title = gtk::Label::new(Some(kind.label()));
title.set_xalign(0.0);
title.set_hexpand(true);
row.append(&title);
let state = gtk::Label::new(Some("Running · 0%"));
state.set_width_chars(19);
row.append(&state);
let pause = gtk::Button::with_label("Pause");
pause.connect_clicked({
let actions = actions.clone();
move |_| actions.borrow_mut().pause_or_resume(id)
});
row.append(&pause);
let stop = gtk::Button::with_label("Stop");
stop.connect_clicked({
let actions = actions.clone();
move |_| actions.borrow_mut().stop(id)
});
row.append(&stop);
action_rows.prepend(&row);
glib::timeout_add_local(Duration::from_millis(250), {
let actions = actions.clone();
move || {
let Some((status, fraction)) = actions.borrow().status(id) else {
return glib::ControlFlow::Break;
};
state.set_text(&format!("{} · {:.0}%", status.label(), fraction * 100.0));
if status == Status::Running {
pause.set_label("Pause");
} else if status == Status::Paused {
pause.set_label("Resume");
} else {
pause.set_sensitive(false);
stop.set_sensitive(false);
return glib::ControlFlow::Break;
}
glib::ControlFlow::Continue
}
});
}
});
let reset = gtk::Button::with_label("Restore pre-action baseline (stop all events)");
reset.connect_clicked({
let actions = actions.clone();
let params = params.clone();
move |_| actions.borrow_mut().restore_baseline(&mut params.borrow_mut())
});
panel.append(&reset);
scroller.set_child(Some(&panel));
scroller
}