FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
#171: files dropped onto the Timeline are placed there, not just imported
Mitcha0708ff24322
diff --git a/crates/engine/src/settings.rs b/crates/engine/src/settings.rsindex 1e0350358..d417298fb 100644--- a/crates/engine/src/settings.rs+++ b/crates/engine/src/settings.rs@@ -428,6 +428,8 @@ pub struct TimelinePrefs {pub match_frame_sets_in: bool,pub restore_open_sequences: bool,pub add_tracks_automatically: bool,+ /// Files dropped onto the Timeline are placed directly on it.+ pub drop_import_to_timeline: bool,}impl Default for TimelinePrefs {@@ -454,6 +456,7 @@ impl Default for TimelinePrefs {match_frame_sets_in: false,restore_open_sequences: true,add_tracks_automatically: true,+ drop_import_to_timeline: true,}}}@@ -1005,6 +1008,7 @@ static CATEGORIES: &[Category] = &[b("timeline.matchFrameSetsIn", "Match frame sets in point", false),b("timeline.restoreOpenSequences", "Restore open sequences when opening projects", false),b("timeline.addTracksAutomatically", "Add tracks automatically when editing source clips onto the Timeline", false),+ b("timeline.dropImportToTimeline", "Place files dropped onto the Timeline directly on the Timeline", true),],},Category {diff --git a/crates/engine/src/settings_tests.rs b/crates/engine/src/settings_tests.rsindex d706e4a19..1686bf57e 100644--- a/crates/engine/src/settings_tests.rs+++ b/crates/engine/src/settings_tests.rs@@ -551,3 +551,44 @@ fn hardware_decoding_setting_drives_the_decoder_switch() {assert!(filmcraft_codecs::hw::hardware_decoding());assert!(settings::field("playback.hardwareDecoding").is_some_and(|f| f.wired && matches!(f.kind, Kind::Choice(_))));}++/// Settings ▸ Timeline ▸ "Place files dropped onto the Timeline directly on the Timeline": on by default.+#[test]+fn drop_import_to_timeline_defaults_to_on() {+ assert!(settings::TimelinePrefs::default().drop_import_to_timeline);+ assert!(Preferences::default().timeline.drop_import_to_timeline);+}++/// The key is saved under `timeline.dropImportToTimeline`, read back by `prefs.get`, and persisted.+#[test]+fn drop_import_to_timeline_round_trips_through_prefs() {+ let dir = tmp_dir("drop-import-to-timeline");+ let path = dir.join("preferences.json");+ let mut s = Session { prefs_path: Some(path.clone()), ..Session::default() };+ set(&mut s, "timeline.dropImportToTimeline", json!(false));+ assert!(!s.prefs.timeline.drop_import_to_timeline);+ assert_eq!(s.execute("prefs.get", json!({"key": "timeline.dropImportToTimeline"})).unwrap(), json!(false));+ assert!(!Preferences::load(&path).timeline.drop_import_to_timeline);+ // a non-boolean is rejected and the stored value is kept+ assert!(s.execute("prefs.set", json!({"key": "timeline.dropImportToTimeline", "value": "no"})).is_err());+ assert!(!s.prefs.timeline.drop_import_to_timeline);+ std::fs::remove_dir_all(dir).unwrap();+}++/// Preferences files written before the key existed load it as on.+#[test]+fn drop_import_to_timeline_defaults_to_on_for_older_prefs() {+ assert!(serde_json::from_value::<settings::TimelinePrefs>(json!({})).unwrap().drop_import_to_timeline);+ let old = Preferences::from_value(json!({"version": 2, "timeline": {"stillImageDuration": 3}}));+ assert!(old.timeline.drop_import_to_timeline);+ assert_eq!(old.timeline.still_image_duration, 3.0);+}++/// The key is a Boolean field of the Timeline category in the settings registry.+#[test]+fn drop_import_to_timeline_is_in_the_settings_registry() {+ let (cat, f) = settings::fields().into_iter().find(|(_, f)| f.key == "timeline.dropImportToTimeline").expect("registry field");+ assert_eq!(cat, "timeline");+ assert!(matches!(f.kind, Kind::Bool));+ assert_eq!(settings::field("timeline.dropImportToTimeline").map(|f| f.key), Some("timeline.dropImportToTimeline"));+}diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsvindex a39dc82ea..d51f4cf74 100644--- a/crates/ui-egui/src/i18n/es.tsv+++ b/crates/ui-egui/src/i18n/es.tsv@@ -1251,6 +1251,7 @@Active Monitor Monitor activoAdd AñadirAdd tracks automatically when editing source clips onto the Timeline Añadir pistas automáticamente al editar clips de origen en la línea de tiempo+ Place files dropped onto the Timeline directly on the Timeline Colocar los archivos soltados en la línea de tiempo directamente en ellaAdditional Scale Escala adicionalAdditive Dissolve Disolución aditivaAdditive Dissolve (Legacy) Disolución aditiva (heredada)diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 83d18261e..b846cc991 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -266,6 +266,8 @@ pub struct FilmcraftApp {/// The sequence whose view `ui.timeline` holds, and that view as it was last exchanged with/// `session.state.timeline_views` (see `sync_timeline_view`).timeline_view_of: Option<filmcraft_engine::project::ItemId>,+ /// Items imported by an OS file drop, to place on the Timeline at the drop point this frame.+ pending_timeline_drop: Option<(Vec<filmcraft_engine::project::ItemId>, egui::Pos2)>,timeline_view_last: Option<filmcraft_engine::project::SequenceView>,pub fps: f32,last_time: f64,@@ -453,6 +455,7 @@ impl FilmcraftApp {integrated_titlebar: false,last_timeline_width: 1000.0,timeline_view_of: None,+ pending_timeline_drop: None,timeline_view_last: None,fps: 60.0,last_time: 0.0,@@ -1126,7 +1129,8 @@ impl FilmcraftApp {r}- /// Import dropped files.+ /// Import dropped files. With Timeline ▸ drop imports to the timeline, the new items are also+ /// queued to be placed at the pointer (see `timeline::interact`).fn handle_drops(&mut self, ctx: &egui::Context) {let dropped = ctx.input(|i| i.raw.dropped_files.clone());let mut paths = Vec::new();@@ -1137,7 +1141,18 @@ impl FilmcraftApp {}}if !paths.is_empty() {- let _ = self.session.execute("file.import", json!({"paths": paths, "bin": self.import_bin().0}));+ let pointer = ctx.input(|i| i.pointer.hover_pos().or(i.pointer.latest_pos()));+ let imported = self.session.execute("file.import", json!({"paths": paths, "bin": self.import_bin().0}));+ if let Ok(v) = imported+ && let Some(pos) = pointer+ && self.session.prefs.timeline.drop_import_to_timeline+ {+ let items: Vec<filmcraft_engine::project::ItemId> =+ v["items"].as_array().map(|a| a.iter().filter_map(|i| i.as_u64()).map(filmcraft_engine::project::ItemId).collect()).unwrap_or_default();+ if !items.is_empty() {+ self.pending_timeline_drop = Some((items, pos));+ }+ }}}@@ -1366,6 +1381,8 @@ impl FilmcraftApp {state::Mode::Import => panels::import_mode::show(self, ui, body),state::Mode::Export => panels::export_mode::show(self, ui, body),}+ // the Timeline has had its chance to place a file drop this frame; anything left stays a bin import+ self.pending_timeline_drop = None;panels::dialogs::show(self, &ctx);if !self.ui.show_status_bar {// no bar to draw the job in, but a finished preview render still playsdiff --git a/crates/ui-egui/src/panels/timeline.rs b/crates/ui-egui/src/panels/timeline.rsindex 811a75eea..6c6494710 100644--- a/crates/ui-egui/src/panels/timeline.rs+++ b/crates/ui-egui/src/panels/timeline.rs@@ -2186,9 +2186,50 @@ fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &}}}+ // ---- OS file drops imported with "drop imports to the timeline": placed at the drop point, one after another+ if let Some((items, p)) = app.pending_timeline_drop.clone()+ && layout.content.contains(p)+ {+ app.pending_timeline_drop = None;+ let row = layout.row_at(p.y).cloned().or_else(|| layout.rows.iter().find(|r| r.kind == TrackKind::Video).cloned());+ if let Some(row) = row {+ let (vt, at) = match row.kind {+ TrackKind::Video => (Some(row.track.0), seq.audio_tracks.get(row.index).or(seq.audio_tracks.first()).map(|t| t.id.0)),+ TrackKind::Audio => (seq.video_tracks.get(row.index).or(seq.video_tracks.first()).map(|t| t.id.0), Some(row.track.0)),+ };+ let still = app.session.prefs.timeline.still_duration(rate);+ let durations: Vec<Tick> = items+ .iter()+ .map(|&item| {+ let is_still = app.session.project.item(item).and_then(|i| i.as_media()).is_some_and(|m| m.info.kind == filmcraft_media::MediaKind::Still);+ app.session.project.item(item).map(|i| i.duration()).filter(|d| d.0 > 0 && !is_still).unwrap_or(still)+ })+ .collect();+ let start = snap(app, seq, layout, rate.snap_nearest(layout.tick_at(p.x).max(Tick::ZERO)), &[]);+ for (item, t) in items.iter().zip(chain_starts(start, &durations)) {+ let params = json!({"item": item.0, "track": vt, "audioTrack": at, "time": t.0, "insert": false});+ if let Err(e) = app.session.execute("timeline.place", params) {+ app.ui.status = e.to_string();+ }+ }+ }+ }app.auto.add("timeline.tracks", layout.content, "tracks");}+/// Start tick of each clip when the clips are laid end to end from `start`. Saturates rather than overflows.+pub(crate) fn chain_starts(start: Tick, durations: &[Tick]) -> Vec<Tick> {+ let mut t = start;+ durations+ .iter()+ .map(|d| {+ let at = t;+ t = Tick(t.0.saturating_add(d.0.max(0)));+ at+ })+ .collect()+}+#[cfg(test)]mod waveform_tests {use super::waveform_display_gain;@@ -2211,3 +2252,41 @@ mod waveform_tests {assert!((db(waveform_display_gain(1.0, -6.0)) - (-6.0)).abs() < 0.1);}}++#[cfg(test)]+mod chain_starts_tests {+ use super::chain_starts;+ use filmcraft_time::Tick;++ #[test]+ fn empty_list_has_no_starts() {+ assert!(chain_starts(Tick(100), &[]).is_empty());+ }++ #[test]+ fn one_clip_starts_at_the_drop_point() {+ assert_eq!(chain_starts(Tick(7), &[Tick(30)]), vec![Tick(7)]);+ }++ #[test]+ fn several_clips_are_laid_end_to_end() {+ let durations = [Tick(10), Tick(25), Tick(5)];+ assert_eq!(chain_starts(Tick(100), &durations), vec![Tick(100), Tick(110), Tick(135)]);+ }++ #[test]+ fn start_near_i64_max_saturates_without_panicking() {+ let starts = chain_starts(Tick(i64::MAX - 5), &[Tick(10), Tick(10), Tick(10)]);+ assert_eq!(starts, vec![Tick(i64::MAX - 5), Tick(i64::MAX), Tick(i64::MAX)]);+ }++ #[test]+ fn zero_length_clips_share_one_start() {+ assert_eq!(chain_starts(Tick(42), &[Tick(0), Tick(0), Tick(9)]), vec![Tick(42), Tick(42), Tick(42)]);+ }++ #[test]+ fn negative_durations_count_as_zero() {+ assert_eq!(chain_starts(Tick(5), &[Tick(-3), Tick(4)]), vec![Tick(5), Tick(5)]);+ }+}diff --git a/crates/ui-egui/tests/timeline_drop_ui.rs b/crates/ui-egui/tests/timeline_drop_ui.rsnew file mode 100644index 000000000..76bdde9fa--- /dev/null+++ b/crates/ui-egui/tests/timeline_drop_ui.rs@@ -0,0 +1,154 @@+//! Files dropped from the OS onto the Timeline. With Preferences ▸ Timeline ▸ "Place files dropped+//! onto the Timeline directly on the Timeline" (`drop_import_to_timeline`) they are also placed at+//! the pointer; with it off they are only imported to the bin.++use std::path::{Path, PathBuf};++use egui_kittest::Harness;+use filmcraft_engine::Session;+use filmcraft_ui_egui::FilmcraftApp;+use serde_json::json;++fn step(h: &mut Harness<'static, FilmcraftApp>) {+ let ctx = h.ctx.clone();+ let mut raw = std::mem::take(h.input_mut());+ eframe::App::raw_input_hook(h.state_mut(), &ctx, &mut raw);+ *h.input_mut() = raw;+ ctx.request_repaint();+ h.step();+}++fn harness() -> Harness<'static, FilmcraftApp> {+ let mut s = Session::default();+ s.execute("file.openDemoProject", json!({})).unwrap();+ s.execute("file.newSequence", json!({"name":"Drop test","width":1280,"height":720,"fps":24})).unwrap();+ let mut h = Harness::builder().with_size(egui::vec2(1600.0, 980.0)).build_eframe(move |_cc| FilmcraftApp::new(s));+ for _ in 0..4 {+ step(&mut h);+ }+ h+}++fn pointer_to(h: &mut Harness<'static, FilmcraftApp>, pos: egui::Pos2) {+ h.input_mut().events.push(egui::Event::PointerMoved(pos));+ step(h);+}++fn control_rect(h: &Harness<'static, FilmcraftApp>, id: &str) -> egui::Rect {+ let [x, y, w, height] = h.state().auto.elements.iter().find(|e| e.id == id).or_else(|| h.state().auto.find(id)).unwrap().rect;+ egui::Rect::from_min_size(egui::pos2(x, y), egui::vec2(w, height))+}++/// A point 60 px into the Timeline's clip area on the named track row.+fn point_on_row(h: &Harness<'static, FilmcraftApp>, row_control: &str) -> egui::Pos2 {+ let row = control_rect(h, row_control);+ let panel = control_rect(h, "panel.Timeline");+ egui::pos2(panel.min.x + h.state().ui.timeline.header_w + 60.0, row.center().y)+}++/// A file the OS dropped on the window, as the native integration hands it to egui.+#[derive(Debug)]+struct OsFile(PathBuf);++impl egui::DroppedFile for OsFile {+ fn path(&self) -> &Path {+ &self.0+ }++ fn bytes(&self) -> Result<Vec<u8>, String> {+ std::fs::read(&self.0).map_err(|e| e.to_string())+ }+}++/// Drops `path` with the pointer over `row_control`, as the OS does: the pointer is hovering first,+/// then one frame carries the dropped file. The file is cleared afterwards, as egui only reports it once.+fn drop_on_row(h: &mut Harness<'static, FilmcraftApp>, row_control: &str, path: &Path) {+ let at = point_on_row(h, row_control);+ pointer_to(h, at);+ h.input_mut().dropped_files.push(std::sync::Arc::new(OsFile(path.to_path_buf())));+ step(h);+ h.input_mut().dropped_files.clear();+ step(h);+}++/// (video clips, audio clips) on the active sequence.+fn clip_counts(h: &Harness<'static, FilmcraftApp>) -> (usize, usize) {+ let q = h.state().session.active_sequence().unwrap();+ (q.video_tracks.iter().map(|t| t.items.len()).sum(), q.audio_tracks.iter().map(|t| t.items.len()).sum())+}++fn fixture(name: &str) -> PathBuf {+ let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/fixtures/ui-egui");+ std::fs::create_dir_all(&dir).unwrap();+ dir.join(name)+}++/// A small generated PNG still.+fn still(name: &str) -> PathBuf {+ let p = fixture(name);+ image::RgbaImage::from_pixel(64, 36, image::Rgba([40, 140, 220, 255])).save(&p).unwrap();+ p+}++/// A 0.5 s mono 48 kHz 16-bit WAV tone (audio only).+fn tone(name: &str) -> PathBuf {+ let p = fixture(name);+ let rate = 48_000u32;+ let n = rate / 2;+ let mut data = Vec::with_capacity(n as usize * 2);+ for i in 0..n {+ let s = (f32::sin(2.0 * std::f32::consts::PI * 440.0 * i as f32 / rate as f32) * 0.5 * i16::MAX as f32) as i16;+ data.extend_from_slice(&s.to_le_bytes());+ }+ let mut wav = Vec::with_capacity(44 + data.len());+ wav.extend_from_slice(b"RIFF");+ wav.extend_from_slice(&(36 + data.len() as u32).to_le_bytes());+ wav.extend_from_slice(b"WAVEfmt ");+ wav.extend_from_slice(&16u32.to_le_bytes());+ wav.extend_from_slice(&1u16.to_le_bytes()); // PCM+ wav.extend_from_slice(&1u16.to_le_bytes()); // mono+ wav.extend_from_slice(&rate.to_le_bytes());+ wav.extend_from_slice(&(rate * 2).to_le_bytes());+ wav.extend_from_slice(&2u16.to_le_bytes());+ wav.extend_from_slice(&16u16.to_le_bytes());+ wav.extend_from_slice(b"data");+ wav.extend_from_slice(&(data.len() as u32).to_le_bytes());+ wav.extend_from_slice(&data);+ std::fs::write(&p, wav).unwrap();+ p+}++#[test]+fn still_dropped_on_the_video_row_is_placed_at_the_pointer() {+ let mut h = harness();+ let items_before = h.state().session.project.items.len();+ drop_on_row(&mut h, "timeline.track.V1.target", &still("drop_still_video_row.png"));+ assert_eq!(h.state().session.project.items.len(), items_before + 1, "the still is imported to the bin");+ assert_eq!(clip_counts(&h), (1, 0), "status: {}", h.state().ui.status);+}++#[test]+fn still_dropped_on_an_audio_row_goes_to_the_video_track_without_error() {+ // a video-only item over an audio row: the picture takes the matching video track, no error+ let mut h = harness();+ drop_on_row(&mut h, "timeline.track.A1.target", &still("drop_still_audio_row.png"));+ assert_eq!(clip_counts(&h), (1, 0), "status: {}", h.state().ui.status);+}++#[test]+fn tone_dropped_on_a_video_row_goes_to_the_audio_track_without_error() {+ // an audio-only item over a video row: the sound takes the matching audio track, no error+ let mut h = harness();+ drop_on_row(&mut h, "timeline.track.V1.target", &tone("drop_tone_video_row.wav"));+ assert_eq!(clip_counts(&h), (0, 1), "status: {}", h.state().ui.status);+}++#[test]+fn with_drop_import_off_the_file_is_only_imported() {+ let mut h = harness();+ h.state_mut().session.prefs.timeline.drop_import_to_timeline = false;+ let items_before = h.state().session.project.items.len();+ drop_on_row(&mut h, "timeline.track.V1.target", &still("drop_still_pref_off.png"));+ assert_eq!(h.state().session.project.items.len(), items_before + 1, "the still is imported to the bin");+ assert_eq!(clip_counts(&h), (0, 0), "status: {}", h.state().ui.status);+}