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
|
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
}
func NewBuffer(x, y int, width, height int) *Buffer {
b := &Buffer{NewWidgetBase(x, y, width, height), []string{}, 0, font.Font18, 1.5, 10.}
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)
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(BUFFER_FOREGROUND)
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) 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()
}
|