sonos-cli 0.8.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
//! Speaker list widget — render-only component.
//!
//! Takes pre-computed `SpeakerListData` and `Theme`, outputs to frame.
//! No hooks, no SDK, no key handling.
//!
//! Group headers are single-line with dot leader fill:
//!   `▶ Bedroom ::::: BOY IN RED — Artist ::::::::::::: 30%`
//!   `■ Kitchen ::::::::::::::::::::::::::::::::::::::: 21%`
//!
//! Speaker rows use tree connectors with model names:
//!   `├─ Bathroom • Sonos Connect:AMP                  46%`
//!   `└─ Bedroom • Sonos Amp                           28%`
//!
//! Muted speakers and groups show the mute glyph before the volume:
//!   `├─ Bathroom • Sonos Connect:AMP                × 46%`
//!
//! During pickup mode, inline action rows appear:
//!   `└─ Add to group`       (selectable drop target)
//!   `└─ Already in group`   (dimmed, home group)
//!   `► Create new group`    (standalone target)

use ratatui::layout::Rect;
use ratatui::text::{Line, Span};
use ratatui::widgets::Paragraph;
use ratatui::Frame;
use sonos_sdk::PlaybackState;

use crate::tui::theme::Theme;
use crate::tui::types::{group_for_entry, ListEntry, SpeakerListData};
use crate::tui::widgets::volume_bar;

/// Render the speaker list from pre-computed data.
pub fn render(frame: &mut Frame, area: Rect, data: &SpeakerListData, theme: &Theme) {
    render_normal(frame, area, data, theme);
}

// ===========================================================================
// Normal mode rendering
// ===========================================================================

