hal-9001 0.2.0

HAL-9001 — Central TUI de Controle do Sistema & Assistente de Sistema (Rust/ratatui)
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Paragraph, Row, Table};
use ratatui::Frame;

use crate::app::App;
use crate::backend::audio::{AudioCategory, AudioNode, AudioSnapshot};
use crate::ui::widgets::truncate_str;

use super::theme::Palette;

pub fn draw(app: &App, pal: &Palette, f: &mut Frame, area: Rect) {
    let m = app.lang.messages();
    let Some(snap) = &app.audio else {
        super::draw_pending(
            app,
            pal,
            f,
            area,
            m.audio_pending_title,
            "audio",
            &[
                m.audio_pending_focus,
                m.audio_pending_nav_volume,
                m.audio_pending_mute,
                m.audio_pending_default,
            ],
        );
        return;
    };

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3),
            Constraint::Percentage(55),
            Constraint::Percentage(45),
            Constraint::Length(3),
        ])
        .split(area);

    let top_cols = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
        .split(chunks[1]);

    let focus = app.audio_category.min(2);
    let selected = app.audio_selected;

    draw_header(snap, m, pal, f, chunks[0]);
    draw_card_panel(
        snap.nodes_for_category(AudioCategory::Sink),
        AudioCategory::Sink,
        focus == 0,
        selected,
        m,
        pal,
        f,
        top_cols[0],
    );
    draw_card_panel(
        snap.nodes_for_category(AudioCategory::AppStream),
        AudioCategory::AppStream,
        focus == 1,
        selected,
        m,
        pal,
        f,
        top_cols[1],
    );
    draw_source_panel(
        snap.nodes_for_category(AudioCategory::Source),
        focus == 2,
        selected,
        m,
        pal,
        f,
        chunks[2],
    );
    draw_footer(m, pal, f, chunks[3]);
}

fn default_node_name(nodes: &[AudioNode]) -> Option<&str> {
    nodes.iter().find(|n| n.is_default).map(|n| n.name.as_str())
}

fn draw_header(
    snap: &AudioSnapshot,
    m: &'static crate::i18n::Messages,
    pal: &Palette,
    f: &mut Frame,
    area: Rect,
) {
    let output = default_node_name(&snap.sinks).unwrap_or(m.audio_none_output);
    let mic = default_node_name(&snap.sources).unwrap_or(m.audio_none_mic);

    let avail = area.width.saturating_sub(2) as usize;
    let seg = avail / 3;

    let line = Line::from(vec![
        Span::styled(
            format!(" {} ", m.audio_label_server),
            Style::default().fg(pal.dim),
        ),
        Span::styled(
            truncate_str(&snap.server_name, seg),
            Style::default().fg(pal.ok).add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            format!("   {} ", m.audio_label_output),
            Style::default().fg(pal.dim),
        ),
        Span::styled(
            truncate_str(output, seg),
            Style::default().fg(pal.accent).add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            format!("   {} ", m.audio_label_mic),
            Style::default().fg(pal.dim),
        ),
        Span::styled(
            truncate_str(mic, seg),
            Style::default().fg(pal.accent).add_modifier(Modifier::BOLD),
        ),
    ]);

    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(pal.accent))
        .title(Span::styled(
            m.audio_title_header,
            Style::default().fg(pal.accent).add_modifier(Modifier::BOLD),
        ));

    f.render_widget(Paragraph::new(line).block(block), area);
}

fn scroll_window(len: usize, visible: usize, selected: usize, focused: bool) -> (usize, usize) {
    if visible == 0 || len == 0 {
        return (0, 0);
    }
    if len <= visible || !focused {
        return (0, len.min(visible));
    }
    let sel = selected.min(len - 1);
    let mut start = sel.saturating_sub(visible - 1);
    if start + visible > len {
        start = len - visible;
    }
    if sel < start {
        start = sel;
    }
    (start, (start + visible).min(len))
}

fn scroll_indicator(start: usize, end: usize, len: usize) -> String {
    let above = start;
    let below = len.saturating_sub(end);
    let mut s = String::new();
    if above > 0 {
        s.push_str(&format!(" ▲{above}"));
    }
    if below > 0 {
        s.push_str(&format!(" ▼{below}"));
    }
    s
}

fn panel_title(icon: &str, label: &str, count: usize, start: usize, end: usize) -> String {
    format!(
        " {icon} {label} ({count}){} ",
        scroll_indicator(start, end, count)
    )
}

