Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
name: CI

on:
push:
branches: [main]
pull_request:

jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- run: cargo test
67 changes: 60 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
# dap-tui

[![CI](https://github.com/ssalentin/dap-tui/actions/workflows/ci.yml/badge.svg)](https://github.com/ssalentin/dap-tui/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/github/license/ssalentin/dap-tui)](LICENSE)
[![Version](https://img.shields.io/badge/version-0.3.3-blue)](Cargo.toml)

A terminal UI for device sync of portable music players, rewritten from scratch
in Rust on top of [ratatui](https://ratatui.rs/).

It mirrors the StorageBox masters library into your local music directory, then
syncs a device profile — the same pipeline as the Python `dap-sync`, now as a
living dashboard instead of a batch CLI.

![Dashboard](docs/screenshots/dashboard.png)

## Highlights

- **Tokyo Night** palette, rounded panels, gradient title rule, status & key
Expand All @@ -19,7 +25,8 @@ living dashboard instead of a batch CLI.
mode, warning/error counters).
- **Responsive layout** — short terminals drop the decorative sync-path card,
narrow cards switch to compact labels/values and ellipsize long paths
instead of clipping them mid-word.
instead of clipping them mid-word, and cards size to their own content
instead of stretching into dead space on a tall terminal.
- **Live sync engine** — streams `rclone` and `rsync` output, parses progress
(byte-weighted via `--info=progress2`), NFC-aware diffing for
macOS→FAT32/Android devices, optional `fatsort` finalize for Mlove devices.
Expand Down Expand Up @@ -60,6 +67,49 @@ dap-tui
| `?` / `h` | help overlay |
| `q` / `Esc` | quit |

## Manual

### Syncing a device

![Sync tab](docs/screenshots/sync.png)

Select a device in the **DEVICES** sidebar with `↑`/`↓` or `j`/`k`, then press
`s` or `Enter`. The Sync tab switches to a live step timeline — Mirror
StorageBox → Sync *device* → Finalize FAT (Mlove devices only) — with a
progress gauge showing percent complete, bytes transferred, speed and ETA. A
cloud mirror shows a "Scanning remote" phase first while rclone lists the
whole remote (`--check-first`) before any bytes move, so the percentage is a
true overall figure instead of a growing-total guess. Once a sync finishes,
the step timeline and its ✓/✗ outcomes stay on screen — press `s` again to
rerun.

### Mounting and unmounting

Press `m` on the selected device to mount or unmount it via **udisks2** — no
`sudo` required. Starting a sync on an unmounted device mounts it
automatically first; if that fails, dap-tui tells you to connect the device
and mount it (`m`), then retry. Mount state and the sync target are always
checked against the real kernel mount table (`/proc/self/mountinfo`), never
just whether the configured directory happens to exist, so a leftover empty
mount folder from an earlier unclean eject is never mistaken for a connected
device.

### Aborting

Press `a` while a sync is running to abort it: the whole child process group
(rclone, rsync, podkit, and anything they in turn spawned) is signalled to
terminate, escalating to a hard kill if it hasn't stopped within a couple of
seconds. Quitting (`q` / `Esc`) during an active sync runs the same abort
first, so closing dap-tui can never leave a sync running in the background.

### Following logs

Switch to the Logs tab (`3`, or `Tab`/`Shift-Tab`) for color-coded output —
info, file transfers, warnings and errors are each styled distinctly, with a
running warning/error count in the header. Press `f` to toggle follow mode
(auto-scroll to the newest line) on and off, `u`/`d` to scroll manually, and
`x` to clear the buffer.

## Configuration

`dap-tui` reads the standard `dap-sync` config format:
Expand Down Expand Up @@ -103,16 +153,19 @@ Firmware types: `apple` (podkit command), `rockbox`, `android`, `sony`

Devices are mounted/unmounted without sudo via **udisks2**:
`m` in the TUI mounts/unmounts the selected device, and a sync automatically
mounts the target first (resolved by mount-point label via `lsblk`). Only the
mlove `fatsort` step needs root (raw block device).
mounts the target first (resolved by mount-point label via `lsblk`, matched
case-insensitively). Only the mlove `fatsort` step needs root (raw block
device).

Mount status and sync targets are validated against the kernel mount table
(`/proc/self/mountinfo`), not just directory existence. The configured
`mount_point` is a hint: if udisks mounted the volume at a suffixed sibling
because the configured directory already existed (e.g. `IPOD` → `IPOD1`),
dap-tui follows the actual mount and uses it as the sync destination. If the
path exists but is not a mount at all, syncing into it is refused rather than
writing the library onto the root filesystem.
because the configured directory already existed (e.g. `IPOD` → `IPOD1`), or
under a different parent than configured (e.g. an automount service using
`/run/media/...` while the config says `/media/...`), dap-tui follows the
actual mount and uses it as the sync destination. If the path exists but is
not a mount at all, syncing into it is refused rather than writing the
library onto the root filesystem.

## Development

Expand Down
Binary file added docs/screenshots/dashboard.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/screenshots/sync.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
46 changes: 41 additions & 5 deletions src/disk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,17 +70,31 @@ pub fn mounted_path_for(path: &Path) -> Option<PathBuf> {
mounted_by_label(&base)
}

/// Find a mount point whose basename equals `label`, preferring the highest
/// mount (shortest path) so nested mounts do not shadow a real volume.
/// Find a mount point whose basename equals `label` case-insensitively,
/// preferring the highest mount (shortest path) so nested mounts do not
/// shadow a real volume.
fn mounted_by_label(label: &str) -> Option<PathBuf> {
pick_by_label(mount_points(), label)
}

/// ASCII case-insensitive (`eq_ignore_ascii_case`, not a full Unicode
/// case-fold — FAT32/vfat labels are effectively ASCII-only, so this is
/// cheaper than `udisks::resolve_block_device`'s `to_lowercase()` without
/// behaving differently for any label this codebase actually sees), so the
/// dashboard and the sync engine never disagree about whether a device is
/// mounted just because a udev/vfat label (commonly all-uppercase) doesn't
/// match a configured `mount_point` directory's case. Takes the mount list
/// as a parameter (rather than reading `/proc/self/mountinfo` itself) so
/// the matching logic is unit-testable without a real mount table.
fn pick_by_label(mounts: Vec<PathBuf>, label: &str) -> Option<PathBuf> {
if label.is_empty() {
return None;
}
let mut matches: Vec<PathBuf> = mount_points()
let mut matches: Vec<PathBuf> = mounts
.into_iter()
.filter(|mp| {
mp.file_name()
.map(|n| n.to_string_lossy() == label)
.map(|n| n.to_string_lossy().eq_ignore_ascii_case(label))
.unwrap_or(false)
})
.collect();
Expand Down Expand Up @@ -163,7 +177,29 @@ pub fn fmt_bytes(n: u64) -> String {

#[cfg(test)]
mod tests {
use super::{fmt_bytes, mounted_path_for, mount_suffix_rank, unescape_octal};
use super::{fmt_bytes, mounted_path_for, mount_suffix_rank, pick_by_label, unescape_octal};

#[test]
fn matches_mount_labels_case_insensitively() {
// A udev/vfat label is commonly all-uppercase (e.g. "IPOD") even when
// the configured mount_point directory is not — this must still
// resolve, mirroring udisks::resolve_block_device's own
// case-insensitive label lookup so the dashboard and the sync engine
// never disagree about whether a device is mounted.
let mounts = vec![
std::path::PathBuf::from("/media/sebastian/IPOD"),
std::path::PathBuf::from("/media/sebastian/OTHER"),
];
assert_eq!(
pick_by_label(mounts.clone(), "ipod"),
Some(std::path::PathBuf::from("/media/sebastian/IPOD"))
);
assert_eq!(
pick_by_label(mounts.clone(), "IPOD"),
Some(std::path::PathBuf::from("/media/sebastian/IPOD"))
);
assert_eq!(pick_by_label(mounts, "nope"), None);
}

#[test]
fn ranks_udisks_suffixed_mounts() {
Expand Down
56 changes: 43 additions & 13 deletions src/ui/components.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,14 +68,15 @@ pub fn key_hint(key: &str) -> Span<'static> {
// ── title bar ─────────────────────────────────────────────────────────────────

pub fn draw_title(f: &mut Frame, area: Rect, app: &App) {
let mut spans = vec![
Span::styled(
" dap-tui ",
Style::default()
.fg(theme::BG)
.bg(theme::ACCENT)
.add_modifier(Modifier::BOLD),
),
let brand = Span::styled(
" dap-tui ",
Style::default()
.fg(theme::BG)
.bg(theme::ACCENT)
.add_modifier(Modifier::BOLD),
);
let full_chain = vec![
brand.clone(),
Span::raw(" "),
Span::styled(
"StorageBox",
Expand Down Expand Up @@ -111,10 +112,22 @@ pub fn draw_title(f: &mut Frame, area: Rect, app: &App) {
),
];

// pad to full width
let left_w: usize = spans.iter().map(|s| s.width()).sum();
// pad to full width. The breadcrumb chain is decorative, so on a narrow
// terminal it is dropped first rather than letting it collide with the
// live mirror/sync status (the one thing here that is never safe to lose
// — padding used to saturate to 0 and run both halves together).
let right_w: usize = right_spans.iter().map(|s| s.width()).sum();
let total = area.width as usize;
let full_w: usize = full_chain.iter().map(|s| s.width()).sum();
let brand_w: usize = brand.width();
let mut spans = if full_w + right_w + 1 <= total {
full_chain
} else if brand_w + right_w + 1 <= total {
vec![brand]
} else {
Vec::new()
};
let left_w: usize = spans.iter().map(|s| s.width()).sum();
let pad = total.saturating_sub(left_w + right_w);
spans.push(Span::raw(" ".repeat(pad)));
spans.append(&mut right_spans);
Expand Down Expand Up @@ -383,10 +396,15 @@ pub fn draw_status(f: &mut Frame, area: Rect, app: &App) {
let total = area.width as usize;
let lw: usize = left_spans.iter().map(|s| s.width()).sum();
let rw: usize = right_spans.iter().map(|s| s.width()).sum();
let pad = total.saturating_sub(lw + rw);
let mut all = left_spans;
all.push(Span::raw(" ".repeat(pad)));
all.extend(right_spans);
// The device-count/version footer is secondary to the live status
// message on the left; drop it on a narrow terminal rather than letting
// the two halves collide with no separating space.
if lw + rw + 1 <= total {
let pad = total.saturating_sub(lw + rw);
all.push(Span::raw(" ".repeat(pad)));
all.extend(right_spans);
}

f.render_widget(
Paragraph::new(Line::from(all)).style(Style::default().bg(theme::BG_ALT)),
Expand Down Expand Up @@ -462,6 +480,18 @@ pub fn draw_keys(f: &mut Frame, area: Rect, _app: &App) {

// ── shared helpers ────────────────────────────────────────────────────────────

/// Vertically centre `lines` within a card `height` rows tall by padding
/// blank lines above. Dashboard cards size to the richest device/config
/// combination, so on a roomier terminal a sparser one (fewer devices, no
/// excludes, …) would otherwise sit glued to the top with a dead gap below;
/// centering reads as a deliberately framed card instead.
pub fn vcenter(lines: Vec<Line<'static>>, height: u16) -> Vec<Line<'static>> {
let pad = (height as usize).saturating_sub(lines.len()) / 2;
let mut out = vec![Line::raw(""); pad];
out.extend(lines);
out
}

pub fn step_icon(status: StepStatus, app: &App) -> Span<'static> {
match status {
StepStatus::Done => Span::styled("●", Style::default().fg(theme::GREEN)),
Expand Down
2 changes: 2 additions & 0 deletions src/ui/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,8 @@ mod tests {
dump_frame_sized(&app, "SYNC / FINISHED 80x24", 80, 24);
app.tab = crate::app::Tab::Dashboard;
dump_frame_sized(&app, "DASHBOARD 80x24", 80, 24);
dump_frame_sized(&app, "DASHBOARD 40x15", 40, 15);
dump_frame_sized(&app, "DASHBOARD 60x12", 60, 12);
}

#[test]
Expand Down
45 changes: 33 additions & 12 deletions src/ui/tabs/dashboard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::Paragraph;
use unicode_width::UnicodeWidthStr;

fn kv_w<'a>(label: &str, value: String, value_style: Style, label_w: usize) -> Line<'a> {
Line::from(vec![
Expand Down Expand Up @@ -56,9 +57,17 @@ pub fn draw(f: &mut Frame, area: Rect, app: &App) {

// Three stacked rows normally; drop the decorative SYNC PATH card when the
// terminal is too short for all cards to keep a content row.
//
// Row 1 (DEVICE/SETTINGS) is capped to its natural content height (8 =
// 2 border + up to 6 lines, the Apple-firmware worst case) instead of
// stretching with the terminal: on a tall terminal a `Min` row here used
// to leave most of the card empty below a handful of lines. Row 2
// (LIBRARY/SYNC STATUS) still grows to take the rest, but those cards
// vertically centre their own content so the extra space reads as
// deliberate framing instead of a dead trailing gap.
let (row1, row2, chain) = if area.height >= 19 {
let [r1, r2, ch] = Layout::vertical([
Constraint::Min(8),
Constraint::Length(8),
Constraint::Min(8),
Constraint::Length(3),
])
Expand Down Expand Up @@ -277,7 +286,6 @@ fn draw_settings_card(f: &mut Frame, area: Rect, device: &crate::config::Device)
Style::default().fg(theme::MAGENTA),
));
}
lines.push(Line::raw(""));
lines.push(Line::from(vec![
Span::raw(" "),
Span::styled(
Expand All @@ -304,7 +312,6 @@ fn draw_library_card(f: &mut Frame, area: Rect, app: &App) {
let mut lines = vec![
path_kv("music", &app.config.local_music_dir, value_w, lw),
path_kv("hoerspiele", &app.config.local_hoerspiele_dir, value_w, lw),
Line::raw(""),
];
let source_kv = |label: &str, source: &str, lines: &mut Vec<Line>| {
let path = std::path::Path::new(source);
Expand All @@ -331,13 +338,13 @@ fn draw_library_card(f: &mut Frame, area: Rect, app: &App) {
Style::default().fg(theme::DIM),
lw,
));
lines.push(Line::raw(""));
lines.push(kv_w(
"output",
truncate(&app.config.output_dir.display().to_string(), value_w),
Style::default().fg(theme::DIM),
lw,
));
let lines = crate::ui::components::vcenter(lines, inner.height);
f.render_widget(Paragraph::new(lines).style(Style::default().bg(theme::PANEL_BG)), inner);
}

Expand Down Expand Up @@ -406,13 +413,10 @@ fn draw_sync_status_card(f: &mut Frame, area: Rect, app: &App) {
lines.push(Line::from(spans));
}

// summary footer (two compact lines — the one-line variant used to end in
// an ugly "…" because the card is narrow)
lines.push(Line::raw(""));
lines.push(Line::from(Span::styled(
format!(" {ok} ok · {err} err · {never} never"),
Style::default().fg(theme::DIM),
)));
// One summary footer line (used to be two plus a blank separator, which
// ran off the bottom of a short card with several devices — the ok/err
// summary and the last-sync time are exactly the "state at a glance"
// this card exists for, so they must not be the part that gets clipped).
let last = app
.config
.devices
Expand All @@ -421,11 +425,28 @@ fn draw_sync_status_card(f: &mut Frame, area: Rect, app: &App) {
.min_by_key(|dt| now.signed_duration_since(*dt).num_seconds().max(0))
.map(relative_ago)
.unwrap_or_else(|| "—".to_string());
// Drop whole fields right-to-left rather than char-truncating when the
// card is too narrow for the full summary: a char-level ellipsis cut
// (e.g. "1 nev…") loses meaning mid-word, exactly the failure this line
// exists to avoid. Checked by display-cell width, not char count, so a
// future non-ASCII `last` string (relative_ago is ASCII-only today)
// can't misjudge the budget either.
let candidates = [
format!(" {ok} ok · {err} err · {never} never · last {last}"),
format!(" {ok} ok · {err} err · {never} never"),
format!(" {ok} ok · {err} err"),
format!(" {ok} ok"),
];
let footer = candidates
.into_iter()
.find(|c| c.width() <= inner.width as usize)
.unwrap_or_default();
lines.push(Line::from(Span::styled(
format!(" last sync {last}"),
footer,
Style::default().fg(theme::DIM),
)));

let lines = crate::ui::components::vcenter(lines, inner.height);
f.render_widget(Paragraph::new(lines).style(Style::default().bg(theme::PANEL_BG)), inner);
}

Expand Down
Loading