diff --git a/screen_main.go b/screen_main.go index 47ee302..273daf6 100644 --- a/screen_main.go +++ b/screen_main.go @@ -42,7 +42,7 @@ func (screen *mainScreen) handleKeyPress(event termbox.Event) int { } } if screen.GameMode == modePause || screen.GameMode == modeGameOver { - screen.PauseMenu.HandleKeyPress(event) + screen.PauseMenu.HandleEvent(event) if screen.PauseMenu.IsDone() { selOpt := screen.PauseMenu.GetSelectedOption() if selOpt.GetText() == "Exit" { diff --git a/screen_title.go b/screen_title.go index cb9ea04..1719fae 100644 --- a/screen_title.go +++ b/screen_title.go @@ -20,7 +20,7 @@ type titleScreen struct { } func (screen *titleScreen) handleKeyPress(event termbox.Event) int { - if screen.menu.HandleKeyPress(event) { + if screen.menu.HandleEvent(event) { if screen.menu.IsDone() { selOpt := screen.menu.GetSelectedOption() if strings.Trim(selOpt.GetText(), " ") == "Exit" { diff --git a/vendor/github.com/mattn/go-runewidth/README.mkd b/vendor/github.com/mattn/go-runewidth/README.mkd new file mode 100644 index 0000000..ffb0edd --- /dev/null +++ b/vendor/github.com/mattn/go-runewidth/README.mkd @@ -0,0 +1,26 @@ +go-runewidth +============ + +[![Build Status](https://travis-ci.org/mattn/go-runewidth.png?branch=master)](https://travis-ci.org/mattn/go-runewidth) +[![Coverage Status](https://coveralls.io/repos/mattn/go-runewidth/badge.png?branch=HEAD)](https://coveralls.io/r/mattn/go-runewidth?branch=HEAD) +[![GoDoc](https://godoc.org/github.com/mattn/go-runewidth?status.svg)](http://godoc.org/github.com/mattn/go-runewidth) + +Provides functions to get fixed width of the character or string. + +Usage +----- + +```go +runewidth.StringWidth("つのだ☆HIRO") == 12 +``` + + +Author +------ + +Yasuhiro Matsumoto + +License +------- + +under the MIT License: http://mattn.mit-license.org/2013 diff --git a/vendor/github.com/mattn/go-runewidth/runewidth.go b/vendor/github.com/mattn/go-runewidth/runewidth.go new file mode 100644 index 0000000..3fbf33d --- /dev/null +++ b/vendor/github.com/mattn/go-runewidth/runewidth.go @@ -0,0 +1,464 @@ +package runewidth + +var EastAsianWidth = IsEastAsian() +var DefaultCondition = &Condition{EastAsianWidth} + +type interval struct { + first rune + last rune +} + +var combining = []interval{ + {0x0300, 0x036F}, {0x0483, 0x0486}, {0x0488, 0x0489}, + {0x0591, 0x05BD}, {0x05BF, 0x05BF}, {0x05C1, 0x05C2}, + {0x05C4, 0x05C5}, {0x05C7, 0x05C7}, {0x0600, 0x0603}, + {0x0610, 0x0615}, {0x064B, 0x065E}, {0x0670, 0x0670}, + {0x06D6, 0x06E4}, {0x06E7, 0x06E8}, {0x06EA, 0x06ED}, + {0x070F, 0x070F}, {0x0711, 0x0711}, {0x0730, 0x074A}, + {0x07A6, 0x07B0}, {0x07EB, 0x07F3}, {0x0901, 0x0902}, + {0x093C, 0x093C}, {0x0941, 0x0948}, {0x094D, 0x094D}, + {0x0951, 0x0954}, {0x0962, 0x0963}, {0x0981, 0x0981}, + {0x09BC, 0x09BC}, {0x09C1, 0x09C4}, {0x09CD, 0x09CD}, + {0x09E2, 0x09E3}, {0x0A01, 0x0A02}, {0x0A3C, 0x0A3C}, + {0x0A41, 0x0A42}, {0x0A47, 0x0A48}, {0x0A4B, 0x0A4D}, + {0x0A70, 0x0A71}, {0x0A81, 0x0A82}, {0x0ABC, 0x0ABC}, + {0x0AC1, 0x0AC5}, {0x0AC7, 0x0AC8}, {0x0ACD, 0x0ACD}, + {0x0AE2, 0x0AE3}, {0x0B01, 0x0B01}, {0x0B3C, 0x0B3C}, + {0x0B3F, 0x0B3F}, {0x0B41, 0x0B43}, {0x0B4D, 0x0B4D}, + {0x0B56, 0x0B56}, {0x0B82, 0x0B82}, {0x0BC0, 0x0BC0}, + {0x0BCD, 0x0BCD}, {0x0C3E, 0x0C40}, {0x0C46, 0x0C48}, + {0x0C4A, 0x0C4D}, {0x0C55, 0x0C56}, {0x0CBC, 0x0CBC}, + {0x0CBF, 0x0CBF}, {0x0CC6, 0x0CC6}, {0x0CCC, 0x0CCD}, + {0x0CE2, 0x0CE3}, {0x0D41, 0x0D43}, {0x0D4D, 0x0D4D}, + {0x0DCA, 0x0DCA}, {0x0DD2, 0x0DD4}, {0x0DD6, 0x0DD6}, + {0x0E31, 0x0E31}, {0x0E34, 0x0E3A}, {0x0E47, 0x0E4E}, + {0x0EB1, 0x0EB1}, {0x0EB4, 0x0EB9}, {0x0EBB, 0x0EBC}, + {0x0EC8, 0x0ECD}, {0x0F18, 0x0F19}, {0x0F35, 0x0F35}, + {0x0F37, 0x0F37}, {0x0F39, 0x0F39}, {0x0F71, 0x0F7E}, + {0x0F80, 0x0F84}, {0x0F86, 0x0F87}, {0x0F90, 0x0F97}, + {0x0F99, 0x0FBC}, {0x0FC6, 0x0FC6}, {0x102D, 0x1030}, + {0x1032, 0x1032}, {0x1036, 0x1037}, {0x1039, 0x1039}, + {0x1058, 0x1059}, {0x1160, 0x11FF}, {0x135F, 0x135F}, + {0x1712, 0x1714}, {0x1732, 0x1734}, {0x1752, 0x1753}, + {0x1772, 0x1773}, {0x17B4, 0x17B5}, {0x17B7, 0x17BD}, + {0x17C6, 0x17C6}, {0x17C9, 0x17D3}, {0x17DD, 0x17DD}, + {0x180B, 0x180D}, {0x18A9, 0x18A9}, {0x1920, 0x1922}, + {0x1927, 0x1928}, {0x1932, 0x1932}, {0x1939, 0x193B}, + {0x1A17, 0x1A18}, {0x1B00, 0x1B03}, {0x1B34, 0x1B34}, + {0x1B36, 0x1B3A}, {0x1B3C, 0x1B3C}, {0x1B42, 0x1B42}, + {0x1B6B, 0x1B73}, {0x1DC0, 0x1DCA}, {0x1DFE, 0x1DFF}, + {0x200B, 0x200F}, {0x202A, 0x202E}, {0x2060, 0x2063}, + {0x206A, 0x206F}, {0x20D0, 0x20EF}, {0x302A, 0x302F}, + {0x3099, 0x309A}, {0xA806, 0xA806}, {0xA80B, 0xA80B}, + {0xA825, 0xA826}, {0xFB1E, 0xFB1E}, {0xFE00, 0xFE0F}, + {0xFE20, 0xFE23}, {0xFEFF, 0xFEFF}, {0xFFF9, 0xFFFB}, + {0x10A01, 0x10A03}, {0x10A05, 0x10A06}, {0x10A0C, 0x10A0F}, + {0x10A38, 0x10A3A}, {0x10A3F, 0x10A3F}, {0x1D167, 0x1D169}, + {0x1D173, 0x1D182}, {0x1D185, 0x1D18B}, {0x1D1AA, 0x1D1AD}, + {0x1D242, 0x1D244}, {0xE0001, 0xE0001}, {0xE0020, 0xE007F}, + {0xE0100, 0xE01EF}, +} + +type ctype int + +const ( + narrow ctype = iota + ambiguous + wide + halfwidth + fullwidth + neutral +) + +type intervalType struct { + first rune + last rune + ctype ctype +} + +var ctypes = []intervalType{ + {0x0020, 0x007E, narrow}, + {0x00A1, 0x00A1, ambiguous}, + {0x00A2, 0x00A3, narrow}, + {0x00A4, 0x00A4, ambiguous}, + {0x00A5, 0x00A6, narrow}, + {0x00A7, 0x00A8, ambiguous}, + {0x00AA, 0x00AA, ambiguous}, + {0x00AC, 0x00AC, narrow}, + {0x00AD, 0x00AE, ambiguous}, + {0x00AF, 0x00AF, narrow}, + {0x00B0, 0x00B4, ambiguous}, + {0x00B6, 0x00BA, ambiguous}, + {0x00BC, 0x00BF, ambiguous}, + {0x00C6, 0x00C6, ambiguous}, + {0x00D0, 0x00D0, ambiguous}, + {0x00D7, 0x00D8, ambiguous}, + {0x00DE, 0x00E1, ambiguous}, + {0x00E6, 0x00E6, ambiguous}, + {0x00E8, 0x00EA, ambiguous}, + {0x00EC, 0x00ED, ambiguous}, + {0x00F0, 0x00F0, ambiguous}, + {0x00F2, 0x00F3, ambiguous}, + {0x00F7, 0x00FA, ambiguous}, + {0x00FC, 0x00FC, ambiguous}, + {0x00FE, 0x00FE, ambiguous}, + {0x0101, 0x0101, ambiguous}, + {0x0111, 0x0111, ambiguous}, + {0x0113, 0x0113, ambiguous}, + {0x011B, 0x011B, ambiguous}, + {0x0126, 0x0127, ambiguous}, + {0x012B, 0x012B, ambiguous}, + {0x0131, 0x0133, ambiguous}, + {0x0138, 0x0138, ambiguous}, + {0x013F, 0x0142, ambiguous}, + {0x0144, 0x0144, ambiguous}, + {0x0148, 0x014B, ambiguous}, + {0x014D, 0x014D, ambiguous}, + {0x0152, 0x0153, ambiguous}, + {0x0166, 0x0167, ambiguous}, + {0x016B, 0x016B, ambiguous}, + {0x01CE, 0x01CE, ambiguous}, + {0x01D0, 0x01D0, ambiguous}, + {0x01D2, 0x01D2, ambiguous}, + {0x01D4, 0x01D4, ambiguous}, + {0x01D6, 0x01D6, ambiguous}, + {0x01D8, 0x01D8, ambiguous}, + {0x01DA, 0x01DA, ambiguous}, + {0x01DC, 0x01DC, ambiguous}, + {0x0251, 0x0251, ambiguous}, + {0x0261, 0x0261, ambiguous}, + {0x02C4, 0x02C4, ambiguous}, + {0x02C7, 0x02C7, ambiguous}, + {0x02C9, 0x02CB, ambiguous}, + {0x02CD, 0x02CD, ambiguous}, + {0x02D0, 0x02D0, ambiguous}, + {0x02D8, 0x02DB, ambiguous}, + {0x02DD, 0x02DD, ambiguous}, + {0x02DF, 0x02DF, ambiguous}, + {0x0300, 0x036F, ambiguous}, + {0x0391, 0x03A2, ambiguous}, + {0x03A3, 0x03A9, ambiguous}, + {0x03B1, 0x03C1, ambiguous}, + {0x03C3, 0x03C9, ambiguous}, + {0x0401, 0x0401, ambiguous}, + {0x0410, 0x044F, ambiguous}, + {0x0451, 0x0451, ambiguous}, + {0x1100, 0x115F, wide}, + {0x2010, 0x2010, ambiguous}, + {0x2013, 0x2016, ambiguous}, + {0x2018, 0x2019, ambiguous}, + {0x201C, 0x201D, ambiguous}, + {0x2020, 0x2022, ambiguous}, + {0x2024, 0x2027, ambiguous}, + {0x2030, 0x2030, ambiguous}, + {0x2032, 0x2033, ambiguous}, + {0x2035, 0x2035, ambiguous}, + {0x203B, 0x203B, ambiguous}, + {0x203E, 0x203E, ambiguous}, + {0x2074, 0x2074, ambiguous}, + {0x207F, 0x207F, ambiguous}, + {0x2081, 0x2084, ambiguous}, + {0x20A9, 0x20A9, halfwidth}, + {0x20AC, 0x20AC, ambiguous}, + {0x2103, 0x2103, ambiguous}, + {0x2105, 0x2105, ambiguous}, + {0x2109, 0x2109, ambiguous}, + {0x2113, 0x2113, ambiguous}, + {0x2116, 0x2116, ambiguous}, + {0x2121, 0x2122, ambiguous}, + {0x2126, 0x2126, ambiguous}, + {0x212B, 0x212B, ambiguous}, + {0x2153, 0x2154, ambiguous}, + {0x215B, 0x215E, ambiguous}, + {0x2160, 0x216B, ambiguous}, + {0x2170, 0x2179, ambiguous}, + {0x2189, 0x218A, ambiguous}, + {0x2190, 0x2199, ambiguous}, + {0x21B8, 0x21B9, ambiguous}, + {0x21D2, 0x21D2, ambiguous}, + {0x21D4, 0x21D4, ambiguous}, + {0x21E7, 0x21E7, ambiguous}, + {0x2200, 0x2200, ambiguous}, + {0x2202, 0x2203, ambiguous}, + {0x2207, 0x2208, ambiguous}, + {0x220B, 0x220B, ambiguous}, + {0x220F, 0x220F, ambiguous}, + {0x2211, 0x2211, ambiguous}, + {0x2215, 0x2215, ambiguous}, + {0x221A, 0x221A, ambiguous}, + {0x221D, 0x2220, ambiguous}, + {0x2223, 0x2223, ambiguous}, + {0x2225, 0x2225, ambiguous}, + {0x2227, 0x222C, ambiguous}, + {0x222E, 0x222E, ambiguous}, + {0x2234, 0x2237, ambiguous}, + {0x223C, 0x223D, ambiguous}, + {0x2248, 0x2248, ambiguous}, + {0x224C, 0x224C, ambiguous}, + {0x2252, 0x2252, ambiguous}, + {0x2260, 0x2261, ambiguous}, + {0x2264, 0x2267, ambiguous}, + {0x226A, 0x226B, ambiguous}, + {0x226E, 0x226F, ambiguous}, + {0x2282, 0x2283, ambiguous}, + {0x2286, 0x2287, ambiguous}, + {0x2295, 0x2295, ambiguous}, + {0x2299, 0x2299, ambiguous}, + {0x22A5, 0x22A5, ambiguous}, + {0x22BF, 0x22BF, ambiguous}, + {0x2312, 0x2312, ambiguous}, + {0x2329, 0x232A, wide}, + {0x2460, 0x24E9, ambiguous}, + {0x24EB, 0x254B, ambiguous}, + {0x2550, 0x2573, ambiguous}, + {0x2580, 0x258F, ambiguous}, + {0x2592, 0x2595, ambiguous}, + {0x25A0, 0x25A1, ambiguous}, + {0x25A3, 0x25A9, ambiguous}, + {0x25B2, 0x25B3, ambiguous}, + {0x25B6, 0x25B7, ambiguous}, + {0x25BC, 0x25BD, ambiguous}, + {0x25C0, 0x25C1, ambiguous}, + {0x25C6, 0x25C8, ambiguous}, + {0x25CB, 0x25CB, ambiguous}, + {0x25CE, 0x25D1, ambiguous}, + {0x25E2, 0x25E5, ambiguous}, + {0x25EF, 0x25EF, ambiguous}, + {0x2605, 0x2606, ambiguous}, + {0x2609, 0x2609, ambiguous}, + {0x260E, 0x260F, ambiguous}, + {0x2614, 0x2615, ambiguous}, + {0x261C, 0x261C, ambiguous}, + {0x261E, 0x261E, ambiguous}, + {0x2640, 0x2640, ambiguous}, + {0x2642, 0x2642, ambiguous}, + {0x2660, 0x2661, ambiguous}, + {0x2663, 0x2665, ambiguous}, + {0x2667, 0x266A, ambiguous}, + {0x266C, 0x266D, ambiguous}, + {0x266F, 0x266F, ambiguous}, + {0x269E, 0x269F, ambiguous}, + {0x26BE, 0x26BF, ambiguous}, + {0x26C4, 0x26CD, ambiguous}, + {0x26CF, 0x26E1, ambiguous}, + {0x26E3, 0x26E3, ambiguous}, + {0x26E8, 0x26FF, ambiguous}, + {0x273D, 0x273D, ambiguous}, + {0x2757, 0x2757, ambiguous}, + {0x2776, 0x277F, ambiguous}, + {0x27E6, 0x27ED, narrow}, + {0x2985, 0x2986, narrow}, + {0x2B55, 0x2B59, ambiguous}, + {0x2E80, 0x2E9A, wide}, + {0x2E9B, 0x2EF4, wide}, + {0x2F00, 0x2FD6, wide}, + {0x2FF0, 0x2FFC, wide}, + {0x3000, 0x3000, fullwidth}, + {0x3001, 0x303E, wide}, + {0x3041, 0x3097, wide}, + {0x3099, 0x3100, wide}, + {0x3105, 0x312E, wide}, + {0x3131, 0x318F, wide}, + {0x3190, 0x31BB, wide}, + {0x31C0, 0x31E4, wide}, + {0x31F0, 0x321F, wide}, + {0x3220, 0x3247, wide}, + {0x3248, 0x324F, ambiguous}, + {0x3250, 0x32FF, wide}, + {0x3300, 0x4DBF, wide}, + {0x4E00, 0xA48D, wide}, + {0xA490, 0xA4C7, wide}, + {0xA960, 0xA97D, wide}, + {0xAC00, 0xD7A4, wide}, + {0xE000, 0xF8FF, ambiguous}, + {0xF900, 0xFAFF, wide}, + {0xFE00, 0xFE0F, ambiguous}, + {0xFE10, 0xFE1A, wide}, + {0xFE30, 0xFE53, wide}, + {0xFE54, 0xFE67, wide}, + {0xFE68, 0xFE6C, wide}, + {0xFF01, 0xFF60, fullwidth}, + {0xFF61, 0xFFBF, halfwidth}, + {0xFFC2, 0xFFC8, halfwidth}, + {0xFFCA, 0xFFD0, halfwidth}, + {0xFFD2, 0xFFD8, halfwidth}, + {0xFFDA, 0xFFDD, halfwidth}, + {0xFFE0, 0xFFE7, fullwidth}, + {0xFFE8, 0xFFEF, halfwidth}, + {0xFFFD, 0xFFFE, ambiguous}, + {0x1B000, 0x1B002, wide}, + {0x1F100, 0x1F10A, ambiguous}, + {0x1F110, 0x1F12D, ambiguous}, + {0x1F130, 0x1F169, ambiguous}, + {0x1F170, 0x1F19B, ambiguous}, + {0x1F200, 0x1F203, wide}, + {0x1F210, 0x1F23B, wide}, + {0x1F240, 0x1F249, wide}, + {0x1F250, 0x1F252, wide}, + {0x20000, 0x2FFFE, wide}, + {0x30000, 0x3FFFE, wide}, + {0xE0100, 0xE01F0, ambiguous}, + {0xF0000, 0xFFFFD, ambiguous}, + {0x100000, 0x10FFFE, ambiguous}, +} + +type Condition struct { + EastAsianWidth bool +} + +func NewCondition() *Condition { + return &Condition{EastAsianWidth} +} + +// RuneWidth returns the number of cells in r. +// See http://www.unicode.org/reports/tr11/ +func (c *Condition) RuneWidth(r rune) int { + if r == 0 { + return 0 + } + if r < 32 || (r >= 0x7f && r < 0xa0) { + return 1 + } + for _, iv := range combining { + if iv.first <= r && r <= iv.last { + return 0 + } + } + + if c.EastAsianWidth && IsAmbiguousWidth(r) { + return 2 + } + + if r >= 0x1100 && + (r <= 0x115f || r == 0x2329 || r == 0x232a || + (r >= 0x2e80 && r <= 0xa4cf && r != 0x303f) || + (r >= 0xac00 && r <= 0xd7a3) || + (r >= 0xf900 && r <= 0xfaff) || + (r >= 0xfe30 && r <= 0xfe6f) || + (r >= 0xff00 && r <= 0xff60) || + (r >= 0xffe0 && r <= 0xffe6) || + (r >= 0x20000 && r <= 0x2fffd) || + (r >= 0x30000 && r <= 0x3fffd)) { + return 2 + } + return 1 +} + +func (c *Condition) StringWidth(s string) (width int) { + for _, r := range []rune(s) { + width += c.RuneWidth(r) + } + return width +} + +func (c *Condition) Truncate(s string, w int, tail string) string { + if c.StringWidth(s) <= w { + return s + } + r := []rune(s) + tw := c.StringWidth(tail) + w -= tw + width := 0 + i := 0 + for ; i < len(r); i++ { + cw := c.RuneWidth(r[i]) + if width+cw > w { + break + } + width += cw + } + return string(r[0:i]) + tail +} + +func (c *Condition) Wrap(s string, w int) string { + width := 0 + out := "" + for _, r := range []rune(s) { + cw := RuneWidth(r) + if r == '\n' { + out += string(r) + width = 0 + continue + } else if width+cw > w { + out += "\n" + width = 0 + out += string(r) + width += cw + continue + } + out += string(r) + width += cw + } + return out +} + +func (c *Condition) FillLeft(s string, w int) string { + width := c.StringWidth(s) + count := w - width + if count > 0 { + b := make([]byte, count) + for i := range b { + b[i] = ' ' + } + return string(b) + s + } + return s +} + +func (c *Condition) FillRight(s string, w int) string { + width := c.StringWidth(s) + count := w - width + if count > 0 { + b := make([]byte, count) + for i := range b { + b[i] = ' ' + } + return s + string(b) + } + return s +} + +// RuneWidth returns the number of cells in r. +// See http://www.unicode.org/reports/tr11/ +func RuneWidth(r rune) int { + return DefaultCondition.RuneWidth(r) +} + +func ct(r rune) ctype { + for _, iv := range ctypes { + if iv.first <= r && r <= iv.last { + return iv.ctype + } + } + return neutral +} + +// IsAmbiguousWidth returns whether is ambiguous width or not. +func IsAmbiguousWidth(r rune) bool { + return ct(r) == ambiguous +} + +// IsAmbiguousWidth returns whether is ambiguous width or not. +func IsNeutralWidth(r rune) bool { + return ct(r) == neutral +} + +func StringWidth(s string) (width int) { + return DefaultCondition.StringWidth(s) +} + +func Truncate(s string, w int, tail string) string { + return DefaultCondition.Truncate(s, w, tail) +} + +func Wrap(s string, w int) string { + return DefaultCondition.Wrap(s, w) +} + +func FillLeft(s string, w int) string { + return DefaultCondition.FillLeft(s, w) +} + +func FillRight(s string, w int) string { + return DefaultCondition.FillRight(s, w) +} diff --git a/vendor/github.com/mattn/go-runewidth/runewidth_js.go b/vendor/github.com/mattn/go-runewidth/runewidth_js.go new file mode 100644 index 0000000..0ce32c5 --- /dev/null +++ b/vendor/github.com/mattn/go-runewidth/runewidth_js.go @@ -0,0 +1,8 @@ +// +build js + +package runewidth + +func IsEastAsian() bool { + // TODO: Implement this for the web. Detect east asian in a compatible way, and return true. + return false +} diff --git a/vendor/github.com/mattn/go-runewidth/runewidth_posix.go b/vendor/github.com/mattn/go-runewidth/runewidth_posix.go new file mode 100644 index 0000000..a449590 --- /dev/null +++ b/vendor/github.com/mattn/go-runewidth/runewidth_posix.go @@ -0,0 +1,69 @@ +// +build !windows,!js + +package runewidth + +import ( + "os" + "regexp" + "strings" +) + +var reLoc = regexp.MustCompile(`^[a-z][a-z][a-z]?(?:_[A-Z][A-Z])?\.(.+)`) + +func IsEastAsian() bool { + locale := os.Getenv("LC_CTYPE") + if locale == "" { + locale = os.Getenv("LANG") + } + + // ignore C locale + if locale == "POSIX" || locale == "C" { + return false + } + if len(locale) > 1 && locale[0] == 'C' && (locale[1] == '.' || locale[1] == '-') { + return false + } + + charset := strings.ToLower(locale) + r := reLoc.FindStringSubmatch(locale) + if len(r) == 2 { + charset = strings.ToLower(r[1]) + } + + if strings.HasSuffix(charset, "@cjk_narrow") { + return false + } + + for pos, b := range []byte(charset) { + if b == '@' { + charset = charset[:pos] + break + } + } + + mbc_max := 1 + switch charset { + case "utf-8", "utf8": + mbc_max = 6 + case "jis": + mbc_max = 8 + case "eucjp": + mbc_max = 3 + case "euckr", "euccn": + mbc_max = 2 + case "sjis", "cp932", "cp51932", "cp936", "cp949", "cp950": + mbc_max = 2 + case "big5": + mbc_max = 2 + case "gbk", "gb2312": + mbc_max = 2 + } + + if mbc_max > 1 && (charset[0] != 'u' || + strings.HasPrefix(locale, "ja") || + strings.HasPrefix(locale, "ko") || + strings.HasPrefix(locale, "zh")) { + return true + } + return false +} diff --git a/vendor/github.com/mattn/go-runewidth/runewidth_windows.go b/vendor/github.com/mattn/go-runewidth/runewidth_windows.go new file mode 100644 index 0000000..bdd8445 --- /dev/null +++ b/vendor/github.com/mattn/go-runewidth/runewidth_windows.go @@ -0,0 +1,24 @@ +package runewidth + +import ( + "syscall" +) + +var ( + kernel32 = syscall.NewLazyDLL("kernel32") + procGetConsoleOutputCP = kernel32.NewProc("GetConsoleOutputCP") +) + +func IsEastAsian() bool { + r1, _, _ := procGetConsoleOutputCP.Call() + if r1 == 0 { + return false + } + + switch int(r1) { + case 932, 51932, 936, 949, 950: + return true + } + + return false +} diff --git a/vendor/github.com/nsf/termbox-go/AUTHORS b/vendor/github.com/nsf/termbox-go/AUTHORS new file mode 100644 index 0000000..fe26fb0 --- /dev/null +++ b/vendor/github.com/nsf/termbox-go/AUTHORS @@ -0,0 +1,4 @@ +# Please keep this file sorted. + +Georg Reinke +nsf diff --git a/vendor/github.com/nsf/termbox-go/LICENSE b/vendor/github.com/nsf/termbox-go/LICENSE new file mode 100644 index 0000000..d9bc068 --- /dev/null +++ b/vendor/github.com/nsf/termbox-go/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2012 termbox-go authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/github.com/nsf/termbox-go/README.md b/vendor/github.com/nsf/termbox-go/README.md new file mode 100644 index 0000000..9a7b356 --- /dev/null +++ b/vendor/github.com/nsf/termbox-go/README.md @@ -0,0 +1,28 @@ +## Termbox +Termbox is a library that provides a minimalistic API which allows the programmer to write text-based user interfaces. The library is crossplatform and has both terminal-based implementations on *nix operating systems and a winapi console based implementation for windows operating systems. The basic idea is an abstraction of the greatest common subset of features available on all major terminals and other terminal-like APIs in a minimalistic fashion. Small API means it is easy to implement, test, maintain and learn it, that's what makes the termbox a distinct library in its area. + +### Installation +Install and update this go package with `go get -u github.com/nsf/termbox-go` + +### Examples +For examples of what can be done take a look at demos in the _demos directory. You can try them with go run: `go run _demos/keyboard.go` + +There are also some interesting projects using termbox-go: + - [godit](https://github.com/nsf/godit) is an emacsish lightweight text editor written using termbox. + - [gomatrix](https://github.com/GeertJohan/gomatrix) connects to The Matrix and displays its data streams in your terminal. + - [gotetris](https://github.com/jjinux/gotetris) is an implementation of Tetris. + - [sokoban-go](https://github.com/rn2dy/sokoban-go) is an implementation of sokoban game. + - [hecate](https://github.com/evanmiller/hecate) is a hex editor designed by Satan. + - [httopd](https://github.com/verdverm/httopd) is top for httpd logs. + - [mop](https://github.com/michaeldv/mop) is stock market tracker for hackers. + - [termui](https://github.com/gizak/termui) is a terminal dashboard. + - [termloop](https://github.com/JoelOtter/termloop) is a terminal game engine. + - [xterm-color-chart](https://github.com/kutuluk/xterm-color-chart) is a XTerm 256 color chart. + - [gocui](https://github.com/jroimartin/gocui) is a minimalist Go library aimed at creating console user interfaces. + - [dry](https://github.com/moncho/dry) is an interactive cli to manage Docker containers. + - [pxl](https://github.com/ichinaski/pxl) displays images in the terminal. + - [snake-game](https://github.com/DyegoCosta/snake-game) is an implementation of the Snake game. + - [gone](https://github.com/guillaumebreton/gone) is a CLI pomodoro® timer. + +### API reference +[godoc.org/github.com/nsf/termbox-go](http://godoc.org/github.com/nsf/termbox-go) diff --git a/vendor/github.com/nsf/termbox-go/api.go b/vendor/github.com/nsf/termbox-go/api.go new file mode 100644 index 0000000..b339e53 --- /dev/null +++ b/vendor/github.com/nsf/termbox-go/api.go @@ -0,0 +1,458 @@ +// +build !windows + +package termbox + +import "github.com/mattn/go-runewidth" +import "fmt" +import "os" +import "os/signal" +import "syscall" +import "runtime" + +// public API + +// Initializes termbox library. This function should be called before any other functions. +// After successful initialization, the library must be finalized using 'Close' function. +// +// Example usage: +// err := termbox.Init() +// if err != nil { +// panic(err) +// } +// defer termbox.Close() +func Init() error { + var err error + + out, err = os.OpenFile("/dev/tty", syscall.O_WRONLY, 0) + if err != nil { + return err + } + in, err = syscall.Open("/dev/tty", syscall.O_RDONLY, 0) + if err != nil { + return err + } + + err = setup_term() + if err != nil { + return fmt.Errorf("termbox: error while reading terminfo data: %v", err) + } + + signal.Notify(sigwinch, syscall.SIGWINCH) + signal.Notify(sigio, syscall.SIGIO) + + _, err = fcntl(in, syscall.F_SETFL, syscall.O_ASYNC|syscall.O_NONBLOCK) + if err != nil { + return err + } + _, err = fcntl(in, syscall.F_SETOWN, syscall.Getpid()) + if runtime.GOOS != "darwin" && err != nil { + return err + } + err = tcgetattr(out.Fd(), &orig_tios) + if err != nil { + return err + } + + tios := orig_tios + tios.Iflag &^= syscall_IGNBRK | syscall_BRKINT | syscall_PARMRK | + syscall_ISTRIP | syscall_INLCR | syscall_IGNCR | + syscall_ICRNL | syscall_IXON + tios.Lflag &^= syscall_ECHO | syscall_ECHONL | syscall_ICANON | + syscall_ISIG | syscall_IEXTEN + tios.Cflag &^= syscall_CSIZE | syscall_PARENB + tios.Cflag |= syscall_CS8 + tios.Cc[syscall_VMIN] = 1 + tios.Cc[syscall_VTIME] = 0 + + err = tcsetattr(out.Fd(), &tios) + if err != nil { + return err + } + + out.WriteString(funcs[t_enter_ca]) + out.WriteString(funcs[t_enter_keypad]) + out.WriteString(funcs[t_hide_cursor]) + out.WriteString(funcs[t_clear_screen]) + + termw, termh = get_term_size(out.Fd()) + back_buffer.init(termw, termh) + front_buffer.init(termw, termh) + back_buffer.clear() + front_buffer.clear() + + go func() { + buf := make([]byte, 128) + for { + select { + case <-sigio: + for { + n, err := syscall.Read(in, buf) + if err == syscall.EAGAIN || err == syscall.EWOULDBLOCK { + break + } + select { + case input_comm <- input_event{buf[:n], err}: + ie := <-input_comm + buf = ie.data[:128] + case <-quit: + return + } + } + case <-quit: + return + } + } + }() + + IsInit = true + return nil +} + +// Interrupt an in-progress call to PollEvent by causing it to return +// EventInterrupt. Note that this function will block until the PollEvent +// function has successfully been interrupted. +func Interrupt() { + interrupt_comm <- struct{}{} +} + +// Finalizes termbox library, should be called after successful initialization +// when termbox's functionality isn't required anymore. +func Close() { + quit <- 1 + out.WriteString(funcs[t_show_cursor]) + out.WriteString(funcs[t_sgr0]) + out.WriteString(funcs[t_clear_screen]) + out.WriteString(funcs[t_exit_ca]) + out.WriteString(funcs[t_exit_keypad]) + out.WriteString(funcs[t_exit_mouse]) + tcsetattr(out.Fd(), &orig_tios) + + out.Close() + syscall.Close(in) + + // reset the state, so that on next Init() it will work again + termw = 0 + termh = 0 + input_mode = InputEsc + out = nil + in = 0 + lastfg = attr_invalid + lastbg = attr_invalid + lastx = coord_invalid + lasty = coord_invalid + cursor_x = cursor_hidden + cursor_y = cursor_hidden + foreground = ColorDefault + background = ColorDefault + IsInit = false +} + +// Synchronizes the internal back buffer with the terminal. +func Flush() error { + // invalidate cursor position + lastx = coord_invalid + lasty = coord_invalid + + update_size_maybe() + + for y := 0; y < front_buffer.height; y++ { + line_offset := y * front_buffer.width + for x := 0; x < front_buffer.width; { + cell_offset := line_offset + x + back := &back_buffer.cells[cell_offset] + front := &front_buffer.cells[cell_offset] + if back.Ch < ' ' { + back.Ch = ' ' + } + w := runewidth.RuneWidth(back.Ch) + if w == 0 || w == 2 && runewidth.IsAmbiguousWidth(back.Ch) { + w = 1 + } + if *back == *front { + x += w + continue + } + *front = *back + send_attr(back.Fg, back.Bg) + + if w == 2 && x == front_buffer.width-1 { + // there's not enough space for 2-cells rune, + // let's just put a space in there + send_char(x, y, ' ') + } else { + send_char(x, y, back.Ch) + if w == 2 { + next := cell_offset + 1 + front_buffer.cells[next] = Cell{ + Ch: 0, + Fg: back.Fg, + Bg: back.Bg, + } + } + } + x += w + } + } + if !is_cursor_hidden(cursor_x, cursor_y) { + write_cursor(cursor_x, cursor_y) + } + return flush() +} + +// Sets the position of the cursor. See also HideCursor(). +func SetCursor(x, y int) { + if is_cursor_hidden(cursor_x, cursor_y) && !is_cursor_hidden(x, y) { + outbuf.WriteString(funcs[t_show_cursor]) + } + + if !is_cursor_hidden(cursor_x, cursor_y) && is_cursor_hidden(x, y) { + outbuf.WriteString(funcs[t_hide_cursor]) + } + + cursor_x, cursor_y = x, y + if !is_cursor_hidden(cursor_x, cursor_y) { + write_cursor(cursor_x, cursor_y) + } +} + +// The shortcut for SetCursor(-1, -1). +func HideCursor() { + SetCursor(cursor_hidden, cursor_hidden) +} + +// Changes cell's parameters in the internal back buffer at the specified +// position. +func SetCell(x, y int, ch rune, fg, bg Attribute) { + if x < 0 || x >= back_buffer.width { + return + } + if y < 0 || y >= back_buffer.height { + return + } + + back_buffer.cells[y*back_buffer.width+x] = Cell{ch, fg, bg} +} + +// Returns a slice into the termbox's back buffer. You can get its dimensions +// using 'Size' function. The slice remains valid as long as no 'Clear' or +// 'Flush' function calls were made after call to this function. +func CellBuffer() []Cell { + return back_buffer.cells +} + +// After getting a raw event from PollRawEvent function call, you can parse it +// again into an ordinary one using termbox logic. That is parse an event as +// termbox would do it. Returned event in addition to usual Event struct fields +// sets N field to the amount of bytes used within 'data' slice. If the length +// of 'data' slice is zero or event cannot be parsed for some other reason, the +// function will return a special event type: EventNone. +// +// IMPORTANT: EventNone may contain a non-zero N, which means you should skip +// these bytes, because termbox cannot recognize them. +// +// NOTE: This API is experimental and may change in future. +func ParseEvent(data []byte) Event { + event := Event{Type: EventKey} + ok := extract_event(data, &event) + if !ok { + return Event{Type: EventNone, N: event.N} + } + return event +} + +// Wait for an event and return it. This is a blocking function call. Instead +// of EventKey and EventMouse it returns EventRaw events. Raw event is written +// into `data` slice and Event's N field is set to the amount of bytes written. +// The minimum required length of the 'data' slice is 1. This requirement may +// vary on different platforms. +// +// NOTE: This API is experimental and may change in future. +func PollRawEvent(data []byte) Event { + if len(data) == 0 { + panic("len(data) >= 1 is a requirement") + } + + var event Event + if extract_raw_event(data, &event) { + return event + } + + for { + select { + case ev := <-input_comm: + if ev.err != nil { + return Event{Type: EventError, Err: ev.err} + } + + inbuf = append(inbuf, ev.data...) + input_comm <- ev + if extract_raw_event(data, &event) { + return event + } + case <-interrupt_comm: + event.Type = EventInterrupt + return event + + case <-sigwinch: + event.Type = EventResize + event.Width, event.Height = get_term_size(out.Fd()) + return event + } + } +} + +// Wait for an event and return it. This is a blocking function call. +func PollEvent() Event { + var event Event + + // try to extract event from input buffer, return on success + event.Type = EventKey + ok := extract_event(inbuf, &event) + if event.N != 0 { + copy(inbuf, inbuf[event.N:]) + inbuf = inbuf[:len(inbuf)-event.N] + } + if ok { + return event + } + + for { + select { + case ev := <-input_comm: + if ev.err != nil { + return Event{Type: EventError, Err: ev.err} + } + + inbuf = append(inbuf, ev.data...) + input_comm <- ev + ok := extract_event(inbuf, &event) + if event.N != 0 { + copy(inbuf, inbuf[event.N:]) + inbuf = inbuf[:len(inbuf)-event.N] + } + if ok { + return event + } + case <-interrupt_comm: + event.Type = EventInterrupt + return event + + case <-sigwinch: + event.Type = EventResize + event.Width, event.Height = get_term_size(out.Fd()) + return event + } + } + panic("unreachable") +} + +// Returns the size of the internal back buffer (which is mostly the same as +// terminal's window size in characters). But it doesn't always match the size +// of the terminal window, after the terminal size has changed, the internal +// back buffer will get in sync only after Clear or Flush function calls. +func Size() (width int, height int) { + return termw, termh +} + +// Clears the internal back buffer. +func Clear(fg, bg Attribute) error { + foreground, background = fg, bg + err := update_size_maybe() + back_buffer.clear() + return err +} + +// Sets termbox input mode. Termbox has two input modes: +// +// 1. Esc input mode. When ESC sequence is in the buffer and it doesn't match +// any known sequence. ESC means KeyEsc. This is the default input mode. +// +// 2. Alt input mode. When ESC sequence is in the buffer and it doesn't match +// any known sequence. ESC enables ModAlt modifier for the next keyboard event. +// +// Both input modes can be OR'ed with Mouse mode. Setting Mouse mode bit up will +// enable mouse button press/release and drag events. +// +// If 'mode' is InputCurrent, returns the current input mode. See also Input* +// constants. +func SetInputMode(mode InputMode) InputMode { + if mode == InputCurrent { + return input_mode + } + if mode&(InputEsc|InputAlt) == 0 { + mode |= InputEsc + } + if mode&(InputEsc|InputAlt) == InputEsc|InputAlt { + mode &^= InputAlt + } + if mode&InputMouse != 0 { + out.WriteString(funcs[t_enter_mouse]) + } else { + out.WriteString(funcs[t_exit_mouse]) + } + + input_mode = mode + return input_mode +} + +// Sets the termbox output mode. Termbox has four output options: +// +// 1. OutputNormal => [1..8] +// This mode provides 8 different colors: +// black, red, green, yellow, blue, magenta, cyan, white +// Shortcut: ColorBlack, ColorRed, ... +// Attributes: AttrBold, AttrUnderline, AttrReverse +// +// Example usage: +// SetCell(x, y, '@', ColorBlack | AttrBold, ColorRed); +// +// 2. Output256 => [1..256] +// In this mode you can leverage the 256 terminal mode: +// 0x01 - 0x08: the 8 colors as in OutputNormal +// 0x09 - 0x10: Color* | AttrBold +// 0x11 - 0xe8: 216 different colors +// 0xe9 - 0x1ff: 24 different shades of grey +// +// Example usage: +// SetCell(x, y, '@', 184, 240); +// SetCell(x, y, '@', 0xb8, 0xf0); +// +// 3. Output216 => [1..216] +// This mode supports the 3rd range of the 256 mode only. +// But you dont need to provide an offset. +// +// 4. OutputGrayscale => [1..26] +// This mode supports the 4th range of the 256 mode +// and black and white colors from 3th range of the 256 mode +// But you dont need to provide an offset. +// +// In all modes, 0x00 represents the default color. +// +// `go run _demos/output.go` to see its impact on your terminal. +// +// If 'mode' is OutputCurrent, it returns the current output mode. +// +// Note that this may return a different OutputMode than the one requested, +// as the requested mode may not be available on the target platform. +func SetOutputMode(mode OutputMode) OutputMode { + if mode == OutputCurrent { + return output_mode + } + + output_mode = mode + return output_mode +} + +// Sync comes handy when something causes desync between termbox's understanding +// of a terminal buffer and the reality. Such as a third party process. Sync +// forces a complete resync between the termbox and a terminal, it may not be +// visually pretty though. +func Sync() error { + front_buffer.clear() + err := send_clear() + if err != nil { + return err + } + + return Flush() +} diff --git a/vendor/github.com/nsf/termbox-go/api_common.go b/vendor/github.com/nsf/termbox-go/api_common.go new file mode 100644 index 0000000..9f23661 --- /dev/null +++ b/vendor/github.com/nsf/termbox-go/api_common.go @@ -0,0 +1,187 @@ +// termbox is a library for creating cross-platform text-based interfaces +package termbox + +// public API, common OS agnostic part + +type ( + InputMode int + OutputMode int + EventType uint8 + Modifier uint8 + Key uint16 + Attribute uint16 +) + +// This type represents a termbox event. The 'Mod', 'Key' and 'Ch' fields are +// valid if 'Type' is EventKey. The 'Width' and 'Height' fields are valid if +// 'Type' is EventResize. The 'Err' field is valid if 'Type' is EventError. +type Event struct { + Type EventType // one of Event* constants + Mod Modifier // one of Mod* constants or 0 + Key Key // one of Key* constants, invalid if 'Ch' is not 0 + Ch rune // a unicode character + Width int // width of the screen + Height int // height of the screen + Err error // error in case if input failed + MouseX int // x coord of mouse + MouseY int // y coord of mouse + N int // number of bytes written when getting a raw event +} + +// A cell, single conceptual entity on the screen. The screen is basically a 2d +// array of cells. 'Ch' is a unicode character, 'Fg' and 'Bg' are foreground +// and background attributes respectively. +type Cell struct { + Ch rune + Fg Attribute + Bg Attribute +} + +// To know if termbox has been initialized or not +var ( + IsInit bool = false +) + +// Key constants, see Event.Key field. +const ( + KeyF1 Key = 0xFFFF - iota + KeyF2 + KeyF3 + KeyF4 + KeyF5 + KeyF6 + KeyF7 + KeyF8 + KeyF9 + KeyF10 + KeyF11 + KeyF12 + KeyInsert + KeyDelete + KeyHome + KeyEnd + KeyPgup + KeyPgdn + KeyArrowUp + KeyArrowDown + KeyArrowLeft + KeyArrowRight + key_min // see terminfo + MouseLeft + MouseMiddle + MouseRight + MouseRelease + MouseWheelUp + MouseWheelDown +) + +const ( + KeyCtrlTilde Key = 0x00 + KeyCtrl2 Key = 0x00 + KeyCtrlSpace Key = 0x00 + KeyCtrlA Key = 0x01 + KeyCtrlB Key = 0x02 + KeyCtrlC Key = 0x03 + KeyCtrlD Key = 0x04 + KeyCtrlE Key = 0x05 + KeyCtrlF Key = 0x06 + KeyCtrlG Key = 0x07 + KeyBackspace Key = 0x08 + KeyCtrlH Key = 0x08 + KeyTab Key = 0x09 + KeyCtrlI Key = 0x09 + KeyCtrlJ Key = 0x0A + KeyCtrlK Key = 0x0B + KeyCtrlL Key = 0x0C + KeyEnter Key = 0x0D + KeyCtrlM Key = 0x0D + KeyCtrlN Key = 0x0E + KeyCtrlO Key = 0x0F + KeyCtrlP Key = 0x10 + KeyCtrlQ Key = 0x11 + KeyCtrlR Key = 0x12 + KeyCtrlS Key = 0x13 + KeyCtrlT Key = 0x14 + KeyCtrlU Key = 0x15 + KeyCtrlV Key = 0x16 + KeyCtrlW Key = 0x17 + KeyCtrlX Key = 0x18 + KeyCtrlY Key = 0x19 + KeyCtrlZ Key = 0x1A + KeyEsc Key = 0x1B + KeyCtrlLsqBracket Key = 0x1B + KeyCtrl3 Key = 0x1B + KeyCtrl4 Key = 0x1C + KeyCtrlBackslash Key = 0x1C + KeyCtrl5 Key = 0x1D + KeyCtrlRsqBracket Key = 0x1D + KeyCtrl6 Key = 0x1E + KeyCtrl7 Key = 0x1F + KeyCtrlSlash Key = 0x1F + KeyCtrlUnderscore Key = 0x1F + KeySpace Key = 0x20 + KeyBackspace2 Key = 0x7F + KeyCtrl8 Key = 0x7F +) + +// Alt modifier constant, see Event.Mod field and SetInputMode function. +const ( + ModAlt Modifier = 1 << iota + ModMotion +) + +// Cell colors, you can combine a color with multiple attributes using bitwise +// OR ('|'). +const ( + ColorDefault Attribute = iota + ColorBlack + ColorRed + ColorGreen + ColorYellow + ColorBlue + ColorMagenta + ColorCyan + ColorWhite +) + +// Cell attributes, it is possible to use multiple attributes by combining them +// using bitwise OR ('|'). Although, colors cannot be combined. But you can +// combine attributes and a single color. +// +// It's worth mentioning that some platforms don't support certain attibutes. +// For example windows console doesn't support AttrUnderline. And on some +// terminals applying AttrBold to background may result in blinking text. Use +// them with caution and test your code on various terminals. +const ( + AttrBold Attribute = 1 << (iota + 9) + AttrUnderline + AttrReverse +) + +// Input mode. See SetInputMode function. +const ( + InputEsc InputMode = 1 << iota + InputAlt + InputMouse + InputCurrent InputMode = 0 +) + +// Output mode. See SetOutputMode function. +const ( + OutputCurrent OutputMode = iota + OutputNormal + Output256 + Output216 + OutputGrayscale +) + +// Event type. See Event.Type field. +const ( + EventKey EventType = iota + EventResize + EventMouse + EventError + EventInterrupt + EventRaw + EventNone +) diff --git a/vendor/github.com/nsf/termbox-go/api_windows.go b/vendor/github.com/nsf/termbox-go/api_windows.go new file mode 100644 index 0000000..7def30a --- /dev/null +++ b/vendor/github.com/nsf/termbox-go/api_windows.go @@ -0,0 +1,239 @@ +package termbox + +import ( + "syscall" +) + +// public API + +// Initializes termbox library. This function should be called before any other functions. +// After successful initialization, the library must be finalized using 'Close' function. +// +// Example usage: +// err := termbox.Init() +// if err != nil { +// panic(err) +// } +// defer termbox.Close() +func Init() error { + var err error + + interrupt, err = create_event() + if err != nil { + return err + } + + in, err = syscall.Open("CONIN$", syscall.O_RDWR, 0) + if err != nil { + return err + } + out, err = syscall.Open("CONOUT$", syscall.O_RDWR, 0) + if err != nil { + return err + } + + err = get_console_mode(in, &orig_mode) + if err != nil { + return err + } + + err = set_console_mode(in, enable_window_input) + if err != nil { + return err + } + + orig_size = get_term_size(out) + win_size := get_win_size(out) + + err = set_console_screen_buffer_size(out, win_size) + if err != nil { + return err + } + + err = get_console_cursor_info(out, &orig_cursor_info) + if err != nil { + return err + } + + show_cursor(false) + term_size = get_term_size(out) + back_buffer.init(int(term_size.x), int(term_size.y)) + front_buffer.init(int(term_size.x), int(term_size.y)) + back_buffer.clear() + front_buffer.clear() + clear() + + diffbuf = make([]diff_msg, 0, 32) + + go input_event_producer() + IsInit = true + return nil +} + +// Finalizes termbox library, should be called after successful initialization +// when termbox's functionality isn't required anymore. +func Close() { + // we ignore errors here, because we can't really do anything about them + Clear(0, 0) + Flush() + + // stop event producer + cancel_comm <- true + set_event(interrupt) + select { + case <-input_comm: + default: + } + <-cancel_done_comm + + set_console_cursor_info(out, &orig_cursor_info) + set_console_cursor_position(out, coord{}) + set_console_screen_buffer_size(out, orig_size) + set_console_mode(in, orig_mode) + syscall.Close(in) + syscall.Close(out) + syscall.Close(interrupt) + IsInit = false +} + +// Interrupt an in-progress call to PollEvent by causing it to return +// EventInterrupt. Note that this function will block until the PollEvent +// function has successfully been interrupted. +func Interrupt() { + interrupt_comm <- struct{}{} +} + +// Synchronizes the internal back buffer with the terminal. +func Flush() error { + update_size_maybe() + prepare_diff_messages() + for _, diff := range diffbuf { + r := small_rect{ + left: 0, + top: diff.pos, + right: term_size.x - 1, + bottom: diff.pos + diff.lines - 1, + } + write_console_output(out, diff.chars, r) + } + if !is_cursor_hidden(cursor_x, cursor_y) { + move_cursor(cursor_x, cursor_y) + } + return nil +} + +// Sets the position of the cursor. See also HideCursor(). +func SetCursor(x, y int) { + if is_cursor_hidden(cursor_x, cursor_y) && !is_cursor_hidden(x, y) { + show_cursor(true) + } + + if !is_cursor_hidden(cursor_x, cursor_y) && is_cursor_hidden(x, y) { + show_cursor(false) + } + + cursor_x, cursor_y = x, y + if !is_cursor_hidden(cursor_x, cursor_y) { + move_cursor(cursor_x, cursor_y) + } +} + +// The shortcut for SetCursor(-1, -1). +func HideCursor() { + SetCursor(cursor_hidden, cursor_hidden) +} + +// Changes cell's parameters in the internal back buffer at the specified +// position. +func SetCell(x, y int, ch rune, fg, bg Attribute) { + if x < 0 || x >= back_buffer.width { + return + } + if y < 0 || y >= back_buffer.height { + return + } + + back_buffer.cells[y*back_buffer.width+x] = Cell{ch, fg, bg} +} + +// Returns a slice into the termbox's back buffer. You can get its dimensions +// using 'Size' function. The slice remains valid as long as no 'Clear' or +// 'Flush' function calls were made after call to this function. +func CellBuffer() []Cell { + return back_buffer.cells +} + +// Wait for an event and return it. This is a blocking function call. +func PollEvent() Event { + select { + case ev := <-input_comm: + return ev + case <-interrupt_comm: + return Event{Type: EventInterrupt} + } +} + +// Returns the size of the internal back buffer (which is mostly the same as +// console's window size in characters). But it doesn't always match the size +// of the console window, after the console size has changed, the internal back +// buffer will get in sync only after Clear or Flush function calls. +func Size() (int, int) { + return int(term_size.x), int(term_size.y) +} + +// Clears the internal back buffer. +func Clear(fg, bg Attribute) error { + foreground, background = fg, bg + update_size_maybe() + back_buffer.clear() + return nil +} + +// Sets termbox input mode. Termbox has two input modes: +// +// 1. Esc input mode. When ESC sequence is in the buffer and it doesn't match +// any known sequence. ESC means KeyEsc. This is the default input mode. +// +// 2. Alt input mode. When ESC sequence is in the buffer and it doesn't match +// any known sequence. ESC enables ModAlt modifier for the next keyboard event. +// +// Both input modes can be OR'ed with Mouse mode. Setting Mouse mode bit up will +// enable mouse button press/release and drag events. +// +// If 'mode' is InputCurrent, returns the current input mode. See also Input* +// constants. +func SetInputMode(mode InputMode) InputMode { + if mode == InputCurrent { + return input_mode + } + if mode&InputMouse != 0 { + err := set_console_mode(in, enable_window_input|enable_mouse_input|enable_extended_flags) + if err != nil { + panic(err) + } + } else { + err := set_console_mode(in, enable_window_input) + if err != nil { + panic(err) + } + } + + input_mode = mode + return input_mode +} + +// Sets the termbox output mode. +// +// Windows console does not support extra colour modes, +// so this will always set and return OutputNormal. +func SetOutputMode(mode OutputMode) OutputMode { + return OutputNormal +} + +// Sync comes handy when something causes desync between termbox's understanding +// of a terminal buffer and the reality. Such as a third party process. Sync +// forces a complete resync between the termbox and a terminal, it may not be +// visually pretty though. At the moment on Windows it does nothing. +func Sync() error { + return nil +} diff --git a/vendor/github.com/nsf/termbox-go/collect_terminfo.py b/vendor/github.com/nsf/termbox-go/collect_terminfo.py new file mode 100755 index 0000000..5e50975 --- /dev/null +++ b/vendor/github.com/nsf/termbox-go/collect_terminfo.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python + +import sys, os, subprocess + +def escaped(s): + return repr(s)[1:-1] + +def tput(term, name): + try: + return subprocess.check_output(['tput', '-T%s' % term, name]).decode() + except subprocess.CalledProcessError as e: + return e.output.decode() + + +def w(s): + if s == None: + return + sys.stdout.write(s) + +terminals = { + 'xterm' : 'xterm', + 'rxvt-256color' : 'rxvt_256color', + 'rxvt-unicode' : 'rxvt_unicode', + 'linux' : 'linux', + 'Eterm' : 'eterm', + 'screen' : 'screen' +} + +keys = [ + "F1", "kf1", + "F2", "kf2", + "F3", "kf3", + "F4", "kf4", + "F5", "kf5", + "F6", "kf6", + "F7", "kf7", + "F8", "kf8", + "F9", "kf9", + "F10", "kf10", + "F11", "kf11", + "F12", "kf12", + "INSERT", "kich1", + "DELETE", "kdch1", + "HOME", "khome", + "END", "kend", + "PGUP", "kpp", + "PGDN", "knp", + "KEY_UP", "kcuu1", + "KEY_DOWN", "kcud1", + "KEY_LEFT", "kcub1", + "KEY_RIGHT", "kcuf1" +] + +funcs = [ + "T_ENTER_CA", "smcup", + "T_EXIT_CA", "rmcup", + "T_SHOW_CURSOR", "cnorm", + "T_HIDE_CURSOR", "civis", + "T_CLEAR_SCREEN", "clear", + "T_SGR0", "sgr0", + "T_UNDERLINE", "smul", + "T_BOLD", "bold", + "T_BLINK", "blink", + "T_REVERSE", "rev", + "T_ENTER_KEYPAD", "smkx", + "T_EXIT_KEYPAD", "rmkx" +] + +def iter_pairs(iterable): + iterable = iter(iterable) + while True: + yield (next(iterable), next(iterable)) + +def do_term(term, nick): + w("// %s\n" % term) + w("var %s_keys = []string{\n\t" % nick) + for k, v in iter_pairs(keys): + w('"') + w(escaped(tput(term, v))) + w('",') + w("\n}\n") + w("var %s_funcs = []string{\n\t" % nick) + for k,v in iter_pairs(funcs): + w('"') + if v == "sgr": + w("\\033[3%d;4%dm") + elif v == "cup": + w("\\033[%d;%dH") + else: + w(escaped(tput(term, v))) + w('", ') + w("\n}\n\n") + +def do_terms(d): + w("var terms = []struct {\n") + w("\tname string\n") + w("\tkeys []string\n") + w("\tfuncs []string\n") + w("}{\n") + for k, v in d.items(): + w('\t{"%s", %s_keys, %s_funcs},\n' % (k, v, v)) + w("}\n\n") + +w("// +build !windows\n\npackage termbox\n\n") + +for k,v in terminals.items(): + do_term(k, v) + +do_terms(terminals) + diff --git a/vendor/github.com/nsf/termbox-go/syscalls.go b/vendor/github.com/nsf/termbox-go/syscalls.go new file mode 100644 index 0000000..4f52bb9 --- /dev/null +++ b/vendor/github.com/nsf/termbox-go/syscalls.go @@ -0,0 +1,39 @@ +// +build ignore + +package termbox + +/* +#include +#include +*/ +import "C" + +type syscall_Termios C.struct_termios + +const ( + syscall_IGNBRK = C.IGNBRK + syscall_BRKINT = C.BRKINT + syscall_PARMRK = C.PARMRK + syscall_ISTRIP = C.ISTRIP + syscall_INLCR = C.INLCR + syscall_IGNCR = C.IGNCR + syscall_ICRNL = C.ICRNL + syscall_IXON = C.IXON + syscall_OPOST = C.OPOST + syscall_ECHO = C.ECHO + syscall_ECHONL = C.ECHONL + syscall_ICANON = C.ICANON + syscall_ISIG = C.ISIG + syscall_IEXTEN = C.IEXTEN + syscall_CSIZE = C.CSIZE + syscall_PARENB = C.PARENB + syscall_CS8 = C.CS8 + syscall_VMIN = C.VMIN + syscall_VTIME = C.VTIME + + // on darwin change these to (on *bsd too?): + // C.TIOCGETA + // C.TIOCSETA + syscall_TCGETS = C.TCGETS + syscall_TCSETS = C.TCSETS +) diff --git a/vendor/github.com/nsf/termbox-go/syscalls_darwin.go b/vendor/github.com/nsf/termbox-go/syscalls_darwin.go new file mode 100644 index 0000000..25b78f7 --- /dev/null +++ b/vendor/github.com/nsf/termbox-go/syscalls_darwin.go @@ -0,0 +1,41 @@ +// Created by cgo -godefs - DO NOT EDIT +// cgo -godefs syscalls.go + +// +build !amd64 + +package termbox + +type syscall_Termios struct { + Iflag uint32 + Oflag uint32 + Cflag uint32 + Lflag uint32 + Cc [20]uint8 + Ispeed uint32 + Ospeed uint32 +} + +const ( + syscall_IGNBRK = 0x1 + syscall_BRKINT = 0x2 + syscall_PARMRK = 0x8 + syscall_ISTRIP = 0x20 + syscall_INLCR = 0x40 + syscall_IGNCR = 0x80 + syscall_ICRNL = 0x100 + syscall_IXON = 0x200 + syscall_OPOST = 0x1 + syscall_ECHO = 0x8 + syscall_ECHONL = 0x10 + syscall_ICANON = 0x100 + syscall_ISIG = 0x80 + syscall_IEXTEN = 0x400 + syscall_CSIZE = 0x300 + syscall_PARENB = 0x1000 + syscall_CS8 = 0x300 + syscall_VMIN = 0x10 + syscall_VTIME = 0x11 + + syscall_TCGETS = 0x402c7413 + syscall_TCSETS = 0x802c7414 +) diff --git a/vendor/github.com/nsf/termbox-go/syscalls_darwin_amd64.go b/vendor/github.com/nsf/termbox-go/syscalls_darwin_amd64.go new file mode 100644 index 0000000..11f25be --- /dev/null +++ b/vendor/github.com/nsf/termbox-go/syscalls_darwin_amd64.go @@ -0,0 +1,40 @@ +// Created by cgo -godefs - DO NOT EDIT +// cgo -godefs syscalls.go + +package termbox + +type syscall_Termios struct { + Iflag uint64 + Oflag uint64 + Cflag uint64 + Lflag uint64 + Cc [20]uint8 + Pad_cgo_0 [4]byte + Ispeed uint64 + Ospeed uint64 +} + +const ( + syscall_IGNBRK = 0x1 + syscall_BRKINT = 0x2 + syscall_PARMRK = 0x8 + syscall_ISTRIP = 0x20 + syscall_INLCR = 0x40 + syscall_IGNCR = 0x80 + syscall_ICRNL = 0x100 + syscall_IXON = 0x200 + syscall_OPOST = 0x1 + syscall_ECHO = 0x8 + syscall_ECHONL = 0x10 + syscall_ICANON = 0x100 + syscall_ISIG = 0x80 + syscall_IEXTEN = 0x400 + syscall_CSIZE = 0x300 + syscall_PARENB = 0x1000 + syscall_CS8 = 0x300 + syscall_VMIN = 0x10 + syscall_VTIME = 0x11 + + syscall_TCGETS = 0x40487413 + syscall_TCSETS = 0x80487414 +) diff --git a/vendor/github.com/nsf/termbox-go/syscalls_freebsd.go b/vendor/github.com/nsf/termbox-go/syscalls_freebsd.go new file mode 100644 index 0000000..e03624e --- /dev/null +++ b/vendor/github.com/nsf/termbox-go/syscalls_freebsd.go @@ -0,0 +1,39 @@ +// Created by cgo -godefs - DO NOT EDIT +// cgo -godefs syscalls.go + +package termbox + +type syscall_Termios struct { + Iflag uint32 + Oflag uint32 + Cflag uint32 + Lflag uint32 + Cc [20]uint8 + Ispeed uint32 + Ospeed uint32 +} + +const ( + syscall_IGNBRK = 0x1 + syscall_BRKINT = 0x2 + syscall_PARMRK = 0x8 + syscall_ISTRIP = 0x20 + syscall_INLCR = 0x40 + syscall_IGNCR = 0x80 + syscall_ICRNL = 0x100 + syscall_IXON = 0x200 + syscall_OPOST = 0x1 + syscall_ECHO = 0x8 + syscall_ECHONL = 0x10 + syscall_ICANON = 0x100 + syscall_ISIG = 0x80 + syscall_IEXTEN = 0x400 + syscall_CSIZE = 0x300 + syscall_PARENB = 0x1000 + syscall_CS8 = 0x300 + syscall_VMIN = 0x10 + syscall_VTIME = 0x11 + + syscall_TCGETS = 0x402c7413 + syscall_TCSETS = 0x802c7414 +) diff --git a/vendor/github.com/nsf/termbox-go/syscalls_linux.go b/vendor/github.com/nsf/termbox-go/syscalls_linux.go new file mode 100644 index 0000000..b88960d --- /dev/null +++ b/vendor/github.com/nsf/termbox-go/syscalls_linux.go @@ -0,0 +1,33 @@ +// Created by cgo -godefs - DO NOT EDIT +// cgo -godefs syscalls.go + +package termbox + +import "syscall" + +type syscall_Termios syscall.Termios + +const ( + syscall_IGNBRK = syscall.IGNBRK + syscall_BRKINT = syscall.BRKINT + syscall_PARMRK = syscall.PARMRK + syscall_ISTRIP = syscall.ISTRIP + syscall_INLCR = syscall.INLCR + syscall_IGNCR = syscall.IGNCR + syscall_ICRNL = syscall.ICRNL + syscall_IXON = syscall.IXON + syscall_OPOST = syscall.OPOST + syscall_ECHO = syscall.ECHO + syscall_ECHONL = syscall.ECHONL + syscall_ICANON = syscall.ICANON + syscall_ISIG = syscall.ISIG + syscall_IEXTEN = syscall.IEXTEN + syscall_CSIZE = syscall.CSIZE + syscall_PARENB = syscall.PARENB + syscall_CS8 = syscall.CS8 + syscall_VMIN = syscall.VMIN + syscall_VTIME = syscall.VTIME + + syscall_TCGETS = syscall.TCGETS + syscall_TCSETS = syscall.TCSETS +) diff --git a/vendor/github.com/nsf/termbox-go/syscalls_netbsd.go b/vendor/github.com/nsf/termbox-go/syscalls_netbsd.go new file mode 100644 index 0000000..49a3355 --- /dev/null +++ b/vendor/github.com/nsf/termbox-go/syscalls_netbsd.go @@ -0,0 +1,39 @@ +// Created by cgo -godefs - DO NOT EDIT +// cgo -godefs syscalls.go + +package termbox + +type syscall_Termios struct { + Iflag uint32 + Oflag uint32 + Cflag uint32 + Lflag uint32 + Cc [20]uint8 + Ispeed int32 + Ospeed int32 +} + +const ( + syscall_IGNBRK = 0x1 + syscall_BRKINT = 0x2 + syscall_PARMRK = 0x8 + syscall_ISTRIP = 0x20 + syscall_INLCR = 0x40 + syscall_IGNCR = 0x80 + syscall_ICRNL = 0x100 + syscall_IXON = 0x200 + syscall_OPOST = 0x1 + syscall_ECHO = 0x8 + syscall_ECHONL = 0x10 + syscall_ICANON = 0x100 + syscall_ISIG = 0x80 + syscall_IEXTEN = 0x400 + syscall_CSIZE = 0x300 + syscall_PARENB = 0x1000 + syscall_CS8 = 0x300 + syscall_VMIN = 0x10 + syscall_VTIME = 0x11 + + syscall_TCGETS = 0x402c7413 + syscall_TCSETS = 0x802c7414 +) diff --git a/vendor/github.com/nsf/termbox-go/syscalls_openbsd.go b/vendor/github.com/nsf/termbox-go/syscalls_openbsd.go new file mode 100644 index 0000000..49a3355 --- /dev/null +++ b/vendor/github.com/nsf/termbox-go/syscalls_openbsd.go @@ -0,0 +1,39 @@ +// Created by cgo -godefs - DO NOT EDIT +// cgo -godefs syscalls.go + +package termbox + +type syscall_Termios struct { + Iflag uint32 + Oflag uint32 + Cflag uint32 + Lflag uint32 + Cc [20]uint8 + Ispeed int32 + Ospeed int32 +} + +const ( + syscall_IGNBRK = 0x1 + syscall_BRKINT = 0x2 + syscall_PARMRK = 0x8 + syscall_ISTRIP = 0x20 + syscall_INLCR = 0x40 + syscall_IGNCR = 0x80 + syscall_ICRNL = 0x100 + syscall_IXON = 0x200 + syscall_OPOST = 0x1 + syscall_ECHO = 0x8 + syscall_ECHONL = 0x10 + syscall_ICANON = 0x100 + syscall_ISIG = 0x80 + syscall_IEXTEN = 0x400 + syscall_CSIZE = 0x300 + syscall_PARENB = 0x1000 + syscall_CS8 = 0x300 + syscall_VMIN = 0x10 + syscall_VTIME = 0x11 + + syscall_TCGETS = 0x402c7413 + syscall_TCSETS = 0x802c7414 +) diff --git a/vendor/github.com/nsf/termbox-go/syscalls_windows.go b/vendor/github.com/nsf/termbox-go/syscalls_windows.go new file mode 100644 index 0000000..472d002 --- /dev/null +++ b/vendor/github.com/nsf/termbox-go/syscalls_windows.go @@ -0,0 +1,61 @@ +// Created by cgo -godefs - DO NOT EDIT +// cgo -godefs -- -DUNICODE syscalls.go + +package termbox + +const ( + foreground_blue = 0x1 + foreground_green = 0x2 + foreground_red = 0x4 + foreground_intensity = 0x8 + background_blue = 0x10 + background_green = 0x20 + background_red = 0x40 + background_intensity = 0x80 + std_input_handle = -0xa + std_output_handle = -0xb + key_event = 0x1 + mouse_event = 0x2 + window_buffer_size_event = 0x4 + enable_window_input = 0x8 + enable_mouse_input = 0x10 + enable_extended_flags = 0x80 + + vk_f1 = 0x70 + vk_f2 = 0x71 + vk_f3 = 0x72 + vk_f4 = 0x73 + vk_f5 = 0x74 + vk_f6 = 0x75 + vk_f7 = 0x76 + vk_f8 = 0x77 + vk_f9 = 0x78 + vk_f10 = 0x79 + vk_f11 = 0x7a + vk_f12 = 0x7b + vk_insert = 0x2d + vk_delete = 0x2e + vk_home = 0x24 + vk_end = 0x23 + vk_pgup = 0x21 + vk_pgdn = 0x22 + vk_arrow_up = 0x26 + vk_arrow_down = 0x28 + vk_arrow_left = 0x25 + vk_arrow_right = 0x27 + vk_backspace = 0x8 + vk_tab = 0x9 + vk_enter = 0xd + vk_esc = 0x1b + vk_space = 0x20 + + left_alt_pressed = 0x2 + left_ctrl_pressed = 0x8 + right_alt_pressed = 0x1 + right_ctrl_pressed = 0x4 + shift_pressed = 0x10 + + generic_read = 0x80000000 + generic_write = 0x40000000 + console_textmode_buffer = 0x1 +) diff --git a/vendor/github.com/nsf/termbox-go/termbox.go b/vendor/github.com/nsf/termbox-go/termbox.go new file mode 100644 index 0000000..6e5ba6c --- /dev/null +++ b/vendor/github.com/nsf/termbox-go/termbox.go @@ -0,0 +1,514 @@ +// +build !windows + +package termbox + +import "unicode/utf8" +import "bytes" +import "syscall" +import "unsafe" +import "strings" +import "strconv" +import "os" +import "io" + +// private API + +const ( + t_enter_ca = iota + t_exit_ca + t_show_cursor + t_hide_cursor + t_clear_screen + t_sgr0 + t_underline + t_bold + t_blink + t_reverse + t_enter_keypad + t_exit_keypad + t_enter_mouse + t_exit_mouse + t_max_funcs +) + +const ( + coord_invalid = -2 + attr_invalid = Attribute(0xFFFF) +) + +type input_event struct { + data []byte + err error +} + +var ( + // term specific sequences + keys []string + funcs []string + + // termbox inner state + orig_tios syscall_Termios + back_buffer cellbuf + front_buffer cellbuf + termw int + termh int + input_mode = InputEsc + output_mode = OutputNormal + out *os.File + in int + lastfg = attr_invalid + lastbg = attr_invalid + lastx = coord_invalid + lasty = coord_invalid + cursor_x = cursor_hidden + cursor_y = cursor_hidden + foreground = ColorDefault + background = ColorDefault + inbuf = make([]byte, 0, 64) + outbuf bytes.Buffer + sigwinch = make(chan os.Signal, 1) + sigio = make(chan os.Signal, 1) + quit = make(chan int) + input_comm = make(chan input_event) + interrupt_comm = make(chan struct{}) + intbuf = make([]byte, 0, 16) + + // grayscale indexes + grayscale = []Attribute{ + 0, 17, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, + 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 232, + } +) + +func write_cursor(x, y int) { + outbuf.WriteString("\033[") + outbuf.Write(strconv.AppendUint(intbuf, uint64(y+1), 10)) + outbuf.WriteString(";") + outbuf.Write(strconv.AppendUint(intbuf, uint64(x+1), 10)) + outbuf.WriteString("H") +} + +func write_sgr_fg(a Attribute) { + switch output_mode { + case Output256, Output216, OutputGrayscale: + outbuf.WriteString("\033[38;5;") + outbuf.Write(strconv.AppendUint(intbuf, uint64(a-1), 10)) + outbuf.WriteString("m") + default: + outbuf.WriteString("\033[3") + outbuf.Write(strconv.AppendUint(intbuf, uint64(a-1), 10)) + outbuf.WriteString("m") + } +} + +func write_sgr_bg(a Attribute) { + switch output_mode { + case Output256, Output216, OutputGrayscale: + outbuf.WriteString("\033[48;5;") + outbuf.Write(strconv.AppendUint(intbuf, uint64(a-1), 10)) + outbuf.WriteString("m") + default: + outbuf.WriteString("\033[4") + outbuf.Write(strconv.AppendUint(intbuf, uint64(a-1), 10)) + outbuf.WriteString("m") + } +} + +func write_sgr(fg, bg Attribute) { + switch output_mode { + case Output256, Output216, OutputGrayscale: + outbuf.WriteString("\033[38;5;") + outbuf.Write(strconv.AppendUint(intbuf, uint64(fg-1), 10)) + outbuf.WriteString("m") + outbuf.WriteString("\033[48;5;") + outbuf.Write(strconv.AppendUint(intbuf, uint64(bg-1), 10)) + outbuf.WriteString("m") + default: + outbuf.WriteString("\033[3") + outbuf.Write(strconv.AppendUint(intbuf, uint64(fg-1), 10)) + outbuf.WriteString(";4") + outbuf.Write(strconv.AppendUint(intbuf, uint64(bg-1), 10)) + outbuf.WriteString("m") + } +} + +type winsize struct { + rows uint16 + cols uint16 + xpixels uint16 + ypixels uint16 +} + +func get_term_size(fd uintptr) (int, int) { + var sz winsize + _, _, _ = syscall.Syscall(syscall.SYS_IOCTL, + fd, uintptr(syscall.TIOCGWINSZ), uintptr(unsafe.Pointer(&sz))) + return int(sz.cols), int(sz.rows) +} + +func send_attr(fg, bg Attribute) { + if fg == lastfg && bg == lastbg { + return + } + + outbuf.WriteString(funcs[t_sgr0]) + + var fgcol, bgcol Attribute + + switch output_mode { + case Output256: + fgcol = fg & 0x1FF + bgcol = bg & 0x1FF + case Output216: + fgcol = fg & 0xFF + bgcol = bg & 0xFF + if fgcol > 216 { + fgcol = ColorDefault + } + if bgcol > 216 { + bgcol = ColorDefault + } + if fgcol != ColorDefault { + fgcol += 0x10 + } + if bgcol != ColorDefault { + bgcol += 0x10 + } + case OutputGrayscale: + fgcol = fg & 0x1F + bgcol = bg & 0x1F + if fgcol > 26 { + fgcol = ColorDefault + } + if bgcol > 26 { + bgcol = ColorDefault + } + if fgcol != ColorDefault { + fgcol = grayscale[fgcol] + } + if bgcol != ColorDefault { + bgcol = grayscale[bgcol] + } + default: + fgcol = fg & 0x0F + bgcol = bg & 0x0F + } + + if fgcol != ColorDefault { + if bgcol != ColorDefault { + write_sgr(fgcol, bgcol) + } else { + write_sgr_fg(fgcol) + } + } else if bgcol != ColorDefault { + write_sgr_bg(bgcol) + } + + if fg&AttrBold != 0 { + outbuf.WriteString(funcs[t_bold]) + } + if bg&AttrBold != 0 { + outbuf.WriteString(funcs[t_blink]) + } + if fg&AttrUnderline != 0 { + outbuf.WriteString(funcs[t_underline]) + } + if fg&AttrReverse|bg&AttrReverse != 0 { + outbuf.WriteString(funcs[t_reverse]) + } + + lastfg, lastbg = fg, bg +} + +func send_char(x, y int, ch rune) { + var buf [8]byte + n := utf8.EncodeRune(buf[:], ch) + if x-1 != lastx || y != lasty { + write_cursor(x, y) + } + lastx, lasty = x, y + outbuf.Write(buf[:n]) +} + +func flush() error { + _, err := io.Copy(out, &outbuf) + outbuf.Reset() + if err != nil { + return err + } + return nil +} + +func send_clear() error { + send_attr(foreground, background) + outbuf.WriteString(funcs[t_clear_screen]) + if !is_cursor_hidden(cursor_x, cursor_y) { + write_cursor(cursor_x, cursor_y) + } + + // we need to invalidate cursor position too and these two vars are + // used only for simple cursor positioning optimization, cursor + // actually may be in the correct place, but we simply discard + // optimization once and it gives us simple solution for the case when + // cursor moved + lastx = coord_invalid + lasty = coord_invalid + + return flush() +} + +func update_size_maybe() error { + w, h := get_term_size(out.Fd()) + if w != termw || h != termh { + termw, termh = w, h + back_buffer.resize(termw, termh) + front_buffer.resize(termw, termh) + front_buffer.clear() + return send_clear() + } + return nil +} + +func tcsetattr(fd uintptr, termios *syscall_Termios) error { + r, _, e := syscall.Syscall(syscall.SYS_IOCTL, + fd, uintptr(syscall_TCSETS), uintptr(unsafe.Pointer(termios))) + if r != 0 { + return os.NewSyscallError("SYS_IOCTL", e) + } + return nil +} + +func tcgetattr(fd uintptr, termios *syscall_Termios) error { + r, _, e := syscall.Syscall(syscall.SYS_IOCTL, + fd, uintptr(syscall_TCGETS), uintptr(unsafe.Pointer(termios))) + if r != 0 { + return os.NewSyscallError("SYS_IOCTL", e) + } + return nil +} + +func parse_mouse_event(event *Event, buf string) (int, bool) { + if strings.HasPrefix(buf, "\033[M") && len(buf) >= 6 { + // X10 mouse encoding, the simplest one + // \033 [ M Cb Cx Cy + b := buf[3] - 32 + switch b & 3 { + case 0: + if b&64 != 0 { + event.Key = MouseWheelUp + } else { + event.Key = MouseLeft + } + case 1: + if b&64 != 0 { + event.Key = MouseWheelDown + } else { + event.Key = MouseMiddle + } + case 2: + event.Key = MouseRight + case 3: + event.Key = MouseRelease + default: + return 6, false + } + event.Type = EventMouse // KeyEvent by default + if b&32 != 0 { + event.Mod |= ModMotion + } + + // the coord is 1,1 for upper left + event.MouseX = int(buf[4]) - 1 - 32 + event.MouseY = int(buf[5]) - 1 - 32 + return 6, true + } else if strings.HasPrefix(buf, "\033[<") || strings.HasPrefix(buf, "\033[") { + // xterm 1006 extended mode or urxvt 1015 extended mode + // xterm: \033 [ < Cb ; Cx ; Cy (M or m) + // urxvt: \033 [ Cb ; Cx ; Cy M + + // find the first M or m, that's where we stop + mi := strings.IndexAny(buf, "Mm") + if mi == -1 { + return 0, false + } + + // whether it's a capital M or not + isM := buf[mi] == 'M' + + // whether it's urxvt or not + isU := false + + // buf[2] is safe here, because having M or m found means we have at + // least 3 bytes in a string + if buf[2] == '<' { + buf = buf[3:mi] + } else { + isU = true + buf = buf[2:mi] + } + + s1 := strings.Index(buf, ";") + s2 := strings.LastIndex(buf, ";") + // not found or only one ';' + if s1 == -1 || s2 == -1 || s1 == s2 { + return 0, false + } + + n1, err := strconv.ParseInt(buf[0:s1], 10, 64) + if err != nil { + return 0, false + } + n2, err := strconv.ParseInt(buf[s1+1:s2], 10, 64) + if err != nil { + return 0, false + } + n3, err := strconv.ParseInt(buf[s2+1:], 10, 64) + if err != nil { + return 0, false + } + + // on urxvt, first number is encoded exactly as in X10, but we need to + // make it zero-based, on xterm it is zero-based already + if isU { + n1 -= 32 + } + switch n1 & 3 { + case 0: + if n1&64 != 0 { + event.Key = MouseWheelUp + } else { + event.Key = MouseLeft + } + case 1: + if n1&64 != 0 { + event.Key = MouseWheelDown + } else { + event.Key = MouseMiddle + } + case 2: + event.Key = MouseRight + case 3: + event.Key = MouseRelease + default: + return mi + 1, false + } + if !isM { + // on xterm mouse release is signaled by lowercase m + event.Key = MouseRelease + } + + event.Type = EventMouse // KeyEvent by default + if n1&32 != 0 { + event.Mod |= ModMotion + } + + event.MouseX = int(n2) - 1 + event.MouseY = int(n3) - 1 + return mi + 1, true + } + + return 0, false +} + +func parse_escape_sequence(event *Event, buf []byte) (int, bool) { + bufstr := string(buf) + for i, key := range keys { + if strings.HasPrefix(bufstr, key) { + event.Ch = 0 + event.Key = Key(0xFFFF - i) + return len(key), true + } + } + + // if none of the keys match, let's try mouse seqences + return parse_mouse_event(event, bufstr) +} + +func extract_raw_event(data []byte, event *Event) bool { + if len(inbuf) == 0 { + return false + } + + n := len(data) + if n == 0 { + return false + } + + n = copy(data, inbuf) + copy(inbuf, inbuf[n:]) + inbuf = inbuf[:len(inbuf)-n] + + event.N = n + event.Type = EventRaw + return true +} + +func extract_event(inbuf []byte, event *Event) bool { + if len(inbuf) == 0 { + event.N = 0 + return false + } + + if inbuf[0] == '\033' { + // possible escape sequence + if n, ok := parse_escape_sequence(event, inbuf); n != 0 { + event.N = n + return ok + } + + // it's not escape sequence, then it's Alt or Esc, check input_mode + switch { + case input_mode&InputEsc != 0: + // if we're in escape mode, fill Esc event, pop buffer, return success + event.Ch = 0 + event.Key = KeyEsc + event.Mod = 0 + event.N = 1 + return true + case input_mode&InputAlt != 0: + // if we're in alt mode, set Alt modifier to event and redo parsing + event.Mod = ModAlt + ok := extract_event(inbuf[1:], event) + if ok { + event.N++ + } else { + event.N = 0 + } + return ok + default: + panic("unreachable") + } + } + + // if we're here, this is not an escape sequence and not an alt sequence + // so, it's a FUNCTIONAL KEY or a UNICODE character + + // first of all check if it's a functional key + if Key(inbuf[0]) <= KeySpace || Key(inbuf[0]) == KeyBackspace2 { + // fill event, pop buffer, return success + event.Ch = 0 + event.Key = Key(inbuf[0]) + event.N = 1 + return true + } + + // the only possible option is utf8 rune + if r, n := utf8.DecodeRune(inbuf); r != utf8.RuneError { + event.Ch = r + event.Key = 0 + event.N = n + return true + } + + return false +} + +func fcntl(fd int, cmd int, arg int) (val int, err error) { + r, _, e := syscall.Syscall(syscall.SYS_FCNTL, uintptr(fd), uintptr(cmd), + uintptr(arg)) + val = int(r) + if e != 0 { + err = e + } + return +} diff --git a/vendor/github.com/nsf/termbox-go/termbox_common.go b/vendor/github.com/nsf/termbox-go/termbox_common.go new file mode 100644 index 0000000..c3355cc --- /dev/null +++ b/vendor/github.com/nsf/termbox-go/termbox_common.go @@ -0,0 +1,59 @@ +package termbox + +// private API, common OS agnostic part + +type cellbuf struct { + width int + height int + cells []Cell +} + +func (this *cellbuf) init(width, height int) { + this.width = width + this.height = height + this.cells = make([]Cell, width*height) +} + +func (this *cellbuf) resize(width, height int) { + if this.width == width && this.height == height { + return + } + + oldw := this.width + oldh := this.height + oldcells := this.cells + + this.init(width, height) + this.clear() + + minw, minh := oldw, oldh + + if width < minw { + minw = width + } + if height < minh { + minh = height + } + + for i := 0; i < minh; i++ { + srco, dsto := i*oldw, i*width + src := oldcells[srco : srco+minw] + dst := this.cells[dsto : dsto+minw] + copy(dst, src) + } +} + +func (this *cellbuf) clear() { + for i := range this.cells { + c := &this.cells[i] + c.Ch = ' ' + c.Fg = foreground + c.Bg = background + } +} + +const cursor_hidden = -1 + +func is_cursor_hidden(x, y int) bool { + return x == cursor_hidden || y == cursor_hidden +} diff --git a/vendor/github.com/nsf/termbox-go/termbox_windows.go b/vendor/github.com/nsf/termbox-go/termbox_windows.go new file mode 100644 index 0000000..f7dad7b --- /dev/null +++ b/vendor/github.com/nsf/termbox-go/termbox_windows.go @@ -0,0 +1,856 @@ +package termbox + +import "syscall" +import "unsafe" +import "unicode/utf16" +import "github.com/mattn/go-runewidth" + +type ( + wchar uint16 + short int16 + dword uint32 + word uint16 + char_info struct { + char wchar + attr word + } + coord struct { + x short + y short + } + small_rect struct { + left short + top short + right short + bottom short + } + console_screen_buffer_info struct { + size coord + cursor_position coord + attributes word + window small_rect + maximum_window_size coord + } + console_cursor_info struct { + size dword + visible int32 + } + input_record struct { + event_type word + _ [2]byte + event [16]byte + } + key_event_record struct { + key_down int32 + repeat_count word + virtual_key_code word + virtual_scan_code word + unicode_char wchar + control_key_state dword + } + window_buffer_size_record struct { + size coord + } + mouse_event_record struct { + mouse_pos coord + button_state dword + control_key_state dword + event_flags dword + } +) + +const ( + mouse_lmb = 0x1 + mouse_rmb = 0x2 + mouse_mmb = 0x4 | 0x8 | 0x10 +) + +func (this coord) uintptr() uintptr { + return uintptr(*(*int32)(unsafe.Pointer(&this))) +} + +var kernel32 = syscall.NewLazyDLL("kernel32.dll") +var is_cjk = runewidth.IsEastAsian() + +var ( + proc_set_console_active_screen_buffer = kernel32.NewProc("SetConsoleActiveScreenBuffer") + proc_set_console_screen_buffer_size = kernel32.NewProc("SetConsoleScreenBufferSize") + proc_create_console_screen_buffer = kernel32.NewProc("CreateConsoleScreenBuffer") + proc_get_console_screen_buffer_info = kernel32.NewProc("GetConsoleScreenBufferInfo") + proc_write_console_output = kernel32.NewProc("WriteConsoleOutputW") + proc_write_console_output_character = kernel32.NewProc("WriteConsoleOutputCharacterW") + proc_write_console_output_attribute = kernel32.NewProc("WriteConsoleOutputAttribute") + proc_set_console_cursor_info = kernel32.NewProc("SetConsoleCursorInfo") + proc_set_console_cursor_position = kernel32.NewProc("SetConsoleCursorPosition") + proc_get_console_cursor_info = kernel32.NewProc("GetConsoleCursorInfo") + proc_read_console_input = kernel32.NewProc("ReadConsoleInputW") + proc_get_console_mode = kernel32.NewProc("GetConsoleMode") + proc_set_console_mode = kernel32.NewProc("SetConsoleMode") + proc_fill_console_output_character = kernel32.NewProc("FillConsoleOutputCharacterW") + proc_fill_console_output_attribute = kernel32.NewProc("FillConsoleOutputAttribute") + proc_create_event = kernel32.NewProc("CreateEventW") + proc_wait_for_multiple_objects = kernel32.NewProc("WaitForMultipleObjects") + proc_set_event = kernel32.NewProc("SetEvent") +) + +func set_console_active_screen_buffer(h syscall.Handle) (err error) { + r0, _, e1 := syscall.Syscall(proc_set_console_active_screen_buffer.Addr(), + 1, uintptr(h), 0, 0) + if int(r0) == 0 { + if e1 != 0 { + err = error(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func set_console_screen_buffer_size(h syscall.Handle, size coord) (err error) { + r0, _, e1 := syscall.Syscall(proc_set_console_screen_buffer_size.Addr(), + 2, uintptr(h), size.uintptr(), 0) + if int(r0) == 0 { + if e1 != 0 { + err = error(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func create_console_screen_buffer() (h syscall.Handle, err error) { + r0, _, e1 := syscall.Syscall6(proc_create_console_screen_buffer.Addr(), + 5, uintptr(generic_read|generic_write), 0, 0, console_textmode_buffer, 0, 0) + if int(r0) == 0 { + if e1 != 0 { + err = error(e1) + } else { + err = syscall.EINVAL + } + } + return syscall.Handle(r0), err +} + +func get_console_screen_buffer_info(h syscall.Handle, info *console_screen_buffer_info) (err error) { + r0, _, e1 := syscall.Syscall(proc_get_console_screen_buffer_info.Addr(), + 2, uintptr(h), uintptr(unsafe.Pointer(info)), 0) + if int(r0) == 0 { + if e1 != 0 { + err = error(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func write_console_output(h syscall.Handle, chars []char_info, dst small_rect) (err error) { + tmp_coord = coord{dst.right - dst.left + 1, dst.bottom - dst.top + 1} + tmp_rect = dst + r0, _, e1 := syscall.Syscall6(proc_write_console_output.Addr(), + 5, uintptr(h), uintptr(unsafe.Pointer(&chars[0])), tmp_coord.uintptr(), + tmp_coord0.uintptr(), uintptr(unsafe.Pointer(&tmp_rect)), 0) + if int(r0) == 0 { + if e1 != 0 { + err = error(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func write_console_output_character(h syscall.Handle, chars []wchar, pos coord) (err error) { + r0, _, e1 := syscall.Syscall6(proc_write_console_output_character.Addr(), + 5, uintptr(h), uintptr(unsafe.Pointer(&chars[0])), uintptr(len(chars)), + pos.uintptr(), uintptr(unsafe.Pointer(&tmp_arg)), 0) + if int(r0) == 0 { + if e1 != 0 { + err = error(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func write_console_output_attribute(h syscall.Handle, attrs []word, pos coord) (err error) { + r0, _, e1 := syscall.Syscall6(proc_write_console_output_attribute.Addr(), + 5, uintptr(h), uintptr(unsafe.Pointer(&attrs[0])), uintptr(len(attrs)), + pos.uintptr(), uintptr(unsafe.Pointer(&tmp_arg)), 0) + if int(r0) == 0 { + if e1 != 0 { + err = error(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func set_console_cursor_info(h syscall.Handle, info *console_cursor_info) (err error) { + r0, _, e1 := syscall.Syscall(proc_set_console_cursor_info.Addr(), + 2, uintptr(h), uintptr(unsafe.Pointer(info)), 0) + if int(r0) == 0 { + if e1 != 0 { + err = error(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func get_console_cursor_info(h syscall.Handle, info *console_cursor_info) (err error) { + r0, _, e1 := syscall.Syscall(proc_get_console_cursor_info.Addr(), + 2, uintptr(h), uintptr(unsafe.Pointer(info)), 0) + if int(r0) == 0 { + if e1 != 0 { + err = error(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func set_console_cursor_position(h syscall.Handle, pos coord) (err error) { + r0, _, e1 := syscall.Syscall(proc_set_console_cursor_position.Addr(), + 2, uintptr(h), pos.uintptr(), 0) + if int(r0) == 0 { + if e1 != 0 { + err = error(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func read_console_input(h syscall.Handle, record *input_record) (err error) { + r0, _, e1 := syscall.Syscall6(proc_read_console_input.Addr(), + 4, uintptr(h), uintptr(unsafe.Pointer(record)), 1, uintptr(unsafe.Pointer(&tmp_arg)), 0, 0) + if int(r0) == 0 { + if e1 != 0 { + err = error(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func get_console_mode(h syscall.Handle, mode *dword) (err error) { + r0, _, e1 := syscall.Syscall(proc_get_console_mode.Addr(), + 2, uintptr(h), uintptr(unsafe.Pointer(mode)), 0) + if int(r0) == 0 { + if e1 != 0 { + err = error(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func set_console_mode(h syscall.Handle, mode dword) (err error) { + r0, _, e1 := syscall.Syscall(proc_set_console_mode.Addr(), + 2, uintptr(h), uintptr(mode), 0) + if int(r0) == 0 { + if e1 != 0 { + err = error(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func fill_console_output_character(h syscall.Handle, char wchar, n int) (err error) { + r0, _, e1 := syscall.Syscall6(proc_fill_console_output_character.Addr(), + 5, uintptr(h), uintptr(char), uintptr(n), tmp_coord.uintptr(), + uintptr(unsafe.Pointer(&tmp_arg)), 0) + if int(r0) == 0 { + if e1 != 0 { + err = error(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func fill_console_output_attribute(h syscall.Handle, attr word, n int) (err error) { + r0, _, e1 := syscall.Syscall6(proc_fill_console_output_attribute.Addr(), + 5, uintptr(h), uintptr(attr), uintptr(n), tmp_coord.uintptr(), + uintptr(unsafe.Pointer(&tmp_arg)), 0) + if int(r0) == 0 { + if e1 != 0 { + err = error(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func create_event() (out syscall.Handle, err error) { + r0, _, e1 := syscall.Syscall6(proc_create_event.Addr(), + 4, 0, 0, 0, 0, 0, 0) + if int(r0) == 0 { + if e1 != 0 { + err = error(e1) + } else { + err = syscall.EINVAL + } + } + return syscall.Handle(r0), err +} + +func wait_for_multiple_objects(objects []syscall.Handle) (err error) { + r0, _, e1 := syscall.Syscall6(proc_wait_for_multiple_objects.Addr(), + 4, uintptr(len(objects)), uintptr(unsafe.Pointer(&objects[0])), + 0, 0xFFFFFFFF, 0, 0) + if uint32(r0) == 0xFFFFFFFF { + if e1 != 0 { + err = error(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func set_event(ev syscall.Handle) (err error) { + r0, _, e1 := syscall.Syscall(proc_set_event.Addr(), + 1, uintptr(ev), 0, 0) + if int(r0) == 0 { + if e1 != 0 { + err = error(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +type diff_msg struct { + pos short + lines short + chars []char_info +} + +type input_event struct { + event Event + err error +} + +var ( + orig_cursor_info console_cursor_info + orig_size coord + orig_mode dword + orig_screen syscall.Handle + back_buffer cellbuf + front_buffer cellbuf + term_size coord + input_mode = InputEsc + cursor_x = cursor_hidden + cursor_y = cursor_hidden + foreground = ColorDefault + background = ColorDefault + in syscall.Handle + out syscall.Handle + interrupt syscall.Handle + charbuf []char_info + diffbuf []diff_msg + beg_x = -1 + beg_y = -1 + beg_i = -1 + input_comm = make(chan Event) + interrupt_comm = make(chan struct{}) + cancel_comm = make(chan bool, 1) + cancel_done_comm = make(chan bool) + alt_mode_esc = false + + // these ones just to prevent heap allocs at all costs + tmp_info console_screen_buffer_info + tmp_arg dword + tmp_coord0 = coord{0, 0} + tmp_coord = coord{0, 0} + tmp_rect = small_rect{0, 0, 0, 0} +) + +func get_cursor_position(out syscall.Handle) coord { + err := get_console_screen_buffer_info(out, &tmp_info) + if err != nil { + panic(err) + } + return tmp_info.cursor_position +} + +func get_term_size(out syscall.Handle) coord { + err := get_console_screen_buffer_info(out, &tmp_info) + if err != nil { + panic(err) + } + return tmp_info.size +} + +func get_win_size(out syscall.Handle) coord { + err := get_console_screen_buffer_info(out, &tmp_info) + if err != nil { + panic(err) + } + return coord{ + x: tmp_info.window.right - tmp_info.window.left + 1, + y: tmp_info.window.bottom - tmp_info.window.top + 1, + } +} + +func update_size_maybe() { + size := get_term_size(out) + if size.x != term_size.x || size.y != term_size.y { + term_size = size + back_buffer.resize(int(size.x), int(size.y)) + front_buffer.resize(int(size.x), int(size.y)) + front_buffer.clear() + clear() + + area := int(size.x) * int(size.y) + if cap(charbuf) < area { + charbuf = make([]char_info, 0, area) + } + } +} + +var color_table_bg = []word{ + 0, // default (black) + 0, // black + background_red, + background_green, + background_red | background_green, // yellow + background_blue, + background_red | background_blue, // magenta + background_green | background_blue, // cyan + background_red | background_blue | background_green, // white +} + +var color_table_fg = []word{ + foreground_red | foreground_blue | foreground_green, // default (white) + 0, + foreground_red, + foreground_green, + foreground_red | foreground_green, // yellow + foreground_blue, + foreground_red | foreground_blue, // magenta + foreground_green | foreground_blue, // cyan + foreground_red | foreground_blue | foreground_green, // white +} + +const ( + replacement_char = '\uFFFD' + max_rune = '\U0010FFFF' + surr1 = 0xd800 + surr2 = 0xdc00 + surr3 = 0xe000 + surr_self = 0x10000 +) + +func append_diff_line(y int) int { + n := 0 + for x := 0; x < front_buffer.width; { + cell_offset := y*front_buffer.width + x + back := &back_buffer.cells[cell_offset] + front := &front_buffer.cells[cell_offset] + attr, char := cell_to_char_info(*back) + charbuf = append(charbuf, char_info{attr: attr, char: char[0]}) + *front = *back + n++ + w := runewidth.RuneWidth(back.Ch) + if w == 0 || w == 2 && runewidth.IsAmbiguousWidth(back.Ch) { + w = 1 + } + x += w + // If not CJK, fill trailing space with whitespace + if !is_cjk && w == 2 { + charbuf = append(charbuf, char_info{attr: attr, char: ' '}) + } + } + return n +} + +// compares 'back_buffer' with 'front_buffer' and prepares all changes in the form of +// 'diff_msg's in the 'diff_buf' +func prepare_diff_messages() { + // clear buffers + diffbuf = diffbuf[:0] + charbuf = charbuf[:0] + + var diff diff_msg + gbeg := 0 + for y := 0; y < front_buffer.height; y++ { + same := true + line_offset := y * front_buffer.width + for x := 0; x < front_buffer.width; x++ { + cell_offset := line_offset + x + back := &back_buffer.cells[cell_offset] + front := &front_buffer.cells[cell_offset] + if *back != *front { + same = false + break + } + } + if same && diff.lines > 0 { + diffbuf = append(diffbuf, diff) + diff = diff_msg{} + } + if !same { + beg := len(charbuf) + end := beg + append_diff_line(y) + if diff.lines == 0 { + diff.pos = short(y) + gbeg = beg + } + diff.lines++ + diff.chars = charbuf[gbeg:end] + } + } + if diff.lines > 0 { + diffbuf = append(diffbuf, diff) + diff = diff_msg{} + } +} + +func get_ct(table []word, idx int) word { + idx = idx & 0x0F + if idx >= len(table) { + idx = len(table) - 1 + } + return table[idx] +} + +func cell_to_char_info(c Cell) (attr word, wc [2]wchar) { + attr = get_ct(color_table_fg, int(c.Fg)) | get_ct(color_table_bg, int(c.Bg)) + if c.Fg&AttrReverse|c.Bg&AttrReverse != 0 { + attr = (attr&0xF0)>>4 | (attr&0x0F)<<4 + } + if c.Fg&AttrBold != 0 { + attr |= foreground_intensity + } + if c.Bg&AttrBold != 0 { + attr |= background_intensity + } + + r0, r1 := utf16.EncodeRune(c.Ch) + if r0 == 0xFFFD { + wc[0] = wchar(c.Ch) + wc[1] = ' ' + } else { + wc[0] = wchar(r0) + wc[1] = wchar(r1) + } + return +} + +func move_cursor(x, y int) { + err := set_console_cursor_position(out, coord{short(x), short(y)}) + if err != nil { + panic(err) + } +} + +func show_cursor(visible bool) { + var v int32 + if visible { + v = 1 + } + + var info console_cursor_info + info.size = 100 + info.visible = v + err := set_console_cursor_info(out, &info) + if err != nil { + panic(err) + } +} + +func clear() { + var err error + attr, char := cell_to_char_info(Cell{ + ' ', + foreground, + background, + }) + + area := int(term_size.x) * int(term_size.y) + err = fill_console_output_attribute(out, attr, area) + if err != nil { + panic(err) + } + err = fill_console_output_character(out, char[0], area) + if err != nil { + panic(err) + } + if !is_cursor_hidden(cursor_x, cursor_y) { + move_cursor(cursor_x, cursor_y) + } +} + +func key_event_record_to_event(r *key_event_record) (Event, bool) { + if r.key_down == 0 { + return Event{}, false + } + + e := Event{Type: EventKey} + if input_mode&InputAlt != 0 { + if alt_mode_esc { + e.Mod = ModAlt + alt_mode_esc = false + } + if r.control_key_state&(left_alt_pressed|right_alt_pressed) != 0 { + e.Mod = ModAlt + } + } + + ctrlpressed := r.control_key_state&(left_ctrl_pressed|right_ctrl_pressed) != 0 + + if r.virtual_key_code >= vk_f1 && r.virtual_key_code <= vk_f12 { + switch r.virtual_key_code { + case vk_f1: + e.Key = KeyF1 + case vk_f2: + e.Key = KeyF2 + case vk_f3: + e.Key = KeyF3 + case vk_f4: + e.Key = KeyF4 + case vk_f5: + e.Key = KeyF5 + case vk_f6: + e.Key = KeyF6 + case vk_f7: + e.Key = KeyF7 + case vk_f8: + e.Key = KeyF8 + case vk_f9: + e.Key = KeyF9 + case vk_f10: + e.Key = KeyF10 + case vk_f11: + e.Key = KeyF11 + case vk_f12: + e.Key = KeyF12 + default: + panic("unreachable") + } + + return e, true + } + + if r.virtual_key_code <= vk_delete { + switch r.virtual_key_code { + case vk_insert: + e.Key = KeyInsert + case vk_delete: + e.Key = KeyDelete + case vk_home: + e.Key = KeyHome + case vk_end: + e.Key = KeyEnd + case vk_pgup: + e.Key = KeyPgup + case vk_pgdn: + e.Key = KeyPgdn + case vk_arrow_up: + e.Key = KeyArrowUp + case vk_arrow_down: + e.Key = KeyArrowDown + case vk_arrow_left: + e.Key = KeyArrowLeft + case vk_arrow_right: + e.Key = KeyArrowRight + case vk_backspace: + if ctrlpressed { + e.Key = KeyBackspace2 + } else { + e.Key = KeyBackspace + } + case vk_tab: + e.Key = KeyTab + case vk_enter: + e.Key = KeyEnter + case vk_esc: + switch { + case input_mode&InputEsc != 0: + e.Key = KeyEsc + case input_mode&InputAlt != 0: + alt_mode_esc = true + return Event{}, false + } + case vk_space: + if ctrlpressed { + // manual return here, because KeyCtrlSpace is zero + e.Key = KeyCtrlSpace + return e, true + } else { + e.Key = KeySpace + } + } + + if e.Key != 0 { + return e, true + } + } + + if ctrlpressed { + if Key(r.unicode_char) >= KeyCtrlA && Key(r.unicode_char) <= KeyCtrlRsqBracket { + e.Key = Key(r.unicode_char) + if input_mode&InputAlt != 0 && e.Key == KeyEsc { + alt_mode_esc = true + return Event{}, false + } + return e, true + } + switch r.virtual_key_code { + case 192, 50: + // manual return here, because KeyCtrl2 is zero + e.Key = KeyCtrl2 + return e, true + case 51: + if input_mode&InputAlt != 0 { + alt_mode_esc = true + return Event{}, false + } + e.Key = KeyCtrl3 + case 52: + e.Key = KeyCtrl4 + case 53: + e.Key = KeyCtrl5 + case 54: + e.Key = KeyCtrl6 + case 189, 191, 55: + e.Key = KeyCtrl7 + case 8, 56: + e.Key = KeyCtrl8 + } + + if e.Key != 0 { + return e, true + } + } + + if r.unicode_char != 0 { + e.Ch = rune(r.unicode_char) + return e, true + } + + return Event{}, false +} + +func input_event_producer() { + var r input_record + var err error + var last_button Key + var last_button_pressed Key + var last_state = dword(0) + var last_x, last_y = -1, -1 + handles := []syscall.Handle{in, interrupt} + for { + err = wait_for_multiple_objects(handles) + if err != nil { + input_comm <- Event{Type: EventError, Err: err} + } + + select { + case <-cancel_comm: + cancel_done_comm <- true + return + default: + } + + err = read_console_input(in, &r) + if err != nil { + input_comm <- Event{Type: EventError, Err: err} + } + + switch r.event_type { + case key_event: + kr := (*key_event_record)(unsafe.Pointer(&r.event)) + ev, ok := key_event_record_to_event(kr) + if ok { + for i := 0; i < int(kr.repeat_count); i++ { + input_comm <- ev + } + } + case window_buffer_size_event: + sr := *(*window_buffer_size_record)(unsafe.Pointer(&r.event)) + input_comm <- Event{ + Type: EventResize, + Width: int(sr.size.x), + Height: int(sr.size.y), + } + case mouse_event: + mr := *(*mouse_event_record)(unsafe.Pointer(&r.event)) + ev := Event{Type: EventMouse} + switch mr.event_flags { + case 0, 2: + // single or double click + cur_state := mr.button_state + switch { + case last_state&mouse_lmb == 0 && cur_state&mouse_lmb != 0: + last_button = MouseLeft + last_button_pressed = last_button + case last_state&mouse_rmb == 0 && cur_state&mouse_rmb != 0: + last_button = MouseRight + last_button_pressed = last_button + case last_state&mouse_mmb == 0 && cur_state&mouse_mmb != 0: + last_button = MouseMiddle + last_button_pressed = last_button + case last_state&mouse_lmb != 0 && cur_state&mouse_lmb == 0: + last_button = MouseRelease + case last_state&mouse_rmb != 0 && cur_state&mouse_rmb == 0: + last_button = MouseRelease + case last_state&mouse_mmb != 0 && cur_state&mouse_mmb == 0: + last_button = MouseRelease + default: + last_state = cur_state + continue + } + last_state = cur_state + ev.Key = last_button + last_x, last_y = int(mr.mouse_pos.x), int(mr.mouse_pos.y) + ev.MouseX = last_x + ev.MouseY = last_y + case 1: + // mouse motion + x, y := int(mr.mouse_pos.x), int(mr.mouse_pos.y) + if last_state != 0 && (last_x != x || last_y != y) { + ev.Key = last_button_pressed + ev.Mod = ModMotion + ev.MouseX = x + ev.MouseY = y + last_x, last_y = x, y + } else { + ev.Type = EventNone + } + case 4: + // mouse wheel + n := int16(mr.button_state >> 16) + if n > 0 { + ev.Key = MouseWheelUp + } else { + ev.Key = MouseWheelDown + } + last_x, last_y = int(mr.mouse_pos.x), int(mr.mouse_pos.y) + ev.MouseX = last_x + ev.MouseY = last_y + default: + ev.Type = EventNone + } + if ev.Type != EventNone { + input_comm <- ev + } + } + } +} diff --git a/vendor/github.com/nsf/termbox-go/terminfo.go b/vendor/github.com/nsf/termbox-go/terminfo.go new file mode 100644 index 0000000..35dbd70 --- /dev/null +++ b/vendor/github.com/nsf/termbox-go/terminfo.go @@ -0,0 +1,221 @@ +// +build !windows +// This file contains a simple and incomplete implementation of the terminfo +// database. Information was taken from the ncurses manpages term(5) and +// terminfo(5). Currently, only the string capabilities for special keys and for +// functions without parameters are actually used. Colors are still done with +// ANSI escape sequences. Other special features that are not (yet?) supported +// are reading from ~/.terminfo, the TERMINFO_DIRS variable, Berkeley database +// format and extended capabilities. + +package termbox + +import ( + "bytes" + "encoding/binary" + "encoding/hex" + "errors" + "fmt" + "io/ioutil" + "os" + "strings" +) + +const ( + ti_magic = 0432 + ti_header_length = 12 + ti_mouse_enter = "\x1b[?1000h\x1b[?1002h\x1b[?1015h\x1b[?1006h" + ti_mouse_leave = "\x1b[?1006l\x1b[?1015l\x1b[?1002l\x1b[?1000l" +) + +func load_terminfo() ([]byte, error) { + var data []byte + var err error + + term := os.Getenv("TERM") + if term == "" { + return nil, fmt.Errorf("termbox: TERM not set") + } + + // The following behaviour follows the one described in terminfo(5) as + // distributed by ncurses. + + terminfo := os.Getenv("TERMINFO") + if terminfo != "" { + // if TERMINFO is set, no other directory should be searched + return ti_try_path(terminfo) + } + + // next, consider ~/.terminfo + home := os.Getenv("HOME") + if home != "" { + data, err = ti_try_path(home + "/.terminfo") + if err == nil { + return data, nil + } + } + + // next, TERMINFO_DIRS + dirs := os.Getenv("TERMINFO_DIRS") + if dirs != "" { + for _, dir := range strings.Split(dirs, ":") { + if dir == "" { + // "" -> "/usr/share/terminfo" + dir = "/usr/share/terminfo" + } + data, err = ti_try_path(dir) + if err == nil { + return data, nil + } + } + } + + // fall back to /usr/share/terminfo + return ti_try_path("/usr/share/terminfo") +} + +func ti_try_path(path string) (data []byte, err error) { + // load_terminfo already made sure it is set + term := os.Getenv("TERM") + + // first try, the typical *nix path + terminfo := path + "/" + term[0:1] + "/" + term + data, err = ioutil.ReadFile(terminfo) + if err == nil { + return + } + + // fallback to darwin specific dirs structure + terminfo = path + "/" + hex.EncodeToString([]byte(term[:1])) + "/" + term + data, err = ioutil.ReadFile(terminfo) + return +} + +func setup_term_builtin() error { + name := os.Getenv("TERM") + if name == "" { + return errors.New("termbox: TERM environment variable not set") + } + + for _, t := range terms { + if t.name == name { + keys = t.keys + funcs = t.funcs + return nil + } + } + + compat_table := []struct { + partial string + keys []string + funcs []string + }{ + {"xterm", xterm_keys, xterm_funcs}, + {"rxvt", rxvt_unicode_keys, rxvt_unicode_funcs}, + {"linux", linux_keys, linux_funcs}, + {"Eterm", eterm_keys, eterm_funcs}, + {"screen", screen_keys, screen_funcs}, + // let's assume that 'cygwin' is xterm compatible + {"cygwin", xterm_keys, xterm_funcs}, + {"st", xterm_keys, xterm_funcs}, + } + + // try compatibility variants + for _, it := range compat_table { + if strings.Contains(name, it.partial) { + keys = it.keys + funcs = it.funcs + return nil + } + } + + return errors.New("termbox: unsupported terminal") +} + +func setup_term() (err error) { + var data []byte + var header [6]int16 + var str_offset, table_offset int16 + + data, err = load_terminfo() + if err != nil { + return setup_term_builtin() + } + + rd := bytes.NewReader(data) + // 0: magic number, 1: size of names section, 2: size of boolean section, 3: + // size of numbers section (in integers), 4: size of the strings section (in + // integers), 5: size of the string table + + err = binary.Read(rd, binary.LittleEndian, header[:]) + if err != nil { + return + } + + if (header[1]+header[2])%2 != 0 { + // old quirk to align everything on word boundaries + header[2] += 1 + } + str_offset = ti_header_length + header[1] + header[2] + 2*header[3] + table_offset = str_offset + 2*header[4] + + keys = make([]string, 0xFFFF-key_min) + for i, _ := range keys { + keys[i], err = ti_read_string(rd, str_offset+2*ti_keys[i], table_offset) + if err != nil { + return + } + } + funcs = make([]string, t_max_funcs) + // the last two entries are reserved for mouse. because the table offset is + // not there, the two entries have to fill in manually + for i, _ := range funcs[:len(funcs)-2] { + funcs[i], err = ti_read_string(rd, str_offset+2*ti_funcs[i], table_offset) + if err != nil { + return + } + } + funcs[t_max_funcs-2] = ti_mouse_enter + funcs[t_max_funcs-1] = ti_mouse_leave + return nil +} + +func ti_read_string(rd *bytes.Reader, str_off, table int16) (string, error) { + var off int16 + + _, err := rd.Seek(int64(str_off), 0) + if err != nil { + return "", err + } + err = binary.Read(rd, binary.LittleEndian, &off) + if err != nil { + return "", err + } + _, err = rd.Seek(int64(table+off), 0) + if err != nil { + return "", err + } + var bs []byte + for { + b, err := rd.ReadByte() + if err != nil { + return "", err + } + if b == byte(0x00) { + break + } + bs = append(bs, b) + } + return string(bs), nil +} + +// "Maps" the function constants from termbox.go to the number of the respective +// string capability in the terminfo file. Taken from (ncurses) term.h. +var ti_funcs = []int16{ + 28, 40, 16, 13, 5, 39, 36, 27, 26, 34, 89, 88, +} + +// Same as above for the special keys. +var ti_keys = []int16{ + 66, 68 /* apparently not a typo; 67 is F10 for whatever reason */, 69, 70, + 71, 72, 73, 74, 75, 67, 216, 217, 77, 59, 76, 164, 82, 81, 87, 61, 79, 83, +} diff --git a/vendor/github.com/nsf/termbox-go/terminfo_builtin.go b/vendor/github.com/nsf/termbox-go/terminfo_builtin.go new file mode 100644 index 0000000..a948660 --- /dev/null +++ b/vendor/github.com/nsf/termbox-go/terminfo_builtin.go @@ -0,0 +1,64 @@ +// +build !windows + +package termbox + +// Eterm +var eterm_keys = []string{ + "\x1b[11~", "\x1b[12~", "\x1b[13~", "\x1b[14~", "\x1b[15~", "\x1b[17~", "\x1b[18~", "\x1b[19~", "\x1b[20~", "\x1b[21~", "\x1b[23~", "\x1b[24~", "\x1b[2~", "\x1b[3~", "\x1b[7~", "\x1b[8~", "\x1b[5~", "\x1b[6~", "\x1b[A", "\x1b[B", "\x1b[D", "\x1b[C", +} +var eterm_funcs = []string{ + "\x1b7\x1b[?47h", "\x1b[2J\x1b[?47l\x1b8", "\x1b[?25h", "\x1b[?25l", "\x1b[H\x1b[2J", "\x1b[m\x0f", "\x1b[4m", "\x1b[1m", "\x1b[5m", "\x1b[7m", "", "", "", "", +} + +// screen +var screen_keys = []string{ + "\x1bOP", "\x1bOQ", "\x1bOR", "\x1bOS", "\x1b[15~", "\x1b[17~", "\x1b[18~", "\x1b[19~", "\x1b[20~", "\x1b[21~", "\x1b[23~", "\x1b[24~", "\x1b[2~", "\x1b[3~", "\x1b[1~", "\x1b[4~", "\x1b[5~", "\x1b[6~", "\x1bOA", "\x1bOB", "\x1bOD", "\x1bOC", +} +var screen_funcs = []string{ + "\x1b[?1049h", "\x1b[?1049l", "\x1b[34h\x1b[?25h", "\x1b[?25l", "\x1b[H\x1b[J", "\x1b[m\x0f", "\x1b[4m", "\x1b[1m", "\x1b[5m", "\x1b[7m", "\x1b[?1h\x1b=", "\x1b[?1l\x1b>", ti_mouse_enter, ti_mouse_leave, +} + +// xterm +var xterm_keys = []string{ + "\x1bOP", "\x1bOQ", "\x1bOR", "\x1bOS", "\x1b[15~", "\x1b[17~", "\x1b[18~", "\x1b[19~", "\x1b[20~", "\x1b[21~", "\x1b[23~", "\x1b[24~", "\x1b[2~", "\x1b[3~", "\x1bOH", "\x1bOF", "\x1b[5~", "\x1b[6~", "\x1bOA", "\x1bOB", "\x1bOD", "\x1bOC", +} +var xterm_funcs = []string{ + "\x1b[?1049h", "\x1b[?1049l", "\x1b[?12l\x1b[?25h", "\x1b[?25l", "\x1b[H\x1b[2J", "\x1b(B\x1b[m", "\x1b[4m", "\x1b[1m", "\x1b[5m", "\x1b[7m", "\x1b[?1h\x1b=", "\x1b[?1l\x1b>", ti_mouse_enter, ti_mouse_leave, +} + +// rxvt-unicode +var rxvt_unicode_keys = []string{ + "\x1b[11~", "\x1b[12~", "\x1b[13~", "\x1b[14~", "\x1b[15~", "\x1b[17~", "\x1b[18~", "\x1b[19~", "\x1b[20~", "\x1b[21~", "\x1b[23~", "\x1b[24~", "\x1b[2~", "\x1b[3~", "\x1b[7~", "\x1b[8~", "\x1b[5~", "\x1b[6~", "\x1b[A", "\x1b[B", "\x1b[D", "\x1b[C", +} +var rxvt_unicode_funcs = []string{ + "\x1b[?1049h", "\x1b[r\x1b[?1049l", "\x1b[?25h", "\x1b[?25l", "\x1b[H\x1b[2J", "\x1b[m\x1b(B", "\x1b[4m", "\x1b[1m", "\x1b[5m", "\x1b[7m", "\x1b=", "\x1b>", ti_mouse_enter, ti_mouse_leave, +} + +// linux +var linux_keys = []string{ + "\x1b[[A", "\x1b[[B", "\x1b[[C", "\x1b[[D", "\x1b[[E", "\x1b[17~", "\x1b[18~", "\x1b[19~", "\x1b[20~", "\x1b[21~", "\x1b[23~", "\x1b[24~", "\x1b[2~", "\x1b[3~", "\x1b[1~", "\x1b[4~", "\x1b[5~", "\x1b[6~", "\x1b[A", "\x1b[B", "\x1b[D", "\x1b[C", +} +var linux_funcs = []string{ + "", "", "\x1b[?25h\x1b[?0c", "\x1b[?25l\x1b[?1c", "\x1b[H\x1b[J", "\x1b[0;10m", "\x1b[4m", "\x1b[1m", "\x1b[5m", "\x1b[7m", "", "", "", "", +} + +// rxvt-256color +var rxvt_256color_keys = []string{ + "\x1b[11~", "\x1b[12~", "\x1b[13~", "\x1b[14~", "\x1b[15~", "\x1b[17~", "\x1b[18~", "\x1b[19~", "\x1b[20~", "\x1b[21~", "\x1b[23~", "\x1b[24~", "\x1b[2~", "\x1b[3~", "\x1b[7~", "\x1b[8~", "\x1b[5~", "\x1b[6~", "\x1b[A", "\x1b[B", "\x1b[D", "\x1b[C", +} +var rxvt_256color_funcs = []string{ + "\x1b7\x1b[?47h", "\x1b[2J\x1b[?47l\x1b8", "\x1b[?25h", "\x1b[?25l", "\x1b[H\x1b[2J", "\x1b[m\x0f", "\x1b[4m", "\x1b[1m", "\x1b[5m", "\x1b[7m", "\x1b=", "\x1b>", ti_mouse_enter, ti_mouse_leave, +} + +var terms = []struct { + name string + keys []string + funcs []string +}{ + {"Eterm", eterm_keys, eterm_funcs}, + {"screen", screen_keys, screen_funcs}, + {"xterm", xterm_keys, xterm_funcs}, + {"rxvt-unicode", rxvt_unicode_keys, rxvt_unicode_funcs}, + {"linux", linux_keys, linux_funcs}, + {"rxvt-256color", rxvt_256color_keys, rxvt_256color_funcs}, +} diff --git a/vendor/gogs.bullercodeworks.com/brian/termbox-util/LICENSE b/vendor/gogs.bullercodeworks.com/brian/termbox-util/LICENSE new file mode 100644 index 0000000..70566f2 --- /dev/null +++ b/vendor/gogs.bullercodeworks.com/brian/termbox-util/LICENSE @@ -0,0 +1,674 @@ +GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {one line to give the program's name and a brief idea of what it does.} + Copyright (C) {year} {name of author} + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + {project} Copyright (C) {year} {fullname} + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. \ No newline at end of file diff --git a/vendor/gogs.bullercodeworks.com/brian/termbox-util/README.md b/vendor/gogs.bullercodeworks.com/brian/termbox-util/README.md new file mode 100644 index 0000000..089d459 --- /dev/null +++ b/vendor/gogs.bullercodeworks.com/brian/termbox-util/README.md @@ -0,0 +1,4 @@ +termbox-util +============ + +Utility Library for Termbox \ No newline at end of file diff --git a/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_alertmodal.go b/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_alertmodal.go new file mode 100644 index 0000000..ea6ec99 --- /dev/null +++ b/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_alertmodal.go @@ -0,0 +1,212 @@ +package termboxUtil + +import ( + "github.com/nsf/termbox-go" +) + +// AlertModal is a modal with yes/no (or similar) buttons +type AlertModal struct { + id string + title string + text string + x, y, width, height int + showHelp bool + cursor int + bg, fg termbox.Attribute + isDone bool + accepted bool + value string + isVisible bool + bordered bool + tabSkip bool +} + +// CreateAlertModal Creates a confirmation modal with the specified attributes +func CreateAlertModal(title string, x, y, width, height int, fg, bg termbox.Attribute) *AlertModal { + i := AlertModal{title: title, x: x, y: y, width: width, height: height, fg: fg, bg: bg, bordered: true} + if i.title == "" { + i.title = "Alert!" + } + i.showHelp = true + return &i +} + +// GetID returns this control's ID +func (i *AlertModal) GetID() string { return i.id } + +// SetID sets this control's ID +func (i *AlertModal) SetID(newID string) { + i.id = newID +} + +// GetTitle returns the current title of the modal +func (i *AlertModal) GetTitle() string { return i.title } + +// SetTitle sets the current title of the modal to s +func (i *AlertModal) SetTitle(s string) { + i.title = s +} + +// GetText returns the current text of the modal +func (i *AlertModal) GetText() string { return i.text } + +// SetText sets the text of the modal to s +func (i *AlertModal) SetText(s string) { + i.text = s +} + +// GetX returns the current x coordinate of the control +func (i *AlertModal) GetX() int { return i.x } + +// SetX sets the current x coordinate of the control to x +func (i *AlertModal) SetX(x int) { + i.x = x +} + +// GetY returns the current y coordinate of the control +func (i *AlertModal) GetY() int { return i.y } + +// SetY sets the current y coordinate of the control to y +func (i *AlertModal) SetY(y int) { + i.y = y +} + +// GetWidth returns the current width of the control +func (i *AlertModal) GetWidth() int { return i.width } + +// SetWidth sets the current control width to width +func (i *AlertModal) SetWidth(width int) { + i.width = width +} + +// GetHeight returns the current height of the control +func (i *AlertModal) GetHeight() int { return i.height } + +// SetHeight set the height of the control to height +func (i *AlertModal) SetHeight(height int) { + i.height = height +} + +// GetFgColor returns the foreground color +func (i *AlertModal) GetFgColor() termbox.Attribute { return i.fg } + +// SetFgColor sets the foreground color +func (i *AlertModal) SetFgColor(fg termbox.Attribute) { + i.fg = fg +} + +// GetBgColor returns the background color +func (i *AlertModal) GetBgColor() termbox.Attribute { return i.bg } + +// SetBgColor sets the current background color +func (i *AlertModal) SetBgColor(bg termbox.Attribute) { + i.bg = bg +} + +// IsBordered returns whether this control is bordered or not +func (i *AlertModal) IsBordered() bool { + return i.bordered +} + +// SetBordered sets whether we render a border around the frame +func (i *AlertModal) SetBordered(b bool) { + i.bordered = b +} + +// IsTabSkipped returns whether this control has it's tabskip flag set +func (i *AlertModal) IsTabSkipped() bool { + return i.tabSkip +} + +// SetTabSkip sets the tabskip flag for this control +func (i *AlertModal) SetTabSkip(b bool) { + i.tabSkip = b +} + +// HelpIsShown returns true or false if the help is displayed +func (i *AlertModal) HelpIsShown() bool { return i.showHelp } + +// ShowHelp sets whether or not to display the help text +func (i *AlertModal) ShowHelp(b bool) { + i.showHelp = b +} + +// GetBackground returns the current background color +func (i *AlertModal) GetBackground() termbox.Attribute { return i.bg } + +// SetBackground sets the background color to bg +func (i *AlertModal) SetBackground(bg termbox.Attribute) { + i.bg = bg +} + +// GetForeground returns the current foreground color +func (i *AlertModal) GetForeground() termbox.Attribute { return i.fg } + +// SetForeground sets the current foreground color to fg +func (i *AlertModal) SetForeground(fg termbox.Attribute) { + i.fg = fg +} + +// IsDone returns whether the user has answered the modal +func (i *AlertModal) IsDone() bool { return i.isDone } + +// SetDone sets whether the modal has completed it's purpose +func (i *AlertModal) SetDone(b bool) { + i.isDone = b +} + +// Show sets the visibility flag of the modal to true +func (i *AlertModal) Show() { + i.isVisible = true +} + +// Hide sets the visibility flag of the modal to false +func (i *AlertModal) Hide() { + i.isVisible = false +} + +// IsAccepted returns whether the user accepted the modal +func (i *AlertModal) IsAccepted() bool { return i.accepted } + +// Clear clears all of the non-positional parameters of the modal +func (i *AlertModal) Clear() { + i.title = "" + i.text = "" + i.accepted = false + i.isDone = false +} + +// HandleEvent handles the termbox event and returns whether it was consumed +func (i *AlertModal) HandleEvent(event termbox.Event) bool { + if event.Key == termbox.KeyEnter { + i.isDone = true + return true + } + return false +} + +// Draw draws the modal +func (i *AlertModal) Draw() { + // First blank out the area we'll be putting the modal + FillWithChar(' ', i.x, i.y, i.x+i.width, i.y+i.height, i.fg, i.bg) + // Now draw the border + DrawBorder(i.x, i.y, i.x+i.width, i.y+i.height, i.fg, i.bg) + + nextY := i.y + 1 + // The title + if i.title != "" { + DrawStringAtPoint(i.title, i.x+1, nextY, i.fg, i.bg) + nextY++ + FillWithChar('-', i.x+1, nextY, i.x+i.width-1, nextY, i.fg, i.bg) + nextY++ + } + if i.text != "" { + DrawStringAtPoint(i.text, i.x+1, nextY, i.fg, i.bg) + } + nextY += 2 + if i.showHelp { + helpString := "Press Enter to Continue" + helpX := (i.x + i.width) - len(helpString) - 1 + DrawStringAtPoint(helpString, helpX, nextY, i.fg, i.bg) + } +} diff --git a/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_asciiart.go b/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_asciiart.go new file mode 100644 index 0000000..4f0746e --- /dev/null +++ b/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_asciiart.go @@ -0,0 +1,171 @@ +package termboxUtil + +import ( + "strings" + + "github.com/nsf/termbox-go" +) + +// ASCIIArt is a []string with more functions +type ASCIIArt struct { + id string + contents []string + x, y int + bg, fg termbox.Attribute + bordered bool + tabSkip bool +} + +// CreateASCIIArt Create an ASCII art object from a string slice +func CreateASCIIArt(c []string, x, y int, fg, bg termbox.Attribute) *ASCIIArt { + i := ASCIIArt{contents: c, x: x, y: y, fg: fg, bg: bg, bordered: false, tabSkip: true} + return &i +} + +// GetID returns this control's ID +func (i *ASCIIArt) GetID() string { return i.id } + +// SetID sets this control's ID +func (i *ASCIIArt) SetID(newID string) { + i.id = newID +} + +// GetX Return the x position of the modal +func (i *ASCIIArt) GetX() int { return i.x } + +// SetX set the x position of the modal to x +func (i *ASCIIArt) SetX(x int) { + i.x = x +} + +// GetY Return the y position of the modal +func (i *ASCIIArt) GetY() int { return i.y } + +// SetY Set the y position of the modal to y +func (i *ASCIIArt) SetY(y int) { + i.y = y +} + +// GetHeight Returns the number of strings in the contents slice +func (i *ASCIIArt) GetHeight() int { + return len(i.contents) +} + +// SetHeight truncates lines from the bottom of the ascii art +func (i *ASCIIArt) SetHeight(h int) { + if len(i.contents) > h { + i.contents = i.contents[:h] + } else { + for j := len(i.contents); j < h; j++ { + i.contents = append(i.contents, "") + } + } +} + +// GetWidth Returns the number of strings in the contents slice +func (i *ASCIIArt) GetWidth() int { + // Find the longest line + var ret int + for j := range i.contents { + if len(i.contents[j]) > ret { + ret = len(i.contents[j]) + } + } + return ret +} + +// SetWidth Sets all lines in the contents to width w +func (i *ASCIIArt) SetWidth(w int) { + // Find the longest line + for j := range i.contents { + mkUp := w - len(i.contents[j]) + if mkUp > 0 { + i.contents[j] = i.contents[j] + strings.Repeat(" ", mkUp) + } else { + i.contents[j] = i.contents[j][:w] + } + } +} + +// SetContents Sets the contents of i to c +func (i *ASCIIArt) SetContents(c []string) { + i.contents = c +} + +// GetContents returns the ascii art +func (i *ASCIIArt) GetContents() []string { + return i.contents +} + +// SetContentLine Sets a specific line of the contents to s +func (i *ASCIIArt) SetContentLine(s string, idx int) { + if idx >= 0 && idx < len(i.contents) { + i.contents[idx] = s + } +} + +// GetFgColor returns the foreground color +func (i *ASCIIArt) GetFgColor() termbox.Attribute { return i.fg } + +// SetFgColor sets the foreground color +func (i *ASCIIArt) SetFgColor(fg termbox.Attribute) { + i.fg = fg +} + +// GetBgColor returns the background color +func (i *ASCIIArt) GetBgColor() termbox.Attribute { return i.bg } + +// SetBgColor sets the current background color +func (i *ASCIIArt) SetBgColor(bg termbox.Attribute) { + i.bg = bg +} + +// Align Align the Ascii art over width width with alignment a +func (i *ASCIIArt) Align(a TextAlignment, width int) { + // First get the width of the longest string in the slice + var newContents []string + incomingLength := 0 + for _, line := range i.contents { + if len(line) > incomingLength { + incomingLength = len(line) + } + } + for _, line := range i.contents { + newContents = append(newContents, AlignText(AlignText(line, incomingLength, AlignLeft), width, a)) + } + i.contents = newContents +} + +// IsBordered returns whether this modal is bordered or not +func (i *ASCIIArt) IsBordered() bool { + return i.bordered +} + +// SetBordered sets whether we render a border around the frame +func (i *ASCIIArt) SetBordered(b bool) { + i.bordered = b +} + +// IsTabSkipped returns whether this modal has it's tabskip flag set +func (i *ASCIIArt) IsTabSkipped() bool { + return i.tabSkip +} + +// SetTabSkip sets the tabskip flag for this control +func (i *ASCIIArt) SetTabSkip(b bool) { + i.tabSkip = b +} + +// HandleEvent accepts the termbox event and returns whether it was consumed +func (i *ASCIIArt) HandleEvent(event termbox.Event) bool { + return false +} + +// Draw outputs the input field on the screen +func (i *ASCIIArt) Draw() { + drawX, drawY := i.x, i.y + for _, line := range i.contents { + DrawStringAtPoint(line, drawX, drawY, i.fg, i.bg) + drawY++ + } +} diff --git a/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_confirmmodal.go b/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_confirmmodal.go new file mode 100644 index 0000000..9a22fd6 --- /dev/null +++ b/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_confirmmodal.go @@ -0,0 +1,201 @@ +package termboxUtil + +import ( + "github.com/nsf/termbox-go" +) + +// ConfirmModal is a modal with yes/no (or similar) buttons +type ConfirmModal struct { + id string + title string + text string + x, y, width, height int + showHelp bool + cursor int + bg, fg termbox.Attribute + isDone bool + accepted bool + value string + isVisible bool + bordered bool + tabSkip bool +} + +// CreateConfirmModal Creates a confirmation modal with the specified attributes +func CreateConfirmModal(title string, x, y, width, height int, fg, bg termbox.Attribute) *ConfirmModal { + i := ConfirmModal{title: title, x: x, y: y, width: width, height: height, fg: fg, bg: bg} + if i.title == "" && i.text == "" { + i.title = "Confirm?" + } + i.showHelp = true + return &i +} + +// GetID returns this control's ID +func (i *ConfirmModal) GetID() string { return i.id } + +// SetID sets this control's ID +func (i *ConfirmModal) SetID(newID string) { + i.id = newID +} + +// GetTitle returns the current title of the modal +func (i *ConfirmModal) GetTitle() string { return i.title } + +// SetTitle sets the current title of the modal to s +func (i *ConfirmModal) SetTitle(s string) { + i.title = s +} + +// GetText returns the current text of the modal +func (i *ConfirmModal) GetText() string { return i.text } + +// SetText sets the text of the modal to s +func (i *ConfirmModal) SetText(s string) { + i.text = s +} + +// GetX returns the current x coordinate of the modal +func (i *ConfirmModal) GetX() int { return i.x } + +// SetX sets the current x coordinate of the modal to x +func (i *ConfirmModal) SetX(x int) { + i.x = x +} + +// GetY returns the current y coordinate of the modal +func (i *ConfirmModal) GetY() int { return i.y } + +// SetY sets the current y coordinate of the modal to y +func (i *ConfirmModal) SetY(y int) { + i.y = y +} + +// GetWidth returns the current width of the modal +func (i *ConfirmModal) GetWidth() int { return i.width } + +// SetWidth sets the current modal width to width +func (i *ConfirmModal) SetWidth(width int) { + i.width = width +} + +// GetHeight returns the current height of the modal +func (i *ConfirmModal) GetHeight() int { return i.height } + +// SetHeight set the height of the modal to height +func (i *ConfirmModal) SetHeight(height int) { + i.height = height +} + +// HelpIsShown returns true or false if the help is displayed +func (i *ConfirmModal) HelpIsShown() bool { return i.showHelp } + +// ShowHelp sets whether or not to display the help text +func (i *ConfirmModal) ShowHelp(b bool) { + i.showHelp = b +} + +// GetFgColor returns the foreground color +func (i *ConfirmModal) GetFgColor() termbox.Attribute { return i.fg } + +// SetFgColor sets the foreground color +func (i *ConfirmModal) SetFgColor(fg termbox.Attribute) { + i.fg = fg +} + +// GetBgColor returns the background color +func (i *ConfirmModal) GetBgColor() termbox.Attribute { return i.bg } + +// SetBgColor sets the current background color +func (i *ConfirmModal) SetBgColor(bg termbox.Attribute) { + i.bg = bg +} + +// IsDone returns whether the user has answered the modal +func (i *ConfirmModal) IsDone() bool { return i.isDone } + +// SetDone sets whether the modal has completed it's purpose +func (i *ConfirmModal) SetDone(b bool) { + i.isDone = b +} + +// Show sets the visibility flag of the modal to true +func (i *ConfirmModal) Show() { + i.isVisible = true +} + +// Hide sets the visibility flag of the modal to false +func (i *ConfirmModal) Hide() { + i.isVisible = false +} + +// IsAccepted returns whether the user accepted the modal +func (i *ConfirmModal) IsAccepted() bool { return i.accepted } + +// Clear clears all of the non-positional parameters of the modal +func (i *ConfirmModal) Clear() { + i.title = "" + i.text = "" + i.accepted = false + i.isDone = false +} + +// IsBordered returns whether this modal is bordered or not +func (i *ConfirmModal) IsBordered() bool { + return i.bordered +} + +// SetBordered sets whether we render a border around the frame +func (i *ConfirmModal) SetBordered(b bool) { + i.bordered = b +} + +// IsTabSkipped returns whether this modal has it's tabskip flag set +func (i *ConfirmModal) IsTabSkipped() bool { + return i.tabSkip +} + +// SetTabSkip sets the tabskip flag for this control +func (i *ConfirmModal) SetTabSkip(b bool) { + i.tabSkip = b +} + +// HandleEvent handles the termbox event and returns whether it was consumed +func (i *ConfirmModal) HandleEvent(event termbox.Event) bool { + if event.Ch == 'Y' || event.Ch == 'y' { + i.accepted = true + i.isDone = true + return true + } else if event.Ch == 'N' || event.Ch == 'n' { + i.accepted = false + i.isDone = true + return true + } + return false +} + +// Draw draws the modal +func (i *ConfirmModal) Draw() { + // First blank out the area we'll be putting the modal + FillWithChar(' ', i.x, i.y, i.x+i.width, i.y+i.height, i.fg, i.bg) + // Now draw the border + DrawBorder(i.x, i.y, i.x+i.width, i.y+i.height, i.fg, i.bg) + + nextY := i.y + 1 + // The title + if i.title != "" { + DrawStringAtPoint(i.title, i.x+1, nextY, i.fg, i.bg) + nextY++ + FillWithChar('-', i.x+1, nextY, i.x+i.width-1, nextY, i.fg, i.bg) + nextY++ + } + if i.text != "" { + DrawStringAtPoint(i.text, i.x+1, nextY, i.fg, i.bg) + } + nextY += 2 + if i.showHelp { + helpString := " (Y/y) Confirm. (N/n) Reject. " + helpX := (i.x + i.width) - len(helpString) - 1 + DrawStringAtPoint(helpString, helpX, nextY, i.fg, i.bg) + } +} diff --git a/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_dropmenu.go b/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_dropmenu.go new file mode 100644 index 0000000..3d755d7 --- /dev/null +++ b/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_dropmenu.go @@ -0,0 +1,177 @@ +package termboxUtil + +import "github.com/nsf/termbox-go" + +// DropMenu is a title that, when active drops a menu down +type DropMenu struct { + id string + title string + x, y, width, height int + bg, fg termbox.Attribute + selectedBg, selectedFg termbox.Attribute + menu *Menu + menuSelected bool + showMenu bool + bordered bool + tabSkip bool +} + +// CreateDropMenu Creates a menu with the specified attributes +func CreateDropMenu(title string, options []string, x, y, width, height int, fg, bg, selectedFg, selectedBg termbox.Attribute) *DropMenu { + i := DropMenu{ + title: title, + x: x, y: y, width: width, height: height, + fg: fg, bg: bg, + selectedFg: fg, selectedBg: bg, + } + i.menu = CreateMenu("", options, x, y+2, width, height, fg, bg) + return &i +} + +// GetID returns this control's ID +func (i *DropMenu) GetID() string { return i.id } + +// SetID sets this control's ID +func (i *DropMenu) SetID(newID string) { + i.id = newID +} + +// GetTitle returns the current title of the menu +func (i *DropMenu) GetTitle() string { return i.title } + +// SetTitle sets the current title of the menu to s +func (i *DropMenu) SetTitle(s string) { + i.title = s +} + +// GetMenu returns the menu for this dropmenu +func (i *DropMenu) GetMenu() *Menu { + return i.menu +} + +// GetX returns the current x coordinate of the menu +func (i *DropMenu) GetX() int { return i.x } + +// SetX sets the current x coordinate of the menu to x +func (i *DropMenu) SetX(x int) { + i.x = x +} + +// GetY returns the current y coordinate of the menu +func (i *DropMenu) GetY() int { return i.y } + +// SetY sets the current y coordinate of the menu to y +func (i *DropMenu) SetY(y int) { + i.y = y +} + +// GetWidth returns the current width of the menu +func (i *DropMenu) GetWidth() int { return i.width } + +// SetWidth sets the current menu width to width +func (i *DropMenu) SetWidth(width int) { + i.width = width +} + +// GetHeight returns the current height of the menu +func (i *DropMenu) GetHeight() int { return i.height } + +// SetHeight set the height of the menu to height +func (i *DropMenu) SetHeight(height int) { + i.height = height +} + +// GetFgColor returns the foreground color +func (i *DropMenu) GetFgColor() termbox.Attribute { return i.fg } + +// SetFgColor sets the foreground color +func (i *DropMenu) SetFgColor(fg termbox.Attribute) { + i.fg = fg +} + +// GetBgColor returns the background color +func (i *DropMenu) GetBgColor() termbox.Attribute { return i.bg } + +// SetBgColor sets the current background color +func (i *DropMenu) SetBgColor(bg termbox.Attribute) { + i.bg = bg +} + +// IsBordered returns the bordered flag +func (i *DropMenu) IsBordered() bool { return i.bordered } + +// SetBordered sets the bordered flag +func (i *DropMenu) SetBordered(b bool) { + i.bordered = b + i.menu.SetBordered(b) +} + +// IsDone returns whether the user has answered the modal +func (i *DropMenu) IsDone() bool { return i.menu.isDone } + +// SetDone sets whether the modal has completed it's purpose +func (i *DropMenu) SetDone(b bool) { + i.menu.isDone = b +} + +// IsTabSkipped returns whether this modal has it's tabskip flag set +func (i *DropMenu) IsTabSkipped() bool { + return i.tabSkip +} + +// SetTabSkip sets the tabskip flag for this control +func (i *DropMenu) SetTabSkip(b bool) { + i.tabSkip = b +} + +// ShowMenu tells the menu to draw the options +func (i *DropMenu) ShowMenu() { + i.showMenu = true + i.menuSelected = true +} + +// HideMenu tells the menu to hide the options +func (i *DropMenu) HideMenu() { + i.showMenu = false + i.menuSelected = false +} + +// HandleEvent handles the termbox event and returns whether it was consumed +func (i *DropMenu) HandleEvent(event termbox.Event) bool { + moveUp := (event.Key == termbox.KeyArrowUp || (i.menu.vimMode && event.Ch == 'k')) + moveDown := (event.Key == termbox.KeyArrowDown || (i.menu.vimMode && event.Ch == 'j')) + if i.menuSelected { + selIdx := i.menu.GetSelectedIndex() + if (moveUp && selIdx == 0) || (moveDown && selIdx == (len(i.menu.options)-1)) { + i.menuSelected = false + } else { + if i.menu.HandleEvent(event) { + if i.menu.IsDone() { + i.HideMenu() + } + return true + } + } + } else { + i.ShowMenu() + return true + } + return false +} + +// Draw draws the menu +func (i *DropMenu) Draw() { + // The title + ttlFg, ttlBg := i.fg, i.bg + if !i.menuSelected { + ttlFg, ttlBg = i.selectedFg, i.selectedBg + } + ttlTxt := i.title + if i.showMenu { + ttlTxt = ttlTxt + "-Showing Menu" + } + DrawStringAtPoint(AlignText(i.title, i.width, AlignLeft), i.x, i.y, ttlFg, ttlBg) + if i.showMenu { + i.menu.Draw() + } +} diff --git a/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_frame.go b/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_frame.go new file mode 100644 index 0000000..fa1df36 --- /dev/null +++ b/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_frame.go @@ -0,0 +1,198 @@ +package termboxUtil + +import "github.com/nsf/termbox-go" + +// Frame is a frame for holding other elements +// It manages it's own x/y, tab index +type Frame struct { + id string + x, y, width, height int + tabIdx int + fg, bg termbox.Attribute + bordered bool + controls []termboxControl + tabSkip bool +} + +// CreateFrame creates a Frame at x, y that is w by h +func CreateFrame(x, y, w, h int, fg, bg termbox.Attribute) *Frame { + s := Frame{x: x, y: y, width: w, height: h, fg: fg, bg: bg, bordered: true} + return &s +} + +// GetID returns this control's ID +func (i *Frame) GetID() string { return i.id } + +// SetID sets this control's ID +func (i *Frame) SetID(newID string) { + i.id = newID +} + +// GetX returns the x position of the frame +func (i *Frame) GetX() int { return i.x } + +// SetX sets the x position of the frame +func (i *Frame) SetX(x int) { + i.x = x +} + +// GetY returns the y position of the frame +func (i *Frame) GetY() int { return i.y } + +// SetY sets the y position of the frame +func (i *Frame) SetY(y int) { + i.y = y +} + +// GetWidth returns the current width of the frame +func (i *Frame) GetWidth() int { return i.width } + +// SetWidth sets the current width of the frame +func (i *Frame) SetWidth(w int) { + i.width = w +} + +// GetHeight returns the current height of the frame +func (i *Frame) GetHeight() int { return i.height } + +// SetHeight sets the current height of the frame +func (i *Frame) SetHeight(h int) { + i.height = h +} + +// GetFgColor returns the foreground color +func (i *Frame) GetFgColor() termbox.Attribute { return i.fg } + +// SetFgColor sets the foreground color +func (i *Frame) SetFgColor(fg termbox.Attribute) { + i.fg = fg +} + +// GetBgColor returns the background color +func (i *Frame) GetBgColor() termbox.Attribute { return i.bg } + +// SetBgColor sets the current background color +func (i *Frame) SetBgColor(bg termbox.Attribute) { + i.bg = bg +} + +// IsBordered returns true or false if this frame has a border +func (i *Frame) IsBordered() bool { return i.bordered } + +// SetBordered sets whether we render a border around the frame +func (i *Frame) SetBordered(b bool) { + i.bordered = b +} + +// IsTabSkipped returns whether this modal has it's tabskip flag set +func (i *Frame) IsTabSkipped() bool { + return i.tabSkip +} + +// SetTabSkip sets the tabskip flag for this control +func (i *Frame) SetTabSkip(b bool) { + i.tabSkip = b +} + +// AddControl adds a control to the frame +func (i *Frame) AddControl(t termboxControl) { + i.controls = append(i.controls, t) +} + +// GetActiveControl returns the control at tabIdx +func (i *Frame) GetActiveControl() termboxControl { + if len(i.controls) >= i.tabIdx { + return i.controls[i.tabIdx] + } + return nil +} + +// GetControls returns a slice of all controls +func (i *Frame) GetControls() []termboxControl { + return i.controls +} + +// GetControl returns the control at index i +func (i *Frame) GetControl(idx int) termboxControl { + if len(i.controls) >= idx { + return i.controls[idx] + } + return nil +} + +// GetControlCount returns the number of controls contained +func (i *Frame) GetControlCount() int { + return len(i.controls) +} + +// GetLastControl returns the last control contained +func (i *Frame) GetLastControl() termboxControl { + return i.controls[len(i.controls)-1] +} + +// DrawControl figures out the relative position of the control, +// sets it, draws it, then resets it. +func (i *Frame) DrawControl(t termboxControl) { + ctlX, ctlY := t.GetX(), t.GetY() + t.SetX((i.GetX() + ctlX)) + t.SetY((i.GetY() + ctlY)) + t.Draw() + t.SetX(ctlX) + t.SetY(ctlY) +} + +// GetBottomY returns the y of the lowest control in the frame +func (i *Frame) GetBottomY() int { + var ret int + for idx := range i.controls { + if i.controls[idx].GetY()+i.controls[idx].GetHeight() > ret { + ret = i.controls[idx].GetY() + i.controls[idx].GetHeight() + } + } + return ret +} + +// HandleEvent accepts the termbox event and returns whether it was consumed +func (i *Frame) HandleEvent(event termbox.Event) bool { + if event.Key == termbox.KeyTab { + i.FindNextTabStop() + return true + } + return i.controls[i.tabIdx].HandleEvent(event) +} + +// FindNextTabStop finds the next control that can be tabbed to +// A return of true means it found a different one than we started on. +func (i *Frame) FindNextTabStop() bool { + startTab := i.tabIdx + i.tabIdx = (i.tabIdx + 1) % len(i.controls) + for i.controls[i.tabIdx].IsTabSkipped() { + i.tabIdx = (i.tabIdx + 1) % len(i.controls) + if i.tabIdx == startTab { + break + } + } + return i.tabIdx != startTab +} + +// Draw outputs the Scoll Frame on the screen +func (i *Frame) Draw() { + maxWidth := i.width + maxHeight := i.height + x, y := i.x, i.y + startX := i.x + startY := i.y + if i.bordered { + FillWithChar(' ', i.x, i.y, i.x+i.width, i.y+i.height, i.fg, i.bg) + DrawBorder(i.x, i.y, i.x+i.width, i.y+i.height, i.fg, i.bg) + maxWidth-- + maxHeight-- + x++ + y++ + startX++ + startY++ + } + for idx := range i.controls { + i.DrawControl(i.controls[idx]) + } +} diff --git a/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_inputfield.go b/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_inputfield.go new file mode 100644 index 0000000..089ff51 --- /dev/null +++ b/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_inputfield.go @@ -0,0 +1,261 @@ +package termboxUtil + +import "github.com/nsf/termbox-go" + +// InputField is a field for inputting text +type InputField struct { + id string + value string + x, y, width, height int + cursor int + fg, bg termbox.Attribute + cursorFg, cursorBg termbox.Attribute + bordered bool + wrap bool + multiline bool + tabSkip bool +} + +// CreateInputField creates an input field at x, y that is w by h +func CreateInputField(x, y, w, h int, fg, bg termbox.Attribute) *InputField { + i := InputField{x: x, y: y, width: w, height: h, fg: fg, bg: bg, cursorFg: bg, cursorBg: fg} + return &i +} + +// GetID returns this control's ID +func (i *InputField) GetID() string { return i.id } + +// SetID sets this control's ID +func (i *InputField) SetID(newID string) { + i.id = newID +} + +// GetValue gets the current text that is in the InputField +func (i *InputField) GetValue() string { return i.value } + +// SetValue sets the current text in the InputField to s +func (i *InputField) SetValue(s string) { + i.value = s +} + +// GetX returns the x position of the input field +func (i *InputField) GetX() int { return i.x } + +// SetX sets the x position of the input field +func (i *InputField) SetX(x int) { + i.x = x +} + +// GetY returns the y position of the input field +func (i *InputField) GetY() int { return i.y } + +// SetY sets the y position of the input field +func (i *InputField) SetY(y int) { + i.y = y +} + +// GetWidth returns the current width of the input field +func (i *InputField) GetWidth() int { return i.width } + +// SetWidth sets the current width of the input field +func (i *InputField) SetWidth(w int) { + i.width = w +} + +// GetHeight returns the current height of the input field +func (i *InputField) GetHeight() int { return i.height } + +// SetHeight sets the current height of the input field +func (i *InputField) SetHeight(h int) { + i.height = h +} + +// GetFgColor returns the foreground color +func (i *InputField) GetFgColor() termbox.Attribute { return i.fg } + +// SetFgColor sets the foreground color +func (i *InputField) SetFgColor(fg termbox.Attribute) { + i.fg = fg +} + +// GetBgColor returns the background color +func (i *InputField) GetBgColor() termbox.Attribute { return i.bg } + +// SetBgColor sets the current background color +func (i *InputField) SetBgColor(bg termbox.Attribute) { + i.bg = bg +} + +// IsBordered returns true or false if this input field has a border +func (i *InputField) IsBordered() bool { return i.bordered } + +// SetBordered sets whether we render a border around the input field +func (i *InputField) SetBordered(b bool) { + i.bordered = b +} + +// IsTabSkipped returns whether this modal has it's tabskip flag set +func (i *InputField) IsTabSkipped() bool { + return i.tabSkip +} + +// SetTabSkip sets the tabskip flag for this control +func (i *InputField) SetTabSkip(b bool) { + i.tabSkip = b +} + +// DoesWrap returns true or false if this input field wraps text +func (i *InputField) DoesWrap() bool { return i.wrap } + +// SetWrap sets whether we wrap the text at width. +func (i *InputField) SetWrap(b bool) { + i.wrap = b +} + +// IsMultiline returns true or false if this field can have multiple lines +func (i *InputField) IsMultiline() bool { return i.multiline } + +// SetMultiline sets whether the field can have multiple lines +func (i *InputField) SetMultiline(b bool) { + i.multiline = b +} + +// HandleEvent accepts the termbox event and returns whether it was consumed +func (i *InputField) HandleEvent(event termbox.Event) bool { + if event.Key == termbox.KeyBackspace || event.Key == termbox.KeyBackspace2 { + if len(i.value) > 0 { + i.value = i.value[:len(i.value)-1] + } + } else if event.Key == termbox.KeyArrowLeft { + if i.cursor+len(i.value) > 0 { + i.cursor-- + } + } else if event.Key == termbox.KeyArrowRight { + if i.cursor < 0 { + i.cursor++ + } + } else if event.Key == termbox.KeyCtrlU { + // Ctrl+U Clears the Input (before the cursor) + i.value = i.value[i.cursor:] + } else { + // Get the rune to add to our value. Space and Tab are special cases where + // we can't use the event's rune directly + var ch string + switch event.Key { + case termbox.KeySpace: + ch = " " + case termbox.KeyTab: + ch = "\t" + case termbox.KeyEnter: + if i.multiline { + ch = "\n" + } + default: + if KeyIsAlphaNumeric(event) || KeyIsSymbol(event) { + ch = string(event.Ch) + } + } + + // TODO: Handle newlines + if i.cursor+len(i.value) == 0 { + i.value = string(ch) + i.value + } else if i.cursor == 0 { + i.value = i.value + string(ch) + } else { + strPt1 := i.value[:(len(i.value) + i.cursor)] + strPt2 := i.value[(len(i.value) + i.cursor):] + i.value = strPt1 + string(ch) + strPt2 + } + } + return true +} + +// Draw outputs the input field on the screen +func (i *InputField) Draw() { + maxWidth := i.width + maxHeight := i.height + x, y := i.x, i.y + startX := i.x + startY := i.y + if i.bordered { + DrawBorder(i.x, i.y, i.x+i.width, i.y+i.height, i.fg, i.bg) + maxWidth-- + maxHeight-- + x++ + y++ + startX++ + startY++ + } + + var strPt1, strPt2 string + var cursorRune rune + if len(i.value) > 0 { + if i.cursor+len(i.value) == 0 { + strPt1 = "" + strPt2 = i.value[1:] + cursorRune = rune(i.value[0]) + } else if i.cursor == 0 { + strPt1 = i.value + strPt2 = "" + cursorRune = ' ' + } else { + strPt1 = i.value[:(len(i.value) + i.cursor)] + strPt2 = i.value[(len(i.value)+i.cursor)+1:] + cursorRune = rune(i.value[len(i.value)+i.cursor]) + } + } else { + strPt1, strPt2, cursorRune = "", "", ' ' + } + // Original: + /* + x, y = DrawStringAtPoint(strPt1, i.x+1, i.y+1, i.fg, i.bg) + termbox.SetCell(x, y, cursorRune, i.bg, i.fg) + DrawStringAtPoint(strPt2, x+1, y, i.fg, i.bg) + */ + if i.wrap { + // Split the text into maxWidth chunks + for len(strPt1) > maxWidth { + breakAt := maxWidth + DrawStringAtPoint(strPt1[:breakAt], x, y, i.fg, i.bg) + x = startX + y++ + strPt1 = strPt1[breakAt:] + } + x, y = DrawStringAtPoint(strPt1, x, y, i.fg, i.bg) + if x >= maxWidth { + y++ + x = startX + } + termbox.SetCell(x, y, cursorRune, i.cursorFg, i.cursorBg) + x++ + if len(strPt2) > 0 { + lenLeft := maxWidth - len(strPt1) - 1 + if lenLeft > 0 && len(strPt2) > lenLeft { + DrawStringAtPoint(strPt2[:lenLeft], x+1, y, i.fg, i.bg) + strPt2 = strPt2[lenLeft:] + } + for len(strPt2) > maxWidth { + breakAt := maxWidth + DrawStringAtPoint(strPt2[:breakAt], x, y, i.fg, i.bg) + x = startX + y++ + strPt2 = strPt2[breakAt:] + } + x, y = DrawStringAtPoint(strPt2, x, y, i.fg, i.bg) + } + } else { + for len(strPt1)+len(strPt2)+1 > maxWidth { + if len(strPt1) >= len(strPt2) { + if len(strPt1) == 0 { + break + } + strPt1 = strPt1[1:] + } else { + strPt2 = strPt2[:len(strPt2)-1] + } + } + x, y = DrawStringAtPoint(strPt1, i.x+1, i.y+1, i.fg, i.bg) + termbox.SetCell(x, y, cursorRune, i.cursorFg, i.cursorBg) + DrawStringAtPoint(strPt2, x+1, y, i.fg, i.bg) + } +} diff --git a/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_inputmodal.go b/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_inputmodal.go new file mode 100644 index 0000000..4268314 --- /dev/null +++ b/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_inputmodal.go @@ -0,0 +1,257 @@ +package termboxUtil + +import ( + "github.com/nsf/termbox-go" +) + +// InputModal A modal for text input +type InputModal struct { + id string + title string + text string + input *InputField + x, y, width, height int + showHelp bool + cursor int + bg, fg termbox.Attribute + isDone bool + isAccepted bool + isVisible bool + bordered bool + tabSkip bool + inputSelected bool +} + +// CreateInputModal Create an input modal with the given attributes +func CreateInputModal(title string, x, y, width, height int, fg, bg termbox.Attribute) *InputModal { + i := InputModal{title: title, x: x, y: y, width: width, height: height, fg: fg, bg: bg, bordered: true} + i.input = CreateInputField(i.x+2, i.y+3, i.width-2, 2, i.fg, i.bg) + i.showHelp = true + i.input.bordered = true + i.isVisible = true + i.inputSelected = true + return &i +} + +// GetID returns this control's ID +func (i *InputModal) GetID() string { return i.id } + +// SetID sets this control's ID +func (i *InputModal) SetID(newID string) { + i.id = newID +} + +// GetTitle Return the title of the modal +func (i *InputModal) GetTitle() string { return i.title } + +// SetTitle Sets the title of the modal to s +func (i *InputModal) SetTitle(s string) { + i.title = s +} + +// GetText Return the text of the modal +func (i *InputModal) GetText() string { return i.text } + +// SetText Set the text of the modal to s +func (i *InputModal) SetText(s string) { + i.text = s +} + +// GetX Return the x position of the modal +func (i *InputModal) GetX() int { return i.x } + +// SetX set the x position of the modal to x +func (i *InputModal) SetX(x int) { + i.x = x +} + +// GetY Return the y position of the modal +func (i *InputModal) GetY() int { return i.y } + +// SetY Set the y position of the modal to y +func (i *InputModal) SetY(y int) { + i.y = y +} + +// GetWidth Return the width of the modal +func (i *InputModal) GetWidth() int { return i.width } + +// SetWidth Set the width of the modal to width +func (i *InputModal) SetWidth(width int) { + i.width = width +} + +// GetHeight Return the height of the modal +func (i *InputModal) GetHeight() int { return i.height } + +// SetHeight Set the height of the modal to height +func (i *InputModal) SetHeight(height int) { + i.height = height +} + +// SetMultiline returns whether this is a multiline modal +func (i *InputModal) SetMultiline(m bool) { + i.input.multiline = m +} + +// IsMultiline returns whether this is a multiline modal +func (i *InputModal) IsMultiline() bool { + return i.input.multiline +} + +// IsBordered returns whether this control is bordered or not +func (i *InputModal) IsBordered() bool { + return i.bordered +} + +// SetBordered sets whether we render a border around the frame +func (i *InputModal) SetBordered(b bool) { + i.bordered = b +} + +// IsTabSkipped returns whether this control has it's tabskip flag set +func (i *InputModal) IsTabSkipped() bool { + return i.tabSkip +} + +// SetTabSkip sets the tabskip flag for this control +func (i *InputModal) SetTabSkip(b bool) { + i.tabSkip = b +} + +// HelpIsShown Returns whether the modal is showing it's help text or not +func (i *InputModal) HelpIsShown() bool { return i.showHelp } + +// ShowHelp Set the "Show Help" flag +func (i *InputModal) ShowHelp(b bool) { + i.showHelp = b +} + +// GetFgColor returns the foreground color +func (i *InputModal) GetFgColor() termbox.Attribute { return i.fg } + +// SetFgColor sets the foreground color +func (i *InputModal) SetFgColor(fg termbox.Attribute) { + i.fg = fg +} + +// GetBgColor returns the background color +func (i *InputModal) GetBgColor() termbox.Attribute { return i.bg } + +// SetBgColor sets the current background color +func (i *InputModal) SetBgColor(bg termbox.Attribute) { + i.bg = bg +} + +// Show Sets the visibility flag to true +func (i *InputModal) Show() { + i.isVisible = true +} + +// Hide Sets the visibility flag to false +func (i *InputModal) Hide() { + i.isVisible = false +} + +// IsVisible returns the isVisible flag +func (i *InputModal) IsVisible() bool { + return i.isVisible +} + +// SetDone Sets the flag that tells whether this modal has completed it's purpose +func (i *InputModal) SetDone(b bool) { + i.isDone = b +} + +// IsDone Returns the "isDone" flag +func (i *InputModal) IsDone() bool { + return i.isDone +} + +// IsAccepted Returns whether the modal has been accepted +func (i *InputModal) IsAccepted() bool { + return i.isAccepted +} + +// GetValue Return the current value of the input +func (i *InputModal) GetValue() string { return i.input.GetValue() } + +// SetValue Sets the value of the input to s +func (i *InputModal) SetValue(s string) { + i.input.SetValue(s) +} + +// SetInputWrap sets whether the input field will wrap long text or not +func (i *InputModal) SetInputWrap(b bool) { + i.input.SetWrap(b) +} + +// Clear Resets all non-positional parameters of the modal +func (i *InputModal) Clear() { + i.title = "" + i.text = "" + i.input.SetValue("") + i.isDone = false + i.isVisible = false +} + +// HandleEvent Handle the termbox event, return true if it was consumed +func (i *InputModal) HandleEvent(event termbox.Event) bool { + if event.Key == termbox.KeyEnter { + if !i.input.IsMultiline() || !i.inputSelected { + // Done editing + i.isDone = true + i.isAccepted = true + } else { + i.input.HandleEvent(event) + } + return true + } else if event.Key == termbox.KeyTab { + if i.input.IsMultiline() { + i.inputSelected = !i.inputSelected + } + } else if event.Key == termbox.KeyEsc { + // Done editing + i.isDone = true + i.isAccepted = false + return true + } + return i.input.HandleEvent(event) +} + +// Draw Draw the modal +func (i *InputModal) Draw() { + if i.isVisible { + // First blank out the area we'll be putting the modal + FillWithChar(' ', i.x, i.y, i.x+i.width, i.y+i.height, i.fg, i.bg) + nextY := i.y + 1 + // The title + if i.title != "" { + if len(i.title) > i.width { + diff := i.width - len(i.title) + DrawStringAtPoint(i.title[:len(i.title)+diff-1], i.x+1, nextY, i.fg, i.bg) + } else { + DrawStringAtPoint(i.title, i.x+1, nextY, i.fg, i.bg) + } + nextY++ + FillWithChar('-', i.x+1, nextY, i.x+i.width-1, nextY, i.fg, i.bg) + nextY++ + } + if i.text != "" { + DrawStringAtPoint(i.text, i.x+1, nextY, i.fg, i.bg) + nextY++ + } + i.input.SetY(nextY) + i.input.Draw() + nextY += 3 + if i.showHelp { + helpString := " (ENTER) to Accept. (ESC) to Cancel. " + helpX := (i.x + i.width - len(helpString)) - 1 + DrawStringAtPoint(helpString, helpX, nextY, i.fg, i.bg) + } + if i.bordered { + // Now draw the border + DrawBorder(i.x, i.y, i.x+i.width, i.y+i.height, i.fg, i.bg) + } + } +} diff --git a/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_label.go b/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_label.go new file mode 100644 index 0000000..cc65cc8 --- /dev/null +++ b/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_label.go @@ -0,0 +1,140 @@ +package termboxUtil + +import "github.com/nsf/termbox-go" + +// Label is a field for inputting text +type Label struct { + id string + value string + x, y, width, height int + cursor int + fg, bg termbox.Attribute + bordered bool + wrap bool + multiline bool +} + +// CreateLabel creates an input field at x, y that is w by h +func CreateLabel(lbl string, x, y, w, h int, fg, bg termbox.Attribute) *Label { + i := Label{value: lbl, x: x, y: y, width: w, height: h, fg: fg, bg: bg} + return &i +} + +// GetID returns this control's ID +func (i *Label) GetID() string { return i.id } + +// SetID sets this control's ID +func (i *Label) SetID(newID string) { + i.id = newID +} + +// GetValue gets the current text that is in the Label +func (i *Label) GetValue() string { return i.value } + +// SetValue sets the current text in the Label to s +func (i *Label) SetValue(s string) { + i.value = s +} + +// GetX returns the x position of the input field +func (i *Label) GetX() int { return i.x } + +// SetX sets the x position of the input field +func (i *Label) SetX(x int) { + i.x = x +} + +// GetY returns the y position of the input field +func (i *Label) GetY() int { return i.y } + +// SetY sets the y position of the input field +func (i *Label) SetY(y int) { + i.y = y +} + +// GetWidth returns the current width of the input field +func (i *Label) GetWidth() int { + if i.width == -1 { + if i.bordered { + return len(i.value) + 2 + } + return len(i.value) + } + return i.width +} + +// SetWidth sets the current width of the input field +func (i *Label) SetWidth(w int) { + i.width = w +} + +// GetHeight returns the current height of the input field +func (i *Label) GetHeight() int { return i.height } + +// SetHeight sets the current height of the input field +func (i *Label) SetHeight(h int) { + i.height = h +} + +// GetFgColor returns the foreground color +func (i *Label) GetFgColor() termbox.Attribute { return i.fg } + +// SetFgColor sets the foreground color +func (i *Label) SetFgColor(fg termbox.Attribute) { + i.fg = fg +} + +// GetBgColor returns the background color +func (i *Label) GetBgColor() termbox.Attribute { return i.bg } + +// SetBgColor sets the current background color +func (i *Label) SetBgColor(bg termbox.Attribute) { + i.bg = bg +} + +// IsBordered returns true or false if this input field has a border +func (i *Label) IsBordered() bool { return i.bordered } + +// SetBordered sets whether we render a border around the input field +func (i *Label) SetBordered(b bool) { + i.bordered = b +} + +// DoesWrap returns true or false if this input field wraps text +func (i *Label) DoesWrap() bool { return i.wrap } + +// SetWrap sets whether we wrap the text at width. +func (i *Label) SetWrap(b bool) { + i.wrap = b +} + +// IsMultiline returns true or false if this field can have multiple lines +func (i *Label) IsMultiline() bool { return i.multiline } + +// SetMultiline sets whether the field can have multiple lines +func (i *Label) SetMultiline(b bool) { + i.multiline = b +} + +// HandleEvent accepts the termbox event and returns whether it was consumed +func (i *Label) HandleEvent(event termbox.Event) bool { return false } + +// Draw outputs the input field on the screen +func (i *Label) Draw() { + maxWidth := i.width + maxHeight := i.height + x, y := i.x, i.y + startX := i.x + startY := i.y + if i.bordered { + DrawBorder(i.x, i.y, i.x+i.GetWidth(), i.y+i.height, i.fg, i.bg) + maxWidth-- + maxHeight-- + x++ + y++ + startX++ + startY++ + } + + DrawStringAtPoint(i.value, x, y, i.fg, i.bg) +} diff --git a/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_menu.go b/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_menu.go new file mode 100644 index 0000000..700ab04 --- /dev/null +++ b/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_menu.go @@ -0,0 +1,478 @@ +package termboxUtil + +import "github.com/nsf/termbox-go" + +// Menu is a menu with a list of options +type Menu struct { + id string + title string + options []MenuOption + // If height is -1, then it is adaptive to the menu + x, y, width, height int + showHelp bool + cursor int + bg, fg termbox.Attribute + selectedBg, selectedFg termbox.Attribute + disabledBg, disabledFg termbox.Attribute + isDone bool + bordered bool + vimMode bool + tabSkip bool +} + +// CreateMenu Creates a menu with the specified attributes +func CreateMenu(title string, options []string, x, y, width, height int, fg, bg termbox.Attribute) *Menu { + i := Menu{ + title: title, + x: x, y: y, width: width, height: height, + fg: fg, bg: bg, selectedFg: bg, selectedBg: fg, + disabledFg: bg, disabledBg: bg, + } + for _, line := range options { + i.options = append(i.options, MenuOption{text: line}) + } + if len(i.options) > 0 { + i.SetSelectedOption(&i.options[0]) + } + return &i +} + +// GetID returns this control's ID +func (i *Menu) GetID() string { return i.id } + +// SetID sets this control's ID +func (i *Menu) SetID(newID string) { + i.id = newID +} + +// GetTitle returns the current title of the menu +func (i *Menu) GetTitle() string { return i.title } + +// SetTitle sets the current title of the menu to s +func (i *Menu) SetTitle(s string) { + i.title = s +} + +// GetOptions returns the current options of the menu +func (i *Menu) GetOptions() []MenuOption { + return i.options +} + +// SetOptions set the menu's options to opts +func (i *Menu) SetOptions(opts []MenuOption) { + i.options = opts +} + +// SetOptionsFromStrings sets the options of this menu from a slice of strings +func (i *Menu) SetOptionsFromStrings(opts []string) { + var newOpts []MenuOption + for _, v := range opts { + newOpts = append(newOpts, *CreateOptionFromText(v)) + } + i.SetOptions(newOpts) + i.SetSelectedOption(i.GetOptionFromIndex(0)) +} + +// GetX returns the current x coordinate of the menu +func (i *Menu) GetX() int { return i.x } + +// SetX sets the current x coordinate of the menu to x +func (i *Menu) SetX(x int) { + i.x = x +} + +// GetY returns the current y coordinate of the menu +func (i *Menu) GetY() int { return i.y } + +// SetY sets the current y coordinate of the menu to y +func (i *Menu) SetY(y int) { + i.y = y +} + +// GetWidth returns the current width of the menu +func (i *Menu) GetWidth() int { return i.width } + +// SetWidth sets the current menu width to width +func (i *Menu) SetWidth(width int) { + i.width = width +} + +// GetHeight returns the current height of the menu +func (i *Menu) GetHeight() int { return i.height } + +// SetHeight set the height of the menu to height +func (i *Menu) SetHeight(height int) { + i.height = height +} + +// GetSelectedOption returns the current selected option +func (i *Menu) GetSelectedOption() *MenuOption { + idx := i.GetSelectedIndex() + if idx != -1 { + return &i.options[idx] + } + return nil +} + +// GetOptionFromIndex Returns the +func (i *Menu) GetOptionFromIndex(idx int) *MenuOption { + if idx >= 0 && idx < len(i.options) { + return &i.options[idx] + } + return nil +} + +// GetOptionFromText Returns the first option with the text v +func (i *Menu) GetOptionFromText(v string) *MenuOption { + for idx := range i.options { + testOption := &i.options[idx] + if testOption.GetText() == v { + return testOption + } + } + return nil +} + +// GetSelectedIndex returns the index of the selected option +// Returns -1 if nothing is selected +func (i *Menu) GetSelectedIndex() int { + for idx := range i.options { + if i.options[idx].IsSelected() { + return idx + } + } + return -1 +} + +// SetSelectedIndex sets the selection to setIdx +func (i *Menu) SetSelectedIndex(idx int) { + if len(i.options) > 0 { + if idx < 0 { + idx = 0 + } else if idx >= len(i.options) { + idx = len(i.options) - 1 + } + i.SetSelectedOption(&i.options[idx]) + } +} + +// SetSelectedOption sets the current selected option to v (if it's valid) +func (i *Menu) SetSelectedOption(v *MenuOption) { + for idx := range i.options { + if &i.options[idx] == v { + i.options[idx].Select() + } else { + i.options[idx].Unselect() + } + } +} + +// SelectPrevOption Decrements the selected option (if it can) +func (i *Menu) SelectPrevOption() { + idx := i.GetSelectedIndex() + for idx >= 0 { + idx-- + testOption := i.GetOptionFromIndex(idx) + if testOption != nil && !testOption.IsDisabled() { + i.SetSelectedOption(testOption) + return + } + } +} + +// SelectNextOption Increments the selected option (if it can) +func (i *Menu) SelectNextOption() { + idx := i.GetSelectedIndex() + for idx < len(i.options) { + idx++ + testOption := i.GetOptionFromIndex(idx) + if testOption != nil && !testOption.IsDisabled() { + i.SetSelectedOption(testOption) + return + } + } +} + +// SelectPageUpOption Goes up 'menu height' options +func (i *Menu) SelectPageUpOption() { + idx := i.GetSelectedIndex() + idx -= i.height + if idx < 0 { + idx = 0 + } + i.SetSelectedIndex(idx) + return +} + +// SelectPageDownOption Goes down 'menu height' options +func (i *Menu) SelectPageDownOption() { + idx := i.GetSelectedIndex() + idx += i.height + if idx >= len(i.options) { + idx = len(i.options) - 1 + } + i.SetSelectedIndex(idx) + return +} + +// SelectFirstOption Goes to the top +func (i *Menu) SelectFirstOption() { + i.SetSelectedIndex(0) + return +} + +// SelectLastOption Goes to the bottom +func (i *Menu) SelectLastOption() { + i.SetSelectedIndex(len(i.options) - 1) + return +} + +// SetOptionDisabled Disables the specified option +func (i *Menu) SetOptionDisabled(idx int) { + if len(i.options) > idx { + i.GetOptionFromIndex(idx).Disable() + } +} + +// SetOptionEnabled Enables the specified option +func (i *Menu) SetOptionEnabled(idx int) { + if len(i.options) > idx { + i.GetOptionFromIndex(idx).Enable() + } +} + +// HelpIsShown returns true or false if the help is displayed +func (i *Menu) HelpIsShown() bool { return i.showHelp } + +// ShowHelp sets whether or not to display the help text +func (i *Menu) ShowHelp(b bool) { + i.showHelp = b +} + +// GetFgColor returns the foreground color +func (i *Menu) GetFgColor() termbox.Attribute { return i.fg } + +// SetFgColor sets the foreground color +func (i *Menu) SetFgColor(fg termbox.Attribute) { + i.fg = fg +} + +// GetBgColor returns the background color +func (i *Menu) GetBgColor() termbox.Attribute { return i.bg } + +// SetBgColor sets the current background color +func (i *Menu) SetBgColor(bg termbox.Attribute) { + i.bg = bg +} + +// IsDone returns whether the user has answered the modal +func (i *Menu) IsDone() bool { return i.isDone } + +// SetDone sets whether the modal has completed it's purpose +func (i *Menu) SetDone(b bool) { + i.isDone = b +} + +// IsBordered returns true or false if this menu has a border +func (i *Menu) IsBordered() bool { return i.bordered } + +// SetBordered sets whether we render a border around the menu +func (i *Menu) SetBordered(b bool) { + i.bordered = b +} + +// EnableVimMode Enables h,j,k,l navigation +func (i *Menu) EnableVimMode() { + i.vimMode = true +} + +// DisableVimMode Disables h,j,k,l navigation +func (i *Menu) DisableVimMode() { + i.vimMode = false +} + +// HandleEvent handles the termbox event and returns whether it was consumed +func (i *Menu) HandleEvent(event termbox.Event) bool { + if event.Key == termbox.KeyEnter || event.Key == termbox.KeySpace { + i.isDone = true + return true + } + currentIdx := i.GetSelectedIndex() + switch event.Key { + case termbox.KeyArrowUp: + i.SelectPrevOption() + case termbox.KeyArrowDown: + i.SelectNextOption() + case termbox.KeyArrowLeft: + i.SelectPageUpOption() + case termbox.KeyArrowRight: + i.SelectPageDownOption() + } + if i.vimMode { + switch event.Ch { + case 'j': + i.SelectNextOption() + case 'k': + i.SelectPrevOption() + } + if event.Key == termbox.KeyCtrlF { + i.SelectPageDownOption() + } else if event.Key == termbox.KeyCtrlB { + i.SelectPageUpOption() + } + } + if i.GetSelectedIndex() != currentIdx { + return true + } + return false +} + +// Draw draws the modal +func (i *Menu) Draw() { + // First blank out the area we'll be putting the menu + FillWithChar(' ', i.x, i.y, i.x+i.width, i.y+i.height, i.fg, i.bg) + // Now draw the border + optionStartX := i.x + optionStartY := i.y + optionWidth := i.width + optionHeight := i.height + if optionHeight == -1 { + optionHeight = len(i.options) + } + if i.bordered { + if i.height == -1 { + DrawBorder(i.x, i.y, i.x+i.width, i.y+optionHeight+1, i.fg, i.bg) + } else { + DrawBorder(i.x, i.y, i.x+i.width, i.y+optionHeight, i.fg, i.bg) + } + optionStartX = i.x + 1 + optionStartY = i.y + 1 + optionWidth = i.width - 1 + optionHeight -= 2 + } + + // The title + if i.title != "" { + DrawStringAtPoint(AlignText(i.title, optionWidth, AlignCenter), optionStartX, optionStartY, i.fg, i.bg) + optionStartY++ + if i.bordered { + FillWithChar('-', optionStartX, optionStartY, optionWidth, optionStartY, i.fg, i.bg) + optionStartY++ + optionHeight-- + } + optionHeight-- + } + + if len(i.options) > 0 { + // If the currently selected option is disabled, move to the next + if i.GetSelectedOption().IsDisabled() { + i.SelectNextOption() + } + + // Print the options + bldHeight := (optionHeight / 2) + startIdx := i.GetSelectedIndex() + endIdx := i.GetSelectedIndex() + for bldHeight > 0 && startIdx >= 1 { + startIdx-- + bldHeight-- + } + bldHeight += (optionHeight / 2) + for bldHeight > 0 && endIdx < len(i.options) { + endIdx++ + bldHeight-- + } + + for idx := startIdx; idx < endIdx; idx++ { //i.options { + if i.GetSelectedIndex()-idx >= optionHeight-1 { + // Skip this one + continue + } + currOpt := &i.options[idx] + outTxt := currOpt.GetText() + if len(outTxt) >= i.width { + outTxt = outTxt[:i.width] + } + if currOpt.IsDisabled() { + DrawStringAtPoint(outTxt, optionStartX, optionStartY, i.disabledFg, i.disabledBg) + } else if i.GetSelectedOption() == currOpt { + DrawStringAtPoint(outTxt, optionStartX, optionStartY, i.selectedFg, i.selectedBg) + } else { + DrawStringAtPoint(outTxt, optionStartX, optionStartY, i.fg, i.bg) + } + optionStartY++ + if optionStartY > i.y+optionHeight-1 { + break + } + } + } +} + +/* MenuOption Struct & methods */ + +// MenuOption An option in the menu +type MenuOption struct { + id string + text string + selected bool + disabled bool + helpText string + subMenu []MenuOption +} + +// CreateOptionFromText just returns a MenuOption object +// That only has it's text value set. +func CreateOptionFromText(s string) *MenuOption { + return &MenuOption{text: s} +} + +// SetText Sets the text for this option +func (i *MenuOption) SetText(s string) { + i.text = s +} + +// GetText Returns the text for this option +func (i *MenuOption) GetText() string { return i.text } + +// Disable Sets this option to disabled +func (i *MenuOption) Disable() { + i.disabled = true +} + +// Enable Sets this option to enabled +func (i *MenuOption) Enable() { + i.disabled = false +} + +// IsDisabled returns whether this option is enabled +func (i *MenuOption) IsDisabled() bool { + return i.disabled +} + +// IsSelected Returns whether this option is selected +func (i *MenuOption) IsSelected() bool { + return i.selected +} + +// Select Sets this option to selected +func (i *MenuOption) Select() { + i.selected = true +} + +// Unselect Sets this option to not selected +func (i *MenuOption) Unselect() { + i.selected = false +} + +// SetHelpText Sets this option's help text to s +func (i *MenuOption) SetHelpText(s string) { + i.helpText = s +} + +// GetHelpText Returns the help text for this option +func (i *MenuOption) GetHelpText() string { return i.helpText } + +// AddToSubMenu adds a slice of MenuOptions to this option +func (i *MenuOption) AddToSubMenu(sub *MenuOption) { + i.subMenu = append(i.subMenu, *sub) +} diff --git a/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_progressbar.go b/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_progressbar.go new file mode 100644 index 0000000..962433e --- /dev/null +++ b/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_progressbar.go @@ -0,0 +1,237 @@ +package termboxUtil + +import "github.com/nsf/termbox-go" + +// ProgressBar Just contains the data needed to display a progress bar +type ProgressBar struct { + id string + total int + progress int + allowOverflow bool + allowUnderflow bool + fullChar rune + emptyChar rune + bordered bool + alignment TextAlignment + colorized bool + + x, y int + width, height int + bg, fg termbox.Attribute +} + +// CreateProgressBar Create a progress bar object +func CreateProgressBar(tot, x, y int, fg, bg termbox.Attribute) *ProgressBar { + i := ProgressBar{total: tot, + fullChar: '#', emptyChar: ' ', + x: x, y: y, height: 1, width: 10, + bordered: true, fg: fg, bg: bg, + alignment: AlignLeft, + } + return &i +} + +// GetID returns this control's ID +func (i *ProgressBar) GetID() string { return i.id } + +// SetID sets this control's ID +func (i *ProgressBar) SetID(newID string) { + i.id = newID +} + +// GetProgress returns the curret progress value +func (i *ProgressBar) GetProgress() int { + return i.progress +} + +// SetProgress sets the current progress of the bar +func (i *ProgressBar) SetProgress(p int) { + if (p <= i.total || i.allowOverflow) || (p >= 0 || i.allowUnderflow) { + i.progress = p + } +} + +// IncrProgress increments the current progress of the bar +func (i *ProgressBar) IncrProgress() { + if i.progress < i.total || i.allowOverflow { + i.progress++ + } +} + +// DecrProgress decrements the current progress of the bar +func (i *ProgressBar) DecrProgress() { + if i.progress > 0 || i.allowUnderflow { + i.progress-- + } +} + +// GetPercent returns the percent full of the bar +func (i *ProgressBar) GetPercent() int { + return int(float64(i.progress) / float64(i.total) * 100) +} + +// EnableOverflow Tells the progress bar that it can go over the total +func (i *ProgressBar) EnableOverflow() { + i.allowOverflow = true +} + +// DisableOverflow Tells the progress bar that it can NOT go over the total +func (i *ProgressBar) DisableOverflow() { + i.allowOverflow = false +} + +// EnableUnderflow Tells the progress bar that it can go below zero +func (i *ProgressBar) EnableUnderflow() { + i.allowUnderflow = true +} + +// DisableUnderflow Tells the progress bar that it can NOT go below zero +func (i *ProgressBar) DisableUnderflow() { + i.allowUnderflow = false +} + +// GetFullChar returns the rune used for 'full' +func (i *ProgressBar) GetFullChar() rune { + return i.fullChar +} + +// SetFullChar sets the rune used for 'full' +func (i *ProgressBar) SetFullChar(f rune) { + i.fullChar = f +} + +// GetEmptyChar gets the rune used for 'empty' +func (i *ProgressBar) GetEmptyChar() rune { + return i.emptyChar +} + +// SetEmptyChar sets the rune used for 'empty' +func (i *ProgressBar) SetEmptyChar(f rune) { + i.emptyChar = f +} + +// GetX Return the x position of the Progress Bar +func (i *ProgressBar) GetX() int { return i.x } + +// SetX set the x position of the ProgressBar to x +func (i *ProgressBar) SetX(x int) { + i.x = x +} + +// GetY Return the y position of the ProgressBar +func (i *ProgressBar) GetY() int { return i.y } + +// SetY Set the y position of the ProgressBar to y +func (i *ProgressBar) SetY(y int) { + i.y = y +} + +// GetHeight returns the height of the progress bar +// Defaults to 1 (3 if bordered) +func (i *ProgressBar) GetHeight() int { + return i.height +} + +// SetHeight Sets the height of the progress bar +func (i *ProgressBar) SetHeight(h int) { + i.height = h +} + +// GetWidth returns the width of the progress bar +func (i *ProgressBar) GetWidth() int { + return i.width +} + +// SetWidth Sets the width of the progress bar +func (i *ProgressBar) SetWidth(w int) { + i.width = w +} + +// GetFgColor returns the foreground color +func (i *ProgressBar) GetFgColor() termbox.Attribute { return i.fg } + +// SetFgColor sets the foreground color +func (i *ProgressBar) SetFgColor(fg termbox.Attribute) { + i.fg = fg +} + +// GetBgColor returns the background color +func (i *ProgressBar) GetBgColor() termbox.Attribute { return i.bg } + +// SetBgColor sets the current background color +func (i *ProgressBar) SetBgColor(bg termbox.Attribute) { + i.bg = bg +} + +// Align Tells which direction the progress bar empties +func (i *ProgressBar) Align(a TextAlignment) { + i.alignment = a +} + +// SetColorized sets whether the progress bar should be colored +// depending on how full it is: +// 10% - Red +// 50% - Yellow +// 80% - Green +func (i *ProgressBar) SetColorized(c bool) { + i.colorized = c +} + +// HandleEvent accepts the termbox event and returns whether it was consumed +func (i *ProgressBar) HandleEvent(event termbox.Event) bool { + return false +} + +// Draw outputs the input field on the screen +func (i *ProgressBar) Draw() { + // For now, just draw a [#### ] bar + // TODO: make this more advanced + useFg := i.fg + if i.colorized { + if i.GetPercent() < 10 { + useFg = termbox.ColorRed + } else if i.GetPercent() < 50 { + useFg = termbox.ColorYellow + } else { + useFg = termbox.ColorGreen + } + } + drawX, drawY := i.x, i.y + fillWidth, fillHeight := i.width-2, i.height + DrawStringAtPoint("[", drawX, drawY, i.fg, i.bg) + numFull := int(float64(fillWidth) * float64(i.progress) / float64(i.total)) + FillWithChar(i.fullChar, drawX+1, drawY, drawX+1+numFull, drawY+(fillHeight-1), useFg, i.bg) + DrawStringAtPoint("]", drawX+i.width-1, drawY, i.fg, i.bg) + + /* + drawX, drawY := i.x, i.y + drawWidth, drawHeight := i.width, i.height + if i.bordered { + if i.height == 1 && i.width > 2 { + // Just using [ & ] for the border + DrawStringAtPoint("[", drawX, drawY, i.fg, i.bg) + DrawStringAtPoint("]", drawX+i.width-1, drawY, i.fg, i.bg) + drawX++ + drawWidth -= 2 + } else if i.height >= 3 { + DrawBorder(drawX, drawY, drawX+i.width, drawY+i.height, i.fg, i.bg) + drawX++ + drawY++ + drawWidth -= 2 + drawHeight -= 2 + } + } + + // Figure out how many chars are full + numFull := drawWidth * (i.progress / i.total) + switch i.alignment { + case AlignRight: // TODO: Fill from right to left + case AlignCenter: // TODO: Fill from middle out + default: // Fill from left to right + FillWithChar(i.fullChar, drawX, drawY, drawX+numFull, drawY+(drawHeight-1), i.fg, i.bg) + if numFull < drawWidth { + FillWithChar(i.emptyChar, drawX+numFull, drawY, drawX+drawWidth-1, drawY+(drawHeight-1), i.fg, i.bg) + } + } + */ +} diff --git a/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_scrollframe.go b/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_scrollframe.go new file mode 100644 index 0000000..0b83de4 --- /dev/null +++ b/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_scrollframe.go @@ -0,0 +1,180 @@ +package termboxUtil + +import "github.com/nsf/termbox-go" + +// ScrollFrame is a frame for holding other elements +// It manages it's own x/y, tab index +type ScrollFrame struct { + id string + x, y, width, height int + scrollX, scrollY int + tabIdx int + fg, bg termbox.Attribute + bordered bool + controls []termboxControl +} + +// CreateScrollFrame creates Scrolling Frame at x, y that is w by h +func CreateScrollFrame(x, y, w, h int, fg, bg termbox.Attribute) *ScrollFrame { + s := ScrollFrame{x: x, y: y, width: w, height: h, fg: fg, bg: bg} + return &s +} + +// GetID returns this control's ID +func (i *ScrollFrame) GetID() string { return i.id } + +// SetID sets this control's ID +func (i *ScrollFrame) SetID(newID string) { + i.id = newID +} + +// GetX returns the x position of the scroll frame +func (i *ScrollFrame) GetX() int { return i.x } + +// SetX sets the x position of the scroll frame +func (i *ScrollFrame) SetX(x int) { + i.x = x +} + +// GetY returns the y position of the scroll frame +func (i *ScrollFrame) GetY() int { return i.y } + +// SetY sets the y position of the scroll frame +func (i *ScrollFrame) SetY(y int) { + i.y = y +} + +// GetWidth returns the current width of the scroll frame +func (i *ScrollFrame) GetWidth() int { return i.width } + +// SetWidth sets the current width of the scroll frame +func (i *ScrollFrame) SetWidth(w int) { + i.width = w +} + +// GetHeight returns the current height of the scroll frame +func (i *ScrollFrame) GetHeight() int { return i.height } + +// SetHeight sets the current height of the scroll frame +func (i *ScrollFrame) SetHeight(h int) { + i.height = h +} + +// GetFgColor returns the foreground color +func (i *ScrollFrame) GetFgColor() termbox.Attribute { return i.fg } + +// SetFgColor sets the foreground color +func (i *ScrollFrame) SetFgColor(fg termbox.Attribute) { + i.fg = fg +} + +// GetBgColor returns the background color +func (i *ScrollFrame) GetBgColor() termbox.Attribute { return i.bg } + +// SetBgColor sets the current background color +func (i *ScrollFrame) SetBgColor(bg termbox.Attribute) { + i.bg = bg +} + +// IsBordered returns true or false if this scroll frame has a border +func (i *ScrollFrame) IsBordered() bool { return i.bordered } + +// SetBordered sets whether we render a border around the scroll frame +func (i *ScrollFrame) SetBordered(b bool) { + i.bordered = b +} + +// GetScrollX returns the x distance scrolled +func (i *ScrollFrame) GetScrollX() int { + return i.scrollX +} + +// GetScrollY returns the y distance scrolled +func (i *ScrollFrame) GetScrollY() int { + return i.scrollY +} + +// ScrollDown scrolls the frame down +func (i *ScrollFrame) ScrollDown() { + i.scrollY++ +} + +// ScrollUp scrolls the frame up +func (i *ScrollFrame) ScrollUp() { + if i.scrollY > 0 { + i.scrollY-- + } +} + +// ScrollLeft scrolls the frame left +func (i *ScrollFrame) ScrollLeft() { + if i.scrollX > 0 { + i.scrollX-- + } +} + +// ScrollRight scrolls the frame right +func (i *ScrollFrame) ScrollRight() { + i.scrollX++ +} + +// AddControl adds a control to the frame +func (i *ScrollFrame) AddControl(t termboxControl) { + i.controls = append(i.controls, t) +} + +// DrawControl figures out the relative position of the control, +// sets it, draws it, then resets it. +func (i *ScrollFrame) DrawControl(t termboxControl) { + if i.IsVisible(t) { + ctlX, ctlY := t.GetX(), t.GetY() + t.SetX((i.GetX() + ctlX)) + t.SetY((i.GetY() + ctlY)) + t.Draw() + t.SetX(ctlX) + t.SetY(ctlY) + } +} + +// IsVisible takes a Termbox Control and returns whether +// that control would be visible in the frame +func (i *ScrollFrame) IsVisible(t termboxControl) bool { + // Check if any part of t should be visible + cX, cY := t.GetX(), t.GetY() + if cX+t.GetWidth() >= i.scrollX && cX <= i.scrollX+i.width { + return cY+t.GetHeight() >= i.scrollY && cY <= i.scrollY+i.height + } + return false +} + +// HandleEvent accepts the termbox event and returns whether it was consumed +func (i *ScrollFrame) HandleEvent(event termbox.Event) bool { + return false +} + +// DrawToStrings generates a slice of strings with what should +// be drawn to the screen +func (i *ScrollFrame) DrawToStrings() []string { + return []string{} +} + +// Draw outputs the Scoll Frame on the screen +func (i *ScrollFrame) Draw() { + maxWidth := i.width + maxHeight := i.height + x, y := i.x, i.y + startX := i.x + startY := i.y + if i.bordered { + DrawBorder(i.x, i.y, i.x+i.width, i.y+i.height, i.fg, i.bg) + maxWidth-- + maxHeight-- + x++ + y++ + startX++ + startY++ + } + for idx := range i.controls { + i.DrawControl(i.controls[idx]) + } +} diff --git a/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_util.go b/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_util.go new file mode 100644 index 0000000..fdab4ba --- /dev/null +++ b/vendor/gogs.bullercodeworks.com/brian/termbox-util/termbox_util.go @@ -0,0 +1,151 @@ +package termboxUtil + +import ( + "fmt" + "strings" + + "github.com/nsf/termbox-go" +) + +type termboxControl interface { + GetID() string + GetX() int + SetX(int) + GetY() int + SetY(int) + GetWidth() int + SetWidth(int) + GetHeight() int + SetHeight(int) + GetFgColor() termbox.Attribute + SetFgColor(termbox.Attribute) + GetBgColor() termbox.Attribute + SetBgColor(termbox.Attribute) + HandleEvent(termbox.Event) bool + IsBordered() bool + SetBordered(bool) + SetTabSkip(bool) + IsTabSkipped() bool + Draw() +} + +// TextAlignment is an int value for how we're aligning text +type TextAlignment int + +const ( + // AlignLeft Aligns text to the left + AlignLeft = iota + // AlignCenter Aligns text to the center + AlignCenter + // AlignRight Aligns text to the right + AlignRight +) + +/* Basic Input Helpers */ + +// KeyIsAlphaNumeric Returns whether the termbox event is an +// Alpha-Numeric Key Press +func KeyIsAlphaNumeric(event termbox.Event) bool { + return KeyIsAlpha(event) || KeyIsNumeric(event) +} + +// KeyIsAlpha Returns whether the termbox event is a +// alphabetic Key press +func KeyIsAlpha(event termbox.Event) bool { + k := event.Ch + if (k >= 'a' && k <= 'z') || (k >= 'A' && k <= 'Z') { + return true + } + return false +} + +// KeyIsNumeric Returns whether the termbox event is a +// numeric Key press +func KeyIsNumeric(event termbox.Event) bool { + k := event.Ch + if k >= '0' && k <= '9' { + return true + } + return false +} + +// KeyIsSymbol Returns whether the termbox event is a +// symbol Key press +func KeyIsSymbol(event termbox.Event) bool { + symbols := []rune{'!', '@', '#', '$', '%', '^', '&', '*', + '(', ')', '-', '_', '=', '+', '[', ']', '{', '}', '|', + ';', ':', '"', '\'', ',', '<', '.', '>', '/', '?', '`', '~'} + k := event.Ch + for i := range symbols { + if k == symbols[i] { + return true + } + } + return false +} + +/* Basic Output Helpers */ + +// DrawStringAtPoint Draw a string of text at x, y with foreground color fg, background color bg +func DrawStringAtPoint(str string, x int, y int, fg termbox.Attribute, bg termbox.Attribute) (int, int) { + xPos := x + for _, runeValue := range str { + termbox.SetCell(xPos, y, runeValue, fg, bg) + xPos++ + } + return xPos, y +} + +// FillWithChar Fills from x1,y1 through x2,y2 with the rune r, foreground color fg, background bg +func FillWithChar(r rune, x1, y1, x2, y2 int, fg termbox.Attribute, bg termbox.Attribute) { + for xx := x1; xx <= x2; xx++ { + for yx := y1; yx <= y2; yx++ { + termbox.SetCell(xx, yx, r, fg, bg) + } + } +} + +// DrawBorder Draw a border around the area inside x1,y1 -> x2, y2 +func DrawBorder(x1, y1, x2, y2 int, fg termbox.Attribute, bg termbox.Attribute) { + termbox.SetCell(x1, y1, '+', fg, bg) + FillWithChar('-', x1+1, y1, x2-1, y1, fg, bg) + termbox.SetCell(x2, y1, '+', fg, bg) + + FillWithChar('|', x1, y1+1, x1, y2-1, fg, bg) + FillWithChar('|', x2, y1+1, x2, y2-1, fg, bg) + + termbox.SetCell(x1, y2, '+', fg, bg) + FillWithChar('-', x1+1, y2, x2-1, y2, fg, bg) + termbox.SetCell(x2, y2, '+', fg, bg) +} + +// AlignText Aligns the text txt within width characters using the specified alignment +func AlignText(txt string, width int, align TextAlignment) string { + return AlignTextWithFill(txt, width, align, ' ') +} + +// AlignTextWithFill Aligns the text txt within width characters using the specified alignment +// filling any spaces with the 'fill' character +func AlignTextWithFill(txt string, width int, align TextAlignment, fill rune) string { + fillChar := string(fill) + numSpaces := width - len(txt) + switch align { + case AlignCenter: + if numSpaces/2 > 0 { + return fmt.Sprintf("%s%s%s", + strings.Repeat(fillChar, numSpaces/2), + txt, strings.Repeat(fillChar, numSpaces/2), + ) + } + return txt + case AlignRight: + return fmt.Sprintf("%s%s", strings.Repeat(fillChar, numSpaces), txt) + default: + if numSpaces >= 0 { + return fmt.Sprintf("%s%s", txt, strings.Repeat(fillChar, numSpaces)) + } + return txt + } +} + +/* More advanced things are in their respective files */ diff --git a/vendor/vendor.json b/vendor/vendor.json new file mode 100644 index 0000000..1b48d0e --- /dev/null +++ b/vendor/vendor.json @@ -0,0 +1,25 @@ +{ + "comment": "", + "ignore": "test", + "package": [ + { + "checksumSHA1": "DdH3xAkzAWJ4B/LGYJyCeRsly2I=", + "path": "github.com/mattn/go-runewidth", + "revision": "d6bea18f789704b5f83375793155289da36a3c7f", + "revisionTime": "2016-03-15T04:07:12Z" + }, + { + "checksumSHA1": "ymd32uFjzdvI2g1f1RiDc2eebUc=", + "path": "github.com/nsf/termbox-go", + "revision": "0723e7c3d0a317dea811f0fbe4d6edd81908c971", + "revisionTime": "2016-07-18T14:06:19Z" + }, + { + "checksumSHA1": "Tcrg5XlCcJktDmTdu9nVt/TG0lo=", + "path": "gogs.bullercodeworks.com/brian/termbox-util", + "revision": "d5803aecc499185e9ccb225bba6f9c36508cc5f0", + "revisionTime": "2016-02-25T16:31:28Z" + } + ], + "rootPath": "gogs.bullercodeworks.com/brian/gopher-battle" +}