Skip to main content

egui_pop_views/timeline/
mod.rs

1//! Timeline: the [`Timeline`] widget, a ruler of time with a playhead, a
2//! range, markers and the transport keys, over a [`TimeScale`] (seconds,
3//! frames and timecode, bars and beats).
4//!
5//! <div class="warning">Experimental: may change in any release
6//! (docs/stability.md).</div>
7//!
8//! ```no_run
9//! use egui_pop_views::timeline::{Marker, TimeScale, Timeline, TimelineState};
10//!
11//! fn ui(ui: &mut egui::Ui, song: &mut TimelineState, dt: f64) {
12//!     // The application moves the time; the widget asks for it.
13//!     song.advance(dt);
14//!     let out = Timeline::new(song).id("song").show(ui);
15//!     if out.response.has_focus() && song.is_playing() {
16//!         ui.ctx().request_repaint();
17//!     }
18//! }
19//!
20//! let mut song = TimelineState::new(TimeScale::beats(128.0), 240.0);
21//! song.add_marker(Marker::new(0, 30.0, "Drop"));
22//! ```
23//!
24//! - **Time** is an `f64` in seconds everywhere; a [`TimeScale`] only reads
25//!   and writes it in its units, spaces the ruler and gives the grid.
26//! - **State**: the application keeps a [`TimelineState`] (serializable):
27//!   the view, the playhead, the range and its loop, the markers, and the
28//!   play state and speed the user asked for. Playing is the application's
29//!   job: it moves the playhead ([`TimelineState::advance`] does it the
30//!   usual way) and repaints while it plays.
31//! - **Pointer**: a press on the ruler or the lanes moves the playhead and a
32//!   drag scrubs; Shift+drag selects a range; Ctrl+drag or the middle
33//!   button pans; the wheel pans, Ctrl+wheel and a pinch zoom around the
34//!   pointer. A marker is clicked to select it, dragged to move it; a double
35//!   click on the markers' lane adds one. Snapping goes to the grid (the
36//!   ruler's small ticks), the markers, the playhead and the range's ends;
37//!   Alt turns it off while held ([`Snap`] chooses the targets).
38//! - **Keys**, while it has the focus (a Tab stop): Space plays or pauses;
39//!   J, K, L shuttle (J or L again doubles the speed, K pauses, K held with
40//!   J or L steps one unit); Left and Right step one unit, Shift for a
41//!   bigger one ([`TimeScale::step`]); Home and End; I and O set the range's
42//!   in and out points, Shift+I and Shift+O go to them, Alt+X clears the
43//!   range, Ctrl+L loops it; M adds a marker at the playhead; Up and Down
44//!   select the previous and next marker; Ctrl+Left and Ctrl+Right move the
45//!   selected one; Delete removes it, Escape lets it go; `+` and `-` zoom.
46//!   A key an application binds on the timeline's surface ([`SURFACE`]) runs
47//!   its command instead.
48//! - **Tracks and clips**: [`TimelineState::tracks`] are rows under the
49//!   ruler holding [`Clip`]s (a start, a length, an offset into a source),
50//!   never overlapping on a track. A [`ClipPainter`] the application gives
51//!   ([`Timeline::clips`]) draws their content; a click selects a clip, a
52//!   drag moves the selection along a track or across tracks, a clip's
53//!   edges trim it. Page Up and Page Down walk a track's clips, Shift+Up
54//!   and Shift+Down reach the next track's, Ctrl+arrows move the selection,
55//!   `[` and `]` trim it to the playhead, Ctrl+K splits clips at the
56//!   playhead, Shift+Delete removes the selection and closes its gaps.
57//! - **History**: with [`Timeline::history`], each change of the document
58//!   (adding, moving, removing a marker, setting or clearing the range,
59//!   looping, adding, moving, trimming, removing clips) is one step of
60//!   egui-pop's history, undone with Ctrl+Z; the playhead, the view,
61//!   playing and selecting are not. Without it, the output lists
62//!   the changes ([`TimelineOutput::edits`]) for the application's own.
63//! - **Accessibility**: the timeline is a slider whose value is the
64//!   playhead's text; Up and Down reach the markers, each named.
65//! - **Agents**: a timeline given an [`id`](Timeline::id) is listed by the
66//!   `timeline` collector and driven by the `timeline.*` commands
67//!   ([`TimelinePlugin`]).
68//! - **Look**: the theme's tokens only, `timeline.*` with fallbacks
69//!   ([`TimelineTokens`]).
70
71mod plugin;
72pub mod ruler;
73mod scale;
74mod state;
75mod tokens;
76mod tracks;
77mod transport;
78
79use crate::app_link::AppHandle;
80use egui::accesskit::{Action, ActionData, Role};
81use egui::{
82    Color32, Event, EventFilter, FontId, Id, Key, Modifiers, PointerButton, Pos2, Rect, Response,
83    Sense, Shape, Stroke, StrokeKind, Ui, UiBuilder, pos2, vec2,
84};
85use egui_pop_core::a11y::{self, Politeness};
86use egui_pop_core::lock;
87use egui_pop_core::pointer::{self, DragKind};
88use egui_pop_core::strings::{StrKey, tr, tr_args, tr_with};
89use egui_pop_model::commands::Origin;
90use egui_pop_model::ids::OwnerId;
91use egui_pop_model::values::{Change, Descriptor, Set, Value};
92
93#[cfg(feature = "api")]
94pub use plugin::TimelinePlugin;
95pub use plugin::{
96    CMD_ADD_CLIP, CMD_ADD_MARKER, CMD_GO_TO_END, CMD_GO_TO_START, CMD_MOVE_CLIP, CMD_PAUSE,
97    CMD_PLAY, CMD_REMOVE_CLIP, CMD_REMOVE_MARKER, CMD_RIPPLE_DELETE, CMD_SELECT_CLIPS,
98    CMD_SET_RANGE, CMD_SET_TIME, CMD_SHUTTLE_BACKWARD, CMD_SHUTTLE_FORWARD, CMD_SPLIT_CLIP,
99    CMD_STEP_BACKWARD, CMD_STEP_FORWARD, CMD_TOGGLE_LOOP, CMD_TOGGLE_PLAY, CMD_TRIM_CLIP, PLUGIN,
100    Timelines, describe,
101};
102pub use ruler::{Snapped, Ticks};
103pub use scale::{FrameRate, Tempo, TimeScale};
104pub use state::{
105    Edit, MAX_SPEED, Marker, MarkerKind, PlayState, TimeRange, TimeView, TimelineDoc, TimelineState,
106};
107pub use tokens::TimelineTokens;
108pub use tracks::{
109    Clip, ClipEdge, ClipError, ClipMove, ClipPaint, ClipPainter, ClipPlace, ClipSpan, PlainClips,
110    Track,
111};
112pub use transport::{Transport, TransportButton, TransportOutput};
113
114use crate::strings as txt;
115
116/// The surface a timeline opens, for key bindings (`timelineFocus`).
117pub const SURFACE: &str = "timeline";
118/// How near, in points, a time is pulled to a marker, the playhead or a
119/// range's end.
120pub const SNAP_REACH: f32 = 8.0;
121/// How much of a drag's own speed a nudge adds to playing
122/// ([`Timeline::nudge_on_drag`]).
123pub const NUDGE_GAIN: f64 = 0.25;
124
125/// How the view follows the playhead ([`Timeline::follow_mode`]).
126#[derive(Clone, Copy, Debug, Default, PartialEq)]
127pub enum Follow {
128    /// The view stays where the user puts it.
129    Off,
130    /// While it plays, the view turns a page when the playhead leaves it
131    /// (editors' habit).
132    #[default]
133    Page,
134    /// The playhead stays at this fraction of the width (0.5 the middle, a
135    /// third `1.0 / 3.0`), playing or not, and the content scrolls under
136    /// it (DJ decks' habit). The view may then reach past the bounds. A
137    /// drag moves the content (the playhead with it, relative to where the
138    /// drag began), a click on the ruler or the lanes moves the playhead
139    /// there, the wheel steps it by a unit (onto the grid) while paused,
140    /// and zooming keeps it in place.
141    Fixed(f32),
142}
143
144impl Follow {
145    /// The playhead in the middle.
146    pub const CENTRE: Follow = Follow::Fixed(0.5);
147}
148
149/// What a timeline snaps to; Alt held snaps to nothing.
150#[derive(Clone, Copy, Debug, PartialEq, Eq)]
151pub struct Snap {
152    /// The grid, the ruler's small ticks.
153    pub grid: bool,
154    /// The markers and the range's ends.
155    pub markers: bool,
156    pub playhead: bool,
157    /// The clips' edges.
158    pub clips: bool,
159}
160
161impl Default for Snap {
162    fn default() -> Self {
163        Self {
164            grid: true,
165            markers: true,
166            playhead: true,
167            clips: true,
168        }
169    }
170}
171
172impl Snap {
173    /// Nothing: times as the pointer gives them (whole frames on frames).
174    pub const OFF: Snap = Snap {
175        grid: false,
176        markers: false,
177        playhead: false,
178        clips: false,
179    };
180}
181
182/// What a user, a key or an agent asks of a timeline.
183#[derive(Clone, Debug)]
184#[cfg_attr(
185    not(feature = "api"),
186    allow(
187        dead_code,
188        reason = "only the api feature's steps build some operations"
189    )
190)]
191enum Op {
192    SetTime(f64),
193    /// From the keys: a step, which pauses.
194    StepBy(f64),
195    Toggle,
196    Play(f64),
197    Pause,
198    Shuttle(bool),
199    /// One unit (or a bigger step) forward or back, pausing.
200    Step {
201        forward: bool,
202        big: bool,
203    },
204    /// The bounds' start.
205    Home,
206    /// The bounds' end.
207    End,
208    ToggleLoop,
209    SetRange(Option<TimeRange>),
210    SetLoop(bool),
211    AddMarker(Marker),
212    /// A marker moved already (a drag), from `from`: its step.
213    CommitMove {
214        id: u64,
215        from: f64,
216    },
217    MoveMarker(u64, f64),
218    RemoveMarker(u64),
219    AddClip {
220        track: u64,
221        clip: Clip,
222    },
223    MoveClips(Vec<ClipMove>),
224    /// Clips moved already (a drag), from where they were: one step.
225    CommitClipMoves(Vec<(u64, ClipPlace)>),
226    TrimClip {
227        id: u64,
228        edge: ClipEdge,
229        time: f64,
230    },
231    /// A clip trimmed already (a drag), from its span before: its step.
232    CommitTrim {
233        id: u64,
234        from: ClipSpan,
235    },
236    RemoveClips(Vec<u64>),
237    /// Removes clips and closes their gaps.
238    RippleRemove(Vec<u64>),
239    /// Splits clips at a time.
240    SplitClips {
241        ids: Vec<u64>,
242        time: f64,
243    },
244    SelectClips(Vec<u64>),
245}
246
247/// What applying an op did.
248#[derive(Debug, Default)]
249struct Applied {
250    /// The document's changes, one step of the history together.
251    edits: Vec<Edit>,
252    transport: bool,
253    moved: bool,
254    /// Why it was refused (agents are told).
255    error: Option<String>,
256}
257
258/// Applies `op` to `state`.
259fn apply(state: &mut TimelineState, op: Op) -> Applied {
260    let mut done = Applied::default();
261    let before = (state.play, state.speed, state.playhead);
262    match op {
263        Op::SetTime(t) => {
264            state.set_playhead(t);
265        }
266        Op::StepBy(by) => {
267            state.step_by(by);
268        }
269        Op::Toggle => state.toggle(),
270        Op::Play(speed) => state.play_at(speed),
271        Op::Pause => state.pause(),
272        Op::Shuttle(forward) => state.shuttle(forward),
273        Op::Step { forward, big } => {
274            let by = state.scale.step(big);
275            state.step_by(if forward { by } else { -by });
276        }
277        Op::Home => {
278            state.set_playhead(state.home());
279        }
280        Op::End => {
281            state.set_playhead(state.end());
282        }
283        Op::ToggleLoop => {
284            state.looping = !state.looping;
285            done.edits.push(Edit::LoopSet(state.looping));
286        }
287        Op::SetRange(range) => {
288            let to = range.map(|r| TimeRange::new(state.clamp(r.start), state.clamp(r.end)));
289            if to != state.range {
290                done.edits.push(Edit::RangeSet {
291                    from: state.range,
292                    to,
293                });
294                state.range = to;
295            }
296        }
297        Op::SetLoop(on) => {
298            if on != state.looping {
299                state.looping = on;
300                done.edits.push(Edit::LoopSet(on));
301            }
302        }
303        Op::AddMarker(m) => {
304            let id = state.add_marker(m);
305            state.selected = Some(id);
306            state.selected_clips.clear();
307            done.edits
308                .extend(state.marker(id).cloned().map(Edit::MarkerAdded));
309        }
310        Op::CommitMove { id, from } => {
311            if let Some(m) = state.marker(id)
312                && m.time != from
313            {
314                done.edits.push(Edit::MarkerMoved {
315                    id,
316                    from,
317                    to: m.time,
318                });
319            }
320        }
321        Op::MoveMarker(id, to) => {
322            if let Some(from) = state.move_marker(id, to)
323                && let Some(m) = state.marker(id)
324                && m.time != from
325            {
326                done.edits.push(Edit::MarkerMoved {
327                    id,
328                    from,
329                    to: m.time,
330                });
331            }
332        }
333        Op::RemoveMarker(id) => {
334            done.edits
335                .extend(state.remove_marker(id).map(Edit::MarkerRemoved));
336        }
337        Op::AddClip { track, clip } => match state.add_clip(track, clip) {
338            Ok(id) => {
339                state.selected_clips = vec![id];
340                state.selected = None;
341                if let Some(clip) = state.clip(id).cloned() {
342                    done.edits.push(Edit::ClipAdded { track, clip });
343                }
344            }
345            Err(e) => done.error = Some(e.to_string()),
346        },
347        Op::MoveClips(moves) => match state.move_clips(&moves) {
348            Ok(edits) => done.edits = edits,
349            Err(e) => done.error = Some(e.to_string()),
350        },
351        Op::CommitClipMoves(from) => {
352            for (id, place) in from {
353                if let (Some(c), Some(t)) = (state.clip(id), state.clip_track(id)) {
354                    let to = ClipPlace {
355                        track: t.id,
356                        start: c.start,
357                    };
358                    if to != place {
359                        done.edits.push(Edit::ClipMoved {
360                            id,
361                            from: place,
362                            to,
363                        });
364                    }
365                }
366            }
367        }
368        Op::TrimClip { id, edge, time } => match state.trim_clip(id, edge, time) {
369            Ok(from) => {
370                if let Some(to) = state.clip(id).map(Clip::span)
371                    && to != from
372                {
373                    done.edits.push(Edit::ClipTrimmed { id, from, to });
374                }
375            }
376            Err(e) => done.error = Some(e.to_string()),
377        },
378        Op::CommitTrim { id, from } => {
379            if let Some(to) = state.clip(id).map(Clip::span)
380                && to != from
381            {
382                done.edits.push(Edit::ClipTrimmed { id, from, to });
383            }
384        }
385        Op::RemoveClips(ids) => match ids.iter().find(|id| state.clip(**id).is_none()) {
386            Some(id) => done.error = Some(ClipError::NoClip(*id).to_string()),
387            None => {
388                done.edits.extend(
389                    state
390                        .remove_clips(&ids)
391                        .into_iter()
392                        .map(|(track, clip)| Edit::ClipRemoved { track, clip }),
393                );
394            }
395        },
396        Op::RippleRemove(ids) => match ids.iter().find(|id| state.clip(**id).is_none()) {
397            Some(id) => done.error = Some(ClipError::NoClip(*id).to_string()),
398            None => {
399                let (removed, moved) = state.ripple_remove_clips(&ids);
400                done.edits.extend(
401                    removed
402                        .into_iter()
403                        .map(|(track, clip)| Edit::ClipRemoved { track, clip }),
404                );
405                done.edits.extend(moved);
406            }
407        },
408        Op::SplitClips { ids, time } => {
409            // All or none: each must hold the time.
410            let t = state.scale.quantize(time);
411            let min = state.min_clip_length();
412            match ids.iter().find_map(|id| match state.clip(*id) {
413                None => Some(ClipError::NoClip(*id)),
414                Some(c) if t < c.start + min - 1e-9 || t > c.end() - min + 1e-9 => {
415                    Some(ClipError::BadLength)
416                }
417                Some(_) => None,
418            }) {
419                Some(e) => done.error = Some(e.to_string()),
420                None => {
421                    for id in ids {
422                        if let Ok(new) = state.split_clip(id, t) {
423                            done.edits.push(Edit::ClipSplit { id, at: t, new });
424                        }
425                    }
426                }
427            }
428        }
429        Op::SelectClips(ids) => match ids.iter().find(|id| state.clip(**id).is_none()) {
430            Some(id) => done.error = Some(ClipError::NoClip(*id).to_string()),
431            None => {
432                state.selected_clips = ids;
433                if !state.selected_clips.is_empty() {
434                    state.selected = None;
435                }
436            }
437        },
438    }
439    done.transport = (state.play, state.speed) != (before.0, before.1);
440    done.moved = state.playhead != before.2;
441    done
442}
443
444/// The history step's name for the edits of one op.
445fn edit_label(edits: &[Edit]) -> Option<&'static StrKey> {
446    let many = edits.len() > 1;
447    let removes = edits.iter().any(|e| matches!(e, Edit::ClipRemoved { .. }));
448    if removes && edits.iter().any(|e| matches!(e, Edit::ClipMoved { .. })) {
449        return Some(&txt::TIMELINE_RIPPLE_DELETE);
450    }
451    Some(match edits.first()? {
452        Edit::ClipAdded { .. } => &txt::TIMELINE_ADD_CLIP,
453        Edit::ClipMoved { .. } if many => &txt::TIMELINE_MOVE_CLIPS,
454        Edit::ClipMoved { .. } => &txt::TIMELINE_MOVE_CLIP,
455        Edit::ClipTrimmed { .. } => &txt::TIMELINE_TRIM_CLIP,
456        Edit::ClipSplit { .. } if many => &txt::TIMELINE_SPLIT_CLIPS,
457        Edit::ClipSplit { .. } => &txt::TIMELINE_SPLIT_CLIP,
458        Edit::ClipRemoved { .. } if many => &txt::TIMELINE_REMOVE_CLIPS,
459        Edit::ClipRemoved { .. } => &txt::TIMELINE_REMOVE_CLIP,
460        Edit::MarkerAdded(_) => &txt::TIMELINE_ADD_MARKER,
461        Edit::MarkerMoved { .. } => &txt::TIMELINE_MOVE_MARKER,
462        Edit::MarkerRemoved(_) => &txt::TIMELINE_REMOVE_MARKER,
463        Edit::RangeSet { to: Some(_), .. } => &txt::TIMELINE_SET_RANGE,
464        Edit::RangeSet { to: None, .. } => &txt::TIMELINE_CLEAR_RANGE,
465        Edit::LoopSet(true) => &txt::TIMELINE_LOOP_ON,
466        Edit::LoopSet(false) => &txt::TIMELINE_LOOP_OFF,
467        Edit::Restored => return None,
468    })
469}
470
471/// The lanes under the ruler, for what an application draws there (rows of
472/// data, clips): where a time is across them.
473#[derive(Clone, Copy, Debug, PartialEq)]
474pub struct Lanes {
475    pub rect: Rect,
476    pub view: TimeView,
477    pub ticks: Ticks,
478}
479
480impl Lanes {
481    /// The x of `time`.
482    pub fn x_of(&self, time: f64) -> f32 {
483        self.rect.left() + self.view.x_of(time, self.rect.width())
484    }
485
486    /// The time at `x`.
487    pub fn time_at(&self, x: f32) -> f64 {
488        self.view.time_at(x - self.rect.left(), self.rect.width())
489    }
490}
491
492/// What a timeline did this pass.
493#[derive(Debug)]
494pub struct TimelineOutput {
495    /// The whole timeline (its keyboard focus, its accessible node).
496    pub response: Response,
497    /// The playhead moved (the user, a key or an agent; not playing).
498    pub playhead_moved: bool,
499    /// The playhead is being dragged.
500    pub scrubbing: bool,
501    /// Play, pause or the speed was asked this pass.
502    pub transport_changed: bool,
503    pub play: PlayState,
504    /// Asked speed, negative backwards.
505    pub speed: f64,
506    /// Zoomed or panned.
507    pub view_changed: bool,
508    /// The document's changes this pass (with [`Timeline::history`], each
509    /// is a step of the history already).
510    pub edits: Vec<Edit>,
511    /// Each track's id and row, from the top: where an application draws
512    /// beside them (headers, meters).
513    pub tracks: Vec<(u64, Rect)>,
514}
515
516/// A drag going on.
517#[derive(Clone, Copy, Debug, Default, PartialEq)]
518enum Drag {
519    #[default]
520    None,
521    Scrub,
522    Range {
523        anchor: f64,
524    },
525    Pan {
526        start: f64,
527        x: f32,
528    },
529    /// The content dragged under the playhead, or nudged while playing:
530    /// the time the drag puts the playhead at (unsnapped) and the pointer's
531    /// last x.
532    Content {
533        at: f64,
534        last: f32,
535    },
536    Marker {
537        id: u64,
538        from: f64,
539    },
540    /// Clips moved together ([`Memory::moving`]): `lead`, grabbed `grab`
541    /// seconds after its start.
542    Clips {
543        lead: u64,
544        grab: f64,
545    },
546    Trim {
547        id: u64,
548        edge: ClipEdge,
549        from: ClipSpan,
550    },
551}
552
553/// What a timeline keeps from one pass to the next.
554#[derive(Clone, Debug, Default)]
555struct Memory {
556    drag: Drag,
557    /// The range a Shift+drag is drawing.
558    preview: Option<TimeRange>,
559    /// The document's text as last written to or read from the store.
560    text: Option<String>,
561    /// The clips a drag moves, as they were when it began.
562    moving: Vec<tracks::Origin>,
563    /// Wheel lines not yet stepped ([`Follow::Fixed`]).
564    wheel: f32,
565}
566
567/// A timeline drawn over a [`TimelineState`] the application keeps.
568#[must_use = "call `show` to draw it"]
569pub struct Timeline<'a> {
570    state: &'a mut TimelineState,
571    id: Option<String>,
572    label: Option<String>,
573    lanes: Option<f32>,
574    width: Option<f32>,
575    snap: Snap,
576    app: Option<&'a AppHandle>,
577    history: Option<String>,
578    surface: &'a str,
579    take_focus: bool,
580    follow: Follow,
581    scrub_on_drag: bool,
582    nudge_on_drag: bool,
583    track_height: Option<f32>,
584    painter: Option<&'a mut dyn ClipPainter>,
585}
586
587impl std::fmt::Debug for Timeline<'_> {
588    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
589        f.debug_struct("Timeline")
590            .field("id", &self.id)
591            .field("history", &self.history)
592            .finish_non_exhaustive()
593    }
594}
595
596/// The context of one pass: the output being filled, who acts.
597struct Pass<'h> {
598    out_edits: Vec<Edit>,
599    transport: bool,
600    moved: bool,
601    history: Option<(&'h AppHandle, &'h str)>,
602}
603
604impl Pass<'_> {
605    /// Runs `op`, recording its edit (a step of the history when bound).
606    fn run(
607        &mut self,
608        ctx: &egui::Context,
609        state: &mut TimelineState,
610        mem: &mut Memory,
611        op: Op,
612        origin: &Origin,
613    ) {
614        let done = apply(state, op);
615        self.transport |= done.transport;
616        self.moved |= done.moved;
617        if let (Some((app, path)), Some(label)) = (self.history, edit_label(&done.edits)) {
618            commit(app, path, state, &tr(ctx, label), origin, mem);
619        }
620        self.out_edits.extend(done.edits);
621    }
622}
623
624impl<'a> Timeline<'a> {
625    pub fn new(state: &'a mut TimelineState) -> Self {
626        Self {
627            state,
628            id: None,
629            label: None,
630            lanes: None,
631            width: None,
632            snap: Snap::default(),
633            app: None,
634            history: None,
635            surface: SURFACE,
636            take_focus: false,
637            follow: Follow::Page,
638            scrub_on_drag: false,
639            nudge_on_drag: false,
640            track_height: None,
641            painter: None,
642        }
643    }
644
645    /// Its name for agents (the `timeline` collector, the `timeline.*`
646    /// commands' `timeline`) and its key in the context. Without one, it is
647    /// keyed by its place in the `Ui`, and agents do not see it.
648    pub fn id(mut self, id: impl Into<String>) -> Self {
649        self.id = Some(id.into());
650        self
651    }
652
653    /// Its accessible name, instead of "Timeline".
654    pub fn label(mut self, label: impl Into<String>) -> Self {
655        self.label = Some(label.into());
656        self
657    }
658
659    /// The height of the lanes under the tracks (by default, a control's
660    /// height without tracks, none with some).
661    pub fn lanes(mut self, height: f32) -> Self {
662        self.lanes = Some(height.max(0.0));
663        self
664    }
665
666    /// Its width (by default, the width available).
667    pub fn width(mut self, width: f32) -> Self {
668        self.width = Some(width);
669        self
670    }
671
672    pub fn snap(mut self, snap: Snap) -> Self {
673        self.snap = snap;
674        self
675    }
676
677    /// The application, for [`history`](Self::history).
678    #[cfg(feature = "api")]
679    pub fn app(mut self, app: &'a AppHandle) -> Self {
680        self.app = Some(app);
681        self
682    }
683
684    /// Keeps the document's part (markers, range, loop) as text at `path` of
685    /// the application's value store, declared there if it is not: each
686    /// change is one step of its history, and an undo puts the document
687    /// back. Needs [`app`](Self::app).
688    pub fn history(mut self, path: impl Into<String>) -> Self {
689        self.history = Some(path.into());
690        self
691    }
692
693    /// The focus surface around it, for key bindings ([`SURFACE`] by
694    /// default).
695    pub fn surface(mut self, surface: &'a str) -> Self {
696        self.surface = surface;
697        self
698    }
699
700    /// It takes the keyboard focus this pass.
701    pub fn take_focus(mut self, on: bool) -> Self {
702        self.take_focus = on;
703        self
704    }
705
706    /// While it plays, the view follows the playhead a page at a time (on
707    /// by default): [`Follow::Page`], else [`Follow::Off`].
708    pub fn follow(mut self, on: bool) -> Self {
709        self.follow = if on { Follow::Page } else { Follow::Off };
710        self
711    }
712
713    /// How the view follows the playhead ([`Follow::Page`] by default);
714    /// [`Follow::Fixed`] keeps the playhead in place and scrolls the content
715    /// under it.
716    pub fn follow_mode(mut self, follow: Follow) -> Self {
717        self.follow = follow;
718        self
719    }
720
721    /// A drag on a clip scrubs as a drag on the lanes does, instead of
722    /// moving or trimming it (off by default): the clips are locked to the
723    /// pointer, still selected by a click. With [`Follow::Fixed`], the
724    /// content follows the pointer and the playhead stays.
725    pub fn scrub_on_drag(mut self, on: bool) -> Self {
726        self.scrub_on_drag = on;
727        self
728    }
729
730    /// While it plays, a drag on the ruler or the lanes (and the clips with
731    /// [`scrub_on_drag`](Self::scrub_on_drag)) nudges instead of scrubbing
732    /// (off by default): it adds [`NUDGE_GAIN`] of its own speed to the
733    /// playing, dragging the content forward (to the left) speeding up and
734    /// back slowing down, as a jog wheel's edge does; released, the playing
735    /// goes on at its speed. Play and speed are not changed.
736    pub fn nudge_on_drag(mut self, on: bool) -> Self {
737        self.nudge_on_drag = on;
738        self
739    }
740
741    /// A track's height unless the track says (by default, twice a
742    /// control's).
743    pub fn track_height(mut self, height: f32) -> Self {
744        self.track_height = Some(height.max(4.0));
745        self
746    }
747
748    /// What draws the clips' content ([`PlainClips`], their labels, by
749    /// default).
750    pub fn clips(mut self, painter: &'a mut dyn ClipPainter) -> Self {
751        self.painter = Some(painter);
752        self
753    }
754
755    /// Draws it, its lanes empty.
756    pub fn show(self, ui: &mut Ui) -> TimelineOutput {
757        self.show_with(ui, |_, _| {})
758    }
759
760    /// Draws it, `lanes` drawing what goes under the ruler (rows of data, a
761    /// beat grid) before the clips, the markers and the playhead are drawn
762    /// over it.
763    pub fn show_with(self, ui: &mut Ui, lanes: impl FnOnce(&mut Ui, &Lanes)) -> TimelineOutput {
764        let surface = self.surface;
765        egui_pop_core::focus::scope(ui, surface, &[], |ui| self.draw(ui, lanes))
766    }
767
768    fn draw(self, ui: &mut Ui, body: impl FnOnce(&mut Ui, &Lanes)) -> TimelineOutput {
769        let Timeline {
770            state,
771            id,
772            label,
773            lanes,
774            width,
775            snap,
776            app,
777            history,
778            surface: _,
779            take_focus,
780            follow,
781            scrub_on_drag,
782            nudge_on_drag,
783            track_height,
784            painter: clip_painter,
785        } = self;
786        let anchor = match follow {
787            Follow::Fixed(at) if at.is_finite() => Some(f64::from(at.clamp(0.0, 1.0))),
788            _ => None,
789        };
790        let fixed = anchor.is_some();
791        let ctx = ui.ctx().clone();
792        let tk = TimelineTokens::of(&ctx);
793        let key = match &id {
794            Some(id) => Id::unique(("egui_pop.timeline", id)),
795            None => ui.auto_id_with("egui_pop.timeline"),
796        };
797        let mut mem: Memory = ctx.data(|d| d.get_temp(key)).unwrap_or_default();
798        let history = match (app, history.as_deref()) {
799            (Some(app), Some(path)) => Some((app, path)),
800            _ => None,
801        };
802        let mut pass = Pass {
803            out_edits: Vec::new(),
804            transport: false,
805            moved: false,
806            history,
807        };
808        if let Some((app, path)) = history
809            && sync(app, path, state, &mut mem)
810        {
811            pass.out_edits.push(Edit::Restored);
812        }
813        // The agents' commands since the last pass.
814        let registry = id.as_ref().map(|_| plugin::Timelines::of(&ctx));
815        if let (Some(reg), Some(id)) = (&registry, &id) {
816            for (op, origin) in reg.drawn(id, state) {
817                pass.run(&ctx, state, &mut mem, op, &origin);
818            }
819        }
820
821        let width = width.unwrap_or_else(|| ui.available_width()).max(40.0);
822        let row_h = |t: &Track| {
823            t.height
824                .unwrap_or(track_height.unwrap_or(tk.track_height))
825                .max(4.0)
826        };
827        let tracks_h: f32 = state.tracks.iter().map(row_h).sum();
828        let lanes_h = lanes.unwrap_or(if state.tracks.is_empty() {
829            tk.ruler_height
830        } else {
831            0.0
832        });
833        let size = vec2(width, tk.ruler_height + tk.lane_height + tracks_h + lanes_h);
834        let (rect, response) = ui.allocate_exact_size(size, Sense::click_and_drag());
835        let ruler_rect = Rect::from_min_size(rect.min, vec2(width, tk.ruler_height));
836        let lane = Rect::from_min_size(
837            pos2(rect.left(), ruler_rect.bottom()),
838            vec2(width, tk.lane_height),
839        );
840        let lanes_rect = Rect::from_min_max(pos2(rect.left(), lane.bottom()), rect.max);
841        // The tracks' rows, from the top of the lanes.
842        let rows: Vec<Rect> = {
843            let mut top = lanes_rect.top();
844            state
845                .tracks
846                .iter()
847                .map(|t| {
848                    let r = Rect::from_min_size(pos2(rect.left(), top), vec2(width, row_h(t)));
849                    top = r.bottom();
850                    r
851                })
852                .collect()
853        };
854        let font = FontId::monospace(tk.font_size);
855        let painter = ui.painter_at(rect);
856        let measure = |s: &str| {
857            painter
858                .layout_no_wrap(s.to_string(), font.clone(), Color32::WHITE)
859                .size()
860                .x
861        };
862
863        state.view = match anchor {
864            Some(at) => fixed_view(state, at),
865            None => state.fit_view(state.view),
866        };
867        let view_before = state.view;
868        let enabled = ui.is_enabled();
869        let line = ctx.options(|o| o.input_options.line_scroll_speed);
870        let (hover, mods, zoom, scroll, press, primary_pressed, middle_down, lines) =
871            ui.input(|i| {
872                (
873                    i.pointer.interact_pos(),
874                    i.modifiers,
875                    i.zoom_delta(),
876                    i.smooth_scroll_delta,
877                    i.pointer.press_origin(),
878                    i.pointer.primary_pressed(),
879                    i.pointer.button_down(PointerButton::Middle),
880                    wheel_lines(i, line),
881                )
882            });
883        let time_at = |view: &TimeView, x: f32| view.time_at(x - rect.left(), width);
884
885        // Zoom and pan by the wheel and pinch (over a clip too).
886        if enabled && (response.hovered() || ui.rect_contains_pointer(rect)) {
887            if zoom != 1.0 {
888                let at = match anchor {
889                    Some(_) => state.playhead,
890                    None => hover.map_or(state.playhead, |p| time_at(&state.view, p.x)),
891                };
892                state.view = state.fit_view(state.view.zoomed(f64::from(zoom), at));
893                if let Some(at) = anchor {
894                    state.view = fixed_view(state, at);
895                }
896            } else if fixed {
897                // The view is the playhead's: the wheel steps it, paused.
898                ui.input_mut(|i| i.smooth_scroll_delta = egui::Vec2::ZERO);
899                if state.is_playing() {
900                    mem.wheel = 0.0;
901                } else {
902                    mem.wheel += lines;
903                    let n = mem.wheel.trunc();
904                    mem.wheel -= n;
905                    if n != 0.0 {
906                        // Wheel up goes back, as panning does.
907                        let unit = state.scale.step(false);
908                        let from = if mods.alt {
909                            state.playhead
910                        } else {
911                            state.scale.round_to(state.playhead, unit)
912                        };
913                        let t = from - f64::from(n) * unit;
914                        pass.run(&ctx, state, &mut mem, Op::SetTime(t), &Origin::User);
915                    }
916                }
917            } else if scroll.x != 0.0 || scroll.y != 0.0 {
918                let per_point = state.view.duration / f64::from(width);
919                state.view.start -= f64::from(scroll.x + scroll.y) * per_point;
920                state.view = state.fit_view(state.view);
921                ui.input_mut(|i| i.smooth_scroll_delta = egui::Vec2::ZERO);
922            }
923        }
924
925        let mut ticks = ruler::ticks(&state.scale, &state.view, width, &measure);
926        let snapper =
927            |state: &TimelineState, ticks: Ticks, t: f64, skip: Option<u64>, scrub: bool| {
928                snap_time(state, &snap, ticks, width, t, skip, &[], scrub, mods.alt)
929            };
930
931        // The pointer on the ruler and the lanes.
932        let mut scrubbing = false;
933        if enabled {
934            if take_focus {
935                response.request_focus();
936            }
937            let pressed_here = primary_pressed && response.is_pointer_button_down_on();
938            let plain = !mods.shift && !mods.command && !mods.ctrl;
939            if pressed_here && plain {
940                response.request_focus();
941                // A press on the lanes, off the clips, lets them go.
942                if hover.is_some_and(|p| lanes_rect.contains(p)) {
943                    state.selected_clips.clear();
944                }
945                // It moves the playhead there, unless the content is dragged
946                // under a fixed playhead or nudged (a click does then).
947                if let Some(p) = hover
948                    && !fixed
949                    && !(nudge_on_drag && state.is_playing())
950                {
951                    let t = snapper(state, ticks, time_at(&state.view, p.x), None, true);
952                    pass.run(&ctx, state, &mut mem, Op::SetTime(t), &Origin::User);
953                }
954            } else if pressed_here {
955                response.request_focus();
956            }
957            if response.clicked()
958                && plain
959                && (fixed || (nudge_on_drag && state.is_playing()))
960                && let Some(p) = hover
961            {
962                let t = snapper(state, ticks, time_at(&state.view, p.x), None, true);
963                pass.run(&ctx, state, &mut mem, Op::SetTime(t), &Origin::User);
964            }
965            if response.drag_started() {
966                let origin_x = press.map_or(rect.center().x, |p| p.x);
967                let pan = middle_down || mods.command || mods.ctrl;
968                mem.drag = if fixed
969                    || (nudge_on_drag && state.is_playing() && plain && !middle_down)
970                {
971                    if mods.shift && !pan {
972                        Drag::Range {
973                            anchor: snapper(
974                                state,
975                                ticks,
976                                time_at(&state.view, origin_x),
977                                None,
978                                false,
979                            ),
980                        }
981                    } else {
982                        // The content follows the pointer: panning a fixed
983                        // view moves the playhead too.
984                        Drag::Content {
985                            at: state.playhead,
986                            last: origin_x,
987                        }
988                    }
989                } else if pan {
990                    Drag::Pan {
991                        start: state.view.start,
992                        x: origin_x,
993                    }
994                } else if mods.shift {
995                    Drag::Range {
996                        anchor: snapper(state, ticks, time_at(&state.view, origin_x), None, false),
997                    }
998                } else {
999                    Drag::Scrub
1000                };
1001            }
1002            if response.dragged()
1003                && let Some(p) = hover
1004            {
1005                match mem.drag {
1006                    Drag::Pan { start, x } => {
1007                        let per_point = state.view.duration / f64::from(width);
1008                        state.view.start = start - f64::from(p.x - x) * per_point;
1009                        state.view = state.fit_view(state.view);
1010                    }
1011                    Drag::Range { anchor } => {
1012                        let t = snapper(state, ticks, time_at(&state.view, p.x), None, false);
1013                        mem.preview = Some(TimeRange::new(anchor, t));
1014                    }
1015                    Drag::Scrub => {
1016                        scrubbing = true;
1017                        let t = snapper(state, ticks, time_at(&state.view, p.x), None, true);
1018                        pass.run(&ctx, state, &mut mem, Op::SetTime(t), &Origin::User);
1019                    }
1020                    Drag::Content { at, last } => {
1021                        let per_point = state.view.duration / f64::from(width);
1022                        let by = -f64::from(p.x - last) * per_point;
1023                        scrubbing = drag_content(
1024                            &ctx,
1025                            state,
1026                            &mut pass,
1027                            &mut mem,
1028                            ContentDrag {
1029                                at,
1030                                by,
1031                                x: p.x,
1032                                nudge: nudge_on_drag,
1033                            },
1034                            |state, t| snapper(state, ticks, t, None, true),
1035                        );
1036                    }
1037                    Drag::None | Drag::Marker { .. } | Drag::Clips { .. } | Drag::Trim { .. } => {}
1038                }
1039            }
1040            // The lanes' cursor, set before the clips', markers' and
1041            // handles' (theirs win over them): each drag keeps its own
1042            // until let go, wherever the pointer goes.
1043            if response.dragged() {
1044                let kind = match mem.drag {
1045                    Drag::Pan { .. } => Some(DragKind::Pan),
1046                    Drag::Content { .. } => Some(DragKind::Scrub),
1047                    Drag::Range { .. } => Some(DragKind::Select),
1048                    Drag::Scrub => Some(DragKind::Value),
1049                    Drag::None | Drag::Marker { .. } | Drag::Clips { .. } | Drag::Trim { .. } => {
1050                        None
1051                    }
1052                };
1053                if let Some(kind) = kind {
1054                    pointer::hold_drag_cursor(&ctx, kind);
1055                }
1056            } else if fixed && ctx.dragged_id().is_none() && ui.rect_contains_pointer(rect) {
1057                // A click there moves the playhead: the arrow until the
1058                // scrub starts, unless the hover policy says otherwise.
1059                pointer::hover_drag_cursor(&ctx, DragKind::Scrub, true);
1060            }
1061            if response.drag_stopped() {
1062                if let (Drag::Range { .. }, Some(r)) = (mem.drag, mem.preview.take())
1063                    && r.duration() > 0.0
1064                {
1065                    pass.run(&ctx, state, &mut mem, Op::SetRange(Some(r)), &Origin::User);
1066                }
1067                mem.drag = Drag::None;
1068                mem.preview = None;
1069            }
1070            if response.double_clicked()
1071                && let Some(p) = hover
1072                && lane.contains(p)
1073            {
1074                let t = snapper(state, ticks, time_at(&state.view, p.x), None, false);
1075                let label = new_marker_label(&ctx, state);
1076                pass.run(
1077                    &ctx,
1078                    state,
1079                    &mut mem,
1080                    Op::AddMarker(Marker::new(0, t, label)),
1081                    &Origin::User,
1082                );
1083            }
1084        }
1085
1086        // The markers: each a flag on the markers' lane.
1087        let x_of = |view: &TimeView, t: f64| rect.left() + view.x_of(t, width);
1088        let flags: Vec<(u64, Rect, String)> = state
1089            .markers
1090            .iter()
1091            .filter_map(|m| {
1092                let x = x_of(&state.view, m.time);
1093                if x < rect.left() - 2.0 || x > rect.right() + 2.0 {
1094                    return None;
1095                }
1096                let label_w = if m.label.is_empty() {
1097                    0.0
1098                } else {
1099                    measure(&m.label) + 4.0
1100                };
1101                let flag = Rect::from_min_size(
1102                    pos2(x - 5.0, lane.top() + 1.0),
1103                    vec2(10.0 + label_w, lane.height() - 2.0),
1104                )
1105                .intersect(lane);
1106                let name = marker_name(&ctx, state, m);
1107                Some((m.id, flag, name))
1108            })
1109            .collect();
1110        for (id, flag, name) in &flags {
1111            if !enabled {
1112                break;
1113            }
1114            let r = ui.interact(*flag, key.with(("marker", id)), Sense::CLICK | Sense::DRAG);
1115            a11y::name(&r, Role::Button, name);
1116            pointer::drag_cursor(&r, DragKind::ResizeHorizontal);
1117            if r.clicked() || r.drag_started() {
1118                state.selected = Some(*id);
1119                state.selected_clips.clear();
1120                ui.memory_mut(|m| m.request_focus(response.id));
1121            }
1122            if r.clicked()
1123                && let Some(t) = state.marker(*id).map(|m| m.time)
1124            {
1125                pass.run(&ctx, state, &mut mem, Op::SetTime(t), &Origin::User);
1126            }
1127            if r.drag_started()
1128                && let Some(m) = state.marker(*id)
1129            {
1130                mem.drag = Drag::Marker {
1131                    id: *id,
1132                    from: m.time,
1133                };
1134            }
1135            if r.dragged()
1136                && let Some(p) = hover
1137            {
1138                let t = snapper(state, ticks, time_at(&state.view, p.x), Some(*id), false);
1139                state.move_marker(*id, t);
1140            }
1141            if r.drag_stopped() {
1142                if let Drag::Marker { id, from } = mem.drag {
1143                    pass.run(
1144                        &ctx,
1145                        state,
1146                        &mut mem,
1147                        Op::CommitMove { id, from },
1148                        &Origin::User,
1149                    );
1150                }
1151                mem.drag = Drag::None;
1152            }
1153        }
1154
1155        // The clips: a click selects, a drag moves, their edges trim.
1156        let mut hovered_clip = None;
1157        let mut hovered_edge = None;
1158        if enabled {
1159            let row_at = |y: f32| {
1160                rows.iter()
1161                    .position(|r| y < r.bottom())
1162                    .unwrap_or(rows.len().saturating_sub(1))
1163            };
1164            let hits = clip_hits(state, &rows, lanes_rect, &|t| x_of(&state.view, t));
1165            for hit in hits {
1166                let Some(clip) = state.clip(hit.id).cloned() else {
1167                    continue;
1168                };
1169                let track = state.tracks[hit.row].name.clone();
1170                let name = clip_name(&ctx, state, &clip, &track);
1171                let selected = state.selected_clips.contains(&hit.id);
1172                // Locked to the pointer, a clip lets its drags through to the
1173                // lanes (a scrub).
1174                let sense = if scrub_on_drag {
1175                    Sense::click()
1176                } else {
1177                    Sense::click_and_drag()
1178                };
1179                let r = ui.interact(hit.visible, key.with(("clip", hit.id)), sense);
1180                r.widget_info(|| egui::WidgetInfo::selected(Role::Button, true, selected, &name));
1181                if r.hovered() {
1182                    hovered_clip = Some(hit.id);
1183                }
1184                if r.dragged() {
1185                    let kind = match mem.drag {
1186                        Drag::Pan { .. } => DragKind::Pan,
1187                        _ => DragKind::Move,
1188                    };
1189                    pointer::hold_drag_cursor(&ctx, kind);
1190                } else if !scrub_on_drag {
1191                    pointer::drag_cursor(&r, DragKind::Move);
1192                }
1193                if r.clicked() {
1194                    select_clip(state, hit.id, mods);
1195                    ui.memory_mut(|m| m.request_focus(response.id));
1196                }
1197                if r.drag_started() {
1198                    ui.memory_mut(|m| m.request_focus(response.id));
1199                    if middle_down {
1200                        mem.drag = Drag::Pan {
1201                            start: state.view.start,
1202                            x: press.map_or(hit.visible.center().x, |p| p.x),
1203                        };
1204                    } else {
1205                        if !state.selected_clips.contains(&hit.id) {
1206                            select_clip(state, hit.id, mods);
1207                        }
1208                        state.selected = None;
1209                        let at = press.map_or(clip.start, |p| time_at(&state.view, p.x));
1210                        mem.moving = state
1211                            .selected_clips
1212                            .iter()
1213                            .filter_map(|id| {
1214                                let (row, at) = state.locate(*id)?;
1215                                let c = &state.tracks[row].clips[at];
1216                                Some(tracks::Origin {
1217                                    id: *id,
1218                                    row,
1219                                    start: c.start,
1220                                    length: c.length,
1221                                })
1222                            })
1223                            .collect();
1224                        mem.drag = Drag::Clips {
1225                            lead: hit.id,
1226                            grab: at - clip.start,
1227                        };
1228                    }
1229                }
1230                if r.dragged()
1231                    && let Some(p) = hover
1232                {
1233                    match mem.drag {
1234                        Drag::Pan { start, x } => {
1235                            let per_point = state.view.duration / f64::from(width);
1236                            state.view.start = start - f64::from(p.x - x) * per_point;
1237                            state.view = state.fit_view(state.view);
1238                        }
1239                        Drag::Clips { lead, grab } => {
1240                            if let Some(o) = mem.moving.iter().find(|o| o.id == lead).copied() {
1241                                let skip: Vec<u64> = mem.moving.iter().map(|o| o.id).collect();
1242                                let raw = time_at(&state.view, p.x) - grab;
1243                                let start = if mods.alt {
1244                                    state.scale.quantize(raw)
1245                                } else {
1246                                    let targets =
1247                                        snap_targets(state, &snap, ticks, None, &skip, false);
1248                                    ruler::snap_span(
1249                                        &state.scale,
1250                                        raw,
1251                                        o.length,
1252                                        &targets,
1253                                        snap_reach(state, width),
1254                                    )
1255                                    .0
1256                                };
1257                                let lo = mem.moving.iter().map(|o| o.row).min().unwrap_or(0);
1258                                let hi = mem.moving.iter().map(|o| o.row).max().unwrap_or(0);
1259                                let drow = (row_at(p.y) as isize - o.row as isize)
1260                                    .clamp(-(lo as isize), rows.len() as isize - 1 - hi as isize);
1261                                if let Some(dt) =
1262                                    state.fit_shift(&mem.moving, start - o.start, drow)
1263                                {
1264                                    for m in mem.moving.clone() {
1265                                        let row = (m.row as isize + drow) as usize;
1266                                        let to = state.scale.quantize(m.start + dt);
1267                                        state.place(m.id, row, to);
1268                                    }
1269                                }
1270                            }
1271                        }
1272                        _ => {}
1273                    }
1274                }
1275                if r.drag_stopped() {
1276                    if let Drag::Clips { .. } = mem.drag {
1277                        let from: Vec<(u64, ClipPlace)> = mem
1278                            .moving
1279                            .iter()
1280                            .filter_map(|o| {
1281                                let track = state.tracks.get(o.row)?.id;
1282                                Some((
1283                                    o.id,
1284                                    ClipPlace {
1285                                        track,
1286                                        start: o.start,
1287                                    },
1288                                ))
1289                            })
1290                            .collect();
1291                        pass.run(
1292                            &ctx,
1293                            state,
1294                            &mut mem,
1295                            Op::CommitClipMoves(from),
1296                            &Origin::User,
1297                        );
1298                    }
1299                    mem.drag = Drag::None;
1300                    mem.moving.clear();
1301                }
1302                // Its edges, over it (none when locked).
1303                let handles = if scrub_on_drag {
1304                    Vec::new()
1305                } else {
1306                    hit.handles()
1307                };
1308                for (edge, handle) in handles {
1309                    let h = ui.interact(
1310                        handle,
1311                        key.with(("clip-edge", hit.id, edge)),
1312                        Sense::click_and_drag(),
1313                    );
1314                    pointer::drag_cursor(&h, DragKind::ResizeHorizontal);
1315                    if h.hovered() || h.dragged() {
1316                        hovered_edge = Some((hit.id, edge));
1317                    }
1318                    if h.clicked() {
1319                        select_clip(state, hit.id, mods);
1320                        ui.memory_mut(|m| m.request_focus(response.id));
1321                    }
1322                    if h.drag_started() {
1323                        ui.memory_mut(|m| m.request_focus(response.id));
1324                        state.selected_clips = vec![hit.id];
1325                        state.selected = None;
1326                        if let Some(c) = state.clip(hit.id) {
1327                            mem.drag = Drag::Trim {
1328                                id: hit.id,
1329                                edge,
1330                                from: c.span(),
1331                            };
1332                        }
1333                    }
1334                    if h.dragged()
1335                        && let (Some(p), Drag::Trim { id, edge, .. }) = (hover, mem.drag)
1336                    {
1337                        let t = snap_time(
1338                            state,
1339                            &snap,
1340                            ticks,
1341                            width,
1342                            time_at(&state.view, p.x),
1343                            None,
1344                            &[id],
1345                            false,
1346                            mods.alt,
1347                        );
1348                        let _ = state.trim_clip(id, edge, t);
1349                    }
1350                    if h.drag_stopped() {
1351                        if let Drag::Trim { id, from, .. } = mem.drag {
1352                            pass.run(
1353                                &ctx,
1354                                state,
1355                                &mut mem,
1356                                Op::CommitTrim { id, from },
1357                                &Origin::User,
1358                            );
1359                        }
1360                        mem.drag = Drag::None;
1361                    }
1362                }
1363            }
1364        }
1365
1366        // The keys.
1367        if response.has_focus() && enabled {
1368            ui.memory_mut(|m| {
1369                m.set_focus_lock_filter(
1370                    response.id,
1371                    EventFilter {
1372                        horizontal_arrows: true,
1373                        vertical_arrows: true,
1374                        escape: state.selected.is_some() || !state.selected_clips.is_empty(),
1375                        ..Default::default()
1376                    },
1377                );
1378            });
1379            egui_pop_core::focus::takes_keys(&ctx, response.id);
1380            let k_held = ui.input(|i| i.key_down(Key::K));
1381            let selected = state.selected.is_some() || !state.selected_clips.is_empty();
1382            let acts = ui.input_mut(|i| {
1383                let mut acts = Vec::new();
1384                i.events.retain(|e| match e {
1385                    Event::Key {
1386                        key,
1387                        pressed: true,
1388                        repeat,
1389                        modifiers,
1390                        ..
1391                    } => match key_act(*key, *modifiers, *repeat, k_held, selected) {
1392                        Some(a) => {
1393                            acts.push(a);
1394                            false
1395                        }
1396                        None => true,
1397                    },
1398                    _ => true,
1399                });
1400                acts
1401            });
1402            for act in acts {
1403                key_run(&ctx, state, &mut pass, &mut mem, act);
1404            }
1405        }
1406        // A screen reader's actions on the slider.
1407        if enabled {
1408            let (inc, dec, set) = ui.input(|i| {
1409                let set = i
1410                    .accesskit_action_requests(response.id, Action::SetValue)
1411                    .find_map(|r| match &r.data {
1412                        Some(ActionData::NumericValue(v)) => Some(*v),
1413                        Some(ActionData::Value(text)) => state.scale.parse(text),
1414                        _ => None,
1415                    });
1416                (
1417                    i.num_accesskit_action_requests(response.id, Action::Increment),
1418                    i.num_accesskit_action_requests(response.id, Action::Decrement),
1419                    set,
1420                )
1421            });
1422            let unit = state.scale.step(false);
1423            for (n, by) in [(inc, unit), (dec, -unit)] {
1424                for _ in 0..n {
1425                    pass.run(&ctx, state, &mut mem, Op::StepBy(by), &Origin::User);
1426                }
1427            }
1428            if let Some(t) = set {
1429                pass.run(&ctx, state, &mut mem, Op::SetTime(t), &Origin::User);
1430            }
1431        }
1432
1433        // The view follows the playhead: kept in place, or a page at a time
1434        // while it plays.
1435        if let Some(at) = anchor {
1436            state.view = fixed_view(state, at);
1437        } else if follow == Follow::Page
1438            && state.is_playing()
1439            && mem.drag == Drag::None
1440            && !state.view.contains(state.playhead)
1441        {
1442            let d = state.view.duration;
1443            let start = if state.speed >= 0.0 {
1444                state.playhead - d * 0.05
1445            } else {
1446                state.playhead - d * 0.95
1447            };
1448            state.view = state.fit_view(TimeView::new(start, d));
1449        }
1450        let view_changed = state.view != view_before;
1451        if view_changed {
1452            ticks = ruler::ticks(&state.scale, &state.view, width, &measure);
1453        }
1454
1455        // Accessibility: a slider over the time.
1456        let name = label.unwrap_or_else(|| tr(&ctx, &txt::TIMELINE));
1457        a11y::name(&response, Role::Slider, &name);
1458        let value = state.scale.format(state.playhead);
1459        let (lo, hi) = state
1460            .bounds
1461            .map_or((state.view.start, state.view.end()), |b| (b.start, b.end));
1462        let unit = state.scale.step(false);
1463        let playhead = state.playhead;
1464        ctx.accesskit_node_builder(response.id, |node| {
1465            node.set_value(value);
1466            node.set_numeric_value(playhead);
1467            node.set_min_numeric_value(lo.min(playhead));
1468            node.set_max_numeric_value(hi.max(playhead));
1469            node.set_numeric_value_step(unit);
1470            node.add_action(Action::SetValue);
1471            node.add_action(Action::Increment);
1472            node.add_action(Action::Decrement);
1473        });
1474        egui_pop_core::focus::own_ring(&ctx, response.id);
1475
1476        // Drawing.
1477        if ui.is_rect_visible(rect) {
1478            paint_base(&painter, &tk, state, &mem, rect, ruler_rect, ticks, &font);
1479        }
1480        let lanes = Lanes {
1481            rect: lanes_rect,
1482            view: state.view,
1483            ticks,
1484        };
1485        let mut child = ui.new_child(
1486            UiBuilder::new()
1487                .max_rect(lanes_rect)
1488                .id_salt(key.with("lanes")),
1489        );
1490        child.set_clip_rect(lanes_rect.intersect(ui.clip_rect()));
1491        body(&mut child, &lanes);
1492        if ui.is_rect_visible(rect) && !rows.is_empty() {
1493            let mut plain = PlainClips;
1494            let clip_painter: &mut dyn ClipPainter = match clip_painter {
1495                Some(p) => p,
1496                None => &mut plain,
1497            };
1498            let lanes_painter = ui.painter_at(lanes_rect);
1499            paint_tracks(
1500                &lanes_painter,
1501                &tk,
1502                state,
1503                &rows,
1504                &lanes,
1505                clip_painter,
1506                hovered_clip,
1507                hovered_edge,
1508            );
1509        }
1510        if ui.is_rect_visible(rect) {
1511            paint_over(&painter, &tk, state, rect, lane, ruler_rect, &font, &ctx);
1512            if egui_pop_core::focus::shows_ring(&response) {
1513                painter.rect_stroke(rect, 0.0, Stroke::new(1.0, tk.focus), StrokeKind::Inside);
1514            }
1515        }
1516
1517        if let (Some(reg), Some(id)) = (&registry, &id) {
1518            reg.update(id, state, response.has_focus());
1519        }
1520        ctx.data_mut(|d| d.insert_temp(key, mem));
1521        TimelineOutput {
1522            response,
1523            playhead_moved: pass.moved,
1524            scrubbing,
1525            transport_changed: pass.transport,
1526            play: state.play,
1527            speed: state.speed,
1528            view_changed,
1529            edits: pass.out_edits,
1530            tracks: state.tracks.iter().map(|t| t.id).zip(rows).collect(),
1531        }
1532    }
1533}
1534
1535/// The view of a [`Follow::Fixed`] timeline: the playhead at `at` of its
1536/// width, the duration within the zoom limits.
1537fn fixed_view(state: &TimelineState, at: f64) -> TimeView {
1538    let duration = state.fit_view(state.view).duration;
1539    TimeView::new(state.playhead - at * duration, duration)
1540}
1541
1542/// The wheel's motion this pass, in lines (a notch is one), Ctrl's
1543/// (zooming) left out.
1544fn wheel_lines(i: &egui::InputState, line: f32) -> f32 {
1545    i.events
1546        .iter()
1547        .filter_map(|e| match e {
1548            Event::MouseWheel {
1549                unit,
1550                delta,
1551                modifiers,
1552                ..
1553            } if !modifiers.command && !modifiers.ctrl => {
1554                let d = delta.x + delta.y;
1555                Some(match unit {
1556                    egui::MouseWheelUnit::Point => d / line.max(1.0),
1557                    egui::MouseWheelUnit::Line | egui::MouseWheelUnit::Page => d,
1558                })
1559            }
1560            _ => None,
1561        })
1562        .sum()
1563}
1564
1565/// A pass of a content drag.
1566struct ContentDrag {
1567    /// Where the drag puts the playhead so far, unsnapped.
1568    at: f64,
1569    /// The seconds the pointer moved the content by (forward positive).
1570    by: f64,
1571    /// The pointer's x.
1572    x: f32,
1573    /// Playing, a nudge rather than a scrub.
1574    nudge: bool,
1575}
1576
1577/// Moves the playhead by a content drag: paused, with the content (snapped,
1578/// whether it scrubs is answered); playing, by the drag's motion, a
1579/// [`NUDGE_GAIN`] of it when nudging.
1580fn drag_content(
1581    ctx: &egui::Context,
1582    state: &mut TimelineState,
1583    pass: &mut Pass<'_>,
1584    mem: &mut Memory,
1585    d: ContentDrag,
1586    snap: impl Fn(&TimelineState, f64) -> f64,
1587) -> bool {
1588    let inside = |state: &TimelineState, t: f64| state.bounds.map_or(t, |b| b.clamp(t));
1589    if state.is_playing() {
1590        // Not quantized, as playing is not.
1591        let gain = if d.nudge { NUDGE_GAIN } else { 1.0 };
1592        let to = inside(state, state.playhead + d.by * gain);
1593        if to != state.playhead {
1594            state.playhead = to;
1595            pass.moved = true;
1596        }
1597        mem.drag = Drag::Content {
1598            at: state.playhead,
1599            last: d.x,
1600        };
1601        false
1602    } else {
1603        let at = inside(state, d.at + d.by);
1604        let t = snap(state, at);
1605        pass.run(ctx, state, mem, Op::SetTime(t), &Origin::User);
1606        mem.drag = Drag::Content { at, last: d.x };
1607        true
1608    }
1609}
1610
1611/// Runs a key's act.
1612fn key_run(
1613    ctx: &egui::Context,
1614    state: &mut TimelineState,
1615    pass: &mut Pass<'_>,
1616    mem: &mut Memory,
1617    act: KeyAct,
1618) {
1619    let user = &Origin::User;
1620    let mut run = |state: &mut TimelineState, mem: &mut Memory, op: Op| {
1621        pass.run(ctx, state, mem, op, user);
1622    };
1623    match act {
1624        KeyAct::Toggle => run(state, mem, Op::Toggle),
1625        KeyAct::Pause => run(state, mem, Op::Pause),
1626        KeyAct::Shuttle(forward) => run(state, mem, Op::Shuttle(forward)),
1627        // The same ops as the transport's commands.
1628        KeyAct::Step(sign, big) => run(
1629            state,
1630            mem,
1631            Op::Step {
1632                forward: sign > 0.0,
1633                big,
1634            },
1635        ),
1636        KeyAct::Home => run(state, mem, Op::Home),
1637        KeyAct::End => run(state, mem, Op::End),
1638        KeyAct::In => {
1639            let r = state.in_at(state.playhead);
1640            run(state, mem, Op::SetRange(Some(r)));
1641        }
1642        KeyAct::Out => {
1643            let r = state.out_at(state.playhead);
1644            run(state, mem, Op::SetRange(Some(r)));
1645        }
1646        KeyAct::GoIn | KeyAct::GoOut => {
1647            if let Some(r) = state.range {
1648                let t = if act == KeyAct::GoIn { r.start } else { r.end };
1649                run(state, mem, Op::SetTime(t));
1650            }
1651        }
1652        KeyAct::ClearRange => run(state, mem, Op::SetRange(None)),
1653        KeyAct::ToggleLoop => run(state, mem, Op::ToggleLoop),
1654        KeyAct::AddMarker => {
1655            let label = new_marker_label(ctx, state);
1656            let m = Marker::new(0, state.playhead, label);
1657            run(state, mem, Op::AddMarker(m));
1658        }
1659        KeyAct::Neighbour(forward) => {
1660            if let Some(id) = state.neighbour_marker(forward) {
1661                state.selected = Some(id);
1662                if let Some(m) = state.marker(id).cloned() {
1663                    run(state, mem, Op::SetTime(m.time));
1664                    a11y::announce(ctx, marker_name(ctx, state, &m), Politeness::Polite);
1665                }
1666            }
1667        }
1668        KeyAct::Nudge(sign, big) => {
1669            let by = sign * state.scale.step(big);
1670            if let Some(m) = state.selected.and_then(|id| state.marker(id)).cloned() {
1671                run(state, mem, Op::MoveMarker(m.id, m.time + by));
1672            } else {
1673                let moves = clip_moves(state, |row, c| Some((c.start + by, row)));
1674                if !moves.is_empty() {
1675                    run(state, mem, Op::MoveClips(moves));
1676                }
1677            }
1678        }
1679        KeyAct::Remove => {
1680            if let Some(id) = state.selected {
1681                run(state, mem, Op::RemoveMarker(id));
1682            } else if !state.selected_clips.is_empty() {
1683                let ids = state.selected_clips.clone();
1684                run(state, mem, Op::RemoveClips(ids));
1685            }
1686        }
1687        KeyAct::Ripple => {
1688            if !state.selected_clips.is_empty() {
1689                let ids = state.selected_clips.clone();
1690                run(state, mem, Op::RippleRemove(ids));
1691            }
1692        }
1693        KeyAct::Split => {
1694            // The selected clips under the playhead, else every clip there.
1695            let t = state.playhead;
1696            let at = |c: &Clip| c.start < t && t < c.end();
1697            let selected: Vec<u64> = state
1698                .selected_clips
1699                .iter()
1700                .copied()
1701                .filter(|id| state.clip(*id).is_some_and(at))
1702                .collect();
1703            let ids = if selected.is_empty() {
1704                state
1705                    .clips()
1706                    .filter(|(_, c)| at(c))
1707                    .map(|(_, c)| c.id)
1708                    .collect()
1709            } else {
1710                selected
1711            };
1712            if !ids.is_empty() {
1713                run(state, mem, Op::SplitClips { ids, time: t });
1714            }
1715        }
1716        KeyAct::Deselect => {
1717            state.selected = None;
1718            state.selected_clips.clear();
1719        }
1720        KeyAct::ClipWalk(forward) => {
1721            if let Some(id) = state.neighbour_clip(forward) {
1722                reach_clip(ctx, state, id);
1723                if let Some(t) = state.clip(id).map(|c| c.start) {
1724                    run(state, mem, Op::SetTime(t));
1725                }
1726            }
1727        }
1728        KeyAct::ClipAcross(up) => {
1729            if let Some(id) = state.clip_across(up) {
1730                reach_clip(ctx, state, id);
1731            }
1732        }
1733        KeyAct::ClipTrack(up) => {
1734            let rows = state.tracks.len();
1735            let moves = clip_moves(state, |row, c| {
1736                let to = if up { row.checked_sub(1)? } else { row + 1 };
1737                (to < rows).then_some((c.start, to))
1738            });
1739            if !moves.is_empty() && moves.len() == state.selected_clips.len() {
1740                run(state, mem, Op::MoveClips(moves));
1741            }
1742        }
1743        KeyAct::Trim(edge) => {
1744            if let Some(id) = state.selected_clips.last().copied() {
1745                let time = state.playhead;
1746                run(state, mem, Op::TrimClip { id, edge, time });
1747            }
1748        }
1749        KeyAct::Zoom(factor) => {
1750            state.view = state.fit_view(state.view.zoomed(factor, state.playhead));
1751        }
1752    }
1753}
1754
1755/// What a key asks.
1756#[derive(Clone, Copy, Debug, PartialEq)]
1757enum KeyAct {
1758    Toggle,
1759    Pause,
1760    Shuttle(bool),
1761    /// -1 or 1, and whether the big step.
1762    Step(f64, bool),
1763    Home,
1764    End,
1765    In,
1766    Out,
1767    GoIn,
1768    GoOut,
1769    ClearRange,
1770    ToggleLoop,
1771    AddMarker,
1772    Neighbour(bool),
1773    Nudge(f64, bool),
1774    Remove,
1775    /// The selected clips removed, their gaps closed.
1776    Ripple,
1777    /// The clips at the playhead split there.
1778    Split,
1779    Deselect,
1780    Zoom(f64),
1781    /// The next (or previous) clip on the selected one's track.
1782    ClipWalk(bool),
1783    /// The clip at the playhead on the track above (or below).
1784    ClipAcross(bool),
1785    /// The selected clips a track up (or down).
1786    ClipTrack(bool),
1787    /// The selected clip's start or end to the playhead.
1788    Trim(ClipEdge),
1789}
1790
1791/// The act of a key pressed with exactly these modifiers.
1792fn key_act(key: Key, m: Modifiers, repeat: bool, k_held: bool, selected: bool) -> Option<KeyAct> {
1793    let ctrl = m.command || m.ctrl;
1794    let (none, shift, ctrl_only, alt_only, ctrl_shift) = (
1795        !ctrl && !m.shift && !m.alt,
1796        m.shift && !ctrl && !m.alt,
1797        ctrl && !m.shift && !m.alt,
1798        m.alt && !ctrl && !m.shift,
1799        ctrl && m.shift && !m.alt,
1800    );
1801    let once = !repeat;
1802    Some(match key {
1803        Key::Space if none && once => KeyAct::Toggle,
1804        Key::K if none && once => KeyAct::Pause,
1805        Key::J if none && k_held => KeyAct::Step(-1.0, false),
1806        Key::L if none && k_held => KeyAct::Step(1.0, false),
1807        Key::J if none && once => KeyAct::Shuttle(false),
1808        Key::L if none && once => KeyAct::Shuttle(true),
1809        Key::L if ctrl_only && once => KeyAct::ToggleLoop,
1810        Key::ArrowLeft if none || shift => KeyAct::Step(-1.0, shift),
1811        Key::ArrowRight if none || shift => KeyAct::Step(1.0, shift),
1812        Key::ArrowLeft if ctrl_only || ctrl_shift => KeyAct::Nudge(-1.0, ctrl_shift),
1813        Key::ArrowRight if ctrl_only || ctrl_shift => KeyAct::Nudge(1.0, ctrl_shift),
1814        Key::ArrowUp if none => KeyAct::Neighbour(false),
1815        Key::ArrowDown if none => KeyAct::Neighbour(true),
1816        Key::PageUp if none => KeyAct::ClipWalk(false),
1817        Key::PageDown if none => KeyAct::ClipWalk(true),
1818        Key::ArrowUp if shift => KeyAct::ClipAcross(true),
1819        Key::ArrowDown if shift => KeyAct::ClipAcross(false),
1820        Key::ArrowUp if ctrl_only => KeyAct::ClipTrack(true),
1821        Key::ArrowDown if ctrl_only => KeyAct::ClipTrack(false),
1822        Key::OpenBracket if none && once => KeyAct::Trim(ClipEdge::Start),
1823        Key::CloseBracket if none && once => KeyAct::Trim(ClipEdge::End),
1824        Key::Home if none => KeyAct::Home,
1825        Key::End if none => KeyAct::End,
1826        Key::I if none && once => KeyAct::In,
1827        Key::O if none && once => KeyAct::Out,
1828        Key::I if shift && once => KeyAct::GoIn,
1829        Key::O if shift && once => KeyAct::GoOut,
1830        Key::X if alt_only && once => KeyAct::ClearRange,
1831        Key::M if none && once => KeyAct::AddMarker,
1832        Key::Delete | Key::Backspace if none && once && selected => KeyAct::Remove,
1833        Key::Delete | Key::Backspace if shift && once && selected => KeyAct::Ripple,
1834        Key::K if ctrl_only && once => KeyAct::Split,
1835        Key::Escape if none && selected => KeyAct::Deselect,
1836        Key::Plus | Key::Equals if none || shift => KeyAct::Zoom(2.0),
1837        Key::Minus if none => KeyAct::Zoom(0.5),
1838        _ => return None,
1839    })
1840}
1841
1842/// `t` snapped as [`Snap`] says (nothing with Alt held, `free`).
1843#[allow(
1844    clippy::too_many_arguments,
1845    reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
1846)]
1847fn snap_time(
1848    state: &TimelineState,
1849    snap: &Snap,
1850    ticks: Ticks,
1851    width: f32,
1852    t: f64,
1853    skip_marker: Option<u64>,
1854    skip_clips: &[u64],
1855    scrubbing: bool,
1856    free: bool,
1857) -> f64 {
1858    let t = state.clamp(t);
1859    if free {
1860        return t;
1861    }
1862    let targets = snap_targets(state, snap, ticks, skip_marker, skip_clips, scrubbing);
1863    state.clamp(ruler::snap(&state.scale, t, &targets, snap_reach(state, width)).0)
1864}
1865
1866/// How near, in seconds, a time is pulled to a point.
1867fn snap_reach(state: &TimelineState, width: f32) -> f64 {
1868    f64::from(SNAP_REACH) * state.view.duration / f64::from(width.max(1.0))
1869}
1870
1871/// What a time snaps to, as [`Snap`] says, but `skip_marker` and the edges
1872/// of `skip_clips` (being moved), and the playhead while it is scrubbed.
1873fn snap_targets(
1874    state: &TimelineState,
1875    snap: &Snap,
1876    ticks: Ticks,
1877    skip_marker: Option<u64>,
1878    skip_clips: &[u64],
1879    scrubbing: bool,
1880) -> ruler::SnapTargets {
1881    let mut targets = ruler::SnapTargets {
1882        grid: snap.grid.then_some(ticks.minor),
1883        points: Vec::new(),
1884    };
1885    if snap.markers {
1886        targets.points.extend(
1887            state
1888                .markers
1889                .iter()
1890                .filter(|m| Some(m.id) != skip_marker)
1891                .map(|m| (m.time, Snapped::Marker)),
1892        );
1893        if let Some(r) = state.range {
1894            targets.points.push((r.start, Snapped::Range));
1895            targets.points.push((r.end, Snapped::Range));
1896        }
1897    }
1898    if snap.playhead && !scrubbing {
1899        targets.points.push((state.playhead, Snapped::Playhead));
1900    }
1901    if snap.clips {
1902        for (_, c) in state.clips().filter(|(_, c)| !skip_clips.contains(&c.id)) {
1903            targets.points.push((c.start, Snapped::Clip));
1904            targets.points.push((c.end(), Snapped::Clip));
1905        }
1906    }
1907    targets
1908}
1909
1910/// A clip in view: its row, and its rect cut to the lanes.
1911#[derive(Clone, Copy, Debug)]
1912struct ClipHit {
1913    id: u64,
1914    row: usize,
1915    rect: Rect,
1916    visible: Rect,
1917}
1918
1919impl ClipHit {
1920    /// Its edges in view, each a handle to trim it by.
1921    fn handles(&self) -> Vec<(ClipEdge, Rect)> {
1922        let w = (self.rect.width() / 3.0).min(6.0);
1923        let y = self.visible.y_range();
1924        let mut out = Vec::new();
1925        if self.rect.left() >= self.visible.left() - 0.5 {
1926            let x = self.rect.left();
1927            out.push((ClipEdge::Start, Rect::from_x_y_ranges(x - 1.0..=x + w, y)));
1928        }
1929        if self.rect.right() <= self.visible.right() + 0.5 {
1930            let x = self.rect.right();
1931            out.push((ClipEdge::End, Rect::from_x_y_ranges(x - w..=x + 1.0, y)));
1932        }
1933        out
1934    }
1935}
1936
1937/// The clips in view, track by track.
1938fn clip_hits(
1939    state: &TimelineState,
1940    rows: &[Rect],
1941    lanes: Rect,
1942    x_of: &dyn Fn(f64) -> f32,
1943) -> Vec<ClipHit> {
1944    let mut hits = Vec::new();
1945    for (row, (t, r)) in state.tracks.iter().zip(rows).enumerate() {
1946        for c in &t.clips {
1947            let (a, b) = (x_of(c.start), x_of(c.end()));
1948            if b < lanes.left() || a > lanes.right() {
1949                continue;
1950            }
1951            let rect = Rect::from_x_y_ranges(a..=b.max(a + 1.0), r.top() + 1.0..=r.bottom() - 1.0);
1952            hits.push(ClipHit {
1953                id: c.id,
1954                row,
1955                rect,
1956                visible: rect.intersect(lanes),
1957            });
1958        }
1959    }
1960    hits
1961}
1962
1963/// A click on clip `id`: it alone selected; with Ctrl, in or out of the
1964/// selection; with Shift, added to it.
1965fn select_clip(state: &mut TimelineState, id: u64, mods: Modifiers) {
1966    state.selected = None;
1967    if mods.command || mods.ctrl {
1968        if let Some(at) = state.selected_clips.iter().position(|c| *c == id) {
1969            state.selected_clips.remove(at);
1970        } else {
1971            state.selected_clips.push(id);
1972        }
1973    } else if mods.shift {
1974        state.selected_clips.retain(|c| *c != id);
1975        state.selected_clips.push(id);
1976    } else {
1977        state.selected_clips = vec![id];
1978    }
1979}
1980
1981/// Clip `id` alone selected, and announced.
1982fn reach_clip(ctx: &egui::Context, state: &mut TimelineState, id: u64) {
1983    state.selected = None;
1984    state.selected_clips = vec![id];
1985    if let (Some(c), Some(t)) = (state.clip(id), state.clip_track(id)) {
1986        let name = clip_name(ctx, state, c, &t.name);
1987        a11y::announce(ctx, name, Politeness::Polite);
1988    }
1989}
1990
1991/// The selected clips' moves `to` gives (a start and a track's index), or
1992/// none when one has nowhere to go.
1993fn clip_moves(
1994    state: &TimelineState,
1995    to: impl Fn(usize, &Clip) -> Option<(f64, usize)>,
1996) -> Vec<ClipMove> {
1997    let mut moves = Vec::new();
1998    for id in &state.selected_clips {
1999        let Some((row, at)) = state.locate(*id) else {
2000            continue;
2001        };
2002        let c = &state.tracks[row].clips[at];
2003        let Some((start, r)) = to(row, c) else {
2004            return Vec::new();
2005        };
2006        moves.push(ClipMove {
2007            id: *id,
2008            track: state.tracks[r].id,
2009            start,
2010        });
2011    }
2012    moves
2013}
2014
2015/// "Marker 3", the next one's default label.
2016fn new_marker_label(ctx: &egui::Context, state: &TimelineState) -> String {
2017    let n = state.markers.len() + 1;
2018    tr_with(ctx, &txt::TIMELINE_NEW_MARKER, &[("number", n.into())])
2019}
2020
2021/// A clip's accessible name: "Clip Intro on V1, 00:00:00:00 to 00:00:04:00".
2022fn clip_name(ctx: &egui::Context, state: &TimelineState, c: &Clip, track: &str) -> String {
2023    tr_args(
2024        ctx,
2025        &txt::TIMELINE_CLIP,
2026        &[
2027            ("label", &c.label),
2028            ("track", track),
2029            ("start", &state.scale.format(c.start)),
2030            ("end", &state.scale.format(c.end())),
2031        ],
2032    )
2033}
2034
2035/// A marker's accessible name: "Marker Drop at 1.1.000".
2036fn marker_name(ctx: &egui::Context, state: &TimelineState, m: &Marker) -> String {
2037    let key = match m.kind {
2038        MarkerKind::Marker => &txt::TIMELINE_MARKER,
2039        MarkerKind::Cue => &txt::TIMELINE_CUE,
2040    };
2041    tr_args(
2042        ctx,
2043        key,
2044        &[("label", &m.label), ("time", &state.scale.format(m.time))],
2045    )
2046}
2047
2048/// The store's document into `state` when it changed there (an undo):
2049/// whether it did. Declares the path, and seeds it with `state`'s document
2050/// the first time.
2051fn sync(app: &AppHandle, path: &str, state: &mut TimelineState, mem: &mut Memory) -> bool {
2052    let store = app.store();
2053    let mut s = lock(&store);
2054    if s.get(path).is_none()
2055        && s.declare(&OwnerId::FRAMEWORK, path, Descriptor::text("Timeline", ""))
2056            .is_err()
2057    {
2058        return false;
2059    }
2060    let text = s
2061        .get(path)
2062        .and_then(|e| e.value.as_text().map(str::to_string))
2063        .unwrap_or_default();
2064    if text.is_empty() {
2065        let json = serde_json::to_string(&state.doc()).unwrap_or_default();
2066        let _ = s.set(
2067            Set::new(path, Change::To(Value::Text(json.clone())), Origin::User)
2068                .untracked()
2069                .force(),
2070        );
2071        mem.text = Some(json);
2072        return false;
2073    }
2074    if mem.text.as_deref() == Some(text.as_str()) {
2075        return false;
2076    }
2077    let Ok(doc) = serde_json::from_str::<TimelineDoc>(&text) else {
2078        return false;
2079    };
2080    mem.text = Some(text);
2081    if doc == state.doc() {
2082        return false;
2083    }
2084    state.set_doc(doc);
2085    true
2086}
2087
2088/// Writes `state`'s document to the store as one step named `label`.
2089fn commit(
2090    app: &AppHandle,
2091    path: &str,
2092    state: &TimelineState,
2093    label: &str,
2094    origin: &Origin,
2095    mem: &mut Memory,
2096) {
2097    let json = serde_json::to_string(&state.doc()).unwrap_or_default();
2098    let store = app.store();
2099    let mut s = lock(&store);
2100    if s.get(path).is_none() {
2101        let _ = s.declare(&OwnerId::FRAMEWORK, path, Descriptor::text("Timeline", ""));
2102    }
2103    let group = s.begin_group(origin.clone(), label);
2104    let _ = s.set(
2105        Set::new(path, Change::To(Value::Text(json.clone())), origin.clone())
2106            .gesture(group)
2107            .force(),
2108    );
2109    s.end(group);
2110    mem.text = Some(json);
2111}
2112
2113/// The ruler, the range and the grid, under the lanes.
2114#[allow(
2115    clippy::too_many_arguments,
2116    reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
2117)]
2118fn paint_base(
2119    p: &egui::Painter,
2120    tk: &TimelineTokens,
2121    state: &TimelineState,
2122    mem: &Memory,
2123    rect: Rect,
2124    ruler: Rect,
2125    ticks: Ticks,
2126    font: &FontId,
2127) {
2128    let width = rect.width();
2129    p.rect_filled(rect, 0.0, tk.background);
2130    p.rect_filled(ruler, 0.0, tk.ruler_fill);
2131    let x_of = |t: f64| rect.left() + state.view.x_of(t, width);
2132    // The range: a fill down the lanes, a band under the ruler's ticks.
2133    if let Some(r) = mem.preview.or(state.range) {
2134        let (a, b) = (x_of(r.start), x_of(r.end));
2135        let span = Rect::from_x_y_ranges(a..=b, ruler.bottom()..=rect.bottom()).intersect(rect);
2136        p.rect_filled(span, 0.0, tk.range_fill);
2137        let edge = if state.looping {
2138            tk.range_edge
2139        } else {
2140            tk.range_edge_idle
2141        };
2142        let band =
2143            Rect::from_x_y_ranges(a..=b, ruler.bottom() - 3.0..=ruler.bottom()).intersect(rect);
2144        p.rect_filled(band, 0.0, edge);
2145        for x in [a, b] {
2146            if x >= rect.left() && x <= rect.right() {
2147                p.line_segment(
2148                    [pos2(x, ruler.bottom()), pos2(x, rect.bottom())],
2149                    Stroke::new(1.0, edge),
2150                );
2151            }
2152        }
2153    }
2154    let marks = ruler::marks(&state.scale, &state.view, width, ticks);
2155    let mut last_end = f32::NEG_INFINITY;
2156    for m in &marks {
2157        let x = rect.left() + m.x;
2158        if x < rect.left() - 1.0 || x > rect.right() + 1.0 {
2159            continue;
2160        }
2161        let h = if m.major { 0.45 } else { 0.2 } * ruler.height();
2162        p.line_segment(
2163            [pos2(x, ruler.bottom() - h), pos2(x, ruler.bottom())],
2164            Stroke::new(1.0, tk.ruler_tick),
2165        );
2166        if m.major {
2167            p.line_segment(
2168                [pos2(x, ruler.bottom()), pos2(x, rect.bottom())],
2169                Stroke::new(1.0, tk.grid),
2170            );
2171        }
2172    }
2173    // The labels, never over one another.
2174    for m in marks.iter().filter(|m| m.major) {
2175        let x = rect.left() + m.x + ruler::LABEL_INSET;
2176        let Some(label) = &m.label else { continue };
2177        let galley = p.layout_no_wrap(label.clone(), font.clone(), tk.ruler_text);
2178        let w = galley.size().x;
2179        if x + w < rect.left() || x > rect.right() || x < last_end {
2180            continue;
2181        }
2182        last_end = x + w + ruler::LABEL_GAP / 2.0;
2183        p.galley(pos2(x, ruler.top() + 2.0), galley, tk.ruler_text);
2184    }
2185    p.line_segment(
2186        [ruler.left_bottom(), ruler.right_bottom()],
2187        Stroke::new(1.0, tk.ruler_border),
2188    );
2189}
2190
2191/// The tracks' rows and names, and their clips: each its box, what the
2192/// painter draws in it, its selection and the edge the pointer would trim.
2193#[allow(
2194    clippy::too_many_arguments,
2195    reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
2196)]
2197fn paint_tracks(
2198    p: &egui::Painter,
2199    tk: &TimelineTokens,
2200    state: &TimelineState,
2201    rows: &[Rect],
2202    lanes: &Lanes,
2203    clip_painter: &mut dyn ClipPainter,
2204    hovered: Option<u64>,
2205    edge: Option<(u64, ClipEdge)>,
2206) {
2207    let font = FontId::proportional(tk.font_size);
2208    for (t, r) in state.tracks.iter().zip(rows) {
2209        p.line_segment(
2210            [r.left_bottom(), r.right_bottom()],
2211            Stroke::new(1.0, tk.track_border),
2212        );
2213        if !t.name.is_empty() {
2214            p.text(
2215                r.left_bottom() + vec2(4.0, -2.0),
2216                egui::Align2::LEFT_BOTTOM,
2217                &t.name,
2218                font.clone(),
2219                tk.track_text,
2220            );
2221        }
2222    }
2223    let x_of = |t: f64| lanes.x_of(t);
2224    for hit in clip_hits(state, rows, lanes.rect, &x_of) {
2225        let (track, clip) = (&state.tracks[hit.row], state.clip(hit.id));
2226        let Some(clip) = clip else { continue };
2227        let selected = state.selected_clips.contains(&clip.id);
2228        let (fill, border) = match clip.color {
2229            Some(c) => (c.gamma_multiply(0.5), c),
2230            None => (tk.clip_fill, tk.clip_border),
2231        };
2232        let radius = tk.radius.min(3.0);
2233        p.rect_filled(hit.rect, radius, fill);
2234        let label_h = tk.font_size + 4.0;
2235        let content = if hit.rect.height() >= label_h * 2.0 + 4.0 {
2236            Rect::from_min_max(
2237                pos2(hit.rect.left(), hit.rect.top() + label_h),
2238                pos2(hit.rect.right(), hit.rect.bottom() - 2.0),
2239            )
2240        } else {
2241            hit.rect.shrink2(vec2(0.0, 2.0))
2242        };
2243        let inside = p.with_clip_rect(hit.visible.intersect(p.clip_rect()));
2244        clip_painter.paint(
2245            &inside,
2246            &ClipPaint {
2247                clip,
2248                track,
2249                rect: hit.rect,
2250                visible: hit.visible,
2251                content,
2252                lanes,
2253                scale: &state.scale,
2254                selected,
2255                hovered: hovered == Some(clip.id),
2256                tokens: tk,
2257            },
2258        );
2259        let (width, color) = if selected {
2260            (2.0, tk.clip_selected)
2261        } else {
2262            (1.0, border)
2263        };
2264        p.rect_stroke(
2265            hit.rect,
2266            radius,
2267            Stroke::new(width, color),
2268            StrokeKind::Inside,
2269        );
2270        if let Some((id, e)) = edge
2271            && id == clip.id
2272        {
2273            let x = match e {
2274                ClipEdge::Start => hit.rect.left() + 1.5,
2275                ClipEdge::End => hit.rect.right() - 1.5,
2276            };
2277            p.line_segment(
2278                [pos2(x, hit.rect.top()), pos2(x, hit.rect.bottom())],
2279                Stroke::new(3.0, tk.clip_selected),
2280            );
2281        }
2282    }
2283}
2284
2285/// The markers and the playhead, over the lanes.
2286#[allow(
2287    clippy::too_many_arguments,
2288    reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
2289)]
2290fn paint_over(
2291    p: &egui::Painter,
2292    tk: &TimelineTokens,
2293    state: &TimelineState,
2294    rect: Rect,
2295    lane: Rect,
2296    ruler: Rect,
2297    font: &FontId,
2298    ctx: &egui::Context,
2299) {
2300    let width = rect.width();
2301    let x_of = |t: f64| rect.left() + state.view.x_of(t, width);
2302    for m in &state.markers {
2303        let x = x_of(m.time);
2304        if x < rect.left() - 1.0 || x > rect.right() + 1.0 {
2305            continue;
2306        }
2307        let color = m.color.unwrap_or(tk.marker);
2308        p.line_segment(
2309            [pos2(x, lane.top()), pos2(x, rect.bottom())],
2310            Stroke::new(1.0, color.gamma_multiply(0.7)),
2311        );
2312        let top = lane.top() + 2.0;
2313        let head = match m.kind {
2314            // A flag on its pole.
2315            MarkerKind::Marker => {
2316                let flag = Rect::from_min_size(pos2(x, top), vec2(7.0, 7.0));
2317                p.rect_filled(flag, 1.0, color);
2318                flag
2319            }
2320            // A pin pointing down at its time.
2321            MarkerKind::Cue => {
2322                let pin = vec![pos2(x - 5.0, top), pos2(x + 5.0, top), pos2(x, top + 8.0)];
2323                let bounds = Rect::from_min_max(pos2(x - 5.0, top), pos2(x + 5.0, top + 8.0));
2324                p.add(Shape::convex_polygon(pin, color, Stroke::NONE));
2325                bounds
2326            }
2327        };
2328        let mut around = head;
2329        if !m.label.is_empty() {
2330            let galley = p.layout_no_wrap(m.label.clone(), font.clone(), tk.marker_text);
2331            let at = pos2(head.right() + 3.0, lane.center().y - galley.size().y / 2.0);
2332            around = around.union(Rect::from_min_size(at, galley.size()));
2333            p.galley(at, galley, tk.marker_text);
2334        }
2335        if state.selected == Some(m.id) {
2336            p.rect_stroke(
2337                around.expand(2.0),
2338                tk.radius.min(3.0),
2339                Stroke::new(1.0, tk.marker_selected),
2340                StrokeKind::Outside,
2341            );
2342        }
2343    }
2344    // The playhead: a head on the ruler, a line down the lanes.
2345    let x = x_of(state.playhead);
2346    if x >= rect.left() - 6.0 && x <= rect.right() + 6.0 {
2347        p.line_segment(
2348            [pos2(x, ruler.top()), pos2(x, rect.bottom())],
2349            Stroke::new(1.5, tk.playhead),
2350        );
2351        let head: Vec<Pos2> = vec![
2352            pos2(x - 6.0, ruler.top()),
2353            pos2(x + 6.0, ruler.top()),
2354            pos2(x + 6.0, ruler.top() + 5.0),
2355            pos2(x, ruler.top() + 11.0),
2356            pos2(x - 6.0, ruler.top() + 5.0),
2357        ];
2358        p.add(Shape::convex_polygon(head, tk.playhead, Stroke::NONE));
2359        // Shuttling: the speed beside the head.
2360        if state.is_playing() && state.speed != 1.0 {
2361            let speed = format_speed(state.speed);
2362            let text = tr_args(ctx, &txt::TIMELINE_SPEED, &[("speed", &speed)]);
2363            let galley = p.layout_no_wrap(text, font.clone(), tk.badge_text);
2364            let size = galley.size() + vec2(6.0, 2.0);
2365            let at = if x + 8.0 + size.x <= rect.right() {
2366                pos2(x + 8.0, ruler.top() + 1.0)
2367            } else {
2368                pos2(x - 8.0 - size.x, ruler.top() + 1.0)
2369            };
2370            let badge = Rect::from_min_size(at, size);
2371            p.rect_filled(badge, tk.radius.min(3.0), tk.badge_fill);
2372            p.galley(badge.center() - galley.size() / 2.0, galley, tk.badge_text);
2373        }
2374    }
2375}
2376
2377/// `2`, `-4`, `0.5`.
2378fn format_speed(speed: f64) -> String {
2379    if speed.fract() == 0.0 {
2380        format!("{}", speed as i64)
2381    } else {
2382        format!("{speed}")
2383    }
2384}
2385
2386#[cfg(test)]
2387mod tests {
2388    use super::*;
2389
2390    #[test]
2391    fn keys_map_with_their_exact_modifiers() {
2392        let none = Modifiers::NONE;
2393        let shift = Modifiers::SHIFT;
2394        let ctrl = Modifiers::COMMAND;
2395        let alt = Modifiers::ALT;
2396        let act = |k, m| key_act(k, m, false, false, true);
2397        assert_eq!(act(Key::Space, none), Some(KeyAct::Toggle));
2398        assert_eq!(act(Key::L, none), Some(KeyAct::Shuttle(true)));
2399        assert_eq!(act(Key::L, ctrl), Some(KeyAct::ToggleLoop));
2400        assert_eq!(act(Key::ArrowLeft, shift), Some(KeyAct::Step(-1.0, true)));
2401        assert_eq!(act(Key::ArrowRight, ctrl), Some(KeyAct::Nudge(1.0, false)));
2402        assert_eq!(act(Key::I, shift), Some(KeyAct::GoIn));
2403        assert_eq!(act(Key::X, alt), Some(KeyAct::ClearRange));
2404        assert_eq!(act(Key::X, none), None);
2405        assert_eq!(act(Key::M, ctrl), None);
2406        // K held: J and L step.
2407        assert_eq!(
2408            key_act(Key::L, none, false, true, false),
2409            Some(KeyAct::Step(1.0, false))
2410        );
2411        // A held Space does not toggle again and again.
2412        assert_eq!(key_act(Key::Space, none, true, false, false), None);
2413        // Clips: Page Up and Down walk a track, Shift crosses tracks, Ctrl
2414        // moves them across tracks, the brackets trim.
2415        assert_eq!(act(Key::PageDown, none), Some(KeyAct::ClipWalk(true)));
2416        assert_eq!(act(Key::ArrowUp, shift), Some(KeyAct::ClipAcross(true)));
2417        assert_eq!(act(Key::ArrowUp, alt), None);
2418        assert_eq!(act(Key::ArrowDown, ctrl), Some(KeyAct::ClipTrack(false)));
2419        assert_eq!(
2420            act(Key::CloseBracket, none),
2421            Some(KeyAct::Trim(ClipEdge::End))
2422        );
2423        // Delete and Escape only with a marker or a clip selected.
2424        assert_eq!(key_act(Key::Delete, none, false, false, false), None);
2425        assert_eq!(key_act(Key::Escape, none, false, false, false), None);
2426    }
2427
2428    #[test]
2429    fn ops_report_edits_and_transport() {
2430        let mut s = TimelineState::new(TimeScale::Seconds, 60.0);
2431        let done = apply(&mut s, Op::Shuttle(true));
2432        assert!(done.transport && done.edits.is_empty());
2433        let done = apply(&mut s, Op::SetRange(Some(TimeRange::new(5.0, 2.0))));
2434        assert_eq!(
2435            done.edits,
2436            [Edit::RangeSet {
2437                from: None,
2438                to: Some(TimeRange::new(2.0, 5.0))
2439            }]
2440        );
2441        // The same again changes nothing.
2442        let done = apply(&mut s, Op::SetRange(Some(TimeRange::new(2.0, 5.0))));
2443        assert!(done.edits.is_empty());
2444        let done = apply(&mut s, Op::AddMarker(Marker::new(0, 3.0, "A")));
2445        assert!(matches!(done.edits[..], [Edit::MarkerAdded(_)]));
2446        assert_eq!(s.selected, Some(1));
2447        let done = apply(&mut s, Op::SetTime(7.0));
2448        assert!(done.moved && done.edits.is_empty());
2449        // Clips: a refusal is said, several moved are one step.
2450        let v = s.add_track(Track::new(0, "V1"));
2451        let done = apply(
2452            &mut s,
2453            Op::AddClip {
2454                track: v,
2455                clip: Clip::new(0, 0.0, 4.0, "A"),
2456            },
2457        );
2458        assert!(matches!(done.edits[..], [Edit::ClipAdded { .. }]));
2459        assert_eq!((s.selected, &s.selected_clips[..]), (None, &[1][..]));
2460        let done = apply(
2461            &mut s,
2462            Op::AddClip {
2463                track: v,
2464                clip: Clip::new(0, 2.0, 4.0, "B"),
2465            },
2466        );
2467        assert_eq!(done.error.as_deref(), Some("it would overlap clip 1"));
2468        let b = s.add_clip(v, Clip::new(0, 10.0, 4.0, "B")).unwrap();
2469        let moves = [1, b].map(|id| ClipMove {
2470            id,
2471            track: v,
2472            start: s.clip(id).unwrap().start + 1.0,
2473        });
2474        let done = apply(&mut s, Op::MoveClips(moves.to_vec()));
2475        assert_eq!(edit_label(&done.edits), Some(&txt::TIMELINE_MOVE_CLIPS));
2476        let done = apply(&mut s, Op::RemoveClips(vec![b, 99]));
2477        assert_eq!(done.error.as_deref(), Some("no clip 99"));
2478        assert!(s.clip(b).is_some(), "nothing removed");
2479        assert_eq!(format_speed(-4.0), "-4");
2480        assert_eq!(format_speed(0.5), "0.5");
2481    }
2482}