Skip to main content

egui_pop_views/timeline/
tracks.rs

1//! Tracks and clips: rows under a timeline's ruler, each holding clips (a
2//! start, a length, an offset into a source), and how an application draws
3//! them ([`ClipPainter`]). The model is plain data, without egui's input:
4//! adding, moving, trimming and removing clips, never overlapping on a
5//! track and kept inside the timeline's bounds.
6
7use egui::{Color32, FontId, Painter, Rect, pos2};
8use serde::{Deserialize, Serialize};
9
10use super::Lanes;
11use super::scale::TimeScale;
12use super::state::{Edit, TimelineState};
13use super::tokens::TimelineTokens;
14
15/// Two times this close are the same (seconds): clips touching end to start
16/// do not overlap.
17const EPSILON: f64 = 1e-9;
18
19/// A piece of a source placed on a track: from `start`, `length` long, the
20/// source read from `offset` (all in seconds). A video's shot, a sample, a
21/// span of recorded data.
22#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
23pub struct Clip {
24    /// Unique among all the clips of its timeline.
25    pub id: u64,
26    pub start: f64,
27    pub length: f64,
28    /// Where in its source it starts (seconds into the source).
29    #[serde(default)]
30    pub offset: f64,
31    #[serde(default)]
32    pub label: String,
33    /// What it plays, for the application and its painter: a file, a
34    /// sample's name, a stream. The timeline does not read it.
35    #[serde(default)]
36    pub source: String,
37    /// How long its source is: trimming stops at its ends. `None`: a source
38    /// without an end (a still, a generator).
39    #[serde(default)]
40    pub source_length: Option<f64>,
41    /// Its own colour; the theme's (`timeline.clip.fill`) when `None`.
42    #[serde(default)]
43    pub color: Option<Color32>,
44}
45
46impl Clip {
47    pub fn new(id: u64, start: f64, length: f64, label: impl Into<String>) -> Self {
48        Self {
49            id,
50            start,
51            length,
52            offset: 0.0,
53            label: label.into(),
54            source: String::new(),
55            source_length: None,
56            color: None,
57        }
58    }
59
60    /// Reads its source from `offset` seconds in.
61    pub fn offset(mut self, offset: f64) -> Self {
62        self.offset = offset;
63        self
64    }
65
66    pub fn source(mut self, source: impl Into<String>) -> Self {
67        self.source = source.into();
68        self
69    }
70
71    /// Its source lasts `length` seconds: trimming stops at its ends.
72    pub fn source_length(mut self, length: f64) -> Self {
73        self.source_length = Some(length);
74        self
75    }
76
77    pub fn color(mut self, color: Color32) -> Self {
78        self.color = Some(color);
79        self
80    }
81
82    pub fn end(&self) -> f64 {
83        self.start + self.length
84    }
85
86    /// Whether `time` is on it (its start included, its end not).
87    pub fn contains(&self, time: f64) -> bool {
88        time >= self.start && time < self.end()
89    }
90
91    /// The source's time playing at the timeline's `time`.
92    pub fn source_at(&self, time: f64) -> f64 {
93        self.offset + (time - self.start)
94    }
95
96    /// The timeline's time at which the source's `source_time` plays.
97    pub fn time_of(&self, source_time: f64) -> f64 {
98        self.start + (source_time - self.offset)
99    }
100
101    /// Its span: start, length, offset.
102    pub fn span(&self) -> ClipSpan {
103        ClipSpan {
104            start: self.start,
105            length: self.length,
106            offset: self.offset,
107        }
108    }
109}
110
111/// A row of clips under the ruler.
112#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
113pub struct Track {
114    /// Unique among its timeline's tracks.
115    pub id: u64,
116    pub name: String,
117    /// What its clips are, for the application's painter (`video`, `audio`,
118    /// `data`...). The timeline does not read it.
119    #[serde(default)]
120    pub kind: String,
121    /// Its height in points; the timeline's (`Timeline::track_height`) when
122    /// `None`.
123    #[serde(default)]
124    pub height: Option<f32>,
125    /// In time order, never overlapping.
126    #[serde(default)]
127    pub clips: Vec<Clip>,
128}
129
130impl Track {
131    pub fn new(id: u64, name: impl Into<String>) -> Self {
132        Self {
133            id,
134            name: name.into(),
135            ..Self::default()
136        }
137    }
138
139    pub fn kind(mut self, kind: impl Into<String>) -> Self {
140        self.kind = kind.into();
141        self
142    }
143
144    pub fn height(mut self, height: f32) -> Self {
145        self.height = Some(height);
146        self
147    }
148
149    fn sort(&mut self) {
150        self.clips
151            .sort_by(|a, b| a.start.total_cmp(&b.start).then(a.id.cmp(&b.id)));
152    }
153}
154
155/// Which end of a clip a trim moves.
156#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
157#[serde(rename_all = "snake_case")]
158pub enum ClipEdge {
159    Start,
160    End,
161}
162
163/// Where a clip is: its track and its start.
164#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
165pub struct ClipPlace {
166    pub track: u64,
167    pub start: f64,
168}
169
170/// What a trim changes: a clip's start, length and offset.
171#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
172pub struct ClipSpan {
173    pub start: f64,
174    pub length: f64,
175    pub offset: f64,
176}
177
178/// A clip to move: to `track`, starting at `start`.
179#[derive(Clone, Copy, Debug, PartialEq)]
180pub struct ClipMove {
181    pub id: u64,
182    pub track: u64,
183    pub start: f64,
184}
185
186/// Why a change of the clips was refused.
187#[derive(Clone, Debug, PartialEq)]
188pub enum ClipError {
189    NoTrack(u64),
190    NoClip(u64),
191    /// It would overlap this clip.
192    Overlaps(u64),
193    /// Outside the timeline's bounds.
194    OutOfBounds,
195    /// Not a length a clip can have.
196    BadLength,
197}
198
199impl std::fmt::Display for ClipError {
200    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
201        match self {
202            ClipError::NoTrack(id) => write!(f, "no track {id}"),
203            ClipError::NoClip(id) => write!(f, "no clip {id}"),
204            ClipError::Overlaps(id) => write!(f, "it would overlap clip {id}"),
205            ClipError::OutOfBounds => write!(f, "outside the timeline's bounds"),
206            ClipError::BadLength => write!(f, "a clip's length is a positive number"),
207        }
208    }
209}
210
211impl std::error::Error for ClipError {}
212
213/// A clip being moved, as it was when the move began.
214#[derive(Clone, Copy, Debug, PartialEq)]
215pub(super) struct Origin {
216    pub id: u64,
217    /// Its track's index.
218    pub row: usize,
219    pub start: f64,
220    pub length: f64,
221}
222
223impl TimelineState {
224    pub fn track(&self, id: u64) -> Option<&Track> {
225        self.tracks.iter().find(|t| t.id == id)
226    }
227
228    pub fn track_mut(&mut self, id: u64) -> Option<&mut Track> {
229        self.tracks.iter_mut().find(|t| t.id == id)
230    }
231
232    /// Adds a track below the others (its id taken if free, else the next
233    /// one); returns the id.
234    pub fn add_track(&mut self, mut track: Track) -> u64 {
235        if track.id == 0 || self.track(track.id).is_some() {
236            track.id = self.tracks.iter().map(|t| t.id).max().map_or(1, |m| m + 1);
237        }
238        track.sort();
239        let id = track.id;
240        self.tracks.push(track);
241        id
242    }
243
244    /// Where clip `id` is: its track's index and its own in the track.
245    pub(super) fn locate(&self, id: u64) -> Option<(usize, usize)> {
246        self.tracks
247            .iter()
248            .enumerate()
249            .find_map(|(row, t)| t.clips.iter().position(|c| c.id == id).map(|at| (row, at)))
250    }
251
252    pub fn clip(&self, id: u64) -> Option<&Clip> {
253        let (row, at) = self.locate(id)?;
254        Some(&self.tracks[row].clips[at])
255    }
256
257    /// The track clip `id` is on.
258    pub fn clip_track(&self, id: u64) -> Option<&Track> {
259        self.locate(id).map(|(row, _)| &self.tracks[row])
260    }
261
262    /// Every clip with its track, track by track.
263    pub fn clips(&self) -> impl Iterator<Item = (&Track, &Clip)> {
264        self.tracks
265            .iter()
266            .flat_map(|t| t.clips.iter().map(move |c| (t, c)))
267    }
268
269    /// The id the next clip takes.
270    pub fn next_clip_id(&self) -> u64 {
271        self.clips().map(|(_, c)| c.id).max().map_or(1, |m| m + 1)
272    }
273
274    /// The shortest a clip can be: a frame, else the ruler's finest step.
275    pub fn min_clip_length(&self) -> f64 {
276        match self.scale {
277            TimeScale::Frames(r) => r.frame(),
278            s => s.steps().first().copied().unwrap_or(0.001),
279        }
280    }
281
282    /// The clip on track `row` that `start..end` would overlap, besides the
283    /// clips of `skip`.
284    fn overlap(&self, row: usize, start: f64, end: f64, skip: &[u64]) -> Option<u64> {
285        self.tracks[row]
286            .clips
287            .iter()
288            .filter(|c| !skip.contains(&c.id))
289            .find(|c| start < c.end() - EPSILON && c.start < end - EPSILON)
290            .map(|c| c.id)
291    }
292
293    fn in_bounds(&self, start: f64, end: f64) -> bool {
294        self.bounds
295            .is_none_or(|b| start >= b.start - EPSILON && end <= b.end + EPSILON)
296    }
297
298    /// Adds `clip` to track `track` (its id taken if free, else the next
299    /// one), on the scale's units: refused where it would overlap a clip or
300    /// leave the bounds. Returns the id.
301    pub fn add_clip(&mut self, track: u64, mut clip: Clip) -> Result<u64, ClipError> {
302        let row = self
303            .tracks
304            .iter()
305            .position(|t| t.id == track)
306            .ok_or(ClipError::NoTrack(track))?;
307        if !clip.length.is_finite() || clip.length <= 0.0 || !clip.start.is_finite() {
308            return Err(ClipError::BadLength);
309        }
310        clip.start = self.scale.quantize(clip.start);
311        clip.length = self.scale.quantize(clip.length).max(self.min_clip_length());
312        clip.offset = self.scale.quantize(clip.offset.max(0.0));
313        if !self.in_bounds(clip.start, clip.end()) {
314            return Err(ClipError::OutOfBounds);
315        }
316        if let Some(other) = self.overlap(row, clip.start, clip.end(), &[]) {
317            return Err(ClipError::Overlaps(other));
318        }
319        if clip.id == 0 || self.clip(clip.id).is_some() {
320            clip.id = self.next_clip_id();
321        }
322        let id = clip.id;
323        let t = &mut self.tracks[row];
324        t.clips.push(clip);
325        t.sort();
326        Ok(id)
327    }
328
329    /// Moves clips at once, each to its track and start (on the scale's
330    /// units): refused, nothing moved, where one would overlap a clip or
331    /// leave the bounds. The edits, one per clip that moved.
332    pub fn move_clips(&mut self, moves: &[ClipMove]) -> Result<Vec<Edit>, ClipError> {
333        let mut placed: Vec<(usize, u64, f64, f64)> = Vec::new();
334        let ids: Vec<u64> = moves.iter().map(|m| m.id).collect();
335        for m in moves {
336            let (row, at) = self.locate(m.id).ok_or(ClipError::NoClip(m.id))?;
337            let length = self.tracks[row].clips[at].length;
338            let to = self
339                .tracks
340                .iter()
341                .position(|t| t.id == m.track)
342                .ok_or(ClipError::NoTrack(m.track))?;
343            let start = self.scale.quantize(m.start);
344            if !start.is_finite() || !self.in_bounds(start, start + length) {
345                return Err(ClipError::OutOfBounds);
346            }
347            if let Some(other) = self.overlap(to, start, start + length, &ids) {
348                return Err(ClipError::Overlaps(other));
349            }
350            // Nor over one another.
351            if let Some(&(_, other, ..)) = placed.iter().find(|(r, _, s, l)| {
352                *r == to && start < s + l - EPSILON && *s < start + length - EPSILON
353            }) {
354                return Err(ClipError::Overlaps(other));
355            }
356            placed.push((to, m.id, start, length));
357        }
358        let mut edits = Vec::new();
359        for (to, id, start, _) in placed {
360            if let Some((from, place)) = self.place(id, to, start)
361                && from != place
362            {
363                edits.push(Edit::ClipMoved {
364                    id,
365                    from,
366                    to: place,
367                });
368            }
369        }
370        Ok(edits)
371    }
372
373    /// Puts clip `id` on track `row` at `start`, unchecked: where it was
374    /// and where it is.
375    pub(super) fn place(
376        &mut self,
377        id: u64,
378        row: usize,
379        start: f64,
380    ) -> Option<(ClipPlace, ClipPlace)> {
381        let (from_row, at) = self.locate(id)?;
382        let from = ClipPlace {
383            track: self.tracks[from_row].id,
384            start: self.tracks[from_row].clips[at].start,
385        };
386        let mut clip = self.tracks[from_row].clips.remove(at);
387        clip.start = start;
388        let track = self.tracks.get_mut(row)?;
389        let to = ClipPlace {
390            track: track.id,
391            start,
392        };
393        track.clips.push(clip);
394        track.sort();
395        Some((from, to))
396    }
397
398    /// Moves clip `id`'s `edge` to `time`, kept on its source (never before
399    /// its start nor past its end), off its neighbours, inside the bounds,
400    /// and at least [`min_clip_length`](Self::min_clip_length) long. Its
401    /// span before.
402    pub fn trim_clip(&mut self, id: u64, edge: ClipEdge, time: f64) -> Result<ClipSpan, ClipError> {
403        let (row, at) = self.locate(id).ok_or(ClipError::NoClip(id))?;
404        if !time.is_finite() {
405            return Err(ClipError::OutOfBounds);
406        }
407        let min = self.min_clip_length();
408        let clips = &self.tracks[row].clips;
409        let c = &clips[at];
410        let before = c.span();
411        let (prev_end, next_start) = (
412            at.checked_sub(1).map(|i| clips[i].end()),
413            clips.get(at + 1).map(|n| n.start),
414        );
415        let t = self.scale.quantize(time);
416        let bounds = self.bounds;
417        let c = &mut self.tracks[row].clips[at];
418        match edge {
419            ClipEdge::Start => {
420                let end = c.end();
421                let mut lo = c.start - c.offset;
422                if let Some(p) = prev_end {
423                    lo = lo.max(p);
424                }
425                if let Some(b) = bounds {
426                    lo = lo.max(b.start);
427                }
428                let start = t.max(lo).min(end - min);
429                c.offset += start - c.start;
430                c.start = start;
431                c.length = end - start;
432            }
433            ClipEdge::End => {
434                let mut hi = f64::INFINITY;
435                if let Some(n) = next_start {
436                    hi = hi.min(n);
437                }
438                if let Some(b) = bounds {
439                    hi = hi.min(b.end);
440                }
441                if let Some(s) = c.source_length {
442                    hi = hi.min(c.start + (s - c.offset));
443                }
444                let end = t.min(hi).max(c.start + min);
445                c.length = end - c.start;
446            }
447        }
448        Ok(before)
449    }
450
451    /// Splits clip `id` at `time` (on the scale's units) into two clips
452    /// touching there: the clip keeps its id and ends at `time`, the new
453    /// one (the next id) starts there, reading its source on from where
454    /// the first stops. Refused unless both parts are at least
455    /// [`min_clip_length`](Self::min_clip_length) long. The new clip's id.
456    pub fn split_clip(&mut self, id: u64, time: f64) -> Result<u64, ClipError> {
457        let (row, at) = self.locate(id).ok_or(ClipError::NoClip(id))?;
458        let t = self.scale.quantize(time);
459        let min = self.min_clip_length();
460        let next = self.next_clip_id();
461        let c = &mut self.tracks[row].clips[at];
462        if !t.is_finite() || t < c.start + min - EPSILON || t > c.end() - min + EPSILON {
463            return Err(ClipError::BadLength);
464        }
465        let mut second = c.clone();
466        second.id = next;
467        second.start = t;
468        second.length = c.end() - t;
469        second.offset = c.offset + (t - c.start);
470        c.length = t - c.start;
471        let track = &mut self.tracks[row];
472        track.clips.push(second);
473        track.sort();
474        Ok(next)
475    }
476
477    /// Removes clips and closes the gaps they leave: on each track, the
478    /// clips after a removed one move back by its length. The clips
479    /// removed (each with its track's id), and an edit per clip moved.
480    pub fn ripple_remove_clips(&mut self, ids: &[u64]) -> (Vec<(u64, Clip)>, Vec<Edit>) {
481        let removed = self.remove_clips(ids);
482        let before: Vec<(u64, ClipPlace)> = self
483            .tracks
484            .iter()
485            .flat_map(|t| {
486                t.clips.iter().map(|c| {
487                    let place = ClipPlace {
488                        track: t.id,
489                        start: c.start,
490                    };
491                    (c.id, place)
492                })
493            })
494            .collect();
495        // The last gap first, so that the ones before still see the clips
496        // after them where they were.
497        let mut gaps: Vec<&(u64, Clip)> = removed.iter().collect();
498        gaps.sort_by(|a, b| b.1.start.total_cmp(&a.1.start));
499        for (track, gone) in gaps {
500            if let Some(t) = self.tracks.iter_mut().find(|t| t.id == *track) {
501                for c in &mut t.clips {
502                    if c.start >= gone.end() - EPSILON {
503                        c.start = self.scale.quantize((c.start - gone.length).max(gone.start));
504                    }
505                }
506                t.sort();
507            }
508        }
509        let mut moved = Vec::new();
510        for (id, from) in before {
511            if let Some(c) = self.clip(id)
512                && c.start != from.start
513            {
514                let to = ClipPlace {
515                    track: from.track,
516                    start: c.start,
517                };
518                moved.push(Edit::ClipMoved { id, from, to });
519            }
520        }
521        (removed, moved)
522    }
523
524    /// Removes clips: those removed, each with its track's id.
525    pub fn remove_clips(&mut self, ids: &[u64]) -> Vec<(u64, Clip)> {
526        let mut removed = Vec::new();
527        for id in ids {
528            if let Some((row, at)) = self.locate(*id) {
529                removed.push((self.tracks[row].id, self.tracks[row].clips.remove(at)));
530            }
531        }
532        self.selected_clips.retain(|id| !ids.contains(id));
533        removed
534    }
535
536    /// The clips selected that still exist, the selection kept in order.
537    pub(super) fn prune_selection(&mut self) {
538        let alive: Vec<u64> = self
539            .selected_clips
540            .iter()
541            .copied()
542            .filter(|id| self.locate(*id).is_some())
543            .collect();
544        self.selected_clips = alive;
545    }
546
547    /// The shift nearest `dt` (seconds) by which the clips of `origin`,
548    /// `drow` tracks down, fit: off the other clips and inside the bounds.
549    /// `None` when no shift fits.
550    pub(super) fn fit_shift(&self, origin: &[Origin], dt: f64, drow: isize) -> Option<f64> {
551        let ids: Vec<u64> = origin.iter().map(|o| o.id).collect();
552        let rows = self.tracks.len() as isize;
553        let target = |o: &Origin| {
554            let r = o.row as isize + drow;
555            (0..rows).contains(&r).then_some(r as usize)
556        };
557        if origin.iter().any(|o| target(o).is_none()) {
558            return None;
559        }
560        let fits = |d: f64| {
561            origin.iter().all(|o| {
562                let s = o.start + d;
563                let row = target(o).unwrap_or(0);
564                self.in_bounds(s, s + o.length)
565                    && self.overlap(row, s, s + o.length, &ids).is_none()
566            })
567        };
568        if fits(dt) {
569            return Some(dt);
570        }
571        // Against an edge: of another clip, or of the bounds.
572        let mut candidates = Vec::new();
573        for o in origin {
574            let row = target(o).unwrap_or(0);
575            for c in self.tracks[row]
576                .clips
577                .iter()
578                .filter(|c| !ids.contains(&c.id))
579            {
580                candidates.push(c.end() - o.start);
581                candidates.push(c.start - (o.start + o.length));
582            }
583            if let Some(b) = self.bounds {
584                candidates.push(b.start - o.start);
585                candidates.push(b.end - (o.start + o.length));
586            }
587        }
588        candidates
589            .into_iter()
590            .filter(|d| d.is_finite() && fits(*d))
591            .min_by(|a, b| (a - dt).abs().total_cmp(&(b - dt).abs()))
592    }
593
594    /// The clip after (`forward`) or before the one selected last, on its
595    /// track; with none selected, the first after the playhead (or the last
596    /// before it) on the first track holding clips.
597    pub fn neighbour_clip(&self, forward: bool) -> Option<u64> {
598        if let Some((row, at)) = self.selected_clips.last().and_then(|id| self.locate(*id)) {
599            let clips = &self.tracks[row].clips;
600            return if forward {
601                clips.get(at + 1).map(|c| c.id)
602            } else {
603                at.checked_sub(1).map(|i| clips[i].id)
604            };
605        }
606        let t = self.tracks.iter().find(|t| !t.clips.is_empty())?;
607        let p = self.playhead;
608        if forward {
609            t.clips
610                .iter()
611                .find(|c| c.start >= p - EPSILON)
612                .map(|c| c.id)
613        } else {
614            t.clips
615                .iter()
616                .rev()
617                .find(|c| c.end() <= p + EPSILON)
618                .map(|c| c.id)
619        }
620    }
621
622    /// The clip under the playhead (else the nearest to it) on the next
623    /// track holding clips above (`up`) or below the selected clip's track
624    /// (with none selected, from the last or the first track).
625    pub fn clip_across(&self, up: bool) -> Option<u64> {
626        let rows = self.tracks.len();
627        let from = self
628            .selected_clips
629            .last()
630            .and_then(|id| self.locate(*id))
631            .map(|(row, _)| row);
632        let order: Vec<usize> = match (from, up) {
633            (Some(r), true) => (0..r).rev().collect(),
634            (Some(r), false) => (r + 1..rows).collect(),
635            (None, true) => (0..rows).rev().collect(),
636            (None, false) => (0..rows).collect(),
637        };
638        let p = self.playhead;
639        let distance = |c: &Clip| {
640            if c.contains(p) {
641                0.0
642            } else {
643                (c.start - p).abs().min((c.end() - p).abs())
644            }
645        };
646        order.into_iter().find_map(|row| {
647            self.tracks[row]
648                .clips
649                .iter()
650                .min_by(|a, b| distance(a).total_cmp(&distance(b)))
651                .map(|c| c.id)
652        })
653    }
654}
655
656/// What a [`ClipPainter`] draws a clip with: the clip, its track, where it is
657/// on screen, and the mapping of time.
658#[derive(Debug)]
659pub struct ClipPaint<'a> {
660    pub clip: &'a Clip,
661    pub track: &'a Track,
662    /// The whole clip, often wider than the lanes when zoomed in.
663    pub rect: Rect,
664    /// The part of it in view.
665    pub visible: Rect,
666    /// Where its content goes: under its label when the track is tall
667    /// enough, else the whole clip.
668    pub content: Rect,
669    /// The lanes, for [`Lanes::x_of`] and [`Lanes::time_at`].
670    pub lanes: &'a Lanes,
671    pub scale: &'a TimeScale,
672    pub selected: bool,
673    pub hovered: bool,
674    pub tokens: &'a TimelineTokens,
675}
676
677impl ClipPaint<'_> {
678    /// The x of the source's `source_time`.
679    pub fn x_of_source(&self, source_time: f64) -> f32 {
680        self.lanes.x_of(self.clip.time_of(source_time))
681    }
682
683    /// The source's time at `x`.
684    pub fn source_at(&self, x: f32) -> f64 {
685        self.clip.source_at(self.lanes.time_at(x))
686    }
687
688    /// The source's times in view: from, to.
689    pub fn source_in_view(&self) -> (f64, f64) {
690        (
691            self.source_at(self.visible.left()),
692            self.source_at(self.visible.right()),
693        )
694    }
695
696    /// The text its label is drawn in.
697    pub fn text_color(&self) -> Color32 {
698        self.tokens.clip_text
699    }
700
701    /// Its label at the top left of the part in view (so a long clip keeps
702    /// it in sight), as [`PlainClips`] draws it.
703    pub fn paint_label(&self, painter: &Painter) {
704        if self.clip.label.is_empty() {
705            return;
706        }
707        let font = FontId::proportional(self.tokens.font_size);
708        let galley = painter.layout_no_wrap(self.clip.label.clone(), font, self.tokens.clip_text);
709        let at = pos2(self.visible.left() + 4.0, self.rect.top() + 2.0);
710        if at.x + 8.0 < self.visible.right() {
711            painter.galley(at, galley, self.tokens.clip_text);
712        }
713    }
714}
715
716/// How an application draws its clips' content: a video's thumbnails, an
717/// audio waveform, a data plot. The timeline draws a clip's box, its
718/// selection and its trimming handles; the painter what is inside, clipped
719/// to the clip.
720pub trait ClipPainter {
721    /// Draws `clip` with `painter` (clipped to the clip in view).
722    fn paint(&mut self, painter: &Painter, clip: &ClipPaint<'_>);
723}
724
725/// The plain painter: each clip's label, nothing else.
726#[derive(Clone, Copy, Debug, Default)]
727pub struct PlainClips;
728
729impl ClipPainter for PlainClips {
730    fn paint(&mut self, painter: &Painter, clip: &ClipPaint<'_>) {
731        clip.paint_label(painter);
732    }
733}
734
735impl<F: FnMut(&Painter, &ClipPaint<'_>)> ClipPainter for F {
736    fn paint(&mut self, painter: &Painter, clip: &ClipPaint<'_>) {
737        self(painter, clip)
738    }
739}
740
741#[cfg(test)]
742mod tests {
743    use super::*;
744    use crate::timeline::state::TimeRange;
745
746    /// Two tracks at 25 fps over a minute: V1 holds clips at 0..10 and
747    /// 20..30, A1 one at 5..15.
748    fn edit() -> TimelineState {
749        let mut s = TimelineState::new(TimeScale::frames(25), 60.0);
750        let v1 = s.add_track(Track::new(0, "V1").kind("video"));
751        let a1 = s.add_track(Track::new(0, "A1").kind("audio"));
752        s.add_clip(v1, Clip::new(0, 0.0, 10.0, "One").source_length(12.0))
753            .unwrap();
754        s.add_clip(
755            v1,
756            Clip::new(0, 20.0, 10.0, "Two")
757                .offset(2.0)
758                .source_length(20.0),
759        )
760        .unwrap();
761        s.add_clip(a1, Clip::new(0, 5.0, 10.0, "Sound")).unwrap();
762        s
763    }
764
765    #[test]
766    fn a_split_makes_two_clips_reading_the_source_on() {
767        let mut s = edit();
768        // Clip 2: 20..30 on the timeline, its source from 2 s in.
769        let new = s.split_clip(2, 24.0).unwrap();
770        assert_eq!(new, 4);
771        let (a, b) = (s.clip(2).unwrap(), s.clip(4).unwrap());
772        assert_eq!((a.start, a.length, a.offset), (20.0, 4.0, 2.0));
773        assert_eq!((b.start, b.length, b.offset), (24.0, 6.0, 6.0));
774        assert_eq!(b.source_length, Some(20.0));
775        assert_eq!(s.clip_track(4).unwrap().name, "V1");
776        // Not at an end, nor nearer it than a frame, nor off the clip.
777        assert_eq!(s.split_clip(2, 20.0), Err(ClipError::BadLength));
778        assert_eq!(s.split_clip(2, 23.99), Err(ClipError::BadLength));
779        assert_eq!(s.split_clip(4, 40.0), Err(ClipError::BadLength));
780        assert_eq!(s.split_clip(9, 1.0), Err(ClipError::NoClip(9)));
781        // On frames, the cut lands on a whole frame.
782        let new = s.split_clip(1, 3.013).unwrap();
783        assert_eq!(s.clip(new).unwrap().start, 3.0);
784    }
785
786    #[test]
787    fn a_ripple_delete_closes_the_gaps_on_their_tracks() {
788        let mut s = edit();
789        s.split_clip(2, 25.0).unwrap(); // V1: 0..10, 20..25, 25..30
790        let (removed, moved) = s.ripple_remove_clips(&[1, 2]);
791        assert_eq!(removed.len(), 2);
792        // 25..30 moves back by both: 5 s for clip 2, then 10 for clip 1.
793        assert_eq!(s.clip(4).unwrap().start, 10.0);
794        assert_eq!(
795            moved,
796            [Edit::ClipMoved {
797                id: 4,
798                from: ClipPlace {
799                    track: 1,
800                    start: 25.0
801                },
802                to: ClipPlace {
803                    track: 1,
804                    start: 10.0
805                },
806            }]
807        );
808        // Other tracks stay.
809        assert_eq!(s.clip(3).unwrap().start, 5.0);
810    }
811
812    #[test]
813    fn clips_never_overlap_on_a_track_nor_leave_the_bounds() {
814        let mut s = edit();
815        assert_eq!(s.next_clip_id(), 4);
816        assert_eq!(
817            s.add_clip(1, Clip::new(0, 8.0, 5.0, "Over")),
818            Err(ClipError::Overlaps(1))
819        );
820        assert_eq!(
821            s.add_clip(1, Clip::new(0, 55.0, 10.0, "Late")),
822            Err(ClipError::OutOfBounds)
823        );
824        assert_eq!(
825            s.add_clip(9, Clip::new(0, 40.0, 1.0, "")),
826            Err(ClipError::NoTrack(9))
827        );
828        // Touching end to start is no overlap; on whole frames.
829        let id = s
830            .add_clip(1, Clip::new(0, 10.013, 9.98, "Between"))
831            .unwrap();
832        assert_eq!(s.clip(id).map(|c| (c.start, c.end())), Some((10.0, 20.0)));
833        assert_eq!(
834            s.track(1)
835                .unwrap()
836                .clips
837                .iter()
838                .map(|c| c.id)
839                .collect::<Vec<_>>(),
840            [1, id, 2],
841            "in time order"
842        );
843    }
844
845    #[test]
846    fn moves_are_all_or_nothing_and_cross_tracks() {
847        let mut s = edit();
848        // Onto the sound: refused, nothing moved.
849        let refused = s.move_clips(&[ClipMove {
850            id: 1,
851            track: 2,
852            start: 0.0,
853        }]);
854        assert_eq!(refused, Err(ClipError::Overlaps(3)));
855        assert_eq!(s.clip_track(1).map(|t| t.id), Some(1));
856        let edits = s
857            .move_clips(&[ClipMove {
858                id: 1,
859                track: 2,
860                start: 40.0,
861            }])
862            .unwrap();
863        assert_eq!(
864            edits,
865            [Edit::ClipMoved {
866                id: 1,
867                from: ClipPlace {
868                    track: 1,
869                    start: 0.0
870                },
871                to: ClipPlace {
872                    track: 2,
873                    start: 40.0
874                },
875            }]
876        );
877        assert_eq!(s.track(2).unwrap().clips.len(), 2);
878        // Two moved together may take each other's place.
879        let swap = s.move_clips(&[
880            ClipMove {
881                id: 1,
882                track: 2,
883                start: 5.0,
884            },
885            ClipMove {
886                id: 3,
887                track: 2,
888                start: 40.0,
889            },
890        ]);
891        assert_eq!(swap.map(|e| e.len()), Ok(2));
892        // Nor over one another.
893        let both = s.move_clips(&[
894            ClipMove {
895                id: 1,
896                track: 1,
897                start: 40.0,
898            },
899            ClipMove {
900                id: 3,
901                track: 1,
902                start: 45.0,
903            },
904        ]);
905        assert_eq!(both, Err(ClipError::Overlaps(1)));
906    }
907
908    #[test]
909    fn trimming_keeps_to_the_source_the_neighbours_and_a_frame() {
910        let mut s = edit();
911        // The end: no further than the source (12 s), nor the next clip.
912        s.trim_clip(1, ClipEdge::End, 30.0).unwrap();
913        assert_eq!(s.clip(1).unwrap().end(), 12.0);
914        s.trim_clip(1, ClipEdge::End, 3.0).unwrap();
915        assert_eq!(s.clip(1).unwrap().length, 3.0);
916        // The start: the offset follows, never before the source's start.
917        let before = s.trim_clip(2, ClipEdge::Start, 25.0).unwrap();
918        assert_eq!(
919            before,
920            ClipSpan {
921                start: 20.0,
922                length: 10.0,
923                offset: 2.0
924            }
925        );
926        let c = s.clip(2).unwrap();
927        assert_eq!((c.start, c.length, c.offset), (25.0, 5.0, 7.0));
928        s.trim_clip(2, ClipEdge::Start, 0.0).unwrap();
929        let c = s.clip(2).unwrap();
930        assert_eq!(
931            (c.start, c.offset),
932            (18.0, 0.0),
933            "the source starts at 18 s"
934        );
935        // Never shorter than a frame.
936        s.trim_clip(2, ClipEdge::Start, 59.0).unwrap();
937        assert!((s.clip(2).unwrap().length - 0.04).abs() < 1e-9);
938        // What plays where.
939        let c = s.clip(2).unwrap();
940        assert!((c.source_at(c.start) - c.offset).abs() < 1e-9);
941        assert!((c.time_of(c.offset + 0.02) - (c.start + 0.02)).abs() < 1e-9);
942    }
943
944    #[test]
945    fn a_shift_that_does_not_fit_lands_against_the_nearest_edge() {
946        let s = edit();
947        let one = Origin {
948            id: 1,
949            row: 0,
950            start: 0.0,
951            length: 10.0,
952        };
953        assert_eq!(s.fit_shift(&[one], 5.0, 0), Some(5.0), "free");
954        assert_eq!(s.fit_shift(&[one], 15.0, 0), Some(10.0), "against Two");
955        assert_eq!(s.fit_shift(&[one], 22.0, 0), Some(30.0), "past Two");
956        assert_eq!(s.fit_shift(&[one], -3.0, 0), Some(0.0), "the bounds");
957        assert_eq!(s.fit_shift(&[one], 8.0, 1), Some(15.0), "after Sound");
958        assert_eq!(s.fit_shift(&[one], 8.0, 2), None, "no third track");
959    }
960
961    #[test]
962    fn walking_the_clips() {
963        let mut s = edit();
964        s.playhead = 12.0;
965        assert_eq!(s.neighbour_clip(true), Some(2));
966        assert_eq!(s.neighbour_clip(false), Some(1));
967        s.selected_clips = vec![2];
968        assert_eq!(s.neighbour_clip(false), Some(1));
969        assert_eq!(s.neighbour_clip(true), None);
970        // Across: the clip under the playhead on the next track down.
971        assert_eq!(s.clip_across(false), Some(3));
972        assert_eq!(s.clip_across(true), None);
973        s.selected_clips.clear();
974        assert_eq!(s.clip_across(false), Some(1), "nearest on the first");
975        assert_eq!(s.clip_across(true), Some(3), "from the last");
976    }
977
978    #[test]
979    fn removing_lets_go_of_the_selection_and_the_doc_keeps_the_tracks() {
980        let mut s = edit();
981        s.selected_clips = vec![1, 3];
982        let removed = s.remove_clips(&[3]);
983        assert_eq!(removed.len(), 1);
984        assert_eq!(removed[0].0, 2);
985        assert_eq!(s.selected_clips, [1]);
986        let doc = s.doc();
987        assert_eq!(doc.tracks.len(), 2);
988        s.remove_clips(&[1]);
989        s.selected_clips = vec![1];
990        s.set_doc(doc);
991        assert!(s.clip(1).is_some());
992        let json = serde_json::to_string(&s).unwrap();
993        let back: TimelineState = serde_json::from_str(&json).unwrap();
994        assert_eq!(back, s);
995        // No bounds: anywhere.
996        s.bounds = None;
997        assert!(s.in_bounds(-5.0, 1e6));
998        s.bounds = Some(TimeRange::new(0.0, 60.0));
999        assert!(!s.in_bounds(-5.0, 1.0));
1000    }
1001}