Created
May 18, 2021 17:35
-
-
Save eNV25/536f826c54a4392b8f795f66dfaf7bb2 to your computer and use it in GitHub Desktop.
tcell ChannelEvents examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"os" | |
"strings" | |
"github.com/gdamore/tcell/v2" | |
"github.com/gdamore/tcell/v2/encoding" | |
"github.com/mattn/go-runewidth" | |
) | |
func emit(s tcell.Screen, x, y int, style tcell.Style, str string) { | |
for _, c := range str { | |
var comb []rune | |
w := runewidth.RuneWidth(c) | |
if w == 0 { | |
comb = []rune{c} | |
c = ' ' | |
w = 1 | |
} | |
s.SetContent(x, y, c, comb, style) | |
x += w | |
} | |
} | |
func display(s tcell.Screen) { | |
w, h := s.Size() | |
s.Clear() | |
emit(s, w/2-7, h/2, tcell.StyleDefault, "Hello, World!") | |
emit(s, w/2-10, h/2+1, tcell.StyleDefault, "Press Enter to exit.") | |
s.Show() | |
} | |
func main() { | |
var log strings.Builder | |
encoding.Register() | |
screen, err := tcell.NewScreen() | |
if err != nil { | |
os.Exit(1) | |
} | |
if err := screen.Init(); err != nil { | |
os.Exit(1) | |
} | |
events := make(chan tcell.Event) | |
quit := make(chan struct{}) | |
go screen.ChannelEvents(events, quit) | |
display(screen) | |
loop: | |
for ev := range events { | |
if ev == nil { | |
continue | |
} | |
log.WriteString(fmt.Sprintf("%#v\n", ev)) | |
switch ev := ev.(type) { | |
case *tcell.EventResize: | |
screen.Sync() | |
display(screen) | |
case *tcell.EventKey: | |
if ev.Key() == tcell.KeyEnter { | |
screen.Fini() | |
break loop | |
} | |
} | |
} | |
fmt.Fprint(os.Stderr, log.String()) | |
os.Exit(0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment