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 player: rodio::Player,
62 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 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 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#[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
429use crate::capabilities::media::format_time;
430
431#[derive(IntoElement)]
432pub struct AudioPlayer {
433 state: Entity<AudioPlayerState>,
434 size: AudioPlayerSize,
435 disabled: bool,
436 title: Option<SharedString>,
437 on_play: Option<WindowCallback>,
438 on_pause: Option<WindowCallback>,
439 on_seek: Option<ValueCallback<f32>>,
440 on_volume_change: Option<ValueCallback<f32>>,
441 on_speed_change: Option<ValueCallback<PlaybackSpeed>>,
442 style: StyleRefinement,
443}
444
445impl AudioPlayer {
446 pub fn new(state: Entity<AudioPlayerState>) -> Self {
447 Self {
448 state,
449 size: AudioPlayerSize::Full,
450 disabled: false,
451 title: None,
452 on_play: None,
453 on_pause: None,
454 on_seek: None,
455 on_volume_change: None,
456 on_speed_change: None,
457 style: StyleRefinement::default(),
458 }
459 }
460
461 pub fn size(mut self, size: AudioPlayerSize) -> Self {
462 self.size = size;
463 self
464 }
465
466 pub fn compact(mut self) -> Self {
467 self.size = AudioPlayerSize::Compact;
468 self
469 }
470
471 pub fn full(mut self) -> Self {
472 self.size = AudioPlayerSize::Full;
473 self
474 }
475
476 pub fn disabled(mut self, disabled: bool) -> Self {
477 self.disabled = disabled;
478 self
479 }
480
481 pub fn title(mut self, title: impl Into<SharedString>) -> Self {
482 self.title = Some(title.into());
483 self
484 }
485
486 pub fn on_play(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
487 self.on_play = Some(Rc::new(handler));
488 self
489 }
490
491 pub fn on_pause(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
492 self.on_pause = Some(Rc::new(handler));
493 self
494 }
495
496 pub fn on_seek(mut self, handler: impl Fn(f32, &mut Window, &mut App) + 'static) -> Self {
497 self.on_seek = Some(Rc::new(handler));
498 self
499 }
500
501 pub fn on_volume_change(
502 mut self,
503 handler: impl Fn(f32, &mut Window, &mut App) + 'static,
504 ) -> Self {
505 self.on_volume_change = Some(Rc::new(handler));
506 self
507 }
508
509 pub fn on_speed_change(
510 mut self,
511 handler: impl Fn(PlaybackSpeed, &mut Window, &mut App) + 'static,
512 ) -> Self {
513 self.on_speed_change = Some(Rc::new(handler));
514 self
515 }
516}
517
518impl Styled for AudioPlayer {
519 fn style(&mut self) -> &mut StyleRefinement {
520 &mut self.style
521 }
522}
523
524impl RenderOnce for AudioPlayer {
525 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
526 let theme = use_theme(cx);
527 let state = self.state.read(cx);
528 let is_playing = state.is_playing;
529 let is_muted = state.is_muted;
530 let current_time = state.current_time;
531 let duration = state.duration;
532 let volume = state.volume;
533 let progress_percentage = state.progress_percentage();
534 let playback_speed = state.playback_speed;
535 let user_style = self.style.clone();
536
537 let (padding, gap, button_size, icon_size, track_height, thumb_size) = match self.size {
538 AudioPlayerSize::Compact => (px(8.0), px(8.0), px(32.0), px(16.0), px(4.0), px(12.0)),
539 AudioPlayerSize::Full => (px(16.0), px(12.0), px(40.0), px(20.0), px(6.0), px(16.0)),
540 };
541
542 let play_icon = if is_playing { "pause" } else { "play" };
543 let volume_icon = if is_muted || volume == 0.0 {
544 "volume-x"
545 } else if volume < 0.5 {
546 "volume-1"
547 } else {
548 "volume-2"
549 };
550
551 let base = div()
552 .flex()
553 .items_center()
554 .gap(gap)
555 .p(padding)
556 .bg(theme.tokens.card)
557 .border_1()
558 .border_color(theme.tokens.border)
559 .rounded(theme.tokens.radius_lg)
560 .when(self.disabled, |this| this.opacity(0.5));
561
562 match self.size {
563 AudioPlayerSize::Compact => base
564 .map(|this| {
565 let mut div = this;
566 div.style().refine(&user_style);
567 div
568 })
569 .child(self.render_play_button(
570 window,
571 &theme,
572 play_icon,
573 is_playing,
574 button_size,
575 icon_size,
576 ))
577 .child(self.render_progress_bar(
578 window,
579 &theme,
580 progress_percentage,
581 track_height,
582 thumb_size,
583 ))
584 .child(
585 div()
586 .text_size(px(11.0))
587 .text_color(theme.tokens.muted_foreground)
588 .font_family(theme.tokens.font_mono.clone())
589 .child(format!(
590 "{} / {}",
591 format_time(current_time as f64),
592 format_time(duration as f64)
593 )),
594 ),
595
596 AudioPlayerSize::Full => base
597 .flex_col()
598 .gap(px(12.0))
599 .map(|this| {
600 let mut div = this;
601 div.style().refine(&user_style);
602 div
603 })
604 .when_some(self.title.clone(), |this, title| {
605 this.child(
606 div()
607 .w_full()
608 .text_size(px(14.0))
609 .font_weight(FontWeight::MEDIUM)
610 .text_color(theme.tokens.foreground)
611 .overflow_hidden()
612 .text_ellipsis()
613 .child(title),
614 )
615 })
616 .child(
617 div()
618 .flex()
619 .flex_col()
620 .gap(px(4.0))
621 .w_full()
622 .child(self.render_progress_bar(
623 window,
624 &theme,
625 progress_percentage,
626 track_height,
627 thumb_size,
628 ))
629 .child(
630 div()
631 .flex()
632 .justify_between()
633 .w_full()
634 .text_size(px(12.0))
635 .font_family(theme.tokens.font_mono.clone())
636 .text_color(theme.tokens.muted_foreground)
637 .child(format_time(current_time as f64))
638 .child(format_time(duration as f64)),
639 ),
640 )
641 .child(
642 div()
643 .flex()
644 .items_center()
645 .justify_between()
646 .w_full()
647 .child(div().flex().items_center().gap(px(8.0)).child(
648 self.render_play_button(
649 window,
650 &theme,
651 play_icon,
652 is_playing,
653 button_size,
654 icon_size,
655 ),
656 ))
657 .child(
658 div()
659 .flex()
660 .items_center()
661 .gap(px(8.0))
662 .child(self.render_speed_button(window, &theme, playback_speed))
663 .child(self.render_mute_button(
664 window,
665 &theme,
666 volume_icon,
667 px(28.0),
668 px(14.0),
669 ))
670 .child(self.render_volume_slider(
671 window,
672 &theme,
673 volume,
674 px(80.0),
675 px(4.0),
676 px(12.0),
677 )),
678 ),
679 ),
680 }
681 }
682}
683
684impl AudioPlayer {
685 fn render_play_button(
686 &self,
687 window: &mut Window,
688 theme: &crate::capabilities::foundation::theme::Theme,
689 icon_name: &str,
690 _is_playing: bool,
691 button_size: Pixels,
692 icon_size: Pixels,
693 ) -> impl IntoElement {
694 let state = self.state.clone();
695 let on_play = self.on_play.clone();
696 let on_pause = self.on_pause.clone();
697 let disabled = self.disabled;
698
699 div()
700 .id("audio-play-button")
701 .flex()
702 .items_center()
703 .justify_center()
704 .size(button_size)
705 .rounded_full()
706 .bg(theme.tokens.primary)
707 .when(!disabled, |this| {
708 this.cursor(CursorStyle::PointingHand)
709 .hover(|style| style.bg(theme.tokens.primary.opacity(0.9)))
710 })
711 .child(
712 svg()
713 .path(resolve_icon_path(icon_name))
714 .size(icon_size)
715 .text_color(theme.tokens.primary_foreground),
716 )
717 .when(!disabled, |this| {
718 this.on_click(window.listener_for(&state, move |state, _, window, cx| {
719 state.toggle_playing(cx);
720 if state.is_playing {
721 if let Some(ref handler) = on_play {
722 handler(window, cx);
723 }
724 } else if let Some(ref handler) = on_pause {
725 handler(window, cx);
726 }
727 }))
728 })
729 }
730
731 fn render_progress_bar(
732 &self,
733 window: &mut Window,
734 theme: &crate::capabilities::foundation::theme::Theme,
735 percentage: f32,
736 track_height: Pixels,
737 thumb_size: Pixels,
738 ) -> impl IntoElement {
739 let state = self.state.clone();
740 let on_seek = self.on_seek.clone();
741 let disabled = self.disabled;
742
743 div()
744 .flex_1()
745 .h(thumb_size)
746 .flex()
747 .items_center()
748 .relative()
749 .child(
750 canvas(
751 {
752 let state = state.clone();
753 move |bounds, _, cx| {
754 state.update(cx, |state, _| {
755 state.progress_bounds = bounds;
756 });
757 }
758 },
759 |_, _, _, _| {},
760 )
761 .absolute()
762 .size_full(),
763 )
764 .child(
765 div()
766 .w_full()
767 .h(track_height)
768 .rounded_full()
769 .bg(theme.tokens.muted)
770 .overflow_hidden()
771 .child(
772 div()
773 .h_full()
774 .w(relative(percentage))
775 .bg(theme.tokens.primary),
776 ),
777 )
778 .child(
779 div()
780 .absolute()
781 .left(relative(percentage))
782 .top(px(0.0))
783 .ml(-(thumb_size / 2.0))
784 .size(thumb_size)
785 .rounded_full()
786 .bg(theme.tokens.primary)
787 .border_2()
788 .border_color(theme.tokens.background)
789 .shadow_sm()
790 .when(!disabled, |this| this.cursor(CursorStyle::PointingHand)),
791 )
792 .when(!disabled, |this| {
793 let state_down = state.clone();
794 let on_seek_down = on_seek.clone();
795 let state_move = state.clone();
796 let on_seek_move = on_seek.clone();
797 let state_up = state.clone();
798
799 this.on_mouse_down(
800 MouseButton::Left,
801 window.listener_for(
802 &state_down,
803 move |state, e: &MouseDownEvent, window, cx| {
804 state.progress_dragging = true;
805 state.update_progress_from_position(e.position, cx);
806 if let Some(ref handler) = on_seek_down {
807 handler(state.current_time, window, cx);
808 }
809 },
810 ),
811 )
812 .on_mouse_move(window.listener_for(
813 &state_move,
814 move |state, e: &MouseMoveEvent, window, cx| {
815 if state.progress_dragging {
816 state.update_progress_from_position(e.position, cx);
817 if let Some(ref handler) = on_seek_move {
818 handler(state.current_time, window, cx);
819 }
820 }
821 },
822 ))
823 .on_mouse_up(
824 MouseButton::Left,
825 window.listener_for(&state_up, move |state, _: &MouseUpEvent, _, _| {
826 state.progress_dragging = false;
827 }),
828 )
829 .on_mouse_up_out(
830 MouseButton::Left,
831 window.listener_for(&state_up, move |state, _: &MouseUpEvent, _, _| {
832 state.progress_dragging = false;
833 }),
834 )
835 })
836 }
837
838 fn render_mute_button(
839 &self,
840 window: &mut Window,
841 theme: &crate::capabilities::foundation::theme::Theme,
842 icon_name: &str,
843 button_size: Pixels,
844 icon_size: Pixels,
845 ) -> impl IntoElement {
846 let state = self.state.clone();
847 let disabled = self.disabled;
848
849 div()
850 .id("audio-mute-button")
851 .flex()
852 .items_center()
853 .justify_center()
854 .size(button_size)
855 .rounded(theme.tokens.radius_md)
856 .when(!disabled, |this| {
857 this.cursor(CursorStyle::PointingHand)
858 .hover(|style| style.bg(theme.tokens.accent))
859 })
860 .child(
861 svg()
862 .path(resolve_icon_path(icon_name))
863 .size(icon_size)
864 .text_color(theme.tokens.muted_foreground),
865 )
866 .when(!disabled, |this| {
867 this.on_click(window.listener_for(&state, move |state, _, _, cx| {
868 state.toggle_muted(cx);
869 }))
870 })
871 }
872
873 fn render_volume_slider(
874 &self,
875 window: &mut Window,
876 theme: &crate::capabilities::foundation::theme::Theme,
877 volume: f32,
878 width: Pixels,
879 track_height: Pixels,
880 thumb_size: Pixels,
881 ) -> impl IntoElement {
882 let state = self.state.clone();
883 let on_volume_change = self.on_volume_change.clone();
884 let disabled = self.disabled;
885
886 div()
887 .w(width)
888 .h(thumb_size)
889 .flex()
890 .items_center()
891 .relative()
892 .child(
893 canvas(
894 {
895 let state = state.clone();
896 move |bounds, _, cx| {
897 state.update(cx, |state, _| {
898 state.volume_bounds = bounds;
899 });
900 }
901 },
902 |_, _, _, _| {},
903 )
904 .absolute()
905 .size_full(),
906 )
907 .child(
908 div()
909 .w_full()
910 .h(track_height)
911 .rounded_full()
912 .bg(theme.tokens.muted)
913 .overflow_hidden()
914 .child(
915 div()
916 .h_full()
917 .w(relative(volume))
918 .bg(theme.tokens.muted_foreground),
919 ),
920 )
921 .child(
922 div()
923 .absolute()
924 .left(relative(volume))
925 .top(px(0.0))
926 .ml(-(thumb_size / 2.0))
927 .size(thumb_size)
928 .rounded_full()
929 .bg(theme.tokens.foreground)
930 .border_2()
931 .border_color(theme.tokens.background)
932 .shadow_sm()
933 .when(!disabled, |this| this.cursor(CursorStyle::PointingHand)),
934 )
935 .when(!disabled, |this| {
936 let state_down = state.clone();
937 let on_vol_down = on_volume_change.clone();
938 let state_move = state.clone();
939 let on_vol_move = on_volume_change.clone();
940 let state_up = state.clone();
941
942 this.on_mouse_down(
943 MouseButton::Left,
944 window.listener_for(
945 &state_down,
946 move |state, e: &MouseDownEvent, window, cx| {
947 state.volume_dragging = true;
948 state.update_volume_from_position(e.position, cx);
949 if let Some(ref handler) = on_vol_down {
950 handler(state.volume, window, cx);
951 }
952 },
953 ),
954 )
955 .on_mouse_move(window.listener_for(
956 &state_move,
957 move |state, e: &MouseMoveEvent, window, cx| {
958 if state.volume_dragging {
959 state.update_volume_from_position(e.position, cx);
960 if let Some(ref handler) = on_vol_move {
961 handler(state.volume, window, cx);
962 }
963 }
964 },
965 ))
966 .on_mouse_up(
967 MouseButton::Left,
968 window.listener_for(&state_up, move |state, _: &MouseUpEvent, _, _| {
969 state.volume_dragging = false;
970 }),
971 )
972 .on_mouse_up_out(
973 MouseButton::Left,
974 window.listener_for(&state_up, move |state, _: &MouseUpEvent, _, _| {
975 state.volume_dragging = false;
976 }),
977 )
978 })
979 }
980
981 fn render_speed_button(
982 &self,
983 window: &mut Window,
984 theme: &crate::capabilities::foundation::theme::Theme,
985 speed: PlaybackSpeed,
986 ) -> impl IntoElement {
987 let state = self.state.clone();
988 let on_speed_change = self.on_speed_change.clone();
989 let disabled = self.disabled;
990
991 div()
992 .id("audio-speed-button")
993 .flex()
994 .items_center()
995 .justify_center()
996 .px(px(8.0))
997 .h(px(28.0))
998 .rounded(theme.tokens.radius_md)
999 .text_size(px(12.0))
1000 .font_weight(FontWeight::MEDIUM)
1001 .text_color(theme.tokens.muted_foreground)
1002 .when(!disabled, |this| {
1003 this.cursor(CursorStyle::PointingHand)
1004 .hover(|style| style.bg(theme.tokens.accent))
1005 })
1006 .child(speed.label())
1007 .when(!disabled, |this| {
1008 this.on_click(window.listener_for(&state, move |state, _, window, cx| {
1009 state.cycle_playback_speed(cx);
1010 if let Some(ref handler) = on_speed_change {
1011 handler(state.playback_speed, window, cx);
1012 }
1013 }))
1014 })
1015 }
1016}
1017
1018#[cfg(all(test, feature = "audio"))]
1019mod tests {
1020 use super::open_decoder;
1021 use rodio::Source;
1022
1023 const SAMPLE: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/assets/audio/sample.mp3");
1024
1025 #[test]
1029 fn decoding_a_file_reports_its_duration() {
1030 let source = open_decoder(SAMPLE).expect("decode sample.mp3");
1031 let duration = source.total_duration().expect("duration is known");
1032
1033 assert!(
1036 duration.as_secs_f64() > 300.0,
1037 "expected a multi-minute duration, got {duration:?}"
1038 );
1039 }
1040
1041 #[test]
1044 fn a_decoded_file_can_be_seeked() {
1045 let mut source = open_decoder(SAMPLE).expect("decode sample.mp3");
1046 let _: Vec<_> = source.by_ref().take(44_100).collect();
1047
1048 assert!(
1049 source.try_seek(std::time::Duration::from_secs(30)).is_ok(),
1050 "seeking a decoded file failed"
1051 );
1052 }
1053
1054 #[test]
1055 fn a_missing_file_is_an_error_rather_than_a_panic() {
1056 assert!(open_decoder("/nonexistent/fc-ui.mp3").is_err());
1057 }
1058}