playr 0.14.0

A minimal TUI music player that plays local files and contacts nothing
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
//! playr: a minimal TUI music player.

use std::io::IsTerminal;
use std::path::PathBuf;
use std::process::ExitCode;

mod analyze;

use playr_app::config::Program;

use clap::{Parser, Subcommand};
use playr::ui;
use playr_core::audio::Player;
use playr_core::db::{self, Track};
use playr_core::m3u;
use playr_core::scan;

/// playr - a minimal TUI music player
///
/// With no command, browses the library; with paths, plays them.
#[derive(Parser)]
#[command(
    version,
    // Each subcommand name is a file `playr <path>` cannot play; `help` need not be one.
    disable_help_subcommand = true,
    override_usage = "playr [OPTIONS] [PATHS]...\n       playr [OPTIONS] <COMMAND>"
)]
struct Cli {
    /// Files or directories to play; directories are played recursively
    paths: Vec<PathBuf>,

    /// Use a different library file
    #[arg(long, global = true, value_name = "PATH")]
    db: Option<PathBuf>,

    /// Use a different settings file
    #[arg(long, global = true, value_name = "PATH")]
    settings: Option<PathBuf>,

    /// Play to this output device instead of the default, overriding the
    /// device setting; `playr devices` lists them
    #[arg(long, value_name = "ID")]
    device: Option<String>,

    #[command(subcommand)]
    command: Option<Command>,
}

#[derive(Subcommand)]
enum Command {
    /// Add directories to the library, creating it if there is none
    Scan {
        /// Directories to scan, recursively. With none, re-scans those recorded.
        #[arg(value_name = "DIR")]
        dirs: Vec<PathBuf>,
    },
    /// List the directories the library covers, or change them
    Roots {
        #[command(subcommand)]
        op: Option<RootsOp>,
    },
    /// Remove tracks under directories whose files are gone, with their marks
    Prune {
        /// Directories to check. With none, checks every directory previously scanned.
        #[arg(value_name = "DIR")]
        dirs: Vec<PathBuf>,
    },
    /// Play everything matching a search; put a query that starts with - after --
    Search {
        /// Print the matches as a JSON array instead of playing them
        #[arg(long)]
        json: bool,
        /// Words to match, as in the / prompt; field:word matches one field
        #[arg(required = true, value_name = "QUERY")]
        query: Vec<String>,
    },
    /// Play a saved playlist
    Playlist {
        /// The playlist's name; quotes are optional
        #[arg(required = true, value_name = "NAME")]
        name: Vec<String>,
    },
    /// List saved playlists
    Playlists,
    /// Write a saved playlist as an M3U8 file, or to stdout with no FILE
    Export {
        /// The playlist's name; quote it if it has spaces
        name: String,
        /// Where to write it
        file: Option<PathBuf>,
        /// Replace FILE if it exists
        #[arg(long)]
        force: bool,
    },
    /// Save M3U or M3U8 files as playlists; tracks not in the library are
    /// left out and listed
    Import {
        #[arg(required = true, value_name = "FILE")]
        files: Vec<PathBuf>,
        /// The playlist's name, for one file; else its #PLAYLIST line or its
        /// file name
        #[arg(long)]
        name: Option<String>,
    },
    /// Show which formats this build can decode
    Formats,
    /// List output devices, by the ID --device and the device setting take
    Devices,
    /// Decode library tracks once, recording checks, loudness and tempo;
    /// files are only read. Runs beside a playing playr
    Analyze {
        /// Files or directories in the library. With none, every track.
        #[arg(value_name = "PATH")]
        paths: Vec<PathBuf>,
        /// Analyse tracks again even when nothing changed since
        #[arg(long)]
        force: bool,
        /// Print what is recorded, decoding nothing
        #[arg(long)]
        report: bool,
        /// Print the findings as JSON
        #[arg(long)]
        json: bool,
        /// Files to decode at once; the default leaves one processor free
        #[arg(long, value_name = "N")]
        jobs: Option<usize>,
    },
}

#[derive(Subcommand)]
enum RootsOp {
    /// Record a directory and scan it, as `playr scan DIR` does
    Add {
        #[arg(required = true, value_name = "DIR")]
        dirs: Vec<PathBuf>,
    },
    /// Forget a directory, and the tracks and marks under it
    Rm {
        #[arg(required = true, value_name = "DIR")]
        dirs: Vec<PathBuf>,
    },
}

