synh8 0.1.0

A synaptic-inspired TUI for managing APT packages on Debian/Ubuntu. Linux only.
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
//! TUI progress display for APT download and install operations.
//!
//! Uses `Rc<RefCell<ProgressState>>` to share terminal access between
//! `TuiAcquireProgress` (download phase) and `TuiInstallProgress` (install phase).
//! Both phases render into the same ratatui terminal as a centered modal.
//!
//! The progress terminal writes to `/dev/tty` directly, while `StdioRedirect`
//! redirects fd 1/2 to `/dev/null` so dpkg's stdout output is suppressed.

use std::cell::RefCell;
use std::fs::File;
use std::rc::Rc;

use ratatui::prelude::*;
use ratatui::widgets::{Block, Borders, Clear, Gauge, Paragraph, Wrap};
use ratatui::Terminal;
use rust_apt::raw::{AcqTextStatus, ItemDesc, PkgAcquire};

use crate::types::PackageInfo;

// ============================================================================
// Types
// ============================================================================

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProgressPhase {
    Downloading,
    Installing,
    Done,
}

/// RAII guard that redirects stdout/stderr to a temp file.
/// Restores the original file descriptors when dropped.
pub struct StdioRedirect {
    saved_stdout: libc::c_int,
    saved_stderr: libc::c_int,
    capture_path: std::path::PathBuf,
}

impl StdioRedirect {
    /// Redirect stdout and stderr to a temp file for later retrieval.
    pub fn capture() -> std::io::Result<Self> {
        use std::os::unix::io::AsRawFd;

        let capture_path = std::env::temp_dir().join("synh8-apt-output.tmp");
        unsafe {
            let saved_stdout = libc::dup(libc::STDOUT_FILENO);
            if saved_stdout == -1 {
                return Err(std::io::Error::last_os_error());
            }
            let saved_stderr = libc::dup(libc::STDERR_FILENO);
            if saved_stderr == -1 {
                libc::close(saved_stdout);
                return Err(std::io::Error::last_os_error());
            }

            let file = match std::fs::File::create(&capture_path) {
                Ok(f) => f,
                Err(e) => {
                    libc::close(saved_stdout);
                    libc::close(saved_stderr);
                    return Err(e);
                }
            };
            let capture_fd = file.as_raw_fd();
            if libc::dup2(capture_fd, libc::STDOUT_FILENO) == -1 {
                libc::close(saved_stdout);
                libc::close(saved_stderr);
                return Err(std::io::Error::last_os_error());
            }
            if libc::dup2(capture_fd, libc::STDERR_FILENO) == -1 {
                // Restore stdout before bailing out
                libc::dup2(saved_stdout, libc::STDOUT_FILENO);
                libc::close(saved_stdout);
                libc::close(saved_stderr);
                return Err(std::io::Error::last_os_error());
            }
            // file drops here closing capture_fd, but the dup'd fds keep it open

            Ok(Self { saved_stdout, saved_stderr, capture_path })
        }
    }

    /// Read the captured output.
    pub fn output(&self) -> Vec<String> {
        // Flush C stdio buffers so all libapt output is written to the file
        unsafe { libc::fflush(std::ptr::null_mut()); }
        std::fs::read_to_string(&self.capture_path)
            .unwrap_or_default()
            .lines()
            .map(String::from)
            .collect()
    }
}

impl Drop for StdioRedirect {
    fn drop(&mut self) {
        unsafe {
            let r1 = libc::dup2(self.saved_stdout, libc::STDOUT_FILENO);
            debug_assert!(r1 != -1, "dup2 failed restoring stdout");
            let r2 = libc::dup2(self.saved_stderr, libc::STDERR_FILENO);
            debug_assert!(r2 != -1, "dup2 failed restoring stderr");
            libc::close(self.saved_stdout);
            libc::close(self.saved_stderr);
        }
        drop(std::fs::remove_file(&self.capture_path));
    }
}

/// Snapshot of progress data passed to the render function.
pub struct ProgressSnapshot<'a> {
    pub phase: ProgressPhase,
    pub percent: f64,
    pub current_bytes: u64,
    pub total_bytes: u64,
    pub speed_bps: u64,
    pub install_steps_done: u64,
    pub install_total_steps: u64,
    pub install_action: &'a str,
    pub errors: &'a [String],
    pub title: &'a str,
}

/// Shared progress state, owned by `Rc<RefCell<_>>`.
///
/// The terminal writes to `/dev/tty` directly, bypassing stdout.
/// This allows dpkg output (which goes to fd 1) to be suppressed via
/// `StdioRedirect` without affecting progress rendering.
pub struct ProgressState {
    terminal: Terminal<TermionBackend<File>>,
    pub phase: ProgressPhase,
    // Download phase
    pub percent: f64,
    pub current_bytes: u64,
    pub total_bytes: u64,
    pub speed_bps: u64,
    // Install phase
    pub install_steps_done: u64,
    pub install_total_steps: u64,
    pub install_action: String,
    // Shared
    pub errors: Vec<String>,
    /// Title shown in the modal border
    pub title: String,
}

