ctop/widgets/input.go

81 lines
1.4 KiB
Go
Raw Normal View History

2017-01-21 18:15:29 +00:00
package widgets
import (
"strings"
ui "github.com/gizak/termui"
)
var (
input_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_."
)
2017-02-15 07:40:16 +00:00
type Padding [2]int // x,y padding
2017-01-21 18:15:29 +00:00
type Input struct {
ui.Block
Label string
Data string
2017-01-21 18:46:48 +00:00
MaxLen int
2017-01-21 18:15:29 +00:00
TextFgColor ui.Attribute
TextBgColor ui.Attribute
2017-01-21 18:41:28 +00:00
padding Padding
2017-01-21 18:15:29 +00:00
}
func NewInput() *Input {
i := &Input{
Block: *ui.NewBlock(),
Label: "input",
2017-01-21 18:46:48 +00:00
MaxLen: 20,
2017-01-21 18:15:29 +00:00
TextFgColor: ui.ThemeAttr("par.text.fg"),
TextBgColor: ui.ThemeAttr("par.text.bg"),
2017-01-21 18:41:28 +00:00
padding: Padding{4, 2},
2017-01-21 18:15:29 +00:00
}
2017-01-21 18:46:48 +00:00
i.calcSize()
2017-01-21 18:15:29 +00:00
return i
}
2017-01-21 18:46:48 +00:00
func (i *Input) calcSize() {
i.Height = 3 // minimum height
i.Width = i.MaxLen + (i.padding[0] * 2)
}
2017-01-21 18:15:29 +00:00
func (i *Input) Buffer() ui.Buffer {
var cell ui.Cell
buf := i.Block.Buffer()
2017-02-13 03:16:36 +00:00
x := i.Block.X + i.padding[0]
y := i.Block.Y + 1
2017-01-21 18:15:29 +00:00
for _, ch := range i.Data {
cell = ui.Cell{Ch: ch, Fg: i.TextFgColor, Bg: i.TextBgColor}
2017-02-13 03:16:36 +00:00
buf.Set(x, y, cell)
2017-01-21 18:15:29 +00:00
x++
}
return buf
}
func (i *Input) KeyPress(e ui.Event) {
ch := strings.Replace(e.Path, "/sys/kbd/", "", -1)
if ch == "C-8" {
idx := len(i.Data) - 1
if idx > -1 {
i.Data = i.Data[0:idx]
}
ui.Render(i)
2017-01-21 18:46:48 +00:00
return
}
if len(i.Data) >= i.MaxLen {
return
2017-01-21 18:15:29 +00:00
}
if strings.Index(input_chars, ch) > -1 {
i.Data += ch
ui.Render(i)
}
}
// Setup some default handlers for menu navigation
func (i *Input) InputHandlers() {
ui.Handle("/sys/kbd/", i.KeyPress)
}