fn render_normal(frame: &mut Frame, area: Rect, data: &SpeakerListData, theme: &Theme) {
    if data.entries.is_empty() {
        let paragraph = Paragraph::new("No speakers found")
            .alignment(ratatui::layout::Alignment::Center)
            .style(theme.muted);
        frame.render_widget(paragraph, area);
        return;
    }

    let selected_index = data
        .selected_index
        .min(data.entries.len().saturating_sub(1));

    let viewport_height = area.height as usize;
    let vol_width = 16.min(area.width.saturating_sub(50));
    let total_width = area.width as usize;
    let g = &theme.glyphs;

    let cursor_prefix_width = 2;
    let is_pickup = data.picked_up_speaker_id.is_some();
    let focused_group = group_for_entry(&data.entries, selected_index);

    let mut lines: Vec<Line> = Vec::new();
    let mut entry_visual_starts: Vec<usize> = Vec::new();
    let mut entry_visual_heights: Vec<usize> = Vec::new();

    for (idx, (entry, entry_data)) in data.entries.iter().zip(data.entry_data.iter()).enumerate() {
        let is_selected = idx == selected_index;

        // Insert blank separator + divider between groups (not before the first entry)
        let is_group_header = matches!(entry, ListEntry::GroupHeader(_));
        if idx > 0 && is_group_header {
            lines.push(Line::raw(""));
            let divider_inner_w = total_width.saturating_sub(cursor_prefix_width + 2 + 2);
            let left_pad = divider_inner_w / 2;
            let right_pad = divider_inner_w.saturating_sub(left_pad + 1);
            let divider = format!(
                "{}{}{}{}{}",
                g.divider_left,
                " ".repeat(left_pad),
                g.divider_fill,
                " ".repeat(right_pad),
                g.divider_right,
            );
            lines.push(Line::from(vec![
                Span::raw(" ".repeat(cursor_prefix_width + 2)),
                Span::styled(divider, theme.muted),
            ]));
            lines.push(Line::raw(""));
        }

        let start_line = lines.len();

        match entry {
            ListEntry::GroupHeader(group_id) => {
                let is_focused_group = focused_group.as_ref().is_some_and(|fg| fg == group_id);

                let (icon, icon_style) = match &entry_data.playback_state {
                    Some(PlaybackState::Playing) => (g.playing, theme.playing_icon),
                    Some(PlaybackState::Paused) => (g.paused, theme.paused_icon),
                    _ => (g.stopped, theme.stopped_icon),
                };

                let name_style = if is_selected {
                    theme.speaker_cursor
                } else {
                    theme.group_header
                };

                let leader_style = if is_focused_group {
                    theme.accent_secondary
                } else {
                    theme.leader
                };

                let cursor_str = if is_selected { g.cursor } else { " " };

                let vol_text = format_volume(entry_data.group_volume);
                let mute_text = if entry_data.is_muted {
                    format!(" {}", g.muted)
                } else {
                    String::new()
                };
                let vol_chars = vol_text.chars().count() + mute_text.chars().count();

                let name_chars = entry_data.name.chars().count();
                let icon_chars = icon.chars().count();

                let track_text = entry_data.track_info.as_deref().unwrap_or("");
                let track_chars = track_text.chars().count();

                let fixed_chars =
                    cursor_prefix_width + icon_chars + 1 + name_chars + 1 + vol_chars + 1;
                let available = total_width.saturating_sub(fixed_chars);

                let mut spans = vec![
                    Span::styled(cursor_str, theme.speaker_cursor),
                    Span::raw(" "),
                    Span::styled(format!("{icon} "), icon_style),
                    Span::styled(entry_data.name.clone(), name_style),
                    Span::raw(" "),
                ];

                if !track_text.is_empty() && available > track_chars + 4 {
                    let leaders_total = available.saturating_sub(track_chars + 2);
                    let leaders_before = 5.min(leaders_total / 2);
                    let leaders_after = leaders_total.saturating_sub(leaders_before);

                    spans.push(Span::styled(
                        std::iter::repeat_n(g.leader_char, leaders_before).collect::<String>(),
                        leader_style,
                    ));
                    spans.push(Span::styled(format!(" {track_text} "), theme.track_info));
                    spans.push(Span::styled(
                        std::iter::repeat_n(g.leader_char, leaders_after).collect::<String>(),
                        leader_style,
                    ));
                } else {
                    spans.push(Span::styled(
                        std::iter::repeat_n(g.leader_char, available).collect::<String>(),
                        leader_style,
                    ));
                }

                if !mute_text.is_empty() {
                    spans.push(Span::styled(mute_text, theme.error));
                }
                spans.push(Span::styled(format!(" {vol_text}"), theme.muted));

                lines.push(Line::from(spans));
                entry_visual_starts.push(start_line);
                entry_visual_heights.push(lines.len() - start_line);
            }
            ListEntry::SpeakerRow(speaker_id) => {
                let connector = if entry_data.is_last_in_group {
                    g.connector_last
                } else {
                    g.connector_branch
                };

                let is_picked_up = data
                    .picked_up_speaker_id
                    .as_ref()
                    .is_some_and(|id| id == speaker_id);

                let name_style = if is_picked_up {
                    theme.picked_up
                } else if is_selected {
                    theme.speaker_cursor
                } else {
                    theme.speaker_name
                };

                let cursor_str = if is_selected { g.cursor } else { " " };

                let mut spans = vec![
                    Span::styled(cursor_str, theme.speaker_cursor),
                    Span::raw(" "),
                    Span::styled(" ".repeat(2), theme.muted),
                ];

                if is_picked_up {
                    spans.push(Span::styled(connector, theme.picked_up));
                    spans.push(Span::styled(entry_data.name.clone(), theme.picked_up));
                    if let Some(ref model) = entry_data.model_name {
                        spans.push(Span::styled(g.model_separator.to_string(), theme.picked_up));
                        spans.push(Span::styled(model.clone(), theme.picked_up));
                    }
                    let content_width: usize =
                        spans.iter().map(|s| s.content.chars().count()).sum();
                    let remaining = total_width.saturating_sub(content_width);
                    if remaining > 0 {
                        spans.push(Span::styled(" ".repeat(remaining), theme.picked_up));
                    }
                } else {
                    spans.push(Span::styled(connector, theme.muted));
                    spans.push(Span::styled(entry_data.name.clone(), name_style));

                    if let Some(ref model) = entry_data.model_name {
                        spans.push(Span::styled(g.model_separator.to_string(), theme.muted));
                        spans.push(Span::styled(model.clone(), theme.muted));
                    }

                    if let Some(vol) = entry_data.speaker_volume {
                        append_volume_spans(
                            &mut spans,
                            vol,
                            entry_data.is_muted,
                            is_selected && !is_pickup,
                            vol_width,
                            total_width,
                            theme,
                        );
                    }
                }

                lines.push(Line::from(spans));
                entry_visual_starts.push(start_line);
                entry_visual_heights.push(1);
            }
            ListEntry::AddToGroupRow(_) => {
                let cursor_str = if is_selected { g.cursor } else { " " };

                let style = if entry_data.is_home_group {
                    theme.muted
                } else if is_selected {
                    theme.accent
                } else {
                    theme.muted
                };

                let cursor_style = if is_selected && !entry_data.is_home_group {
                    theme.speaker_cursor
                } else {
                    theme.muted
                };

                lines.push(Line::from(vec![
                    Span::styled(cursor_str, cursor_style),
                    Span::raw(" "),
                    Span::styled(" ".repeat(2), theme.muted),
                    Span::styled(g.connector_last, style),
                    Span::styled(entry_data.name.clone(), style),
                ]));

                entry_visual_starts.push(start_line);
                entry_visual_heights.push(1);
            }
            ListEntry::CreateNewGroupRow => {
                // Divider before "Create new group"
                lines.push(Line::raw(""));
                let divider_inner_w = total_width.saturating_sub(cursor_prefix_width + 2 + 2);
                let left_pad = divider_inner_w / 2;
                let right_pad = divider_inner_w.saturating_sub(left_pad + 1);
                let divider = format!(
                    "{}{}{}{}{}",
                    g.divider_left,
                    " ".repeat(left_pad),
                    g.divider_fill,
                    " ".repeat(right_pad),
                    g.divider_right,
                );
                lines.push(Line::from(vec![
                    Span::raw(" ".repeat(cursor_prefix_width + 2)),
                    Span::styled(divider, theme.muted),
                ]));
                lines.push(Line::raw(""));

                let cursor_str = if is_selected { g.cursor } else { " " };
                let style = if is_selected {
                    theme.accent
                } else {
                    theme.muted
                };
                let cursor_style = if is_selected {
                    theme.speaker_cursor
                } else {
                    theme.muted
                };

                lines.push(Line::from(vec![
                    Span::styled(cursor_str, cursor_style),
                    Span::raw(" "),
                    Span::styled(" ".repeat(2), theme.muted),
                    Span::styled(format!("{} ", g.tab_active_indicator), style),
                    Span::styled(entry_data.name.clone(), style),
                ]));

                entry_visual_starts.push(start_line);
                entry_visual_heights.push(lines.len() - start_line);
            }
        }
    }

    let scroll_offset = if viewport_height == 0 || entry_visual_starts.is_empty() {
        0
    } else if selected_index < entry_visual_starts.len() {
        let top = entry_visual_starts[selected_index];
        let bottom = top + entry_visual_heights[selected_index];

        let visible_top = if selected_index > 0
            && matches!(&data.entries[selected_index], ListEntry::GroupHeader(_))
        {
            top.saturating_sub(3)
        } else {
            top
        };

        if bottom <= viewport_height {
            0
        } else if visible_top + viewport_height >= bottom {
            visible_top
        } else {
            bottom.saturating_sub(viewport_height)
        }
    } else {
        0
    };

    let paragraph = Paragraph::new(lines).scroll((scroll_offset as u16, 0));
    frame.render_widget(paragraph, area);
}

