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