Skip to main content

egui_pop_views/timeline/
transport.rs

1//! [`Transport`]: a row of transport buttons over a [`TimelineState`]
2//! (go to start, step back, play backward, stop, play or pause, step
3//! forward, go to end, loop) and the playhead's text beside them. Each
4//! button does what its key does on the timeline: with an application and
5//! the timeline's id it runs the same `timeline.*` command (so the palette,
6//! the history and agents see one thing), else it changes the state
7//! directly.
8
9use crate::app_link::AppHandle;
10use egui::accesskit::Role;
11use egui::{
12    Color32, Painter, Pos2, Rect, Response, Sense, Shape, Stroke, Ui, WidgetInfo, pos2, vec2,
13};
14use egui_pop_core::strings::{StrKey, tr, tr_args};
15use egui_pop_model::ids::CommandId;
16use serde_json::json;
17
18use super::plugin::{
19    CMD_GO_TO_END, CMD_GO_TO_START, CMD_PAUSE, CMD_SHUTTLE_BACKWARD, CMD_STEP_BACKWARD,
20    CMD_STEP_FORWARD, CMD_TOGGLE_LOOP, CMD_TOGGLE_PLAY,
21};
22use super::state::TimelineState;
23use super::{Op, apply};
24use crate::strings as txt;
25
26/// A transport button.
27#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
28#[non_exhaustive]
29pub enum TransportButton {
30    /// To the bounds' start (Home).
31    Start,
32    /// One unit back, pausing (Left).
33    StepBack,
34    /// Plays backward, twice as fast again (J).
35    PlayBackward,
36    /// Pauses, the speed back to 1 (K).
37    Stop,
38    /// Plays forward at 1, or pauses (Space).
39    PlayPause,
40    /// One unit on, pausing (Right).
41    StepForward,
42    /// To the bounds' end (End).
43    End,
44    /// Loops the range, or no longer (Ctrl+L).
45    Loop,
46}
47
48impl TransportButton {
49    /// A video editor's row, in this order.
50    pub const ALL: [TransportButton; 8] = [
51        TransportButton::Start,
52        TransportButton::StepBack,
53        TransportButton::PlayBackward,
54        TransportButton::Stop,
55        TransportButton::PlayPause,
56        TransportButton::StepForward,
57        TransportButton::End,
58        TransportButton::Loop,
59    ];
60
61    /// The `timeline.*` command it runs, its key's.
62    pub fn command(self) -> CommandId {
63        match self {
64            TransportButton::Start => CMD_GO_TO_START,
65            TransportButton::StepBack => CMD_STEP_BACKWARD,
66            TransportButton::PlayBackward => CMD_SHUTTLE_BACKWARD,
67            TransportButton::Stop => CMD_PAUSE,
68            TransportButton::PlayPause => CMD_TOGGLE_PLAY,
69            TransportButton::StepForward => CMD_STEP_FORWARD,
70            TransportButton::End => CMD_GO_TO_END,
71            TransportButton::Loop => CMD_TOGGLE_LOOP,
72        }
73    }
74
75    /// What it does to the state.
76    fn op(self) -> Op {
77        match self {
78            TransportButton::Start => Op::Home,
79            TransportButton::StepBack => Op::Step {
80                forward: false,
81                big: false,
82            },
83            TransportButton::PlayBackward => Op::Shuttle(false),
84            TransportButton::Stop => Op::Pause,
85            TransportButton::PlayPause => Op::Toggle,
86            TransportButton::StepForward => Op::Step {
87                forward: true,
88                big: false,
89            },
90            TransportButton::End => Op::End,
91            TransportButton::Loop => Op::ToggleLoop,
92        }
93    }
94
95    /// Its name (playing or not) and its keys, for the tooltip.
96    fn name_and_keys(self, playing: bool) -> (&'static StrKey, &'static str) {
97        match self {
98            TransportButton::Start => (&txt::TRANSPORT_START, "Home"),
99            TransportButton::StepBack => (&txt::TRANSPORT_STEP_BACK, "←"),
100            TransportButton::PlayBackward => (&txt::TRANSPORT_PLAY_BACKWARD, "J"),
101            TransportButton::Stop => (&txt::TRANSPORT_STOP, "K"),
102            TransportButton::PlayPause if playing => (&txt::TRANSPORT_PAUSE, "Space, K"),
103            TransportButton::PlayPause => (&txt::TRANSPORT_PLAY, "Space, L"),
104            TransportButton::StepForward => (&txt::TRANSPORT_STEP_FORWARD, "→"),
105            TransportButton::End => (&txt::TRANSPORT_END, "End"),
106            TransportButton::Loop => (&txt::TRANSPORT_LOOP, "Ctrl+L"),
107        }
108    }
109}
110
111/// What a transport did this pass.
112#[derive(Debug)]
113#[non_exhaustive]
114pub struct TransportOutput {
115    /// The whole row.
116    pub response: Response,
117    /// The button clicked, if one was.
118    pub clicked: Option<TransportButton>,
119}
120
121/// A row of transport buttons over a timeline's state, the playhead's text
122/// beside them.
123///
124/// ```no_run
125/// use egui_pop_views::timeline::{Timeline, TimelineState, Transport};
126///
127/// fn ui(ui: &mut egui::Ui, app: &egui_pop_api::AppHandle, seq: &mut TimelineState) {
128///     // The buttons run the `timeline.*` commands on the timeline `sequence`.
129///     Transport::new(seq).app(app).timeline("sequence").show(ui);
130///     Timeline::new(seq).id("sequence").app(app).show(ui);
131/// }
132/// ```
133#[must_use = "call `show` to draw it"]
134pub struct Transport<'a> {
135    state: &'a mut TimelineState,
136    app: Option<&'a AppHandle>,
137    timeline: Option<&'a str>,
138    buttons: &'a [TransportButton],
139    timecode: bool,
140}
141
142impl std::fmt::Debug for Transport<'_> {
143    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144        f.debug_struct("Transport")
145            .field("timeline", &self.timeline)
146            .field("buttons", &self.buttons)
147            .finish_non_exhaustive()
148    }
149}
150
151impl<'a> Transport<'a> {
152    pub fn new(state: &'a mut TimelineState) -> Self {
153        Self {
154            state,
155            app: None,
156            timeline: None,
157            buttons: &TransportButton::ALL,
158            timecode: true,
159        }
160    }
161
162    /// The application whose `timeline.*` commands the buttons run (with
163    /// [`timeline`](Self::timeline)): each click is then the command, a
164    /// step of the history where the key's is.
165    #[cfg(feature = "api")]
166    pub fn app(mut self, app: &'a AppHandle) -> Self {
167        self.app = Some(app);
168        self
169    }
170
171    /// The timeline's id ([`Timeline::id`](super::Timeline::id)), the
172    /// commands' `timeline`.
173    pub fn timeline(mut self, id: &'a str) -> Self {
174        self.timeline = Some(id);
175        self
176    }
177
178    /// The buttons, in order ([`TransportButton::ALL`] by default).
179    pub fn buttons(mut self, buttons: &'a [TransportButton]) -> Self {
180        self.buttons = buttons;
181        self
182    }
183
184    /// The playhead's text after the buttons (on by default).
185    pub fn timecode(mut self, on: bool) -> Self {
186        self.timecode = on;
187        self
188    }
189
190    pub fn show(self, ui: &mut Ui) -> TransportOutput {
191        let Transport {
192            state,
193            app,
194            timeline,
195            buttons,
196            timecode,
197        } = self;
198        let ctx = ui.ctx().clone();
199        let mut clicked = None;
200        let row = ui.horizontal(|ui| {
201            ui.spacing_mut().item_spacing.x = 2.0;
202            let playing = state.is_playing();
203            for &b in buttons {
204                let (name, keys) = b.name_and_keys(playing);
205                let name = tr(&ctx, name);
206                let selected = match b {
207                    TransportButton::PlayBackward => playing && state.speed < 0.0,
208                    TransportButton::Loop => state.looping,
209                    _ => false,
210                };
211                let r = button(ui, b, &name, selected, playing).on_hover_text(tr_args(
212                    &ctx,
213                    &txt::TRANSPORT_KEYS,
214                    &[("action", &name), ("keys", keys)],
215                ));
216                if r.clicked() {
217                    clicked = Some(b);
218                }
219            }
220            if timecode {
221                ui.add_space(6.0);
222                ui.monospace(state.scale.format(state.playhead));
223            }
224        });
225        if let Some(b) = clicked {
226            match (app, timeline) {
227                (Some(app), Some(id)) => app.run(b.command(), json!({ "timeline": id })),
228                _ => {
229                    apply(state, b.op());
230                }
231            }
232        }
233        TransportOutput {
234            response: row.response,
235            clicked,
236        }
237    }
238}
239
240/// A transport button: the theme's button look, its glyph painted.
241fn button(ui: &mut Ui, b: TransportButton, name: &str, selected: bool, playing: bool) -> Response {
242    let h = ui.spacing().interact_size.y;
243    let (rect, r) = ui.allocate_exact_size(vec2(h * 1.3, h), Sense::click());
244    let enabled = ui.is_enabled();
245    r.widget_info(|| WidgetInfo::selected(Role::Button, enabled, selected, name));
246    if ui.is_rect_visible(rect) {
247        let v = ui.style().interact_selectable(&r, selected);
248        let p = ui.painter();
249        p.rect(
250            rect.expand(v.expansion),
251            v.corner_radius,
252            v.weak_bg_fill,
253            v.bg_stroke,
254            egui::StrokeKind::Inside,
255        );
256        glyph(p, rect, b, playing, v.fg_stroke.color);
257    }
258    r
259}
260
261/// A triangle pointing right (or left) in `r`.
262fn triangle(p: &Painter, r: Rect, right: bool, color: Color32) {
263    let pts = if right {
264        vec![r.left_top(), r.right_center(), r.left_bottom()]
265    } else {
266        vec![r.right_top(), r.left_center(), r.right_bottom()]
267    };
268    p.add(Shape::convex_polygon(pts, color, Stroke::NONE));
269}
270
271/// A bar from `top` down `h`, at `x`.
272fn bar(p: &Painter, x: f32, top: f32, h: f32, w: f32, color: Color32) {
273    p.rect_filled(Rect::from_min_size(pos2(x, top), vec2(w, h)), 0.0, color);
274}
275
276fn glyph(p: &Painter, rect: Rect, b: TransportButton, playing: bool, color: Color32) {
277    let s = (rect.height() * 0.45).round();
278    let c = rect.center();
279    let g = Rect::from_center_size(c, vec2(s, s));
280    let w = (s / 5.0).max(1.5);
281    let half = |left: bool| {
282        let x = if left { g.left() } else { c.x };
283        Rect::from_min_size(pos2(x, g.top()), vec2(s / 2.0, s))
284    };
285    match b {
286        TransportButton::Start => {
287            bar(p, g.left() - w, g.top(), s, w, color);
288            triangle(p, half(true), false, color);
289            triangle(p, half(false), false, color);
290        }
291        TransportButton::End => {
292            triangle(p, half(true), true, color);
293            triangle(p, half(false), true, color);
294            bar(p, g.right(), g.top(), s, w, color);
295        }
296        TransportButton::StepBack => {
297            let t = Rect::from_min_size(g.left_top(), vec2(s * 0.7, s));
298            triangle(p, t, false, color);
299            bar(p, g.right() - w, g.top(), s, w, color);
300        }
301        TransportButton::StepForward => {
302            bar(p, g.left(), g.top(), s, w, color);
303            let t = Rect::from_min_size(pos2(g.right() - s * 0.7, g.top()), vec2(s * 0.7, s));
304            triangle(p, t, true, color);
305        }
306        TransportButton::PlayBackward => {
307            triangle(p, g.shrink2(vec2(s * 0.1, 0.0)), false, color);
308        }
309        TransportButton::PlayPause if playing => {
310            bar(p, g.left() + s * 0.1, g.top(), s, s * 0.3, color);
311            bar(p, g.right() - s * 0.4, g.top(), s, s * 0.3, color);
312        }
313        TransportButton::PlayPause => {
314            triangle(p, g.shrink2(vec2(s * 0.1, 0.0)), true, color);
315        }
316        TransportButton::Stop => {
317            p.rect_filled(g.shrink(s * 0.08), 1.0, color);
318        }
319        TransportButton::Loop => {
320            // A ring, its arrowhead on top going right.
321            let radius = s * 0.45;
322            p.circle_stroke(c, radius, Stroke::new(w * 0.8, color));
323            let tip: Pos2 = c + vec2(s * 0.12, -radius);
324            let head = Rect::from_center_size(tip, vec2(s * 0.35, s * 0.4));
325            triangle(p, head, true, color);
326        }
327    }
328}