impl ProgressState {
    pub fn new(title: &str) -> std::io::Result<Self> {
        let tty = std::fs::OpenOptions::new()
            .write(true)
            .open("/dev/tty")?;
        let backend = TermionBackend::new(tty);
        let terminal = Terminal::new(backend)?;
        Ok(Self {
            terminal,
            phase: ProgressPhase::Downloading,
            percent: 0.0,
            current_bytes: 0,
            total_bytes: 0,
            speed_bps: 0,
            install_steps_done: 0,
            install_total_steps: 0,
            install_action: String::new(),
            errors: Vec::new(),
            title: title.to_string(),
        })
    }

    fn draw(&mut self) {
        let snap = ProgressSnapshot {
            phase: self.phase,
            percent: self.percent,
            current_bytes: self.current_bytes,
            total_bytes: self.total_bytes,
            speed_bps: self.speed_bps,
            install_steps_done: self.install_steps_done,
            install_total_steps: self.install_total_steps,
            install_action: &self.install_action,
            errors: &self.errors,
            title: &self.title,
        };

        let _ = self.terminal.draw(|frame| {
            render_progress_modal(frame, &snap);
        });
    }
}

// ============================================================================
// DynAcquireProgress implementation
// ============================================================================

pub struct TuiAcquireProgress {
    state: Rc<RefCell<ProgressState>>,
}

impl TuiAcquireProgress {
    pub fn new(state: Rc<RefCell<ProgressState>>) -> Self {
        Self { state }
    }
}

impl rust_apt::progress::DynAcquireProgress for TuiAcquireProgress {
    fn pulse_interval(&self) -> usize {
        500_000 // 500ms
    }

    fn hit(&mut self, _item: &ItemDesc) {}

    fn fetch(&mut self, _item: &ItemDesc) {}

    fn done(&mut self, _item: &ItemDesc) {}

    fn fail(&mut self, item: &ItemDesc) {
        let owner = item.owner();
        let error_text = owner.error_text();
        if !error_text.is_empty() {
            let mut state = self.state.borrow_mut();
            state.errors.push(format!("{}: {error_text}", item.short_desc()));
            state.draw();
        }
    }

    fn pulse(&mut self, status: &AcqTextStatus, _owner: &PkgAcquire) {
        let mut state = self.state.borrow_mut();
        state.percent = status.percent();
        state.current_bytes = status.current_bytes();
        state.total_bytes = status.total_bytes();
        state.speed_bps = status.current_cps();
        state.draw();
    }

    fn start(&mut self) {
        let mut state = self.state.borrow_mut();
        state.phase = ProgressPhase::Downloading;
        state.draw();
    }

    fn stop(&mut self, _status: &AcqTextStatus) {
        // Phase transition handled externally
    }
}

// ============================================================================
// DynInstallProgress implementation
// ============================================================================

pub struct TuiInstallProgress {
    state: Rc<RefCell<ProgressState>>,
}

impl TuiInstallProgress {
    pub fn new(state: Rc<RefCell<ProgressState>>) -> Self {
        Self { state }
    }
}

impl rust_apt::progress::DynInstallProgress for TuiInstallProgress {
    fn status_changed(
        &mut self,
        pkgname: String,
        steps_done: u64,
        total_steps: u64,
        action: String,
    ) {
        let mut state = self.state.borrow_mut();
        state.phase = ProgressPhase::Installing;
        state.install_steps_done = steps_done;
        state.install_total_steps = total_steps;
        state.install_action = if pkgname.is_empty() {
            action
        } else {
            format!("{action} {pkgname}")
        };
        state.draw();
    }

    fn error(&mut self, pkgname: String, _steps_done: u64, _total_steps: u64, error: String) {
        let mut state = self.state.borrow_mut();
        state.errors.push(format!("{pkgname}: {error}"));
        state.draw();
    }
}

// ============================================================================
// Rendering — compact centered modal
// ============================================================================

