Files
beatglow/app/widget/menu.go
T
2026-10-29 17:29:54 +01:00

121 lines
2.4 KiB
Go

package widget
import (
"image"
"image/color"
"reflect"
"github.com/sirupsen/logrus"
"github.com/BeatGlow/beatglow/app"
"github.com/BeatGlow/beatglow/app/menu"
"github.com/BeatGlow/display/draw"
)
type Menu struct {
Base
Root *menu.Menu
curr, next *menu.Menu // currently in view and next in view
}
func NewMenu(size image.Point, root *menu.Menu) *Menu {
w := new(Menu)
w.Extend(w)
w.Resize(size)
return w
}
func (w *Menu) String() string {
return "menu"
}
func (w *Menu) Update(root *menu.Menu) *Menu {
w.mu.Lock()
w.Root = root
w.curr = nil
w.next = root
w.mu.Unlock()
w.changed.Store(true)
return w
}
func (w *Menu) Redraw() {
w.changed.Store(true)
}
func (w *Menu) Refresh(ctx app.Context) bool {
if !w.IsVisible() {
return false
}
var (
bounds = w.Bounds()
size = bounds.Size()
)
if w.changed.CompareAndSwap(true, false) || w.buffer == nil || (w.curr != w.next && w.next != nil) {
if w.buffer == nil {
w.buffer = app.BufferFor(ctx, size)
w.Root.SetPageSize(size.Y / 16)
}
if w.curr != w.next && w.next != nil {
w.curr, w.next = w.next, nil
}
// Clear the buffer.
app.ImageClear(w.buffer)
// Calculate the start and end indices for the current page
var (
menu = w.curr
pageSize = menu.PageSize()
start = (menu.Position / pageSize) * pageSize
end = start + pageSize
)
if max := len(menu.Items); end > max {
end = max
}
// Draw visible menu items.
logrus.WithFields(logrus.Fields{
"start": start,
"end": end,
"per page": pageSize,
}).Debug("showing menu items")
for i, item := range menu.Items[start:end] {
var (
y = i * 16 // 16 pixels per line
rect = image.Rect(0, 0, size.X-8, 16).Add(image.Pt(0, y))
view = app.ImageView(w.buffer, rect)
isActive = start+i == menu.Position
)
item.Render(view, isActive, menu.IsEditing(), &w.styles.Text)
}
// Draw scroll bar.
for y := 0; y < size.Y; y += 2 {
w.buffer.Set(size.X-2, y, color.Gray{Y: 0x1f})
}
if len(menu.Items) > pageSize {
y := size.Y / len(menu.Items) * menu.Position
draw.Box(w.buffer, image.Rect(size.X-3, y, size.X, y+size.Y/len(menu.Items)), color.Gray{Y: 0x7f})
}
}
app.ImageCopyBounds(ctx.Display(), w.buffer, bounds.Add(w.position.Load()))
return true
}
type MenuItem struct {
Icon string
Text string
Type reflect.Type
Value reflect.Value
}
var (
_ app.Widget = (*Menu)(nil)
)