46 lines
1.1 KiB
Go
46 lines
1.1 KiB
Go
|
|
package media
|
||
|
|
|
||
|
|
import (
|
||
|
|
"github.com/creack/pty"
|
||
|
|
"golang.org/x/term"
|
||
|
|
"io"
|
||
|
|
"os"
|
||
|
|
"os/exec"
|
||
|
|
"os/signal"
|
||
|
|
"syscall"
|
||
|
|
)
|
||
|
|
|
||
|
|
func Watch(path string) {
|
||
|
|
cmd := exec.Command("mpv", "--osd-fractions", "--term-osd=force", path)
|
||
|
|
ptmx, err := pty.Start(cmd)
|
||
|
|
|
||
|
|
if err != nil {
|
||
|
|
panic(err)
|
||
|
|
}
|
||
|
|
// Make sure to close the pty at the end.
|
||
|
|
defer func() { ptmx.Close() }() // Best effort.
|
||
|
|
|
||
|
|
// Handle pty size.
|
||
|
|
ch := make(chan os.Signal, 1)
|
||
|
|
signal.Notify(ch, syscall.SIGWINCH)
|
||
|
|
go func() {
|
||
|
|
for range ch {
|
||
|
|
pty.InheritSize(os.Stdin, ptmx)
|
||
|
|
}
|
||
|
|
}()
|
||
|
|
ch <- syscall.SIGWINCH // Initial resize.
|
||
|
|
defer func() { signal.Stop(ch); close(ch) }() // Cleanup signals when done.
|
||
|
|
|
||
|
|
// Set stdin in raw mode.
|
||
|
|
oldState, err := term.MakeRaw(int(os.Stdin.Fd()))
|
||
|
|
if err != nil {
|
||
|
|
panic(err)
|
||
|
|
}
|
||
|
|
defer func() { term.Restore(int(os.Stdin.Fd()), oldState) }() // Best effort.
|
||
|
|
|
||
|
|
// Copy stdin to the pty and the pty to stdout.
|
||
|
|
// NOTE: The goroutine will keep reading until the next keystroke before returning.
|
||
|
|
go func() { io.Copy(ptmx, os.Stdin) }()
|
||
|
|
io.Copy(os.Stdout, ptmx)
|
||
|
|
}
|