From 16db9400e194a5de72b9153c0e9779433d984365 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 10:44:52 -0800 Subject: [PATCH 01/14] craft-audio: repair_wav rewrites the sizes of a WAV left unfinished by a crash A recorder that writes the WAV header first and rewrites it as the file grows leaves stale RIFF, data, ds64 and fact sizes when the process dies. repair_wav walks the chunks up to the data chunk, counts the whole frames the file holds and rewrites those fields in place, keeping bext and every other chunk. It writes the pad byte an odd data length needs, turns a file past 4 GiB into RF64 when it starts with the JUNK chunk FileEncoder and wav_float_header reserve, and returns the frame count and the length to truncate the file to. A finished file is left as it is. Compressed formats, headers whose block size does not match the channels and bit depth, and unfinished 8-bit mono data of even length (where a pad byte cannot be told from a sample) are refused. --- crates/audio/README.md | 2 +- crates/audio/src/lib.rs | 6 +- crates/audio/src/write/mod.rs | 45 ++++++++ crates/audio/src/write/wav.rs | 150 ++++++++++++++++++++++++- crates/audio/tests/audio/roundtrip.rs | 156 ++++++++++++++++++++++++++ 5 files changed, 354 insertions(+), 5 deletions(-) diff --git a/crates/audio/README.md b/crates/audio/README.md index bd80b54069..7c01fddd1f 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -31,7 +31,7 @@ No default features. The shared types (`AudioBuffer`, `AudioInfo`, `ChannelLayou | `symphonia` | the fallback for formats with no native decoder; turning it on is the same as `decode` | `decode-native`, symphonia | | `encode` | every encoder, and every format of `encode` and `FileEncoder` | `lossless-encode`, `aac-encode`, `alac-encode`, `ac3-encode`, `eac3-encode`, `mp3-encode`, `opus-encode`, `vorbis-encode` | | `lossless-encode` | WAV, AIFF and FLAC writing | `pcm-encode`, `flac-encode` | -| `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`; `pcm_wav_file`, `pcm_wav_header`, `pcm_aiff_file`, `pcm_aiff_header` (minimal files around integer PCM bytes, for essence embedded in AAF / OMF) | none | +| `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`; `repair_wav` (size fields of a WAV left unfinished by a crash); `pcm_wav_file`, `pcm_wav_header`, `pcm_aiff_file`, `pcm_aiff_header` (minimal files around integer PCM bytes, for essence embedded in AAF / OMF) | none | | `flac-decode` | `flac::decode` (whole `.flac` files) and `flac::Decoder` (single frames, for callers that demux FLAC themselves); native, CRC-checked, 4 to 32 bits. `decode` still uses symphonia for FLAC files | none | | `flac-encode` | `encode`, `FileEncoder` for FLAC; `flac::Encoder`, the packet encoder for callers that mux FLAC themselves | craft-media `bitstream` | | `aac-decode`, `aac-encode` | `aac::Decoder`, `aac::Encoder`; with `aac-decode`, `aac::latm_config` / `latm_split` for LOAS / LATM frames (AAC in MPEG transport streams); with `aac-encode`, `encode`, `FileEncoder` for AAC in M4A | craft-media `bitstream`; `aac-encode` also `isobmff` | diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index fcaf2897e1..4197cf0f71 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -19,7 +19,7 @@ //! - [`TrackDecoder`] (any decoder feature): one track's packets from any demuxer to planar //! `f32` in WAV channel order. //! - [`encode`], [`FileEncoder`]: WAV/BWF/RF64 and AIFF/AIFF-C (feature `pcm-encode`, which also -//! gives [`wav_float_header`]), FLAC (feature `flac-encode`), AAC-LC and ALAC in M4A +//! gives [`wav_float_header`] and [`repair_wav`]), FLAC (feature `flac-encode`), AAC-LC and ALAC in M4A //! (`aac-encode`, `alac-encode`) and MP3, AC-3 and E-AC-3 streams (`mp3-encode`, `ac3-encode`, //! `eac3-encode`), whole-buffer or incremental into any `Write + Seek`. Feature //! `lossless-encode` turns on WAV, AIFF and FLAC; feature `encode` turns on every format and encoder. @@ -162,8 +162,6 @@ pub use track::{LOOKAHEAD_PACKETS, TrackDecoder}; feature = "eac3-encode" ))] pub use write::FileEncoder; -#[cfg(feature = "pcm-encode")] -pub use write::wav_float_header; #[cfg(any( feature = "pcm-encode", feature = "flac-encode", @@ -176,6 +174,8 @@ pub use write::wav_float_header; ))] pub use write::{ENCODE_EXTENSIONS, encode, encode_format_for}; #[cfg(feature = "pcm-encode")] +pub use write::{WavRepair, repair_wav, wav_float_header}; +#[cfg(feature = "pcm-encode")] pub use write::{pcm_aiff_file, pcm_aiff_header, pcm_wav_file, pcm_wav_header}; /// Errors from probing, decoding and encoding. diff --git a/crates/audio/src/write/mod.rs b/crates/audio/src/write/mod.rs index a2043d2797..384465f135 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -455,6 +455,51 @@ pub fn wav_float_header(sample_rate: u32, channels: u16, frames: u64) -> Result< wav::header(usize::from(channels), sample_rate, (32, true), None, None, frames, false) } +/// What [`repair_wav`] wrote into a file. +#[cfg(feature = "pcm-encode")] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct WavRepair { + /// The whole frames the data chunk holds. + pub frames: u64, + /// The length of the repaired file. Bytes past it are a partial last frame; truncate the + /// file to this length (`File::set_len`) to drop them. + pub len: u64, +} + +/// Rewrites the size fields of a PCM or float WAV whose writer stopped before finishing it, such +/// as a recorder's file after a crash, for the whole frames the file holds. Every chunk before the +/// data (`bext`, `fmt `, `fact` and others) keeps its contents, and a file that grew past 4 GiB +/// becomes RF64 when it starts with the 28-byte `JUNK` chunk that [`FileEncoder`] and +/// [`wav_float_header`] write. The file must end in its data chunk: everything after the data +/// chunk's header counts as samples, whatever its size field says. +/// +/// Errors: [`AudioError::Malformed`] when `file` is not a WAV or has no `fmt ` or data chunk, +/// [`AudioError::Unsupported`] for a compressed format and for unfinished 8-bit mono data of even +/// length (its last byte may be a sample or a pad byte), and [`AudioError::TooLarge`] for a RIFF +/// file past 4 GiB with no room for a `ds64` chunk. +/// +/// ``` +/// use craft_audio::{repair_wav, wav_float_header}; +/// use std::io::Cursor; +/// +/// // A recorder wrote the header for 0 frames, then 2 frames and part of a third, then stopped. +/// let mut bytes = wav_float_header(48_000, 2, 0).unwrap(); +/// bytes.extend([0.25f32, -0.25, 0.5, -0.5, 0.75].iter().flat_map(|s| s.to_le_bytes())); +/// let mut file = Cursor::new(bytes); +/// let repaired = repair_wav(&mut file).unwrap(); +/// assert_eq!(repaired.frames, 2); +/// let mut bytes = file.into_inner(); +/// bytes.truncate(repaired.len as usize); +/// let header = wav_float_header(48_000, 2, 2).unwrap(); +/// assert_eq!(bytes[..header.len()], header[..]); +/// ``` +#[cfg(feature = "pcm-encode")] +pub fn repair_wav(file: &mut F) -> Result { + let (frames, len) = wav::repair(file)?; + Ok(WavRepair { frames, len }) +} + // With only one of `pcm-encode` and `flac-encode`, the other's formats are refused, not silently // written as something else. #[cfg(all(test, any(feature = "pcm-encode", feature = "flac-encode"), not(all(feature = "pcm-encode", feature = "flac-encode"))))] diff --git a/crates/audio/src/write/wav.rs b/crates/audio/src/write/wav.rs index 96ba532510..3c8f08f1d0 100644 --- a/crates/audio/src/write/wav.rs +++ b/crates/audio/src/write/wav.rs @@ -4,7 +4,7 @@ use super::pcm::{Quantizer, sample_format, validate_buffer, validate_layout, write_interleaved}; use crate::wav::{GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM}; use crate::{AudioBuffer, AudioError, BitDepth, BwfInfo, Result}; -use std::io::{Cursor, Seek, SeekFrom, Write}; +use std::io::{Cursor, ErrorKind, Read, Seek, SeekFrom, Write}; const BEXT_MIN_LEN: usize = 602; @@ -239,3 +239,151 @@ pub(crate) fn header( head.extend_from_slice(&(if rf64 { u32::MAX } else { data_len as u32 }).to_le_bytes()); Ok(head) } + +/// Where the size fields of a WAV sit, from a walk of its chunks up to `data`. +struct Layout { + rf64: bool, + /// The body of the `ds64` chunk, or of a 28-byte `JUNK` chunk right after `WAVE` that can + /// become one. + ds64: Option, + junk: bool, + fact: Option, + block_align: u64, + data: u64, +} + +fn read_at(file: &mut F, pos: u64, buf: &mut [u8]) -> Result { + file.seek(SeekFrom::Start(pos))?; + match file.read_exact(buf) { + Ok(()) => Ok(true), + Err(e) if e.kind() == ErrorKind::UnexpectedEof => Ok(false), + Err(e) => Err(e.into()), + } +} + +fn write_at(file: &mut F, pos: u64, bytes: &[u8]) -> Result<()> { + file.seek(SeekFrom::Start(pos))?; + file.write_all(bytes)?; + Ok(()) +} + +/// The block size of a PCM or float `fmt ` chunk body at `pos` of `size` bytes. +fn pcm_block_align(file: &mut F, pos: u64, size: u32) -> Result { + let mut fmt = [0u8; 40]; + let n = if size >= 40 { 40 } else { 16 }; + if size < 16 || !read_at(file, pos, &mut fmt[..n])? { + return Err(AudioError::Malformed("WAV fmt chunk is cut short".into())); + } + let field = |at: usize| u16::from_le_bytes([fmt[at], fmt[at + 1]]); + let mut tag = field(0); + if tag == WAVE_FORMAT_EXTENSIBLE && n == 40 && fmt[26..] == GUID_TAIL { + tag = field(24); + } + if tag != WAVE_FORMAT_PCM && tag != WAVE_FORMAT_IEEE_FLOAT { + return Err(AudioError::Unsupported(format!("repairing a WAV of format tag {tag:#06x}"))); + } + let (channels, align, bits) = (field(2), field(12), field(14)); + if channels == 0 || bits == 0 || u32::from(align) != u32::from(channels) * u32::from(bits.div_ceil(8)) { + return Err(AudioError::Malformed(format!("WAV block size {align} does not fit {channels} channels of {bits} bits"))); + } + Ok(u64::from(align)) +} + +fn layout(file: &mut F, len: u64) -> Result { + let mut riff = [0u8; 12]; + if !read_at(file, 0, &mut riff)? || !(riff.starts_with(b"RIFF") || riff.starts_with(b"RF64")) || &riff[8..] != b"WAVE" { + return Err(AudioError::Malformed("not a WAV file".into())); + } + let rf64 = riff.starts_with(b"RF64"); + let (mut ds64, mut junk, mut fact, mut block_align) = (None, false, None, None); + let mut pos = 12u64; + let mut chunk = [0u8; 8]; + // The same bound as the reader's, so a file of tiny chunks can't spin forever. + for _ in 0..100_000 { + if pos >= len || !read_at(file, pos, &mut chunk)? { + break; + } + let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]); + let body = pos + 8; + match &chunk[..4] { + b"data" => { + let block_align = block_align.ok_or_else(|| AudioError::Malformed("WAV data chunk before its fmt chunk".into()))?; + return Ok(Layout { rf64, ds64, junk, fact, block_align, data: body }); + } + b"ds64" if size >= 28 => ds64 = Some(body), + b"JUNK" if !rf64 && pos == 12 && size == 28 => (ds64, junk) = (Some(body), true), + b"fact" if size >= 4 => fact = Some(body), + b"fmt " => block_align = Some(pcm_block_align(file, body, size)?), + _ => {} + } + pos = body + u64::from(size) + u64::from(size & 1); + } + Err(AudioError::Malformed("WAV has no data chunk".into())) +} + +/// The data size the header records: the `ds64` field of an RF64 file, else the data chunk's. +fn stored_data_len(file: &mut F, l: &Layout) -> Result> { + let mut size = [0u8; 8]; + Ok(match (l.rf64, l.ds64) { + (true, Some(at)) => read_at(file, at + 8, &mut size)?.then(|| u64::from_le_bytes(size)), + (true, None) => None, + (false, _) => read_at(file, l.data - 4, &mut size[..4])? + .then(|| u32::from_le_bytes([size[0], size[1], size[2], size[3]])) + .filter(|&s| s != u32::MAX) + .map(u64::from), + }) +} + +/// Rewrites the size fields of a WAV that ends in its data chunk for the whole frames it holds. +/// Returns the frame count and the length the file should have; bytes past it are a partial frame. +pub(crate) fn repair(file: &mut F) -> Result<(u64, u64)> { + let len = file.seek(SeekFrom::End(0))?; + let l = layout(file, len)?; + let held = len.saturating_sub(l.data); + // A finished file's own size, which also tells its pad byte from a frame of one byte. + let stored = stored_data_len(file, &l)?.filter(|&s| s % l.block_align == 0 && s.checked_add(s & 1) == Some(held)); + if stored.is_none() && l.block_align == 1 && held > 0 && held % 2 == 0 { + // The last byte may be a sample or the pad byte after an odd count of them. + return Err(AudioError::Unsupported("repairing 8-bit mono WAV data of even length: a pad byte reads as a sample".into())); + } + let frames = stored.unwrap_or(held) / l.block_align; + let data_len = frames * l.block_align; + let pad = data_len & 1; + let new_len = l.data + data_len + pad; + let riff_len = new_len - 8; + let rf64 = l.rf64 || u32::try_from(riff_len).is_err(); + let ds64 = match (rf64, l.ds64) { + (false, _) => None, + (true, Some(at)) if l.rf64 || l.junk => Some(at), + (true, _) if l.rf64 => return Err(AudioError::Malformed("RF64 file has no ds64 chunk".into())), + (true, _) => return Err(AudioError::TooLarge("WAV past 4 GiB has no room for a ds64 chunk".into())), + }; + if pad == 1 { + write_at(file, l.data + data_len, &[0])?; + } + if let Some(at) = l.fact { + write_at(file, at, &u32::try_from(frames).unwrap_or(u32::MAX).to_le_bytes())?; + } + match ds64 { + Some(at) => { + let mut body = Vec::with_capacity(24); + body.extend_from_slice(&riff_len.to_le_bytes()); + body.extend_from_slice(&data_len.to_le_bytes()); + body.extend_from_slice(&frames.to_le_bytes()); + write_at(file, at, &body)?; + if !l.rf64 { + write_at(file, at - 8, b"ds64")?; + write_at(file, 0, b"RF64")?; + } + write_at(file, l.data - 4, &u32::MAX.to_le_bytes())?; + write_at(file, 4, &u32::MAX.to_le_bytes())?; + } + None => { + write_at(file, l.data - 4, &(data_len as u32).to_le_bytes())?; + write_at(file, 4, &(riff_len as u32).to_le_bytes())?; + } + } + file.seek(SeekFrom::Start(new_len))?; + file.flush()?; + Ok((frames, new_len)) +} diff --git a/crates/audio/tests/audio/roundtrip.rs b/crates/audio/tests/audio/roundtrip.rs index 35f1b15684..48c8f47e8f 100644 --- a/crates/audio/tests/audio/roundtrip.rs +++ b/crates/audio/tests/audio/roundtrip.rs @@ -323,6 +323,162 @@ fn float_wav_header_is_rewritten_in_place_as_the_file_grows() { assert!(wav_float_header(48_000, 0, 0).is_err()); } +/// A file that stopped growing before its header was rewritten: the header for 0 frames, the +/// samples of `buf`, then `extra` bytes of a frame that was never finished. +fn unfinished_wav(buf: &AudioBuffer, opts: &EncodeOptions, extra: usize) -> (Vec, Vec) { + let finished = encode(buf, opts).unwrap(); + let mut file = encode(&AudioBuffer::new(buf.sample_rate, buf.num_channels(), 0), opts).unwrap(); + let head = file.len(); + let sample_bytes = match opts.bit_depth { + BitDepth::Int16 => 2, + BitDepth::Int24 => 3, + _ => 4, + }; + let data_len = buf.frames() * usize::from(buf.num_channels()) * sample_bytes; + file.extend_from_slice(&finished[head..head + data_len]); + file.extend(std::iter::repeat_n(0x55, extra)); + (file, finished) +} + +#[test] +fn repair_wav_rewrites_the_sizes_of_an_unfinished_file() { + let bwf = BwfInfo::default().with_description("take 3").with_time_reference(48_000 * 3600); + let cases = [ + (sine(48_000, 2, 1_000), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Float32).with_bwf(bwf.clone()), 5), + // 3 bytes a frame and an odd frame count: the data needs a pad byte. + (sine(44_100, 1, 999), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24).with_bwf(bwf.clone()), 2), + (sine(44_100, 1, 999), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24).with_bwf(bwf), 0), + (sine(48_000, 6, 300), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16).with_force_rf64(true), 11), + (sine(48_000, 2, 0), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16), 3), + ]; + for (buf, opts, extra) in cases { + let (file, finished) = unfinished_wav(&buf, &opts, extra); + assert_ne!(file, finished); + let mut file = std::io::Cursor::new(file); + let repaired = craft_audio::repair_wav(&mut file).unwrap(); + assert_eq!(repaired.frames, buf.frames() as u64); + let mut file = file.into_inner(); + assert!(file.len() as u64 >= repaired.len); + file.truncate(repaired.len as usize); + assert_eq!(file, finished, "{opts:?}"); + // A finished file stays as it is. + let mut again = std::io::Cursor::new(file.clone()); + assert_eq!(craft_audio::repair_wav(&mut again).unwrap(), repaired); + assert_eq!(again.into_inner(), file); + } +} + +/// A file whose data is all zeros past `head`, `len` bytes long, without holding them in memory. +struct SparseWav { + head: Vec, + len: u64, + pos: u64, +} + +impl std::io::Read for SparseWav { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let n = (self.len.saturating_sub(self.pos)).min(buf.len() as u64) as usize; + for (i, b) in buf[..n].iter_mut().enumerate() { + *b = self.head.get(self.pos as usize + i).copied().unwrap_or(0); + } + self.pos += n as u64; + Ok(n) + } +} + +impl std::io::Write for SparseWav { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + let end = self.pos as usize + buf.len(); + if end <= self.head.len() { + self.head[self.pos as usize..end].copy_from_slice(buf); + } else { + assert!(buf.iter().all(|&b| b == 0), "only padding is written past the header"); + } + self.pos += buf.len() as u64; + self.len = self.len.max(self.pos); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +impl std::io::Seek for SparseWav { + fn seek(&mut self, to: std::io::SeekFrom) -> std::io::Result { + self.pos = match to { + std::io::SeekFrom::Start(p) => p, + std::io::SeekFrom::End(d) => self.len.checked_add_signed(d).unwrap(), + std::io::SeekFrom::Current(d) => self.pos.checked_add_signed(d).unwrap(), + }; + Ok(self.pos) + } +} + +#[test] +fn repair_wav_turns_a_file_past_4_gib_into_rf64() { + let frames = 600_000_000u64; // 4.8 GB of stereo float + let head = wav_float_header(48_000, 2, 0).unwrap(); + let len = head.len() as u64 + frames * 8 + 3; + let mut file = SparseWav { head: head.clone(), len, pos: 0 }; + let repaired = craft_audio::repair_wav(&mut file).unwrap(); + assert_eq!((repaired.frames, repaired.len), (frames, len - 3)); + assert_eq!(file.head, wav_float_header(48_000, 2, frames).unwrap()); + + // A RIFF file with no JUNK chunk to turn into ds64 cannot grow past 4 GiB. + let bare = craft_audio::pcm_wav_header(0, 2, 48_000, 16); + assert_eq!(&bare[12..16], b"fmt "); + let len = bare.len() as u64 + (1u64 << 32); + let mut file = SparseWav { head: bare, len, pos: 0 }; + assert!(matches!(craft_audio::repair_wav(&mut file), Err(craft_audio::AudioError::TooLarge(_)))); +} + +#[test] +fn repair_wav_refuses_what_it_cannot_repair() { + use craft_audio::AudioError; + let repair = |bytes: Vec| craft_audio::repair_wav(&mut std::io::Cursor::new(bytes)); + let wav = encode(&sine(48_000, 1, 100), &EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16)).unwrap(); + assert!(matches!(repair(b"not a wave file at all".to_vec()), Err(AudioError::Malformed(_)))); + // Every cut inside the header is an error, not a panic. + let data = wav.windows(4).position(|w| w == b"data").unwrap(); + for cut in 0..data + 8 { + assert!(repair(wav[..cut].to_vec()).is_err(), "cut at {cut}"); + } + // A compressed format (format tag 2, Microsoft ADPCM) has no fixed frame size to count by. + let fmt = wav.windows(4).position(|w| w == b"fmt ").unwrap() + 8; + let mut adpcm = wav.clone(); + adpcm[fmt..fmt + 2].copy_from_slice(&2u16.to_le_bytes()); + assert!(matches!(repair(adpcm), Err(AudioError::Unsupported(_)))); + // The chunk walk stops, as the reader's does, after 100,000 chunks. + let mut many = wav[..12].to_vec(); + many.extend(b"JUNK\0\0\0\0".repeat(100_001)); + many.extend_from_slice(&wav[12..]); + assert!(matches!(repair(many), Err(AudioError::Malformed(_)))); + // 8-bit mono: an even data length could end in a sample or in the pad after an odd count. + let u8_mono = craft_audio::pcm_wav_header(0, 1, 8_000, 8); + for (samples, ok) in [(3, true), (4, false)] { + let mut file = u8_mono.clone(); + file.extend(std::iter::repeat_n(0x80, samples)); + assert_eq!(repair(file.clone()).map(|r| r.frames).ok(), ok.then_some(3), "{samples} bytes"); + if ok { + // Once repaired, the size settles it. + let mut file = std::io::Cursor::new(file); + let r = craft_audio::repair_wav(&mut file).unwrap(); + assert_eq!(repair(file.into_inner()).unwrap(), r); + } + } + // A block size that is not channels × sample bytes would count the wrong frames. + let mut odd_align = wav.clone(); + odd_align[fmt + 12..fmt + 14].copy_from_slice(&4u16.to_le_bytes()); + assert!(matches!(repair(odd_align), Err(AudioError::Malformed(_)))); + // An extensible file whose subformat is PCM's tag under another GUID is not PCM. + let ext = encode(&sine(48_000, 2, 100), &EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24)).unwrap(); + let fmt = ext.windows(4).position(|w| w == b"fmt ").unwrap() + 8; + assert!(repair(ext.clone()).is_ok()); + let mut other_guid = ext; + other_guid[fmt + 39] ^= 0xFF; + assert!(matches!(repair(other_guid), Err(AudioError::Unsupported(_)))); +} + #[test] fn zero_frame_flac_round_trips_like_wav_and_aiff() { for format in [EncodeFormat::Wav, EncodeFormat::Aiff, EncodeFormat::Flac] { From 5d9da61dae49ad4c5e34f81991d5423b5343c912 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 11:11:10 -0800 Subject: [PATCH 02/14] craft-audio: repair_wav docs name each field it rewrites and every error The repair_wav doc comment said every chunk before the data keeps its contents, but repair rewrites the frame count in a fact chunk, the start of an existing ds64 chunk, and turns the leading 28-byte JUNK chunk into ds64 when a RIFF file passes 4 GiB. It now lists the fields it writes and the bytes it leaves alone. The Errors section now names every case: Malformed also for the data chunk before fmt, a short fmt chunk, 0 channels or bits, a block size that does not match, no data chunk in the first 100,000 chunks, and RF64 without ds64; Unsupported for an extensible format whose subformat is not PCM or float; and Io. --- crates/audio/src/write/mod.rs | 35 ++++++++++++++++++++++++++--------- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/crates/audio/src/write/mod.rs b/crates/audio/src/write/mod.rs index 384465f135..bc2a09b062 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -468,16 +468,33 @@ pub struct WavRepair { } /// Rewrites the size fields of a PCM or float WAV whose writer stopped before finishing it, such -/// as a recorder's file after a crash, for the whole frames the file holds. Every chunk before the -/// data (`bext`, `fmt `, `fact` and others) keeps its contents, and a file that grew past 4 GiB -/// becomes RF64 when it starts with the 28-byte `JUNK` chunk that [`FileEncoder`] and -/// [`wav_float_header`] write. The file must end in its data chunk: everything after the data -/// chunk's header counts as samples, whatever its size field says. +/// as a recorder's file after a crash, for the whole frames the file holds. The file must end in +/// its data chunk: everything after the data chunk's header counts as samples, whatever its size +/// field says. /// -/// Errors: [`AudioError::Malformed`] when `file` is not a WAV or has no `fmt ` or data chunk, -/// [`AudioError::Unsupported`] for a compressed format and for unfinished 8-bit mono data of even -/// length (its last byte may be a sample or a pad byte), and [`AudioError::TooLarge`] for a RIFF -/// file past 4 GiB with no room for a `ds64` chunk. +/// It writes these fields and leaves every other byte before the samples as it is, `fmt `, `bext` +/// and unknown chunks included: +/// +/// - the RIFF size and the data chunk's size (both `0xFFFF_FFFF` in an RF64 file); +/// - the frame count, the first field of a `fact` chunk (`0xFFFF_FFFF` past `u32::MAX` frames); +/// - in an RF64 file, the RIFF size, data size and frame count at the start of the `ds64` chunk; +/// - the pad byte after an odd data length. +/// +/// A RIFF file that grew past 4 GiB becomes RF64 when it starts with the 28-byte `JUNK` chunk that +/// [`FileEncoder`] and [`wav_float_header`] write: `RIFF` becomes `RF64` and that `JUNK` chunk +/// becomes the `ds64` chunk. +/// +/// Errors: +/// +/// - [`AudioError::Malformed`] when `file` is not a RIFF or RF64 WAVE file, has no data chunk within +/// its first 100,000 chunks, has its data chunk before its `fmt ` chunk, has a `fmt ` chunk shorter +/// than 16 bytes or cut short by the end of the file, has 0 channels or 0 bits, has a block size +/// other than the channels times the bytes per sample, or is RF64 without a `ds64` chunk. +/// - [`AudioError::Unsupported`] for a format other than PCM and IEEE float, an extensible format +/// whose subformat is neither, and unfinished 8-bit mono data of even length (its last byte may +/// be a sample or a pad byte). +/// - [`AudioError::TooLarge`] for a RIFF file past 4 GiB that does not start with that `JUNK` chunk. +/// - [`AudioError::Io`] when reading, writing or seeking `file` fails. /// /// ``` /// use craft_audio::{repair_wav, wav_float_header}; From d24067aac4d775ab14287059499af583921ab1f8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 11:21:15 -0800 Subject: [PATCH 03/14] craft-audio: repair_wav reads Ambisonic PCM and empties the ds64 table repair_wav refused an extensible WAV with the Ambisonic PCM or float subformat, which the WAV reader reads as PCM. The Ambisonic GUID tail now lives with the other shared WAVE constants and both sides check it. When a RIFF file past 4 GiB becomes RF64, the last 4 bytes of the leading JUNK chunk become the ds64 table length. repair_wav wrote only the first 24 bytes, so a JUNK chunk holding other bytes left a table length that names entries the file does not have. It now writes a table length of 0. --- crates/audio/src/read/wav.rs | 5 +---- crates/audio/src/wav.rs | 2 ++ crates/audio/src/write/mod.rs | 2 +- crates/audio/src/write/wav.rs | 10 +++++++--- crates/audio/tests/audio/roundtrip.rs | 14 +++++++++++++- 5 files changed, 24 insertions(+), 9 deletions(-) diff --git a/crates/audio/src/read/wav.rs b/crates/audio/src/read/wav.rs index c1552d7e29..5f0ace68ae 100644 --- a/crates/audio/src/read/wav.rs +++ b/crates/audio/src/read/wav.rs @@ -3,12 +3,9 @@ use super::source::Src; use crate::pcm::{PcmKind, le_u16, le_u32, le_u64, tag}; -use crate::wav::{GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM}; +use crate::wav::{AMBISONIC_TAIL, GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM}; use crate::{AudioError, AudioInfo, BwfInfo, ChannelLayout, CodecId, Container, Result, SampleFormat}; -/// Tail of the Ambisonic subtype GUIDs {0000000x-0721-11D3-8644-C8C1CA000000}: PCM (x = 1) and float (x = 3) as well. -const AMBISONIC_TAIL: [u8; 14] = [0x00, 0x00, 0x21, 0x07, 0xD3, 0x11, 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00]; - /// Parsed WAV layout (no sample data decoded yet). pub(crate) struct WavLayout { pub info: AudioInfo, diff --git a/crates/audio/src/wav.rs b/crates/audio/src/wav.rs index 61e32593a1..2a208d68bb 100644 --- a/crates/audio/src/wav.rs +++ b/crates/audio/src/wav.rs @@ -5,3 +5,5 @@ pub(crate) const WAVE_FORMAT_IEEE_FLOAT: u16 = 3; pub(crate) const WAVE_FORMAT_EXTENSIBLE: u16 = 0xFFFE; /// Tail of the KSDATAFORMAT_SUBTYPE_* GUIDs (bytes 2..16); bytes 0..2 hold the format tag. pub(crate) const GUID_TAIL: [u8; 14] = [0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71]; +/// Tail of the Ambisonic subtype GUIDs {0000000x-0721-11D3-8644-C8C1CA000000}: PCM (x = 1) and float (x = 3) as well. +pub(crate) const AMBISONIC_TAIL: [u8; 14] = [0x00, 0x00, 0x21, 0x07, 0xD3, 0x11, 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00]; diff --git a/crates/audio/src/write/mod.rs b/crates/audio/src/write/mod.rs index bc2a09b062..f601e5756a 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -482,7 +482,7 @@ pub struct WavRepair { /// /// A RIFF file that grew past 4 GiB becomes RF64 when it starts with the 28-byte `JUNK` chunk that /// [`FileEncoder`] and [`wav_float_header`] write: `RIFF` becomes `RF64` and that `JUNK` chunk -/// becomes the `ds64` chunk. +/// becomes a `ds64` chunk with an empty table. /// /// Errors: /// diff --git a/crates/audio/src/write/wav.rs b/crates/audio/src/write/wav.rs index 3c8f08f1d0..0a5d7fc75f 100644 --- a/crates/audio/src/write/wav.rs +++ b/crates/audio/src/write/wav.rs @@ -2,7 +2,7 @@ //! specification, `bext` per EBU Tech 3285, `ds64` per EBU Tech 3306). use super::pcm::{Quantizer, sample_format, validate_buffer, validate_layout, write_interleaved}; -use crate::wav::{GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM}; +use crate::wav::{AMBISONIC_TAIL, GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM}; use crate::{AudioBuffer, AudioError, BitDepth, BwfInfo, Result}; use std::io::{Cursor, ErrorKind, Read, Seek, SeekFrom, Write}; @@ -276,7 +276,7 @@ fn pcm_block_align(file: &mut F, pos: u64, size: u32) -> Result< } let field = |at: usize| u16::from_le_bytes([fmt[at], fmt[at + 1]]); let mut tag = field(0); - if tag == WAVE_FORMAT_EXTENSIBLE && n == 40 && fmt[26..] == GUID_TAIL { + if tag == WAVE_FORMAT_EXTENSIBLE && n == 40 && (fmt[26..] == GUID_TAIL || fmt[26..] == AMBISONIC_TAIL) { tag = field(24); } if tag != WAVE_FORMAT_PCM && tag != WAVE_FORMAT_IEEE_FLOAT { @@ -366,10 +366,14 @@ pub(crate) fn repair(file: &mut F) -> Result<(u64, u64)> } match ds64 { Some(at) => { - let mut body = Vec::with_capacity(24); + let mut body = Vec::with_capacity(28); body.extend_from_slice(&riff_len.to_le_bytes()); body.extend_from_slice(&data_len.to_le_bytes()); body.extend_from_slice(&frames.to_le_bytes()); + if !l.rf64 { + // The `JUNK` chunk's last 4 bytes become the table length: no table entries. + body.extend_from_slice(&0u32.to_le_bytes()); + } write_at(file, at, &body)?; if !l.rf64 { write_at(file, at - 8, b"ds64")?; diff --git a/crates/audio/tests/audio/roundtrip.rs b/crates/audio/tests/audio/roundtrip.rs index 48c8f47e8f..720e150129 100644 --- a/crates/audio/tests/audio/roundtrip.rs +++ b/crates/audio/tests/audio/roundtrip.rs @@ -424,6 +424,14 @@ fn repair_wav_turns_a_file_past_4_gib_into_rf64() { assert_eq!((repaired.frames, repaired.len), (frames, len - 3)); assert_eq!(file.head, wav_float_header(48_000, 2, frames).unwrap()); + // A JUNK chunk holding other bytes becomes a ds64 chunk with an empty table. + let mut dirty = head.clone(); + assert_eq!(&dirty[12..16], b"JUNK"); + dirty[20..48].fill(0xAA); + let mut file = SparseWav { head: dirty, len, pos: 0 }; + craft_audio::repair_wav(&mut file).unwrap(); + assert_eq!(file.head, wav_float_header(48_000, 2, frames).unwrap()); + // A RIFF file with no JUNK chunk to turn into ds64 cannot grow past 4 GiB. let bare = craft_audio::pcm_wav_header(0, 2, 48_000, 16); assert_eq!(&bare[12..16], b"fmt "); @@ -474,9 +482,13 @@ fn repair_wav_refuses_what_it_cannot_repair() { let ext = encode(&sine(48_000, 2, 100), &EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24)).unwrap(); let fmt = ext.windows(4).position(|w| w == b"fmt ").unwrap() + 8; assert!(repair(ext.clone()).is_ok()); - let mut other_guid = ext; + let mut other_guid = ext.clone(); other_guid[fmt + 39] ^= 0xFF; assert!(matches!(repair(other_guid), Err(AudioError::Unsupported(_)))); + // The Ambisonic PCM subformat {00000001-0721-11D3-8644-C8C1CA000000}, which the reader reads as PCM. + let mut ambisonic = ext; + ambisonic[fmt + 26..fmt + 40].copy_from_slice(&[0x00, 0x00, 0x21, 0x07, 0xD3, 0x11, 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00]); + assert_eq!(repair(ambisonic).unwrap().frames, 100); } #[test] From 3228207a0a3e55eabf10adb97b199405fb0376ca Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 11:34:58 -0800 Subject: [PATCH 04/14] craft-audio: repair_wav finishes an interrupted RF64 promotion When repair_wav turns a RIFF file past 4 GiB into RF64, it renames the JUNK chunk after WAVE to ds64 before it writes RF64. A write error between the two left a RIFF file with a ds64 chunk there, and every later repair returned TooLarge. repair_wav now takes a 28-byte ds64 chunk right after WAVE in a RIFF file as the slot to promote. In a RIFF file, a ds64 chunk further on is no longer used. Before, a later ds64 chunk took the place of the leading JUNK chunk, so the file became RF64 with JUNK as its first chunk and the later chunk's table length was set to 0. --- crates/audio/src/write/mod.rs | 6 ++++-- crates/audio/src/write/wav.rs | 9 +++++---- crates/audio/tests/audio/roundtrip.rs | 17 +++++++++++++++++ 3 files changed, 26 insertions(+), 6 deletions(-) diff --git a/crates/audio/src/write/mod.rs b/crates/audio/src/write/mod.rs index f601e5756a..e976b761f4 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -482,7 +482,8 @@ pub struct WavRepair { /// /// A RIFF file that grew past 4 GiB becomes RF64 when it starts with the 28-byte `JUNK` chunk that /// [`FileEncoder`] and [`wav_float_header`] write: `RIFF` becomes `RF64` and that `JUNK` chunk -/// becomes a `ds64` chunk with an empty table. +/// becomes a `ds64` chunk with an empty table. A RIFF file whose 28-byte chunk there already has the +/// `ds64` id, left by an earlier repair that stopped before writing `RF64`, becomes RF64 the same way. /// /// Errors: /// @@ -493,7 +494,8 @@ pub struct WavRepair { /// - [`AudioError::Unsupported`] for a format other than PCM and IEEE float, an extensible format /// whose subformat is neither, and unfinished 8-bit mono data of even length (its last byte may /// be a sample or a pad byte). -/// - [`AudioError::TooLarge`] for a RIFF file past 4 GiB that does not start with that `JUNK` chunk. +/// - [`AudioError::TooLarge`] for a RIFF file past 4 GiB that does not start with that `JUNK` or +/// `ds64` chunk. /// - [`AudioError::Io`] when reading, writing or seeking `file` fails. /// /// ``` diff --git a/crates/audio/src/write/wav.rs b/crates/audio/src/write/wav.rs index 0a5d7fc75f..b0aa6f52fc 100644 --- a/crates/audio/src/write/wav.rs +++ b/crates/audio/src/write/wav.rs @@ -243,8 +243,8 @@ pub(crate) fn header( /// Where the size fields of a WAV sit, from a walk of its chunks up to `data`. struct Layout { rf64: bool, - /// The body of the `ds64` chunk, or of a 28-byte `JUNK` chunk right after `WAVE` that can - /// become one. + /// The body of the `ds64` chunk of an RF64 file, or in a RIFF file the body of the 28-byte + /// `JUNK` or `ds64` chunk right after `WAVE` that can become one. ds64: Option, junk: bool, fact: Option, @@ -310,8 +310,9 @@ fn layout(file: &mut F, len: u64) -> Result { let block_align = block_align.ok_or_else(|| AudioError::Malformed("WAV data chunk before its fmt chunk".into()))?; return Ok(Layout { rf64, ds64, junk, fact, block_align, data: body }); } - b"ds64" if size >= 28 => ds64 = Some(body), - b"JUNK" if !rf64 && pos == 12 && size == 28 => (ds64, junk) = (Some(body), true), + b"ds64" if rf64 && size >= 28 => ds64 = Some(body), + // A `ds64` id here in a RIFF file is a promotion that stopped before the RF64 id. + b"JUNK" | b"ds64" if !rf64 && pos == 12 && size == 28 => (ds64, junk) = (Some(body), true), b"fact" if size >= 4 => fact = Some(body), b"fmt " => block_align = Some(pcm_block_align(file, body, size)?), _ => {} diff --git a/crates/audio/tests/audio/roundtrip.rs b/crates/audio/tests/audio/roundtrip.rs index 720e150129..d913feeca1 100644 --- a/crates/audio/tests/audio/roundtrip.rs +++ b/crates/audio/tests/audio/roundtrip.rs @@ -432,6 +432,23 @@ fn repair_wav_turns_a_file_past_4_gib_into_rf64() { craft_audio::repair_wav(&mut file).unwrap(); assert_eq!(file.head, wav_float_header(48_000, 2, frames).unwrap()); + // A repair that stopped after naming the ds64 chunk but before writing RF64 finishes next time. + let mut half = head.clone(); + half[12..16].copy_from_slice(b"ds64"); + let mut file = SparseWav { head: half, len, pos: 0 }; + assert_eq!(craft_audio::repair_wav(&mut file).unwrap(), repaired); + assert_eq!(file.head, wav_float_header(48_000, 2, frames).unwrap()); + + // In a RIFF file only the chunk right after WAVE becomes ds64; a later ds64 chunk is left as it is. + let at = head.windows(4).position(|w| w == b"data").unwrap(); + let later: Vec = [&b"ds64"[..], &28u32.to_le_bytes(), &[0xBB; 28]].concat(); + let mut two = head.clone(); + two.splice(at..at, later.iter().copied()); + let mut file = SparseWav { head: two, len: len + 36, pos: 0 }; + assert_eq!(craft_audio::repair_wav(&mut file).unwrap().frames, frames); + assert_eq!((&file.head[..4], &file.head[12..16]), (&b"RF64"[..], &b"ds64"[..])); + assert_eq!(file.head[at..at + 36], later[..]); + // A RIFF file with no JUNK chunk to turn into ds64 cannot grow past 4 GiB. let bare = craft_audio::pcm_wav_header(0, 2, 48_000, 16); assert_eq!(&bare[12..16], b"fmt "); From 53df8e8c070b4ccc802ccb0727427182aa88f3da Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 14:44:15 -0800 Subject: [PATCH 05/14] craft-audio: repair_wav refuses sample widths the WAV reader cannot decode repair_wav accepted any bit width for PCM and IEEE float, so a 16-bit float file or PCM wider than 32 bits had its sizes rewritten and was reported repaired, though the WAV reader still refuses it. repair_wav now returns Unsupported unless the file is PCM of 1 to 32 bits or float of 32 or 64 bits, the widths the reader decodes, and leaves the file unchanged. --- crates/audio/src/write/mod.rs | 5 +++-- crates/audio/src/write/wav.rs | 4 ++++ crates/audio/tests/audio/roundtrip.rs | 9 +++++++++ 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/crates/audio/src/write/mod.rs b/crates/audio/src/write/mod.rs index e976b761f4..2f8eb7db37 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -492,8 +492,9 @@ pub struct WavRepair { /// than 16 bytes or cut short by the end of the file, has 0 channels or 0 bits, has a block size /// other than the channels times the bytes per sample, or is RF64 without a `ds64` chunk. /// - [`AudioError::Unsupported`] for a format other than PCM and IEEE float, an extensible format -/// whose subformat is neither, and unfinished 8-bit mono data of even length (its last byte may -/// be a sample or a pad byte). +/// whose subformat is neither, a sample width the WAV reader does not decode (PCM above 32 bits, +/// float other than 32 or 64 bits), and unfinished 8-bit mono data of even length (its last byte +/// may be a sample or a pad byte). /// - [`AudioError::TooLarge`] for a RIFF file past 4 GiB that does not start with that `JUNK` or /// `ds64` chunk. /// - [`AudioError::Io`] when reading, writing or seeking `file` fails. diff --git a/crates/audio/src/write/wav.rs b/crates/audio/src/write/wav.rs index b0aa6f52fc..0ff6965b9d 100644 --- a/crates/audio/src/write/wav.rs +++ b/crates/audio/src/write/wav.rs @@ -286,6 +286,10 @@ fn pcm_block_align(file: &mut F, pos: u64, size: u32) -> Result< if channels == 0 || bits == 0 || u32::from(align) != u32::from(channels) * u32::from(bits.div_ceil(8)) { return Err(AudioError::Malformed(format!("WAV block size {align} does not fit {channels} channels of {bits} bits"))); } + // The widths the WAV reader decodes. + if !matches!((tag, bits), (WAVE_FORMAT_PCM, 1..=32) | (WAVE_FORMAT_IEEE_FLOAT, 32 | 64)) { + return Err(AudioError::Unsupported(format!("repairing a WAV of format tag {tag:#06x} with {bits} bits per sample"))); + } Ok(u64::from(align)) } diff --git a/crates/audio/tests/audio/roundtrip.rs b/crates/audio/tests/audio/roundtrip.rs index d913feeca1..9137bf6456 100644 --- a/crates/audio/tests/audio/roundtrip.rs +++ b/crates/audio/tests/audio/roundtrip.rs @@ -495,6 +495,15 @@ fn repair_wav_refuses_what_it_cannot_repair() { let mut odd_align = wav.clone(); odd_align[fmt + 12..fmt + 14].copy_from_slice(&4u16.to_le_bytes()); assert!(matches!(repair(odd_align), Err(AudioError::Malformed(_)))); + // Widths the reader does not decode: 16-bit float and 40-bit PCM, each with a block size that fits. + let mut float16 = wav.clone(); + float16[fmt..fmt + 2].copy_from_slice(&3u16.to_le_bytes()); + let mut pcm40 = wav.clone(); + pcm40[fmt + 12..fmt + 16].copy_from_slice(&[5, 0, 40, 0]); + for bad in [float16, pcm40] { + assert!(craft_audio::decode(&bad, Some("wav")).is_err()); + assert!(matches!(repair(bad), Err(AudioError::Unsupported(_)))); + } // An extensible file whose subformat is PCM's tag under another GUID is not PCM. let ext = encode(&sine(48_000, 2, 100), &EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24)).unwrap(); let fmt = ext.windows(4).position(|w| w == b"fmt ").unwrap() + 8; From 21d0cd6a4a7c4d8eeaab3d372c66cdc2a28921b7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:13:20 -0800 Subject: [PATCH 06/14] craft-audio: repair_wav and the WAV reader use the first ds64 and fact chunks An RF64 file with a second ds64 chunk before its data had repair_wav write the 24-byte size table over the start of that later chunk, leaving the leading ds64 with its stale sizes, and the reader took the data size from the last ds64 it met. EBU Tech 3306 places ds64 first after WAVE, and both now use the first one. repair_wav also writes the frame count into the first fact chunk instead of the last. --- crates/audio/src/read/wav.rs | 3 +- crates/audio/src/write/wav.rs | 5 +-- crates/audio/tests/audio/roundtrip.rs | 44 +++++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 3 deletions(-) diff --git a/crates/audio/src/read/wav.rs b/crates/audio/src/read/wav.rs index 5f0ace68ae..1e568b1f61 100644 --- a/crates/audio/src/read/wav.rs +++ b/crates/audio/src/read/wav.rs @@ -343,7 +343,8 @@ pub(crate) fn parse(src: &Src<'_>) -> Result { ixml_time = ixml_time_reference(&small(IXML_MAX as u64)); } } - b"ds64" => ds64_data = le_u64(&small(64), 8), + // The sizes come from the first `ds64` chunk that holds them. + b"ds64" if ds64_data.is_none() => ds64_data = le_u64(&small(64), 8), _ => {} } } diff --git a/crates/audio/src/write/wav.rs b/crates/audio/src/write/wav.rs index 0ff6965b9d..d502787553 100644 --- a/crates/audio/src/write/wav.rs +++ b/crates/audio/src/write/wav.rs @@ -314,10 +314,11 @@ fn layout(file: &mut F, len: u64) -> Result { let block_align = block_align.ok_or_else(|| AudioError::Malformed("WAV data chunk before its fmt chunk".into()))?; return Ok(Layout { rf64, ds64, junk, fact, block_align, data: body }); } - b"ds64" if rf64 && size >= 28 => ds64 = Some(body), + // The first `ds64` and `fact` chunks take the sizes; later ones are left as they are. + b"ds64" if rf64 && size >= 28 && ds64.is_none() => ds64 = Some(body), // A `ds64` id here in a RIFF file is a promotion that stopped before the RF64 id. b"JUNK" | b"ds64" if !rf64 && pos == 12 && size == 28 => (ds64, junk) = (Some(body), true), - b"fact" if size >= 4 => fact = Some(body), + b"fact" if size >= 4 && fact.is_none() => fact = Some(body), b"fmt " => block_align = Some(pcm_block_align(file, body, size)?), _ => {} } diff --git a/crates/audio/tests/audio/roundtrip.rs b/crates/audio/tests/audio/roundtrip.rs index 9137bf6456..9b0f987a46 100644 --- a/crates/audio/tests/audio/roundtrip.rs +++ b/crates/audio/tests/audio/roundtrip.rs @@ -449,6 +449,19 @@ fn repair_wav_turns_a_file_past_4_gib_into_rf64() { assert_eq!((&file.head[..4], &file.head[12..16]), (&b"RF64"[..], &b"ds64"[..])); assert_eq!(file.head[at..at + 36], later[..]); + // In an RF64 file the ds64 chunk right after WAVE takes the sizes; a later ds64 chunk is left as it is. + let finished = wav_float_header(48_000, 2, frames).unwrap(); + assert_eq!((&finished[..4], &finished[12..16]), (&b"RF64"[..], &b"ds64"[..])); + let mut stale = finished.clone(); + stale[20..44].fill(0); + stale.splice(at..at, later.iter().copied()); + let mut file = SparseWav { head: stale, len: len + 36, pos: 0 }; + let r = craft_audio::repair_wav(&mut file).unwrap(); + assert_eq!((r.frames, r.len), (frames, len + 33)); + let field = |at: usize| u64::from_le_bytes(file.head[at..at + 8].try_into().unwrap()); + assert_eq!((field(20), field(28), field(36)), (len + 25, frames * 8, frames)); + assert_eq!(file.head[at..at + 36], later[..]); + // A RIFF file with no JUNK chunk to turn into ds64 cannot grow past 4 GiB. let bare = craft_audio::pcm_wav_header(0, 2, 48_000, 16); assert_eq!(&bare[12..16], b"fmt "); @@ -457,6 +470,37 @@ fn repair_wav_turns_a_file_past_4_gib_into_rf64() { assert!(matches!(craft_audio::repair_wav(&mut file), Err(craft_audio::AudioError::TooLarge(_)))); } +#[test] +fn repair_wav_writes_the_frame_count_into_the_first_fact_chunk() { + let mut file = wav_float_header(48_000, 2, 0).unwrap(); + let fact = file.windows(4).position(|w| w == b"fact").unwrap() + 8; + let at = file.windows(4).position(|w| w == b"data").unwrap(); + let later: Vec = [&b"fact"[..], &4u32.to_le_bytes(), &[0xCC; 4]].concat(); + file.splice(at..at, later.iter().copied()); + file.extend(std::iter::repeat_n(0, 100 * 8)); + let mut file = std::io::Cursor::new(file); + assert_eq!(craft_audio::repair_wav(&mut file).unwrap().frames, 100); + let file = file.into_inner(); + assert_eq!(file[fact..fact + 4], 100u32.to_le_bytes()); + assert_eq!(file[at..at + 12], later[..]); +} + +#[test] +fn rf64_data_size_comes_from_the_ds64_chunk_after_wave() { + let opts = EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16).with_force_rf64(true); + let wav = encode(&sine(48_000, 2, 300), &opts).unwrap(); + assert_eq!(&wav[12..16], b"ds64"); + // A later ds64 chunk that gives the data 4 bytes, one frame. + let mut body = [0u8; 28]; + body[8..16].copy_from_slice(&4u64.to_le_bytes()); + let later = [&b"ds64"[..], &28u32.to_le_bytes(), &body].concat(); + let at = wav.windows(4).position(|w| w == b"data").unwrap(); + let mut two = wav.clone(); + two.splice(at..at, later); + let (info, buf) = decode(&two, Some("wav")).unwrap(); + assert_eq!((info.frames, buf.frames()), (300, 300)); +} + #[test] fn repair_wav_refuses_what_it_cannot_repair() { use craft_audio::AudioError; From 40a85523dfd8c3479671eb1dace12d363c628b43 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:23:42 -0800 Subject: [PATCH 07/14] craft-audio: repair_wav refuses the extensible fmt fields the reader refuses An extensible fmt chunk with a cbSize below 22, or with more valid bits than bits per sample, passed repair_wav's checks and was rewritten, while the WAV reader rejects it as malformed. repair_wav now returns AudioError::Malformed for both, and its docs list the case. --- crates/audio/src/write/mod.rs | 7 ++++--- crates/audio/src/write/wav.rs | 10 ++++++++-- crates/audio/tests/audio/roundtrip.rs | 9 +++++++++ 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/crates/audio/src/write/mod.rs b/crates/audio/src/write/mod.rs index 2f8eb7db37..7bff14fe10 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -476,8 +476,8 @@ pub struct WavRepair { /// and unknown chunks included: /// /// - the RIFF size and the data chunk's size (both `0xFFFF_FFFF` in an RF64 file); -/// - the frame count, the first field of a `fact` chunk (`0xFFFF_FFFF` past `u32::MAX` frames); -/// - in an RF64 file, the RIFF size, data size and frame count at the start of the `ds64` chunk; +/// - the frame count, the first field of the first `fact` chunk (`0xFFFF_FFFF` past `u32::MAX` frames); +/// - in an RF64 file, the RIFF size, data size and frame count at the start of the first `ds64` chunk; /// - the pad byte after an odd data length. /// /// A RIFF file that grew past 4 GiB becomes RF64 when it starts with the 28-byte `JUNK` chunk that @@ -490,7 +490,8 @@ pub struct WavRepair { /// - [`AudioError::Malformed`] when `file` is not a RIFF or RF64 WAVE file, has no data chunk within /// its first 100,000 chunks, has its data chunk before its `fmt ` chunk, has a `fmt ` chunk shorter /// than 16 bytes or cut short by the end of the file, has 0 channels or 0 bits, has a block size -/// other than the channels times the bytes per sample, or is RF64 without a `ds64` chunk. +/// other than the channels times the bytes per sample, has an extensible `fmt ` chunk with a cbSize +/// below 22 or more valid bits than bits per sample, or is RF64 without a `ds64` chunk. /// - [`AudioError::Unsupported`] for a format other than PCM and IEEE float, an extensible format /// whose subformat is neither, a sample width the WAV reader does not decode (PCM above 32 bits, /// float other than 32 or 64 bits), and unfinished 8-bit mono data of even length (its last byte diff --git a/crates/audio/src/write/wav.rs b/crates/audio/src/write/wav.rs index d502787553..4b0b268f90 100644 --- a/crates/audio/src/write/wav.rs +++ b/crates/audio/src/write/wav.rs @@ -276,8 +276,14 @@ fn pcm_block_align(file: &mut F, pos: u64, size: u32) -> Result< } let field = |at: usize| u16::from_le_bytes([fmt[at], fmt[at + 1]]); let mut tag = field(0); - if tag == WAVE_FORMAT_EXTENSIBLE && n == 40 && (fmt[26..] == GUID_TAIL || fmt[26..] == AMBISONIC_TAIL) { - tag = field(24); + if tag == WAVE_FORMAT_EXTENSIBLE && n == 40 { + // The extensible fields the reader checks. + if field(16) < 22 || field(18) > field(14) { + return Err(AudioError::Malformed("WAVE_FORMAT_EXTENSIBLE fmt chunk has a cbSize below 22 or too many valid bits".into())); + } + if fmt[26..] == GUID_TAIL || fmt[26..] == AMBISONIC_TAIL { + tag = field(24); + } } if tag != WAVE_FORMAT_PCM && tag != WAVE_FORMAT_IEEE_FLOAT { return Err(AudioError::Unsupported(format!("repairing a WAV of format tag {tag:#06x}"))); diff --git a/crates/audio/tests/audio/roundtrip.rs b/crates/audio/tests/audio/roundtrip.rs index 9b0f987a46..cc85587fcc 100644 --- a/crates/audio/tests/audio/roundtrip.rs +++ b/crates/audio/tests/audio/roundtrip.rs @@ -555,6 +555,15 @@ fn repair_wav_refuses_what_it_cannot_repair() { let mut other_guid = ext.clone(); other_guid[fmt + 39] ^= 0xFF; assert!(matches!(repair(other_guid), Err(AudioError::Unsupported(_)))); + // Extensible fields the reader refuses: a cbSize below 22 and more valid bits than the sample holds. + let mut short_cb = ext.clone(); + short_cb[fmt + 16..fmt + 18].copy_from_slice(&21u16.to_le_bytes()); + let mut wide_valid = ext.clone(); + wide_valid[fmt + 18..fmt + 20].copy_from_slice(&25u16.to_le_bytes()); + for bad in [short_cb, wide_valid] { + assert!(craft_audio::decode(&bad, Some("wav")).is_err()); + assert!(matches!(repair(bad), Err(AudioError::Malformed(_)))); + } // The Ambisonic PCM subformat {00000001-0721-11D3-8644-C8C1CA000000}, which the reader reads as PCM. let mut ambisonic = ext; ambisonic[fmt + 26..fmt + 40].copy_from_slice(&[0x00, 0x00, 0x21, 0x07, 0xD3, 0x11, 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00]); From 20a4c50d45ddb5635a91487802c354c3cf1f5c03 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:56:01 -0800 Subject: [PATCH 08/14] craft-audio: repair_wav refuses a short first ds64 and writes the pad byte last The WAV reader takes an RF64 file's data size from the first ds64 chunk of 16 bytes or more. repair_wav skipped a first ds64 chunk under 28 bytes and wrote the sizes into a later one, so the frame count it returned differed from what decoding gave. It now returns Malformed for a first ds64 chunk of 16 to 27 bytes, before writing anything. repair_wav wrote the pad byte of odd-length data before the size fields. A write error after the pad left 8-bit mono data of even length with the old size, which a second repair refused. The pad byte is now written last. --- crates/audio/src/write/mod.rs | 3 +- crates/audio/src/write/wav.rs | 16 +++++-- crates/audio/tests/audio/roundtrip.rs | 62 +++++++++++++++++++++++++++ 3 files changed, 76 insertions(+), 5 deletions(-) diff --git a/crates/audio/src/write/mod.rs b/crates/audio/src/write/mod.rs index 7bff14fe10..34229d2314 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -491,7 +491,8 @@ pub struct WavRepair { /// its first 100,000 chunks, has its data chunk before its `fmt ` chunk, has a `fmt ` chunk shorter /// than 16 bytes or cut short by the end of the file, has 0 channels or 0 bits, has a block size /// other than the channels times the bytes per sample, has an extensible `fmt ` chunk with a cbSize -/// below 22 or more valid bits than bits per sample, or is RF64 without a `ds64` chunk. +/// below 22 or more valid bits than bits per sample, or is RF64 without a `ds64` chunk or with a +/// first `ds64` chunk of 16 to 27 bytes (the WAV reader takes the data size from that chunk). /// - [`AudioError::Unsupported`] for a format other than PCM and IEEE float, an extensible format /// whose subformat is neither, a sample width the WAV reader does not decode (PCM above 32 bits, /// float other than 32 or 64 bits), and unfinished 8-bit mono data of even length (its last byte diff --git a/crates/audio/src/write/wav.rs b/crates/audio/src/write/wav.rs index 4b0b268f90..496bb95801 100644 --- a/crates/audio/src/write/wav.rs +++ b/crates/audio/src/write/wav.rs @@ -321,7 +321,13 @@ fn layout(file: &mut F, len: u64) -> Result { return Ok(Layout { rf64, ds64, junk, fact, block_align, data: body }); } // The first `ds64` and `fact` chunks take the sizes; later ones are left as they are. - b"ds64" if rf64 && size >= 28 && ds64.is_none() => ds64 = Some(body), + // The WAV reader takes the data size from the first `ds64` chunk of 16 bytes or more. + b"ds64" if rf64 && size >= 16 && ds64.is_none() => { + if size < 28 { + return Err(AudioError::Malformed("RF64 ds64 chunk is shorter than 28 bytes".into())); + } + ds64 = Some(body); + } // A `ds64` id here in a RIFF file is a promotion that stopped before the RF64 id. b"JUNK" | b"ds64" if !rf64 && pos == 12 && size == 28 => (ds64, junk) = (Some(body), true), b"fact" if size >= 4 && fact.is_none() => fact = Some(body), @@ -370,9 +376,6 @@ pub(crate) fn repair(file: &mut F) -> Result<(u64, u64)> (true, _) if l.rf64 => return Err(AudioError::Malformed("RF64 file has no ds64 chunk".into())), (true, _) => return Err(AudioError::TooLarge("WAV past 4 GiB has no room for a ds64 chunk".into())), }; - if pad == 1 { - write_at(file, l.data + data_len, &[0])?; - } if let Some(at) = l.fact { write_at(file, at, &u32::try_from(frames).unwrap_or(u32::MAX).to_le_bytes())?; } @@ -399,6 +402,11 @@ pub(crate) fn repair(file: &mut F) -> Result<(u64, u64)> write_at(file, 4, &(riff_len as u32).to_le_bytes())?; } } + // The pad byte goes last: until it is written, 8-bit mono data keeps an odd length that a + // repeated repair can count. + if pad == 1 { + write_at(file, l.data + data_len, &[0])?; + } file.seek(SeekFrom::Start(new_len))?; file.flush()?; Ok((frames, new_len)) diff --git a/crates/audio/tests/audio/roundtrip.rs b/crates/audio/tests/audio/roundtrip.rs index cc85587fcc..43ca8f1309 100644 --- a/crates/audio/tests/audio/roundtrip.rs +++ b/crates/audio/tests/audio/roundtrip.rs @@ -499,6 +499,68 @@ fn rf64_data_size_comes_from_the_ds64_chunk_after_wave() { two.splice(at..at, later); let (info, buf) = decode(&two, Some("wav")).unwrap(); assert_eq!((info.frames, buf.frames()), (300, 300)); + + // A 16-byte first ds64 chunk gives the reader the data size, so repair does not use the later one. + let mut short = two; + short[16..20].copy_from_slice(&16u32.to_le_bytes()); + short[28..36].copy_from_slice(&4u64.to_le_bytes()); + short[36..44].copy_from_slice(&[&b"JUNK"[..], &4u32.to_le_bytes()].concat()); + assert_eq!(decode(&short, Some("wav")).unwrap().1.frames(), 1); + let repaired = craft_audio::repair_wav(&mut std::io::Cursor::new(short)); + assert!(matches!(repaired, Err(craft_audio::AudioError::Malformed(_))), "{repaired:?}"); +} + +/// A file whose writes fail once `writes` of them have gone through. +struct FailingWrites { + file: std::io::Cursor>, + writes: usize, +} + +impl std::io::Read for FailingWrites { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + std::io::Read::read(&mut self.file, buf) + } +} + +impl std::io::Write for FailingWrites { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if self.writes == 0 { + return Err(std::io::Error::other("disk full")); + } + self.writes -= 1; + std::io::Write::write(&mut self.file, buf) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +impl std::io::Seek for FailingWrites { + fn seek(&mut self, to: std::io::SeekFrom) -> std::io::Result { + std::io::Seek::seek(&mut self.file, to) + } +} + +#[test] +fn repair_wav_runs_again_after_a_write_error() { + let mut u8_mono = craft_audio::pcm_wav_header(0, 1, 8_000, 8); + u8_mono.extend([0x80; 3]); + let opts = EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24); + let (int24, _) = unfinished_wav(&sine(44_100, 1, 999), &opts, 2); + for (file, frames) in [(u8_mono, 3), (int24, 999)] { + let mut whole = std::io::Cursor::new(file.clone()); + let repaired = craft_audio::repair_wav(&mut whole).unwrap(); + assert_eq!(repaired.frames, frames); + for writes in 0.. { + let mut failing = FailingWrites { file: std::io::Cursor::new(file.clone()), writes }; + if craft_audio::repair_wav(&mut failing).is_ok() { + break; + } + let mut again = failing.file; + assert_eq!(craft_audio::repair_wav(&mut again).unwrap(), repaired, "stopped after {writes} writes"); + assert_eq!(again.into_inner(), *whole.get_ref(), "stopped after {writes} writes"); + } + } } #[test] From ce2cd56271a768eaadc5505fe01a19a3f63b1fb9 Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Tue, 24 Nov 2026 20:55:24 +0100 Subject: [PATCH 09/14] Focus: a Tab onto a stop gone in the same pass goes on to the next stop Since a focused stop that is no longer shown leaves focus nowhere (8206a076a), a Tab onto a stop that exists only while another one holds the focus (a field's completion list, shown while the field is focused) lost the focus: in the pass the Tab moved it, the target was not shown, and the next Tab started again at the window's first stop. A stop the focus arrived at in this pass never held it, so it now hands the focus on: to the next stop of its scope that is shown, in the direction of the Tab, else back to the stop the Tab left. A focused stop that goes away later still leaves focus nowhere. --- crates/ui-contract/src/runtime/focus/nav.rs | 35 ++++++++++++++++-- crates/ui-panels/tests/it/focus/scopes.rs | 40 ++++++++++++++++++++- 2 files changed, 71 insertions(+), 4 deletions(-) diff --git a/crates/ui-contract/src/runtime/focus/nav.rs b/crates/ui-contract/src/runtime/focus/nav.rs index 8dce33400b..0e92bebc28 100644 --- a/crates/ui-contract/src/runtime/focus/nav.rs +++ b/crates/ui-contract/src/runtime/focus/nav.rs @@ -590,9 +590,38 @@ impl State { let target = owner.or_else(|| { gone.stop.arena.and_then(|arena| self.stops.iter().filter(live).find(|rec| rec.stop.id == arena && rec.stop.part.is_none()).cloned()) }); - Some(match target { - Some(target) => self.focus_stop_from(target, FocusOrigin::Removal), - None => vec![Act::Surrender(root)], + if let Some(target) = target { + return Some(self.focus_stop_from(target, FocusOrigin::Removal)); + } + // A stop that Tab or a request moved the focus to in this pass, and that is not shown in it (a list a field shows + // only while it is focused), never held the focus: it goes on to the next stop that is, in the direction of the + // Tab, else back to the stop the Tab left. + if let Some(next) = self.arrived_unshown(key, gone.scope) { + return Some(self.focus_stop_from(next, FocusOrigin::Request)); + } + Some(vec![Act::Surrender(root)]) + } + + /// The stop that takes the focus from `key`, a stop of `scope` the focus arrived at in this pass that is not shown in + /// it: the next stop of `scope` in last pass's order that this pass shows (`live`), the previous one for a Shift+Tab, + /// else the stop a Tab left. `None` when the focus did not arrive at `key` in this pass. + fn arrived_unshown(&self, key: StopKey, scope: Option) -> Option { + let live = |rec: &&StopRec| !self.fading(rec.scope); + // `end` has moved the frame on: an arrival of this pass is stamped with the frame before. + let arrived = self.arrived.is_some_and(|(frame, at, _)| at == key && frame + 1 == self.frame); + if !arrived { + return None; + } + let tab = self.press.tabbed_from; + let forward = tab.is_none_or(|(_, forward)| forward); + let order: Vec<&StopRec> = + self.last_stops.iter().filter(|rec| rec.scope == scope && (rec.stop.key() == key || !rec.stop.press_only)).collect(); + let at = order.iter().position(|rec| rec.stop.key() == key)?; + let shown = |candidate: &&StopRec| self.stops.iter().filter(&live).find(|rec| rec.stop.key() == candidate.stop.key()).cloned(); + let next = if forward { order[at + 1..].iter().find_map(shown) } else { order[..at].iter().rev().find_map(shown) }; + next.or_else(|| { + let (from, _) = tab?; + self.stops.iter().filter(&live).find(|rec| rec.stop.id == from || rec.stop.root == from).cloned() }) } diff --git a/crates/ui-panels/tests/it/focus/scopes.rs b/crates/ui-panels/tests/it/focus/scopes.rs index 6b3def45b7..e001718833 100644 --- a/crates/ui-panels/tests/it/focus/scopes.rs +++ b/crates/ui-panels/tests/it/focus/scopes.rs @@ -1,6 +1,6 @@ //! Focus scopes: initial focus, restore, trapping, panes, programmatic requests and focus after removal. -use super::{control, focus, focused}; +use super::{control, focus, focused, id, tap}; use craft_ui::testing::{Frames, trial}; use egui::Ui; use std::cell::Cell; @@ -30,3 +30,41 @@ fn focus_goes_nowhere_when_the_focused_stop_is_not_shown() { frames.idle(2, &mut show); assert_eq!(focused(&frames.ctx), None, "no stop after it: the one before does not take the focus either"); } + +/// A stop that is shown only while another one holds the focus (a field's completion list) is not shown in the pass a +/// Tab moves the focus onto it: the focus goes on to the next stop that is shown, not nowhere. +#[trial] +fn tab_onto_a_stop_gone_in_the_same_pass_goes_on_to_the_next_stop() { + let mut frames = Frames::new(); + let mut show = |ui: &mut Ui| { + control(ui, "field"); + if focused(ui.ctx()) == Some(id("field")) { + control(ui, "offer"); + } + control(ui, "next"); + }; + frames.idle(2, &mut show); + focus(&mut frames, "field", &mut show); + frames.idle(1, &mut show); + tap(&mut frames, egui::Key::Tab, egui::Modifiers::NONE, &mut show); + frames.idle(2, &mut show); + assert_eq!(focused(&frames.ctx), Some(id("next")), "the Tab goes on past the stop that went away"); +} + +/// With no stop shown after the one that went away, the Tab gives the focus back to the stop it left. +#[trial] +fn tab_onto_the_last_stop_gone_in_the_same_pass_stays_where_it_was() { + let mut frames = Frames::new(); + let mut show = |ui: &mut Ui| { + control(ui, "field"); + if focused(ui.ctx()) == Some(id("field")) { + control(ui, "offer"); + } + }; + frames.idle(2, &mut show); + focus(&mut frames, "field", &mut show); + frames.idle(1, &mut show); + tap(&mut frames, egui::Key::Tab, egui::Modifiers::NONE, &mut show); + frames.idle(2, &mut show); + assert_eq!(focused(&frames.ctx), Some(id("field")), "the focus stays on the stop the Tab left"); +} From 3632f97645c1256756b5f3e308bfde0d638f12f8 Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Wed, 25 Nov 2026 17:45:46 +0100 Subject: [PATCH 10/14] Focus: a Tab that lands on a stop gone in the same pass goes on through Tab's own entries Review (aiongg): the fallback after such a Tab walked last pass's stops by scope and press-only, so it skipped the rules Tab applies, and it acted for any arrival in the frame, a press's or a restoration's as well as a Tab's. The entries now come from the same `tab_entries` Tab cycles, kept to the stops this pass shows: the next entry in the Tab's direction, wrapping as Tab does from the last entry. It acts only for an arrival by Tab: the Tab this pass made from the stop it left, at a stop whose focus came by request. --- crates/ui-contract/src/runtime/focus.rs | 4 ++ crates/ui-contract/src/runtime/focus/nav.rs | 56 ++++++++++++--------- crates/ui-panels/tests/it/focus/scopes.rs | 20 ++++++++ 3 files changed, 56 insertions(+), 24 deletions(-) diff --git a/crates/ui-contract/src/runtime/focus.rs b/crates/ui-contract/src/runtime/focus.rs index 7cdd0fe54d..2cf1bc6116 100644 --- a/crates/ui-contract/src/runtime/focus.rs +++ b/crates/ui-contract/src/runtime/focus.rs @@ -148,6 +148,10 @@ pub(crate) struct RowGroups { #[derive(Default)] pub(crate) struct State { pub(crate) stops: Vec, + /// The Tab settings of this pass (`BeginIn::tab_all_controls`, `BeginIn::dialog_tab`), kept for the moves the end + /// hook makes: a Tab that lands on a stop this pass does not show goes on through this pass's Tab entries. + pub(crate) tab_all_controls: bool, + pub(crate) dialog_tab: TabReach, stop_ids: IdSet, /// The egui roots of `stops`. stop_roots: IdSet, diff --git a/crates/ui-contract/src/runtime/focus/nav.rs b/crates/ui-contract/src/runtime/focus/nav.rs index 2dddce4cd2..50e4fdd69f 100644 --- a/crates/ui-contract/src/runtime/focus/nav.rs +++ b/crates/ui-contract/src/runtime/focus/nav.rs @@ -402,8 +402,17 @@ impl State { /// A Tab move. In a dialog's trap with `dialog_tab` at `Fields`, only text stops are entries, whatever the /// window's rule: a roving group whose arrival member holds no text is skipped too. pub(super) fn tab(&mut self, forward: bool, all_controls: bool, dialog_tab: TabReach) -> Vec { - // A child of a collection row tabs on from its collection: the row groups are no Tab entries. The content of a - // layer that keeps the focus on its anchor (a dropdown) is no Tab entry either: Tab goes on from the anchor. + let (current, entries) = self.tab_entries(all_controls, dialog_tab); + let top = current.as_ref().and_then(|rec| rec.stop.group).map(|group| self.last().outermost(group)); + let Some(next) = cycle(&entries, current.as_ref(), top, forward) else { return Vec::new() }; + let arrival = entries[next].arrival().clone(); + self.focus_stop(arrival) + } + + /// The Tab entries this pass moves over, from the stop the focus is on (a row's child tabs on from its collection, + /// a dropdown's content from its anchor). They are last pass's entries: what `tab` cycles, and what a Tab that + /// landed on a stop this pass does not show goes on through. + fn tab_entries(&self, all_controls: bool, dialog_tab: TabReach) -> (Option, Vec) { let current = self.stop_of_focus().map(|rec| { let owner = rec.stop.group.and_then(|group| self.group(group)).filter(|group| group.row).and_then(|group| self.row_owner(&group)); let rec = owner.unwrap_or(rec); @@ -414,10 +423,7 @@ impl State { let fields = in_dialog && dialog_tab == TabReach::Fields; let mut entries = self.entries(trap, all_controls && !fields); entries.retain(|entry| self.anchored_layer(entry.arrival().scope).is_none() && (!fields || entry.arrival().stop.text)); - let top = current.as_ref().and_then(|rec| rec.stop.group).map(|group| self.last().outermost(group)); - let Some(next) = cycle(&entries, current.as_ref(), top, forward) else { return Vec::new() }; - let arrival = entries[next].arrival().clone(); - self.focus_stop(arrival) + (current, entries) } /// F6: the first stop of the next pane, with its label as the announcement. Inside a trapping scope (a modal @@ -602,33 +608,33 @@ impl State { // A stop that Tab or a request moved the focus to in this pass, and that is not shown in it (a list a field shows // only while it is focused), never held the focus: it goes on to the next stop that is, in the direction of the // Tab, else back to the stop the Tab left. - if let Some(next) = self.arrived_unshown(key, gone.scope) { + if let Some(next) = self.arrived_unshown(key) { return Some(self.focus_stop_from(next, FocusOrigin::Request)); } Some(vec![Act::Surrender(root)]) } - /// The stop that takes the focus from `key`, a stop of `scope` the focus arrived at in this pass that is not shown in - /// it: the next stop of `scope` in last pass's order that this pass shows (`live`), the previous one for a Shift+Tab, - /// else the stop a Tab left. `None` when the focus did not arrive at `key` in this pass. - fn arrived_unshown(&self, key: StopKey, scope: Option) -> Option { - let live = |rec: &&StopRec| !self.fading(rec.scope); + /// The stop a Tab that landed on a stop this pass does not show goes on to: the next Tab entry, in the direction + /// of the Tab, that this pass shows. A stop the focus arrived at by a press, a scope opening or a restoration never + /// held the focus, so it leaves the focus nowhere as any other removed stop does: only a Tab takes it here. + fn arrived_unshown(&self, key: StopKey) -> Option { + // The Tab this pass made, from the stop it left, and the direction it went. + let (_, forward) = self.press.tabbed_from?; // `end` has moved the frame on: an arrival of this pass is stamped with the frame before. - let arrived = self.arrived.is_some_and(|(frame, at, _)| at == key && frame + 1 == self.frame); + let arrived = self.arrived.is_some_and(|(frame, at, origin)| at == key && frame + 1 == self.frame && origin == FocusOrigin::Request); if !arrived { return None; } - let tab = self.press.tabbed_from; - let forward = tab.is_none_or(|(_, forward)| forward); - let order: Vec<&StopRec> = - self.last_stops.iter().filter(|rec| rec.scope == scope && (rec.stop.key() == key || !rec.stop.press_only)).collect(); - let at = order.iter().position(|rec| rec.stop.key() == key)?; - let shown = |candidate: &&StopRec| self.stops.iter().filter(&live).find(|rec| rec.stop.key() == candidate.stop.key()).cloned(); - let next = if forward { order[at + 1..].iter().find_map(shown) } else { order[..at].iter().rev().find_map(shown) }; - next.or_else(|| { - let (from, _) = tab?; - self.stops.iter().filter(&live).find(|rec| rec.stop.id == from || rec.stop.root == from).cloned() - }) + let (current, entries) = self.tab_entries(self.tab_all_controls, self.dialog_tab); + let current = current?; + let top = current.stop.group.map(|group| self.last().outermost(group)); + let at = entries.iter().position(|entry| entry.holds(¤t, top))?; + let shown = |rec: &StopRec| self.stops.iter().any(|now| now.stop.key() == rec.stop.key() && !self.fading(now.scope)); + let count = entries.len(); + (1..=count) + .map(|step| if forward { (at + step) % count } else { (at + count - step) % count }) + .find(|index| shown(entries[*index].arrival())) + .map(|index| entries[index].arrival().clone()) } /// Whether the scope `scope` of this pass, or one around it, is a layer playing its exit: its stops take no focus. @@ -843,6 +849,8 @@ pub(super) fn begin(state: &mut State, input: BeginIn) -> (Vec, Vec state.rotate(); state.frame = input.frame; state.focus_now = input.focused; + state.tab_all_controls = input.tab_all_controls; + state.dialog_tab = input.dialog_tab; state.press.rotate(input.focused); let mut acts = Vec::new(); let mut announcements = Vec::new(); diff --git a/crates/ui-panels/tests/it/focus/scopes.rs b/crates/ui-panels/tests/it/focus/scopes.rs index e001718833..902618b973 100644 --- a/crates/ui-panels/tests/it/focus/scopes.rs +++ b/crates/ui-panels/tests/it/focus/scopes.rs @@ -68,3 +68,23 @@ fn tab_onto_the_last_stop_gone_in_the_same_pass_stays_where_it_was() { frames.idle(2, &mut show); assert_eq!(focused(&frames.ctx), Some(id("field")), "the focus stays on the stop the Tab left"); } + +/// A Tab onto the last entry that went away wraps to the first entry, as Tab does from the last stop, rather than +/// staying on the stop it left. +#[trial] +fn tab_onto_the_last_stop_gone_in_the_same_pass_wraps_to_the_first() { + let mut frames = Frames::new(); + let mut show = |ui: &mut Ui| { + control(ui, "first"); + control(ui, "field"); + if focused(ui.ctx()) == Some(id("field")) { + control(ui, "offer"); + } + }; + frames.idle(2, &mut show); + focus(&mut frames, "field", &mut show); + frames.idle(1, &mut show); + tap(&mut frames, egui::Key::Tab, egui::Modifiers::NONE, &mut show); + frames.idle(2, &mut show); + assert_eq!(focused(&frames.ctx), Some(id("first")), "the last entry gone, Tab wraps to the first, as it does from any last stop"); +} From 693b97c792c34a1868073a0a49c8a2ef4a9e1bbb Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Thu, 26 Nov 2026 17:44:16 +0100 Subject: [PATCH 11/14] Focus: the stop a Tab leaves, and a restoring scope's opener, after an unshown Tab target Review (CodeRabbit), nav.rs:612 and nav.rs:602. Two loose ends in the recovery that moves focus on from a Tab target this pass does not show: - `tabbed_from` recorded the widget egui held at the begin hook, so a focus request the same pass applied (which moves the focus before the Tab) was not the stop the Tab left, and a text part that lost the focus by Tab read it as a blur. It now records the stop focus is on as the Tab applies. - The recovery moved the focus with no source, so entering a scope that restores the focus made the stop that went away its opener; closing that scope would return the focus to a stop that is gone. The Tab's own source is the opener now. Trial: text::tab_source::a_pending_focus_request_moves_the_stop_a_tab_leaves. --- crates/ui-contract/src/runtime/focus/nav.rs | 41 ++++++++++++++++-- crates/ui-widgets/tests/it/text/mod.rs | 1 + crates/ui-widgets/tests/it/text/tab_source.rs | 42 +++++++++++++++++++ 3 files changed, 80 insertions(+), 4 deletions(-) create mode 100644 crates/ui-widgets/tests/it/text/tab_source.rs diff --git a/crates/ui-contract/src/runtime/focus/nav.rs b/crates/ui-contract/src/runtime/focus/nav.rs index 39a27228d5..9a56c7d5ec 100644 --- a/crates/ui-contract/src/runtime/focus/nav.rs +++ b/crates/ui-contract/src/runtime/focus/nav.rs @@ -248,8 +248,14 @@ impl State { /// [`focus_stop`](Self::focus_stop) with what moved focus there. A row that takes the focus back from its removed /// child is not revealed: nothing chose to show it. fn focus_stop_from(&mut self, rec: StopRec, origin: FocusOrigin) -> Vec { + self.focus_stop_from_source(rec, origin, None) + } + + /// [`focus_stop_from`](Self::focus_stop_from) with the stop the focus came from, for a move past a stop that is no + /// longer shown: a restoring scope's opener is that stop, which is still there, not the one that went away. + fn focus_stop_from_source(&mut self, rec: StopRec, origin: FocusOrigin, source: Option<&StopRec>) -> Vec { let key = rec.stop.key(); - let acts = self.enter_stop(rec, origin); + let acts = self.enter_stop_from(rec, origin, source); if origin != FocusOrigin::Removal { self.revealed = Some(key); } @@ -263,7 +269,16 @@ impl State { } fn enter_stop(&mut self, rec: StopRec, origin: FocusOrigin) -> Vec { - self.note_entry(&rec); + self.enter_stop_from(rec, origin, None) + } + + /// [`enter_stop`](Self::enter_stop) with the stop the focus came from, when it is not the stop focus is on: the Tab + /// source a recovery moves the focus on from. + fn enter_stop_from(&mut self, rec: StopRec, origin: FocusOrigin, source: Option<&StopRec>) -> Vec { + match source { + Some(from) => self.note_entry_from(&rec, from), + None => self.note_entry(&rec), + } let stop = &rec.stop; let moved = self.focus_now != Some(stop.root) || self.focused.get(&stop.root) != Some(&stop.key()); if moved { @@ -279,6 +294,12 @@ impl State { /// returns there. fn note_entry(&mut self, rec: &StopRec) { let Some(from) = self.stop_of_focus() else { return }; + self.note_entry_from(rec, &from); + } + + /// [`note_entry`](Self::note_entry) with the stop the move came from, which is not the stop focus is on when a + /// recovery moves it past a stop that is no longer shown. + fn note_entry_from(&mut self, rec: &StopRec, from: &StopRec) { let mut at = rec.scope; while let Some(id) = at { let Some(scope) = self.scopes.get(&id).or_else(|| self.last_scopes.get(&id)) else { return }; @@ -599,7 +620,9 @@ impl State { // only while it is focused), never held the focus: it goes on to the next stop that is, in the direction of the // Tab, else back to the stop the Tab left. if let Some(next) = self.arrived_unshown(key) { - return Some(self.focus_stop_from(next, FocusOrigin::Request)); + // The move comes from the stop the Tab left, which is still shown, not from the stop it landed on. + let source = self.press.tabbed_from.and_then(|(from, _)| self.stop_by_root(from)); + return Some(self.focus_stop_from_source(next, FocusOrigin::Request, source.as_ref())); } Some(vec![Act::Surrender(root)]) } @@ -627,6 +650,13 @@ impl State { .map(|index| entries[index].arrival().clone()) } + /// The stop focus was on when `root` held egui focus: the stop of that root, or the member recorded for it. + fn stop_by_root(&self, root: Id) -> Option { + let key = self.focused.get(&root).copied(); + key.and_then(|key| self.stops.iter().chain(&self.last_stops).find(|rec| rec.stop.key() == key).cloned()) + .or_else(|| self.stops.iter().chain(&self.last_stops).find(|rec| rec.stop.root == root).cloned()) + } + /// Whether the scope `scope` of this pass, or one around it, is a layer playing its exit: its stops take no focus. fn fading(&self, scope: Option) -> bool { let mut at = scope; @@ -869,9 +899,12 @@ pub(super) fn begin(state: &mut State, input: BeginIn) -> (Vec, Vec acts.extend(state.apply_target(target)); } for forward in input.nav.tabs { + // The stop the Tab leaves is the one focus is on now: a request this pass applied above may have moved it on + // from the widget egui held at the begin hook, and the components read this to tell a Tab from a blur. + let from = state.focus_now; let moved = state.tab(forward, input.tab_all_controls, input.dialog_tab); state.press.by_keys |= !moved.is_empty(); - if let Some(from) = input.focused.filter(|_| !moved.is_empty()) { + if let Some(from) = from.filter(|_| !moved.is_empty()) { state.press.tabbed_from = Some((from, forward)); } acts.extend(moved); diff --git a/crates/ui-widgets/tests/it/text/mod.rs b/crates/ui-widgets/tests/it/text/mod.rs index 57a72fe228..f23b5756b1 100644 --- a/crates/ui-widgets/tests/it/text/mod.rs +++ b/crates/ui-widgets/tests/it/text/mod.rs @@ -18,6 +18,7 @@ pub(crate) mod rtl_paragraph; pub(crate) mod selectable; pub(crate) mod step_arrows; pub(crate) mod submit_key; +pub(crate) mod tab_source; pub(crate) mod text_field; pub(crate) mod widths; pub(crate) mod word_run; diff --git a/crates/ui-widgets/tests/it/text/tab_source.rs b/crates/ui-widgets/tests/it/text/tab_source.rs new file mode 100644 index 0000000000..0f00ac9d41 --- /dev/null +++ b/crates/ui-widgets/tests/it/text/tab_source.rs @@ -0,0 +1,42 @@ +//! The stop a Tab leaves is the one focus is on when the Tab applies: a focus request the same pass moved the focus to +//! the second field means the Tab left the second field, so the first, which lost the focus to the request, does not +//! report a Tab departure. + +use craft_ui::contract::{Bind, Show as _}; +use craft_ui::runtime::focus::{FocusTarget, request}; +use craft_ui::testing::focus::key_release; +use craft_ui::testing::input::key_press; +use craft_ui::testing::{Fixture, trial}; +use craft_ui::text::TextField; +use egui::{Id, Key, Modifiers}; +use std::cell::{Cell, RefCell}; +use std::rc::Rc; + +#[trial] +fn a_pending_focus_request_moves_the_stop_a_tab_leaves() { + let first = Rc::new(RefCell::new("one".to_owned())); + let second = Rc::new(RefCell::new("two".to_owned())); + let second_id = Rc::new(Cell::new(Id::NULL)); + let first_left = Rc::new(Cell::new(None::>)); + let (held_first, held_second, held_id, held_left) = (first.clone(), second.clone(), second_id.clone(), first_left.clone()); + let mut fixture = Fixture::new(move |ui| { + let one = TextField::new("First", Bind::bound(&mut *held_first.borrow_mut())).show(ui); + // The first field lost the focus to a request this pass, which is no Tab departure. + if let Some(Some(left)) = one.left_by_tab.map(Some) { + held_left.set(Some(Some(left))); + } + let two = TextField::new("Second", Bind::bound(&mut *held_second.borrow_mut())).show(ui); + held_id.set(two.response.id); + }); + fixture.settle(); + let first_field = fixture.by_label("First").expect("the first field"); + fixture.click(&first_field).settle(); + assert!(fixture.focused_stop().is_some(), "the first field has the focus"); + // One pass: the request for the second field, then the Tab that leaves it; the first field must not claim the Tab. + request(fixture.ctx(), FocusTarget::Id(second_id.get())); + fixture.frame(vec![key_press(Key::Tab, Modifiers::NONE)]); + fixture.frame(vec![key_release(Key::Tab, Modifiers::NONE)]); + fixture.frame(Vec::new()); + assert_eq!(first_left.get(), None, "the first field lost the focus to the request, not to the Tab"); + assert!(fixture.by_label("Second").is_some(), "both fields are still shown"); +} From d46582174adf24987a660cfbb49471ef785b5644 Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Thu, 26 Nov 2026 22:12:47 +0100 Subject: [PATCH 12/14] Focus: a Tab from no focus still records which way it went Review (CodeRabbit), nav.rs:907. The Tab direction was kept only with a source stop, so a Tab that began with nothing focused and landed on a stop this pass does not show had no direction to read and the focus was surrendered instead of going on to the next shown Tab entry. The direction is now recorded for every Tab that moved the focus, and the source stop stays what the restoring scope's opener needs. Trial: tab_from_no_focus_onto_a_stop_gone_in_the_same_pass_goes_on. --- crates/ui-contract/src/runtime/focus/nav.rs | 11 +++++++---- crates/ui-contract/src/runtime/focus/press.rs | 3 +++ crates/ui-panels/tests/it/focus/scopes.rs | 19 +++++++++++++++++++ 3 files changed, 29 insertions(+), 4 deletions(-) diff --git a/crates/ui-contract/src/runtime/focus/nav.rs b/crates/ui-contract/src/runtime/focus/nav.rs index 9a56c7d5ec..4316225ec9 100644 --- a/crates/ui-contract/src/runtime/focus/nav.rs +++ b/crates/ui-contract/src/runtime/focus/nav.rs @@ -631,8 +631,8 @@ impl State { /// of the Tab, that this pass shows. A stop the focus arrived at by a press, a scope opening or a restoration never /// held the focus, so it leaves the focus nowhere as any other removed stop does: only a Tab takes it here. fn arrived_unshown(&self, key: StopKey) -> Option { - // The Tab this pass made, from the stop it left, and the direction it went. - let (_, forward) = self.press.tabbed_from?; + // The Tab this pass made and the direction it went; the stop it left may be none at all. + let forward = self.press.tabbed?; // `end` has moved the frame on: an arrival of this pass is stamped with the frame before. let arrived = self.arrived.is_some_and(|(frame, at, origin)| at == key && frame + 1 == self.frame && origin == FocusOrigin::Request); if !arrived { @@ -904,8 +904,11 @@ pub(super) fn begin(state: &mut State, input: BeginIn) -> (Vec, Vec let from = state.focus_now; let moved = state.tab(forward, input.tab_all_controls, input.dialog_tab); state.press.by_keys |= !moved.is_empty(); - if let Some(from) = from.filter(|_| !moved.is_empty()) { - state.press.tabbed_from = Some((from, forward)); + if !moved.is_empty() { + // The direction is the Tab's own, whether or not a stop was there to leave: a Tab from no focus can land + // on a stop this pass does not show, and the recovery below still needs to know which way it went. + state.press.tabbed = Some(forward); + state.press.tabbed_from = from.map(|from| (from, forward)); } acts.extend(moved); } diff --git a/crates/ui-contract/src/runtime/focus/press.rs b/crates/ui-contract/src/runtime/focus/press.rs index 08fdb2f518..5bf9ec8709 100644 --- a/crates/ui-contract/src/runtime/focus/press.rs +++ b/crates/ui-contract/src/runtime/focus/press.rs @@ -59,6 +59,8 @@ struct Plan { pub(crate) struct PressState { plan: Option, pub(super) commit_now: Option, + /// A Tab (`true`) or Shift+Tab (`false`) moved focus this pass, from nothing as well as from a stop. + pub(super) tabbed: Option, /// The widget a Tab or Shift+Tab moved focus off this pass, and whether the move was forward. pub(super) tabbed_from: Option<(Id, bool)>, /// Tab, Shift+Tab or F6 moved focus this pass. @@ -76,6 +78,7 @@ impl PressState { pub(super) fn rotate(&mut self, focused: Option) { self.plan = None; self.commit_now = None; + self.tabbed = None; self.tabbed_from = None; self.by_keys = false; self.focus_at_begin = focused; diff --git a/crates/ui-panels/tests/it/focus/scopes.rs b/crates/ui-panels/tests/it/focus/scopes.rs index 902618b973..1975a7dfbf 100644 --- a/crates/ui-panels/tests/it/focus/scopes.rs +++ b/crates/ui-panels/tests/it/focus/scopes.rs @@ -88,3 +88,22 @@ fn tab_onto_the_last_stop_gone_in_the_same_pass_wraps_to_the_first() { frames.idle(2, &mut show); assert_eq!(focused(&frames.ctx), Some(id("first")), "the last entry gone, Tab wraps to the first, as it does from any last stop"); } + +/// A Tab from no focus at all can land on a stop this pass does not show (one drawn only while it lacks the focus): +/// the direction is the Tab's own, so the focus goes on to the next shown stop rather than nowhere. +#[trial] +fn tab_from_no_focus_onto_a_stop_gone_in_the_same_pass_goes_on() { + let mut frames = Frames::new(); + let mut show = |ui: &mut Ui| { + if focused(ui.ctx()) != Some(id("offer")) { + control(ui, "offer"); + } + control(ui, "first"); + control(ui, "next"); + }; + frames.idle(2, &mut show); + assert_eq!(focused(&frames.ctx), None, "nothing has the focus"); + tap(&mut frames, egui::Key::Tab, egui::Modifiers::NONE, &mut show); + frames.idle(2, &mut show); + assert_eq!(focused(&frames.ctx), Some(id("first")), "the Tab goes on past the stop it landed on"); +} From 0c82089207db38b30c9ba9be50a5a7034b042ad5 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:10:50 +0700 Subject: [PATCH 13/14] ui-contract: run the body's and the editor's per-pass work once for every component type BodyHooks::updated and editor::run were monomorphized for every container and text component; their work only needs the pass core. The generic hooks now read what they need from the component (its props, whether it senses its surface, its style's minimum size, the commit) and hand the rest to non-generic functions. No behavior change. --- crates/ui-contract/src/contract/body/hooks.rs | 115 ++++++++++-------- .../ui-contract/src/contract/body/scroll.rs | 14 +-- .../ui-contract/src/contract/body/window.rs | 50 ++++---- crates/ui-contract/src/contract/editor.rs | 26 ++-- 4 files changed, 110 insertions(+), 95 deletions(-) diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index 6704964c33..bb633f4604 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -548,60 +548,9 @@ impl ShapeHooks for BodyHooks<'_> { } fn updated(&mut self, comp: &mut C, cx: &mut Cx<'_, C>) { - use crate::contract::Pointer as _; - let props = comp.props(Internal::new()); - let (scroll, layer) = (scroll_of(props), matches!(props.mount, Mount::Layer(_) | Mount::Viewport { .. })); - // The OS asked a viewport mount's window to close: the container closes at step 15. - if matches!(props.mount, Mount::Viewport { .. }) && windows::take_close_request(cx.core.memory.ctx(), cx.core.id) { - self.close = true; - self.reason = self.reason.or(Some(CloseReason::Requested)); - } - if scroll.is_some() { - self.scroll_input(props, cx); - } - // A reveal queued for the body moves its offset against the view this pass shows, on top of a move - // `scroll_input` queued, within the offsets the content allows; the next pass takes the offset at step 4, as it - // takes the scroll bar's, and places by it. A reveal that moves nothing queues no jump, so it costs no pass. The - // part of the rect the moved view shows goes on to the scroll owner around. - if let Some((scroll, view)) = scroll.zip(self.view) - && let Some(rect) = crate::contract::take_reveal(&cx.core.ctx, cx.core.id) - { - let view = self.shown_view(scroll, view); - let (by, _) = crate::contract::steps::reveal_move(rect, view); - let rtl = cx.core.env.direction().is_rtl(); - let id = cx.core.id; - let from = super::scroll::queued_jump(&cx.core.ctx, id).unwrap_or(self.offset); - let mut offset = from; - offset.y += f64::from(by.y); - offset.x += f64::from(if rtl { -by.x } else { by.x }); - let offset = self.clamped(scroll, view.size(), offset); - // A reveal of what the view shows moves nothing: no jump, so no repeated pass. - if offset != from { - super::scroll::queue_jump(&cx.core.ctx, id, offset); - } - let moved = Vec2::new((offset.x - from.x) as f32, (offset.y - from.y) as f32); - let moved = Vec2::new(if rtl { -moved.x } else { moved.x }, moved.y); - crate::contract::Focus::reveal(cx, rect.translate(-moved).intersect(view)); - } - // AccessKit Expand, Collapse and Click reach a collapsible container as an activation: it folds or unfolds. - if props.collapse.is_some() && cx.activation().is_some_and(|activation| activation.by_key) { - self.open = !self.open; - } - self.band_double(cx.core); - self.surface_press(comp.sense().contains(craft_behavior::Sense::SURFACE), cx.core); - let band = props.header.is_some_and(|header| header.band == DragBand::Move); - if (band || matches!(props.mount, Mount::Viewport { .. } | Mount::Window { .. })) - && let Some(viewport) = os_window(props, cx.core.memory.ctx(), cx.core.id, &cx.core.env) - { - self.window_os(viewport, props, cx); - self.window_movable(viewport, cx.core); - } - self.pane_drag(props, cx.core); - if layer && !(matches!(props.mount, Mount::Viewport { .. }) && windows::mount_window(cx.core.memory.ctx(), cx.core.id)) { - self.window_keys(props, cx); - self.window_drag(props, cx); - } - self.window_placed(props, cx.core); + let style_min = cx.style.metrics().min_size; + let surface = comp.sense().contains(craft_behavior::Sense::SURFACE); + self.updated_core(comp.props(Internal::new()), surface, style_min, cx.core); // The body moves and resizes the layer in screen space; the caller places it in its parent's layer space. let from_screen = crate::runtime::overlay::parent_space(&cx.core.ctx, cx.core.id).inverse(); for mut change in std::mem::take(&mut self.reports) { @@ -790,6 +739,64 @@ fn first_line_found(ctx: &Context, (header, body): (Id, Id), top: f32, moved: f3 } impl BodyHooks<'_> { + /// Step 13 of a body, without the component: what `updated` does for every container type, kept out of the + /// generic hook so the web build carries it once. The placement changes it reports wait in `self.reports`. + fn updated_core(&mut self, props: &ContainerProps, surface: bool, style_min: Vec2, core: &mut CxCore<'_>) { + use crate::contract::Pointer as _; + let (scroll, layer) = (scroll_of(props), matches!(props.mount, Mount::Layer(_) | Mount::Viewport { .. })); + // The OS asked a viewport mount's window to close: the container closes at step 15. + if matches!(props.mount, Mount::Viewport { .. }) && windows::take_close_request(core.memory.ctx(), core.id) { + self.close = true; + self.reason = self.reason.or(Some(CloseReason::Requested)); + } + if scroll.is_some() { + self.scroll_input(props, core); + } + // A reveal queued for the body moves its offset against the view this pass shows, on top of a move + // `scroll_input` queued, within the offsets the content allows; the next pass takes the offset at step 4, as it + // takes the scroll bar's, and places by it. A reveal that moves nothing queues no jump, so it costs no pass. The + // part of the rect the moved view shows goes on to the scroll owner around. + if let Some((scroll, view)) = scroll.zip(self.view) + && let Some(rect) = crate::contract::take_reveal(&core.ctx, core.id) + { + let view = self.shown_view(scroll, view); + let (by, _) = crate::contract::steps::reveal_move(rect, view); + let rtl = core.env.direction().is_rtl(); + let id = core.id; + let from = super::scroll::queued_jump(&core.ctx, id).unwrap_or(self.offset); + let mut offset = from; + offset.y += f64::from(by.y); + offset.x += f64::from(if rtl { -by.x } else { by.x }); + let offset = self.clamped(scroll, view.size(), offset); + // A reveal of what the view shows moves nothing: no jump, so no repeated pass. + if offset != from { + super::scroll::queue_jump(&core.ctx, id, offset); + } + let moved = Vec2::new((offset.x - from.x) as f32, (offset.y - from.y) as f32); + let moved = Vec2::new(if rtl { -moved.x } else { moved.x }, moved.y); + crate::contract::Focus::reveal(core, rect.translate(-moved).intersect(view)); + } + // AccessKit Expand, Collapse and Click reach a collapsible container as an activation: it folds or unfolds. + if props.collapse.is_some() && core.activation().is_some_and(|activation| activation.by_key) { + self.open = !self.open; + } + self.band_double(core); + self.surface_press(surface, core); + let band = props.header.is_some_and(|header| header.band == DragBand::Move); + if (band || matches!(props.mount, Mount::Viewport { .. } | Mount::Window { .. })) + && let Some(viewport) = os_window(props, core.memory.ctx(), core.id, &core.env) + { + self.window_os(viewport, props, core, style_min); + self.window_movable(viewport, core); + } + self.pane_drag(props, core); + if layer && !(matches!(props.mount, Mount::Viewport { .. }) && windows::mount_window(core.memory.ctx(), core.id)) { + self.window_keys(props, core, style_min); + self.window_drag(props, core, style_min); + } + self.window_placed(props, core); + } + /// The measuring run of the regions in `self.room`, under the inputs `key`: what they took together, padding /// included. `content`: the size the body's content took in the run taken back before this one, recorded with it. fn measure_run( diff --git a/crates/ui-contract/src/contract/body/scroll.rs b/crates/ui-contract/src/contract/body/scroll.rs index e592fcd68a..d28c314d33 100644 --- a/crates/ui-contract/src/contract/body/scroll.rs +++ b/crates/ui-contract/src/contract/body/scroll.rs @@ -219,12 +219,12 @@ impl BodyHooks<'_> { /// it, so the content laid out for the view (out-of-view children skip their run, `runtime::lazy`) is the content /// shown. Every input read here is the pass's own, and the strips step by the pass's elapsed time, so a pass that /// repeats a frame moves nothing. - pub(super) fn scroll_input(&self, props: &ContainerProps, cx: &mut Cx<'_, C>) { + pub(super) fn scroll_input(&self, props: &ContainerProps, core: &mut CxCore<'_>) { use crate::contract::Pointer as _; let Some(scroll) = scroll_of(props) else { return }; - let ctx = cx.core.ctx.clone(); + let ctx = core.ctx.clone(); let mut offset = self.offset; - if let Some(range) = cx.scroll_moved(SCROLL_Y) { + if let Some(range) = core.scroll_moved(SCROLL_Y) { offset.y = range.start; } // Resting the pointer on a strip scrolls toward it at a steady speed. @@ -232,19 +232,19 @@ impl BodyHooks<'_> { let elapsed = crate::runtime::frame::facts(&ctx).elapsed.clamp(0.0, 0.1); let step = f64::from(STRIP_ROWS_PER_SECOND * self.row) * elapsed; for (strip, toward) in [(STRIP_BACK, -1.0), (STRIP_FORWARD, 1.0)] { - if cx.core.results.get(&(strip, None)).is_some_and(|result| result.hovered) { + if core.results.get(&(strip, None)).is_some_and(|result| result.hovered) { offset.y += toward * step; } } } - if let Some(range) = cx.scroll_moved(SCROLL_X) { + if let Some(range) = core.scroll_moved(SCROLL_X) { offset.x = range.start; } - self.access_scroll(scroll, &mut offset, cx.core); + self.access_scroll(scroll, &mut offset, core); let view = self.last.view.map_or(Vec2::ZERO, |view| self.shown_view(scroll, rect_of(view)).size()); let offset = self.clamped(scroll, view, offset); if offset != self.offset { - queue_jump(&ctx, cx.core.id, offset); + queue_jump(&ctx, core.id, offset); } } diff --git a/crates/ui-contract/src/contract/body/window.rs b/crates/ui-contract/src/contract/body/window.rs index a36f7d200e..7829c9be88 100644 --- a/crates/ui-contract/src/contract/body/window.rs +++ b/crates/ui-contract/src/contract/body/window.rs @@ -13,7 +13,7 @@ use crate::runtime::env::{EnvView, ShellEntry}; use crate::runtime::memory::sub; use crate::runtime::windows::{self, ResizeEdge, WindowAction, WindowHit}; use crate::runtime::{keys, pointer}; -use crate::style::{ComponentStyle as _, UiTokens}; +use crate::style::UiTokens; use craft_behavior::{CursorIcon, GesturePhase, HitLevel, HitPriority, PartKey, PointerEvent, PressPhase}; use craft_host::target::{Caps, WindowChrome, WindowState}; use craft_keymap::{Chord, Key, Mods}; @@ -402,15 +402,15 @@ impl BodyHooks<'_> { /// resize by a step (Shift: four steps), Enter, the command again or a primary press keeps the placement, Escape /// restores it, and focus leaving the container ends the mode. The mode holds its chords through the key stage, so no /// component under focus sees them. Each step is reported as a `PlacementKind::Keyboard` change. - pub(super) fn window_keys(&mut self, props: &ContainerProps, cx: &mut Cx<'_, C>) { - let (id, ctx) = (cx.core.id, cx.core.ctx.clone()); + pub(super) fn window_keys(&mut self, props: &ContainerProps, core: &mut CxCore<'_>, style_min: Vec2) { + let (id, ctx) = (core.id, core.ctx.clone()); let (Some(window), Some(overlay)) = (window_instance(props, id), overlay_of(props)) else { return }; let overlay = overlay.in_screen(crate::runtime::overlay::parent_space(&ctx, id)); let overlay = &*overlay; - let limits = Limits::new(overlay, window_min(props, cx.style.metrics().min_size)); - let rect = cx.core.rect; - let rtl = cx.core.env.direction().is_rtl(); - let mut slot = PlacementSlot::new(&mut *cx.core.memory, id, self.save.as_ref(), overlay); + let limits = Limits::new(overlay, window_min(props, style_min)); + let rect = core.rect; + let rtl = core.env.direction().is_rtl(); + let mut slot = PlacementSlot::new(&mut *core.memory, id, self.save.as_ref(), overlay); let current = slot.read(); let step = |rect: Rect, phase: GesturePhase| PlacementChange { rect, phase, pointer: None, kind: PlacementKind::Keyboard, continued: false }; let started = commands::take_for_instance(&ctx, Some(window), false, WindowCommand::from_ref).map(|(command, _)| command); @@ -480,21 +480,21 @@ impl BodyHooks<'_> { /// A drag of the move band or a grip of a layer (not an OS window): the layer follows the pointer within the /// limits, and each step is reported. The drag runs from the rect the layer had when the press went down. Escape, /// which cancels the press, restores the placement from before. - pub(super) fn window_drag(&mut self, props: &ContainerProps, cx: &mut Cx<'_, C>) { + pub(super) fn window_drag(&mut self, props: &ContainerProps, core: &mut CxCore<'_>, style_min: Vec2) { let Some(overlay) = overlay_of(props) else { return }; // A band that moves the window below starts the OS move of the window the layer is shown in. if overlay.moves_window { - let viewport = pass::current_viewport(&cx.core.ctx); - self.window_os(viewport, props, cx); + let viewport = pass::current_viewport(&core.ctx); + self.window_os(viewport, props, core, style_min); return; } - let id = cx.core.id; - let overlay = overlay.in_screen(crate::runtime::overlay::parent_space(&cx.core.ctx, id)); + let id = core.id; + let overlay = overlay.in_screen(crate::runtime::overlay::parent_space(&core.ctx, id)); let overlay = &*overlay; - let limits = Limits::new(overlay, window_min(props, cx.style.metrics().min_size)); - let rect = cx.core.rect; + let limits = Limits::new(overlay, window_min(props, style_min)); + let rect = core.rect; // A part the container did not declare this pass (no band, no grips) has no result. - let phase = |key: (PartKey, Option)| cx.core.results.get(&key).map(|result| result.press.phase); + let phase = |key: (PartKey, Option)| core.results.get(&key).map(|result| result.press.phase); let mut pressed = vec![(None, phase((MOVE_BAND, None)))]; pressed.extend((0..GRIPS.len()).map(|index| (Some(index), phase((GRIP, Some(index as u64)))))); let Some((grip, phase)) = pressed.into_iter().find_map(|(grip, phase)| match phase? { @@ -507,7 +507,7 @@ impl BodyHooks<'_> { }) else { return; }; - let mut slot = PlacementSlot::new(&mut *cx.core.memory, id, self.save.as_ref(), overlay); + let mut slot = PlacementSlot::new(&mut *core.memory, id, self.save.as_ref(), overlay); let current = slot.read(); let (start, pos, gesture) = match phase { PressPhase::Down { .. } => { @@ -563,30 +563,30 @@ impl BodyHooks<'_> { /// caller sizes that resize ([`Self::window_resize`]). Where the platform answers the hit test /// (`answered_by_platform`), the parts it takes stand for its sink only; the grips of a window its caller sizes /// are never its. - pub(super) fn window_os(&mut self, viewport: ViewportId, props: &ContainerProps, cx: &mut Cx<'_, C>) { + pub(super) fn window_os(&mut self, viewport: ViewportId, props: &ContainerProps, core: &mut CxCore<'_>, style_min: Vec2) { let by_caller = overlay_of(props).is_some_and(|overlay| overlay.resize.by_caller); if by_caller { - let limits = overlay_of(props).map(|overlay| Limits::new(overlay, window_min(props, cx.style.metrics().min_size))); + let limits = overlay_of(props).map(|overlay| Limits::new(overlay, window_min(props, style_min))); if let Some(limits) = limits { - self.window_resize(viewport, &limits, cx.core); + self.window_resize(viewport, &limits, core); } } - if answered_by_platform(&cx.core.ctx, viewport) { + if answered_by_platform(&core.ctx, viewport) { return; } - let app_moves = windows::app_moves(&cx.core.ctx, viewport); + let app_moves = windows::app_moves(&core.ctx, viewport); if app_moves { - self.window_move(viewport, cx.core); + self.window_move(viewport, core); } // The parts stand only by `WindowParts`, and the results of a part not registered this pass are gone. let started = - |key: (PartKey, Option)| cx.core.results.get(&key).is_some_and(|result| matches!(result.press.phase, PressPhase::DragStart { .. })); + |key: (PartKey, Option)| core.results.get(&key).is_some_and(|result| matches!(result.press.phase, PressPhase::DragStart { .. })); if !app_moves && started((MOVE_BAND, None)) { - windows::act(&cx.core.ctx, viewport, WindowAction::StartMove); + windows::act(&core.ctx, viewport, WindowAction::StartMove); } for (index, (dx, dy, _)) in GRIPS.into_iter().enumerate() { if !by_caller && started((GRIP, Some(index as u64))) { - windows::act(&cx.core.ctx, viewport, WindowAction::StartResize(edge_of(dx, dy))); + windows::act(&core.ctx, viewport, WindowAction::StartResize(edge_of(dx, dy))); } } } diff --git a/crates/ui-contract/src/contract/editor.rs b/crates/ui-contract/src/contract/editor.rs index 8ac4bd4514..9f02d6f89f 100644 --- a/crates/ui-contract/src/contract/editor.rs +++ b/crates/ui-contract/src/contract/editor.rs @@ -3,7 +3,7 @@ //! undo state back to the IME engine and AccessKit. use super::Component; -use super::cx::{Cx, Edit as _, PartsCx}; +use super::cx::{Cx, CxCore, Edit as _, PartsCx}; use crate::primitives::{EditorPurpose, EditorState, ImeStamp, ImeSurface}; use crate::runtime::access::text::{self as text_access, Line, Run, TextFacts}; @@ -65,18 +65,26 @@ pub(crate) fn keys_of(base: KeyUse, purpose: EditorPurpose) -> KeyUse { /// then keys, text and edit commands). A read-only editor receives only inputs that change no text; undo and redo /// the editor cannot do go to the app command. pub(crate) fn run(cx: &mut Cx<'_, C>, ui: &mut Ui, step: &mut super::text::TextStep, keys: KeyUse) { - let Some(decl) = step.editor.take() else { return }; + if step.editor.is_none() { + return; + } // A press that leaves the editor ends its gesture, as a focus loss ends a text field's draft. if step.commit_now { cx.commit(); } - let (ctx, id) = (cx.core.ctx.clone(), cx.core.id); + run_core(cx.core, ui, step, keys); +} + +/// The editor step past the commit: the same for every component type, so it is compiled once. +fn run_core(core: &mut CxCore<'_>, ui: &mut Ui, step: &mut super::text::TextStep, keys: KeyUse) { + let Some(decl) = step.editor.take() else { return }; + let (ctx, id) = (core.ctx.clone(), core.id); let widget = ImeSurface::of(id, decl.key).widget(); - let focusable = super::steps::takes_focus(cx.core.resolved); + let focusable = super::steps::takes_focus(core.resolved); let focused = egui_editor::show(ui, widget, decl.rect, egui_focus::event_filter(keys.keep, false), focusable); // The focus widget is the component's, enabled or not: it is never one of the app's own widgets (`take_app_widgets`). crate::runtime::pointer::record_text_widget(&ctx, widget, id); - let read_only = cx.core.resolved.read_only || !cx.core.resolved.enabled; + let read_only = core.resolved.read_only || !core.resolved.enabled; let mut inputs: Vec<(Order, EditorInput)> = Vec::new(); if focused { // Each input goes where its event arrived among the frame's events: an IME edit before the press or text that @@ -84,12 +92,12 @@ pub(crate) fn run(cx: &mut Cx<'_, C>, ui: &mut Ui, step: &mut supe // came before any key, and an intent of no one event (an Escape, a queued edit command) last, as routed. let mut placed: Vec<(Order, EditorInput)> = Vec::new(); placed.extend(ime::take_placed(&ctx, widget, read_only).into_iter().map(|(input, place)| ((place, 0), input))); - while let Some(request) = cx.core.intents.take_access_where(text_access::is_text_request) { + while let Some(request) = core.intents.take_access_where(text_access::is_text_request) { if let Some((anchor, focus)) = text_access::requested_selection(&ctx, id, &request) { placed.push(((0, 1), EditorInput::select(anchor, focus))); } } - while let Some((input, place)) = cx.core.intents.take_editor_input(keys.keep) { + while let Some((input, place)) = core.intents.take_editor_input(keys.keep) { placed.push(((place.unwrap_or(usize::MAX), 2), input)); } // A stable sort: inputs of one place keep the order they were taken in. @@ -109,8 +117,8 @@ pub(crate) fn run(cx: &mut Cx<'_, C>, ui: &mut Ui, step: &mut supe can }); } - cx.core.editor = Some(EditorInfo { widget, rect: decl.rect, purpose: decl.purpose, focused, read_only, commit_now: step.commit_now }); - cx.core.editor_inputs = inputs; + core.editor = Some(EditorInfo { widget, rect: decl.rect, purpose: decl.purpose, focused, read_only, commit_now: step.commit_now }); + core.editor_inputs = inputs; } /// The editor part's widget, rect, purpose, focus and read-only state of this pass, which a body that runs inside a From f6c109dc2b1850e6a5cae1907fb4b7ef86d5455f Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:12:12 +0700 Subject: [PATCH 14/14] ui-contract: run the body's read step once for every container type The step reads the component only for its open binding and its bound scroll offset; the rest moves to non-generic functions. No behavior change. --- crates/ui-contract/src/contract/body/hooks.rs | 300 ++++++++++-------- 1 file changed, 159 insertions(+), 141 deletions(-) diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index bb633f4604..b6a9ddffc3 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -153,149 +153,16 @@ impl ShapeHooks for BodyHooks<'_> { } fn read(&mut self, comp: &mut C, stage: &mut MemoryStage, id: Id, env: &Env) { - let ctx = stage.ctx().clone(); - let props = Arc::clone(&self.props); - let props = &*props; - let scroll = scroll_of(props); - let collapse = props.collapse; - let save = props.save.clone(); - self.save = save.clone(); - // The overlay host decides a layer's Escape; so does a full-window mount's. - self.layer = matches!(props.mount, Mount::Layer(_) | Mount::Viewport { .. } | Mount::FullWindow); - self.region_gap = gap_of(&env.tokens, Gap::Tight); - self.end_gap = gap_of(&env.tokens, props.end.map_or(Gap::Tight, |end| end.gap)); - self.header_gap = header_gap_of(props, &env.tokens); - let start = layout::flow_start(&ctx, env); - self.after_rule = start == Some(true); - self.rules = RuleBands::of(props, env, crate::runtime::egui::scale::pixels_per_point(&ctx), start); - self.least_width = least_of(&env.tokens, props.least_width); - let quiet = stage.is_peek() || crate::runtime::measure::active(&ctx); - if !matches!(props.mount, Mount::Inline | Mount::Pane(_)) - && let Some(why) = if quiet { crate::runtime::overlay::peek_close(&ctx, id) } else { crate::runtime::overlay::take_close(&ctx, id) } - { - self.close = true; - self.reason = Some(why); - } + let quiet = self.read_before_open(stage, id, env); self.open_bound = comp.open().is_some(); - self.open = open_now(comp, stage, id, props); - self.open_at_read = self.open; - self.presence = match collapse { - Some(collapse) if collapse.animated => { - Driver { stage: &*stage, base: id, policy: env.motion }.presence("collapse", self.open, spec::OPEN_RISE) - } - _ => Presence { t: f32::from(u8::from(self.open)), visible: self.open, exiting: false }, - }; - self.mode = stage.session::(sub(id, "window_mode")).clone(); - self.fixed = match &props.mount { - Mount::FullWindow => true, - // A viewport whose fallback covers the window is fixed in both modes, as a full-window mount is: its body - // never sizes as a layer's content. - Mount::Viewport { fallback, .. } if fallback.is_full_window() => true, - Mount::Viewport { .. } if windows::mount_window(&ctx, id) => true, - Mount::Layer(_) | Mount::Viewport { .. } => { - let placement = overlay_of(props).map_or_else(Placement::default, |overlay| { - let screen = crate::contract::overlay::screen_for(&ctx, env, overlay); - shown_placement(&ctx, id, save.as_ref(), overlay, None, screen, env.tokens.space.inset.screen) - }); - // A layer the user sized takes that size, at its saved position or where its anchor places it. - placement.size.is_some() - } - _ => false, - }; - self.last = stage.recall::(sub(id, "view")); - self.strip = scroll_strip_height(&env.tokens); - self.row = env.tokens.size.control.md; - let Some(scroll) = scroll else { return }; - // A scrolled body of a layer, or in one, starts at the top at every opening of the layer, as at its first. - let opening = match props.mount { - Mount::Layer(_) => crate::runtime::overlay::appears(&ctx, id, false), - _ => crate::runtime::overlay::drawing_parent(&ctx).is_some_and(|layer| crate::runtime::overlay::opening(&ctx, layer)), - }; - if opening && comp.scroll().is_none() { - *stage.session::(sub(id, "scroll")) = ScrollState::default(); - } - self.last_extent = stage.session::(sub(id, "scroll")).extent; - self.scroll_bound = comp.scroll().is_some(); - let held = match comp.scroll() { - Some(bind) => match bind.get() { - Some(Mixed::Same(pos)) => pos, - _ => ScrollPos::default(), - }, - None => { - let state = stage.session::(sub(id, "scroll")); - self.anchor = state.anchor; - ScrollPos { x: state.offset.0, y: state.offset.1 } - } - }; - self.anchor_at_read = self.anchor; - self.offset = held; - self.offset_at_read = held; - let rtl = env.direction.is_rtl(); - let view = self.last.view.map_or(Vec2::ZERO, |view| self.shown_view(scroll, rect_of(view)).size()); - // Step 4 applies, in order, the scroll bar, AccessKit and reveal moves the update step of the last pass queued - // (`Jumps`), this pass's wheel share and the scroll moves queued for the body. - let frame = jump_frame(&ctx); - let jump = pass_state::with::(&ctx, |jumps| { - jumps.0.retain(|(.., queued)| queued + 1 >= frame); - let at = jumps.0.iter().position(|(owner, ..)| *owner == id)?; - Some(if quiet { jumps.0[at].1 } else { jumps.0.remove(at).1 }) + let props = Arc::clone(&self.props); + self.open = open_now(comp, stage, id, &props); + // The caller's scroll offset: the position it holds, the default when it is mixed or unset. + let bound_scroll = comp.scroll().map(|bind| match bind.get() { + Some(Mixed::Same(pos)) => pos, + _ => ScrollPos::default(), }); - if let Some(jump) = jump { - self.offset = jump; - self.moved = true; - } - if let Some(share) = if quiet { wheel::peek(&ctx, id) } else { wheel::take(&ctx, id) } { - let sign = if rtl { 1.0 } else { -1.0 }; - self.offset.x += f64::from(sign * share.scroll.x); - self.offset.y -= f64::from(share.scroll.y); - self.moved = true; - } - for (mv, _) in crate::contract::steps::scroll_moves(&ctx, id, quiet) { - let (visible, extent, offset, vertical) = if scroll.vertical_on() { - (view.y, self.last_extent.1, self.offset.y, true) - } else { - (view.x, self.last_extent.0, self.offset.x, false) - }; - let span = ScrollSpan::new(0.0..f64::from(extent).max(f64::from(visible)), offset..offset + f64::from(visible)); - if let Some(range) = craft_behavior::scroll::jump(&span, mv) { - if vertical { - self.offset.y = range.start; - } else { - self.offset.x = range.start; - } - self.moved = true; - } - } - // A move of the area's own ends a glide; a child reveal starts one. A running glide moves the offset toward - // its aim. - self.glide = if self.moved { None } else { stage.session::(sub(id, "scroll")).glide }; - if let Some(child) = crate::contract::child_reveal(&ctx, id, quiet) { - self.glide = Some(Glide { child, to: None, running: false }); - } - self.glide_at_read = self.glide; - if let Some(glide) = self.glide.as_mut() - && let Some(to) = glide.to - && (glide.running || !quiet) - { - let driver = Driver { stage: &*stage, base: id, policy: env.motion }; - if !glide.running { - driver.jump("glide", Vec2::new(self.offset.x as f32, self.offset.y as f32)); - glide.running = true; - } - let at = driver.anim("glide", to, spec::FOLLOW); - self.offset = ScrollPos { x: f64::from(at.x), y: f64::from(at.y) }; - self.moved = true; - if at == to { - self.glide = None; - } - } - let follows = stage.session::(sub(id, "scroll")).follow_end.unwrap_or(true); - self.follows_end = scroll.anchor == crate::contract::ScrollAnchor::End && follows; - if self.follows_end && !self.moved { - self.offset.y = f64::from((self.last_extent.1 - view.y).max(0.0)); - } - self.clamp_offset(scroll, view); - self.view_offset = self.offset; + self.read_after_open(stage, id, env, quiet, bound_scroll); } fn overflow(&self) -> f32 { @@ -739,6 +606,157 @@ fn first_line_found(ctx: &Context, (header, body): (Id, Id), top: f32, moved: f3 } impl BodyHooks<'_> { + /// The read step up to the container's open state, which needs the component: the same for every container type. + /// Whether the stage only peeks (a peek or a measuring pass), which the rest of the step needs too. + fn read_before_open(&mut self, stage: &mut MemoryStage, id: Id, env: &Env) -> bool { + let ctx = stage.ctx().clone(); + let props = Arc::clone(&self.props); + let props = &*props; + self.save = props.save.clone(); + // The overlay host decides a layer's Escape; so does a full-window mount's. + self.layer = matches!(props.mount, Mount::Layer(_) | Mount::Viewport { .. } | Mount::FullWindow); + self.region_gap = gap_of(&env.tokens, Gap::Tight); + self.end_gap = gap_of(&env.tokens, props.end.map_or(Gap::Tight, |end| end.gap)); + self.header_gap = header_gap_of(props, &env.tokens); + let start = layout::flow_start(&ctx, env); + self.after_rule = start == Some(true); + self.rules = RuleBands::of(props, env, crate::runtime::egui::scale::pixels_per_point(&ctx), start); + self.least_width = least_of(&env.tokens, props.least_width); + let quiet = stage.is_peek() || crate::runtime::measure::active(&ctx); + if !matches!(props.mount, Mount::Inline | Mount::Pane(_)) + && let Some(why) = if quiet { crate::runtime::overlay::peek_close(&ctx, id) } else { crate::runtime::overlay::take_close(&ctx, id) } + { + self.close = true; + self.reason = Some(why); + } + quiet + } + + /// The read step from the open state on, given the caller's bound scroll offset: the same for every container type. + fn read_after_open(&mut self, stage: &mut MemoryStage, id: Id, env: &Env, quiet: bool, bound_scroll: Option) { + let ctx = stage.ctx().clone(); + let props = Arc::clone(&self.props); + let props = &*props; + let scroll = scroll_of(props); + let collapse = props.collapse; + let save = props.save.clone(); + self.open_at_read = self.open; + self.presence = match collapse { + Some(collapse) if collapse.animated => { + Driver { stage: &*stage, base: id, policy: env.motion }.presence("collapse", self.open, spec::OPEN_RISE) + } + _ => Presence { t: f32::from(u8::from(self.open)), visible: self.open, exiting: false }, + }; + self.mode = stage.session::(sub(id, "window_mode")).clone(); + self.fixed = match &props.mount { + Mount::FullWindow => true, + // A viewport whose fallback covers the window is fixed in both modes, as a full-window mount is: its body + // never sizes as a layer's content. + Mount::Viewport { fallback, .. } if fallback.is_full_window() => true, + Mount::Viewport { .. } if windows::mount_window(&ctx, id) => true, + Mount::Layer(_) | Mount::Viewport { .. } => { + let placement = overlay_of(props).map_or_else(Placement::default, |overlay| { + let screen = crate::contract::overlay::screen_for(&ctx, env, overlay); + shown_placement(&ctx, id, save.as_ref(), overlay, None, screen, env.tokens.space.inset.screen) + }); + // A layer the user sized takes that size, at its saved position or where its anchor places it. + placement.size.is_some() + } + _ => false, + }; + self.last = stage.recall::(sub(id, "view")); + self.strip = scroll_strip_height(&env.tokens); + self.row = env.tokens.size.control.md; + let Some(scroll) = scroll else { return }; + // A scrolled body of a layer, or in one, starts at the top at every opening of the layer, as at its first. + let opening = match props.mount { + Mount::Layer(_) => crate::runtime::overlay::appears(&ctx, id, false), + _ => crate::runtime::overlay::drawing_parent(&ctx).is_some_and(|layer| crate::runtime::overlay::opening(&ctx, layer)), + }; + if opening && bound_scroll.is_none() { + *stage.session::(sub(id, "scroll")) = ScrollState::default(); + } + self.last_extent = stage.session::(sub(id, "scroll")).extent; + self.scroll_bound = bound_scroll.is_some(); + let held = match bound_scroll { + Some(pos) => pos, + None => { + let state = stage.session::(sub(id, "scroll")); + self.anchor = state.anchor; + ScrollPos { x: state.offset.0, y: state.offset.1 } + } + }; + self.anchor_at_read = self.anchor; + self.offset = held; + self.offset_at_read = held; + let rtl = env.direction.is_rtl(); + let view = self.last.view.map_or(Vec2::ZERO, |view| self.shown_view(scroll, rect_of(view)).size()); + // Step 4 applies, in order, the scroll bar, AccessKit and reveal moves the update step of the last pass queued + // (`Jumps`), this pass's wheel share and the scroll moves queued for the body. + let frame = jump_frame(&ctx); + let jump = pass_state::with::(&ctx, |jumps| { + jumps.0.retain(|(.., queued)| queued + 1 >= frame); + let at = jumps.0.iter().position(|(owner, ..)| *owner == id)?; + Some(if quiet { jumps.0[at].1 } else { jumps.0.remove(at).1 }) + }); + if let Some(jump) = jump { + self.offset = jump; + self.moved = true; + } + if let Some(share) = if quiet { wheel::peek(&ctx, id) } else { wheel::take(&ctx, id) } { + let sign = if rtl { 1.0 } else { -1.0 }; + self.offset.x += f64::from(sign * share.scroll.x); + self.offset.y -= f64::from(share.scroll.y); + self.moved = true; + } + for (mv, _) in crate::contract::steps::scroll_moves(&ctx, id, quiet) { + let (visible, extent, offset, vertical) = if scroll.vertical_on() { + (view.y, self.last_extent.1, self.offset.y, true) + } else { + (view.x, self.last_extent.0, self.offset.x, false) + }; + let span = ScrollSpan::new(0.0..f64::from(extent).max(f64::from(visible)), offset..offset + f64::from(visible)); + if let Some(range) = craft_behavior::scroll::jump(&span, mv) { + if vertical { + self.offset.y = range.start; + } else { + self.offset.x = range.start; + } + self.moved = true; + } + } + // A move of the area's own ends a glide; a child reveal starts one. A running glide moves the offset toward + // its aim. + self.glide = if self.moved { None } else { stage.session::(sub(id, "scroll")).glide }; + if let Some(child) = crate::contract::child_reveal(&ctx, id, quiet) { + self.glide = Some(Glide { child, to: None, running: false }); + } + self.glide_at_read = self.glide; + if let Some(glide) = self.glide.as_mut() + && let Some(to) = glide.to + && (glide.running || !quiet) + { + let driver = Driver { stage: &*stage, base: id, policy: env.motion }; + if !glide.running { + driver.jump("glide", Vec2::new(self.offset.x as f32, self.offset.y as f32)); + glide.running = true; + } + let at = driver.anim("glide", to, spec::FOLLOW); + self.offset = ScrollPos { x: f64::from(at.x), y: f64::from(at.y) }; + self.moved = true; + if at == to { + self.glide = None; + } + } + let follows = stage.session::(sub(id, "scroll")).follow_end.unwrap_or(true); + self.follows_end = scroll.anchor == crate::contract::ScrollAnchor::End && follows; + if self.follows_end && !self.moved { + self.offset.y = f64::from((self.last_extent.1 - view.y).max(0.0)); + } + self.clamp_offset(scroll, view); + self.view_offset = self.offset; + } + /// Step 13 of a body, without the component: what `updated` does for every container type, kept out of the /// generic hook so the web build carries it once. The placement changes it reports wait in `self.reports`. fn updated_core(&mut self, props: &ContainerProps, surface: bool, style_min: Vec2, core: &mut CxCore<'_>) {