fn main() -> ExitCode {
    let cli = Cli::parse();
    match run(cli) {
        Ok(code) => code,
        Err(e) => {
            eprintln!("playr: {e}");
            ExitCode::FAILURE
        }
    }
}

fn run(cli: Cli) -> Result<ExitCode, Box<dyn std::error::Error>> {
    // Read whatever the command, so a bad file is seen early. Only playback
    // uses it; a command that does not warns and runs, so scripts still work.
    let plays = matches!(
        cli.command,
        None | Some(Command::Search { json: false, .. } | Command::Playlist { .. })
    );
    let config = match (&cli.settings, playr_app::config::default_path()) {
        (Some(path), _) => playr_app::config::Config::load_for(Program::Terminal, path, true),
        (None, Some(path)) => playr_app::config::Config::load_for(Program::Terminal, &path, false),
        (None, None) => Ok(playr_app::config::Config::default()),
    };
    let config = match config {
        Ok(config) => config,
        Err(errors) => {
            let label = if plays { "playr" } else { "playr: warning" };
            for e in errors {
                eprintln!("{label}: {e}");
            }
            if plays {
                return Ok(ExitCode::FAILURE);
            }
            playr_app::config::Config::default()
        }
    };

    if let Some(Command::Formats) = cli.command {
        print_formats();
        return Ok(ExitCode::SUCCESS);
    }
    if let Some(Command::Devices) = cli.command {
        print_devices()?;
        return Ok(ExitCode::SUCCESS);
    }

    // One playr at a time, terminal or window; reading the library needs no
    // claim. Held until `run` returns.
    // `analyze` writes only its own tables, which no running playr caches.
    let reads_only = matches!(
        cli.command,
        Some(
            Command::Playlists
                | Command::Export { .. }
                | Command::Search { json: true, .. }
                | Command::Roots { op: None }
                | Command::Analyze { .. }
        )
    );
    let _instance = if reads_only {
        None
    } else {
        Some(playr_app::instance::claim()?)
    };

    // Only `scan` creates the library. Without one, everything else runs on an
    // empty in-memory library, so playing a file leaves nothing behind.
    let db_path = cli.db.unwrap_or_else(db::default_path);
    let scanning = matches!(
        cli.command,
        Some(
            Command::Scan { .. }
                | Command::Roots {
                    op: Some(RootsOp::Add { .. })
                }
        )
    );
    if matches!(
        cli.command,
        Some(
            Command::Prune { .. }
                | Command::Analyze { .. }
                | Command::Export { .. }
                | Command::Import { .. }
                | Command::Roots {
                    op: None | Some(RootsOp::Rm { .. })
                }
        )
    ) && !db_path.try_exists()?
    {
        return Err(format!("no library at {}", db_path.display()).into());
    }
    // A bare `playr scan` covers the recorded roots, and without a library
    // there are none. Checked before the library is opened, which would
    // otherwise leave an empty file behind. `prune` already returned above.
    if let Some(Command::Scan { ref dirs }) = cli.command {
        if dirs.is_empty() && !db_path.try_exists()? {
            eprintln!("{NO_SCAN_DIRS}");
            return Ok(ExitCode::FAILURE);
        }
    }
    let mut conn = if scanning || db_path.try_exists()? {
        db::open(&db_path)?
    } else {
        db::open_memory()?
    };

    // Everything else opens the interface, with tracks chosen by the arguments.
    let start: Vec<Track> = match cli.command {
        Some(Command::Formats | Command::Devices) => unreachable!("handled above"),
        Some(Command::Scan { dirs }) => return cmd_scan(&mut conn, &dirs),
        // `roots add` is `scan`: recording a root without scanning it would
        // leave a root the library holds nothing for.
        Some(Command::Roots {
            op: Some(RootsOp::Add { dirs }),
        }) => return cmd_scan(&mut conn, &dirs),
        Some(Command::Roots {
            op: Some(RootsOp::Rm { dirs }),
        }) => return cmd_forget(&conn, &dirs),
        Some(Command::Roots { op: None }) => {
            for root in db::roots(&conn)? {
                println!("{}", root.display());
            }
            return Ok(ExitCode::SUCCESS);
        }
        Some(Command::Prune { dirs }) => return cmd_prune(&conn, &dirs),
        Some(Command::Analyze {
            paths,
            force,
            report,
            json,
            jobs,
        }) => {
            let opts = analyze::Options {
                paths,
                force,
                report,
                json,
                jobs,
            };
            return analyze::run(&mut conn, opts);
        }
        Some(Command::Playlists) => {
            for p in db::query::playlists(&conn)? {
                println!("{:<40} {:>4} tracks", p.name, p.len);
            }
            return Ok(ExitCode::SUCCESS);
        }
        Some(Command::Export { name, file, force }) => {
            return cmd_export(&conn, &name, file.as_deref(), force)
        }
        Some(Command::Import { files, name }) => return cmd_import(&mut conn, &files, name),
        Some(Command::Search { json, query }) => {
            let q = query.join(" ");
            if q.trim().is_empty() {
                return Err("search needs a query".into());
            }
            let hits = db::query::search(&conn, &q)?;
            if json {
                // `[]` for no matches, so a script can always parse the output.
                println!("{}", tracks_json(&hits));
                return Ok(if hits.is_empty() {
                    ExitCode::FAILURE
                } else {
                    ExitCode::SUCCESS
                });
            }
            if hits.is_empty() {
                eprintln!("playr: nothing matches {q:?}");
                return Ok(ExitCode::FAILURE);
            }
            hits
        }
        Some(Command::Playlist { name }) => {
            let name = name.join(" ");
            let lists = db::query::playlists(&conn)?;
            let pl = db::query::find_playlist(&lists, name.trim())
                .ok_or_else(|| format!("no single playlist named {name:?}"))?;
            db::query::playlist_tracks(&conn, pl.id)?
        }
        None if cli.paths.is_empty() => Vec::new(),
        None => collect_paths(&conn, &cli.paths)?,
    };

    // crossterm opens /dev/tty when stdin is not a terminal, so only stdout
    // shows whether the interface can be seen. Checked before the device opens.
    if !std::io::stdout().is_terminal() {
        return Err("playr needs a terminal: stdout is not one".into());
    }
    let player = Player::new(cli.device.as_deref().or(config.settings.device.as_deref()))?;

    // `ratatui::init` panics without a terminal; report it instead, since
    // running playr from a pipe or a service is an easy mistake to make.
    let mut terminal = ratatui::try_init().map_err(|e| format!("playr needs a terminal: {e}"))?;
    let mut app = ui::App::configured(conn, player, start, config);
    // crossterm drops colour under NO_COLOR (https://no-color.org) with an SGR
    // reset, which also clears the cursor row's reverse video, so playr drops it.
    app.set_colour(std::env::var_os("NO_COLOR").is_none_or(|v| v.is_empty()));
    ratatui::crossterm::style::force_color_output(true);
    // `:scan` creates the library here when there is none yet.
    app.set_library_path(db_path);
    // The terminal and the window gain media keys together, under the parity
    // rule in docs/dev/gui.md.
    app.attach_media();
    let result = app.run(&mut terminal);
    ratatui::restore();
    result?;
    Ok(ExitCode::SUCCESS)
}

