From 01495efa4a74a7a76a5dc3bc0f5c537f84dbd21f Mon Sep 17 00:00:00 2001 From: BlueJayLouche Date: Sat, 21 Nov 2026 21:40:51 +1100 Subject: [PATCH 01/15] engine: a stereo or wider file imported onto a mono track with as many mono tracks below it splits across them, one mono source per channel (.L, .R), in one undo step; fewer mono tracks below and it lands whole as before --- crates/engine/src/cmd/file.rs | 2 +- crates/engine/src/io.rs | 45 ++++++++++++- crates/engine/tests/import_split.rs | 100 ++++++++++++++++++++++++++++ docs/user-guide.md | 6 +- 4 files changed, 150 insertions(+), 3 deletions(-) create mode 100644 crates/engine/tests/import_split.rs diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index cb2ce606..51ebe61d 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -56,7 +56,7 @@ pub fn specs() -> Vec { "Audio...", ["File", "Import"], Some("Cmd+Shift+I"), - "{path | paths: [..], track?: target track, at?: position, name?: clip, source and new track name, new_tracks?: true (default; false uses `track` or the selected audio track)}", + "{path | paths: [..], track?: target track (a mono one with mono tracks below takes one channel of a wider file each), at?: position, name?: clip, source and new track name, new_tracks?: true (default; false uses `track` or the selected audio track)}", always, import_audio ), diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index 67500e58..b572726e 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -300,13 +300,18 @@ pub fn prepare_audio_bytes( /// Place prepared audio: a new source, and a clip at `at` on `target` (or on a new track of /// matching width). `name` replaces the file name as the source, clip and new track name. Audio -/// prepared at another rate than the session's is resampled here. +/// prepared at another rate than the session's is resampled here. A file of several channels on a +/// mono track with as many mono tracks below it splits across them, one channel each. pub fn place_prepared(e: &mut Engine, prepared: PreparedAudio, target: Option, at: Samples, name: Option<&str>) -> Result { let PreparedAudio { name: file, path, audio, format, file_rate, time_reference } = prepared; let label = name.map(str::trim).filter(|n| !n.is_empty()).unwrap_or(&file).to_string(); let channels = audio.buffer.num_channels(); let s = e.session_mut(); let session_rate = s.sample_rate.hz(); + if let Some(tracks) = target.and_then(|t| split_tracks(s, t, channels)).filter(|_| !audio.is_disk()) { + let stamp = time_reference.map(|t| stamp_at_rate(t, file_rate, session_rate)); + return Ok(place_split(s, audio, &label, &tracks, at, stamp)); + } let src = if audio.buffer.sample_rate == session_rate { add_source_audio(s, &label, audio, path.as_deref(), format) } else { @@ -327,6 +332,44 @@ pub fn place_prepared(e: &mut Engine, prepared: PreparedAudio, target: Option Option> { + let mono = |t: &&transit_model::Track| t.kind == TrackKind::Audio && t.format == ChannelFormat::Mono; + let i = s.track_index(target).filter(|_| channels > 1)?; + let first = s.tracks.get(i).filter(mono)?; + let below = s.tracks.iter().skip(i + 1).filter(|t| crate::edit::shown(s, t)).take(channels - 1); + let tracks: Vec = std::iter::once(first).chain(below).take_while(mono).map(|t| t.id).collect(); + (tracks.len() == channels).then_some(tracks) +} + +/// One mono source per channel, `.L` and `.R` (past stereo, the channel labels of the +/// format a new track that wide gets), written to `Audio Files` on save, and a clip of each at +/// `at` on its track of `tracks`. The reply is the first clip's, with every clip under `split`. +fn place_split(s: &mut Session, audio: Arc, label: &str, tracks: &[TrackId], at: Samples, stamp: Option) -> Value { + let stem = Path::new(label).file_stem().and_then(|x| x.to_str()).unwrap_or(label).to_string(); + let layout = ChannelFormat::for_channels(tracks.len()); + let buf = Arc::try_unwrap(audio).map_or_else(|a| a.buffer.clone(), |mut a| std::mem::take(&mut a.buffer)); + let rate = buf.sample_rate; + let mut placed = Vec::new(); + for (ch, (samples, &track)) in buf.channels.into_iter().zip(tracks).enumerate() { + // The source name is the given name's stem, so the extension keeps the channel label. + let name = format!("{stem}.{}.wav", layout.channel_label(ch)); + let src = add_source(s, &name, AudioBuffer { sample_rate: rate, channels: vec![samples] }, None, FileFormat::Wav); + if let (Some(stamp), Some(sx)) = (stamp, s.sources.last_mut()) { + sx.time_reference = stamp; + } + let frames = s.source(src).map_or(0, |x| i64::try_from(x.frames).unwrap_or(0)); + let clip_name = s.source(src).map(|x| x.name.clone()).unwrap_or_default(); + let cid = s.new_clip_id(); + crate::edit::place_clip(s, track, Clip::audio(cid, clip_name, src, 0, at, frames)); + placed.push(json!({"track": track, "clip": cid, "source": src, "frames": frames, "channels": 1})); + } + let mut reply = placed.first().cloned().unwrap_or_else(|| json!({})); + reply["split"] = json!(placed); + reply +} + /// Decode and place an audio file. With no target track, a new track of matching width is made. /// The synchronous import: [`prepare_audio_bytes`], then [`place_prepared`]. pub fn import_audio_bytes(e: &mut Engine, name: &str, bytes: &[u8], path: Option<&str>, target: Option, at: Samples) -> Result { diff --git a/crates/engine/tests/import_split.rs b/crates/engine/tests/import_split.rs new file mode 100644 index 00000000..92917c89 --- /dev/null +++ b/crates/engine/tests/import_split.rs @@ -0,0 +1,100 @@ +//! A stereo file imported onto a mono track with a mono track below it splits across the two: the +//! left channel on the first, the right on the second, each its own mono source, in one undo step. + +use serde_json::json; +use transit_engine::Engine; +use transit_engine::model::TrackId; + +/// A 16-bit stereo PCM WAV: every left sample is `l`, every right one `r`. +fn stereo_wav(frames: u32, l: i16, r: i16) -> Vec { + let data = frames * 4; + let mut b = Vec::new(); + b.extend_from_slice(b"RIFF"); + b.extend_from_slice(&(36 + data).to_le_bytes()); + b.extend_from_slice(b"WAVEfmt "); + for v in [16u32, 0x0002_0001, 48_000, 48_000 * 4, 0x0010_0004] { + b.extend_from_slice(&v.to_le_bytes()); + } + b.extend_from_slice(b"data"); + b.extend_from_slice(&data.to_le_bytes()); + for _ in 0..frames { + b.extend_from_slice(&l.to_le_bytes()); + b.extend_from_slice(&r.to_le_bytes()); + } + b +} + +fn track(e: &mut Engine, format: &str) -> u64 { + e.execute("track.new", &json!({"kind": "audio", "format": format})).unwrap()["tracks"][0].as_u64().unwrap() +} + +/// Each clip on `t`: its start, length, name, its source's channel count and first sample. +fn clips(e: &Engine, t: u64) -> Vec<(i64, i64, String, usize, f32)> { + let s = e.session(); + let tr = s.track(TrackId(t)).unwrap(); + tr.clips() + .iter() + .map(|c| { + let transit_engine::model::ClipContent::Audio { source, .. } = c.content else { panic!("an audio clip") }; + let buf = &s.pool.get(source).unwrap().buffer; + (c.start, c.length, c.name.clone(), buf.num_channels(), buf.channels[0][0]) + }) + .collect() +} + +#[test] +fn a_stereo_file_on_a_mono_track_with_a_mono_track_below_splits_and_saves_two_mono_files() { + let d = transit_test_support::TestDir::new("import-split"); + std::fs::create_dir_all(&*d).unwrap(); + let wav = d.join("LAV-2.wav"); + std::fs::write(&wav, stereo_wav(4_800, 16_384, -8_192)).unwrap(); + let mut e = Engine::default(); + let (a, b) = (track(&mut e, "mono"), track(&mut e, "mono")); + let undo = e.undo_history().len(); + let r = e.execute("file.import_audio", &json!({"path": wav.to_string_lossy(), "track": a, "at": 960})).unwrap(); + assert_eq!(r["imported"][0]["split"].as_array().map(Vec::len), Some(2), "{r}"); + assert_eq!(clips(&e, a), vec![(960, 4_800, "LAV-2.L".to_string(), 1, 0.5)], "the left channel on the first track"); + assert_eq!(clips(&e, b), vec![(960, 4_800, "LAV-2.R".to_string(), 1, -0.25)], "the right channel on the track below"); + assert_eq!(e.undo_history().len(), undo + 1, "one undo step"); + + let file = d.join("split.transit"); + e.execute("session.save", &json!({"path": file.to_string_lossy()})).unwrap(); + let mut f = Engine::default(); + f.execute("session.open", &json!({"path": file.to_string_lossy()})).unwrap(); + let paths: Vec<&str> = f.session().sources.iter().map(|s| s.path.as_str()).collect(); + assert_eq!(paths, ["Audio Files/LAV-2.L.wav", "Audio Files/LAV-2.R.wav"]); + assert_eq!((clips(&f, a), clips(&f, b)), (clips(&e, a), clips(&e, b)), "the split reopens from its two mono files"); + + e.undo(); + assert!(clips(&e, a).is_empty() && clips(&e, b).is_empty() && e.session().sources.is_empty(), "one undo takes it back"); +} + +#[test] +fn without_a_mono_track_below_the_stereo_file_lands_whole() { + let d = transit_test_support::TestDir::new("import-split-whole"); + std::fs::create_dir_all(&*d).unwrap(); + let wav = d.join("LAV-2.wav"); + std::fs::write(&wav, stereo_wav(480, 16_384, -8_192)).unwrap(); + let mut e = Engine::default(); + let (a, b) = (track(&mut e, "mono"), track(&mut e, "stereo")); + e.execute("file.import_audio", &json!({"path": wav.to_string_lossy(), "track": a})).unwrap(); + assert_eq!(clips(&e, a), vec![(0, 480, "LAV-2".to_string(), 2, 0.5)], "a stereo track below: one stereo clip"); + assert!(clips(&e, b).is_empty()); + e.execute("file.import_audio", &json!({"path": wav.to_string_lossy(), "track": b, "at": 960})).unwrap(); + assert_eq!(clips(&e, b).len(), 1, "a stereo track takes the file whole"); + assert_eq!(clips(&e, b)[0].3, 2); +} + +#[test] +fn a_hidden_track_below_is_passed_over_for_the_next_shown_mono_track() { + let d = transit_test_support::TestDir::new("import-split-hidden"); + std::fs::create_dir_all(&*d).unwrap(); + let wav = d.join("LAV-2.wav"); + std::fs::write(&wav, stereo_wav(480, 16_384, -8_192)).unwrap(); + let mut e = Engine::default(); + let (a, hidden, b) = (track(&mut e, "mono"), track(&mut e, "mono"), track(&mut e, "mono")); + e.execute("track.hide", &json!({"tracks": [hidden], "hidden": true})).unwrap(); + e.execute("file.import_audio", &json!({"path": wav.to_string_lossy(), "track": a})).unwrap(); + assert!(clips(&e, hidden).is_empty(), "nothing lands on a track the Edit window hides"); + assert_eq!(clips(&e, b), vec![(0, 480, "LAV-2.R".to_string(), 1, -0.25)]); +} diff --git a/docs/user-guide.md b/docs/user-guide.md index 2f69830d..37dfecf8 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -900,7 +900,11 @@ drop, so nothing behind it is reached. Anywhere else, a browser drag lands on th header, mixer strip or device chain where you let go, and a file from the file manager is imported into the arrangement at the cursor (a `.transit` or `.dawproject` file opens as the session, a MIDI file imports as MIDI). On Windows a file manager drop lands where the pointer is when you let go; on other -platforms it lands as soon as the pointer moves after you let go (see the known issues). +platforms it lands as soon as the pointer moves after you let go (see the known issues). A stereo +or wider file that lands on a mono audio track with as many mono tracks below it (in the Edit +window's order) splits across them in one undo step: each channel becomes its own mono file, +`.L` and `.R`, saved to `Audio Files`; with fewer mono tracks below, the file lands +whole on the one track. Right-click a pad and choose **Clear pad** to empty it and reset its name, choke group, mute, and solo. Delete or Backspace does the same for the selected pad while the Sampler window has From 88948ba9c2dbcf978f599222f363bec5054d36a4 Mon Sep 17 00:00:00 2001 From: BlueJayLouche Date: Sat, 21 Nov 2026 21:55:01 +1100 Subject: [PATCH 02/15] engine, ui: Split to Mono Tracks (clip.split_to_mono, the clip menu): each channel of the selected stereo or wider clips on a new mono track below its track, the originals muted, one undo step; a take played from its file gets a mono WAV per channel beside it Refutation review of the import split (ADR 0009): a frozen mono track below, or one holding a clip where the file goes, is never edited (the file lands whole as before); each split source keeps the peaks the import built; channels past stereo are numbered, not named as a surround layout --- crates/engine/src/cmd/clip_split.rs | 215 ++++++++++++++++++++++++++++ crates/engine/src/cmd/mod.rs | 2 + crates/engine/src/io.rs | 46 ++++-- crates/engine/tests/import_split.rs | 74 ++++++++++ crates/ui-studio/src/arrange.rs | 5 + docs/user-guide.md | 9 +- 6 files changed, 334 insertions(+), 17 deletions(-) create mode 100644 crates/engine/src/cmd/clip_split.rs diff --git a/crates/engine/src/cmd/clip_split.rs b/crates/engine/src/cmd/clip_split.rs new file mode 100644 index 00000000..3fd4cbc6 --- /dev/null +++ b/crates/engine/src/cmd/clip_split.rs @@ -0,0 +1,215 @@ +//! Split to Mono Tracks (`clip.split_to_mono`): each channel of the selected stereo or wider audio +//! clips on a new mono track below its track, the originals muted, in one undo step: two +//! microphones recorded onto one stereo track come apart this way. The clips of one track share +//! its new tracks. An in-memory source splits in memory (each channel is written to `Audio Files` +//! on save, as a recording is); a source played from its file (ADR 0035) gets one mono WAV per +//! channel written beside that file, played from disk in turn. + +use super::*; +use crate::cmd; +use serde_json::json; +use std::collections::BTreeMap; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use transit_audio_io::{AudioBuffer, BitDepth, EncodeOptions, FileEncoder, FileFormat}; +use transit_model::disk::DiskSource; +use transit_model::{ChannelFormat, ClipContent, ClipId, SourceAudio, SourceId, TrackId, TrackKind}; + +const ID: &str = "clip.split_to_mono"; + +pub fn specs() -> Vec { + vec![cmd!( + "clip.split_to_mono", + "Split to Mono Tracks", + ["Clip"], + None, + "{clips?} — each channel of the stereo or wider audio clips on a new mono track below its track; the originals are muted", + has_selection, + split_to_mono + )] +} + +/// A channel's audio, ready to become a source. +enum Mono { + Memory(SourceAudio), + /// The file written for it, as the session names it, and its audio played from that file. + Disk(String, Arc), +} + +fn split_to_mono(e: &mut Engine, p: &Value) -> Result { + let ids = clip_ids_param(e, p); + let s = e.session(); + // The clips to split on each track, in track order, with their sources' channel counts. + let mut by_track: BTreeMap)> = BTreeMap::new(); + for id in &ids { + let (t, c) = s.find_clip(*id).ok_or_else(|| bad(ID, format!("unknown clip {}", id.0)))?; + let ClipContent::Audio { source, .. } = c.content else { continue }; + let n = s.pool.get(source).map_or(0, |a| a.buffer.num_channels()); + if let (true, Some(i)) = (n > 1, s.track_index(t)) { + by_track.entry(i).or_insert((t, Vec::new())).1.push((*id, source, n)); + } + } + if by_track.is_empty() { + return Err(bad(ID, "no stereo or wider audio clip is selected")); + } + // Muting the originals edits their tracks: refused before any file is written. + if let Some(tr) = by_track.values().filter_map(|(t, _)| s.track(*t)).find(|t| t.freeze.is_some()) { + return Err(bad(ID, format!("{} is frozen: unfreeze it to split its clips", tr.name))); + } + // Every channel's audio before the session changes, so a refusal leaves it as it was. + let mut split: BTreeMap> = BTreeMap::new(); + for (_, clips) in by_track.values() { + for &(_, src, n) in clips { + if split.contains_key(&src) { + continue; + } + let (Some(meta), Some(audio)) = (s.source(src), s.pool.get(src)) else { continue }; + let names: Vec = (0..n).map(|ch| format!("{}.{}", meta.name, crate::io::split_label(n, ch))).collect(); + let monos = match &audio.disk { + Some(disk) => write_files(disk, &meta.path, &names)?.into_iter().map(|(path, a)| Mono::Disk(path, a)).collect(), + None => (0..n).map(|ch| Mono::Memory(mono_audio(audio, ch))).collect::>(), + }; + split.insert(src, names.into_iter().zip(monos).collect()); + } + } + let s = e.session_mut(); + let mut sources: BTreeMap<(SourceId, usize), SourceId> = BTreeMap::new(); + for (src, monos) in split { + for (ch, (name, mono)) in monos.into_iter().enumerate() { + let id = match mono { + // The extension keeps the label: a source is named after its file's stem. + Mono::Memory(audio) => crate::io::add_source_audio(s, &format!("{name}.wav"), Arc::new(audio), None, FileFormat::Wav), + Mono::Disk(path, audio) => crate::io::add_disk_source(s, &format!("{name}.wav"), audio, &path), + }; + sources.insert((src, ch), id); + } + } + let (mut new_tracks, mut new_clips) = (Vec::new(), Vec::new()); + for (t, clips) in by_track.into_values() { + let Some(tr) = s.track(t).cloned() else { continue }; + let n = clips.iter().map(|c| c.2).max().unwrap_or(0); + let mut lanes = Vec::with_capacity(n); + for ch in 0..n { + let nt = s.add_track(TrackKind::Audio, ChannelFormat::Mono, Some(&format!("{} {}", tr.name, crate::io::split_label(n, ch)))); + if let (Some(at), Some(from)) = (s.track_index(t), s.track_index(nt)) { + let moved = s.tracks.remove(from); + s.tracks.insert((at + 1 + ch).min(s.tracks.len()), moved); + } + if let Some(m) = s.track_mut(nt) { + m.folder = tr.folder; + m.mixer.volume_db = tr.mixer.volume_db; + m.mixer.output = tr.mixer.output.clone(); + m.mixer.sends = tr.mixer.sends.clone(); + } + lanes.push(nt); + new_tracks.push(nt); + } + for (cid, src, channels) in clips { + let Some(orig) = s.find_clip(cid).map(|(_, c)| c.clone()) else { continue }; + let ClipContent::Audio { offset, .. } = orig.content else { continue }; + for (ch, &lane) in lanes.iter().enumerate().take(channels) { + let Some(&mono) = sources.get(&(src, ch)) else { continue }; + let mut c = orig.clone(); + c.id = s.new_clip_id(); + c.name = format!("{}.{}", orig.name, crate::io::split_label(channels, ch)); + c.content = ClipContent::Audio { source: mono, offset }; + c.group = None; + new_clips.push(c.id); + // Pushed as they are: the original's layering on its track stays as it was. + if let Some(pl) = s.track_mut(lane).and_then(|l| l.playlist_mut()) { + pl.clips.push(c); + pl.sort(); + } + } + if let Some(c) = s.find_clip_mut(cid) { + c.muted = true; + } + } + } + Ok(json!({"tracks": new_tracks, "clips": new_clips})) +} + +/// Channel `ch` of in-memory `audio` as mono audio, its peaks kept (rebuilt when there are none). +fn mono_audio(audio: &SourceAudio, ch: usize) -> SourceAudio { + let buffer = AudioBuffer { sample_rate: audio.buffer.sample_rate, channels: audio.buffer.channels.get(ch).cloned().into_iter().collect() }; + match audio.peaks.get(ch) { + Some(p) => SourceAudio { buffer, peaks: vec![p.clone()], disk: None }, + None => SourceAudio::new(buffer), + } +} + +/// One mono WAV per channel of `disk`'s file, written beside it in one pass as `.wav` (a +/// number added while that name is taken), each opened to play from disk. Each comes back with +/// its path as the session names it, beside `named` (the source's own path). Nothing is left +/// behind on a failure. +fn write_files(disk: &DiskSource, named: &str, names: &[String]) -> Result)>> { + let dir = disk.path().parent().map(Path::to_path_buf).unwrap_or_default(); + let mut paths: Vec = Vec::new(); + let r = write_channels(disk, &dir, names, &mut paths); + let opened = r.and_then(|()| { + paths + .iter() + .map(|p| { + let len = std::fs::metadata(p).map_err(|err| EngineError::Io(format!("{}: {err}", p.display())))?.len(); + let audio = crate::io::disk::open_disk_audio(p, len, disk.rate()).map_err(EngineError::Io)?; + let file = p.file_name().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default(); + Ok((Path::new(named).with_file_name(file).to_string_lossy().into_owned(), audio)) + }) + .collect::>>() + }); + if opened.is_err() { + for p in &paths { + let _ = std::fs::remove_file(p); + } + } + opened +} + +/// Writes the files [`write_files`] describes, pushing each path to `paths` once it is created. +fn write_channels(disk: &DiskSource, dir: &Path, names: &[String], paths: &mut Vec) -> Result<()> { + let io = |p: &Path, err: &dyn std::fmt::Display| EngineError::Io(format!("{}: {err}", p.display())); + let opts = EncodeOptions { format: FileFormat::Wav, bit_depth: BitDepth::Float32, dither: false, bwf: None, bitrate_kbps: None, title: None }; + let mut encoders = Vec::with_capacity(names.len()); + for name in names { + let stem = crate::io::sanitize_name(name); + let (path, file) = (1..1000) + .map(|i| dir.join(if i == 1 { format!("{stem}.wav") } else { format!("{stem}-{i}.wav") })) + .find_map(|p| { + crate::file_access::check_write(&p).ok()?; + std::fs::OpenOptions::new().write(true).create_new(true).open(&p).ok().map(|f| (p, f)) + }) + .ok_or_else(|| EngineError::Io(format!("{}: no file name free for {stem}.wav", dir.display())))?; + paths.push(path.clone()); + let enc = FileEncoder::new(std::io::BufWriter::new(file), &opts, 1, disk.rate(), None).map_err(|err| io(&path, &err))?; + enc.check_room(disk.frames()).map_err(|err| io(&path, &err))?; + encoders.push((path, enc)); + } + const BLOCK: usize = 64 * 1024; + let frames = usize::try_from(disk.frames()).unwrap_or(usize::MAX); + let mut block = vec![vec![0.0f32; BLOCK]; encoders.len()]; + let unread = || EngineError::Io(format!("{}: the file could not be read", disk.path().display())); + disk.with_sync(|read| { + let mut at = 0; + while at < frames { + let len = BLOCK.min(frames - at); + // Frame by frame across the channels, so the reader passes over the file once. + for i in 0..len { + for (ch, out) in block.iter_mut().enumerate() { + out[i] = read(ch, at + i).ok_or_else(unread)?; + } + } + for ((path, enc), out) in encoders.iter_mut().zip(&block) { + enc.write(std::slice::from_ref(out), len).map_err(|err| io(path, &err))?; + } + at += len; + } + Ok::<(), EngineError>(()) + })?; + for (path, enc) in encoders { + let mut w = enc.finish().map_err(|err| io(&path, &err))?; + w.flush().map_err(|err| io(&path, &err))?; + w.into_inner().map_err(|err| io(&path, &err.error()))?.sync_all().map_err(|err| io(&path, &err))?; + } + Ok(()) +} diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index da60fdd9..3e92cbeb 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -13,6 +13,7 @@ mod clip; pub(crate) mod clip_bounce; mod clip_list; mod clip_more; +mod clip_split; mod device_pages; mod edit; mod edit_more; @@ -188,6 +189,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(track_more::specs()); v.extend(clip_more::specs()); v.extend(clip_bounce::specs()); + v.extend(clip_split::specs()); v.extend(clip_list::specs()); v.extend(event_more::specs()); v.extend(setup_more::specs()); diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index b572726e..bf38b01c 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -308,7 +308,8 @@ pub fn place_prepared(e: &mut Engine, prepared: PreparedAudio, target: Option Option> { - let mono = |t: &&transit_model::Track| t.kind == TrackKind::Audio && t.format == ChannelFormat::Mono; +/// The tracks a file of `channels` channels splits across when it lands on `target` over `span`: +/// `target` and the next `channels - 1` tracks the Edit window shows, when every one is a mono +/// audio track, none is frozen, and the ones below hold nothing in `span` (a split never edits +/// a track it was not dropped on). +fn split_tracks(s: &Session, target: TrackId, channels: usize, span: Range) -> Option> { + let mono = |t: &&transit_model::Track| t.kind == TrackKind::Audio && t.format == ChannelFormat::Mono && t.freeze.is_none(); + let free = |t: &&transit_model::Track| mono(t) && !t.clips().iter().any(|c| c.start < span.end && c.end() > span.start); let i = s.track_index(target).filter(|_| channels > 1)?; let first = s.tracks.get(i).filter(mono)?; - let below = s.tracks.iter().skip(i + 1).filter(|t| crate::edit::shown(s, t)).take(channels - 1); - let tracks: Vec = std::iter::once(first).chain(below).take_while(mono).map(|t| t.id).collect(); + let below = s.tracks.iter().skip(i + 1).filter(|t| crate::edit::shown(s, t)).take(channels - 1).take_while(free); + let tracks: Vec = std::iter::once(first).chain(below).map(|t| t.id).collect(); (tracks.len() == channels).then_some(tracks) } -/// One mono source per channel, `.L` and `.R` (past stereo, the channel labels of the -/// format a new track that wide gets), written to `Audio Files` on save, and a clip of each at -/// `at` on its track of `tracks`. The reply is the first clip's, with every clip under `split`. +/// Channel `ch` of `n` in a split's names: `L` and `R` for stereo, else its number from 1 (a +/// file's channels carry no layout here; an eight-track field recording is not 7.1). +pub(crate) fn split_label(n: usize, ch: usize) -> String { + match (n, ch) { + (2, 0) => "L".into(), + (2, 1) => "R".into(), + _ => (ch + 1).to_string(), + } +} + +/// One mono source per channel, `.L` and `.R` (`.1`, `.2`… past stereo), written to +/// `Audio Files` on save, and a clip of each at `at` on its track of `tracks`, each keeping its +/// channel's peaks. The reply is the first clip's, with every clip under `split`. fn place_split(s: &mut Session, audio: Arc, label: &str, tracks: &[TrackId], at: Samples, stamp: Option) -> Value { let stem = Path::new(label).file_stem().and_then(|x| x.to_str()).unwrap_or(label).to_string(); - let layout = ChannelFormat::for_channels(tracks.len()); - let buf = Arc::try_unwrap(audio).map_or_else(|a| a.buffer.clone(), |mut a| std::mem::take(&mut a.buffer)); + let (buf, mut peaks) = Arc::try_unwrap(audio) + .map_or_else(|a| (a.buffer.clone(), a.peaks.clone()), |mut a| (std::mem::take(&mut a.buffer), std::mem::take(&mut a.peaks))); let rate = buf.sample_rate; let mut placed = Vec::new(); for (ch, (samples, &track)) in buf.channels.into_iter().zip(tracks).enumerate() { // The source name is the given name's stem, so the extension keeps the channel label. - let name = format!("{stem}.{}.wav", layout.channel_label(ch)); - let src = add_source(s, &name, AudioBuffer { sample_rate: rate, channels: vec![samples] }, None, FileFormat::Wav); + let name = format!("{stem}.{}.wav", split_label(tracks.len(), ch)); + let mono = AudioBuffer { sample_rate: rate, channels: vec![samples] }; + let src = match peaks.get_mut(ch).map(std::mem::take).filter(|_| rate == s.sample_rate.hz()) { + Some(p) => add_source_audio(s, &name, Arc::new(SourceAudio { buffer: mono, peaks: vec![p], disk: None }), None, FileFormat::Wav), + None => add_source(s, &name, mono, None, FileFormat::Wav), + }; if let (Some(stamp), Some(sx)) = (stamp, s.sources.last_mut()) { sx.time_reference = stamp; } diff --git a/crates/engine/tests/import_split.rs b/crates/engine/tests/import_split.rs index 92917c89..6bdc571c 100644 --- a/crates/engine/tests/import_split.rs +++ b/crates/engine/tests/import_split.rs @@ -98,3 +98,77 @@ fn a_hidden_track_below_is_passed_over_for_the_next_shown_mono_track() { assert!(clips(&e, hidden).is_empty(), "nothing lands on a track the Edit window hides"); assert_eq!(clips(&e, b), vec![(0, 480, "LAV-2.R".to_string(), 1, -0.25)]); } + +#[test] +fn a_frozen_or_occupied_mono_track_below_is_never_edited_and_the_file_lands_whole() { + let d = transit_test_support::TestDir::new("import-split-guarded"); + std::fs::create_dir_all(&*d).unwrap(); + let wav = d.join("LAV-2.wav"); + std::fs::write(&wav, stereo_wav(480, 16_384, -8_192)).unwrap(); + let path = wav.to_string_lossy(); + let mut e = Engine::default(); + let (a, b) = (track(&mut e, "mono"), track(&mut e, "mono")); + // The last track has no track below: the file lands whole on it. + e.execute("file.import_audio", &json!({"path": path, "track": b})).unwrap(); + let below = clips(&e, b); + e.execute("file.import_audio", &json!({"path": path, "track": a})).unwrap(); + assert_eq!(clips(&e, a), vec![(0, 480, "LAV-2".to_string(), 2, 0.5)], "B holds a clip there: whole on A"); + assert_eq!(clips(&e, b), below, "B is untouched"); + e.execute("file.import_audio", &json!({"path": path, "track": a, "at": 960})).unwrap(); + assert_eq!(clips(&e, b).len(), 2, "B is free from 960: the split lands there"); + e.execute("track.freeze", &json!({"tracks": [b]})).unwrap(); + let undo = e.undo_history().len(); + e.execute("file.import_audio", &json!({"path": path, "track": a, "at": 4_800})).unwrap(); + assert_eq!(clips(&e, a).last().map(|c| (c.0, c.3)), Some((4_800, 2)), "B is frozen: whole on A"); + assert_eq!(e.undo_history().len(), undo + 1); +} + +#[test] +fn split_to_mono_tracks_puts_each_channel_of_a_stereo_clip_on_a_new_mono_track_below() { + let d = transit_test_support::TestDir::new("split-to-mono"); + std::fs::create_dir_all(&*d).unwrap(); + let wav = d.join("LAV-2.wav"); + std::fs::write(&wav, stereo_wav(4_800, 16_384, -8_192)).unwrap(); + let mut e = Engine::default(); + let mics = e.execute("track.new", &json!({"kind": "audio", "format": "stereo", "name": "Mics"})).unwrap()["tracks"][0].as_u64().unwrap(); + track(&mut e, "mono"); + e.execute("file.import_audio", &json!({"path": wav.to_string_lossy(), "track": mics, "at": 960})).unwrap(); + let cid = e.session().track(TrackId(mics)).unwrap().clips()[0].id.0; + let undo = e.undo_history().len(); + let r = e.execute("clip.split_to_mono", &json!({"clips": [cid]})).unwrap(); + let names: Vec = e.session().tracks.iter().map(|t| t.name.clone()).collect(); + assert_eq!(names[..3], ["Mics", "Mics L", "Mics R"], "the new tracks sit right below: {names:?}"); + let (l, r) = (r["tracks"][0].as_u64().unwrap(), r["tracks"][1].as_u64().unwrap()); + assert_eq!(clips(&e, l), vec![(960, 4_800, "LAV-2.L".to_string(), 1, 0.5)]); + assert_eq!(clips(&e, r), vec![(960, 4_800, "LAV-2.R".to_string(), 1, -0.25)]); + assert!(e.session().find_clip(transit_engine::model::ClipId(cid)).unwrap().1.muted, "the original is muted"); + assert_eq!(e.undo_history().len(), undo + 1, "one undo step"); + e.undo(); + assert_eq!(e.session().tracks.len(), 2, "one undo takes the tracks back"); + assert!(!e.session().find_clip(transit_engine::model::ClipId(cid)).unwrap().1.muted); +} + +#[test] +fn split_to_mono_tracks_writes_a_mono_file_per_channel_for_a_take_played_from_disk() { + let d = transit_test_support::TestDir::new("split-to-mono-disk"); + std::fs::create_dir_all(&*d).unwrap(); + let take = d.join("Take.wav"); + std::fs::write(&take, stereo_wav(4_800, 16_384, -8_192)).unwrap(); + let mut e = Engine::default(); + // A take longer than this plays from its file (ADR 0035): 0.001 minutes is 2880 frames. + e.session_mut().edit.values.insert(transit_model::disk::STREAM_MINUTES_KEY.into(), 0.001); + let mics = track(&mut e, "stereo"); + let ids = transit_engine::io::add_recording_take(&mut e, &transit_engine::io::Recording::new(0), vec![(TrackId(mics), take)], false); + assert!(e.session().sources.last().is_some_and(|s| s.disk), "the take plays from disk"); + let r = e.execute("clip.split_to_mono", &json!({"clips": [ids[0].0]})).unwrap(); + for (i, (side, want)) in [("L", 0.5), ("R", -0.25)].into_iter().enumerate() { + let t = r["tracks"][i].as_u64().unwrap(); + let s = e.session(); + let c = &s.track(TrackId(t)).unwrap().clips()[0]; + let transit_engine::model::ClipContent::Audio { source, .. } = c.content else { panic!("an audio clip") }; + let src = s.source(source).unwrap(); + assert!(src.disk && src.channels == 1 && src.path.ends_with(&format!("Take.{side}.wav")), "{src:?}"); + let disk = s.pool.get(source).unwrap().disk.clone().unwrap(); + assert_eq!((disk.frames(), disk.with_sync(|read| read(0, 4_799))), (4_800, Some(want)), "Take.{side}.wav holds that channel"); + } +} diff --git a/crates/ui-studio/src/arrange.rs b/crates/ui-studio/src/arrange.rs index 7d2aa05e..b6617867 100644 --- a/crates/ui-studio/src/arrange.rs +++ b/crates/ui-studio/src/arrange.rs @@ -855,6 +855,11 @@ fn timeline_input(app: &mut StudioApp, ui: &mut Ui, s: &Session, map: Map, tl: R let item = crate::bounce_in_place::clip_menu_item(app, ui); app.arrange.menu.retain(|m| m.label != item.label); app.arrange.menu.push(item); + // Each channel of the selected stereo or wider clips on a new mono track below. + if on_clip && ui.add(crate::chrome::MenuRow::new("Split to Mono Tracks")).clicked() { + let _ = app.run("clip.split_to_mono", json!({})); + ui.close(); + } ui.separator(); crate::edit_tools::context_menu_items(app, ui); }); diff --git a/docs/user-guide.md b/docs/user-guide.md index 37dfecf8..75c8cbdc 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -902,9 +902,12 @@ into the arrangement at the cursor (a `.transit` or `.dawproject` file opens as file imports as MIDI). On Windows a file manager drop lands where the pointer is when you let go; on other platforms it lands as soon as the pointer moves after you let go (see the known issues). A stereo or wider file that lands on a mono audio track with as many mono tracks below it (in the Edit -window's order) splits across them in one undo step: each channel becomes its own mono file, -`.L` and `.R`, saved to `Audio Files`; with fewer mono tracks below, the file lands -whole on the one track. +window's order, none frozen and none holding a clip where the file goes) splits across them in +one undo step: each channel becomes its own mono file, `.L` and `.R` (`.1`, `.2`… past +stereo), saved to `Audio Files`; otherwise the file lands whole on the one track. To split a clip +already in the session, such as two microphones recorded onto one stereo track, right-click it and +choose **Split to Mono Tracks**: each channel goes to a new mono track below the clip's track, the +original clip is muted, and a take played from its file gets one mono WAV per channel beside it. Right-click a pad and choose **Clear pad** to empty it and reset its name, choke group, mute, and solo. Delete or Backspace does the same for the selected pad while the Sampler window has From b179c1f96318b4be6ed340e0c654fdd067979ccf Mon Sep 17 00:00:00 2001 From: BlueJayLouche Date: Sat, 21 Nov 2026 22:03:14 +1100 Subject: [PATCH 03/15] ui: a file dropped from the file manager lands where it is let go, as a browser drag does: on the audio track lane or header under the pointer (at the pointer's time on a lane), or on a new track below the tracks; anywhere else at the cursor as before. A stereo file on a mono lane with a mono track below now splits there instead of making a new stereo track --- crates/ui-studio/src/browser.rs | 2 +- crates/ui-studio/src/drops.rs | 35 ++++++++++++++++--- .../src/sampler_panel/drop_routing_tests.rs | 26 ++++++++++++++ docs/user-guide.md | 7 ++-- 4 files changed, 61 insertions(+), 9 deletions(-) diff --git a/crates/ui-studio/src/browser.rs b/crates/ui-studio/src/browser.rs index 589e7fa5..afd7ec93 100644 --- a/crates/ui-studio/src/browser.rs +++ b/crates/ui-studio/src/browser.rs @@ -666,7 +666,7 @@ impl StudioApp { /// device layouts. An editor window on top at `pos` comes first and takes the drop whole: /// `audio` (the payload holds an audio file) lands on a Sampler pad or an empty Sampler view's /// well, anything else over a window is no target (nothing behind a window is reached). - fn drop_target(&self, ctx: &egui::Context, pos: Pos2, snap: bool, audio: bool) -> Option<(Target, R4)> { + pub(crate) fn drop_target(&self, ctx: &egui::Context, pos: Pos2, snap: bool, audio: bool) -> Option<(Target, R4)> { if let Some(key) = self.editor_window_at(ctx, pos) { return if audio { self.editor_target(key, pos) } else { None }; } diff --git a/crates/ui-studio/src/drops.rs b/crates/ui-studio/src/drops.rs index 361a2924..9168dbdf 100644 --- a/crates/ui-studio/src/drops.rs +++ b/crates/ui-studio/src/drops.rs @@ -8,12 +8,14 @@ //! frame or a later one). A `PointerGone` does not route it blind: the drop stays held, and only //! after [`GONE_GRACE_FRAMES`] frames with no position does it go to the arrangement. Then the //! editor window on top at that position (egui's own layer order) claims it, or the arrangement -//! imports it. Exactly one claimant takes a drop; a held drop never vanishes (a second drop while +//! imports it: on the audio track under the pointer or below the tracks, as a browser drag lands, +//! else at the cursor. Exactly one claimant takes a drop; a held drop never vanishes (a second drop while //! one is held routes with it). use crate::StudioApp; use std::path::PathBuf; use transit_model::TrackId; +use transit_time::Samples; /// Files offered to a claimant, and where they were dropped (`None`: the pointer left the window). #[derive(Debug, Clone)] @@ -110,8 +112,22 @@ pub(crate) fn route(app: &mut StudioApp, ctx: &egui::Context, offer: DropOffer) r.offer = Some((key, offer)); return; } + let snap = !ctx.input(|i| i.modifiers.shift); + let at = offer.pos.and_then(|p| arrangement_target(app, ctx, p, snap)); for p in &offer.paths { - open_path(app, &p.to_string_lossy()); + open_path_at(app, &p.to_string_lossy(), at); + } +} + +/// Where a file-manager drop at `pos` lands in the arrangement, as a browser drag does: the audio +/// track whose lane (at the pointer's time) or header is under the pointer, or a new track when it +/// is below the tracks. `None` elsewhere: the drop imports at the cursor, as before. +fn arrangement_target(app: &StudioApp, ctx: &egui::Context, pos: egui::Pos2, snap: bool) -> Option<(Option, Option)> { + let audio = |t: TrackId| app.engine.session().track(t).is_some_and(|t| t.kind == transit_model::TrackKind::Audio); + match app.drop_target(ctx, pos, snap, true)?.0 { + crate::browser::Target::Track { track, at } if audio(track) => Some((Some(track), at)), + crate::browser::Target::Below { at } => Some((None, at)), + _ => None, } } @@ -131,6 +147,12 @@ pub(crate) fn take(app: &mut StudioApp, key: (TrackId, usize)) -> Option, Option)>) { let lower = p.to_ascii_lowercase(); if lower.ends_with(".transit") || lower.ends_with(".dawproject") { app.run_or_ask("session.open", serde_json::json!({"path": p})); @@ -139,9 +161,12 @@ pub fn open_path(app: &mut StudioApp, p: &str) { let r = if lower.ends_with(".mid") || lower.ends_with(".midi") || lower.ends_with(".smf") { app.run("file.import_midi", serde_json::json!({"path": p})) } else { - let at = app.cursor(); - let mut params = serde_json::json!({"path": p, "at": at}); - if let Some(t) = app.cursor_track() { + let (track, time) = match at { + Some((track, time)) => (track, time.unwrap_or_else(|| app.cursor())), + None => (app.cursor_track(), app.cursor()), + }; + let mut params = serde_json::json!({"path": p, "at": time}); + if let Some(t) = track { params["track"] = serde_json::json!(t.0); } app.run("file.import_audio", params) diff --git a/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs b/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs index 3096261a..d0666efa 100644 --- a/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs +++ b/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs @@ -157,3 +157,29 @@ fn the_gone_rule_holds_where_the_old_rule_imported() { assert_eq!(placement(None, false, &mut count), Placement::Hold); } } + +/// A file-manager drop lands where it is let go, as a browser drag does: a stereo file on a mono +/// track's lane with a mono track below splits there, rather than going to the cursor's track (a +/// new stereo track when the cursor has none). +#[test] +fn a_stereo_file_dropped_on_a_mono_lane_splits_onto_that_track_and_the_one_below() { + let mut t = T::new(); + let mono = |t: &mut T| t.app.run("track.new", serde_json::json!({"kind": "audio", "format": "mono"})).unwrap()["tracks"][0].as_u64().unwrap(); + let (a, b) = (mono(&mut t), mono(&mut t)); + t.frames(3); + let mut wav = Vec::new(); + for v in [0x4646_4952u32, 36 + 4_800 * 4, 0x4556_4157, 0x2074_6d66, 16, 0x0002_0001, 48_000, 48_000 * 4, 0x0010_0004, 0x6174_6164, 4_800 * 4] { + wav.extend(v.to_le_bytes()); + } + for _ in 0..4_800 { + wav.extend([0x00, 0x40, 0x00, 0xe0]); // 0.5 left, -0.25 right + } + let path = t.dir.join("Mics.wav"); + std::fs::write(&path, wav).unwrap(); + let lane = t.app.arrange.layout.tracks.iter().find(|r| r.id == a).unwrap().lane; + t.drop_file(&path, mid(lane)); + let s = t.app.engine.session(); + let names = |id: u64| s.track(TrackId(id)).unwrap().clips().iter().map(|c| c.name.clone()).collect::>(); + assert_eq!(s.tracks.len(), 2, "no new track"); + assert_eq!((names(a), names(b)), (vec!["Mics.L".to_string()], vec!["Mics.R".to_string()])); +} diff --git a/docs/user-guide.md b/docs/user-guide.md index 75c8cbdc..8891dd10 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -897,9 +897,10 @@ slot), in one undo step, with the dashed well outlined while you hold it there; view has content it takes no drag. On an Instrument key map with zones, a file dragged over keys no zone plays shows, dashed, the keys it will cover, and letting go makes a zone there (see below). A file or plug-in dropped elsewhere on a device window is ignored; the window takes the drop, so nothing behind it is reached. Anywhere else, a browser drag lands on the track lane, -header, mixer strip or device chain where you let go, and a file from the file manager is imported -into the arrangement at the cursor (a `.transit` or `.dawproject` file opens as the session, a MIDI -file imports as MIDI). On Windows a file manager drop lands where the pointer is when you let go; on other +header, mixer strip or device chain where you let go. A file from the file manager lands the same +way on an audio track's lane or header, or below the tracks on a new track; anywhere else it is +imported into the arrangement at the cursor (a `.transit` or `.dawproject` file opens as the +session, a MIDI file imports as MIDI). On Windows a file manager drop lands where the pointer is when you let go; on other platforms it lands as soon as the pointer moves after you let go (see the known issues). A stereo or wider file that lands on a mono audio track with as many mono tracks below it (in the Edit window's order, none frozen and none holding a clip where the file goes) splits across them in From 07f30979e6a735a2cba8f3e05b98f5c49534ba50 Mon Sep 17 00:00:00 2001 From: BlueJayLouche Date: Sat, 21 Nov 2026 22:10:35 +1100 Subject: [PATCH 04/15] engine: second refutation review of Split to Mono Tracks (ADR 0009): a failure on a later take removes every file the split wrote; the new tracks sit right below the clip's track with a Master above it; a split take's sources name the files written and keep its BWF stamp; duplicate clip ids split once; at most 64 channels; a write refusal says why; the import split keeps disk-backed audio whole --- crates/engine/src/cmd/clip_split.rs | 154 ++++++++++++++++++---------- crates/engine/src/io.rs | 2 +- crates/engine/tests/import_split.rs | 47 +++++++++ 3 files changed, 148 insertions(+), 55 deletions(-) diff --git a/crates/engine/src/cmd/clip_split.rs b/crates/engine/src/cmd/clip_split.rs index 3fd4cbc6..72109652 100644 --- a/crates/engine/src/cmd/clip_split.rs +++ b/crates/engine/src/cmd/clip_split.rs @@ -30,15 +30,25 @@ pub fn specs() -> Vec { )] } +/// The most channels a clip splits into: one track each, so a hostile file's channel count must +/// not become tens of thousands of tracks. +// ponytail: a fixed cap; a MADI-sized recording (64) fits, a wider one is refused. +const MAX_CHANNELS: usize = 64; + /// A channel's audio, ready to become a source. enum Mono { Memory(SourceAudio), - /// The file written for it, as the session names it, and its audio played from that file. - Disk(String, Arc), + /// The file written for it, and its audio played from that file. + Disk(PathBuf, Arc), } +/// One source's split: its id, its BWF time stamp, and each channel's name and audio. +type Split = (SourceId, u64, Vec<(String, Mono)>); + fn split_to_mono(e: &mut Engine, p: &Value) -> Result { - let ids = clip_ids_param(e, p); + let mut ids = clip_ids_param(e, p); + let mut seen = std::collections::HashSet::new(); + ids.retain(|id| seen.insert(*id)); let s = e.session(); // The clips to split on each track, in track order, with their sources' channel counts. let mut by_track: BTreeMap)> = BTreeMap::new(); @@ -46,6 +56,9 @@ fn split_to_mono(e: &mut Engine, p: &Value) -> Result { let (t, c) = s.find_clip(*id).ok_or_else(|| bad(ID, format!("unknown clip {}", id.0)))?; let ClipContent::Audio { source, .. } = c.content else { continue }; let n = s.pool.get(source).map_or(0, |a| a.buffer.num_channels()); + if n > MAX_CHANNELS { + return Err(bad(ID, format!("{} has {n} channels: a clip splits into at most {MAX_CHANNELS} tracks", c.name))); + } if let (true, Some(i)) = (n > 1, s.track_index(t)) { by_track.entry(i).or_insert((t, Vec::new())).1.push((*id, source, n)); } @@ -57,31 +70,32 @@ fn split_to_mono(e: &mut Engine, p: &Value) -> Result { if let Some(tr) = by_track.values().filter_map(|(t, _)| s.track(*t)).find(|t| t.freeze.is_some()) { return Err(bad(ID, format!("{} is frozen: unfreeze it to split its clips", tr.name))); } - // Every channel's audio before the session changes, so a refusal leaves it as it was. - let mut split: BTreeMap> = BTreeMap::new(); - for (_, clips) in by_track.values() { - for &(_, src, n) in clips { - if split.contains_key(&src) { - continue; + // Every channel's audio before the session changes, so a refusal leaves it as it was and no + // file written for it behind. + let mut written = Vec::new(); + let split = match prepare(s, &by_track, &mut written) { + Ok(split) => split, + Err(err) => { + for p in &written { + let _ = std::fs::remove_file(p); + let _ = std::fs::remove_file(transit_model::disk::sidecar_path(p)); } - let (Some(meta), Some(audio)) = (s.source(src), s.pool.get(src)) else { continue }; - let names: Vec = (0..n).map(|ch| format!("{}.{}", meta.name, crate::io::split_label(n, ch))).collect(); - let monos = match &audio.disk { - Some(disk) => write_files(disk, &meta.path, &names)?.into_iter().map(|(path, a)| Mono::Disk(path, a)).collect(), - None => (0..n).map(|ch| Mono::Memory(mono_audio(audio, ch))).collect::>(), - }; - split.insert(src, names.into_iter().zip(monos).collect()); + return Err(err); } - } + }; let s = e.session_mut(); let mut sources: BTreeMap<(SourceId, usize), SourceId> = BTreeMap::new(); - for (src, monos) in split { + for (src, stamp, monos) in split { for (ch, (name, mono)) in monos.into_iter().enumerate() { let id = match mono { // The extension keeps the label: a source is named after its file's stem. Mono::Memory(audio) => crate::io::add_source_audio(s, &format!("{name}.wav"), Arc::new(audio), None, FileFormat::Wav), - Mono::Disk(path, audio) => crate::io::add_disk_source(s, &format!("{name}.wav"), audio, &path), + // The path written, absolute as a recording's is: a save brings it into the session folder. + Mono::Disk(path, audio) => crate::io::add_disk_source(s, &format!("{name}.wav"), audio, &path.to_string_lossy()), }; + if let Some(sx) = s.sources.last_mut() { + sx.time_reference = stamp; + } sources.insert((src, ch), id); } } @@ -92,9 +106,11 @@ fn split_to_mono(e: &mut Engine, p: &Value) -> Result { let mut lanes = Vec::with_capacity(n); for ch in 0..n { let nt = s.add_track(TrackKind::Audio, ChannelFormat::Mono, Some(&format!("{} {}", tr.name, crate::io::split_label(n, ch)))); - if let (Some(at), Some(from)) = (s.track_index(t), s.track_index(nt)) { + // Taken out before `t` is found: a new track goes in before a Master, which may sit above `t`. + if let Some(from) = s.track_index(nt) { let moved = s.tracks.remove(from); - s.tracks.insert((at + 1 + ch).min(s.tracks.len()), moved); + let at = s.track_index(t).map_or(s.tracks.len(), |at| at + 1 + ch); + s.tracks.insert(at.min(s.tracks.len()), moved); } if let Some(m) = s.track_mut(nt) { m.folder = tr.folder; @@ -139,48 +155,78 @@ fn mono_audio(audio: &SourceAudio, ch: usize) -> SourceAudio { } } -/// One mono WAV per channel of `disk`'s file, written beside it in one pass as `.wav` (a -/// number added while that name is taken), each opened to play from disk. Each comes back with -/// its path as the session names it, beside `named` (the source's own path). Nothing is left -/// behind on a failure. -fn write_files(disk: &DiskSource, named: &str, names: &[String]) -> Result)>> { - let dir = disk.path().parent().map(Path::to_path_buf).unwrap_or_default(); - let mut paths: Vec = Vec::new(); - let r = write_channels(disk, &dir, names, &mut paths); - let opened = r.and_then(|()| { - paths - .iter() - .map(|p| { - let len = std::fs::metadata(p).map_err(|err| EngineError::Io(format!("{}: {err}", p.display())))?.len(); - let audio = crate::io::disk::open_disk_audio(p, len, disk.rate()).map_err(EngineError::Io)?; - let file = p.file_name().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default(); - Ok((Path::new(named).with_file_name(file).to_string_lossy().into_owned(), audio)) - }) - .collect::>>() - }); - if opened.is_err() { - for p in &paths { - let _ = std::fs::remove_file(p); +/// Each source's channels, in memory or as one mono WAV per channel written beside its file (a +/// number added while a name is taken). The files are opened to play from disk only once every +/// one is complete; each path created is in `written`, for the caller to remove on a failure. +fn prepare( + s: &transit_model::Session, + by_track: &BTreeMap)>, + written: &mut Vec, +) -> Result> { + let mut out: Vec<(SourceId, u64, Vec<(String, Option)>, Option>)> = Vec::new(); + for (_, clips) in by_track.values() { + for &(_, src, n) in clips { + if out.iter().any(|o| o.0 == src) { + continue; + } + let (Some(meta), Some(audio)) = (s.source(src), s.pool.get(src)) else { continue }; + let names: Vec = (0..n).map(|ch| format!("{}.{}", meta.name, crate::io::split_label(n, ch))).collect(); + let channels = match &audio.disk { + Some(disk) => { + write_channels(disk, &names, written)?; + names.into_iter().map(|name| (name, None)).collect() + } + None => names.into_iter().enumerate().map(|(ch, name)| (name, Some(mono_audio(audio, ch)))).collect(), + }; + out.push((src, meta.time_reference, channels, audio.disk.clone())); } } - opened + let mut files = written.iter(); + out.into_iter() + .map(|(src, stamp, channels, disk)| { + let monos = channels + .into_iter() + .map(|(name, mem)| match (mem, &disk) { + (Some(audio), _) => Ok((name, Mono::Memory(audio))), + (None, Some(disk)) => { + let p = files.next().ok_or_else(|| EngineError::Io(format!("{name}: its file was not written")))?; + let len = std::fs::metadata(p).map_err(|err| EngineError::Io(format!("{}: {err}", p.display())))?.len(); + let audio = crate::io::disk::open_disk_audio(p, len, disk.rate()).map_err(EngineError::Io)?; + Ok((name, Mono::Disk(p.clone(), audio))) + } + (None, None) => Err(EngineError::Io(format!("{name}: no audio"))), + }) + .collect::>>()?; + Ok((src, stamp, monos)) + }) + .collect() } -/// Writes the files [`write_files`] describes, pushing each path to `paths` once it is created. -fn write_channels(disk: &DiskSource, dir: &Path, names: &[String], paths: &mut Vec) -> Result<()> { +/// One mono float WAV per channel of `disk`'s file, beside it, named `names` (`.wav`, or +/// `-2.wav` and on while that is taken), in one pass over the file. Each path is pushed to +/// `written` as soon as it is created. +fn write_channels(disk: &DiskSource, names: &[String], written: &mut Vec) -> Result<()> { let io = |p: &Path, err: &dyn std::fmt::Display| EngineError::Io(format!("{}: {err}", p.display())); + let dir = disk.path().parent().map(Path::to_path_buf).unwrap_or_default(); let opts = EncodeOptions { format: FileFormat::Wav, bit_depth: BitDepth::Float32, dither: false, bwf: None, bitrate_kbps: None, title: None }; let mut encoders = Vec::with_capacity(names.len()); for name in names { let stem = crate::io::sanitize_name(name); - let (path, file) = (1..1000) - .map(|i| dir.join(if i == 1 { format!("{stem}.wav") } else { format!("{stem}-{i}.wav") })) - .find_map(|p| { - crate::file_access::check_write(&p).ok()?; - std::fs::OpenOptions::new().write(true).create_new(true).open(&p).ok().map(|f| (p, f)) - }) - .ok_or_else(|| EngineError::Io(format!("{}: no file name free for {stem}.wav", dir.display())))?; - paths.push(path.clone()); + let mut found = None; + for i in 1..1000 { + let p = dir.join(if i == 1 { format!("{stem}.wav") } else { format!("{stem}-{i}.wav") }); + crate::file_access::check_write(&p).map_err(EngineError::Io)?; + match std::fs::OpenOptions::new().write(true).create_new(true).open(&p) { + Ok(f) => { + found = Some((p, f)); + break; + } + Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(err) => return Err(io(&p, &err)), + } + } + let (path, file) = found.ok_or_else(|| EngineError::Io(format!("{}: no file name free for {stem}.wav", dir.display())))?; + written.push(path.clone()); let enc = FileEncoder::new(std::io::BufWriter::new(file), &opts, 1, disk.rate(), None).map_err(|err| io(&path, &err))?; enc.check_room(disk.frames()).map_err(|err| io(&path, &err))?; encoders.push((path, enc)); diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index bf38b01c..810b6811 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -309,7 +309,7 @@ pub fn place_prepared(e: &mut Engine, prepared: PreparedAudio, target: Option>()})); + assert!(r.is_err(), "{r:?}"); + // The takes' own peaks sidecars are built in the background; only split files are counted. + let left: Vec = std::fs::read_dir(&*d).unwrap().map(|f| f.unwrap().file_name().to_string_lossy().into_owned()).collect(); + assert!(left.iter().all(|f| !f.contains(".L") && !f.contains(".R")), "no split file stays behind: {left:?}"); + assert_eq!(e.session().tracks.len(), tracks, "the session is as it was"); +} + +#[test] +fn the_new_tracks_sit_right_below_the_clips_track_with_a_master_above_it() { + let d = transit_test_support::TestDir::new("split-to-mono-master"); + std::fs::create_dir_all(&*d).unwrap(); + let wav = d.join("LAV-2.wav"); + std::fs::write(&wav, stereo_wav(480, 16_384, -8_192)).unwrap(); + let mut e = Engine::default(); + let mics = e.execute("track.new", &json!({"kind": "audio", "format": "stereo", "name": "Mics"})).unwrap()["tracks"][0].as_u64().unwrap(); + e.execute("track.new", &json!({"kind": "audio", "format": "mono", "name": "Other"})).unwrap(); + let master = e.session_mut().add_track(transit_model::TrackKind::Master, transit_model::ChannelFormat::Stereo, Some("Master")); + let s = e.session_mut(); + let m = s.tracks.iter().position(|t| t.id == master).unwrap(); + let moved = s.tracks.remove(m); + s.tracks.insert(0, moved); + e.execute("file.import_audio", &json!({"path": wav.to_string_lossy(), "track": mics})).unwrap(); + let cid = e.session().track(TrackId(mics)).unwrap().clips()[0].id.0; + e.execute("clip.split_to_mono", &json!({"clips": [cid, cid]})).unwrap(); + let names: Vec = e.session().tracks.iter().map(|t| t.name.clone()).collect(); + assert_eq!(names, ["Master 1", "Mics", "Mics L", "Mics R", "Other"]); + let per_track: Vec = e.session().tracks[2..4].iter().map(|t| t.clips().len()).collect(); + assert_eq!(per_track, [1, 1], "a clip named twice splits once"); +} From f9b191a6c58fc3f9151f908cabeeb1619b89476c Mon Sep 17 00:00:00 2001 From: BlueJayLouche Date: Sat, 21 Nov 2026 22:26:40 +1100 Subject: [PATCH 05/15] ui, engine: third refutation review of the file-manager drop routing (ADR 0009): a drop that also opens a session lands none of its files by the pointer, so none reaches a track of the new session by an old track's id; several files dropped on a track follow each other there instead of each erasing the last; file.import_audio refuses a track that is not an audio track (as file.commit_import does), and a drop at the cursor uses the cursor's track only when it holds audio; K113 notes that the drop position now picks the track --- crates/engine/src/cmd/file.rs | 4 ++ crates/engine/tests/import_split.rs | 13 +++++ crates/ui-studio/src/drops.rs | 48 +++++++++++++++---- .../src/sampler_panel/drop_routing_tests.rs | 41 ++++++++++++++++ .../ui-studio/src/sampler_panel/test_rig.rs | 7 ++- docs/known-issues/entries/K113.md | 2 +- docs/user-guide.md | 7 +-- 7 files changed, 107 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 51ebe61d..7960574a 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -361,6 +361,10 @@ fn commit_import(e: &mut Engine, p: &Value) -> Result { /// audio track or errors when none is selected. fn import_audio_target(e: &Engine, p: &Value) -> Result> { if let Some(t) = track_param(e, "file.import_audio", p, "track")? { + // As `file.commit_import`: audio never lands on a MIDI, instrument or other track. + if let Some(tr) = e.session().track(t).filter(|tr| tr.kind != TrackKind::Audio) { + return Err(bad("file.import_audio", format!("{} is not an audio track", tr.name))); + } return Ok(Some(t)); } if bool_or(p, "new_tracks", true) { diff --git a/crates/engine/tests/import_split.rs b/crates/engine/tests/import_split.rs index 2aafa2f6..c82c352c 100644 --- a/crates/engine/tests/import_split.rs +++ b/crates/engine/tests/import_split.rs @@ -219,3 +219,16 @@ fn the_new_tracks_sit_right_below_the_clips_track_with_a_master_above_it() { let per_track: Vec = e.session().tracks[2..4].iter().map(|t| t.clips().len()).collect(); assert_eq!(per_track, [1, 1], "a clip named twice splits once"); } + +#[test] +fn audio_is_never_imported_onto_a_midi_track() { + let d = transit_test_support::TestDir::new("import-onto-midi"); + std::fs::create_dir_all(&*d).unwrap(); + let wav = d.join("Kick.wav"); + std::fs::write(&wav, stereo_wav(480, 16_384, -8_192)).unwrap(); + let mut e = Engine::default(); + let midi = e.execute("track.new", &json!({"kind": "midi", "name": "Synth"})).unwrap()["tracks"][0].as_u64().unwrap(); + let r = e.execute("file.import_audio", &json!({"path": wav.to_string_lossy(), "track": midi})); + assert!(r.as_ref().is_err_and(|err| err.to_string().contains("Synth is not an audio track")), "{r:?}"); + assert!(e.session().track(TrackId(midi)).unwrap().clips().is_empty() && e.session().sources.is_empty()); +} diff --git a/crates/ui-studio/src/drops.rs b/crates/ui-studio/src/drops.rs index 9168dbdf..b5359a61 100644 --- a/crates/ui-studio/src/drops.rs +++ b/crates/ui-studio/src/drops.rs @@ -113,15 +113,32 @@ pub(crate) fn route(app: &mut StudioApp, ctx: &egui::Context, offer: DropOffer) return; } let snap = !ctx.input(|i| i.modifiers.shift); - let at = offer.pos.and_then(|p| arrangement_target(app, ctx, p, snap)); + // A drop that opens a session replaces the document the pointer was over: none of it lands + // by the pointer, so no file can reach a track of the new session by an old track's id. + let opens = offer.paths.iter().any(|p| opens_session(&p.to_string_lossy())); + let mut at = offer.pos.filter(|_| !opens).and_then(|p| arrangement_target(app, ctx, p, snap)); + if let Some((_, time)) = at.as_mut() { + *time = Some(time.unwrap_or_else(|| app.cursor())); + } for p in &offer.paths { - open_path_at(app, &p.to_string_lossy(), at); + let placed = open_path_at(app, &p.to_string_lossy(), at); + // The files of one drop follow each other on one track, as a browser drag's do. + if let (Some(at), Some((track, end))) = (at.as_mut(), placed) { + *at = (Some(track), Some(end)); + } } } +/// Whether dropping `p` opens it as the session. +fn opens_session(p: &str) -> bool { + let lower = p.to_ascii_lowercase(); + lower.ends_with(".transit") || lower.ends_with(".dawproject") +} + /// Where a file-manager drop at `pos` lands in the arrangement, as a browser drag does: the audio -/// track whose lane (at the pointer's time) or header is under the pointer, or a new track when it -/// is below the tracks. `None` elsewhere: the drop imports at the cursor, as before. +/// track whose lane (at the pointer's time), header, mixer strip or device chain is under the +/// pointer, or a new track when it is below the tracks. `None` elsewhere: the drop imports at the +/// cursor, as before. fn arrangement_target(app: &StudioApp, ctx: &egui::Context, pos: egui::Pos2, snap: bool) -> Option<(Option, Option)> { let audio = |t: TrackId| app.engine.session().track(t).is_some_and(|t| t.kind == transit_model::TrackKind::Audio); match app.drop_target(ctx, pos, snap, true)?.0 { @@ -151,27 +168,38 @@ pub fn open_path(app: &mut StudioApp, p: &str) { } /// [`open_path`], with an audio file landing on `at`'s track (none: a new track) at its time (none: -/// the cursor) when `at` is given, where [`arrangement_target`] put a drop. -fn open_path_at(app: &mut StudioApp, p: &str, at: Option<(Option, Option)>) { +/// the cursor) when `at` is given, where [`arrangement_target`] put a drop. Returns the track an +/// audio file landed on and where it ends there. +fn open_path_at(app: &mut StudioApp, p: &str, at: Option<(Option, Option)>) -> Option<(TrackId, Samples)> { let lower = p.to_ascii_lowercase(); - if lower.ends_with(".transit") || lower.ends_with(".dawproject") { + if opens_session(p) { app.run_or_ask("session.open", serde_json::json!({"path": p})); - return; + return None; } let r = if lower.ends_with(".mid") || lower.ends_with(".midi") || lower.ends_with(".smf") { app.run("file.import_midi", serde_json::json!({"path": p})) } else { + // The cursor's track only when it holds audio; else a new track. + let audio = |t: &TrackId| app.engine.session().track(*t).is_some_and(|t| t.kind == transit_model::TrackKind::Audio); let (track, time) = match at { Some((track, time)) => (track, time.unwrap_or_else(|| app.cursor())), - None => (app.cursor_track(), app.cursor()), + None => (app.cursor_track().filter(audio), app.cursor()), }; let mut params = serde_json::json!({"path": p, "at": time}); if let Some(t) = track { params["track"] = serde_json::json!(t.0); } - app.run("file.import_audio", params) + let r = app.run("file.import_audio", params); + if let Ok(v) = &r { + let one = &v["imported"][0]; + if let (Some(t), Some(len)) = (one["track"].as_u64(), one["frames"].as_i64()) { + return Some((TrackId(t), time.saturating_add(len))); + } + } + r }; if let Err(e) = r { log::warn!("{p}: {e}"); } + None } diff --git a/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs b/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs index d0666efa..975dcb52 100644 --- a/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs +++ b/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs @@ -183,3 +183,44 @@ fn a_stereo_file_dropped_on_a_mono_lane_splits_onto_that_track_and_the_one_below assert_eq!(s.tracks.len(), 2, "no new track"); assert_eq!((names(a), names(b)), (vec!["Mics.L".to_string()], vec!["Mics.R".to_string()])); } + +/// Several files dropped on a lane follow each other on its track, as a browser drag's do: each +/// lands where the one before ends, so none erases another. +#[test] +fn files_dropped_together_on_a_lane_follow_each_other_on_its_track() { + let mut t = T::new(); + let a = t.app.run("track.new", serde_json::json!({"kind": "audio", "format": "mono"})).unwrap()["tracks"][0].as_u64().unwrap(); + t.frames(3); + let (one, two) = (t.sample("One.wav", 4_800), t.sample("Two.wav", 4_800)); + let lane = t.app.arrange.layout.tracks.iter().find(|r| r.id == a).unwrap().lane; + t.drop_files(vec![one, two], mid(lane)); + let clips: Vec<(String, i64)> = t.app.engine.session().track(TrackId(a)).unwrap().clips().iter().map(|c| (c.name.clone(), c.start)).collect(); + assert_eq!(clips.len(), 2, "both files are on the track: {clips:?}"); + assert_eq!(clips[1].1 - clips[0].1, 4_800, "Two starts where One ends: {clips:?}"); +} + +/// A drop that opens a session lands none of its files by the pointer: the track it was over +/// belongs to the document the session replaced, and its id may name another track (here a MIDI +/// track) in the new one. +#[test] +fn a_drop_that_opens_a_session_puts_no_audio_on_the_new_sessions_track_of_the_same_id() { + let mut t = T::new(); + let mut other = transit_engine::Engine::default(); + other.execute("track.new", &serde_json::json!({"kind": "audio", "name": "Drums"})).unwrap(); + let synth = other.execute("track.new", &serde_json::json!({"kind": "midi", "name": "Synth"})).unwrap()["tracks"][0].as_u64().unwrap(); + let b = t.dir.join("B.transit"); + other.execute("session.save", &serde_json::json!({"path": b.to_string_lossy()})).unwrap(); + for _ in 0..2 { + t.app.run("track.new", serde_json::json!({"kind": "audio", "format": "mono"})).unwrap(); + } + t.app.run("session.save", serde_json::json!({"path": t.dir.join("A.transit").to_string_lossy()})).unwrap(); + t.frames(3); + let lane = t.app.arrange.layout.tracks.iter().find(|r| r.id == synth).expect("A has a track of Synth's id").lane; + let kick = t.sample("Kick.wav", 2_400); + t.drop_files(vec![b, kick], mid(lane)); + let s = t.app.engine.session(); + assert!(s.tracks.iter().any(|tr| tr.name == "Synth"), "B is open"); + assert!(s.track(TrackId(synth)).unwrap().clips().is_empty(), "no audio on the MIDI track"); + let kick_on_audio = s.tracks.iter().any(|tr| tr.kind == transit_model::TrackKind::Audio && tr.clips().iter().any(|c| c.name == "Kick")); + assert!(kick_on_audio, "Kick is imported, on an audio track"); +} diff --git a/crates/ui-studio/src/sampler_panel/test_rig.rs b/crates/ui-studio/src/sampler_panel/test_rig.rs index 918c3b30..6a91670d 100644 --- a/crates/ui-studio/src/sampler_panel/test_rig.rs +++ b/crates/ui-studio/src/sampler_panel/test_rig.rs @@ -161,7 +161,12 @@ impl T { /// Drops `path` at `at` (the next frame sees it), then runs a few frames. pub fn drop_file(&mut self, path: &Path, at: (f32, f32)) { - self.drop = Some((vec![path.to_path_buf()], Some(egui::pos2(at.0, at.1)))); + self.drop_files(vec![path.to_path_buf()], at); + } + + /// Drops `paths` together at `at`, as [`T::drop_file`] drops one. + pub fn drop_files(&mut self, paths: Vec, at: (f32, f32)) { + self.drop = Some((paths, Some(egui::pos2(at.0, at.1)))); self.frames(3); } diff --git a/docs/known-issues/entries/K113.md b/docs/known-issues/entries/K113.md index a8890443..5bf2d74d 100644 --- a/docs/known-issues/entries/K113.md +++ b/docs/known-issues/entries/K113.md @@ -4,4 +4,4 @@ follow-up: Use the drop's own position once winit's drag events carry one (`Drag order: 119 --> -A file dragged in from the file manager has no drop position on any platform: winit 0.30 reports `DroppedFile(PathBuf)` alone (the Windows drop handler ignores the OLE `POINTL`), and no cursor motion arrives during the OS drag, so egui's pointer is stale or gone when the drop lands. On Windows transit asks the OS for the cursor position at the drop's frame and routes the drop there (on hardware the pointer's next report did not come first: a `PointerGone` did, and the drop went to the arrangement). Other platforms still hold the drop until the pointer's next report and route it there; a `PointerGone` keeps it held, and after 30 frames with no position it goes to the arrangement (#368). +A file dragged in from the file manager has no drop position on any platform: winit 0.30 reports `DroppedFile(PathBuf)` alone (the Windows drop handler ignores the OLE `POINTL`), and no cursor motion arrives during the OS drag, so egui's pointer is stale or gone when the drop lands. On Windows transit asks the OS for the cursor position at the drop's frame and routes the drop there (on hardware the pointer's next report did not come first: a `PointerGone` did, and the drop went to the arrangement). Other platforms still hold the drop until the pointer's next report and route it there; a `PointerGone` keeps it held, and after 30 frames with no position it goes to the arrangement (#368). That position also picks where an arrangement drop lands (the audio track under the pointer, at its time), so a pointer moved before its next report imports the file onto the track it reached. diff --git a/docs/user-guide.md b/docs/user-guide.md index 8891dd10..5573addd 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -898,9 +898,10 @@ view has content it takes no drag. On an Instrument key map with zones, a file d no zone plays shows, dashed, the keys it will cover, and letting go makes a zone there (see below). A file or plug-in dropped elsewhere on a device window is ignored; the window takes the drop, so nothing behind it is reached. Anywhere else, a browser drag lands on the track lane, header, mixer strip or device chain where you let go. A file from the file manager lands the same -way on an audio track's lane or header, or below the tracks on a new track; anywhere else it is -imported into the arrangement at the cursor (a `.transit` or `.dawproject` file opens as the -session, a MIDI file imports as MIDI). On Windows a file manager drop lands where the pointer is when you let go; on other +way on an audio track's lane, header, mixer strip or device chain, or below the tracks on a new +track, and several files follow each other on that track; anywhere else, or when the drop also +opens a session, it is imported into the arrangement at the cursor (a `.transit` or `.dawproject` +file opens as the session, a MIDI file imports as MIDI). On Windows a file manager drop lands where the pointer is when you let go; on other platforms it lands as soon as the pointer moves after you let go (see the known issues). A stereo or wider file that lands on a mono audio track with as many mono tracks below it (in the Edit window's order, none frozen and none holding a clip where the file goes) splits across them in From 60f21b9968c0c21e52a223d4dde3e1a242eb8ca1 Mon Sep 17 00:00:00 2001 From: BlueJayLouche Date: Sat, 21 Nov 2026 22:46:21 +1100 Subject: [PATCH 06/15] ui, engine: fourth refutation review (ADR 0009): a drop holding a session opens it alone and the status line says what was left out, so no file lands by a pointer or cursor that names the closing session's tracks; files dropped at the cursor follow each other there too; the split's file writing, opening and removal move to io/split_files.rs behind the checked file access (the file_access gate) --- crates/engine/src/cmd/clip_split.rs | 74 ++--------------- crates/engine/src/io.rs | 1 + crates/engine/src/io/split_files.rs | 80 +++++++++++++++++++ crates/ui-studio/src/drops.rs | 29 +++++-- .../src/sampler_panel/drop_routing_tests.rs | 34 +++++--- docs/user-guide.md | 7 +- 6 files changed, 136 insertions(+), 89 deletions(-) create mode 100644 crates/engine/src/io/split_files.rs diff --git a/crates/engine/src/cmd/clip_split.rs b/crates/engine/src/cmd/clip_split.rs index 72109652..8dd9e871 100644 --- a/crates/engine/src/cmd/clip_split.rs +++ b/crates/engine/src/cmd/clip_split.rs @@ -9,10 +9,9 @@ use super::*; use crate::cmd; use serde_json::json; use std::collections::BTreeMap; -use std::io::Write; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use std::sync::Arc; -use transit_audio_io::{AudioBuffer, BitDepth, EncodeOptions, FileEncoder, FileFormat}; +use transit_audio_io::{AudioBuffer, FileFormat}; use transit_model::disk::DiskSource; use transit_model::{ChannelFormat, ClipContent, ClipId, SourceAudio, SourceId, TrackId, TrackKind}; @@ -76,10 +75,7 @@ fn split_to_mono(e: &mut Engine, p: &Value) -> Result { let split = match prepare(s, &by_track, &mut written) { Ok(split) => split, Err(err) => { - for p in &written { - let _ = std::fs::remove_file(p); - let _ = std::fs::remove_file(transit_model::disk::sidecar_path(p)); - } + crate::io::split_files::remove(&written); return Err(err); } }; @@ -173,7 +169,7 @@ fn prepare( let names: Vec = (0..n).map(|ch| format!("{}.{}", meta.name, crate::io::split_label(n, ch))).collect(); let channels = match &audio.disk { Some(disk) => { - write_channels(disk, &names, written)?; + crate::io::split_files::write(disk, &names, written)?; names.into_iter().map(|name| (name, None)).collect() } None => names.into_iter().enumerate().map(|(ch, name)| (name, Some(mono_audio(audio, ch)))).collect(), @@ -190,9 +186,7 @@ fn prepare( (Some(audio), _) => Ok((name, Mono::Memory(audio))), (None, Some(disk)) => { let p = files.next().ok_or_else(|| EngineError::Io(format!("{name}: its file was not written")))?; - let len = std::fs::metadata(p).map_err(|err| EngineError::Io(format!("{}: {err}", p.display())))?.len(); - let audio = crate::io::disk::open_disk_audio(p, len, disk.rate()).map_err(EngineError::Io)?; - Ok((name, Mono::Disk(p.clone(), audio))) + Ok((name, Mono::Disk(p.clone(), crate::io::split_files::open(p, disk.rate())?))) } (None, None) => Err(EngineError::Io(format!("{name}: no audio"))), }) @@ -201,61 +195,3 @@ fn prepare( }) .collect() } - -/// One mono float WAV per channel of `disk`'s file, beside it, named `names` (`.wav`, or -/// `-2.wav` and on while that is taken), in one pass over the file. Each path is pushed to -/// `written` as soon as it is created. -fn write_channels(disk: &DiskSource, names: &[String], written: &mut Vec) -> Result<()> { - let io = |p: &Path, err: &dyn std::fmt::Display| EngineError::Io(format!("{}: {err}", p.display())); - let dir = disk.path().parent().map(Path::to_path_buf).unwrap_or_default(); - let opts = EncodeOptions { format: FileFormat::Wav, bit_depth: BitDepth::Float32, dither: false, bwf: None, bitrate_kbps: None, title: None }; - let mut encoders = Vec::with_capacity(names.len()); - for name in names { - let stem = crate::io::sanitize_name(name); - let mut found = None; - for i in 1..1000 { - let p = dir.join(if i == 1 { format!("{stem}.wav") } else { format!("{stem}-{i}.wav") }); - crate::file_access::check_write(&p).map_err(EngineError::Io)?; - match std::fs::OpenOptions::new().write(true).create_new(true).open(&p) { - Ok(f) => { - found = Some((p, f)); - break; - } - Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {} - Err(err) => return Err(io(&p, &err)), - } - } - let (path, file) = found.ok_or_else(|| EngineError::Io(format!("{}: no file name free for {stem}.wav", dir.display())))?; - written.push(path.clone()); - let enc = FileEncoder::new(std::io::BufWriter::new(file), &opts, 1, disk.rate(), None).map_err(|err| io(&path, &err))?; - enc.check_room(disk.frames()).map_err(|err| io(&path, &err))?; - encoders.push((path, enc)); - } - const BLOCK: usize = 64 * 1024; - let frames = usize::try_from(disk.frames()).unwrap_or(usize::MAX); - let mut block = vec![vec![0.0f32; BLOCK]; encoders.len()]; - let unread = || EngineError::Io(format!("{}: the file could not be read", disk.path().display())); - disk.with_sync(|read| { - let mut at = 0; - while at < frames { - let len = BLOCK.min(frames - at); - // Frame by frame across the channels, so the reader passes over the file once. - for i in 0..len { - for (ch, out) in block.iter_mut().enumerate() { - out[i] = read(ch, at + i).ok_or_else(unread)?; - } - } - for ((path, enc), out) in encoders.iter_mut().zip(&block) { - enc.write(std::slice::from_ref(out), len).map_err(|err| io(path, &err))?; - } - at += len; - } - Ok::<(), EngineError>(()) - })?; - for (path, enc) in encoders { - let mut w = enc.finish().map_err(|err| io(&path, &err))?; - w.flush().map_err(|err| io(&path, &err))?; - w.into_inner().map_err(|err| io(&path, &err.error()))?.sync_all().map_err(|err| io(&path, &err))?; - } - Ok(()) -} diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index 810b6811..67789fe7 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -879,6 +879,7 @@ pub(crate) use session::{DecodedFiles, decode_file_streamed, file_key, open_sess use session::{replace_with, write_synced}; pub(crate) mod disk; +pub(crate) mod split_files; pub use disk::{add_disk_source, copy_path}; mod disk_reads; pub use disk_reads::{DiskReads, unreadable_line}; diff --git a/crates/engine/src/io/split_files.rs b/crates/engine/src/io/split_files.rs new file mode 100644 index 00000000..22c4b096 --- /dev/null +++ b/crates/engine/src/io/split_files.rs @@ -0,0 +1,80 @@ +//! The files of Split to Mono Tracks (`clip.split_to_mono`) for a take played from its file (ADR +//! 0035): one mono float WAV per channel written beside it, opened to play from disk, and removed +//! again when the split fails. + +use super::*; +use std::io::Write; +use transit_audio_io::{BitDepth, FileEncoder}; +use transit_model::disk::DiskSource; + +/// The file `path`, written by [`write`], as a source played from disk at `rate`. +pub(crate) fn open(path: &Path, rate: u32) -> Result> { + let len = std::fs::metadata(path).map_err(|err| EngineError::Io(format!("{}: {err}", path.display())))?.len(); + disk::open_disk_audio(path, len, rate).map_err(EngineError::Io) +} + +/// Removes the files a failed split wrote, and any peaks sidecar begun beside one. +pub(crate) fn remove(paths: &[PathBuf]) { + for p in paths { + let _ = std::fs::remove_file(p); + let _ = std::fs::remove_file(transit_model::disk::sidecar_path(p)); + } +} + +/// One mono float WAV per channel of `disk`'s file, beside it, named `names` (`.wav`, or +/// `-2.wav` and on while that is taken), in one pass over the file. Each path is pushed to +/// `written` as soon as it is created. +pub(crate) fn write(disk: &DiskSource, names: &[String], written: &mut Vec) -> Result<()> { + let io = |p: &Path, err: &dyn std::fmt::Display| EngineError::Io(format!("{}: {err}", p.display())); + let dir = disk.path().parent().map(Path::to_path_buf).unwrap_or_default(); + let opts = EncodeOptions { format: FileFormat::Wav, bit_depth: BitDepth::Float32, dither: false, bwf: None, bitrate_kbps: None, title: None }; + let mut encoders = Vec::with_capacity(names.len()); + for name in names { + let stem = crate::io::sanitize_name(name); + let mut found = None; + for i in 1..1000 { + let p = dir.join(if i == 1 { format!("{stem}.wav") } else { format!("{stem}-{i}.wav") }); + crate::file_access::check_write(&p).map_err(EngineError::Io)?; + match std::fs::OpenOptions::new().write(true).create_new(true).open(&p) { + Ok(f) => { + found = Some((p, f)); + break; + } + Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(err) => return Err(io(&p, &err)), + } + } + let (path, file) = found.ok_or_else(|| EngineError::Io(format!("{}: no file name free for {stem}.wav", dir.display())))?; + written.push(path.clone()); + let enc = FileEncoder::new(std::io::BufWriter::new(file), &opts, 1, disk.rate(), None).map_err(|err| io(&path, &err))?; + enc.check_room(disk.frames()).map_err(|err| io(&path, &err))?; + encoders.push((path, enc)); + } + const BLOCK: usize = 64 * 1024; + let frames = usize::try_from(disk.frames()).unwrap_or(usize::MAX); + let mut block = vec![vec![0.0f32; BLOCK]; encoders.len()]; + let unread = || EngineError::Io(format!("{}: the file could not be read", disk.path().display())); + disk.with_sync(|read| { + let mut at = 0; + while at < frames { + let len = BLOCK.min(frames - at); + // Frame by frame across the channels, so the reader passes over the file once. + for i in 0..len { + for (ch, out) in block.iter_mut().enumerate() { + out[i] = read(ch, at + i).ok_or_else(unread)?; + } + } + for ((path, enc), out) in encoders.iter_mut().zip(&block) { + enc.write(std::slice::from_ref(out), len).map_err(|err| io(path, &err))?; + } + at += len; + } + Ok::<(), EngineError>(()) + })?; + for (path, enc) in encoders { + let mut w = enc.finish().map_err(|err| io(&path, &err))?; + w.flush().map_err(|err| io(&path, &err))?; + w.into_inner().map_err(|err| io(&path, &err.error()))?.sync_all().map_err(|err| io(&path, &err))?; + } + Ok(()) +} diff --git a/crates/ui-studio/src/drops.rs b/crates/ui-studio/src/drops.rs index b5359a61..eb5163c3 100644 --- a/crates/ui-studio/src/drops.rs +++ b/crates/ui-studio/src/drops.rs @@ -112,19 +112,32 @@ pub(crate) fn route(app: &mut StudioApp, ctx: &egui::Context, offer: DropOffer) r.offer = Some((key, offer)); return; } + // A drop holding a session opens it and nothing else: its other files would land in whichever + // document is open when their turn came, the closing one or the new one by a pointer or a + // cursor that still names the closing one's tracks. + if let Some(session) = offer.paths.iter().find(|p| opens_session(&p.to_string_lossy())) { + let left = offer.paths.len() - 1; + open_path(app, &session.to_string_lossy()); + if left > 0 { + let name = session.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned()); + app.status = format!( + "Opening {name}: the other {left} dropped file{} not imported; drop {} on the session once it is open", + if left == 1 { " was" } else { "s were" }, + if left == 1 { "it" } else { "them" } + ); + } + return; + } let snap = !ctx.input(|i| i.modifiers.shift); - // A drop that opens a session replaces the document the pointer was over: none of it lands - // by the pointer, so no file can reach a track of the new session by an old track's id. - let opens = offer.paths.iter().any(|p| opens_session(&p.to_string_lossy())); - let mut at = offer.pos.filter(|_| !opens).and_then(|p| arrangement_target(app, ctx, p, snap)); + let mut at = offer.pos.and_then(|p| arrangement_target(app, ctx, p, snap)); if let Some((_, time)) = at.as_mut() { *time = Some(time.unwrap_or_else(|| app.cursor())); } for p in &offer.paths { - let placed = open_path_at(app, &p.to_string_lossy(), at); - // The files of one drop follow each other on one track, as a browser drag's do. - if let (Some(at), Some((track, end))) = (at.as_mut(), placed) { - *at = (Some(track), Some(end)); + // The files of one drop follow each other on one track, as a browser drag's do: the first + // lands by the pointer (or at the cursor), each next one where the last ended. + if let Some((track, end)) = open_path_at(app, &p.to_string_lossy(), at) { + at = Some((Some(track), Some(end))); } } } diff --git a/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs b/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs index 975dcb52..40b46046 100644 --- a/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs +++ b/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs @@ -199,11 +199,11 @@ fn files_dropped_together_on_a_lane_follow_each_other_on_its_track() { assert_eq!(clips[1].1 - clips[0].1, 4_800, "Two starts where One ends: {clips:?}"); } -/// A drop that opens a session lands none of its files by the pointer: the track it was over -/// belongs to the document the session replaced, and its id may name another track (here a MIDI -/// track) in the new one. +/// A drop holding a session opens it and imports nothing else: its other files would land by a +/// pointer or a cursor that still names the closing session's tracks (here the cursor is on the +/// track with the id of the new session's MIDI track). #[test] -fn a_drop_that_opens_a_session_puts_no_audio_on_the_new_sessions_track_of_the_same_id() { +fn a_drop_that_opens_a_session_opens_it_and_imports_nothing_else() { let mut t = T::new(); let mut other = transit_engine::Engine::default(); other.execute("track.new", &serde_json::json!({"kind": "audio", "name": "Drums"})).unwrap(); @@ -214,13 +214,29 @@ fn a_drop_that_opens_a_session_puts_no_audio_on_the_new_sessions_track_of_the_sa t.app.run("track.new", serde_json::json!({"kind": "audio", "format": "mono"})).unwrap(); } t.app.run("session.save", serde_json::json!({"path": t.dir.join("A.transit").to_string_lossy()})).unwrap(); + t.app.set_cursor(96_000, Some(TrackId(synth))); t.frames(3); let lane = t.app.arrange.layout.tracks.iter().find(|r| r.id == synth).expect("A has a track of Synth's id").lane; - let kick = t.sample("Kick.wav", 2_400); - t.drop_files(vec![b, kick], mid(lane)); + let (one, two) = (t.sample("One.wav", 2_400), t.sample("Two.wav", 2_400)); + t.drop_files(vec![b, one, two], mid(lane)); let s = t.app.engine.session(); assert!(s.tracks.iter().any(|tr| tr.name == "Synth"), "B is open"); - assert!(s.track(TrackId(synth)).unwrap().clips().is_empty(), "no audio on the MIDI track"); - let kick_on_audio = s.tracks.iter().any(|tr| tr.kind == transit_model::TrackKind::Audio && tr.clips().iter().any(|c| c.name == "Kick")); - assert!(kick_on_audio, "Kick is imported, on an audio track"); + assert!(s.tracks.iter().all(|tr| tr.clips().is_empty()), "nothing else is imported"); + assert!(t.app.status.contains("2 dropped files were not imported"), "{}", t.app.status); +} + +/// Files dropped at the cursor (here on a MIDI lane, which takes no audio) follow each other on +/// the cursor's track, as they do on a lane, rather than each erasing the last. +#[test] +fn files_dropped_at_the_cursor_follow_each_other_on_its_track() { + let mut t = T::new(); + let a = t.app.run("track.new", serde_json::json!({"kind": "audio", "format": "mono"})).unwrap()["tracks"][0].as_u64().unwrap(); + let m = t.app.run("track.new", serde_json::json!({"kind": "midi"})).unwrap()["tracks"][0].as_u64().unwrap(); + t.app.set_cursor(48_000, Some(TrackId(a))); + t.frames(3); + let lane = t.app.arrange.layout.tracks.iter().find(|r| r.id == m).unwrap().lane; + let (one, two) = (t.sample("One.wav", 4_800), t.sample("Two.wav", 2_400)); + t.drop_files(vec![one, two], mid(lane)); + let clips: Vec<(String, i64)> = t.app.engine.session().track(TrackId(a)).unwrap().clips().iter().map(|c| (c.name.clone(), c.start)).collect(); + assert_eq!(clips, [("One".to_string(), 48_000), ("Two".to_string(), 52_800)]); } diff --git a/docs/user-guide.md b/docs/user-guide.md index 5573addd..b5cfd228 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -899,9 +899,10 @@ no zone plays shows, dashed, the keys it will cover, and letting go makes a zone drop, so nothing behind it is reached. Anywhere else, a browser drag lands on the track lane, header, mixer strip or device chain where you let go. A file from the file manager lands the same way on an audio track's lane, header, mixer strip or device chain, or below the tracks on a new -track, and several files follow each other on that track; anywhere else, or when the drop also -opens a session, it is imported into the arrangement at the cursor (a `.transit` or `.dawproject` -file opens as the session, a MIDI file imports as MIDI). On Windows a file manager drop lands where the pointer is when you let go; on other +track, and several files follow each other on that track; anywhere else it is imported into the +arrangement at the cursor (a MIDI file imports as MIDI). A `.transit` or `.dawproject` file opens +as the session; dropped with other files, it opens alone and the status line names what was left +out. On Windows a file manager drop lands where the pointer is when you let go; on other platforms it lands as soon as the pointer moves after you let go (see the known issues). A stereo or wider file that lands on a mono audio track with as many mono tracks below it (in the Edit window's order, none frozen and none holding a clip where the file goes) splits across them in From 87d52c311d310293a216558702a648f35cfc7225 Mon Sep 17 00:00:00 2001 From: BlueJayLouche Date: Sat, 21 Nov 2026 23:04:17 +1100 Subject: [PATCH 07/15] ui: fifth refutation review of the drop routing (ADR 0009): files dropped at a cursor before bar 1 chain from 0, where the engine puts the first, instead of each erasing the last; a session that fails to open keeps its own reason on the status line --- crates/ui-studio/src/drops.rs | 11 +++++--- .../src/sampler_panel/drop_routing_tests.rs | 25 ++++++++++++++++++- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/crates/ui-studio/src/drops.rs b/crates/ui-studio/src/drops.rs index eb5163c3..4d55b28e 100644 --- a/crates/ui-studio/src/drops.rs +++ b/crates/ui-studio/src/drops.rs @@ -117,15 +117,17 @@ pub(crate) fn route(app: &mut StudioApp, ctx: &egui::Context, offer: DropOffer) // cursor that still names the closing one's tracks. if let Some(session) = offer.paths.iter().find(|p| opens_session(&p.to_string_lossy())) { let left = offer.paths.len() - 1; - open_path(app, &session.to_string_lossy()); if left > 0 { + // Said first, so a session that fails to open replaces it with its own reason. let name = session.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned()); app.status = format!( - "Opening {name}: the other {left} dropped file{} not imported; drop {} on the session once it is open", - if left == 1 { " was" } else { "s were" }, + "{left} file{} dropped with {name} {} not imported; drop {} on the session once it is open", + if left == 1 { "" } else { "s" }, + if left == 1 { "was" } else { "were" }, if left == 1 { "it" } else { "them" } ); } + open_path(app, &session.to_string_lossy()); return; } let snap = !ctx.input(|i| i.modifiers.shift); @@ -198,6 +200,9 @@ fn open_path_at(app: &mut StudioApp, p: &str, at: Option<(Option, Optio Some((track, time)) => (track, time.unwrap_or_else(|| app.cursor())), None => (app.cursor_track().filter(audio), app.cursor()), }; + // Where the engine puts it (a cursor before bar 1 imports at 0), so the next file of the + // drop starts where this one really ends. + let time = time.max(0); let mut params = serde_json::json!({"path": p, "at": time}); if let Some(t) = track { params["track"] = serde_json::json!(t.0); diff --git a/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs b/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs index 40b46046..ab643517 100644 --- a/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs +++ b/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs @@ -222,7 +222,7 @@ fn a_drop_that_opens_a_session_opens_it_and_imports_nothing_else() { let s = t.app.engine.session(); assert!(s.tracks.iter().any(|tr| tr.name == "Synth"), "B is open"); assert!(s.tracks.iter().all(|tr| tr.clips().is_empty()), "nothing else is imported"); - assert!(t.app.status.contains("2 dropped files were not imported"), "{}", t.app.status); + assert!(t.app.status.contains("2 files dropped with B.transit were not imported"), "{}", t.app.status); } /// Files dropped at the cursor (here on a MIDI lane, which takes no audio) follow each other on @@ -240,3 +240,26 @@ fn files_dropped_at_the_cursor_follow_each_other_on_its_track() { let clips: Vec<(String, i64)> = t.app.engine.session().track(TrackId(a)).unwrap().clips().iter().map(|c| (c.name.clone(), c.start)).collect(); assert_eq!(clips, [("One".to_string(), 48_000), ("Two".to_string(), 52_800)]); } + +/// With the cursor before bar 1 (a count-in session's pre-count zone), files dropped at the cursor +/// still follow each other: the first lands at 0, where the engine puts it, and the next after it. +#[test] +fn files_dropped_at_a_cursor_before_bar_one_follow_each_other_from_zero() { + let mut t = T::new(); + let a = t.app.run("track.new", serde_json::json!({"kind": "audio", "format": "mono"})).unwrap()["tracks"][0].as_u64().unwrap(); + let m = t.app.run("track.new", serde_json::json!({"kind": "midi"})).unwrap()["tracks"][0].as_u64().unwrap(); + // A pickup clip at -96 000 opens the pre-count zone (ADR 0052), so the cursor can sit before 0. + let s = t.app.engine.session_mut(); + let id = s.new_clip_id(); + let pickup = transit_model::Clip::midi(id, "Pickup", -96_000, 48_000, Default::default()); + s.track_mut(TrackId(m)).unwrap().playlist_mut().unwrap().clips.push(pickup); + t.frames(3); + t.app.ui.cursor = -48_000; + t.app.ui.cursor_track = Some(TrackId(a)); + assert_eq!(t.app.cursor(), -48_000, "the cursor is before bar 1"); + let lane = t.app.arrange.layout.tracks.iter().find(|r| r.id == m).unwrap().lane; + let (one, two) = (t.sample("One.wav", 4_800), t.sample("Two.wav", 4_800)); + t.drop_files(vec![one, two], mid(lane)); + let clips: Vec<(String, i64)> = t.app.engine.session().track(TrackId(a)).unwrap().clips().iter().map(|c| (c.name.clone(), c.start)).collect(); + assert_eq!(clips, [("One".to_string(), 0), ("Two".to_string(), 4_800)]); +} From 5b94b37c037be96f96d65693a90404a3d226ea9d Mon Sep 17 00:00:00 2001 From: BlueJayLouche Date: Sun, 22 Nov 2026 05:55:44 +1100 Subject: [PATCH 08/15] ui: sixth refutation review of the drop routing (ADR 0009): a test that a dropped session failing to open keeps its own reason on the status line --- .../src/sampler_panel/drop_routing_tests.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs b/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs index ab643517..cf8d0cb2 100644 --- a/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs +++ b/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs @@ -263,3 +263,17 @@ fn files_dropped_at_a_cursor_before_bar_one_follow_each_other_from_zero() { let clips: Vec<(String, i64)> = t.app.engine.session().track(TrackId(a)).unwrap().clips().iter().map(|c| (c.name.clone(), c.start)).collect(); assert_eq!(clips, [("One".to_string(), 0), ("Two".to_string(), 4_800)]); } + +/// A dropped session that fails to open keeps its own reason on the status line: the line about +/// the files left out comes first, so the open's refusal replaces it. +#[test] +fn a_dropped_session_that_fails_to_open_shows_why() { + let mut t = T::new(); + let bad = t.dir.join("B.transit"); + std::fs::write(&bad, b"not a session").unwrap(); + let (one, two) = (t.sample("One.wav", 2_400), t.sample("Two.wav", 2_400)); + let tl = t.app.arrange.layout.timeline; + t.drop_files(vec![bad, one, two], (tl[0] + 40.0, tl[1] + 12.0)); + assert!(t.app.status.starts_with("Could not open"), "{}", t.app.status); + assert!(t.app.engine.session().tracks.iter().all(|tr| tr.clips().is_empty()), "nothing is imported"); +} From fa4968ba111ffa52f3a6eae4b7cefbd7454946a1 Mon Sep 17 00:00:00 2001 From: BlueJayLouche Date: Mon, 23 Nov 2026 08:47:56 +1100 Subject: [PATCH 09/15] engine, ui: maintainer review of #767: import keeps a file's channels (the automatic split on import is removed; Split to Mono Tracks is the way to split); a file-manager drop lands by the browser drag's rules (import_files: the track under the pointer at its time, or below the tracks, else at the cursor; a track that takes no audio or a file that is not audio is refused with the reason on the status line; queued like a browser drag); a dropped session asks to save unsaved changes as File > Open does (tested); the known-issues index regenerated --- crates/engine/src/cmd/clip_split.rs | 21 +++-- crates/engine/src/cmd/file.rs | 2 +- crates/engine/src/io.rs | 63 +------------ .../{import_split.rs => split_to_mono.rs} | 89 +++--------------- crates/ui-studio/src/drops.rs | 91 +++++++------------ .../src/sampler_panel/drop_routing_tests.rs | 84 +++++++++++++---- .../ui-studio/src/sampler_panel/test_rig.rs | 14 ++- docs/known-issues/README.md | 2 +- docs/known-issues/entries/K113.md | 2 +- docs/user-guide.md | 29 +++--- 10 files changed, 163 insertions(+), 234 deletions(-) rename crates/engine/tests/{import_split.rs => split_to_mono.rs} (69%) diff --git a/crates/engine/src/cmd/clip_split.rs b/crates/engine/src/cmd/clip_split.rs index 8dd9e871..e2064031 100644 --- a/crates/engine/src/cmd/clip_split.rs +++ b/crates/engine/src/cmd/clip_split.rs @@ -29,11 +29,20 @@ pub fn specs() -> Vec { )] } -/// The most channels a clip splits into: one track each, so a hostile file's channel count must -/// not become tens of thousands of tracks. -// ponytail: a fixed cap; a MADI-sized recording (64) fits, a wider one is refused. +/// The most channels a clip splits into, one track each, so a hostile file's channel count never +/// becomes tens of thousands of tracks: a MADI-sized recording (64) fits, a wider one is refused. const MAX_CHANNELS: usize = 64; +/// Channel `ch` of `n` in a split's names: `L` and `R` for stereo, else its number from 1 (a +/// file's channels carry no layout here; an eight-track field recording is not 7.1). +fn split_label(n: usize, ch: usize) -> String { + match (n, ch) { + (2, 0) => "L".into(), + (2, 1) => "R".into(), + _ => (ch + 1).to_string(), + } +} + /// A channel's audio, ready to become a source. enum Mono { Memory(SourceAudio), @@ -101,7 +110,7 @@ fn split_to_mono(e: &mut Engine, p: &Value) -> Result { let n = clips.iter().map(|c| c.2).max().unwrap_or(0); let mut lanes = Vec::with_capacity(n); for ch in 0..n { - let nt = s.add_track(TrackKind::Audio, ChannelFormat::Mono, Some(&format!("{} {}", tr.name, crate::io::split_label(n, ch)))); + let nt = s.add_track(TrackKind::Audio, ChannelFormat::Mono, Some(&format!("{} {}", tr.name, split_label(n, ch)))); // Taken out before `t` is found: a new track goes in before a Master, which may sit above `t`. if let Some(from) = s.track_index(nt) { let moved = s.tracks.remove(from); @@ -124,7 +133,7 @@ fn split_to_mono(e: &mut Engine, p: &Value) -> Result { let Some(&mono) = sources.get(&(src, ch)) else { continue }; let mut c = orig.clone(); c.id = s.new_clip_id(); - c.name = format!("{}.{}", orig.name, crate::io::split_label(channels, ch)); + c.name = format!("{}.{}", orig.name, split_label(channels, ch)); c.content = ClipContent::Audio { source: mono, offset }; c.group = None; new_clips.push(c.id); @@ -166,7 +175,7 @@ fn prepare( continue; } let (Some(meta), Some(audio)) = (s.source(src), s.pool.get(src)) else { continue }; - let names: Vec = (0..n).map(|ch| format!("{}.{}", meta.name, crate::io::split_label(n, ch))).collect(); + let names: Vec = (0..n).map(|ch| format!("{}.{}", meta.name, split_label(n, ch))).collect(); let channels = match &audio.disk { Some(disk) => { crate::io::split_files::write(disk, &names, written)?; diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 7960574a..7341ae74 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -56,7 +56,7 @@ pub fn specs() -> Vec { "Audio...", ["File", "Import"], Some("Cmd+Shift+I"), - "{path | paths: [..], track?: target track (a mono one with mono tracks below takes one channel of a wider file each), at?: position, name?: clip, source and new track name, new_tracks?: true (default; false uses `track` or the selected audio track)}", + "{path | paths: [..], track?: target track, at?: position, name?: clip, source and new track name, new_tracks?: true (default; false uses `track` or the selected audio track)}", always, import_audio ), diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index 67789fe7..bf0a6727 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -300,19 +300,13 @@ pub fn prepare_audio_bytes( /// Place prepared audio: a new source, and a clip at `at` on `target` (or on a new track of /// matching width). `name` replaces the file name as the source, clip and new track name. Audio -/// prepared at another rate than the session's is resampled here. A file of several channels on a -/// mono track with as many mono tracks below it splits across them, one channel each. +/// prepared at another rate than the session's is resampled here. pub fn place_prepared(e: &mut Engine, prepared: PreparedAudio, target: Option, at: Samples, name: Option<&str>) -> Result { let PreparedAudio { name: file, path, audio, format, file_rate, time_reference } = prepared; let label = name.map(str::trim).filter(|n| !n.is_empty()).unwrap_or(&file).to_string(); let channels = audio.buffer.num_channels(); let s = e.session_mut(); let session_rate = s.sample_rate.hz(); - let span = Range::new(at, at.saturating_add(i64::try_from(audio.frames()).unwrap_or(i64::MAX))); - if let Some(tracks) = target.and_then(|t| split_tracks(s, t, channels, span)).filter(|_| !audio.is_disk()) { - let stamp = time_reference.map(|t| stamp_at_rate(t, file_rate, session_rate)); - return Ok(place_split(s, audio, &label, &tracks, at, stamp)); - } let src = if audio.buffer.sample_rate == session_rate { add_source_audio(s, &label, audio, path.as_deref(), format) } else { @@ -333,61 +327,6 @@ pub fn place_prepared(e: &mut Engine, prepared: PreparedAudio, target: Option Option> { - let mono = |t: &&transit_model::Track| t.kind == TrackKind::Audio && t.format == ChannelFormat::Mono && t.freeze.is_none(); - let free = |t: &&transit_model::Track| mono(t) && !t.clips().iter().any(|c| c.start < span.end && c.end() > span.start); - let i = s.track_index(target).filter(|_| channels > 1)?; - let first = s.tracks.get(i).filter(mono)?; - let below = s.tracks.iter().skip(i + 1).filter(|t| crate::edit::shown(s, t)).take(channels - 1).take_while(free); - let tracks: Vec = std::iter::once(first).chain(below).map(|t| t.id).collect(); - (tracks.len() == channels).then_some(tracks) -} - -/// Channel `ch` of `n` in a split's names: `L` and `R` for stereo, else its number from 1 (a -/// file's channels carry no layout here; an eight-track field recording is not 7.1). -pub(crate) fn split_label(n: usize, ch: usize) -> String { - match (n, ch) { - (2, 0) => "L".into(), - (2, 1) => "R".into(), - _ => (ch + 1).to_string(), - } -} - -/// One mono source per channel, `.L` and `.R` (`.1`, `.2`… past stereo), written to -/// `Audio Files` on save, and a clip of each at `at` on its track of `tracks`, each keeping its -/// channel's peaks. The reply is the first clip's, with every clip under `split`. -fn place_split(s: &mut Session, audio: Arc, label: &str, tracks: &[TrackId], at: Samples, stamp: Option) -> Value { - let stem = Path::new(label).file_stem().and_then(|x| x.to_str()).unwrap_or(label).to_string(); - let (buf, mut peaks) = Arc::try_unwrap(audio) - .map_or_else(|a| (a.buffer.clone(), a.peaks.clone()), |mut a| (std::mem::take(&mut a.buffer), std::mem::take(&mut a.peaks))); - let rate = buf.sample_rate; - let mut placed = Vec::new(); - for (ch, (samples, &track)) in buf.channels.into_iter().zip(tracks).enumerate() { - // The source name is the given name's stem, so the extension keeps the channel label. - let name = format!("{stem}.{}.wav", split_label(tracks.len(), ch)); - let mono = AudioBuffer { sample_rate: rate, channels: vec![samples] }; - let src = match peaks.get_mut(ch).map(std::mem::take).filter(|_| rate == s.sample_rate.hz()) { - Some(p) => add_source_audio(s, &name, Arc::new(SourceAudio { buffer: mono, peaks: vec![p], disk: None }), None, FileFormat::Wav), - None => add_source(s, &name, mono, None, FileFormat::Wav), - }; - if let (Some(stamp), Some(sx)) = (stamp, s.sources.last_mut()) { - sx.time_reference = stamp; - } - let frames = s.source(src).map_or(0, |x| i64::try_from(x.frames).unwrap_or(0)); - let clip_name = s.source(src).map(|x| x.name.clone()).unwrap_or_default(); - let cid = s.new_clip_id(); - crate::edit::place_clip(s, track, Clip::audio(cid, clip_name, src, 0, at, frames)); - placed.push(json!({"track": track, "clip": cid, "source": src, "frames": frames, "channels": 1})); - } - let mut reply = placed.first().cloned().unwrap_or_else(|| json!({})); - reply["split"] = json!(placed); - reply -} - /// Decode and place an audio file. With no target track, a new track of matching width is made. /// The synchronous import: [`prepare_audio_bytes`], then [`place_prepared`]. pub fn import_audio_bytes(e: &mut Engine, name: &str, bytes: &[u8], path: Option<&str>, target: Option, at: Samples) -> Result { diff --git a/crates/engine/tests/import_split.rs b/crates/engine/tests/split_to_mono.rs similarity index 69% rename from crates/engine/tests/import_split.rs rename to crates/engine/tests/split_to_mono.rs index c82c352c..b2714a2c 100644 --- a/crates/engine/tests/import_split.rs +++ b/crates/engine/tests/split_to_mono.rs @@ -1,5 +1,5 @@ -//! A stereo file imported onto a mono track with a mono track below it splits across the two: the -//! left channel on the first, the right on the second, each its own mono source, in one undo step. +//! Split to Mono Tracks (`clip.split_to_mono`): each channel of a stereo or wider clip on a new mono +//! track below its track, in one undo step. Import itself keeps a file's channels as they are. use serde_json::json; use transit_engine::Engine; @@ -43,84 +43,16 @@ fn clips(e: &Engine, t: u64) -> Vec<(i64, i64, String, usize, f32)> { } #[test] -fn a_stereo_file_on_a_mono_track_with_a_mono_track_below_splits_and_saves_two_mono_files() { - let d = transit_test_support::TestDir::new("import-split"); - std::fs::create_dir_all(&*d).unwrap(); - let wav = d.join("LAV-2.wav"); - std::fs::write(&wav, stereo_wav(4_800, 16_384, -8_192)).unwrap(); - let mut e = Engine::default(); - let (a, b) = (track(&mut e, "mono"), track(&mut e, "mono")); - let undo = e.undo_history().len(); - let r = e.execute("file.import_audio", &json!({"path": wav.to_string_lossy(), "track": a, "at": 960})).unwrap(); - assert_eq!(r["imported"][0]["split"].as_array().map(Vec::len), Some(2), "{r}"); - assert_eq!(clips(&e, a), vec![(960, 4_800, "LAV-2.L".to_string(), 1, 0.5)], "the left channel on the first track"); - assert_eq!(clips(&e, b), vec![(960, 4_800, "LAV-2.R".to_string(), 1, -0.25)], "the right channel on the track below"); - assert_eq!(e.undo_history().len(), undo + 1, "one undo step"); - - let file = d.join("split.transit"); - e.execute("session.save", &json!({"path": file.to_string_lossy()})).unwrap(); - let mut f = Engine::default(); - f.execute("session.open", &json!({"path": file.to_string_lossy()})).unwrap(); - let paths: Vec<&str> = f.session().sources.iter().map(|s| s.path.as_str()).collect(); - assert_eq!(paths, ["Audio Files/LAV-2.L.wav", "Audio Files/LAV-2.R.wav"]); - assert_eq!((clips(&f, a), clips(&f, b)), (clips(&e, a), clips(&e, b)), "the split reopens from its two mono files"); - - e.undo(); - assert!(clips(&e, a).is_empty() && clips(&e, b).is_empty() && e.session().sources.is_empty(), "one undo takes it back"); -} - -#[test] -fn without_a_mono_track_below_the_stereo_file_lands_whole() { - let d = transit_test_support::TestDir::new("import-split-whole"); +fn import_keeps_a_stereo_file_whole_even_on_a_mono_track_with_a_free_mono_track_below() { + let d = transit_test_support::TestDir::new("import-stays-whole"); std::fs::create_dir_all(&*d).unwrap(); let wav = d.join("LAV-2.wav"); std::fs::write(&wav, stereo_wav(480, 16_384, -8_192)).unwrap(); let mut e = Engine::default(); - let (a, b) = (track(&mut e, "mono"), track(&mut e, "stereo")); + let (a, b) = (track(&mut e, "mono"), track(&mut e, "mono")); e.execute("file.import_audio", &json!({"path": wav.to_string_lossy(), "track": a})).unwrap(); - assert_eq!(clips(&e, a), vec![(0, 480, "LAV-2".to_string(), 2, 0.5)], "a stereo track below: one stereo clip"); + assert_eq!(clips(&e, a), vec![(0, 480, "LAV-2".to_string(), 2, 0.5)], "one stereo clip: a split is asked for, never done on import"); assert!(clips(&e, b).is_empty()); - e.execute("file.import_audio", &json!({"path": wav.to_string_lossy(), "track": b, "at": 960})).unwrap(); - assert_eq!(clips(&e, b).len(), 1, "a stereo track takes the file whole"); - assert_eq!(clips(&e, b)[0].3, 2); -} - -#[test] -fn a_hidden_track_below_is_passed_over_for_the_next_shown_mono_track() { - let d = transit_test_support::TestDir::new("import-split-hidden"); - std::fs::create_dir_all(&*d).unwrap(); - let wav = d.join("LAV-2.wav"); - std::fs::write(&wav, stereo_wav(480, 16_384, -8_192)).unwrap(); - let mut e = Engine::default(); - let (a, hidden, b) = (track(&mut e, "mono"), track(&mut e, "mono"), track(&mut e, "mono")); - e.execute("track.hide", &json!({"tracks": [hidden], "hidden": true})).unwrap(); - e.execute("file.import_audio", &json!({"path": wav.to_string_lossy(), "track": a})).unwrap(); - assert!(clips(&e, hidden).is_empty(), "nothing lands on a track the Edit window hides"); - assert_eq!(clips(&e, b), vec![(0, 480, "LAV-2.R".to_string(), 1, -0.25)]); -} - -#[test] -fn a_frozen_or_occupied_mono_track_below_is_never_edited_and_the_file_lands_whole() { - let d = transit_test_support::TestDir::new("import-split-guarded"); - std::fs::create_dir_all(&*d).unwrap(); - let wav = d.join("LAV-2.wav"); - std::fs::write(&wav, stereo_wav(480, 16_384, -8_192)).unwrap(); - let path = wav.to_string_lossy(); - let mut e = Engine::default(); - let (a, b) = (track(&mut e, "mono"), track(&mut e, "mono")); - // The last track has no track below: the file lands whole on it. - e.execute("file.import_audio", &json!({"path": path, "track": b})).unwrap(); - let below = clips(&e, b); - e.execute("file.import_audio", &json!({"path": path, "track": a})).unwrap(); - assert_eq!(clips(&e, a), vec![(0, 480, "LAV-2".to_string(), 2, 0.5)], "B holds a clip there: whole on A"); - assert_eq!(clips(&e, b), below, "B is untouched"); - e.execute("file.import_audio", &json!({"path": path, "track": a, "at": 960})).unwrap(); - assert_eq!(clips(&e, b).len(), 2, "B is free from 960: the split lands there"); - e.execute("track.freeze", &json!({"tracks": [b]})).unwrap(); - let undo = e.undo_history().len(); - e.execute("file.import_audio", &json!({"path": path, "track": a, "at": 4_800})).unwrap(); - assert_eq!(clips(&e, a).last().map(|c| (c.0, c.3)), Some((4_800, 2)), "B is frozen: whole on A"); - assert_eq!(e.undo_history().len(), undo + 1); } #[test] @@ -143,6 +75,15 @@ fn split_to_mono_tracks_puts_each_channel_of_a_stereo_clip_on_a_new_mono_track_b assert_eq!(clips(&e, r), vec![(960, 4_800, "LAV-2.R".to_string(), 1, -0.25)]); assert!(e.session().find_clip(transit_engine::model::ClipId(cid)).unwrap().1.muted, "the original is muted"); assert_eq!(e.undo_history().len(), undo + 1, "one undo step"); + + let file = d.join("split.transit"); + e.execute("session.save", &json!({"path": file.to_string_lossy()})).unwrap(); + let mut f = Engine::default(); + f.execute("session.open", &json!({"path": file.to_string_lossy()})).unwrap(); + let paths: Vec<&str> = f.session().sources.iter().map(|s| s.path.as_str()).collect(); + assert!(paths.contains(&"Audio Files/LAV-2.L.wav") && paths.contains(&"Audio Files/LAV-2.R.wav"), "{paths:?}"); + assert_eq!((clips(&f, l), clips(&f, r)), (clips(&e, l), clips(&e, r)), "the split reopens from its two mono files"); + e.undo(); assert_eq!(e.session().tracks.len(), 2, "one undo takes the tracks back"); assert!(!e.session().find_clip(transit_engine::model::ClipId(cid)).unwrap().1.muted); diff --git a/crates/ui-studio/src/drops.rs b/crates/ui-studio/src/drops.rs index 4d55b28e..9f223d75 100644 --- a/crates/ui-studio/src/drops.rs +++ b/crates/ui-studio/src/drops.rs @@ -8,14 +8,14 @@ //! frame or a later one). A `PointerGone` does not route it blind: the drop stays held, and only //! after [`GONE_GRACE_FRAMES`] frames with no position does it go to the arrangement. Then the //! editor window on top at that position (egui's own layer order) claims it, or the arrangement -//! imports it: on the audio track under the pointer or below the tracks, as a browser drag lands, -//! else at the cursor. Exactly one claimant takes a drop; a held drop never vanishes (a second drop while -//! one is held routes with it). +//! imports it by the browser drag's rules: on the track under the pointer or below the tracks, else +//! at the cursor, with the reason on the status line when it can't. Exactly one claimant takes a +//! drop; a held drop never vanishes (a second drop while one is held routes with it). use crate::StudioApp; +use crate::browser::Target; use std::path::PathBuf; use transit_model::TrackId; -use transit_time::Samples; /// Files offered to a claimant, and where they were dropped (`None`: the pointer left the window). #[derive(Debug, Clone)] @@ -130,18 +130,24 @@ pub(crate) fn route(app: &mut StudioApp, ctx: &egui::Context, offer: DropOffer) open_path(app, &session.to_string_lossy()); return; } - let snap = !ctx.input(|i| i.modifiers.shift); - let mut at = offer.pos.and_then(|p| arrangement_target(app, ctx, p, snap)); - if let Some((_, time)) = at.as_mut() { - *time = Some(time.unwrap_or_else(|| app.cursor())); + let (midi, audio): (Vec, Vec) = offer.paths.iter().cloned().partition(|p| is_midi(&p.to_string_lossy())); + for p in midi { + open_path(app, &p.to_string_lossy()); } - for p in &offer.paths { - // The files of one drop follow each other on one track, as a browser drag's do: the first - // lands by the pointer (or at the cursor), each next one where the last ended. - if let Some((track, end)) = open_path_at(app, &p.to_string_lossy(), at) { - at = Some((Some(track), Some(end))); - } + if audio.is_empty() { + return; } + // The rest lands as a browser drag's files do (`import_files`): on the track under the pointer + // (at the pointer's time on its lane) or on a new track below the tracks, one after another; + // anywhere else at the cursor. A track that takes no audio, or a file that is not audio this + // app imports, is refused with the reason on the status line. + let snap = !ctx.input(|i| i.modifiers.shift); + let cursor = app.cursor(); + let _ = match offer.pos.and_then(|p| app.drop_target(ctx, p, snap, true)).map(|(t, _)| t) { + Some(Target::Track { track, at }) => app.import_files(&audio, Some(track), at.unwrap_or(cursor)), + Some(Target::Below { at }) => app.import_files(&audio, None, at.unwrap_or(cursor)), + _ => app.import_at_cursor(&audio), + }; } /// Whether dropping `p` opens it as the session. @@ -150,17 +156,10 @@ fn opens_session(p: &str) -> bool { lower.ends_with(".transit") || lower.ends_with(".dawproject") } -/// Where a file-manager drop at `pos` lands in the arrangement, as a browser drag does: the audio -/// track whose lane (at the pointer's time), header, mixer strip or device chain is under the -/// pointer, or a new track when it is below the tracks. `None` elsewhere: the drop imports at the -/// cursor, as before. -fn arrangement_target(app: &StudioApp, ctx: &egui::Context, pos: egui::Pos2, snap: bool) -> Option<(Option, Option)> { - let audio = |t: TrackId| app.engine.session().track(t).is_some_and(|t| t.kind == transit_model::TrackKind::Audio); - match app.drop_target(ctx, pos, snap, true)?.0 { - crate::browser::Target::Track { track, at } if audio(track) => Some((Some(track), at)), - crate::browser::Target::Below { at } => Some((None, at)), - _ => None, - } +/// Whether `p` imports as MIDI. +fn is_midi(p: &str) -> bool { + let lower = p.to_ascii_lowercase(); + lower.ends_with(".mid") || lower.ends_with(".midi") || lower.ends_with(".smf") } /// Offers `path` to the editor window `key` in the next frame, as a file dropped on it at `pos` (a @@ -175,49 +174,27 @@ pub(crate) fn take(app: &mut StudioApp, key: (TrackId, usize)) -> Option Open does), a MIDI file imports, any other file imports +/// as audio at the cursor (on the cursor's track when it is an audio track, else on a new one). +/// Used for files named on the command line; a failure's reason goes to the status line. pub fn open_path(app: &mut StudioApp, p: &str) { - open_path_at(app, p, None); -} - -/// [`open_path`], with an audio file landing on `at`'s track (none: a new track) at its time (none: -/// the cursor) when `at` is given, where [`arrangement_target`] put a drop. Returns the track an -/// audio file landed on and where it ends there. -fn open_path_at(app: &mut StudioApp, p: &str, at: Option<(Option, Option)>) -> Option<(TrackId, Samples)> { - let lower = p.to_ascii_lowercase(); if opens_session(p) { app.run_or_ask("session.open", serde_json::json!({"path": p})); - return None; + return; } - let r = if lower.ends_with(".mid") || lower.ends_with(".midi") || lower.ends_with(".smf") { + let r = if is_midi(p) { app.run("file.import_midi", serde_json::json!({"path": p})) } else { - // The cursor's track only when it holds audio; else a new track. + let at = app.cursor(); + let mut params = serde_json::json!({"path": p, "at": at}); let audio = |t: &TrackId| app.engine.session().track(*t).is_some_and(|t| t.kind == transit_model::TrackKind::Audio); - let (track, time) = match at { - Some((track, time)) => (track, time.unwrap_or_else(|| app.cursor())), - None => (app.cursor_track().filter(audio), app.cursor()), - }; - // Where the engine puts it (a cursor before bar 1 imports at 0), so the next file of the - // drop starts where this one really ends. - let time = time.max(0); - let mut params = serde_json::json!({"path": p, "at": time}); - if let Some(t) = track { + if let Some(t) = app.cursor_track().filter(audio) { params["track"] = serde_json::json!(t.0); } - let r = app.run("file.import_audio", params); - if let Ok(v) = &r { - let one = &v["imported"][0]; - if let (Some(t), Some(len)) = (one["track"].as_u64(), one["frames"].as_i64()) { - return Some((TrackId(t), time.saturating_add(len))); - } - } - r + app.run("file.import_audio", params) }; if let Err(e) = r { log::warn!("{p}: {e}"); } - None } diff --git a/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs b/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs index cf8d0cb2..3eaf11cd 100644 --- a/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs +++ b/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs @@ -5,12 +5,17 @@ use super::test_rig::{T, mid}; use transit_model::TrackId; -/// A point on the arrangement's timeline that no editor window covers. +/// A point on the menu bar: no track, nor the space below the tracks, so a drop there lands at the +/// cursor. +const MENU_BAR: (f32, f32) = (300.0, 12.0); + +/// A point on the arrangement's timeline that no editor window covers, below the tracks (a drop +/// there lands on a new track; the Sampler's own instrument track takes no audio). fn arrangement_point(t: &T, tr: TrackId) -> (f32, f32) { let tl = t.app.arrange.layout.timeline; let w = t.window(tr).rect; let inside = |p: (f32, f32)| p.0 >= w[0] && p.0 <= w[2] && p.1 >= w[1] && p.1 <= w[3]; - let candidates = [(tl[0] + 40.0, tl[1] + 12.0), (tl[2] - 40.0, tl[1] + 12.0), (tl[0] + 40.0, tl[3] - 12.0), (tl[2] - 40.0, tl[3] - 12.0)]; + let candidates = [(tl[0] + 40.0, tl[3] - 12.0), (tl[2] - 40.0, tl[3] - 12.0)]; *candidates.iter().find(|p| !inside(**p) && tl[3] - tl[1] > 24.0).expect("a visible stretch of timeline outside the editor window") } @@ -110,8 +115,9 @@ fn a_drop_with_the_pointer_gone_then_a_position_on_the_arrangement_imports_a_cli let snare = t.sample("Snare.wav", 2400); let clips = t.clip_count(); t.drop_gone(&snare); - assert_eq!(t.clip_count(), clips, "held"); + assert!(t.clip_count() == clips && !t.app.imports.active(), "held"); t.point(arrangement_point(&t, tr)); + t.settle_imports(); assert_eq!(t.clip_count(), clips + 1, "one clip imported"); assert!(t.patch(tr).zones.is_empty(), "no pad bound"); } @@ -124,8 +130,10 @@ fn a_drop_held_after_the_pointer_left_goes_to_the_arrangement_after_the_grace_fr // The drop frame counts as the first held frame; the last held frame is the grace count. t.drop_gone(&snare); t.frames(crate::drops::GONE_GRACE_FRAMES as usize - 1); - assert_eq!(t.clip_count(), clips, "still held on the last grace frame"); + assert!(t.clip_count() == clips && !t.app.imports.active(), "still held on the last grace frame"); t.frames(1); + assert!(t.app.imports.active() || t.clip_count() == clips + 1, "routed on the next frame"); + t.settle_imports(); assert_eq!(t.clip_count(), clips + 1, "then imported to the arrangement: the drop never vanishes"); assert!(t.patch(tr).zones.is_empty()); } @@ -158,11 +166,12 @@ fn the_gone_rule_holds_where_the_old_rule_imported() { } } -/// A file-manager drop lands where it is let go, as a browser drag does: a stereo file on a mono -/// track's lane with a mono track below splits there, rather than going to the cursor's track (a -/// new stereo track when the cursor has none). +/// A file-manager drop lands where it is let go, as a browser drag does: on the track under the +/// pointer, at the pointer's time on its lane, rather than at the cursor (on a new track when the +/// cursor has none). A stereo file keeps its channels there: a split is asked for, never done on +/// import, even with a free mono track below. #[test] -fn a_stereo_file_dropped_on_a_mono_lane_splits_onto_that_track_and_the_one_below() { +fn a_stereo_file_dropped_on_a_mono_lane_lands_whole_on_that_track_at_the_pointer() { let mut t = T::new(); let mono = |t: &mut T| t.app.run("track.new", serde_json::json!({"kind": "audio", "format": "mono"})).unwrap()["tracks"][0].as_u64().unwrap(); let (a, b) = (mono(&mut t), mono(&mut t)); @@ -177,11 +186,17 @@ fn a_stereo_file_dropped_on_a_mono_lane_splits_onto_that_track_and_the_one_below let path = t.dir.join("Mics.wav"); std::fs::write(&path, wav).unwrap(); let lane = t.app.arrange.layout.tracks.iter().find(|r| r.id == a).unwrap().lane; - t.drop_file(&path, mid(lane)); + let at = (lane[0] + (lane[2] - lane[0]) * 0.75, (lane[1] + lane[3]) / 2.0); + let Some((crate::browser::Target::Track { at: Some(want), .. }, _)) = t.app.drop_target(&t.ctx, egui::pos2(at.0, at.1), true, true) else { + panic!("the lane is a drop target") + }; + assert!(want > 0 && t.app.cursor() == 0, "the pointer's time ({want}) is not the cursor's"); + t.drop_file(&path, at); let s = t.app.engine.session(); - let names = |id: u64| s.track(TrackId(id)).unwrap().clips().iter().map(|c| c.name.clone()).collect::>(); + let on = |id: u64| s.track(TrackId(id)).unwrap().clips().iter().map(|c| (c.name.clone(), c.start)).collect::>(); assert_eq!(s.tracks.len(), 2, "no new track"); - assert_eq!((names(a), names(b)), (vec!["Mics.L".to_string()], vec!["Mics.R".to_string()])); + assert_eq!((on(a), on(b)), (vec![("Mics".to_string(), want)], vec![]), "whole, on A, at the pointer"); + assert_eq!(s.sources.iter().map(|x| x.channels).collect::>(), [2], "one stereo source"); } /// Several files dropped on a lane follow each other on its track, as a browser drag's do: each @@ -225,22 +240,56 @@ fn a_drop_that_opens_a_session_opens_it_and_imports_nothing_else() { assert!(t.app.status.contains("2 files dropped with B.transit were not imported"), "{}", t.app.status); } -/// Files dropped at the cursor (here on a MIDI lane, which takes no audio) follow each other on -/// the cursor's track, as they do on a lane, rather than each erasing the last. +/// Files dropped where no track or the space below them is (here the menu bar) land at the cursor +/// on the cursor's track, and follow each other there, rather than each erasing the last. #[test] fn files_dropped_at_the_cursor_follow_each_other_on_its_track() { let mut t = T::new(); let a = t.app.run("track.new", serde_json::json!({"kind": "audio", "format": "mono"})).unwrap()["tracks"][0].as_u64().unwrap(); - let m = t.app.run("track.new", serde_json::json!({"kind": "midi"})).unwrap()["tracks"][0].as_u64().unwrap(); + t.app.run("track.new", serde_json::json!({"kind": "midi"})).unwrap(); t.app.set_cursor(48_000, Some(TrackId(a))); t.frames(3); - let lane = t.app.arrange.layout.tracks.iter().find(|r| r.id == m).unwrap().lane; let (one, two) = (t.sample("One.wav", 4_800), t.sample("Two.wav", 2_400)); - t.drop_files(vec![one, two], mid(lane)); + t.drop_files(vec![one, two], MENU_BAR); let clips: Vec<(String, i64)> = t.app.engine.session().track(TrackId(a)).unwrap().clips().iter().map(|c| (c.name.clone(), c.start)).collect(); assert_eq!(clips, [("One".to_string(), 48_000), ("Two".to_string(), 52_800)]); } +/// Audio dropped on a track that takes none (a MIDI track's lane) is refused with the reason on +/// the status line, as a browser drag's is, rather than landing somewhere else unannounced. +#[test] +fn audio_dropped_on_a_midi_lane_is_refused_with_the_reason() { + let mut t = T::new(); + let a = t.app.run("track.new", serde_json::json!({"kind": "audio", "format": "mono"})).unwrap()["tracks"][0].as_u64().unwrap(); + let m = t.app.run("track.new", serde_json::json!({"kind": "midi", "name": "Synth"})).unwrap()["tracks"][0].as_u64().unwrap(); + t.app.set_cursor(0, Some(TrackId(a))); + t.frames(3); + let lane = t.app.arrange.layout.tracks.iter().find(|r| r.id == m).unwrap().lane; + let one = t.sample("One.wav", 2_400); + t.drop_file(&one, mid(lane)); + assert!(t.app.status.starts_with("Synth is not an audio track"), "{}", t.app.status); + assert!(t.app.engine.session().tracks.iter().all(|tr| tr.clips().is_empty()), "nothing is imported"); +} + +/// A dropped session goes through the save question File > Open asks: with unsaved changes it +/// opens only once the question is answered, and nothing else of the drop is imported. +#[test] +fn a_dropped_session_asks_to_save_unsaved_changes_first() { + let mut t = T::new(); + let b = t.dir.join("B.transit"); + let mut other = transit_engine::Engine::default(); + other.execute("track.new", &serde_json::json!({"kind": "midi", "name": "Synth"})).unwrap(); + other.execute("session.save", &serde_json::json!({"path": b.to_string_lossy()})).unwrap(); + t.app.run("track.new", serde_json::json!({"kind": "audio", "name": "Unsaved"})).unwrap(); + t.frames(3); + assert!(t.app.unsaved_changes()); + let one = t.sample("One.wav", 2_400); + t.drop_files(vec![b, one], MENU_BAR); + assert!(matches!(t.app.dialog, Some(crate::Dialog::SaveChanges { .. })), "the save question is up"); + let s = t.app.engine.session(); + assert!(s.tracks.iter().any(|tr| tr.name == "Unsaved") && s.tracks.iter().all(|tr| tr.clips().is_empty()), "nothing opened or imported yet"); +} + /// With the cursor before bar 1 (a count-in session's pre-count zone), files dropped at the cursor /// still follow each other: the first lands at 0, where the engine puts it, and the next after it. #[test] @@ -257,9 +306,8 @@ fn files_dropped_at_a_cursor_before_bar_one_follow_each_other_from_zero() { t.app.ui.cursor = -48_000; t.app.ui.cursor_track = Some(TrackId(a)); assert_eq!(t.app.cursor(), -48_000, "the cursor is before bar 1"); - let lane = t.app.arrange.layout.tracks.iter().find(|r| r.id == m).unwrap().lane; let (one, two) = (t.sample("One.wav", 4_800), t.sample("Two.wav", 4_800)); - t.drop_files(vec![one, two], mid(lane)); + t.drop_files(vec![one, two], MENU_BAR); let clips: Vec<(String, i64)> = t.app.engine.session().track(TrackId(a)).unwrap().clips().iter().map(|c| (c.name.clone(), c.start)).collect(); assert_eq!(clips, [("One".to_string(), 0), ("Two".to_string(), 4_800)]); } diff --git a/crates/ui-studio/src/sampler_panel/test_rig.rs b/crates/ui-studio/src/sampler_panel/test_rig.rs index 6a91670d..2c0f6f2b 100644 --- a/crates/ui-studio/src/sampler_panel/test_rig.rs +++ b/crates/ui-studio/src/sampler_panel/test_rig.rs @@ -164,10 +164,22 @@ impl T { self.drop_files(vec![path.to_path_buf()], at); } - /// Drops `paths` together at `at`, as [`T::drop_file`] drops one. + /// Drops `paths` together at `at`, as [`T::drop_file`] drops one, then lets the arrangement's + /// queued imports land. pub fn drop_files(&mut self, paths: Vec, at: (f32, f32)) { self.drop = Some((paths, Some(egui::pos2(at.0, at.1)))); self.frames(3); + self.settle_imports(); + } + + /// Runs frames until the arrangement's queued imports are committed (or 10 s). + pub fn settle_imports(&mut self) { + let t0 = std::time::Instant::now(); + while self.app.imports.active() && t0.elapsed().as_secs() < 10 { + self.frames(6); + std::thread::sleep(std::time::Duration::from_millis(2)); + } + assert!(!self.app.imports.active(), "imports never finished: {}", self.app.status); } /// Drops `path` with no pointer motion in the drop's frame (egui's pointer stays where it last diff --git a/docs/known-issues/README.md b/docs/known-issues/README.md index b03e8fa5..dc1e922c 100644 --- a/docs/known-issues/README.md +++ b/docs/known-issues/README.md @@ -101,7 +101,7 @@ existed keep their K numbers and their historical order. | K110 | The Sampler's core path (#269, C2) holds every zone's audio in memory: a sample longer than 30 s or 32 MiB of decoded audio, or one over the session's streaming threshold, is refused for a zone, and a patch holds at most 128 MiB of distinct audio. Its zone controls (`zone001_level`, ...) are not automatable yet. | Open, by design until #271 | Long samples stream from disk in #271 (ADR 0041); slot automation needs the lanes to learn the 28,928 slot ids. | | K111 | On Windows a device that only the old cpal WASAPI path could open no longer opens: since ADR 0046 Windows opens audio through native WASAPI or native ASIO only, and a device that does not open stays closed with the reason. None is known: cpal's Windows host was WASAPI alone, and the slice 2 test found the native backend lists the same endpoints. | Open, none observed | On a report: paste the "did not open" status and the report from Copy diagnostics, and reopen ADR 0046 (its Reopen when). A v0.6.x release still has the cpal path for comparison. | | K112 | Opus export is mono and stereo only (#238): a surround main mix, bus or output path exported as Opus is refused with "transit writes mono and stereo Opus only; fold the export down to stereo, or export WAV or FLAC". Surround Opus needs channel mapping family 1 (Vorbis channel order) and libopus's multistream encoder; the import side reads mono and stereo Opus files and refuses other mapping families the same way. | Open, by design for #238 | Fold down to stereo (`fold_down: "stereo"` on `file.bounce_mix` and `file.bounce_stems`) or export WAV/FLAC. Family 1 for 3 to 8 channels is Rust only: the multistream and projection encoders are already compiled in `crates/opus`, so the follow-up is the OpusHead mapping table, the SMPTE-to-Vorbis reorder and a multistream handle in `ffi.rs` (ADR 0048 decision 3). | -| K113 | A file dragged in from the file manager has no drop position on any platform: winit 0.30 reports `DroppedFile(PathBuf)` alone (the Windows drop handler ignores the OLE `POINTL`), and no cursor motion arrives during the OS drag, so egui's pointer is stale or gone when the drop lands. On Windows transit asks the OS for the cursor position at the drop's frame and routes the drop there (on hardware the pointer's next report did not come first: a `PointerGone` did, and the drop went to the arrangement). Other platforms still hold the drop until the pointer's next report and route it there; a `PointerGone` keeps it held, and after 30 frames with no position it goes to the arrangement (#368). | Open, dependency | Use the drop's own position once winit's drag events carry one (`DragDropped { position }` in winit's next release) and egui-winit forwards it. | +| K113 | A file dragged in from the file manager has no drop position on any platform: winit 0.30 reports `DroppedFile(PathBuf)` alone (the Windows drop handler ignores the OLE `POINTL`), and no cursor motion arrives during the OS drag, so egui's pointer is stale or gone when the drop lands. On Windows transit asks the OS for the cursor position at the drop's frame and routes the drop there (on hardware the pointer's next report did not come first: a `PointerGone` did, and the drop went to the arrangement). Other platforms still hold the drop until the pointer's next report and route it there; a `PointerGone` keeps it held, and after 30 frames with no position it goes to the arrangement (#368). That position also picks where an arrangement drop lands (the track under the pointer, at its time, as a browser drag), so a pointer moved before its next report imports the file onto the track it reached, or is refused there when that track takes no audio. | Open, dependency | Use the drop's own position once winit's drag events carry one (`DragDropped { position }` in winit's next release) and egui-winit forwards it. | | K114 | Upgrading to v0.7.0 rescans every plug-in once: the plug-in scan cache now lives only in transit's own settings folder, and the cache in the inherited app's `SoundCraft` folder under the user's config root (`%APPDATA%\SoundCraft`, `~/Library/Application Support/SoundCraft`, `~/.config/soundcraft`) is no longer read or written. | Open, by design (alpha) | None in code. That folder can be deleted by hand once no other program uses it. | | K115 | Clip group files tagged `soundcraft.clipgroup` and track presets tagged `soundcraft-track-preset` (written before v0.7.0) read in v0.7.x only. v0.7.x reads them, tells the caller once per read (the status line and the command result's `note`: ": saved before transit 0.7.0; ... to keep it opening in 0.8.0 and later"), and writes `transit.clipgroup` (`.tclips`) and `transit-track-preset` (`.tpreset`); from the **v0.8.0 tag** they are refused with "This file was saved by a version before transit 0.7.0. Open and save it in transit 0.7.0 first: https://github.com/transit-audio/transit/releases/tag/v0.7.0" ([ADR 0049](../adr/0049-inherited-file-identifiers-retire.md)). Files written by v0.7.0 do not open in v0.6.x. On Linux the session MIME type is now `application/x-transit-session`, so a hand-set per-user default app for `.transit` files is set once more. | Open, by design (alpha); the old tags are refused from the v0.8.0 tag | Convert in any 0.7 release: import each clip group and export the clips again (`file.export_clip_groups`); load each preset and save it again (`track.save_preset`). The v0.8.0 release moves the old tags from the readers' accept checks to the refusal; a version-gated test in `transit-engine` fails a 0.8 version bump that skips it. K114 comes from #374; renumber at landing if the order changes. | | K116 | macOS: a CLAP editor opens in the same `NSWindow` the VST3 host uses, and that window has no header strip (presets, Save, Bypass, the menu and MIDI Learn: use the device card and the mixer), is not user-resizable, and follows the plug-in's own resize requests only (as on Linux, K94). | Open, macOS CLAP editors have no header strip | A macOS header strip needs AppKit drawing in `transit-rt`. `crates/clap-host/tests/editor_main_thread.rs` expects the embedded editor on macOS. | diff --git a/docs/known-issues/entries/K113.md b/docs/known-issues/entries/K113.md index 5bf2d74d..d2d02a2f 100644 --- a/docs/known-issues/entries/K113.md +++ b/docs/known-issues/entries/K113.md @@ -4,4 +4,4 @@ follow-up: Use the drop's own position once winit's drag events carry one (`Drag order: 119 --> -A file dragged in from the file manager has no drop position on any platform: winit 0.30 reports `DroppedFile(PathBuf)` alone (the Windows drop handler ignores the OLE `POINTL`), and no cursor motion arrives during the OS drag, so egui's pointer is stale or gone when the drop lands. On Windows transit asks the OS for the cursor position at the drop's frame and routes the drop there (on hardware the pointer's next report did not come first: a `PointerGone` did, and the drop went to the arrangement). Other platforms still hold the drop until the pointer's next report and route it there; a `PointerGone` keeps it held, and after 30 frames with no position it goes to the arrangement (#368). That position also picks where an arrangement drop lands (the audio track under the pointer, at its time), so a pointer moved before its next report imports the file onto the track it reached. +A file dragged in from the file manager has no drop position on any platform: winit 0.30 reports `DroppedFile(PathBuf)` alone (the Windows drop handler ignores the OLE `POINTL`), and no cursor motion arrives during the OS drag, so egui's pointer is stale or gone when the drop lands. On Windows transit asks the OS for the cursor position at the drop's frame and routes the drop there (on hardware the pointer's next report did not come first: a `PointerGone` did, and the drop went to the arrangement). Other platforms still hold the drop until the pointer's next report and route it there; a `PointerGone` keeps it held, and after 30 frames with no position it goes to the arrangement (#368). That position also picks where an arrangement drop lands (the track under the pointer, at its time, as a browser drag), so a pointer moved before its next report imports the file onto the track it reached, or is refused there when that track takes no audio. diff --git a/docs/user-guide.md b/docs/user-guide.md index b5cfd228..ec4a4f41 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -898,19 +898,22 @@ view has content it takes no drag. On an Instrument key map with zones, a file d no zone plays shows, dashed, the keys it will cover, and letting go makes a zone there (see below). A file or plug-in dropped elsewhere on a device window is ignored; the window takes the drop, so nothing behind it is reached. Anywhere else, a browser drag lands on the track lane, header, mixer strip or device chain where you let go. A file from the file manager lands the same -way on an audio track's lane, header, mixer strip or device chain, or below the tracks on a new -track, and several files follow each other on that track; anywhere else it is imported into the -arrangement at the cursor (a MIDI file imports as MIDI). A `.transit` or `.dawproject` file opens -as the session; dropped with other files, it opens alone and the status line names what was left -out. On Windows a file manager drop lands where the pointer is when you let go; on other -platforms it lands as soon as the pointer moves after you let go (see the known issues). A stereo -or wider file that lands on a mono audio track with as many mono tracks below it (in the Edit -window's order, none frozen and none holding a clip where the file goes) splits across them in -one undo step: each channel becomes its own mono file, `.L` and `.R` (`.1`, `.2`… past -stereo), saved to `Audio Files`; otherwise the file lands whole on the one track. To split a clip -already in the session, such as two microphones recorded onto one stereo track, right-click it and -choose **Split to Mono Tracks**: each channel goes to a new mono track below the clip's track, the -original clip is muted, and a take played from its file gets one mono WAV per channel beside it. +way: on the track under the pointer (at the pointer's time on its lane) or below the tracks on a +new track, several files one after another, and anywhere else at the cursor (a MIDI file imports +as MIDI). A track that takes no audio, or a file that is not audio transit imports, is refused +with the reason on the status line. A file keeps its channels: a stereo file dropped on a mono +track lands there as one stereo clip. A `.transit` or `.dawproject` file opens as the session, +asking first to save unsaved changes as File > Open does; dropped with other files, it opens alone +and the status line names what was left out. On Windows a file manager drop lands where the pointer +is when you let go; on other platforms it lands as soon as the pointer moves after you let go (see +the known issues). + +To split a stereo or wider clip into mono tracks, such as two microphones recorded onto one stereo +track, right-click it and choose **Split to Mono Tracks**: each channel goes to a new mono track +below the clip's track (` L` and ` R`, numbered past stereo), with the clip's +timing, fades and gain, the original clip is muted, and the whole split is one undo step. Each +channel becomes its own mono file, saved to `Audio Files`; a take played from its file gets one +mono WAV per channel beside it. Right-click a pad and choose **Clear pad** to empty it and reset its name, choke group, mute, and solo. Delete or Backspace does the same for the selected pad while the Sampler window has From 13179db6f05bb42f6fe01a189887765991351fae Mon Sep 17 00:00:00 2001 From: BlueJayLouche Date: Mon, 23 Nov 2026 09:08:08 +1100 Subject: [PATCH 10/15] ui, engine: refutation review of the #767 rework (ADR 0009): whether a dropped file is audio is the engine's call again (import_files leaves out only Maschine/Kontakt files, so WAV data named .rf64 or with no extension imports from a file-manager drop, as on main, and a text file is never called a Maschine/Kontakt file); a file that fails to decode keeps its reason on its drop's last line; a split opens a take's reader anew, so a take whose file is back splits again; the guide says a session drop counts what it left out --- crates/engine/src/io/split_files.rs | 3 ++ crates/engine/tests/split_to_mono.rs | 20 ++++++++++++ crates/ui-studio/src/browser.rs | 4 ++- crates/ui-studio/src/import.rs | 8 +++-- .../src/sampler_panel/drop_routing_tests.rs | 31 +++++++++++++++++++ docs/user-guide.md | 2 +- 6 files changed, 64 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/io/split_files.rs b/crates/engine/src/io/split_files.rs index 22c4b096..498867cb 100644 --- a/crates/engine/src/io/split_files.rs +++ b/crates/engine/src/io/split_files.rs @@ -26,6 +26,9 @@ pub(crate) fn remove(paths: &[PathBuf]) { /// `written` as soon as it is created. pub(crate) fn write(disk: &DiskSource, names: &[String], written: &mut Vec) -> Result<()> { let io = |p: &Path, err: &dyn std::fmt::Display| EngineError::Io(format!("{}: {err}", p.display())); + // A reader that failed once reads nothing more: opened anew, as before an offline render, so a + // take whose file is back splits again. + disk.check().map_err(|why| io(&disk.path(), &why))?; let dir = disk.path().parent().map(Path::to_path_buf).unwrap_or_default(); let opts = EncodeOptions { format: FileFormat::Wav, bit_depth: BitDepth::Float32, dither: false, bwf: None, bitrate_kbps: None, title: None }; let mut encoders = Vec::with_capacity(names.len()); diff --git a/crates/engine/tests/split_to_mono.rs b/crates/engine/tests/split_to_mono.rs index b2714a2c..88d6c9af 100644 --- a/crates/engine/tests/split_to_mono.rs +++ b/crates/engine/tests/split_to_mono.rs @@ -173,3 +173,23 @@ fn audio_is_never_imported_onto_a_midi_track() { assert!(r.as_ref().is_err_and(|err| err.to_string().contains("Synth is not an audio track")), "{r:?}"); assert!(e.session().track(TrackId(midi)).unwrap().clips().is_empty() && e.session().sources.is_empty()); } + +#[test] +fn a_take_whose_file_is_back_after_a_failed_read_splits_again() { + let d = transit_test_support::TestDir::new("split-to-mono-reopen"); + std::fs::create_dir_all(&*d).unwrap(); + let take = d.join("Take.wav"); + let bytes = stereo_wav(4_800, 16_384, -8_192); + std::fs::write(&take, &bytes).unwrap(); + let mut e = Engine::default(); + e.session_mut().edit.values.insert(transit_model::disk::STREAM_MINUTES_KEY.into(), 0.001); + let mics = track(&mut e, "stereo"); + let ids = transit_engine::io::add_recording_take(&mut e, &transit_engine::io::Recording::new(0), vec![(TrackId(mics), take.clone())], false); + // The file loses its audio (a drive unplugged): the split's read fails and its reader with it. + std::fs::OpenOptions::new().write(true).open(&take).unwrap().set_len(44).unwrap(); + assert!(e.execute("clip.split_to_mono", &json!({"clips": [ids[0].0]})).is_err()); + // The file is back: the split opens the take anew, as an offline render does. + std::fs::write(&take, &bytes).unwrap(); + let r = e.execute("clip.split_to_mono", &json!({"clips": [ids[0].0]})); + assert!(r.as_ref().is_ok_and(|r| r["tracks"].as_array().map(Vec::len) == Some(2)), "{r:?}"); +} diff --git a/crates/ui-studio/src/browser.rs b/crates/ui-studio/src/browser.rs index afd7ec93..f214aa42 100644 --- a/crates/ui-studio/src/browser.rs +++ b/crates/ui-studio/src/browser.rs @@ -630,8 +630,10 @@ impl StudioApp { /// Import audio files at `at`: onto `track` (an audio track), or onto a new track when /// `track` is `None`. Several files go one after another on the same track. The files are /// prepared in the background and committed in order, one undo step each (see `import`). + /// Maschine/Kontakt files are left out here; whether any other file is audio is the engine's + /// call (it reads a file by its contents), and a refusal gives its reason. pub fn import_files(&mut self, files: &[PathBuf], track: Option, at: Samples) -> Result<(), String> { - let (ok, closed): (Vec<&PathBuf>, Vec<&PathBuf>) = files.iter().partition(|p| kind_of(&p.to_string_lossy(), false) == Some(Kind::Audio)); + let (ok, closed): (Vec<&PathBuf>, Vec<&PathBuf>) = files.iter().partition(|p| kind_of(&p.to_string_lossy(), false) != Some(Kind::Closed)); if ok.is_empty() { let what = closed.first().map_or("Nothing to import".to_string(), |p| refusal(p)); self.status = what.clone(); diff --git a/crates/ui-studio/src/import.rs b/crates/ui-studio/src/import.rs index 94c4bc1d..15b039dc 100644 --- a/crates/ui-studio/src/import.rs +++ b/crates/ui-studio/src/import.rs @@ -280,8 +280,12 @@ pub fn step(app: &mut StudioApp, ctx: &egui::Context) { app.drop_item(0, msg); } "failed" => { - let msg = format!("Couldn't import {}: {}", front.name, front.error.clone().unwrap_or_default()); - app.drop_item(0, msg); + let (name, why, batch) = (front.name.clone(), front.error.clone().unwrap_or_default(), front.batch); + // Kept for the drop's last line too, so a later file's commit keeps the reason. + if let Some(b) = app.imports.batches.get_mut(&batch) { + b.refused.push((name.clone(), why.clone())); + } + app.drop_item(0, format!("Couldn't import {name}: {why}")); } _ => break, } diff --git a/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs b/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs index 3eaf11cd..33af0b41 100644 --- a/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs +++ b/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs @@ -325,3 +325,34 @@ fn a_dropped_session_that_fails_to_open_shows_why() { assert!(t.app.status.starts_with("Could not open"), "{}", t.app.status); assert!(t.app.engine.session().tracks.iter().all(|tr| tr.clips().is_empty()), "nothing is imported"); } + +/// Whether a dropped file is audio is the engine's call, as it was for every file-manager drop: +/// WAV data named `.rf64`, or with no extension at all, imports, though the browser lists neither. +#[test] +fn audio_the_engine_reads_imports_whatever_its_file_is_named() { + let mut t = T::new(); + let a = t.app.run("track.new", serde_json::json!({"kind": "audio", "format": "mono"})).unwrap()["tracks"][0].as_u64().unwrap(); + t.frames(3); + let (rf64, bare) = (t.sample("Kick.rf64", 2_400), t.sample("Snare", 2_400)); + let lane = t.app.arrange.layout.tracks.iter().find(|r| r.id == a).unwrap().lane; + t.drop_files(vec![rf64, bare], mid(lane)); + let names: Vec = t.app.engine.session().track(TrackId(a)).unwrap().clips().iter().map(|c| c.name.clone()).collect(); + assert_eq!(names, ["Kick", "Snare"], "{}", t.app.status); +} + +/// A file that is not audio, dropped with one that is, is named on the drop's last line with the +/// engine's reason (never as a Maschine/Kontakt file), though the audio after it commits later. +#[test] +fn a_file_that_is_not_audio_in_a_drop_is_named_with_its_reason() { + let mut t = T::new(); + let a = t.app.run("track.new", serde_json::json!({"kind": "audio", "format": "mono"})).unwrap()["tracks"][0].as_u64().unwrap(); + t.frames(3); + let notes = t.dir.join("notes.txt"); + std::fs::write(¬es, b"not audio").unwrap(); + let kick = t.sample("Kick.wav", 2_400); + let lane = t.app.arrange.layout.tracks.iter().find(|r| r.id == a).unwrap().lane; + t.drop_files(vec![notes, kick], mid(lane)); + assert_eq!(t.app.engine.session().track(TrackId(a)).unwrap().clips().len(), 1, "Kick lands"); + let status = &t.app.status; + assert!(status.contains("notes.txt (") && !status.contains("Maschine"), "{status}"); +} diff --git a/docs/user-guide.md b/docs/user-guide.md index ec4a4f41..80e422ba 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -904,7 +904,7 @@ as MIDI). A track that takes no audio, or a file that is not audio transit impor with the reason on the status line. A file keeps its channels: a stereo file dropped on a mono track lands there as one stereo clip. A `.transit` or `.dawproject` file opens as the session, asking first to save unsaved changes as File > Open does; dropped with other files, it opens alone -and the status line names what was left out. On Windows a file manager drop lands where the pointer +and the status line says how many were left out. On Windows a file manager drop lands where the pointer is when you let go; on other platforms it lands as soon as the pointer moves after you let go (see the known issues). From 8fc9842c22975a6c3e3a01d391ee2f2f85e06123 Mon Sep 17 00:00:00 2001 From: BlueJayLouche Date: Mon, 23 Nov 2026 09:27:07 +1100 Subject: [PATCH 11/15] ui: second refutation review of the #767 rework (ADR 0009): a drop at the cursor lands on the cursor's audio track, as on main, not the focused one; when a drop's last file fails, its line names every file of the drop that failed; a drop on a track deleted since its frame says so instead of importing nothing unannounced --- crates/ui-studio/src/browser.rs | 5 +- crates/ui-studio/src/drops.rs | 15 ++++-- crates/ui-studio/src/import.rs | 12 +++-- .../src/sampler_panel/drop_routing_tests.rs | 51 +++++++++++++++++++ 4 files changed, 74 insertions(+), 9 deletions(-) diff --git a/crates/ui-studio/src/browser.rs b/crates/ui-studio/src/browser.rs index f214aa42..d9789a02 100644 --- a/crates/ui-studio/src/browser.rs +++ b/crates/ui-studio/src/browser.rs @@ -641,7 +641,10 @@ impl StudioApp { } if let Some(t) = track { let s = self.engine.session(); - let Some(tr) = s.track(t) else { return Err("no such track".into()) }; + let Some(tr) = s.track(t) else { + self.status = "The track was deleted: drop the files again".into(); + return Err(self.status.clone()); + }; if tr.kind != TrackKind::Audio { self.status = format!("{} is not an audio track: drop audio files on an audio track or below the tracks", tr.name); return Err(self.status.clone()); diff --git a/crates/ui-studio/src/drops.rs b/crates/ui-studio/src/drops.rs index 9f223d75..0b281263 100644 --- a/crates/ui-studio/src/drops.rs +++ b/crates/ui-studio/src/drops.rs @@ -139,17 +139,23 @@ pub(crate) fn route(app: &mut StudioApp, ctx: &egui::Context, offer: DropOffer) } // The rest lands as a browser drag's files do (`import_files`): on the track under the pointer // (at the pointer's time on its lane) or on a new track below the tracks, one after another; - // anywhere else at the cursor. A track that takes no audio, or a file that is not audio this - // app imports, is refused with the reason on the status line. + // anywhere else at the cursor (on the cursor's track, as before). A track that takes no audio, + // or a file that is not audio, is refused with the reason on the status line. let snap = !ctx.input(|i| i.modifiers.shift); let cursor = app.cursor(); let _ = match offer.pos.and_then(|p| app.drop_target(ctx, p, snap, true)).map(|(t, _)| t) { Some(Target::Track { track, at }) => app.import_files(&audio, Some(track), at.unwrap_or(cursor)), Some(Target::Below { at }) => app.import_files(&audio, None, at.unwrap_or(cursor)), - _ => app.import_at_cursor(&audio), + _ => app.import_files(&audio, cursor_audio_track(app), cursor), }; } +/// The cursor's track when it is an audio track: where audio lands at the cursor (none: a new +/// track). +fn cursor_audio_track(app: &StudioApp) -> Option { + app.cursor_track().filter(|t| app.engine.session().track(*t).is_some_and(|t| t.kind == transit_model::TrackKind::Audio)) +} + /// Whether dropping `p` opens it as the session. fn opens_session(p: &str) -> bool { let lower = p.to_ascii_lowercase(); @@ -188,8 +194,7 @@ pub fn open_path(app: &mut StudioApp, p: &str) { } else { let at = app.cursor(); let mut params = serde_json::json!({"path": p, "at": at}); - let audio = |t: &TrackId| app.engine.session().track(*t).is_some_and(|t| t.kind == transit_model::TrackKind::Audio); - if let Some(t) = app.cursor_track().filter(audio) { + if let Some(t) = cursor_audio_track(app) { params["track"] = serde_json::json!(t.0); } app.run("file.import_audio", params) diff --git a/crates/ui-studio/src/import.rs b/crates/ui-studio/src/import.rs index 15b039dc..26b1fef5 100644 --- a/crates/ui-studio/src/import.rs +++ b/crates/ui-studio/src/import.rs @@ -281,11 +281,17 @@ pub fn step(app: &mut StudioApp, ctx: &egui::Context) { } "failed" => { let (name, why, batch) = (front.name.clone(), front.error.clone().unwrap_or_default(), front.batch); - // Kept for the drop's last line too, so a later file's commit keeps the reason. + let mut msg = format!("Couldn't import {name}: {why}"); + // Kept for the drop's last line, so a later file's commit keeps the reason; when + // this is that last file, the line names every file of the drop that failed. + let last = !app.imports.items.iter().skip(1).any(|i| i.batch == batch); if let Some(b) = app.imports.batches.get_mut(&batch) { - b.refused.push((name.clone(), why.clone())); + b.refused.push((name, why)); + if last && (b.refused.len() > 1 || b.committed > 0) { + msg = not_prepared(&b.refused, b.asked); + } } - app.drop_item(0, format!("Couldn't import {name}: {why}")); + app.drop_item(0, msg); } _ => break, } diff --git a/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs b/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs index 33af0b41..a8d4c96d 100644 --- a/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs +++ b/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs @@ -356,3 +356,54 @@ fn a_file_that_is_not_audio_in_a_drop_is_named_with_its_reason() { let status = &t.app.status; assert!(status.contains("notes.txt (") && !status.contains("Maschine"), "{status}"); } + +/// A drop at the cursor lands on the cursor's track, as it did before drops followed the pointer, +/// even when an earlier import left the focus on another audio track. +#[test] +fn a_drop_at_the_cursor_lands_on_the_cursors_track_not_the_focused_one() { + let mut t = T::new(); + let new = |t: &mut T| t.app.run("track.new", serde_json::json!({"kind": "audio", "format": "mono"})).unwrap()["tracks"][0].as_u64().unwrap(); + let (a, b) = (new(&mut t), new(&mut t)); + t.app.set_cursor(48_000, Some(TrackId(a))); + t.app.ui.focus_track = Some(TrackId(b)); + t.frames(3); + let one = t.sample("One.wav", 2_400); + t.drop_file(&one, MENU_BAR); + let on = |id: u64| t.app.engine.session().track(TrackId(id)).unwrap().clips().iter().map(|c| c.start).collect::>(); + assert_eq!((on(a), on(b)), (vec![48_000], vec![]), "{}", t.app.status); +} + +/// When the last file of a drop fails too, the drop's last line still names every file that +/// failed, and says that the others imported; a lone failure keeps its own line. +#[test] +fn a_drop_whose_last_file_fails_names_every_failure() { + let mut t = T::new(); + let a = t.app.run("track.new", serde_json::json!({"kind": "audio", "format": "mono"})).unwrap()["tracks"][0].as_u64().unwrap(); + t.frames(3); + let lane = mid(t.app.arrange.layout.tracks.iter().find(|r| r.id == a).unwrap().lane); + let text = |t: &T, name: &str| { + let p = t.dir.join(name); + std::fs::write(&p, b"not audio").unwrap(); + p + }; + let (x, y) = (text(&t, "a.txt"), text(&t, "b.txt")); + t.drop_files(vec![x, y], lane); + assert!(t.app.status.starts_with("2 of 2 could not be prepared: a.txt (") && t.app.status.contains("b.txt"), "{}", t.app.status); + let (kick, notes) = (t.sample("Kick.wav", 2_400), text(&t, "notes.txt")); + t.drop_files(vec![kick, notes], lane); + assert!(t.app.status.starts_with("1 of 2 could not be prepared: notes.txt ("), "{}", t.app.status); + let lone = text(&t, "c.txt"); + t.drop_files(vec![lone], lane); + assert!(t.app.status.starts_with("Couldn't import c.txt: "), "{}", t.app.status); +} + +/// A drop on a track deleted since the frame it was seen in says so, rather than importing nothing +/// unannounced. +#[test] +fn a_drop_on_a_deleted_track_says_so() { + let mut t = T::new(); + let one = t.sample("One.wav", 2_400); + let r = t.app.import_files(&[one], Some(TrackId(9_999)), 0); + assert!(r.is_err() && t.app.status == "The track was deleted: drop the files again", "{}", t.app.status); + assert!(!t.app.imports.active()); +} From 3aa2ea13feb245b61e4b6a284445f5c84164f01f Mon Sep 17 00:00:00 2001 From: BlueJayLouche Date: Mon, 23 Nov 2026 09:38:20 +1100 Subject: [PATCH 12/15] =?UTF-8?q?ui:=20third=20refutation=20review=20of=20?= =?UTF-8?q?the=20#767=20rework=20(ADR=200009):=20the=20mixer's=20Main=20st?= =?UTF-8?q?rip=20of=20a=20session=20with=20no=20Master=20track=20is=20no?= =?UTF-8?q?=20drop=20target=20(its=20track=20id=20is=200,=20no=20track's),?= =?UTF-8?q?=20so=20a=20drop=20there=20lands=20at=20the=20cursor=20instead?= =?UTF-8?q?=20of=20being=20refused=20as=20a=20deleted=20track;=20a=20drop?= =?UTF-8?q?=20whose=20last=20file=20fails=20ends=20on=20the=20same=20"Impo?= =?UTF-8?q?rted=20=E2=80=A6"=20line=20as=20one=20whose=20failure=20comes?= =?UTF-8?q?=20first?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/ui-studio/src/browser.rs | 4 +- crates/ui-studio/src/import.rs | 44 +++++++++++-------- .../src/sampler_panel/drop_routing_tests.rs | 26 ++++++++++- 3 files changed, 52 insertions(+), 22 deletions(-) diff --git a/crates/ui-studio/src/browser.rs b/crates/ui-studio/src/browser.rs index d9789a02..0527741a 100644 --- a/crates/ui-studio/src/browser.rs +++ b/crates/ui-studio/src/browser.rs @@ -677,7 +677,9 @@ impl StudioApp { } let m = &self.mixer.layout; if m.visible { - for s in m.strips.iter().chain(m.master.iter()) { + // The Main strip of a session with no Master track is the main bus, no track (its + // `track` is 0, an id no track has): no target, as the mixer's empty area. + for s in m.strips.iter().chain(m.master.iter()).filter(|s| s.track != 0) { if rect(s.rect).contains(pos) { return Some((Target::Track { track: TrackId(s.track), at: None }, s.rect)); } diff --git a/crates/ui-studio/src/import.rs b/crates/ui-studio/src/import.rs index 26b1fef5..cab4cdbd 100644 --- a/crates/ui-studio/src/import.rs +++ b/crates/ui-studio/src/import.rs @@ -170,6 +170,26 @@ impl StudioApp { self.forget_batches(); } + /// A drop's last line once its last file is done: what was imported where (`one`: the file's + /// name when the drop queued one), the Maschine/Kontakt files left out, and the files that + /// could not be prepared, with the first reason. + fn imported_line(&self, b: &Batch, one: &str) -> String { + let what = match (b.files, b.committed) { + (1, _) => one.to_string(), + (f, c) if f == c => format!("{c} files"), + (f, c) => format!("{c} of {f} files"), + }; + let name = b.track.and_then(|t| self.engine.session().track(t)).map_or_else(String::new, |t| t.name.clone()); + let mut msg = format!("Imported {what} to {name} at {}", crate::browser::bbs(self, b.at)); + if b.closed > 0 { + msg.push_str(&format!(" ({} Maschine/Kontakt file{} skipped: not supported)", b.closed, if b.closed == 1 { "" } else { "s" })); + } + if !b.refused.is_empty() { + msg.push_str(&format!("; {}", not_prepared(&b.refused, b.asked))); + } + msg + } + /// Commit the oldest item: at its drop's track and next position. fn commit_front(&mut self) { let it = self.imports.items[0].clone(); @@ -207,24 +227,7 @@ impl StudioApp { self.imports.batches.insert(it.batch, b.clone()); let left = self.imports.items.iter().any(|i| i.batch == it.batch); if !left { - let what = match (b.files, b.committed) { - (1, _) => it.name.clone(), - (f, c) if f == c => format!("{c} files"), - (f, c) => format!("{c} of {f} files"), - }; - let name = b.track.and_then(|t| self.engine.session().track(t)).map_or_else(String::new, |t| t.name.clone()); - let mut msg = format!("Imported {what} to {name} at {}", crate::browser::bbs(self, b.at)); - if b.closed > 0 { - msg.push_str(&format!( - " ({} Maschine/Kontakt file{} skipped: not supported)", - b.closed, - if b.closed == 1 { "" } else { "s" } - )); - } - if !b.refused.is_empty() { - msg.push_str(&format!("; {}", not_prepared(&b.refused, b.asked))); - } - self.status = msg; + self.status = self.imported_line(&b, &it.name); self.forget_batches(); } if let Some(t) = b.track { @@ -287,7 +290,10 @@ pub fn step(app: &mut StudioApp, ctx: &egui::Context) { let last = !app.imports.items.iter().skip(1).any(|i| i.batch == batch); if let Some(b) = app.imports.batches.get_mut(&batch) { b.refused.push((name, why)); - if last && (b.refused.len() > 1 || b.committed > 0) { + let b = b.clone(); + if last && b.committed > 0 { + msg = app.imported_line(&b, ""); + } else if last && b.refused.len() > 1 { msg = not_prepared(&b.refused, b.asked); } } diff --git a/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs b/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs index a8d4c96d..f3bf27e2 100644 --- a/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs +++ b/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs @@ -374,7 +374,8 @@ fn a_drop_at_the_cursor_lands_on_the_cursors_track_not_the_focused_one() { } /// When the last file of a drop fails too, the drop's last line still names every file that -/// failed, and says that the others imported; a lone failure keeps its own line. +/// failed, and says where the others were imported, as it does when the failure comes first; a +/// lone failure keeps its own line. #[test] fn a_drop_whose_last_file_fails_names_every_failure() { let mut t = T::new(); @@ -391,7 +392,11 @@ fn a_drop_whose_last_file_fails_names_every_failure() { assert!(t.app.status.starts_with("2 of 2 could not be prepared: a.txt (") && t.app.status.contains("b.txt"), "{}", t.app.status); let (kick, notes) = (t.sample("Kick.wav", 2_400), text(&t, "notes.txt")); t.drop_files(vec![kick, notes], lane); - assert!(t.app.status.starts_with("1 of 2 could not be prepared: notes.txt ("), "{}", t.app.status); + assert!( + t.app.status.starts_with("Imported 1 of 2 files to Audio 1 at ") && t.app.status.contains("; 1 of 2 could not be prepared: notes.txt ("), + "{}", + t.app.status + ); let lone = text(&t, "c.txt"); t.drop_files(vec![lone], lane); assert!(t.app.status.starts_with("Couldn't import c.txt: "), "{}", t.app.status); @@ -407,3 +412,20 @@ fn a_drop_on_a_deleted_track_says_so() { assert!(r.is_err() && t.app.status == "The track was deleted: drop the files again", "{}", t.app.status); assert!(!t.app.imports.active()); } + +/// The mixer's Main strip with no Master track is the main bus, no track: a file dropped there +/// lands at the cursor, as anywhere else no track is, never refused as a deleted track. +#[test] +fn a_drop_on_the_main_strip_with_no_master_track_lands_at_the_cursor() { + let mut t = T::new(); + let a = t.app.run("track.new", serde_json::json!({"kind": "audio", "format": "mono"})).unwrap()["tracks"][0].as_u64().unwrap(); + t.app.set_cursor(48_000, Some(TrackId(a))); + t.app.ui.show_mixer = true; + t.frames(3); + assert!(t.app.engine.session().tracks.iter().all(|tr| tr.kind != transit_model::TrackKind::Master)); + let main = t.app.mixer.layout.master.clone().expect("the Main strip is drawn"); + let one = t.sample("One.wav", 2_400); + t.drop_file(&one, mid(main.rect)); + let starts: Vec = t.app.engine.session().track(TrackId(a)).unwrap().clips().iter().map(|c| c.start).collect(); + assert_eq!(starts, [48_000], "{}", t.app.status); +} From e3aad37e87e29a33ac6fcd3d80b438ff79f65b6c Mon Sep 17 00:00:00 2001 From: BlueJayLouche Date: Mon, 23 Nov 2026 09:48:39 +1100 Subject: [PATCH 13/15] =?UTF-8?q?ui:=20fourth=20refutation=20review=20of?= =?UTF-8?q?=20the=20#767=20rework=20(ADR=200009):=20a=20drop=20whose=20las?= =?UTF-8?q?t=20file=20fails=20ends=20on=20its=20"Imported=20=E2=80=A6"=20l?= =?UTF-8?q?ine=20only=20while=20the=20drop's=20track=20is=20still=20there,?= =?UTF-8?q?=20never=20naming=20a=20track=20deleted=20or=20undone=20in=20be?= =?UTF-8?q?tween;=20a=20test=20that=20a=20real=20Master=20track's=20strip?= =?UTF-8?q?=20still=20takes=20a=20drop=20(and=20refuses=20audio=20with=20t?= =?UTF-8?q?he=20reason)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/ui-studio/src/import.rs | 37 +++++++++++++++++-- .../src/sampler_panel/drop_routing_tests.rs | 18 +++++++++ 2 files changed, 51 insertions(+), 4 deletions(-) diff --git a/crates/ui-studio/src/import.rs b/crates/ui-studio/src/import.rs index cab4cdbd..2924ae65 100644 --- a/crates/ui-studio/src/import.rs +++ b/crates/ui-studio/src/import.rs @@ -190,6 +190,19 @@ impl StudioApp { msg } + /// The line a drop ends on when its last file fails (`lone`: that failure's own line): the + /// drop's "Imported …" line when a file of it committed onto a track still there, else the + /// files that failed when there are several, else `lone`. + fn failed_line(&self, b: &Batch, lone: String) -> String { + if b.committed > 0 && b.track.is_some_and(|t| self.engine.session().track(t).is_some()) { + self.imported_line(b, "") + } else if b.refused.len() > 1 { + not_prepared(&b.refused, b.asked) + } else { + lone + } + } + /// Commit the oldest item: at its drop's track and next position. fn commit_front(&mut self) { let it = self.imports.items[0].clone(); @@ -291,10 +304,8 @@ pub fn step(app: &mut StudioApp, ctx: &egui::Context) { if let Some(b) = app.imports.batches.get_mut(&batch) { b.refused.push((name, why)); let b = b.clone(); - if last && b.committed > 0 { - msg = app.imported_line(&b, ""); - } else if last && b.refused.len() > 1 { - msg = not_prepared(&b.refused, b.asked); + if last { + msg = app.failed_line(&b, msg); } } app.drop_item(0, msg); @@ -441,3 +452,21 @@ pub fn paint(app: &mut StudioApp, ctx: &egui::Context) { app.cancel_imports(Some(id)); } } + +#[cfg(test)] +mod tests { + use super::*; + + /// A drop whose first file committed and whose last one failed never ends on "Imported … to" + /// a track deleted (or undone) in between: the failure's own line stands. + #[test] + fn a_failed_last_file_never_claims_an_import_onto_a_track_that_is_gone() { + let mut app = crate::tests::app(); + let a = TrackId(app.run("track.new", json!({"kind": "audio", "name": "Kicks"})).unwrap()["tracks"][0].as_u64().unwrap()); + let refused = vec![("notes.txt".to_string(), "unsupported".to_string())]; + let b = Batch { track: Some(a), at: 0, next: 2_400, files: 2, committed: 1, closed: 0, refused, asked: 2 }; + assert!(app.failed_line(&b, "lone".into()).starts_with("Imported 1 of 2 files to Kicks at ")); + app.run("track.delete", json!({"tracks": [a.0]})).unwrap(); + assert_eq!(app.failed_line(&b, "lone".into()), "lone"); + } +} diff --git a/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs b/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs index f3bf27e2..ad4f5054 100644 --- a/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs +++ b/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs @@ -429,3 +429,21 @@ fn a_drop_on_the_main_strip_with_no_master_track_lands_at_the_cursor() { let starts: Vec = t.app.engine.session().track(TrackId(a)).unwrap().clips().iter().map(|c| c.start).collect(); assert_eq!(starts, [48_000], "{}", t.app.status); } + +/// A real Master track's strip is still a drop target, refused for audio with the reason (only the +/// main bus with no Master track is no target). +#[test] +fn audio_dropped_on_a_master_tracks_strip_is_refused_with_the_reason() { + let mut t = T::new(); + let a = t.app.run("track.new", serde_json::json!({"kind": "audio", "format": "mono"})).unwrap()["tracks"][0].as_u64().unwrap(); + t.app.run("track.new", serde_json::json!({"kind": "master"})).unwrap(); + t.app.set_cursor(0, Some(TrackId(a))); + t.app.ui.show_mixer = true; + t.frames(3); + let master = t.app.mixer.layout.master.clone().expect("the Master strip is drawn"); + assert_ne!(master.track, 0, "a Master track's own strip"); + let one = t.sample("One.wav", 2_400); + t.drop_file(&one, mid(master.rect)); + assert!(t.app.status.contains("is not an audio track"), "{}", t.app.status); + assert!(t.app.engine.session().tracks.iter().all(|tr| tr.clips().is_empty()), "nothing is imported"); +} From 22d235d63f04136c61de7b18354b4ccf04862938 Mon Sep 17 00:00:00 2001 From: BlueJayLouche Date: Mon, 23 Nov 2026 09:59:04 +1100 Subject: [PATCH 14/15] =?UTF-8?q?ui:=20fifth=20refutation=20review=20of=20?= =?UTF-8?q?the=20#767=20rework=20(ADR=200009):=20a=20drop=20whose=20last?= =?UTF-8?q?=20file=20fails=20ends=20on=20a=20line=20that=20names=20its=20f?= =?UTF-8?q?ailures=20and=20the=20Maschine/Kontakt=20files=20left=20out,=20?= =?UTF-8?q?never=20a=20track=20(one=20deleted,=20undone=20or=20reused=20by?= =?UTF-8?q?=20id=20since),=20so=20commit=5Ffront's=20"Imported=20=E2=80=A6?= =?UTF-8?q?"=20line=20is=20main's=20again;=20the=20tests=20go=20through=20?= =?UTF-8?q?the=20real=20import=20queue?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/ui-studio/src/import.rs | 84 ++++++------------- .../src/sampler_panel/drop_routing_tests.rs | 16 ++-- 2 files changed, 33 insertions(+), 67 deletions(-) diff --git a/crates/ui-studio/src/import.rs b/crates/ui-studio/src/import.rs index 2924ae65..aacd3e67 100644 --- a/crates/ui-studio/src/import.rs +++ b/crates/ui-studio/src/import.rs @@ -170,39 +170,6 @@ impl StudioApp { self.forget_batches(); } - /// A drop's last line once its last file is done: what was imported where (`one`: the file's - /// name when the drop queued one), the Maschine/Kontakt files left out, and the files that - /// could not be prepared, with the first reason. - fn imported_line(&self, b: &Batch, one: &str) -> String { - let what = match (b.files, b.committed) { - (1, _) => one.to_string(), - (f, c) if f == c => format!("{c} files"), - (f, c) => format!("{c} of {f} files"), - }; - let name = b.track.and_then(|t| self.engine.session().track(t)).map_or_else(String::new, |t| t.name.clone()); - let mut msg = format!("Imported {what} to {name} at {}", crate::browser::bbs(self, b.at)); - if b.closed > 0 { - msg.push_str(&format!(" ({} Maschine/Kontakt file{} skipped: not supported)", b.closed, if b.closed == 1 { "" } else { "s" })); - } - if !b.refused.is_empty() { - msg.push_str(&format!("; {}", not_prepared(&b.refused, b.asked))); - } - msg - } - - /// The line a drop ends on when its last file fails (`lone`: that failure's own line): the - /// drop's "Imported …" line when a file of it committed onto a track still there, else the - /// files that failed when there are several, else `lone`. - fn failed_line(&self, b: &Batch, lone: String) -> String { - if b.committed > 0 && b.track.is_some_and(|t| self.engine.session().track(t).is_some()) { - self.imported_line(b, "") - } else if b.refused.len() > 1 { - not_prepared(&b.refused, b.asked) - } else { - lone - } - } - /// Commit the oldest item: at its drop's track and next position. fn commit_front(&mut self) { let it = self.imports.items[0].clone(); @@ -240,7 +207,24 @@ impl StudioApp { self.imports.batches.insert(it.batch, b.clone()); let left = self.imports.items.iter().any(|i| i.batch == it.batch); if !left { - self.status = self.imported_line(&b, &it.name); + let what = match (b.files, b.committed) { + (1, _) => it.name.clone(), + (f, c) if f == c => format!("{c} files"), + (f, c) => format!("{c} of {f} files"), + }; + let name = b.track.and_then(|t| self.engine.session().track(t)).map_or_else(String::new, |t| t.name.clone()); + let mut msg = format!("Imported {what} to {name} at {}", crate::browser::bbs(self, b.at)); + if b.closed > 0 { + msg.push_str(&format!( + " ({} Maschine/Kontakt file{} skipped: not supported)", + b.closed, + if b.closed == 1 { "" } else { "s" } + )); + } + if !b.refused.is_empty() { + msg.push_str(&format!("; {}", not_prepared(&b.refused, b.asked))); + } + self.status = msg; self.forget_batches(); } if let Some(t) = b.track { @@ -298,14 +282,18 @@ pub fn step(app: &mut StudioApp, ctx: &egui::Context) { "failed" => { let (name, why, batch) = (front.name.clone(), front.error.clone().unwrap_or_default(), front.batch); let mut msg = format!("Couldn't import {name}: {why}"); - // Kept for the drop's last line, so a later file's commit keeps the reason; when - // this is that last file, the line names every file of the drop that failed. + // Kept for the drop's last line, so a later file's commit keeps the reason. When + // this is the drop's last file, its line names the drop's failures and the files + // left out up front, never a track (it may be gone, or undone, by now). let last = !app.imports.items.iter().skip(1).any(|i| i.batch == batch); if let Some(b) = app.imports.batches.get_mut(&batch) { b.refused.push((name, why)); - let b = b.clone(); - if last { - msg = app.failed_line(&b, msg); + if last && b.refused.len() > 1 { + msg = not_prepared(&b.refused, b.asked); + } + if last && b.closed > 0 { + let s = if b.closed == 1 { "" } else { "s" }; + msg.push_str(&format!(" ({} Maschine/Kontakt file{s} skipped: not supported)", b.closed)); } } app.drop_item(0, msg); @@ -452,21 +440,3 @@ pub fn paint(app: &mut StudioApp, ctx: &egui::Context) { app.cancel_imports(Some(id)); } } - -#[cfg(test)] -mod tests { - use super::*; - - /// A drop whose first file committed and whose last one failed never ends on "Imported … to" - /// a track deleted (or undone) in between: the failure's own line stands. - #[test] - fn a_failed_last_file_never_claims_an_import_onto_a_track_that_is_gone() { - let mut app = crate::tests::app(); - let a = TrackId(app.run("track.new", json!({"kind": "audio", "name": "Kicks"})).unwrap()["tracks"][0].as_u64().unwrap()); - let refused = vec![("notes.txt".to_string(), "unsupported".to_string())]; - let b = Batch { track: Some(a), at: 0, next: 2_400, files: 2, committed: 1, closed: 0, refused, asked: 2 }; - assert!(app.failed_line(&b, "lone".into()).starts_with("Imported 1 of 2 files to Kicks at ")); - app.run("track.delete", json!({"tracks": [a.0]})).unwrap(); - assert_eq!(app.failed_line(&b, "lone".into()), "lone"); - } -} diff --git a/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs b/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs index ad4f5054..e53e753e 100644 --- a/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs +++ b/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs @@ -373,9 +373,8 @@ fn a_drop_at_the_cursor_lands_on_the_cursors_track_not_the_focused_one() { assert_eq!((on(a), on(b)), (vec![48_000], vec![]), "{}", t.app.status); } -/// When the last file of a drop fails too, the drop's last line still names every file that -/// failed, and says where the others were imported, as it does when the failure comes first; a -/// lone failure keeps its own line. +/// When the last file of a drop fails too, the drop's last line still names every file of it that +/// failed and the Maschine/Kontakt files left out; a lone failure keeps its own line. #[test] fn a_drop_whose_last_file_fails_names_every_failure() { let mut t = T::new(); @@ -390,13 +389,10 @@ fn a_drop_whose_last_file_fails_names_every_failure() { let (x, y) = (text(&t, "a.txt"), text(&t, "b.txt")); t.drop_files(vec![x, y], lane); assert!(t.app.status.starts_with("2 of 2 could not be prepared: a.txt (") && t.app.status.contains("b.txt"), "{}", t.app.status); - let (kick, notes) = (t.sample("Kick.wav", 2_400), text(&t, "notes.txt")); - t.drop_files(vec![kick, notes], lane); - assert!( - t.app.status.starts_with("Imported 1 of 2 files to Audio 1 at ") && t.app.status.contains("; 1 of 2 could not be prepared: notes.txt ("), - "{}", - t.app.status - ); + let (kick, notes, kit) = (t.sample("Kick.wav", 2_400), text(&t, "notes.txt"), text(&t, "Kit.nki")); + t.drop_files(vec![kick, notes, kit], lane); + let status = &t.app.status; + assert!(status.starts_with("Couldn't import notes.txt: ") && status.ends_with(" (1 Maschine/Kontakt file skipped: not supported)"), "{status}"); let lone = text(&t, "c.txt"); t.drop_files(vec![lone], lane); assert!(t.app.status.starts_with("Couldn't import c.txt: "), "{}", t.app.status); From d851acc6d7186bfc75a709cc859c19257f14dc0b Mon Sep 17 00:00:00 2001 From: BlueJayLouche Date: Mon, 23 Nov 2026 10:05:54 +1100 Subject: [PATCH 15/15] ui: sixth refutation review of the #767 rework (ADR 0009): a drop whose last file fails ends on that file's own reason, then the Maschine/Kontakt files left out, then its earlier failures with the first reason, each its own part, so no reason main showed is lost and no file reads as a Maschine/Kontakt file --- crates/ui-studio/src/import.rs | 14 ++++++------ .../src/sampler_panel/drop_routing_tests.rs | 22 ++++++++++++++----- 2 files changed, 23 insertions(+), 13 deletions(-) diff --git a/crates/ui-studio/src/import.rs b/crates/ui-studio/src/import.rs index aacd3e67..18cf26bc 100644 --- a/crates/ui-studio/src/import.rs +++ b/crates/ui-studio/src/import.rs @@ -283,18 +283,18 @@ pub fn step(app: &mut StudioApp, ctx: &egui::Context) { let (name, why, batch) = (front.name.clone(), front.error.clone().unwrap_or_default(), front.batch); let mut msg = format!("Couldn't import {name}: {why}"); // Kept for the drop's last line, so a later file's commit keeps the reason. When - // this is the drop's last file, its line names the drop's failures and the files - // left out up front, never a track (it may be gone, or undone, by now). + // this is the drop's last file, its own line goes on with the files left out up + // front and the drop's earlier failures, never a track (it may be gone by now). let last = !app.imports.items.iter().skip(1).any(|i| i.batch == batch); if let Some(b) = app.imports.batches.get_mut(&batch) { - b.refused.push((name, why)); - if last && b.refused.len() > 1 { - msg = not_prepared(&b.refused, b.asked); - } if last && b.closed > 0 { let s = if b.closed == 1 { "" } else { "s" }; - msg.push_str(&format!(" ({} Maschine/Kontakt file{s} skipped: not supported)", b.closed)); + msg.push_str(&format!("; {} Maschine/Kontakt file{s} skipped: not supported", b.closed)); } + if last && !b.refused.is_empty() { + msg.push_str(&format!("; {}", not_prepared(&b.refused, b.asked))); + } + b.refused.push((name, why)); } app.drop_item(0, msg); } diff --git a/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs b/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs index e53e753e..0e31793e 100644 --- a/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs +++ b/crates/ui-studio/src/sampler_panel/drop_routing_tests.rs @@ -373,8 +373,9 @@ fn a_drop_at_the_cursor_lands_on_the_cursors_track_not_the_focused_one() { assert_eq!((on(a), on(b)), (vec![48_000], vec![]), "{}", t.app.status); } -/// When the last file of a drop fails too, the drop's last line still names every file of it that -/// failed and the Maschine/Kontakt files left out; a lone failure keeps its own line. +/// When the last file of a drop fails too, the drop's last line gives that failure's own reason, +/// then the Maschine/Kontakt files left out, then the drop's earlier failures with the first +/// reason, each its own part; a lone failure keeps its own line. #[test] fn a_drop_whose_last_file_fails_names_every_failure() { let mut t = T::new(); @@ -388,11 +389,20 @@ fn a_drop_whose_last_file_fails_names_every_failure() { }; let (x, y) = (text(&t, "a.txt"), text(&t, "b.txt")); t.drop_files(vec![x, y], lane); - assert!(t.app.status.starts_with("2 of 2 could not be prepared: a.txt (") && t.app.status.contains("b.txt"), "{}", t.app.status); - let (kick, notes, kit) = (t.sample("Kick.wav", 2_400), text(&t, "notes.txt"), text(&t, "Kit.nki")); - t.drop_files(vec![kick, notes, kit], lane); + let why = "unsupported audio"; + let status = t.app.status.clone(); + assert!( + status.starts_with("Couldn't import b.txt: b.txt: unsupported audio") + && status.contains("; 1 of 2 could not be prepared: a.txt (a.txt: unsupported audio"), + "{status}" + ); + let (bad, kick, notes, kit) = (text(&t, "Bad.wav"), t.sample("Kick.wav", 2_400), text(&t, "notes.txt"), text(&t, "Kit.nki")); + t.drop_files(vec![bad, kick, notes, kit], lane); let status = &t.app.status; - assert!(status.starts_with("Couldn't import notes.txt: ") && status.ends_with(" (1 Maschine/Kontakt file skipped: not supported)"), "{status}"); + let parts: Vec<&str> = status.split("; ").collect(); + assert!(parts.len() == 3 && parts[0].starts_with("Couldn't import notes.txt: ") && parts[0].contains(why), "{status}"); + assert_eq!(parts[1], "1 Maschine/Kontakt file skipped: not supported", "{status}"); + assert!(parts[2].starts_with("1 of 3 could not be prepared: Bad.wav (") && parts[2].contains(why), "{status}"); let lone = text(&t, "c.txt"); t.drop_files(vec![lone], lane); assert!(t.app.status.starts_with("Couldn't import c.txt: "), "{}", t.app.status);