package ui import ( "image/color" "iter" "github.com/hajimehoshi/ebiten/v2" "github.com/hajimehoshi/ebiten/v2/text/v2" "muhq.space/muhqs-game/go/font" ) var ( BUFFER_BACKGROUND = Gray BUFFER_FOREGROUND = color.White ) type Buffer struct { WidgetBase lines []string pos int font *text.GoTextFace lineSpacing float64 xMargin float64 bg color.Color fg color.Color } func NewBuffer(x, y int, width, height int) *Buffer { b := &Buffer{ NewWidgetBase(x, y, width, height), []string{}, 0, font.Font18, 1.5, 10., BUFFER_BACKGROUND, BUFFER_FOREGROUND, } b.renderImpl = func() *ebiten.Image { return b.render() } return b } func (b *Buffer) render() *ebiten.Image { img := ebiten.NewImage(b.Width, b.Height) img.Fill(b.bg) var y float64 = -b.font.Size for _, line := range b.lines[b.pos:] { _, h := text.Measure(line, b.font, b.font.Size*b.lineSpacing) y += h if y > float64(b.Height) { break } op := &text.DrawOptions{} op.ColorScale.ScaleWithColor(b.fg) op.GeoM.Translate(b.xMargin, float64(y)) op.LineSpacing = b.font.Size * b.lineSpacing text.Draw(img, line, b.font, op) } return img } func (b *Buffer) AddLines(lines []string) { b.lines = append(b.lines, lines...) b.ForceRedraw() } func (b *Buffer) AddLine(line string) { b.AddLines([]string{line}) } func (b *Buffer) AddText(text string) { // TODO: auto break text lines := []string{text} b.AddLines(lines) } func (b *Buffer) ClearLines() { b.lines = []string{} b.ForceRedraw() } func (b *Buffer) RemoveLast() { b.lines = b.lines[:len(b.lines)-1] b.ForceRedraw() } func (b *Buffer) Remove(idx int) { b.lines = append(b.lines[:idx], b.lines[idx+1:]...) b.ForceRedraw() } func (b *Buffer) PrefixLine(idx int, prefix string) { b.lines[idx] = prefix + b.lines[idx] b.ForceRedraw() } func (b *Buffer) LinesSeq() iter.Seq[string] { return func(yield func(string) bool) { for _, l := range b.lines { if !yield(l) { return } } } } func (*Buffer) IsScrollable() bool { return true } func (b *Buffer) Scroll(x, y int) { if y == 0 { return } if y < 0 && b.pos > 0 { b.pos-- } else if y > 0 && b.pos < len(b.lines)-1 { b.pos++ } b.ForceRedraw() } func (b *Buffer) Bg(bg color.Color) *Buffer { b.bg = bg return b } func (b *Buffer) Fg(fg color.Color) *Buffer { b.fg = fg return b }