From 727d8b28b7653656ebc94e8d9268475b7cf0f52f Mon Sep 17 00:00:00 2001 From: Timon Ringwald Date: Tue, 3 May 2022 17:59:34 +0200 Subject: [PATCH] introduce default KeyPressed behavior --- screen.go | 2 ++ utils.go | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/screen.go b/screen.go index 6d9be93..df6b387 100644 --- a/screen.go +++ b/screen.go @@ -39,6 +39,8 @@ func NewScreen(root View) (*Screen, error) { redrawCh: make(chan struct{}, 1), } + s.KeyPressed = CloseOnCtrlC(s) + go s.eventloop() go s.drawloop() diff --git a/utils.go b/utils.go index e2ec568..1748145 100644 --- a/utils.go +++ b/utils.go @@ -3,6 +3,7 @@ package tui import ( "strings" + "github.com/gdamore/tcell" "github.com/mattn/go-runewidth" ) @@ -113,3 +114,21 @@ func ConstrainBufferToAnchor(buf *ViewBuffer, anchor Anchor, width, height int) return buf.Sub(buf.Width()-width, buf.Height()-height, width, height) } } + +// CloseOnCtrlC returns a KeyPress handler which closes the screen when Ctrl-C is pressed. +// This is the default behavior for all new screens. +// CloseOnCtrlC is a shorthand for CloseOnKeyPressed(screen, tcell.KeyCtrlC) +func CloseOnCtrlC(screen *Screen) func(event *KeyEvent) (consumed bool) { + return CloseOnKeyPressed(screen, tcell.KeyCtrlC) +} + +// CloseOnKeyPressed returns a KeyPress handler which closes the screen when the given key is pressed. +func CloseOnKeyPressed(screen *Screen, key tcell.Key) func(event *KeyEvent) (consumed bool) { + return func(event *KeyEvent) (consumed bool) { + if event.Key() == key { + screen.Stop() + return false + } + return true + } +}