Skip to content

Commit

Permalink
Improve tutorial program to show how to catch and re-raise a panic.
Browse files Browse the repository at this point in the history
Some other clarifications added as well.

Co-authored-by: Garrett D'Amore <[email protected]>
  • Loading branch information
eric-s-raymond and gdamore committed Oct 20, 2022
1 parent d3cbfcf commit 3e6ca93
Showing 1 changed file with 31 additions and 11 deletions.
42 changes: 31 additions & 11 deletions TUTORIAL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -167,7 +171,6 @@ package main
import (
"fmt"
"log"
"os"

"github.com/gdamore/tcell/v2"
)
Expand Down Expand Up @@ -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")

// Event loop
ox, oy := -1, -1
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()
os.Exit(0)
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
for {
// Update screen
s.Show()
Expand All @@ -264,22 +284,21 @@ 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' {
s.Clear()
}
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)
Expand All @@ -291,3 +310,4 @@ func main() {
}
}
```

0 comments on commit 3e6ca93

Please sign in to comment.