fn render_progress_modal(frame: &mut Frame, snap: &ProgressSnapshot) {
    let &ProgressSnapshot {
        phase,
        percent,
        current_bytes,
        total_bytes,
        speed_bps,
        install_steps_done,
        install_total_steps,
        install_action,
        errors,
        title,
    } = snap;
    let area = frame.area();

    // Modal size: roomy when no errors, expands to show errors
    let modal_width = 70.min(area.width.saturating_sub(4));
    // border(1) + pad(1) + status(1) + pad(1) + gauge(1) + pad(1) + detail(1) + pad(1) + border(1)
    let base_height: u16 = 9;
    let error_height = if errors.is_empty() {
        0
    } else {
        // 1 for separator + up to 4 error lines
        1 + (errors.len() as u16).min(4)
    };
    let modal_height = (base_height + error_height).min(area.height.saturating_sub(2));

    let modal_x = area.x + (area.width - modal_width) / 2;
    let modal_y = area.y + (area.height - modal_height) / 2;
    let modal_area = Rect::new(modal_x, modal_y, modal_width, modal_height);

    frame.render_widget(Clear, modal_area);

    let border_color = match phase {
        ProgressPhase::Downloading => Color::Cyan,
        ProgressPhase::Installing => Color::Green,
        ProgressPhase::Done => Color::Green,
    };
    let block = Block::default()
        .title(format!(" {title} "))
        .borders(Borders::ALL)
        .border_style(Style::default().fg(border_color));
    let inner = block.inner(modal_area);
    frame.render_widget(block, modal_area);

    // Inner layout: pad, status, pad, gauge, pad, detail, pad, [errors]
    let mut constraints = vec![
        Constraint::Length(1), // top padding
        Constraint::Length(1), // status line
        Constraint::Length(1), // spacing
        Constraint::Length(1), // progress bar
        Constraint::Length(1), // spacing
        Constraint::Length(1), // detail line (bytes or action)
        Constraint::Length(1), // bottom padding
    ];
    if error_height > 0 {
        constraints.push(Constraint::Min(error_height));
    }
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints(constraints)
        .split(inner);

    match phase {
        ProgressPhase::Downloading => {
            // Status: "Downloading...  45%  2.1 MB/s"
            let speed_str = if speed_bps > 0 {
                format!("  {}/s", PackageInfo::size_str(speed_bps))
            } else {
                String::new()
            };
            let status = Line::from(vec![
                Span::styled("Downloading... ", Style::default().fg(Color::Cyan)),
                Span::styled(format!("{percent:.0}%"), Style::default().fg(Color::White).bold()),
                Span::styled(speed_str, Style::default().fg(Color::DarkGray)),
            ]);
            frame.render_widget(Paragraph::new(status), chunks[1]);

            // Gauge
            let ratio = (percent / 100.0).clamp(0.0, 1.0);
            let gauge = Gauge::default()
                .gauge_style(Style::default().fg(Color::Cyan).bg(Color::DarkGray))
                .ratio(ratio);
            frame.render_widget(gauge, chunks[3]);

            // Detail: byte counter
            let detail = Line::from(Span::styled(
                format!(
                    "{} / {}",
                    PackageInfo::size_str(current_bytes),
                    PackageInfo::size_str(total_bytes),
                ),
                Style::default().fg(Color::DarkGray),
            ));
            frame.render_widget(Paragraph::new(detail), chunks[5]);
        }
        ProgressPhase::Installing => {
            // Status: "Installing...  Step 14 / 38"
            let status = Line::from(vec![
                Span::styled("Installing... ", Style::default().fg(Color::Green)),
                Span::styled(
                    format!("Step {install_steps_done} / {install_total_steps}"),
                    Style::default().fg(Color::White).bold(),
                ),
            ]);
            frame.render_widget(Paragraph::new(status), chunks[1]);

            // Gauge
            let ratio = if install_total_steps > 0 {
                (install_steps_done as f64 / install_total_steps as f64).clamp(0.0, 1.0)
            } else {
                0.0
            };
            let gauge = Gauge::default()
                .gauge_style(Style::default().fg(Color::Green).bg(Color::DarkGray))
                .ratio(ratio);
            frame.render_widget(gauge, chunks[3]);

            // Detail: current action
            let detail = Line::from(Span::styled(
                install_action,
                Style::default().fg(Color::DarkGray),
            ));
            frame.render_widget(Paragraph::new(detail), chunks[5]);
        }
        ProgressPhase::Done => {
            let status = Line::from(Span::styled(
                "Complete.",
                Style::default().fg(Color::Green).bold(),
            ));
            frame.render_widget(Paragraph::new(status), chunks[1]);

            let gauge = Gauge::default()
                .gauge_style(Style::default().fg(Color::Green).bg(Color::DarkGray))
                .ratio(1.0);
            frame.render_widget(gauge, chunks[3]);
        }
    }

    // Errors section (only shown when errors exist)
    if error_height > 0 && chunks.len() > 7 {
        let error_lines: Vec<Line> = errors
            .iter()
            .rev()
            .take(4)
            .rev()
            .map(|e| Line::from(Span::styled(e.as_str(), Style::default().fg(Color::Red))))
            .collect();
        let error_para = Paragraph::new(error_lines)
            .wrap(Wrap { trim: false });
        frame.render_widget(error_para, chunks[7]);
    }
}