Skip to content

Commit

Permalink
Detect errors immediately, rather than after an event
Browse files Browse the repository at this point in the history
Convert the termbox PollEvent into a channel. Use this channel with the
new Machine.ErrorC to detect an error immediately even if a termbox
event hasn't come in yet.
  • Loading branch information
lilyball committed Apr 26, 2012
1 parent 9483d1f commit c8ce37b
Showing 1 changed file with 42 additions and 31 deletions.
73 changes: 42 additions & 31 deletions main.go
Expand Up @@ -59,42 +59,53 @@ func main() {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
// convert termbox event polling into a channel
events := make(chan termbox.Event)
go func() {
for {
events <- termbox.PollEvent()
}
}()
var effectiveRate dcpu.ClockRate
// now wait for the ^C key
printErr := func(err error) {
fmt.Fprintln(os.Stderr, err)
machine.State.Ram.DumpMemory(os.Stderr, []int{int(machine.State.PC())})
os.Exit(1)
}
// now wait for keyboard events
loop:
for {
evt := termbox.PollEvent()
if err := machine.HasError(); err != nil {
fmt.Fprintln(os.Stderr, err)
machine.State.Ram.DumpMemory(os.Stderr, []int{int(machine.State.PC())})
os.Exit(1)
}
if evt.Type == termbox.EventKey {
if evt.Key == termbox.KeyCtrlC {
effectiveRate = machine.EffectiveClockRate()
if err := machine.Stop(); err != nil {
fmt.Fprintln(os.Stderr, err)
machine.State.Ram.DumpMemory(os.Stderr, []int{int(machine.State.PC())})
os.Exit(1)
}
break
}
// else pass it to the keyboard
if evt.Ch == 0 {
// it's a key constant
key := evt.Key
if r, ok := keymapTermboxKeyToRune[key]; ok {
machine.Keyboard.RegisterKeyTyped(r)
} else if k, ok := keymapTermboxKeyToKey[key]; ok {
machine.Keyboard.RegisterKeyPressed(k)
machine.Keyboard.RegisterKeyReleased(k)
select {
case evt := <-events:
if evt.Type == termbox.EventKey {
if evt.Key == termbox.KeyCtrlC {
effectiveRate = machine.EffectiveClockRate()
if err := machine.Stop(); err != nil {
printErr(err)
}
break loop
}
} else {
ch := evt.Ch
if r, ok := keymapRuneToRune[evt.Ch]; ok {
ch = r
// else pass it to the keyboard
if evt.Ch == 0 {
// it's a key constant
key := evt.Key
if r, ok := keymapTermboxKeyToRune[key]; ok {
machine.Keyboard.RegisterKeyTyped(r)
} else if k, ok := keymapTermboxKeyToKey[key]; ok {
machine.Keyboard.RegisterKeyPressed(k)
machine.Keyboard.RegisterKeyReleased(k)
}
} else {
ch := evt.Ch
if r, ok := keymapRuneToRune[evt.Ch]; ok {
ch = r
}
machine.Keyboard.RegisterKeyTyped(ch)
}
machine.Keyboard.RegisterKeyTyped(ch)
}
case err := <-machine.ErrorC:
machine.Stop() // unlike HasError(), ErrorC doesn't shut down the machine
printErr(err)
}
}
if *printRate {
Expand Down

0 comments on commit c8ce37b

Please sign in to comment.