ctop/widgets/input.go

91 lines
1.7 KiB
Go
Raw Permalink Normal View History

2017-01-21 19:15:29 +01:00
package widgets
import (
"strings"
ui "github.com/gizak/termui"
)
var (
2017-03-12 22:31:51 +01:00
input_chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_."
2017-01-21 19:15:29 +01:00
)
2017-02-15 08:40:16 +01:00
type Padding [2]int // x,y padding
2017-01-21 19:15:29 +01:00
type Input struct {
ui.Block
Label string
Data string
2017-01-21 19:46:48 +01:00
MaxLen int
2017-01-21 19:15:29 +01:00
TextFgColor ui.Attribute
TextBgColor ui.Attribute
stream chan string // stream text as it changes
2017-01-21 19:41:28 +01:00
padding Padding
2017-01-21 19:15:29 +01:00
}
func NewInput() *Input {
i := &Input{
Block: *ui.NewBlock(),
Label: "input",
2017-01-21 19:46:48 +01:00
MaxLen: 20,
2017-03-08 00:40:03 +01:00
TextFgColor: ui.ThemeAttr("menu.text.fg"),
TextBgColor: ui.ThemeAttr("menu.text.bg"),
2017-01-21 19:41:28 +01:00
padding: Padding{4, 2},
2017-01-21 19:15:29 +01:00
}
2017-03-08 00:40:03 +01:00
i.BorderFg = ui.ThemeAttr("menu.border.fg")
i.BorderLabelFg = ui.ThemeAttr("menu.label.fg")
2017-01-21 19:46:48 +01:00
i.calcSize()
2017-01-21 19:15:29 +01:00
return i
}
2017-01-21 19:46:48 +01:00
func (i *Input) calcSize() {
i.Height = 3 // minimum height
i.Width = i.MaxLen + (i.padding[0] * 2)
}
2017-01-21 19:15:29 +01:00
func (i *Input) Buffer() ui.Buffer {
var cell ui.Cell
buf := i.Block.Buffer()
2017-02-13 04:16:36 +01:00
x := i.Block.X + i.padding[0]
y := i.Block.Y + 1
2017-01-21 19:15:29 +01:00
for _, ch := range i.Data {
cell = ui.Cell{Ch: ch, Fg: i.TextFgColor, Bg: i.TextBgColor}
2017-02-13 04:16:36 +01:00
buf.Set(x, y, cell)
2017-01-21 19:15:29 +01:00
x++
}
return buf
}
func (i *Input) Stream() chan string {
i.stream = make(chan string)
return i.stream
}
2017-01-21 19:15:29 +01:00
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]
i.stream <- i.Data
2017-01-21 19:15:29 +01:00
}
ui.Render(i)
2017-01-21 19:46:48 +01:00
return
}
if len(i.Data) >= i.MaxLen {
return
2017-01-21 19:15:29 +01:00
}
if strings.Contains(input_chars, ch) {
2017-01-21 19:15:29 +01:00
i.Data += ch
i.stream <- i.Data
2017-01-21 19:15:29 +01:00
ui.Render(i)
}
}
// Setup some default handlers for menu navigation
func (i *Input) InputHandlers() {
ui.Handle("/sys/kbd/", i.KeyPress)
}