diff --git a/Cargo.toml b/Cargo.toml index 77b0b47..fa0ab8d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "patient-monitor-simulation" -version = "0.5.7" +version = "0.5.8" edition = "2021" license = "MIT" description = "Synthetic patient-monitor simulation for teaching (not for clinical use)" diff --git a/README.de.md b/README.de.md index 0fdf2d0..7e03cee 100644 --- a/README.de.md +++ b/README.de.md @@ -1,4 +1,4 @@ -# Patient Monitor Simulation (PaMSim) — v0.5.7 +# Patient Monitor Simulation (PaMSim) — v0.5.8 Ein mit Rust und GTK4 entwickelter Patient*innenmonitor-Simulator mit zwei Fenstern für die Lehre unter Fedora Linux. @@ -26,6 +26,33 @@ vierten Feldes; die gesamte untere Wertezeile bleibt bestehen. Beim Ausblenden anderer Parameter werden die verbleibenden Kurvenzeilen wie bisher dynamisch verteilt. +## EKG-Bedienung direkt am Monitor (v0.5.8) + +Durch Berühren oder Anklicken der **EKG-Zeile** öffnet sich ein eigenes +Einstellfenster mit **grüner Schrift auf schwarzem Hintergrund**. Die gesamte +EKG-Zeile ist aktiv, sowohl die Kurve links (75 %) als auch das numerische +Herzfrequenzfeld rechts (25 %). Die Bedienung ist auch im Vollbildmodus möglich. +Bei ausgeblendetem EKG ist die Interaktionsfläche deaktiviert. + +Im Einstellfenster stehen folgende Optionen zur Verfügung: + +- **ECG lead:** I, II (Voreinstellung), III, aVR, aVL, aVF und V1–V6. Nach + **Apply** ändert sich die Ableitungsbezeichnung im Monitor sowie die + schematische Polarität/Amplitude der Kurve. Es handelt sich **nicht** um + eine klinisch validierte 12-Kanal-EKG-Ableitung. Frequenz, QRS-Zeitpunkte + und mechanische Pulskopplung bleiben unverändert. +- **HR alarm limits:** unabhängig einstellbare untere (↓) und obere (↑) + Herzfrequenzgrenze in /min. Ein leeres Eingabefeld (**OFF**) deaktiviert + die jeweilige Grenze. Zulässig sind 0–240; die untere Grenze darf die obere + nicht überschreiten. +- **Apply** übernimmt beide Alarmgrenzen und die Ableitung gemeinsam; + **Cancel** oder **Esc** verwirft die noch nicht übernommenen Eingaben. + +Die Einstellungen werden mit der Admin-Oberfläche synchronisiert. Eine am +Monitor geänderte Alarmgrenze schaltet die Alarmvoreinstellung auf **Custom**. +Auch in der Admin-Oberfläche ist die EKG-Ableitung auswählbar. Andere +Monitorparameter besitzen vorerst noch keine berührungsempfindlichen Menüs. + ## Thoraxkompressionen (v0.5.4) Im Admin-Bereich **Chest compressions** startet die grüne Schaltfläche @@ -506,3 +533,12 @@ untersten Zeile stehen vier gleich breite Bereiche: CO/CI, SVRI/GEDI/ELWI, ein vollständig leerer Platzhalter und NIBP. Die ersten beiden Bereiche zeigen derzeit nur ihre Bezeichnungen. Wird NIBP ausgeblendet, bleibt die untere Zeile bestehen. Das Simulationsverhalten ist unverändert. + +### v0.5.8 – EKG-Bedienung am Monitor + +Mit einem Fingertipp oder Mausklick auf die EKG-Kurve oder das numerische +HF-Feld öffnet sich ein monitorähnliches Einstellfenster. Darin können +EKG-Ableitung und untere/obere HF-Alarmgrenze verändert werden. Eingaben +werden geprüft und mit dem Admin-Fenster synchronisiert. Die geänderte +Kurvenpolarität ist eine schematische Darstellung ohne diagnostischen +Anspruch; die zugrunde liegende Rhythmus- und Pulssimulation bleibt gleich. diff --git a/README.md b/README.md index fe6cac3..05cd987 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ -# Patient Monitor Simulation (PaMSim) — v0.5.7 +# Patient Monitor Simulation (PaMSim) — v0.5.8 -A two-window, Rust/GTK4 patient-monitor simulator for teaching on Fedora Linux. +A Rust/GTK4 patient-monitor simulator with two main windows for teaching on Fedora Linux. > **Synthetic training signals only — not for clinical use.** ECG, arterial pressure, > plethysmography and capnography are schematic mathematical approximations. The @@ -23,6 +23,32 @@ The NIBP visibility toggle hides **only the fourth group's content**; the bottom measurement row and other three groups remain present. Disabling one of the four waveform channels still reflows the remaining rows above it. +## ECG touchscreen settings (v0.5.8) + +Tap or click **anywhere in the ECG row**, on either the **trace (left 75%)** or +**heart-rate readout (right 25%)**, to open a modal green-on-black ECG settings +window above the monitor. The same interaction works when the monitor is in +fullscreen mode. Touch/click input outside the ECG row opens no menu. Hiding +the ECG channel also disables its touch target. + +The menu offers: + +- **ECG lead:** I, II (default), III, aVR, aVL, aVF, and V1–V6. The monitor + trace label changes immediately after **Apply**, and the waveform undergoes + an *illustrative lead-dependent gain/polarity transformation*. This is **not** + a diagnostic 12-lead ECG derivation; cardiac timing, HR and mechanical + capture do not change when the lead changes. +- **HR alarm limits:** optional **↓ Lower** and **↑ Upper**, in bpm. Leave + either box empty (OFF) to disable that alarm boundary. A limit must be in + the range 0–240 and the lower limit must not exceed the upper limit. +- **Apply** commits lead and limits together; **Cancel** or **Esc** discards + unsaved changes. Both Admin and monitor displays reflect committed changes. + Changing limits in the monitor marks the Admin alarm preset as **Custom**. + +The Admin ECG section also includes an ECG-lead selector, synchronized with +changes made from the monitor. No settings menu is yet provided for other +channels. + ## Chest compressions (v0.5.4) The **Chest compressions** Admin group provides a large **Start Chest Compressions** @@ -527,3 +553,11 @@ row has four equally sized measurement groups: CO/CI; SVRI/GEDI/ELWI; reserved empty; and the unchanged NIBP readout. Only headings are rendered in the first two groups; the third has no content. NIBP can be hidden without removing the final row. No physiological simulation behavior was modified. + +### v0.5.8 — ECG touchscreen controls + +Added a monitor-styled ECG settings window, opened by touching either the ECG +waveform or numeric HR cell. Edits HR lower/upper alarms and displayed lead +(I, II, III, aVR, aVL, aVF, V1–V6), with input validation and Admin sync. +Lead changes are schematic display projections only; arrhythmia and pulse +simulation remain unchanged. diff --git a/src/model.rs b/src/model.rs index 009b231..8f0e7d4 100644 --- a/src/model.rs +++ b/src/model.rs @@ -33,6 +33,48 @@ impl EcgRhythm { } } +/// Displayed single-channel ECG lead. Synthetic morphology is lead-II-like; +/// projection below provides illustrative polarity/gain, not a 12-lead model. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum EcgLead { + I, II, III, AVR, AVL, AVF, V1, V2, V3, V4, V5, V6, +} + +impl EcgLead { + pub const LABELS: &'static [&'static str] = &[ + "I", "II", "III", "aVR", "aVL", "aVF", "V1", "V2", "V3", "V4", "V5", "V6", + ]; + + pub fn from_index(index: u32) -> Self { + match index { + 0 => Self::I, 2 => Self::III, 3 => Self::AVR, 4 => Self::AVL, + 5 => Self::AVF, 6 => Self::V1, 7 => Self::V2, 8 => Self::V3, + 9 => Self::V4, 10 => Self::V5, 11 => Self::V6, _ => Self::II, + } + } + + pub fn index(self) -> u32 { + match self { + Self::I => 0, Self::II => 1, Self::III => 2, Self::AVR => 3, + Self::AVL => 4, Self::AVF => 5, Self::V1 => 6, Self::V2 => 7, + Self::V3 => 8, Self::V4 => 9, Self::V5 => 10, Self::V6 => 11, + } + } + + pub fn label(self) -> &'static str { Self::LABELS[self.index() as usize] } + + /// Illustrative polarity and voltage gain relative to lead II. This changes + /// only the trace, never ECG event timing or mechanical capture. + pub fn display_gain(self) -> f64 { + match self { + Self::I => 0.82, Self::II => 1.0, Self::III => 0.67, + Self::AVR => -0.85, Self::AVL => 0.52, Self::AVF => 0.75, + Self::V1 => -0.75, Self::V2 => -0.38, Self::V3 => 0.52, + Self::V4 => 1.08, Self::V5 => 1.0, Self::V6 => 0.83, + } + } +} + /// Pulse-oximeter availability and technical alarms. Sensor loss takes precedence. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Spo2Status { @@ -228,6 +270,7 @@ pub struct Parameters { pub chest_compressions_active: bool, pub chest_compression_quality: ChestCompressionQuality, pub ecg_rhythm: EcgRhythm, + pub ecg_lead: EcgLead, // ECG trace label and illustrative lead projection pub heart_rate: i32, // bpm, organized electrical rate; not mechanical pulse rate pub pulse_conduction: PulseConduction, pub spo2: i32, // %; instructor-set nominal saturation @@ -305,6 +348,7 @@ impl Default for Parameters { chest_compressions_active: false, chest_compression_quality: ChestCompressionQuality::Adequate, ecg_rhythm: EcgRhythm::Sinus, + ecg_lead: EcgLead::II, heart_rate: 75, pulse_conduction: PulseConduction::OneToOne, spo2: 98, @@ -351,6 +395,21 @@ mod tests { assert_eq!(ChestCompressionQuality::Bad.peak_range(), None); } + #[test] + fn ecg_lead_defaults_to_ii_and_selection_is_bijective() { + let p = Parameters::default(); + assert_eq!(p.ecg_lead, EcgLead::II); + assert_eq!(p.ecg_lead.label(), "II"); + for index in 0..EcgLead::LABELS.len() as u32 { + let lead = EcgLead::from_index(index); + assert_eq!(lead.index(), index); + assert_eq!(lead.label(), EcgLead::LABELS[index as usize]); + } + assert_eq!(EcgLead::from_index(999), EcgLead::II); + assert!(EcgLead::AVR.display_gain() < 0.0); + assert_eq!(EcgLead::II.display_gain(), 1.0); + } + #[test] fn mean_pressure_uses_one_third_pulse_pressure() { assert_eq!(mean_arterial_pressure(120, 75), 90); diff --git a/src/render.rs b/src/render.rs index cb62a42..efb8cf2 100644 --- a/src/render.rs +++ b/src/render.rs @@ -67,7 +67,10 @@ pub fn draw(cr: &Context, width: i32, height: i32, p: &Parameters, sim: &Simulat let top = header + index as f64 * row_height; let bottom = top + row_height; stroke_line(cr, pad, bottom, w - pad, bottom, MUTED, 0.65); - text(cr, title, trace_left + 4.0, top + row_height * 0.17, + let displayed_title = if matches!(channel, Channel::Ecg) { + format!("{} / ECG", p.ecg_lead.label()) + } else { title.to_owned() }; + text(cr, &displayed_title, trace_left + 4.0, top + row_height * 0.17, (row_height * 0.11).clamp(10.0, 17.0), color, false); draw_trace(cr, channel, color, trace_left, trace_right, top + row_height * 0.25, bottom - row_height * 0.06, p, sim); @@ -82,6 +85,20 @@ pub fn draw(cr: &Context, width: i32, height: i32, p: &Parameters, sim: &Simulat numeric_width, p, sim); } +/// Same geometry as the Cairo renderer: the full first ECG row (waveform +/// and numeric region) is one target for touch, pen, or mouse interaction. +/// Hidden ECG is never interactive; other rows and the header are excluded. +pub fn ecg_hit_test(x: f64, y: f64, width: i32, height: i32, p: &Parameters) -> bool { + if !p.show_ecg { return false; } + let w = f64::from(width.max(1)); + let h = f64::from(height.max(1)); + let pad = (w.min(h) * 0.018).clamp(6.0, 20.0); + let header = (h * 0.083).clamp(32.0, 68.0); + let body_height = (h - header - pad).max(20.0); + let (row_height, _) = monitor_rows(header, body_height, visible_channels(p).len()); + x >= pad && x <= w - pad && y >= header && y < header + row_height +} + /// Left/right split and the width of each bottom-row group. Outer margins /// are excluded, so 75% / 25% holds at all window sizes (no width clamping). fn monitor_columns(window_width: f64, pad: f64) -> (f64, f64) { @@ -497,7 +514,7 @@ fn draw_trace(cr: &Context, channel: Channel, color: Color, fn normalized(channel: Channel, s: &Sample, p: &Parameters) -> f64 { match channel { - Channel::Ecg => (0.40 + s.ecg * 0.38).clamp(0.02, 0.98), + Channel::Ecg => (0.40 + s.ecg * p.ecg_lead.display_gain() * 0.38).clamp(0.02, 0.98), Channel::Pleth => (0.10 + pleth_visual_amplitude(s.pleth, s.time, s.pleth_quality) * 0.78) .clamp(0.02, 0.98), Channel::Art => (s.art / 200.0).clamp(0.0, 1.0), @@ -636,6 +653,36 @@ mod tests { assert_eq!(p.alarms.spo2, AlarmLimits::default()); } + #[test] + fn ecg_touch_target_covers_curve_and_hr_and_reflows() { + let mut p = Parameters::default(); + assert!(!ecg_hit_test(100.0, 20.0, 1200, 760, &p)); // header + assert!(ecg_hit_test(140.0, 110.0, 1200, 760, &p)); // curve + assert!(ecg_hit_test(1080.0, 110.0, 1200, 760, &p)); // HR numbers + assert!(!ecg_hit_test(140.0, 300.0, 1200, 760, &p)); // next channel + assert!(!ecg_hit_test(1.0, 110.0, 1200, 760, &p)); // outside padding + p.show_spo2 = false; + p.show_art = false; + p.show_capno = false; + assert!(ecg_hit_test(900.0, 300.0, 1200, 760, &p)); + p.show_ecg = false; + assert!(!ecg_hit_test(900.0, 110.0, 1200, 760, &p)); + } + + #[test] + fn displayed_ecg_lead_changes_polarity_without_touching_sample() { + let mut p = Parameters::default(); + let s = Sample { time: 0.0, ecg: 1.0, pleth: 0.0, + pleth_valid: true, pleth_quality: Spo2Quality::Good, + art: 0.0, co2: 0.0 }; + let lead_ii = normalized(Channel::Ecg, &s, &p); + p.ecg_lead = crate::model::EcgLead::AVR; + let lead_avr = normalized(Channel::Ecg, &s, &p); + assert!(lead_ii > 0.40); + assert!(lead_avr < 0.40); + assert_eq!(s.ecg, 1.0); + } + #[test] fn toggled_channels_disappear_and_remaining_rows_reflow() { let mut p = Parameters::default(); diff --git a/src/ui.rs b/src/ui.rs index ffb8579..724bc80 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -10,11 +10,14 @@ use gtk::{Application, ApplicationWindow, Orientation}; use crate::alarm::{self, AlarmAudio}; use crate::model::{AlarmLimits, AlarmSettings, ArterialShape, CapnoShape, - ChestCompressionQuality, EcgRhythm, Parameters, PulseConduction, Spo2Quality}; + ChestCompressionQuality, EcgLead, EcgRhythm, Parameters, PulseConduction, Spo2Quality}; use crate::render; use crate::simulation::Simulator; type SharedParams = Rc>; +/// Refresh the Admin alarm widgets when a limit is changed on the monitor. +type EcgAlarmChanged = Rc>>>; +type EcgMenuHandle = Rc>>>; // 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(¶meters.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>) -> ApplicationWindow { + simulator: Rc>, + 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>, monitor: &ApplicationWindow, - audio: Rc>) -> ApplicationWindow { + audio: Rc>, + 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(>k::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(>k::Label::new(Some("↓ Lower"))); + limits_row.append(&lower); + limits_row.append(>k::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: >k::Box, title: &str, accent: Option) -> gtk::Box { @@ -619,6 +828,7 @@ fn normalize_entry(entry: >k::Entry, slider: >k::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,