use std::any::{Any, TypeId};
use std::collections::{HashMap, HashSet};
use sonos_sdk::property::{GroupFetchable, GroupPropertyHandle, PropertyHandle, WatchHandle};
use sonos_sdk::SdkError;
use sonos_sdk::SonosProperty;
use crate::tui::app::App;
pub struct RenderContext<'a> {
pub app: &'a App,
pub hooks: &'a mut Hooks,
}
#[derive(Hash, Eq, PartialEq, Clone, Debug)]
struct HookKey {
type_id: TypeId,
name: String,
}
impl HookKey {
fn new<V: 'static>(name: &str) -> Self {
Self {
type_id: TypeId::of::<V>(),
name: name.to_string(),
}
}
}
#[derive(Clone, Debug)]
pub struct ProgressState {
pub last_position_ms: u64,
pub last_duration_ms: u64,
pub wall_clock_at_last_update: std::time::Instant,
pub is_playing: bool,
}
impl Default for ProgressState {
fn default() -> Self {
Self {
last_position_ms: 0,
last_duration_ms: 0,
wall_clock_at_last_update: std::time::Instant::now(),
is_playing: false,
}
}
}
impl ProgressState {
pub fn update(&mut self, position_ms: u64, duration_ms: u64, is_playing: bool) {
if self.is_playing && !is_playing {
self.last_position_ms = self.interpolated_position_ms();
}
self.last_position_ms = position_ms;
self.last_duration_ms = duration_ms;
self.is_playing = is_playing;
self.wall_clock_at_last_update = std::time::Instant::now();
}
pub fn interpolated_position_ms(&self) -> u64 {
if !self.is_playing {
return self.last_position_ms;
}
let elapsed = self.wall_clock_at_last_update.elapsed().as_millis() as u64;
let capped_elapsed = elapsed.min(10_000);
(self.last_position_ms + capped_elapsed).min(self.last_duration_ms)
}
}
pub struct Hooks {
states: HashMap<HookKey, Box<dyn Any>>,
watches: HashMap<String, Box<dyn Any>>,
animations: HashSet<String>,
accessed_states: HashSet<HookKey>,
accessed_watches: HashSet<String>,
accessed_animations: HashSet<String>,
}
impl Default for Hooks {
fn default() -> Self {
Self::new()
}
}
impl Hooks {
pub fn new() -> Self {
Self {
states: HashMap::new(),
watches: HashMap::new(),
animations: HashSet::new(),
accessed_states: HashSet::new(),
accessed_watches: HashSet::new(),
accessed_animations: HashSet::new(),
}
}
pub fn begin_frame(&mut self) {
self.accessed_states.clear();
self.accessed_watches.clear();
self.accessed_animations.clear();
}
pub fn end_frame(&mut self) {
self.states
.retain(|key, _| self.accessed_states.contains(key));
self.watches
.retain(|key, _| self.accessed_watches.contains(key));
self.animations
.retain(|key| self.accessed_animations.contains(key));
}
pub fn use_state<V: 'static>(&mut self, key: &str, default: impl FnOnce() -> V) -> &mut V {
let hook_key = HookKey::new::<V>(key);
self.accessed_states.insert(hook_key.clone());
self.states
.entry(hook_key)
.or_insert_with(|| Box::new(default()))
.downcast_mut::<V>()
.expect("use_state: type mismatch for key (same key used with different types)")
}
fn use_watch_cached<P>(
&mut self,
key: String,
acquire: impl FnOnce() -> Result<WatchHandle<P>, SdkError>,
fallback: impl FnOnce() -> Option<P>,
) -> Option<P>
where
P: 'static,
{
self.accessed_watches.insert(key.clone());
let handle = match self.watches.entry(key) {
std::collections::hash_map::Entry::Occupied(e) => e.into_mut(),
std::collections::hash_map::Entry::Vacant(e) => match acquire() {
Ok(wh) => e.insert(Box::new(wh)),
Err(err) => {
tracing::warn!("use_watch: watch() failed ({err}), falling back to get()");
return fallback();
}
},
};
handle
.downcast_ref::<WatchHandle<P>>()
.expect("use_watch: same key used with two property types")
.value()
}
pub fn use_watch<P>(&mut self, prop: &PropertyHandle<P>) -> Option<P>
where
P: SonosProperty + Clone + 'static,
{
let key = format!("{}:{}", prop.speaker_id(), P::KEY);
self.use_watch_cached(key, || prop.watch(), || prop.get())
}
#[allow(dead_code)]
pub fn use_watch_group<P>(&mut self, prop: &GroupPropertyHandle<P>) -> Option<P>
where
P: SonosProperty + Clone + 'static,
{
let key = format!("group:{}:{}", prop.group_id(), P::KEY);
self.use_watch_cached(key, || prop.watch(), || prop.get())
}
pub fn use_watch_group_or_fetch<P>(&mut self, prop: &GroupPropertyHandle<P>) -> Option<P>
where
P: SonosProperty + GroupFetchable + Clone + 'static,
{
let key = format!("group:{}:{}", prop.group_id(), P::KEY);
self.use_watch_cached(key, || prop.watch_or_fetch(), || prop.get())
}
pub fn use_animation(&mut self, key: &str, active: bool) {
let key = key.to_string();
self.accessed_animations.insert(key.clone());
if active {
self.animations.insert(key);
} else {
self.animations.remove(&key);
}
}
pub fn has_active_animations(&self) -> bool {
!self.animations.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[cfg(feature = "test-helpers")]
fn use_watch_reports_values_written_after_the_handle_was_acquired() {
use sonos_sdk::{SonosSystem, Volume};
let system = SonosSystem::with_speakers(&["Kitchen"]);
let speaker = system.speakers().into_iter().next().expect("one speaker");
let speaker_id = speaker.id.clone();
let mut hooks = Hooks::new();
hooks.begin_frame();
assert_eq!(hooks.use_watch(&speaker.volume), None);
hooks.end_frame();
system
.state_manager()
.set_property(&speaker_id, Volume::new(42));
hooks.begin_frame();
assert_eq!(
hooks.use_watch(&speaker.volume).map(|v| v.value()),
Some(42),
"a handle held across frames must read the store live"
);
hooks.end_frame();
system
.state_manager()
.set_property(&speaker_id, Volume::new(43));
hooks.begin_frame();
assert_eq!(
hooks.use_watch(&speaker.volume).map(|v| v.value()),
Some(43)
);
hooks.end_frame();
}
#[test]
#[cfg(feature = "test-helpers")]
fn use_watch_reuses_one_handle_across_frames_then_evicts() {
use sonos_sdk::SonosSystem;
let system = SonosSystem::with_speakers(&["Kitchen"]);
let speaker = system.speakers().into_iter().next().expect("one speaker");
let mut hooks = Hooks::new();
let mut first_addr: Option<usize> = None;
for frame in 0..5 {
hooks.begin_frame();
let _ = hooks.use_watch(&speaker.volume);
hooks.end_frame();
assert_eq!(
hooks.watches.len(),
1,
"one property watched continuously must hold exactly one handle"
);
let addr = hooks
.watches
.values()
.next()
.map(|b| std::ptr::addr_of!(**b) as *const () as usize)
.expect("handle present");
match first_addr {
None => first_addr = Some(addr),
Some(expected) => assert_eq!(
addr, expected,
"frame {frame} replaced the handle — it must be acquired once and reused"
),
}
}
hooks.begin_frame();
hooks.end_frame();
assert!(
hooks.watches.is_empty(),
"unaccessed handle must be evicted"
);
}
#[test]
fn use_state_creates_default_on_first_call() {
let mut hooks = Hooks::new();
hooks.begin_frame();
let val = hooks.use_state::<u32>("counter", || 42);
assert_eq!(*val, 42);
}
#[test]
fn use_state_persists_across_frames() {
let mut hooks = Hooks::new();
hooks.begin_frame();
*hooks.use_state::<u32>("counter", || 0) = 10;
hooks.end_frame();
hooks.begin_frame();
let val = hooks.use_state::<u32>("counter", || 0);
assert_eq!(*val, 10);
hooks.end_frame();
}
#[test]
fn use_state_evicts_on_unaccessed_frame() {
let mut hooks = Hooks::new();
hooks.begin_frame();
*hooks.use_state::<u32>("counter", || 42) = 100;
hooks.end_frame();
hooks.begin_frame();
hooks.end_frame();
hooks.begin_frame();
let val = hooks.use_state::<u32>("counter", || 42);
assert_eq!(*val, 42); }
#[test]
fn use_state_different_types_same_name_are_separate() {
let mut hooks = Hooks::new();
hooks.begin_frame();
*hooks.use_state::<u32>("val", || 1) = 10;
let s = hooks.use_state::<String>("val", || "hello".to_string());
assert_eq!(s, "hello"); }
#[test]
fn use_animation_registers_and_deregisters() {
let mut hooks = Hooks::new();
hooks.begin_frame();
assert!(!hooks.has_active_animations());
hooks.use_animation("progress", true);
assert!(hooks.has_active_animations());
hooks.use_animation("progress", false);
assert!(!hooks.has_active_animations());
}
#[test]
fn use_animation_evicts_on_unaccessed_frame() {
let mut hooks = Hooks::new();
hooks.begin_frame();
hooks.use_animation("progress", true);
hooks.end_frame();
assert!(hooks.has_active_animations());
hooks.begin_frame();
hooks.end_frame();
assert!(!hooks.has_active_animations());
}
#[test]
fn progress_state_interpolation() {
let mut ps = ProgressState {
last_position_ms: 1000,
last_duration_ms: 5000,
is_playing: false,
..Default::default()
};
assert_eq!(ps.interpolated_position_ms(), 1000);
ps.is_playing = true;
ps.wall_clock_at_last_update = std::time::Instant::now();
assert!(ps.interpolated_position_ms() >= 1000);
}
#[test]
fn progress_state_caps_at_duration() {
let ps = ProgressState {
last_position_ms: 4900,
last_duration_ms: 5000,
is_playing: true,
wall_clock_at_last_update: std::time::Instant::now()
- std::time::Duration::from_secs(20),
};
assert_eq!(ps.interpolated_position_ms(), 5000);
}
#[test]
fn mark_and_sweep_preserves_accessed_drops_rest() {
let mut hooks = Hooks::new();
hooks.begin_frame();
*hooks.use_state::<u32>("keep", || 1) = 10;
let _ = hooks.use_state::<u32>("drop_me", || 2);
hooks.use_animation("keep_anim", true);
hooks.use_animation("drop_anim", true);
hooks.end_frame();
hooks.begin_frame();
let val = hooks.use_state::<u32>("keep", || 99);
assert_eq!(*val, 10); hooks.use_animation("keep_anim", true);
hooks.end_frame();
hooks.begin_frame();
let val = hooks.use_state::<u32>("drop_me", || 99);
assert_eq!(*val, 99); hooks.end_frame();
}
}