/// Writes playlist `name` as M3U8 to `file`, or to stdout.
fn cmd_export(
    conn: &rusqlite::Connection,
    name: &str,
    file: Option<&std::path::Path>,
    force: bool,
) -> Result<ExitCode, Box<dyn std::error::Error>> {
    let lists = db::query::playlists(conn)?;
    let pl = db::query::find_playlist(&lists, name.trim())
        .ok_or_else(|| format!("no single playlist named {name:?}"))?;
    let tracks = db::query::playlist_tracks(conn, pl.id)?;
    let (text, left_out) = m3u::write(&pl.name, &tracks);
    if left_out > 0 {
        eprintln!("playr: {left_out} tracks left out: their paths hold a line break");
    }
    match file {
        None => print!("{text}"),
        Some(file) => {
            // Not `write`, which would replace a file the user may not mean to lose.
            let mut out = std::fs::OpenOptions::new();
            match force {
                true => out.write(true).create(true).truncate(true),
                false => out.write(true).create_new(true),
            };
            let mut out = out.open(file).map_err(|e| match e.kind() {
                std::io::ErrorKind::AlreadyExists => {
                    format!("{} exists; --force replaces it", file.display())
                }
                _ => format!("{}: {e}", file.display()),
            })?;
            std::io::Write::write_all(&mut out, text.as_bytes())
                .map_err(|e| format!("{}: {e}", file.display()))?;
        }
    }
    Ok(ExitCode::SUCCESS)
}

