sampler-fork/component/asciibox/asciibox.go

85 lines
1.8 KiB
Go
Raw Normal View History

2019-02-17 23:00:00 +00:00
package asciibox
import (
2019-03-14 03:01:44 +00:00
ui "github.com/gizak/termui/v3"
2019-02-26 04:36:23 +00:00
fl "github.com/mbndr/figlet4go"
2019-02-24 06:14:12 +00:00
"github.com/sqshq/sampler/asset"
2019-03-13 03:19:19 +00:00
"github.com/sqshq/sampler/component"
2019-03-08 04:04:46 +00:00
"github.com/sqshq/sampler/config"
2019-02-17 23:00:00 +00:00
"github.com/sqshq/sampler/data"
"image"
)
type AsciiBox struct {
ui.Block
2019-03-08 04:04:46 +00:00
data.Consumer
2019-03-13 03:19:19 +00:00
*component.Alerter
2019-02-17 23:00:00 +00:00
text string
ascii string
style ui.Style
render *fl.AsciiRender
options *fl.RenderOptions
}
2019-02-26 04:36:23 +00:00
const asciiFontExtension = ".flf"
2019-03-08 04:04:46 +00:00
func NewAsciiBox(c config.AsciiBoxConfig) *AsciiBox {
2019-02-17 23:00:00 +00:00
2019-03-13 03:19:19 +00:00
consumer := data.NewConsumer()
2019-02-17 23:00:00 +00:00
block := *ui.NewBlock()
2019-03-08 04:04:46 +00:00
block.Title = c.Title
2019-02-17 23:00:00 +00:00
options := fl.NewRenderOptions()
2019-03-08 04:04:46 +00:00
options.FontName = string(*c.Font)
2019-02-17 23:00:00 +00:00
2019-02-26 04:36:23 +00:00
fontStr, err := asset.Asset(options.FontName + asciiFontExtension)
2019-02-24 06:14:12 +00:00
if err != nil {
panic("Can't load the font: " + err.Error())
}
render := fl.NewAsciiRender()
_ = render.LoadBindataFont(fontStr, options.FontName)
2019-03-08 04:04:46 +00:00
box := AsciiBox{
Block: block,
2019-03-13 03:19:19 +00:00
Consumer: consumer,
Alerter: component.NewAlerter(consumer.AlertChannel),
2019-03-08 04:04:46 +00:00
style: ui.NewStyle(*c.Color),
render: render,
options: options,
2019-02-17 23:00:00 +00:00
}
2019-03-08 04:04:46 +00:00
go box.consume()
return &box
2019-02-17 23:00:00 +00:00
}
2019-03-08 04:04:46 +00:00
func (a *AsciiBox) consume() {
for {
select {
case sample := <-a.SampleChannel:
a.text = sample.Value
a.ascii, _ = a.render.RenderOpts(sample.Value, a.options)
//case alert := <-a.alertChannel:
// TODO base alerting mechanism
}
}
2019-02-17 23:00:00 +00:00
}
func (a *AsciiBox) Draw(buffer *ui.Buffer) {
buffer.Fill(ui.NewCell(' ', ui.NewStyle(ui.ColorBlack)), a.GetRect())
a.Block.Draw(buffer)
point := a.Inner.Min
2019-03-14 03:01:44 +00:00
cells := ui.ParseStyles(a.ascii, a.style)
2019-02-17 23:00:00 +00:00
for i := 0; i < len(cells) && point.Y < a.Inner.Max.Y; i++ {
if cells[i].Rune == '\n' {
point = image.Pt(a.Inner.Min.X, point.Y+1)
} else if point.In(a.Inner) {
buffer.SetCell(cells[i], point)
point = point.Add(image.Pt(1, 0))
}
}
}