Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 34 additions & 4 deletions crates/faderframe-session/src/browser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ pub struct PreviewSettings {
pub sync: bool,
/// In the project's key (transposed).
pub key: bool,
/// Loops and MIDI files go round until stopped.
/// Loops (audio and MIDI) go round until stopped.
pub looped: bool,
/// A file previews when it is selected.
pub auto: bool,
Expand Down Expand Up @@ -640,7 +640,13 @@ pub fn is_loop(bpm: Option<f64>, seconds: Option<f64>) -> bool {
let (Some(bpm), Some(s)) = (bpm, seconds) else {
return false;
};
let beats = s * bpm / 60.0;
beats_loop(s * bpm / 60.0)
}

/// An even number of beats (within 3 %): a loop's length. A MIDI file's
/// last event on it goes round; one ending elsewhere (a fill, a phrase
/// with a tail) plays once, as audio that is not a loop does.
pub fn beats_loop(beats: f64) -> bool {
let whole = beats.round();
whole >= 2.0 && whole as i64 % 2 == 0 && (beats - whole).abs() <= whole * 0.03
}
Expand Down Expand Up @@ -902,8 +908,11 @@ impl Session {
let auto = self.browser.user.preview.auto;
let one = (paths.len() == 1).then(|| paths[0].clone());
self.browser.selected = paths;
// A click on the file already heard (to drag it, say)
// leaves its preview as it is.
if auto
&& let Some(p) = one
&& !self.still_heard(&p)
&& FileKind::of(&p).is_some()
&& p.is_file()
{
Expand Down Expand Up @@ -1589,7 +1598,7 @@ impl Session {
.set_midi_preview(Some(MidiPreview {
events,
length,
looped: settings.looped,
looped: settings.looped && beats_loop(notes.quarters),
start,
}))
.map_err(|e| SessionError::Other(e.to_string()))?
Expand Down Expand Up @@ -1631,6 +1640,23 @@ impl Session {
.map(|t| t.id)
}

/// `path`'s preview plays on (not ended).
fn still_heard(&self, path: &Path) -> bool {
let Some(p) = self.browser.preview.as_ref().filter(|p| p.path == path) else {
return false;
};
match &p.sound {
Sound::Audio { generation, .. } => !self
.engine
.listening()
.link
.preview()
.shared()
.has_ended(*generation),
Sound::Midi { status, .. } => !status.has_ended(),
}
}

/// The preview's worker and end (`true`: what is shown changed).
fn poll_preview(&mut self) -> bool {
let Some(p) = self.browser.preview.as_mut() else {
Expand Down Expand Up @@ -1691,7 +1717,7 @@ impl Session {
for f in &midi {
match to {
Destination::Arranger => {
self.import_midi_file(f, at, false)?;
self.import_midi_file_onto(f, at, false, track)?;
self.browser.user.used(f);
}
Destination::Launcher { .. } => self.notify(
Expand Down Expand Up @@ -1993,6 +2019,10 @@ mod tests {
assert!(!is_loop(Some(120.0), Some(1.75)));
assert!(!is_loop(None, Some(4.0)));
assert!(!is_loop(Some(120.0), Some(0.5)));
// MIDI files by their last event: two bars round, a tail doesn't.
assert!(beats_loop(8.0));
assert!(beats_loop(15.75));
assert!(!beats_loop(8.58));
assert_eq!(nearest_tempo(170.0, 90.0), 85.0);
assert_eq!(nearest_tempo(60.0, 120.0), 120.0);
assert_eq!(nearest_tempo(100.0, 104.0), 100.0);
Expand Down
3 changes: 2 additions & 1 deletion crates/faderframe-session/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5417,7 +5417,8 @@ impl Session {
}
}
for f in midi {
if let Err(e) = self.import_midi_file(&f, at, empty && at == MusicalTime::ZERO)
if let Err(e) =
self.import_midi_file_onto(&f, at, empty && at == MusicalTime::ZERO, track)
{
self.notify(NoticeLevel::Error, e.to_string());
}
Expand Down
74 changes: 60 additions & 14 deletions crates/faderframe-session/src/midifile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,23 @@ impl Session {
at: MusicalTime,
tempo: bool,
) -> Result<Vec<TrackId>> {
self.import_midi_file_onto(path, at, tempo, None)
}

/// [`Self::import_midi_file`], its first part onto `onto` where that is
/// an instrument or MIDI track (dropped on it); the rest on new tracks.
pub fn import_midi_file_onto(
&mut self,
path: &Path,
at: MusicalTime,
tempo: bool,
onto: Option<TrackId>,
) -> Result<Vec<TrackId>> {
let mut onto = onto.filter(|t| {
self.project
.track(*t)
.is_some_and(|t| matches!(t.kind, TrackKind::Instrument | TrackKind::Midi))
});
if crate::midi2file::is_midi2_clip_file(path) {
return self.import_midi2_clip(path, at, tempo).map(|t| vec![t]);
}
Expand Down Expand Up @@ -198,11 +215,13 @@ impl Session {
}

let p = &mut self.project;
let mut index = p
.tracks
.iter()
.rposition(|t| t.kind.has_clips())
// New tracks go under the one dropped on, else after the last.
let mut index = onto
.and_then(|t| p.track_index(t))
.or_else(|| p.tracks.iter().rposition(|t| t.kind.has_clips()))
.map_or(0, |i| i + 1);
let mut placed = None;
let mut placed_clip = None;
let mut created = Vec::new();
for part in parts {
let mut notes: Vec<MidiNote> = Vec::new();
Expand Down Expand Up @@ -342,14 +361,23 @@ impl Session {
meter.bar_start(bar + 1)
};
let length = (bar_end - at).max(MusicalTime::from_quarters(1.0));
let track_id: TrackId = p.ids.allocate();
let color = TrackColor::palette(p.tracks.len() + created.len());
let track = Track::new(track_id, TrackKind::Instrument, part.name.clone(), color);
cmds.push(Command::AddTrack {
track: Box::new(track),
index,
});
index += 1;
let track_id: TrackId = match onto.take() {
Some(t) => {
placed = Some(t);
t
}
None => {
let id = p.ids.allocate();
let color = TrackColor::palette(p.tracks.len() + created.len());
let track = Track::new(id, TrackKind::Instrument, part.name.clone(), color);
cmds.push(Command::AddTrack {
track: Box::new(track),
index,
});
index += 1;
id
}
};
let clip_id: ClipId = p.ids.allocate();
cmds.push(Command::AddClip {
clip: Box::new(Clip {
Expand All @@ -376,12 +404,30 @@ impl Session {
}),
}),
});
created.push(track_id);
if placed == Some(track_id) {
placed_clip = Some(clip_id);
} else {
created.push(track_id);
}
}
self.batch("Import MIDI File", cmds)?;
// Dropped on the track the clip editor shows: it shows the new clip.
if let (Some(t), Some(clip)) = (placed, placed_clip)
&& self
.editor_clip()
.and_then(|c| self.project.clip(c))
.is_some_and(|c| c.track == t)
{
self.editor_clip = Some(clip);
self.selection.notes.clear();
}
let shown: Vec<TrackId> = placed.into_iter().chain(created.iter().copied()).collect();
self.selection
.select_tracks(&created, crate::SelectMode::Replace);
.select_tracks(&shown, crate::SelectMode::Replace);
let n = created.len();
if n == 0 {
return Ok(created);
}
let text = format!(
"imported {n} track{} from {} — choose an instrument for {}",
if n == 1 { "" } else { "s" },
Expand Down
53 changes: 53 additions & 0 deletions crates/faderframe-session/tests/midifile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -375,3 +375,56 @@ fn programs_poly_pressure_and_release_velocities_survive_import_and_export() {
};
assert_eq!(strip(&m2), strip(&m));
}

/// A file dropped on an instrument track lands on it (one part), not on a
/// new track; dropped on an audio track it gets its own.
#[test]
fn a_file_dropped_on_an_instrument_track_lands_on_it() {
let mut demo = Session::demo(EngineConfig::default()).unwrap();
let path = dir().join("dropped.mid");
let melody = demo
.project()
.clips
.values()
.find(|c| c.name == "Melody")
.unwrap()
.id;
demo.export_midi_file(&path, Some(&[melody])).unwrap();

let mut s = Session::demo(EngineConfig::default()).unwrap();
let kind_of = |s: &Session, kind| {
s.project()
.tracks
.iter()
.find(|t| t.kind == kind)
.unwrap()
.id
};
let (instrument, audio) = (
kind_of(&s, TrackKind::Instrument),
kind_of(&s, TrackKind::Audio),
);
let tracks = s.project().tracks.len();
let at = MusicalTime::from_quarters(64.0);
s.dispatch(Action::ImportFiles {
files: vec![path.clone()],
track: Some(instrument),
at,
})
.unwrap();
assert_eq!(s.project().tracks.len(), tracks, "no new track");
assert!(
s.project()
.clips_of(instrument)
.iter()
.any(|c| c.start == at && c.as_midi().is_some()),
"on the instrument track"
);
s.dispatch(Action::ImportFiles {
files: vec![path],
track: Some(audio),
at,
})
.unwrap();
assert_eq!(s.project().tracks.len(), tracks + 1, "a new track for it");
}
13 changes: 10 additions & 3 deletions crates/faderframe-view-arranger/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2839,8 +2839,10 @@ impl ArrangerView {
);
}

/// Where files dropped at `pos` go: an audio track under the pointer,
/// otherwise new tracks; time snapped to the grid.
/// Where files dropped at `pos` go: the audio, instrument or MIDI track
/// under the pointer (sounds land on an audio track, MIDI files on an
/// instrument or MIDI one, the rest on new tracks); time snapped to the
/// grid.
fn drop_target(
&self,
pos: Point,
Expand All @@ -2859,7 +2861,12 @@ impl ArrangerView {
let target = self
.row_at(pos.y)
.and_then(|i| tracks.get(i))
.filter(|t| t.kind == TrackKind::Audio)
.filter(|t| {
matches!(
t.kind,
TrackKind::Audio | TrackKind::Instrument | TrackKind::Midi
)
})
.map(|t| t.id);
Some((target, at))
}
Expand Down
60 changes: 60 additions & 0 deletions crates/faderframe-view-pianoroll/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -546,6 +546,27 @@ impl PianoRollView {
Some((id, clip, clip.as_midi()?))
}

/// Where files dropped at `pos` go: the shown clip's track, at the
/// time under the pointer (snapped to the grid); only on the notes.
fn file_drop(
&self,
pos: Point,
size: Size,
model: &Session,
) -> Option<(faderframe_core::TrackId, MusicalTime)> {
let (_, clip, _) = Self::clip(model)?;
if !self.layout(size).grid.contains(pos) {
return None;
}
let at = clip.start + self.time_at(pos.x).max(MusicalTime::ZERO);
let at = if model.editor.snap {
model.editor.snap(at, &model.project().timeline.meter)
} else {
model.on_sample(at)
};
Some((clip.track, at))
}

fn clamp_scroll(&mut self, size: Size, clip_len: MusicalTime) {
let g = self.layout(size).grid;
let max_y = (self.content_h() - g.h).max(0.0);
Expand Down Expand Up @@ -781,6 +802,45 @@ impl faderframe_ui_canvas::CanvasView<Session, faderframe_session::Action> for P
fn scroll_held(&mut self, _axis: faderframe_ui_canvas::ScrollAxis, held: bool) {
self.bar_held = held;
}

fn drag_files(&mut self, pos: Option<Point>, size: Size, model: &Session) -> bool {
pos.and_then(|p| self.file_drop(p, size, model)).is_some()
}

/// Files dropped on the notes go where the arranger puts files dropped
/// on the clip's track: a MIDI file becomes a clip there.
fn drop_files(
&mut self,
files: &[std::path::PathBuf],
pos: Point,
size: Size,
model: &Session,
) -> Option<faderframe_session::Action> {
let (track, at) = self.file_drop(pos, size, model)?;
Some(faderframe_session::Action::ImportFiles {
files: files.to_vec(),
track: Some(track),
at,
})
}

/// Files from the media browser, placed as on the arranger.
fn drop_payload(
&mut self,
payload: &str,
pos: Point,
size: Size,
model: &Session,
) -> Option<faderframe_session::Action> {
use faderframe_session::browser::{BrowserOp, parse_payload};
let files = parse_payload(payload)?;
let (track, at) = self.file_drop(pos, size, model)?;
Some(faderframe_session::Action::Browser(BrowserOp::Place {
files,
track: Some(track),
at,
}))
}
}

/// Values the expression lane shows (pitch: ±12 semitones; volume −24 to
Expand Down
Loading