aboutsummaryrefslogtreecommitdiff
path: root/go/ui/buffer.go
blob: d2a4667e2ee448601fa27200dffb11171b487117 (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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
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
}