fn empty_message(cat: AudioCategory, m: &'static crate::i18n::Messages) -> &'static str {
    match cat {
        AudioCategory::Sink => m.audio_empty_sink,
        AudioCategory::AppStream => m.audio_empty_appstream,
        AudioCategory::Source => m.audio_empty_source,
    }
}

fn cat_title(cat: AudioCategory, m: &'static crate::i18n::Messages) -> &'static str {
    match cat {
        AudioCategory::Sink => m.audio_cat_sink,
        AudioCategory::AppStream => m.audio_cat_appstream,
        AudioCategory::Source => m.audio_cat_source,
    }
}

#[allow(clippy::too_many_arguments)]
fn draw_card_panel(
    nodes: &[AudioNode],
    cat: AudioCategory,
    focused: bool,
    selected: usize,
    m: &'static crate::i18n::Messages,
    pal: &Palette,
    f: &mut Frame,
    area: Rect,
) {
    let border_color = if focused { pal.accent } else { pal.dim };
    let icon = cat.nerd_glyph();

    let visible_items = (area.height.saturating_sub(2) / 2).max(1) as usize;
    let (start, end) = scroll_window(nodes.len(), visible_items, selected, focused);

    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(border_color))
        .title(Span::styled(
            panel_title(icon, cat_title(cat, m), nodes.len(), start, end),
            Style::default()
                .fg(border_color)
                .add_modifier(Modifier::BOLD),
        ));

    if nodes.is_empty() {
        let p = Paragraph::new(Line::from(Span::styled(
            empty_message(cat, m),
            Style::default().fg(pal.dim),
        )))
        .block(block);
        f.render_widget(p, area);
        return;
    }

    let inner_w = area.width.saturating_sub(2) as usize;
    let sel_idx = selected.min(nodes.len() - 1);

    let mut lines: Vec<Line> = Vec::new();
    for (i, node) in nodes.iter().enumerate().take(end).skip(start) {
        let is_sel = focused && i == sel_idx;
        lines.push(name_line(node, is_sel, inner_w, pal));
        lines.push(bar_status_line(node, inner_w, m, pal));
    }

    f.render_widget(Paragraph::new(lines).block(block), area);
}

fn name_line<'a>(node: &AudioNode, is_sel: bool, width: usize, pal: &Palette) -> Line<'a> {
    let bullet = if is_sel {
        "▶ "
    } else if node.is_default {
        "● "
    } else {
        "  "
    };
    let name_style = if node.is_muted {
        Style::default()
            .fg(pal.dim)
            .add_modifier(Modifier::CROSSED_OUT)
    } else if is_sel {
        Style::default().fg(pal.accent).add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(pal.fg)
    };
    let bullet_style = if is_sel {
        Style::default().fg(pal.accent).add_modifier(Modifier::BOLD)
    } else if node.is_default {
        Style::default().fg(pal.ok).add_modifier(Modifier::BOLD)
    } else {
        Style::default()
    };
    let name_budget = width.saturating_sub(2);
    let line_style = if is_sel {
        Style::default().add_modifier(Modifier::REVERSED)
    } else {
        Style::default()
    };
    Line::from(vec![
        Span::styled(bullet, bullet_style),
        Span::styled(truncate_str(&node.name, name_budget), name_style),
    ])
    .style(line_style)
}

fn bar_status_line<'a>(
    node: &AudioNode,
    width: usize,
    m: &'static crate::i18n::Messages,
    pal: &Palette,
) -> Line<'a> {
    let status = if node.is_muted && node.is_default {
        m.audio_tag_muted_default
    } else if node.is_muted {
        m.audio_tag_muted
    } else if node.is_default {
        m.audio_tag_default
    } else {
        m.audio_status_active
    };
    let status_color = if node.is_muted {
        pal.err
    } else if node.is_default {
        pal.ok
    } else {
        pal.dim
    };

    let status_w = status.len().min(width.saturating_sub(4));
    let bar_budget = width.saturating_sub(status_w + 1).max(4);
    let bar_span = format_volume_bar(node.volume, node.is_muted, pal, bar_budget);

    Line::from(vec![
        Span::raw("  "),
        bar_span,
        Span::raw(" "),
        Span::styled(
            truncate_str(status, status_w),
            Style::default().fg(status_color),
        ),
    ])
}

fn format_volume_bar<'a>(volume: f32, is_muted: bool, pal: &Palette, budget: usize) -> Span<'a> {
    let pct = (volume * 100.0).round() as u32;
    let pct_str = format!("{pct:>3}%");

    let overhead = 2 + 1 + pct_str.len();
    let total_bars = budget.saturating_sub(overhead).clamp(3, 16);
    let filled_bars = ((volume.min(1.0) * total_bars as f32).round() as usize).min(total_bars);

    let mut bar_str = String::new();
    for _ in 0..filled_bars {
        bar_str.push('█');
    }
    for _ in filled_bars..total_bars {
        bar_str.push('░');
    }

    let color = if is_muted {
        pal.dim
    } else if volume > 1.0 {
        pal.warn
    } else if volume > 0.7 {
        pal.ok
    } else {
        pal.accent
    };

    Span::styled(
        format!("[{bar_str}] {pct_str}"),
        Style::default().fg(color).add_modifier(Modifier::BOLD),
    )
}

