From bc67e3896b08f35e3df6f63b759adcb3a96d3b3d Mon Sep 17 00:00:00 2001 From: Christian Muehlhaeuser Date: Sat, 25 Jan 2020 07:15:29 +0100 Subject: [PATCH] Add platform-specific terminal init & restore --- tea.go | 18 ++++-------------- tty_unix.go | 28 ++++++++++++++++++++++++++++ tty_windows.go | 12 ++++++++++++ 3 files changed, 44 insertions(+), 14 deletions(-) create mode 100644 tty_unix.go create mode 100644 tty_windows.go diff --git a/tea.go b/tea.go index e37b4f0..2eb44d6 100644 --- a/tea.go +++ b/tea.go @@ -6,8 +6,6 @@ import ( "log" "log/syslog" "strings" - - "github.com/pkg/term" ) // Msg represents an action. It's used by Update to update the UI. @@ -39,7 +37,6 @@ type Program struct { update Update view View subscriptions []Sub - rw io.ReadWriter } // ErrMsg is just a regular message containing an error. We handle it in Update @@ -93,18 +90,11 @@ func (p *Program) Start() error { linesRendered int ) - tty, err := term.Open("/dev/tty") + err := initTerminal() if err != nil { return err } - - p.rw = tty - tty.SetRaw() - hideCursor() - defer func() { - showCursor() - tty.Restore() - }() + defer restoreTerminal() // Initialize program model, cmd = p.init() @@ -122,7 +112,7 @@ func (p *Program) Start() error { // need that we're enabling it by default. go func() { for { - msg, _ := ReadKey(p.rw) + msg, _ := ReadKey(os.Stdin) msgs <- KeyMsg(msg) } }() @@ -183,7 +173,7 @@ func (p *Program) render(model Model, linesRendered int) int { if linesRendered > 0 { clearLines(linesRendered) } - io.WriteString(p.rw, view) + io.WriteString(os.Stdout, view) return strings.Count(view, "\r\n") } diff --git a/tty_unix.go b/tty_unix.go new file mode 100644 index 0000000..67ae58f --- /dev/null +++ b/tty_unix.go @@ -0,0 +1,28 @@ +// +build darwin dragonfly freebsd linux netbsd openbsd solaris + +package tea + +import ( + "github.com/pkg/term" +) + +var ( + tty *term.Term +) + +func initTerminal() error { + var err error + tty, err = term.Open("/dev/tty") + if err != nil { + return err + } + + tty.SetRaw() + hideCursor() + return nil +} + +func restoreTerminal() { + showCursor() + tty.Restore() +} diff --git a/tty_windows.go b/tty_windows.go new file mode 100644 index 0000000..35ae455 --- /dev/null +++ b/tty_windows.go @@ -0,0 +1,12 @@ +// +build windows + +package tea + +func initTerminal() error { + hideCursor() + return nil +} + +func restoreTerminal() { + showCursor() +}