diff --git a/CHANGELOG.md b/CHANGELOG.md index b6265829d..66ed5a66a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,9 @@ hashes are given where a change is easiest to understand by reading the commit. ### Front ends +- `iris --tui` builds a configuration in the terminal: open, convert and save `iris.toml` files, pick the machine, + add and edit devices at its slots, then run it straight into the monitor console. All machines. + - A native Windows front end, `iris-win32`, over the same controllers as the Mac and Linux apps: menu bar, library, machine page, guest display with mouse capture, settings, the New Machine wizard, the disk browser and the diff --git a/Cargo.toml b/Cargo.toml index 306b54b5a..ec805f186 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -97,6 +97,8 @@ tlbvmap = [] # or when stdin is not a terminal, the console reads plain lines. On by default; # `--no-default-features` drops the dependency. lineedit = ["dep:rustyline"] +# `iris --tui`: the configuration builder in the terminal. +tui = ["dep:ratatui"] # CD-ROM media served over HTTP(S) with Range requests (src/http_disk.rs): a # CD-ROM path or changer disc may be an http:// or https:// URL. On by default; # without it such a URL is refused when the disc is opened, and the build @@ -180,7 +182,7 @@ cache-ecc = [] # Always built now; this flag does nothing and is kept so command lines that # still pass `--features decode-cache` keep working. decode-cache = [] -default = ["tlbvmap", "rexdiag", "lineedit", "embedded-proms", "http-media"] +default = ["tlbvmap", "rexdiag", "lineedit", "tui", "embedded-proms", "http-media"] # The SGI PROMs iris carries (data/proms), each a deflate file inflated when its machine # starts. Off, nothing is built in and every machine needs a `prom` file. embedded-proms = [] @@ -360,6 +362,8 @@ iris-hostgl = { path = "iris-hostgl", optional = true } junit-report = "0.9" # `lineedit`'s editor: no file history, hints or derive macros. rustyline = { version = "19", optional = true, default-features = false } +# `tui`'s terminal UI; crossterm comes with it (ratatui::crossterm). +ratatui = { version = "0.30", optional = true } # `http-media`'s client: ring-backed rustls with the bundled Mozilla roots, no gzip. ureq = { version = "3.5", optional = true, default-features = false, features = ["rustls"] } [target.'cfg(target_os = "macos")'.dependencies] diff --git a/FEATURES.md b/FEATURES.md index 1b8d9dfa9..a5182e16c 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -10,7 +10,7 @@ are below the inventory. ### iris (core and standalone CLI) -Source: [Cargo.toml](Cargo.toml). Default features are `tlbvmap,rexdiag,lineedit,embedded-proms,http-media`. +Source: [Cargo.toml](Cargo.toml). Default features are `tlbvmap,rexdiag,lineedit,tui,embedded-proms,http-media`. Select with `cargo build --release --features `; add `--no-default-features` to drop the core default bundle. @@ -39,7 +39,7 @@ Select with `cargo build --release --features `; add | `decode-cache` | Compatibility flag; decoded-instruction caching for the shadow model is unconditional. | — | | `tcache_verify` | Assert transparent-cache/RAM coherence on accesses; very slow. | `tcache` | | `embedded-proms` | The SGI PROMs built into the binary, each inflated when its machine starts. Without it a machine needs a `prom` file. | — | -| `default` | Default bundle: `tlbvmap`, `rexdiag`, `lineedit`, `embedded-proms` and `http-media`. | `tlbvmap`, `rexdiag`, `lineedit`, `embedded-proms`, `http-media` | +| `default` | Default bundle: `tlbvmap`, `rexdiag`, `lineedit`, `tui`, `embedded-proms` and `http-media`. | `tlbvmap`, `rexdiag`, `lineedit`, `tui`, `embedded-proms`, `http-media` | | `rex-dirty-upload` | Track conservative Newport framebuffer damage and copy/upload only dirty regions. Opt-in; the default retains the original REX3 and presentation paths. | — | | `rex-jit` | Cranelift compiler for Newport draw shaders; complements precompiled shaders. | `cranelift-codegen`, `cranelift-frontend`, `cranelift-jit`, `cranelift-module`, `cranelift-native` | | `wgpu` | Host-GPU rasterisation through the common wgpu layer (VPro, IMPACT and experimental GPU-authoritative Newport), plus wgpu window composition. Newport production activation is initially validated on Vulkan and D3D12 and fails closed without CPU fallback. Work in progress; see `clanker/plans/GPUTodo.md`. | `dep:bytemuck`, `dep:pollster`, `dep:wgpu`, `dep:ash` | @@ -55,6 +55,7 @@ Select with `cargo build --release --features `; add | `hostcall` | Private user-mode guest syscall services 3000–3009; IRIX handles other calls. | `dep:iris-hostcall` | | `hostgl` | Guest replacement-libGL command replay; macOS (CGL) and Linux (EGL) backends. | `hostcall`, `dep:iris-hostgl` | | `lineedit` | Terminal console line editing (history, Ctrl-R, cursor keys, Tab completion of command names) when stdin is a terminal. Default on; `--no-default-features` drops rustyline. | `dep:rustyline` | +| `tui` | `iris --tui`, the configuration builder in the terminal (ratatui). Default on; a build without it refuses `--tui`. | `dep:ratatui` | | `http-media` | CD-ROM images given as `http://` or `https://` URLs, read with HTTP `Range` requests (see [STORAGE.md](STORAGE.md#cd-rom-images-over-http)). Default on; without it such a URL is refused when the disc is opened and the build has no HTTP or TLS code. | `dep:ureq` | Cargo also exposes these **implicit optional-dependency features**: @@ -664,6 +665,7 @@ iris-gui does not parse this standalone option set; use its named-machine UI. | `--list-slots` | Print the machine's slots as a tree, their aliases, what is in each and what it takes, then exit. | | `--config-show` | Print the effective config as an iris.toml with only what differs from the machine's defaults, each device at its resolved slot, then exit. | | `--config-dump FILE` | Write that file to `FILE`, which must not exist, then exit. | +| `--tui` | Build the configuration in a terminal UI, then run it (see [HELP.md](HELP.md#building-a-configuration-in-the-terminal)). Opens `--config FILE` when given (a new file when it does not exist); the other options change the first file it opens. Needs a terminal and the `tui` feature. | | `--2x` | 2× window scaling for HiDPI/4K monitors | | `--headless` | Suppress the standalone window (platform-specific graphics/console behavior, as `headless`; audio unaffected) | | `--noaudio` | Disable host audio output, as `no_audio`; graphics is unaffected | @@ -813,6 +815,7 @@ mistaken for GUI settings. | `IRIS_QOS` | HostGL QoS: default/off disables promotion; quiet suppresses logging. | [iris-hostgl/src/qos.rs](iris-hostgl/src/qos.rs) | | `IRIS_REX3_GPU_STATS` | Set (any value) to add the costlier Newport GPU-raster telemetry to `rex status`: command generation time per GO and which state-slot words change from one primitive to the next. Read when the GPU raster starts. | [src/dev/ng1/wgpu/resident.rs](src/dev/ng1/wgpu/resident.rs) | | `IRIS_REX_JIT_PROFILE` | Where the REX3 shader JIT keeps its profile of draw modes between runs, instead of `~/.iris/rex-jit-profile.bin` (`rex-jit` builds). | [src/dev/ng1/rex3_profile.rs](src/dev/ng1/rex3_profile.rs) | +| `IRIS_SIMD` | `sse4.2` caps the host SIMD level on an x86 host with AVX2: the VPro SIMD kernels run at SSE4.2, and every JIT (MIPS, REX3, IMPACT, GR2) compiles without AVX, FMA or BMI, as on a CPU without AVX2. Only lowers the level; a build for `target-cpu=native` on an AVX2 host keeps AVX2. Unset: the level the CPU has, detected once. | [src/host_simd.rs](src/host_simd.rs) | | `IRIS_SNAPSHOT_SKIP_CHECK` | 1 bypasses selected snapshot compatibility checks; diagnostic escape hatch. | [src/machine.rs](src/machine.rs) | | `IRIS_SOCKET` | iris-ci default socket override (Unix path or TCP address). | [src/iris_ci_main.rs](src/iris_ci_main.rs) | | `IRIS_VNC_PASSWORD` | The VNC password itself (first 8 bytes), used when neither `[vnc] password_file` nor `IRIS_VNC_PASSWORD_FILE` is set. Standalone `iris` only. | [src/vnc/auth.rs](src/vnc/auth.rs) | diff --git a/HACKING.md b/HACKING.md index 7bef065ad..e20149241 100644 --- a/HACKING.md +++ b/HACKING.md @@ -386,7 +386,7 @@ Every device that has real work to do runs on its own thread: | `IOC3-NVRAM` | the DS1685 NVRAM file writer (IOC3's other deadlines are `hptimer` one-shots) | | `bcm5701-rx`, `bcm5701-net` | Tezro BCM5701 receive pump and network backend | | `ioc3-eth-rx`, `ioc3-eth-net` | IOC3 ethernet receive pump (every machine with an IOC3); the network backend | -| `odyssey-work`, `odyssey-raster`, `odyssey-pool-N` | VPro: the front end decodes the queued command-FIFO stores (the processor's stores only queue); the raster unit sets each draw up and walks its primitives into 2x2 quads; a pool of workers (`[graphics] threads`, default 2) walks, shades and stores filled triangles and stores every other fragment, one screen tile at a time; and the display composes each whole frame from board memory (64-bit words, as main memory is: a field is a bit range of its word, read by shift and mask with no byte order, `vram.rs`) as the scan-out registers describe it, counts the retrace and presents the window at 60 Hz. No board-wide lock: the front end owns its state, an access that needs the drawing is answered busy until it is done, the display FIFO (PB&J's register file) has its own lock and never waits for the drawing (`display_fifo.rs`), and the display reads board memory while it is drawn, as the board's own scan-out does; nobody tracks which rows changed. The raster thread sets primitives up and writes each as one command in a ring of 64-byte slots (`pipe/ring.rs`): a triangle's record and bounding box, a quad it shaded itself (lines, points), or a clear's rectangle; the slot's index goes on the queue of every screen tile (`[graphics] tile`, default 32 pixels) it touches. A worker takes a ready tile and owns it until its queue is empty, walking each triangle within the tile and shading and storing quad by quad, so every pixel sees its fragments in command order with no other ordering, and the depth pre-test reads depth its own tile stored. A slot is retired once all its tiles have run it. The raster thread drains the ring before any other work on board memory (a texture upload waits for the shader alone). A completion (a fence's token, a query's words) does not drain: it rides the ring and runs once the ring retires past the quads queued before it. A quad's four pixels are lanes: the walk's depth, the texture unit's positions and the colour weights run on the host's SIMD unit (`fearless_simd`, `pipe/lanes.rs`, the level detected at start-up), bit for bit the scalar arithmetic. When its queue runs dry the raster thread does not drain: it keeps one count of the raster unit's pending jobs for the quads still in flight, and a front-end wait or a refused processor read asks it to store them. `IRIS_ODSY_SHADER=inline` makes the raster thread shade every quad itself, and `IRIS_ODSY_BACKEND=inline` stores on the raster thread with no pool. The texture registers a draw reads live in an array of draw state slots (`pipe/slot.rs`): the front end writes the current slot, a draw latches it and holds it until its job is given back, and a write while a queued draw holds the current slot first copies it to a free one, so the stages read their draw's registers with no lock | +| `odyssey-work`, `odyssey-raster`, `odyssey-pool-N` | VPro: the front end decodes the queued command-FIFO stores (the processor's stores only queue); the raster unit sets each draw up and walks its primitives into 2x2 quads; a pool of workers (`[graphics] threads`, default 2) walks, shades and stores filled triangles and stores every other fragment, one screen tile at a time; and the display composes each whole frame from board memory (64-bit words, as main memory is: a field is a bit range of its word, read by shift and mask with no byte order, `vram.rs`) as the scan-out registers describe it, counts the retrace and presents the window at 60 Hz. No board-wide lock: the front end owns its state, an access that needs the drawing is answered busy until it is done, the display FIFO (PB&J's register file) has its own lock and never waits for the drawing (`display_fifo.rs`), and the display reads board memory while it is drawn, as the board's own scan-out does; nobody tracks which rows changed. The raster thread sets primitives up and writes each as one command in a ring of 64-byte slots (`pipe/ring.rs`): a triangle's record and bounding box, a quad it shaded itself (lines, points), or a clear's rectangle; the slot's index goes on the queue of every screen tile (`[graphics] tile`, default 32 pixels) it touches. A worker takes a ready tile and owns it until its queue is empty, walking each triangle within the tile and shading and storing quad by quad, so every pixel sees its fragments in command order with no other ordering, and the depth pre-test reads depth its own tile stored. A slot is retired once all its tiles have run it. The raster thread drains the ring before any other work on board memory (a texture upload waits for the shader alone). A completion (a fence's token, a query's words) does not drain: it rides the ring and runs once the ring retires past the quads queued before it. A quad's four pixels are lanes: the walk's depth, the texture unit's positions and the colour weights run on the host's SIMD unit (`fearless_simd`, `pipe/lanes.rs`, at the level `host_simd.rs` detects once, which the JITs' targets also follow), bit for bit the scalar arithmetic. When its queue runs dry the raster thread does not drain: it keeps one count of the raster unit's pending jobs for the quads still in flight, and a front-end wait or a refused processor read asks it to store them. `IRIS_ODSY_SHADER=inline` makes the raster thread shade every quad itself, and `IRIS_ODSY_BACKEND=inline` stores on the raster thread with no pool. The texture registers a draw reads live in an array of draw state slots (`pipe/slot.rs`): the front end writes the current slot, a draw latches it and holds it until its job is given back, and a write while a queued draw holds the current slot first copies it to a free one, so the stages read their draw's registers with no lock | | `kona-hip`, `kona-tile-N` | InfiniteReality (KONA): the processor's stores to the pipe only queue in a ring (`src/dev/kona/mod.rs`); `kona-hip` takes them in order under the pipe lock, frames the commands and runs the back end inline, so the front end's state needs no lock of its own. A draw is set up on `kona-hip` and its job goes on the index queue of every screen tile it touches (`[graphics] tile`); `kona-tile-N` workers (`[graphics] threads`; none means `kona-hip` runs the tiles itself) each take a ready tile and own it until its queue is empty, so every pixel sees its work in command order. `kona-hip` drains the tiles before any other use of the pixel store. The display refresh thread (`Display-Refresh`, section 7) runs the board at 60 Hz and, at each retrace, completes the retrace requests made since the last one (through the display handle, not the pipe lock); it composes the whole frame from the store and the display tables when drawing finished since the last frame, a screenshot or frame is wanted, or six frames have passed | With VPro's wgpu raster selected, GPU memory is authoritative. CPU geometry, diff --git a/HELP.md b/HELP.md index 61895d01d..10818dd01 100644 --- a/HELP.md +++ b/HELP.md @@ -787,6 +787,32 @@ replaced). The file holds only what differs from the machine's defaults, with ea slot it took. It is not validated, so run `--validate` on the result. Example: `iris --machine octane_ip30 --device hostserial@serial1,path=/dev/ttyUSB0 --config-dump octane.toml`. In the monitor, `config show` and `config dump PATH` do the same for the running machine. +### Building a configuration in the terminal + +`iris --tui` opens a configuration builder in the terminal. It starts in a file browser over the `.toml` files of +the current directory; `iris --tui --config FILE` opens `FILE` straight away, or starts a new one there when it does +not exist. + +- **Files.** Enter opens a file or a directory, Backspace goes up, `n` makes a new file after asking which machine it + is for. A file written in older spellings is converted as it is read, and the builder lists the keys it converted. + A file iris cannot read shows iris's reason; `e` opens its text in your editor to fix it. +- **Slots.** The machine's slots as a tree, with what is in each: the file's own entries in yellow, the machine's + defaults dimmed, and what an empty slot takes. Enter on an empty slot offers the device types that fit it; Enter on a + device edits its entry (a default becomes an entry of the file). `d` removes an entry, or leaves a default's slot + empty. An entry that finds no slot, after a change of machine for instance, is listed in red at the end. +- **Entries.** A form with the type's keys. A value is TOML when it reads as TOML, else a string, so a path needs no + quotes; ←/→ steps through the values of a key that has few, and `b` picks a file for the value. An entry iris + could not place is refused with the reason. +- **Checks.** Under the tree, what a run would stop at (missing disk images, ports in use) and its warnings, kept up to + date as you edit. +- `m` changes the machine, `e` edits the whole file as text in `$VISUAL` or `$EDITOR`. +- `s` saves, `S` saves under another name. A save writes the current spellings and only what differs from the + machine's defaults; comments are not kept, so the first save over a file keeps the original as `FILE.bak`. +- `r` runs. Paths in a configuration are relative to the directory iris runs from, so choose it: the current + directory, the file's directory or the iris checkout above them. The builder offers to save first and shows what + the run would stop at, then closes; the machine starts as it would from the file, and the terminal becomes the + monitor console. + ```toml # ── Top-level scalars (must come before any [section]) ─────────────────────── diff --git a/src/config.rs b/src/config.rs index be4454173..ca60d875b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -3999,6 +3999,11 @@ pub struct Cli { #[arg(long = "config-dump", value_name = "FILE")] pub config_dump: Option, + /// Build the configuration in a terminal UI (open, convert, edit and save iris.toml files), then run it; the other + /// options change the first file it opens + #[arg(long, default_value_t = false)] + pub tui: bool, + /// Additional ISO images for CD-ROM ID 4 (can be specified multiple times) #[arg(long = "cdrom4-extra", value_name = "ISO")] pub cdrom4_extra: Vec, @@ -4383,7 +4388,7 @@ pub fn load_config() -> (MachineConfig, u32) { // against the wrong cwd, and silently booting a default machine instead // (different disks, no DaynaPort, whatever they configured) wastes a run // before anyone notices. - if cli.config != DEFAULT_CONFIG && !std::path::Path::new(&cli.config).exists() { + if !cli.tui && cli.config != DEFAULT_CONFIG && !std::path::Path::new(&cli.config).exists() { eprintln!("Configuration error: --config {} does not exist", cli.config); std::process::exit(1); } @@ -4407,8 +4412,11 @@ pub fn load_config() -> (MachineConfig, u32) { std::process::exit(crate::validate_config::report(&cli.config, &cfg)); } - let toml_cfg = MachineConfig::load_toml(&cli.config); - let mut cfg = cli.apply(toml_cfg); + let mut cfg = match cli.tui { + // The builder applies the command line to the file it opens; a quit ends the process here. + true => tui_config(&cli), + false => cli.apply(MachineConfig::load_toml(&cli.config)), + }; if let Err(e) = cfg.resolve_slots() { eprintln!("Configuration error: {e}"); std::process::exit(1); @@ -4438,6 +4446,25 @@ pub fn load_config() -> (MachineConfig, u32) { (cfg, scale) } +/// The config `iris --tui` builds, or the process ends: on a quit, or when the build has no builder. +fn tui_config(cli: &Cli) -> MachineConfig { + #[cfg(feature = "tui")] + match crate::tui::run(cli) { + Ok(Some(cfg)) => return cfg, + Ok(None) => std::process::exit(0), + Err(e) => { + eprintln!("iris: --tui: {e}"); + std::process::exit(1); + } + } + #[cfg(not(feature = "tui"))] + { + let _ = cli; + eprintln!("iris: --tui needs a build with the tui feature"); + std::process::exit(1); + } +} + /// Parse a CIDR string like "192.168.5.0/24" and return /// `(gateway_ip, client_ip, netmask)` where gateway=host .1, client=host .2. /// diff --git a/src/cpu/jitv2/codegen.rs b/src/cpu/jitv2/codegen.rs index 5434c9990..deb84c8a9 100644 --- a/src/cpu/jitv2/codegen.rs +++ b/src/cpu/jitv2/codegen.rs @@ -692,8 +692,7 @@ impl Codegen { flag_builder.set("regalloc_algorithm", algo).unwrap(); } flag_builder.set("enable_verifier", if verify_ir { "true" } else { "false" }).unwrap(); - let isa_builder = cranelift_native::builder().expect("host ISA not supported"); - let isa = isa_builder.finish(settings::Flags::new(flag_builder)).unwrap(); + let isa = crate::host_simd::jit_isa(flag_builder); let mut jit_builder = cranelift_jit::JITBuilder::with_isa(isa, cranelift_module::default_libcall_names()); let (shared, paged_state) = match shared { Some(shared) => (shared, state.expect("new_module: shared arena given without its PagedArenaState")), diff --git a/src/dev/gr2/re3_jit/compiler.rs b/src/dev/gr2/re3_jit/compiler.rs index 5f5516bd8..d9fc18ae0 100644 --- a/src/dev/gr2/re3_jit/compiler.rs +++ b/src/dev/gr2/re3_jit/compiler.rs @@ -51,10 +51,7 @@ impl Compiler { let mut flags = settings::builder(); flags.set("opt_level", "speed").unwrap(); flags.set("is_pic", "false").unwrap(); - let isa = cranelift_native::builder() - .expect("host ISA not supported") - .finish(settings::Flags::new(flags)) - .unwrap(); + let isa = crate::host_simd::jit_isa(flags); let module = JITModule::new(JITBuilder::with_isa(isa, cranelift_module::default_libcall_names())); Compiler { ctx: module.make_context(), module, fctx: FunctionBuilderContext::new(), n: 0 } } diff --git a/src/dev/mgras/rss_jit/compiler.rs b/src/dev/mgras/rss_jit/compiler.rs index a42768a4b..28858dd47 100644 --- a/src/dev/mgras/rss_jit/compiler.rs +++ b/src/dev/mgras/rss_jit/compiler.rs @@ -60,10 +60,7 @@ impl Compiler { let mut flags = settings::builder(); flags.set("opt_level", "speed").unwrap(); flags.set("is_pic", "false").unwrap(); - let isa = cranelift_native::builder() - .expect("host ISA not supported") - .finish(settings::Flags::new(flags)) - .unwrap(); + let isa = crate::host_simd::jit_isa(flags); let module = JITModule::new(JITBuilder::with_isa(isa, cranelift_module::default_libcall_names())); Compiler { ctx: module.make_context(), module, fctx: FunctionBuilderContext::new(), n: 0 } } diff --git a/src/dev/ng1/rex3_jit/compiler.rs b/src/dev/ng1/rex3_jit/compiler.rs index c4b9d1050..266d571b5 100644 --- a/src/dev/ng1/rex3_jit/compiler.rs +++ b/src/dev/ng1/rex3_jit/compiler.rs @@ -150,8 +150,7 @@ impl ShaderCompiler { flag_builder.set("opt_level", "speed").unwrap(); flag_builder.set("is_pic", "false").unwrap(); - let isa_builder = cranelift_native::builder().expect("host ISA not supported"); - let isa = isa_builder.finish(settings::Flags::new(flag_builder)).unwrap(); + let isa = crate::host_simd::jit_isa(flag_builder); let jit_builder = JITBuilder::with_isa(isa, cranelift_module::default_libcall_names()); let jit_module = JITModule::new(jit_builder); diff --git a/src/dev/odyssey/pipe/lanes.rs b/src/dev/odyssey/pipe/lanes.rs index 7138e77f6..c5a31f0f3 100644 --- a/src/dev/odyssey/pipe/lanes.rs +++ b/src/dev/odyssey/pipe/lanes.rs @@ -11,16 +11,12 @@ //! only that level, and the dispatch folds away; a portable build picks //! its level at run time. -use std::sync::LazyLock; - use fearless_simd::{f32x4, i32x4, Level, Simd}; -static LEVEL: LazyLock = LazyLock::new(Level::new); - -/// The host's SIMD level, detected once. +/// The host's SIMD level, detected once (`crate::host_simd`). #[inline(always)] pub(crate) fn level() -> Level { - *LEVEL + crate::host_simd::level() } /// `x as i32 - (x < (x as i32) as f32) as i32` at four lanes, the diff --git a/src/devices.rs b/src/devices.rs index 215ac5b23..15366ab38 100644 --- a/src/devices.rs +++ b/src/devices.rs @@ -220,6 +220,13 @@ fn scsi_target(t: &DeviceTypeSpec, opts: toml::Table) -> Result &'static [&'static str] { + self.keys + } +} + impl DeviceModel { pub fn spec(&self) -> &'static DeviceTypeSpec { let name = match self { diff --git a/src/exit_persistence_tests.rs b/src/exit_persistence_tests.rs index e4f27ff23..b18687321 100644 --- a/src/exit_persistence_tests.rs +++ b/src/exit_persistence_tests.rs @@ -863,7 +863,7 @@ fn no_process_exit_bypasses_the_flush() { // The bare-metal test device ends the run with the guest's exit code. ("dev/testdev.rs", 1, "bare-metal test device, a harness only"), // Command-line and configuration front ends: nothing is running yet. - ("config.rs", 13, "command-line and configuration errors, the --validate result, --machine, --device, --list-slots and --config-dump"), + ("config.rs", 16, "command-line and configuration errors, the --validate result, --machine, --device, --list-slots, --config-dump and leaving --tui"), ("iris_ci_main.rs", 1, "the iris-ci client"), ("crash_diag.rs", 1, "fatal-signal handler: the process is already dying"), ]; diff --git a/src/host_simd.rs b/src/host_simd.rs new file mode 100644 index 000000000..a2f48bc84 --- /dev/null +++ b/src/host_simd.rs @@ -0,0 +1,141 @@ +//! The host's SIMD level, detected once. +//! +//! Every kernel that dispatches on fearless_simd takes its level from +//! [`level()`], and every Cranelift JIT builds its target with [`jit_isa()`], +//! whose x86 feature flags follow the same level. Interpreted and compiled +//! paths then use the same instruction set, and one setting moves them all. +//! +//! `IRIS_SIMD=sse4.2` caps the level on an x86 host that has AVX2, to run +//! the paths a CPU without AVX2 takes. It only lowers the level, and a build +//! whose target already assumes AVX2 (`target-cpu=native` on such a host) +//! has no SSE4.2 level to cap to: it says so and keeps AVX2. + +use std::sync::LazyLock; + +use fearless_simd::Level; + +static LEVEL: LazyLock = LazyLock::new(|| { + let want = std::env::var("IRIS_SIMD").ok(); + cap(Level::new(), want.as_deref()) +}); + +/// The host's SIMD level, detected on first use. +#[inline(always)] +pub fn level() -> Level { + *LEVEL +} + +/// A level's name, as `IRIS_SIMD` spells it. +pub fn name(level: Level) -> &'static str { + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + { + if level.as_avx2().is_some() { + return "avx2"; + } + if level.as_sse4_2().is_some() { + return "sse4.2"; + } + } + #[cfg(target_arch = "aarch64")] + { + if level.as_neon().is_some() { + return "neon"; + } + } + "fallback" +} + +fn cap(level: Level, want: Option<&str>) -> Level { + match want { + None | Some("") | Some("native") => level, + Some("sse4.2") => match sse4_2(level) { + Some(l) => l, + None => { + eprintln!("iris: IRIS_SIMD=sse4.2: this build has no SSE4.2 level below {}; keeping it", name(level)); + level + } + }, + Some(w) if w == name(level) => level, + Some(other) => { + eprintln!("iris: IRIS_SIMD={other}: can only cap to sse4.2 here; keeping {}", name(level)); + level + } + } +} + +/// `level` lowered to SSE4.2, where this build has that level. +#[allow(unused_variables, unreachable_code)] +fn sse4_2(level: Level) -> Option { + // The same condition under which fearless_simd compiles its Sse4_2 level. + #[cfg(all( + any(target_arch = "x86", target_arch = "x86_64"), + not(all( + target_feature = "avx2", + target_feature = "bmi1", + target_feature = "bmi2", + target_feature = "cmpxchg16b", + target_feature = "f16c", + target_feature = "fma", + target_feature = "lzcnt", + target_feature = "movbe", + target_feature = "popcnt", + target_feature = "xsave" + )) + ))] + return level.as_sse4_2().map(Level::Sse4_2); + None +} + +/// A Cranelift target for the host with `flags`, its x86 instruction-set +/// flags no higher than [`level()`]: below AVX2 the AVX, AVX-512, FMA, BMI +/// and LZCNT flags are off, as for a CPU without AVX2. +#[cfg(any(feature = "jitv2", feature = "rex-jit", feature = "gr4-jit", feature = "gr2-jit"))] +pub fn jit_isa(flags: cranelift_codegen::settings::Builder) -> cranelift_codegen::isa::OwnedTargetIsa { + #[allow(unused_mut)] + let mut isa = cranelift_native::builder().expect("host ISA not supported"); + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + if level().as_avx2().is_none() { + use cranelift_codegen::settings::Configurable; + const ABOVE_SSE4_2: [&str; 11] = [ + "has_avx", "has_avx2", "has_fma", "has_bmi1", "has_bmi2", "has_lzcnt", + "has_avx512bitalg", "has_avx512dq", "has_avx512f", "has_avx512vl", "has_avx512vbmi", + ]; + for f in ABOVE_SSE4_2 { + isa.set(f, "false").expect("a Cranelift x86 flag"); + } + } + isa.finish(cranelift_codegen::settings::Flags::new(flags)).expect("Cranelift target") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn native_and_unknown_keep_the_level() { + let l = Level::new(); + assert_eq!(name(cap(l, None)), name(l)); + assert_eq!(name(cap(l, Some("native"))), name(l)); + assert_eq!(name(cap(l, Some("bogus"))), name(l)); + } + + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + #[test] + fn sse4_2_caps_an_avx2_host() { + let l = Level::new(); + let capped = cap(l, Some("sse4.2")); + if sse4_2(l).is_some() { + assert_eq!(name(capped), "sse4.2"); + assert!(capped.as_avx2().is_none()); + } else { + assert_eq!(name(capped), name(l)); + } + } + + #[cfg(all(any(target_arch = "x86", target_arch = "x86_64"), any(feature = "jitv2", feature = "rex-jit", feature = "gr4-jit", feature = "gr2-jit")))] + #[test] + fn jit_isa_builds_for_the_host() { + let isa = jit_isa(cranelift_codegen::settings::builder()); + assert_eq!(isa.pointer_bytes(), std::mem::size_of::() as u8); + } +} diff --git a/src/lib.rs b/src/lib.rs index 8f36bbd34..d3850cb20 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -202,6 +202,9 @@ pub mod ip22_bus; pub mod monitor; pub mod console_edit; pub mod locks; +pub mod host_simd; +#[cfg(feature = "tui")] +pub mod tui; pub mod sync; pub mod net; pub mod bench_report; diff --git a/src/topology.rs b/src/topology.rs index 1f2bc90bc..12d0daf43 100644 --- a/src/topology.rs +++ b/src/topology.rs @@ -451,6 +451,11 @@ impl DevicePlacement { self.at[i].as_ref().ok() } + /// Why device `i` has no slot, if it has none. + pub fn error(&self, i: usize) -> Option<&str> { + self.at[i].as_ref().err().map(String::as_str) + } + /// How a config file writes device `i`'s slot: with its machine alias where it has one, else the full path. pub fn at_text(&self, i: usize) -> Option { let at = self.at(i)?; diff --git a/src/tui/mod.rs b/src/tui/mod.rs new file mode 100644 index 000000000..847afef10 --- /dev/null +++ b/src/tui/mod.rs @@ -0,0 +1,980 @@ +//! `iris --tui`: build a configuration in the terminal, then run it. +//! +//! A file browser opens and creates `.toml` files; the slot view shows the machine's slots with what is in each, and +//! adds, edits and removes devices there; `e` edits the whole file as text in `$VISUAL`/`$EDITOR`. A file in the older +//! spellings reads into the current ones, and saving writes those (the original is kept as `.bak`). Run hands the +//! config back to `load_config`, which starts the machine as it would from a file, and the terminal goes to the monitor. + +mod model; + +use std::io::IsTerminal; +use std::path::{Path, PathBuf}; + +use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers}; +use ratatui::layout::{Constraint, Layout, Rect}; +use ratatui::style::{Color, Modifier, Style, Stylize}; +use ratatui::text::{Line, Span, Text}; +use ratatui::widgets::{Block, Clear, List, ListItem, ListState, Paragraph, Wrap}; +use ratatui::{DefaultTerminal, Frame}; + +use crate::config::{Cli, MachineConfig, MachineProfile, DEFAULT_CONFIG}; +use crate::slot_path::MachineSlotPath; +use model::{Content, Doc, Form}; + +/// Run the builder. `Some(config)` to run it, `None` when the user quit. +pub fn run(cli: &Cli) -> Result, String> { + if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() { + return Err("needs a terminal".into()); + } + let mut app = App::new(cli)?; + let mut term = ratatui::init(); + let result = app.run(&mut term); + ratatui::restore(); + result +} + +/// A line being typed: its text and the cursor, in characters. +#[derive(Clone, Default)] +struct Input { + text: String, + cursor: usize, +} + +impl Input { + fn new(text: &str) -> Input { + Input { text: text.to_string(), cursor: text.chars().count() } + } + + fn byte(&self, c: usize) -> usize { + self.text.char_indices().nth(c).map_or(self.text.len(), |(i, _)| i) + } + + /// Apply a key: true when the key was the input's. + fn key(&mut self, k: KeyEvent) -> bool { + let n = self.text.chars().count(); + match k.code { + KeyCode::Char(c) if !k.modifiers.contains(KeyModifiers::CONTROL) => { + let at = self.byte(self.cursor); + self.text.insert(at, c); + self.cursor += 1; + } + KeyCode::Char('u') => { + self.text.clear(); + self.cursor = 0; + } + KeyCode::Backspace if self.cursor > 0 => { + self.cursor -= 1; + let at = self.byte(self.cursor); + self.text.remove(at); + } + KeyCode::Delete if self.cursor < n => { + let at = self.byte(self.cursor); + self.text.remove(at); + } + KeyCode::Left => self.cursor = self.cursor.saturating_sub(1), + KeyCode::Right => self.cursor = (self.cursor + 1).min(n), + KeyCode::Home => self.cursor = 0, + KeyCode::End => self.cursor = n, + _ => return false, + } + true + } + + /// The text with the cursor drawn as a reversed cell. + fn line(&self) -> Line<'static> { + let (a, b) = self.text.split_at(self.byte(self.cursor)); + let mut rest = b.chars(); + let at = rest.next().map_or(" ".to_string(), String::from); + Line::from(vec![Span::raw(a.to_string()), Span::styled(at, Style::new().add_modifier(Modifier::REVERSED)), Span::raw(rest.collect::())]) + } +} + +/// What the file browser picks: a config to open, or a file whose path goes into a form's field. +enum Pick { + Open, + Value { form: Form, field: usize }, +} + +struct Browser { + dir: PathBuf, + /// Names, directories first, each with whether it is a directory. + entries: Vec<(String, bool)>, + sel: usize, + pick: Pick, +} + +impl Browser { + fn new(dir: PathBuf, pick: Pick) -> Browser { + let mut b = Browser { dir, entries: Vec::new(), sel: 0, pick }; + b.read(); + b + } + + fn read(&mut self) { + let all = matches!(self.pick, Pick::Value { .. }); + let mut entries: Vec<(String, bool)> = std::fs::read_dir(&self.dir) + .map(|rd| { + rd.filter_map(Result::ok) + .filter_map(|e| { + let name = e.file_name().to_string_lossy().to_string(); + let dir = e.path().is_dir(); + (dir || all || name.ends_with(".toml")).then_some((name, dir)) + }) + .filter(|(n, _)| !n.starts_with('.')) + .collect() + }) + .unwrap_or_default(); + entries.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.to_lowercase().cmp(&b.0.to_lowercase()))); + entries.insert(0, ("..".into(), true)); + self.entries = entries; + self.sel = self.sel.min(self.entries.len() - 1); + } + + fn select(&mut self, name: &str) { + if let Some(i) = self.entries.iter().position(|(n, _)| n == name) { + self.sel = i; + } + } + + fn enter_dir(&mut self, name: &str) { + let from = self.dir.file_name().map(|n| n.to_string_lossy().to_string()); + self.dir = if name == ".." { self.dir.parent().map(Path::to_path_buf).unwrap_or_else(|| self.dir.clone()) } else { self.dir.join(name) }; + self.sel = 0; + self.read(); + if let (Some(from), true) = (from, name == "..") { + self.select(&from); + } + } +} + +enum MachineThen { + Set, + New(PathBuf), +} + +enum PromptThen { + NewFile, + SaveAs, +} + +enum ConfirmThen { + Quit, + Open(PathBuf), + /// Save before a run from this directory. + SaveBeforeRun(PathBuf), + /// Run with these problems; the directory to go back to if not. + RunAnyway(PathBuf), + /// Edit this text (which did not read) again, for the open file or the file it is. + Edit(String, Target), +} + +enum Popup { + Types { path: MachineSlotPath, types: Vec<&'static str>, sel: usize }, + Form { form: Form, sel: usize, edit: Option, error: String }, + Machine { sel: usize, then: MachineThen }, + Prompt { title: String, input: Input, then: PromptThen }, + Confirm { text: String, keys: &'static str, then: ConfirmThen }, + Run { dirs: Vec<(String, PathBuf)>, sel: usize }, + Help, +} + +/// What text edited in the user's editor becomes. +#[derive(Clone)] +enum Target { + /// The open file's config. + Doc, + /// The file at this path, which did not read as it was. + File(PathBuf), +} + +/// What the loop does after a key. +enum Flow { + Go, + Exit(Option), + /// Edit this text in the user's editor. + Editor(String, Target), +} + +#[derive(PartialEq)] +enum Screen { + Browse, + Slots, +} + +struct App<'a> { + /// Applied to the first file opened or created, as the command line changes a file. + cli: Option<&'a Cli>, + doc: Option, + screen: Screen, + browser: Browser, + sel: usize, + popup: Option, + status: String, + /// The current config's warnings and problems, recomputed when it changes. + check: (Vec, Vec), +} + +impl<'a> App<'a> { + fn new(cli: &'a Cli) -> Result, String> { + let cwd = std::env::current_dir().map_err(|e| e.to_string())?; + let mut app = App { cli: Some(cli), doc: None, screen: Screen::Browse, browser: Browser::new(cwd, Pick::Open), sel: 0, popup: None, status: String::new(), check: Default::default() }; + app.browser.select(DEFAULT_CONFIG); + if cli.config != DEFAULT_CONFIG { + let path = PathBuf::from(&cli.config); + if path.exists() { + app.open(&path); + } else { + match cli.machine.as_deref().map(MachineProfile::from_name) { + Some(Ok(p)) => app.create(&path, p), + _ => app.popup = Some(Popup::Machine { sel: 0, then: MachineThen::New(path) }), + } + } + } else { + app.status = "Enter opens a file, n makes a new one, ? for help".into(); + } + Ok(app) + } + + fn run(&mut self, term: &mut DefaultTerminal) -> Result, String> { + loop { + term.draw(|f| self.draw(f)).map_err(|e| e.to_string())?; + let Event::Key(k) = event::read().map_err(|e| e.to_string())? else { continue }; + if k.kind != KeyEventKind::Press { + continue; + } + match self.key(k) { + Flow::Go => {} + Flow::Exit(cfg) => return Ok(cfg), + Flow::Editor(text, target) => self.editor(term, text, target), + } + } + } + + // ── documents ────────────────────────────────────────────────────────── + + fn open(&mut self, path: &Path) { + match Doc::open(path, self.cli.take()) { + Ok(doc) => { + self.status = match doc.notes.is_empty() { + true => format!("opened {}", path.display()), + false => format!("opened {}: converted from older keys, saving writes the current ones", path.display()), + }; + self.set_doc(doc); + } + Err(e) => { + let text = std::fs::read_to_string(path).unwrap_or_default(); + self.popup = Some(Popup::Confirm { + text: format!("{} does not read:\n\n{e}", path.display()), + keys: "e: fix it in your editor (the file is written when you save) · Esc: back", + then: ConfirmThen::Edit(text, Target::File(path.to_path_buf())), + }); + } + } + } + + fn create(&mut self, path: &Path, profile: MachineProfile) { + match Doc::create(path, profile, self.cli.take()) { + Ok(doc) => { + self.status = format!("new {} for the {}; s saves it", path.display(), profile.label()); + self.set_doc(doc); + } + Err(e) => self.status = e, + } + } + + fn set_doc(&mut self, doc: Doc) { + self.doc = Some(doc); + self.sel = 0; + self.screen = Screen::Slots; + self.recheck(); + } + + fn recheck(&mut self) { + self.check = self.doc.as_ref().map(Doc::check).unwrap_or_default(); + } + + fn save(&mut self, to: Option) { + if let Some(doc) = &mut self.doc { + self.status = doc.save(to).unwrap_or_else(|e| format!("not saved: {e}")); + } + } + + /// Edit `text` in `$VISUAL`/`$EDITOR` with the terminal handed over, then read it back. + fn editor(&mut self, term: &mut DefaultTerminal, text: String, target: Target) { + let file = std::env::temp_dir().join(format!("iris-tui-{}.toml", std::process::id())); + if let Err(e) = std::fs::write(&file, &text) { + self.status = format!("{}: {e}", file.display()); + return; + } + let editor = std::env::var("VISUAL").or_else(|_| std::env::var("EDITOR")).unwrap_or_else(|_| if cfg!(windows) { "notepad".into() } else { "vi".into() }); + let mut words = editor.split_whitespace(); + ratatui::restore(); + let ran = match words.next() { + Some(cmd) => std::process::Command::new(cmd).args(words).arg(&file).status().map_err(|e| format!("{editor}: {e}")), + None => Err("no editor".into()), + }; + *term = ratatui::init(); + // Erase what the editor left, without asking the terminal where its cursor is (which `clear` does first). + let _ = ratatui::crossterm::execute!(std::io::stdout(), ratatui::crossterm::terminal::Clear(ratatui::crossterm::terminal::ClearType::All)); + let _ = term.clear(); + let edited = ran.and_then(|_| std::fs::read_to_string(&file).map_err(|e| e.to_string())); + let _ = std::fs::remove_file(&file); + let edited = match edited { + Ok(t) => t, + Err(e) => { + self.status = e; + return; + } + }; + if edited == text && matches!(target, Target::Doc) { + self.status = "unchanged".into(); + return; + } + let read = match &target { + Target::Doc => match &mut self.doc { + Some(doc) => doc.set_text(&edited).map(|()| "edited".to_string()), + None => return, + }, + Target::File(path) => Doc::from_text(path, &edited).map(|doc| { + self.set_doc(doc); + format!("{} reads now; s saves it", path.display()) + }), + }; + match read { + Ok(said) => { + self.status = said; + self.recheck(); + } + Err(e) => { + self.popup = Some(Popup::Confirm { text: format!("The text does not read:\n\n{e}"), keys: "e: edit again · Esc: drop the edit", then: ConfirmThen::Edit(edited, target) }) + } + } + } + + // ── keys ─────────────────────────────────────────────────────────────── + + fn key(&mut self, k: KeyEvent) -> Flow { + if k.code == KeyCode::Char('c') && k.modifiers.contains(KeyModifiers::CONTROL) { + return Flow::Exit(None); + } + if let Some(popup) = self.popup.take() { + return self.popup_key(popup, k); + } + match self.screen { + Screen::Browse => self.browse_key(k), + Screen::Slots => self.slots_key(k), + } + } + + fn quit(&mut self) -> Flow { + match self.doc.as_ref().is_some_and(|d| d.dirty) { + true => { + self.popup = Some(Popup::Confirm { text: "Quit without saving?".into(), keys: "y: quit · Esc: stay", then: ConfirmThen::Quit }); + Flow::Go + } + false => Flow::Exit(None), + } + } + + fn browse_key(&mut self, k: KeyEvent) -> Flow { + let n = self.browser.entries.len(); + match k.code { + KeyCode::Up | KeyCode::Char('k') => self.browser.sel = self.browser.sel.saturating_sub(1), + KeyCode::Down | KeyCode::Char('j') => self.browser.sel = (self.browser.sel + 1).min(n - 1), + KeyCode::PageUp => self.browser.sel = self.browser.sel.saturating_sub(10), + KeyCode::PageDown => self.browser.sel = (self.browser.sel + 10).min(n - 1), + KeyCode::Backspace | KeyCode::Left | KeyCode::Char('h') => self.browser.enter_dir(".."), + KeyCode::Enter | KeyCode::Right | KeyCode::Char('l') => { + let (name, dir) = self.browser.entries[self.browser.sel].clone(); + if dir { + self.browser.enter_dir(&name); + } else { + let path = relative(&self.browser.dir.join(&name)); + return self.picked(path); + } + } + KeyCode::Char('n') if matches!(self.browser.pick, Pick::Open) => { + self.popup = Some(Popup::Prompt { title: "New file".into(), input: Input::new("iris.toml"), then: PromptThen::NewFile }); + } + KeyCode::Esc | KeyCode::Tab if self.doc.is_some() || matches!(self.browser.pick, Pick::Value { .. }) => self.leave_browser(None), + KeyCode::Char('?') => self.popup = Some(Popup::Help), + KeyCode::Char('q') | KeyCode::Esc => return self.quit(), + _ => {} + } + Flow::Go + } + + /// A file chosen in the browser. + fn picked(&mut self, path: PathBuf) -> Flow { + match &self.browser.pick { + Pick::Open if self.doc.as_ref().is_some_and(|d| d.dirty) => { + self.popup = Some(Popup::Confirm { text: "Open another file without saving this one?".into(), keys: "y: open · Esc: stay", then: ConfirmThen::Open(path) }); + } + Pick::Open => self.open(&path), + Pick::Value { .. } => self.leave_browser(Some(path)), + } + Flow::Go + } + + /// Back from the browser: to the slots, or to the form whose value it picked. + fn leave_browser(&mut self, value: Option) { + let pick = std::mem::replace(&mut self.browser.pick, Pick::Open); + self.browser.read(); + if let Pick::Value { mut form, field } = pick { + if let Some(v) = value { + form.fields[field].value = v.to_string_lossy().to_string(); + } + self.popup = Some(Popup::Form { form, sel: field, edit: None, error: String::new() }); + } + if self.doc.is_some() { + self.screen = Screen::Slots; + } + } + + fn slots_key(&mut self, k: KeyEvent) -> Flow { + let Some(doc) = &self.doc else { + self.screen = Screen::Browse; + return Flow::Go; + }; + let (rows, unplaced) = doc.rows(); + let n = rows.len() + unplaced.len(); + let row = rows.get(self.sel); + let lost = self.sel.checked_sub(rows.len()).and_then(|i| unplaced.get(i)); + match k.code { + KeyCode::Up | KeyCode::Char('k') => self.sel = self.sel.saturating_sub(1), + KeyCode::Down | KeyCode::Char('j') => self.sel = (self.sel + 1).min(n.saturating_sub(1)), + KeyCode::PageUp => self.sel = self.sel.saturating_sub(10), + KeyCode::PageDown => self.sel = (self.sel + 10).min(n.saturating_sub(1)), + KeyCode::Home => self.sel = 0, + KeyCode::End => self.sel = n.saturating_sub(1), + KeyCode::Enter => { + if let Some(u) = lost { + if let Some(form) = doc.edit_form(Some(u.index), &MachineSlotPath::root()) { + self.popup = Some(Popup::Form { form, sel: 0, edit: None, error: u.error.clone() }); + } + } else if let Some(r) = row { + match &r.content { + Content::Device { index, .. } => match doc.edit_form(*index, &r.path) { + Some(form) => self.popup = Some(Popup::Form { form, sel: 0, edit: None, error: String::new() }), + None => self.status = "nothing to edit here".into(), + }, + Content::Empty if r.open => { + let types = doc.types_for(&r.path); + match types.is_empty() { + true => self.status = format!("{} takes nothing iris models", r.path), + false => self.popup = Some(Popup::Types { path: r.path.clone(), types, sel: 0 }), + } + } + _ => self.status = format!("{} is part of the machine", r.path), + } + } + } + KeyCode::Char('a') => { + if let Some(r) = row.filter(|r| r.open) { + let types = doc.types_for(&r.path); + if !types.is_empty() { + self.popup = Some(Popup::Types { path: r.path.clone(), types, sel: 0 }); + } + } + } + KeyCode::Char('d') | KeyCode::Delete => { + let path = row.map(|r| r.path.clone()); + let doc = self.doc.as_mut().expect("a doc"); + match (lost.map(|u| u.index), row.map(|r| r.content.clone())) { + (Some(i), _) | (None, Some(Content::Device { index: Some(i), default: false, .. })) => { + doc.remove(i); + self.status = "removed".into(); + } + (None, Some(Content::Device { default: true, .. })) => { + doc.leave_empty(&path.expect("a row")); + self.status = "the slot is left empty (a none entry)".into(); + } + _ => self.status = "nothing to remove here".into(), + } + self.recheck(); + } + KeyCode::Char('m') => { + let sel = MachineProfile::ALL.iter().position(|p| *p == doc.cfg.machine.profile).unwrap_or(0); + self.popup = Some(Popup::Machine { sel, then: MachineThen::Set }); + } + KeyCode::Char('e') => match doc.text() { + Ok(text) => return Flow::Editor(text, Target::Doc), + Err(e) => self.status = e, + }, + KeyCode::Char('s') => self.save(None), + KeyCode::Char('S') => { + let name = doc.path.to_string_lossy().to_string(); + self.popup = Some(Popup::Prompt { title: "Save as".into(), input: Input::new(&name), then: PromptThen::SaveAs }); + } + KeyCode::Char('r') => self.popup = Some(Popup::Run { dirs: run_dirs(&doc.path), sel: 0 }), + KeyCode::Char('o') | KeyCode::Tab => { + self.screen = Screen::Browse; + self.browser.read(); + } + KeyCode::Char('?') => self.popup = Some(Popup::Help), + KeyCode::Char('q') | KeyCode::Esc => return self.quit(), + _ => {} + } + Flow::Go + } + + fn popup_key(&mut self, popup: Popup, k: KeyEvent) -> Flow { + let up = matches!(k.code, KeyCode::Up | KeyCode::Char('k')); + let down = matches!(k.code, KeyCode::Down | KeyCode::Char('j')); + match popup { + Popup::Help => {} + Popup::Types { path, types, mut sel } => match k.code { + KeyCode::Enter => { + let form = self.doc.as_ref().expect("a doc").new_form(types[sel], &path); + // The first of the type's own keys: name and at come first. + let first = 2.min(form_len(&form) - 1); + self.popup = Some(Popup::Form { form, sel: first, edit: None, error: String::new() }); + } + KeyCode::Esc => {} + _ => { + if up { + sel = sel.saturating_sub(1); + } else if down { + sel = (sel + 1).min(types.len() - 1); + } + self.popup = Some(Popup::Types { path, types, sel }); + } + }, + Popup::Machine { mut sel, then } => match k.code { + KeyCode::Enter => { + let p = MachineProfile::ALL[sel]; + match then { + MachineThen::Set => { + if let Some(doc) = &mut self.doc { + doc.set_machine(p); + self.status = format!("now a {}; entries that no longer fit are listed at the end", p.label()); + self.sel = 0; + } + self.recheck(); + } + MachineThen::New(path) => self.create(&path, p), + } + } + KeyCode::Esc => {} + _ => { + if up { + sel = sel.saturating_sub(1); + } else if down { + sel = (sel + 1).min(MachineProfile::ALL.len() - 1); + } + self.popup = Some(Popup::Machine { sel, then }); + } + }, + Popup::Form { form, sel, edit, error } => return self.form_key(form, sel, edit, error, k), + Popup::Prompt { title, mut input, then } => match k.code { + KeyCode::Enter => { + let path = PathBuf::from(input.text.trim()); + let path = if path.is_relative() { relative(&self.browser.dir.join(&path)) } else { path }; + match then { + PromptThen::NewFile if path.exists() => self.status = format!("{} exists: open it instead", path.display()), + PromptThen::NewFile => self.popup = Some(Popup::Machine { sel: 0, then: MachineThen::New(path) }), + PromptThen::SaveAs => self.save(Some(path)), + } + } + KeyCode::Esc => {} + _ => { + input.key(k); + self.popup = Some(Popup::Prompt { title, input, then }); + } + }, + Popup::Confirm { text, keys, then } => { + let yes = matches!(k.code, KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Enter) || matches!(then, ConfirmThen::Edit(..)) && k.code == KeyCode::Char('e'); + let no = matches!(k.code, KeyCode::Char('n') | KeyCode::Char('N')); + let back = k.code == KeyCode::Esc; + if !(yes || no || back) { + self.popup = Some(Popup::Confirm { text, keys, then }); + return Flow::Go; + } + match then { + ConfirmThen::SaveBeforeRun(_) if back => {} + ConfirmThen::SaveBeforeRun(dir) => { + if yes { + self.save(None); + if self.doc.as_ref().is_some_and(|d| d.dirty) { + return Flow::Go; + } + } + return self.run_from(dir); + } + ConfirmThen::RunAnyway(dir) if !yes => { + let _ = std::env::set_current_dir(dir); + self.recheck(); + self.status = "not run".into(); + } + _ if !yes => {} + ConfirmThen::Quit => return Flow::Exit(None), + ConfirmThen::Open(path) => self.open(&path), + ConfirmThen::RunAnyway(_) => return self.start(), + ConfirmThen::Edit(text, target) => return Flow::Editor(text, target), + } + } + Popup::Run { dirs, mut sel } => match k.code { + KeyCode::Enter => { + let dir = dirs[sel].1.clone(); + match self.doc.as_ref().is_some_and(|d| d.dirty) { + true => { + self.popup = Some(Popup::Confirm { + text: "Save the file before running?".into(), + keys: "y: save and run · n: run without saving · Esc: back", + then: ConfirmThen::SaveBeforeRun(dir), + }) + } + false => return self.run_from(dir), + } + } + KeyCode::Esc => {} + _ => { + if up { + sel = sel.saturating_sub(1); + } else if down { + sel = (sel + 1).min(dirs.len() - 1); + } + self.popup = Some(Popup::Run { dirs, sel }); + } + }, + } + Flow::Go + } + + fn form_key(&mut self, mut form: Form, mut sel: usize, edit: Option, mut error: String, k: KeyEvent) -> Flow { + let n = form_len(&form); + if let Some(mut input) = edit { + match k.code { + KeyCode::Enter => form.fields[sel].value = input.text, + KeyCode::Esc => {} + _ => { + input.key(k); + self.popup = Some(Popup::Form { form, sel, edit: Some(input), error }); + return Flow::Go; + } + } + self.popup = Some(Popup::Form { form, sel, edit: None, error }); + return Flow::Go; + } + let apply = sel == form.fields.len(); + match k.code { + KeyCode::Esc => { + self.status = "not changed".into(); + return Flow::Go; + } + KeyCode::Up | KeyCode::Char('k') => sel = sel.saturating_sub(1), + KeyCode::Down | KeyCode::Char('j') | KeyCode::Tab => sel = (sel + 1).min(n - 1), + KeyCode::Left | KeyCode::Right if !apply && !form.fields[sel].choices.is_empty() => { + let f = &mut form.fields[sel]; + let at = f.choices.iter().position(|c| *c == f.value); + let len = f.choices.len(); + let next = match (at, k.code == KeyCode::Right) { + (None, true) => 0, + (None, false) => len - 1, + (Some(i), true) => (i + 1) % len, + (Some(i), false) => (i + len - 1) % len, + }; + f.value = f.choices[next].clone(); + } + KeyCode::Char('b') if !apply => { + let start = self.doc.as_ref().and_then(|d| d.path.parent().map(Path::to_path_buf)).filter(|p| !p.as_os_str().is_empty()); + let dir = start.unwrap_or_else(|| self.browser.dir.clone()); + self.browser = Browser::new(std::fs::canonicalize(&dir).unwrap_or(dir), Pick::Value { form, field: sel }); + self.screen = Screen::Browse; + return Flow::Go; + } + KeyCode::Char('a') | KeyCode::Enter if apply || k.code == KeyCode::Char('a') => { + let doc = self.doc.as_mut().expect("a doc"); + match doc.apply(&form) { + Ok(()) => { + self.status = format!("{} written", form.ty); + self.recheck(); + return Flow::Go; + } + Err(e) => error = e, + } + } + KeyCode::Enter => { + let value = form.fields[sel].value.clone(); + self.popup = Some(Popup::Form { form, sel, edit: Some(Input::new(&value)), error }); + return Flow::Go; + } + _ => {} + } + self.popup = Some(Popup::Form { form, sel, edit: None, error }); + Flow::Go + } + + /// Go to `dir` and run there, after a look at what the run would refuse. + fn run_from(&mut self, dir: PathBuf) -> Flow { + let back = std::env::current_dir().unwrap_or_else(|_| dir.clone()); + if let Err(e) = std::env::set_current_dir(&dir) { + self.status = format!("{}: {e}", dir.display()); + return Flow::Go; + } + self.recheck(); + match self.check.1.is_empty() { + true => self.start(), + false => { + let text = format!("From {}, the run would stop at:\n\n{}", dir.display(), self.check.1.iter().map(|p| format!("• {p}")).collect::>().join("\n")); + self.popup = Some(Popup::Confirm { text, keys: "y: run anyway · Esc: back", then: ConfirmThen::RunAnyway(back) }); + Flow::Go + } + } + } + + fn start(&mut self) -> Flow { + Flow::Exit(self.doc.take().map(|d| d.cfg)) + } + + // ── drawing ──────────────────────────────────────────────────────────── + + fn draw(&self, f: &mut Frame) { + let notes = self.notes(); + // Each note as many rows as it wraps to, at most eight in all. + let inner = f.area().width.saturating_sub(2).max(1) as usize; + let rows: usize = notes.iter().map(|l| l.width().div_ceil(inner).max(1)).sum(); + let note_h = if notes.is_empty() { 0 } else { (rows as u16).min(8) + 2 }; + let [head, body, panel, status, foot] = + Layout::vertical([Constraint::Length(1), Constraint::Min(3), Constraint::Length(note_h), Constraint::Length(1), Constraint::Length(1)]).areas(f.area()); + f.render_widget(Paragraph::new(self.header()).style(Style::new().bg(Color::Blue).fg(Color::White)), head); + match self.screen { + Screen::Browse => self.draw_browser(f, body), + Screen::Slots => self.draw_slots(f, body), + } + if !notes.is_empty() { + let title = format!(" checks: {} problem(s), {} warning(s) ", self.check.1.len(), self.check.0.len()); + f.render_widget(Paragraph::new(Text::from(notes)).wrap(Wrap { trim: false }).block(Block::bordered().title(title)), panel); + } + f.render_widget(Paragraph::new(self.status.as_str()), status); + f.render_widget(Paragraph::new(self.footer()).style(Style::new().dim()), foot); + if let Some(p) = &self.popup { + self.draw_popup(f, p); + } + } + + fn header(&self) -> Line<'static> { + match &self.doc { + Some(d) => Line::from(format!(" iris config · {}{} · {}", d.path.display(), if d.dirty { " *" } else { "" }, d.cfg.machine.profile.label())), + None => Line::from(" iris config"), + } + } + + fn footer(&self) -> &'static str { + match (&self.popup, &self.screen) { + (Some(Popup::Form { edit: Some(_), .. }), _) => "type the value · Enter: keep · Esc: undo · Ctrl-U: clear", + (Some(Popup::Form { .. }), _) => "Enter: edit · ←/→: choose · b: browse for a file · a: apply · Esc: cancel", + (Some(_), _) => "↑/↓: choose · Enter: take · Esc: back", + (None, Screen::Browse) if matches!(self.browser.pick, Pick::Value { .. }) => "Enter: take this file · Backspace: up · Esc: back to the form", + (None, Screen::Browse) => "Enter: open · n: new file · Backspace: up · Tab: back · ?: help · q: quit", + (None, Screen::Slots) => "Enter: add/edit · d: remove · m: machine · e: edit as text · s: save · S: save as · r: run · o: files · ?: help · q: quit", + } + } + + fn notes(&self) -> Vec> { + if self.screen != Screen::Slots { + return Vec::new(); + } + let mut lines = Vec::new(); + for p in &self.check.1 { + lines.push(Line::from(format!("✗ {p}")).red()); + } + for w in &self.check.0 { + lines.push(Line::from(format!("! {w}")).yellow()); + } + for n in self.doc.iter().flat_map(|d| &d.notes) { + lines.push(Line::from(format!("i {n}")).cyan()); + } + lines + } + + fn draw_browser(&self, f: &mut Frame, area: Rect) { + let items: Vec = self + .browser + .entries + .iter() + .map(|(name, dir)| match dir { + true => ListItem::new(format!("{name}/")).blue(), + false => ListItem::new(name.clone()), + }) + .collect(); + let title = match self.browser.pick { + Pick::Open => format!(" {} ", self.browser.dir.display()), + Pick::Value { .. } => format!(" choose a file · {} ", self.browser.dir.display()), + }; + let list = List::new(items).block(Block::bordered().title(title)).highlight_style(Style::new().add_modifier(Modifier::REVERSED)); + f.render_stateful_widget(list, area, &mut ListState::default().with_selected(Some(self.browser.sel))); + } + + fn draw_slots(&self, f: &mut Frame, area: Rect) { + let Some(doc) = &self.doc else { return }; + let (rows, unplaced) = doc.rows(); + let width = rows.iter().map(|r| 2 * r.depth + r.label.chars().count()).max().unwrap_or(0) + 2; + let mut items: Vec = rows + .iter() + .map(|r| { + let name = format!("{}{}", " ".repeat(r.depth), r.label); + let pad = " ".repeat(width.saturating_sub(name.chars().count())); + let what = match &r.content { + Content::Builtin(part) => Span::raw(part.clone()), + Content::Device { summary, default: false, .. } => Span::styled(summary.clone(), Style::new().fg(Color::Yellow).add_modifier(Modifier::BOLD)), + Content::Device { summary, default: true, .. } => Span::styled(format!("{summary} (default)"), Style::new().add_modifier(Modifier::DIM)), + Content::Empty if r.open => Span::styled(format!("- takes {}", r.takes), Style::new().add_modifier(Modifier::DIM)), + Content::Empty => Span::styled("-", Style::new().add_modifier(Modifier::DIM)), + }; + ListItem::new(Line::from(vec![Span::raw(name), Span::raw(pad), what])) + }) + .collect(); + for u in &unplaced { + items.push(ListItem::new(Line::from(format!("no slot: {}: {}", u.summary, u.error))).red()); + } + let title = format!(" {} ", doc.cfg.machine.profile.label()); + let list = List::new(items).block(Block::bordered().title(title)).highlight_style(Style::new().add_modifier(Modifier::REVERSED)); + let mut state = ListState::default().with_selected(Some(self.sel.min((rows.len() + unplaced.len()).saturating_sub(1)))); + f.render_stateful_widget(list, area, &mut state); + } + + fn draw_popup(&self, f: &mut Frame, p: &Popup) { + let hl = Style::new().add_modifier(Modifier::REVERSED); + match p { + Popup::Help => { + let area = centred(f.area(), 74, 22); + f.render_widget(Clear, area); + f.render_widget(Paragraph::new(HELP).wrap(Wrap { trim: false }).block(Block::bordered().title(" help · any key closes ")), area); + } + Popup::Types { path, types, sel } => { + let area = centred(f.area(), 44, types.len() as u16 + 2); + f.render_widget(Clear, area); + let list = List::new(types.iter().map(|t| ListItem::new(*t))).block(Block::bordered().title(format!(" add at {path} "))).highlight_style(hl); + f.render_stateful_widget(list, area, &mut ListState::default().with_selected(Some(*sel))); + } + Popup::Machine { sel, .. } => { + let area = centred(f.area(), 52, MachineProfile::ALL.len() as u16 + 2); + f.render_widget(Clear, area); + let items = MachineProfile::ALL.iter().map(|p| ListItem::new(format!("{:<16}{}", p.name(), p.label()))); + let list = List::new(items).block(Block::bordered().title(" machine ")).highlight_style(hl); + f.render_stateful_widget(list, area, &mut ListState::default().with_selected(Some(*sel))); + } + Popup::Form { form, sel, edit, error } => { + let h = form.fields.len() as u16 + 4 + if error.is_empty() { 0 } else { 3 }; + let area = centred(f.area(), 80, h); + f.render_widget(Clear, area); + let kw = form.fields.iter().map(|f| f.key.len()).max().unwrap_or(0); + let mut lines: Vec = Vec::new(); + for (i, fl) in form.fields.iter().enumerate() { + let key = Span::raw(format!(" {: { + let mut l = input.line(); + l.spans.insert(0, key); + l + } + _ => { + let mut spans = vec![key, Span::raw(fl.value.clone())]; + if !fl.choices.is_empty() { + spans.push(Span::styled(format!(" ←/→ {}", fl.choices.join(", ")), Style::new().add_modifier(Modifier::DIM))); + } + Line::from(spans) + } + }; + if i == *sel && edit.is_none() { + line = line.style(hl); + } + lines.push(line); + } + lines.push(Line::from("")); + let apply = Line::from(" [ apply ]"); + lines.push(if *sel == form.fields.len() { apply.style(hl) } else { apply }); + if !error.is_empty() { + lines.push(Line::from("")); + lines.push(Line::from(error.clone()).red()); + } + let title = match form.index { + Some(_) => format!(" {} ", form.ty), + None => format!(" new {} ", form.ty), + }; + f.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }).block(Block::bordered().title(title)), area); + } + Popup::Prompt { title, input, .. } => { + let area = centred(f.area(), 64, 3); + f.render_widget(Clear, area); + f.render_widget(Paragraph::new(input.line()).block(Block::bordered().title(format!(" {title} "))), area); + } + Popup::Confirm { text, keys, .. } => { + let w = 76u16.min(f.area().width); + let inner = w.saturating_sub(2).max(1) as usize; + let lines: usize = text.lines().map(|l| l.chars().count().div_ceil(inner).max(1)).sum(); + let h = (lines as u16 + 4).min(f.area().height); + let area = centred(f.area(), w, h); + f.render_widget(Clear, area); + let mut t = Text::from(text.clone()); + t.lines.push(Line::from("")); + t.lines.push(Line::from(*keys).dim()); + f.render_widget(Paragraph::new(t).wrap(Wrap { trim: false }).block(Block::bordered()), area); + } + Popup::Run { dirs, sel } => { + let area = centred(f.area(), 80, dirs.len() as u16 + 4); + f.render_widget(Clear, area); + let items = dirs.iter().map(|(what, d)| ListItem::new(format!("{what}: {}", d.display()))); + let list = List::new(items).block(Block::bordered().title(" run from · paths in the file are relative to it ")).highlight_style(hl); + f.render_stateful_widget(list, area, &mut ListState::default().with_selected(Some(*sel))); + } + } + } +} + +const HELP: &str = "\ +Files: Enter opens a .toml file or a directory, Backspace goes up, n makes a new file (after asking which machine). + +Slots: the machine's slots, with what is in each: yellow is the file's own, dim the machine's default. \ +Enter on an empty slot adds a device of a type that fits there; on a device it edits the entry (a default becomes \ +an entry of the file). d removes an entry, or leaves a default's slot empty. Entries that found no slot are listed \ +in red at the end. + +m changes the machine. e edits the whole file as text in $VISUAL or $EDITOR. s saves (the first save over a file \ +keeps the original as .bak; comments are not kept), S saves under another name. + +r runs: choose the directory to run from, since paths in the file are relative to it. The builder closes, the \ +machine starts as it would from the file, and the terminal becomes the monitor. + +A value is TOML when it reads as TOML, else a string: a path needs no quotes."; + +/// The rows a form has: its fields, then apply. +fn form_len(form: &Form) -> usize { + form.fields.len() + 1 +} + +/// A box `w` by `h` in the middle of `area`. +fn centred(area: Rect, w: u16, h: u16) -> Rect { + let w = w.min(area.width); + let h = h.min(area.height); + Rect { x: area.x + (area.width - w) / 2, y: area.y + (area.height - h) / 2, width: w, height: h } +} + +/// `path` relative to the current directory when it is under it. +fn relative(path: &Path) -> PathBuf { + let cwd = std::env::current_dir().ok().and_then(|c| std::fs::canonicalize(c).ok()); + let full = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()); + match cwd.as_ref().and_then(|c| full.strip_prefix(c).ok()) { + Some(rel) if !rel.as_os_str().is_empty() => rel.to_path_buf(), + _ => full, + } +} + +/// Where a run can start: the current directory, the file's directory and the iris checkout above either. +fn run_dirs(config: &Path) -> Vec<(String, PathBuf)> { + let cwd = std::env::current_dir().ok().and_then(|c| std::fs::canonicalize(c).ok()); + let file = std::fs::canonicalize(config).ok().and_then(|p| p.parent().map(Path::to_path_buf)); + let root = [cwd.clone(), file.clone()].into_iter().flatten().find_map(|d| d.ancestors().find(|a| is_iris_root(a)).map(Path::to_path_buf)); + let mut dirs: Vec<(String, PathBuf)> = Vec::new(); + for (what, d) in [("the current directory", cwd), ("the file's directory", file), ("the iris checkout", root)] { + if let Some(d) = d.filter(|d| !dirs.iter().any(|(_, x)| x == d)) { + dirs.push((what.to_string(), d)); + } + } + dirs +} + +fn is_iris_root(dir: &Path) -> bool { + std::fs::read_to_string(dir.join("Cargo.toml")).is_ok_and(|t| t.lines().any(|l| l.trim() == "name = \"iris\"")) +} diff --git a/src/tui/model.rs b/src/tui/model.rs new file mode 100644 index 000000000..0b1e2d456 --- /dev/null +++ b/src/tui/model.rs @@ -0,0 +1,478 @@ +//! The configuration builder's model: the open file, its machine's slots and what is in each, and the edits a user +//! makes. No terminal here; `super` draws it. + +use std::path::{Path, PathBuf}; + +use crate::config::{Cli, Dump, GraphicsBoard, MachineConfig, MachineProfile}; +use crate::devices::{ConfiguredDevice, DeviceModel, DEVICE_TYPES}; +use crate::slot_path::MachineSlotPath; +use crate::topology::{DeviceFamily, DevicePlacement, MachineSlotKind}; + +/// The file being edited. +pub struct Doc { + pub path: PathBuf, + pub cfg: MachineConfig, + /// Changed since it was opened or saved. + pub dirty: bool, + /// What reading the file said: older keys it turned into their current form, a device with no slot. + pub notes: Vec, + /// Whether a save would replace a file that is there, and whether that file has been kept as `.bak`. + exists: bool, + backed_up: bool, +} + +/// What a slot holds. +#[derive(Clone, Debug, PartialEq)] +pub enum Content { + /// A part of the board, which takes nothing itself. + Builtin(String), + /// A device: an entry of the config (its index in `cfg.devices`), or one the machine adds when `index` is `None`. + /// `default` when the user did not choose it. + Device { index: Option, summary: String, default: bool }, + Empty, +} + +/// One line of the slot tree. +#[derive(Clone, Debug)] +pub struct SlotRow { + pub path: MachineSlotPath, + pub depth: usize, + /// The slot's step under its parent, with its aliases. + pub label: String, + pub content: Content, + /// What the slot takes, as `--list-slots` says it. + pub takes: String, + /// Whether a device can be put here. + pub open: bool, +} + +/// An entry of the file that found no slot. +#[derive(Clone, Debug)] +pub struct Unplaced { + pub index: usize, + pub summary: String, + pub error: String, +} + +/// A device entry being written: its type, and a line per key. +#[derive(Clone, Debug)] +pub struct Form { + pub ty: &'static str, + /// The entry it replaces, `None` for a new one. + pub index: Option, + pub fields: Vec, +} + +#[derive(Clone, Debug)] +pub struct Field { + pub key: String, + /// As typed: TOML when it reads as TOML, else a string (as `--device` reads a value). + pub value: String, + /// The values the key takes, when there are few. + pub choices: Vec, +} + +impl Doc { + /// Read `path`, with the command line's changes when `cli` is given. + pub fn open(path: &Path, cli: Option<&Cli>) -> Result { + let cfg = MachineConfig::try_load(&path.to_string_lossy())?; + let cfg = match cli { + Some(cli) => cli.apply(cfg), + None => cfg, + }; + Ok(Doc::settled(path, cfg, true)) + } + + /// The file at `path` as `text`, fixed by hand after it did not read; it is written when saved. + pub fn from_text(path: &Path, text: &str) -> Result { + let cfg = MachineConfig::from_toml_str(text).map_err(|e| e.message().to_string())?; + cfg.clone().resolved()?; + let mut doc = Doc::settled(path, cfg, path.exists()); + doc.dirty = true; + Ok(doc) + } + + /// A new file for `profile` at `path`, which is not written until it is saved. + pub fn create(path: &Path, profile: MachineProfile, cli: Option<&Cli>) -> Result { + let cfg = MachineConfig::from_toml_str(&format!("[machine]\nprofile = \"{}\"\n", profile.name())).map_err(|e| e.message().to_string())?; + let cfg = match cli { + Some(cli) => cli.apply(cfg), + None => cfg, + }; + let mut doc = Doc::settled(path, cfg, path.exists()); + doc.dirty = true; + Ok(doc) + } + + fn settled(path: &Path, cfg: MachineConfig, exists: bool) -> Doc { + let mut doc = Doc { path: path.to_path_buf(), cfg, dirty: false, notes: Vec::new(), exists, backed_up: false }; + doc.settle(); + if !doc.cfg.old_keys.is_empty() { + doc.notes.push(format!("converted from older keys ({}); saving writes the current ones", doc.cfg.old_keys.join(", "))); + } + doc + } + + /// Fold the older card flags into entries, as a run does. A device with no slot is shown, not refused. + fn settle(&mut self) { + let _ = self.cfg.resolve_slots(); + } + + fn placement(&self) -> DevicePlacement { + DevicePlacement::lenient(&self.cfg, &self.cfg.devices) + } + + /// The machine's slots, each with what is in it, and the entries that found none. + pub fn rows(&self) -> (Vec, Vec) { + let p = self.placement(); + let n = self.cfg.devices.len(); + let mut held = std::collections::HashMap::new(); + let mut unplaced = Vec::new(); + for (d, path) in p.placed() { + held.entry(path.clone()).or_insert((d.clone(), d.default)); + } + for idx in 0..n { + if let Some(error) = p.error(idx) { + unplaced.push(Unplaced { index: idx, summary: self.cfg.devices[idx].device.summary(), error: error.to_string() }); + } + } + let entry_at = |path: &MachineSlotPath| (0..n).find(|&i| p.at(i) == Some(path)); + let mut rows: Vec = Vec::new(); + for s in &p.slots { + let parent = rows.iter().rposition(|r| s.path.starts_with(&r.path) && r.path != s.path); + let depth = parent.map_or(0, |i| rows[i].depth + 1); + let full = s.path.to_string(); + let step = match parent.map(|i| rows[i].path.to_string()) { + Some(up) if !up.is_empty() => full.strip_prefix(&format!("{up}/")).unwrap_or(&full).to_string(), + _ => full.clone(), + }; + let label = if s.aliases.is_empty() { step } else { format!("{step} ({})", s.aliases.join(", ")) }; + let content = match (&s.kind, held.get(&s.path)) { + (MachineSlotKind::Fixed(part) | MachineSlotKind::ScsiBus { part, .. } | MachineSlotKind::PciBus(part), _) => Content::Builtin(part.to_string()), + (_, Some((d, default))) => Content::Device { index: entry_at(&s.path), summary: d.device.summary(), default: *default }, + (_, None) => Content::Empty, + }; + let open = matches!(s.kind, MachineSlotKind::Open(f) if !f.is_empty()) || matches!(s.kind, MachineSlotKind::Extra { .. }); + rows.push(SlotRow { path: s.path.clone(), depth, label, content, takes: s.label(), open }); + } + (rows, unplaced) + } + + /// The device types that go in the slot at `path`. + pub fn types_for(&self, path: &MachineSlotPath) -> Vec<&'static str> { + let p = self.placement(); + let Some(slot) = p.slot(path) else { return Vec::new() }; + let boards: Vec = [slot.boards, slot.named].concat(); + DEVICE_TYPES + .iter() + .filter(|t| match t.family { + DeviceFamily::Gfx => boards.iter().any(|b| b.family() == t.name), + DeviceFamily::Empty => false, + family => slot.kind.takes(family, true), + }) + .map(|t| t.name) + .collect() + } + + /// A form for a new device of type `ty` at `path`. + pub fn new_form(&self, ty: &'static str, path: &MachineSlotPath) -> Form { + let mut form = Form { ty, index: None, fields: Vec::new() }; + form.fields.push(field("name", String::new(), Vec::new())); + form.fields.push(field("at", path.to_string(), Vec::new())); + let spec = DEVICE_TYPES.iter().find(|t| t.name == ty).expect("a device type"); + for key in spec.keys() { + form.fields.push(field(key, String::new(), self.choices(ty, key, Some(path)))); + } + form + } + + /// A form for entry `index`, or for the machine's default device at `path` (which becomes an entry when applied). + pub fn edit_form(&self, index: Option, path: &MachineSlotPath) -> Option
{ + let dev = match index { + Some(i) => self.cfg.devices.get(i)?.clone(), + None => { + let p = self.placement(); + let (d, _) = p.placed().find(|(_, at)| *at == path)?; + ConfiguredDevice { at: Some(path.to_string()), default: false, ..d.clone() } + } + }; + let ty = dev.device.spec().name; + let table = toml::Table::try_from(&dev).ok()?; + let mut form = Form { ty, index, fields: Vec::new() }; + for key in ["name", "at"].into_iter().chain(dev.device.spec().keys().iter().copied()) { + let value = table.get(key).map(shown).unwrap_or_default(); + form.fields.push(field(key, value, self.choices(ty, key, Some(path)))); + } + Some(form) + } + + fn choices(&self, ty: &str, key: &str, path: Option<&MachineSlotPath>) -> Vec { + match key { + "model" => { + let fits = path.and_then(|p| self.placement().slot(p).map(|s| [s.boards, s.named].concat())); + GraphicsBoard::ALL + .into_iter() + .filter(|b| b.family() == ty && fits.as_ref().is_none_or(|f| f.contains(b))) + .map(|b| b.as_str().to_string()) + .collect() + } + "overlay" | "scratch" | "write_cache" | "readonly" => vec!["true".into(), "false".into()], + _ => Vec::new(), + } + } + + /// Write `form` into the file: the entry it edits, or a new one. + pub fn apply(&mut self, form: &Form) -> Result<(), String> { + let mut t = toml::Table::new(); + t.insert("type".into(), form.ty.into()); + for f in &form.fields { + let v = f.value.trim(); + if !v.is_empty() { + t.insert(f.key.clone(), value(v)); + } + } + let dev = ConfiguredDevice::from_table(t)?; + let written = toml::Table::try_from(&dev).ok(); + let (before, dirty) = (self.cfg.clone(), self.dirty); + match form.index { + Some(i) => self.cfg.devices[i] = dev, + None => self.cfg.devices.push(dev), + } + self.changed(); + // Refused where it cannot go (a taken slot, a bad name), with the config as it was. + let p = self.placement(); + let at = self.cfg.devices.iter().position(|d| toml::Table::try_from(d).ok() == written); + if let Some(e) = at.and_then(|i| p.error(i)) { + let e = e.to_string(); + (self.cfg, self.dirty) = (before, dirty); + return Err(e); + } + Ok(()) + } + + /// Take entry `index` out of the file. Without the last entry it is a file that names no device, and gets the + /// default disks as it would when read. + pub fn remove(&mut self, index: usize) { + self.cfg.devices.remove(index); + if self.cfg.devices.is_empty() { + self.cfg.devices = MachineConfig::default().devices; + } + self.changed(); + } + + /// Leave the slot at `path` empty where the machine would put a default there. + pub fn leave_empty(&mut self, path: &MachineSlotPath) { + self.cfg.devices.push(ConfiguredDevice::new(&path.to_string(), DeviceModel::Empty)); + self.changed(); + } + + pub fn set_machine(&mut self, profile: MachineProfile) { + self.cfg.machine.profile = profile; + self.changed(); + } + + fn changed(&mut self) { + // As a file is read: the default disks only when it names no device of its own. + if self.cfg.devices.iter().any(|d| !d.default) { + self.cfg.devices.retain(|d| !d.default); + } + self.settle(); + self.dirty = true; + } + + /// The file as a save writes it: current spellings, only what differs from the machine's defaults. + pub fn text(&self) -> Result { + self.cfg.to_toml(Dump::Minimal) + } + + /// Replace the whole config with `text`, as edited by hand. + pub fn set_text(&mut self, text: &str) -> Result<(), String> { + let cfg = MachineConfig::from_toml_str(text).map_err(|e| e.message().to_string())?; + cfg.clone().resolved()?; + self.cfg = cfg; + self.changed(); + Ok(()) + } + + /// Whether saving to the file it was opened from would replace one. + pub fn replaces(&self) -> bool { + self.exists && !self.backed_up + } + + /// Save to `to` (the file's own path when `None`). Replacing the file it was opened from keeps that one as `.bak` + /// the first time. Says what it did. + pub fn save(&mut self, to: Option) -> Result { + let text = self.text()?; + let path = to.unwrap_or_else(|| self.path.clone()); + let mut said = format!("saved {}", path.display()); + if path == self.path && self.replaces() { + let bak = PathBuf::from(format!("{}.bak", path.display())); + std::fs::copy(&path, &bak).map_err(|e| format!("{}: {e}", bak.display()))?; + self.backed_up = true; + said += &format!(" (the original is {})", bak.display()); + } else if path != self.path && path.exists() { + return Err(format!("{} exists", path.display())); + } + std::fs::write(&path, text).map_err(|e| format!("{}: {e}", path.display()))?; + if path != self.path { + self.path = path; + self.backed_up = true; + } + self.exists = true; + self.dirty = false; + Ok(said) + } + + /// What a run would say of the config, from the current directory: warnings, then problems. + pub fn check(&self) -> (Vec, Vec) { + let mut cfg = self.cfg.clone(); + let mut problems = Vec::new(); + if let Err(e) = cfg.resolve_slots() { + problems.push(e); + return (Vec::new(), problems); + } + problems.extend(crate::validate_config::problems(&cfg)); + (crate::validate_config::warnings(&cfg), problems) + } +} + +fn field(key: &str, value: String, choices: Vec) -> Field { + Field { key: key.to_string(), value, choices } +} + +/// A value as a form shows it: a string bare, anything else as TOML. +fn shown(v: &toml::Value) -> String { + match v { + toml::Value::String(s) => s.clone(), + v => v.to_string(), + } +} + +/// A value as typed: TOML when it reads as TOML, else a string, so a path needs no quotes. +fn value(v: &str) -> toml::Value { + toml::from_str::(&format!("v = {v}")).ok().and_then(|mut t| t.remove("v")).unwrap_or_else(|| v.into()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn indy(devices: &str) -> Doc { + let cfg = MachineConfig::from_toml_str(&format!("[machine]\nprofile = \"indy_ip24\"\n{devices}")).unwrap(); + Doc::settled(Path::new("t.toml"), cfg, false) + } + + fn row<'a>(rows: &'a [SlotRow], path: &str) -> &'a SlotRow { + rows.iter().find(|r| r.path.to_string() == path).unwrap_or_else(|| panic!("no slot {path}")) + } + + /// The tree has the machine's slots, built-in parts, entries and defaults, each under its parent. + #[test] + fn rows_show_what_each_slot_holds() { + let doc = indy("[[devices]]\ntype = \"hdd\"\nat = \"scsi0/t2\"\npath = \"irix.img\"\n"); + let (rows, unplaced) = doc.rows(); + assert!(unplaced.is_empty()); + assert_eq!(row(&rows, "hpc3/c0").content, Content::Builtin("wd33c93a".into())); + assert_eq!(row(&rows, "hpc3/c0/t2").content, Content::Device { index: Some(0), summary: "hdd irix.img".into(), default: false }); + assert_eq!(row(&rows, "hpc3/c0/t2").depth, row(&rows, "hpc3/c0").depth + 1); + assert!(matches!(row(&rows, "gfx").content, Content::Device { index: None, default: true, .. }), "the Newport is the machine's"); + assert_eq!(row(&rows, "hpc3/c0/t3").content, Content::Empty); + assert!(row(&rows, "hpc3/c0/t3").open); + } + + /// An empty SCSI target offers the SCSI types, the graphics slot the boards that fit it. + #[test] + fn a_slot_offers_the_types_that_fit() { + let doc = indy(""); + let t3: MachineSlotPath = "hpc3/c0/t3".parse().unwrap(); + assert_eq!(doc.types_for(&t3), ["hdd", "cdrom", "daynaport"]); + let gfx: MachineSlotPath = "gfx".parse().unwrap(); + assert!(doc.types_for(&gfx).contains(&"newport")); + assert!(doc.types_for(&gfx).contains(&"express")); + assert!(!doc.types_for(&gfx).contains(&"vpro")); + } + + /// A form adds an entry, edits it, and a removal takes it out; a bad value is refused with its reason. + #[test] + fn forms_add_edit_and_remove_entries() { + let mut doc = indy(""); + let t3: MachineSlotPath = "hpc3/c0/t3".parse().unwrap(); + let mut form = doc.new_form("hdd", &t3); + form.fields.iter_mut().find(|f| f.key == "path").unwrap().value = "disk.raw".into(); + doc.apply(&form).unwrap(); + assert!(doc.dirty); + let (rows, _) = doc.rows(); + assert_eq!(row(&rows, "hpc3/c0/t3").content, Content::Device { index: Some(0), summary: "hdd disk.raw".into(), default: false }); + // A file with a disk of its own gets no default disks, as when it is read back. + assert_eq!(row(&rows, "hpc3/c0/t1").content, Content::Empty); + assert_eq!(MachineConfig::from_toml_str(&doc.text().unwrap()).unwrap().devices.len(), 1); + let mut form = doc.edit_form(Some(0), &t3).unwrap(); + assert_eq!(form.fields.iter().find(|f| f.key == "path").unwrap().value, "disk.raw"); + form.fields.iter_mut().find(|f| f.key == "overlay").unwrap().value = "true".into(); + doc.apply(&form).unwrap(); + assert!(doc.text().unwrap().contains("overlay = true"), "{}", doc.text().unwrap()); + form.fields.iter_mut().find(|f| f.key == "size_mb").unwrap().value = "\"big\"".into(); + assert!(doc.apply(&form).is_err()); + // An entry that cannot be placed is refused, and the config is as it was. + let mut bad = doc.new_form("cdrom", &"hpc3/c0/t3".parse().unwrap()); + bad.fields.iter_mut().find(|f| f.key == "name").unwrap().value = "Not.A.Name".into(); + let before = doc.cfg.devices.len(); + assert!(doc.apply(&bad).unwrap_err().contains("name")); + assert_eq!(doc.cfg.devices.len(), before); + doc.remove(0); + assert_eq!(row(&doc.rows().0, "hpc3/c0/t3").content, Content::Empty); + assert!(matches!(row(&doc.rows().0, "hpc3/c0/t1").content, Content::Device { default: true, .. }), "no entries: the defaults again"); + } + + /// Editing the machine's default board makes it an entry; changing the machine leaves a device that no longer fits unplaced. + #[test] + fn defaults_become_entries_and_a_new_machine_flags_misfits() { + let mut doc = indy(""); + let gfx: MachineSlotPath = "gfx".parse().unwrap(); + let form = doc.edit_form(None, &gfx).unwrap(); + assert_eq!(form.ty, "newport"); + doc.apply(&form).unwrap(); + assert_eq!(doc.cfg.devices.iter().filter(|d| !d.default).count(), 1); + let mut doc = indy("[[devices]]\ntype = \"hdd\"\nat = \"scsi0/t2\"\npath = \"irix.img\"\n"); + doc.set_machine(MachineProfile::O2Ip32); + let (_, unplaced) = doc.rows(); + assert_eq!(unplaced.len(), 0, "scsi0/t2 exists on the O2 too"); + let mut doc = indy("[[devices]]\ntype = \"express\"\nmodel = \"xz\"\n"); + doc.set_machine(MachineProfile::O2Ip32); + assert_eq!(doc.rows().1.len(), 1, "the O2 takes no GR2"); + } + + /// A file in the older spellings reads into the current ones, and saving writes those, keeping the original as .bak. + #[test] + fn old_files_are_converted_and_kept() { + let dir = std::env::temp_dir().join(format!("iris-tui-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("old.toml"); + std::fs::write(&path, "[machine]\nprofile = \"indy_ip24\"\n\n[scsi.2]\npath = \"irix.img\"\n").unwrap(); + let mut doc = Doc::open(&path, None).unwrap(); + assert!(!doc.notes.is_empty(), "the older key is reported"); + assert!(doc.replaces()); + let said = doc.save(None).unwrap(); + assert!(said.contains(".bak"), "{said}"); + let text = std::fs::read_to_string(&path).unwrap(); + assert!(text.contains("type = \"hdd\"") && !text.contains("[scsi"), "{text}"); + assert!(std::fs::read_to_string(dir.join("old.toml.bak")).unwrap().contains("[scsi.2]")); + assert!(!doc.replaces(), "the .bak is made once"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// Hand-edited text replaces the config; text that does not read is refused and the config stays. + #[test] + fn text_edits_replace_the_config() { + let mut doc = indy(""); + let text = doc.text().unwrap().replace("indy_ip24", "indigo2_ip22"); + doc.set_text(&text).unwrap(); + assert_eq!(doc.cfg.machine.profile, MachineProfile::Indigo2Ip22); + assert!(doc.set_text("[machine]\nprofile = \"nope\"\n").is_err()); + assert_eq!(doc.cfg.machine.profile, MachineProfile::Indigo2Ip22); + // `devices = []` is a machine with no disks, and stays one. + doc.set_text("devices = []\n[machine]\nprofile = \"indy_ip24\"\n").unwrap(); + assert!(doc.cfg.devices.is_empty()); + assert!(doc.text().unwrap().contains("devices = []"), "{}", doc.text().unwrap()); + } +}