fn draw_source_panel(
    nodes: &[AudioNode],
    focused: bool,
    selected: usize,
    m: &'static crate::i18n::Messages,
    pal: &Palette,
    f: &mut Frame,
    area: Rect,
) {
    let border_color = if focused { pal.accent } else { pal.dim };
    let icon = AudioCategory::Source.nerd_glyph();

    let visible_items = area.height.saturating_sub(3).max(1) as usize;
    let (start, end) = scroll_window(nodes.len(), visible_items, selected, focused);

    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(border_color))
        .title(Span::styled(
            panel_title(icon, m.audio_title_input_devices, nodes.len(), start, end),
            Style::default()
                .fg(border_color)
                .add_modifier(Modifier::BOLD),
        ));

    if nodes.is_empty() {
        let p = Paragraph::new(Line::from(Span::styled(
            empty_message(AudioCategory::Source, m),
            Style::default().fg(pal.dim),
        )))
        .block(block);
        f.render_widget(p, area);
        return;
    }

    let header = Row::new(vec![
        Span::styled("  ", Style::default()),
        Span::styled(
            m.audio_col_device,
            Style::default().fg(pal.accent).add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            m.audio_col_level,
            Style::default().fg(pal.accent).add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            m.audio_col_status,
            Style::default().fg(pal.accent).add_modifier(Modifier::BOLD),
        ),
    ])
    .style(Style::default().fg(pal.accent))
    .bottom_margin(1);

    let sel_idx = selected.min(nodes.len() - 1);
    let inner_w = area.width.saturating_sub(2) as usize;
    let name_w = (inner_w * 40 / 100).max(6);

    let rows: Vec<Row> = nodes
        .iter()
        .enumerate()
        .take(end)
        .skip(start)
        .map(|(i, node)| format_source_row(node, focused && i == sel_idx, name_w, m, pal))
        .collect();

    let widths = [
        Constraint::Length(2),
        Constraint::Percentage(40),
        Constraint::Percentage(35),
        Constraint::Percentage(25),
    ];

    let table = Table::new(rows, widths).header(header).block(block);
    f.render_widget(table, area);
}

fn format_source_row<'a>(
    node: &AudioNode,
    is_sel: bool,
    name_w: usize,
    m: &'static crate::i18n::Messages,
    pal: &Palette,
) -> Row<'a> {
    let bullet = if is_sel {
        Span::styled(
            "▶ ",
            Style::default().fg(pal.accent).add_modifier(Modifier::BOLD),
        )
    } else if node.is_default {
        Span::styled(
            "● ",
            Style::default().fg(pal.ok).add_modifier(Modifier::BOLD),
        )
    } else {
        Span::raw("  ")
    };

    let name_style = if node.is_muted {
        Style::default()
            .fg(pal.dim)
            .add_modifier(Modifier::CROSSED_OUT)
    } else if is_sel {
        Style::default().fg(pal.accent).add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(pal.fg)
    };

    let volume_span = format_volume_bar(node.volume, node.is_muted, pal, 20);

    let status_span = if node.is_muted && node.is_default {
        Span::styled(
            m.audio_tag_muted_default,
            Style::default().fg(pal.err).add_modifier(Modifier::BOLD),
        )
    } else if node.is_muted {
        Span::styled(
            m.audio_tag_muted,
            Style::default().fg(pal.err).add_modifier(Modifier::BOLD),
        )
    } else if node.is_default {
        Span::styled(
            m.audio_tag_default,
            Style::default().fg(pal.ok).add_modifier(Modifier::BOLD),
        )
    } else {
        Span::styled(m.audio_status_active, Style::default().fg(pal.dim))
    };

    let row_style = if is_sel {
        Style::default()
            .fg(pal.accent)
            .add_modifier(Modifier::REVERSED)
    } else {
        Style::default()
    };

    Row::new(vec![
        bullet,
        Span::styled(truncate_str(&node.name, name_w), name_style),
        volume_span,
        status_span,
    ])
    .style(row_style)
}

fn draw_footer(m: &'static crate::i18n::Messages, pal: &Palette, f: &mut Frame, area: Rect) {
    let line = Line::from(vec![
        Span::styled(
            " [Tab/⇧Tab] ",
            Style::default().fg(pal.accent).add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            format!("{}   ", m.audio_hint_focus),
            Style::default().fg(pal.dim),
        ),
        Span::styled(
            "[j/k] ",
            Style::default().fg(pal.accent).add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            format!("{}   ", m.audio_hint_nav),
            Style::default().fg(pal.dim),
        ),
        Span::styled(
            "[+/- h/l] ",
            Style::default().fg(pal.accent).add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            format!("{}   ", m.audio_hint_volume),
            Style::default().fg(pal.dim),
        ),
        Span::styled(
            "[m] ",
            Style::default().fg(pal.accent).add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            format!("{}   ", m.audio_hint_mute),
            Style::default().fg(pal.dim),
        ),
        Span::styled(
            "[Enter] ",
            Style::default().fg(pal.accent).add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            format!("{}   ", m.audio_hint_default_mute),
            Style::default().fg(pal.dim),
        ),
        Span::styled(
            "[r] ",
            Style::default().fg(pal.accent).add_modifier(Modifier::BOLD),
        ),
        Span::styled(m.audio_hint_refresh, Style::default().fg(pal.dim)),
    ]);

    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(pal.dim))
        .title(m.audio_footer_title);

    f.render_widget(Paragraph::new(line).block(block), area);
}