Refactored the menu system

This commit is contained in:
maze authored and maze committed 2026-10-29 17:29:54 +01:00
1 parent 4ae7655cd8
commit 86aad51e37
12 files changed
+475 -345

No files matched your search

+18 -4
View File
@@ -12,6 +12,7 @@ import (
_ "embed"
)
// IconFont is the Nerd Font patched Hack Mono Regular font at 16pt.
var IconFont = HackMono.WithPointSize(16)
func init() {
@@ -23,17 +24,30 @@ func init() {
}
}
// Icon draws an icon from the built-in Nerd Font set.
//
// Use https://www.nerdfonts.com/cheat-sheet to find what icons to use;
// you do not have to supply the "nf-" prefix for the name.
func Icon(dst draw.Image, p image.Point, c color.Color, name string) {
icon := nameIcon[strings.ToLower(name)]
logrus.Debugf("map font %q -> %q", name, icon)
IconP(dst, p, c, icon)
if strings.HasPrefix(name, "nf-") {
name = name[3:]
}
icon := nameIcon[strings.ToLower(name)]
if icon == 0 {
logrus.Debugf("icon %q not found", name)
IconP(dst, p, c, nameIcon["md_image_broken"])
} else {
IconP(dst, p, c, icon)
}
}
// IconP draws an icon from the built-in Nerd Font set using code points.
func IconP(dst draw.Image, p image.Point, c color.Color, icon rune) {
IconFont.Draw(dst, p, image.NewUniform(c), string(icon))
}
// Maps codepoints to names used in Nerd Font.
// maps codepoints to names used in Nerd Font.
var nameIcon = map[string]rune{}
var iconName = map[rune]string{
'': "cod_add",
+38
View File
@@ -124,3 +124,41 @@ func (i HorizontalWrappingImage) Bounds() image.Rectangle {
Max: bounds.Max.Add(delta),
}
}
type imageView struct {
draw.Image
Rect image.Rectangle
}
func ImageView(dst draw.Image, rect image.Rectangle) draw.Image {
return imageView{
Image: dst,
Rect: rect,
}
}
func (i imageView) Bounds() image.Rectangle {
return image.Rectangle{
Max: i.Rect.Max.Sub(i.Rect.Min),
}
}
func (i imageView) At(x, y int) color.Color {
// Translate x, y to inside our view
x += i.Rect.Min.X
y += i.Rect.Min.Y
if !(image.Point{X: x, Y: y}).In(i.Rect) {
return color.Transparent
}
return i.Image.At(x, y)
}
func (i imageView) Set(x, y int, c color.Color) {
// Translate x, y to inside our view
x += i.Rect.Min.X
y += i.Rect.Min.Y
if !(image.Point{X: x, Y: y}).In(i.Rect) {
return
}
i.Image.Set(x, y, c)
}
+1 -1
View File
@@ -50,7 +50,7 @@ const playingWaterfallHeight = 32
func Playing(ctx app.Context) app.Layout {
bounds := ctx.Display().Bounds()
styles := app.StylesFor(ctx)
styles := app.StylesFor(ctx.Display().ColorModel())
layout := &playing{
base: base{name: "playing"},
phonesWidget: widget.NewText(image.Pt(10, 12)),
+58 -164
View File
@@ -2,9 +2,9 @@ package layout
import (
"reflect"
"strings"
"github.com/BeatGlow/beatglow/app"
"github.com/BeatGlow/beatglow/app/menu"
"github.com/BeatGlow/beatglow/app/widget"
"github.com/BeatGlow/beatglow/config"
)
@@ -12,204 +12,98 @@ import (
type settings struct {
base
settings *config.Settings
menu []settingsMenu
menu *menu.Menu
menuWidget *widget.Menu
index int
}
type settingsMenu struct {
Item interface{} // pointer to the item we're showing a menu for
Value reflect.Value // value of the item we're showing a menu for
Fields []reflect.Value // fields contained in this item
Items []widget.MenuItem // items shown in the menu
}
// Settings is the settings menu.
func Settings(ctx app.Context) app.Layout {
bounds := ctx.Display().Bounds()
styles := app.StylesFor(ctx)
styles := app.StylesFor(ctx.Display().ColorModel())
layout := &settings{
base: base{name: "settings"},
menuWidget: widget.NewMenu(bounds.Size()),
menuWidget: widget.NewMenu(bounds.Size(), nil),
settings: ctx.Settings(),
}
layout.menuWidget.SetStyles(*styles)
var err error
if layout.menu, err = menu.New(layout.settings, 4, nil); err != nil {
panic(err)
}
layout.menuWidget.
Update(layout.menu).
SetStyles(*styles)
layout.widgets = []app.Widget{
layout.menuWidget,
}
layout.show(layout.settings)
return layout
}
func (l *settings) show(data interface{}) {
var (
log = l.log()
v = reflect.ValueOf(data)
pointer bool
pointerV = v
)
for {
if pointerV.Kind() == reflect.Interface {
pointerV = pointerV.Elem()
}
if pointerV.Kind() == reflect.Ptr {
pointer = true
v = reflect.Indirect(pointerV)
}
if pointer {
pointerV = v
}
pointer = false
// If we still have a pointer or interface we have to indirect another level.
switch pointerV.Kind() {
case reflect.Ptr, reflect.Interface:
continue
}
break
}
switch v.Kind() {
case reflect.Struct:
log.Printf("setup for struct: %T", data)
l.showStruct(v, data)
default:
log.Printf("setup for what? %T", data)
}
// Update widget.
l.menuWidget.SetItems(l.menu[0].Items)
// Reset selected item.
l.index = 0
}
func (l *settings) showStruct(v reflect.Value, data interface{}) {
var (
log = l.log()
vt = v.Type()
fields = make([]reflect.Value, 0, vt.NumField())
menuItems = make([]widget.MenuItem, 0, vt.NumField())
)
foreachStructField(v, func(fv reflect.Value, sf reflect.StructField) bool {
icon, tags := parseSettingsTag(sf.Tag)
log.Printf("field %#+v: %#+v -> %s %v", sf, fv, icon, tags)
log.Printf("can addr? %t", fv.CanAddr())
if _, ignore := tags["ignore"]; ignore {
return false
}
fields = append(fields, fv)
menuItems = append(menuItems, widget.MenuItem{
Icon: icon,
Text: sf.Name,
Type: fv.Type(),
Value: fv,
})
return false
})
// Push current item forward on the stack
l.menu = append([]settingsMenu{{
Item: data,
Value: v,
Fields: fields,
Items: menuItems,
}}, l.menu...)
}
func (l *settings) handleSelect(index int) {
var (
active = l.menu[0].Fields[index]
value = active
kind = value.Type().Kind()
)
if kind == reflect.Ptr {
value = reflect.Indirect(value)
kind = value.Type().Kind()
}
log := l.log()
log.WithField("index", index).Debugf("jump to menu item %v (%v/%v)", value, value.Type(), kind)
switch kind {
case reflect.Struct:
l.show(active.Interface())
case reflect.Bool:
//newValue := reflect.New(active.Type())
//newValue.Elem().Set(reflect.ValueOf(!active.Bool()))
//active.Elem().Set(newValue)
active.SetBool(!active.Bool())
l.menuWidget.Redraw()
default:
log.WithField("type", kind).Debug("no handler for data type")
}
}
func parseSettingsTag(tag reflect.StructTag) (icon string, settings map[string]string) {
icon = tag.Get("icon")
if s, ok := tag.Lookup("settings"); ok {
settings = make(map[string]string)
for _, kv := range strings.Split(s, " ") {
if kv = strings.TrimSpace(kv); kv == "" {
continue
}
if i := strings.IndexByte(kv, ':'); i > -1 {
k, v := kv[:i], kv[i+1:]
settings[k] = v
} else {
settings[kv] = ""
}
}
}
return
}
func (l *settings) HandleRotary(ctx app.Context, delta int) {
if l.menuWidget.IsVisible() {
l.index = l.menuWidget.Change(delta)
l.log().WithField("item", l.index).Debug("menu item changed")
log := l.log()
log.WithField("item", l.index).Debug("menu item changed")
l.menu.Change(delta)
if l.menu.IsEditing() {
// React on changed value, if it's an immediate change.
switch item := l.menu.Items[l.menu.Position]; item.Label {
case "Display contrast":
if err := ctx.Display().SetContrast(*(item.Value.(*uint8))); err != nil {
log.WithError(err).Error("error updating contrast")
}
default:
log.WithField("label", item.Label).Debug("no immediate change")
}
}
l.menuWidget.Redraw()
}
}
func (l *settings) HandleButtonPress(ctx app.Context) {
if l.menuWidget.IsVisible() {
log := l.log().WithField("press", l.index)
if l.index == 0 {
if depth := len(l.menu); depth > 1 {
log.Debug("go back in menu")
l.index = 0
l.menu = l.menu[1:]
l.menuWidget.SetItems(l.menu[0].Items)
} else {
// Go back pressed.
log.Debug("go back to previous layout")
log := l.log()
if l.menu.IsEditing() {
log.Debug("exit edit mode")
l.menu.ToggleEdit()
} else if l.menu.IsSubMenu() {
log.Debug("enter sub menu")
l.menu = l.menu.EnterSubMenu()
} else if item := l.menu.ActiveItem(); item.Value == menu.Back {
log.Debug("exit sub menu")
menu := l.menu.ExitSubMenu()
if menu == nil {
// Close settings layout, exiting root.
ctx.Show(nil)
}
return
}
l.menu = menu
} else {
log.Debug("enter edit mode")
l.menu.ToggleEdit()
}
log.Debug("handle selected item")
l.handleSelect(l.index - 1)
// Trigger re-render.
l.menuWidget.Update(l.menu)
}
}
func (l *settings) HandleButtonLongPress(ctx app.Context) {
if l.menuWidget.IsVisible() {
l.menu = nil
l.show(l.settings)
ctx.Show(nil) // Close settings
// Rewind to root menu
for {
parent := l.menu.Parent
if parent == nil {
break
}
l.menu = parent
}
// Close settings layout.
ctx.Show(nil)
}
}
+121 -41
View File
@@ -6,6 +6,8 @@ import (
"reflect"
"strconv"
"strings"
"github.com/sirupsen/logrus"
)
type Menu struct {
@@ -14,14 +16,14 @@ type Menu struct {
// Current selected position.
Position int
// Number of items visible per page.
PageSize int
// Parent menu for this submenu.
Parent *Menu
// IsEditing indicates edit mode for an item.
IsEditing bool
// Editing indicates edit mode for an item.
Editing bool
// Number of items visible per page.
pageSize int
}
func New(data any, pageSize int, parent *Menu) (*Menu, error) {
@@ -41,8 +43,13 @@ func New(data any, pageSize int, parent *Menu) (*Menu, error) {
}
menu := &Menu{
PageSize: pageSize,
Parent: parent,
pageSize: pageSize,
Items: []Item{{
Label: "Go back",
Icon: "md_history",
Value: Back,
}},
}
typ := ref.Type()
@@ -50,7 +57,7 @@ func New(data any, pageSize int, parent *Menu) (*Menu, error) {
var (
field = typ.Field(i)
fieldRef = ref.Field(i)
value = ref.Field(i).Interface()
value = ref.Field(i).Addr().Interface()
icon = field.Tag.Get("icon")
label = field.Tag.Get("menu")
options = strings.Split(field.Tag.Get("options"), ",")
@@ -81,6 +88,13 @@ func New(data any, pageSize int, parent *Menu) (*Menu, error) {
}
}
if !fieldRef.CanAddr() {
panic(fmt.Sprintf("fieldref %T for %T is not addressable", fieldRef, value))
}
if !fieldRef.CanSet() {
panic(fmt.Sprintf("fieldref %T for %T is not settable", fieldRef, value))
}
switch field.Type.Kind() {
case reflect.Struct:
subMenu, err := New(value, pageSize, menu)
@@ -165,62 +179,56 @@ func New(data any, pageSize int, parent *Menu) (*Menu, error) {
// Change is used for editing and navigating, delta is either positive or negative input.
func (m *Menu) Change(delta int) {
if m.IsEditing {
if m.Editing {
m.edit(delta)
} else {
m.move(delta)
}
}
// ToggleEdit switches between navigation and editing modes.
func (m *Menu) ToggleEdit() {
m.IsEditing = !m.IsEditing
}
// EnterSubmenu enters the selected submenu
func (m *Menu) EnterSubmenu() *Menu {
if m.Position < len(m.Items) && m.Items[m.Position].SubMenu != nil {
return m.Items[m.Position].SubMenu
}
return nil
}
// ExitSubmenu returns to the parent menu
func (m *Menu) ExitSubmenu() *Menu {
if m.Parent != nil {
return m.Parent
}
return m // If no parent, return itself (root menu)
}
func (m *Menu) edit(delta int) {
// Adjust the value if editing
item := &m.Items[m.Position]
logrus.WithFields(logrus.Fields{
"action": "edit",
"delta": delta,
"type": fmt.Sprintf("%T", item.Value),
}).Debug("menu change")
// Adjust the value if editing
switch v := item.Value.(type) {
case int:
newValue := v + delta
case *uint8:
newValue := *v + uint8(delta*item.Step)
if newValue >= uint8(item.Min) && newValue <= uint8(item.Max) {
*v = newValue
}
case *int:
newValue := *v + (delta * item.Step)
if newValue >= item.Min && newValue <= item.Max {
item.Value = newValue
item.Field.SetInt(int64(newValue)) // Update the original struct field
*v = newValue
}
case bool:
case *bool:
if delta != 0 {
item.Value = !v
item.Field.SetBool(!v) // Update the original struct field
*v = !*v
}
case string:
case *string:
if len(item.Options) > 0 {
currentIndex := indexOf(v, item.Options)
currentIndex := indexOf(*v, item.Options)
if currentIndex != -1 {
newIndex := (currentIndex + delta + len(item.Options)) % len(item.Options)
item.Value = item.Options[newIndex]
item.Field.SetString(item.Options[newIndex]) // Update the original struct field
*v = item.Options[newIndex]
}
}
}
}
func (m *Menu) move(delta int) {
logrus.WithFields(logrus.Fields{
"action": "move",
"delta": delta,
"position": m.Position,
}).Debug("menu change")
// Move the cursor if not editing
m.Position += delta
if m.Position < 0 {
@@ -228,6 +236,69 @@ func (m *Menu) move(delta int) {
} else if m.Position >= len(m.Items) {
m.Position = len(m.Items) - 1
}
logrus.WithFields(logrus.Fields{
"action": "move",
"delta": delta,
"position": m.Position,
}).Debug("menu change done")
}
// ActiveItem is the current item that is active.
func (m *Menu) ActiveItem() Item {
return m.Items[m.Position]
}
// PageSize returns the current page size.
func (m *Menu) PageSize() int {
return m.pageSize
}
// SetPageSize updates the page size.
func (m *Menu) SetPageSize(pageSize int) {
m.pageSize = pageSize
for _, item := range m.Items {
if item.SubMenu != nil {
item.SubMenu.SetPageSize(pageSize)
}
}
}
// IsEditing checks if we're in editing mode.
func (m *Menu) IsEditing() bool {
return m.Editing
}
// ToggleEdit switches between navigation and editing modes.
func (m *Menu) ToggleEdit() {
m.Editing = !m.Editing
}
func (m *Menu) IsSubMenu() bool {
return m.Position < len(m.Items) && m.Items[m.Position].SubMenu != nil
}
// EnterSubmenu enters the selected sub menu.
func (m *Menu) EnterSubMenu() *Menu {
if m.Position < len(m.Items) && m.Items[m.Position].SubMenu != nil {
logrus.WithFields(logrus.Fields{
"action": "enter subment",
"item": m.Items[m.Position].Label,
}).Debug("menu enter sub menu")
return m.Items[m.Position].SubMenu
}
logrus.Debug("menu enter sub menu failed; no sub menu item")
return nil
}
// ExitSubmenu returns to the parent menu.
func (m *Menu) ExitSubMenu() *Menu {
if m.Parent != nil {
logrus.Debug("menu exit sub menu")
return m.Parent
}
logrus.Debug("menu exit sub menu failed; no parent")
return nil // If no parent, return nil.
}
type Item struct {
@@ -262,3 +333,12 @@ func indexOf(needle string, haystack []string) int {
}
return -1
}
// Magic actions.
type menuAction struct{}
// Actions.
var (
Back menuAction
SubMenu menuAction
)
+131
View File
@@ -0,0 +1,131 @@
package menu
import (
"fmt"
"image"
"image/color"
"math"
"github.com/sirupsen/logrus"
"github.com/BeatGlow/display/draw"
"github.com/BeatGlow/display/pixel"
"github.com/BeatGlow/beatglow/app"
"github.com/BeatGlow/beatglow/app/font"
)
func (item *Item) Render(dst draw.Image, isActive, isEditing bool, style *app.TextStyle) {
var (
bounds = dst.Bounds()
edge = image.Rectangle{Min: bounds.Min, Max: bounds.Max.Sub(image.Pt(1, 1))}
)
logrus.WithFields(logrus.Fields{
"bounds": bounds,
"size": bounds.Size(),
}).Debug("render menu item")
if style == nil {
style = &app.StylesFor(dst.ColorModel()).Text
}
// Clear area.
app.ImageClear(dst)
if isEditing && isActive {
draw.Box(dst, bounds, pixel.Gray4{Y: 0x4})
draw.Rectangle(dst, edge, pixel.Gray4{Y: 0xf})
} else if isActive {
draw.Box(dst, bounds, pixel.Gray4{Y: 0x2})
draw.Rectangle(dst, edge, pixel.Gray4{Y: 0xb})
} else {
draw.Rectangle(dst, edge, pixel.Gray4{Y: 0x2})
}
// Render icon.
if item.Icon != "" {
font.Icon(dst, bounds.Min.Add(image.Pt(3, 2)), color.White, item.Icon)
}
// Render label.
style.Font.Draw(dst, bounds.Min.Add(image.Pt(16, 3)), style.Foreground(), item.Label)
// Render icon and widgets.
switch value := item.Value.(type) {
case *bool:
item.renderBool(dst, *value, isEditing)
case *uint8:
item.renderUint8(dst, *value, isEditing, style)
case *int:
item.renderInt(dst, *value, isEditing, style)
case *string:
item.renderString(dst, *value, isEditing, style)
case menuAction:
// no further renditions needed
case nil:
// sub menu item has no value
item.renderSubMenu(dst, style)
default:
logrus.WithFields(logrus.Fields{
"label": item.Label,
"type": fmt.Sprintf("%T", value),
}).Warn("no menu renderer for type")
}
}
func (item *Item) renderSubMenu(dst draw.Image, style *app.TextStyle) {
bounds := dst.Bounds()
font.Icon(dst, image.Pt(bounds.Max.X-14, bounds.Min.Y+3), color.White, "md_folder_open_outline")
}
func (item *Item) renderBool(dst draw.Image, value bool, isEditing bool) {
var (
bounds = dst.Bounds()
icon = "md_checkbox_blank_outline"
)
if value {
icon = "md_checkbox_marked_outline"
}
font.Icon(dst, image.Pt(bounds.Max.X-14, bounds.Min.Y+3), color.White, icon)
}
func (item *Item) renderUint8(dst draw.Image, value uint8, isEditing bool, style *app.TextStyle) {
var (
bounds = dst.Bounds()
text = fmt.Sprintf("%d", value)
width, _ = style.Font.MeasureString(text)
point = image.Pt(bounds.Max.X-3-width, bounds.Min.Y+3)
)
style.Font.Draw(dst, point, style.Foreground(), text)
}
func (item *Item) renderInt(dst draw.Image, value int, isEditing bool, style *app.TextStyle) {
var (
bounds = dst.Bounds()
text = fmt.Sprintf("%d", value)
width, _ = style.Font.MeasureString(text)
point = image.Pt(bounds.Max.X-3-width, bounds.Min.Y+3)
)
style.Font.Draw(dst, point, style.Foreground(), text)
}
func (item *Item) renderString(dst draw.Image, value string, isEditing bool, style *app.TextStyle) {
var (
bounds = dst.Bounds()
width, _ = style.Font.MeasureString(value)
point = image.Pt(bounds.Max.X-3-width, bounds.Min.Y+3)
)
style.Font.Draw(dst, point, style.Foreground(), value)
}
func numberOfDigits(n int) int {
if n == 0 {
return 1
}
sign := 0
if n < 0 {
sign++
n = -n
}
return int(math.Log10(float64(n))) + sign + 1
}
+23 -10
View File
@@ -40,7 +40,7 @@ var (
}
defaultGrayObjectStyle = ObjectStyle{
Background: image.Black,
BackgroundImage: image.Black,
BackgroundColor: color.Black,
ForegroundColor: color.White,
BorderColor: color.Gray{Y: 0xBF},
@@ -87,7 +87,7 @@ type Styles struct {
Graph ObjectStyle
}
func StylesFor(ctx Context) *Styles {
func StylesFor(model color.Model) *Styles {
theme := UserTheme
if theme == nil {
// Use the default theme.
@@ -105,7 +105,6 @@ func StylesFor(ctx Context) *Styles {
}
}
model := ctx.Display().ColorModel()
switch model {
case pixel.MonoModel:
return theme.Mono
@@ -118,11 +117,11 @@ func StylesFor(ctx Context) *Styles {
type ObjectStyle struct {
// Background image or color.
Background image.Image
BackgroundImage image.Image
BackgroundColor color.Color
// Foreground image (mask) or color.
Foreground image.Image
ForegroundImage image.Image
ForegroundColor color.Color
// Margin around the object.
@@ -139,10 +138,24 @@ type ObjectStyle struct {
Stroke int
}
func (s ObjectStyle) Background() image.Image {
if s.BackgroundImage == nil {
return image.NewUniform(s.BackgroundColor)
}
return s.BackgroundImage
}
func (s ObjectStyle) Foreground() image.Image {
if s.ForegroundImage == nil {
return image.NewUniform(s.ForegroundColor)
}
return s.ForegroundImage
}
func (s ObjectStyle) WithBackgroundColor(c color.Color) ObjectStyle {
i := new(ObjectStyle)
*i = s
i.Background = nil
i.BackgroundImage = nil
i.BackgroundColor = c
return *i
}
@@ -150,7 +163,7 @@ func (s ObjectStyle) WithBackgroundColor(c color.Color) ObjectStyle {
func (s ObjectStyle) WithForegroundColor(c color.Color) ObjectStyle {
i := new(ObjectStyle)
*i = s
i.Foreground = nil
i.ForegroundImage = nil
i.ForegroundColor = c
return *i
}
@@ -158,7 +171,7 @@ func (s ObjectStyle) WithForegroundColor(c color.Color) ObjectStyle {
func (s ObjectStyle) Inverse() ObjectStyle {
i := new(ObjectStyle)
*i = s
i.Background, i.Foreground = i.Foreground, i.Background
i.BackgroundImage, i.ForegroundImage = i.ForegroundImage, i.BackgroundImage
i.BackgroundColor, i.ForegroundColor = i.ForegroundColor, i.BackgroundColor
return *i
}
@@ -270,7 +283,7 @@ type TextStyle struct {
func (s TextStyle) WithBackgroundColor(c color.Color) TextStyle {
i := new(TextStyle)
*i = s
i.Background = nil
i.BackgroundImage = nil
i.BackgroundColor = c
return *i
}
@@ -278,7 +291,7 @@ func (s TextStyle) WithBackgroundColor(c color.Color) TextStyle {
func (s TextStyle) WithForegroundColor(c color.Color) TextStyle {
i := new(TextStyle)
*i = s
i.Foreground = nil
i.ForegroundImage = nil
i.ForegroundColor = c
return *i
}
+37 -87
View File
@@ -1,7 +1,6 @@
package widget
import (
"fmt"
"image"
"image/color"
"reflect"
@@ -9,17 +8,17 @@ import (
"github.com/sirupsen/logrus"
"github.com/BeatGlow/beatglow/app"
"github.com/BeatGlow/beatglow/app/font"
"github.com/BeatGlow/beatglow/app/menu"
"github.com/BeatGlow/display/draw"
)
type Menu struct {
Base
items []MenuItem
index int
Root *menu.Menu
curr, next *menu.Menu // currently in view and next in view
}
func NewMenu(size image.Point) *Menu {
func NewMenu(size image.Point, root *menu.Menu) *Menu {
w := new(Menu)
w.Extend(w)
w.Resize(size)
@@ -30,32 +29,16 @@ func (w *Menu) String() string {
return "menu"
}
func (w *Menu) SetItems(items []MenuItem) *Menu {
func (w *Menu) Update(root *menu.Menu) *Menu {
w.mu.Lock()
w.items = append([]MenuItem{{
Text: "Go back",
Icon: "md_history",
Type: reflect.TypeOf(""),
}}, items...)
w.index = 0
w.Root = root
w.curr = nil
w.next = root
w.mu.Unlock()
w.changed.Store(true)
return w
}
func (w *Menu) Change(delta int) int {
w.mu.Lock()
if l := len(w.items); l == 0 {
w.index = 0
} else {
w.index = (w.index + delta + len(w.items)) % len(w.items)
}
index := w.index
w.mu.Unlock()
w.changed.Store(true)
return index
}
func (w *Menu) Redraw() {
w.changed.Store(true)
}
@@ -70,86 +53,53 @@ func (w *Menu) Refresh(ctx app.Context) bool {
size = bounds.Size()
)
if w.changed.CompareAndSwap(true, false) || w.buffer == nil {
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 (
itemWidth = size.X - 8
itemHeight = 16
num = len(w.items)
max = size.Y / itemHeight
shift int
menu = w.curr
pageSize = menu.PageSize()
start = (menu.Position / pageSize) * pageSize
end = start + pageSize
)
if w.index >= max {
shift = -(w.index - max)
} else {
shift = -w.index
if max := len(menu.Items); end > max {
end = max
}
for y := 0; y < max && y < num; y++ {
// 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 (
index = (w.index + shift + y + num) % num
item = w.items[index]
rect = image.Rect(0, y*itemHeight, itemWidth, (y+1)*itemHeight-2)
fg image.Image = image.White
border color.Color = color.Gray{Y: 0x1f}
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
)
if index == w.index {
draw.Box(w.buffer, rect, color.Gray{Y: 0x1f})
border = color.Gray{Y: 0xbf}
}
draw.Rectangle(w.buffer, rect, border)
//font.SM4TIK.Draw(w.buffer, rect.Min.Add(image.Pt(1, -2)), fg, string(item.Icon))
w.styles.Text.Font.Draw(w.buffer, rect.Min.Add(image.Pt(16, 3)), fg, item.Text)
var (
value = item.Value
kind = item.Type.Kind()
)
if kind == reflect.Ptr {
value = reflect.Indirect(value)
kind = value.Type().Kind()
}
switch kind {
case reflect.String, reflect.Struct:
if item.Icon == "" {
font.Icon(w.buffer, rect.Min.Add(image.Pt(3, 2)), color.White, "md_star")
} else {
font.Icon(w.buffer, rect.Min.Add(image.Pt(3, 2)), color.White, item.Icon)
}
case reflect.Bool:
if value.Bool() {
font.Icon(w.buffer, rect.Min.Add(image.Pt(3, 2)), color.White, "fa_toggle_on")
} else {
font.Icon(w.buffer, rect.Min.Add(image.Pt(3, 2)), color.White, "fa_toggle_off")
}
case reflect.Uint8:
font.Icon(w.buffer, rect.Min.Add(image.Pt(3, 2)), color.White, "fa_gauge")
value := uint8(value.Uint())
w.styles.Text.Font.Draw(w.buffer, rect.Min.Add(image.Pt(16, itemWidth-64)), fg, fmt.Sprintf("%d", value))
default:
logrus.WithField("type", kind).Warn("no menu item renderer!")
}
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(w.items) > max {
y := size.Y / len(w.items) * w.index
draw.Box(w.buffer, image.Rect(size.X-3, y, size.X, y+size.Y/len(w.items)), color.Gray{Y: 0x7f})
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})
}
}
+2 -10
View File
@@ -123,11 +123,7 @@ func (w *Spectrum) Refresh(ctx app.Context) bool {
if w.changed.CompareAndSwap(true, false) {
if w.buffer == nil {
w.buffer = app.BufferFor(ctx, bounds.Size())
if w.styles.Window.Background != nil {
app.ImageCopy(w.buffer, w.styles.Window.Background)
} else {
app.ImageFill(w.buffer, w.styles.Window.BackgroundColor)
}
app.ImageCopy(w.buffer, w.styles.Window.Background())
}
if w.waterfall {
@@ -143,11 +139,7 @@ func (w *Spectrum) Refresh(ctx app.Context) bool {
}
func (w *Spectrum) refreshAnalyzer(bounds image.Rectangle) {
if w.styles.Window.Background != nil {
app.ImageCopy(w.buffer, w.styles.Window.Background)
} else {
app.ImageFill(w.buffer, w.styles.Window.BackgroundColor)
}
app.ImageCopy(w.buffer, w.styles.Window.Background())
var (
width = bounds.Dx()
+2 -20
View File
@@ -124,29 +124,11 @@ func (w *Text) Refresh(ctx app.Context) bool {
}
// Fill background.
if w.styles.Text.Background != nil {
log.Trace("fill canvas with background")
app.ImageCopy(w.buffer, w.styles.Text.Background)
} else {
log.WithField("color", w.styles.Text.BackgroundColor).
Trace("fill canvas with background color")
app.ImageFill(w.buffer, w.styles.Text.BackgroundColor)
}
app.ImageCopy(w.buffer, w.styles.Text.Background())
// Fill text.
inner := w.styles.Text.Inner(w.buffer)
if w.styles.Text.Foreground != nil {
log.WithField("text", w.text).
WithField("inner", inner).
Debug("text canvas with foreground mask")
w.styles.Text.Font.Draw(inner, w.scroll, w.styles.Text.Foreground, w.text)
} else {
log.WithField("text", w.text).
WithField("inner", inner).
WithField("color", w.styles.Text.ForegroundColor).
Debug("text canvas with foreground color")
w.styles.Text.Font.Draw(inner, w.scroll, image.NewUniform(w.styles.Text.ForegroundColor), w.text)
}
w.styles.Text.Font.Draw(inner, w.scroll, w.styles.Text.Foreground(), w.text)
}
// Scroll text if required.
+32 -6
View File
@@ -14,15 +14,16 @@ import (
// Settings are the user-adjustable settings.
type Settings struct {
Display DisplaySettings `hcl:"display,block" icon:"🖥️"`
Player PlayerSettings ` icon:"🎧"`
Path string `menu:"-"`
Display DisplaySettings `hcl:"display,block" icon:"md_monitor_speaker"`
Player PlayerSettings ` icon:"md_headphones"`
Spectrum SpectrumSettings `hcl:"spectrum,block" icon:"md_chart_line"`
System SystemSettings ` icon:"md_raspberry_pi"`
}
type DisplaySettings struct {
Contrast uint8 `hcl:"contrast" menu:"Display contrast" step:"16"`
Sleep string `hcl:"sleep" menu:"Display sleep time" options:"5min,15min,hour,day"`
Contrast uint8 `hcl:"contrast" menu:"Display contrast" icon:"md_contrast_box"`
Sleep string `hcl:"sleep" menu:"Display sleep time" options:"5min,15min,hour,day" icon:"md_power"`
}
type PlayerSettings struct {
@@ -54,9 +55,28 @@ var DefaultSettings = Settings{
},
}
var DefaultUserSettingsPath = []string{
os.ExpandEnv("/etc/beatglow/settings.conf"),
os.ExpandEnv("${HOME}/.config/beatglow/settings.conf"),
os.ExpandEnv("${HOME}/.beatglow-settings.conf"),
}
func LoadUserSettings(name string) *Settings {
if name == "" {
for _, item := range DefaultUserSettingsPath {
if _, err := os.Stat(item); err == nil {
name = item
break
}
}
if name == "" {
logrus.Warn("user settings does not exist; using defaults")
return &DefaultSettings
}
}
log := logrus.WithField("path", name)
log.Debug("loading configuration")
log.Info("loading user settings")
source, err := os.ReadFile(name)
if err != nil {
@@ -69,7 +89,7 @@ func LoadUserSettings(name string) *Settings {
}
var (
settings = new(Settings)
settings = &Settings{Path: name}
ctx *hcl.EvalContext
file *hcl.File
diag hcl.Diagnostics
@@ -90,6 +110,12 @@ func LoadUserSettings(name string) *Settings {
}
func SaveUserSettings(name string, settings *Settings) error {
if name == "" {
name = DefaultUserSettingsPath[len(DefaultUserSettingsPath)-1]
}
logrus.WithField("path", name).Info("saving user settings")
file := hclwrite.NewEmptyFile()
root := file.Body()
gohcl.EncodeIntoBody(settings, root)
+12 -2
View File
@@ -25,7 +25,7 @@ type controllerContext struct {
active app.Layout
previous app.Layout
settingsLayout app.Layout
settings config.Settings
settings *config.Settings
}
func (c controllerContext) Display() display.Display {
@@ -63,6 +63,13 @@ func (c *controllerContext) teardown(log *logrus.Entry) {
}
c.display = nil
}
if c.settings != nil {
log.Debug("saving user settings")
if err := config.SaveUserSettings(c.settings.Path, c.settings); err != nil {
log.WithError(err).Warn("saving user settings failed")
}
}
}
func (c *controllerContext) addSettings(layout app.Layout) {
@@ -120,7 +127,10 @@ func (c *controllerContext) Show(layout app.Layout) {
}
func (c *controllerContext) Settings() *config.Settings {
return &c.settings
if c.settings == nil {
c.settings = config.LoadUserSettings("")
}
return c.settings
}
func (c *controllerContext) handleStatus(status *player.Status) {