use std::any::{Any, TypeId};
use std::collections::{HashMap, HashSet};
use sonos_sdk::property::{GroupPropertyHandle, PropertyHandle};
use sonos_state::property::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)")
}
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.accessed_watches.insert(key.clone());
match prop.watch() {
Ok(wh) => {
let val = wh.value().cloned();
self.watches.insert(key, Box::new(wh));
val
}
Err(e) => {
tracing::warn!(
"use_watch failed for {}: {e}, falling back to get()",
P::KEY
);
prop.get()
}
}
}
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.accessed_watches.insert(key.clone());
match prop.watch() {
Ok(wh) => {
let val = wh.value().cloned();
self.watches.insert(key, Box::new(wh));
val
}
Err(e) => {
tracing::warn!(
"use_watch_group failed for {}: {e}, falling back to get()",
P::KEY
);
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]
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();
}
}