Skip to main content

fc_ui/capabilities/media/
audio_player.rs

1use crate::capabilities::foundation::icon_config::resolve_icon_path;
2use crate::capabilities::foundation::theme::use_theme;
3use gpui::{prelude::*, *};
4use std::rc::Rc;
5#[cfg(feature = "audio")]
6use std::sync::{Arc, Mutex};
7
8type WindowCallback = Rc<dyn Fn(&mut Window, &mut App) + 'static>;
9type ValueCallback<T> = Rc<dyn Fn(T, &mut Window, &mut App) + 'static>;
10
11#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
12pub enum AudioPlayerSize {
13    Compact,
14    #[default]
15    Full,
16}
17
18#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
19pub enum PlaybackSpeed {
20    Half,
21    #[default]
22    Normal,
23    OneAndHalf,
24    Double,
25}
26
27impl PlaybackSpeed {
28    pub fn value(&self) -> f32 {
29        match self {
30            PlaybackSpeed::Half => 0.5,
31            PlaybackSpeed::Normal => 1.0,
32            PlaybackSpeed::OneAndHalf => 1.5,
33            PlaybackSpeed::Double => 2.0,
34        }
35    }
36
37    pub fn label(&self) -> &'static str {
38        match self {
39            PlaybackSpeed::Half => "0.5x",
40            PlaybackSpeed::Normal => "1x",
41            PlaybackSpeed::OneAndHalf => "1.5x",
42            PlaybackSpeed::Double => "2x",
43        }
44    }
45
46    pub fn next(&self) -> Self {
47        match self {
48            PlaybackSpeed::Half => PlaybackSpeed::Normal,
49            PlaybackSpeed::Normal => PlaybackSpeed::OneAndHalf,
50            PlaybackSpeed::OneAndHalf => PlaybackSpeed::Double,
51            PlaybackSpeed::Double => PlaybackSpeed::Half,
52        }
53    }
54}
55
56#[cfg(feature = "audio")]
57pub struct AudioBackend {
58    // Fields drop in declaration order: `player` is dropped before
59    // `device_sink`, honouring the sink's rule that it must outlive every
60    // `Player` connected to its mixer.
61    player: rodio::Player,
62    /// Owns the output device. Dropping it stops playback.
63    device_sink: rodio::MixerDeviceSink,
64    file_path: Option<String>,
65}
66
67#[cfg(feature = "audio")]
68impl AudioBackend {
69    pub fn new() -> Option<Self> {
70        let mut device_sink = rodio::DeviceSinkBuilder::open_default_sink().ok()?;
71        // Playback ends silently when the sink is dropped; the library should
72        // not print rodio's own notice to stderr.
73        device_sink.log_on_drop(false);
74        let player = rodio::Player::connect_new(device_sink.mixer());
75        player.pause();
76        Some(Self {
77            device_sink,
78            player,
79            file_path: None,
80        })
81    }
82
83    pub fn load(&mut self, path: &str) -> Result<std::time::Duration, String> {
84        use rodio::Source;
85
86        let source = open_decoder(path)?;
87        let duration = source.total_duration().unwrap_or(std::time::Duration::ZERO);
88
89        // Reconnecting a fresh player drops the previous source and resets
90        // volume/speed state along with it, so reapply nothing here.
91        self.player = rodio::Player::connect_new(self.device_sink.mixer());
92        self.player.append(source);
93        self.player.pause();
94        self.file_path = Some(path.to_string());
95
96        Ok(duration)
97    }
98
99    pub fn play(&self) {
100        self.player.play();
101    }
102
103    pub fn pause(&self) {
104        self.player.pause();
105    }
106
107    pub fn stop(&self) {
108        self.player.pause();
109        let _ = self.player.try_seek(std::time::Duration::ZERO);
110    }
111
112    pub fn seek(&self, position: std::time::Duration) {
113        let _ = self.player.try_seek(position);
114    }
115
116    pub fn set_volume(&self, volume: f32) {
117        self.player.set_volume(volume);
118    }
119
120    pub fn set_speed(&self, speed: f32) {
121        self.player.set_speed(speed);
122    }
123
124    pub fn is_empty(&self) -> bool {
125        self.player.empty()
126    }
127}
128
129/// Decodes `path` into a seekable source.
130///
131/// Converts the `File` itself rather than a `BufReader`: only that `TryFrom`
132/// impl records the byte length, which both `total_duration` and `try_seek`
133/// rely on. Wrapping the file in a `BufReader` first produces the same
134/// `Decoder<BufReader<File>>` type but silently reports no duration.
135#[cfg(feature = "audio")]
136fn open_decoder(path: &str) -> Result<rodio::Decoder<std::io::BufReader<std::fs::File>>, String> {
137    let file = std::fs::File::open(path).map_err(|e| e.to_string())?;
138    rodio::Decoder::try_from(file).map_err(|e| e.to_string())
139}
140
141pub struct AudioPlayerState {
142    is_playing: bool,
143    is_muted: bool,
144    current_time: f32,
145    duration: f32,
146    volume: f32,
147    playback_speed: PlaybackSpeed,
148    focus_handle: FocusHandle,
149    progress_dragging: bool,
150    volume_dragging: bool,
151    progress_bounds: Bounds<Pixels>,
152    volume_bounds: Bounds<Pixels>,
153    source_path: Option<String>,
154    #[cfg(feature = "audio")]
155    backend: Option<Arc<Mutex<AudioBackend>>>,
156}
157
158impl AudioPlayerState {
159    pub fn new(cx: &mut Context<Self>) -> Self {
160        Self {
161            is_playing: false,
162            is_muted: false,
163            current_time: 0.0,
164            duration: 0.0,
165            volume: 0.8,
166            playback_speed: PlaybackSpeed::Normal,
167            focus_handle: cx.focus_handle(),
168            progress_dragging: false,
169            volume_dragging: false,
170            progress_bounds: Bounds::default(),
171            volume_bounds: Bounds::default(),
172            source_path: None,
173            #[cfg(feature = "audio")]
174            backend: AudioBackend::new().map(|b| Arc::new(Mutex::new(b))),
175        }
176    }
177
178    #[cfg(feature = "audio")]
179    pub fn load_file(&mut self, path: impl Into<String>, cx: &mut Context<Self>) -> bool {
180        let path_str = path.into();
181
182        if let Some(ref backend) = self.backend {
183            if let Ok(mut backend) = backend.lock() {
184                match backend.load(&path_str) {
185                    Ok(duration) => {
186                        self.duration = duration.as_secs_f32();
187                        self.current_time = 0.0;
188                        self.is_playing = false;
189                        backend.set_volume(self.volume);
190                        backend.set_speed(self.playback_speed.value());
191                        self.source_path = Some(path_str);
192                        cx.notify();
193                        return true;
194                    }
195                    Err(e) => {
196                        eprintln!("Failed to load audio: {}", e);
197                    }
198                }
199            }
200        }
201        self.source_path = None;
202        cx.notify();
203        false
204    }
205
206    #[cfg(not(feature = "audio"))]
207    pub fn load_file(&mut self, path: impl Into<String>, cx: &mut Context<Self>) -> bool {
208        self.source_path = Some(path.into());
209        cx.notify();
210        false
211    }
212
213    pub fn is_playing(&self) -> bool {
214        self.is_playing
215    }
216
217    pub fn set_playing(&mut self, playing: bool, cx: &mut Context<Self>) {
218        self.is_playing = playing;
219        #[cfg(feature = "audio")]
220        if let Some(ref backend) = self.backend {
221            if let Ok(backend) = backend.lock() {
222                if playing {
223                    backend.play();
224                } else {
225                    backend.pause();
226                }
227            }
228        }
229        cx.notify();
230    }
231
232    pub fn toggle_playing(&mut self, cx: &mut Context<Self>) {
233        self.is_playing = !self.is_playing;
234        #[cfg(feature = "audio")]
235        if let Some(ref backend) = self.backend {
236            if let Ok(backend) = backend.lock() {
237                if self.is_playing {
238                    backend.play();
239                } else {
240                    backend.pause();
241                }
242            }
243        }
244        cx.notify();
245    }
246
247    pub fn is_muted(&self) -> bool {
248        self.is_muted
249    }
250
251    pub fn set_muted(&mut self, muted: bool, cx: &mut Context<Self>) {
252        self.is_muted = muted;
253        #[cfg(feature = "audio")]
254        self.apply_volume();
255        cx.notify();
256    }
257
258    pub fn toggle_muted(&mut self, cx: &mut Context<Self>) {
259        self.is_muted = !self.is_muted;
260        #[cfg(feature = "audio")]
261        self.apply_volume();
262        cx.notify();
263    }
264
265    pub fn current_time(&self) -> f32 {
266        self.current_time
267    }
268
269    pub fn set_current_time(&mut self, time: f32, cx: &mut Context<Self>) {
270        self.current_time = time.clamp(0.0, self.duration);
271        cx.notify();
272    }
273
274    pub fn duration(&self) -> f32 {
275        self.duration
276    }
277
278    pub fn set_duration(&mut self, duration: f32, cx: &mut Context<Self>) {
279        if duration < 0.0 {
280            return;
281        }
282        self.duration = duration;
283        self.current_time = self.current_time.min(duration);
284        cx.notify();
285    }
286
287    pub fn volume(&self) -> f32 {
288        self.volume
289    }
290
291    pub fn set_volume(&mut self, volume: f32, cx: &mut Context<Self>) {
292        self.volume = volume.clamp(0.0, 1.0);
293        if self.volume > 0.0 {
294            self.is_muted = false;
295        }
296        #[cfg(feature = "audio")]
297        self.apply_volume();
298        cx.notify();
299    }
300
301    #[cfg(feature = "audio")]
302    fn apply_volume(&self) {
303        if let Some(ref backend) = self.backend {
304            if let Ok(backend) = backend.lock() {
305                let effective_vol = if self.is_muted { 0.0 } else { self.volume };
306                backend.set_volume(effective_vol);
307            }
308        }
309    }
310
311    pub fn effective_volume(&self) -> f32 {
312        if self.is_muted {
313            0.0
314        } else {
315            self.volume
316        }
317    }
318
319    pub fn playback_speed(&self) -> PlaybackSpeed {
320        self.playback_speed
321    }
322
323    pub fn set_playback_speed(&mut self, speed: PlaybackSpeed, cx: &mut Context<Self>) {
324        self.playback_speed = speed;
325        #[cfg(feature = "audio")]
326        if let Some(ref backend) = self.backend {
327            if let Ok(backend) = backend.lock() {
328                backend.set_speed(speed.value());
329            }
330        }
331        cx.notify();
332    }
333
334    pub fn cycle_playback_speed(&mut self, cx: &mut Context<Self>) {
335        self.playback_speed = self.playback_speed.next();
336        #[cfg(feature = "audio")]
337        if let Some(ref backend) = self.backend {
338            if let Ok(backend) = backend.lock() {
339                backend.set_speed(self.playback_speed.value());
340            }
341        }
342        cx.notify();
343    }
344
345    pub fn stop(&mut self, cx: &mut Context<Self>) {
346        self.is_playing = false;
347        self.current_time = 0.0;
348        #[cfg(feature = "audio")]
349        if let Some(ref backend) = self.backend {
350            if let Ok(backend) = backend.lock() {
351                backend.stop();
352            }
353        }
354        cx.notify();
355    }
356
357    #[cfg(feature = "audio")]
358    pub fn is_finished(&self) -> bool {
359        if let Some(ref backend) = self.backend {
360            if let Ok(backend) = backend.lock() {
361                return backend.is_empty();
362            }
363        }
364        false
365    }
366
367    #[cfg(not(feature = "audio"))]
368    pub fn is_finished(&self) -> bool {
369        self.current_time >= self.duration
370    }
371
372    fn progress_percentage(&self) -> f32 {
373        if self.duration <= 0.0 {
374            return 0.0;
375        }
376        (self.current_time / self.duration).clamp(0.0, 1.0)
377    }
378
379    fn update_progress_from_position(&mut self, position: Point<Pixels>, cx: &mut Context<Self>) {
380        let track_width = self.progress_bounds.size.width;
381        if track_width <= px(0.0) {
382            return;
383        }
384        let relative_x = (position.x - self.progress_bounds.left()).clamp(px(0.0), track_width);
385        let percentage = (relative_x / track_width).clamp(0.0, 1.0);
386        self.current_time = percentage * self.duration;
387        #[cfg(feature = "audio")]
388        if let Some(ref backend) = self.backend {
389            if let Ok(backend) = backend.lock() {
390                backend.seek(std::time::Duration::from_secs_f32(self.current_time));
391            }
392        }
393        cx.notify();
394    }
395
396    fn update_volume_from_position(&mut self, position: Point<Pixels>, cx: &mut Context<Self>) {
397        let track_width = self.volume_bounds.size.width;
398        if track_width <= px(0.0) {
399            return;
400        }
401        let relative_x = (position.x - self.volume_bounds.left()).clamp(px(0.0), track_width);
402        let volume = (relative_x / track_width).clamp(0.0, 1.0);
403        self.set_volume(volume, cx);
404    }
405
406    #[cfg(feature = "audio")]
407    pub fn is_audio_loaded(&self) -> bool {
408        self.backend.is_some() && self.source_path.is_some()
409    }
410
411    #[cfg(not(feature = "audio"))]
412    pub fn is_audio_loaded(&self) -> bool {
413        false
414    }
415}
416
417impl Focusable for AudioPlayerState {
418    fn focus_handle(&self, _: &App) -> FocusHandle {
419        self.focus_handle.clone()
420    }
421}
422
423impl Render for AudioPlayerState {
424    fn render(&mut self, _: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
425        div()
426    }
427}
428
429fn format_time(seconds: f32) -> String {
430    let total_seconds = seconds.max(0.0) as u32;
431    let hours = total_seconds / 3600;
432    let minutes = (total_seconds % 3600) / 60;
433    let secs = total_seconds % 60;
434
435    if hours > 0 {
436        format!("{}:{:02}:{:02}", hours, minutes, secs)
437    } else {
438        format!("{:02}:{:02}", minutes, secs)
439    }
440}
441
442#[derive(IntoElement)]
443pub struct AudioPlayer {
444    state: Entity<AudioPlayerState>,
445    size: AudioPlayerSize,
446    disabled: bool,
447    title: Option<SharedString>,
448    on_play: Option<WindowCallback>,
449    on_pause: Option<WindowCallback>,
450    on_seek: Option<ValueCallback<f32>>,
451    on_volume_change: Option<ValueCallback<f32>>,
452    on_speed_change: Option<ValueCallback<PlaybackSpeed>>,
453    style: StyleRefinement,
454}
455
456impl AudioPlayer {
457    pub fn new(state: Entity<AudioPlayerState>) -> Self {
458        Self {
459            state,
460            size: AudioPlayerSize::Full,
461            disabled: false,
462            title: None,
463            on_play: None,
464            on_pause: None,
465            on_seek: None,
466            on_volume_change: None,
467            on_speed_change: None,
468            style: StyleRefinement::default(),
469        }
470    }
471
472    pub fn size(mut self, size: AudioPlayerSize) -> Self {
473        self.size = size;
474        self
475    }
476
477    pub fn compact(mut self) -> Self {
478        self.size = AudioPlayerSize::Compact;
479        self
480    }
481
482    pub fn full(mut self) -> Self {
483        self.size = AudioPlayerSize::Full;
484        self
485    }
486
487    pub fn disabled(mut self, disabled: bool) -> Self {
488        self.disabled = disabled;
489        self
490    }
491
492    pub fn title(mut self, title: impl Into<SharedString>) -> Self {
493        self.title = Some(title.into());
494        self
495    }
496
497    pub fn on_play(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
498        self.on_play = Some(Rc::new(handler));
499        self
500    }
501
502    pub fn on_pause(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
503        self.on_pause = Some(Rc::new(handler));
504        self
505    }
506
507    pub fn on_seek(mut self, handler: impl Fn(f32, &mut Window, &mut App) + 'static) -> Self {
508        self.on_seek = Some(Rc::new(handler));
509        self
510    }
511
512    pub fn on_volume_change(
513        mut self,
514        handler: impl Fn(f32, &mut Window, &mut App) + 'static,
515    ) -> Self {
516        self.on_volume_change = Some(Rc::new(handler));
517        self
518    }
519
520    pub fn on_speed_change(
521        mut self,
522        handler: impl Fn(PlaybackSpeed, &mut Window, &mut App) + 'static,
523    ) -> Self {
524        self.on_speed_change = Some(Rc::new(handler));
525        self
526    }
527}
528
529impl Styled for AudioPlayer {
530    fn style(&mut self) -> &mut StyleRefinement {
531        &mut self.style
532    }
533}
534
535impl RenderOnce for AudioPlayer {
536    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
537        let theme = use_theme(cx);
538        let state = self.state.read(cx);
539        let is_playing = state.is_playing;
540        let is_muted = state.is_muted;
541        let current_time = state.current_time;
542        let duration = state.duration;
543        let volume = state.volume;
544        let progress_percentage = state.progress_percentage();
545        let playback_speed = state.playback_speed;
546        let user_style = self.style.clone();
547
548        let (padding, gap, button_size, icon_size, track_height, thumb_size) = match self.size {
549            AudioPlayerSize::Compact => (px(8.0), px(8.0), px(32.0), px(16.0), px(4.0), px(12.0)),
550            AudioPlayerSize::Full => (px(16.0), px(12.0), px(40.0), px(20.0), px(6.0), px(16.0)),
551        };
552
553        let play_icon = if is_playing { "pause" } else { "play" };
554        let volume_icon = if is_muted || volume == 0.0 {
555            "volume-x"
556        } else if volume < 0.5 {
557            "volume-1"
558        } else {
559            "volume-2"
560        };
561
562        let base = div()
563            .flex()
564            .items_center()
565            .gap(gap)
566            .p(padding)
567            .bg(theme.tokens.card)
568            .border_1()
569            .border_color(theme.tokens.border)
570            .rounded(theme.tokens.radius_lg)
571            .when(self.disabled, |this| this.opacity(0.5));
572
573        match self.size {
574            AudioPlayerSize::Compact => base
575                .map(|this| {
576                    let mut div = this;
577                    div.style().refine(&user_style);
578                    div
579                })
580                .child(self.render_play_button(
581                    window,
582                    &theme,
583                    play_icon,
584                    is_playing,
585                    button_size,
586                    icon_size,
587                ))
588                .child(self.render_progress_bar(
589                    window,
590                    &theme,
591                    progress_percentage,
592                    track_height,
593                    thumb_size,
594                ))
595                .child(
596                    div()
597                        .text_size(px(11.0))
598                        .text_color(theme.tokens.muted_foreground)
599                        .font_family(theme.tokens.font_mono.clone())
600                        .child(format!(
601                            "{} / {}",
602                            format_time(current_time),
603                            format_time(duration)
604                        )),
605                ),
606
607            AudioPlayerSize::Full => base
608                .flex_col()
609                .gap(px(12.0))
610                .map(|this| {
611                    let mut div = this;
612                    div.style().refine(&user_style);
613                    div
614                })
615                .when_some(self.title.clone(), |this, title| {
616                    this.child(
617                        div()
618                            .w_full()
619                            .text_size(px(14.0))
620                            .font_weight(FontWeight::MEDIUM)
621                            .text_color(theme.tokens.foreground)
622                            .overflow_hidden()
623                            .text_ellipsis()
624                            .child(title),
625                    )
626                })
627                .child(
628                    div()
629                        .flex()
630                        .flex_col()
631                        .gap(px(4.0))
632                        .w_full()
633                        .child(self.render_progress_bar(
634                            window,
635                            &theme,
636                            progress_percentage,
637                            track_height,
638                            thumb_size,
639                        ))
640                        .child(
641                            div()
642                                .flex()
643                                .justify_between()
644                                .w_full()
645                                .text_size(px(12.0))
646                                .font_family(theme.tokens.font_mono.clone())
647                                .text_color(theme.tokens.muted_foreground)
648                                .child(format_time(current_time))
649                                .child(format_time(duration)),
650                        ),
651                )
652                .child(
653                    div()
654                        .flex()
655                        .items_center()
656                        .justify_between()
657                        .w_full()
658                        .child(div().flex().items_center().gap(px(8.0)).child(
659                            self.render_play_button(
660                                window,
661                                &theme,
662                                play_icon,
663                                is_playing,
664                                button_size,
665                                icon_size,
666                            ),
667                        ))
668                        .child(
669                            div()
670                                .flex()
671                                .items_center()
672                                .gap(px(8.0))
673                                .child(self.render_speed_button(window, &theme, playback_speed))
674                                .child(self.render_mute_button(
675                                    window,
676                                    &theme,
677                                    volume_icon,
678                                    px(28.0),
679                                    px(14.0),
680                                ))
681                                .child(self.render_volume_slider(
682                                    window,
683                                    &theme,
684                                    volume,
685                                    px(80.0),
686                                    px(4.0),
687                                    px(12.0),
688                                )),
689                        ),
690                ),
691        }
692    }
693}
694
695impl AudioPlayer {
696    fn render_play_button(
697        &self,
698        window: &mut Window,
699        theme: &crate::capabilities::foundation::theme::Theme,
700        icon_name: &str,
701        _is_playing: bool,
702        button_size: Pixels,
703        icon_size: Pixels,
704    ) -> impl IntoElement {
705        let state = self.state.clone();
706        let on_play = self.on_play.clone();
707        let on_pause = self.on_pause.clone();
708        let disabled = self.disabled;
709
710        div()
711            .id("audio-play-button")
712            .flex()
713            .items_center()
714            .justify_center()
715            .size(button_size)
716            .rounded_full()
717            .bg(theme.tokens.primary)
718            .when(!disabled, |this| {
719                this.cursor(CursorStyle::PointingHand)
720                    .hover(|style| style.bg(theme.tokens.primary.opacity(0.9)))
721            })
722            .child(
723                svg()
724                    .path(resolve_icon_path(icon_name))
725                    .size(icon_size)
726                    .text_color(theme.tokens.primary_foreground),
727            )
728            .when(!disabled, |this| {
729                this.on_click(window.listener_for(&state, move |state, _, window, cx| {
730                    state.toggle_playing(cx);
731                    if state.is_playing {
732                        if let Some(ref handler) = on_play {
733                            handler(window, cx);
734                        }
735                    } else if let Some(ref handler) = on_pause {
736                        handler(window, cx);
737                    }
738                }))
739            })
740    }
741
742    fn render_progress_bar(
743        &self,
744        window: &mut Window,
745        theme: &crate::capabilities::foundation::theme::Theme,
746        percentage: f32,
747        track_height: Pixels,
748        thumb_size: Pixels,
749    ) -> impl IntoElement {
750        let state = self.state.clone();
751        let on_seek = self.on_seek.clone();
752        let disabled = self.disabled;
753
754        div()
755            .flex_1()
756            .h(thumb_size)
757            .flex()
758            .items_center()
759            .relative()
760            .child(
761                canvas(
762                    {
763                        let state = state.clone();
764                        move |bounds, _, cx| {
765                            state.update(cx, |state, _| {
766                                state.progress_bounds = bounds;
767                            });
768                        }
769                    },
770                    |_, _, _, _| {},
771                )
772                .absolute()
773                .size_full(),
774            )
775            .child(
776                div()
777                    .w_full()
778                    .h(track_height)
779                    .rounded_full()
780                    .bg(theme.tokens.muted)
781                    .overflow_hidden()
782                    .child(
783                        div()
784                            .h_full()
785                            .w(relative(percentage))
786                            .bg(theme.tokens.primary),
787                    ),
788            )
789            .child(
790                div()
791                    .absolute()
792                    .left(relative(percentage))
793                    .top(px(0.0))
794                    .ml(-(thumb_size / 2.0))
795                    .size(thumb_size)
796                    .rounded_full()
797                    .bg(theme.tokens.primary)
798                    .border_2()
799                    .border_color(theme.tokens.background)
800                    .shadow_sm()
801                    .when(!disabled, |this| this.cursor(CursorStyle::PointingHand)),
802            )
803            .when(!disabled, |this| {
804                let state_down = state.clone();
805                let on_seek_down = on_seek.clone();
806                let state_move = state.clone();
807                let on_seek_move = on_seek.clone();
808                let state_up = state.clone();
809
810                this.on_mouse_down(
811                    MouseButton::Left,
812                    window.listener_for(
813                        &state_down,
814                        move |state, e: &MouseDownEvent, window, cx| {
815                            state.progress_dragging = true;
816                            state.update_progress_from_position(e.position, cx);
817                            if let Some(ref handler) = on_seek_down {
818                                handler(state.current_time, window, cx);
819                            }
820                        },
821                    ),
822                )
823                .on_mouse_move(window.listener_for(
824                    &state_move,
825                    move |state, e: &MouseMoveEvent, window, cx| {
826                        if state.progress_dragging {
827                            state.update_progress_from_position(e.position, cx);
828                            if let Some(ref handler) = on_seek_move {
829                                handler(state.current_time, window, cx);
830                            }
831                        }
832                    },
833                ))
834                .on_mouse_up(
835                    MouseButton::Left,
836                    window.listener_for(&state_up, move |state, _: &MouseUpEvent, _, _| {
837                        state.progress_dragging = false;
838                    }),
839                )
840                .on_mouse_up_out(
841                    MouseButton::Left,
842                    window.listener_for(&state_up, move |state, _: &MouseUpEvent, _, _| {
843                        state.progress_dragging = false;
844                    }),
845                )
846            })
847    }
848
849    fn render_mute_button(
850        &self,
851        window: &mut Window,
852        theme: &crate::capabilities::foundation::theme::Theme,
853        icon_name: &str,
854        button_size: Pixels,
855        icon_size: Pixels,
856    ) -> impl IntoElement {
857        let state = self.state.clone();
858        let disabled = self.disabled;
859
860        div()
861            .id("audio-mute-button")
862            .flex()
863            .items_center()
864            .justify_center()
865            .size(button_size)
866            .rounded(theme.tokens.radius_md)
867            .when(!disabled, |this| {
868                this.cursor(CursorStyle::PointingHand)
869                    .hover(|style| style.bg(theme.tokens.accent))
870            })
871            .child(
872                svg()
873                    .path(resolve_icon_path(icon_name))
874                    .size(icon_size)
875                    .text_color(theme.tokens.muted_foreground),
876            )
877            .when(!disabled, |this| {
878                this.on_click(window.listener_for(&state, move |state, _, _, cx| {
879                    state.toggle_muted(cx);
880                }))
881            })
882    }
883
884    fn render_volume_slider(
885        &self,
886        window: &mut Window,
887        theme: &crate::capabilities::foundation::theme::Theme,
888        volume: f32,
889        width: Pixels,
890        track_height: Pixels,
891        thumb_size: Pixels,
892    ) -> impl IntoElement {
893        let state = self.state.clone();
894        let on_volume_change = self.on_volume_change.clone();
895        let disabled = self.disabled;
896
897        div()
898            .w(width)
899            .h(thumb_size)
900            .flex()
901            .items_center()
902            .relative()
903            .child(
904                canvas(
905                    {
906                        let state = state.clone();
907                        move |bounds, _, cx| {
908                            state.update(cx, |state, _| {
909                                state.volume_bounds = bounds;
910                            });
911                        }
912                    },
913                    |_, _, _, _| {},
914                )
915                .absolute()
916                .size_full(),
917            )
918            .child(
919                div()
920                    .w_full()
921                    .h(track_height)
922                    .rounded_full()
923                    .bg(theme.tokens.muted)
924                    .overflow_hidden()
925                    .child(
926                        div()
927                            .h_full()
928                            .w(relative(volume))
929                            .bg(theme.tokens.muted_foreground),
930                    ),
931            )
932            .child(
933                div()
934                    .absolute()
935                    .left(relative(volume))
936                    .top(px(0.0))
937                    .ml(-(thumb_size / 2.0))
938                    .size(thumb_size)
939                    .rounded_full()
940                    .bg(theme.tokens.foreground)
941                    .border_2()
942                    .border_color(theme.tokens.background)
943                    .shadow_sm()
944                    .when(!disabled, |this| this.cursor(CursorStyle::PointingHand)),
945            )
946            .when(!disabled, |this| {
947                let state_down = state.clone();
948                let on_vol_down = on_volume_change.clone();
949                let state_move = state.clone();
950                let on_vol_move = on_volume_change.clone();
951                let state_up = state.clone();
952
953                this.on_mouse_down(
954                    MouseButton::Left,
955                    window.listener_for(
956                        &state_down,
957                        move |state, e: &MouseDownEvent, window, cx| {
958                            state.volume_dragging = true;
959                            state.update_volume_from_position(e.position, cx);
960                            if let Some(ref handler) = on_vol_down {
961                                handler(state.volume, window, cx);
962                            }
963                        },
964                    ),
965                )
966                .on_mouse_move(window.listener_for(
967                    &state_move,
968                    move |state, e: &MouseMoveEvent, window, cx| {
969                        if state.volume_dragging {
970                            state.update_volume_from_position(e.position, cx);
971                            if let Some(ref handler) = on_vol_move {
972                                handler(state.volume, window, cx);
973                            }
974                        }
975                    },
976                ))
977                .on_mouse_up(
978                    MouseButton::Left,
979                    window.listener_for(&state_up, move |state, _: &MouseUpEvent, _, _| {
980                        state.volume_dragging = false;
981                    }),
982                )
983                .on_mouse_up_out(
984                    MouseButton::Left,
985                    window.listener_for(&state_up, move |state, _: &MouseUpEvent, _, _| {
986                        state.volume_dragging = false;
987                    }),
988                )
989            })
990    }
991
992    fn render_speed_button(
993        &self,
994        window: &mut Window,
995        theme: &crate::capabilities::foundation::theme::Theme,
996        speed: PlaybackSpeed,
997    ) -> impl IntoElement {
998        let state = self.state.clone();
999        let on_speed_change = self.on_speed_change.clone();
1000        let disabled = self.disabled;
1001
1002        div()
1003            .id("audio-speed-button")
1004            .flex()
1005            .items_center()
1006            .justify_center()
1007            .px(px(8.0))
1008            .h(px(28.0))
1009            .rounded(theme.tokens.radius_md)
1010            .text_size(px(12.0))
1011            .font_weight(FontWeight::MEDIUM)
1012            .text_color(theme.tokens.muted_foreground)
1013            .when(!disabled, |this| {
1014                this.cursor(CursorStyle::PointingHand)
1015                    .hover(|style| style.bg(theme.tokens.accent))
1016            })
1017            .child(speed.label())
1018            .when(!disabled, |this| {
1019                this.on_click(window.listener_for(&state, move |state, _, window, cx| {
1020                    state.cycle_playback_speed(cx);
1021                    if let Some(ref handler) = on_speed_change {
1022                        handler(state.playback_speed, window, cx);
1023                    }
1024                }))
1025            })
1026    }
1027}
1028
1029#[cfg(all(test, feature = "audio"))]
1030mod tests {
1031    use super::open_decoder;
1032    use rodio::Source;
1033
1034    const SAMPLE: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/assets/audio/sample.mp3");
1035
1036    /// The `File` decoder path must report the real duration. Decoding through
1037    /// a `BufReader` yields the same type but no duration, which would leave
1038    /// the progress bar and seek target pinned at zero.
1039    #[test]
1040    fn decoding_a_file_reports_its_duration() {
1041        let source = open_decoder(SAMPLE).expect("decode sample.mp3");
1042        let duration = source.total_duration().expect("duration is known");
1043
1044        // `afinfo` reports 372.7s for this asset; allow a wide margin so the
1045        // test tracks the decoder path, not the exact encoder settings.
1046        assert!(
1047            duration.as_secs_f64() > 300.0,
1048            "expected a multi-minute duration, got {duration:?}"
1049        );
1050    }
1051
1052    /// Seeking must work on the decoded source. `rodio::Player::try_seek`
1053    /// delegates here, so a regression shows up as a dead progress bar.
1054    #[test]
1055    fn a_decoded_file_can_be_seeked() {
1056        let mut source = open_decoder(SAMPLE).expect("decode sample.mp3");
1057        let _: Vec<_> = source.by_ref().take(44_100).collect();
1058
1059        assert!(
1060            source.try_seek(std::time::Duration::from_secs(30)).is_ok(),
1061            "seeking a decoded file failed"
1062        );
1063    }
1064
1065    #[test]
1066    fn a_missing_file_is_an_error_rather_than_a_panic() {
1067        assert!(open_decoder("/nonexistent/fc-ui.mp3").is_err());
1068    }
1069}