/// Saves each M3U file as a playlist. A name already taken is refused, so
/// no playlist is replaced. Fails if any file is not saved.
fn cmd_import(
    conn: &mut rusqlite::Connection,
    files: &[PathBuf],
    name: Option<String>,
) -> Result<ExitCode, Box<dyn std::error::Error>> {
    if name.is_some() && files.len() > 1 {
        return Err("--name names one playlist; import one file with it".into());
    }
    let mut failed = false;
    for file in files {
        let shown = file.display();
        let text = match std::fs::read(file) {
            // An `.m3u` may be in a legacy encoding; its paths read as best they can.
            Ok(bytes) => String::from_utf8_lossy(&bytes).into_owned(),
            Err(e) => {
                eprintln!("playr: {shown}: {e}");
                failed = true;
                continue;
            }
        };
        let dir = file.parent().unwrap_or(std::path::Path::new("."));
        let (tracks, missing) = m3u::resolve(conn, &m3u::paths(&text, dir))?;
        let stem = file.file_stem().map(|s| s.to_string_lossy().into_owned());
        let Some(title) = name.clone().or_else(|| m3u::name(&text)).or(stem) else {
            eprintln!("playr: {shown}: no name; give one with --name");
            failed = true;
            continue;
        };
        let lists = db::query::playlists(conn)?;
        if lists.iter().any(|p| p.name == title) {
            eprintln!("playr: {shown}: a playlist named {title:?} exists; --name gives another");
            failed = true;
            continue;
        }
        if tracks.is_empty() {
            eprintln!(
                "playr: {shown}: none of its {} tracks is in the library",
                missing.len()
            );
            failed = true;
            continue;
        }
        let ids: Vec<i64> = tracks.iter().map(|t| t.id).collect();
        db::query::save_playlist(conn, &title, &ids)?;
        println!("saved {title:?}, {} tracks", ids.len());
        if !missing.is_empty() {
            println!("  {} not in the library, left out:", missing.len());
            for path in &missing {
                println!("  {}", path.display());
            }
        }
    }
    Ok(if failed {
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    })
}

/// `tracks` as a JSON array of objects, one field per library column, with
/// `null` for a tag the file lacks.
fn tracks_json(tracks: &[Track]) -> String {
    let rows: Vec<serde_json::Value> = tracks
        .iter()
        .map(|t| {
            serde_json::json!({
                "id": t.id,
                "path": t.path,
                "title": t.title,
                "artist": t.artist,
                "album": t.album,
                "album_artist": t.album_artist,
                "track_no": t.track_no,
                "disc_no": t.disc_no,
                "year": t.year,
                "genre": t.genre,
                "duration_ms": t.duration_ms,
                "sample_rate": t.sample_rate,
                "channels": t.channels,
                "bit_depth": t.bit_depth,
                "mtime": t.mtime,
                "size": t.size,
            })
        })
        .collect();
    serde_json::Value::Array(rows).to_string()
}

/// Refusing a bare `playr scan`, from `run` before the library is opened and
/// from `cmd_scan` once it is.
const NO_SCAN_DIRS: &str = "playr: no directories to scan; give one, as `playr scan DIR`";

fn cmd_scan(
    conn: &mut rusqlite::Connection,
    dirs: &[PathBuf],
) -> Result<ExitCode, Box<dyn std::error::Error>> {
    let recorded;
    let dirs = if dirs.is_empty() {
        recorded = db::roots(conn)?;
        if recorded.is_empty() {
            eprintln!("{NO_SCAN_DIRS}");
            return Ok(ExitCode::FAILURE);
        }
        recorded.as_slice()
    } else {
        dirs
    };
    let mut total = scan::ScanStats::default();
    let multi = dirs.len() > 1;
    for path in dirs {
        if !path.is_dir() {
            eprintln!("playr: not a directory: {}", path.display());
            continue;
        }
        println!("scanning {}", path.display());
        let stats = scan::scan_dir(conn, path, |s, p| {
            // Overwrite one line rather than scrolling a wall of filenames.
            if s.seen % 25 == 0 {
                let name = p
                    .file_name()
                    .map(|n| n.to_string_lossy())
                    .unwrap_or_default();
                print!("\r  {} files, {} added  {:<40.40}", s.seen, s.added, name);
                use std::io::Write;
                let _ = std::io::stdout().flush();
            }
        })?;
        if stats.seen > 0 {
            db::add_root(conn, path)?;
        }
        println!(
            "\r  {} files, {} added, {} unchanged, {} unreadable{:<20}",
            stats.seen, stats.added, stats.skipped, stats.failed, ""
        );
        total.seen += stats.seen;
        total.added += stats.added;
        total.skipped += stats.skipped;
        total.failed += stats.failed;
        let missing = db::missing_under(conn, path)?.len();
        if missing > 0 {
            let path = path.display();
            println!("  {missing} tracks missing; `playr prune {path}` removes them");
        }
    }
    if multi {
        println!(
            "total: {} files, {} added, {} unchanged, {} unreadable",
            total.seen, total.added, total.skipped, total.failed
        );
    }
    println!("library now holds {} tracks", db::query::count(conn)?);
    // The interface can analyse as it scans, with `analyze_on_scan`; here the
    // settings are not read, so say what is waiting instead.
    let waiting = playr_core::analysis::pending(conn, &db::query::all(conn)?)?.len();
    if waiting > 0 {
        println!("  {waiting} tracks not analysed; `playr analyze` measures them");
    }
    Ok(ExitCode::SUCCESS)
}

