1mod timing;
19
20pub use timing::{Break, MARK_SPACING, Mark, Timing, time_label};
21
22use std::borrow::Cow;
23use std::time::Duration;
24
25use iced::advanced::layout::{self, Layout};
26use iced::advanced::text as core_text;
27use iced::advanced::widget::{Tree, Widget, tree};
28use iced::advanced::{Clipboard, Shell, renderer};
29use iced::alignment::Vertical;
30use iced::keyboard::{self, key::Named};
31use iced::widget::text::{self, LineHeight, Shaping, Wrapping};
32use iced::{
33 Border, Color, Element, Event, Length, Pixels, Point, Rectangle, Renderer, Size, Theme, mouse,
34 touch,
35};
36
37use crate::focus;
38use crate::keys::{self, Chord, Keymap};
39use crate::theme::{self, Tokens, fade, mix, radius, space, text_size};
40
41pub const TRACK_HEIGHT: f32 = 28.0;
43pub const LANE_HEIGHT: f32 = 20.0;
45pub const LABEL_WIDTH: f32 = 96.0;
47pub const PLAYHEAD_RADIUS: f32 = 6.0;
49pub const PAGE: usize = 10;
51pub const RULER_HEIGHT: f32 = 20.0;
53
54const RAIL_HEIGHT: f32 = 4.0;
55const TICK_WIDTH: f32 = 2.0;
56const BAR_HEIGHT: f32 = 8.0;
57const MARK_HEIGHT: f32 = 4.0;
58const BREAK_INSET: f32 = 2.0;
60const EDGE_LABEL: f32 = 24.0;
63
64pub use crate::theme::Tone;
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
69pub struct Span {
70 pub start: usize,
71 pub end: usize,
72 pub tone: Tone,
73}
74
75impl Span {
76 pub fn new(start: usize, end: usize) -> Self {
78 Self {
79 start: start.min(end),
80 end: start.max(end),
81 tone: Tone::Neutral,
82 }
83 }
84
85 pub fn tone(mut self, tone: Tone) -> Self {
86 self.tone = tone;
87 self
88 }
89}
90
91#[derive(Debug, Clone, PartialEq)]
93pub struct Lane<'a> {
94 label: text::Fragment<'a>,
95 spans: Vec<Span>,
96}
97
98pub fn lane<'a>(
100 label: impl text::IntoFragment<'a>,
101 spans: impl IntoIterator<Item = Span>,
102) -> Lane<'a> {
103 Lane {
104 label: label.into_fragment(),
105 spans: spans.into_iter().collect(),
106 }
107}
108
109impl Lane<'_> {
110 pub fn label(&self) -> &str {
111 &self.label
112 }
113
114 pub fn spans(&self) -> &[Span] {
115 &self.spans
116 }
117}
118
119pub struct Timeline<'a, Message> {
123 steps: Vec<Tone>,
124 current: usize,
125 lanes: Vec<Lane<'a>>,
126 label_width: f32,
127 width: Length,
128 name: text::Fragment<'a>,
129 keymap: Keymap<Action>,
130 times: Vec<Duration>,
131 end: Option<Duration>,
132 compress: Option<Duration>,
133 timing: Option<Timing>,
134 ruler: bool,
135 format: Option<Box<dyn Fn(Duration) -> String + 'a>>,
136 on_select: Option<Box<dyn Fn(usize) -> Message + 'a>>,
137 on_hover: Option<Box<dyn Fn(Option<usize>) -> Message + 'a>>,
138}
139
140impl<Message> std::fmt::Debug for Timeline<'_, Message> {
141 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
142 f.debug_struct("Timeline")
143 .field("steps", &self.steps.len())
144 .field("current", &self.current)
145 .field("lanes", &self.lanes)
146 .field("label_width", &self.label_width)
147 .field("width", &self.width)
148 .field("name", &self.name)
149 .field("keymap", &self.keymap)
150 .field("timing", &self.timing)
151 .field("ruler", &self.ruler)
152 .field("enabled", &self.on_select.is_some())
153 .field("hover", &self.on_hover.is_some())
154 .finish()
155 }
156}
157
158pub fn timeline<'a, Message>(
161 steps: impl IntoIterator<Item = Tone>,
162 current: usize,
163) -> Timeline<'a, Message> {
164 let steps: Vec<Tone> = steps.into_iter().collect();
165 Timeline {
166 current: current.min(steps.len().saturating_sub(1)),
167 steps,
168 lanes: Vec::new(),
169 label_width: LABEL_WIDTH,
170 width: Length::Fill,
171 name: Cow::Borrowed("Timeline"),
172 keymap: default_keymap(),
173 times: Vec::new(),
174 end: None,
175 compress: None,
176 timing: None,
177 ruler: false,
178 format: None,
179 on_select: None,
180 on_hover: None,
181 }
182}
183
184impl<'a, Message> Timeline<'a, Message> {
185 pub fn lane(mut self, lane: Lane<'a>) -> Self {
187 self.lanes.push(lane);
188 self
189 }
190
191 pub fn lanes(mut self, lanes: impl IntoIterator<Item = Lane<'a>>) -> Self {
193 self.lanes.extend(lanes);
194 self
195 }
196
197 pub fn label_width(mut self, width: f32) -> Self {
199 self.label_width = width.max(0.0);
200 self
201 }
202
203 pub fn width(mut self, width: impl Into<Length>) -> Self {
204 self.width = width.into();
205 self
206 }
207
208 pub fn label(mut self, label: impl text::IntoFragment<'a>) -> Self {
210 self.name = label.into_fragment();
211 self
212 }
213
214 pub fn on_select(mut self, on_select: impl Fn(usize) -> Message + 'a) -> Self {
217 self.on_select = Some(Box::new(on_select));
218 self
219 }
220
221 pub fn on_hover(mut self, on_hover: impl Fn(Option<usize>) -> Message + 'a) -> Self {
227 self.on_hover = Some(Box::new(on_hover));
228 self
229 }
230
231 pub fn keymap(mut self, keymap: Keymap<Action>) -> Self {
234 self.keymap = keymap;
235 self
236 }
237
238 pub fn times(mut self, times: impl IntoIterator<Item = Duration>) -> Self {
243 self.times = times.into_iter().collect();
244 self.retime();
245 self
246 }
247
248 pub fn end(mut self, end: Duration) -> Self {
251 self.end = Some(end);
252 self.retime();
253 self
254 }
255
256 pub fn compress_gaps(mut self, longer_than: Duration) -> Self {
261 self.compress = Some(longer_than);
262 self.retime();
263 self
264 }
265
266 pub fn ruler(mut self, ruler: bool) -> Self {
269 self.ruler = ruler;
270 self
271 }
272
273 pub fn ruler_format(mut self, format: impl Fn(Duration) -> String + 'a) -> Self {
276 self.format = Some(Box::new(format));
277 self
278 }
279
280 pub fn current(&self) -> usize {
281 self.current
282 }
283
284 pub fn timing(&self) -> Option<&Timing> {
286 self.timing.as_ref()
287 }
288
289 fn retime(&mut self) {
290 if self.times.is_empty() {
291 self.timing = None;
292 return;
293 }
294 let mut times = self.times.clone();
295 let last = times.last().copied().unwrap_or_default();
296 times.resize(self.steps.len().max(1), last);
297 self.timing = Some(Timing::new(×, self.end, self.compress));
298 }
299
300 pub fn len(&self) -> usize {
301 self.steps.len()
302 }
303
304 pub fn is_empty(&self) -> bool {
305 self.steps.is_empty()
306 }
307
308 pub fn is_enabled(&self) -> bool {
309 self.on_select.is_some()
310 }
311
312 fn labels(&self) -> f32 {
313 if self.lanes.is_empty() {
314 0.0
315 } else {
316 self.label_width
317 }
318 }
319
320 fn total_height(&self) -> f32 {
321 let ruler = if self.ruler { RULER_HEIGHT } else { 0.0 };
322 height(self.lanes.len()) + ruler
323 }
324
325 fn place_of(&self, index: usize) -> f32 {
327 match &self.timing {
328 Some(timing) => timing.positions().get(index).copied().unwrap_or(0.0),
329 None => position_of(index, 1.0, self.steps.len()),
330 }
331 }
332
333 fn x_of(&self, index: usize, track: Rectangle) -> f32 {
334 track.x + track.width * self.place_of(index)
335 }
336
337 fn index_under(&self, x: f32, track: Rectangle) -> usize {
339 let Some(timing) = &self.timing else {
340 return index_at(x - track.x, track.width, self.steps.len());
341 };
342 if track.width <= 0.0 {
343 return 0;
344 }
345 let nearest = timing.nearest((x - track.x) / track.width);
346 nearest.min(self.steps.len().saturating_sub(1))
347 }
348
349 fn extent(&self, span: Span, track: Rectangle) -> (f32, f32) {
351 match &self.timing {
352 Some(timing) => {
353 let (left, right) = timing.extent(span);
354 (left * track.width, right * track.width)
355 }
356 None => span_extent(span, track.width, self.steps.len()),
357 }
358 }
359
360 fn breaks(&self, track: Rectangle) -> Vec<(f32, f32)> {
362 let Some(timing) = &self.timing else {
363 return Vec::new();
364 };
365 timing
366 .breaks()
367 .iter()
368 .map(|gap| {
369 (
370 track.x + gap.start * track.width,
371 track.x + gap.end * track.width,
372 )
373 })
374 .collect()
375 }
376
377 fn marks(&self, width: f32) -> Vec<(f32, String)> {
380 let Some(timing) = &self.timing else {
381 return step_marks(self.steps.len(), width);
382 };
383 let Some(interval) = timing.interval(width) else {
384 return Vec::new();
385 };
386 timing
387 .marks(width)
388 .into_iter()
389 .map(|mark| {
390 let label = match &self.format {
391 Some(format) => format(mark.time),
392 None => time_label(mark.time, interval, timing.end()),
393 };
394 (mark.place, label)
395 })
396 .collect()
397 }
398}
399
400fn step_marks(count: usize, width: f32) -> Vec<(f32, String)> {
404 if count == 0 {
405 return Vec::new();
406 }
407 let most = (width / MARK_SPACING).floor().max(1.0) as usize;
408 let stride = count.div_ceil(most).max(1);
409 (0..count)
410 .step_by(stride)
411 .map(|index| (position_of(index, 1.0, count), (index + 1).to_string()))
412 .collect()
413}
414
415fn pieces(left: f32, right: f32, gaps: &[(f32, f32)]) -> Vec<(f32, f32)> {
418 let mut pieces = Vec::with_capacity(gaps.len() + 1);
419 let mut start = left;
420 for (gap_left, gap_right) in gaps {
421 let end = (gap_left - BREAK_INSET).min(right);
422 if end > start {
423 pieces.push((start, end));
424 }
425 start = start.max(gap_right + BREAK_INSET);
426 }
427 if right > start {
428 pieces.push((start, right));
429 }
430 pieces
431}
432
433pub fn index_at(x: f32, width: f32, count: usize) -> usize {
436 if count < 2 || width <= 0.0 {
437 return 0;
438 }
439 let last = count - 1;
440 let fraction = (x / width).clamp(0.0, 1.0);
441 let index = (fraction * last as f32).round();
442 (index as usize).min(last)
443}
444
445pub fn position_of(index: usize, width: f32, count: usize) -> f32 {
447 if count < 2 {
448 return 0.0;
449 }
450 width * index.min(count - 1) as f32 / (count - 1) as f32
451}
452
453pub fn span_extent(span: Span, width: f32, count: usize) -> (f32, f32) {
456 let half = if count < 2 {
457 width / 2.0
458 } else {
459 width / (count - 1) as f32 / 2.0
460 };
461 let left = (position_of(span.start, width, count) - half).max(0.0);
462 let right = (position_of(span.end, width, count) + half).min(width);
463 (left, right.max(left))
464}
465
466pub fn height(lanes: usize) -> f32 {
468 TRACK_HEIGHT + lanes as f32 * LANE_HEIGHT
469}
470
471pub fn track_bounds(bounds: Rectangle, labels: f32) -> Rectangle {
474 let left = if labels > 0.0 {
475 labels + space::SM
476 } else {
477 0.0
478 };
479 let x = bounds.x + left + PLAYHEAD_RADIUS;
480 Rectangle {
481 x,
482 y: bounds.y,
483 width: (bounds.width - left - PLAYHEAD_RADIUS * 2.0).max(0.0),
484 height: TRACK_HEIGHT,
485 }
486}
487
488#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
490pub enum Action {
491 Previous,
492 Next,
493 PageBack,
494 PageForward,
495 First,
496 Last,
497}
498
499impl Action {
500 pub fn apply(self, current: usize, count: usize) -> usize {
503 let last = count.saturating_sub(1);
504 let current = current.min(last);
505 match self {
506 Action::Previous => current.saturating_sub(1),
507 Action::Next => (current + 1).min(last),
508 Action::PageBack => current.saturating_sub(PAGE),
509 Action::PageForward => (current + PAGE).min(last),
510 Action::First => 0,
511 Action::Last => last,
512 }
513 }
514}
515
516impl keys::Action for Action {
517 const ALL: &'static [Self] = &[
518 Action::Previous,
519 Action::Next,
520 Action::PageBack,
521 Action::PageForward,
522 Action::First,
523 Action::Last,
524 ];
525
526 fn defaults() -> Keymap<Self> {
527 default_keymap()
528 }
529
530 fn name(self) -> &'static str {
531 match self {
532 Action::Previous => "Previous",
533 Action::Next => "Next",
534 Action::PageBack => "Page back",
535 Action::PageForward => "Page forward",
536 Action::First => "First",
537 Action::Last => "Last",
538 }
539 }
540
541 fn description(self) -> &'static str {
542 match self {
543 Action::Previous => "Moves to the step before the current one.",
544 Action::Next => "Moves to the step after the current one.",
545 Action::PageBack => "Moves ten steps back.",
546 Action::PageForward => "Moves ten steps forward.",
547 Action::First => "Moves to the first step.",
548 Action::Last => "Moves to the last step.",
549 }
550 }
551}
552
553pub fn default_keymap() -> Keymap<Action> {
567 Keymap::new()
568 .bind(Chord::named(Named::ArrowLeft), Action::Previous)
569 .bind(Chord::named(Named::ArrowRight), Action::Next)
570 .bind(Chord::named(Named::ArrowLeft).shift(), Action::PageBack)
571 .bind(Chord::named(Named::PageUp), Action::PageBack)
572 .bind(Chord::named(Named::ArrowRight).shift(), Action::PageForward)
573 .bind(Chord::named(Named::PageDown), Action::PageForward)
574 .bind(Chord::named(Named::Home), Action::First)
575 .bind(Chord::named(Named::End), Action::Last)
576}
577
578#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
580pub enum Status {
581 #[default]
582 Active,
583 Hovered,
584 Dragged,
585 Disabled,
586}
587
588impl Status {
589 pub const ALL: [Status; 4] = [
590 Status::Active,
591 Status::Hovered,
592 Status::Dragged,
593 Status::Disabled,
594 ];
595}
596
597#[derive(Debug, Clone, Copy, PartialEq)]
599pub struct Style {
600 pub rail: Color,
601 pub lane: Color,
602 pub label: Color,
603 pub playhead: Color,
604 pub playhead_border: Color,
605 pub playhead_border_width: f32,
606 pub cursor: Color,
608 pub hover: Color,
610 pub mark: Color,
612 pub tone_alpha: f32,
614}
615
616pub fn style(tokens: &Tokens, status: Status) -> Style {
618 let border = match status {
619 Status::Active | Status::Disabled => tokens.primary,
620 Status::Hovered => mix(tokens.primary, tokens.background, 0.15),
621 Status::Dragged => mix(tokens.primary, tokens.background, 0.3),
622 };
623 let style = Style {
624 rail: mix(tokens.muted, tokens.border, 0.5),
625 lane: tokens.muted,
626 label: tokens.muted_foreground,
627 playhead: tokens.background,
628 playhead_border: border,
629 playhead_border_width: match status {
630 Status::Hovered | Status::Dragged => 2.5,
631 Status::Active | Status::Disabled => 2.0,
632 },
633 cursor: fade(tokens.primary, 0.4),
634 hover: fade(tokens.primary, 0.5),
635 mark: fade(tokens.muted_foreground, 0.6),
636 tone_alpha: 1.0,
637 };
638 if status != Status::Disabled {
639 return style;
640 }
641 Style {
642 rail: fade(style.rail, 0.5),
643 lane: fade(style.lane, 0.5),
644 label: fade(style.label, 0.5),
645 playhead_border: fade(style.playhead_border, 0.5),
646 cursor: fade(style.cursor, 0.5),
647 hover: fade(style.hover, 0.5),
648 mark: fade(style.mark, 0.5),
649 tone_alpha: 0.5,
650 ..style
651 }
652}
653
654#[derive(Debug, Default)]
655struct State {
656 dragging: bool,
657 hovered: bool,
658 finger: Option<touch::Finger>,
659 last: Option<usize>,
660 hover: Option<usize>,
662 keys: focus::Scope,
663}
664
665impl<Message> Timeline<'_, Message> {
666 fn is_focusable(&self) -> bool {
668 self.on_select.is_some() && !self.steps.is_empty()
669 }
670
671 fn is_hoverable(&self) -> bool {
673 (self.on_select.is_some() || self.on_hover.is_some()) && !self.steps.is_empty()
674 }
675
676 fn select(&self, state: &mut State, x: f32, track: Rectangle, shell: &mut Shell<'_, Message>) {
680 let Some(on_select) = &self.on_select else {
681 return;
682 };
683 let index = self.index_under(x, track);
684 if state.last != Some(index) {
685 shell.publish(on_select(index));
686 }
687 state.last = Some(index);
688 }
689
690 fn hover(
693 &self,
694 state: &mut State,
695 hover: Option<usize>,
696 shell: &mut Shell<'_, Message>,
697 ) -> bool {
698 if state.hover == hover {
699 return false;
700 }
701 state.hover = hover;
702 if let Some(on_hover) = &self.on_hover {
703 shell.publish(on_hover(hover));
704 }
705 true
706 }
707
708 fn status(&self, state: &State, layout: Layout<'_>, cursor: mouse::Cursor) -> Status {
709 if self.on_select.is_none() {
710 return Status::Disabled;
711 }
712 if state.dragging {
713 return Status::Dragged;
714 }
715 if cursor.is_over(layout.bounds()) {
716 return Status::Hovered;
717 }
718 Status::Active
719 }
720}
721
722fn focus_target(track: Rectangle) -> Rectangle {
725 let middle = track.center_y();
726 Rectangle {
727 x: track.x - PLAYHEAD_RADIUS,
728 y: middle - PLAYHEAD_RADIUS,
729 width: track.width + PLAYHEAD_RADIUS * 2.0,
730 height: PLAYHEAD_RADIUS * 2.0,
731 }
732}
733
734fn tick_height(tone: Tone) -> f32 {
737 if tone == Tone::Neutral {
738 8.0
739 } else {
740 PLAYHEAD_RADIUS * 2.0
741 }
742}
743
744fn playhead_tick(border: f32) -> f32 {
747 ((PLAYHEAD_RADIUS - border) * 2.0 - 2.0).max(0.0)
748}
749
750fn fill(renderer: &mut Renderer, bounds: Rectangle, colour: Color, corner: f32) {
751 <Renderer as renderer::Renderer>::fill_quad(
752 renderer,
753 renderer::Quad {
754 bounds,
755 border: Border {
756 radius: corner.into(),
757 ..Border::default()
758 },
759 ..renderer::Quad::default()
760 },
761 colour,
762 );
763}
764
765fn caption(
768 renderer: &mut Renderer,
769 content: &str,
770 at: Point,
771 align_x: text::Alignment,
772 colour: Color,
773 clip: Rectangle,
774) {
775 <Renderer as core_text::Renderer>::fill_text(
776 renderer,
777 core_text::Text {
778 content: content.to_owned(),
779 bounds: Size::new(f32::INFINITY, LANE_HEIGHT),
780 size: Pixels(text_size::XS),
781 line_height: LineHeight::Absolute(Pixels(LANE_HEIGHT)),
782 font: theme::font(),
783 align_x,
784 align_y: Vertical::Center,
785 shaping: Shaping::Advanced,
786 wrapping: Wrapping::None,
787 },
788 at,
789 colour,
790 clip,
791 );
792}
793
794fn label(renderer: &mut Renderer, content: &str, bounds: Rectangle, colour: Color) {
795 caption(
796 renderer,
797 content,
798 Point::new(bounds.x, bounds.center_y()),
799 text::Alignment::Left,
800 colour,
801 bounds,
802 );
803}
804
805fn mark_alignment(x: f32, bounds: Rectangle) -> text::Alignment {
808 if x - bounds.x < EDGE_LABEL {
809 text::Alignment::Left
810 } else if bounds.x + bounds.width - x < EDGE_LABEL {
811 text::Alignment::Right
812 } else {
813 text::Alignment::Center
814 }
815}
816
817impl<Message> Widget<Message, Theme, Renderer> for Timeline<'_, Message> {
818 fn size(&self) -> Size<Length> {
819 Size::new(self.width, Length::Fixed(self.total_height()))
820 }
821
822 fn tag(&self) -> tree::Tag {
823 tree::Tag::of::<State>()
824 }
825
826 fn state(&self) -> tree::State {
827 tree::State::new(State::default())
828 }
829
830 fn layout(
831 &mut self,
832 _tree: &mut Tree,
833 _renderer: &Renderer,
834 limits: &layout::Limits,
835 ) -> layout::Node {
836 let height = self.total_height();
837 layout::Node::new(limits.resolve(self.width, Length::Fixed(height), Size::new(0.0, height)))
838 }
839
840 fn draw(
841 &self,
842 tree: &Tree,
843 renderer: &mut Renderer,
844 theme: &Theme,
845 _style: &renderer::Style,
846 layout: Layout<'_>,
847 cursor: mouse::Cursor,
848 _viewport: &Rectangle,
849 ) {
850 let tokens = Tokens::of(theme);
851 let state = tree.state.downcast_ref::<State>();
852 let style = style(&tokens, self.status(state, layout, cursor));
853 let bounds = layout.bounds();
854 let labels = self.labels();
855 let track = track_bounds(bounds, labels);
856 let count = self.steps.len();
857 let middle = track.center_y();
858 let breaks = self.breaks(track);
859 let pieces = pieces(
860 track.x - PLAYHEAD_RADIUS,
861 track.x + track.width + PLAYHEAD_RADIUS,
862 &breaks,
863 );
864 let bars = |renderer: &mut Renderer, y: f32, height: f32, colour: Color| {
866 for (left, right) in &pieces {
867 fill(
868 renderer,
869 Rectangle {
870 x: *left,
871 y: y - height / 2.0,
872 width: right - left,
873 height,
874 },
875 colour,
876 radius::FULL,
877 );
878 }
879 };
880
881 bars(renderer, middle, RAIL_HEIGHT, style.rail);
882 for (left, right) in &breaks {
883 caption(
884 renderer,
885 "//",
886 Point::new((left + right) / 2.0, middle),
887 text::Alignment::Center,
888 style.label,
889 bounds,
890 );
891 }
892 if state.keys.is_focused() && self.is_focusable() {
893 focus::draw_ring(renderer, theme, focus_target(track), radius::FULL);
894 }
895
896 for (index, lane) in self.lanes.iter().enumerate() {
897 let row = Rectangle {
898 x: bounds.x,
899 y: bounds.y + TRACK_HEIGHT + index as f32 * LANE_HEIGHT,
900 width: bounds.width,
901 height: LANE_HEIGHT,
902 };
903 label(
904 renderer,
905 &lane.label,
906 Rectangle {
907 width: labels,
908 ..row
909 },
910 style.label,
911 );
912 let bar_y = row.center_y() - BAR_HEIGHT / 2.0;
913 bars(renderer, row.center_y(), BAR_HEIGHT, style.lane);
914 for span in &lane.spans {
915 if span.start >= count {
916 continue;
917 }
918 let (left, right) = self.extent(*span, track);
919 let (left, right) = (
920 track.x + left,
921 track.x + (right - left).max(BAR_HEIGHT) + left,
922 );
923 for (left, right) in self::pieces(left, right, &breaks) {
924 fill(
925 renderer,
926 Rectangle {
927 x: left,
928 y: bar_y,
929 width: right - left,
930 height: BAR_HEIGHT,
931 },
932 fade(span.tone.colour(&tokens), style.tone_alpha),
933 radius::FULL,
934 );
935 }
936 }
937 }
938
939 if self.ruler {
940 let top = bounds.y + height(self.lanes.len());
941 let span = Rectangle {
944 x: track.x - PLAYHEAD_RADIUS,
945 width: track.width + PLAYHEAD_RADIUS * 2.0,
946 ..bounds
947 };
948 for (place, mark) in self.marks(track.width) {
949 let x = track.x + place * track.width;
950 fill(
951 renderer,
952 Rectangle {
953 x: x - 0.5,
954 y: top,
955 width: 1.0,
956 height: MARK_HEIGHT,
957 },
958 style.mark,
959 0.0,
960 );
961 caption(
962 renderer,
963 &mark,
964 Point::new(x, top + (RULER_HEIGHT + MARK_HEIGHT) / 2.0),
965 mark_alignment(x, span),
966 style.label,
967 bounds,
968 );
969 }
970 }
971
972 for (index, tone) in self.steps.iter().enumerate() {
973 let tall = tick_height(*tone);
974 fill(
975 renderer,
976 Rectangle {
977 x: self.x_of(index, track) - TICK_WIDTH / 2.0,
978 y: middle - tall / 2.0,
979 width: TICK_WIDTH,
980 height: tall,
981 },
982 fade(tone.colour(&tokens), style.tone_alpha),
983 0.0,
984 );
985 }
986
987 if count == 0 {
988 return;
989 }
990 let x = self.x_of(self.current, track);
991 if !self.lanes.is_empty() {
992 fill(
993 renderer,
994 Rectangle {
995 x: x - 0.5,
996 y: middle,
997 width: 1.0,
998 height: bounds.y + height(self.lanes.len()) - middle,
999 },
1000 style.cursor,
1001 0.0,
1002 );
1003 }
1004 if let Some(hover) = state.hover
1005 && hover != self.current
1006 && hover < count
1007 && !state.dragging
1008 && self.is_hoverable()
1009 {
1010 let x = self.x_of(hover, track);
1011 <Renderer as renderer::Renderer>::fill_quad(
1012 renderer,
1013 renderer::Quad {
1014 bounds: Rectangle {
1015 x: x - PLAYHEAD_RADIUS,
1016 y: middle - PLAYHEAD_RADIUS,
1017 width: PLAYHEAD_RADIUS * 2.0,
1018 height: PLAYHEAD_RADIUS * 2.0,
1019 },
1020 border: Border {
1021 color: style.hover,
1022 width: 1.5,
1023 radius: PLAYHEAD_RADIUS.into(),
1024 },
1025 ..renderer::Quad::default()
1026 },
1027 Color::TRANSPARENT,
1028 );
1029 }
1030 <Renderer as renderer::Renderer>::fill_quad(
1031 renderer,
1032 renderer::Quad {
1033 bounds: Rectangle {
1034 x: x - PLAYHEAD_RADIUS,
1035 y: middle - PLAYHEAD_RADIUS,
1036 width: PLAYHEAD_RADIUS * 2.0,
1037 height: PLAYHEAD_RADIUS * 2.0,
1038 },
1039 border: Border {
1040 color: style.playhead_border,
1041 width: style.playhead_border_width,
1042 radius: PLAYHEAD_RADIUS.into(),
1043 },
1044 ..renderer::Quad::default()
1045 },
1046 style.playhead,
1047 );
1048 if let Some(tone) = self.steps.get(self.current) {
1051 let tall = playhead_tick(style.playhead_border_width);
1052 fill(
1053 renderer,
1054 Rectangle {
1055 x: x - TICK_WIDTH / 2.0,
1056 y: middle - tall / 2.0,
1057 width: TICK_WIDTH,
1058 height: tall,
1059 },
1060 fade(tone.colour(&tokens), style.tone_alpha),
1061 0.0,
1062 );
1063 }
1064 }
1065
1066 fn update(
1067 &mut self,
1068 tree: &mut Tree,
1069 event: &Event,
1070 layout: Layout<'_>,
1071 cursor: mouse::Cursor,
1072 _renderer: &Renderer,
1073 _clipboard: &mut dyn Clipboard,
1074 shell: &mut Shell<'_, Message>,
1075 _viewport: &Rectangle,
1076 ) {
1077 let state = tree.state.downcast_mut::<State>();
1078 let bounds = layout.bounds();
1079 let track = track_bounds(bounds, self.labels());
1080 let pressable = Rectangle {
1082 x: track.x - PLAYHEAD_RADIUS,
1083 width: track.width + PLAYHEAD_RADIUS * 2.0,
1084 ..bounds
1085 };
1086 let hover = if !self.is_hoverable() {
1089 Some(None)
1090 } else if state.dragging {
1091 None
1092 } else {
1093 match event {
1094 Event::Mouse(mouse::Event::CursorMoved { position }) => {
1095 let covered = matches!(cursor, mouse::Cursor::Levitating(_));
1097 let over = !covered && pressable.contains(*position);
1098 Some(over.then(|| self.index_under(position.x, track)))
1099 }
1100 Event::Mouse(mouse::Event::CursorLeft) => Some(None),
1101 _ => None,
1102 }
1103 };
1104 let hovered = hover.is_some_and(|hover| self.hover(state, hover, shell));
1105 if !self.is_focusable() {
1106 if state.keys.release() || hovered {
1107 shell.request_redraw();
1108 }
1109 return;
1110 }
1111 let before = (state.dragging, state.hovered);
1112 state.hovered = cursor.is_over(bounds);
1113 let keyed = state.keys.update(event, cursor, pressable);
1114 match event {
1115 Event::Mouse(mouse::Event::ButtonPressed(button)) => {
1116 let position = cursor.position_over(pressable);
1117 if let (mouse::Button::Left, Some(position)) = (button, position) {
1118 state.dragging = true;
1119 state.last = Some(self.current);
1120 self.select(state, position.x, track, shell);
1121 shell.capture_event();
1122 }
1123 }
1124 Event::Touch(touch::Event::FingerPressed { id, position }) => {
1125 if pressable.contains(*position) && !state.dragging {
1126 state.dragging = true;
1127 state.finger = Some(*id);
1128 state.last = Some(self.current);
1129 self.select(state, position.x, track, shell);
1130 shell.capture_event();
1131 }
1132 }
1133 Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. })
1134 if state.keys.has_keys() && !shell.is_event_captured() =>
1135 {
1136 if let Some(action) = self.keymap.resolve(key, *modifiers) {
1137 let next = action.apply(self.current, self.steps.len());
1138 if let Some(on_select) = &self.on_select
1139 && next != self.current
1140 {
1141 shell.publish(on_select(next));
1142 }
1143 shell.capture_event();
1144 }
1145 }
1146 Event::Mouse(mouse::Event::CursorMoved { position })
1147 if state.dragging && state.finger.is_none() =>
1148 {
1149 self.select(state, position.x, track, shell);
1150 }
1151 Event::Touch(touch::Event::FingerMoved { id, position })
1152 if state.finger == Some(*id) =>
1153 {
1154 self.select(state, position.x, track, shell);
1155 shell.capture_event();
1156 }
1157 Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left))
1158 if state.dragging && state.finger.is_none() =>
1159 {
1160 state.dragging = false;
1161 state.last = None;
1162 shell.capture_event();
1163 }
1164 Event::Touch(
1165 touch::Event::FingerLifted { id, .. } | touch::Event::FingerLost { id, .. },
1166 ) if state.finger == Some(*id) => {
1167 state.dragging = false;
1168 state.finger = None;
1169 state.last = None;
1170 shell.capture_event();
1171 }
1172 _ => {}
1173 }
1174 if keyed || hovered || (state.dragging, state.hovered) != before {
1175 shell.request_redraw();
1176 }
1177 }
1178
1179 fn mouse_interaction(
1180 &self,
1181 tree: &Tree,
1182 layout: Layout<'_>,
1183 cursor: mouse::Cursor,
1184 _viewport: &Rectangle,
1185 _renderer: &Renderer,
1186 ) -> mouse::Interaction {
1187 if self.on_select.is_none() {
1188 return mouse::Interaction::None;
1189 }
1190 if tree.state.downcast_ref::<State>().dragging {
1191 return mouse::Interaction::Grabbing;
1192 }
1193 if cursor.is_over(layout.bounds()) {
1194 return mouse::Interaction::Pointer;
1195 }
1196 mouse::Interaction::None
1197 }
1198
1199 fn operate(
1200 &mut self,
1201 tree: &mut Tree,
1202 layout: Layout<'_>,
1203 _renderer: &Renderer,
1204 operation: &mut dyn iced::advanced::widget::Operation,
1205 ) {
1206 let target = focus_target(track_bounds(layout.bounds(), self.labels()));
1207 #[cfg(feature = "icedwright")]
1208 {
1209 use icedwright_probe::{Annotation, report, role};
1210
1211 let enabled = self.on_select.is_some();
1212 let last = self.steps.len().saturating_sub(1) as f64;
1213 let time = self.timing.as_ref().and_then(|_| {
1215 let until = (self.current + 1).min(self.times.len());
1216 let time = self.times.get(..until)?.iter().max()?;
1217 Some(time.as_millis().to_string())
1218 });
1219 report(operation, target, || {
1220 let annotation = Annotation::new()
1221 .role(role::Slider)
1222 .name(self.name.to_string())
1223 .range(self.current as f64, 0.0..=last)
1224 .component("iced_cube::timeline");
1225 let annotation = match time.clone() {
1226 Some(time) => annotation.prop("time_ms", time),
1227 None => annotation,
1228 };
1229 if enabled {
1230 annotation
1231 } else {
1232 annotation.disabled(true)
1233 }
1234 });
1235 }
1236 let state = tree.state.downcast_mut::<State>();
1239 if self.is_focusable() {
1240 focus::report(operation, None, target, &mut state.keys);
1241 } else {
1242 let _ = state.keys.release();
1243 }
1244 }
1245}
1246
1247impl<'a, Message: 'a> From<Timeline<'a, Message>> for Element<'a, Message> {
1248 fn from(timeline: Timeline<'a, Message>) -> Self {
1249 Element::new(timeline)
1250 }
1251}
1252
1253#[cfg(test)]
1254mod tests {
1255 use super::*;
1256 use crate::keys::Action as _;
1257 use crate::theme::{dark, light};
1258
1259 fn bounds() -> Rectangle {
1260 Rectangle {
1261 x: 10.0,
1262 y: 20.0,
1263 width: 400.0,
1264 height: 100.0,
1265 }
1266 }
1267
1268 #[test]
1269 fn default_builder_fills_the_width_and_is_disabled() {
1270 let t: Timeline<'_, ()> = timeline([Tone::Neutral; 3], 1);
1271 assert_eq!(t.width, Length::Fill);
1272 assert_eq!(t.name, "Timeline");
1273 assert_eq!(t.label_width, LABEL_WIDTH);
1274 assert!(t.lanes.is_empty());
1275 assert!(!t.is_enabled());
1276 assert!(t.on_select(|_| ()).is_enabled());
1277 }
1278
1279 #[test]
1280 fn the_current_step_is_clamped_to_the_steps() {
1281 let t: Timeline<'_, ()> = timeline([Tone::Neutral; 3], 9);
1282 assert_eq!(t.current(), 2);
1283 let t: Timeline<'_, ()> = timeline([], 4);
1284 assert_eq!(t.current(), 0);
1285 assert!(t.is_empty());
1286 }
1287
1288 #[test]
1289 fn spans_are_ordered_and_take_a_tone() {
1290 let span = Span::new(5, 2).tone(Tone::Warning);
1291 assert_eq!((span.start, span.end, span.tone), (2, 5, Tone::Warning));
1292 assert_eq!(Span::new(1, 1).tone, Tone::Neutral);
1293 }
1294
1295 #[test]
1296 fn positions_and_indices_agree_at_every_step() {
1297 for count in [1, 2, 3, 10, 57] {
1298 for index in 0..count {
1299 let x = position_of(index, 600.0, count);
1300 assert_eq!(index_at(x, 600.0, count), index, "{index} of {count}");
1301 }
1302 }
1303 }
1304
1305 #[test]
1306 fn points_outside_the_track_clamp_to_the_ends() {
1307 assert_eq!(index_at(-50.0, 100.0, 5), 0);
1308 assert_eq!(index_at(150.0, 100.0, 5), 4);
1309 assert_eq!(index_at(10.0, 0.0, 5), 0);
1310 assert_eq!(index_at(10.0, 100.0, 0), 0);
1311 }
1312
1313 #[test]
1314 fn points_go_to_the_nearest_step() {
1315 assert_eq!(index_at(24.0, 100.0, 5), 1);
1316 assert_eq!(index_at(26.0, 100.0, 5), 1);
1317 assert_eq!(index_at(38.0, 100.0, 5), 2);
1318 }
1319
1320 #[test]
1321 fn a_span_reaches_half_a_step_either_side_and_stays_on_the_track() {
1322 assert_eq!(span_extent(Span::new(1, 2), 100.0, 5), (12.5, 62.5));
1323 assert_eq!(span_extent(Span::new(0, 4), 100.0, 5), (0.0, 100.0));
1324 assert_eq!(span_extent(Span::new(3, 3), 100.0, 1), (0.0, 50.0));
1325 }
1326
1327 #[test]
1328 fn the_track_sits_right_of_the_labels_and_inside_the_playhead() {
1329 let track = track_bounds(bounds(), 0.0);
1330 assert_eq!(track.x, 10.0 + PLAYHEAD_RADIUS);
1331 assert_eq!(track.width, 400.0 - PLAYHEAD_RADIUS * 2.0);
1332 assert_eq!(track.height, TRACK_HEIGHT);
1333 let track = track_bounds(bounds(), 96.0);
1334 assert_eq!(track.x, 10.0 + 96.0 + space::SM + PLAYHEAD_RADIUS);
1335 let narrow = Rectangle {
1336 width: 20.0,
1337 ..bounds()
1338 };
1339 assert_eq!(track_bounds(narrow, 96.0).width, 0.0);
1340 }
1341
1342 #[test]
1343 fn height_grows_by_a_row_per_lane() {
1344 assert_eq!(height(0), TRACK_HEIGHT);
1345 assert_eq!(height(2), TRACK_HEIGHT + 2.0 * LANE_HEIGHT);
1346 }
1347
1348 #[test]
1349 fn actions_move_within_the_steps() {
1350 assert_eq!(Action::Previous.apply(3, 10), 2);
1351 assert_eq!(Action::Previous.apply(0, 10), 0);
1352 assert_eq!(Action::Next.apply(3, 10), 4);
1353 assert_eq!(Action::Next.apply(9, 10), 9);
1354 assert_eq!(Action::PageBack.apply(4, 30), 0);
1355 assert_eq!(Action::PageBack.apply(14, 30), 4);
1356 assert_eq!(Action::PageForward.apply(25, 30), 29);
1357 assert_eq!(Action::PageForward.apply(5, 30), 15);
1358 assert_eq!(Action::First.apply(7, 10), 0);
1359 assert_eq!(Action::Last.apply(2, 10), 9);
1360 assert_eq!(Action::Last.apply(0, 0), 0);
1361 assert_eq!(Action::Next.apply(50, 10), 9);
1362 }
1363
1364 fn resolve(keymap: &Keymap<Action>, chord: Chord) -> Option<Action> {
1365 keymap.resolve(chord.key(), chord.modifiers())
1366 }
1367
1368 #[test]
1369 fn default_keymap_binds_arrows_pages_and_ends() {
1370 let keymap = default_keymap();
1371 assert_eq!(
1372 resolve(&keymap, Chord::named(Named::ArrowLeft)),
1373 Some(Action::Previous)
1374 );
1375 assert_eq!(
1376 resolve(&keymap, Chord::named(Named::ArrowRight).shift()),
1377 Some(Action::PageForward)
1378 );
1379 assert_eq!(
1380 resolve(&keymap, Chord::named(Named::PageUp)),
1381 Some(Action::PageBack)
1382 );
1383 assert_eq!(
1384 resolve(&keymap, Chord::named(Named::End)),
1385 Some(Action::Last)
1386 );
1387 assert_eq!(Keymap::<Action>::defaults(), keymap);
1388 for action in Action::ALL {
1389 assert!(!action.name().is_empty());
1390 assert!(action.description().ends_with('.'));
1391 }
1392 }
1393
1394 #[test]
1395 fn keymap_overrides_and_unbinding() {
1396 let keymap = default_keymap()
1397 .bind(Chord::character('j'), Action::Next)
1398 .unbind(&Chord::named(Named::Home));
1399 assert_eq!(resolve(&keymap, Chord::character('j')), Some(Action::Next));
1400 assert_eq!(resolve(&keymap, Chord::named(Named::Home)), None);
1401 assert_eq!(
1402 resolve(&keymap, Chord::named(Named::End)),
1403 Some(Action::Last)
1404 );
1405 }
1406
1407 #[test]
1408 fn style_follows_the_status_in_light_and_dark() {
1409 for theme in [light(), dark()] {
1410 let tokens = Tokens::of(&theme);
1411 let active = style(&tokens, Status::Active);
1412 assert_eq!(active.playhead_border, tokens.primary);
1413 assert_eq!(active.playhead, tokens.background);
1414 assert_eq!(active.tone_alpha, 1.0);
1415 let hovered = style(&tokens, Status::Hovered);
1416 assert_ne!(hovered.playhead_border, active.playhead_border);
1417 assert!(hovered.playhead_border_width > active.playhead_border_width);
1418 let dragged = style(&tokens, Status::Dragged);
1419 assert_ne!(dragged.playhead_border, hovered.playhead_border);
1420 let disabled = style(&tokens, Status::Disabled);
1421 assert!(disabled.rail.a < active.rail.a);
1422 assert!(disabled.playhead_border.a < active.playhead_border.a);
1423 assert_eq!(disabled.tone_alpha, 0.5);
1424 assert!(disabled.hover.a < active.hover.a);
1425 assert_eq!(Status::ALL.len(), 4);
1426 }
1427 }
1428
1429 #[test]
1430 fn the_current_tick_fits_inside_the_playhead_in_every_status() {
1431 let tokens = Tokens::of(&light());
1432 for status in Status::ALL {
1433 let border = style(&tokens, status).playhead_border_width;
1434 let tall = playhead_tick(border);
1435 assert!(tall >= 4.0, "{status:?} leaves the tick visible");
1436 assert!(tall < (PLAYHEAD_RADIUS - border) * 2.0, "{status:?}");
1437 }
1438 assert!(tick_height(Tone::Warning) > tick_height(Tone::Neutral));
1439 }
1440
1441 #[test]
1442 fn times_place_the_steps_and_fill_in_missing_ones() {
1443 let t: Timeline<'_, ()> = timeline([Tone::Neutral; 4], 0).times([
1444 Duration::from_secs(0),
1445 Duration::from_secs(1),
1446 Duration::from_secs(4),
1447 ]);
1448 let Some(timing) = t.timing() else {
1449 panic!("timed");
1450 };
1451 assert_eq!(timing.positions().len(), 4);
1452 assert!(timing.positions()[3] > timing.positions()[2]);
1453 let track = Rectangle {
1454 x: 0.0,
1455 y: 0.0,
1456 width: 400.0,
1457 height: TRACK_HEIGHT,
1458 };
1459 assert_eq!(t.index_under(0.0, track), 0);
1460 assert_eq!(t.index_under(400.0, track), 3);
1461
1462 let even: Timeline<'_, ()> = timeline([Tone::Neutral; 4], 0);
1463 assert!(even.timing().is_none());
1464 assert_eq!(even.place_of(1), 1.0 / 3.0);
1465 }
1466
1467 #[test]
1468 fn end_and_compression_apply_in_any_order() {
1469 let times = [Duration::from_secs(0), Duration::from_secs(100)];
1470 let a: Timeline<'_, ()> = timeline([Tone::Neutral; 2], 0)
1471 .compress_gaps(Duration::from_secs(1))
1472 .end(Duration::from_secs(101))
1473 .times(times);
1474 let b: Timeline<'_, ()> = timeline([Tone::Neutral; 2], 0)
1475 .times(times)
1476 .end(Duration::from_secs(101))
1477 .compress_gaps(Duration::from_secs(1));
1478 assert_eq!(a.timing(), b.timing());
1479 assert_eq!(a.timing().map(|t| t.breaks().len()), Some(1));
1480 }
1481
1482 #[test]
1483 fn the_ruler_adds_a_row_below_the_lanes() {
1484 let t: Timeline<'_, ()> = timeline([Tone::Neutral; 3], 0);
1485 assert_eq!(t.total_height(), TRACK_HEIGHT);
1486 let t = t.ruler(true).lane(lane("A", []));
1487 assert_eq!(t.total_height(), TRACK_HEIGHT + LANE_HEIGHT + RULER_HEIGHT);
1488 }
1489
1490 #[test]
1491 fn even_rulers_number_the_steps_and_thin_out_when_narrow() {
1492 let marks = step_marks(5, 640.0);
1493 let labels: Vec<&str> = marks.iter().map(|(_, label)| label.as_str()).collect();
1494 assert_eq!(labels, ["1", "2", "3", "4", "5"]);
1495 assert_eq!(marks[4].0, 1.0);
1496 let narrow = step_marks(100, 320.0);
1497 assert_eq!(narrow.len(), 5);
1498 assert_eq!(narrow[1].1, "21");
1499 assert!(step_marks(0, 320.0).is_empty());
1500 }
1501
1502 #[test]
1503 fn timed_rulers_use_the_format() {
1504 let t: Timeline<'_, ()> = timeline([Tone::Neutral; 2], 0)
1505 .times([Duration::from_secs(0), Duration::from_secs(2)])
1506 .ruler(true);
1507 let labels: Vec<String> = t.marks(128.0).into_iter().map(|(_, l)| l).collect();
1508 assert_eq!(labels, ["0 s", "1 s", "2 s"]);
1509 let t = t.ruler_format(|time| format!("t+{}", time.as_secs()));
1510 let labels: Vec<String> = t.marks(128.0).into_iter().map(|(_, l)| l).collect();
1511 assert_eq!(labels, ["t+0", "t+1", "t+2"]);
1512 }
1513
1514 #[test]
1515 fn breaks_cut_gaps_in_the_bars() {
1516 assert_eq!(pieces(0.0, 100.0, &[]), [(0.0, 100.0)]);
1517 assert_eq!(
1518 pieces(0.0, 100.0, &[(40.0, 60.0)]),
1519 [(0.0, 40.0 - BREAK_INSET), (60.0 + BREAK_INSET, 100.0)]
1520 );
1521 assert_eq!(pieces(0.0, 100.0, &[(0.0, 100.0)]), []);
1522 }
1523
1524 #[test]
1525 fn labels_near_an_edge_line_up_with_it() {
1526 let bounds = Rectangle {
1527 x: 0.0,
1528 y: 0.0,
1529 width: 300.0,
1530 height: 40.0,
1531 };
1532 assert_eq!(mark_alignment(6.0, bounds), text::Alignment::Left);
1533 assert_eq!(mark_alignment(150.0, bounds), text::Alignment::Center);
1534 assert_eq!(mark_alignment(294.0, bounds), text::Alignment::Right);
1535 }
1536}