Merge main into feat/craft-xtask-pins-one-commit

This commit is contained in:
dotCooCoo committed 2026-11-28 07:54:38 -08:00
commit 7f203da9df
17 files changed
+1045 -264

No files matched your search

+1 -1
View File
@@ -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`, `wav_float_header_with_bwf`; `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`, `wav_float_header_with_bwf`; `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 and `PacketEncoder` for AAC | craft-media `bitstream`; `aac-encode` also `isobmff` |
+5 -5
View File
@@ -19,9 +19,9 @@
//! - [`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`] and [`wav_float_header_with_bwf`]), 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
//! gives [`wav_float_header`], [`wav_float_header_with_bwf`] 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.
//! - [`PacketEncoder`] (any of `aac-encode`, `alac-encode`, `mp3-encode`, `ac3-encode`,
//! `eac3-encode`, `opus-encode`): planar `f32` in WAV channel order to packets of AAC-LC, ALAC,
@@ -221,9 +221,9 @@ pub use write::FileEncoder;
))]
pub use write::{ENCODE_EXTENSIONS, encode, encode_format_for};
#[cfg(feature = "pcm-encode")]
pub use write::{pcm_aiff_file, pcm_aiff_header, pcm_wav_file, pcm_wav_header};
pub use write::{WavRepair, repair_wav, wav_float_header, wav_float_header_with_bwf};
#[cfg(feature = "pcm-encode")]
pub use write::{wav_float_header, wav_float_header_with_bwf};
pub use write::{pcm_aiff_file, pcm_aiff_header, pcm_wav_file, pcm_wav_header};
/// Errors from probing, decoding and encoding.
#[non_exhaustive]
+3 -5
View File
@@ -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,
@@ -359,7 +356,8 @@ pub(crate) fn parse(src: &Src<'_>) -> Result<WavParse> {
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),
_ => {}
}
}
+2
View File
@@ -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];
+67
View File
@@ -478,3 +478,70 @@ fn float_header(sample_rate: u32, channels: u16, bwf: Option<&crate::BwfInfo>, f
}
wav::header(usize::from(channels), sample_rate, (32, true), bwf, 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. The file must end in
/// its data chunk: everything after the data chunk's header counts as samples, whatever its size
/// field says.
///
/// 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 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
/// [`FileEncoder`] and [`wav_float_header`] write: `RIFF` becomes `RF64` and that `JUNK` chunk
/// 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:
///
/// - [`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, 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 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
/// 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.
///
/// ```
/// 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<F: std::io::Read + Write + Seek>(file: &mut F) -> Result<WavRepair> {
let (frames, len) = wav::repair(file)?;
Ok(WavRepair { frames, len })
}
+174 -2
View File
@@ -2,9 +2,9 @@
//! 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, Seek, SeekFrom, Write};
use std::io::{Cursor, ErrorKind, Read, Seek, SeekFrom, Write};
const BEXT_MIN_LEN: usize = 602;
@@ -239,3 +239,175 @@ 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 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<u64>,
junk: bool,
fact: Option<u64>,
block_align: u64,
data: u64,
}
fn read_at<F: Read + Seek>(file: &mut F, pos: u64, buf: &mut [u8]) -> Result<bool> {
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<F: Write + Seek>(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<F: Read + Seek>(file: &mut F, pos: u64, size: u32) -> Result<u64> {
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 {
// 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}")));
}
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")));
}
// 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))
}
fn layout<F: Read + Seek>(file: &mut F, len: u64) -> Result<Layout> {
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 });
}
// The first `ds64` and `fact` chunks take the sizes; later ones are left as they are.
// 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),
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<F: Read + Seek>(file: &mut F, l: &Layout) -> Result<Option<u64>> {
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<F: Read + Write + Seek>(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 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(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")?;
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())?;
}
}
// 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))
}
+309
View File
@@ -68,6 +68,315 @@ fn wav_and_aiff_roundtrip_all_depths_and_layouts() {
}
}
/// 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<u8>, Vec<u8>) {
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<u8>,
len: u64,
pos: u64,
}
impl std::io::Read for SparseWav {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
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<usize> {
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<u64> {
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 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 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<u8> = [&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[..]);
// 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 ");
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_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<u8> = [&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));
// 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<Vec<u8>>,
writes: usize,
}
impl std::io::Read for FailingWrites {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
std::io::Read::read(&mut self.file, buf)
}
}
impl std::io::Write for FailingWrites {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
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<u64> {
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]
fn repair_wav_refuses_what_it_cannot_repair() {
use craft_audio::AudioError;
let repair = |bytes: Vec<u8>| 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(_))));
// 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;
assert!(repair(ext.clone()).is_ok());
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]);
assert_eq!(repair(ambisonic).unwrap().frames, 100);
}
#[test]
fn float_wav_header_with_bwf_keeps_its_bext_as_the_file_grows() {
let take = sine(48_000, 2, 1_000);
+220 -195
View File
@@ -153,149 +153,16 @@ impl<C: Container> ShapeHooks<C> 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::<WindowMode>(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::<BodyView>(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::<ScrollState>(sub(id, "scroll")) = ScrollState::default();
}
self.last_extent = stage.session::<ScrollState>(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::<ScrollState>(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::<Jumps, _>(&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::<ScrollState>(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::<ScrollState>(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 {
@@ -548,60 +415,9 @@ impl<C: Container> ShapeHooks<C> 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 +606,215 @@ 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<ScrollPos>) {
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::<WindowMode>(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::<BodyView>(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::<ScrollState>(sub(id, "scroll")) = ScrollState::default();
}
self.last_extent = stage.session::<ScrollState>(sub(id, "scroll")).extent;
self.scroll_bound = bound_scroll.is_some();
let held = match bound_scroll {
Some(pos) => pos,
None => {
let state = stage.session::<ScrollState>(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::<Jumps, _>(&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::<ScrollState>(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::<ScrollState>(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<'_>) {
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<C: Container>(
@@ -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<C: Container>(&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);
}
}
+25 -25
View File
@@ -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<C: Container>(&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<C: Container>(&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<u64>)| cx.core.results.get(&key).map(|result| result.press.phase);
let phase = |key: (PartKey, Option<u64>)| 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<C: Container>(&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<u64>)| cx.core.results.get(&key).is_some_and(|result| matches!(result.press.phase, PressPhase::DragStart { .. }));
|key: (PartKey, Option<u64>)| 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)));
}
}
}
+17 -9
View File
@@ -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<C: Component>(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<C: Component>(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<C: Component>(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
+4
View File
@@ -151,6 +151,10 @@ pub(crate) struct RowGroups {
#[derive(Default)]
pub(crate) struct State {
pub(crate) stops: Vec<StopRec>,
/// 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,
+87 -14
View File
@@ -249,8 +249,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<Act> {
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<Act> {
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);
}
@@ -264,7 +270,16 @@ impl State {
}
fn enter_stop(&mut self, rec: StopRec, origin: FocusOrigin) -> Vec<Act> {
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<Act> {
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 {
@@ -280,6 +295,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 };
@@ -393,8 +414,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<Act> {
// 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<StopRec>, Vec<Entry>) {
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);
@@ -405,10 +435,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
@@ -587,10 +614,48 @@ 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) {
// 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)])
}
/// 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<StopRec> {
// 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 {
return None;
}
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(&current, 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())
}
/// 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<StopRec> {
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.
@@ -839,6 +904,8 @@ pub(super) fn begin(state: &mut State, input: BeginIn) -> (Vec<Act>, Vec<String>
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();
@@ -846,10 +913,16 @@ pub(super) fn begin(state: &mut State, input: BeginIn) -> (Vec<Act>, Vec<String>
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()) {
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);
}
@@ -59,6 +59,8 @@ struct Plan {
pub(crate) struct PressState {
plan: Option<Plan>,
pub(super) commit_now: Option<Id>,
/// A Tab (`true`) or Shift+Tab (`false`) moved focus this pass, from nothing as well as from a stop.
pub(super) tabbed: Option<bool>,
/// 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<Id>) {
self.plan = None;
self.commit_now = None;
self.tabbed = None;
self.tabbed_from = None;
self.by_keys = false;
self.focus_at_begin = focused;
+78 -1
View File
@@ -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,80 @@ 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");
}
/// 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");
}
/// 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");
}
+1
View File
@@ -19,6 +19,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;
@@ -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::<Option<bool>>));
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");
}