Map Key to Control

This commit is contained in:
Alexander Heldt
2025-11-15 17:47:59 +01:00
parent ebdba09bc2
commit 4c8fb9a8f9
3 changed files with 51 additions and 21 deletions

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

@@ -0,0 +1,27 @@
import mpv/internal.{type Key}
import tcp/reason.{type Reason}
import tcp/tcp.{type Socket}
pub type Control {
TogglePlayPause
Exit
}
pub fn from_key(key: Key) -> Result(Control, Nil) {
case key {
internal.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, Reason) {
tcp.send(socket, "{\"command\":[\"cycle\",\"pause\"]}\n")
}

View File

@@ -41,7 +41,6 @@ pub fn start_raw_shell() {
shell_start_interactive(#(no_shell, raw))
}
// TODO map key to something like Control, to not leak `Continue` etc.
pub fn read_input_until_key(l: List(String)) -> Key {
let l = read_input() |> list.wrap |> list.append(l, _)

View File

@@ -1,15 +1,13 @@
import gleam/erlang/process.{type Subject}
import gleam/otp/actor
import gleam/result
import gleam/string
import mpv/internal.{type Key, Char}
import tcp/reason.{type Reason}
import mpv/control.{type Control}
import mpv/internal
import tcp/reason
import tcp/tcp.{type Socket}
pub type Message {
KeyPress(Key)
}
type State(socket, exit) {
State(socket: Socket, exit: Subject(Nil))
}
@@ -39,28 +37,34 @@ pub fn new(exit: Subject(Nil)) -> Result(Nil, String) {
}
}
pub fn toggle_play_pause(socket: Socket) -> Result(Nil, Reason) {
tcp.send(socket, "{\"command\":[\"cycle\",\"pause\"]}\n")
}
fn handle_message(
state: State(socket, exit),
message: Message,
) -> actor.Next(State(socket, exit), Message) {
case message {
KeyPress(Char("q")) -> {
control: Control,
) -> actor.Next(State(socket, exit), Control) {
case control {
control.TogglePlayPause -> {
echo "toggling play/pause"
let _ =
result.map_error(control.toggle_play_pause(state.socket), fn(r) {
echo "Could not toggle play/pause: " <> reason.to_string(r)
})
actor.continue(state)
}
control.Exit -> {
process.send(state.exit, Nil)
actor.stop()
}
KeyPress(key) -> {
echo "key: " <> string.inspect(key)
actor.continue(state)
}
}
}
fn read_input(subject: Subject(Message)) -> Nil {
internal.read_input_until_key([]) |> KeyPress |> process.send(subject, _)
fn read_input(subject: Subject(Control)) -> Nil {
case
internal.read_input_until_key([])
|> control.from_key
{
Error(_) -> Nil
Ok(control) -> process.send(subject, control)
}
read_input(subject)
}