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
|
/*
* This file is a part of RSPlayer
* Licensed under the GPL-3.0 License
* Copyright (C) 2026 Salmonik @ salmonik@tuta.io
* https://codeberg.org/salmonik/RSPlayer
*/
//! Interactive control shell (`rsp ctl`), in the spirit of `bluetoothctl`.
//!
//! Every line is parsed with the same clap definitions as the one-shot CLI, so
//! the shell understands exactly the same commands (`play --now …`,
//! `volume +5`, `settings set …`) instead of keeping a second, drifting copy.
//! History is kept in the state directory, and Tab completes commands plus
//! track/album paths for `play`.
use crate::cli::Cli;
use clap::{CommandFactory, Parser};
use rustyline::completion::{Completer, Pair};
use rustyline::error::ReadlineError;
use rustyline::highlight::Highlighter;
use rustyline::hint::Hinter;
use rustyline::history::DefaultHistory;
use rustyline::validate::Validator;
use rustyline::{Context, Editor, Helper};
use std::io::IsTerminal;
use std::process::{Command, Stdio};
const PROMPT: &str = "rsp> ";
/// Commands the shell handles itself.
const LOCAL_COMMANDS: [&str; 5] = ["help", "quit", "exit", "clear", "?"];
struct CtlHelper {
commands: Vec<String>,
}
impl Default for CtlHelper {
fn default() -> Self {
let mut commands: Vec<String> = Cli::command()
.get_subcommands()
.map(|command| command.get_name().to_string())
.chain(LOCAL_COMMANDS.iter().map(|c| c.to_string()))
.collect();
commands.sort();
commands.dedup();
Self { commands }
}
}
impl Helper for CtlHelper {}
impl Highlighter for CtlHelper {}
impl Hinter for CtlHelper {
type Hint = String;
}
impl Validator for CtlHelper {}
impl Completer for CtlHelper {
type Candidate = Pair;
fn complete(
&self,
line: &str,
pos: usize,
_ctx: &Context<'_>,
) -> rustyline::Result<(usize, Vec<Pair>)> {
let before = &line[..pos];
let Some(start) = before.rfind(char::is_whitespace).map(|i| i + 1) else {
let prefix = before.to_string();
let matches = self
.commands
.iter()
.filter(|command| command.starts_with(&prefix))
.map(|command| Pair {
display: command.clone(),
replacement: command.clone(),
})
.collect();
return Ok((0, matches));
};
let word = &before[start..];
let command = before[..start].trim();
let matches = match command {
"play" | "play-album" => complete_music(word),
_ => Vec::new(),
};
Ok((start, matches))
}
}
/// Candidate tracks/albums for the current prefix, from `rsp db-complete`.
///
/// Completion runs out of process on purpose: `db-complete` already applies the
/// 100 ms database timeout and the filesystem fallback, so a slow or missing
/// index cannot hang the shell's input loop.
fn complete_music(prefix: &str) -> Vec<Pair> {
let Ok(exe) = std::env::current_exe() else {
return Vec::new();
};
let Ok(output) = Command::new(exe)
.arg("db-complete")
.arg(prefix)
.stderr(Stdio::null())
.output()
else {
return Vec::new();
};
String::from_utf8_lossy(&output.stdout)
.lines()
.map(str::trim)
.filter(|candidate| !candidate.is_empty())
// The CLI escapes spaces for shells; the shell's own reader needs the
// real text back and re-quotes it below.
.map(unescape)
.map(|candidate| Pair {
display: candidate.clone(),
replacement: quote(&candidate),
})
.collect()
}
/// Undo the shell escaping `rsp db-complete` applies.
fn unescape(candidate: &str) -> String {
let mut out = String::with_capacity(candidate.len());
let mut chars = candidate.chars();
while let Some(c) = chars.next() {
if c == '\\' {
if let Some(next) = chars.next() {
out.push(next);
}
} else {
out.push(c);
}
}
out
}
/// Quote a candidate that contains spaces, so it stays one argument.
fn quote(candidate: &str) -> String {
if candidate.contains(char::is_whitespace) {
format!("'{}'", candidate.replace('\'', r"'\''"))
} else {
candidate.to_string()
}
}
/// Split a command line into arguments, honouring quotes and backslash
/// escapes so that track names with spaces survive.
fn split_args(line: &str) -> Vec<String> {
let mut args = Vec::new();
let mut current = String::new();
let mut quote: Option<char> = None;
let mut in_word = false;
let mut chars = line.chars();
while let Some(c) = chars.next() {
match quote {
Some(q) => {
if c == q {
quote = None;
} else if c == '\\' && q == '"' {
current.extend(chars.next());
} else {
current.push(c);
}
}
None => match c {
'\'' | '"' => {
quote = Some(c);
in_word = true;
}
'\\' => {
current.extend(chars.next());
in_word = true;
}
c if c.is_whitespace() => {
if in_word {
args.push(std::mem::take(&mut current));
in_word = false;
}
}
c => {
current.push(c);
in_word = true;
}
},
}
}
if in_word {
args.push(current);
}
args
}
enum Step {
Continue,
Quit,
}
fn dispatch(line: &str) -> Result<Step, Box<dyn std::error::Error>> {
let mut args = split_args(line);
let Some(command) = args.first().cloned() else {
return Ok(Step::Continue);
};
match command.as_str() {
"quit" | "exit" | "q" => return Ok(Step::Quit),
"clear" => {
print!("\x1b[2J\x1b[H");
return Ok(Step::Continue);
}
"help" | "?" => {
let mut cli = Cli::command();
match args.get(1).and_then(|name| cli.find_subcommand_mut(name)) {
Some(subcommand) => {
subcommand.print_help()?;
println!();
}
None => {
cli.print_help()?;
println!();
}
}
return Ok(Step::Continue);
}
// These replace or block the process the shell runs in.
"start-daemon" | "ctl" => {
return Err(format!(
"`{}` would take over the shell — run it from a normal terminal",
command
)
.into());
}
_ => {}
}
args.insert(0, "rsp".to_string());
match Cli::try_parse_from(args) {
Ok(cli) => cli.run()?,
Err(e)
if matches!(
e.kind(),
clap::error::ErrorKind::DisplayHelp | clap::error::ErrorKind::DisplayVersion
) =>
{
print!("{}", e);
}
Err(e) => eprintln!("{}", e.render()),
}
Ok(Step::Continue)
}
pub fn run() -> Result<(), Box<dyn std::error::Error>> {
if !std::io::stdin().is_terminal() {
return run_piped();
}
let history_path = crate::config::runtime_dir().join("ctl_history");
let mut editor: Editor<CtlHelper, DefaultHistory> = Editor::default()?;
let _ = editor.load_history(&history_path);
if !crate::config::Config::get_socket_path().exists() {
eprintln!("note: no daemon socket — start it with `start-daemon` or the service");
}
println!("RSPlayer control shell — `help` lists commands, `quit` leaves.");
loop {
match editor.readline(PROMPT) {
Ok(line) => {
let line = line.trim().to_string();
if line.is_empty() {
continue;
}
let _ = editor.add_history_entry(line.as_str());
match dispatch(&line) {
Ok(Step::Continue) => {}
Ok(Step::Quit) => break,
Err(e) => eprintln!("Error: {}", e),
}
}
// Ctrl-C drops the line, Ctrl-D leaves.
Err(ReadlineError::Interrupted) => continue,
Err(ReadlineError::Eof) => break,
Err(e) => {
eprintln!("Input error: {}", e);
break;
}
}
}
let _ = editor.save_history(&history_path);
Ok(())
}
/// Same commands without an editor, for pipes and scripts
/// (`rsp ctl < commands.txt`), where rustyline has no terminal to drive.
fn run_piped() -> Result<(), Box<dyn std::error::Error>> {
use std::io::BufRead;
for line in std::io::stdin().lock().lines() {
match dispatch(line?.trim()) {
Ok(Step::Continue) => {}
Ok(Step::Quit) => break,
Err(e) => eprintln!("Error: {}", e),
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use clap::Parser;
#[test]
fn splits_plain_and_quoted_arguments() {
assert_eq!(split_args("seek 1:30"), vec!["seek", "1:30"]);
assert_eq!(
split_args("play 'Some Album/01 Track.mp3'"),
vec!["play", "Some Album/01 Track.mp3"]
);
assert_eq!(
split_args(r#"play "A \"quoted\" name""#),
vec!["play", r#"A "quoted" name"#]
);
assert_eq!(split_args(" status "), vec!["status"]);
assert!(split_args(" ").is_empty());
}
#[test]
fn quoted_arguments_round_trip_through_the_cli() {
let args = split_args("seek +15");
let mut full = vec!["rsp".to_string()];
full.extend(args);
let cli = Cli::try_parse_from(full).expect("seek +15 is a valid command");
assert!(matches!(cli.command, crate::cli::Commands::Seek { .. }));
}
#[test]
fn quotes_single_word_arguments_only_when_needed() {
assert_eq!(quote("AFX"), "AFX");
assert_eq!(
quote("Analogue Bubblebath, Vol 3.1"),
"'Analogue Bubblebath, Vol 3.1'"
);
}
#[test]
fn completes_command_names() {
let helper = CtlHelper::default();
for expected in ["play", "seek", "settings", "status", "quit"] {
assert!(
helper.commands.iter().any(|c| c == expected),
"completion is missing `{}`",
expected
);
}
}
}
|