Add ability to listen to input
This commit is contained in:
66
src/mpv/mpv.gleam
Normal file
66
src/mpv/mpv.gleam
Normal file
@@ -0,0 +1,66 @@
|
||||
import gleam/erlang/process.{type Subject}
|
||||
import gleam/otp/actor
|
||||
import gleam/string
|
||||
|
||||
import mpv/internal.{type Key, Char}
|
||||
import tcp/reason.{type Reason}
|
||||
import tcp/tcp.{type Socket}
|
||||
|
||||
pub type Message {
|
||||
KeyPress(Key)
|
||||
}
|
||||
|
||||
type State(socket, exit) {
|
||||
State(socket: Socket, exit: Subject(Nil))
|
||||
}
|
||||
|
||||
pub fn new(exit: Subject(Nil)) -> Result(Nil, String) {
|
||||
// TODO start up mvp here, currently hi-jacking `naviterm`s socket
|
||||
let socket_path = "/tmp/naviterm_mpv"
|
||||
|
||||
case tcp.connect(socket_path) {
|
||||
Error(r) -> Error("Could not connect to mpv: " <> reason.to_string(r))
|
||||
Ok(socket) -> {
|
||||
case
|
||||
actor.new(State(socket, exit))
|
||||
|> actor.on_message(handle_message)
|
||||
|> actor.start
|
||||
{
|
||||
Error(start_error) ->
|
||||
Error("Could not start actor: " <> string.inspect(start_error))
|
||||
Ok(actor.Started(data:, ..)) -> {
|
||||
echo "waiting for input"
|
||||
internal.start_raw_shell()
|
||||
process.spawn(fn() { read_input(data) })
|
||||
Ok(Nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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")) -> {
|
||||
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, _)
|
||||
|
||||
read_input(subject)
|
||||
}
|
||||
Reference in New Issue
Block a user