aboutsummaryrefslogtreecommitdiff
path: root/go/ui/buffer.go
blob: 201273b837c49b2a82455e4062582582f9eff20d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package ui

import (
	"image/color"

	"github.com/hajimehoshi/ebiten/v2"
	"github.com/hajimehoshi/ebiten/v2/text"

	"muhq.space/muhqs-game/go/font"
)

var (
	BUFFER_BACKGROUND = Gray
	BUFFER_FOREGROUND = color.White
)

type Buffer struct {
	WidgetBase
	lines []string
	pos   int
}

func NewBuffer(x, y int, width, height int) *Buffer {
	b := &Buffer{NewWidgetBase(x, y, width, height), []string{}, 0}
	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(BUFFER_BACKGROUND)
	y := 0
	for _, line := range b.lines[b.pos:] {
		bounds := text.BoundString(font.Font18, line)
		y += bounds.Dy()
		if y > b.Height {
			break
		}
		text.Draw(img, line, font.Font18, 0, y, BUFFER_FOREGROUND)
	}
	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) 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) 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()
}