fn cmd_prune(
    conn: &rusqlite::Connection,
    dirs: &[PathBuf],
) -> Result<ExitCode, Box<dyn std::error::Error>> {
    let recorded;
    let dirs = if dirs.is_empty() {
        recorded = db::roots(conn)?;
        if recorded.is_empty() {
            eprintln!("playr: no directories to prune; give one, or scan one first");
            return Ok(ExitCode::FAILURE);
        }
        recorded.as_slice()
    } else {
        dirs
    };
    for path in dirs {
        if !path.is_dir() {
            eprintln!("playr: not a directory: {}", path.display());
            continue;
        }
        let pruned = db::prune_missing(conn, path)?;
        println!(
            "pruning {}: removed {} tracks and {} marks of missing files",
            path.display(),
            pruned.tracks,
            pruned.marks
        );
    }
    println!("library now holds {} tracks", db::query::count(conn)?);
    Ok(ExitCode::SUCCESS)
}

/// Forgets each root named, with the tracks and marks under it. A path that
/// is not a root is reported and the rest still run.
fn cmd_forget(
    conn: &rusqlite::Connection,
    dirs: &[PathBuf],
) -> Result<ExitCode, Box<dyn std::error::Error>> {
    let mut code = ExitCode::SUCCESS;
    for path in dirs {
        match db::forget_root(conn, path)? {
            Some(removed) => println!(
                "forgot {}: removed {} tracks and {} marks",
                path.display(),
                removed.tracks,
                removed.marks
            ),
            None => {
                eprintln!(
                    "playr: not one of the library's directories: {}",
                    path.display()
                );
                code = ExitCode::FAILURE;
            }
        }
    }
    println!("library now holds {} tracks", db::query::count(conn)?);
    Ok(code)
}

/// The tracks the paths on the command line name, with each problem reported.
fn collect_paths(
    conn: &rusqlite::Connection,
    paths: &[PathBuf],
) -> Result<Vec<Track>, Box<dyn std::error::Error>> {
    let found = scan::playable(paths, |key| db::query::by_path(conn, key).ok().flatten());
    for problem in &found.problems {
        eprintln!("playr: {problem}");
    }
    if found.tracks.is_empty() {
        return Err("nothing playable in those paths".into());
    }
    Ok(found.tracks)
}

fn print_formats() {
    let opus = cfg!(feature = "opus");
    println!("containers: WAV, AIFF, CAF, ISO/MP4 (m4a), MKV/WebM, OGG, FLAC, ADTS");
    print!("codecs:     FLAC, ALAC, MP1/MP2/MP3, AAC-LC, Vorbis, PCM, ADPCM");
    println!("{}", if opus { ", Opus" } else { "" });
    println!();
    if opus {
        println!("Opus is decoded by playr itself, in OGG and WebM; Symphonia 0.6");
        println!("demuxes it but ships no decoder. Mono and stereo only.");
    } else {
        println!("Opus is NOT in this build. It needs libopus, which needs cmake,");
        println!("so it is opt-in. To add it:");
        println!();
        println!("    cargo build --release --features opus");
    }
    println!();
    print!("not decodable: ");
    if !opus {
        print!("Opus, ");
    }
    println!("WavPack, WMA, Musepack, APE, DSD, TTA, TAK.");
    println!("playr reports such files and moves to the next track.");
}

/// One output device a line, its ID then its name, with the default marked `*`.
fn print_devices() -> Result<(), Box<dyn std::error::Error>> {
    let devices = playr_core::audio::output::devices()?;
    let width = devices.iter().map(|d| d.id.len()).max().unwrap_or(0);
    for d in &devices {
        let mark = if d.default { '*' } else { ' ' };
        println!("{mark} {:<width$}  {}", d.id, d.name);
    }
    Ok(())
}