Created
June 9, 2015 12:33
-
-
Save vheon/74388c0dd68e21413eb8 to your computer and use it in GitHub Desktop.
Test case for `tmux list-sessions | ./simplebox`
This file contains hidden or 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 ( | |
"bufio" | |
"io" | |
"log" | |
"os" | |
"github.com/nsf/termbox-go" | |
) | |
func writeLine(row int, text string, background termbox.Attribute) { | |
col := 0 | |
for _, r := range text { | |
termbox.SetCell(col, row, r, termbox.ColorDefault, background) | |
col += 1 | |
} | |
} | |
func draw(items []string, selected int) { | |
termbox.Clear(termbox.ColorDefault, termbox.ColorDefault) | |
for i, item := range items { | |
// write all lines | |
writeLine(i, item, termbox.ColorDefault) | |
} | |
// rewrite the selected candidate line with Reverse attribute | |
writeLine(selected, items[selected], termbox.AttrReverse) | |
termbox.Flush() | |
} | |
func readStrings(r io.Reader) []string { | |
scanner := bufio.NewScanner(r) | |
var strings []string | |
for scanner.Scan() { | |
strings = append(strings, scanner.Text()) | |
} | |
return strings | |
} | |
func main() { | |
err := termbox.Init() | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer termbox.Close() | |
selected := 0 | |
items := readStrings(os.Stdin) | |
draw(items, selected) | |
Loop: | |
for { | |
switch evt := termbox.PollEvent(); evt.Type { | |
case termbox.EventKey: | |
switch evt.Key { | |
case termbox.KeyEsc: | |
break Loop | |
case termbox.KeyCtrlN, termbox.KeyArrowDown: | |
if selected < len(items)-1 { | |
selected += 1 | |
} | |
case termbox.KeyCtrlP, termbox.KeyArrowUp: | |
if selected > 0 { | |
selected -= 1 | |
} | |
} | |
case termbox.EventError: | |
panic(evt.Err) | |
default: | |
panic(evt) | |
} | |
draw(items, selected) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment