SimPaM/patches/patient-monitor-simulation-v0.5.9-to-v0.6.0.patch

1161 lines
53 KiB
Diff
Raw Permalink Normal View History

--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "patient-monitor-simulation"
-version = "0.5.9"
+version = "0.6.0"
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.9
+# Patient Monitor Simulation (PaMSim) — v0.6.0
Ein mit Rust und GTK4 entwickelter Patient*innenmonitor-Simulator mit zwei Fenstern für die Lehre unter Fedora Linux.
@@ -56,8 +56,50 @@
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.
+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 |
+| --- | --- | --- |
+| 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.
+
+### 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.
## Thoraxkompressionen (v0.5.4)
@@ -447,9 +489,11 @@
der **rechten Monitorspalte** dargestellt. Der bisherige NIBP-Bereich am
unteren Fensterrand entfällt. Im Admin-Fenster lässt sich ein Messintervall
von **1, 3, 5, 10, 20, 30 oder 60 Minuten** auswählen (Standard: 5 Minuten).
-Der erste Messzyklus beginnt beim Simulationsstart. Das Folgeintervall zählt
-jeweils **ab dem Ende der vorangegangenen Messung**. Über **Measure now**
-kann während einer Messpause sofort eine neue Messung gestartet werden.
+Die **Automatik ist beim Simulationsstart deaktiviert**. Der erste Zyklus
+startet erst durch **Measure now** oder beim Aktivieren von **Auto**.
+Das Folgeintervall zählt jeweils **ab dem Ende der vorangegangenen Messung**.
+Über **Measure now** kann auch bei ausgeschalteter Automatik während einer
+Messpause sofort eine Messung gestartet werden.
Ein **horizontaler Fortschrittsbalken** zeigt den Ablauf des Messintervalls,
ein **vertikaler Balken** den simulierten Manschettendruck von 0–200 mmHg.
@@ -558,3 +602,15 @@
Die Ableitung wird weiterhin über das Auswahlmenü gewählt. Änderungen
werden erst mit **Apply** übernommen; **Cancel** verwirft sie.
Keine Änderungen an den simulierten Vitalparametern.
+
+### v0.6.0 – Zusätzliche Touch-Menüs und manueller NIBP-Start
+
+Die SpO₂-, ART-, CO₂- und NIBP-Bereiche erhalten eigene monitorähnliche
+Touch-Menüs. Unabhängige Alarmgrenzen werden über große −/+- und
+ON/OFF-Tasten eingestellt. Parameterbezogene Sensor- und Kurveneinstellungen
+werden mit der Admin-Oberfläche synchronisiert. Im NIBP-Menü lassen sich
+darüber hinaus Messintervall, Auto ON/OFF, Messausfall und Manschettenposition
+wählen sowie Messungen unmittelbar auslösen. Beim Start ist Auto OFF und
+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.
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.5.9
+# Patient Monitor Simulation (PaMSim) — v0.6.0
A Rust/GTK4 patient-monitor simulator with two main windows for teaching on Fedora Linux.
@@ -28,7 +28,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 **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
+fullscreen mode. The same interaction now applies to the other channels.
+Hiding
the ECG channel also disables its touch target.
The menu offers:
@@ -53,8 +54,48 @@
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
-channels.
+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 |
+| --- | --- | --- |
+| 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.
+
+### 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`.
## Chest compressions (v0.5.4)
@@ -290,10 +331,12 @@
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
-the last measurement**, not from its beginning. **Measure now** starts an
-additional cycle if none is in progress. The small **horizontal progress bar**
+of **1, 3, 5, 10, 20, 30, or 60 minutes** (default 5).
+**Auto measurement is disabled at startup**, so no reading is shown and no
+measurement starts until the instructor activates Auto or selects **Measure now**.
+When enabled, the first automatic measurement starts immediately; subsequent
+intervals run **from the end of the last measurement**, not from its beginning.
+**Measure now** starts a cycle even when Auto is OFF, if none is in progress. The small **horizontal progress bar**
shows the fraction of the waiting interval elapsed; a **vertical 0–200 mmHg
gauge** shows the current cuff pressure during measurement.
@@ -577,3 +620,13 @@
**−/+** 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.
+
+### v0.6.0 — Additional touchscreen modules and NIBP manual-first startup
+
+Added touch/click settings panels for SpO₂, ART, CO₂ and the bottom-right
+NIBP cell. Their threshold editors use large, unit-specific +/− and ON/OFF
+controls; the panels expose relevant waveform/sensor options and stay
+synchronized with Admin. NIBP additionally provides interval selection,
+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.
--- a/src/model.rs
+++ b/src/model.rs
@@ -283,6 +283,7 @@
pub nibp_systolic: i32, // mmHg, initial measured NIBP result
pub nibp_diastolic: i32, // mmHg, initial measured NIBP result
pub nibp_interval_minutes: i32, // 1 / 3 / 5 / 10 / 20 / 30 / 60
+ pub nibp_auto_measurement: bool, // OFF at startup; manually enable automatic cycles
pub nibp_no_reading: bool, // force unsuccessful cuff measurement
pub nibp_cuff_on_spo2: bool, // simulated probe on cuff extremity
pub nibp_cuff_on_art: bool, // simulated arterial catheter on cuff extremity
@@ -361,6 +362,7 @@
nibp_systolic: 118,
nibp_diastolic: 74,
nibp_interval_minutes: 5,
+ nibp_auto_measurement: false,
nibp_no_reading: false,
nibp_cuff_on_spo2: false,
nibp_cuff_on_art: false,
--- a/src/nibp.rs
+++ b/src/nibp.rs
@@ -35,6 +35,7 @@
pub struct NibpMachine {
cycle: Option<Cycle>,
ever_started: bool,
+ auto_enabled_on_last_update: bool,
ever_successful: bool,
last_completed: Option<f64>,
last_reading: Option<NibpReading>,
@@ -47,6 +48,7 @@
Self {
cycle: None,
ever_started: false,
+ auto_enabled_on_last_update: false,
ever_successful: false,
last_completed: None,
last_reading: None,
@@ -146,17 +148,22 @@
self.ever_started = true;
}
- /// The initial cycle starts at simulation time zero. Afterwards, the
- /// interval is counted from the last completed measurement, not cycle start.
+ /// Automatic cycles only start if the instructor enabled Auto measurement.
+ /// In-flight manual/automatic cycles complete even after Auto is turned off.
+ /// When Auto is switched on, a cycle begins immediately (if idle);
+ /// later cycles start at the interval after the previous completion.
pub fn update(&mut self, now: f64, p: &Parameters, quality_at_start: Spo2Quality) {
if now < 0.0 { return; }
+ let just_enabled_auto = p.nibp_auto_measurement && !self.auto_enabled_on_last_update;
+ self.auto_enabled_on_last_update = p.nibp_auto_measurement;
if let Some(cycle) = self.cycle {
if now - cycle.start >= cycle.duration {
self.complete(now, p, cycle);
}
- } else if !self.ever_started || self.last_completed.is_some_and(|last| {
- now - last >= f64::from(p.nibp_interval_minutes.max(1)) * 60.0
- }) {
+ } else if p.nibp_auto_measurement &&
+ (just_enabled_auto || !self.ever_started || self.last_completed.is_some_and(|last| {
+ now - last >= f64::from(p.nibp_interval_minutes.max(1)) * 60.0
+ })) {
self.start(now, p, quality_at_start);
}
}
@@ -206,9 +213,58 @@
use super::*;
#[test]
+ fn startup_is_blank_and_auto_is_disabled() {
+ let p = Parameters::default();
+ assert!(!p.nibp_auto_measurement);
+ let mut m = NibpMachine::new();
+ for t in [0.0, 20.0, 3600.0] {
+ m.update(t, &p, Spo2Quality::Good);
+ assert!(!m.measuring());
+ assert_eq!(m.reading(), None);
+ }
+ // The first manual cycle completes even though automatic mode is OFF.
+ m.measure_now(3601.0, &p, Spo2Quality::Good);
+ assert!(m.measuring());
+ m.update(3621.0, &p, Spo2Quality::Good);
+ assert_eq!(m.reading(), Some(NibpReading { systolic: 118, diastolic: 74 }));
+ m.update(4400.0, &p, Spo2Quality::Good);
+ assert!(!m.measuring());
+ // Enabling Auto starts the next cycle if the selected interval elapsed.
+ let auto = Parameters { nibp_auto_measurement: true, ..p };
+ m.update(4400.01, &auto, Spo2Quality::Good);
+ assert!(m.measuring());
+ // Disabling Auto again doesn't cancel this running cycle.
+ m.update(4420.01, &Parameters::default(), Spo2Quality::Good);
+ assert!(!m.measuring());
+ }
+
+ #[test]
+ fn turning_auto_on_after_manual_measurement_starts_new_cycle() {
+ let mut m = NibpMachine::new();
+ let p = Parameters::default();
+ m.measure_now(0.0, &p, Spo2Quality::Good);
+ m.update(20.0, &p, Spo2Quality::Good);
+ assert!(m.reading().is_some());
+ assert!(!m.measuring());
+ // No need to wait five minutes after a manual measurement to enable Auto.
+ let auto = Parameters { nibp_auto_measurement: true, ..p };
+ m.update(21.0, &auto, Spo2Quality::Good);
+ assert!(m.measuring());
+ }
+
+ #[test]
+ fn enabling_auto_starts_first_measurement_without_preexisting_reading() {
+ let mut m = NibpMachine::new();
+ let p = Parameters { nibp_auto_measurement: true, ..Parameters::default() };
+ m.update(10.0, &p, Spo2Quality::Good);
+ assert!(m.measuring());
+ assert_eq!(m.reading(), None);
+ }
+
+ #[test]
fn intervals_and_first_values() {
let mut m = NibpMachine::new();
- let p = Parameters::default();
+ let p = Parameters { nibp_auto_measurement: true, ..Parameters::default() };
m.update(0.0, &p, Spo2Quality::Good);
assert!(m.measuring());
assert_eq!(m.reading(), None);
@@ -233,7 +289,8 @@
#[test]
fn failed_measurement_and_retry_cycle() {
- let p = Parameters { nibp_no_reading: true, ..Parameters::default() };
+ let p = Parameters { nibp_no_reading: true, nibp_auto_measurement: true,
+ ..Parameters::default() };
let mut m = NibpMachine::new();
m.update(0.0, &p, Spo2Quality::Good);
assert!(m.measuring());
@@ -246,7 +303,8 @@
#[test]
fn cuff_interference_never_improves_quality() {
- let p = Parameters { nibp_cuff_on_spo2: true, ..Parameters::default() };
+ let p = Parameters { nibp_cuff_on_spo2: true, nibp_auto_measurement: true,
+ ..Parameters::default() };
let mut m = NibpMachine::new();
m.update(0.0, &p, Spo2Quality::Good);
assert_eq!(m.effective_spo2_quality(2.6, &p), Spo2Quality::None);
@@ -269,7 +327,7 @@
(Spo2Quality::None, 120.0),
] {
let mut machine = NibpMachine::new();
- let p = Parameters::default();
+ let p = Parameters { nibp_auto_measurement: true, ..Parameters::default() };
machine.update(0.0, &p, quality);
machine.update(seconds - 0.01, &p, quality);
assert!(machine.measuring());
@@ -278,14 +336,15 @@
assert_eq!(machine.reading().is_some(), quality != Spo2Quality::None);
}
let mut machine = NibpMachine::new();
- let p = Parameters::default();
+ let p = Parameters { nibp_auto_measurement: true, ..Parameters::default() };
machine.update(0.0, &p, Spo2Quality::Poor);
assert!((60.0..=120.0).contains(&machine.cycle.unwrap().duration));
}
#[test]
fn first_successful_reading_uses_admin_even_after_failed_cycle() {
- let mut p = Parameters { nibp_no_reading: true, ..Parameters::default() };
+ let mut p = Parameters { nibp_no_reading: true, nibp_auto_measurement: true,
+ ..Parameters::default() };
let mut machine = NibpMachine::new();
machine.update(0.0, &p, Spo2Quality::None);
machine.update(120.0, &p, Spo2Quality::None);
@@ -298,7 +357,8 @@
#[test]
fn partial_pressure_uses_diastic_and_systolic_boundaries() {
- let p = Parameters { nibp_cuff_on_art: true, ..Parameters::default() };
+ let p = Parameters { nibp_cuff_on_art: true, nibp_auto_measurement: true,
+ ..Parameters::default() };
let mut machine = NibpMachine::new();
machine.update(0.0, &p, Spo2Quality::Good);
assert_eq!(machine.cuff_zone(2.6, &p), CuffZone::Occluded);
--- a/src/render.rs
+++ b/src/render.rs
@@ -85,18 +85,41 @@
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; }
+/// 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)]
+pub enum TouchChannel { Ecg, Spo2, Art, Capno, Nibp }
+
+pub fn monitor_hit_test(x: f64, y: f64, width: i32, height: i32,
+ p: &Parameters) -> Option<TouchChannel> {
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);
+ if x < pad || x > w - pad || y < header || y >= h - pad {
+ return None;
+ }
+ let channels = visible_channels(p);
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
+ let (row_height, measurements_top) = monitor_rows(header, body_height, channels.len());
+ if y >= measurements_top {
+ let (split_x, _) = monitor_columns(w, pad);
+ return if p.show_nibp && x >= split_x { Some(TouchChannel::Nibp) }
+ else { None };
+ }
+ let index = ((y - header) / row_height) as usize;
+ match channels.get(index).map(|entry| entry.0) {
+ Some(Channel::Ecg) => Some(TouchChannel::Ecg),
+ Some(Channel::Pleth) => Some(TouchChannel::Spo2),
+ Some(Channel::Art) => Some(TouchChannel::Art),
+ Some(Channel::Capno) => Some(TouchChannel::Capno),
+ None => None,
+ }
+}
+
+#[cfg(test)]
+pub fn ecg_hit_test(x: f64, y: f64, width: i32, height: i32, p: &Parameters) -> bool {
+ monitor_hit_test(x, y, width, height, p) == Some(TouchChannel::Ecg)
}
/// Left/right split and the width of each bottom-row group. Outer margins
@@ -177,10 +200,14 @@
let progress_width = (width - 9.0).max(8.0);
stroke_line(cr, x, progress_y, x + progress_width, progress_y, MUTED, 4.0);
stroke_line(cr, x, progress_y,
- x + progress_width * sim.nibp().interval_progress(sim.time(), p.nibp_interval_minutes),
+ x + progress_width * (if p.nibp_auto_measurement {
+ sim.nibp().interval_progress(sim.time(), p.nibp_interval_minutes)
+ } else { 0.0 }),
progress_y, RED, 4.0);
- text(cr, &format!("Every {} min", p.nibp_interval_minutes),
- x, top + height * 0.97, small * 0.85, MUTED, false);
+ let schedule = if p.nibp_auto_measurement {
+ format!("Auto {} min", p.nibp_interval_minutes)
+ } else { "AUTO OFF".to_owned() };
+ text(cr, &schedule, x, top + height * 0.97, small * 0.85, MUTED, false);
// Vertical cuff-pressure gauge (0..200 mmHg), always visible when measuring.
let gauge_x = right - 15.0;
@@ -771,4 +798,18 @@
s.art = 0.0;
assert_eq!(normalized(Channel::Art, &s, &p), 0.0);
}
-}
+ #[test]
+ fn touch_hit_test_tracks_rows_and_nibp_quarter() {
+ let p = Parameters::default();
+ assert_eq!(monitor_hit_test(140.0, 110.0, 1200, 760, &p), Some(TouchChannel::Ecg));
+ assert_eq!(monitor_hit_test(1100.0, 250.0, 1200, 760, &p), Some(TouchChannel::Spo2));
+ assert_eq!(monitor_hit_test(120.0, 400.0, 1200, 760, &p), Some(TouchChannel::Art));
+ assert_eq!(monitor_hit_test(1100.0, 540.0, 1200, 760, &p), Some(TouchChannel::Capno));
+ assert_eq!(monitor_hit_test(1100.0, 700.0, 1200, 760, &p), Some(TouchChannel::Nibp));
+ assert_eq!(monitor_hit_test(800.0, 700.0, 1200, 760, &p), None);
+ let p = Parameters { show_spo2: false, show_nibp: false, ..p };
+ assert_eq!(monitor_hit_test(1100.0, 310.0, 1200, 760, &p), Some(TouchChannel::Art));
+ assert_eq!(monitor_hit_test(1100.0, 700.0, 1200, 760, &p), None);
+ }
+
+}
--- a/src/simulation.rs
+++ b/src/simulation.rs
@@ -1014,6 +1014,7 @@
let p = Parameters {
nibp_cuff_on_spo2: true,
nibp_cuff_on_art: true,
+ nibp_auto_measurement: true,
..Parameters::default()
};
let mut sim = Simulator::new(&p);
--- a/src/ui.rs
+++ b/src/ui.rs
@@ -15,9 +15,11 @@
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>>>>;
+/// 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)>>>>;
+/// At most one modal monitor settings panel is open at once.
+type MonitorMenuHandle = 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.
@@ -31,12 +33,12 @@
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()));
- install_ecg_menu_style();
- let ecg_alarm_changed: EcgAlarmChanged = Rc::new(RefCell::new(None));
+ 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(),
- ecg_alarm_changed.clone());
+ admin_changed.clone());
let admin = create_admin(app, parameters.clone(), simulator.clone(), &monitor,
- audio.clone(), ecg_alarm_changed);
+ 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.
@@ -54,7 +56,7 @@
fn create_monitor(app: &Application, params: SharedParams,
simulator: Rc<RefCell<Simulator>>,
- ecg_alarm_changed: EcgAlarmChanged) -> ApplicationWindow {
+ admin_changed: AdminChanged) -> ApplicationWindow {
let window = ApplicationWindow::builder()
.application(app)
.title(concat!("Patient Monitor — Simulation v", env!("CARGO_PKG_VERSION")))
@@ -105,9 +107,10 @@
});
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));
+ // 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.
+ let monitor_menu: MonitorMenuHandle = Rc::new(RefCell::new(None));
let click = gtk::GestureClick::new();
click.connect_released({
let app = app.clone();
@@ -115,13 +118,16 @@
let canvas = canvas.clone();
let params = params.clone();
move |_gesture, _press_count, x, y| {
- let ecg_touched = {
+ let touched = {
let p = params.borrow();
- render::ecg_hit_test(x, y, canvas.width(), canvas.height(), &p)
+ render::monitor_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());
+ 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(),
+ simulator.clone(), admin_changed.clone(), monitor_menu.clone(), channel),
+ None => (),
}
}
});
@@ -134,7 +140,7 @@
simulator: Rc<RefCell<Simulator>>,
monitor: &ApplicationWindow,
audio: Rc<RefCell<AlarmAudio>>,
- ecg_alarm_changed: EcgAlarmChanged) -> ApplicationWindow {
+ admin_changed: AdminChanged) -> ApplicationWindow {
let window = ApplicationWindow::builder()
.application(app)
.title(concat!("Patient Monitor — Admin v", env!("CARGO_PKG_VERSION")))
@@ -324,7 +330,7 @@
move |button| params.borrow_mut().spo2_sensor_attached = !button.is_active()
});
spo2.append(&sensor);
- let _ = add_dropdown_at(&spo2, "Signal quality", &[
+ let spo2_quality_dropdown = add_dropdown_at(&spo2, "Signal quality", &[
"0 — None (no reading)",
"1 — Poor (*)",
"2 — Adequate (**)",
@@ -399,9 +405,9 @@
ppv_hint.set_xalign(0.0);
ppv_hint.set_wrap(true);
art.append(&ppv_hint);
- add_dropdown(&art, "Arterial waveform", &[
+ let art_shape_dropdown = add_dropdown_at(&art, "Arterial waveform", &[
"Normal", "Damped", "Hyperdynamic",
- ], params.clone(), |p, selected| {
+ ], 0, params.clone(), |p, selected| {
p.arterial_shape = match selected {
1 => ArterialShape::Damped,
2 => ArterialShape::Hyperdynamic,
@@ -425,20 +431,31 @@
params.borrow().alarms.nibp_dia, params.clone(), |p, v| p.alarms.nibp_dia = v,
&preset_dropdown, &updating_preset), |s| s.nibp_dia));
- let _nibp_interval = add_dropdown_at(&nibp, "Measurement interval",
+ 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,
};
});
- for (caption, current, update) in [
+ let nibp_auto = gtk::CheckButton::with_label("Automatic NIBP measurement");
+ nibp_auto.set_active(params.borrow().nibp_auto_measurement);
+ nibp_auto.connect_toggled({
+ let params = params.clone();
+ move |button| params.borrow_mut().nibp_auto_measurement = button.is_active()
+ });
+ nibp.append(&nibp_auto);
+ let mut nibp_extra_toggles: Vec<(gtk::CheckButton, fn(&Parameters) -> bool)> = Vec::new();
+ for (caption, current, update, getter) in [
("No reading (simulate failure)", params.borrow().nibp_no_reading,
- (|p: &mut Parameters, on| p.nibp_no_reading = on) as fn(&mut Parameters, bool)),
+ (|p: &mut Parameters, on| p.nibp_no_reading = on) as fn(&mut Parameters, bool),
+ (|p: &Parameters| p.nibp_no_reading) as fn(&Parameters) -> bool),
("Cuff on SpO₂ extremity", params.borrow().nibp_cuff_on_spo2,
- (|p: &mut Parameters, on| p.nibp_cuff_on_spo2 = on) as fn(&mut Parameters, bool)),
+ (|p: &mut Parameters, on| p.nibp_cuff_on_spo2 = on) as fn(&mut Parameters, bool),
+ (|p: &Parameters| p.nibp_cuff_on_spo2) as fn(&Parameters) -> bool),
("Cuff on ART extremity", params.borrow().nibp_cuff_on_art,
- (|p: &mut Parameters, on| p.nibp_cuff_on_art = on) as fn(&mut Parameters, bool)),
+ (|p: &mut Parameters, on| p.nibp_cuff_on_art = on) as fn(&mut Parameters, bool),
+ (|p: &Parameters| p.nibp_cuff_on_art) as fn(&Parameters) -> bool),
] {
let checkbox = gtk::CheckButton::with_label(caption);
checkbox.set_active(current);
@@ -447,6 +464,7 @@
move |button| update(&mut params.borrow_mut(), button.is_active())
});
nibp.append(&checkbox);
+ nibp_extra_toggles.push((checkbox, getter));
}
let measure_now = gtk::Button::with_label("Measure now");
measure_now.connect_clicked({
@@ -464,8 +482,8 @@
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| {
+ let capno_shape_dropdown = add_dropdown_at(&capno, "Capnogram", &["Normal", "Obstructive / shark fin"],
+ 0, params.clone(), |p, selected| {
p.capno_shape = if selected == 1 { CapnoShape::Obstructive }
else { CapnoShape::Normal };
});
@@ -480,7 +498,9 @@
params.borrow().alarms.rr, params.clone(), |p, v| p.alarms.rr = v,
&preset_dropdown, &updating_preset), |s| s.rr));
+ let admin_alarm_editors = alarm_editors.clone();
preset_dropdown.connect_selected_notify({
+ let alarm_editors = admin_alarm_editors;
let params = params.clone();
let updating_preset = updating_preset.clone();
move |dropdown| {
@@ -497,19 +517,36 @@
}
});
- // 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({
+ // Every monitor menu commits to Parameters and refreshes visible Admin
+ // widgets, without breaking preset editing or reentrant RefCell borrows.
+ let admin_alarm_editors = alarm_editors.clone();
+ *admin_changed.borrow_mut() = Some(Box::new({
+ let params = params.clone();
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);
+ move |alarm_changed: bool| {
+ let snapshot = params.borrow().clone();
+ updating_preset.set(true);
+ for (editor, get_limits) in &admin_alarm_editors {
+ editor.set_limits(get_limits(&snapshot.alarms));
}
- lead_dropdown.set_selected(lead.index());
+ updating_preset.set(false);
+ if alarm_changed { preset_dropdown.set_selected(0); }
+ 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);
+ art_shape_dropdown.set_selected(match snapshot.arterial_shape {
+ ArterialShape::Normal => 0, ArterialShape::Damped => 1,
+ ArterialShape::Hyperdynamic => 2,
+ });
+ capno_shape_dropdown.set_selected(match snapshot.capno_shape {
+ CapnoShape::Normal => 0, CapnoShape::Obstructive => 1,
+ });
+ nibp_interval_dropdown.set_selected(nibp_interval_index(snapshot.nibp_interval_minutes));
+ nibp_auto.set_active(snapshot.nibp_auto_measurement);
+ for (checkbox, getter) in &nibp_extra_toggles {
+ checkbox.set_active(getter(&snapshot));
+ }
}
}));
@@ -682,8 +719,8 @@
/// 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) {
+ 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;
@@ -783,7 +820,7 @@
changed
};
if let Some(callback) = on_change.borrow().as_ref() {
- callback(new_limits, new_lead, alarm_changed);
+ callback(alarm_changed);
}
if let Some(window) = weak.upgrade() { window.close(); }
}
@@ -823,6 +860,436 @@
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);
+ }
+}
+
+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
+/// independently optional and only become active after Apply.
+struct TouchAlarmSpec {
+ name: &'static str,
+ unit: &'static str,
+ limits: AlarmLimits,
+ maximum: i32,
+ step: i32,
+ restore_lower: i32,
+ restore_upper: i32,
+ apply: fn(&mut AlarmSettings, AlarmLimits),
+}
+
+struct TouchAlarmDraft {
+ name: &'static str,
+ lower: Rc<Cell<Option<i32>>>,
+ upper: Rc<Cell<Option<i32>>>,
+ apply: fn(&mut AlarmSettings, AlarmLimits),
+}
+
+fn module_alarm_specs(channel: render::TouchChannel, p: &Parameters) -> Vec<TouchAlarmSpec> {
+ let a = &p.alarms;
+ let mut specs = Vec::new();
+ macro_rules! limits {
+ ($name:expr, $unit:expr, $field:ident, $max:expr, $step:expr, $lo:expr, $hi:expr) => {
+ specs.push(TouchAlarmSpec {
+ name: $name, unit: $unit, limits: a.$field, maximum: $max,
+ step: $step, restore_lower: $lo, restore_upper: $hi,
+ apply: |alarms: &mut AlarmSettings, limits| alarms.$field = limits,
+ });
+ };
+ }
+ match channel {
+ render::TouchChannel::Spo2 => {
+ limits!("SpO₂", "%", spo2, 100, 1, 90, 100);
+ limits!("Pulse rate", "bpm", pr, 240, 5, 50, 120);
+ }
+ render::TouchChannel::Art => {
+ limits!("ART systolic", "mmHg", art_sys, 200, 5, 80, 180);
+ limits!("ART MAP", "mmHg", art_map, 200, 5, 60, 100);
+ limits!("ART diastolic", "mmHg", art_dia, 200, 5, 40, 100);
+ limits!("PPV", "%", ppv, 60, 1, 0, 10);
+ }
+ render::TouchChannel::Capno => {
+ limits!("EtCO₂", "mmHg", etco2, 100, 1, 30, 50);
+ limits!("Respiratory rate", "/min", rr, 60, 1, 10, 20);
+ }
+ render::TouchChannel::Nibp => {
+ limits!("NIBP systolic", "mmHg", nibp_sys, 260, 5, 80, 180);
+ 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.
+#[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>>> {
+ 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 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
+}
+
+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.
+#[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) {
+ if let Some(existing) = open_menu.borrow().as_ref().and_then(|weak| weak.upgrade()) {
+ existing.present();
+ return;
+ }
+ let current = params.borrow().clone();
+ let title = match channel {
+ render::TouchChannel::Spo2 => "SpO₂ / SETTINGS",
+ render::TouchChannel::Art => "ART / SETTINGS",
+ render::TouchChannel::Capno => "CO₂ / SETTINGS",
+ render::TouchChannel::Nibp => "NIBP / SETTINGS",
+ render::TouchChannel::Ecg => return,
+ };
+ let dialog = gtk::Window::builder()
+ .application(app)
+ .title(title)
+ .transient_for(monitor)
+ .modal(true)
+ .resizable(true)
+ .default_width(560)
+ .default_height(if channel == render::TouchChannel::Art { 720 } else { 610 })
+ .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, 0);
+ 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 scroller = gtk::ScrolledWindow::new();
+ scroller.set_vexpand(true);
+ scroller.set_policy(gtk::PolicyType::Never, gtk::PolicyType::Automatic);
+ 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);
+ scroller.set_child(Some(&inner));
+ content.append(&scroller);
+
+ let heading = gtk::Label::new(Some(title));
+ heading.set_xalign(0.0);
+ heading.add_css_class("title-2");
+ inner.append(&heading);
+ inner.append(&ecg_menu_divider());
+
+ // 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());
+ }
+
+ // 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");
+ 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 |_| {
+ // Validate the complete draft first. Apply only this module's
+ // fields so Admin edits in another module aren't overwritten.
+ let mut selected_limits = Vec::with_capacity(alarm_drafts.len());
+ for field in &alarm_drafts {
+ let limits = AlarmLimits {
+ lower: field.lower.get(), upper: field.upper.get(),
+ };
+ if !limits.valid() {
+ error.set_text(&format!(
+ "{}: lower limit must not exceed upper limit.", field.name));
+ return;
+ }
+ selected_limits.push((field.apply, limits));
+ }
+ 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 => (),
+ }
+ }
+ if let Some(callback) = on_change.borrow().as_ref() {
+ callback(changed_alarms);
+ }
+ 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 module_touch_menu_tests {
+ use super::*;
+
+ #[test]
+ fn all_non_ecg_modules_have_complete_alarm_specs() {
+ let p = Parameters::default();
+ for (channel, expected) in [
+ (render::TouchChannel::Spo2, 2),
+ (render::TouchChannel::Art, 4),
+ (render::TouchChannel::Capno, 2),
+ (render::TouchChannel::Nibp, 3),
+ ] {
+ let specs = module_alarm_specs(channel, &p);
+ assert_eq!(specs.len(), expected);
+ assert!(specs.iter().all(|spec| spec.maximum > 0 && spec.step > 0));
+ }
+ }
+
+ #[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);
+ }
}
}