Skip to main content

egui_pop_views/timeline/
plugin.rs

1//! [`TimelinePlugin`]: the `timeline.*` commands and the `timeline`
2//! collector, the agents' way to the [`Timeline`](super::Timeline) widgets
3//! given an id; and [`Timelines`], the context's registry of them.
4//!
5//! | Command | Arguments | Does |
6//! |---|---|---|
7//! | `timeline.set_time` | `timeline`, `seconds`, `time` (text in the timeline's scale) or `by` | moves the playhead, kept inside the bounds |
8//! | `timeline.set_range` | `timeline`, `start` and `end` (seconds), or `clear`; `loop` | sets or clears the range, and whether playback loops round it |
9//! | `timeline.add_marker` | `timeline`, `seconds` or `time` (else the playhead), `label`, `kind` (`marker`, `cue`), `color` (`#rrggbb`) | adds a marker; answers its `id` |
10//! | `timeline.remove_marker` | `timeline`, `id` | removes a marker |
11//! | `timeline.play` | `timeline`, `speed` (1 by default, negative backwards) | asks to play |
12//! | `timeline.pause` | `timeline` | asks to pause (K) |
13//! | `timeline.toggle_play` | `timeline` | plays forward at 1, or pauses (Space) |
14//! | `timeline.shuttle_forward`, `timeline.shuttle_backward` | `timeline` | plays that way, twice as fast again (L, J) |
15//! | `timeline.step_forward`, `timeline.step_backward` | `timeline`, `big` | one unit on or back, pausing (Right, Left; `big`: Shift's step) |
16//! | `timeline.go_to_start`, `timeline.go_to_end` | `timeline` | the bounds' start or end (Home, End) |
17//! | `timeline.toggle_loop` | `timeline` | loops the range, or no longer (Ctrl+L) |
18//! | `timeline.add_clip` | `timeline`, `track`, `seconds` or `time` (else the playhead), `length`, `offset`, `label`, `source`, `source_length`, `color` | adds a clip to a track; answers its `id` |
19//! | `timeline.move_clip` | `timeline`, `id`, `seconds` or `time`, `track` | moves a clip along its track or to another |
20//! | `timeline.trim_clip` | `timeline`, `id`, `start`, `end` (seconds) | moves a clip's start or end |
21//! | `timeline.remove_clip` | `timeline`, `id` or `ids` | removes clips |
22//! | `timeline.split_clip` | `timeline`, `id` or `ids`, `seconds` or `time` (else the playhead) | splits clips in two there; answers the new ones' ids |
23//! | `timeline.ripple_delete` | `timeline`, `id` or `ids` | removes clips and closes their gaps |
24//! | `timeline.select_clips` | `timeline`, `ids` | selects clips (an empty list: none) |
25//!
26//! `timeline` is a widget's id; without it, the timeline that last had the
27//! focus, else the only one drawn with an id. A command is checked and
28//! answered at once, with what the timeline then holds as the collector
29//! shows it; the widget applies it when next drawn, as a step of the history
30//! made by the command's origin.
31
32use std::collections::BTreeMap;
33use std::sync::{Arc, Mutex};
34
35use egui::{Color32, Context};
36#[cfg(feature = "api")]
37use egui_pop_api::{Call, Ctx, Plugin, PluginError};
38#[cfg(feature = "api")]
39use egui_pop_core::debug::FnCollector;
40use egui_pop_core::lock;
41use egui_pop_core::state::Slot;
42#[cfg(feature = "api")]
43use egui_pop_model::commands::CommandSpec;
44use egui_pop_model::commands::Origin;
45use egui_pop_model::ids::{CommandId, PluginId};
46use serde_json::{Value as Json, json};
47
48use super::Op;
49#[cfg(feature = "api")]
50use super::apply;
51use super::state::TimelineState;
52#[cfg(feature = "api")]
53use super::state::{Marker, MarkerKind, TimeRange};
54#[cfg(feature = "api")]
55use super::tracks::{Clip, ClipEdge, ClipMove};
56
57/// The plugin's id.
58pub const PLUGIN: PluginId = PluginId::from_static("egui_pop.timeline");
59
60pub const CMD_SET_TIME: CommandId = CommandId::from_static("timeline.set_time");
61pub const CMD_SET_RANGE: CommandId = CommandId::from_static("timeline.set_range");
62pub const CMD_ADD_MARKER: CommandId = CommandId::from_static("timeline.add_marker");
63pub const CMD_REMOVE_MARKER: CommandId = CommandId::from_static("timeline.remove_marker");
64pub const CMD_PLAY: CommandId = CommandId::from_static("timeline.play");
65pub const CMD_PAUSE: CommandId = CommandId::from_static("timeline.pause");
66pub const CMD_ADD_CLIP: CommandId = CommandId::from_static("timeline.add_clip");
67pub const CMD_MOVE_CLIP: CommandId = CommandId::from_static("timeline.move_clip");
68pub const CMD_TRIM_CLIP: CommandId = CommandId::from_static("timeline.trim_clip");
69pub const CMD_REMOVE_CLIP: CommandId = CommandId::from_static("timeline.remove_clip");
70pub const CMD_SELECT_CLIPS: CommandId = CommandId::from_static("timeline.select_clips");
71pub const CMD_SPLIT_CLIP: CommandId = CommandId::from_static("timeline.split_clip");
72pub const CMD_RIPPLE_DELETE: CommandId = CommandId::from_static("timeline.ripple_delete");
73pub const CMD_TOGGLE_PLAY: CommandId = CommandId::from_static("timeline.toggle_play");
74pub const CMD_SHUTTLE_FORWARD: CommandId = CommandId::from_static("timeline.shuttle_forward");
75pub const CMD_SHUTTLE_BACKWARD: CommandId = CommandId::from_static("timeline.shuttle_backward");
76pub const CMD_STEP_FORWARD: CommandId = CommandId::from_static("timeline.step_forward");
77pub const CMD_STEP_BACKWARD: CommandId = CommandId::from_static("timeline.step_backward");
78pub const CMD_GO_TO_START: CommandId = CommandId::from_static("timeline.go_to_start");
79pub const CMD_GO_TO_END: CommandId = CommandId::from_static("timeline.go_to_end");
80pub const CMD_TOGGLE_LOOP: CommandId = CommandId::from_static("timeline.toggle_loop");
81
82/// Passes a timeline may go undrawn before agents no longer see it.
83const GONE_AFTER: u64 = 3;
84
85/// Declares the `timeline.*` commands and the `timeline` collector. Connect
86/// it when an application's timelines should be read and driven by agents;
87/// the widgets work without it.
88#[cfg(feature = "api")]
89#[derive(Debug, Default)]
90pub struct TimelinePlugin;
91
92#[cfg(feature = "api")]
93impl Plugin for TimelinePlugin {
94    fn id(&self) -> PluginId {
95        PLUGIN
96    }
97
98    fn title(&self) -> String {
99        "Timeline".into()
100    }
101
102    fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
103        commands(ctx)?;
104        let egui = ctx.app().egui();
105        ctx.collector(
106            FnCollector::new(
107                "timeline",
108                "The timelines drawn with an id: their scale, view (start, duration, end), bounds, playhead (seconds and text), range and whether it loops, markers (id, time, text, label, kind, colour), the selected marker, the tracks (id, name, kind) and their clips (id, start, end, length, offset, text, label, source, source length, colour), the clips selected, the play state and speed asked; the one that last had the focus.",
109            )
110            .snapshot(move |_| Timelines::of(&egui).describe()),
111        )?;
112        Ok(())
113    }
114}
115
116/// One timeline drawn with an id.
117#[derive(Debug)]
118struct Entry {
119    /// As it was last drawn, with the commands since applied.
120    state: TimelineState,
121    pass: u64,
122    /// Commands waiting for the widget, with who ran them.
123    queue: Vec<(Op, Origin)>,
124}
125
126#[derive(Debug, Default)]
127struct Registry {
128    entries: BTreeMap<String, Entry>,
129    focused: Option<String>,
130}
131
132#[derive(Clone, Default)]
133struct Shared(Arc<Mutex<Registry>>);
134
135impl std::fmt::Debug for Shared {
136    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
137        lock(&self.0).fmt(f)
138    }
139}
140
141const SLOT: Slot<Shared> = Slot::new("views.timeline");
142
143/// The timelines drawn in a context, by id: what the `timeline.*` commands
144/// and the `timeline` collector reach.
145#[derive(Clone)]
146pub struct Timelines {
147    ctx: Context,
148    registry: Arc<Mutex<Registry>>,
149}
150
151impl std::fmt::Debug for Timelines {
152    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153        lock(&self.registry).fmt(f)
154    }
155}
156
157impl Timelines {
158    /// The context's timelines.
159    pub fn of(ctx: &Context) -> Self {
160        Self {
161            ctx: ctx.clone(),
162            registry: SLOT.get_or_insert_with(ctx, Shared::default).0,
163        }
164    }
165
166    fn live(&self, pass: u64) -> impl Fn(&Entry) -> bool {
167        move |e: &Entry| e.pass + GONE_AFTER >= pass
168    }
169
170    /// The ids of the timelines drawn lately.
171    pub fn ids(&self) -> Vec<String> {
172        let pass = self.ctx.cumulative_pass_nr();
173        let live = self.live(pass);
174        lock(&self.registry)
175            .entries
176            .iter()
177            .filter(|(_, e)| live(e))
178            .map(|(id, _)| id.clone())
179            .collect()
180    }
181
182    /// What every timeline drawn lately holds, and the one that last had the
183    /// focus.
184    pub fn describe(&self) -> Json {
185        let pass = self.ctx.cumulative_pass_nr();
186        let live = self.live(pass);
187        let mut reg = lock(&self.registry);
188        reg.entries.retain(|_, e| live(e));
189        let timelines: serde_json::Map<String, Json> = reg
190            .entries
191            .iter()
192            .map(|(id, e)| (id.clone(), describe(&e.state)))
193            .collect();
194        json!({ "timelines": timelines, "focused": reg.focused })
195    }
196
197    /// One timeline as the collector shows it.
198    pub fn get(&self, timeline: Option<&str>) -> Result<Json, String> {
199        let pass = self.ctx.cumulative_pass_nr();
200        let mut reg = lock(&self.registry);
201        let (_, e) = target(&mut reg, timeline, pass)?;
202        Ok(describe(&e.state))
203    }
204
205    /// Records a timeline drawn this pass (and whether it has the focus);
206    /// gives the commands waiting for it.
207    pub(super) fn drawn(&self, id: &str, state: &TimelineState) -> Vec<(Op, Origin)> {
208        let pass = self.ctx.cumulative_pass_nr();
209        let mut reg = lock(&self.registry);
210        let e = reg.entries.entry(id.to_string()).or_insert_with(|| Entry {
211            state: state.clone(),
212            pass,
213            queue: Vec::new(),
214        });
215        e.pass = pass;
216        let queue = std::mem::take(&mut e.queue);
217        // What the commands asked shows until the widget applies it.
218        if queue.is_empty() {
219            e.state.clone_from(state);
220        }
221        queue
222    }
223
224    /// The widget's state at the end of its pass, and whether it has the
225    /// focus.
226    pub(super) fn update(&self, id: &str, state: &TimelineState, focused: bool) {
227        let mut reg = lock(&self.registry);
228        if focused {
229            reg.focused = Some(id.to_string());
230        }
231        if let Some(e) = reg.entries.get_mut(id) {
232            e.state.clone_from(state);
233        }
234    }
235
236    /// Checks `op` on a timeline's last state, queues it for the widget and
237    /// answers what the timeline then holds.
238    #[cfg(feature = "api")]
239    pub(super) fn run(
240        &self,
241        timeline: Option<&str>,
242        op: Op,
243        origin: &Origin,
244    ) -> Result<Json, String> {
245        let pass = self.ctx.cumulative_pass_nr();
246        let answer = {
247            let mut reg = lock(&self.registry);
248            let (_, e) = target(&mut reg, timeline, pass)?;
249            let op = match op {
250                // The id it will take, said in the answer.
251                Op::AddMarker(mut m) => {
252                    m.id = e.state.next_id();
253                    Op::AddMarker(m)
254                }
255                Op::AddClip { track, mut clip } => {
256                    clip.id = e.state.next_clip_id();
257                    Op::AddClip { track, clip }
258                }
259                Op::RemoveMarker(id) if e.state.marker(id).is_none() => {
260                    return Err(format!("no marker {id}"));
261                }
262                op => op,
263            };
264            let added = match &op {
265                Op::AddMarker(m) => Some(m.id),
266                Op::AddClip { clip, .. } => Some(clip.id),
267                _ => None,
268            };
269            // Checked on the state the widget will have: a refusal queues
270            // nothing.
271            let mut tried = e.state.clone();
272            let applied = apply(&mut tried, op.clone());
273            if let Some(error) = applied.error {
274                return Err(error);
275            }
276            e.state = tried;
277            e.queue.push((op, origin.clone()));
278            let mut answer = describe(&e.state);
279            if let Some(id) = added {
280                answer["added"] = json!(id);
281            }
282            let split: Vec<u64> = applied
283                .edits
284                .iter()
285                .filter_map(|e| match e {
286                    super::Edit::ClipSplit { new, .. } => Some(*new),
287                    _ => None,
288                })
289                .collect();
290            if !split.is_empty() {
291                answer["added"] = json!(split);
292            }
293            answer
294        };
295        self.ctx.request_repaint();
296        Ok(answer)
297    }
298}
299
300/// The timeline a command names: `timeline`, else the one that last had the
301/// focus, else the only one drawn.
302fn target<'r>(
303    reg: &'r mut Registry,
304    timeline: Option<&str>,
305    pass: u64,
306) -> Result<(String, &'r mut Entry), String> {
307    let live = |e: &Entry| e.pass + GONE_AFTER >= pass;
308    let name = match timeline {
309        Some(t) => t.to_string(),
310        None => match reg
311            .focused
312            .clone()
313            .filter(|f| reg.entries.get(f).is_some_and(live))
314        {
315            Some(f) => f,
316            None => {
317                let mut names = reg.entries.iter().filter(|(_, e)| live(e)).map(|(n, _)| n);
318                match (names.next(), names.next()) {
319                    (Some(only), None) => only.clone(),
320                    (None, _) => return Err("no timeline with an id is drawn".into()),
321                    _ => {
322                        return Err(
323                            "several timelines have an id and none had the focus; name one with `timeline`"
324                                .into(),
325                        );
326                    }
327                }
328            }
329        },
330    };
331    match reg.entries.get_mut(&name) {
332        Some(e) if live(e) => Ok((name, e)),
333        _ => Err(format!("no timeline `{name}`")),
334    }
335}
336
337/// `#rrggbb`.
338fn hex(c: Color32) -> String {
339    format!("#{:02x}{:02x}{:02x}", c.r(), c.g(), c.b())
340}
341
342#[cfg(feature = "api")]
343fn parse_hex(text: &str) -> Option<Color32> {
344    let h = text.trim().strip_prefix('#')?;
345    if h.len() != 6 {
346        return None;
347    }
348    let v = u32::from_str_radix(h, 16).ok()?;
349    Some(Color32::from_rgb((v >> 16) as u8, (v >> 8) as u8, v as u8))
350}
351
352/// A timeline as agents read it.
353pub fn describe(s: &TimelineState) -> Json {
354    let text = |t: f64| s.scale.format(t);
355    let scale = match s.scale {
356        super::TimeScale::Seconds => json!({ "kind": "seconds" }),
357        super::TimeScale::Frames(r) => {
358            json!({ "kind": "frames", "fps": r.fps(), "rate": [r.num, r.den] })
359        }
360        super::TimeScale::Beats(t) => json!({
361            "kind": "beats",
362            "bpm": t.bpm,
363            "signature": [t.beats_per_bar, t.beat_unit],
364            "offset": t.offset,
365        }),
366    };
367    json!({
368        "scale": scale,
369        "view": { "start": s.view.start, "duration": s.view.duration, "end": s.view.end() },
370        "bounds": s.bounds.map(|b| json!({ "start": b.start, "end": b.end })),
371        "playhead": { "seconds": s.playhead, "text": text(s.playhead) },
372        "range": s.range.map(|r| json!({
373            "start": r.start,
374            "end": r.end,
375            "text": [text(r.start), text(r.end)],
376        })),
377        "looping": s.looping,
378        "markers": s.markers.iter().map(|m| json!({
379            "id": m.id,
380            "seconds": m.time,
381            "text": text(m.time),
382            "label": m.label,
383            "kind": m.kind,
384            "color": m.color.map(hex),
385        })).collect::<Vec<_>>(),
386        "selected": s.selected,
387        "tracks": s.tracks.iter().map(|t| json!({
388            "id": t.id,
389            "name": t.name,
390            "kind": t.kind,
391            "clips": t.clips.iter().map(|c| json!({
392                "id": c.id,
393                "seconds": c.start,
394                "end": c.end(),
395                "length": c.length,
396                "offset": c.offset,
397                "text": [text(c.start), text(c.end())],
398                "label": c.label,
399                "source": c.source,
400                "source_length": c.source_length,
401                "color": c.color.map(hex),
402            })).collect::<Vec<_>>(),
403        })).collect::<Vec<_>>(),
404        "selected_clips": s.selected_clips,
405        "play": s.play,
406        "speed": s.speed,
407    })
408}
409
410#[cfg(feature = "api")]
411fn timelines(call: &Call<'_>) -> Timelines {
412    Timelines::of(&call.app.egui())
413}
414
415/// The `timeline` argument.
416#[cfg(feature = "api")]
417fn name(args: &Json) -> Option<&str> {
418    args.get("timeline").and_then(Json::as_str)
419}
420
421/// A time from `seconds` (a number) or `time` (text in the scale), on the
422/// timeline `name`.
423#[cfg(feature = "api")]
424fn time_of(t: &Timelines, args: &Json) -> Result<Option<f64>, String> {
425    if let Some(s) = args.get("seconds") {
426        return s
427            .as_f64()
428            .map(Some)
429            .ok_or_else(|| "`seconds` is a number".into());
430    }
431    let Some(text) = args.get("time") else {
432        return Ok(None);
433    };
434    let text = text.as_str().ok_or("`time` is text")?;
435    scale_of(t, name(args))?
436        .parse(text)
437        .map(Some)
438        .ok_or_else(|| format!("`{text}` is not a time on this timeline"))
439}
440
441#[cfg(feature = "api")]
442fn scale_of(t: &Timelines, timeline: Option<&str>) -> Result<super::TimeScale, String> {
443    let pass = t.ctx.cumulative_pass_nr();
444    let mut reg = lock(&t.registry);
445    target(&mut reg, timeline, pass).map(|(_, e)| e.state.scale)
446}
447
448/// A transport key's command: its id, title, description and op (given
449/// `big`).
450#[cfg(feature = "api")]
451type TransportCommand = (CommandId, &'static str, &'static str, fn(bool) -> Op);
452
453#[cfg(feature = "api")]
454fn commands(ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
455    const CAT: &str = "Timeline";
456    let timeline = "song (optional: the timeline that last had the focus)";
457    ctx.command(
458        CommandSpec::new(CMD_SET_TIME, "Move a timeline's playhead", CAT)
459            .description("Moves a timeline's playhead (`timeline`, its id) to `seconds`, to `time` (text in the timeline's scale: `1:02.5`, `00:01:02:12`, `17.2.480`), or by `by` seconds; kept inside its bounds.")
460            .args(json!({ "timeline": timeline, "seconds": 12.5 })),
461        |call| {
462            let t = timelines(call);
463            let to = match (time_of(&t, call.args)?, call.args.get("by").and_then(Json::as_f64)) {
464                (Some(s), _) => Op::SetTime(s),
465                (None, Some(by)) => Op::StepBy(by),
466                (None, None) => return Err("`seconds`, `time` or `by` is needed".into()),
467            };
468            t.run(name(call.args), to, call.origin)
469        },
470    )?;
471    ctx.command(
472        CommandSpec::new(CMD_SET_RANGE, "Set a timeline's range", CAT)
473            .description("Sets a timeline's range from `start` to `end` (seconds), or clears it (`clear`: true); `loop` says whether playback goes round it. One step of the history.")
474            .args(json!({ "timeline": timeline, "start": 4.0, "end": 8.0, "loop": true })),
475        |call| {
476            let t = timelines(call);
477            let args = call.args;
478            let tl = name(args);
479            let clear = args.get("clear").and_then(Json::as_bool).unwrap_or(false);
480            let start = args.get("start").and_then(Json::as_f64);
481            let end = args.get("end").and_then(Json::as_f64);
482            let looping = args.get("loop").and_then(Json::as_bool);
483            let range = match (clear, start, end) {
484                (true, _, _) => Some(None),
485                (false, Some(a), Some(b)) => Some(Some(TimeRange::new(a, b))),
486                (false, None, None) => None,
487                _ => return Err("`start` and `end` go together".into()),
488            };
489            if range.is_none() && looping.is_none() {
490                return Err("`start` and `end`, `clear` or `loop` is needed".into());
491            }
492            let mut answer = Json::Null;
493            if let Some(r) = range {
494                answer = t.run(tl, Op::SetRange(r), call.origin)?;
495            }
496            if let Some(l) = looping {
497                answer = t.run(tl, Op::SetLoop(l), call.origin)?;
498            }
499            Ok(answer)
500        },
501    )?;
502    ctx.command(
503        CommandSpec::new(CMD_ADD_MARKER, "Add a marker to a timeline", CAT)
504            .description("Adds a marker to a timeline at `seconds` or `time` (else at the playhead), named `label`, of `kind` `marker` or `cue`, in `color` (`#rrggbb`, else the theme's). Answers its `id` in `added`. One step of the history.")
505            .args(json!({ "timeline": timeline, "seconds": 30.0, "label": "Drop", "kind": "cue", "color": "#ff8800" })),
506        |call| {
507            let t = timelines(call);
508            let args = call.args;
509            let at = match time_of(&t, args)? {
510                Some(s) => s,
511                None => t.get(name(args))?["playhead"]["seconds"].as_f64().unwrap_or(0.0),
512            };
513            let label = args.get("label").and_then(Json::as_str).unwrap_or("").to_string();
514            let kind = match args.get("kind").and_then(Json::as_str) {
515                None | Some("marker") => MarkerKind::Marker,
516                Some("cue") => MarkerKind::Cue,
517                Some(other) => return Err(format!("`kind` is `marker` or `cue`, not `{other}`")),
518            };
519            let mut m = Marker::new(0, at, label).kind(kind);
520            if let Some(c) = args.get("color").and_then(Json::as_str) {
521                m.color = Some(parse_hex(c).ok_or_else(|| format!("`{c}` is not `#rrggbb`"))?);
522            }
523            t.run(name(args), Op::AddMarker(m), call.origin)
524        },
525    )?;
526    ctx.command(
527        CommandSpec::new(CMD_REMOVE_MARKER, "Remove a marker from a timeline", CAT)
528            .description("Removes a timeline's marker `id`. One step of the history.")
529            .args(json!({ "timeline": timeline, "id": 1 })),
530        |call| {
531            let id = call
532                .args
533                .get("id")
534                .and_then(Json::as_u64)
535                .ok_or("`id` is a marker's id")?;
536            timelines(call).run(name(call.args), Op::RemoveMarker(id), call.origin)
537        },
538    )?;
539    ctx.command(
540        CommandSpec::new(CMD_PLAY, "Play a timeline", CAT)
541            .description("Asks a timeline to play at `speed` (1 by default, negative backwards); the application moves the time.")
542            .args(json!({ "timeline": timeline, "speed": 1.0 })),
543        |call| {
544            let speed = call.args.get("speed").and_then(Json::as_f64).unwrap_or(1.0);
545            timelines(call).run(name(call.args), Op::Play(speed), call.origin)
546        },
547    )?;
548    ctx.command(
549        CommandSpec::new(CMD_PAUSE, "Pause a timeline", CAT)
550            .description("Asks a timeline to pause.")
551            .args(json!({ "timeline": timeline })),
552        |call| timelines(call).run(name(call.args), Op::Pause, call.origin),
553    )?;
554    // The transport's keys, one command each (a `Transport`'s buttons run
555    // them): what they do is the key's, applied at the timeline's pass.
556    let transport: [TransportCommand; 7] = [
557        (
558            CMD_TOGGLE_PLAY,
559            "Play or pause a timeline",
560            "Asks a timeline to play forward at 1, or to pause when it plays, as Space does.",
561            |_| Op::Toggle,
562        ),
563        (
564            CMD_SHUTTLE_FORWARD,
565            "Shuttle a timeline forward",
566            "Asks a timeline to play forward at 1, or twice as fast when it already does (up to 32×), as L does.",
567            |_| Op::Shuttle(true),
568        ),
569        (
570            CMD_SHUTTLE_BACKWARD,
571            "Shuttle a timeline backward",
572            "Asks a timeline to play backward at 1, or twice as fast when it already does, as J does.",
573            |_| Op::Shuttle(false),
574        ),
575        (
576            CMD_STEP_FORWARD,
577            "Step a timeline forward",
578            "Moves a timeline's playhead one unit on (a frame, a beat, a second), or Shift's bigger step with `big`, and pauses, as Right does.",
579            |big| Op::Step { forward: true, big },
580        ),
581        (
582            CMD_STEP_BACKWARD,
583            "Step a timeline backward",
584            "Moves a timeline's playhead one unit back, or Shift's bigger step with `big`, and pauses, as Left does.",
585            |big| Op::Step {
586                forward: false,
587                big,
588            },
589        ),
590        (
591            CMD_GO_TO_START,
592            "Go to a timeline's start",
593            "Moves a timeline's playhead to its bounds' start, as Home does.",
594            |_| Op::Home,
595        ),
596        (
597            CMD_GO_TO_END,
598            "Go to a timeline's end",
599            "Moves a timeline's playhead to its bounds' end, as End does.",
600            |_| Op::End,
601        ),
602    ];
603    for (id, title, description, op) in transport {
604        let args = if matches!(op(false), Op::Step { .. }) {
605            json!({ "timeline": timeline, "big": false })
606        } else {
607            json!({ "timeline": timeline })
608        };
609        ctx.command(
610            CommandSpec::new(id, title, CAT)
611                .description(description)
612                .args(args),
613            move |call| {
614                let big = call
615                    .args
616                    .get("big")
617                    .and_then(Json::as_bool)
618                    .unwrap_or(false);
619                timelines(call).run(name(call.args), op(big), call.origin)
620            },
621        )?;
622    }
623    ctx.command(
624        CommandSpec::new(CMD_TOGGLE_LOOP, "Loop a timeline's range or not", CAT)
625            .description("Turns a timeline's looping round its range on, or off, as Ctrl+L does. One step of the history.")
626            .args(json!({ "timeline": timeline })),
627        |call| timelines(call).run(name(call.args), Op::ToggleLoop, call.origin),
628    )?;
629    ctx.command(
630        CommandSpec::new(CMD_ADD_CLIP, "Add a clip to a timeline", CAT)
631            .description("Adds a clip to a timeline's track `track` (its id), starting at `seconds` or `time` (else at the playhead), `length` seconds long, reading its source from `offset` seconds in; `label`, `source` (what it plays, for the application), `source_length` (trimming stops at the source's ends) and `color` (`#rrggbb`) are optional. Refused where it would overlap a clip. Answers its `id` in `added`. One step of the history.")
632            .args(json!({ "timeline": timeline, "track": 1, "seconds": 4.0, "length": 2.5, "label": "Take 2", "source": "take2.mov" })),
633        |call| {
634            let t = timelines(call);
635            let args = call.args;
636            let track = args.get("track").and_then(Json::as_u64).ok_or("`track` is a track's id")?;
637            let at = match time_of(&t, args)? {
638                Some(s) => s,
639                None => t.get(name(args))?["playhead"]["seconds"].as_f64().unwrap_or(0.0),
640            };
641            let length = args.get("length").and_then(Json::as_f64).ok_or("`length` is a number of seconds")?;
642            let text = |key: &str| args.get(key).and_then(Json::as_str).unwrap_or("").to_string();
643            let mut clip = Clip::new(0, at, length, text("label"))
644                .offset(args.get("offset").and_then(Json::as_f64).unwrap_or(0.0))
645                .source(text("source"));
646            clip.source_length = args.get("source_length").and_then(Json::as_f64);
647            if let Some(c) = args.get("color").and_then(Json::as_str) {
648                clip.color = Some(parse_hex(c).ok_or_else(|| format!("`{c}` is not `#rrggbb`"))?);
649            }
650            t.run(name(args), Op::AddClip { track, clip }, call.origin)
651        },
652    )?;
653    ctx.command(
654        CommandSpec::new(CMD_MOVE_CLIP, "Move a clip on a timeline", CAT)
655            .description("Moves a timeline's clip `id` to start at `seconds` or `time`, and to track `track` (its id); what is not given stays. Refused where it would overlap a clip or leave the bounds. One step of the history.")
656            .args(json!({ "timeline": timeline, "id": 1, "seconds": 8.0, "track": 2 })),
657        |call| {
658            let t = timelines(call);
659            let args = call.args;
660            let id = clip_id(args)?;
661            let at = time_of(&t, args)?;
662            let track = args.get("track").and_then(Json::as_u64);
663            let clip = clip_of(&t, name(args), id)?;
664            let mv = ClipMove {
665                id,
666                track: track.unwrap_or(clip.0),
667                start: at.unwrap_or(clip.1),
668            };
669            t.run(name(args), Op::MoveClips(vec![mv]), call.origin)
670        },
671    )?;
672    ctx.command(
673        CommandSpec::new(CMD_TRIM_CLIP, "Trim a clip on a timeline", CAT)
674            .description("Moves a timeline's clip `id` start to `start` and its end to `end` (seconds on the timeline; either or both). Its offset into its source follows its start; it stops at its source's ends, its neighbours and the bounds. One step of the history each.")
675            .args(json!({ "timeline": timeline, "id": 1, "start": 4.5, "end": 9.0 })),
676        |call| {
677            let t = timelines(call);
678            let args = call.args;
679            let id = clip_id(args)?;
680            let start = args.get("start").and_then(Json::as_f64);
681            let end = args.get("end").and_then(Json::as_f64);
682            if start.is_none() && end.is_none() {
683                return Err("`start` or `end` is needed".into());
684            }
685            let mut answer = Json::Null;
686            for (edge, time) in [(ClipEdge::Start, start), (ClipEdge::End, end)] {
687                if let Some(time) = time {
688                    answer = t.run(name(args), Op::TrimClip { id, edge, time }, call.origin)?;
689                }
690            }
691            Ok(answer)
692        },
693    )?;
694    ctx.command(
695        CommandSpec::new(CMD_REMOVE_CLIP, "Remove clips from a timeline", CAT)
696            .description("Removes a timeline's clip `id`, or the clips `ids` (one step of the history together).")
697            .args(json!({ "timeline": timeline, "id": 1 })),
698        |call| {
699            let ids = clip_ids(call.args)?;
700            timelines(call).run(name(call.args), Op::RemoveClips(ids), call.origin)
701        },
702    )?;
703    ctx.command(
704        CommandSpec::new(CMD_SPLIT_CLIP, "Split clips on a timeline", CAT)
705            .description("Splits a timeline's clip `id`, or the clips `ids`, at `seconds` or `time` (else at the playhead): each ends there and a new clip starts there, reading its source on. Refused unless the time is inside each, a frame or more from its ends. Answers the new clips' ids in `added`. One step of the history together.")
706            .args(json!({ "timeline": timeline, "id": 1, "seconds": 6.0 })),
707        |call| {
708            let t = timelines(call);
709            let args = call.args;
710            let ids = clip_ids(args)?;
711            let time = match time_of(&t, args)? {
712                Some(time) => time,
713                None => playhead_of(&t, name(args))?,
714            };
715            t.run(name(args), Op::SplitClips { ids, time }, call.origin)
716        },
717    )?;
718    ctx.command(
719        CommandSpec::new(CMD_RIPPLE_DELETE, "Ripple delete clips on a timeline", CAT)
720            .description("Removes a timeline's clip `id`, or the clips `ids`, and closes the gaps they leave: the clips after them on their tracks move back. One step of the history together.")
721            .args(json!({ "timeline": timeline, "id": 1 })),
722        |call| {
723            let ids = clip_ids(call.args)?;
724            timelines(call).run(name(call.args), Op::RippleRemove(ids), call.origin)
725        },
726    )?;
727    ctx.command(
728        CommandSpec::new(CMD_SELECT_CLIPS, "Select clips on a timeline", CAT)
729            .description("Selects a timeline's clips `ids` (an empty list lets them go); the keys act on the last. Not a step of the history.")
730            .args(json!({ "timeline": timeline, "ids": [1, 2] })),
731        |call| {
732            let ids = clip_ids(call.args)?;
733            timelines(call).run(name(call.args), Op::SelectClips(ids), call.origin)
734        },
735    )?;
736    Ok(())
737}
738
739/// The `id` argument, a clip's.
740#[cfg(feature = "api")]
741fn clip_id(args: &Json) -> Result<u64, String> {
742    args.get("id")
743        .and_then(Json::as_u64)
744        .ok_or_else(|| "`id` is a clip's id".into())
745}
746
747/// `ids` (a list of clips' ids), else `id`.
748#[cfg(feature = "api")]
749fn clip_ids(args: &Json) -> Result<Vec<u64>, String> {
750    match args.get("ids") {
751        Some(Json::Array(ids)) => ids
752            .iter()
753            .map(|v| v.as_u64().ok_or_else(|| "`ids` are clips' ids".to_string()))
754            .collect(),
755        Some(_) => Err("`ids` is a list of clips' ids".into()),
756        None => clip_id(args).map(|id| vec![id]),
757    }
758}
759
760/// The playhead of the timeline `timeline`.
761#[cfg(feature = "api")]
762fn playhead_of(t: &Timelines, timeline: Option<&str>) -> Result<f64, String> {
763    let pass = t.ctx.cumulative_pass_nr();
764    let mut reg = lock(&t.registry);
765    target(&mut reg, timeline, pass).map(|(_, e)| e.state.playhead)
766}
767
768/// Clip `id`'s track and start on the timeline `timeline`.
769#[cfg(feature = "api")]
770fn clip_of(t: &Timelines, timeline: Option<&str>, id: u64) -> Result<(u64, f64), String> {
771    let pass = t.ctx.cumulative_pass_nr();
772    let mut reg = lock(&t.registry);
773    let (_, e) = target(&mut reg, timeline, pass)?;
774    match (e.state.clip_track(id), e.state.clip(id)) {
775        (Some(track), Some(c)) => Ok((track.id, c.start)),
776        _ => Err(format!("no clip {id}")),
777    }
778}
779
780#[cfg(test)]
781mod tests {
782    use super::*;
783
784    #[test]
785    fn colours_read_and_write_as_hex() {
786        assert_eq!(parse_hex("#ff8800"), Some(Color32::from_rgb(255, 136, 0)));
787        assert_eq!(hex(Color32::from_rgb(255, 136, 0)), "#ff8800");
788        assert_eq!(parse_hex("ff8800"), None);
789        assert_eq!(parse_hex("#ff88"), None);
790    }
791}