1
0
mirror of https://github.com/gdamore/tcell.git synced 2025-04-24 13:48:51 +08:00

Improve tutorial program to show how to catch and re-raise a panic.

Some other clarifications added as well.

Co-authored-by: Garrett D'Amore <garrett@damore.org>
This commit is contained in:
Eric S. Raymond 2022-05-26 14:54:45 -04:00 committed by Garrett D'Amore
parent d3cbfcfb7a
commit 3e6ca93679

View File

@ -81,6 +81,10 @@ Button2 | ButtonSecondary | Right button
Button3 | ButtonMiddle | Middle button
Button4 | | Side button (thumb/next)
Button5 | | Side button (thumb/prev)
WheelUp | | Scroll wheel up
WheelDown | | Scroll wheel down
WheelLeft | | Horizontal wheel left
WheelRight | | Horizontal wheel right
## Usage
@ -167,7 +171,6 @@ package main
import (
"fmt"
"log"
"os"
"github.com/gdamore/tcell/v2"
)
@ -245,12 +248,29 @@ func main() {
drawBox(s, 1, 1, 42, 7, boxStyle, "Click and drag to draw a box")
drawBox(s, 5, 9, 32, 14, boxStyle, "Press C to reset")
quit := func() {
// You have to catch panics in a defer, clean up, and
// re-raise them - otherwise your application can
// die without leaving any diagnostic trace.
maybePanic := recover()
s.Fini()
if maybePanic != nil {
panic(maybePanic)
}
}
defer quit()
// Here's how to get the screen size when you need it.
// xmax, ymax := s.Size()
// Here's an example of how to inject a keystroke where it will
// be picked up by the next PollEvent call. Note that the
// queue is LIFO, it has a limited length, and PostEvent() can
// return an error.
// s.PostEvent(tcell.NewEventKey(tcell.KeyRune, rune('a'), 0))
// Event loop
ox, oy := -1, -1
quit := func() {
s.Fini()
os.Exit(0)
}
for {
// Update screen
s.Show()
@ -264,7 +284,7 @@ func main() {
s.Sync()
case *tcell.EventKey:
if ev.Key() == tcell.KeyEscape || ev.Key() == tcell.KeyCtrlC {
quit()
return
} else if ev.Key() == tcell.KeyCtrlL {
s.Sync()
} else if ev.Rune() == 'C' || ev.Rune() == 'c' {
@ -272,14 +292,13 @@ func main() {
}
case *tcell.EventMouse:
x, y := ev.Position()
button := ev.Buttons()
// Only process button events, not wheel events
button &= tcell.ButtonMask(0xff)
if button != tcell.ButtonNone && ox < 0 {
ox, oy = x, y
}
switch ev.Buttons() {
case tcell.Button1, tcell.Button2:
if ox < 0 {
ox, oy = x, y // record location when click started
}
case tcell.ButtonNone:
if ox >= 0 {
label := fmt.Sprintf("%d,%d to %d,%d", ox, oy, x, y)
@ -291,3 +310,4 @@ func main() {
}
}
```