sonos-cli 0.5.0

CLI and TUI for controlling Sonos speakers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
//! TUI hooks system — co-located widget state, SDK subscriptions, and animation.
//!
//! Modeled after React hooks but adapted for Rust's ownership model and
//! ratatui's immediate-mode rendering. Three primitives:
//!
//! - `use_state<V>(key, default)` — Persistent local state across renders
//! - `use_watch(property_handle)` — Subscribe to SDK property, return current value
//! - `use_animation(key, active)` — Request periodic re-renders when active
//!
//! ## Calling Convention
//!
//! `use_state` returns `&mut V` which borrows `&mut self` on `Hooks`.
//! To avoid borrow conflicts, call hooks in this order:
//!
//! 1. `use_watch` — returns owned `Option<V>`, borrow released immediately
//! 2. `use_animation` — `&mut self` borrow released immediately
//! 3. `use_state` — must be called last or in a scoped block
//!
//! ## Frame Lifecycle
//!
//! ```text
//! hooks.begin_frame()     // reset access tracking
//! terminal.draw(...)      // widgets call hooks
//! hooks.end_frame()       // evict unaccessed state + handles
//! ```

use std::any::{Any, TypeId};
use std::collections::{HashMap, HashSet};

use sonos_sdk::property::{GroupFetchable, GroupPropertyHandle, PropertyHandle};
use sonos_state::property::SonosProperty;

use crate::tui::app::App;

// ============================================================================
// RenderContext
// ============================================================================

/// Render context passed to all render functions.
///
/// Wraps `&App` (read) and `&mut Hooks` (write), satisfying the borrow checker
/// by separating immutable app data from mutable hook state.
pub struct RenderContext<'a> {
    pub app: &'a App,
    pub hooks: &'a mut Hooks,
}

// ============================================================================
// HookKey — state identity
// ============================================================================

/// Composite key for `use_state`: combines value type with a string name.
///
/// Two hooks with the same string key but different value types get separate
/// storage slots (keyed by `TypeId`).
#[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(),
        }
    }
}

// ============================================================================
// ProgressState — moved from app.rs to co-locate with hooks
// ============================================================================

/// Client-side progress interpolation state for a single group.
///
/// Stores a snapshot of position + wall-clock timestamp. While playing,
/// `interpolated_position_ms()` advances the position based on elapsed time,
/// capped at 10s to limit drift from system sleep/stalls.
#[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 {
    /// Update from SDK position and playback data.
    pub fn update(&mut self, position_ms: u64, duration_ms: u64, is_playing: bool) {
        // Freeze at interpolated position on pause transition
        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();
    }

    /// Compute interpolated position in milliseconds.
    ///
    /// Caps interpolation at 10s ahead to limit drift from system sleep/stalls.
    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)
    }
}

// ============================================================================
// Hooks
// ============================================================================

/// General-purpose hooks system for TUI widget state management.
///
/// Stores persistent state, SDK watch handles, and animation registrations.
/// Uses mark-and-sweep to automatically clean up state when widgets stop
/// rendering (e.g., screen transitions).
pub struct Hooks {
    // use_state storage — keyed by (TypeId, name)
    states: HashMap<HookKey, Box<dyn Any>>,

    // use_watch storage — type-erased WatchHandle<P>, keyed by "speaker_id:property_key"
    watches: HashMap<String, Box<dyn Any>>,

    // use_animation — keys of active animations
    animations: HashSet<String>,

