Map Key to Control

This commit is contained in:
Alexander Heldt
2025-11-15 17:47:59 +01:00
parent 702313eac2
commit 94212996d2
6 changed files with 97 additions and 21 deletions

46
src/mpv/control.gleam Normal file
View File

@@ -0,0 +1,46 @@
import gleam/json
import gleam/result
import mpv/key.{type Key, Char}
import tcp/reason.{type Reason}
import tcp/tcp.{type Socket}
pub type Control {
TogglePlayPause
Exit
}
pub type ControlError {
ControlError(details: String)
}
pub fn from_key(key: Key) -> Result(Control, Nil) {
case key {
Char(char) -> char_control(char)
_ -> Error(Nil)
}
}
fn char_control(char: String) -> Result(Control, Nil) {
case char {
" " -> Ok(TogglePlayPause)
"q" -> Ok(Exit)
_ -> Error(Nil)
}
}
pub fn toggle_play_pause(socket: Socket) -> Result(Nil, ControlError) {
let command =
json.object([#("command", json.array(["cycle", "pause"], of: json.string))])
case send_command(socket, command) {
Error(r) -> Error(ControlError(reason.to_string(r)))
Ok(_) -> Ok(Nil)
}
}
fn send_command(socket: Socket, command: json.Json) -> Result(String, Reason) {
result.try(tcp.send(socket, json.to_string(command) <> "\n"), fn(_) {
let timeout_ms = 10_000
tcp.receive(socket, timeout_ms)
})
}