v0.5.8 — ECG touchscreen controls

This commit is contained in:
GABRIEL Sebastian 2026-11-12 16:10:57 +01:00
commit 14ee042a0a
10 changed files with 1027 additions and 41 deletions

View file

@ -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);

View file

@ -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();

View file

@ -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,