Map Key to Control
This commit is contained in:
46
src/mpv/control.gleam
Normal file
46
src/mpv/control.gleam
Normal 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)
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user