Initial commit

This commit is contained in:
GABRIEL Sebastian 2026-11-12 09:36:13 +01:00
commit 788c68a1d8
10 changed files with 2020 additions and 0 deletions

2
patient-monitor-simulation/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
/target
*.swp

656
patient-monitor-simulation/Cargo.lock generated Normal file
View file

@ -0,0 +1,656 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "cairo-rs"
version = "0.22.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df683f1d30b457964673a5541a4603208ef95ab6873d2a55871895cf310f3b56"
dependencies = [
"bitflags",
"cairo-sys-rs",
"glib",
"libc",
]
[[package]]
name = "cairo-sys-rs"
version = "0.22.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee548131103ad8f698c6725669647b9c757b3b66992dd6a026037596417bee21"
dependencies = [
"glib-sys",
"libc",
"system-deps",
]
[[package]]
name = "cfg-expr"
version = "0.20.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ba9e9ec16c447027685b1f897b720e18e9a8afd00bd7332c483537e38086c9f"
dependencies = [
"smallvec",
"target-lexicon",
]
[[package]]
name = "equivalent"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
[[package]]
name = "field-offset"
version = "0.3.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f"
dependencies = [
"memoffset",
"rustc_version",
]
[[package]]
name = "futures-channel"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"
dependencies = [
"futures-core",
]
[[package]]
name = "futures-core"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
[[package]]
name = "futures-executor"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432"
dependencies = [
"futures-core",
"futures-task",
"futures-util",
]
[[package]]
name = "futures-io"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"
[[package]]
name = "futures-macro"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "futures-task"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
[[package]]
name = "futures-util"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
dependencies = [
"futures-core",
"futures-macro",
"futures-task",
"pin-project-lite",
"slab",
]
[[package]]
name = "gdk-pixbuf"
version = "0.22.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "25f420376dbee041b2db374ce4573892a36222bb3f6c0c43e24f0d67eae9b646"
dependencies = [
"gdk-pixbuf-sys",
"gio",
"glib",
"libc",
]
[[package]]
name = "gdk-pixbuf-sys"
version = "0.22.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d5209294ba3775f9b650bf78bfadeba4332089f2329b3e2f6ce0a4957a45bff"
dependencies = [
"gio-sys",
"glib-sys",
"gobject-sys",
"libc",
"system-deps",
]
[[package]]
name = "gdk4"
version = "0.11.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e77c579bac9eff8b84c0625d5f533da6d69988c063062fe92c2e955ede8f28eb"
dependencies = [
"cairo-rs",
"gdk-pixbuf",
"gdk4-sys",
"gio",
"glib",
"libc",
"pango",
]
[[package]]
name = "gdk4-sys"
version = "0.11.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3eff6238a30c1f198fb3c8d3d445fa7faf211d11d9075af0772e6e0ca32ae001"
dependencies = [
"cairo-sys-rs",
"gdk-pixbuf-sys",
"gio-sys",
"glib-sys",
"gobject-sys",
"libc",
"pango-sys",
"pkg-config",
"system-deps",
]
[[package]]
name = "gio"
version = "0.22.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4620fbafdf19dba814473e19f18e75290cb3338662f6ae35f0402affd3b2b699"
dependencies = [
"futures-channel",
"futures-core",
"futures-io",
"futures-util",
"gio-sys",
"glib",
"libc",
"pin-project-lite",
"smallvec",
]
[[package]]
name = "gio-sys"
version = "0.22.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c28739f914c15b87a9856000bed9cbd5b3a8afbca5e982d9a299e1601422cb5"
dependencies = [
"glib-sys",
"gobject-sys",
"libc",
"system-deps",
"windows-sys",
]
[[package]]
name = "glib"
version = "0.22.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4cf9e5bd8713f1990a92c422998826e0fb34824277b46bc59757373483c6694"
dependencies = [
"bitflags",
"futures-channel",
"futures-core",
"futures-executor",
"futures-task",
"futures-util",
"gio-sys",
"glib-macros",
"glib-sys",
"gobject-sys",
"libc",
"memchr",
"smallvec",
]
[[package]]
name = "glib-macros"
version = "0.22.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c9597c68fa7bdf4154a3079642cd21c4dccac0b0bdd2897d82861523bf91e7b9"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "glib-sys"
version = "0.22.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "99b38907e67e40dec9b60f858bcada952598719cb512a13eb13d6cdcd16f8295"
dependencies = [
"libc",
"system-deps",
]
[[package]]
name = "gobject-sys"
version = "0.22.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07595c9ba696bd9819cb6a8df39f08078f3dd679508fe052dd558492c2053834"
dependencies = [
"glib-sys",
"libc",
"system-deps",
]
[[package]]
name = "graphene-rs"
version = "0.22.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb856b9c558971c3f13ab692358926da710b046932a4e087aedcc35b040d7dff"
dependencies = [
"glib",
"graphene-sys",
]
[[package]]
name = "graphene-sys"
version = "0.22.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "97842c7543828f98aa5583aa54fcda28aa84fa2b0f8c556142177f7bbb638057"
dependencies = [
"glib-sys",
"libc",
"system-deps",
]
[[package]]
name = "gsk4"
version = "0.11.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eee23d7425c5281ec5a2f40f7b69384aac66c15861d990d248e9d9c9368be464"
dependencies = [
"cairo-rs",
"gdk4",
"glib",
"graphene-rs",
"gsk4-sys",
"libc",
"pango",
]
[[package]]
name = "gsk4-sys"
version = "0.11.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27900c92e47df410bbe43b51818104051e3409da43fb88547a41c0bafddfd39c"
dependencies = [
"cairo-sys-rs",
"gdk4-sys",
"glib-sys",
"gobject-sys",
"graphene-sys",
"libc",
"pango-sys",
"system-deps",
]
[[package]]
name = "gtk4"
version = "0.11.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0f8226c94dd0b65ba2e8fcd8ff402d380e890f6e5a6488e652a0158e827b9bf"
dependencies = [
"cairo-rs",
"field-offset",
"futures-channel",
"gdk-pixbuf",
"gdk4",
"gio",
"glib",
"graphene-rs",
"gsk4",
"gtk4-macros",
"gtk4-sys",
"libc",
"pango",
]
[[package]]
name = "gtk4-macros"
version = "0.11.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb906c98f0b4cc9002594e337e83f40492aa6dca22c97242f13be5b046c5f338"
dependencies = [
"proc-macro-crate",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "gtk4-sys"
version = "0.11.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd14af0137f269bdecee73404157d2a852f9651af7d68bd1023d3b8b914a14c3"
dependencies = [
"cairo-sys-rs",
"gdk-pixbuf-sys",
"gdk4-sys",
"gio-sys",
"glib-sys",
"gobject-sys",
"graphene-sys",
"gsk4-sys",
"libc",
"pango-sys",
"system-deps",
]
[[package]]
name = "hashbrown"
version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "indexmap"
version = "2.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "memoffset"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
dependencies = [
"autocfg",
]
[[package]]
name = "pango"
version = "0.22.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b2022dbbd82e1c42bd950a6f1df9b98c796e725dce5ec275e03cbf9772e4efa"
dependencies = [
"gio",
"glib",
"pango-sys",
]
[[package]]
name = "pango-sys"
version = "0.22.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca02d64761b74d56cdd4b437db6d73dc95e6c0d40f27e1c707952c0f09052948"
dependencies = [
"glib-sys",
"gobject-sys",
"libc",
"system-deps",
]
[[package]]
name = "patient-monitor-simulation"
version = "0.3.0"
dependencies = [
"gtk4",
]
[[package]]
name = "pin-project-lite"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "pkg-config"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
[[package]]
name = "proc-macro-crate"
version = "3.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
dependencies = [
"toml_edit",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rustc_version"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
dependencies = [
"semver",
]
[[package]]
name = "semver"
version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_spanned"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782"
dependencies = [
"serde_core",
]
[[package]]
name = "slab"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
[[package]]
name = "smallvec"
version = "1.16.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46"
[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "system-deps"
version = "9.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db551ad38aac61d5e0343e0eeeb0163be3115c4e23b6a025959570ee0c03c67d"
dependencies = [
"cfg-expr",
"heck",
"pkg-config",
"toml",
"version-compare",
]
[[package]]
name = "target-lexicon"
version = "0.13.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
[[package]]
name = "toml"
version = "1.2.1+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7"
dependencies = [
"indexmap",
"serde_core",
"serde_spanned",
"toml_datetime",
"toml_parser",
"toml_writer",
"winnow",
]
[[package]]
name = "toml_datetime"
version = "1.1.3+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49"
dependencies = [
"serde_core",
]
[[package]]
name = "toml_edit"
version = "0.25.19+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218"
dependencies = [
"indexmap",
"toml_datetime",
"toml_parser",
"winnow",
]
[[package]]
name = "toml_parser"
version = "1.1.5+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
dependencies = [
"winnow",
]
[[package]]
name = "toml_writer"
version = "1.2.0+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "version-compare"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e"
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "winnow"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"
dependencies = [
"memchr",
]

View file

@ -0,0 +1,9 @@
[package]
name = "patient-monitor-simulation"
version = "0.3.0"
edition = "2021"
license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"
[dependencies]
gtk = { package = "gtk4", version = "0.11" }

View file

@ -0,0 +1,141 @@
# Patient Monitor Simulation (PaMSim) — v0.3.0
A two-window, Rust/GTK4 patient-monitor simulator for teaching on Fedora Linux.
> **Synthetic training signals only — not for clinical use.** ECG, arterial pressure,
> plethysmography and capnography are schematic mathematical approximations. The
> simulation has no clinical validation and is not a medical device.
## Build and run on Fedora
```bash
sudo dnf install rust cargo gcc pkgconf-pkg-config gtk4-devel
cargo test
cargo run --release
```
Run these commands from the extracted `patient-monitor-simulation` folder.
Window titles show the application version. GTK4 requires a functional graphical
session (e.g., Fedora KDE/Wayland).
## Windows
**Admin:** Controls ECG rhythm and rate; mechanical capture; SpO₂; invasive
arterial pressure, waveform shape and pulse-pressure variation; NIBP; and
capnography. Numeric inputs have bidirectionally linked sliders and text fields.
Each of the five monitor parameters (ECG, SpO₂/pleth, ART, CO₂, NIBP) has its
own **Show on monitor** checkbox.
**Monitor:** Black background; ECG green, pleth yellow, ART red and capnogram
light grey. Waveforms and vital signs disappear together when their respective
visibility checkbox is cleared. Remaining waveform rows expand to use the space.
Hiding a display channel does **not** stop signal generation or physiological
coupling: for example, hiding ECG does not stop ART or pleth pulses. NIBP can
be hidden independently; this also removes its footer.
The monitor can be resized and toggled fullscreen with **F11**; **Esc** exits
fullscreen. On Wayland, move the monitor to the presentation screen before
activating fullscreen. Fullscreen does not lock down the computer.
## ECG and mechanical coupling
- ECG rhythms: sinus, atrial fibrillation, monomorphic ventricular tachycardia,
ventricular fibrillation and asystole.
- Mechanical capture: **1:1**, **2:1**, **3:1**, **None (PEA)**, or deterministic
pseudo-random capture (~65%). PR is derived from conducted QRS events, never
controlled by a pulse-rate slider.
- A captured QRS leads to an ART upstroke after a schematic **120 ms**, and a
peripheral pleth pulse after **300 ms**. Pleth is strongly damped/filtered.
- VF, asystole and PEA suppress mechanical pulses; old samples scroll out of
view. NIBP is a static, separately entered cuff reading.
## Invasive arterial pressure and PPV (new in v0.3)
The arterial waveform has a fixed **0–200 mmHg** display axis, with tick marks
at **0, 50, 100, 150 and 200 mmHg**. Nominal ART systolic and diastolic inputs
are limited to 0–200 mmHg.
**Pulse pressure variation (PPV)** is adjustable from **0% to 60%**, in 1%
increments, via synchronized slider and text field (Admin → Invasive arterial
blood pressure). Its default is **0%** (no respiratory modulation). The
respiratory cycle comes from the same respiratory-rate parameter as the
capnogram. **RR = 0** disables the respiratory modulation (apnea).
The synthetic PPV definition is:
```text
PPV (%) = 100 × (PPmax − PPmin) / ((PPmax + PPmin) / 2)
```
The model applies a sinusoidal variation to **pulse pressure**, sampled for
each mechanically conducted beat. The diastolic baseline remains nominally
fixed, so this is primarily a **beat-to-beat systolic swing**, not an arbitrary
vertical translation of the entire arterial trace. It does not affect ECG,
mechanical capture or pleth amplitude. This is a visual teaching model, not a
validated predictor of fluid responsiveness.
**Example:** ART 120/75 mmHg has nominal pulse pressure 45 mmHg. At PPV 20%,
the ideal pulse-pressure extrema are 40.5 and 49.5 mmHg, corresponding to
systolic peaks of approximately 115.5 and 124.5 mmHg (assuming the diastolic
baseline stays at 75 mmHg). The rendered waveform shape and finite number of
beats per respiratory cycle mean the visible maxima may not reach the ideal
extrema exactly.
The ART sidebar displays the **nominal** systolic/diastolic pressures and MAP,
plus the **configured** PPV percentage when PPV is greater than 0. It does not
measure PPV from sampled arterial data. At very high nominal systolic pressure,
the highest modulated pulses can exceed the 200 mmHg scale; the displayed
curve is then **clipped** at the top, without rescaling the axis.
## Display options (new in v0.3)
The five **Show on monitor** checkboxes affect the presentation only:
| Checkbox | Hidden monitor content |
| --- | --- |
| ECG | ECG waveform, HR and rhythm label |
| Pulse oximetry | Pleth waveform, SpO₂ and PR |
| Invasive arterial blood pressure | ART waveform, pressure values, MAP and PPV label |
| Capnography | CO₂ waveform, EtCO₂ and RR |
| NIBP | Static cuff pressure values and NIBP footer |
Remaining visible waveforms keep their relative order and receive an equal
share of the available area; zero waveform channels is supported.
## Signal implementation
- 100 Hz synthetic signal samples, 10 s retained history, 8 s scrolling trace.
- Cairo draws into the GTK4 `DrawingArea` and scales with the window.
- A conducted QRS records its own respiratory PPV multiplier at event time.
The arterial pulse thus retains the same amplitude throughout the beat.
- Varying PPV does not alter the peripheral pleth pulse or the number of
mechanical pulses.
- Clinical accuracy, dynamic NIBP measurements, alarms, artifacts, calibration,
precise waveform timing, and patient physiology are outside this prototype.
## Project layout
```text
src/
main.rs GTK application entry point
model.rs Parameters, rhythm/capture settings, display flags
simulation.rs QRS-timed mechanical signals, PPV and respiratory synthesis
render.rs Cairo monitor layout, dynamic visibility, fixed ART axis
ui.rs Admin controls and monitor window
```
## Changes since v0.2.2
1. Respiratory PPV with a 0–60% instructor setting, coupled to the simulated
respiratory cycle and applied **per arterial beat**.
2. Five independent display visibility toggles, dynamic waveform row layout,
and independent NIBP-footer hiding.
3. ART axis reduced from **0–250** to **0–200 mmHg**, with inputs adjusted to
the new range.
4. Added regression tests for PPV arithmetic and its effects on ART, for
hiding ECG while retaining mechanical pulses, for active channel selection,
and for arterial-axis normalization.
**Verification:** The archive is generated from these sources. Run `cargo test`
locally to verify the Rust/GTK build; Rust and GTK4 development components
were not available in the environment where this ZIP was prepared.

View file

@ -0,0 +1,14 @@
mod model;
mod render;
mod simulation;
mod ui;
use gtk::prelude::*;
fn main() -> gtk::glib::ExitCode {
let application = gtk::Application::builder()
.application_id("org.example.PatientMonitorSimulation")
.build();
application.connect_activate(ui::create_windows);
application.run()
}

View file

@ -0,0 +1,131 @@
//! Shared configuration of the synthetic monitor signals.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EcgRhythm {
Sinus,
AtrialFibrillation,
VentricularTachycardia,
VentricularFibrillation,
Asystole,
}
impl EcgRhythm {
/// VF and asystole have no organized QRS to trigger a mechanical pulse.
pub fn has_qrs(self) -> bool {
!matches!(self, Self::VentricularFibrillation | Self::Asystole)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PulseConduction {
OneToOne,
TwoToOne,
ThreeToOne,
None,
Random,
}
impl PulseConduction {
pub fn conducts(self, beat: u64) -> bool {
match self {
Self::OneToOne => true,
// One mechanical pulse for every two QRS complexes.
Self::TwoToOne => (beat - 1) % 2 == 0,
Self::ThreeToOne => (beat - 1) % 3 == 0,
Self::None => false,
Self::Random => {
// Deterministic pseudo-random 65% mechanical capture for reproducible lessons.
let mut x = beat.wrapping_mul(0x9E37_79B9_7F4A_7C15);
x ^= x >> 30;
x = x.wrapping_mul(0xBF58_476D_1CE4_E5B9);
x ^= x >> 27;
(x % 100) < 65
}
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ArterialShape {
Normal,
Damped,
Hyperdynamic,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CapnoShape {
Normal,
Obstructive,
}
#[derive(Clone, Copy, Debug)]
pub struct Parameters {
pub ecg_rhythm: EcgRhythm,
pub heart_rate: i32, // bpm, organized electrical rate; not mechanical pulse rate
pub pulse_conduction: PulseConduction,
pub spo2: i32, // %
pub art_systolic: i32, // mmHg, nominal pressure; display axis 0..200
pub art_diastolic: i32, // mmHg
pub arterial_shape: ArterialShape,
pub pulse_pressure_variation: i32, // PPV %, 0 disables respiratory variation
pub nibp_systolic: i32, // mmHg, historical/static simulated cuff value
pub nibp_diastolic: i32, // mmHg
pub etco2: i32, // mmHg
pub respiratory_rate: i32, // breaths/min
pub capno_shape: CapnoShape,
// These affect display only; the underlying physiological signals continue.
pub show_ecg: bool,
pub show_spo2: bool,
pub show_art: bool,
pub show_capno: bool,
pub show_nibp: bool,
}
impl Default for Parameters {
fn default() -> Self {
Self {
ecg_rhythm: EcgRhythm::Sinus,
heart_rate: 75,
pulse_conduction: PulseConduction::OneToOne,
spo2: 98,
art_systolic: 120,
art_diastolic: 75,
arterial_shape: ArterialShape::Normal,
pulse_pressure_variation: 0,
nibp_systolic: 118,
nibp_diastolic: 74,
etco2: 38,
respiratory_rate: 14,
capno_shape: CapnoShape::Normal,
show_ecg: true,
show_spo2: true,
show_art: true,
show_capno: true,
show_nibp: true,
}
}
}
pub fn mean_arterial_pressure(systolic: i32, diastolic: i32) -> i32 {
((systolic as f64 + 2.0 * diastolic as f64) / 3.0).round() as i32
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mean_pressure_uses_one_third_pulse_pressure() {
assert_eq!(mean_arterial_pressure(120, 75), 90);
}
#[test]
fn grouped_mechanical_capture_follows_requested_patterns() {
assert_eq!((1..=8).filter(|&b| PulseConduction::TwoToOne.conducts(b)).collect::<Vec<_>>(),
vec![1, 3, 5, 7]);
assert_eq!((1..=9).filter(|&b| PulseConduction::ThreeToOne.conducts(b)).collect::<Vec<_>>(),
vec![1, 4, 7]);
assert!((1..=20).all(|b| PulseConduction::OneToOne.conducts(b)));
assert!((1..=20).all(|b| !PulseConduction::None.conducts(b)));
}
}

View file

@ -0,0 +1,255 @@
//! Size-independent Cairo drawing of the synthetic bedside monitor.
use gtk::cairo::{Context, FontSlant, FontWeight, LineCap, LineJoin};
use crate::model::{mean_arterial_pressure, EcgRhythm, Parameters, PulseConduction};
use crate::simulation::{Sample, Simulator};
type Color = (f64, f64, f64);
const BG: Color = (0.0, 0.0, 0.0);
const GREEN: Color = (0.26, 1.0, 0.39);
const YELLOW: Color = (1.0, 0.85, 0.17);
const RED: Color = (1.0, 0.30, 0.31);
const LIGHT_GREY: Color = (0.80, 0.84, 0.87);
const MUTED: Color = (0.42, 0.46, 0.49);
const GRID: Color = (0.10, 0.14, 0.13);
#[derive(Clone, Copy)]
enum Channel { Ecg, Pleth, Art, Capno }
fn visible_channels(p: &Parameters) -> Vec<(Channel, &'static str, Color)> {
let mut channels = Vec::with_capacity(4);
if p.show_ecg { channels.push((Channel::Ecg, "II / ECG", GREEN)); }
if p.show_spo2 { channels.push((Channel::Pleth, "SpO₂ / PLETH", YELLOW)); }
if p.show_art { channels.push((Channel::Art, "ART", RED)); }
if p.show_capno { channels.push((Channel::Capno, "CO₂", LIGHT_GREY)); }
channels
}
pub fn draw(cr: &Context, width: i32, height: i32, p: &Parameters, sim: &Simulator) {
let w = f64::from(width.max(1));
let h = f64::from(height.max(1));
set_color(cr, BG);
let _ = cr.paint();
let pad = (w.min(h) * 0.018).clamp(6.0, 20.0);
let header = (h * 0.083).clamp(32.0, 68.0);
let footer = if p.show_nibp { (h * 0.13).clamp(52.0, 102.0) } else { 0.0 };
let channels = visible_channels(p);
let row_height = ((h - header - footer - pad).max(20.0))
/ (channels.len().max(1) as f64);
let sidebar = (w * 0.235).clamp(125.0, 370.0).min(w * 0.44);
let split_x = w - sidebar - pad;
let trace_left = pad + 6.0;
let trace_right = (split_x - pad).max(trace_left + 40.0);
let text_scale = (w.min(h * 1.7) / 850.0).clamp(0.65, 1.5);
text(cr, "PATIENT MONITOR", pad + 5.0, header * 0.58, 18.0 * text_scale,
LIGHT_GREY, true);
if w >= 850.0 {
text(cr, "SIMULATION", split_x - 128.0 * text_scale, header * 0.58,
11.0 * text_scale, MUTED, false);
}
stroke_line(cr, pad, header, w - pad, header, MUTED, 0.8);
stroke_line(cr, split_x, header, split_x, h - footer, MUTED, 0.9);
for (index, (channel, title, color)) in channels.iter().copied().enumerate() {
let top = header + index as f64 * row_height;
let bottom = top + row_height;
stroke_line(cr, pad, bottom, w - pad, bottom, MUTED, 0.65);
text(cr, title, trace_left + 4.0, top + row_height * 0.17,
(row_height * 0.11).clamp(10.0, 17.0), color, false);
draw_trace(cr, channel, color, trace_left, trace_right,
top + row_height * 0.25, bottom - row_height * 0.06, p, sim);
draw_vitals(cr, channel, color, split_x + pad,
top, row_height, sidebar - 2.0 * pad, p, sim);
}
if p.show_nibp {
let footer_top = h - footer;
text(cr, "NIBP", pad + 6.0, footer_top + footer * 0.32,
(footer * 0.21).clamp(12.0, 20.0), LIGHT_GREY, false);
text(cr, &format!("{} / {}", p.nibp_systolic, p.nibp_diastolic),
pad + 6.0, footer_top + footer * 0.77,
(footer * 0.42).clamp(20.0, 44.0), LIGHT_GREY, true);
if w >= 510.0 {
text(cr, &format!("({}) mmHg", mean_arterial_pressure(p.nibp_systolic, p.nibp_diastolic)),
pad + (w * 0.28).min(260.0), footer_top + footer * 0.73,
(footer * 0.24).clamp(12.0, 23.0), LIGHT_GREY, false);
}
if w >= 1020.0 {
text(cr, "SYNTHETIC SIGNALS · NOT FOR CLINICAL USE",
w * 0.56, footer_top + footer * 0.68,
10.0 * text_scale, MUTED, false);
}
}
}
fn draw_vitals(cr: &Context, ch: Channel, color: Color, x: f64,
top: f64, row_h: f64, width: f64, p: &Parameters, sim: &Simulator) {
let label_size = (row_h * 0.135).clamp(11.0, 19.0);
let number_size = (row_h * 0.375).min(width * 0.26).clamp(16.0, 59.0);
let sub_size = (row_h * 0.16).clamp(11.0, 22.0);
let has_capture = p.ecg_rhythm.has_qrs()
&& p.heart_rate > 0
&& p.pulse_conduction != PulseConduction::None;
let pulse_rate = if has_capture { sim.pulse_rate() } else { None };
let (label, value, info) = match ch {
Channel::Ecg => (
"HR",
if !p.ecg_rhythm.has_qrs() || p.heart_rate <= 0 { "--".to_owned() }
else { p.heart_rate.to_string() },
format!("bpm · {}", match p.ecg_rhythm {
EcgRhythm::Sinus => "Sinus",
EcgRhythm::AtrialFibrillation => "AF",
EcgRhythm::VentricularTachycardia => "VT",
EcgRhythm::VentricularFibrillation => "VF",
EcgRhythm::Asystole => "Asystole",
}),
),
Channel::Pleth => (
"SpO₂",
if pulse_rate.is_some() { p.spo2.to_string() } else { "--".to_owned() },
format!("% PR {} bpm", pulse_rate.map_or("--".to_owned(), |pr| pr.to_string())),
),
Channel::Art => (
"ART",
if pulse_rate.is_some() {
format!("{}/{}", p.art_systolic, p.art_diastolic)
} else { "--/--".to_owned() },
if pulse_rate.is_some() {
if p.pulse_pressure_variation > 0 {
format!("MAP {} · PPV {}%",
mean_arterial_pressure(p.art_systolic, p.art_diastolic),
p.pulse_pressure_variation)
} else {
format!("MAP {} mmHg", mean_arterial_pressure(p.art_systolic, p.art_diastolic))
}
} else { "MAP -- mmHg".to_owned() },
),
Channel::Capno => ("EtCO₂", p.etco2.to_string(),
format!("mmHg RR {} /min", p.respiratory_rate)),
};
text(cr, label, x, top + row_h * 0.24, label_size, color, false);
// Reduce wide BP values so they fit within the sidebar.
let value_size = if matches!(ch, Channel::Art) { number_size * 0.78 } else { number_size };
text(cr, &value, x, top + row_h * 0.64, value_size, color, true);
text(cr, &info, x, top + row_h * 0.87, sub_size * 0.85, color, false);
}
#[allow(clippy::too_many_arguments)]
fn draw_trace(cr: &Context, channel: Channel, color: Color,
left: f64, right: f64, top: f64, bottom: f64,
p: &Parameters, sim: &Simulator) {
// ART is shown on an absolute fixed-pressure axis (0..200 mmHg),
// unlike the automatically normalized ECG, pleth and CO2 traces.
let axis_width = if matches!(channel, Channel::Art) { 36.0 } else { 0.0 };
let plot_left = left + axis_width;
let trace_width = (right - plot_left).max(1.0);
let trace_height = (bottom - top).max(1.0);
const VISIBLE_SECONDS: f64 = 8.0;
let last_t = sim.samples().back().map(|s| s.time).unwrap_or(0.0);
let start_t = last_t - VISIBLE_SECONDS;
let _ = cr.save();
cr.rectangle(left, top, right - left, trace_height);
cr.clip();
// A subtle grid, one vertical division per second.
for second in (start_t.ceil() as i64)..=(last_t.floor() as i64) {
let x = right - (last_t - second as f64) / VISIBLE_SECONDS * trace_width;
stroke_line(cr, x, top, x, bottom, GRID, 0.75);
}
if matches!(channel, Channel::Art) {
for pressure in (0..=200).step_by(50) {
let y = bottom - pressure as f64 / 200.0 * trace_height;
stroke_line(cr, plot_left, y, right, y, GRID, 0.8);
// Right-align tick labels against the axis.
let label = pressure.to_string();
let label_offset = if pressure >= 100 { 23.0 } else if pressure >= 10 { 17.0 } else { 10.0 };
text(cr, &label, plot_left - label_offset, (y + 3.0).max(top + 9.0).min(bottom),
9.5, MUTED, false);
}
stroke_line(cr, plot_left, top, plot_left, bottom, MUTED, 0.75);
} else {
stroke_line(cr, left, top + trace_height * 0.5,
right, top + trace_height * 0.5, GRID, 0.7);
}
set_color(cr, color);
cr.set_line_width((trace_height * 0.016).clamp(1.2, 2.4));
cr.set_line_cap(LineCap::Round);
cr.set_line_join(LineJoin::Round);
let mut started = false;
for s in sim.samples().iter().filter(|s| s.time >= start_t) {
let x = right - (last_t - s.time) / VISIBLE_SECONDS * trace_width;
let amplitude = normalized(channel, s, p);
let y = bottom - amplitude * trace_height;
if started { cr.line_to(x, y); }
else { cr.move_to(x, y); started = true; }
}
if started { let _ = cr.stroke(); }
let _ = cr.restore();
}
fn normalized(channel: Channel, s: &Sample, p: &Parameters) -> f64 {
match channel {
Channel::Ecg => (0.40 + s.ecg * 0.38).clamp(0.02, 0.98),
Channel::Pleth => (0.10 + s.pleth * 0.78).clamp(0.02, 0.98),
Channel::Art => (s.art / 200.0).clamp(0.0, 1.0),
Channel::Capno => (0.08 + (s.co2 / f64::from(p.etco2.max(1))) * 0.80)
.clamp(0.02, 0.98),
}
}
fn set_color(cr: &Context, c: Color) {
cr.set_source_rgb(c.0, c.1, c.2);
}
fn stroke_line(cr: &Context, x1: f64, y1: f64, x2: f64, y2: f64,
color: Color, width: f64) {
set_color(cr, color);
cr.set_line_width(width);
cr.move_to(x1, y1);
cr.line_to(x2, y2);
let _ = cr.stroke();
}
fn text(cr: &Context, value: &str, x: f64, baseline: f64,
size: f64, color: Color, bold: bool) {
set_color(cr, color);
cr.select_font_face("Sans", FontSlant::Normal,
if bold { FontWeight::Bold } else { FontWeight::Normal });
cr.set_font_size(size);
cr.move_to(x, baseline);
let _ = cr.show_text(value);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn toggled_channels_disappear_and_remaining_rows_reflow() {
let mut p = Parameters::default();
assert_eq!(visible_channels(&p).len(), 4);
p.show_ecg = false;
p.show_art = false;
assert_eq!(visible_channels(&p).len(), 2);
assert!(matches!(visible_channels(&p)[0].0, Channel::Pleth));
assert!(matches!(visible_channels(&p)[1].0, Channel::Capno));
p.show_spo2 = false;
p.show_capno = false;
assert!(visible_channels(&p).is_empty());
}
#[test]
fn arterial_axis_is_absolute_and_fixed_to_200_mmhg() {
let p = Parameters::default();
let mut s = Sample { time: 0.0, ecg: 0.0, pleth: 0.0, art: 100.0, co2: 0.0 };
assert_eq!(normalized(Channel::Art, &s, &p), 0.5);
s.art = 200.0;
assert_eq!(normalized(Channel::Art, &s, &p), 1.0);
s.art = 0.0;
assert_eq!(normalized(Channel::Art, &s, &p), 0.0);
}
}

View file

@ -0,0 +1,479 @@
//! Event-driven synthetic QRS, mechanical pulse and respiratory generation.
//! A conducted QRS schedules an arterial pulse and a delayed, smoothed pleth pulse.
use std::collections::VecDeque;
use crate::model::{ArterialShape, CapnoShape, EcgRhythm, Parameters, PulseConduction};
const SAMPLE_STEP: f64 = 0.01; // 100 Hz
const HISTORY_SECONDS: f64 = 10.0;
const ART_DELAY: f64 = 0.12; // QRS -> arterial upstroke, seconds (schematic)
const PLETH_DELAY: f64 = 0.30; // QRS -> peripheral pleth onset, seconds
const PLETH_FILTER_TAU: f64 = 0.16; // seconds: deliberately strong damping
const QRS_PHASE: f64 = 0.335;
/// One mechanically conducted QRS. Respiratory modulation is sampled on the
/// beat, so pressure varies from beat to beat rather than within a single beat.
#[derive(Clone, Copy, Debug)]
struct ConductedBeat {
qrs_time: f64,
pulse_pressure_scale: f64,
}
/// PPV = 100 * (PPmax - PPmin) / ((PPmax + PPmin) / 2).
/// For a requested PPV of 20%, pulse pressure oscillates between 90% and 110%
/// of its nominal value over one respiratory cycle.
fn ppv_multiplier(ppv_percent: i32, respiratory_phase: f64) -> f64 {
1.0 + (ppv_percent.clamp(0, 60) as f64 / 200.0)
* (std::f64::consts::TAU * respiratory_phase).sin()
}
#[derive(Clone, Copy, Debug)]
pub struct Sample {
pub time: f64,
pub ecg: f64, // arbitrary amplitude
pub pleth: f64, // attenuated, low-pass-filtered amplitude 0..1
pub art: f64, // absolute pressure in mmHg; display clips above 200
pub co2: f64, // mmHg
}
pub struct Simulator {
samples: VecDeque<Sample>,
time: f64,
ecg_phase: f64,
respiratory_phase: f64,
ecg_beat_number: u64,
conducted_qrs: VecDeque<ConductedBeat>, // captured QRS with respiratory beat amplitude
rate_qrs: VecDeque<f64>, // captured beats for measured PR; reset after rate changes
filtered_pleth: f64,
previous_rhythm: EcgRhythm,
previous_conduction: PulseConduction,
previous_heart_rate: i32,
pending_time: f64,
}
impl Simulator {
pub fn new(params: &Parameters) -> Self {
let mut sim = Self {
samples: VecDeque::with_capacity(1_100),
time: -8.0,
ecg_phase: 0.0,
respiratory_phase: 0.0,
ecg_beat_number: 0,
conducted_qrs: VecDeque::new(),
rate_qrs: VecDeque::new(),
filtered_pleth: 0.0,
previous_rhythm: params.ecg_rhythm,
previous_conduction: params.pulse_conduction,
previous_heart_rate: params.heart_rate,
pending_time: 0.0,
};
// Prepopulate the trace and pulse history, including the initial pulse rate.
for _ in 0..800 {
sim.step(params);
}
sim
}
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);
while self.pending_time >= SAMPLE_STEP {
self.step(params);
self.pending_time -= SAMPLE_STEP;
}
}
pub fn samples(&self) -> &VecDeque<Sample> {
&self.samples
}
/// Average of recent *mechanically captured* beat intervals, not an independent setting.
pub fn pulse_rate(&self) -> Option<i32> {
if self.rate_qrs.len() < 2 {
return None;
}
let end = self.rate_qrs.len() - 1;
// Use the last three intervals, so PR settles rapidly after a rate change.
let start = end.saturating_sub(3);
let first = self.rate_qrs[start];
let last = self.rate_qrs[end];
// Suppress stale pulse values after a prolonged period without capture.
if self.time - last > 12.0 || last <= first {
return None;
}
Some((((end - start) as f64 * 60.0) / (last - first)).round() as i32)
}
fn step(&mut self, params: &Parameters) {
self.time += SAMPLE_STEP;
if params.ecg_rhythm != self.previous_rhythm
|| params.pulse_conduction != self.previous_conduction
|| !params.ecg_rhythm.has_qrs()
|| params.pulse_conduction == PulseConduction::None
|| params.heart_rate <= 0
{
// A rhythm/capture change terminates previously queued mechanical events.
self.conducted_qrs.clear();
self.rate_qrs.clear();
self.filtered_pleth = 0.0;
self.previous_rhythm = params.ecg_rhythm;
self.previous_conduction = params.pulse_conduction;
}
if params.heart_rate != self.previous_heart_rate {
// Old captured events remain in the *waveforms* until they pass.
// They must not bias the pulse rate after an HR slider change.
self.rate_qrs.clear();
self.previous_heart_rate = params.heart_rate;
}
// Respiratory phase drives both the capnogram and arterial PPV.
let respiratory_rate = params.respiratory_rate.max(0) as f64 / 60.0;
self.respiratory_phase = (self.respiratory_phase + SAMPLE_STEP * respiratory_rate).fract();
if params.ecg_rhythm.has_qrs() && params.heart_rate > 0 {
let irregularity = if params.ecg_rhythm == EcgRhythm::AtrialFibrillation {
// Reproducible irregular R-R durations.
let x = (self.ecg_beat_number.wrapping_mul(1_103_515_245)
.wrapping_add(12_345) % 997) as f64 / 997.0;
0.65 + x * 0.70
} else {
1.0
};
let increment = SAMPLE_STEP * params.heart_rate as f64 / 60.0 / irregularity;
let next_phase = self.ecg_phase + increment;
if self.ecg_phase < QRS_PHASE && next_phase >= QRS_PHASE {
// Interpolate within the 10ms sample so mechanical onsets stay aligned.
let qrs_time = self.time - SAMPLE_STEP * (next_phase - QRS_PHASE) / increment;
self.ecg_beat_number += 1;
if params.pulse_conduction.conducts(self.ecg_beat_number) {
let pulse_pressure_scale = if params.respiratory_rate > 0 {
ppv_multiplier(params.pulse_pressure_variation, self.respiratory_phase)
} else {
1.0 // no respiratory swing during apnea
};
self.conducted_qrs.push_back(ConductedBeat { qrs_time, pulse_pressure_scale });
self.rate_qrs.push_back(qrs_time);
}
}
self.ecg_phase = next_phase.fract();
} else {
self.ecg_phase = 0.0;
}
// Preserve up to 30s of delivered events for stable derived PR calculations.
while self.conducted_qrs.front().is_some_and(|beat| beat.qrs_time < self.time - 30.0) {
self.conducted_qrs.pop_front();
}
while self.rate_qrs.front().is_some_and(|&qrs| qrs < self.time - 30.0) {
self.rate_qrs.pop_front();
}
let ecg = ecg_amplitude(self.ecg_phase, self.time, params.ecg_rhythm, params.heart_rate);
let (art, pleth_target) = self.mechanical_signals(params);
let smoothing = 1.0 - (-SAMPLE_STEP / PLETH_FILTER_TAU).exp();
self.filtered_pleth += smoothing * (pleth_target - self.filtered_pleth);
let pleth = self.filtered_pleth.clamp(0.0, 1.0);
let co2 = params.etco2.max(0) as f64
* if params.respiratory_rate <= 0 { 0.0 } else {
capno_amplitude(self.respiratory_phase, params.capno_shape)
};
self.samples.push_back(Sample { time: self.time, ecg, pleth, art, co2 });
while self.samples.front().is_some_and(|first| first.time < self.time - HISTORY_SECONDS) {
self.samples.pop_front();
}
}
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 pulse_pressure = (systolic - diastolic).max(0.0);
let mut latest_art_age: Option<f64> = None;
let mut art_peak: f64 = 0.0;
let mut pleth_peak: f64 = 0.0;
for beat in &self.conducted_qrs {
let art_age = self.time - beat.qrs_time - ART_DELAY;
if art_age >= 0.0 {
latest_art_age = Some(art_age);
art_peak = art_peak.max(
arterial_amplitude(art_age, params.arterial_shape)
* beat.pulse_pressure_scale,
);
}
let pleth_age = self.time - beat.qrs_time - PLETH_DELAY;
if pleth_age >= 0.0 {
pleth_peak = pleth_peak.max(pleth_amplitude(pleth_age));
}
}
let art = if let Some(age) = latest_art_age {
// Pressure decays after an unperfused interval instead of showing a
// non-existent 75 mmHg baseline during prolonged missed captures.
let baseline = diastolic * (-(age - 0.60).max(0.0) / 1.40).exp();
(baseline + pulse_pressure * art_peak).clamp(0.0, 250.0)
} else {
0.0
};
(art, pleth_peak)
}
}
fn gaussian(x: f64, center: f64, width: f64) -> f64 {
let d = (x - center) / width;
(-0.5 * d * d).exp()
}
fn phase_gaussian(phase: f64, center: f64, width: f64) -> f64 {
let distance = (phase - center + 0.5).rem_euclid(1.0) - 0.5;
gaussian(distance, 0.0, width)
}
fn ecg_amplitude(phase: f64, time: f64, rhythm: EcgRhythm, heart_rate: i32) -> f64 {
if rhythm == EcgRhythm::VentricularFibrillation {
// Non-periodic-looking composite oscillation with no organized QRS.
return 0.29 * (time * 42.1 + 0.40 * (time * 3.1).sin()).sin()
+ 0.22 * (time * 57.2 + 0.57 * (time * 5.7).sin()).sin()
+ 0.14 * (time * 31.4).sin();
}
if heart_rate <= 0 || rhythm == EcgRhythm::Asystole {
return 0.006 * (time * 9.3).sin();
}
match rhythm {
EcgRhythm::Sinus => {
0.16 * phase_gaussian(phase, 0.16, 0.030)
- 0.19 * phase_gaussian(phase, 0.300, 0.011)
+ 1.26 * phase_gaussian(phase, QRS_PHASE, 0.008)
- 0.32 * phase_gaussian(phase, 0.363, 0.014)
+ 0.32 * phase_gaussian(phase, 0.61, 0.070)
}
EcgRhythm::AtrialFibrillation => {
0.023 * (time * 39.0).sin()
+ 0.014 * (time * 57.0).sin()
- 0.19 * phase_gaussian(phase, 0.300, 0.011)
+ 1.26 * phase_gaussian(phase, QRS_PHASE, 0.008)
- 0.32 * phase_gaussian(phase, 0.363, 0.014)
+ 0.28 * phase_gaussian(phase, 0.61, 0.072)
}
EcgRhythm::VentricularTachycardia => {
1.06 * phase_gaussian(phase, 0.31, 0.086)
- 0.49 * phase_gaussian(phase, 0.46, 0.067)
- 0.16 * phase_gaussian(phase, 0.72, 0.10)
}
EcgRhythm::VentricularFibrillation | EcgRhythm::Asystole => unreachable!(),
}
}
fn arterial_amplitude(age: f64, shape: ArterialShape) -> f64 {
if age < 0.0 { return 0.0; }
let value = match shape {
ArterialShape::Normal => {
let envelope = if age < 0.13 { (age / 0.13).powf(1.8) }
else { (-(age - 0.13) / 0.25).exp() };
envelope - 0.12 * gaussian(age, 0.35, 0.023)
+ 0.055 * gaussian(age, 0.43, 0.045)
}
ArterialShape::Damped => {
let envelope = if age < 0.22 { (age / 0.22).powf(1.3) }
else { (-(age - 0.22) / 0.39).exp() };
envelope * 0.82
}
ArterialShape::Hyperdynamic => {
let envelope = if age < 0.085 { (age / 0.085).powf(1.9) }
else { (-(age - 0.085) / 0.18).exp() };
envelope - 0.16 * gaussian(age, 0.27, 0.022)
+ 0.095 * gaussian(age, 0.36, 0.034)
}
};
value.clamp(0.0, 1.0)
}
fn pleth_amplitude(age: f64) -> f64 {
if age < 0.0 { return 0.0; }
// Heavily attenuated, broad pulse, without a prominent dicrotic notch.
0.75 * (1.0 - (-age / 0.13).exp()) * (-age / 0.48).exp()
}
fn capno_amplitude(phase: f64, shape: CapnoShape) -> f64 {
match shape {
CapnoShape::Normal => {
if phase < 0.30 { 0.0 }
else if phase < 0.38 { (phase - 0.30) / 0.08 * 0.92 }
else if phase < 0.76 { 0.92 + 0.08 * ((phase - 0.38) / 0.38) }
else if phase < 0.82 { 1.0 - (phase - 0.76) / 0.06 }
else { 0.0 }
}
CapnoShape::Obstructive => {
if phase < 0.28 { 0.0 }
else if phase < 0.76 { ((phase - 0.28) / 0.48).powf(0.68) }
else if phase < 0.83 { 1.0 - (phase - 0.76) / 0.07 }
else { 0.0 }
}
}.clamp(0.0, 1.0)
}
#[cfg(test)]
mod tests {
use super::*;
fn blank(p: &Parameters) -> Simulator {
let mut sim = Simulator::new(p);
sim.samples.clear();
sim.conducted_qrs.clear();
sim.rate_qrs.clear();
sim.time = 0.0;
sim.ecg_phase = 0.0;
sim.ecg_beat_number = 0;
sim.filtered_pleth = 0.0;
sim
}
#[test]
fn signals_remain_in_expected_ranges() {
let p = Parameters::default();
let mut sim = Simulator::new(&p);
sim.advance(0.1, &p);
assert!(sim.samples().len() >= 800);
for s in sim.samples() {
assert!((0.0..=1.0).contains(&s.pleth));
assert!((0.0..=250.0).contains(&s.art));
assert!((0.0..=f64::from(p.etco2)).contains(&s.co2));
assert!(s.ecg.is_finite());
}
}
#[test]
fn qrs_triggers_delayed_art_and_later_pleth() {
let p = Parameters::default();
let mut sim = blank(&p);
while sim.conducted_qrs.is_empty() { sim.step(&p); }
let qrs = sim.conducted_qrs.back().unwrap().qrs_time;
let art_before = sim.samples.back().unwrap().art;
assert_eq!(art_before, 0.0);
while sim.time < qrs + ART_DELAY + 0.13 { sim.step(&p); }
assert!(sim.samples.back().unwrap().art > p.art_diastolic as f64);
assert_eq!(sim.samples.back().unwrap().pleth, 0.0);
while sim.time < qrs + PLETH_DELAY + 0.20 { sim.step(&p); }
assert!(sim.samples.back().unwrap().pleth > 0.03);
}
#[test]
fn asystole_and_vf_and_pea_produce_no_mechanical_pulses() {
for (rhythm, capture) in [
(EcgRhythm::Asystole, PulseConduction::OneToOne),
(EcgRhythm::VentricularFibrillation, PulseConduction::OneToOne),
(EcgRhythm::Sinus, PulseConduction::None),
] {
let p = Parameters { ecg_rhythm: rhythm, pulse_conduction: capture, ..Parameters::default() };
let mut sim = Simulator::new(&p);
for _ in 0..250 { sim.step(&p); }
assert!(sim.pulse_rate().is_none());
assert!(sim.samples.iter().all(|s| s.art == 0.0 && s.pleth == 0.0));
}
}
#[test]
fn switching_to_pea_cancels_existing_pulses_immediately() {
let mut p = Parameters::default();
let mut sim = Simulator::new(&p);
assert!(sim.pulse_rate().is_some());
p.pulse_conduction = PulseConduction::None;
sim.step(&p);
assert!(sim.pulse_rate().is_none());
assert_eq!(sim.samples.back().unwrap().art, 0.0);
assert_eq!(sim.samples.back().unwrap().pleth, 0.0);
}
#[test]
fn pulse_rate_follows_two_to_one_capture() {
let p = Parameters { pulse_conduction: PulseConduction::TwoToOne, ..Parameters::default() };
let mut sim = blank(&p);
for _ in 0..1_400 { sim.step(&p); }
// 75 QRS/min, with every second QRS producing a pulse = 37.5/min.
assert_eq!(sim.pulse_rate(), Some(38));
}
#[test]
fn pulse_rate_follows_three_to_one_capture() {
let p = Parameters { pulse_conduction: PulseConduction::ThreeToOne, ..Parameters::default() };
let mut sim = blank(&p);
for _ in 0..1_400 { sim.step(&p); }
assert_eq!(sim.pulse_rate(), Some(25));
}
#[test]
fn pulse_rate_updates_when_heart_rate_slider_changes() {
let mut p = Parameters::default();
let mut sim = Simulator::new(&p);
assert_eq!(sim.pulse_rate(), Some(75));
p.heart_rate = 189;
sim.step(&p);
// No old 75 bpm PR is displayed while the new beat interval is measured.
assert_eq!(sim.pulse_rate(), None);
for _ in 0..200 { sim.step(&p); }
assert_eq!(sim.pulse_rate(), Some(189));
}
#[test]
fn new_rate_respects_two_to_one_mechanical_capture() {
let mut p = Parameters::default();
let mut sim = Simulator::new(&p);
p.heart_rate = 180;
p.pulse_conduction = PulseConduction::TwoToOne;
for _ in 0..400 { sim.step(&p); }
assert_eq!(sim.pulse_rate(), Some(90));
}
#[test]
fn asystole_is_flat_and_vf_has_waveform_without_qrs() {
assert!(ecg_amplitude(0.335, 2.0, EcgRhythm::Asystole, 75).abs() < 0.01);
assert!(ecg_amplitude(0.335, 2.0, EcgRhythm::VentricularFibrillation, 75).abs() > 0.01);
}
#[test]
fn ppv_produces_requested_peak_to_trough_pulse_pressure_change() {
let max_scale = ppv_multiplier(20, 0.25);
let min_scale = ppv_multiplier(20, 0.75);
assert!((max_scale - 1.10).abs() < 1e-12);
assert!((min_scale - 0.90).abs() < 1e-12);
let calculated_ppv = 100.0 * (max_scale - min_scale) / ((max_scale + min_scale) / 2.0);
assert!((calculated_ppv - 20.0).abs() < 1e-10);
assert_eq!(ppv_multiplier(0, 0.25), 1.0);
}
#[test]
fn respiratory_phase_modulates_arterial_pulses_not_pleth() {
let p = Parameters::default();
let mut sim = blank(&p);
sim.time = ART_DELAY + 0.13;
sim.conducted_qrs.push_back(ConductedBeat {
qrs_time: 0.0, pulse_pressure_scale: 1.2,
});
let (art_high, pleth_high) = sim.mechanical_signals(&p);
sim.conducted_qrs.front_mut().unwrap().pulse_pressure_scale = 0.8;
let (art_low, pleth_low) = sim.mechanical_signals(&p);
assert!(art_high > art_low);
assert_eq!(pleth_high, pleth_low);
assert!(art_low > f64::from(p.art_diastolic));
}
#[test]
fn apnea_suppresses_ppv_and_hidden_ecg_does_not_suppress_pulses() {
let p = Parameters {
pulse_pressure_variation: 40,
respiratory_rate: 0,
show_ecg: false,
..Parameters::default()
};
let sim = Simulator::new(&p);
assert!(sim.conducted_qrs.iter().all(|b| b.pulse_pressure_scale == 1.0));
assert!(sim.pulse_rate().is_some());
assert!(sim.samples().iter().any(|s| s.art > 0.0));
}
#[test]
fn capnogram_reaches_etco2_plateau() {
assert!((capno_amplitude(0.76, CapnoShape::Normal) - 1.0).abs() < 1e-8);
}
}

View file

@ -0,0 +1,326 @@
//! GTK4 Admin and Monitor windows; all callbacks run on the GTK main thread.
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::time::Instant;
use gtk::gdk;
use gtk::glib;
use gtk::prelude::*;
use gtk::{Application, ApplicationWindow, Orientation};
use crate::model::{ArterialShape, CapnoShape, EcgRhythm, Parameters, PulseConduction};
use crate::render;
use crate::simulation::Simulator;
type SharedParams = Rc<RefCell<Parameters>>;
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 monitor = create_monitor(app, parameters.clone(), simulator);
let admin = create_admin(app, parameters, &monitor);
// Present monitor first, then leave controls in the foreground.
monitor.present();
admin.present();
}
fn create_monitor(app: &Application, params: SharedParams,
simulator: Rc<RefCell<Simulator>>) -> ApplicationWindow {
let window = ApplicationWindow::builder()
.application(app)
.title(concat!("Patient Monitor — Simulation v", env!("CARGO_PKG_VERSION")))
.default_width(1200)
.default_height(760)
.build();
let canvas = gtk::DrawingArea::new();
canvas.set_hexpand(true);
canvas.set_vexpand(true);
canvas.set_draw_func({
let params = params.clone();
let simulator = simulator.clone();
move |_area, cr, width, height| {
let config = *params.borrow();
render::draw(cr, width, height, &config, &simulator.borrow());
}
});
// Synchronize simulation time with frame updates; synthesize at 100 Hz.
let previous = Rc::new(Cell::new(Instant::now()));
canvas.add_tick_callback({
let params = params.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();
simulator.borrow_mut().advance(elapsed, &config);
area.queue_draw();
glib::ControlFlow::Continue
}
});
let keys = gtk::EventControllerKey::new();
let for_keys = window.clone();
keys.connect_key_pressed(move |_, key, _, _| {
if key == gdk::Key::F11 {
if for_keys.is_fullscreen() { for_keys.unfullscreen(); }
else { for_keys.fullscreen(); }
glib::Propagation::Stop
} else if key == gdk::Key::Escape && for_keys.is_fullscreen() {
for_keys.unfullscreen();
glib::Propagation::Stop
} else {
glib::Propagation::Proceed
}
});
window.add_controller(keys);
window.set_child(Some(&canvas));
window
}
fn create_admin(app: &Application, params: SharedParams,
monitor: &ApplicationWindow) -> ApplicationWindow {
let window = ApplicationWindow::builder()
.application(app)
.title(concat!("Patient Monitor — Admin v", env!("CARGO_PKG_VERSION")))
.default_width(600)
.default_height(790)
.build();
let main_box = gtk::Box::new(Orientation::Vertical, 10);
main_box.set_margin_top(12);
main_box.set_margin_bottom(12);
main_box.set_margin_start(12);
main_box.set_margin_end(12);
let header = gtk::Label::new(Some("Patient Monitor Simulation — Teaching Controls"));
header.set_xalign(0.0);
main_box.append(&header);
let scroller = gtk::ScrolledWindow::new();
scroller.set_hexpand(true);
scroller.set_vexpand(true);
scroller.set_policy(gtk::PolicyType::Never, gtk::PolicyType::Automatic);
let controls = gtk::Box::new(Orientation::Vertical, 12);
let ecg = group(&controls, "ECG");
add_visibility(&ecg, params.borrow().show_ecg, params.clone(), |p, show| p.show_ecg = show);
add_dropdown(&ecg, "ECG rhythm", &[
"Sinus rhythm", "Atrial fibrillation", "Ventricular tachycardia",
"Ventricular fibrillation", "Asystole",
], params.clone(), |p, selected| {
p.ecg_rhythm = match selected {
1 => EcgRhythm::AtrialFibrillation,
2 => EcgRhythm::VentricularTachycardia,
3 => EcgRhythm::VentricularFibrillation,
4 => EcgRhythm::Asystole,
_ => EcgRhythm::Sinus,
};
});
add_numeric(&ecg, "Heart rate", "bpm", 0, 240, params.borrow().heart_rate,
params.clone(), |p, v| p.heart_rate = v);
let spo2 = group(&controls, "Pulse oximetry");
add_visibility(&spo2, params.borrow().show_spo2, params.clone(), |p, show| p.show_spo2 = show);
add_numeric(&spo2, "SpO₂", "%", 0, 100, params.borrow().spo2,
params.clone(), |p, v| p.spo2 = v);
add_dropdown(&spo2, "Mechanical capture", &[
"1:1 (every QRS)",
"2:1 (one pulse in two)",
"3:1 (one pulse in three)",
"None (PEA)",
"Random (65% capture)",
], params.clone(), |p, selected| {
p.pulse_conduction = match selected {
1 => PulseConduction::TwoToOne,
2 => PulseConduction::ThreeToOne,
3 => PulseConduction::None,
4 => PulseConduction::Random,
_ => PulseConduction::OneToOne,
};
});
let conduction_hint = gtk::Label::new(Some(
"Pulse rate is derived from captured QRS events.
ART and pleth are delayed; VF and asystole always have no pulse."
));
conduction_hint.set_xalign(0.0);
conduction_hint.set_wrap(true);
spo2.append(&conduction_hint);
let art = group(&controls, "Invasive arterial blood pressure");
add_visibility(&art, params.borrow().show_art, params.clone(), |p, show| p.show_art = show);
add_numeric(&art, "Systolic", "mmHg", 0, 200, params.borrow().art_systolic,
params.clone(), |p, v| p.art_systolic = v);
add_numeric(&art, "Diastolic", "mmHg", 0, 200, params.borrow().art_diastolic,
params.clone(), |p, v| p.art_diastolic = v);
add_numeric(&art, "Pulse pressure variation", "%", 0, 60,
params.borrow().pulse_pressure_variation, params.clone(),
|p, v| p.pulse_pressure_variation = v);
let ppv_hint = gtk::Label::new(Some(
"Respiratory pulse-pressure swing (PPV). 0% = off; requires RR > 0."
));
ppv_hint.set_xalign(0.0);
ppv_hint.set_wrap(true);
art.append(&ppv_hint);
add_dropdown(&art, "Arterial waveform", &[
"Normal", "Damped", "Hyperdynamic",
], params.clone(), |p, selected| {
p.arterial_shape = match selected {
1 => ArterialShape::Damped,
2 => ArterialShape::Hyperdynamic,
_ => ArterialShape::Normal,
};
});
let nibp = group(&controls, "Non-invasive blood pressure (NIBP)");
add_visibility(&nibp, params.borrow().show_nibp, params.clone(), |p, show| p.show_nibp = show);
add_numeric(&nibp, "Systolic", "mmHg", 0, 260, params.borrow().nibp_systolic,
params.clone(), |p, v| p.nibp_systolic = v);
add_numeric(&nibp, "Diastolic", "mmHg", 0, 200, params.borrow().nibp_diastolic,
params.clone(), |p, v| p.nibp_diastolic = v);
let capno = group(&controls, "Capnography");
add_visibility(&capno, params.borrow().show_capno, params.clone(), |p, show| p.show_capno = show);
add_dropdown(&capno, "Capnogram", &["Normal", "Obstructive / shark fin"],
params.clone(), |p, selected| {
p.capno_shape = if selected == 1 { CapnoShape::Obstructive }
else { CapnoShape::Normal };
});
add_numeric(&capno, "EtCO₂", "mmHg", 0, 100, params.borrow().etco2,
params.clone(), |p, v| p.etco2 = v);
add_numeric(&capno, "Respiratory rate", "/min", 0, 60, params.borrow().respiratory_rate,
params.clone(), |p, v| p.respiratory_rate = v);
scroller.set_child(Some(&controls));
main_box.append(&scroller);
let fullscreen = gtk::CheckButton::with_label("Monitor fullscreen (F11 / Esc)");
fullscreen.connect_toggled({
let monitor = monitor.clone();
move |toggle| {
if toggle.is_active() && !monitor.is_fullscreen() { monitor.fullscreen(); }
else if !toggle.is_active() && monitor.is_fullscreen() { monitor.unfullscreen(); }
}
});
monitor.connect_fullscreened_notify({
let fullscreen = fullscreen.clone();
move |monitor| fullscreen.set_active(monitor.is_fullscreen())
});
main_box.append(&fullscreen);
let hint = gtk::Label::new(Some("Move the monitor to your presentation screen before entering fullscreen.\nSynthetic teaching signals only — not for clinical use."));
hint.set_xalign(0.0);
hint.set_wrap(true);
main_box.append(&hint);
window.set_child(Some(&main_box));
window
}
fn group(parent: &gtk::Box, title: &str) -> gtk::Box {
let frame = gtk::Frame::new(Some(title));
let content = gtk::Box::new(Orientation::Vertical, 8);
content.set_margin_top(10);
content.set_margin_bottom(10);
content.set_margin_start(10);
content.set_margin_end(10);
frame.set_child(Some(&content));
parent.append(&frame);
content
}
/// Display toggles never change signal generation or ECG-to-pulse coupling.
fn add_visibility<F>(parent: &gtk::Box, initial: bool, params: SharedParams, setter: F)
where F: Fn(&mut Parameters, bool) + 'static {
let toggle = gtk::CheckButton::with_label("Show on monitor");
toggle.set_active(initial);
toggle.connect_toggled(move |button| setter(&mut params.borrow_mut(), button.is_active()));
parent.append(&toggle);
}
fn add_dropdown<F>(parent: &gtk::Box, label: &str, items: &[&str],
params: SharedParams, setter: F)
where F: Fn(&mut Parameters, u32) + 'static {
let row = gtk::Box::new(Orientation::Horizontal, 8);
let caption = gtk::Label::new(Some(label));
caption.set_xalign(0.0);
caption.set_width_chars(17);
let combo = gtk::DropDown::from_strings(items);
combo.set_hexpand(true);
combo.connect_selected_notify(move |combo| {
setter(&mut params.borrow_mut(), combo.selected());
});
row.append(&caption);
row.append(&combo);
parent.append(&row);
}
#[allow(clippy::too_many_arguments)]
fn add_numeric<F>(parent: &gtk::Box, label: &str, unit: &str,
min: i32, max: i32, initial: i32,
params: SharedParams, setter: F)
where F: Fn(&mut Parameters, i32) + 'static {
let row = gtk::Box::new(Orientation::Horizontal, 8);
let caption = gtk::Label::new(Some(label));
caption.set_xalign(0.0);
caption.set_width_chars(17);
let slider = gtk::Scale::with_range(Orientation::Horizontal,
f64::from(min), f64::from(max), 1.0);
slider.set_draw_value(false);
slider.set_digits(0);
slider.set_hexpand(true);
slider.set_value(f64::from(initial));
let entry = gtk::Entry::new();
entry.set_width_chars(5);
entry.set_max_width_chars(5);
entry.set_text(&initial.to_string());
entry.set_input_purpose(gtk::InputPurpose::Digits);
slider.connect_value_changed({
let entry = entry.clone();
move |slider| {
let v = slider.value().round() as i32;
setter(&mut params.borrow_mut(), v);
// Do not overwrite a partially typed number while the entry has focus.
if !entry.has_focus() { entry.set_text(&v.to_string()); }
}
});
entry.connect_changed({
let slider = slider.clone();
move |entry| {
if let Ok(v) = entry.text().parse::<i32>() {
if (min..=max).contains(&v) { slider.set_value(f64::from(v)); }
}
}
});
entry.connect_activate({
let slider = slider.clone();
move |entry| normalize_entry(entry, &slider, min, max)
});
entry.connect_has_focus_notify({
let slider = slider.clone();
move |entry| {
if !entry.has_focus() { normalize_entry(entry, &slider, min, max); }
}
});
let suffix = gtk::Label::new(Some(unit));
suffix.set_width_chars(5);
suffix.set_xalign(0.0);
row.append(&caption);
row.append(&slider);
row.append(&entry);
row.append(&suffix);
parent.append(&row);
}
fn normalize_entry(entry: &gtk::Entry, slider: &gtk::Scale, min: i32, max: i32) {
let parsed = entry.text().parse::<i32>().ok();
let value = parsed.map(|v| v.clamp(min, max))
.unwrap_or_else(|| slider.value().round() as i32);
slider.set_value(f64::from(value));
entry.set_text(&value.to_string());
}