// ===========================================================================
// Shared helpers
// ===========================================================================

/// Format volume as a fixed 4-char right-aligned string: `" 0%"`, `"60%"`, `"100%"`.
fn format_volume(vol: Option<u16>) -> String {
    match vol {
        Some(v) => format!("{v:>3}%"),
        None => "   -".to_string(),
    }
}

/// Append right-aligned volume bar (when selected) or percentage text to a span list.
///
/// When `is_muted`, the mute glyph precedes the volume and the bar renders dimmed.
fn append_volume_spans(
    spans: &mut Vec<Span>,
    vol: u16,
    is_muted: bool,
    is_selected: bool,
    bar_width: u16,
    total_width: usize,
    theme: &Theme,
) {
    // Calculate current content width
    let content_width: usize = spans.iter().map(|s| s.content.chars().count()).sum();

    let mute_text = if is_muted {
        format!("{} ", theme.glyphs.muted)
    } else {
        String::new()
    };
    let mute_chars = mute_text.chars().count();

    let vol_spans = if is_selected {
        // Right-align the volume bar
        let filled = if is_muted {
            theme.volume_empty
        } else {
            theme.volume_filled
        };
        volume_bar::render_volume_bar(vol, bar_width, filled, theme.volume_empty).spans
    } else {
        // Right-align the volume percentage
        vec![Span::styled(format!("{vol:>3}%"), theme.muted)]
    };
    let vol_display_width: usize = vol_spans.iter().map(|s| s.content.chars().count()).sum();

    let pad = total_width.saturating_sub(content_width + mute_chars + vol_display_width);
    if pad > 0 {
        spans.push(Span::raw(" ".repeat(pad)));
    }
    if is_muted {
        spans.push(Span::styled(mute_text, theme.error));
    }
    spans.extend(vol_spans);
}

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