    // Mark-and-sweep: keys accessed during current frame
    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(),
        }
    }

    // -----------------------------------------------------------------------
    // Frame lifecycle
    // -----------------------------------------------------------------------

    /// Reset access tracking before a render frame.
    pub fn begin_frame(&mut self) {
        self.accessed_states.clear();
        self.accessed_watches.clear();
        self.accessed_animations.clear();
    }

    /// Evict unaccessed state and drop unaccessed watch handles.
    pub fn end_frame(&mut self) {
        // Evict unaccessed states
        self.states
            .retain(|key, _| self.accessed_states.contains(key));

        // Drop unaccessed watch handles (starts grace periods)
        self.watches
            .retain(|key, _| self.accessed_watches.contains(key));

        // Remove unaccessed animations
        self.animations
            .retain(|key| self.accessed_animations.contains(key));
    }

    // -----------------------------------------------------------------------
    // use_state
    // -----------------------------------------------------------------------

    /// Get or create persistent local state.
    ///
    /// On first call for a given key, creates the state using `default()`.
    /// On subsequent calls, returns the existing state.
    ///
    /// **Must be called last** — the returned `&mut V` borrows `&mut self`,
    /// preventing other hook calls until the reference is dropped.
    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)")
    }

    // -----------------------------------------------------------------------
    // use_watch
    // -----------------------------------------------------------------------

    /// Subscribe to an SDK speaker property, returning the current value.
    ///
    /// Each frame, creates a fresh `WatchHandle` via `prop.watch()` to get
    /// an up-to-date snapshot. The old handle is replaced (dropped → grace
    /// period starts → new handle re-acquires → grace period cancelled).
    /// This is the SDK's intended pattern: "Re-watch each frame to refresh
    /// the snapshot."
    ///
    /// Falls back to `prop.get()` if `watch()` fails.
    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());

        // Create a fresh watch handle each frame to get updated values.
        // WatchHandle is a snapshot — value is set at creation and never updates.
        // Replacing the old handle drops it (grace period starts), then the new
        // handle re-acquires the subscription (grace period cancelled).
        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()
            }
        }
    }

    /// Subscribe to an SDK group property, returning the current value.
    ///
    /// Same as `use_watch` but for group-scoped properties (e.g., group volume).
    #[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.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()
            }
        }
    }

    /// Subscribe to a fetchable group property, fetching on first access if empty.
    ///
    /// Like `use_watch_group` but performs a one-time fetch when the cache has
    /// no value yet, so the UI doesn't show a blank until the first UPnP event.
    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.accessed_watches.insert(key.clone());

        match prop.watch_or_fetch() {
            Ok(wh) => {
                let val = wh.value().cloned();
                self.watches.insert(key, Box::new(wh));
                val
            }
            Err(e) => {
                tracing::warn!(
                    "use_watch_group_or_fetch failed for {}: {e}, falling back to get()",
                    P::KEY
                );
                prop.get()
            }
        }
    }

    // -----------------------------------------------------------------------
    // use_animation
    // -----------------------------------------------------------------------

    /// Register an animation tick request.
    ///
    /// When `active` is true, the event loop's global animation timer will
    /// mark the app as dirty every ~250ms, triggering re-renders for smooth
    /// progress bar animation.
    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);
        }
    }

    /// Check if any widget has registered an active animation.
    ///
    /// Called by the event loop between frames to decide whether to tick
    /// the animation timer.
    pub fn has_active_animations(&self) -> bool {
        !self.animations.is_empty()
    }
}

// ============================================================================
// Tests
// ============================================================================

#[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();

        // Frame 1: create state
        hooks.begin_frame();
        *hooks.use_state::<u32>("counter", || 0) = 10;
        hooks.end_frame();

        // Frame 2: state persists
        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();

        // Frame 1: create state
        hooks.begin_frame();
        *hooks.use_state::<u32>("counter", || 42) = 100;
        hooks.end_frame();

        // Frame 2: state NOT accessed → evicted
        hooks.begin_frame();
        hooks.end_frame();

        // Frame 3: recreated from default
        hooks.begin_frame();
        let val = hooks.use_state::<u32>("counter", || 42);
        assert_eq!(*val, 42); // default, not 100
    }

    #[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;
        // Borrow on hooks released after this line since u32 is Copy

        let s = hooks.use_state::<String>("val", || "hello".to_string());
        assert_eq!(s, "hello"); // separate slot, not confused with u32
    }

    #[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();

        // Frame 1: register animation
        hooks.begin_frame();
        hooks.use_animation("progress", true);
        hooks.end_frame();
        assert!(hooks.has_active_animations());

        // Frame 2: animation NOT accessed → evicted
        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()
        };

        // Not playing → returns last position
        assert_eq!(ps.interpolated_position_ms(), 1000);

        // Playing → interpolates forward
        ps.is_playing = true;
        ps.wall_clock_at_last_update = std::time::Instant::now();
        // Position should be >= 1000 (at least the base)
        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,
            // Simulate old timestamp (10+ seconds ago)
            wall_clock_at_last_update: std::time::Instant::now()
                - std::time::Duration::from_secs(20),
        };

        // Should cap at duration, not overflow
        assert_eq!(ps.interpolated_position_ms(), 5000);
    }

    #[test]
    fn mark_and_sweep_preserves_accessed_drops_rest() {
        let mut hooks = Hooks::new();

        // Frame 1: create multiple states
        hooks.begin_frame();
        *hooks.use_state::<u32>("keep", || 1) = 10;
        // Release borrow
        let _ = hooks.use_state::<u32>("drop_me", || 2);
        hooks.use_animation("keep_anim", true);
        hooks.use_animation("drop_anim", true);
        hooks.end_frame();

        // Frame 2: only access "keep" variants
        hooks.begin_frame();
        let val = hooks.use_state::<u32>("keep", || 99);
        assert_eq!(*val, 10); // persisted
        hooks.use_animation("keep_anim", true);
        hooks.end_frame();

        // Frame 3: verify "drop_me" was evicted
        hooks.begin_frame();
        let val = hooks.use_state::<u32>("drop_me", || 99);
        assert_eq!(*val, 99); // recreated from default
        hooks.end_frame();

        // And "drop_anim" should be gone
        // (only "keep_anim" should remain)
    }
}