sonos_cli/tui/hooks.rs
1//! TUI hooks system — co-located widget state, SDK subscriptions, and animation.
2//!
3//! Modeled after React hooks but adapted for Rust's ownership model and
4//! ratatui's immediate-mode rendering. Three primitives:
5//!
6//! - `use_state<V>(key, default)` — Persistent local state across renders
7//! - `use_watch(property_handle)` — Subscribe to SDK property, return current value
8//! - `use_animation(key, active)` — Request periodic re-renders when active
9//!
10//! `use_watch` acquires one SDK `WatchHandle` per property on first access and
11//! keeps it across frames. `WatchHandle` is a live view — `value()` re-reads the
12//! state store — so reading through the cached handle is all a later frame needs.
13//!
14//! ## Calling Convention
15//!
16//! `use_state` returns `&mut V` which borrows `&mut self` on `Hooks`.
17//! To avoid borrow conflicts, call hooks in this order:
18//!
19//! 1. `use_watch` — returns owned `Option<V>`, borrow released immediately
20//! 2. `use_animation` — `&mut self` borrow released immediately
21//! 3. `use_state` — must be called last or in a scoped block
22//!
23//! ## Frame Lifecycle
24//!
25//! ```text
26//! hooks.begin_frame() // reset access tracking
27//! terminal.draw(...) // widgets call hooks
28//! hooks.end_frame() // evict unaccessed state + handles
29//! ```
30
31use std::any::{Any, TypeId};
32use std::collections::{HashMap, HashSet};
33
34use sonos_sdk::property::{GroupFetchable, GroupPropertyHandle, PropertyHandle, WatchHandle};
35use sonos_sdk::SdkError;
36use sonos_sdk::SonosProperty;
37
38use crate::tui::app::App;
39
40// ============================================================================
41// RenderContext
42// ============================================================================
43
44/// Render context passed to all render functions.
45///
46/// Wraps `&App` (read) and `&mut Hooks` (write), satisfying the borrow checker
47/// by separating immutable app data from mutable hook state.
48pub struct RenderContext<'a> {
49 pub app: &'a App,
50 pub hooks: &'a mut Hooks,
51}
52
53// ============================================================================
54// HookKey — state identity
55// ============================================================================
56
57/// Composite key for `use_state`: combines value type with a string name.
58///
59/// Two hooks with the same string key but different value types get separate
60/// storage slots (keyed by `TypeId`).
61#[derive(Hash, Eq, PartialEq, Clone, Debug)]
62struct HookKey {
63 type_id: TypeId,
64 name: String,
65}
66
67impl HookKey {
68 fn new<V: 'static>(name: &str) -> Self {
69 Self {
70 type_id: TypeId::of::<V>(),
71 name: name.to_string(),
72 }
73 }
74}
75
76// ============================================================================
77// ProgressState — moved from app.rs to co-locate with hooks
78// ============================================================================
79
80/// Client-side progress interpolation state for a single group.
81///
82/// Stores a snapshot of position + wall-clock timestamp. While playing,
83/// `interpolated_position_ms()` advances the position based on elapsed time,
84/// capped at 10s to limit drift from system sleep/stalls.
85#[derive(Clone, Debug)]
86pub struct ProgressState {
87 pub last_position_ms: u64,
88 pub last_duration_ms: u64,
89 pub wall_clock_at_last_update: std::time::Instant,
90 pub is_playing: bool,
91}
92
93impl Default for ProgressState {
94 fn default() -> Self {
95 Self {
96 last_position_ms: 0,
97 last_duration_ms: 0,
98 wall_clock_at_last_update: std::time::Instant::now(),
99 is_playing: false,
100 }
101 }
102}
103
104impl ProgressState {
105 /// Update from SDK position and playback data.
106 pub fn update(&mut self, position_ms: u64, duration_ms: u64, is_playing: bool) {
107 // Freeze at interpolated position on pause transition
108 if self.is_playing && !is_playing {
109 self.last_position_ms = self.interpolated_position_ms();
110 }
111
112 self.last_position_ms = position_ms;
113 self.last_duration_ms = duration_ms;
114 self.is_playing = is_playing;
115 self.wall_clock_at_last_update = std::time::Instant::now();
116 }
117
118 /// Compute interpolated position in milliseconds.
119 ///
120 /// Caps interpolation at 10s ahead to limit drift from system sleep/stalls.
121 pub fn interpolated_position_ms(&self) -> u64 {
122 if !self.is_playing {
123 return self.last_position_ms;
124 }
125 let elapsed = self.wall_clock_at_last_update.elapsed().as_millis() as u64;
126 let capped_elapsed = elapsed.min(10_000);
127 (self.last_position_ms + capped_elapsed).min(self.last_duration_ms)
128 }
129}
130
131// ============================================================================
132// Hooks
133// ============================================================================
134
135/// General-purpose hooks system for TUI widget state management.
136///
137/// Stores persistent state, SDK watch handles, and animation registrations.
138/// Uses mark-and-sweep to automatically clean up state when widgets stop
139/// rendering (e.g., screen transitions).
140pub struct Hooks {
141 // use_state storage — keyed by (TypeId, name)
142 states: HashMap<HookKey, Box<dyn Any>>,
143
144 // use_watch storage — type-erased WatchHandle<P>, keyed by "speaker_id:property_key"
145 watches: HashMap<String, Box<dyn Any>>,
146
147 // use_animation — keys of active animations
148 animations: HashSet<String>,
149
150 // Mark-and-sweep: keys accessed during current frame
151 accessed_states: HashSet<HookKey>,
152 accessed_watches: HashSet<String>,
153 accessed_animations: HashSet<String>,
154}
155
156impl Default for Hooks {
157 fn default() -> Self {
158 Self::new()
159 }
160}
161
162impl Hooks {
163 pub fn new() -> Self {
164 Self {
165 states: HashMap::new(),
166 watches: HashMap::new(),
167 animations: HashSet::new(),
168 accessed_states: HashSet::new(),
169 accessed_watches: HashSet::new(),
170 accessed_animations: HashSet::new(),
171 }
172 }
173
174 // -----------------------------------------------------------------------
175 // Frame lifecycle
176 // -----------------------------------------------------------------------
177
178 /// Reset access tracking before a render frame.
179 pub fn begin_frame(&mut self) {
180 self.accessed_states.clear();
181 self.accessed_watches.clear();
182 self.accessed_animations.clear();
183 }
184
185 /// Evict unaccessed state and drop unaccessed watch handles.
186 ///
187 /// Handles for widgets that rendered this frame are retained, so a
188 /// continuously-visible widget holds one subscription for its whole life.
189 pub fn end_frame(&mut self) {
190 // Evict unaccessed states
191 self.states
192 .retain(|key, _| self.accessed_states.contains(key));
193
194 // Drop unaccessed watch handles (starts grace periods)
195 self.watches
196 .retain(|key, _| self.accessed_watches.contains(key));
197
198 // Remove unaccessed animations
199 self.animations
200 .retain(|key| self.accessed_animations.contains(key));
201 }
202
203 // -----------------------------------------------------------------------
204 // use_state
205 // -----------------------------------------------------------------------
206
207 /// Get or create persistent local state.
208 ///
209 /// On first call for a given key, creates the state using `default()`.
210 /// On subsequent calls, returns the existing state.
211 ///
212 /// **Must be called last** — the returned `&mut V` borrows `&mut self`,
213 /// preventing other hook calls until the reference is dropped.
214 pub fn use_state<V: 'static>(&mut self, key: &str, default: impl FnOnce() -> V) -> &mut V {
215 let hook_key = HookKey::new::<V>(key);
216 self.accessed_states.insert(hook_key.clone());
217
218 self.states
219 .entry(hook_key)
220 .or_insert_with(|| Box::new(default()))
221 .downcast_mut::<V>()
222 .expect("use_state: type mismatch for key (same key used with different types)")
223 }
224
225 // -----------------------------------------------------------------------
226 // use_watch
227 // -----------------------------------------------------------------------
228
229 /// Get-or-create a cached `WatchHandle` and read its current value.
230 ///
231 /// `WatchHandle` is a live view: `value()` reads the state store on every
232 /// call, so one handle acquired on the first frame reports every subsequent
233 /// change. The handle is therefore created once, parked in `self.watches`,
234 /// and only *read* on later frames — no per-frame `watch()` call, no
235 /// drop/grace-period/re-acquire churn.
236 ///
237 /// `acquire` is only invoked on a cache miss. `fallback` supplies a value
238 /// when acquisition fails (a plain cache read via `get()`), and is not
239 /// cached, so a transient failure is retried on the next frame.
240 fn use_watch_cached<P>(
241 &mut self,
242 key: String,
243 acquire: impl FnOnce() -> Result<WatchHandle<P>, SdkError>,
244 fallback: impl FnOnce() -> Option<P>,
245 ) -> Option<P>
246 where
247 P: 'static,
248 {
249 self.accessed_watches.insert(key.clone());
250
251 let handle = match self.watches.entry(key) {
252 std::collections::hash_map::Entry::Occupied(e) => e.into_mut(),
253 std::collections::hash_map::Entry::Vacant(e) => match acquire() {
254 Ok(wh) => e.insert(Box::new(wh)),
255 Err(err) => {
256 tracing::warn!("use_watch: watch() failed ({err}), falling back to get()");
257 return fallback();
258 }
259 },
260 };
261
262 handle
263 .downcast_ref::<WatchHandle<P>>()
264 .expect("use_watch: same key used with two property types")
265 .value()
266 }
267
268 /// Subscribe to an SDK speaker property, returning its current value.
269 ///
270 /// The subscription is acquired on first access and held until the widget
271 /// stops rendering (mark-and-sweep in [`Self::end_frame`]).
272 pub fn use_watch<P>(&mut self, prop: &PropertyHandle<P>) -> Option<P>
273 where
274 P: SonosProperty + Clone + 'static,
275 {
276 let key = format!("{}:{}", prop.speaker_id(), P::KEY);
277 self.use_watch_cached(key, || prop.watch(), || prop.get())
278 }
279
280 /// Subscribe to an SDK group property, returning its current value.
281 ///
282 /// Same as `use_watch` but for group-scoped properties (e.g., group volume).
283 #[allow(dead_code)]
284 pub fn use_watch_group<P>(&mut self, prop: &GroupPropertyHandle<P>) -> Option<P>
285 where
286 P: SonosProperty + Clone + 'static,
287 {
288 let key = format!("group:{}:{}", prop.group_id(), P::KEY);
289 self.use_watch_cached(key, || prop.watch(), || prop.get())
290 }
291
292 /// Subscribe to a fetchable group property, fetching on first access if empty.
293 ///
294 /// Like `use_watch_group` but performs a one-time fetch when the cache has
295 /// no value yet, so the UI doesn't show a blank until the first UPnP event.
296 /// The fetch happens only on the frame that acquires the handle, since
297 /// later frames reuse it.
298 pub fn use_watch_group_or_fetch<P>(&mut self, prop: &GroupPropertyHandle<P>) -> Option<P>
299 where
300 P: SonosProperty + GroupFetchable + Clone + 'static,
301 {
302 let key = format!("group:{}:{}", prop.group_id(), P::KEY);
303 self.use_watch_cached(key, || prop.watch_or_fetch(), || prop.get())
304 }
305
306 // -----------------------------------------------------------------------
307 // use_animation
308 // -----------------------------------------------------------------------
309
310 /// Register an animation tick request.
311 ///
312 /// When `active` is true, the event loop's global animation timer will
313 /// mark the app as dirty every ~250ms, triggering re-renders for smooth
314 /// progress bar animation.
315 pub fn use_animation(&mut self, key: &str, active: bool) {
316 let key = key.to_string();
317 self.accessed_animations.insert(key.clone());
318 if active {
319 self.animations.insert(key);
320 } else {
321 self.animations.remove(&key);
322 }
323 }
324
325 /// Check if any widget has registered an active animation.
326 ///
327 /// Called by the event loop between frames to decide whether to tick
328 /// the animation timer.
329 pub fn has_active_animations(&self) -> bool {
330 !self.animations.is_empty()
331 }
332}
333
334// ============================================================================
335// Tests
336// ============================================================================
337
338#[cfg(test)]
339mod tests {
340 use super::*;
341
342 /// A `use_watch` handle acquired on one frame must report values written
343 /// *after* that frame, without being re-acquired.
344 ///
345 /// This is the property that made the per-frame re-`watch()` pattern
346 /// obsolete (sonos-sdk PR #99). If `WatchHandle` ever reverts to a frozen
347 /// snapshot, `use_watch` would silently pin the first observed value and the
348 /// TUI would stop updating — a failure with no compiler signal at all, which
349 /// is why it is asserted here rather than trusted from the SDK's own suite.
350 #[test]
351 #[cfg(feature = "test-helpers")]
352 fn use_watch_reports_values_written_after_the_handle_was_acquired() {
353 use sonos_sdk::{SonosSystem, Volume};
354
355 let system = SonosSystem::with_speakers(&["Kitchen"]);
356 let speaker = system.speakers().into_iter().next().expect("one speaker");
357 let speaker_id = speaker.id.clone();
358
359 let mut hooks = Hooks::new();
360
361 // Frame 1: acquires the handle. Nothing observed yet.
362 hooks.begin_frame();
363 assert_eq!(hooks.use_watch(&speaker.volume), None);
364 hooks.end_frame();
365
366 system
367 .state_manager()
368 .set_property(&speaker_id, Volume::new(42));
369
370 // Frame 2: same cached handle, new value.
371 hooks.begin_frame();
372 assert_eq!(
373 hooks.use_watch(&speaker.volume).map(|v| v.value()),
374 Some(42),
375 "a handle held across frames must read the store live"
376 );
377 hooks.end_frame();
378
379 system
380 .state_manager()
381 .set_property(&speaker_id, Volume::new(43));
382
383 // Frame 3: keeps tracking, rather than refreshing once.
384 hooks.begin_frame();
385 assert_eq!(
386 hooks.use_watch(&speaker.volume).map(|v| v.value()),
387 Some(43)
388 );
389 hooks.end_frame();
390 }
391
392 /// The handle is acquired once and reused, not rebuilt per frame.
393 ///
394 /// Asserts the churn reduction directly: `watches` must hold exactly one
395 /// entry for the property across many frames, and mark-and-sweep must still
396 /// evict it once the widget stops rendering.
397 #[test]
398 #[cfg(feature = "test-helpers")]
399 fn use_watch_reuses_one_handle_across_frames_then_evicts() {
400 use sonos_sdk::SonosSystem;
401
402 let system = SonosSystem::with_speakers(&["Kitchen"]);
403 let speaker = system.speakers().into_iter().next().expect("one speaker");
404
405 let mut hooks = Hooks::new();
406
407 // Identity of the stored handle, so a re-acquire is detectable — a
408 // count-only assertion passes even if the handle is dropped and rebuilt
409 // every frame, which is exactly the churn this migration removed.
410 let mut first_addr: Option<usize> = None;
411
412 for frame in 0..5 {
413 hooks.begin_frame();
414 let _ = hooks.use_watch(&speaker.volume);
415 hooks.end_frame();
416
417 assert_eq!(
418 hooks.watches.len(),
419 1,
420 "one property watched continuously must hold exactly one handle"
421 );
422
423 let addr = hooks
424 .watches
425 .values()
426 .next()
427 .map(|b| std::ptr::addr_of!(**b) as *const () as usize)
428 .expect("handle present");
429
430 match first_addr {
431 None => first_addr = Some(addr),
432 Some(expected) => assert_eq!(
433 addr, expected,
434 "frame {frame} replaced the handle — it must be acquired once and reused"
435 ),
436 }
437 }
438
439 // Widget stops rendering → handle released.
440 hooks.begin_frame();
441 hooks.end_frame();
442 assert!(
443 hooks.watches.is_empty(),
444 "unaccessed handle must be evicted"
445 );
446 }
447
448 #[test]
449 fn use_state_creates_default_on_first_call() {
450 let mut hooks = Hooks::new();
451 hooks.begin_frame();
452
453 let val = hooks.use_state::<u32>("counter", || 42);
454 assert_eq!(*val, 42);
455 }
456
457 #[test]
458 fn use_state_persists_across_frames() {
459 let mut hooks = Hooks::new();
460
461 // Frame 1: create state
462 hooks.begin_frame();
463 *hooks.use_state::<u32>("counter", || 0) = 10;
464 hooks.end_frame();
465
466 // Frame 2: state persists
467 hooks.begin_frame();
468 let val = hooks.use_state::<u32>("counter", || 0);
469 assert_eq!(*val, 10);
470 hooks.end_frame();
471 }
472
473 #[test]
474 fn use_state_evicts_on_unaccessed_frame() {
475 let mut hooks = Hooks::new();
476
477 // Frame 1: create state
478 hooks.begin_frame();
479 *hooks.use_state::<u32>("counter", || 42) = 100;
480 hooks.end_frame();
481
482 // Frame 2: state NOT accessed → evicted
483 hooks.begin_frame();
484 hooks.end_frame();
485
486 // Frame 3: recreated from default
487 hooks.begin_frame();
488 let val = hooks.use_state::<u32>("counter", || 42);
489 assert_eq!(*val, 42); // default, not 100
490 }
491
492 #[test]
493 fn use_state_different_types_same_name_are_separate() {
494 let mut hooks = Hooks::new();
495 hooks.begin_frame();
496
497 *hooks.use_state::<u32>("val", || 1) = 10;
498 // Borrow on hooks released after this line since u32 is Copy
499
500 let s = hooks.use_state::<String>("val", || "hello".to_string());
501 assert_eq!(s, "hello"); // separate slot, not confused with u32
502 }
503
504 #[test]
505 fn use_animation_registers_and_deregisters() {
506 let mut hooks = Hooks::new();
507 hooks.begin_frame();
508
509 assert!(!hooks.has_active_animations());
510
511 hooks.use_animation("progress", true);
512 assert!(hooks.has_active_animations());
513
514 hooks.use_animation("progress", false);
515 assert!(!hooks.has_active_animations());
516 }
517
518 #[test]
519 fn use_animation_evicts_on_unaccessed_frame() {
520 let mut hooks = Hooks::new();
521
522 // Frame 1: register animation
523 hooks.begin_frame();
524 hooks.use_animation("progress", true);
525 hooks.end_frame();
526 assert!(hooks.has_active_animations());
527
528 // Frame 2: animation NOT accessed → evicted
529 hooks.begin_frame();
530 hooks.end_frame();
531 assert!(!hooks.has_active_animations());
532 }
533
534 #[test]
535 fn progress_state_interpolation() {
536 let mut ps = ProgressState {
537 last_position_ms: 1000,
538 last_duration_ms: 5000,
539 is_playing: false,
540 ..Default::default()
541 };
542
543 // Not playing → returns last position
544 assert_eq!(ps.interpolated_position_ms(), 1000);
545
546 // Playing → interpolates forward
547 ps.is_playing = true;
548 ps.wall_clock_at_last_update = std::time::Instant::now();
549 // Position should be >= 1000 (at least the base)
550 assert!(ps.interpolated_position_ms() >= 1000);
551 }
552
553 #[test]
554 fn progress_state_caps_at_duration() {
555 let ps = ProgressState {
556 last_position_ms: 4900,
557 last_duration_ms: 5000,
558 is_playing: true,
559 // Simulate old timestamp (10+ seconds ago)
560 wall_clock_at_last_update: std::time::Instant::now()
561 - std::time::Duration::from_secs(20),
562 };
563
564 // Should cap at duration, not overflow
565 assert_eq!(ps.interpolated_position_ms(), 5000);
566 }
567
568 #[test]
569 fn mark_and_sweep_preserves_accessed_drops_rest() {
570 let mut hooks = Hooks::new();
571
572 // Frame 1: create multiple states
573 hooks.begin_frame();
574 *hooks.use_state::<u32>("keep", || 1) = 10;
575 // Release borrow
576 let _ = hooks.use_state::<u32>("drop_me", || 2);
577 hooks.use_animation("keep_anim", true);
578 hooks.use_animation("drop_anim", true);
579 hooks.end_frame();
580
581 // Frame 2: only access "keep" variants
582 hooks.begin_frame();
583 let val = hooks.use_state::<u32>("keep", || 99);
584 assert_eq!(*val, 10); // persisted
585 hooks.use_animation("keep_anim", true);
586 hooks.end_frame();
587
588 // Frame 3: verify "drop_me" was evicted
589 hooks.begin_frame();
590 let val = hooks.use_state::<u32>("drop_me", || 99);
591 assert_eq!(*val, 99); // recreated from default
592 hooks.end_frame();
593
594 // And "drop_anim" should be gone
595 // (only "keep_anim" should remain)
596 }
597}